From 60c6d7996d0e93a61450b4179c4cca5e8a88b05b Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Fri, 11 Sep 2026 09:58:26 +1000 Subject: [PATCH 01/68] Recover from a 421 on the evidence rather than on the cache's age A 421 tells us, authoritatively, that the swarm we resolved for an account is wrong. `_handle_421_retry` answered it with `refresh_if_needed`, which decides on `cache_expiration` (2h) and so declines on any cache younger than that, and then re-read the same `_swarm_cache` entry - so the retry went to another node in the list that had just rejected us, and every later request for that account did the same until the cache aged out. Evicting the swarm cache entry alone cannot fix it: the entry is only ever a memo of `swarm::get_swarm(pubkey, _all_swarms)`, so it recomputes the identical answer. What the rejection disproves is the pool snapshot the swarms were generated from, and only a refresh replaces that. `invalidate_swarm` refreshes on that evidence, with a backoff that doubles each time another rejection arrives after a refresh we already ran for one, so a node rejecting everything costs a handful of refreshes over a couple of hours rather than one every minute for as long as it keeps it up. --- include/session/network/snode_pool.hpp | 10 ++ src/network/session_network.cpp | 18 ++-- src/network/snode_pool.cpp | 80 ++++++++++++++ tests/test_snode_pool.cpp | 143 +++++++++++++++++++++++++ 4 files changed, 243 insertions(+), 8 deletions(-) diff --git a/include/session/network/snode_pool.hpp b/include/session/network/snode_pool.hpp index 787e2c582..22c0194f2 100644 --- a/include/session/network/snode_pool.hpp +++ b/include/session/network/snode_pool.hpp @@ -76,6 +76,14 @@ class SnodePool : public std::enable_shared_from_this { const std::vector& in_use_nodes, std::function on_refresh_complete = nullptr); + // Re-resolves `swarm_pubkey` after a node we believed was in its swarm has told us the account + // isn't there. Where `refresh_if_needed` decides on the cache's age, this decides on that + // rejection, so a mapping we have direct proof is wrong can be replaced long before + // `cache_expiration`. `on_complete` runs once the swarm can be resolved again. + virtual void invalidate_swarm( + session::network::x25519_pubkey swarm_pubkey, + std::function on_complete = nullptr); + virtual void get_swarm( session::network::x25519_pubkey swarm_pubkey, bool ignore_strike_count, @@ -109,6 +117,8 @@ class SnodePool : public std::enable_shared_from_this { // Refresh logic std::chrono::system_clock::time_point _last_snode_cache_update; + std::chrono::system_clock::time_point _last_evidence_refresh; + std::chrono::seconds _evidence_refresh_backoff{0}; std::optional _current_snode_cache_refresh_id; int _snode_cache_refresh_failure_count = 0; std::vector _refresh_candidate_nodes; diff --git a/src/network/session_network.cpp b/src/network/session_network.cpp index 7d160fc41..474ed48cf 100644 --- a/src/network/session_network.cpp +++ b/src/network/session_network.cpp @@ -821,24 +821,26 @@ void Network::_handle_421_retry( "421 Misdirected Request for a request with no swarm"); } - // If we got a 421 it means our snode cache is outdated (because the swarm the destination node - // belongs to doesn't match our cache anymore) log::info( cat, - "Request {} received 421 from node {}, refreshing swarm if stale.", + "Request {} received 421 from node {}, re-resolving its swarm.", original_request.request_id, original_dest_node->to_string()); auto failed_node_copy = *original_dest_node; - std::vector nodes_to_exclude = _router->get_all_used_nodes(); - _snode_pool->refresh_if_needed( - std::move(nodes_to_exclude), + auto swarm_pubkey = *original_request.swarm_pubkey; + + // A node in the swarm we resolved has told us the account isn't in its swarm, which is proof + // the mapping is wrong now rather than a reason to suspect it might be; asking for a refresh + // by age (`refresh_if_needed`) would decline for as long as `cache_expiration`, leaving every + // request for this account failing until then. + _snode_pool->invalidate_swarm( + swarm_pubkey, [this, + swarm_pubkey, req_to_retry = std::move(original_request), cb = std::move(final_callback), failed_node = failed_node_copy] { - auto swarm_pubkey = *req_to_retry.swarm_pubkey; - _snode_pool->get_swarm( swarm_pubkey, false, diff --git a/src/network/snode_pool.cpp b/src/network/snode_pool.cpp index d4f61ad9a..273a0a0a2 100644 --- a/src/network/snode_pool.cpp +++ b/src/network/snode_pool.cpp @@ -42,6 +42,18 @@ namespace { const std::chrono::seconds STRIKE_EXPIRY = 48h; const std::chrono::seconds SAVE_THROTTLE = 5min; + + // A swarm rejection is evidence against the pool snapshot the swarm was derived from, so it is + // only worth acting on once that snapshot is old enough for a refresh to plausibly return + // something different. + const std::chrono::seconds EVIDENCE_REFRESH_MIN_POOL_AGE = 1min; + + // A rejection arriving *after* we already refreshed on one is the refresh telling us it didn't + // help - the network hasn't settled, or the node is lying - so each successive one waits twice + // as long, up to `cache_expiration`. A single 3-node refresh per minute sustained indefinitely + // is not an acceptable resting state for a client on a bad connection, and without this it is + // exactly what a persistent rejection source would produce. + const std::chrono::seconds EVIDENCE_REFRESH_BASE_BACKOFF = 1min; } // namespace SnodePool::SnodePool( @@ -1113,6 +1125,74 @@ void SnodePool::refresh_if_needed( }); } +void SnodePool::invalidate_swarm(x25519_pubkey swarm_pubkey, std::function on_complete) { + _loop->call([this, swarm_pubkey, cb = std::move(on_complete)]() mutable { + if (_suspended) { + log::info(cat, "Ignoring swarm invalidation as pool is suspended."); + + if (cb) + cb(); + return; + } + + // The swarm cache only ever memoises `swarm::get_swarm(pubkey, _all_swarms)`, and + // `_all_swarms` is generated from the pool, so dropping the single entry would recompute + // the same rejected answer. What the rejection actually disproves is the pool snapshot, + // and a refresh is the only thing that replaces it - clearing the swarm cache as it goes. + auto now = std::chrono::system_clock::now(); + + if (!_current_snode_cache_refresh_id) { + // The backoff is deliberately global rather than per-swarm: a refresh replaces the pool + // every swarm is derived from, so a rejection for one swarm is exactly as unhelpful to + // act on right after a refresh as a second rejection for the swarm that prompted it + auto pool_age = now - _last_snode_cache_update; + auto since_last = now - _last_evidence_refresh; + + // Quiet for twice the interval we were holding means whatever caused the last run is + // over, so the next incident starts from the base delay rather than inheriting it + if (since_last > 2 * _evidence_refresh_backoff) + _evidence_refresh_backoff = 0s; + + if (pool_age < EVIDENCE_REFRESH_MIN_POOL_AGE || since_last < _evidence_refresh_backoff) + log::info( + cat, + "Swarm {} was rejected, but the pool is {}s old and the last refresh on a " + "rejection was {}s ago (backoff {}s); leaving it alone.", + swarm_pubkey.hex(), + std::chrono::duration_cast(pool_age).count(), + std::chrono::duration_cast(since_last).count(), + _evidence_refresh_backoff.count()); + else { + _evidence_refresh_backoff = std::min( + std::chrono::seconds{_config.cache_expiration}, + (_evidence_refresh_backoff == 0s ? EVIDENCE_REFRESH_BASE_BACKOFF + : _evidence_refresh_backoff * 2)); + _last_evidence_refresh = now; + + log::info( + cat, + "Swarm {} was rejected by a node we had in it, refreshing the pool (next " + "rejection-driven refresh no sooner than {}s from now).", + swarm_pubkey.hex(), + _evidence_refresh_backoff.count()); + _refresh_snode_cache(); + } + } + + if (!cb) + return; + + // `_refresh_snode_cache` runs inline here (we are on the loop thread) and can decline to + // start, so it is the refresh id - not the call above - that says whether there is anything + // to wait for. A callback queued against a refresh that never started never runs, and on + // this path that would strand the request that triggered the rejection. + if (_current_snode_cache_refresh_id) + _after_snode_cache_refresh.push_back(std::move(cb)); + else + cb(); + }); +} + std::vector SnodePool::get_unused_nodes( size_t count, const std::vector& exclude_nodes) { // Kick of a cache refresh in the background if needed (call_soon to ensure it is scheduled diff --git a/tests/test_snode_pool.cpp b/tests/test_snode_pool.cpp index d470ed193..05073eff0 100644 --- a/tests/test_snode_pool.cpp +++ b/tests/test_snode_pool.cpp @@ -69,6 +69,30 @@ class TestSnodePool : public SnodePool { // loop thread void update_cache(std::vector nodes) { _update_cache("test", std::move(nodes)); } + bool debug_refresh_in_progress() { + return _loop->call_get([this] { return _current_snode_cache_refresh_id.has_value(); }); + } + + // Backdates the pool snapshot so the age-based policies can be exercised without waiting + void debug_age_pool(std::chrono::seconds by) { + _loop->call_get([this, by] { _last_snode_cache_update -= by; }); + } + + void debug_age_evidence_refresh(std::chrono::seconds by) { + _loop->call_get([this, by] { _last_evidence_refresh -= by; }); + } + + std::chrono::seconds debug_evidence_backoff() { + return _loop->call_get([this] { return _evidence_refresh_backoff; }); + } + + // Runs `fn` on the loop thread, which is what makes `get_swarm` / `invalidate_swarm` resolve + // inline rather than being queued: a test observing them from off the loop has no ordering + // guarantee at all + void debug_run_on_loop(std::function fn) { + _loop->call_get([fn = std::move(fn)] { fn(); }); + } + void debug_on_refresh_complete(std::vector> raw_results) { auto total_requests = static_cast(raw_results.size()); _loop->call_get([&] { @@ -77,6 +101,19 @@ class TestSnodePool : public SnodePool { } }; +// `TestSnodePool` stubs out `refresh_if_needed` so tests don't kick off real refreshes; the swarm +// invalidation test needs the real age-based policy to compare against, so it uses this instead +class TestSnodePoolAgePolicy : public TestSnodePool { + public: + using TestSnodePool::TestSnodePool; + + void refresh_if_needed( + const std::vector& in_use_nodes, + std::function on_refresh_complete = nullptr) override { + SnodePool::refresh_if_needed(in_use_nodes, std::move(on_refresh_complete)); + } +}; + // Encodes nodes the way the storage server returns them, so they can be fed to // `_on_refresh_complete`: 51 bytes per node, all multi-byte fields big-endian std::vector to_snode_cache_bin(const std::vector& nodes) { @@ -336,3 +373,109 @@ TEST_CASE("Network", "[network][refresh_min_cache_size]") { snode_pool->debug_on_refresh_complete({to_snode_cache_bin(enough)}); CHECK(snode_pool->size() == 12); } + +TEST_CASE("Network", "[network][invalidate_swarm]") { + session::network::config::SnodePool pool_config{ + .cache_expiration = 2h, + .cache_min_lifetime = 2s, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .cache_min_size = 12, + .cache_min_swarm_size = 3, + .cache_num_nodes_to_use_for_refresh = 1, + .cache_min_num_refresh_presence_to_include_node = 1, + .cache_node_strike_threshold = 3}; + + auto ed_pk_before = "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7"_hexbytes; + auto ed_pk_after = "5ea34e72bb044654a6a23675690ef5ffaaf1656b02f93fb76655f9cbdbe89876"_hexbytes; + + // Two snapshots of the same two swarms, with an entirely different set of nodes serving them. + // Which swarm the pubkey lands in doesn't matter; what matters is that the correct answer + // changed and no node is common to both. + auto pool_snapshot = [](const std::vector& ed_pk, uint8_t subnet) { + std::vector nodes; + + for (uint16_t i = 0; i < 12; ++i) + nodes.emplace_back(service_node{ + ed25519_pubkey::from_bytes(ed_pk), + oxen::quic::ipv4{"192.168.{}.{}"_format(subnet, i)}, + static_cast(20000 + i), + static_cast(30000 + i), + {2, 11, 0}, + static_cast(i < 6 ? 0 : 1)}); + + return nodes; + }; + auto nodes_before = pool_snapshot(ed_pk_before, 0); + auto nodes_after = pool_snapshot(ed_pk_after, 1); + + auto loop = std::make_shared(); + auto disk_loop = std::make_shared(); + auto snode_pool = std::make_shared(pool_config, loop, disk_loop); + snode_pool->update_cache(nodes_before); + snode_pool->debug_age_pool(10min); + + auto swarm_pubkey = x25519_pubkey::from_hex( + "0000000000000000000000000000000000000000000000000000000000000000"); + + std::vector rejected_swarm, recovered_swarm; + bool age_policy_started_refresh = false, recovery_ran = false; + + snode_pool->debug_run_on_loop([&] { + snode_pool->get_swarm( + swarm_pubkey, true, [&](swarm::swarm_id_t, std::vector nodes) { + rejected_swarm = std::move(nodes); + }); + + // Asking by age is what the 421 path used to do, and on a cache this far short of + // `cache_expiration` it declines - which is what left the disproven mapping in place + snode_pool->refresh_if_needed({}); + age_policy_started_refresh = snode_pool->debug_refresh_in_progress(); + + snode_pool->invalidate_swarm(swarm_pubkey, [&] { + recovery_ran = true; + snode_pool->get_swarm( + swarm_pubkey, true, [&](swarm::swarm_id_t, std::vector nodes) { + recovered_swarm = std::move(nodes); + }); + }); + }); + + REQUIRE_FALSE(rejected_swarm.empty()); + CHECK_FALSE(age_policy_started_refresh); + + // The rejection has to produce a refresh, and the retry has to wait for it rather than being + // handed the answer that was just rejected + REQUIRE(snode_pool->debug_refresh_in_progress()); + CHECK_FALSE(recovery_ran); + + snode_pool->update_cache(nodes_after); + REQUIRE(recovery_ran); + REQUIRE_FALSE(recovered_swarm.empty()); + + for (const auto& node : recovered_swarm) + CHECK(std::ranges::find(rejected_swarm, node) == rejected_swarm.end()); + + // A rejection that arrives after we already refreshed on one has to be held off, or a node that + // rejects everything keeps a client refreshing from three nodes forever + CHECK(snode_pool->debug_evidence_backoff() == 1min); + snode_pool->debug_age_pool(10min); + snode_pool->debug_run_on_loop([&] { snode_pool->invalidate_swarm(swarm_pubkey); }); + CHECK_FALSE(snode_pool->debug_refresh_in_progress()); + + // Once it has elapsed the next one runs, and the one after it waits twice as long again + snode_pool->debug_age_evidence_refresh(90s); + snode_pool->debug_run_on_loop([&] { snode_pool->invalidate_swarm(swarm_pubkey); }); + CHECK(snode_pool->debug_refresh_in_progress()); + CHECK(snode_pool->debug_evidence_backoff() == 2min); + + // Staying quiet for twice the interval means the next incident starts from the base delay + // rather than inheriting an escalated one + snode_pool->update_cache(nodes_after); + snode_pool->debug_age_pool(10min); + snode_pool->debug_age_evidence_refresh(10min); + snode_pool->debug_run_on_loop([&] { snode_pool->invalidate_swarm(swarm_pubkey); }); + CHECK(snode_pool->debug_refresh_in_progress()); + CHECK(snode_pool->debug_evidence_backoff() == 1min); +} From 348b778ea5719cfcd1aa4cfcfb159cb2544d45ce Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Fri, 11 Sep 2026 12:23:57 -0300 Subject: [PATCH 02/68] Fix uninitialized requested_unlock_height usage Some responses (like 421s) don't include requested_unlock_height values, and when that happens we were leaving the value uninitialized. This fixes it to default to -1, which means "unknown" so that a missing value can't get misinterpreted as a node about to leave the network. --- include/session/network/service_node.h | 2 +- include/session/network/service_node.hpp | 5 ++++- src/network/service_node.cpp | 6 +++--- src/network/snode_pool.cpp | 2 +- 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/include/session/network/service_node.h b/include/session/network/service_node.h index 8462f6e64..ae09ba4c6 100644 --- a/include/session/network/service_node.h +++ b/include/session/network/service_node.h @@ -13,7 +13,7 @@ typedef struct network_service_node { uint16_t omq_port; uint16_t version[3]; uint64_t swarm_id; - uint64_t requested_unlock_height; + int64_t requested_unlock_height; // -1 if unknown; 0 if no unlock has been requested. } network_service_node; #ifdef __cplusplus diff --git a/include/session/network/service_node.hpp b/include/session/network/service_node.hpp index a2306f083..6f26e8c92 100644 --- a/include/session/network/service_node.hpp +++ b/include/session/network/service_node.hpp @@ -41,7 +41,10 @@ struct service_node { uint16_t omq_port; std::array storage_server_version; swarm_id_t swarm_id; - uint64_t requested_unlock_height; + + // -1 when we don't know: most sources (the binary pool format, the on-disk cache, swarm + // responses) carry no unlock information at all, and 0 would claim they said "not requested". + int64_t requested_unlock_height = -1; oxen::quic::RemoteAddress to_https_address() const { return oxen::quic::RemoteAddress{remote_pubkey, ip, https_port}; diff --git a/src/network/service_node.cpp b/src/network/service_node.cpp index affa303a2..4335e3451 100644 --- a/src/network/service_node.cpp +++ b/src/network/service_node.cpp @@ -121,9 +121,9 @@ service_node service_node::from_json(nlohmann::json json) { if (!quic::parse_int(json["swarm"].get(), swarm_id, 16)) throw std::runtime_error{"Invalid swarm id"}; - uint64_t requested_unlock_height; - if (json.contains("requested_unlock_height")) - requested_unlock_height = json["requested_unlock_height"].get(); + // Swarm responses (the `get_swarm` endpoint and 421 bodies) omit this entirely, and an oxend + // node dump omits it for a node with no unlock requested; neither case is distinguishable here + auto requested_unlock_height = json.value("requested_unlock_height", -1); return {ed25519_pubkey::from_bytes(pubkey), quic::ipv4{ip}, diff --git a/src/network/snode_pool.cpp b/src/network/snode_pool.cpp index d4f61ad9a..7d88fcd1c 100644 --- a/src/network/snode_pool.cpp +++ b/src/network/snode_pool.cpp @@ -496,7 +496,7 @@ void SnodePool::_launch_next_refresh_request( // possible that the node is offline so don't both including it in the // initial cache (if we get a successful connection and refresh the // cache then it would be added back at that point) - if (snode.requested_unlock_height && + if (snode.requested_unlock_height > 0 && snode.requested_unlock_height <= expected_current_height) { unlocked_count++; continue; From 329f8b9d209e2a51830a9ad2c1e39af2c8fde93d Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Mon, 14 Sep 2026 09:15:48 +1000 Subject: [PATCH 03/68] Follow a 421's redirect instead of refreshing the whole pool Refreshing on a 421 recovers the account, but it means a swarm change has every client of that swarm fetch the full node list - 51 bytes per node from each of `cache_num_nodes_to_use_for_refresh` nodes - where nothing made them fetch it at all before. The backoff added with `invalidate_swarm` bounds how often one client repeats that; it does nothing about the aggregate. A node rejecting a request for an account usually names the swarm it actually belongs to, which corrects the one mapping we know is wrong without fetching anything. `get_swarm` prefers such a redirect over its own calculation until the pool is refreshed, and the refresh stays as the fallback for a 421 that carries no usable redirect. Only the node pubkeys are read from the response, and only ones that resolve against the pool we fetched ourselves, so a redirect reaches registered service nodes we already know about and nothing else - it cannot invent a node or name an address of its own choosing. It can still choose which of those nodes we talk to, so: a redirect naming the swarm we already calculated is refused, fewer than `cache_min_swarm_size` resolved names is refused, three in a row without an intervening refresh is refused, and a pool refresh drops every override it was correcting. The redirects are kept out of `_swarm_cache`, which stays a pure memo of `_all_swarms`. --- include/session/network/session_network.hpp | 5 +- include/session/network/snode_pool.hpp | 19 +++ src/network/session_network.cpp | 138 ++++++++++++-------- src/network/snode_pool.cpp | 92 +++++++++++++ tests/test_snode_pool.cpp | 124 ++++++++++++++++++ 5 files changed, 325 insertions(+), 53 deletions(-) diff --git a/include/session/network/session_network.hpp b/include/session/network/session_network.hpp index 9c8f07eb9..cc495e9c8 100644 --- a/include/session/network/session_network.hpp +++ b/include/session/network/session_network.hpp @@ -116,7 +116,10 @@ class Network : public std::enable_shared_from_this { void _recalculate_status(); void _update_status(ConnectionStatus new_status); void _update_network_state(const std::string& body); - void _handle_421_retry(Request original_request, network_response_callback_t final_callback); + void _handle_421_retry( + Request original_request, + std::optional response_body, + network_response_callback_t final_callback); void _resync_clock( std::optional original_request, network_response_callback_t request_callback); diff --git a/include/session/network/snode_pool.hpp b/include/session/network/snode_pool.hpp index 22c0194f2..25995fc69 100644 --- a/include/session/network/snode_pool.hpp +++ b/include/session/network/snode_pool.hpp @@ -84,6 +84,18 @@ class SnodePool : public std::enable_shared_from_this { session::network::x25519_pubkey swarm_pubkey, std::function on_complete = nullptr); + // Records the swarm a node named when it rejected a request for `swarm_pubkey`, so the mapping + // can be corrected without refreshing the whole pool - a swarm change would otherwise have + // every client of that swarm fetch the full node list, where nothing made them before. + // + // Only the node pubkeys are taken from the response, and only ones that resolve against the + // pool we fetched ourselves, so a redirect can reach registered service nodes we already know + // and nothing else. Returns false when the redirect is unusable, which is the caller's cue to + // fall back to `invalidate_swarm`. + virtual bool record_swarm_redirect( + session::network::x25519_pubkey swarm_pubkey, + const std::vector& swarm_node_keys); + virtual void get_swarm( session::network::x25519_pubkey swarm_pubkey, bool ignore_strike_count, @@ -108,6 +120,13 @@ class SnodePool : public std::enable_shared_from_this { std::vector>> _all_swarms; std::unordered_map>> _swarm_cache; + + // Swarms a node has redirected us to, which `get_swarm` prefers over its own calculation. Kept + // apart from `_swarm_cache` deliberately: that is a memo of `_all_swarms` and stays one, where + // these are claims from outside that outrank it until the pool is refreshed. The count bounds + // how far a disagreement between nodes can bounce us before we go and refresh instead. + std::unordered_map, uint8_t>> + _swarm_overrides; std::map> _snode_strikes; bool _strikes_flush_scheduled = false; diff --git a/src/network/session_network.cpp b/src/network/session_network.cpp index 474ed48cf..24d4babce 100644 --- a/src/network/session_network.cpp +++ b/src/network/session_network.cpp @@ -1,6 +1,7 @@ #include "session/network/session_network.hpp" #include +#include #include #include @@ -482,7 +483,7 @@ void Network::send_request(Request request, network_response_callback_t callback // cache, the original request might succeed after this refresh so we should // just automatically retry if (final_status_code == 421) { - _handle_421_retry(std::move(original_req), std::move(cb)); + _handle_421_retry(std::move(original_req), std::move(body), std::move(cb)); return; } @@ -779,8 +780,41 @@ void Network::_update_network_state(const std::string& body) { // MARK: Specific Error Handling +// Pulls the node pubkeys out of a 421 body. Only the pubkeys: the rest of each record is contact +// information we deliberately don't read, so a redirect can't put us in touch with anything the +// pool hasn't already told us about. +static std::vector redirect_node_keys(const std::optional& body) { + std::vector keys; + + if (!body) + return keys; + + try { + auto json = nlohmann::json::parse(*body); + + if (!json.contains("snodes") || !json["snodes"].is_array()) + return keys; + + for (const auto& entry : json["snodes"]) { + if (!entry.contains("pubkey_ed25519") || !entry["pubkey_ed25519"].is_string()) + continue; + + auto hex = entry["pubkey_ed25519"].get(); + + if (hex.size() == 64 && oxenc::is_hex(hex)) + keys.push_back(ed25519_pubkey::from_hex(hex)); + } + } catch (const std::exception& e) { + log::debug(cat, "Could not read a swarm redirect from the 421 body: {}", e.what()); + } + + return keys; +} + void Network::_handle_421_retry( - Request original_request, network_response_callback_t final_callback) { + Request original_request, + std::optional response_body, + network_response_callback_t final_callback) { if (original_request.retry_count >= config.redirect_retry_count) { log::error( cat, @@ -830,56 +864,56 @@ void Network::_handle_421_retry( auto failed_node_copy = *original_dest_node; auto swarm_pubkey = *original_request.swarm_pubkey; - // A node in the swarm we resolved has told us the account isn't in its swarm, which is proof - // the mapping is wrong now rather than a reason to suspect it might be; asking for a refresh - // by age (`refresh_if_needed`) would decline for as long as `cache_expiration`, leaving every - // request for this account failing until then. - _snode_pool->invalidate_swarm( - swarm_pubkey, - [this, - swarm_pubkey, - req_to_retry = std::move(original_request), - cb = std::move(final_callback), - failed_node = failed_node_copy] { - _snode_pool->get_swarm( - swarm_pubkey, - false, - [this, - req_to_retry = std::move(req_to_retry), - cb = std::move(cb), - failed_node](swarm::swarm_id_t, std::vector swarm_nodes) { - // Extract a single random index from the vector indices, but excluding - // the index of the failing node: - size_t new_target; - auto out = std::ranges::sample( - std::views::iota(0, static_cast(swarm_nodes.size())) | - std::views::filter([&](int i) { - return swarm_nodes[i] != failed_node; - }), - &new_target, - 1, - csrng); - - if (out == &new_target) - return cb( - false, - false, - ERROR_MISDIRECTED_REQUEST, - {content_type_plain_text}, - "421 Misdirected Request, but no other nodes in swarm to " - "retry"); - - log::info( - cat, - "Request {} retrying 421 error on new node {}.", - req_to_retry.request_id, - swarm_nodes[new_target].to_string()); - auto final_request = req_to_retry; - final_request.retry_count++; - final_request.destination = std::move(swarm_nodes[new_target]); - this->send_request(std::move(final_request), std::move(cb)); - }); - }); + auto retry_on_resolved_swarm = [this, + swarm_pubkey, + req_to_retry = std::move(original_request), + cb = std::move(final_callback), + failed_node = failed_node_copy]() mutable { + _snode_pool->get_swarm( + swarm_pubkey, + false, + [this, req_to_retry = std::move(req_to_retry), cb = std::move(cb), failed_node]( + swarm::swarm_id_t, std::vector swarm_nodes) { + // Extract a single random index from the vector indices, but excluding + // the index of the failing node: + size_t new_target; + auto out = std::ranges::sample( + std::views::iota(0, static_cast(swarm_nodes.size())) | + std::views::filter( + [&](int i) { return swarm_nodes[i] != failed_node; }), + &new_target, + 1, + csrng); + + if (out == &new_target) + return cb( + false, + false, + ERROR_MISDIRECTED_REQUEST, + {content_type_plain_text}, + "421 Misdirected Request, but no other nodes in swarm to " + "retry"); + + log::info( + cat, + "Request {} retrying 421 error on new node {}.", + req_to_retry.request_id, + swarm_nodes[new_target].to_string()); + auto final_request = req_to_retry; + final_request.retry_count++; + final_request.destination = std::move(swarm_nodes[new_target]); + this->send_request(std::move(final_request), std::move(cb)); + }); + }; + + // A node that rejects a request for an account usually names the swarm it actually belongs to. + // Taking its word (bounded - see `record_swarm_redirect`) fixes the one mapping we know is + // wrong, where refreshing has every client of a changed swarm fetch the full node list for it. + if (_snode_pool->record_swarm_redirect(swarm_pubkey, redirect_node_keys(response_body))) + return retry_on_resolved_swarm(); + + // No usable redirect, so the pool itself is the only thing that can put this right + _snode_pool->invalidate_swarm(swarm_pubkey, std::move(retry_on_resolved_swarm)); } void Network::_resync_clock( diff --git a/src/network/snode_pool.cpp b/src/network/snode_pool.cpp index 273a0a0a2..d41ce44d2 100644 --- a/src/network/snode_pool.cpp +++ b/src/network/snode_pool.cpp @@ -54,6 +54,10 @@ namespace { // is not an acceptable resting state for a client on a bad connection, and without this it is // exactly what a persistent rejection source would produce. const std::chrono::seconds EVIDENCE_REFRESH_BASE_BACKOFF = 1min; + + // Two nodes disagreeing about who owns a swarm can redirect us back and forth; after this many + // in a row without an intervening pool refresh, stop believing them and go and refresh. + constexpr uint8_t MAX_CONSECUTIVE_SWARM_REDIRECTS = 3; } // namespace SnodePool::SnodePool( @@ -889,6 +893,11 @@ void SnodePool::_update_cache(std::string refresh_id, std::vector _snode_cache = std::move(nodes); _all_swarms = swarm::generate_swarms(_snode_cache); _swarm_cache.clear(); + + // The pool these redirects were correcting has been replaced, so they have outlived what + // they were for. Keeping them would let one node's claim outlast the ground truth that + // would have overruled it. + _swarm_overrides.clear(); _last_snode_cache_update = std::chrono::system_clock::now(); // Reset all failure and refresh-in-progress state @@ -970,6 +979,7 @@ void SnodePool::clear_cache() { _snode_cache = {}; _all_swarms = {}; _swarm_cache = {}; + _swarm_overrides = {}; _disk_loop->call([path = _snode_cache_file_path] { SnodePool::_clear_disk_cache(path); }); }); @@ -1193,6 +1203,77 @@ void SnodePool::invalidate_swarm(x25519_pubkey swarm_pubkey, std::function& swarm_node_keys) { + return _loop->call_get([this, swarm_pubkey, &swarm_node_keys] { + if (_snode_cache.empty() || _all_swarms.empty()) + return false; + + // Resolving the names against our own pool is what makes a redirect safe to act on: the + // responding node chooses which registered nodes we end up talking to, but it cannot invent + // a node or point us at an address of its own choosing, because we never read the contact + // details it sent + std::unordered_set named{swarm_node_keys.begin(), swarm_node_keys.end()}; + std::vector resolved; + + for (const auto& node : _snode_cache) + if (named.count(node.remote_pubkey)) + resolved.push_back(node); + + if (resolved.size() < _config.cache_min_swarm_size) { + log::debug( + cat, + "Ignoring redirect for {}: only {}/{} named nodes are in our pool.", + swarm_pubkey.hex(), + resolved.size(), + swarm_node_keys.size()); + return false; + } + + // A redirect naming the swarm we already calculated is the node contradicting itself - it + // rejected the request and then pointed us back at the nodes we asked through. Refusing it + // sends the caller off to refresh the pool, which is the only thing that can help + auto computed = swarm::get_swarm(swarm_pubkey, _all_swarms); + if (computed.second.size() == resolved.size()) { + std::unordered_set computed_keys; + for (const auto& node : computed.second) + computed_keys.insert(node.remote_pubkey); + + if (std::ranges::all_of(resolved, [&computed_keys](const auto& node) { + return computed_keys.count(node.remote_pubkey) > 0; + })) { + log::debug( + cat, + "Ignoring redirect for {}: it names the swarm we already calculated.", + swarm_pubkey.hex()); + return false; + } + } + + auto& [nodes, redirects] = _swarm_overrides[swarm_pubkey]; + + if (++redirects > MAX_CONSECUTIVE_SWARM_REDIRECTS) { + log::warning( + cat, + "Dropping redirects for {} after {} in a row; refreshing the pool instead.", + swarm_pubkey.hex(), + MAX_CONSECUTIVE_SWARM_REDIRECTS); + _swarm_overrides.erase(swarm_pubkey); + return false; + } + + log::info( + cat, + "Redirected to a swarm of {} nodes for {} ({} of at most {}).", + resolved.size(), + swarm_pubkey.hex(), + redirects, + MAX_CONSECUTIVE_SWARM_REDIRECTS); + nodes = std::move(resolved); + return true; + }); +} + std::vector SnodePool::get_unused_nodes( size_t count, const std::vector& exclude_nodes) { // Kick of a cache refresh in the background if needed (call_soon to ensure it is scheduled @@ -1304,6 +1385,17 @@ void SnodePool::get_swarm( return nodes; }; + // A node that rejected a request for this account told us where it belongs, which beats + // anything we can work out from a pool we now know is behind. There is no swarm id to give + // back - a redirect names members, not an id - and nothing downstream reads it. + if (auto it = _swarm_overrides.find(swarm_pubkey); it != _swarm_overrides.end()) { + const auto& swarm_nodes = it->second.first; + + return cb( + swarm::INVALID_SWARM_ID, + (ignore_strike_count ? swarm_nodes : filter_by_strikes(swarm_nodes))); + } + // Check the in-memory swarm cache first if (auto it = _swarm_cache.find(swarm_pubkey); it != _swarm_cache.end()) { const auto& swarm_nodes = it->second.second; diff --git a/tests/test_snode_pool.cpp b/tests/test_snode_pool.cpp index 05073eff0..87c0e3994 100644 --- a/tests/test_snode_pool.cpp +++ b/tests/test_snode_pool.cpp @@ -479,3 +479,127 @@ TEST_CASE("Network", "[network][invalidate_swarm]") { CHECK(snode_pool->debug_refresh_in_progress()); CHECK(snode_pool->debug_evidence_backoff() == 1min); } + +TEST_CASE("Network", "[network][swarm_redirect]") { + session::network::config::SnodePool pool_config{ + .cache_expiration = 2h, + .cache_min_lifetime = 2s, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .cache_min_size = 12, + .cache_min_swarm_size = 3, + .cache_num_nodes_to_use_for_refresh = 1, + .cache_min_num_refresh_presence_to_include_node = 1, + .cache_node_strike_threshold = 3}; + + // A redirect is resolved by node pubkey, so every node needs its own + auto key_for = [](uint16_t i) { + return ed25519_pubkey::from_hex( + "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46a{:02x}"_format(i)); + }; + std::vector snode_cache; + + for (uint16_t i = 0; i < 12; ++i) + snode_cache.emplace_back(service_node{ + key_for(i), + oxen::quic::ipv4{"192.168.0.{}"_format(i)}, + static_cast(20000 + i), + static_cast(30000 + i), + {2, 11, 0}, + static_cast(i < 6 ? 0 : 1)}); + + auto loop = std::make_shared(); + auto disk_loop = std::make_shared(); + auto snode_pool = std::make_shared(pool_config, loop, disk_loop); + snode_pool->update_cache(snode_cache); + + // Old enough that the fallback would refresh, so "no refresh happened" below means the redirect + // was taken rather than the pool being too fresh to bother + snode_pool->debug_age_pool(10min); + + auto swarm_pubkey = x25519_pubkey::from_hex( + "0000000000000000000000000000000000000000000000000000000000000000"); + + std::vector calculated; + snode_pool->debug_run_on_loop([&] { + snode_pool->get_swarm( + swarm_pubkey, true, [&](swarm::swarm_id_t, std::vector nodes) { + calculated = std::move(nodes); + }); + }); + REQUIRE(calculated.size() == 6); + + // Everything the calculation didn't pick, which is what a real redirect would be naming + std::vector elsewhere; + for (const auto& node : snode_cache) + if (std::ranges::find(calculated, node) == calculated.end()) + elsewhere.push_back(node); + REQUIRE(elsewhere.size() == 6); + + // Membership is the claim in every comparison below; the pool is reshuffled on each refresh and + // a redirect is resolved in pool order, so neither side has an order worth asserting + auto sorted = [](std::vector nodes) { + std::ranges::sort(nodes); + return nodes; + }; + auto keys_of = [](const std::vector& nodes, size_t count) { + std::vector keys; + for (size_t i = 0; i < count && i < nodes.size(); ++i) + keys.push_back(nodes[i].remote_pubkey); + return keys; + }; + + // Nodes we've never heard of can't redirect us anywhere - this is what stops a response putting + // us in touch with something that isn't a registered service node + CHECK_FALSE(snode_pool->record_swarm_redirect(swarm_pubkey, {key_for(200), key_for(201)})); + + // Too few of the named nodes resolve to be a swarm + CHECK_FALSE(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 2))); + + // Naming the swarm we already calculated is the node contradicting itself + CHECK_FALSE(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(calculated, 6))); + + // A usable redirect is taken, and - the point of all this - no pool refresh is started for it + REQUIRE(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 4))); + CHECK_FALSE(snode_pool->debug_refresh_in_progress()); + + std::vector redirected; + snode_pool->debug_run_on_loop([&] { + snode_pool->get_swarm( + swarm_pubkey, true, [&](swarm::swarm_id_t, std::vector nodes) { + redirected = std::move(nodes); + }); + }); + CHECK(sorted(redirected) == + sorted(std::vector(elsewhere.begin(), elsewhere.begin() + 4))); + CHECK_FALSE(snode_pool->debug_refresh_in_progress()); + + // Nodes that keep disagreeing must not bounce us forever; after the third we stop believing + // them and the calculated swarm is back, for the caller to fall back on refreshing the pool + CHECK(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 5))); + CHECK(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 4))); + CHECK_FALSE(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 5))); + + std::vector after_giving_up; + snode_pool->debug_run_on_loop([&] { + snode_pool->get_swarm( + swarm_pubkey, true, [&](swarm::swarm_id_t, std::vector nodes) { + after_giving_up = std::move(nodes); + }); + }); + CHECK(sorted(after_giving_up) == sorted(calculated)); + + // A refreshed pool is ground truth again, so redirects correcting the old one are dropped + REQUIRE(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 4))); + snode_pool->update_cache(snode_cache); + + std::vector after_refresh; + snode_pool->debug_run_on_loop([&] { + snode_pool->get_swarm( + swarm_pubkey, true, [&](swarm::swarm_id_t, std::vector nodes) { + after_refresh = std::move(nodes); + }); + }); + CHECK(sorted(after_refresh) == sorted(calculated)); +} From 152a46e1efd94d2a871b202630f1cbd1ace6f31e Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Fri, 11 Sep 2026 10:18:51 +1000 Subject: [PATCH 04/68] Expire snode strikes where it matters, not only where it's reported `STRIKE_EXPIRY` was applied in `node_strike_count()` - which nothing in this repo calls - and on the disk load. Every place that actually decides something counted the raw vector instead, and `record_node_failure` only ever appends, so a node struck during a two-minute outage stayed out of path building, swarm answers and refresh candidates for the life of the process, and its timestamp vector grew without bound. Restarting was the only thing that cleared it, because loading is the one path that filtered. Counting is now in one place, used by all four, and a node's expired strikes are dropped when it collects a new one. Two things this uncovered, both only reachable with a strike threshold of 0, which is what `tests/test_snode_pool.cpp` has been running with: - comparing the count against the threshold with a bare `>=` excludes every node in the pool, including ones that have never failed, so a threshold of 0 has to keep meaning "drop a node on its first strike". - a permanent failure looped up to the threshold, recording no strikes at all and leaving a node we know is gone in rotation. --- include/session/network/snode_pool.hpp | 5 ++ src/network/snode_pool.cpp | 67 ++++++++++++------------ tests/test_snode_pool.cpp | 71 ++++++++++++++++++++++++++ 3 files changed, 109 insertions(+), 34 deletions(-) diff --git a/include/session/network/snode_pool.hpp b/include/session/network/snode_pool.hpp index 25995fc69..436cd632a 100644 --- a/include/session/network/snode_pool.hpp +++ b/include/session/network/snode_pool.hpp @@ -144,6 +144,11 @@ class SnodePool : public std::enable_shared_from_this { std::vector> _snode_refresh_results; std::vector> _after_snode_cache_refresh; + // Counts a node's strikes that haven't expired yet. `record_node_failure` only appends, so the + // raw vector answers a different question - every strike the node has ever collected. + size_t _active_strike_count(const ed25519_pubkey& key) const; + bool _node_struck_out(const ed25519_pubkey& key) const; + // Disk I/O functions void _load_from_disk(); static void _clear_disk_cache(const std::filesystem::path& path); diff --git a/src/network/snode_pool.cpp b/src/network/snode_pool.cpp index d41ce44d2..d4b9d7848 100644 --- a/src/network/snode_pool.cpp +++ b/src/network/snode_pool.cpp @@ -985,6 +985,25 @@ void SnodePool::clear_cache() { }); } +size_t SnodePool::_active_strike_count(const ed25519_pubkey& key) const { + auto it = _snode_strikes.find(key); + + if (it == _snode_strikes.end()) + return 0; + + auto threshold = sysclock_now_s() - STRIKE_EXPIRY; + + return std::ranges::count_if(it->second, [threshold](auto t) { return t > threshold; }); +} + +bool SnodePool::_node_struck_out(const ed25519_pubkey& key) const { + auto strikes = _active_strike_count(key); + + // The `strikes > 0` is what keeps a threshold of 0 meaning "drop a node on its first strike"; + // comparing straight against 0 also drops every node that has never failed at all + return (strikes > 0 && strikes >= _config.cache_node_strike_threshold); +} + void SnodePool::record_node_failure(const service_node& node, bool permanent) { record_node_failure(node.remote_pubkey, permanent); } @@ -992,18 +1011,17 @@ void SnodePool::record_node_failure(const service_node& node, bool permanent) { void SnodePool::record_node_failure(const ed25519_pubkey& key, bool permanent) { _loop->call([this, key, permanent] { auto now = sysclock_now_s(); + auto& stamps = _snode_strikes[key]; + std::erase_if(stamps, [threshold = now - STRIKE_EXPIRY](auto t) { return t <= threshold; }); - if (permanent) - for (int i = 0; i < _config.cache_node_strike_threshold; ++i) - _snode_strikes[key].push_back(now); - else - _snode_strikes[key].push_back(now); + // A permanent failure has to strike the node out whatever the threshold is - looping up to + // a threshold of 0 records nothing and leaves the node in rotation + auto strikes = (permanent ? std::max(1, _config.cache_node_strike_threshold) : 1); - log::trace( - cat, - "Recorded strike for node {}, total: {}", - key.hex(), - _snode_strikes[key].size()); + for (uint16_t i = 0; i < strikes; ++i) + stamps.push_back(now); + + log::trace(cat, "Recorded strike for node {}, total: {}", key.hex(), stamps.size()); // Throttle persisting the strikes to disk to at most every X minutes if (!_strikes_flush_scheduled && !_suspended) { @@ -1031,22 +1049,8 @@ uint16_t SnodePool::node_strike_count(const service_node& node) { } uint16_t SnodePool::node_strike_count(const ed25519_pubkey& key) { - return _loop->call_get([this, &key] { - auto it = _snode_strikes.find(key); - if (it == _snode_strikes.end()) - return uint16_t{0}; - - const auto& stamps = it->second; - - const auto threshold = sysclock_now_s() - STRIKE_EXPIRY; - - uint16_t count = 0; - for (auto t : stamps) - if (t > threshold) - count++; - - return count; - }); + return _loop->call_get( + [this, &key] { return static_cast(_active_strike_count(key)); }); } void SnodePool::clear_node_strikes() { @@ -1090,9 +1094,7 @@ void SnodePool::refresh_if_needed( in_use_keys.insert(node.remote_pubkey); for (const auto& node : _snode_cache) { - auto it = _snode_strikes.find(node.remote_pubkey); - if (it != _snode_strikes.end() && - it->second.size() >= _config.cache_node_strike_threshold) + if (_node_struck_out(node.remote_pubkey)) continue; // If the caller considers the node as already in use then it wouldn't be @@ -1319,9 +1321,7 @@ std::vector SnodePool::get_unused_nodes( continue; // Skip nodes with too many failures - auto it = _snode_strikes.find(node.remote_pubkey); - if (it != _snode_strikes.end() && - it->second.size() >= _config.cache_node_strike_threshold) + if (_node_struck_out(node.remote_pubkey)) continue; // Skip nodes whos IP addresses are in the exclusion list @@ -1357,8 +1357,7 @@ void SnodePool::get_swarm( std::ranges::shuffle(nodes, csrng); auto get_strike_count = [this](const service_node& node) -> size_t { - auto it = _snode_strikes.find(node.remote_pubkey); - return (it != _snode_strikes.end() ? it->second.size() : 0); + return _active_strike_count(node.remote_pubkey); }; // Partition into below-threshold and above-thresold. This keeps the shuffled order of diff --git a/tests/test_snode_pool.cpp b/tests/test_snode_pool.cpp index 87c0e3994..3518f0363 100644 --- a/tests/test_snode_pool.cpp +++ b/tests/test_snode_pool.cpp @@ -93,6 +93,23 @@ class TestSnodePool : public SnodePool { _loop->call_get([fn = std::move(fn)] { fn(); }); } + // Backdates every recorded strike so `STRIKE_EXPIRY` can be crossed without a 48h wait + void debug_age_strikes(std::chrono::seconds by) { + _loop->call_get([this, by] { + for (auto& [key, stamps] : _snode_strikes) + for (auto& stamp : stamps) + stamp -= by; + }); + } + + // Every strike on record, expired or not - which is what the decision sites used to count + size_t debug_recorded_strikes(const ed25519_pubkey& key) { + return _loop->call_get([this, &key] { + auto it = _snode_strikes.find(key); + return (it == _snode_strikes.end() ? size_t{0} : it->second.size()); + }); + } + void debug_on_refresh_complete(std::vector> raw_results) { auto total_requests = static_cast(raw_results.size()); _loop->call_get([&] { @@ -603,3 +620,57 @@ TEST_CASE("Network", "[network][swarm_redirect]") { }); CHECK(sorted(after_refresh) == sorted(calculated)); } + +TEST_CASE("Network", "[network][strike_expiry]") { + session::network::config::SnodePool pool_config{ + .cache_expiration = 5min, + .cache_min_lifetime = 5min, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .cache_min_size = 0, + .cache_min_swarm_size = 0, + .cache_num_nodes_to_use_for_refresh = 0, + .cache_min_num_refresh_presence_to_include_node = 0, + .cache_node_strike_threshold = 3}; + + // Strikes are keyed by node pubkey, so these have to differ per node or striking one strikes + // every node sharing its key + std::vector> ed_pks{ + "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7"_hexbytes, + "5ea34e72bb044654a6a23675690ef5ffaaf1656b02f93fb76655f9cbdbe89876"_hexbytes, + "e17a692033200ae41350df9709754edde7343e2cf2f23e88f993319e0720e5e5"_hexbytes, + "7b633fa6fb462b90db6f0f50384190ce7715e31b7aa93d87dbd7e94e33d4251f"_hexbytes}; + std::vector snode_cache; + + for (uint16_t i = 0; i < ed_pks.size(); ++i) + snode_cache.emplace_back(service_node{ + ed25519_pubkey::from_bytes(ed_pks[i]), + oxen::quic::ipv4{"192.168.0.{}"_format(i)}, + static_cast(20000 + i), + static_cast(30000 + i), + {2, 11, 0}, + 0}); + + auto loop = std::make_shared(); + auto disk_loop = std::make_shared(); + auto snode_pool = std::make_shared(pool_config, loop, disk_loop); + snode_pool->reset_state_with_cache(snode_cache); + + snode_pool->record_node_failure(snode_cache[0], true); + snode_pool->record_node_failure(snode_cache[1], true); + REQUIRE(snode_pool->node_strike_count(snode_cache[0]) == 3); + REQUIRE(snode_pool->get_unused_nodes(4).size() == 2); + + // Once the strikes are older than `STRIKE_EXPIRY` the node has to become selectable again; a + // node dropped for a blip two days ago is not evidence about the node now + snode_pool->debug_age_strikes(49h); + CHECK(snode_pool->node_strike_count(snode_cache[0]) == 0); + CHECK(snode_pool->get_unused_nodes(4).size() == 4); + + // ... and a fresh failure starts from one rather than stacking onto the expired ones, which is + // also what stops the vector growing for the life of the process + snode_pool->record_node_failure(snode_cache[0]); + CHECK(snode_pool->node_strike_count(snode_cache[0]) == 1); + CHECK(snode_pool->debug_recorded_strikes(snode_cache[0].remote_pubkey) == 1); +} From 1159595138ddd6329c651ab6a644980fa7e54b7e Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Fri, 11 Sep 2026 10:50:40 +1000 Subject: [PATCH 05/68] Drop a cached edge node once it has been struck out A cached edge node is handed to `_build_path` as a forced first hop, so it is the one node in a path that never passes the strike filter `get_unused_nodes` applies to the rest, and the only thing that dropped it was `edge_node_cache_duration` (10 days). So a node we already had evidence was unreachable got another path built onto it on every launch and every resume, and a path rotation carried it into the replacement path. It loses the cached-edge role rather than its place in the pool: it stays a node like any other and can be picked again once its strikes expire. Keeping the entry and merely skipping it would hand the role back at that expiry, by which point we have been running on a different edge node for two days - a second change of first hop, not a return to a stable one. --- .../network/routing/onion_request_router.hpp | 1 + include/session/network/snode_pool.hpp | 7 ++ src/network/routing/onion_request_router.cpp | 35 ++++++- src/network/snode_pool.cpp | 8 ++ tests/test_onion_request_router.cpp | 92 +++++++++++++++++++ 5 files changed, 140 insertions(+), 3 deletions(-) diff --git a/include/session/network/routing/onion_request_router.hpp b/include/session/network/routing/onion_request_router.hpp index 1dbbbcee3..da17f3c40 100644 --- a/include/session/network/routing/onion_request_router.hpp +++ b/include/session/network/routing/onion_request_router.hpp @@ -168,6 +168,7 @@ class OnionRequestRouter : public IRouter, public std::enable_shared_from_this { virtual void record_node_failure(const ed25519_pubkey& key, bool permanent = false); uint16_t node_strike_count(const service_node& node); uint16_t node_strike_count(const ed25519_pubkey& key); + + // Whether the node has collected enough unexpired strikes to be kept out of node selection. + // Callers that pick a node by some other route - a cached one, say - need this to apply the + // same bar `get_unused_nodes` does, rather than comparing a raw count to a threshold they'd + // have to know about. + virtual bool node_struck_out(const service_node& node); + virtual bool node_struck_out(const ed25519_pubkey& key); void clear_node_strikes(); // Checks if the pool is empty or stale and triggers a refresh if needed diff --git a/src/network/routing/onion_request_router.cpp b/src/network/routing/onion_request_router.cpp index 99f6c4549..9915dd453 100644 --- a/src/network/routing/onion_request_router.cpp +++ b/src/network/routing/onion_request_router.cpp @@ -595,9 +595,37 @@ void OnionRequestRouter::_finish_setup() { } } +// A cached edge node is handed to `_build_path` as a forced first hop, so it is the one node in a +// path that never passes the strike filter `get_unused_nodes` applies to the rest, and the only +// thing that dropped it was `edge_node_cache_duration` (10 days). +// +// Being struck out costs it the cached-edge-node role, not its place in the pool: it stays a node +// like any other and `get_unused_nodes` can pick it again once its strikes expire. Keeping the +// entry and merely skipping it would hand the role back at that expiry, by which point we have been +// running on a different edge node for two days - that is a second change of first hop, not a +// return to a stable one. +void OnionRequestRouter::_drop_struck_cached_edge_nodes() { + auto snode_pool = _snode_pool.lock(); + + if (!snode_pool) + return; + + std::erase_if(_cached_edge_nodes, [&snode_pool](const auto& cached) { + if (!snode_pool->node_struck_out(cached.node)) + return false; + + log::debug( + cat, + "Dropping cached edge node {}, it has been struck out.", + cached.node.to_string()); + return true; + }); +} + void OnionRequestRouter::_pre_build_paths_if_needed() { if (!_config.disable_pre_build_paths) { log::info(cat, "Pre-building initial paths."); + _drop_struck_cached_edge_nodes(); std::vector edge_nodes = _cached_edge_nodes; if (_config.single_path_mode) { @@ -2128,13 +2156,14 @@ void OnionRequestRouter::_rotate_path(const std::string& path_id, PathCategory c } // Get enough nodes for the path (if the edge node has been used for longer than the cache - // duration then we should create an entirely new path, otherwise we should try to reuse the - // edge node) + // duration, or has been struck out since we connected to it, then we should create an entirely + // new path, otherwise we should try to reuse the edge node) auto now = std::chrono::system_clock::now(); auto rotate_at = (std::chrono::steady_clock::now() + _config.path_rotation_frequency); std::vector rotated_path_nodes; - if (now > path.edge_first_connected_at + _config.edge_node_cache_duration) + if (now > path.edge_first_connected_at + _config.edge_node_cache_duration || + snode_pool->node_struck_out(edge_node)) rotated_path_nodes = snode_pool->get_unused_nodes(_config.path_length, nodes_to_exclude); else { rotated_path_nodes = diff --git a/src/network/snode_pool.cpp b/src/network/snode_pool.cpp index d4b9d7848..fe312431d 100644 --- a/src/network/snode_pool.cpp +++ b/src/network/snode_pool.cpp @@ -1053,6 +1053,14 @@ uint16_t SnodePool::node_strike_count(const ed25519_pubkey& key) { [this, &key] { return static_cast(_active_strike_count(key)); }); } +bool SnodePool::node_struck_out(const service_node& node) { + return node_struck_out(node.remote_pubkey); +} + +bool SnodePool::node_struck_out(const ed25519_pubkey& key) { + return _loop->call_get([this, &key] { return _node_struck_out(key); }); +} + void SnodePool::clear_node_strikes() { // Use 'call_get' to force this to be synchronous _loop->call_get([this] { diff --git a/tests/test_onion_request_router.cpp b/tests/test_onion_request_router.cpp index 8913315d8..910d0f217 100644 --- a/tests/test_onion_request_router.cpp +++ b/tests/test_onion_request_router.cpp @@ -50,6 +50,20 @@ class TestOnionRequestRouter { return 0; } + static void set_cached_edge_nodes( + std::shared_ptr router, std::vector nodes) { + router->_cached_edge_nodes = std::move(nodes); + } + + static std::vector cached_edge_nodes( + std::shared_ptr router) { + return router->_cached_edge_nodes; + } + + static void drop_struck_cached_edge_nodes(std::shared_ptr router) { + router->_drop_struck_cached_edge_nodes(); + } + static void build_path( std::shared_ptr router, PathCategory category, @@ -832,4 +846,82 @@ TEST_CASE("Network", "[network][onion_request_router][check_request_queue_timeou CHECK(result.timeout); } +TEST_CASE("Network", "[network][onion_request_router][cached_edge_nodes]") { + const auto node_strike_threshold = 3; + config::SnodePool pool_config = { + .cache_directory = std::nullopt, + .fallback_snode_pool_path = std::nullopt, + .cache_expiration = std::chrono::minutes{5}, + .cache_min_lifetime = std::chrono::minutes{5}, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .seed_nodes = {}, + .cache_min_size = 0, + .cache_min_swarm_size = 0, + .cache_num_nodes_to_use_for_refresh = 3, + .cache_min_num_refresh_presence_to_include_node = 2, + .cache_node_strike_threshold = node_strike_threshold}; + config::OnionRequestRouter config = { + file_server::DEFAULT_CONFIG, + std::nullopt, + std::chrono::days{10}, + opt::netid::Target::testnet, + {}, + network::opt::retry_delay{50ms, 200ms}, + 3, + 3, + 10, + 10min, + node_strike_threshold, + true, + true, + {{PathCategory::standard, 1}}}; + + auto ed_pk = "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7"_hexbytes; + auto ed_pk2 = "5ea34e72bb044654a6a23675690ef5ffaaf1656b02f93fb76655f9cbdbe89876"_hexbytes; + auto healthy = service_node{ + ed25519_pubkey::from_bytes(ed_pk), + oxen::quic::ipv4{"127.0.0.1"}, + 20001, + 30001, + {2, 11, 0}, + 0}; + auto struck = service_node{ + ed25519_pubkey::from_bytes(ed_pk2), + oxen::quic::ipv4{"127.0.0.2"}, + 20002, + 30002, + {2, 11, 0}, + 0}; + + auto loop = std::make_shared(); + auto disk_loop = std::make_shared(); + auto snode_pool = std::make_shared(pool_config, loop, disk_loop); + auto transport = std::make_shared(); + auto router = + std::make_shared(config, loop, disk_loop, snode_pool, transport); + + auto now = std::chrono::system_clock::now(); + TestOnionRequestRouter::set_cached_edge_nodes( + router, {cached_edge_node{healthy, now}, cached_edge_node{struck, now}}); + + // Both are well inside `edge_node_cache_duration`, which is the only thing that used to matter + TestOnionRequestRouter::drop_struck_cached_edge_nodes(router); + CHECK(TestOnionRequestRouter::cached_edge_nodes(router).size() == 2); + + // A cached edge node is forced as a path's first hop without going through `get_unused_nodes`, + // so nothing else would apply the strike filter to it. Striking it out has to cost it the + // cached-edge role outright - skipping it while keeping the entry would hand the role back when + // the strikes expire, long after we moved to another edge node. + snode_pool->SnodePool::record_node_failure(struck, true); + REQUIRE(snode_pool->node_struck_out(struck)); + + // Only the cached-edge role is lost; nothing here touches `_snode_cache`, so it stays a node + // like any other and `get_unused_nodes` can pick it again when its strikes expire + TestOnionRequestRouter::drop_struck_cached_edge_nodes(router); + auto remaining = TestOnionRequestRouter::cached_edge_nodes(router); + REQUIRE(remaining.size() == 1); + CHECK(remaining.front().node == healthy); +} } // namespace session::network From 6446f67a4c2d431dc1bdda95eb8a0bac00cb4056 Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Fri, 11 Sep 2026 10:46:00 +1000 Subject: [PATCH 06/68] Tell callers when the snode pool could not be refreshed `refresh_if_needed` had three ways to do nothing and say nothing: a suspended pool, no candidate nodes, and no fetcher. The callback was simply never invoked, and every caller sets its own state up before calling, so "never" is not a delay - it is permanent: - `_resync_clock` sets `_current_clock_resync_id` first, so a dropped callback makes every later clock resync short-circuit as "already in progress" and strands everything queued behind it. - both routers finish setup from the callback, so they never finish it. - `get_random_nodes` and the path builder retry from the callback, so their callers wait on something that will not arrive. The callback now takes whether a refresh actually happened, which is the smallest thing that lets a caller tell "the pool is fine" from "we could not find out". Nothing needing a refresh reports true - that is the answer the caller wanted, not a failure to get one. Each caller had to be given a failing branch, and two of them would have spun rather than hung if the callback had simply always been invoked: `get_random_nodes` re-enters itself, and the path builder rebuilds into the same too-few-nodes branch. `SnodePool` has no C API surface, so this is internal only. --- include/session/network/session_network.hpp | 2 +- include/session/network/snode_pool.hpp | 14 +++- src/network/routing/onion_request_router.cpp | 52 ++++++++++-- src/network/routing/session_router_router.cpp | 20 ++++- src/network/session_network.cpp | 48 +++++++++-- src/network/snode_pool.cpp | 75 +++++++++++------ tests/test_onion_request_router.cpp | 2 +- tests/test_snode_pool.cpp | 81 +++++++++++++++++-- 8 files changed, 240 insertions(+), 54 deletions(-) diff --git a/include/session/network/session_network.hpp b/include/session/network/session_network.hpp index cc495e9c8..2cc2c237b 100644 --- a/include/session/network/session_network.hpp +++ b/include/session/network/session_network.hpp @@ -128,7 +128,7 @@ class Network : public std::enable_shared_from_this { const uint8_t index, const service_node& node, const uint8_t total_requests); - void _on_clock_resync_complete(const uint8_t total_requests); + void _on_clock_resync_complete(); Request _preprocess_request(Request request); }; diff --git a/include/session/network/snode_pool.hpp b/include/session/network/snode_pool.hpp index 6eb5ed73a..64515c565 100644 --- a/include/session/network/snode_pool.hpp +++ b/include/session/network/snode_pool.hpp @@ -42,6 +42,12 @@ class empty_file_exception : public std::runtime_error { class SnodePool : public std::enable_shared_from_this { public: using network_fetcher_t = std::function; + + // `refreshed` is false when the pool could not be refreshed at all - suspended, no candidate + // nodes, no fetcher. Callers that retry their work on this callback have to check it: without + // it the only way to signal "that didn't happen" was to never call back, which leaves whatever + // the caller set up beforehand set up forever. + using refresh_callback_t = std::function; using fetcher_connectivity_check_t = std::function; SnodePool( @@ -81,15 +87,14 @@ class SnodePool : public std::enable_shared_from_this { // Checks if the pool is empty or stale and triggers a refresh if needed virtual void refresh_if_needed( const std::vector& in_use_nodes, - std::function on_refresh_complete = nullptr); + refresh_callback_t on_refresh_complete = nullptr); // Re-resolves `swarm_pubkey` after a node we believed was in its swarm has told us the account // isn't there. Where `refresh_if_needed` decides on the cache's age, this decides on that // rejection, so a mapping we have direct proof is wrong can be replaced long before // `cache_expiration`. `on_complete` runs once the swarm can be resolved again. virtual void invalidate_swarm( - session::network::x25519_pubkey swarm_pubkey, - std::function on_complete = nullptr); + session::network::x25519_pubkey swarm_pubkey, refresh_callback_t on_complete = nullptr); // Records the swarm a node named when it rejected a request for `swarm_pubkey`, so the mapping // can be corrected without refreshing the whole pool - a swarm change would otherwise have @@ -149,7 +154,7 @@ class SnodePool : public std::enable_shared_from_this { int _snode_cache_refresh_failure_count = 0; std::vector _refresh_candidate_nodes; std::vector> _snode_refresh_results; - std::vector> _after_snode_cache_refresh; + std::vector _after_snode_cache_refresh; // Counts a node's strikes that haven't expired yet. `record_node_failure` only appends, so the // raw vector answers a different question - every strike the node has ever collected. @@ -186,6 +191,7 @@ class SnodePool : public std::enable_shared_from_this { const bool use_direct_fetcher, const uint8_t total_requests); void _update_cache(std::string refresh_id, std::vector nodes); + void _run_pending_refresh_callbacks(bool refreshed); }; } // namespace session::network diff --git a/src/network/routing/onion_request_router.cpp b/src/network/routing/onion_request_router.cpp index 9915dd453..de0b947aa 100644 --- a/src/network/routing/onion_request_router.cpp +++ b/src/network/routing/onion_request_router.cpp @@ -331,7 +331,12 @@ OnionRequestRouter::OnionRequestRouter( } if (snode_pool->size() == 0) - snode_pool->refresh_if_needed({}, [weak_self = weak_from_this()] { + snode_pool->refresh_if_needed({}, [weak_self = weak_from_this()](bool refreshed) { + // Setup finishes either way: not finishing leaves the router permanently unusable, + // where finishing with an empty pool just means the first request refreshes again + if (!refreshed) + log::warning(cat, "Finishing router setup without a refreshed snode pool."); + if (auto self = weak_self.lock()) self->_loop->call([weak_self] { if (auto self = weak_self.lock()) @@ -1188,15 +1193,50 @@ void OnionRequestRouter::_build_path( snode_pool->refresh_if_needed( nodes_to_exclude, - [weak_self = weak_from_this(), - this, - category, - initiating_req_id, - nodes_to_exclude]() { + [weak_self = weak_from_this(), this, category, initiating_req_id, nodes_to_exclude]( + bool refreshed) { auto self = weak_self.lock(); if (!self) return; + // Rebuilding without a refresh lands back in this same branch with the same + // too-few nodes, so the queued requests would wait on a loop that cannot end + if (!refreshed) { + log::error( + cat, + "[Request {}]: Cannot build a path, the snode pool could not be " + "refreshed.", + initiating_req_id.value_or("internal")); + _update_status(); + + auto queue_it = _request_queues.find(category); + if (queue_it == _request_queues.end()) { + log::critical( + cat, + "No request queue for category '{}'.", + to_string(category, _config.single_path_mode)); + return; + } + + if (!queue_it->second->is_empty()) { + auto to_fail = queue_it->second->pop_all(); + log::error( + cat, + "Failing {} queued requests for '{}' paths; the snode pool " + "could not be refreshed.", + to_fail.size(), + to_string(category, _config.single_path_mode)); + + for (const auto& [req, cb] : to_fail) + cb(false, + false, + -1, + {content_type_plain_text}, + "Failed to refresh the snode pool to build a path."); + } + return; + } + log::info( cat, "[Request {}]: SnodePool refresh complete, retrying path build.", diff --git a/src/network/routing/session_router_router.cpp b/src/network/routing/session_router_router.cpp index cf1606d05..5dd80ecbd 100644 --- a/src/network/routing/session_router_router.cpp +++ b/src/network/routing/session_router_router.cpp @@ -131,11 +131,19 @@ void SessionRouter::_init() { return; if (snode_pool->size() == 0) - snode_pool->refresh_if_needed({}, [weak_self, this] { + snode_pool->refresh_if_needed({}, [weak_self, this](bool refreshed) { auto self = weak_self.lock(); if (!self) return; + // Setup finishes either way: not finishing leaves the router + // permanently unusable, where finishing with an empty pool just means + // the first request refreshes again + if (!refreshed) + log::warning( + cat, + "Finishing router setup without a refreshed snode pool."); + _loop->call([weak_self] { if (auto self = weak_self.lock()) self->_finish_setup(); @@ -458,11 +466,19 @@ void SessionRouter::_send_proxy_request(Request request, network_response_callba [weak_self = weak_from_this(), this, req = std::move(request), - cb = std::move(callback)]() { + cb = std::move(callback)](bool refreshed) { auto self = weak_self.lock(); if (!self) return; + if (!refreshed) + return cb( + false, + false, + -1, + {content_type_plain_text}, + "Failed to refresh the snode pool to find a proxy."); + auto snode_pool = _snode_pool.lock(); if (!snode_pool) return cb( diff --git a/src/network/session_network.cpp b/src/network/session_network.cpp index 24d4babce..1fdce62f1 100644 --- a/src/network/session_network.cpp +++ b/src/network/session_network.cpp @@ -410,8 +410,19 @@ void Network::get_random_nodes( std::vector nodes_to_exclude = _router->get_all_used_nodes(); return _snode_pool->refresh_if_needed( - nodes_to_exclude, - [this, count, cb = std::move(cb)] { get_random_nodes(count, cb); }); + nodes_to_exclude, [this, count, cb = std::move(cb)](bool refreshed) { + // Retrying without a refresh would re-enter this same branch and recurse + // until the stack gives out + if (!refreshed) { + log::warning( + cat, + "Cannot get {} random nodes: the pool could not be refreshed.", + count); + return cb({}); + } + + get_random_nodes(count, cb); + }); } cb(unused_nodes); }); @@ -868,7 +879,17 @@ void Network::_handle_421_retry( swarm_pubkey, req_to_retry = std::move(original_request), cb = std::move(final_callback), - failed_node = failed_node_copy]() mutable { + failed_node = failed_node_copy](bool swarm_resolved) mutable { + // Without a re-resolve the swarm cache still holds the mapping the 421 disproved, so the + // retry would go straight back to the swarm that just rejected us + if (!swarm_resolved) + return cb( + false, + false, + ERROR_MISDIRECTED_REQUEST, + {content_type_plain_text}, + "421 Misdirected Request, and the swarm could not be re-resolved"); + _snode_pool->get_swarm( swarm_pubkey, false, @@ -910,7 +931,7 @@ void Network::_handle_421_retry( // Taking its word (bounded - see `record_swarm_redirect`) fixes the one mapping we know is // wrong, where refreshing has every client of a changed swarm fetch the full node list for it. if (_snode_pool->record_swarm_redirect(swarm_pubkey, redirect_node_keys(response_body))) - return retry_on_resolved_swarm(); + return retry_on_resolved_swarm(true); // No usable redirect, so the pool itself is the only thing that can put this right _snode_pool->invalidate_swarm(swarm_pubkey, std::move(retry_on_resolved_swarm)); @@ -969,7 +990,20 @@ void Network::_resync_clock( // Refresh the snode pool if needed to ensure we have the most up-to-date cache std::vector nodes_to_exclude = _router->get_all_used_nodes(); - _snode_pool->refresh_if_needed(std::move(nodes_to_exclude), [this, request_id] { + _snode_pool->refresh_if_needed(std::move(nodes_to_exclude), [this, request_id](bool refreshed) { + // `_current_clock_resync_id` was set before this call, so giving up without clearing it + // blocks every later resync attempt for the life of the process and strands everything + // queued behind it. Completing with no results takes the existing "resync finished, + // successful or not" path, which does both and leaves the offset we already had alone - + // an old offset beats none, and this says nothing about whether it was right. + if (!refreshed) { + log::warning( + cat, + "[Request {}] Abandoning clock resync: the snode pool could not be refreshed.", + request_id); + return _on_clock_resync_complete(); + } + // Pick the random nodes we want to use for retrying (these won't change for this resync // attempt) auto resync_nodes = @@ -1076,11 +1110,11 @@ void Network::_launch_next_clock_out_of_sync_request( // If we've received all the results then we need to process them and complete the // resync if (_clock_resync_results.size() >= total_requests) - _on_clock_resync_complete(total_requests); + _on_clock_resync_complete(); }); } -void Network::_on_clock_resync_complete(const uint8_t /*total_requests*/) { +void Network::_on_clock_resync_complete() { auto raw_results = std::move(_clock_resync_results); auto refresh_id = std::move(*_current_clock_resync_id); diff --git a/src/network/snode_pool.cpp b/src/network/snode_pool.cpp index fe312431d..ac4e2a8e0 100644 --- a/src/network/snode_pool.cpp +++ b/src/network/snode_pool.cpp @@ -355,6 +355,11 @@ void SnodePool::_refresh_snode_cache(std::optional request_id_opt) _loop->call([this, request_id_opt] { if (_suspended) { log::info(cat, "Ignoring refresh as pool is suspended."); + + // Anything queued against a refresh we are declining to start has nothing left to wait + // for, unless one is already in flight and still owns it + if (!_current_snode_cache_refresh_id) + _run_pending_refresh_callbacks(false); return; } @@ -432,6 +437,7 @@ void SnodePool::_refresh_snode_cache(std::optional request_id_opt) (use_seed_nodes ? "No seed nodes are configured!" : "Found no nodes and decided not to use seed nodes!")); _current_snode_cache_refresh_id.reset(); + _run_pending_refresh_callbacks(false); return; } @@ -586,6 +592,7 @@ void SnodePool::_launch_next_refresh_request( cat, "[Request {}] No fetcher available, aborting refresh.", target_request_id); _current_snode_cache_refresh_id.reset(); _refresh_candidate_nodes.clear(); + _run_pending_refresh_callbacks(false); return; } @@ -910,28 +917,35 @@ void SnodePool::_update_cache(std::string refresh_id, std::vector SnodePool::_perform_cache_write(path, cache); }); - // Trigger any callbacks - // - // These must be moved out of the member before being run: a callback can re-enter the pool - // and register another post-refresh callback (`get_swarm` does exactly that if the cache is - // still empty), which would reallocate the vector we're iterating and leave us calling - // through a freed `std::function`. Anything registered while we're here accumulates in the - // now-empty member and runs after the next refresh instead of being silently discarded. - if (!_after_snode_cache_refresh.empty()) { - auto callbacks = std::move(_after_snode_cache_refresh); - _after_snode_cache_refresh.clear(); // A moved-from vector is valid but unspecified + _run_pending_refresh_callbacks(true); + }); +} - log::debug(cat, "Executing {} post-refresh callbacks.", callbacks.size()); +void SnodePool::_run_pending_refresh_callbacks(bool refreshed) { + if (_after_snode_cache_refresh.empty()) + return; - for (const auto& cb : callbacks) { - try { - cb(); - } catch (const std::exception& e) { - log::error(cat, "Exception thrown in a post-refresh callback: {}", e.what()); - } - } + // These must be moved out of the member before being run: a callback can re-enter the pool and + // register another post-refresh callback (`get_swarm` does exactly that if the cache is still + // empty), which would reallocate the vector we're iterating and leave us calling through a + // freed `std::function`. Anything registered while we're here accumulates in the now-empty + // member and runs after the next refresh instead of being silently discarded. + auto callbacks = std::move(_after_snode_cache_refresh); + _after_snode_cache_refresh.clear(); // A moved-from vector is valid but unspecified + + log::debug( + cat, + "Executing {} post-refresh callbacks ({}).", + callbacks.size(), + (refreshed ? "refreshed" : "refresh did not happen")); + + for (const auto& cb : callbacks) { + try { + cb(refreshed); + } catch (const std::exception& e) { + log::error(cat, "Exception thrown in a post-refresh callback: {}", e.what()); } - }); + } } // MARK: Public Functions @@ -1074,10 +1088,13 @@ void SnodePool::clear_node_strikes() { } void SnodePool::refresh_if_needed( - const std::vector& in_use_nodes, std::function on_refresh_complete) { + const std::vector& in_use_nodes, refresh_callback_t on_refresh_complete) { _loop->call([this, in_use_nodes, cb = std::move(on_refresh_complete)] { if (_suspended) { log::info(cat, "Ignoring refresh as pool is suspended."); + + if (cb) + cb(false); return; } @@ -1141,17 +1158,19 @@ void SnodePool::refresh_if_needed( } else _refresh_snode_cache(); else if (!already_running && cb) - cb(); + // Nothing needed refreshing, which is the answer the caller wanted rather than a + // failure to get one + cb(true); }); } -void SnodePool::invalidate_swarm(x25519_pubkey swarm_pubkey, std::function on_complete) { +void SnodePool::invalidate_swarm(x25519_pubkey swarm_pubkey, refresh_callback_t on_complete) { _loop->call([this, swarm_pubkey, cb = std::move(on_complete)]() mutable { if (_suspended) { log::info(cat, "Ignoring swarm invalidation as pool is suspended."); if (cb) - cb(); + cb(false); return; } @@ -1209,7 +1228,8 @@ void SnodePool::invalidate_swarm(x25519_pubkey swarm_pubkey, std::functionget_swarm(swarm_pubkey, ignore_strike_count, std::move(cb)); }); diff --git a/tests/test_onion_request_router.cpp b/tests/test_onion_request_router.cpp index 910d0f217..380dd2315 100644 --- a/tests/test_onion_request_router.cpp +++ b/tests/test_onion_request_router.cpp @@ -168,7 +168,7 @@ namespace { void refresh_if_needed( const std::vector& /*in_use_nodes*/, - std::function /*on_refresh_complete*/ = nullptr) override { + refresh_callback_t /*on_refresh_complete*/ = nullptr) override { func_called("refresh_if_needed"); // Do nothing (don't want to trigger a cache refresh) } diff --git a/tests/test_snode_pool.cpp b/tests/test_snode_pool.cpp index 3518f0363..63df35675 100644 --- a/tests/test_snode_pool.cpp +++ b/tests/test_snode_pool.cpp @@ -32,11 +32,11 @@ class TestSnodePool : public SnodePool { void refresh_if_needed( const std::vector& /*in_use_nodes*/, - std::function /*on_refresh_complete*/ = nullptr) override { + refresh_callback_t /*on_refresh_complete*/ = nullptr) override { // Do nothing (don't want to trigger a cache refresh) } - void debug_queue_post_refresh_callback(std::function cb) { + void debug_queue_post_refresh_callback(refresh_callback_t cb) { _loop->call_get([this, cb = std::move(cb)]() mutable { _after_snode_cache_refresh.push_back(std::move(cb)); }); @@ -110,6 +110,14 @@ class TestSnodePool : public SnodePool { }); } + // Reaches past the no-op override above to the real age-based policy, on the loop thread so it + // resolves inline + void debug_refresh_if_needed(refresh_callback_t cb) { + _loop->call_get([this, cb = std::move(cb)]() mutable { + SnodePool::refresh_if_needed({}, std::move(cb)); + }); + } + void debug_on_refresh_complete(std::vector> raw_results) { auto total_requests = static_cast(raw_results.size()); _loop->call_get([&] { @@ -126,7 +134,7 @@ class TestSnodePoolAgePolicy : public TestSnodePool { void refresh_if_needed( const std::vector& in_use_nodes, - std::function on_refresh_complete = nullptr) override { + refresh_callback_t on_refresh_complete = nullptr) override { SnodePool::refresh_if_needed(in_use_nodes, std::move(on_refresh_complete)); } }; @@ -317,12 +325,12 @@ TEST_CASE("Network", "[network][update_cache]") { // what a deferred `get_swarm` does when the refresh left the cache empty) rather than // invalidating the vector it's iterating std::vector callbacks_run; - snode_pool->debug_queue_post_refresh_callback([&] { + snode_pool->debug_queue_post_refresh_callback([&](bool) { callbacks_run.push_back(0); - snode_pool->debug_queue_post_refresh_callback([&] { callbacks_run.push_back(3); }); + snode_pool->debug_queue_post_refresh_callback([&](bool) { callbacks_run.push_back(3); }); }); - snode_pool->debug_queue_post_refresh_callback([&] { callbacks_run.push_back(1); }); - snode_pool->debug_queue_post_refresh_callback([&] { callbacks_run.push_back(2); }); + snode_pool->debug_queue_post_refresh_callback([&](bool) { callbacks_run.push_back(1); }); + snode_pool->debug_queue_post_refresh_callback([&](bool) { callbacks_run.push_back(2); }); REQUIRE(snode_pool->debug_remove_post_refresh_callback_spare_capacity()); snode_pool->update_cache({}); CHECK(callbacks_run == std::vector{0, 1, 2}); @@ -450,8 +458,9 @@ TEST_CASE("Network", "[network][invalidate_swarm]") { snode_pool->refresh_if_needed({}); age_policy_started_refresh = snode_pool->debug_refresh_in_progress(); - snode_pool->invalidate_swarm(swarm_pubkey, [&] { + snode_pool->invalidate_swarm(swarm_pubkey, [&](bool refreshed) { recovery_ran = true; + CHECK(refreshed); snode_pool->get_swarm( swarm_pubkey, true, [&](swarm::swarm_id_t, std::vector nodes) { recovered_swarm = std::move(nodes); @@ -674,3 +683,59 @@ TEST_CASE("Network", "[network][strike_expiry]") { CHECK(snode_pool->node_strike_count(snode_cache[0]) == 1); CHECK(snode_pool->debug_recorded_strikes(snode_cache[0].remote_pubkey) == 1); } + +TEST_CASE("Network", "[network][refresh_callback_contract]") { + session::network::config::SnodePool pool_config{ + .cache_expiration = 2h, + .cache_min_lifetime = 2s, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .seed_nodes = {}, + .cache_min_size = 0, + .cache_min_swarm_size = 0, + .cache_num_nodes_to_use_for_refresh = 0, + .cache_min_num_refresh_presence_to_include_node = 0, + .cache_node_strike_threshold = 3}; + auto ed_pk = "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7"_hexbytes; + std::vector snode_cache; + + for (uint16_t i = 0; i < 5; ++i) + snode_cache.emplace_back(service_node{ + ed25519_pubkey::from_bytes(ed_pk), + oxen::quic::ipv4{"192.168.0.{}"_format(i)}, + static_cast(20000 + i), + static_cast(30000 + i), + {2, 11, 0}, + 0}); + + auto loop = std::make_shared(); + auto disk_loop = std::make_shared(); + auto snode_pool = std::make_shared(pool_config, loop, disk_loop); + + auto run = [&snode_pool] { + std::pair result{false, true}; // {called, refreshed} + snode_pool->debug_refresh_if_needed( + [&result](bool refreshed) { result = {true, refreshed}; }); + return result; + }; + + // An empty cache and no seed nodes means the refresh cannot even start. The callback still has + // to run: callers set state up before calling (`_resync_clock` sets its in-progress id) and + // never hearing back leaves that set for the life of the process. + auto [called, refreshed] = run(); + CHECK(called); + CHECK_FALSE(refreshed); + + // Nothing needing a refresh is the answer the caller asked for, not a failure to get one + snode_pool->update_cache(snode_cache); + std::tie(called, refreshed) = run(); + CHECK(called); + CHECK(refreshed); + + // ... and a suspended pool reports that it didn't refresh rather than going quiet + snode_pool->suspend(); + std::tie(called, refreshed) = run(); + CHECK(called); + CHECK_FALSE(refreshed); +} From 9c274741cbe4f567d079fd64481c49651ae1fe3e Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 24 Sep 2026 15:45:09 -0300 Subject: [PATCH 07/68] Follow a 421's redirect for each account a batch rejects Issue: a batch or sequence request that gets a 421 carries its redirect inside each sub-response, but the redirect was only read from the top level of the body. Every batched 421 therefore fell back to a full pool refresh - the very thundering herd the redirect exists to prevent, on the path Session polls through. Separately, a batch that is rejected for some accounts and answered for others (as coalescing requests for several accounts into one batch to their shared swarm will produce) never reached the 421 handling at all, because its results aren't uniformly 421. Solution: the redirects are taken from every snode response, per account. `Request::swarm_pubkey` becomes `swarm_pubkeys`, one account per sub-request in order, and each 421 is attributed to the account at its position; the legacy C API fills this in by parsing the pregenerated batch body. Session storage server 2.12 also echoes the rejected account as `pubkey` in the 421 body, but that is the responding node's word, so it is only checked against the position: a 421 naming a different account is ignored. Trusting it instead would let any node the client talks to install a redirect for any account - a group everyone is in, say - rather than only the ones it was asked about. A rejection of a single account still retries the whole request on its (possibly redirected) swarm. A batch rejected for several accounts is not retried - a retry goes to one swarm - but its redirects are recorded, so the next request for each account goes to the right place. A rejection that names no usable swarm falls back to one pool refresh for the whole response. Because the redirects are now recorded before anything else happens to the response, a 421 on a request whose retry budget is already spent no longer discards its redirect either. The batch walk shared by `find_uniform_batch_error`, `_update_network_state` and the redirect extraction is now one `response::subresponses`, and the response body is parsed once rather than separately by each. Forward-porting to `client`: Core's `_swarm_request` needs to fill in `swarm_pubkeys` from the accounts it builds each body for. --- include/session/network/session_network.hpp | 11 +- .../session/network/session_network_types.h | 4 +- .../session/network/session_network_types.hpp | 61 +++++- src/network/session_network.cpp | 150 ++++++++------- src/network/session_network_types.cpp | 160 ++++++++++++++-- tests/test_network_swarm.cpp | 181 ++++++++++++++++++ 6 files changed, 469 insertions(+), 98 deletions(-) diff --git a/include/session/network/session_network.hpp b/include/session/network/session_network.hpp index 2cc2c237b..cb1ce2099 100644 --- a/include/session/network/session_network.hpp +++ b/include/session/network/session_network.hpp @@ -115,10 +115,17 @@ class Network : public std::enable_shared_from_this { void _close_connections(); void _recalculate_status(); void _update_status(ConnectionStatus new_status); - void _update_network_state(const std::string& body); + void _update_network_state(const nlohmann::json& json); + + // An account's redirect is left empty where there was none to take. + response::swarm_rejections _take_swarm_redirects( + const Request& request, const nlohmann::json* json, int16_t status_code); + void _refresh_if_unredirected(const response::swarm_rejections& rejections); void _handle_421_retry( Request original_request, - std::optional response_body, + response::swarm_rejections rejections, + std::vector> headers, + std::optional body, network_response_callback_t final_callback); void _resync_clock( diff --git a/include/session/network/session_network_types.h b/include/session/network/session_network_types.h index a830cdebb..f312d5381 100644 --- a/include/session/network/session_network_types.h +++ b/include/session/network/session_network_types.h @@ -66,7 +66,9 @@ typedef struct { // The account whose swarm this request addresses, as 64 hex chars of its X25519 pubkey — the // same value passed to session_network_get_swarm() to choose the destination node. Null for a // request aimed at a node rather than about an account (a cache refresh, a clock resync) or at - // a server, which no swarm membership applies to. + // a server, which no swarm membership applies to. For a `batch` or `sequence` request each + // sub-request's account is read from the body instead, and this is used only if the body + // can't be parsed. // // Set it whenever there is one: a storage server rejects a request whose pubkey is outside its // swarm with a 421, and recovering means re-resolving this account's swarm. Left null, such a diff --git a/include/session/network/session_network_types.hpp b/include/session/network/session_network_types.hpp index 266cbf12b..3b255321c 100644 --- a/include/session/network/session_network_types.hpp +++ b/include/session/network/session_network_types.hpp @@ -2,7 +2,9 @@ #include #include +#include #include +#include #include #include "session/network/key_types.hpp" @@ -166,15 +168,16 @@ struct Request { /// Any extra request details which may modify the structure of the request. RequestDetails details; - /// The account whose swarm this request addresses, when it addresses one: the X25519 pubkey of - /// a session ID, group ID, etc. Set it for anything sent to a swarm member *about* that - /// account, and leave it unset for a request merely aimed at a node (a snode cache refresh, a - /// clock resync), which no swarm membership applies to. + /// The accounts this request addresses: one entry per sub-request of a `batch` or `sequence`, + /// in order, or a single entry for any other request. Each is the 32-byte pubkey an account's + /// swarm is computed from (a session ID or group ID without its prefix); an entry is empty for + /// a sub-request that isn't about an account. A single entry applies to every sub-request. + /// Leave it empty for a request merely aimed at a node (a snode cache refresh, a clock resync). /// - /// Required to recover from a 421: the storage server rejects a request whose pubkey is not in - /// its swarm, and recovering means re-resolving the swarm of *this account*, which cannot be - /// derived from the node we happened to ask. - std::optional swarm_pubkey; + /// Required to recover from a 421: it is what says whose swarm the redirect a 421 carries is + /// for. The account a storage server names in a 421 is only checked against it, never trusted + /// in its place. + std::vector> swarm_pubkeys; /// The time the request was created, this is used primarily for determining whether the /// `overall_timeout` has been exceeded. @@ -266,9 +269,51 @@ using network_response_callback_t = std::function> headers, std::optional response)>; +/// The accounts of each sub-request in a pregenerated `batch`/`sequence` body, in the form +/// `Request::swarm_pubkeys` takes, for a request whose body was built by the caller. Returns +/// nullopt when `endpoint` is neither or the body can't be parsed. +std::optional>> batch_request_accounts( + std::string_view endpoint, std::span body); + namespace response { std::optional> parse_text_error(std::string_view body); std::optional find_uniform_batch_error(std::string_view body); + + /// As `find_uniform_batch_error`, for a body that has already been parsed. + std::optional uniform_batch_error(const nlohmann::json& json); + + /// One result of a `batch`/`sequence` response, or the whole of any other response. + struct subresponse { + /// The result's own status code; nullopt for a response that isn't a batch, whose status + /// is the one it came back with. + std::optional code; + + /// The result's body when it is a JSON object. Points into the parsed response. + const nlohmann::json* body = nullptr; + }; + + /// The sub-responses of a parsed response: one per entry of `results` for a batch or sequence, + /// otherwise the response itself as the only one. The returned bodies point into `json`. + std::vector subresponses(const nlohmann::json& json); + + /// The accounts a response's 421s rejected. + struct swarm_rejections { + /// Each rejected account, with the ed25519 pubkeys of the swarm its 421 redirected it to: + /// empty when the 421 named no swarm. An account with several 421s takes the first. + std::unordered_map> accounts; + + /// Whether a 421 could not be attributed to any account. + bool unattributed = false; + }; + + /// Finds the 421s in a storage server response. `json` is its parsed body, or null when the + /// body isn't JSON. `status_code` is the response's own status, which is the only status a + /// response that isn't a batch has. `accounts` is the request's `swarm_pubkeys`, which each + /// 421 is attributed by; a 421 naming a different account than its position does is ignored. + swarm_rejections find_swarm_rejections( + const nlohmann::json* json, + int16_t status_code, + std::span> accounts); } // namespace response struct OnionPathMetadata { diff --git a/src/network/session_network.cpp b/src/network/session_network.cpp index 1fdce62f1..0e7c8d73c 100644 --- a/src/network/session_network.cpp +++ b/src/network/session_network.cpp @@ -468,20 +468,34 @@ void Network::send_request(Request request, network_response_callback_t callback const auto dest_is_snode = std::holds_alternative(original_req.destination); + // Parsed once for everything below, since a retrieve's body can be large + std::optional json; + if (body) + if (auto parsed = nlohmann::json::parse(*body, nullptr, false); + !parsed.is_discarded()) + json = std::move(parsed); + // If we got a successful response (with a body) and the request was sent to a // service node then we should update the network state based on the response // (Note: we don't want to do this for server requests because they could // include values in different formats, eg. the "Session Network" API returns // `t` in seconds) - if (success && body && dest_is_snode) - _update_network_state(*body); + if (success && json && dest_is_snode) + _update_network_state(*json); int16_t final_status_code = status_code; - if (body) - if (auto uniform_error = response::find_uniform_batch_error(*body)) + if (json) + if (auto uniform_error = response::uniform_batch_error(*json)) final_status_code = *uniform_error; + // Taken from every snode response rather than only a 421 one: a batch can be + // rejected for some accounts and answered for others + response::swarm_rejections rejections; + if (dest_is_snode) + rejections = _take_swarm_redirects( + original_req, json ? &*json : nullptr, status_code); + // If we got a 406 from a snode, or a 425 from a server, then the device clock // is out of sync so we need to kick off a clock resync request if ((final_status_code == ERROR_NOT_ACCEPTABLE && dest_is_snode) || @@ -494,10 +508,17 @@ void Network::send_request(Request request, network_response_callback_t callback // cache, the original request might succeed after this refresh so we should // just automatically retry if (final_status_code == 421) { - _handle_421_retry(std::move(original_req), std::move(body), std::move(cb)); + _handle_421_retry( + std::move(original_req), + std::move(rejections), + std::move(headers), + std::move(body), + std::move(cb)); return; } + _refresh_if_unredirected(rejections); + // For debugging purposes we want to add a log if this was a successful request // after we did an automatic retry if (original_req.retry_count > 0) @@ -715,37 +736,22 @@ Request Network::_preprocess_request(Request request) { return request; } -void Network::_update_network_state(const std::string& body) { +void Network::_update_network_state(const nlohmann::json& json) { try { - auto json = nlohmann::json::parse(body); const nlohmann::json* target_json = &json; // If it was a batch/sequence request then take the one with the highest "t" value as that // would have been the one which was returned last - if (json.contains("results") && json["results"].is_array()) { - log::trace(cat, "Parsing batch response for latest network state."); - - int64_t max_t = -1; - const nlohmann::json* latest_body = nullptr; - - for (const auto& result : json["results"]) { - if (!result.is_object() || !result.contains("body") || !result["body"].is_object()) - continue; - - const auto& result_body = result["body"]; - - if (result_body.contains("t") && result_body["t"].is_number()) { - int64_t current_t = result_body["t"].get(); + int64_t max_t = -1; + for (const auto& sub : response::subresponses(json)) { + if (!sub.body) + continue; - if (current_t > max_t) { - max_t = current_t; - latest_body = &result_body; - } + if (auto t = sub.body->find("t"); t != sub.body->end() && t->is_number()) + if (auto current_t = t->get(); current_t > max_t) { + max_t = current_t; + target_json = sub.body; } - } - - if (latest_body) - target_json = latest_body; } // Update hardfork/softfork versions @@ -791,46 +797,40 @@ void Network::_update_network_state(const std::string& body) { // MARK: Specific Error Handling -// Pulls the node pubkeys out of a 421 body. Only the pubkeys: the rest of each record is contact -// information we deliberately don't read, so a redirect can't put us in touch with anything the -// pool hasn't already told us about. -static std::vector redirect_node_keys(const std::optional& body) { - std::vector keys; - - if (!body) - return keys; +// A node that rejects a request for an account usually names the swarm it actually belongs to. +// Taking its word (bounded - see `record_swarm_redirect`) fixes the one mapping we know is wrong, +// where refreshing has every client of a changed swarm fetch the full node list for it. +response::swarm_rejections Network::_take_swarm_redirects( + const Request& request, const nlohmann::json* json, int16_t status_code) { + auto rejections = response::find_swarm_rejections(json, status_code, request.swarm_pubkeys); - try { - auto json = nlohmann::json::parse(*body); - - if (!json.contains("snodes") || !json["snodes"].is_array()) - return keys; - - for (const auto& entry : json["snodes"]) { - if (!entry.contains("pubkey_ed25519") || !entry["pubkey_ed25519"].is_string()) - continue; + for (auto& [account, keys] : rejections.accounts) + if (!keys.empty() && !_snode_pool->record_swarm_redirect(account, keys)) + keys.clear(); - auto hex = entry["pubkey_ed25519"].get(); - - if (hex.size() == 64 && oxenc::is_hex(hex)) - keys.push_back(ed25519_pubkey::from_hex(hex)); - } - } catch (const std::exception& e) { - log::debug(cat, "Could not read a swarm redirect from the 421 body: {}", e.what()); - } + return rejections; +} - return keys; +// With no usable redirect the pool itself is the only thing that can put a rejection right, and +// one refresh re-resolves every account at once +void Network::_refresh_if_unredirected(const response::swarm_rejections& rejections) { + for (const auto& [account, keys] : rejections.accounts) + if (keys.empty()) + return _snode_pool->invalidate_swarm(account); } void Network::_handle_421_retry( Request original_request, - std::optional response_body, + response::swarm_rejections rejections, + std::vector> headers, + std::optional body, network_response_callback_t final_callback) { if (original_request.retry_count >= config.redirect_retry_count) { log::error( cat, "Request {} received 421 but exceeded max retry count.", original_request.request_id); + _refresh_if_unredirected(rejections); return final_callback( false, false, @@ -851,12 +851,12 @@ void Network::_handle_421_retry( "Received 421 from a non-service-node destination"); // A 421 says the account we asked about is not in this node's swarm, so recovering means - // re-resolving *that account's* swarm. Nothing about the node we asked can tell us which - // account that was, so a request that did not record one cannot be redirected. - if (!original_request.swarm_pubkey) { + // re-resolving *that account's* swarm; without knowing which account that was, there is + // nothing to re-resolve. + if (rejections.accounts.empty()) { log::warning( cat, - "Request {} received 421 but carries no swarm pubkey to re-resolve.", + "Request {} received 421 but names no account to re-resolve.", original_request.request_id); return final_callback( false, @@ -866,6 +866,19 @@ void Network::_handle_421_retry( "421 Misdirected Request for a request with no swarm"); } + // A retry goes to a single swarm, which a batch spanning several accounts doesn't have. Their + // redirects are already taken, so the next request for each goes to the right place. + if (rejections.accounts.size() > 1 || rejections.unattributed) { + log::info( + cat, + "Request {} received 421s for {} accounts; not retrying it as a whole.", + original_request.request_id, + rejections.accounts.size()); + _refresh_if_unredirected(rejections); + return final_callback( + false, false, ERROR_MISDIRECTED_REQUEST, std::move(headers), std::move(body)); + } + log::info( cat, "Request {} received 421 from node {}, re-resolving its swarm.", @@ -873,7 +886,7 @@ void Network::_handle_421_retry( original_dest_node->to_string()); auto failed_node_copy = *original_dest_node; - auto swarm_pubkey = *original_request.swarm_pubkey; + auto [swarm_pubkey, redirect] = *rejections.accounts.begin(); auto retry_on_resolved_swarm = [this, swarm_pubkey, @@ -927,13 +940,9 @@ void Network::_handle_421_retry( }); }; - // A node that rejects a request for an account usually names the swarm it actually belongs to. - // Taking its word (bounded - see `record_swarm_redirect`) fixes the one mapping we know is - // wrong, where refreshing has every client of a changed swarm fetch the full node list for it. - if (_snode_pool->record_swarm_redirect(swarm_pubkey, redirect_node_keys(response_body))) + if (!redirect.empty()) return retry_on_resolved_swarm(true); - // No usable redirect, so the pool itself is the only thing that can put this right _snode_pool->invalidate_swarm(swarm_pubkey, std::move(retry_on_resolved_swarm)); } @@ -1835,8 +1844,13 @@ LIBSESSION_C_API void session_network_send_request( std::nullopt, request_id}; - if (params->swarm_pubkey_hex) - request.swarm_pubkey = x25519_pubkey::from_hex({params->swarm_pubkey_hex, 64}); + std::optional>> batch_accounts; + if (request.body) + batch_accounts = batch_request_accounts(request.endpoint, *request.body); + if (batch_accounts) + request.swarm_pubkeys = std::move(*batch_accounts); + else if (params->swarm_pubkey_hex) + request.swarm_pubkeys = {x25519_pubkey::from_hex({params->swarm_pubkey_hex, 64})}; auto cpp_callback = [c_cb = callback, c_ctx = ctx]( bool success, diff --git a/src/network/session_network_types.cpp b/src/network/session_network_types.cpp index 4b40e1325..163fa0be6 100644 --- a/src/network/session_network_types.cpp +++ b/src/network/session_network_types.cpp @@ -73,35 +73,157 @@ std::optional> response::parse_text_error(std::string_v return std::nullopt; } +namespace { + inline auto cat = log::Cat("network"); + + const nlohmann::json* field( + const nlohmann::json& j, + std::string_view key, + bool (nlohmann::json::*is_kind)() const noexcept) { + auto it = j.find(key); + return it != j.end() && ((*it).*is_kind)() ? &*it : nullptr; + } + + std::optional account_in(const nlohmann::json& obj) { + auto pk = field(obj, "pubkey", &nlohmann::json::is_string); + if (!pk) + return std::nullopt; + + // Prefixed with the network id, except on testnet + auto hex = pk->get(); + if (hex.size() == 66) + hex.remove_prefix(2); + return x25519_pubkey::maybe_from_hex(hex); + } + + // Only the pubkeys: the rest of each record is contact information we deliberately don't read, + // so a redirect can't put us in touch with anything the pool hasn't already told us about. + std::vector redirect_keys(const nlohmann::json& body) { + std::vector keys; + + if (auto snodes = field(body, "snodes", &nlohmann::json::is_array)) + for (const auto& snode : *snodes) + if (auto pk = field(snode, "pubkey_ed25519", &nlohmann::json::is_string)) + if (auto key = ed25519_pubkey::maybe_from_hex(pk->get())) + keys.push_back(*key); + + return keys; + } + + std::optional account_by_position( + std::span> accounts, size_t index) { + if (accounts.size() == 1) + return accounts.front(); + return index < accounts.size() ? accounts[index] : std::nullopt; + } +} // namespace + std::optional response::find_uniform_batch_error(std::string_view body) { try { - auto json = nlohmann::json::parse(body); + return uniform_batch_error(nlohmann::json::parse(body)); + } catch (...) { /* Do nothing */ + } - // If it wasn't a batch response then just handle the non-batch status code - if (json.contains("results") && json["results"].is_array() && !json["results"].empty()) { - int16_t first_status_code = -1; + return std::nullopt; +} + +std::optional response::uniform_batch_error(const nlohmann::json& json) { + std::optional uniform; - for (const auto& result : json["results"]) { - if (!result.contains("code") || !result["code"].is_number()) - return std::nullopt; + // A response that isn't a batch has no per-result codes, so its own status stands + for (const auto& sub : subresponses(json)) { + if (!sub.code || (*sub.code >= 200 && *sub.code <= 299)) + return std::nullopt; + if (uniform && *uniform != *sub.code) + return std::nullopt; + uniform = sub.code; + } - // If we got a success then we can just use the original status code - int16_t code = result["code"].get(); - if (code >= 200 && code <= 299) - return std::nullopt; + return uniform; +} - if (first_status_code == -1) - first_status_code = code; - else if (first_status_code != code) - return std::nullopt; - } +std::vector response::subresponses(const nlohmann::json& json) { + auto results = field(json, "results", &nlohmann::json::is_array); + if (!results) + return {{std::nullopt, json.is_object() ? &json : nullptr}}; - return first_status_code; + std::vector subs; + subs.reserve(results->size()); + + for (const auto& result : *results) { + auto& sub = subs.emplace_back(); + if (auto code = field(result, "code", &nlohmann::json::is_number)) + sub.code = code->get(); + sub.body = field(result, "body", &nlohmann::json::is_object); + } + + return subs; +} + +std::optional>> batch_request_accounts( + std::string_view endpoint, std::span body) { + if (endpoint != "batch" && endpoint != "sequence") + return std::nullopt; + + auto json = nlohmann::json::parse(body.begin(), body.end(), nullptr, false); + auto requests = field(json, "requests", &nlohmann::json::is_array); + if (!requests) + return std::nullopt; + + std::vector> accounts; + accounts.reserve(requests->size()); + + for (const auto& req : *requests) { + auto& account = accounts.emplace_back(); + if (auto params = field(req, "params", &nlohmann::json::is_object)) + account = account_in(*params); + } + + return accounts; +} + +response::swarm_rejections response::find_swarm_rejections( + const nlohmann::json* json, + int16_t status_code, + std::span> accounts) { + swarm_rejections result; + + // A body that isn't JSON still leaves the response's own status to act on, just with no + // redirect to go with it + auto subs = json ? subresponses(*json) : std::vector{{}}; + + for (size_t i = 0; i < subs.size(); ++i) { + const auto& [code, sub_body] = subs[i]; + if (code.value_or(status_code) != ERROR_MISDIRECTED_REQUEST) + continue; + + // Attributed by position in our own request, never by the account the 421 names: that is + // the responding node's word, and taking it would let any node we talk to redirect any + // account it likes - not just the ones it was asked about - onto nodes of its choosing + auto account = account_by_position(accounts, i); + if (!account) { + result.unattributed = true; + continue; } - } catch (...) { /* Do nothing */ + + if (auto echoed = sub_body ? account_in(*sub_body) : std::nullopt; + echoed && *echoed != *account) { + log::warning( + cat, + "Ignoring a 421 for {} that names {} as the rejected account.", + account->hex(), + echoed->hex()); + result.unattributed = true; + continue; + } + + // Several sub-requests for one account (a retrieve per namespace, say) all name its swarm, + // so the first is as good as any + if (auto [it, inserted] = result.accounts.try_emplace(*account); inserted && sub_body) + it->second = redirect_keys(*sub_body); } - return std::nullopt; + return result; } } // namespace session::network diff --git a/tests/test_network_swarm.cpp b/tests/test_network_swarm.cpp index 887ea581e..1cd0df5c1 100644 --- a/tests/test_network_swarm.cpp +++ b/tests/test_network_swarm.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include @@ -198,3 +199,183 @@ TEST_CASE("Swarm", "[network][swarm][get_swarm]") { "05000000000000000000000000000000000000000000000000fffffffffffffffe", swarms) == 0); } + +namespace { +using json = nlohmann::json; + +x25519_pubkey account(char c) { + return x25519_pubkey::from_hex(std::string(64, c)); +} + +std::vector nodes(std::string_view chars) { + std::vector keys; + for (char c : chars) + keys.push_back(ed25519_pubkey::from_hex(std::string(64, c))); + return keys; +} + +json rejection(std::optional echoed, std::string_view node_chars) { + auto snodes = json::array(); + for (char c : node_chars) + snodes.push_back({{"pubkey_ed25519", std::string(64, c)}, {"ip", "10.0.0.1"}}); + + json body = {{"snodes", std::move(snodes)}, {"swarm", "abc"}}; + if (echoed) + body["pubkey"] = *echoed; + return body; +} + +json batch(std::vector> results) { + auto list = json::array(); + for (auto& [code, body] : results) + list.push_back({{"code", code}, {"body", std::move(body)}}); + return {{"results", std::move(list)}}; +} + +response::swarm_rejections rejections( + const json& body, + int16_t status_code, + std::vector> accounts = {}) { + return response::find_swarm_rejections(&body, status_code, accounts); +} + +const std::string A = "05" + std::string(64, 'a'); +const std::string B = "03" + std::string(64, 'b'); +} // namespace + +TEST_CASE("Swarm", "[network][swarm][batch_error]") { + CHECK(response::find_uniform_batch_error(batch({{421, {}}, {421, {}}}).dump()) == 421); + CHECK_FALSE(response::find_uniform_batch_error(batch({{421, {}}, {406, {}}}).dump())); + CHECK_FALSE(response::find_uniform_batch_error(batch({{421, {}}, {200, {}}}).dump())); + CHECK_FALSE(response::find_uniform_batch_error(batch({}).dump())); + CHECK_FALSE(response::find_uniform_batch_error(rejection(A, "12").dump())); + CHECK_FALSE(response::find_uniform_batch_error("not json")); +} + +TEST_CASE("Swarm", "[network][swarm][rejections]") { + SECTION("A plain 421 is attributed to the request's account") { + auto r = rejections(rejection(A, "123"), 421, {account('a')}); + CHECK_FALSE(r.unattributed); + REQUIRE(r.accounts.size() == 1); + CHECK(r.accounts.at(account('a')) == nodes("123")); + } + + SECTION("An account echoed in testnet form, without a prefix, still matches") { + auto r = rejections(rejection(std::string(64, 'a'), "12"), 421, {account('a')}); + REQUIRE(r.accounts.count(account('a'))); + CHECK(r.accounts.at(account('a')) == nodes("12")); + } + + SECTION("A 421 needn't name its account") { + auto r = rejections( + batch({{421, rejection(std::nullopt, "12")}, {421, rejection(std::nullopt, "34")}}), + 421, + {account('a'), account('b')}); + CHECK_FALSE(r.unattributed); + REQUIRE(r.accounts.size() == 2); + CHECK(r.accounts.at(account('a')) == nodes("12")); + CHECK(r.accounts.at(account('b')) == nodes("34")); + } + + SECTION("Nothing is found in a response that isn't a 421") { + auto r = rejections(json{{"t", 1}}, 200, {account('a')}); + CHECK(r.accounts.empty()); + CHECK_FALSE(r.unattributed); + } + + SECTION("A batch can reject some accounts and answer others") { + auto r = rejections( + batch({{421, rejection(A, "12")}, + {200, json{{"messages", json::array()}}}, + {421, rejection(B, "34")}}), + 200, + {account('a'), account('c'), account('b')}); + CHECK_FALSE(r.unattributed); + REQUIRE(r.accounts.size() == 2); + CHECK(r.accounts.at(account('a')) == nodes("12")); + CHECK(r.accounts.at(account('b')) == nodes("34")); + } + + SECTION("Several rejections of one account are one redirect") { + auto r = rejections( + batch({{421, rejection(A, "12")}, {421, rejection(A, "12")}}), 421, {account('a')}); + REQUIRE(r.accounts.size() == 1); + CHECK(r.accounts.at(account('a')) == nodes("12")); + } + + SECTION("A single account applies to every sub-request") { + auto r = rejections( + batch({{421, rejection(std::nullopt, "12")}, {421, rejection(std::nullopt, "12")}}), + 421, + {account('a')}); + REQUIRE(r.accounts.size() == 1); + CHECK(r.accounts.at(account('a')) == nodes("12")); + } + + SECTION("A sequence that stopped early is still attributed by position") { + auto r = rejections( + batch({{200, json::object()}, {421, rejection(std::nullopt, "34")}}), + 200, + {account('a'), account('b'), account('c')}); + REQUIRE(r.accounts.size() == 1); + CHECK(r.accounts.at(account('b')) == nodes("34")); + } + + // The account a 421 names is the responding node's word; taking it would let any node redirect + // any account it likes, not just those it was asked about + SECTION("The account a 421 names is never trusted in place of the request's") { + auto r = rejections(rejection(A, "12"), 421, {account('b')}); + CHECK(r.accounts.empty()); + CHECK(r.unattributed); + + r = rejections( + batch({{421, rejection("05" + std::string(64, 'c'), "12")}, + {421, rejection(B, "34")}}), + 421, + {account('a'), account('b')}); + CHECK(r.unattributed); + REQUIRE(r.accounts.size() == 1); + CHECK(r.accounts.at(account('b')) == nodes("34")); + + CHECK(rejections(rejection(A, "12"), 421).accounts.empty()); + } + + SECTION("A sub-request with no account leaves its 421 unattributed") { + auto r = rejections( + batch({{200, json::object()}, {421, rejection(std::nullopt, "12")}}), + 200, + {account('a'), std::nullopt}); + CHECK(r.accounts.empty()); + CHECK(r.unattributed); + } + + SECTION("A 421 whose body isn't JSON has no redirect") { + std::vector> accounts{account('a')}; + auto r = response::find_swarm_rejections(nullptr, 421, accounts); + REQUIRE(r.accounts.size() == 1); + CHECK(r.accounts.at(account('a')).empty()); + CHECK(response::find_swarm_rejections(nullptr, 200, accounts).accounts.empty()); + } +} + +TEST_CASE("Swarm", "[network][swarm][batch_request_accounts]") { + SECTION("A pregenerated batch body gives each sub-request's account") { + auto body = json{{"requests", + {{{"method", "retrieve"}, {"params", {{"pubkey", A}}}}, + {{"method", "info"}, {"params", json::object()}}, + {{"method", "retrieve"}, {"params", {{"pubkey", B}}}}}}} + .dump(); + auto bytes = std::span{reinterpret_cast(body.data()), body.size()}; + + auto accounts = batch_request_accounts("batch", bytes); + REQUIRE(accounts); + CHECK(*accounts == + std::vector>{account('a'), std::nullopt, account('b')}); + CHECK(batch_request_accounts("sequence", bytes) == accounts); + CHECK_FALSE(batch_request_accounts("retrieve", bytes)); + + std::string_view junk = "not json"; + CHECK_FALSE(batch_request_accounts( + "batch", {reinterpret_cast(junk.data()), junk.size()})); + } +} From 16be3674a734f7394dc59bf15e558bed81ba0aad Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 24 Sep 2026 15:56:32 -0300 Subject: [PATCH 08/68] Act on a destination's status only when its response decrypted Issue: an onion or proxied request's response is encrypted by the destination, and only a response that decrypts is the destination's answer. When decryption fails - as it does for anything a node along the path sends back on its own - the onion router and the session-router proxy both passed the outer HTTP status through unchanged. Network acts on some statuses as the destination's verdict: - 421 re-resolves the account's swarm, refreshing the whole pool when there is no usable redirect, and retries; - 406 resyncs the clock against the snode network; - 425 resyncs the clock against a server. So any node on the path could force a pool refresh or a clock resync just by answering with one of those statuses in plaintext. With 421 recovery now refreshing on evidence rather than on the pool's age, that is a cheap way to make a client fetch the full node list. Solution: when a response can't be decrypted, those three statuses are reported as a new ERROR_UNAUTHENTICATED_RESPONSE instead. Every other status passes through as before: the same path also carries timeouts and transport failures, and the onion router's path-failure handling matches on the statuses nodes along the path return, none of which is one of these three. The error message now carries the status the node sent, since the reported status no longer does. Requests sent to a storage server through session-router tunnels, and by the direct router, are unaffected: they aren't body-encrypted, their status is the destination's own over an authenticated connection, and they never reach either decryption path. --- .../session/network/session_network_types.hpp | 8 ++ src/network/routing/onion_request_router.cpp | 86 +++++++------ src/network/routing/session_router_router.cpp | 55 +++++---- src/network/session_network_types.cpp | 9 ++ tests/test_onion_request_router.cpp | 116 +++++++++++++++++- 5 files changed, 203 insertions(+), 71 deletions(-) diff --git a/include/session/network/session_network_types.hpp b/include/session/network/session_network_types.hpp index 3b255321c..52e6e6b5b 100644 --- a/include/session/network/session_network_types.hpp +++ b/include/session/network/session_network_types.hpp @@ -30,6 +30,7 @@ constexpr int16_t ERROR_FAILED_TO_QUEUE_REQUEST = -10008; constexpr int16_t ERROR_INVALID_DESTINATION = -10009; constexpr int16_t ERROR_FAILED_GENERATE_ONION_PAYLOAD = -10010; constexpr int16_t ERROR_FAILED_TO_GET_STREAM = -10011; +constexpr int16_t ERROR_UNAUTHENTICATED_RESPONSE = -10012; constexpr int16_t ERROR_BUILD_TIMEOUT = -10100; constexpr int16_t ERROR_REQUEST_CANCELLED = -10200; constexpr int16_t ERROR_UNKNOWN = -11000; @@ -282,6 +283,13 @@ namespace response { /// As `find_uniform_batch_error`, for a body that has already been parsed. std::optional uniform_batch_error(const nlohmann::json& json); + /// The status to report for a proxied response that could not be decrypted, whose status + /// therefore came from whichever node on the way answered rather than from the destination. + /// Statuses that are acted on as the destination's verdict (406, 421, 425) become + /// `ERROR_UNAUTHENTICATED_RESPONSE`, since any node on the path could have sent them; anything + /// else is returned unchanged. + int16_t undecrypted_status(int16_t status); + /// One result of a `batch`/`sequence` response, or the whole of any other response. struct subresponse { /// The result's own status code; nullopt for a response that isn't a batch, whose status diff --git a/src/network/routing/onion_request_router.cpp b/src/network/routing/onion_request_router.cpp index de0b947aa..c3f0ad044 100644 --- a/src/network/routing/onion_request_router.cpp +++ b/src/network/routing/onion_request_router.cpp @@ -1634,51 +1634,49 @@ void OnionRequestRouter::_send_on_path( return; } - auto decryption_callback = [weak_self = weak_from_this(), - this, - parser = std::move(parser), - path_id = path.id, - original_request = std::move(request), - cb = std::move(callback)]( - bool success, - bool timeout, - int16_t status, - auto headers, - auto response) { - auto self = weak_self.lock(); - if (!self) - return; + auto decryption_callback = + [weak_self = weak_from_this(), + this, + parser = std::move(parser), + path_id = path.id, + original_request = std::move(request), + cb = std::move(callback)]( + bool success, bool timeout, int16_t status, auto headers, auto response) { + auto self = weak_self.lock(); + if (!self) + return; - try { - if (!success) - throw std::runtime_error{response.value_or("Unknown request failure")}; - if (timeout) - throw std::runtime_error{response.value_or("Timed out")}; - if (!response) - throw std::runtime_error{"Unexpected empty response"}; - - onionreq::DecryptedResponse decrypted = parser->decrypted_response(*response); - _handle_transport_response( - path_id, - std::move(original_request), - true, - false, - decrypted.status_code, - std::move(decrypted.headers), - std::move(decrypted.body), - std::move(cb)); - } catch (const std::exception& e) { - _handle_transport_response( - path_id, - std::move(original_request), - false, - timeout, - status, - std::move(headers), - std::move("Failed to handle onion response due to error: {}"_format(e.what())), - std::move(cb)); - } - }; + try { + if (!success) + throw std::runtime_error{response.value_or("Unknown request failure")}; + if (timeout) + throw std::runtime_error{response.value_or("Timed out")}; + if (!response) + throw std::runtime_error{"Unexpected empty response"}; + + onionreq::DecryptedResponse decrypted = parser->decrypted_response(*response); + _handle_transport_response( + path_id, + std::move(original_request), + true, + false, + decrypted.status_code, + std::move(decrypted.headers), + std::move(decrypted.body), + std::move(cb)); + } catch (const std::exception& e) { + _handle_transport_response( + path_id, + std::move(original_request), + false, + timeout, + response::undecrypted_status(status), + std::move(headers), + "Failed to handle onion response (status {}) due to error: {}"_format( + status, e.what()), + std::move(cb)); + } + }; transport->send_request(std::move(onion_request), std::move(decryption_callback)); } diff --git a/src/network/routing/session_router_router.cpp b/src/network/routing/session_router_router.cpp index 5dd80ecbd..f8f54d814 100644 --- a/src/network/routing/session_router_router.cpp +++ b/src/network/routing/session_router_router.cpp @@ -539,32 +539,35 @@ void SessionRouter::_send_proxy_request(Request request, network_response_callba request.time_remaining(), request.overall_timeout}; - auto proxy_callback = - [parser = std::move(parser), cb = std::move(callback)]( - bool success, bool timeout, int16_t status, auto headers, auto response) { - try { - if (!success) - throw std::runtime_error{response.value_or("Unknown request failure")}; - if (timeout) - throw std::runtime_error{response.value_or("Timed out")}; - if (!response) - throw std::runtime_error{"Unexpected empty response"}; - - onionreq::DecryptedResponse decrypted = parser->decrypted_response(*response); - cb(true, - false, - decrypted.status_code, - std::move(decrypted.headers), - std::move(decrypted.body)); - } catch (const std::exception& e) { - cb(false, - timeout, - status, - std::move(headers), - "Failed to handle proxied request response due to error: {}"_format( - e.what())); - } - }; + auto proxy_callback = [parser = std::move(parser), cb = std::move(callback)]( + bool success, + bool timeout, + int16_t status, + auto headers, + auto response) { + try { + if (!success) + throw std::runtime_error{response.value_or("Unknown request failure")}; + if (timeout) + throw std::runtime_error{response.value_or("Timed out")}; + if (!response) + throw std::runtime_error{"Unexpected empty response"}; + + onionreq::DecryptedResponse decrypted = parser->decrypted_response(*response); + cb(true, + false, + decrypted.status_code, + std::move(decrypted.headers), + std::move(decrypted.body)); + } catch (const std::exception& e) { + cb(false, + timeout, + response::undecrypted_status(status), + std::move(headers), + "Failed to handle proxied request response (status {}) due to error: {}"_format( + status, e.what())); + } + }; // Now that we have a service_node destination we can send a direct request _send_direct_request(std::move(proxy_request), std::move(proxy_callback)); diff --git a/src/network/session_network_types.cpp b/src/network/session_network_types.cpp index 163fa0be6..f64e6a0d6 100644 --- a/src/network/session_network_types.cpp +++ b/src/network/session_network_types.cpp @@ -118,6 +118,15 @@ namespace { } } // namespace +int16_t response::undecrypted_status(int16_t status) { + switch (status) { + case ERROR_NOT_ACCEPTABLE: + case ERROR_MISDIRECTED_REQUEST: + case ERROR_TOO_EARLY: return ERROR_UNAUTHENTICATED_RESPONSE; + default: return status; + } +} + std::optional response::find_uniform_batch_error(std::string_view body) { try { return uniform_batch_error(nlohmann::json::parse(body)); diff --git a/tests/test_onion_request_router.cpp b/tests/test_onion_request_router.cpp index 380dd2315..d668b0e46 100644 --- a/tests/test_onion_request_router.cpp +++ b/tests/test_onion_request_router.cpp @@ -78,6 +78,14 @@ class TestOnionRequestRouter { return router->_find_valid_path(request); } + static void send_on_path( + std::shared_ptr router, + OnionPath& path, + Request request, + network_response_callback_t callback) { + router->_send_on_path(path, std::move(request), std::move(callback)); + } + static void handle_transport_response( std::shared_ptr router, std::string path_id, @@ -218,8 +226,19 @@ namespace { func_called("remove_failure_listeners"); } - void send_request(Request /*request*/, network_response_callback_t /*callback*/) override { + // Answered the way a node on the path does when it fails a request itself: a status of its + // own and a plaintext body, which is nothing the destination encrypted + std::optional> plaintext_reply; + + void send_request(Request /*request*/, network_response_callback_t callback) override { func_called("send_request"); + if (plaintext_reply) + callback( + false, + false, + plaintext_reply->first, + {content_type_plain_text}, + plaintext_reply->second); } }; @@ -924,4 +943,99 @@ TEST_CASE("Network", "[network][onion_request_router][cached_edge_nodes]") { REQUIRE(remaining.size() == 1); CHECK(remaining.front().node == healthy); } + +TEST_CASE("Network", "[network][onion_request_router][undecrypted_response]") { + config::SnodePool pool_config = { + .cache_directory = std::nullopt, + .fallback_snode_pool_path = std::nullopt, + .cache_expiration = std::chrono::minutes{5}, + .cache_min_lifetime = std::chrono::minutes{5}, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .seed_nodes = {}, + .cache_min_size = 0, + .cache_min_swarm_size = 0, + .cache_num_nodes_to_use_for_refresh = 3, + .cache_min_num_refresh_presence_to_include_node = 2, + .cache_node_strike_threshold = 3}; + config::OnionRequestRouter config = { + file_server::DEFAULT_CONFIG, + std::nullopt, + std::chrono::days{10}, + opt::netid::Target::testnet, + {}, + network::opt::retry_delay{50ms, 200ms}, + 3, + 3, + 10, + 10min, + 3, + true, + true, + {{PathCategory::standard, 1}}}; + + auto node = [](std::string_view pk_hex, uint16_t port) { + return service_node{ + ed25519_pubkey::from_hex(pk_hex), + oxen::quic::ipv4{"127.0.0.1"}, + port, + static_cast(port + 10000), + {2, 11, 0}, + 0}; + }; + auto target = node("4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7", 20001); + auto path_nodes = std::vector{ + node("5ea34e72bb044654a6a23675690ef5ffaaf1656b02f93fb76655f9cbdbe89876", 20002), + node("e17a692033200ae41350df9709754edde7343e2cf2f23e88f993319e0720e5e5", 20003), + node("7b633fa6fb462b90db6f0f50384190ce7715e31b7aa93d87dbd7e94e33d4251f", 20004)}; + + auto loop = std::make_shared(); + auto disk_loop = std::make_shared(); + auto snode_pool = std::make_shared(pool_config, loop, disk_loop); + auto transport = std::make_shared(); + auto router = + std::make_shared(config, loop, disk_loop, snode_pool, transport); + TestOnionRequestRouter::set_paths( + router, PathCategory::standard, {OnionPath{"Test", path_nodes}}); + + auto send_with_reply = [&](int16_t status) { + transport->plaintext_reply.emplace(status, "Forged by a node on the path"); + auto request = Request{ + "AAAA", target, "retrieve", to_vector("{}"), RequestCategory::standard, 10s}; + auto* path = TestOnionRequestRouter::find_valid_path(router, request); + REQUIRE(path); + + std::optional result; + TestOnionRequestRouter::send_on_path( + router, + *path, + request, + [&result]( + bool success, + bool timeout, + int16_t status_code, + std::vector> headers, + std::optional response) { + result = {success, timeout, status_code, headers, response}; + }); + REQUIRE(result); + return *result; + }; + + // Each of these is acted on as the destination's verdict (a swarm redirect, a clock resync), + // which only the destination can give; a node on the path sending one mustn't pass for it + for (int16_t status : {ERROR_MISDIRECTED_REQUEST, ERROR_NOT_ACCEPTABLE, ERROR_TOO_EARLY}) { + CAPTURE(status); + auto result = send_with_reply(status); + CHECK_FALSE(result.success); + CHECK(result.status_code == ERROR_UNAUTHENTICATED_RESPONSE); + CHECK(result.response.value_or("").find("status {}"_format(status)) != std::string::npos); + } + + // Anything else a node on the path says about its own failure is reported as it was + auto result = send_with_reply(502); + CHECK_FALSE(result.success); + CHECK(result.status_code == 502); +} } // namespace session::network From 6499e95e842696bf66c6ae4f6e02f930b87955af Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 24 Sep 2026 16:15:01 -0300 Subject: [PATCH 09/68] Follow a swarm redirect without checking it against our own grouping Issue: a redirect was refused as "the node contradicting itself" when it named the swarm calculated from our pool. That comparison measures a redirect against exactly the data the 421 says is out of date. Swarms can be rearranged any way at all - members join or leave, a swarm is disbanded and its members scattered, a new one is formed from nodes anywhere in the pool - so the account's actual swarm can relate to our grouping in any way: the same, a part of it, overlapping, or disjoint. How a redirect compares with it says nothing about whether the redirect is right. In particular, once a redirect had been followed to swarm T, a node in T correctly naming the calculated swarm - which is how a wrong redirect gets put right - was refused, and since refused redirects don't count towards the limit, the account stayed pinned to T until a pool refresh, which invalidate_swarm declines while the pool is under a minute old or its backoff is active. Solution: the comparison is gone. A redirect is followed whenever enough of the nodes it names resolve against our pool. What bounds a redirect is unchanged and never depended on the comparison: only nodes already in the pool can be named, and every redirect is dropped at the next pool refresh. --- src/network/snode_pool.cpp | 20 ------------ tests/test_snode_pool.cpp | 64 ++++++++++++++++++-------------------- 2 files changed, 31 insertions(+), 53 deletions(-) diff --git a/src/network/snode_pool.cpp b/src/network/snode_pool.cpp index ac4e2a8e0..9408ceff3 100644 --- a/src/network/snode_pool.cpp +++ b/src/network/snode_pool.cpp @@ -1260,26 +1260,6 @@ bool SnodePool::record_swarm_redirect( return false; } - // A redirect naming the swarm we already calculated is the node contradicting itself - it - // rejected the request and then pointed us back at the nodes we asked through. Refusing it - // sends the caller off to refresh the pool, which is the only thing that can help - auto computed = swarm::get_swarm(swarm_pubkey, _all_swarms); - if (computed.second.size() == resolved.size()) { - std::unordered_set computed_keys; - for (const auto& node : computed.second) - computed_keys.insert(node.remote_pubkey); - - if (std::ranges::all_of(resolved, [&computed_keys](const auto& node) { - return computed_keys.count(node.remote_pubkey) > 0; - })) { - log::debug( - cat, - "Ignoring redirect for {}: it names the swarm we already calculated.", - swarm_pubkey.hex()); - return false; - } - } - auto& [nodes, redirects] = _swarm_overrides[swarm_pubkey]; if (++redirects > MAX_CONSECUTIVE_SWARM_REDIRECTS) { diff --git a/tests/test_snode_pool.cpp b/tests/test_snode_pool.cpp index 63df35675..52d59b0f8 100644 --- a/tests/test_snode_pool.cpp +++ b/tests/test_snode_pool.cpp @@ -583,51 +583,49 @@ TEST_CASE("Network", "[network][swarm_redirect]") { // Too few of the named nodes resolve to be a swarm CHECK_FALSE(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 2))); - // Naming the swarm we already calculated is the node contradicting itself - CHECK_FALSE(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(calculated, 6))); + auto current_swarm = [&] { + std::vector swarm; + snode_pool->debug_run_on_loop([&] { + snode_pool->get_swarm( + swarm_pubkey, true, [&](swarm::swarm_id_t, std::vector nodes) { + swarm = std::move(nodes); + }); + }); + return sorted(std::move(swarm)); + }; + auto overridden = sorted(std::vector(elsewhere.begin(), elsewhere.begin() + 4)); // A usable redirect is taken, and - the point of all this - no pool refresh is started for it REQUIRE(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 4))); CHECK_FALSE(snode_pool->debug_refresh_in_progress()); - - std::vector redirected; - snode_pool->debug_run_on_loop([&] { - snode_pool->get_swarm( - swarm_pubkey, true, [&](swarm::swarm_id_t, std::vector nodes) { - redirected = std::move(nodes); - }); - }); - CHECK(sorted(redirected) == - sorted(std::vector(elsewhere.begin(), elsewhere.begin() + 4))); + CHECK(current_swarm() == overridden); CHECK_FALSE(snode_pool->debug_refresh_in_progress()); - // Nodes that keep disagreeing must not bounce us forever; after the third we stop believing - // them and the calculated swarm is back, for the caller to fall back on refreshing the pool - CHECK(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 5))); + // How the named swarm relates to the one we sent to says nothing, since swarms can be + // rearranged any way at all: a node that has left the overridden swarm names its current + // members, and one in it naming the calculated swarm is how a wrong redirect gets put right CHECK(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 4))); - CHECK_FALSE(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 5))); + CHECK(current_swarm() == overridden); + CHECK(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(calculated, 6))); + CHECK(current_swarm() == sorted(calculated)); - std::vector after_giving_up; - snode_pool->debug_run_on_loop([&] { - snode_pool->get_swarm( - swarm_pubkey, true, [&](swarm::swarm_id_t, std::vector nodes) { - after_giving_up = std::move(nodes); - }); - }); - CHECK(sorted(after_giving_up) == sorted(calculated)); + // Every redirect counts, though, so two sets of nodes that keep disagreeing can't bounce us + // between them forever; after the third we stop believing them and the calculated swarm is + // back, for the caller to fall back on refreshing the pool + CHECK_FALSE(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 4))); + CHECK(current_swarm() == sorted(calculated)); // A refreshed pool is ground truth again, so redirects correcting the old one are dropped REQUIRE(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 4))); snode_pool->update_cache(snode_cache); - - std::vector after_refresh; - snode_pool->debug_run_on_loop([&] { - snode_pool->get_swarm( - swarm_pubkey, true, [&](swarm::swarm_id_t, std::vector nodes) { - after_refresh = std::move(nodes); - }); - }); - CHECK(sorted(after_refresh) == sorted(calculated)); + CHECK(current_swarm() == sorted(calculated)); + + // ... and the calculated swarm itself, or part of it, is followed like any other + CHECK(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(calculated, 6))); + CHECK(current_swarm() == sorted(calculated)); + auto remaining = std::vector(calculated.begin() + 1, calculated.end()); + CHECK(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(remaining, 5))); + CHECK(current_swarm() == sorted(remaining)); } TEST_CASE("Network", "[network][strike_expiry]") { From 190f017a4b008edd9d026a13b6050460e9bb6fff Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 24 Sep 2026 16:25:56 -0300 Subject: [PATCH 10/68] Check the pool can now serve a caller before retrying it Issue: refresh_if_needed reports true both when a refresh ran and when nothing needed refreshing, and in the latter case calls back straight away - inline, since Network, the pool and the routers share one loop. Two callers retried on true without checking that they could now get what they needed: - get_random_nodes called itself again; - _build_path rebuilt the path. get_unused_nodes applies subnet diversity, exclusions and strikes, none of which refresh_if_needed's count of usable nodes does, so a pool can be healthy by refresh_if_needed's measure and still unable to supply the caller. Each retry then landed back in the same branch with nothing changed, recursing until the stack gave out: get_random_nodes from the C API with a count the pool can't meet, _build_path on a pool whose usable nodes sit in too few /24s to fill a path, such as a small testnet or devnet. This predates the refresh callback reporting a result - it only stopped the retry when a refresh could not be started at all. Solution: both check before retrying, as the session-router proxy selection already did, so each makes at most one refresh request. get_random_nodes calls back with an empty list, per its documented contract, and _build_path fails the queued requests for the category through the same path as a refresh that could not start, with messages that now say which it was. The onion router test's snode pool can now call back from refresh_if_needed, up to a limit so that code which asks again on every callback stops rather than overflowing the stack. Against the unfixed _build_path the new test sees 21 refresh requests and the queued request never answered; with the fix it sees one, and the request failed. --- src/network/routing/onion_request_router.cpp | 31 ++- src/network/session_network.cpp | 17 +- tests/test_onion_request_router.cpp | 197 +++++++++++++------ 3 files changed, 168 insertions(+), 77 deletions(-) diff --git a/src/network/routing/onion_request_router.cpp b/src/network/routing/onion_request_router.cpp index c3f0ad044..c828f1f21 100644 --- a/src/network/routing/onion_request_router.cpp +++ b/src/network/routing/onion_request_router.cpp @@ -1199,14 +1199,25 @@ void OnionRequestRouter::_build_path( if (!self) return; - // Rebuilding without a refresh lands back in this same branch with the same - // too-few nodes, so the queued requests would wait on a loop that cannot end - if (!refreshed) { + // Rebuilding lands back in this same branch unless the pool can now fill a + // path, and `refreshed` includes nothing having needed refreshing, which calls + // back inline - so rebuilding without checking first recurses until the stack + // gives out + std::optional cannot_build; + if (!refreshed) + cannot_build = "the snode pool could not be refreshed"; + else if (auto pool = _snode_pool.lock(); + !pool || + pool->get_unused_nodes(_config.path_length, nodes_to_exclude).size() < + _config.path_length) + cannot_build = "the snode pool has too few usable nodes"; + + if (cannot_build) { log::error( cat, - "[Request {}]: Cannot build a path, the snode pool could not be " - "refreshed.", - initiating_req_id.value_or("internal")); + "[Request {}]: Cannot build a path, {}.", + initiating_req_id.value_or("internal"), + *cannot_build); _update_status(); auto queue_it = _request_queues.find(category); @@ -1222,17 +1233,17 @@ void OnionRequestRouter::_build_path( auto to_fail = queue_it->second->pop_all(); log::error( cat, - "Failing {} queued requests for '{}' paths; the snode pool " - "could not be refreshed.", + "Failing {} queued requests for '{}' paths; {}.", to_fail.size(), - to_string(category, _config.single_path_mode)); + to_string(category, _config.single_path_mode), + *cannot_build); for (const auto& [req, cb] : to_fail) cb(false, false, -1, {content_type_plain_text}, - "Failed to refresh the snode pool to build a path."); + "Cannot build a path: {}."_format(*cannot_build)); } return; } diff --git a/src/network/session_network.cpp b/src/network/session_network.cpp index 0e7c8d73c..baeeccaf1 100644 --- a/src/network/session_network.cpp +++ b/src/network/session_network.cpp @@ -411,8 +411,6 @@ void Network::get_random_nodes( return _snode_pool->refresh_if_needed( nodes_to_exclude, [this, count, cb = std::move(cb)](bool refreshed) { - // Retrying without a refresh would re-enter this same branch and recurse - // until the stack gives out if (!refreshed) { log::warning( cat, @@ -421,7 +419,20 @@ void Network::get_random_nodes( return cb({}); } - get_random_nodes(count, cb); + // `refreshed` includes nothing having needed refreshing, which calls back + // inline, so asking again of a pool that can't supply `count` would + // re-enter this branch until the stack gives out + auto nodes = _snode_pool->get_unused_nodes(count); + if (nodes.size() < count) { + log::warning( + cat, + "Cannot get {} random nodes: the pool has only {} to give.", + count, + nodes.size()); + return cb({}); + } + + cb(std::move(nodes)); }); } cb(unused_nodes); diff --git a/tests/test_onion_request_router.cpp b/tests/test_onion_request_router.cpp index d668b0e46..778c608d6 100644 --- a/tests/test_onion_request_router.cpp +++ b/tests/test_onion_request_router.cpp @@ -174,11 +174,21 @@ namespace { SnodePool::record_node_failure(key, permanent); } + // When set, `refresh_if_needed` calls back with it straight away - as the real one does, on + // the loop thread, when nothing needs refreshing - instead of never calling back. Only the + // first `max_refresh_callbacks` calls do, so code that asks again on every callback stops + // there instead of recursing until the stack gives out. + std::optional refresh_result; + int max_refresh_callbacks = 20; + void refresh_if_needed( const std::vector& /*in_use_nodes*/, - refresh_callback_t /*on_refresh_complete*/ = nullptr) override { + refresh_callback_t on_refresh_complete = nullptr) override { func_called("refresh_if_needed"); - // Do nothing (don't want to trigger a cache refresh) + // Don't trigger a real cache refresh + if (refresh_result && on_refresh_complete && + get_call_count("refresh_if_needed") <= max_refresh_callbacks) + on_refresh_complete(*refresh_result); } void get_swarm( @@ -249,6 +259,60 @@ namespace { std::vector> headers; std::optional response; }; + + config::SnodePool test_pool_config() { + return {.cache_directory = std::nullopt, + .fallback_snode_pool_path = std::nullopt, + .cache_expiration = std::chrono::minutes{5}, + .cache_min_lifetime = std::chrono::minutes{5}, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .seed_nodes = {}, + .cache_min_size = 0, + .cache_min_swarm_size = 0, + .cache_num_nodes_to_use_for_refresh = 3, + .cache_min_num_refresh_presence_to_include_node = 2, + .cache_node_strike_threshold = 3}; + } + + config::OnionRequestRouter test_router_config() { + return {.file_server_config = file_server::DEFAULT_CONFIG, + .cache_directory = std::nullopt, + .edge_node_cache_duration = std::chrono::days{10}, + .netid = opt::netid::Target::testnet, + .seed_nodes = {}, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .path_length = 3, + .path_strike_threshold = 3, + .path_build_retry_limit = 10, + .path_rotation_frequency = 10min, + .node_strike_threshold = 3, + .disable_pre_build_paths = true, + .single_path_mode = true, + .min_path_counts = {{PathCategory::standard, 1}}}; + } + + service_node test_node(std::string_view pk_hex, uint16_t port) { + return service_node{ + ed25519_pubkey::from_hex(pk_hex), + oxen::quic::ipv4{"127.0.0.1"}, + port, + static_cast(port + 10000), + {2, 11, 0}, + 0}; + } + + network_response_callback_t record_into(std::optional& result) { + return [&result]( + bool success, + bool timeout, + int16_t status_code, + std::vector> headers, + std::optional response) { + result = {success, timeout, status_code, headers, response}; + }; + } } // namespace TEST_CASE("Network", "[network][onion_request_router][handle_errors]") { @@ -945,80 +1009,40 @@ TEST_CASE("Network", "[network][onion_request_router][cached_edge_nodes]") { } TEST_CASE("Network", "[network][onion_request_router][undecrypted_response]") { - config::SnodePool pool_config = { - .cache_directory = std::nullopt, - .fallback_snode_pool_path = std::nullopt, - .cache_expiration = std::chrono::minutes{5}, - .cache_min_lifetime = std::chrono::minutes{5}, - .enforce_subnet_diversity = false, - .retry_delay = network::opt::retry_delay{50ms, 200ms}, - .netid = opt::netid::Target::testnet, - .seed_nodes = {}, - .cache_min_size = 0, - .cache_min_swarm_size = 0, - .cache_num_nodes_to_use_for_refresh = 3, - .cache_min_num_refresh_presence_to_include_node = 2, - .cache_node_strike_threshold = 3}; - config::OnionRequestRouter config = { - file_server::DEFAULT_CONFIG, - std::nullopt, - std::chrono::days{10}, - opt::netid::Target::testnet, - {}, - network::opt::retry_delay{50ms, 200ms}, - 3, - 3, - 10, - 10min, - 3, - true, - true, - {{PathCategory::standard, 1}}}; - - auto node = [](std::string_view pk_hex, uint16_t port) { - return service_node{ - ed25519_pubkey::from_hex(pk_hex), - oxen::quic::ipv4{"127.0.0.1"}, - port, - static_cast(port + 10000), - {2, 11, 0}, - 0}; - }; - auto target = node("4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7", 20001); + auto target = + test_node("4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7", 20001); auto path_nodes = std::vector{ - node("5ea34e72bb044654a6a23675690ef5ffaaf1656b02f93fb76655f9cbdbe89876", 20002), - node("e17a692033200ae41350df9709754edde7343e2cf2f23e88f993319e0720e5e5", 20003), - node("7b633fa6fb462b90db6f0f50384190ce7715e31b7aa93d87dbd7e94e33d4251f", 20004)}; + test_node("5ea34e72bb044654a6a23675690ef5ffaaf1656b02f93fb76655f9cbdbe89876", 20002), + test_node("e17a692033200ae41350df9709754edde7343e2cf2f23e88f993319e0720e5e5", 20003), + test_node("7b633fa6fb462b90db6f0f50384190ce7715e31b7aa93d87dbd7e94e33d4251f", 20004)}; auto loop = std::make_shared(); auto disk_loop = std::make_shared(); - auto snode_pool = std::make_shared(pool_config, loop, disk_loop); + auto snode_pool = std::make_shared(test_pool_config(), loop, disk_loop); auto transport = std::make_shared(); - auto router = - std::make_shared(config, loop, disk_loop, snode_pool, transport); - TestOnionRequestRouter::set_paths( - router, PathCategory::standard, {OnionPath{"Test", path_nodes}}); + auto router = std::make_shared( + test_router_config(), loop, disk_loop, snode_pool, transport); + + // The router is driven on the loop, as its own code is, and checked from here + loop->call_get([&] { + TestOnionRequestRouter::set_paths( + router, PathCategory::standard, {OnionPath{"Test", path_nodes}}); + }); auto send_with_reply = [&](int16_t status) { transport->plaintext_reply.emplace(status, "Forged by a node on the path"); auto request = Request{ "AAAA", target, "retrieve", to_vector("{}"), RequestCategory::standard, 10s}; - auto* path = TestOnionRequestRouter::find_valid_path(router, request); - REQUIRE(path); + bool have_path = false; std::optional result; - TestOnionRequestRouter::send_on_path( - router, - *path, - request, - [&result]( - bool success, - bool timeout, - int16_t status_code, - std::vector> headers, - std::optional response) { - result = {success, timeout, status_code, headers, response}; - }); + loop->call_get([&] { + if (auto* path = TestOnionRequestRouter::find_valid_path(router, request)) { + have_path = true; + TestOnionRequestRouter::send_on_path(router, *path, request, record_into(result)); + } + }); + REQUIRE(have_path); REQUIRE(result); return *result; }; @@ -1038,4 +1062,49 @@ TEST_CASE("Network", "[network][onion_request_router][undecrypted_response]") { CHECK_FALSE(result.success); CHECK(result.status_code == 502); } + +TEST_CASE("Network", "[network][onion_request_router][build_path_too_few_nodes]") { + auto loop = std::make_shared(); + auto disk_loop = std::make_shared(); + auto snode_pool = std::make_shared(test_pool_config(), loop, disk_loop); + auto transport = std::make_shared(); + auto router = std::make_shared( + test_router_config(), loop, disk_loop, snode_pool, transport); + + // Run on the loop, as the router's own code is: that also puts it after the router's setup, + // which asks for the (empty) pool to be refreshed and mustn't be counted below + std::optional result; + loop->call_get([&] { + snode_pool->reset_calls(); + + auto queue = std::make_shared(loop); + TestOnionRequestRouter::set_request_queues(router, {{PathCategory::standard, queue}}); + queue->add( + Request{"AAAA", + test_node( + "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7", + 20001), + "retrieve", + to_vector("{}"), + RequestCategory::standard, + 10s}, + record_into(result)); + + // A path needs three nodes and the pool can only offer one, while saying nothing needs + // refreshing - which is a pool too concentrated in a few subnets to fill a path, say + snode_pool->mock_unused_nodes = std::vector{test_node( + "5ea34e72bb044654a6a23675690ef5ffaaf1656b02f93fb76655f9cbdbe89876", 20002)}; + snode_pool->refresh_result = true; + + TestOnionRequestRouter::build_path(router, PathCategory::standard, "AAAA"); + }); + + // Asking for a refresh once and then giving up; without checking that the pool can now fill a + // path, every "refreshed" rebuilt straight into another refresh request, and only the mock's + // limit stops it + CHECK(snode_pool->get_call_count("refresh_if_needed") == 1); + REQUIRE(result); + CHECK_FALSE(result->success); + CHECK(result->response.value_or("").find("too few usable nodes") != std::string::npos); +} } // namespace session::network From 35387a982501f8864984258dc3255b19d9eb912b Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 24 Sep 2026 16:55:28 -0300 Subject: [PATCH 11/68] Keep following swarm redirects past the limit, and ask for a refresh Issue: after MAX_CONSECUTIVE_SWARM_REDIRECTS (3) redirects for an account, the next was refused and the account's override erased, for the caller to fall back on refreshing the pool. But that refresh goes through invalidate_swarm's throttle, which declines while the pool is under a minute old or its backoff is active - exactly when a network-wide rearrangement makes hitting the limit likely. When it declined, the request failed, the account went back to the swarm calculated from the pool (the one the first 421 had already disproved), and with the entry erased the count started over from zero, so the limit never held. The count was also never reset by anything but a refresh, so "consecutive" was wrong, and legitimate changes to a swarm's membership spent it just as disagreeing nodes did. Solution: the limit only ever asks for a refresh; it never refuses a redirect, since refusing one only guarantees the request fails. Past it, each further redirect is followed as usual and also asks invalidate_swarm for a refresh, so the refresh happens at the first redirect its throttle allows, and until then the account stays on its latest redirect. Renamed to SWARM_REDIRECTS_BEFORE_REFRESH for what it now does, and raised to 8: a genuine bounce between disagreeing nodes still reaches it within a few requests, while ordinary rearrangements, which take one or two redirects an account, don't. The count saturates rather than wrapping, since it keeps climbing for as long as the refresh stays throttled. --- include/session/network/snode_pool.hpp | 4 +-- src/network/snode_pool.cpp | 42 ++++++++++++++++---------- tests/test_snode_pool.cpp | 28 ++++++++++++++--- 3 files changed, 52 insertions(+), 22 deletions(-) diff --git a/include/session/network/snode_pool.hpp b/include/session/network/snode_pool.hpp index 64515c565..4ebd252aa 100644 --- a/include/session/network/snode_pool.hpp +++ b/include/session/network/snode_pool.hpp @@ -135,8 +135,8 @@ class SnodePool : public std::enable_shared_from_this { // Swarms a node has redirected us to, which `get_swarm` prefers over its own calculation. Kept // apart from `_swarm_cache` deliberately: that is a memo of `_all_swarms` and stays one, where - // these are claims from outside that outrank it until the pool is refreshed. The count bounds - // how far a disagreement between nodes can bounce us before we go and refresh instead. + // these are claims from outside that outrank it until the pool is refreshed. The count is the + // account's redirects since that refresh, which past a limit also ask for the next one. std::unordered_map, uint8_t>> _swarm_overrides; std::map> _snode_strikes; diff --git a/src/network/snode_pool.cpp b/src/network/snode_pool.cpp index 9408ceff3..a1f327810 100644 --- a/src/network/snode_pool.cpp +++ b/src/network/snode_pool.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -55,9 +56,12 @@ namespace { // exactly what a persistent rejection source would produce. const std::chrono::seconds EVIDENCE_REFRESH_BASE_BACKOFF = 1min; - // Two nodes disagreeing about who owns a swarm can redirect us back and forth; after this many - // in a row without an intervening pool refresh, stop believing them and go and refresh. - constexpr uint8_t MAX_CONSECUTIVE_SWARM_REDIRECTS = 3; + // An account redirected more than this many times within one pool generation is being bounced + // between nodes that disagree, or its swarm has moved on too far for our pool to keep up. A + // redirect is still the best information we have, so past it each one is still followed, and + // also asks for the refresh that can settle it. Legitimate rearrangements count too (nothing + // resets this short of a refresh), hence the headroom. + constexpr uint8_t SWARM_REDIRECTS_BEFORE_REFRESH = 8; } // namespace SnodePool::SnodePool( @@ -1261,25 +1265,31 @@ bool SnodePool::record_swarm_redirect( } auto& [nodes, redirects] = _swarm_overrides[swarm_pubkey]; + nodes = std::move(resolved); + + // Saturating, because counting carries on past the limit for as long as the refresh it + // asks for is throttled, and wrapping would stop it asking + if (redirects < std::numeric_limits::max()) + ++redirects; + + log::info( + cat, + "Redirected to a swarm of {} nodes for {} (redirect {} since the pool was " + "refreshed).", + nodes.size(), + swarm_pubkey.hex(), + redirects); - if (++redirects > MAX_CONSECUTIVE_SWARM_REDIRECTS) { + if (redirects > SWARM_REDIRECTS_BEFORE_REFRESH) { log::warning( cat, - "Dropping redirects for {} after {} in a row; refreshing the pool instead.", + "{} has been redirected {} times since the pool was refreshed; asking for a " + "refresh.", swarm_pubkey.hex(), - MAX_CONSECUTIVE_SWARM_REDIRECTS); - _swarm_overrides.erase(swarm_pubkey); - return false; + redirects); + invalidate_swarm(swarm_pubkey); } - log::info( - cat, - "Redirected to a swarm of {} nodes for {} ({} of at most {}).", - resolved.size(), - swarm_pubkey.hex(), - redirects, - MAX_CONSECUTIVE_SWARM_REDIRECTS); - nodes = std::move(resolved); return true; }); } diff --git a/tests/test_snode_pool.cpp b/tests/test_snode_pool.cpp index 52d59b0f8..764c143db 100644 --- a/tests/test_snode_pool.cpp +++ b/tests/test_snode_pool.cpp @@ -609,11 +609,24 @@ TEST_CASE("Network", "[network][swarm_redirect]") { CHECK(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(calculated, 6))); CHECK(current_swarm() == sorted(calculated)); - // Every redirect counts, though, so two sets of nodes that keep disagreeing can't bounce us - // between them forever; after the third we stop believing them and the calculated swarm is - // back, for the caller to fall back on refreshing the pool - CHECK_FALSE(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 4))); + // Two sets of nodes that disagree, each redirecting to the other + auto bounce = [&](int times) { + for (int i = 0; i < times; ++i) + REQUIRE(snode_pool->record_swarm_redirect( + swarm_pubkey, i % 2 == 0 ? keys_of(elsewhere, 4) : keys_of(calculated, 6))); + }; + + // Every redirect counts, but none is refused for it - refusing would only fail the request. + // Up to the limit nothing else happens... + bounce(5); + CHECK(current_swarm() == overridden); + CHECK_FALSE(snode_pool->debug_refresh_in_progress()); + + // ... and past it the redirect is still followed, but also asks for a refresh, which the pool + // being old enough lets start + CHECK(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(calculated, 6))); CHECK(current_swarm() == sorted(calculated)); + CHECK(snode_pool->debug_refresh_in_progress()); // A refreshed pool is ground truth again, so redirects correcting the old one are dropped REQUIRE(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 4))); @@ -626,6 +639,13 @@ TEST_CASE("Network", "[network][swarm_redirect]") { auto remaining = std::vector(calculated.begin() + 1, calculated.end()); CHECK(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(remaining, 5))); CHECK(current_swarm() == sorted(remaining)); + + // Past the limit with the refresh throttled - the pool was only just refreshed - redirects are + // still followed, rather than leaving the account on a swarm already known to be wrong + bounce(6); + CHECK(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 4))); + CHECK(current_swarm() == overridden); + CHECK_FALSE(snode_pool->debug_refresh_in_progress()); } TEST_CASE("Network", "[network][strike_expiry]") { From 78c55b9ebccfc3548b7978b206ddc3ea9068d129 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 24 Sep 2026 17:12:08 -0300 Subject: [PATCH 12/68] Follow a redirect with the nodes of it we know, and refresh for the rest Issue: a redirect was refused unless at least cache_min_swarm_size of the nodes it named were in our pool. That is the realistic way a redirect can't be followed in full: a swarm rearranged partly out of nodes that registered after our last pool refresh. The nodes we do know are still members of the account's actual swarm, but refusing the redirect left the account on the swarm that had just rejected it, with the request falling back to invalidate_swarm - which declines while the pool is under a minute old or its backoff is active, and when it declines fails the request outright. Solution: a redirect is followed with whichever of its nodes are in our pool, and refused only when none are. When some of the named nodes are unknown and that leaves fewer than cache_min_swarm_size, it also asks invalidate_swarm for a refresh, through the same throttle as the redirect limit, to fill in the rest. A small swarm whose members are all known doesn't count, since the pool isn't missing anything. Failing the request when the swarm can't be re-resolved is kept, and now says why: it is reached only when no node the redirect named is one we know, so a retry could only go back to the swarm that rejected us. --- src/network/session_network.cpp | 6 ++++-- src/network/snode_pool.cpp | 20 +++++++++++++------- tests/test_snode_pool.cpp | 17 ++++++++++++++--- 3 files changed, 31 insertions(+), 12 deletions(-) diff --git a/src/network/session_network.cpp b/src/network/session_network.cpp index baeeccaf1..3662479a6 100644 --- a/src/network/session_network.cpp +++ b/src/network/session_network.cpp @@ -904,8 +904,10 @@ void Network::_handle_421_retry( req_to_retry = std::move(original_request), cb = std::move(final_callback), failed_node = failed_node_copy](bool swarm_resolved) mutable { - // Without a re-resolve the swarm cache still holds the mapping the 421 disproved, so the - // retry would go straight back to the swarm that just rejected us + // Without a re-resolve there is nothing better than the mapping the 421 disproved - a + // redirect naming any node we know would have been followed instead - so a retry would go + // straight back to the swarm that just rejected us. The refresh has been asked for, and + // the account's next rejection asks again. if (!swarm_resolved) return cb( false, diff --git a/src/network/snode_pool.cpp b/src/network/snode_pool.cpp index a1f327810..788bd0fea 100644 --- a/src/network/snode_pool.cpp +++ b/src/network/snode_pool.cpp @@ -1254,16 +1254,21 @@ bool SnodePool::record_swarm_redirect( if (named.count(node.remote_pubkey)) resolved.push_back(node); - if (resolved.size() < _config.cache_min_swarm_size) { + if (resolved.empty()) { log::debug( cat, - "Ignoring redirect for {}: only {}/{} named nodes are in our pool.", + "Ignoring redirect for {}: none of the {} named nodes are in our pool.", swarm_pubkey.hex(), - resolved.size(), swarm_node_keys.size()); return false; } + // Named nodes we don't have are ones our pool is too old to know, and when that leaves too + // few to work with only a refresh can fill them in; the ones we do have are still in the + // right swarm, where the swarm we had just rejected us, so they are followed meanwhile + const bool pool_missing_members = + resolved.size() < named.size() && resolved.size() < _config.cache_min_swarm_size; + auto& [nodes, redirects] = _swarm_overrides[swarm_pubkey]; nodes = std::move(resolved); @@ -1280,13 +1285,14 @@ bool SnodePool::record_swarm_redirect( swarm_pubkey.hex(), redirects); - if (redirects > SWARM_REDIRECTS_BEFORE_REFRESH) { + if (redirects > SWARM_REDIRECTS_BEFORE_REFRESH || pool_missing_members) { log::warning( cat, - "{} has been redirected {} times since the pool was refreshed; asking for a " - "refresh.", + "Asking for a refresh for {}: {}.", swarm_pubkey.hex(), - redirects); + pool_missing_members + ? "its redirect names nodes our pool doesn't have" + : "{} redirects since the pool was refreshed"_format(redirects)); invalidate_swarm(swarm_pubkey); } diff --git a/tests/test_snode_pool.cpp b/tests/test_snode_pool.cpp index 764c143db..ce2dd0fee 100644 --- a/tests/test_snode_pool.cpp +++ b/tests/test_snode_pool.cpp @@ -580,9 +580,6 @@ TEST_CASE("Network", "[network][swarm_redirect]") { // us in touch with something that isn't a registered service node CHECK_FALSE(snode_pool->record_swarm_redirect(swarm_pubkey, {key_for(200), key_for(201)})); - // Too few of the named nodes resolve to be a swarm - CHECK_FALSE(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 2))); - auto current_swarm = [&] { std::vector swarm; snode_pool->debug_run_on_loop([&] { @@ -646,6 +643,20 @@ TEST_CASE("Network", "[network][swarm_redirect]") { CHECK(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 4))); CHECK(current_swarm() == overridden); CHECK_FALSE(snode_pool->debug_refresh_in_progress()); + + // A redirect naming nodes we mostly haven't heard of is followed with the ones we have - they + // are the right swarm, where the one we had just rejected us - and asks for the refresh that + // can fill in the rest (from a fresh count, so the limit plays no part) + snode_pool->update_cache(snode_cache); + snode_pool->debug_age_pool(10min); + snode_pool->debug_age_evidence_refresh(10min); + auto partial = keys_of(elsewhere, 2); + partial.push_back(key_for(200)); + partial.push_back(key_for(201)); + CHECK(snode_pool->record_swarm_redirect(swarm_pubkey, partial)); + CHECK(current_swarm() == + sorted(std::vector(elsewhere.begin(), elsewhere.begin() + 2))); + CHECK(snode_pool->debug_refresh_in_progress()); } TEST_CASE("Network", "[network][strike_expiry]") { From fd6321f505c624220526bf2545d53e1de5c76dd4 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 24 Sep 2026 17:21:02 -0300 Subject: [PATCH 13/68] Report too few usable nodes with a named error code Issue: when a path couldn't be built, or the session router couldn't find a proxy, because the snode pool couldn't supply enough usable nodes, the failure was reported with a bare -1. Network failures are otherwise reported with the named ERROR_* codes, which is what lets a caller (through the C API included) tell what went wrong; -1 only says that something did. Solution: a new ERROR_INSUFFICIENT_NODES (-10013) for all three sites - the path builder failing its queued requests, and proxy selection after a pool refresh that failed or left no usable node. --- include/session/network/session_network_types.hpp | 1 + src/network/routing/onion_request_router.cpp | 2 +- src/network/routing/session_router_router.cpp | 4 ++-- tests/test_onion_request_router.cpp | 1 + 4 files changed, 5 insertions(+), 3 deletions(-) diff --git a/include/session/network/session_network_types.hpp b/include/session/network/session_network_types.hpp index 52e6e6b5b..cf29731fc 100644 --- a/include/session/network/session_network_types.hpp +++ b/include/session/network/session_network_types.hpp @@ -31,6 +31,7 @@ constexpr int16_t ERROR_INVALID_DESTINATION = -10009; constexpr int16_t ERROR_FAILED_GENERATE_ONION_PAYLOAD = -10010; constexpr int16_t ERROR_FAILED_TO_GET_STREAM = -10011; constexpr int16_t ERROR_UNAUTHENTICATED_RESPONSE = -10012; +constexpr int16_t ERROR_INSUFFICIENT_NODES = -10013; constexpr int16_t ERROR_BUILD_TIMEOUT = -10100; constexpr int16_t ERROR_REQUEST_CANCELLED = -10200; constexpr int16_t ERROR_UNKNOWN = -11000; diff --git a/src/network/routing/onion_request_router.cpp b/src/network/routing/onion_request_router.cpp index c828f1f21..0c379b173 100644 --- a/src/network/routing/onion_request_router.cpp +++ b/src/network/routing/onion_request_router.cpp @@ -1241,7 +1241,7 @@ void OnionRequestRouter::_build_path( for (const auto& [req, cb] : to_fail) cb(false, false, - -1, + ERROR_INSUFFICIENT_NODES, {content_type_plain_text}, "Cannot build a path: {}."_format(*cannot_build)); } diff --git a/src/network/routing/session_router_router.cpp b/src/network/routing/session_router_router.cpp index f8f54d814..19240cfc1 100644 --- a/src/network/routing/session_router_router.cpp +++ b/src/network/routing/session_router_router.cpp @@ -475,7 +475,7 @@ void SessionRouter::_send_proxy_request(Request request, network_response_callba return cb( false, false, - -1, + ERROR_INSUFFICIENT_NODES, {content_type_plain_text}, "Failed to refresh the snode pool to find a proxy."); @@ -492,7 +492,7 @@ void SessionRouter::_send_proxy_request(Request request, network_response_callba return cb( false, false, - -1, + ERROR_INSUFFICIENT_NODES, {content_type_plain_text}, "SnodePool refresh failed."); diff --git a/tests/test_onion_request_router.cpp b/tests/test_onion_request_router.cpp index 778c608d6..4a3953559 100644 --- a/tests/test_onion_request_router.cpp +++ b/tests/test_onion_request_router.cpp @@ -1105,6 +1105,7 @@ TEST_CASE("Network", "[network][onion_request_router][build_path_too_few_nodes]" CHECK(snode_pool->get_call_count("refresh_if_needed") == 1); REQUIRE(result); CHECK_FALSE(result->success); + CHECK(result->status_code == ERROR_INSUFFICIENT_NODES); CHECK(result->response.value_or("").find("too few usable nodes") != std::string::npos); } } // namespace session::network From c038a7be9c12579c79c77eec3bdc6f0a5cb3aceb Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 24 Sep 2026 17:37:18 -0300 Subject: [PATCH 14/68] Actually suspend the QUIC transport, and close without blaming nodes Issue: QuicTransport::suspend() returned early unless the transport was already suspended - the guard was inverted - so it never did anything and _suspended was never set. In production that mostly didn't show, because Network::suspend closed the transport's connections straight afterwards, which resets its endpoint: requests during a suspension still failed at once, just with -1 ("Network is invalid") rather than ERROR_NETWORK_SUSPENDED. The defect was the wrong error code and a suspended flag nothing could rely on. This is on dev as well. Fixing the guard makes the transport's suspend() close its connections itself, and exposes how that close treated the nodes it closed on: - The connections are closed synchronously by the endpoint's destructor when _close_connections() resets it (close_conns() only defers, and its deferred job finds the endpoint gone). Each close runs the transport's handler with code 0, and _fail_connection passes that code to every pending edge verification. The router strikes an edge node whose verification fails with an error code other than a handshake timeout, and 0 counts - so a close we asked for struck every edge node with a verification in flight. Verifications with no connection yet were cancelled with -1, to the same effect. - _fail_connection also fires the transport's failure listeners, and the router's listener retires the path and starts rebuilding it. Both reach the router while it is still live, because Network::suspend suspended the transport before the router, and Network::_close_connections (the public close_connections() route, on dev too) closes the transport before the router. Solution: - suspend() returns early only when already suspended. - _close_connections() takes the pending verifications and requests out of their maps before resetting the endpoint, so the destructor's closes find nothing to fail, and answers the copies once the transport is fully closed: verifications with no error code, since our own close is no evidence against a node, and requests with ERROR_NETWORK_SUSPENDED when suspended or ERROR_CONNECTION_CLOSED when not (they were told "suspended" either way). Answering copies rather than walking the members also means a callback that calls back into the transport - the router's path rebuild calling verify_connectivity, say - can't insert into the maps being walked; such a call finds no endpoint and fails cleanly, without an error code. That is a reason to keep this shape even if the code-0 close is ever avoided some other way. - Network::suspend suspends the router before the transport, and Network::_close_connections closes the router before the transport, so the router has dropped its path builds and failure listeners before the transport closes the connections they are attached to. Tests: a request sent to a suspended transport is refused with ERROR_NETWORK_SUSPENDED (with the inverted guard it went out and failed on the network with -1), and a verification in flight when the transport is closed is answered exactly once, with no error code (before, it got 0 from the destructor's close). --- src/network/session_network.cpp | 13 ++-- src/network/transport/quic_transport.cpp | 43 +++++++------ tests/CMakeLists.txt | 1 + tests/test_quic_transport.cpp | 80 ++++++++++++++++++++++++ 4 files changed, 115 insertions(+), 22 deletions(-) create mode 100644 tests/test_quic_transport.cpp diff --git a/src/network/session_network.cpp b/src/network/session_network.cpp index 3662479a6..307ba7e85 100644 --- a/src/network/session_network.cpp +++ b/src/network/session_network.cpp @@ -293,12 +293,14 @@ void Network::suspend() { _loop->call_get([this] { _suspended = true; + // The router before the transport, so that it has let go of its path builds and failure + // listeners before the transport closes the connections they're attached to if (_snode_pool) _snode_pool->suspend(); - if (_transport) - _transport->suspend(); if (_router) _router->suspend(); + if (_transport) + _transport->suspend(); _close_connections(); }); @@ -651,10 +653,13 @@ void Network::download(DownloadRequest request) { // MARK: Internal Logic void Network::_close_connections() { - if (_transport) - _transport->close_connections(); + // The router first, for the same reason as in `suspend`: otherwise each edge connection the + // transport closes fires a failure listener into a live router, which retires the path and + // starts rebuilding it if (_router) _router->close_connections(); + if (_transport) + _transport->close_connections(); _recalculate_status(); log::info(cat, "Closed all connections."); diff --git a/src/network/transport/quic_transport.cpp b/src/network/transport/quic_transport.cpp index f90f72007..a86fb4bc3 100644 --- a/src/network/transport/quic_transport.cpp +++ b/src/network/transport/quic_transport.cpp @@ -51,7 +51,7 @@ QuicTransport::~QuicTransport() { void QuicTransport::suspend() { // Use 'call_get' to force this to be synchronous _loop->call_get([this] { - if (!_suspended) + if (_suspended) return; _suspended = true; @@ -156,34 +156,41 @@ void QuicTransport::_recreate_endpoint() { } void QuicTransport::_close_connections() { - // Explicitly close all connections then reset the endpoint + // Taken out before the endpoint goes. Resetting it destroys it on the spot (close_conns() + // only defers), and its destructor closes every connection with code 0 through the handler + // that fails whatever is pending on it - so left in place, our own close would reach each + // pending verification as an error code, which is what gets a node struck. Answering copies + // also keeps a callback that calls back into the transport from changing the maps being walked. + auto verifications = std::exchange(_pending_verification_callbacks, {}); + auto requests = std::exchange(_pending_requests, {}); + if (_endpoint) _endpoint->close_conns(); _endpoint.reset(); - // Cancel any pending verifications (they can't succeed once the connection is closed) - for (const auto& [pubkey, callbacks] : _pending_verification_callbacks) + // Clear all storage of requests, paths and connections so that we are in a fresh state on + // relaunch + _active_connection_ids.clear(); + _available_stream_ids.clear(); + _update_status(ConnectionStatus::disconnected); + + // Answered only now the transport is fully closed, so anything a callback asks of it fails + // cleanly, without an error code, rather than meeting half-closed state. A verification gets + // no error code either: a close we asked for is no evidence against the node. + for (const auto& [pubkey, callbacks] : verifications) for (const auto& callback : callbacks) - callback(false, -1); + callback(false, std::nullopt); - // Cancel any pending requests (they can't succeed once the connection is closed) - for (const auto& [pubkey, pupkey_requests] : _pending_requests) - for (const auto& [info, callback] : pupkey_requests) + for (const auto& [pubkey, pubkey_requests] : requests) + for (const auto& [info, callback] : pubkey_requests) callback( false, false, - ERROR_NETWORK_SUSPENDED, + (_suspended ? ERROR_NETWORK_SUSPENDED : ERROR_CONNECTION_CLOSED), {content_type_plain_text}, - "QuickTransport is suspended."); + (_suspended ? "QuickTransport is suspended." + : "QuickTransport closed its connections.")); - // Clear all storage of requests, paths and connections so that we are in a fresh state on - // relaunch - _active_connection_ids.clear(); - _available_stream_ids.clear(); - _pending_verification_callbacks.clear(); - _pending_requests.clear(); - - _update_status(ConnectionStatus::disconnected); log::info(cat, "Closed all connections."); } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 2ed0d1af5..3f0cd7f9a 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -44,6 +44,7 @@ if(ENABLE_NETWORKING) list(APPEND LIB_SESSION_UTESTS_SOURCES test_network_swarm.cpp) list(APPEND LIB_SESSION_UTESTS_SOURCES test_onionreq.cpp) list(APPEND LIB_SESSION_UTESTS_SOURCES test_onion_request_router.cpp) + list(APPEND LIB_SESSION_UTESTS_SOURCES test_quic_transport.cpp) list(APPEND LIB_SESSION_UTESTS_SOURCES test_snode_pool.cpp) endif() diff --git a/tests/test_quic_transport.cpp b/tests/test_quic_transport.cpp new file mode 100644 index 000000000..52464e236 --- /dev/null +++ b/tests/test_quic_transport.cpp @@ -0,0 +1,80 @@ +#include +#include +#include +#include + +using namespace session::network; +using namespace std::literals; + +namespace { +std::shared_ptr make_transport(std::shared_ptr loop) { + return std::make_shared( + config::QuicTransport{ + .handshake_timeout = 1s, .keep_alive = 10s, .disable_mtu_discovery = false}, + std::move(loop)); +} + +service_node test_node() { + auto pubkey = "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7"sv; + return service_node{ + ed25519_pubkey::from_hex(pubkey), + oxen::quic::ipv4{"127.0.0.1"}, + 20001, + 30001, + {2, 11, 0}, + 0}; +} +} // namespace + +TEST_CASE("Network", "[network][quic_transport][suspend]") { + auto loop = std::make_shared(); + auto transport = make_transport(loop); + transport->suspend(); + + std::promise status; + transport->send_request( + Request{"AAAA", test_node(), "info", std::nullopt, RequestCategory::standard, 1s}, + [&status, answered = false](bool, bool, int16_t status_code, auto, auto) mutable { + if (!std::exchange(answered, true)) + status.set_value(status_code); + }); + + // Refused outright rather than attempted: a suspended transport sends nothing + auto answer = status.get_future(); + REQUIRE(answer.wait_for(5s) == std::future_status::ready); + CHECK(answer.get() == ERROR_NETWORK_SUSPENDED); +} + +TEST_CASE("Network", "[network][quic_transport][close_connections]") { + auto loop = std::make_shared(); + auto transport = make_transport(loop); + + // Verified and closed within one loop job, so nothing from the network can settle the + // verification before the close does + int answers = 0; + bool success = true; + std::optional error_code; + loop->call_get([&] { + transport->verify_connectivity( + test_node(), + 3s, + "AAAA", + RequestCategory::standard, + [&](bool s, std::optional e) { + ++answers; + success = s; + error_code = e; + }); + transport->close_connections(); + }); + + // Anything the close deferred has run by the time a later job does + loop->call_get([] {}); + + // One answer, from the close, and with no error code: a close we asked for is no evidence + // against the node, which is what an error code would say - the router strikes a node whose + // verification fails with one + CHECK(answers == 1); + CHECK_FALSE(success); + CHECK_FALSE(error_code); +} From 8ee229314810b8d01e8d653b70eb3887e211e527 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 24 Sep 2026 19:33:30 -0300 Subject: [PATCH 15/68] Abandon a snode pool refresh when the pool is suspended Issue: SnodePool::suspend() set its flag and flushed strikes, and left any refresh in progress to carry on. With the transport and router both refusing requests while suspended, every fetch that refresh made failed at once, and its retry paths - a failed fetch moving to the next candidate, a rejected set of results being fetched again - don't check for suspension, so it worked its way through the candidate list at the retry delay (capped at 5s, three chains in parallel): about an hour for a mainnet-sized pool, waking the process to do nothing useful on Android and desktop (iOS freezes it, so there the timers never fire). Whatever waited on the refresh was answered only when the candidates ran out, and the failures it counted up slowed the first refreshes after resume. Solution: suspend() abandons a refresh in progress - resetting its id, candidates, results and failure count - and answers everything waiting on it with false, as the router and transport already do with their own work in flight. Treating a suspension as a fresh start drops genuine pre-suspend failures too; that is deliberate, since they say nothing about the network we resume on. Nothing can be in flight while suspended any more, so _refresh_snode_cache's suspended branch answers its waiters unconditionally. Retries belonging to an abandoned refresh can still fire afterwards, so: - _launch_next_refresh_request does nothing unless its refresh is still the current one; before, it only checked that some refresh was, and would take candidates from whichever refresh had replaced it; - the "ran out of candidates" retry captures its refresh id and does nothing when that refresh is gone. Before, it reset the id and started a new refresh unconditionally, which could wipe out a refresh started after resume. This was the one place a refresh restarted itself; after a suspension, the next refresh now comes from the pool's ordinary callers asking again - the router's path pre-build on resume, via get_unused_nodes, or a clock resync. A refresh invalidate_swarm started has already stepped its backoff when it is abandoned, so after a short suspension the first rejection-driven refresh can be declined, for at most the current backoff interval. The throttle resets itself after quiet for twice that interval, so a longer suspension carries nothing over. --- src/network/snode_pool.cpp | 32 ++++++++-- tests/test_snode_pool.cpp | 124 +++++++++++++++++++++++++++++++++++++ 2 files changed, 151 insertions(+), 5 deletions(-) diff --git a/src/network/snode_pool.cpp b/src/network/snode_pool.cpp index 788bd0fea..842d6ea48 100644 --- a/src/network/snode_pool.cpp +++ b/src/network/snode_pool.cpp @@ -361,9 +361,8 @@ void SnodePool::_refresh_snode_cache(std::optional request_id_opt) log::info(cat, "Ignoring refresh as pool is suspended."); // Anything queued against a refresh we are declining to start has nothing left to wait - // for, unless one is already in flight and still owns it - if (!_current_snode_cache_refresh_id) - _run_pending_refresh_callbacks(false); + // for: suspending abandons any refresh in progress, so none can answer it later + _run_pending_refresh_callbacks(false); return; } @@ -464,7 +463,9 @@ void SnodePool::_launch_next_refresh_request( refreshing_from_seed_nodes, use_direct_fetcher, total_requests] { - if (!_current_snode_cache_refresh_id) + // A retry scheduled for a refresh that has since been abandoned or replaced mustn't touch + // the one in its place - its candidates in particular + if (_current_snode_cache_refresh_id != request_id) return; const auto target_request_id = "{}-{}"_format(request_id, index); @@ -570,7 +571,7 @@ void SnodePool::_launch_next_refresh_request( "trying again in {}ms.", target_request_id, delay.count()); - _loop->call_later(delay, [weak_self = weak_from_this(), this] { + _loop->call_later(delay, [weak_self = weak_from_this(), this, request_id] { // We need to wait until after the `call_later` to reset the `refresh_id` (and clear // previous results) as if we don't then additional refreshes could be triggered // during the delay @@ -578,6 +579,11 @@ void SnodePool::_launch_next_refresh_request( if (!self) return; + // Abandoned (by a suspend) or replaced during the delay: resetting the id would + // wipe out whichever refresh has it now, and there is nothing of ours to restart + if (_current_snode_cache_refresh_id != request_id) + return; + _current_snode_cache_refresh_id.reset(); _snode_refresh_results.clear(); _refresh_snode_cache(); @@ -959,6 +965,22 @@ void SnodePool::suspend() { _loop->call_get([this] { _suspended = true; + // A refresh in progress can only fail from here on, since every fetch is refused while + // suspended, so it is abandoned rather than left to work its way through the candidates, + // and whatever waits on it is answered now. The failures it built up are dropped too: + // they say nothing about the network we resume on. + if (_current_snode_cache_refresh_id) { + log::info( + cat, + "[Request {}] Abandoning cache refresh for suspension.", + *_current_snode_cache_refresh_id); + _current_snode_cache_refresh_id.reset(); + _refresh_candidate_nodes.clear(); + _snode_refresh_results.clear(); + _snode_cache_refresh_failure_count = 0; + _run_pending_refresh_callbacks(false); + } + // Force a strike write immediately if we had one scheduled if (_strikes_flush_scheduled) _disk_loop->call([path = _strikes_file_path, strikes = _snode_strikes] { diff --git a/tests/test_snode_pool.cpp b/tests/test_snode_pool.cpp index ce2dd0fee..de732ef60 100644 --- a/tests/test_snode_pool.cpp +++ b/tests/test_snode_pool.cpp @@ -1,5 +1,6 @@ #include #include +#include #include "utils.hpp" @@ -73,6 +74,37 @@ class TestSnodePool : public SnodePool { return _loop->call_get([this] { return _current_snode_cache_refresh_id.has_value(); }); } + void debug_start_refresh() { + _loop->call_get([this] { _refresh_snode_cache(); }); + } + + std::optional debug_refresh_id() { + return _loop->call_get([this] { return _current_snode_cache_refresh_id; }); + } + + size_t debug_refresh_candidate_count() { + return _loop->call_get([this] { return _refresh_candidate_nodes.size(); }); + } + + void debug_clear_refresh_candidates() { + _loop->call_get([this] { _refresh_candidate_nodes.clear(); }); + } + + int debug_refresh_failure_count() { + return _loop->call_get([this] { return _snode_cache_refresh_failure_count; }); + } + + void debug_set_refresh_failure_count(int count) { + _loop->call_get([this, count] { _snode_cache_refresh_failure_count = count; }); + } + + // Launches one of the refresh `request_id`'s fetches, as its retries do + void debug_launch_refresh_request(const std::string& request_id) { + _loop->call_get([this, request_id] { + _launch_next_refresh_request(request_id, 0, false, true, 1); + }); + } + // Backdates the pool snapshot so the age-based policies can be exercised without waiting void debug_age_pool(std::chrono::seconds by) { _loop->call_get([this, by] { _last_snode_cache_update -= by; }); @@ -768,3 +800,95 @@ TEST_CASE("Network", "[network][refresh_callback_contract]") { CHECK(called); CHECK_FALSE(refreshed); } + +TEST_CASE("Network", "[network][suspend_refresh]") { + session::network::config::SnodePool pool_config{ + .cache_expiration = 2h, + .cache_min_lifetime = 2s, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .cache_min_size = 1, + .cache_min_swarm_size = 1, + .cache_num_nodes_to_use_for_refresh = 1, + .cache_min_num_refresh_presence_to_include_node = 1, + .cache_node_strike_threshold = 3}; + + std::vector snode_cache; + for (uint16_t i = 0; i < 4; ++i) + snode_cache.emplace_back(service_node{ + ed25519_pubkey::from_hex( + "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46a{:02x}"_format( + i)), + oxen::quic::ipv4{"192.168.0.{}"_format(i)}, + static_cast(20000 + i), + static_cast(30000 + i), + {2, 11, 0}, + 0}); + + // The default fetcher never answers, so a refresh stays in progress until the test ends it + auto loop = std::make_shared(); + auto disk_loop = std::make_shared(); + auto snode_pool = std::make_shared(pool_config, loop, disk_loop); + snode_pool->update_cache(snode_cache); + + SECTION("Suspending abandons a refresh in progress, and answers what waits on it") { + snode_pool->debug_start_refresh(); + REQUIRE(snode_pool->debug_refresh_in_progress()); + + std::optional answer; + snode_pool->debug_queue_post_refresh_callback( + [&answer](bool refreshed) { answer = refreshed; }); + snode_pool->debug_set_refresh_failure_count(3); + + snode_pool->suspend(); + CHECK(answer == false); + CHECK_FALSE(snode_pool->debug_refresh_in_progress()); + CHECK(snode_pool->debug_refresh_failure_count() == 0); + } + + SECTION("A fetch belonging to an abandoned refresh leaves the next refresh alone") { + snode_pool->debug_start_refresh(); + auto abandoned = snode_pool->debug_refresh_id(); + REQUIRE(abandoned); + snode_pool->suspend(); + snode_pool->resume(); + + snode_pool->debug_start_refresh(); + auto current = snode_pool->debug_refresh_id(); + REQUIRE(current); + REQUIRE(current != abandoned); + auto candidates = snode_pool->debug_refresh_candidate_count(); + + snode_pool->debug_launch_refresh_request(*abandoned); + CHECK(snode_pool->debug_refresh_id() == current); + CHECK(snode_pool->debug_refresh_candidate_count() == candidates); + } + + SECTION("An abandoned refresh's retry after running out of candidates restarts nothing") { + // Running out schedules a retry of the whole refresh, after the retry delay + auto run_out_then_suspend = [&] { + snode_pool->debug_start_refresh(); + auto id = snode_pool->debug_refresh_id(); + REQUIRE(id); + snode_pool->debug_clear_refresh_candidates(); + snode_pool->debug_launch_refresh_request(*id); + snode_pool->suspend(); + snode_pool->resume(); + }; + auto past_retry_delay = [] { std::this_thread::sleep_for(500ms); }; + + // Once it was the refresh that used to restart itself here + run_out_then_suspend(); + past_retry_delay(); + CHECK_FALSE(snode_pool->debug_refresh_in_progress()); + + // ... and with another refresh started by the time it fires, that one is left running + run_out_then_suspend(); + snode_pool->debug_start_refresh(); + auto current = snode_pool->debug_refresh_id(); + REQUIRE(current); + past_retry_delay(); + CHECK(snode_pool->debug_refresh_id() == current); + } +} From 561054cb2ade8c1adff796d08e8cc336d49f13dc Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 24 Sep 2026 19:48:13 -0300 Subject: [PATCH 16/68] Give the older snode pool tests the config they were written for Issue: [get_unused_nodes], [update_cache] and [refresh_min_cache_size] built their config::SnodePool positionally, with trailing comments naming fields the values no longer went into. Each list was one entry short of the struct and misaligned by two, so the value commented as cache_node_strike_threshold went two fields early and the trailing false filled a numeric field as 0: - in [get_unused_nodes] (both of its configs) and [update_cache], the 3 went into cache_num_nodes_to_use_for_refresh and the false into cache_min_num_refresh_presence_to_include_node; - in [refresh_min_cache_size], which also sets cache_min_size, the 3 went into cache_min_num_refresh_presence_to_include_node and the false into cache_node_strike_threshold. Every one of them therefore ran with a strike threshold of 0 - a node out on its first strike. None of the three tests' outcomes depended on that, or on the refresh settings the values landed in: TestSnodePool makes refresh_if_needed a no-op, none of them reaches a refresh through get_swarm on an empty pool, and [refresh_min_cache_size] feeds _on_refresh_complete a single response, for which the presence requirement doesn't apply. But the one strike check, in [get_unused_nodes], uses permanent failures, which strike a node out at any threshold, so nothing checked the threshold itself. Solution: all four configs are designated, with the values the comments meant - cache_node_strike_threshold 3, plus cache_min_size 12 where marked - and everything else they didn't annotate left 0. So besides the threshold, cache_num_nodes_to_use_for_refresh goes from 3 to 0 in the short lists and the presence requirement from 3 to 0 in [refresh_min_cache_size]; for the reasons above, neither has any effect on these tests. [get_unused_nodes] now also checks the threshold: a node with two ordinary strikes is still picked, and with a third it isn't. At the old threshold of 0 that check fails, since two strikes already exclude the node. --- tests/test_snode_pool.cpp | 91 ++++++++++++++++++--------------------- 1 file changed, 42 insertions(+), 49 deletions(-) diff --git a/tests/test_snode_pool.cpp b/tests/test_snode_pool.cpp index de732ef60..f56b12376 100644 --- a/tests/test_snode_pool.cpp +++ b/tests/test_snode_pool.cpp @@ -201,18 +201,12 @@ std::vector to_snode_cache_bin(const std::vector& nodes TEST_CASE("Network", "[network][get_unused_nodes]") { session::network::config::SnodePool pool_config = { - std::nullopt, - std::nullopt, - std::chrono::minutes{5}, - std::chrono::minutes{5}, - false, // enforce_subnet_diversity - network::opt::retry_delay{50ms, 200ms}, - opt::netid::Target::testnet, - {}, - 0, - 0, - 3, // cache_node_strike_threshold - false}; + .cache_expiration = std::chrono::minutes{5}, + .cache_min_lifetime = std::chrono::minutes{5}, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .cache_node_strike_threshold = 3}; auto ed_pk = "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7"_hexbytes; auto ed_pk2 = "5ea34e72bb044654a6a23675690ef5ffaaf1656b02f93fb76655f9cbdbe89876"_hexbytes; auto ed_pk3 = "e17a692033200ae41350df9709754edde7343e2cf2f23e88f993319e0720e5e5"_hexbytes; @@ -297,20 +291,31 @@ TEST_CASE("Network", "[network][get_unused_nodes]") { std::sort(unused_nodes.begin(), unused_nodes.end()); CHECK(unused_nodes == remaining); + // ... but only once they have passed it: ordinary strikes below the threshold leave a node in + // use (strikes are per pubkey, so these apply to every node sharing the struck node's key) + snode_pool->reset_state_with_cache(snode_cache); + auto struck_key = snode_cache[0].remote_pubkey; + auto uses_struck_key = [&struck_key](const service_node& n) { + return n.remote_pubkey == struck_key; + }; + auto with_struck_key = std::ranges::count_if(snode_cache, uses_struck_key); + + snode_pool->record_node_failure(snode_cache[0]); + snode_pool->record_node_failure(snode_cache[0]); + CHECK(std::ranges::count_if(snode_pool->get_unused_nodes(20), uses_struck_key) == + with_struck_key); + + snode_pool->record_node_failure(snode_cache[0]); + CHECK(std::ranges::none_of(snode_pool->get_unused_nodes(20), uses_struck_key)); + // Should exclude nodes which have the same subnet pool_config = { - std::nullopt, - std::nullopt, - std::chrono::minutes{5}, - std::chrono::minutes{5}, - true, // enforce_subnet_diversity - network::opt::retry_delay{50ms, 200ms}, - opt::netid::Target::testnet, - {}, - 0, - 0, - 3, // cache_node_strike_threshold - false}; + .cache_expiration = std::chrono::minutes{5}, + .cache_min_lifetime = std::chrono::minutes{5}, + .enforce_subnet_diversity = true, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .cache_node_strike_threshold = 3}; snode_pool = std::make_shared(pool_config, loop, disk_loop); snode_pool->reset_state_with_cache(snode_cache); unused_nodes = snode_pool->get_unused_nodes(20); @@ -325,18 +330,12 @@ TEST_CASE("Network", "[network][get_unused_nodes]") { TEST_CASE("Network", "[network][update_cache]") { session::network::config::SnodePool pool_config = { - std::nullopt, - std::nullopt, - 5min, - 5min, - false, // enforce_subnet_diversity - network::opt::retry_delay{50ms, 200ms}, - opt::netid::Target::testnet, - {}, - 0, - 0, - 3, // cache_node_strike_threshold - false}; + .cache_expiration = 5min, + .cache_min_lifetime = 5min, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .cache_node_strike_threshold = 3}; auto ed_pk = "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7"_hexbytes; std::vector snode_cache; @@ -380,19 +379,13 @@ TEST_CASE("Network", "[network][update_cache]") { TEST_CASE("Network", "[network][refresh_min_cache_size]") { session::network::config::SnodePool pool_config = { - std::nullopt, - std::nullopt, - 5min, - 5min, - false, // enforce_subnet_diversity - network::opt::retry_delay{50ms, 200ms}, - opt::netid::Target::testnet, - {}, - 12, // cache_min_size - 0, - 0, - 3, // cache_node_strike_threshold - false}; + .cache_expiration = 5min, + .cache_min_lifetime = 5min, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .cache_min_size = 12, + .cache_node_strike_threshold = 3}; auto ed_pk = "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7"_hexbytes; std::vector snode_cache; From c84039c1ba336426122cb70645a79763509bb009 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 24 Sep 2026 19:53:37 -0300 Subject: [PATCH 17/68] Test that rotating a path drops a struck-out edge node Issue: _rotate_path keeps a path's edge node across rotations - so a client's first hop stays stable - unless it has been in use longer than edge_node_cache_duration, or (since the cached edge node change) it has been struck out. Nothing tested the struck-out case; the existing test covers only the edge nodes cached from a previous run. Solution: [onion_request_router][rotate_path] rotates a path whose edge node was connected just now, so the ten-day rule can't be what decides, and checks what the rotation asks the pool for: the rest of a path keeping the edge node (path_length - 1 nodes) when it isn't struck, a whole new path (path_length) once it is. The mock pool now records the count of each get_unused_nodes call, since its canned result doesn't reflect it. Without the struck-out condition the second rotation asks for path_length - 1 and the test fails. TestOnionRequestRouter::set_paths used emplace, which leaves a category's paths alone if it already has some, so setting them twice on one router silently kept the first set. It now replaces them, which is what its name says and what the new test needs; no existing test set them twice. --- tests/test_onion_request_router.cpp | 58 ++++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/tests/test_onion_request_router.cpp b/tests/test_onion_request_router.cpp index 4a3953559..20ac44c7c 100644 --- a/tests/test_onion_request_router.cpp +++ b/tests/test_onion_request_router.cpp @@ -25,7 +25,7 @@ class TestOnionRequestRouter { std::shared_ptr router, PathCategory category, std::vector paths) { - router->_paths.emplace(category, paths); + router->_paths[category] = std::move(paths); } static std::vector get_paths( @@ -86,6 +86,13 @@ class TestOnionRequestRouter { router->_send_on_path(path, std::move(request), std::move(callback)); } + static void rotate_path( + std::shared_ptr router, + const std::string& path_id, + PathCategory category) { + router->_rotate_path(path_id, category); + } + static void handle_transport_response( std::shared_ptr router, std::string path_id, @@ -200,8 +207,12 @@ namespace { // Do nothing (don't want to trigger a cache refresh) } + // The `count` of each `get_unused_nodes` call, which the mock result doesn't reflect + std::vector unused_node_counts; + std::vector get_unused_nodes( size_t count, const std::vector& exclude = {}) override { + unused_node_counts.push_back(count); if (check_should_ignore_and_log_call("get_unused_nodes")) return {}; @@ -1108,4 +1119,49 @@ TEST_CASE("Network", "[network][onion_request_router][build_path_too_few_nodes]" CHECK(result->status_code == ERROR_INSUFFICIENT_NODES); CHECK(result->response.value_or("").find("too few usable nodes") != std::string::npos); } + +TEST_CASE("Network", "[network][onion_request_router][rotate_path]") { + auto key1 = "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7"sv; + auto key2 = "5ea34e72bb044654a6a23675690ef5ffaaf1656b02f93fb76655f9cbdbe89876"sv; + auto key3 = "e17a692033200ae41350df9709754edde7343e2cf2f23e88f993319e0720e5e5"sv; + auto key4 = "7b633fa6fb462b90db6f0f50384190ce7715e31b7aa93d87dbd7e94e33d4251f"sv; + auto edge = test_node(key1, 20001); + auto path_nodes = std::vector{edge, test_node(key2, 20002), test_node(key3, 20003)}; + + auto loop = std::make_shared(); + auto disk_loop = std::make_shared(); + auto snode_pool = std::make_shared(test_pool_config(), loop, disk_loop); + auto transport = std::make_shared(); + auto config = test_router_config(); + auto router = + std::make_shared(config, loop, disk_loop, snode_pool, transport); + snode_pool->mock_unused_nodes = + std::vector{test_node(key2, 20012), test_node(key3, 20013), test_node(key4, 20014)}; + + // Rotates a path whose edge node was connected just now, so well inside + // `edge_node_cache_duration`, and returns what the rotation asked the pool for. The first + // request says which it chose: a whole new path, or the rest of one that keeps the edge node. + auto rotate = [&] { + std::vector counts; + loop->call_get([&] { + auto now = std::chrono::system_clock::now(); + TestOnionRequestRouter::set_paths( + router, PathCategory::standard, {OnionPath{"Test", path_nodes, now, now}}); + snode_pool->unused_node_counts.clear(); + TestOnionRequestRouter::rotate_path(router, "Test", PathCategory::standard); + counts = snode_pool->unused_node_counts; + }); + return counts; + }; + + auto kept = rotate(); + REQUIRE_FALSE(kept.empty()); + CHECK(kept.front() == config.path_length - 1u); + + // Struck out since we connected to it, the edge node is replaced along with the rest + snode_pool->record_node_failure(edge, true); + auto replaced = rotate(); + REQUIRE_FALSE(replaced.empty()); + CHECK(replaced.front() == config.path_length); +} } // namespace session::network From aeac6b6d9dfaf596b57791d44dd9bbe078a94c95 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 24 Sep 2026 20:13:48 -0300 Subject: [PATCH 18/68] Check the pool's age on every get_swarm, not only the first per account Issue: get_swarm schedules a background refresh_if_needed, the check that refreshes a pool past cache_expiration, only on the path that works a swarm out from the pool. Answers from the swarm cache return before it, and so, since the redirect commits, do answers from an override. So each account triggered the check once per pool generation, on its first lookup, and never again while its swarm was cached - and an overridden account, whose override only a refresh clears, never did at all. Refreshes still happened, because path rotation and building call get_unused_nodes, which schedules the same check, but only thanks to that unrelated caller. The cached case predates this branch; the override case widened it. Solution: the check is scheduled at the top of get_swarm, so every call makes it. It costs nothing when the pool is fresh or a refresh is already running. A test counts the checks: one each for a swarm worked out from the pool, one answered from the cache and one answered from an override; before, the last two made none. --- src/network/snode_pool.cpp | 14 +++++---- tests/test_snode_pool.cpp | 61 +++++++++++++++++++++++++++++++++++++- 2 files changed, 68 insertions(+), 7 deletions(-) diff --git a/src/network/snode_pool.cpp b/src/network/snode_pool.cpp index 842d6ea48..4c7320034 100644 --- a/src/network/snode_pool.cpp +++ b/src/network/snode_pool.cpp @@ -1397,6 +1397,14 @@ void SnodePool::get_swarm( log::trace(cat, "{} called for {}.", __PRETTY_FUNCTION__, swarm_pubkey.hex()); _loop->call([this, swarm_pubkey, ignore_strike_count, cb = std::move(callback)] { + // Trigger a non-blocking background refresh if the data is stale. Up here so that it runs + // for every call: answers from an override or the swarm cache below return early, and + // they are most of them. + _loop->call_soon([weak_self = weak_from_this()] { + if (auto self = weak_self.lock()) + self->refresh_if_needed({}); + }); + auto filter_by_strikes = [this](std::vector nodes) -> std::vector { // Shuffle everything to start with @@ -1473,12 +1481,6 @@ void SnodePool::get_swarm( return; } - // Trigger a non-blocking background refresh if the data is stale - _loop->call_soon([weak_self = weak_from_this()] { - if (auto self = weak_self.lock()) - self->refresh_if_needed({}); - }); - // Perform the swarm calculation using our local copy of the data auto swarm = swarm::get_swarm(swarm_pubkey, _all_swarms); _swarm_cache[swarm_pubkey] = swarm; diff --git a/tests/test_snode_pool.cpp b/tests/test_snode_pool.cpp index f56b12376..5b57f49fe 100644 --- a/tests/test_snode_pool.cpp +++ b/tests/test_snode_pool.cpp @@ -31,10 +31,15 @@ class TestSnodePool : public SnodePool { }); } + // How often the pool was asked to check whether it needs refreshing; read it only after a + // loop job has run, since the checks are scheduled onto the loop + int refresh_checks = 0; + void refresh_if_needed( const std::vector& /*in_use_nodes*/, refresh_callback_t /*on_refresh_complete*/ = nullptr) override { - // Do nothing (don't want to trigger a cache refresh) + // Don't trigger a cache refresh + ++refresh_checks; } void debug_queue_post_refresh_callback(refresh_callback_t cb) { @@ -684,6 +689,60 @@ TEST_CASE("Network", "[network][swarm_redirect]") { CHECK(snode_pool->debug_refresh_in_progress()); } +TEST_CASE("Network", "[network][get_swarm_checks_age]") { + session::network::config::SnodePool pool_config{ + .cache_expiration = 2h, + .cache_min_lifetime = 2s, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .cache_min_swarm_size = 3, + .cache_node_strike_threshold = 3}; + + std::vector snode_cache; + for (uint16_t i = 0; i < 6; ++i) + snode_cache.emplace_back(service_node{ + ed25519_pubkey::from_hex( + "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46a{:02x}"_format( + i)), + oxen::quic::ipv4{"192.168.0.{}"_format(i)}, + static_cast(20000 + i), + static_cast(30000 + i), + {2, 11, 0}, + static_cast(i < 3 ? 0 : 1)}); + + auto loop = std::make_shared(); + auto disk_loop = std::make_shared(); + auto snode_pool = std::make_shared(pool_config, loop, disk_loop); + snode_pool->update_cache(snode_cache); + + auto swarm_pubkey = x25519_pubkey::from_hex( + "0000000000000000000000000000000000000000000000000000000000000000"); + + // The check is scheduled onto the loop, so it has run by the time a later loop job does + auto checks_for_one_get_swarm = [&] { + snode_pool->debug_run_on_loop([&] { + snode_pool->refresh_checks = 0; + snode_pool->get_swarm(swarm_pubkey, true, [](auto, auto) {}); + }); + snode_pool->debug_run_on_loop([] {}); + return snode_pool->refresh_checks; + }; + + // Worked out from the pool and cached... + CHECK(checks_for_one_get_swarm() == 1); + + // ... then answered from that cache, and from an override, each of which returns before the + // swarm is worked out, and neither of which may skip checking whether the pool is stale + CHECK(checks_for_one_get_swarm() == 1); + + std::vector redirect; + for (const auto& node : snode_cache) + redirect.push_back(node.remote_pubkey); + REQUIRE(snode_pool->record_swarm_redirect(swarm_pubkey, redirect)); + CHECK(checks_for_one_get_swarm() == 1); +} + TEST_CASE("Network", "[network][strike_expiry]") { session::network::config::SnodePool pool_config{ .cache_expiration = 5min, From 044ef5164ac645eff01d84df03b272958d7a5f2c Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 24 Sep 2026 20:15:11 -0300 Subject: [PATCH 19/68] Fall back on the C API's swarm pubkey for sub-requests naming no account Issue: session_network_send_request takes each sub-request's account from a pregenerated batch or sequence body, and uses the caller's swarm_pubkey_hex only when the body can't be parsed at all. A sub-request whose params carry no pubkey got an empty entry even when the caller had said which account the request was for. With 421s attributed strictly by position in the request, a 421 for that sub-request could then be attributed to no account, and the redirect it carried was lost. Solution: batch_request_accounts takes a fallback account, which fills any sub-request whose params name none; accounts parsed from the body are kept, since they can differ per sub-request. The C API passes swarm_pubkey_hex as the fallback. --- include/session/network/session_network_types.hpp | 9 ++++++--- src/network/session_network.cpp | 10 +++++++--- src/network/session_network_types.cpp | 6 +++++- tests/test_network_swarm.cpp | 5 +++++ 4 files changed, 23 insertions(+), 7 deletions(-) diff --git a/include/session/network/session_network_types.hpp b/include/session/network/session_network_types.hpp index cf29731fc..efecd7e01 100644 --- a/include/session/network/session_network_types.hpp +++ b/include/session/network/session_network_types.hpp @@ -272,10 +272,13 @@ using network_response_callback_t = std::function response)>; /// The accounts of each sub-request in a pregenerated `batch`/`sequence` body, in the form -/// `Request::swarm_pubkeys` takes, for a request whose body was built by the caller. Returns -/// nullopt when `endpoint` is neither or the body can't be parsed. +/// `Request::swarm_pubkeys` takes, for a request whose body was built by the caller. A +/// sub-request whose params name no account gets `fallback` instead: the account the caller said +/// the request is for. Returns nullopt when `endpoint` is neither or the body can't be parsed. std::optional>> batch_request_accounts( - std::string_view endpoint, std::span body); + std::string_view endpoint, + std::span body, + std::optional fallback = std::nullopt); namespace response { std::optional> parse_text_error(std::string_view body); diff --git a/src/network/session_network.cpp b/src/network/session_network.cpp index 307ba7e85..1270771db 100644 --- a/src/network/session_network.cpp +++ b/src/network/session_network.cpp @@ -1862,13 +1862,17 @@ LIBSESSION_C_API void session_network_send_request( std::nullopt, request_id}; + std::optional swarm_pubkey; + if (params->swarm_pubkey_hex) + swarm_pubkey = x25519_pubkey::from_hex({params->swarm_pubkey_hex, 64}); + std::optional>> batch_accounts; if (request.body) - batch_accounts = batch_request_accounts(request.endpoint, *request.body); + batch_accounts = batch_request_accounts(request.endpoint, *request.body, swarm_pubkey); if (batch_accounts) request.swarm_pubkeys = std::move(*batch_accounts); - else if (params->swarm_pubkey_hex) - request.swarm_pubkeys = {x25519_pubkey::from_hex({params->swarm_pubkey_hex, 64})}; + else if (swarm_pubkey) + request.swarm_pubkeys = {*swarm_pubkey}; auto cpp_callback = [c_cb = callback, c_ctx = ctx]( bool success, diff --git a/src/network/session_network_types.cpp b/src/network/session_network_types.cpp index f64e6a0d6..7f5af921a 100644 --- a/src/network/session_network_types.cpp +++ b/src/network/session_network_types.cpp @@ -170,7 +170,9 @@ std::vector response::subresponses(const nlohmann::json& } std::optional>> batch_request_accounts( - std::string_view endpoint, std::span body) { + std::string_view endpoint, + std::span body, + std::optional fallback) { if (endpoint != "batch" && endpoint != "sequence") return std::nullopt; @@ -186,6 +188,8 @@ std::optional>> batch_request_accounts( auto& account = accounts.emplace_back(); if (auto params = field(req, "params", &nlohmann::json::is_object)) account = account_in(*params); + if (!account) + account = fallback; } return accounts; diff --git a/tests/test_network_swarm.cpp b/tests/test_network_swarm.cpp index 1cd0df5c1..fa9dc0019 100644 --- a/tests/test_network_swarm.cpp +++ b/tests/test_network_swarm.cpp @@ -374,6 +374,11 @@ TEST_CASE("Swarm", "[network][swarm][batch_request_accounts]") { CHECK(batch_request_accounts("sequence", bytes) == accounts); CHECK_FALSE(batch_request_accounts("retrieve", bytes)); + // A sub-request naming no account takes the one the caller gave for the whole request, + // while those that name their own keep it + CHECK(batch_request_accounts("batch", bytes, account('c')) == + std::vector>{account('a'), account('c'), account('b')}); + std::string_view junk = "not json"; CHECK_FALSE(batch_request_accounts( "batch", {reinterpret_cast(junk.data()), junk.size()})); From dbb8aebea5d2802ddc05f68501f204ecbb632818 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 24 Sep 2026 20:16:22 -0300 Subject: [PATCH 20/68] Keep repeated swarm redirect logging out of the default log Issue: every accepted swarm redirect logged at info, and once an account is past SWARM_REDIRECTS_BEFORE_REFRESH every further redirect warned and asked invalidate_swarm for a refresh, whose "leaving it alone" line for a throttled refresh was also at info. During a bounce between disagreeing nodes that is several lines per request for as long as the backoff holds, up to its two-hour cap - useful once, noise after that. Solution: the per-redirect line and invalidate_swarm's decline line are debug. The limit warning fires only on the redirect that crosses it, and later ones log at debug. The warning for a redirect naming nodes our pool doesn't have is unchanged. It can repeat too - every request for that account produces one while the refresh it asks for is throttled - and the same first-then-debug treatment would apply, but that waits for evidence that it is noisy in practice. --- src/network/snode_pool.cpp | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/src/network/snode_pool.cpp b/src/network/snode_pool.cpp index 4c7320034..0d345a51b 100644 --- a/src/network/snode_pool.cpp +++ b/src/network/snode_pool.cpp @@ -1219,7 +1219,7 @@ void SnodePool::invalidate_swarm(x25519_pubkey swarm_pubkey, refresh_callback_t _evidence_refresh_backoff = 0s; if (pool_age < EVIDENCE_REFRESH_MIN_POOL_AGE || since_last < _evidence_refresh_backoff) - log::info( + log::debug( cat, "Swarm {} was rejected, but the pool is {}s old and the last refresh on a " "rejection was {}s ago (backoff {}s); leaving it alone.", @@ -1299,7 +1299,7 @@ bool SnodePool::record_swarm_redirect( if (redirects < std::numeric_limits::max()) ++redirects; - log::info( + log::debug( cat, "Redirected to a swarm of {} nodes for {} (redirect {} since the pool was " "refreshed).", @@ -1307,14 +1307,28 @@ bool SnodePool::record_swarm_redirect( swarm_pubkey.hex(), redirects); - if (redirects > SWARM_REDIRECTS_BEFORE_REFRESH || pool_missing_members) { + if (pool_missing_members) { log::warning( cat, - "Asking for a refresh for {}: {}.", - swarm_pubkey.hex(), - pool_missing_members - ? "its redirect names nodes our pool doesn't have" - : "{} redirects since the pool was refreshed"_format(redirects)); + "Asking for a refresh for {}: its redirect names nodes our pool doesn't have.", + swarm_pubkey.hex()); + invalidate_swarm(swarm_pubkey); + } else if (redirects > SWARM_REDIRECTS_BEFORE_REFRESH) { + // Past the limit every redirect asks again, for as long as the refresh stays + // throttled, so only crossing it is worth a warning + if (redirects == SWARM_REDIRECTS_BEFORE_REFRESH + 1) + log::warning( + cat, + "Asking for a refresh for {}: {} redirects since the pool was refreshed.", + swarm_pubkey.hex(), + redirects); + else + log::debug( + cat, + "Asking again for a refresh for {}: {} redirects since the pool was " + "refreshed.", + swarm_pubkey.hex(), + redirects); invalidate_swarm(swarm_pubkey); } From acad948095f3852eba8e50a52ef3fb313ee5048f Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Mon, 28 Sep 2026 12:13:15 +1000 Subject: [PATCH 21/68] Ask for a refresh whenever a redirect resolves to too few nodes A redirect asked for a pool refresh only when it named nodes we don't have *and* that left fewer than cache_min_swarm_size of them. The first half reads "our pool is behind", which is a fair guess for an honest redirect - a rearrangement pulls in nodes registered since our last refresh, so some names don't resolve - but it is exactly backwards for a dishonest one: a node naming only itself leaves nothing unresolved, so the pool looks fine and no refresh is asked for, while the account is pinned to a single node until one happens for another reason. Dropping that half changes one shape - a redirect naming fewer than cache_min_swarm_size nodes, all of which we know. Once enough resolve the condition is false either way, so a redirect naming a node or two we don't happen to have alongside a full swarm still asks for nothing. The redirect is followed either way; this only decides whether a refresh is also requested, and that request goes through invalidate_swarm's throttle. --- src/network/snode_pool.cpp | 20 ++++++++++++-------- tests/test_snode_pool.cpp | 12 ++++++++++++ 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/network/snode_pool.cpp b/src/network/snode_pool.cpp index 0d345a51b..3dc99999e 100644 --- a/src/network/snode_pool.cpp +++ b/src/network/snode_pool.cpp @@ -1285,11 +1285,12 @@ bool SnodePool::record_swarm_redirect( return false; } - // Named nodes we don't have are ones our pool is too old to know, and when that leaves too - // few to work with only a refresh can fill them in; the ones we do have are still in the - // right swarm, where the swarm we had just rejected us, so they are followed meanwhile - const bool pool_missing_members = - resolved.size() < named.size() && resolved.size() < _config.cache_min_swarm_size; + // Too few of the named nodes resolved to call the result a swarm: either our pool is too + // old to know the rest, or the redirect isn't describing one. Only a refresh settles + // which, and the nodes we do have still beat the swarm that just rejected us, so they are + // followed meanwhile. Deliberately not also requiring that some names were unknown - a + // redirect naming one node we do know is the shape with no stale pool to explain it. + const bool too_few_resolved = resolved.size() < _config.cache_min_swarm_size; auto& [nodes, redirects] = _swarm_overrides[swarm_pubkey]; nodes = std::move(resolved); @@ -1307,11 +1308,14 @@ bool SnodePool::record_swarm_redirect( swarm_pubkey.hex(), redirects); - if (pool_missing_members) { + if (too_few_resolved) { log::warning( cat, - "Asking for a refresh for {}: its redirect names nodes our pool doesn't have.", - swarm_pubkey.hex()); + "Asking for a refresh for {}: only {} of the {} nodes its redirect named are " + "ones we know.", + swarm_pubkey.hex(), + nodes.size(), + named.size()); invalidate_swarm(swarm_pubkey); } else if (redirects > SWARM_REDIRECTS_BEFORE_REFRESH) { // Past the limit every redirect asks again, for as long as the refresh stays diff --git a/tests/test_snode_pool.cpp b/tests/test_snode_pool.cpp index 5b57f49fe..1a9eeb4b2 100644 --- a/tests/test_snode_pool.cpp +++ b/tests/test_snode_pool.cpp @@ -687,6 +687,18 @@ TEST_CASE("Network", "[network][swarm_redirect]") { CHECK(current_swarm() == sorted(std::vector(elsewhere.begin(), elsewhere.begin() + 2))); CHECK(snode_pool->debug_refresh_in_progress()); + + // A redirect naming too few nodes to be a swarm asks for the refresh whether or not any of the + // names were unknown. One naming a single node we do know has no stale pool to explain it, and + // is the only thing serving the account until a refresh drops it, so it is the case that most + // wants one + snode_pool->update_cache(snode_cache); + snode_pool->debug_age_pool(10min); + snode_pool->debug_age_evidence_refresh(10min); + CHECK(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 1))); + CHECK(current_swarm() == + sorted(std::vector(elsewhere.begin(), elsewhere.begin() + 1))); + CHECK(snode_pool->debug_refresh_in_progress()); } TEST_CASE("Network", "[network][get_swarm_checks_age]") { From d81d252e4d9ee50dacf993e947b53e83177aee60 Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Mon, 28 Sep 2026 16:09:22 +1000 Subject: [PATCH 22/68] Silence the disable_mtu_discovery deprecation until the pin can move The Linux CI stages build against the system liboxenquic, which deprecates quic::opt::disable_mtu_discovery in favour of max_udp_payload::minimum(), and -Werror makes that fatal. The vendored libquic this repo pins has no max_udp_payload at all, so the deprecated name is the only spelling that compiles against both - there is nothing to migrate to here yet. Moving the pin is not a pin change: the newer session-router defines oxen::quic through its own session-deps, which collides with the definition in external/CMakeLists.txt, so the dependency handling has to move onto session-deps first. That comes over with the Session client work, and the TODO goes with it. --- src/network/transport/quic_transport.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/network/transport/quic_transport.cpp b/src/network/transport/quic_transport.cpp index a86fb4bc3..a743944db 100644 --- a/src/network/transport/quic_transport.cpp +++ b/src/network/transport/quic_transport.cpp @@ -148,11 +148,24 @@ void QuicTransport::_recreate_endpoint() { // The optional must CONTAIN the option to have any effect: libquic's optional-taking // handle_ep_opt overload does nothing when the optional is empty, so a default-constructed // std::optional{} silently leaves discovery enabled. + // + // TODO: replace with quic::opt::max_udp_payload::minimum(), which is the same value under the + // name that isn't deprecated. That needs a newer libquic than this pin carries, and moving the + // pin needs the dependency handling in external/CMakeLists.txt moved onto session-deps first - + // the newer session-router defines oxen::quic itself, which collides with our own definition of + // it. Both of those come over with the Session client work, and this goes when they do. + // + // Until then the deprecated name is the only spelling that compiles against both this pin and + // the newer liboxenquic the Linux CI stages take from the system, which deprecates it under + // -Werror. The replacement does not exist in the pinned copy at all. +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" _endpoint = quic::Endpoint::endpoint( *_loop, quic::Address{}, (_config.disable_mtu_discovery ? std::make_optional() : std::nullopt)); +#pragma GCC diagnostic pop } void QuicTransport::_close_connections() { From 588286d3f527147661e7c3e6c04855b9a1fb4a27 Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Mon, 28 Sep 2026 16:25:54 +1000 Subject: [PATCH 23/68] Include what the test helpers use tests/utils.hpp uses std::condition_variable, std::mutex and the lock guards without including or , and test_config_userprofile.cpp calls std::this_thread::sleep_for without . Newer standard libraries pull all three in through something else, so this builds everywhere except the older libstdc++ on the Debian 12 CI stage, which is where it fails. Both predate this branch. They surfaced now because every Linux stage used to fail compiling the network library, before it got as far as the tests. --- tests/test_config_userprofile.cpp | 1 + tests/utils.hpp | 2 ++ 2 files changed, 3 insertions(+) diff --git a/tests/test_config_userprofile.cpp b/tests/test_config_userprofile.cpp index 9133e38a8..1c72e2eb6 100644 --- a/tests/test_config_userprofile.cpp +++ b/tests/test_config_userprofile.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include "utils.hpp" diff --git a/tests/utils.hpp b/tests/utils.hpp index 047a3ba77..120637abf 100644 --- a/tests/utils.hpp +++ b/tests/utils.hpp @@ -5,7 +5,9 @@ #include #include +#include #include +#include #include #include #include From 3e9279550ad8461e3538f3fe981f368123df03d0 Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Tue, 29 Sep 2026 06:37:45 +1000 Subject: [PATCH 24/68] Version bump --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1e4365205..fee48f551 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -17,7 +17,7 @@ if(CCACHE_PROGRAM) endif() project(libsession-util - VERSION 1.9.1 + VERSION 1.9.2 DESCRIPTION "Session client utility library" LANGUAGES ${LANGS}) From dd3b0aeb9a0d698d874f8a591078e010a421f829 Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Fri, 2 Oct 2026 09:40:41 +1000 Subject: [PATCH 25/68] Switch dependency handling to session-deps Replace the libsodium-internal, zstd and simdutf submodules and cmake/StaticBuild.cmake with cmake/session-deps, and bump session-router to 2b91e9ab4 (libquic c0b9cf6). xed25519::pubkey() used libsodium-internal's fe25519 internals; it now uses a TweetNaCl subset (src/xed25519-tweetnacl.cpp). session-deps builds nettle 4, so digest calls go through nettle-compat.hpp. zstd moves 1.5.2 -> 1.5.7, which changes compressed output; test vectors updated. USE_LTO becomes the single LTO switch for session-deps and session-router. --- .gitmodules | 12 +- CMakeLists.txt | 47 ++++-- cmake/StaticBuild.cmake | 224 --------------------------- cmake/session-deps | 1 + external/CMakeLists.txt | 259 ++++++++------------------------ external/libsodium-internal | 1 - external/session-router | 2 +- external/simdutf | 1 - external/zstd | 1 - src/CMakeLists.txt | 28 ++-- src/nettle-compat.hpp | 21 +++ src/onionreq/hop_encryption.cpp | 5 +- src/xed25519-tweetnacl.cpp | 150 ++++++++++++++++++ src/xed25519.cpp | 22 +-- tests/CMakeLists.txt | 2 +- tests/test_compression.cpp | 10 +- 16 files changed, 293 insertions(+), 493 deletions(-) delete mode 100644 cmake/StaticBuild.cmake create mode 160000 cmake/session-deps delete mode 160000 external/libsodium-internal delete mode 160000 external/simdutf delete mode 160000 external/zstd create mode 100644 src/nettle-compat.hpp create mode 100644 src/xed25519-tweetnacl.cpp diff --git a/.gitmodules b/.gitmodules index a029c2087..8d6f7cfea 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,24 +1,18 @@ -[submodule "external/libsodium-internal"] - path = external/libsodium-internal - url = https://github.com/session-foundation/libsodium-internal.git [submodule "tests/Catch2"] path = tests/Catch2 url = https://github.com/catchorg/Catch2 [submodule "external/ios-cmake"] path = external/ios-cmake url = https://github.com/leetal/ios-cmake -[submodule "external/zstd"] - path = external/zstd - url = https://github.com/facebook/zstd.git [submodule "external/protobuf"] path = external/protobuf url = https://github.com/protocolbuffers/protobuf.git [submodule "external/session-router"] path = external/session-router url = https://github.com/session-foundation/session-router.git -[submodule "external/simdutf"] - path = external/simdutf - url = https://github.com/simdutf/simdutf.git [submodule "external/date"] path = external/date url = https://github.com/HowardHinnant/date.git +[submodule "cmake/session-deps"] + path = cmake/session-deps + url = https://github.com/session-foundation/session-deps.git diff --git a/CMakeLists.txt b/CMakeLists.txt index fee48f551..9ea88526e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -58,7 +58,12 @@ else() set(static_default ON) endif() -option(BUILD_STATIC_DEPS "Build all dependencies statically rather than trying to link to them on the system" ${static_default}) +# session-deps declares BUILD_STATIC_DEPS itself, defaulting to OFF; setting the cache entry first +# keeps the historical "static unless building a shared library" default. +set(BUILD_STATIC_DEPS ${static_default} CACHE BOOL "Build all dependencies statically rather than trying to link to them on the system") + +include(cmake/session-deps/Deps.cmake) + option(STATIC_BUNDLE "Build a single static .a containing everything (both code and dependencies)" ${BUILD_STATIC_DEPS}) if(STATIC_BUNDLE AND NOT BUILD_STATIC_DEPS) @@ -107,6 +112,22 @@ if(IPO_ENABLED AND NOT DEFINED CMAKE_INTERPROCEDURAL_OPTIMIZATION) set(CMAKE_INTERPROCEDURAL_OPTIMIZATION ON) endif() +# USE_LTO is the single LTO knob. Two submodule-provided options default ON independently of it: +# SESSIONDEPS_LTO (session-deps) controls LTO for static dependency builds, and WITH_LTO +# (session-router's enable_lto.cmake) controls LTO for session-router's own targets. Leaving either +# ON in a non-LTO build breaks the link: LTO'd static archives can't be consumed by a non-LTO link +# (clang emits pure bitcode archives that a plain bfd link reports as "file format not recognized", +# or silently drops the members), and session-router's LTO probe fails outright on iOS, where the +# build script configures with the macOS SDK. Seed both before any submodule evaluates its own +# option() so there is exactly one LTO switch. +set(SESSIONDEPS_LTO ${USE_LTO} CACHE BOOL "Use LTO for static dependency builds, where supported" FORCE) +set(WITH_LTO ${USE_LTO} CACHE BOOL "enable lto on compile time" FORCE) + +# The same for plain subdirectories: one whose cmake_minimum_required predates 3.9 (protobuf's is +# 3.5) has CMP0069 OLD, which makes CMake ignore CMAKE_INTERPROCEDURAL_OPTIMIZATION and build it +# without LTO, so a link that pulls such an archive's members in late fails on inline std:: functions. +set(CMAKE_POLICY_DEFAULT_CMP0069 NEW) + if(STATIC_LIBSTD) add_link_options(-static-libstdc++) if(NOT CMAKE_CXX_COMPILER_ID MATCHES Clang) @@ -123,29 +144,23 @@ include(AddStaticBundleLib) set(CMAKE_POSITION_INDEPENDENT_CODE ON) +# For a static-deps build we build everything from source; don't let oxen-logging pick up system +# fmt/spdlog via find_package. Beyond the usual reasons to prefer our own versions, a system +# fmt/spdlog is built against libstdc++ and cannot be linked into a libc++ build (undefined +# std::__1 symbols), so force the bundled submodules which build with our toolchain. +if(BUILD_STATIC_DEPS) + set(OXEN_LOGGING_FORCE_SUBMODULES ON CACHE INTERNAL "") +endif() + add_subdirectory(external) if(ENABLE_NETWORKING) - if(NOT TARGET nettle::nettle) - if(BUILD_STATIC_DEPS) - message(FATAL_ERROR "Internal error: nettle::nettle target (expected via libquic BUILD_STATIC_DEPS) not found") - else() - find_package(PkgConfig REQUIRED) - pkg_check_modules(NETTLE REQUIRED IMPORTED_TARGET nettle) - add_library(nettle INTERFACE) - target_link_libraries(nettle INTERFACE PkgConfig::NETTLE) - add_library(nettle::nettle ALIAS nettle) - endif() - endif() + session_dep(nettle 3) endif() add_subdirectory(src) add_subdirectory(proto) -if (BUILD_STATIC_DEPS) - include(StaticBuild) -endif() - if(STATIC_BUNDLE) include(combine_archives) diff --git a/cmake/StaticBuild.cmake b/cmake/StaticBuild.cmake deleted file mode 100644 index 49863f8c8..000000000 --- a/cmake/StaticBuild.cmake +++ /dev/null @@ -1,224 +0,0 @@ -# cmake bits to do a full static build, downloading and building all dependencies. - -# Most of these are CACHE STRINGs so that you can override them using -DWHATEVER during cmake -# invocation to override. - -set(LOCAL_MIRROR "" CACHE STRING "local mirror path/URL for lib downloads") - -include(ExternalProject) - -set(DEPS_DESTDIR ${CMAKE_BINARY_DIR}/static-deps) -set(DEPS_SOURCEDIR ${CMAKE_BINARY_DIR}/static-deps-sources) - -file(MAKE_DIRECTORY ${DEPS_DESTDIR}/include) - -add_library(libsession-external-libs INTERFACE IMPORTED GLOBAL) -target_include_directories(libsession-external-libs SYSTEM BEFORE INTERFACE ${DEPS_DESTDIR}/include) - -set(deps_cc "${CMAKE_C_COMPILER}") -set(deps_cxx "${CMAKE_CXX_COMPILER}") - - -function(expand_urls output source_file) - set(expanded) - foreach(mirror ${ARGN}) - list(APPEND expanded "${mirror}/${source_file}") - endforeach() - set(${output} "${expanded}" PARENT_SCOPE) -endfunction() - -function(add_static_target target ext_target libname) - add_library(${target} STATIC IMPORTED GLOBAL) - add_dependencies(${target} ${ext_target}) - target_link_libraries(${target} INTERFACE libsession-external-libs) - set_target_properties(${target} PROPERTIES - IMPORTED_LOCATION ${DEPS_DESTDIR}/lib/${libname} - ) - if(ARGN) - target_link_libraries(${target} INTERFACE ${ARGN}) - endif() - libsession_static_bundle(${target}) -endfunction() - - - -set(cross_host "") -set(cross_rc "") -if(CMAKE_CROSSCOMPILING) - if(APPLE AND NOT ARCH_TRIPLET AND APPLE_TARGET_TRIPLE) - set(ARCH_TRIPLET "${APPLE_TARGET_TRIPLE}") - endif() - set(cross_host "--host=${ARCH_TRIPLET}") - if (ARCH_TRIPLET MATCHES mingw AND CMAKE_RC_COMPILER) - set(cross_rc "WINDRES=${CMAKE_RC_COMPILER}") - endif() -endif() -if(ANDROID) - set(android_toolchain_suffix linux-android) - set(android_compiler_suffix linux-android${ANDROID_PLATFORM_LEVEL}) - if(CMAKE_ANDROID_ARCH_ABI MATCHES x86_64) - set(cross_host "--host=x86_64-linux-android") - set(android_compiler_prefix x86_64) - set(android_compiler_suffix linux-android${ANDROID_PLATFORM_LEVEL}) - set(android_toolchain_prefix x86_64) - set(android_toolchain_suffix linux-android) - elseif(CMAKE_ANDROID_ARCH_ABI MATCHES x86) - set(cross_host "--host=i686-linux-android") - set(android_compiler_prefix i686) - set(android_compiler_suffix linux-android${ANDROID_PLATFORM_LEVEL}) - set(android_toolchain_prefix i686) - set(android_toolchain_suffix linux-android) - elseif(CMAKE_ANDROID_ARCH_ABI MATCHES armeabi-v7a) - set(cross_host "--host=armv7a-linux-androideabi") - set(android_compiler_prefix armv7a) - set(android_compiler_suffix linux-androideabi${ANDROID_PLATFORM_LEVEL}) - set(android_toolchain_prefix arm) - set(android_toolchain_suffix linux-androideabi) - elseif(CMAKE_ANDROID_ARCH_ABI MATCHES arm64-v8a) - set(cross_host "--host=aarch64-linux-android") - set(android_compiler_prefix aarch64) - set(android_compiler_suffix linux-android${ANDROID_PLATFORM_LEVEL}) - set(android_toolchain_prefix aarch64) - set(android_toolchain_suffix linux-android) - else() - message(FATAL_ERROR "unknown android arch: ${CMAKE_ANDROID_ARCH_ABI}") - endif() - set(deps_cc "${ANDROID_TOOLCHAIN_ROOT}/bin/${android_compiler_prefix}-${android_compiler_suffix}-clang") - set(deps_cxx "${ANDROID_TOOLCHAIN_ROOT}/bin/${android_compiler_prefix}-${android_compiler_suffix}-clang++") - set(deps_ld "${ANDROID_TOOLCHAIN_ROOT}/bin/${android_compiler_prefix}-${android_toolchain_suffix}-ld") - set(deps_ranlib "${ANDROID_TOOLCHAIN_ROOT}/bin/${android_toolchain_prefix}-${android_toolchain_suffix}-ranlib") - set(deps_ar "${ANDROID_TOOLCHAIN_ROOT}/bin/${android_toolchain_prefix}-${android_toolchain_suffix}-ar") -endif() - -set(deps_CFLAGS "-O2") -set(deps_CXXFLAGS "-O2") - -if(CMAKE_C_COMPILER_LAUNCHER) - set(deps_cc "${CMAKE_C_COMPILER_LAUNCHER} ${deps_cc}") -endif() -if(CMAKE_CXX_COMPILER_LAUNCHER) - set(deps_cxx "${CMAKE_CXX_COMPILER_LAUNCHER} ${deps_cxx}") -endif() - -if(WITH_LTO) - set(deps_CFLAGS "${deps_CFLAGS} -flto") -endif() - -if(APPLE AND CMAKE_OSX_DEPLOYMENT_TARGET) - if(SDK_NAME) - set(deps_CFLAGS "${deps_CFLAGS} -m${SDK_NAME}-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}") - set(deps_CXXFLAGS "${deps_CXXFLAGS} -m${SDK_NAME}-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}") - else() - set(deps_CFLAGS "${deps_CFLAGS} -mmacosx-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}") - set(deps_CXXFLAGS "${deps_CXXFLAGS} -mmacosx-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}") - endif() -endif() - -if(_winver) - set(deps_CFLAGS "${deps_CFLAGS} -D_WIN32_WINNT=${_winver}") - set(deps_CXXFLAGS "${deps_CXXFLAGS} -D_WIN32_WINNT=${_winver}") -endif() - - -if("${CMAKE_GENERATOR}" STREQUAL "Unix Makefiles") - set(_make $(MAKE)) -else() - set(_make make) -endif() - - -# Builds a target; takes the target name (e.g. "readline") and builds it in an external project with -# target name suffixed with `_external`. Its upper-case value is used to get the download details -# (from the variables set above). The following options are supported and passed through to -# ExternalProject_Add if specified. If omitted, these defaults are used: -set(build_def_DEPENDS "") -set(build_def_PATCH_COMMAND "") -set(build_def_CONFIGURE_COMMAND ./configure ${cross_host} --disable-shared --prefix=${DEPS_DESTDIR} --with-pic - "CC=${deps_cc}" "CXX=${deps_cxx}" "CFLAGS=${deps_CFLAGS}" "CXXFLAGS=${deps_CXXFLAGS}" ${cross_rc}) -set(build_def_CONFIGURE_EXTRA "") -set(build_def_BUILD_COMMAND ${_make}) -set(build_def_INSTALL_COMMAND ${_make} install) -set(build_def_BUILD_BYPRODUCTS ${DEPS_DESTDIR}/lib/lib___TARGET___.a ${DEPS_DESTDIR}/include/___TARGET___.h) - -function(build_external target) - set(options DEPENDS PATCH_COMMAND CONFIGURE_COMMAND CONFIGURE_EXTRA BUILD_COMMAND INSTALL_COMMAND BUILD_BYPRODUCTS) - cmake_parse_arguments(PARSE_ARGV 1 arg "" "" "${options}") - foreach(o ${options}) - if(NOT DEFINED arg_${o}) - set(arg_${o} ${build_def_${o}}) - endif() - endforeach() - string(REPLACE ___TARGET___ ${target} arg_BUILD_BYPRODUCTS "${arg_BUILD_BYPRODUCTS}") - - string(TOUPPER "${target}" prefix) - expand_urls(urls ${${prefix}_SOURCE} ${${prefix}_MIRROR}) - set(extract_ts) - if(NOT CMAKE_VERSION VERSION_LESS 3.24) - set(extract_ts DOWNLOAD_EXTRACT_TIMESTAMP ON) - endif() - ExternalProject_Add("${target}_external" - DEPENDS ${arg_DEPENDS} - BUILD_IN_SOURCE ON - PREFIX ${DEPS_SOURCEDIR} - URL ${urls} - URL_HASH ${${prefix}_HASH} - DOWNLOAD_NO_PROGRESS ON - PATCH_COMMAND ${arg_PATCH_COMMAND} - CONFIGURE_COMMAND ${arg_CONFIGURE_COMMAND} ${arg_CONFIGURE_EXTRA} - BUILD_COMMAND ${arg_BUILD_COMMAND} - INSTALL_COMMAND ${arg_INSTALL_COMMAND} - BUILD_BYPRODUCTS ${arg_BUILD_BYPRODUCTS} - EXCLUDE_FROM_ALL ON - ${extract_ts} - ) -endfunction() - - -set(apple_cflags_arch) -set(apple_cxxflags_arch) -set(apple_ldflags_arch) -set(gmp_build_host "${cross_host}") -if(APPLE AND CMAKE_CROSSCOMPILING) - if(gmp_build_host MATCHES "^(.*-.*-)ios([0-9.]+)(-.*)?$") - set(gmp_build_host "${CMAKE_MATCH_1}darwin${CMAKE_MATCH_2}${CMAKE_MATCH_3}") - endif() - if(gmp_build_host MATCHES "^(.*-.*-.*)-simulator$") - set(gmp_build_host "${CMAKE_MATCH_1}") - endif() - - set(apple_arch) - if(ARCH_TRIPLET MATCHES "^(arm|aarch)64.*") - set(apple_arch "arm64") - elseif(ARCH_TRIPLET MATCHES "^x86_64.*") - set(apple_arch "x86_64") - else() - message(FATAL_ERROR "Don't know how to specify -arch for GMP for ${ARCH_TRIPLET} (${APPLE_TARGET_TRIPLE})") - endif() - - set(apple_cflags_arch " -arch ${apple_arch}") - set(apple_cxxflags_arch " -arch ${apple_arch}") - if(CMAKE_OSX_DEPLOYMENT_TARGET) - if (SDK_NAME) - set(apple_ldflags_arch " -m${SDK_NAME}-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}") - elseif(CMAKE_OSX_DEPLOYMENT_TARGET) - set(apple_ldflags_arch " -mmacosx-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}") - endif() - endif() - set(apple_ldflags_arch "${apple_ldflags_arch} -arch ${apple_arch}") - - if(CMAKE_OSX_SYSROOT) - foreach(f c cxx ld) - set(apple_${f}flags_arch "${apple_${f}flags_arch} -isysroot ${CMAKE_OSX_SYSROOT}") - endforeach() - endif() -elseif(gmp_build_host STREQUAL "") - set(gmp_build_host "--build=${CMAKE_LIBRARY_ARCHITECTURE}") -endif() - -link_libraries(-static-libstdc++) -if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") - link_libraries(-static-libgcc) -endif() -if(MINGW) - link_libraries(-Wl,-Bstatic -lpthread) -endif() diff --git a/cmake/session-deps b/cmake/session-deps new file mode 160000 index 000000000..dae3b07a9 --- /dev/null +++ b/cmake/session-deps @@ -0,0 +1 @@ +Subproject commit dae3b07a96020efcb3d2844eb40de35a7816f66e diff --git a/external/CMakeLists.txt b/external/CMakeLists.txt index 305c3749b..9753a5410 100644 --- a/external/CMakeLists.txt +++ b/external/CMakeLists.txt @@ -1,162 +1,68 @@ -option(SUBMODULE_CHECK "Enables checking that vendored library submodules are up to date" ON) - -if(SUBMODULE_CHECK) - find_package(Git) - if(GIT_FOUND) - function(check_submodule relative_path) - execute_process(COMMAND git rev-parse "HEAD" WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/${relative_path} OUTPUT_VARIABLE localHead) - execute_process(COMMAND git rev-parse "HEAD:external/${relative_path}" WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} OUTPUT_VARIABLE checkedHead) - string(COMPARE EQUAL "${localHead}" "${checkedHead}" upToDate) - if (upToDate) - message(STATUS "Submodule 'external/${relative_path}' is up-to-date") - else() - message(FATAL_ERROR "Submodule 'external/${relative_path}' is not up-to-date. Please update with\ngit submodule update --init --recursive\nor run cmake with -DSUBMODULE_CHECK=OFF") - endif() - - # Extra arguments check nested submodules - foreach(submod ${ARGN}) - execute_process(COMMAND git rev-parse "HEAD" WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/${relative_path}/${submod} OUTPUT_VARIABLE localHead) - execute_process(COMMAND git rev-parse "HEAD:${submod}" WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/${relative_path} OUTPUT_VARIABLE checkedHead) - string(COMPARE EQUAL "${localHead}" "${checkedHead}" upToDate) - if (NOT upToDate) - message(FATAL_ERROR "Nested submodule '${relative_path}/${submod}' is not up-to-date. Please update with\ngit submodule update --init --recursive\nor run cmake with -DSUBMODULE_CHECK=OFF") - endif() - endforeach() - endfunction () - - message(STATUS "Checking submodules") - check_submodule(ios-cmake) - check_submodule(libsodium-internal) - check_submodule(zstd) - check_submodule(protobuf) - check_submodule(session-router) - check_submodule(date) - endif() -endif() +include(../cmake/session-deps/Deps.cmake) + +message(STATUS "Checking submodules") +check_submodule(ios-cmake) +check_submodule(session-router external/nlohmann external/oxen-libquic) +# check_submodule's extra arguments are resolved as gitlinks of the first argument's repo, and it +# only recurses one level, so anything deeper needs its own call rooted at the repo that records it: +# oxen-encoding and oxen-logging belong to oxen-libquic, and fmt/spdlog to oxen-logging. +set(libquic_dir "${CMAKE_CURRENT_SOURCE_DIR}/session-router/external/oxen-libquic") +check_submodule(external/oxen-encoding WORKING_DIRECTORY "${libquic_dir}") +check_submodule(external/oxen-logging fmt spdlog WORKING_DIRECTORY "${libquic_dir}") +check_submodule(protobuf) +check_submodule(date) if(NOT BUILD_STATIC_DEPS AND NOT FORCE_ALL_SUBMODULES) find_package(PkgConfig REQUIRED) endif() -macro(libsession_system_or_submodule BIGNAME smallname target pkgconf subdir) - if(NOT TARGET ${target}) - option(FORCE_${BIGNAME}_SUBMODULE "force using ${smallname} submodule" OFF) - if(NOT BUILD_STATIC_DEPS AND NOT FORCE_${BIGNAME}_SUBMODULE AND NOT FORCE_ALL_SUBMODULES) - pkg_check_modules(${BIGNAME} ${pkgconf} IMPORTED_TARGET GLOBAL) - endif() - if(${BIGNAME}_FOUND) - add_library(${smallname} INTERFACE IMPORTED GLOBAL) - if(NOT TARGET PkgConfig::${BIGNAME} AND CMAKE_VERSION VERSION_LESS "3.21") - # Work around cmake bug 22180 (PkgConfig::THING not set if no flags needed) - else() - target_link_libraries(${smallname} INTERFACE PkgConfig::${BIGNAME}) - endif() - message(STATUS "Found system ${smallname} ${${BIGNAME}_VERSION}") - else() - message(STATUS "using ${smallname} submodule ${subdir}") - add_subdirectory(${subdir}) - endif() - if(NOT TARGET ${target}) - add_library(${target} ALIAS ${smallname}) - endif() - if(BUILD_STATIC_DEPS AND STATIC_BUNDLE) - libsession_static_bundle(${smallname}::${smallname}) - endif() - endif() -endmacro() - - -set(deps_cc "${CMAKE_C_COMPILER}") -set(cross_host "") -set(cross_rc "") -if(CMAKE_CROSSCOMPILING) - if(APPLE_TARGET_TRIPLE) - set(cross_host "--host=${APPLE_TARGET_TRIPLE}") - elseif(ANDROID) - if(CMAKE_ANDROID_ARCH_ABI MATCHES x86_64) - set(cross_host "--host=x86_64-linux-android") - set(android_compiler_prefix x86_64) - set(android_compiler_suffix linux-android) - elseif(CMAKE_ANDROID_ARCH_ABI MATCHES x86) - set(cross_host "--host=i686-linux-android") - set(android_compiler_prefix i686) - set(android_compiler_suffix linux-android) - elseif(CMAKE_ANDROID_ARCH_ABI MATCHES armeabi-v7a) - set(cross_host "--host=armv7a-linux-androideabi") - set(android_compiler_prefix armv7a) - set(android_compiler_suffix linux-androideabi) - elseif(CMAKE_ANDROID_ARCH_ABI MATCHES arm64-v8a) - set(cross_host "--host=aarch64-linux-android") - set(android_compiler_prefix aarch64) - set(android_compiler_suffix linux-android) - else() - message(FATAL_ERROR "unknown android arch: ${CMAKE_ANDROID_ARCH_ABI}") - endif() - - string(REPLACE "android-" "" android_platform_num "${ANDROID_PLATFORM}") - set(deps_cc "${ANDROID_TOOLCHAIN_ROOT}/bin/${android_compiler_prefix}-${android_compiler_suffix}${android_platform_num}-clang") - else() - set(cross_host "--host=${ARCH_TRIPLET}") - if (ARCH_TRIPLET MATCHES mingw AND CMAKE_RC_COMPILER) - set(cross_rc "WINDRES=${CMAKE_RC_COMPILER}") - endif() - endif() -endif() - -if(ENABLE_NETWORKING) - set(LIBQUIC_BUILD_TESTS OFF CACHE BOOL "") - libsession_system_or_submodule(OXENQUIC quic oxen::quic liboxenquic>=1.8 session-router/external/oxen-libquic) -endif() - -libsession_system_or_submodule(OXENC oxenc oxenc::oxenc liboxenc>=1.5.0 session-router/external/oxen-libquic/external/oxen-encoding) +function(add_static_subdirectory dir) + set(BUILD_SHARED_LIBS OFF) + add_subdirectory(${dir} ${ARGN}) +endfunction() -if(NOT TARGET oxen::logging) - # Find this one using an intermediate target alias (oxenlogging::oxenlogging) rather than the - # final oxen::logging alias target that we actually use: that way either we go into using it as - # a submodule (in which case the submodule sets up oxen::logging), or else we find via system - # lib, in which case we need an extra intermediate interface library that also brings in fmt and - # spdlog. - libsession_system_or_submodule(OXENLOGGING oxen-logging oxenlogging::oxenlogging liboxen-logging>=1.2.0 session-router/external/oxen-libquic/external/oxen-logging) - if(NOT TARGET oxen::logging) - # If we load oxen-logging via system lib then we won't necessarily have fmt/spdlog targets, - # but this script will give us them: - include(session-router/external/oxen-libquic/external/oxen-logging/cmake/load_fmt_spdlog.cmake) +# Stock libsodium, not the libsodium-internal fork: the one thing the fork exposed that we used was +# the field arithmetic behind xed25519::pubkey(), which src/xed25519-tweetnacl.cpp now supplies. +session_dep(libsodium 1.0.21) +libsession_static_bundle(sessiondep::libsodium) - add_library(oxen-logging-fmt-spdlog INTERFACE) - target_link_libraries(oxen-logging-fmt-spdlog INTERFACE oxenlogging::oxenlogging ${OXEN_LOGGING_FMT_TARGET} ${OXEN_LOGGING_SPDLOG_TARGET}) - add_library(oxen::logging ALIAS oxen-logging-fmt-spdlog) - endif() +# Needed even without networking: oxenc is part of the public interface of `common`. +if(NOT TARGET oxenc::oxenc) + set(OXENC_BUILD_TESTS OFF CACHE BOOL "") + set(OXENC_BUILD_DOCS OFF CACHE BOOL "") + sessiondep_or_submodule(liboxenc 1.5.0 session-router/external/oxen-libquic/external/oxen-encoding oxenc::oxenc) endif() +if(ENABLE_NETWORKING AND ENABLE_NETWORKING_SROUTER) + set(SROUTER_FULL OFF CACHE BOOL "") + set(SROUTER_DAEMON OFF CACHE BOOL "") + set(SROUTER_NATIVE_BUILD OFF CACHE BOOL "") + set(SROUTER_JEMALLOC OFF CACHE BOOL "") - -if(CMAKE_C_COMPILER_LAUNCHER) - set(deps_cc "${CMAKE_C_COMPILER_LAUNCHER} ${deps_cc}") + add_static_subdirectory(session-router EXCLUDE_FROM_ALL) + libsession_static_bundle(session-router::core) endif() -set(deps_CFLAGS "-O2") -if(IPO_ENABLED) - set(deps_CFLAGS "${deps_CFLAGS} -flto") +# session-router provides oxen::quic when it is built (above); otherwise pull in oxen-libquic alone. +if(ENABLE_NETWORKING AND NOT TARGET oxen::quic) + set(LIBQUIC_BUILD_TESTS OFF CACHE BOOL "") + sessiondep_or_submodule(liboxenquic 1.8.0 session-router/external/oxen-libquic oxen::quic) endif() -if(APPLE) - foreach(lang C CXX) - string(APPEND deps_${lang}FLAGS " ${CMAKE_${lang}_SYSROOT_FLAG} ${CMAKE_OSX_SYSROOT} ${CMAKE_${lang}_OSX_DEPLOYMENT_TARGET_FLAG}${CMAKE_OSX_DEPLOYMENT_TARGET}") - foreach(arch ${CMAKE_OSX_ARCHITECTURES}) - string(APPEND deps_${lang}FLAGS " -arch ${arch}") - endforeach() - endforeach() +if(NOT TARGET oxen::logging) + # oxen-logging can't go through sessiondep_or_submodule: its public headers expose fmt types and + # a system liboxen-logging's .pc doesn't pull in fmt/spdlog, so consumers must add them + # explicitly. oxen-logging ships a cmake/load.cmake that resolves oxen::logging for us -- either + # a system liboxen-logging bundled with suitable fmt/spdlog targets, or the submodule (which + # builds its own fmt/spdlog). We just force the submodule path when our other deps would also + # prefer submodules over system libs. + option(DEPS_FORCE_liboxen-logging_SUBMODULE "force using liboxen-logging submodule" OFF) + if(BUILD_STATIC_DEPS OR DEPS_FORCE_SUBMODULE OR DEPS_FORCE_liboxen-logging_SUBMODULE) + set(OXEN_LOGGING_FORCE_SUBMODULES ON) + endif() + include(session-router/external/oxen-libquic/external/oxen-logging/cmake/load.cmake) endif() -function(add_static_subdirectory dir) - set(BUILD_SHARED_LIBS OFF) - add_subdirectory(${dir} ${ARGN}) -endfunction() - -add_static_subdirectory(libsodium-internal) -libsession_static_bundle(libsodium::sodium-internal) - - set(protobuf_VERBOSE ON CACHE BOOL "" FORCE) set(protobuf_INSTALL ON CACHE BOOL "" FORCE) set(protobuf_WITH_ZLIB OFF CACHE BOOL "" FORCE) @@ -167,60 +73,23 @@ set(protobuf_BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) set(protobuf_ABSL_PROVIDER "module" CACHE STRING "" FORCE) set(protobuf_BUILD_PROTOC_BINARIES OFF CACHE BOOL "") set(protobuf_BUILD_PROTOBUF_BINARIES ON CACHE BOOL "" FORCE) -libsession_system_or_submodule(PROTOBUF_LITE protobuf_lite protobuf::libprotobuf-lite protobuf-lite>=3.21 protobuf) -if(TARGET PkgConfig::PROTOBUF_LITE AND NOT TARGET protobuf::libprotobuf-lite) - add_library(protobuf::libprotobuf-lite ALIAS PkgConfig::PROTOBUF_LITE) +sessiondep_or_submodule(protobuf-lite 3.21 protobuf protobuf::libprotobuf-lite) + +# Force a static libzstd: we want semi-stable compressed output, which means we want all session +# clients to use the same version (where that is guaranteed) as much as possible, so that duplicate +# configs get deduplicated at the swarm. +set(BUILD_STATIC_libzstd ON CACHE BOOL "" FORCE) +session_dep(libzstd 1.5) +libsession_static_bundle(sessiondep::libzstd) + +if(NOT TARGET nlohmann_json::nlohmann_json) + set(JSON_BuildTests OFF CACHE INTERNAL "") + set(JSON_Install ON CACHE INTERNAL "") # Required to export targets that we use + sessiondep_or_submodule(nlohmann_json 3.7.0 session-router/external/nlohmann nlohmann_json::nlohmann_json) endif() - -set(ZSTD_BUILD_PROGRAMS OFF CACHE BOOL "") -set(ZSTD_BUILD_TESTS OFF CACHE BOOL "") -set(ZSTD_BUILD_CONTRIB OFF CACHE BOOL "") -set(ZSTD_BUILD_SHARED OFF CACHE BOOL "") -set(ZSTD_BUILD_STATIC ON CACHE BOOL "") -set(ZSTD_MULTITHREAD_SUPPORT OFF CACHE BOOL "") -add_subdirectory(zstd/build/cmake EXCLUDE_FROM_ALL) -# zstd's cmake doesn't properly set up include paths on its targets, so we have to wrap it in an -# interface target that does: -add_library(libzstd_static_fixed_includes INTERFACE) -target_include_directories(libzstd_static_fixed_includes INTERFACE zstd/lib zstd/lib/common) -target_link_libraries(libzstd_static_fixed_includes INTERFACE libzstd_static) -add_library(libzstd::static ALIAS libzstd_static_fixed_includes) -export( - TARGETS libzstd_static_fixed_includes - NAMESPACE libsession:: - FILE libsessionZstd.cmake -) -libsession_static_bundle(libzstd_static) - - -set(JSON_BuildTests OFF CACHE INTERNAL "") -set(JSON_Install ON CACHE INTERNAL "") # Required to export targets that we use -libsession_system_or_submodule(NLOHMANN nlohmann_json nlohmann_json::nlohmann_json nlohmann_json>=3.7.0 session-router/external/nlohmann) - -if(ENABLE_NETWORKING AND ENABLE_NETWORKING_SROUTER) - set(SROUTER_FULL OFF CACHE BOOL "") - set(SROUTER_DAEMON OFF CACHE BOOL "") - set(SROUTER_NATIVE_BUILD OFF CACHE BOOL "") - set(SROUTER_JEMALLOC OFF CACHE BOOL "") - - add_library(sodium INTERFACE) - target_link_libraries(sodium INTERFACE libsodium::sodium-internal) - add_static_subdirectory(session-router EXCLUDE_FROM_ALL) - libsession_static_bundle(session-router::libsessionrouter) -endif() - -set(JSON_BuildTests OFF CACHE INTERNAL "") -set(JSON_Install ON CACHE INTERNAL "") # Required to export targets that we use - -function(simdutf_subdir) - set(SIMDUTF_TESTS OFF CACHE BOOL "") - set(SIMDUTF_TOOLS OFF CACHE BOOL "") - set(BUILD_SHARED_LIBS OFF) - add_subdirectory(simdutf) -endfunction() -simdutf_subdir() -libsession_static_bundle(simdutf) +session_dep(simdutf 7) +libsession_static_bundle(sessiondep::simdutf) # We need Howard Hinnant's header-only date library for now because the STL implementation of # std::chrono::parse() is spotty or broken on: diff --git a/external/libsodium-internal b/external/libsodium-internal deleted file mode 160000 index e12e612dc..000000000 --- a/external/libsodium-internal +++ /dev/null @@ -1 +0,0 @@ -Subproject commit e12e612dc735909a59be552f9bf03fe98e320703 diff --git a/external/session-router b/external/session-router index d2def4c91..2b91e9ab4 160000 --- a/external/session-router +++ b/external/session-router @@ -1 +1 @@ -Subproject commit d2def4c91d024f9d896b43e817520f27a41a7995 +Subproject commit 2b91e9ab42b36c4f802d3a1548d139712ee9e5df diff --git a/external/simdutf b/external/simdutf deleted file mode 160000 index 7b3f5afca..000000000 --- a/external/simdutf +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 7b3f5afcae322391a03736809ef6eea0c2934388 diff --git a/external/zstd b/external/zstd deleted file mode 160000 index e47e674cd..000000000 --- a/external/zstd +++ /dev/null @@ -1 +0,0 @@ -Subproject commit e47e674cd09583ff0503f0f6defd6d23d8b718d3 diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index e6815bc3a..578d25a1b 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -60,6 +60,7 @@ add_libsession_util_library(crypto session_protocol.cpp sodium_array.cpp xed25519.cpp + xed25519-tweetnacl.cpp pro_backend.cpp types.cpp ) @@ -91,15 +92,16 @@ target_link_libraries(util PUBLIC common oxen::logging - libzstd::static - simdutf + PRIVATE + sessiondep::libzstd + sessiondep::simdutf ) target_link_libraries(crypto PUBLIC util PRIVATE - libsodium::sodium-internal + sessiondep::libsodium nlohmann_json::nlohmann_json libsession::protos ) @@ -109,17 +111,11 @@ target_link_libraries(config crypto libsession::protos PRIVATE - libsodium::sodium-internal + sessiondep::libsodium ) if(ENABLE_NETWORKING) - # libevent - if(NOT TARGET libevent::core) - add_library(libevent_core INTERFACE) - pkg_check_modules(LIBEVENT_core libevent_core>=2.1 IMPORTED_TARGET REQUIRED) - target_link_libraries(libevent_core INTERFACE PkgConfig::LIBEVENT_core) - add_library(libevent::core ALIAS libevent_core) - endif() + session_dep(libevent_core 2.1) add_libsession_util_library(network onionreq/builder.cpp @@ -145,20 +141,20 @@ if(ENABLE_NETWORKING) target_link_libraries(network PUBLIC crypto - quic + oxen::quic PRIVATE nlohmann_json::nlohmann_json - libsodium::sodium-internal - nettle::nettle + sessiondep::libsodium + sessiondep::nettle date::date - libevent::core + sessiondep::libevent_core ) if(ENABLE_NETWORKING_SROUTER) target_sources(network PRIVATE network/routing/session_router_router.cpp) - target_link_libraries(network PUBLIC session-router::libsessionrouter) + target_link_libraries(network PUBLIC session-router::core) endif() if (BUILD_STATIC_DEPS) diff --git a/src/nettle-compat.hpp b/src/nettle-compat.hpp new file mode 100644 index 000000000..07111004c --- /dev/null +++ b/src/nettle-compat.hpp @@ -0,0 +1,21 @@ +#pragma once + +#include +#include + +namespace session { + +// nettle 4.0 dropped the length argument from the *_digest functions, which now always write the +// full digest. We build against both a distro nettle 3 and the vendored nettle 4, so dispatch on +// whichever signature the nettle in use declares rather than on a version macro. Every call site +// asks for the full digest length, which is what nettle 3 needs and what nettle 4 assumes, so the +// two spellings compute the same thing. +template +void nettle_digest(Ctx* ctx, std::size_t length, Out* out) { + if constexpr (std::is_invocable_v) + digest(ctx, length, out); + else + digest(ctx, out); +} + +} // namespace session diff --git a/src/onionreq/hop_encryption.cpp b/src/onionreq/hop_encryption.cpp index 69a491c6c..10fb69d81 100644 --- a/src/onionreq/hop_encryption.cpp +++ b/src/onionreq/hop_encryption.cpp @@ -16,6 +16,7 @@ #include #include +#include "../nettle-compat.hpp" #include "session/export.h" #include "session/network/key_types.hpp" #include "session/onionreq/builder.hpp" @@ -134,7 +135,7 @@ std::vector HopEncryption::encrypt_aesgcm( o += plaintext.size(); // Append digest - gcm_aes256_digest(&ctx, GCM_DIGEST_SIZE, o); + nettle_digest(&ctx, GCM_DIGEST_SIZE, o); o += GCM_DIGEST_SIZE; assert(o == output.data() + output.size()); @@ -169,7 +170,7 @@ std::vector HopEncryption::decrypt_aesgcm( gcm_aes256_decrypt(&ctx, ciphertext.size(), plaintext.data(), ciphertext.data()); std::array digest_out; - gcm_aes256_digest(&ctx, digest_out.size(), digest_out.data()); + nettle_digest(&ctx, digest_out.size(), digest_out.data()); if (sodium_memcmp(digest_out.data(), digest_in.data(), GCM_DIGEST_SIZE) != 0) throw std::runtime_error{"Decryption failed (AES256-GCM)"}; diff --git a/src/xed25519-tweetnacl.cpp b/src/xed25519-tweetnacl.cpp new file mode 100644 index 000000000..b0b572221 --- /dev/null +++ b/src/xed25519-tweetnacl.cpp @@ -0,0 +1,150 @@ +// This file contains a subset of TweetNaCl (https://tweetnacl.cr.yp.to/software.html) public domain +// code to perform the X25519 -> Ed25519 conversion; libsodium doesn't provide enough access to +// internals to compute this without hacking up libsodium's build, which is fragile. Hence we use +// this subset of the portable TweetNaCl for that single function, and libsodium for everything +// else. + +#include +#include +#include + +#include "session/xed25519.hpp" + +namespace session::xed25519 { + +namespace { + + // clang-format off + +#define FOR(i,n) for (i = 0;i < n;++i) + +using gf = int64_t[16]; + +const gf gf1 = {1}; + +void car25519(gf o) +{ + int i; + int64_t c; + FOR(i,16) { + o[i]+=(1LL<<16); + c=o[i]>>16; + o[(i+1)*(i<15)]+=c-1+37*(c-1)*(i==15); + o[i]-=c<<16; + } +} + +void sel25519(gf p,gf q,int b) +{ + int64_t t,i,c=~(b-1); + FOR(i,16) { + t= c&(p[i]^q[i]); + p[i]^=t; + q[i]^=t; + } +} + +void pack25519(uint8_t *o,const gf n) +{ + int i,j,b; + gf m,t; + FOR(i,16) t[i]=n[i]; + car25519(t); + car25519(t); + car25519(t); + FOR(j,2) { + m[0]=t[0]-0xffed; + for(i=1;i<15;i++) { + m[i]=t[i]-0xffff-((m[i-1]>>16)&1); + m[i-1]&=0xffff; + } + m[15]=t[15]-0x7fff-((m[14]>>16)&1); + b=(m[15]>>16)&1; + m[14]&=0xffff; + sel25519(t,m,1-b); + } + FOR(i,16) { + o[2*i]=t[i]&0xff; + o[2*i+1]=t[i]>>8; + } +} + +void unpack25519(gf o, const uint8_t *n) +{ + int i; + FOR(i,16) o[i]=n[2*i]+((int64_t)n[2*i+1]<<8); + o[15]&=0x7fff; +} + +void A(gf o,const gf a,const gf b) +{ + int i; + FOR(i,16) o[i]=a[i]+b[i]; +} + +void Z(gf o,const gf a,const gf b) +{ + int i; + FOR(i,16) o[i]=a[i]-b[i]; +} + +void M(gf o,const gf a,const gf b) +{ + int64_t i,j,t[31]; + FOR(i,31) t[i]=0; + FOR(i,16) FOR(j,16) t[i+j]+=a[i]*b[j]; + FOR(i,15) t[i]+=38*t[i+16]; + FOR(i,16) o[i]=t[i]; + car25519(o); + car25519(o); +} + +void S(gf o,const gf a) +{ + M(o,a,a); +} + +// Y +void inv25519(gf o,const gf i) +{ + gf c; + int a; + FOR(a,16) c[a]=i[a]; + for(a=253;a>=0;a--) { + S(c,c); + if(a!=2&&a!=4) M(c,c,i); + } + FOR(a,16) o[a]=c[a]; +} + + // clang-format on + +} // namespace + +std::array pubkey(std::span x_pk) { + gf u; + unpack25519(u, x_pk.data()); + + // u - 1 + gf u_minus_one; + Z(u_minus_one, u, gf1); + + // Compute: u + 1 + gf u_plus_one; + A(u_plus_one, u, gf1); + + // Compute: (u + 1)^-1 + gf u_plus_one_inv; + inv25519(u_plus_one_inv, u_plus_one); + + // Compute: y = (u - 1) * (u + 1)^-1 + gf y; + M(y, u_minus_one, u_plus_one_inv); + + // Encode to 32 bytes (sign bit is naturally 0) + std::array ed_pk; + pack25519(ed_pk.data(), y); + return ed_pk; +} + +} // namespace session::xed25519 diff --git a/src/xed25519.cpp b/src/xed25519.cpp index ce1e9e5fb..6e5a87177 100644 --- a/src/xed25519.cpp +++ b/src/xed25519.cpp @@ -2,7 +2,6 @@ #include #include -#include #include #include #include @@ -21,16 +20,6 @@ using bytes = std::array; namespace { - void fe25519_montx_to_edy(fe25519 y, const fe25519 u) { - fe25519 one; - crypto_internal_fe25519_1(one); - fe25519 um1, up1; - crypto_internal_fe25519_sub(um1, u, one); - crypto_internal_fe25519_add(up1, u, one); - crypto_internal_fe25519_invert(up1, up1); - crypto_internal_fe25519_mul(y, um1, up1); - } - // We construct an Ed25519-like signature with one important difference: where Ed25519 // calculates `r = H(S || M) mod L` (where S is the second half of the SHA-512 hash of the // secret key) we instead calculate `r = H(a || M || Z) mod L`. @@ -144,16 +133,7 @@ bool verify(std::string_view signature, std::string_view curve25519_pubkey, std: return verify(sig.first<64>(), pubkey.first<32>(), to_span(msg)); } -std::array pubkey(std::span curve25519_pubkey) { - fe25519 u, y; - crypto_internal_fe25519_frombytes(u, curve25519_pubkey.data()); - fe25519_montx_to_edy(y, u); - - std::array ed_pubkey; - crypto_internal_fe25519_tobytes(ed_pubkey.data(), y); - - return ed_pubkey; -} +// pubkey(std::span) is in xed25519-tweetnacl.cpp std::string pubkey(std::string_view curve25519_pubkey) { auto x_pk = to_span(curve25519_pubkey); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 3f0cd7f9a..4b93aa096 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -52,7 +52,7 @@ add_library(test_libs INTERFACE) target_link_libraries(test_libs INTERFACE libsession::config - libsodium::sodium-internal + sessiondep::libsodium nlohmann_json::nlohmann_json oxen::logging) diff --git a/tests/test_compression.cpp b/tests/test_compression.cpp index 2667d3423..fa361e334 100644 --- a/tests/test_compression.cpp +++ b/tests/test_compression.cpp @@ -123,11 +123,11 @@ TEST_CASE("compression", "[config][compression]") { d = data2; session::config::compress_message(d, 19); CHECK(d[0] == 'z'); - CHECK(d.size() == 157); // Yeah, it actually gets *bigger* with supposedly "higher" compression + CHECK(d.size() == 156); CHECK(d.size() < data2.size()); CHECK(to_hex(d) == - "7a28b52ffd20aa9d0400e40764313a23693165313a2664313a6e31323a4b616c6c6965313a7032393a68" - "7474703a2f2f6b2e6578616d706c652e6f72672f4b626d70313a71323473656372657465313a3c6c6c69" - "306533323aea173b57beca8af18c3519a7bbf69c3e7a05d1c049fa9558341d8ebb48b0c96564653d6431" - "3a6e303a313a7071303a6565070028812c55282f03fceac460149b57cd509a"); + "7a28b52ffd20aa95040022881f1f907d9c93291a7627219a79d06bb82c3c69341b104115dbf3c0860176" + "f63013ff7ba4247de211d1275be493fffff6eb7892db81b9dc9da26f40955e5d868586cd577bb69e00f7" + "caf2110f04219f7cf49bda3f19a5f4091966d5c199a3f14132c4d26f7cc7e14914edbca3903ef91e0862" + "955712d1275be1939f78844fb606008c12e0cb50be3a1c18c5e655339426"); } From 44958ab9fcadf93c17bba0f10cf6560412725b2a Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Fri, 2 Oct 2026 10:30:20 +1000 Subject: [PATCH 26/68] Port session_router_router to session-router's tunnel claims; bump session-router to afb98f9 --- external/session-router | 2 +- .../network/routing/session_router_router.hpp | 9 +++++++ src/network/routing/session_router_router.cpp | 27 ++++++++++++++++--- 3 files changed, 33 insertions(+), 5 deletions(-) diff --git a/external/session-router b/external/session-router index 2b91e9ab4..afb98f959 160000 --- a/external/session-router +++ b/external/session-router @@ -1 +1 @@ -Subproject commit 2b91e9ab42b36c4f802d3a1548d139712ee9e5df +Subproject commit afb98f959f4f7e0ef996aef02fa21a6caf26b1e9 diff --git a/include/session/network/routing/session_router_router.hpp b/include/session/network/routing/session_router_router.hpp index 64e5c4e23..805b734dc 100644 --- a/include/session/network/routing/session_router_router.hpp +++ b/include/session/network/routing/session_router_router.hpp @@ -42,6 +42,15 @@ class SessionRouter : public IRouter, public std::enable_shared_from_this _transport; std::unordered_map _active_tunnels; + + // The claim on each tunnel we have asked session-router for. session-router closes a tunnel + // when its last claim is destroyed, so these have to outlive the request that created them: + // dropping the return value of establish_udp() tears the tunnel down immediately. Type-erased + // (each is a session::router::udp_tunnel) so that this header need not include + // . Guarded separately from `_active_tunnels` because session-router + // invokes the failure callback, which releases a claim, from its own thread. + std::mutex _tunnel_claims_mutex; + std::unordered_map> _tunnel_claims; std::unordered_map>> _pending_requests; std::unordered_map> _active_uploads; diff --git a/src/network/routing/session_router_router.cpp b/src/network/routing/session_router_router.cpp index 19240cfc1..4645d0f43 100644 --- a/src/network/routing/session_router_router.cpp +++ b/src/network/routing/session_router_router.cpp @@ -302,6 +302,10 @@ void SessionRouter::_close_connections() { // Clear all storage of requests, paths and connections so that we are in a fresh state on // relaunch _active_tunnels.clear(); + { + std::lock_guard lock{_tunnel_claims_mutex}; + _tunnel_claims.clear(); + } _pending_requests.clear(); _update_status(ConnectionStatus::disconnected); log::info(cat, "Closed all connections."); @@ -855,7 +859,7 @@ void SessionRouter::_establish_tunnel( "[Request {}] Establishing new tunnel to {}.", initiating_req_id, address_pubkey_hex); - srouter->establish_udp( + auto claim = srouter->establish_udp( srouter_address, test_port, [weak_self = weak_from_this(), this, address_pubkey_hex, initiating_req_id]( @@ -888,18 +892,26 @@ void SessionRouter::_establish_tunnel( _send_via_tunnel(info, std::move(req), std::move(cb)); } }, - [weak_self = weak_from_this(), this, address_pubkey_hex, initiating_req_id]() mutable { + [weak_self = weak_from_this(), this, address_pubkey_hex, initiating_req_id]( + router::tunnel_failure reason) mutable { auto self = weak_self.lock(); if (!self) return; log::info( cat, - "[Request {}] Unable to establish session router UDP connection to {}.", + "[Request {}] Unable to establish session router UDP connection to {} " + "({}).", initiating_req_id, - address_pubkey_hex); + address_pubkey_hex, + reason == router::tunnel_failure::unreachable ? "no relay contact" + : "timed out"); _active_tunnels.erase(address_pubkey_hex); + { + std::lock_guard lock{_tunnel_claims_mutex}; + _tunnel_claims.erase(address_pubkey_hex); + } // Fail all the pending requests for this connection if (auto it = _pending_requests.find(address_pubkey_hex); @@ -924,6 +936,13 @@ void SessionRouter::_establish_tunnel( if (_active_tunnels.empty()) _update_status(ConnectionStatus::disconnected); }); + + // Keep the tunnel open for as long as we hold the node's entry. If the failure callback has + // already run on session-router's thread this leaves a claim behind for a tunnel that failed, + // which is harmless: a later request to the same node replaces it. + std::lock_guard lock{_tunnel_claims_mutex}; + _tunnel_claims.insert_or_assign( + address_pubkey_hex, std::make_shared(std::move(claim))); } void SessionRouter::_send_via_tunnel( From 203c65b0bf00d78da8544038f00cce413e84ff21 Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Fri, 2 Oct 2026 13:59:44 +1000 Subject: [PATCH 27/68] quic: use max_udp_payload::minimum() instead of the deprecated disable_mtu_discovery libquic 1.9 deprecates opt::disable_mtu_discovery as exactly this value; behaviour is unchanged. --- src/network/transport/quic_transport.cpp | 22 +++++++--------------- 1 file changed, 7 insertions(+), 15 deletions(-) diff --git a/src/network/transport/quic_transport.cpp b/src/network/transport/quic_transport.cpp index a743944db..8c53bbe76 100644 --- a/src/network/transport/quic_transport.cpp +++ b/src/network/transport/quic_transport.cpp @@ -147,25 +147,17 @@ void QuicTransport::send_request(Request request, network_response_callback_t ca void QuicTransport::_recreate_endpoint() { // The optional must CONTAIN the option to have any effect: libquic's optional-taking // handle_ep_opt overload does nothing when the optional is empty, so a default-constructed - // std::optional{} silently leaves discovery enabled. + // std::optional{} silently leaves discovery enabled. // - // TODO: replace with quic::opt::max_udp_payload::minimum(), which is the same value under the - // name that isn't deprecated. That needs a newer libquic than this pin carries, and moving the - // pin needs the dependency handling in external/CMakeLists.txt moved onto session-deps first - - // the newer session-router defines oxen::quic itself, which collides with our own definition of - // it. Both of those come over with the Session client work, and this goes when they do. - // - // Until then the deprecated name is the only spelling that compiles against both this pin and - // the newer liboxenquic the Linux CI stages take from the system, which deprecates it under - // -Werror. The replacement does not exist in the pinned copy at all. -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wdeprecated-declarations" + // Capping the payload at the QUIC minimum leaves path MTU discovery nothing to probe, which is + // what "disable" has always meant here. This replaces the deprecated opt::disable_mtu_discovery, + // which libquic defines as exactly this value. _endpoint = quic::Endpoint::endpoint( *_loop, quic::Address{}, - (_config.disable_mtu_discovery ? std::make_optional() - : std::nullopt)); -#pragma GCC diagnostic pop + (_config.disable_mtu_discovery + ? std::make_optional(quic::opt::max_udp_payload::minimum()) + : std::nullopt)); } void QuicTransport::_close_connections() { From 798a4cfbb0d007394f0c43ad77ccabd6fb720e35 Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Tue, 6 Oct 2026 09:48:29 +1100 Subject: [PATCH 28/68] Bump version number --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 9ea88526e..cda2a7b90 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -17,7 +17,7 @@ if(CCACHE_PROGRAM) endif() project(libsession-util - VERSION 1.9.2 + VERSION 1.9.3 DESCRIPTION "Session client utility library" LANGUAGES ${LANGS}) From 1ed9624daa7d17a6ee51fbafa7167858f1e99a7b Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Tue, 6 Oct 2026 10:05:05 +1100 Subject: [PATCH 29/68] Drop the unused build-tree export() calls; clang-format session-deps' system-library targets (e.g. protobuf-lite) are not in any export set, so export(TARGETS protos) fails to generate when building against system libraries. Nothing consumes libsessionTargets.cmake; client removed these as well. --- proto/CMakeLists.txt | 5 ----- src/CMakeLists.txt | 5 ----- src/network/transport/quic_transport.cpp | 4 ++-- 3 files changed, 2 insertions(+), 12 deletions(-) diff --git a/proto/CMakeLists.txt b/proto/CMakeLists.txt index 324b116b8..a7ab778af 100644 --- a/proto/CMakeLists.txt +++ b/proto/CMakeLists.txt @@ -23,11 +23,6 @@ endif() libsession_static_bundle(protos) add_library(libsession::protos ALIAS protos) -export( - TARGETS protos - NAMESPACE libsession:: - FILE libsessionTargets.cmake -) list(APPEND libsession_export_targets protos) set(libsession_export_targets "${libsession_export_targets}" PARENT_SCOPE) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 578d25a1b..8f9cff05e 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -212,11 +212,6 @@ target_link_libraries(common INTERFACE version) foreach(tgt ${export_targets}) add_library("libsession::${tgt}" ALIAS "${tgt}") endforeach() -export( - TARGETS ${export_targets} common version - NAMESPACE libsession:: - APPEND FILE libsessionTargets.cmake -) list(APPEND libsession_export_targets ${export_targets}) set(libsession_export_targets "${libsession_export_targets}" PARENT_SCOPE) diff --git a/src/network/transport/quic_transport.cpp b/src/network/transport/quic_transport.cpp index 8c53bbe76..f4c97376a 100644 --- a/src/network/transport/quic_transport.cpp +++ b/src/network/transport/quic_transport.cpp @@ -150,8 +150,8 @@ void QuicTransport::_recreate_endpoint() { // std::optional{} silently leaves discovery enabled. // // Capping the payload at the QUIC minimum leaves path MTU discovery nothing to probe, which is - // what "disable" has always meant here. This replaces the deprecated opt::disable_mtu_discovery, - // which libquic defines as exactly this value. + // what "disable" has always meant here. This replaces the deprecated + // opt::disable_mtu_discovery, which libquic defines as exactly this value. _endpoint = quic::Endpoint::endpoint( *_loop, quic::Address{}, From 6f27df0c9e24ed8d37e495c5c581c474fbbdfe10 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Fri, 2 Oct 2026 13:47:53 -0300 Subject: [PATCH 30/68] Bump session-deps to current dev libquic 1.11.0 relies on session-deps' patched ngtcp2 1.25.0 recipe (6b37832, d74f5b1). That change kept session_deps_version at 1.28, the same as 58c5a08, and with equal versions the first copy loaded wins: ours, at the top level. So anything older here would quietly build libquic against the unpatched ngtcp2. Also picked up from dae3b07 (what client pins): 9051cd2 passes the macOS deployment target to the CMake-built deps on native builds (zstd and simdutf were being built for the SDK's own macOS version, 15.0 on a current Xcode, rather than our 10.15), and cc67e32 builds CMake deps as Release by default. --- cmake/session-deps | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/session-deps b/cmake/session-deps index dae3b07a9..d74f5b137 160000 --- a/cmake/session-deps +++ b/cmake/session-deps @@ -1 +1 @@ -Subproject commit dae3b07a96020efcb3d2844eb40de35a7816f66e +Subproject commit d74f5b1376cd2c106461d9a334a5c635d50bed87 From 8ee3ea55008da340cb9ed91fadf965f265e3ee23 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Fri, 2 Oct 2026 13:48:01 -0300 Subject: [PATCH 31/68] Make ENABLE_NETWORKING_SROUTER=OFF link, and default it off session_network.cpp called SessionRouter::make() unconditionally while session_router_router.cpp is only compiled with ENABLE_NETWORKING_SROUTER, so an OFF build produced a static library with an undefined reference that only showed up when something linked it (which is why the mingw CI build, a static library alone, never noticed). Gate the session-router code on a compile definition, as client does, and throw if the session_router router is requested from a build without it. No client on this branch routes through session-router, so default the option off rather than making every networking build carry it. --- CMakeLists.txt | 4 +++- src/CMakeLists.txt | 1 + src/network/session_network.cpp | 8 ++++++++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index cda2a7b90..a9389a577 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -93,7 +93,9 @@ option(USE_LTO "Use Link-Time Optimization" ${use_lto_default}) # Provide this as an option for now because GMP and Desktop are sometimes unhappy with each other. option(ENABLE_NETWORKING "Build with networking functionality" ON) -option(ENABLE_NETWORKING_SROUTER "Build with session-router networking support (requires ENABLE_NETWORKING)" ON) +# No client on this branch routes through session-router, so it is off by default rather than costing +# every networking build its dependency tree. +option(ENABLE_NETWORKING_SROUTER "Build with session-router networking support (requires ENABLE_NETWORKING)" OFF) if(USE_LTO) include(CheckIPOSupported) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 8f9cff05e..00821b6da 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -155,6 +155,7 @@ if(ENABLE_NETWORKING) PRIVATE network/routing/session_router_router.cpp) target_link_libraries(network PUBLIC session-router::core) + target_compile_definitions(network PRIVATE ENABLE_NETWORKING_SROUTER) endif() if (BUILD_STATIC_DEPS) diff --git a/src/network/session_network.cpp b/src/network/session_network.cpp index 1270771db..f56e690be 100644 --- a/src/network/session_network.cpp +++ b/src/network/session_network.cpp @@ -18,7 +18,9 @@ #include "session/network/request_queue.hpp" #include "session/network/routing/direct_router.hpp" #include "session/network/routing/onion_request_router.hpp" +#ifdef ENABLE_NETWORKING_SROUTER #include "session/network/routing/session_router_router.hpp" +#endif #include "session/network/session_network.h" #include "session/network/session_network_types.hpp" #include "session/network/transport/quic_transport.hpp" @@ -87,6 +89,7 @@ namespace { return {file_server_config}; } +#ifdef ENABLE_NETWORKING_SROUTER config::SessionRouter build_session_router_config( const config::Config& main_config, const config::FileServer& file_server_config) { if (!main_config.cache_directory) @@ -101,6 +104,7 @@ namespace { *main_config.cache_directory, main_config.path_length}; } +#endif config::OnionRequestRouter build_onion_request_router_config( const config::Config& main_config, const config::FileServer& file_server_config) { @@ -203,12 +207,16 @@ Network::Network(config::Config _conf) : break; case opt::router::Type::session_router: +#ifdef ENABLE_NETWORKING_SROUTER _router = SessionRouter::make( std::move(build_session_router_config(config, file_server_config)), _loop, _snode_pool, _transport); break; +#else + throw std::runtime_error{"Session Router support is not enabled in this build!"}; +#endif case opt::router::Type::direct: _router = std::make_unique( From 5893e627490278a48226fe20472fef1150030574 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Fri, 2 Oct 2026 13:59:50 -0300 Subject: [PATCH 32/68] quic_transport: describe the MTU cap, not the change that introduced it --- src/network/transport/quic_transport.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/network/transport/quic_transport.cpp b/src/network/transport/quic_transport.cpp index f4c97376a..2ccc40320 100644 --- a/src/network/transport/quic_transport.cpp +++ b/src/network/transport/quic_transport.cpp @@ -150,8 +150,7 @@ void QuicTransport::_recreate_endpoint() { // std::optional{} silently leaves discovery enabled. // // Capping the payload at the QUIC minimum leaves path MTU discovery nothing to probe, which is - // what "disable" has always meant here. This replaces the deprecated - // opt::disable_mtu_discovery, which libquic defines as exactly this value. + // how "disable" is expressed to libquic. _endpoint = quic::Endpoint::endpoint( *_loop, quic::Address{}, From 025c2288f11c566a5877e0e5f313a50671a782fc Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Mon, 5 Oct 2026 18:49:50 -0300 Subject: [PATCH 33/68] Bump session-router for libquic 1.11.0 libsession takes libquic from session-router's submodule even with ENABLE_NETWORKING_SROUTER off, so this is what moves it from a pre-1.9.0 snapshot (c1835882) to 1.11.0. Since then libquic has fixed a use-after-free in Endpoint::drop_connection (1.9.1), stopped using a connection that ngtcp2 has rejected and stopped requesting chunks from a closing stream (1.10.1), no longer treats writing to a closing or draining connection as an error (1.10.2), and in 1.11.0 does its own PMTU probing, drops packets on EMSGSIZE/ENOBUFS rather than closing the connection, and migrates rather than closes a connection when the host's source address changes. --- external/session-router | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/external/session-router b/external/session-router index afb98f959..1f5da8692 160000 --- a/external/session-router +++ b/external/session-router @@ -1 +1 @@ -Subproject commit afb98f959f4f7e0ef996aef02fa21a6caf26b1e9 +Subproject commit 1f5da86924d49278ada9e926eff38f78d8c9a25e From 609408cd70964c4044425d1b85bf2afa5096a939 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Mon, 5 Oct 2026 19:54:44 -0300 Subject: [PATCH 34/68] Bump session-deps for gnutls's Apple frameworks session-deps' gnutls recipe never passed on the Security and CoreFoundation frameworks that gnutls's own gnutls.pc lists on darwin, so a static macOS link of anything using libquic failed on gnutls's system-trust symbols unless something else happened to add them. With session-router off by default here, nothing else does. --- cmake/session-deps | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/session-deps b/cmake/session-deps index d74f5b137..695ac85f0 160000 --- a/cmake/session-deps +++ b/cmake/session-deps @@ -1 +1 @@ -Subproject commit d74f5b1376cd2c106461d9a334a5c635d50bed87 +Subproject commit 695ac85f00cde0117f8017b7b68a7c3db17f2c70 From 080744c138428785558c795c96a49b1307965561 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Mon, 5 Oct 2026 22:34:15 -0300 Subject: [PATCH 35/68] Bump session-deps for macOS cross-arch builds session-deps' meson cross file setup died on utils/macos.sh's x86_64 build (CMAKE_SYSTEM_NAME=Darwin with no SDK_NAME) before any dependency was asked for, breaking the static macOS build. --- cmake/session-deps | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/session-deps b/cmake/session-deps index 695ac85f0..e809a6419 160000 --- a/cmake/session-deps +++ b/cmake/session-deps @@ -1 +1 @@ -Subproject commit 695ac85f00cde0117f8017b7b68a7c3db17f2c70 +Subproject commit e809a64190494683935b63a8b8481178c1b1a8ab From a9bafa6c42d93018c00d5ca4a6da704b714cafa5 Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Tue, 6 Oct 2026 12:37:22 +1100 Subject: [PATCH 36/68] Add opt::quic_max_udp_payload (from client) Backports client's QUIC payload cap (b46b88f7), MTU part only: a size cap in the C++ options, Config, the C API (session_network_config.quic_max_udp_payload) and QuicTransport. quic_disable_mtu_discovery stays as a supported alias for a 1200 cap rather than being deprecated. Values under 1200 are rejected when the option is set instead of when libquic builds the endpoint. --- include/session/network/network_config.hpp | 3 +- include/session/network/network_opt.hpp | 11 ++++++- include/session/network/session_network.h | 5 ++- .../network/transport/quic_transport.hpp | 2 +- src/network/network_config.cpp | 13 ++++++-- src/network/session_network.cpp | 9 ++++-- src/network/transport/quic_transport.cpp | 9 ++---- tests/CMakeLists.txt | 1 + tests/test_network_config.cpp | 32 +++++++++++++++++++ tests/test_quic_transport.cpp | 2 +- 10 files changed, 71 insertions(+), 16 deletions(-) create mode 100644 tests/test_network_config.cpp diff --git a/include/session/network/network_config.hpp b/include/session/network/network_config.hpp index 50eded586..c1b0bcf65 100644 --- a/include/session/network/network_config.hpp +++ b/include/session/network/network_config.hpp @@ -64,7 +64,7 @@ struct Config { // Quic Transport Options std::chrono::milliseconds quic_handshake_timeout{3s}; std::chrono::seconds quic_keep_alive{10s}; - bool quic_disable_mtu_discovery = false; + std::optional quic_max_udp_payload; template requires(sizeof...(Opt) > 0 && (opt::is_option> && ...)) @@ -115,6 +115,7 @@ struct Config { // Quic transport options void handle_config_opt(opt::quic_handshake_timeout qht); void handle_config_opt(opt::quic_keep_alive qka); + void handle_config_opt(opt::quic_max_udp_payload qmup); void handle_config_opt(opt::quic_disable_mtu_discovery qdmd); // Onion request router options diff --git a/include/session/network/network_opt.hpp b/include/session/network/network_opt.hpp index 67c52bfc5..10ee3170b 100644 --- a/include/session/network/network_opt.hpp +++ b/include/session/network/network_opt.hpp @@ -376,7 +376,15 @@ namespace opt { quic_keep_alive(std::chrono::seconds duration) : duration{duration} {} }; - /// Can be used to disable Quic MTU discovery. + /// Caps the QUIC UDP payload size. Path MTU discovery still probes upward from 1200 but never + /// past this value. Must be at least 1200, the QUIC minimum. + struct quic_max_udp_payload { + size_t size; + explicit quic_max_udp_payload(size_t s) : size{s} {} + }; + + /// Equivalent to `quic_max_udp_payload{1200}`, which leaves path MTU discovery nothing to + /// probe. struct quic_disable_mtu_discovery {}; // MARK: Onion Request Router Options @@ -467,6 +475,7 @@ namespace opt { // Quic transport options quic_handshake_timeout, quic_keep_alive, + quic_max_udp_payload, quic_disable_mtu_discovery, // Onion request router options diff --git a/include/session/network/session_network.h b/include/session/network/session_network.h index 43451f18d..dff3a5025 100644 --- a/include/session/network/session_network.h +++ b/include/session/network/session_network.h @@ -94,7 +94,10 @@ typedef struct session_network_config { // Quic transport options (for transport == SESSION_NETWORK_TRANSPORT_QUIC) uint32_t quic_handshake_timeout_seconds; uint32_t quic_keep_alive_seconds; - bool quic_disable_mtu_discovery; + bool quic_disable_mtu_discovery; // same as quic_max_udp_payload = 1200 + /// Maximum QUIC UDP payload size; 0 for no cap. Must otherwise be at least 1200. Takes + /// precedence over quic_disable_mtu_discovery when non-zero. + size_t quic_max_udp_payload; } session_network_config; diff --git a/include/session/network/transport/quic_transport.hpp b/include/session/network/transport/quic_transport.hpp index 12f220b71..d0281f5ce 100644 --- a/include/session/network/transport/quic_transport.hpp +++ b/include/session/network/transport/quic_transport.hpp @@ -24,7 +24,7 @@ namespace config { std::chrono::milliseconds handshake_timeout; std::chrono::seconds keep_alive; - bool disable_mtu_discovery; + std::optional max_udp_payload; }; } // namespace config diff --git a/src/network/network_config.cpp b/src/network/network_config.cpp index e97aca9ea..392460c01 100644 --- a/src/network/network_config.cpp +++ b/src/network/network_config.cpp @@ -235,9 +235,18 @@ void Config::handle_config_opt(opt::quic_keep_alive qka) { log::debug(cat, "Network config quic keep alive set to {}s", qka.duration.count()); } +void Config::handle_config_opt(opt::quic_max_udp_payload qmup) { + // libquic rejects anything smaller, but only once the endpoint is built: catch it here, where + // it is still a configuration error rather than a failure deep inside network setup. + if (qmup.size < 1200) + throw std::invalid_argument{ + "quic_max_udp_payload must be at least 1200, got {}"_format(qmup.size)}; + quic_max_udp_payload = qmup.size; + log::debug(cat, "Network config max QUIC UDP payload set to {} bytes", qmup.size); +} + void Config::handle_config_opt(opt::quic_disable_mtu_discovery) { - quic_disable_mtu_discovery = true; - log::debug(cat, "Network config disabled MTU discovery for Quic"); + handle_config_opt(opt::quic_max_udp_payload{1200}); } // MARK: Onion Request Router Options diff --git a/src/network/session_network.cpp b/src/network/session_network.cpp index f56e690be..5d70f1ed3 100644 --- a/src/network/session_network.cpp +++ b/src/network/session_network.cpp @@ -81,7 +81,7 @@ namespace { config::QuicTransport build_quic_transport_config(const config::Config& main_config) { return {main_config.quic_handshake_timeout, main_config.quic_keep_alive, - main_config.quic_disable_mtu_discovery}; + main_config.quic_max_udp_payload}; } config::DirectRouter build_direct_router_config( @@ -1349,7 +1349,8 @@ LIBSESSION_C_API session_network_config session_network_config_default() { .count(); config.quic_keep_alive_seconds = std::chrono::duration_cast(cpp_defaults.quic_keep_alive).count(); - config.quic_disable_mtu_discovery = cpp_defaults.quic_disable_mtu_discovery; + config.quic_disable_mtu_discovery = false; + config.quic_max_udp_payload = cpp_defaults.quic_max_udp_payload.value_or(0); return config; } @@ -1536,7 +1537,9 @@ LIBSESSION_C_API bool session_network_init( cpp_opts.emplace_back(opt::quic_keep_alive{ std::chrono::seconds{config->quic_keep_alive_seconds}}); - if (config->quic_disable_mtu_discovery) + if (config->quic_max_udp_payload > 0) + cpp_opts.emplace_back(opt::quic_max_udp_payload{config->quic_max_udp_payload}); + else if (config->quic_disable_mtu_discovery) cpp_opts.emplace_back(opt::quic_disable_mtu_discovery{}); break; diff --git a/src/network/transport/quic_transport.cpp b/src/network/transport/quic_transport.cpp index 2ccc40320..16c73c813 100644 --- a/src/network/transport/quic_transport.cpp +++ b/src/network/transport/quic_transport.cpp @@ -147,15 +147,12 @@ void QuicTransport::send_request(Request request, network_response_callback_t ca void QuicTransport::_recreate_endpoint() { // The optional must CONTAIN the option to have any effect: libquic's optional-taking // handle_ep_opt overload does nothing when the optional is empty, so a default-constructed - // std::optional{} silently leaves discovery enabled. - // - // Capping the payload at the QUIC minimum leaves path MTU discovery nothing to probe, which is - // how "disable" is expressed to libquic. + // std::optional{} silently leaves discovery uncapped. _endpoint = quic::Endpoint::endpoint( *_loop, quic::Address{}, - (_config.disable_mtu_discovery - ? std::make_optional(quic::opt::max_udp_payload::minimum()) + (_config.max_udp_payload + ? std::make_optional(*_config.max_udp_payload) : std::nullopt)); } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 4b93aa096..d06b99f31 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -41,6 +41,7 @@ set(LIB_SESSION_UTESTS_SOURCES ) if(ENABLE_NETWORKING) + list(APPEND LIB_SESSION_UTESTS_SOURCES test_network_config.cpp) list(APPEND LIB_SESSION_UTESTS_SOURCES test_network_swarm.cpp) list(APPEND LIB_SESSION_UTESTS_SOURCES test_onionreq.cpp) list(APPEND LIB_SESSION_UTESTS_SOURCES test_onion_request_router.cpp) diff --git a/tests/test_network_config.cpp b/tests/test_network_config.cpp new file mode 100644 index 000000000..dc60c9347 --- /dev/null +++ b/tests/test_network_config.cpp @@ -0,0 +1,32 @@ +#include + +#include +#include + +using namespace session::network; + +TEST_CASE("Network config: QUIC UDP payload cap", "[network][config][quic]") { + SECTION("unset by default") { + config::Config cfg{opt::quic_keep_alive{std::chrono::seconds{10}}}; + CHECK_FALSE(cfg.quic_max_udp_payload.has_value()); + } + SECTION("explicit cap") { + config::Config cfg{opt::quic_max_udp_payload{1400}}; + REQUIRE(cfg.quic_max_udp_payload.has_value()); + CHECK(*cfg.quic_max_udp_payload == 1400); + } + SECTION("disable_mtu_discovery is a 1200-byte cap") { + config::Config cfg{opt::quic_disable_mtu_discovery{}}; + REQUIRE(cfg.quic_max_udp_payload.has_value()); + CHECK(*cfg.quic_max_udp_payload == 1200); + } + SECTION("below the QUIC minimum is rejected") { + CHECK_THROWS_AS(config::Config{opt::quic_max_udp_payload{1199}}, std::invalid_argument); + CHECK_NOTHROW(config::Config{opt::quic_max_udp_payload{1200}}); + } + SECTION("C defaults leave it uncapped") { + auto c = session_network_config_default(); + CHECK(c.quic_max_udp_payload == 0); + CHECK_FALSE(c.quic_disable_mtu_discovery); + } +} diff --git a/tests/test_quic_transport.cpp b/tests/test_quic_transport.cpp index 52464e236..33fcde945 100644 --- a/tests/test_quic_transport.cpp +++ b/tests/test_quic_transport.cpp @@ -10,7 +10,7 @@ namespace { std::shared_ptr make_transport(std::shared_ptr loop) { return std::make_shared( config::QuicTransport{ - .handshake_timeout = 1s, .keep_alive = 10s, .disable_mtu_discovery = false}, + .handshake_timeout = 1s, .keep_alive = 10s, .max_udp_payload = std::nullopt}, std::move(loop)); } From 867ea7bbbc907c5d746b52809d14d6c6e3f6ee2f Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Tue, 6 Oct 2026 17:13:33 +1100 Subject: [PATCH 37/68] Fix the static bundle missing session-deps libraries Moving to session-deps dropped the explicit libsession_static_bundle() registrations, so libsession-util.a shipped without libquic, oxen-logging, fmt, spdlog, ngtcp2, gnutls, nettle/hogweed, gmp, idn2, unistring, tasn1 and libevent. The 1.9.3 iOS xcframework therefore failed to link (74 undefined symbols in Session iOS). Resolve the bundle's full static closure once all targets are linked, instead of relying on per-dependency registration. The iOS modulemap now autolinks iconv. libunistring needs it, and session-deps takes it from the system on Apple rather than bundling it as 1.9.2 did. --- CMakeLists.txt | 1 + cmake/AddStaticBundleLib.cmake | 59 ++++++++++++++++++++++++++++++++++ utils/ios.sh | 4 +++ 3 files changed, 64 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index a9389a577..de61a0169 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -167,6 +167,7 @@ if(STATIC_BUNDLE) include(combine_archives) + libsession_static_bundle_resolve() combine_archives(session-util libsession-static-bundle "${LIBSESSION_STATIC_BUNDLE_LIBS}") set(lib_folder lib) if(IOS) diff --git a/cmake/AddStaticBundleLib.cmake b/cmake/AddStaticBundleLib.cmake index 2e37c0b67..3c9690165 100644 --- a/cmake/AddStaticBundleLib.cmake +++ b/cmake/AddStaticBundleLib.cmake @@ -34,3 +34,62 @@ function(libsession_static_bundle) endif() endforeach() endfunction() + +function(_libsession_static_bundle_walk tgt) + if(tgt MATCHES "^\\$$") + set(tgt "${CMAKE_MATCH_1}") + endif() + if(NOT TARGET "${tgt}") + return() + endif() + get_target_property(aliased ${tgt} ALIASED_TARGET) + if(aliased) + set(tgt "${aliased}") + endif() + + get_property(visited GLOBAL PROPERTY _libsession_static_bundle_visited) + if("${tgt}" IN_LIST visited) + return() + endif() + set_property(GLOBAL APPEND PROPERTY _libsession_static_bundle_visited "${tgt}") + + get_target_property(tgt_type ${tgt} TYPE) + if(tgt_type STREQUAL STATIC_LIBRARY) + # The list can hold alias names (eg. protobuf::libprotobuf-lite), so compare what they resolve to + set(already_bundled FALSE) + foreach(bundled IN LISTS LIBSESSION_STATIC_BUNDLE_LIBS) + get_target_property(bundled_aliased ${bundled} ALIASED_TARGET) + if(bundled STREQUAL tgt OR bundled_aliased STREQUAL tgt) + set(already_bundled TRUE) + break() + endif() + endforeach() + if(NOT already_bundled) + message(STATUS "Adding ${tgt} to libsession-util bundled library list") + _libsession_static_bundle_append("${tgt}") + endif() + endif() + + # An imported target (which is what session-deps produces for each static dependency) carries + # its own dependencies only in INTERFACE_LINK_LIBRARIES; a target built here has them in + # LINK_LIBRARIES. + get_target_property(deps ${tgt} INTERFACE_LINK_LIBRARIES) + get_target_property(imported ${tgt} IMPORTED) + if(NOT tgt_type STREQUAL INTERFACE_LIBRARY AND NOT imported) + get_target_property(link_deps ${tgt} LINK_LIBRARIES) + list(APPEND deps ${link_deps}) + endif() + foreach(dep IN LISTS deps) + _libsession_static_bundle_walk("${dep}") + endforeach() +endfunction() + +# Adds every static library that the already-registered targets link against, transitively. Call +# once all targets have their links set up: libsession_static_bundle() runs as each library is +# created, before its target_link_libraries(), so on its own it never sees a library's dependencies. +function(libsession_static_bundle_resolve) + set_property(GLOBAL PROPERTY _libsession_static_bundle_visited "") + foreach(tgt IN LISTS LIBSESSION_STATIC_BUNDLE_LIBS) + _libsession_static_bundle_walk("${tgt}") + endforeach() +endfunction() diff --git a/utils/ios.sh b/utils/ios.sh index 623656695..01605b1d9 100755 --- a/utils/ios.sh +++ b/utils/ios.sh @@ -222,6 +222,10 @@ if [ "${SHOULD_CREATE_FRAMEWORK}" == "SHOULD_CREATE_FRAMEWORK" ]; then # The 'module.modulemap' is needed for XCode to be able to find the headers modmap="${OUTPUT_DIR}/module.modulemap" echo "module SessionUtil {" >"$modmap" + # libunistring (via gnutls -> libidn2) calls iconv, which session-deps takes from the system on + # Apple rather than bundling. An SPM binary target can't declare linker flags, so autolink it + # from the module instead. + echo " link \"iconv\"" >>"$modmap" echo " module capi {" >>"$modmap" for x in $(cd include && find session -name '*.h'); do echo " header \"$x\"" >>"$modmap" From 79750412f69ef000962c4a6a5b1e95ddd0ead163 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Tue, 6 Oct 2026 12:22:52 -0300 Subject: [PATCH 38/68] Bump session-deps for libunistring's iconv on Apple session-deps' libunistring recipe never passed on the -liconv that libunistring needs on Apple, where iconv is its own system dylib rather than part of libSystem. --- cmake/session-deps | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/session-deps b/cmake/session-deps index e809a6419..67d347c3a 160000 --- a/cmake/session-deps +++ b/cmake/session-deps @@ -1 +1 @@ -Subproject commit e809a64190494683935b63a8b8481178c1b1a8ab +Subproject commit 67d347c3ae0bddcffadf8b1231a772798eacd640 From 741df684f43fffa5ef4a08abd3341449a1f08d90 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Tue, 6 Oct 2026 12:49:12 -0300 Subject: [PATCH 39/68] Build the static bundle from one walk of the link closure The bundle's archive list came from libsession_static_bundle() calls scattered across src/, proto/ and external/, each of which also tried to recurse into the target's dependencies at a point (right after add_library) where it had none yet. When dependencies stopped being registered by hand with the move to session-deps, the bundle silently lost libquic, oxen-logging, fmt, spdlog, ngtcp2, gnutls, nettle and the rest, and the 1.9.3 iOS build failed to link. Replace all of that with a single walk, run once every target is linked, from the libraries we export: every static library in their link closure goes into the bundle, so it can no longer drift from what is actually linked. Everything else in the closure (system libraries, frameworks, imported non-static targets such as Threads::Threads) is returned separately, since it has to be supplied by whatever links the bundle. A generator expression or imported target the walk cannot see into is a configure error rather than a silent omission. --- CMakeLists.txt | 9 +- cmake/AddStaticBundleLib.cmake | 147 ++++++++++++++------------------- external/CMakeLists.txt | 4 - proto/CMakeLists.txt | 5 -- src/CMakeLists.txt | 3 - 5 files changed, 70 insertions(+), 98 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index de61a0169..550b8edf3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -167,8 +167,13 @@ if(STATIC_BUNDLE) include(combine_archives) - libsession_static_bundle_resolve() - combine_archives(session-util libsession-static-bundle "${LIBSESSION_STATIC_BUNDLE_LIBS}") + # Threads::Threads comes from find_package() calls in subdirectories, which make it visible only + # there; the bundle walk has to be able to see it. + find_package(Threads REQUIRED) + libsession_static_bundle_libs(bundle_archives bundle_system_libs ${libsession_export_targets}) + message(STATUS "Static bundle libsession-util.a combines: ${bundle_archives}") + message(STATUS "Static bundle libsession-util.a also needs: ${bundle_system_libs}") + combine_archives(session-util libsession-static-bundle ${bundle_archives}) set(lib_folder lib) if(IOS) set(lib_folder "${lib_folder}-${ARCH}") diff --git a/cmake/AddStaticBundleLib.cmake b/cmake/AddStaticBundleLib.cmake index 3c9690165..8f8aff11a 100644 --- a/cmake/AddStaticBundleLib.cmake +++ b/cmake/AddStaticBundleLib.cmake @@ -1,95 +1,74 @@ -set(LIBSESSION_STATIC_BUNDLE_LIBS "" CACHE INTERNAL "list of libs to go into the static bundle lib") - -function(_libsession_static_bundle_append tgt) - list(APPEND LIBSESSION_STATIC_BUNDLE_LIBS "${tgt}") - set(LIBSESSION_STATIC_BUNDLE_LIBS "${LIBSESSION_STATIC_BUNDLE_LIBS}" CACHE INTERNAL "") -endfunction() - # Call as: # -# libsession_static_bundle(target [target2 ...]) +# libsession_static_bundle_libs(ARCHIVES_VAR SYSTEM_VAR target [target2 ...]) # -# to append the given target(s) to the list of libraries that will be combined to make the static -# bundled libsession-util.a. -function(libsession_static_bundle) - foreach(tgt IN LISTS ARGN) - if(TARGET "${tgt}" AND NOT "${tgt}" IN_LIST LIBSESSION_STATIC_BUNDLE_LIBS) - get_target_property(tgt_type ${tgt} TYPE) - - if(tgt_type STREQUAL STATIC_LIBRARY) - message(STATUS "Adding ${tgt} to libsession-util bundled library list") - _libsession_static_bundle_append("${tgt}") - endif() - - if(tgt_type STREQUAL INTERFACE_LIBRARY) - get_target_property(tgt_link_deps ${tgt} INTERFACE_LINK_LIBRARIES) - else() - get_target_property(tgt_link_deps ${tgt} LINK_LIBRARIES) +# to walk the link closure of the given targets. ARCHIVES_VAR is set to every static library in +# it: the archives that combine into the STATIC_BUNDLE libsession-util.a. SYSTEM_VAR is set to +# everything else the closure links: system libraries such as iconv, Apple frameworks, linker flags +# and imported non-static targets such as Threads::Threads. None of those can go into an archive, +# so whatever links the bundle has to supply them. +# +# The closure is read from the targets' link properties, so this has to be called after every +# target_link_libraries() it depends on. +function(libsession_static_bundle_libs archives_out system_out) + set(pending ${ARGN}) + set(visited) + set(archives) + set(system) + while(NOT "${pending}" STREQUAL "") + list(POP_FRONT pending tgt) + if(tgt MATCHES "^\\$$") + set(tgt "${CMAKE_MATCH_1}") + endif() + if(NOT TARGET "${tgt}") + # Silently skipping either of these could drop a library from the bundle, which then + # only shows up when something links against it. A `::` name is an imported target + # created in some subdirectory without GLOBAL, which we cannot see (let alone look + # inside) from here: find_package() it before calling this. + if(tgt MATCHES "\\$<") + message(FATAL_ERROR "Static bundle: don't know how to follow link item ${tgt}") endif() - - if(tgt_link_deps) - libsession_static_bundle(${tgt_link_deps}) + if(tgt MATCHES "::") + message(FATAL_ERROR "Static bundle: imported target ${tgt} is not visible here") endif() + list(APPEND system "${tgt}") + continue() endif() - endforeach() -endfunction() - -function(_libsession_static_bundle_walk tgt) - if(tgt MATCHES "^\\$$") - set(tgt "${CMAKE_MATCH_1}") - endif() - if(NOT TARGET "${tgt}") - return() - endif() - get_target_property(aliased ${tgt} ALIASED_TARGET) - if(aliased) - set(tgt "${aliased}") - endif() - - get_property(visited GLOBAL PROPERTY _libsession_static_bundle_visited) - if("${tgt}" IN_LIST visited) - return() - endif() - set_property(GLOBAL APPEND PROPERTY _libsession_static_bundle_visited "${tgt}") - - get_target_property(tgt_type ${tgt} TYPE) - if(tgt_type STREQUAL STATIC_LIBRARY) - # The list can hold alias names (eg. protobuf::libprotobuf-lite), so compare what they resolve to - set(already_bundled FALSE) - foreach(bundled IN LISTS LIBSESSION_STATIC_BUNDLE_LIBS) - get_target_property(bundled_aliased ${bundled} ALIASED_TARGET) - if(bundled STREQUAL tgt OR bundled_aliased STREQUAL tgt) - set(already_bundled TRUE) - break() - endif() - endforeach() - if(NOT already_bundled) - message(STATUS "Adding ${tgt} to libsession-util bundled library list") - _libsession_static_bundle_append("${tgt}") + get_target_property(aliased ${tgt} ALIASED_TARGET) + if(aliased) + set(tgt "${aliased}") endif() - endif() + if(tgt IN_LIST visited) + continue() + endif() + list(APPEND visited "${tgt}") - # An imported target (which is what session-deps produces for each static dependency) carries - # its own dependencies only in INTERFACE_LINK_LIBRARIES; a target built here has them in - # LINK_LIBRARIES. - get_target_property(deps ${tgt} INTERFACE_LINK_LIBRARIES) - get_target_property(imported ${tgt} IMPORTED) - if(NOT tgt_type STREQUAL INTERFACE_LIBRARY AND NOT imported) - get_target_property(link_deps ${tgt} LINK_LIBRARIES) - list(APPEND deps ${link_deps}) - endif() - foreach(dep IN LISTS deps) - _libsession_static_bundle_walk("${dep}") - endforeach() -endfunction() + get_target_property(type ${tgt} TYPE) + get_target_property(imported ${tgt} IMPORTED) + if(type STREQUAL STATIC_LIBRARY) + list(APPEND archives "${tgt}") + elseif(imported) + # Something the system provides (Threads::Threads). Linking it by name brings + # everything it carries, including link options, which this walk does not read. + list(APPEND system "${tgt}") + continue() + endif() -# Adds every static library that the already-registered targets link against, transitively. Call -# once all targets have their links set up: libsession_static_bundle() runs as each library is -# created, before its target_link_libraries(), so on its own it never sees a library's dependencies. -function(libsession_static_bundle_resolve) - set_property(GLOBAL PROPERTY _libsession_static_bundle_visited "") - foreach(tgt IN LISTS LIBSESSION_STATIC_BUNDLE_LIBS) - _libsession_static_bundle_walk("${tgt}") - endforeach() + # An imported target (which is what session-deps produces for each static dependency) + # carries its dependencies only in INTERFACE_LINK_LIBRARIES; one built here also has its + # private ones in LINK_LIBRARIES. + get_target_property(deps ${tgt} INTERFACE_LINK_LIBRARIES) + if(NOT type STREQUAL INTERFACE_LIBRARY AND NOT imported) + get_target_property(link_deps ${tgt} LINK_LIBRARIES) + list(APPEND deps ${link_deps}) + endif() + # ::@(dir) ... ::@ are cmake's own markers around items that target_link_libraries() added + # from another directory, not link items themselves. + list(FILTER deps EXCLUDE REGEX "-NOTFOUND$|^::@") + list(APPEND pending ${deps}) + endwhile() + list(REMOVE_DUPLICATES system) + set(${archives_out} "${archives}" PARENT_SCOPE) + set(${system_out} "${system}" PARENT_SCOPE) endfunction() diff --git a/external/CMakeLists.txt b/external/CMakeLists.txt index 9753a5410..932e2e1c5 100644 --- a/external/CMakeLists.txt +++ b/external/CMakeLists.txt @@ -24,7 +24,6 @@ endfunction() # Stock libsodium, not the libsodium-internal fork: the one thing the fork exposed that we used was # the field arithmetic behind xed25519::pubkey(), which src/xed25519-tweetnacl.cpp now supplies. session_dep(libsodium 1.0.21) -libsession_static_bundle(sessiondep::libsodium) # Needed even without networking: oxenc is part of the public interface of `common`. if(NOT TARGET oxenc::oxenc) @@ -40,7 +39,6 @@ if(ENABLE_NETWORKING AND ENABLE_NETWORKING_SROUTER) set(SROUTER_JEMALLOC OFF CACHE BOOL "") add_static_subdirectory(session-router EXCLUDE_FROM_ALL) - libsession_static_bundle(session-router::core) endif() # session-router provides oxen::quic when it is built (above); otherwise pull in oxen-libquic alone. @@ -80,7 +78,6 @@ sessiondep_or_submodule(protobuf-lite 3.21 protobuf protobuf::libprotobuf-lite) # configs get deduplicated at the swarm. set(BUILD_STATIC_libzstd ON CACHE BOOL "" FORCE) session_dep(libzstd 1.5) -libsession_static_bundle(sessiondep::libzstd) if(NOT TARGET nlohmann_json::nlohmann_json) set(JSON_BuildTests OFF CACHE INTERNAL "") @@ -89,7 +86,6 @@ if(NOT TARGET nlohmann_json::nlohmann_json) endif() session_dep(simdutf 7) -libsession_static_bundle(sessiondep::simdutf) # We need Howard Hinnant's header-only date library for now because the STL implementation of # std::chrono::parse() is spotty or broken on: diff --git a/proto/CMakeLists.txt b/proto/CMakeLists.txt index a7ab778af..5f13e7d27 100644 --- a/proto/CMakeLists.txt +++ b/proto/CMakeLists.txt @@ -1,7 +1,4 @@ -libsession_static_bundle(protobuf::libprotobuf-lite) - - add_library(protos SessionProtos.pb.cc WebSocketResources.pb.cc) @@ -20,8 +17,6 @@ else() target_compile_options(protos PUBLIC -Wno-error=unused-parameter) endif() -libsession_static_bundle(protos) - add_library(libsession::protos ALIAS protos) list(APPEND libsession_export_targets protos) set(libsession_export_targets "${libsession_export_targets}" PARENT_SCOPE) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 00821b6da..ffd1702b0 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -35,8 +35,6 @@ macro(add_libsession_util_library name) OUTPUT_NAME session-${name} SOVERSION ${LIBSESSION_LIBVERSION}) - libsession_static_bundle(${name}) - list(APPEND export_targets ${name}) endmacro() @@ -205,7 +203,6 @@ else() endif() endif() add_library(version STATIC version.c) -libsession_static_bundle(version) target_include_directories(version PRIVATE ../include) target_link_libraries(common INTERFACE version) From 6824566e843997ae8101fae1452e2ec85f4e696c Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Tue, 6 Oct 2026 12:49:22 -0300 Subject: [PATCH 40/68] Make static-bundle-test link the bundle alone, and build it in CI static-bundle-test linked quic and oxenc next to libsession-util.a and only called config code, so it could not notice libquic or anything the network needs going missing from the bundle -- and no CI job built it anyway: the debian jobs build shared libraries, and the static jobs ran static-bundle.sh with WITH_TESTS=OFF and built only session-util. It now links the bundle and nothing but the system requirements the bundle walk reports, calls into the network as well as config, and is defined alongside the bundle rather than under tests/ so it does not need WITH_TESTS. static-bundle.sh, which every static job (Linux, Windows, macOS, iOS) goes through, builds it after the bundle, so a dependency missing from the bundle now fails the build that produces it. --- CMakeLists.txt | 19 +++++++++++++++++++ tests/CMakeLists.txt | 7 ------- tests/static_bundle.cpp | 11 ++++++++++- utils/static-bundle.sh | 4 +++- 4 files changed, 32 insertions(+), 9 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 550b8edf3..6afb257ff 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -174,6 +174,25 @@ if(STATIC_BUNDLE) message(STATUS "Static bundle libsession-util.a combines: ${bundle_archives}") message(STATUS "Static bundle libsession-util.a also needs: ${bundle_system_libs}") combine_archives(session-util libsession-static-bundle ${bundle_archives}) + + # Links the bundle and only what the walk says it needs from the system, so that a library + # missing from the bundle fails here rather than in whatever consumes it. Headers come from our + # targets' usage requirements, without linking them. + add_executable(static-bundle-test tests/static_bundle.cpp) + if(ENABLE_NETWORKING) + set(bundle_header_target network) + else() + set(bundle_header_target config) + target_compile_definitions(static-bundle-test PRIVATE DISABLE_NETWORKING) + endif() + target_include_directories(static-bundle-test PRIVATE + $) + target_compile_definitions(static-bundle-test PRIVATE + $) + target_link_libraries(static-bundle-test PRIVATE + "${CMAKE_CURRENT_BINARY_DIR}/libsession-util.a" ${bundle_system_libs}) + add_dependencies(static-bundle-test session-util) + set(lib_folder lib) if(IOS) set(lib_folder "${lib_folder}-${ARCH}") diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index d06b99f31..ae479eca3 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -91,10 +91,3 @@ endif() add_executable(swarm-auth-test EXCLUDE_FROM_ALL swarm-auth-test.cpp) target_link_libraries(swarm-auth-test PRIVATE config) - -if(STATIC_BUNDLE) - add_executable(static-bundle-test static_bundle.cpp) - target_include_directories(static-bundle-test PUBLIC ../include) - target_link_libraries(static-bundle-test PRIVATE "${PROJECT_BINARY_DIR}/libsession-util.a" oxenc::oxenc quic) - add_dependencies(static-bundle-test session-util) -endif() diff --git a/tests/static_bundle.cpp b/tests/static_bundle.cpp index a760a178d..7ba9f91a3 100644 --- a/tests/static_bundle.cpp +++ b/tests/static_bundle.cpp @@ -1,12 +1,21 @@ // This file isn't designed to do anything useful, but just to test that we can compile and link -// against the combined static bundle (when using cmake ... -DSTATIC_BUILD=ON) +// against the combined static bundle (when using cmake ... -DSTATIC_BUNDLE=ON) with nothing else. +// The calls are there to make the linker pull in the code that needs the bundle's dependencies: +// config for libsodium/protobuf/zstd, and the network for libquic, gnutls, ngtcp2 and libevent. #include #include +#ifndef DISABLE_NETWORKING +#include +#endif int main() { if (std::mt19937_64{}() == 123) { auto& k = *reinterpret_cast(12345); k.encrypt_message(std::span{}); +#ifndef DISABLE_NETWORKING + auto& n = *reinterpret_cast(12345); + n.close_connections(); +#endif } } diff --git a/utils/static-bundle.sh b/utils/static-bundle.sh index 7f6c88385..c0fd64473 100755 --- a/utils/static-bundle.sh +++ b/utils/static-bundle.sh @@ -71,7 +71,9 @@ cmake -G 'Unix Makefiles' \ "$@" \ "$projdir" -make -j${JOBS:-$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 1)} VERBOSE=1 session-util +# static-bundle-test links against nothing but the bundle and its declared system libraries, so +# building it is what catches a dependency missing from the bundle. +make -j${JOBS:-$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 1)} VERBOSE=1 session-util static-bundle-test if [ -z "$archive" ]; then exit 0 From 6c0c3307b18c1854388483e417485af6889c0c5b Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Tue, 6 Oct 2026 12:49:26 -0300 Subject: [PATCH 41/68] Bump version to 1.9.4 --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 6afb257ff..31aca0caa 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -17,7 +17,7 @@ if(CCACHE_PROGRAM) endif() project(libsession-util - VERSION 1.9.3 + VERSION 1.9.4 DESCRIPTION "Session client utility library" LANGUAGES ${LANGS}) From 07b533e2d0f405f5c839f2f749be289ee20c61fc Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Tue, 6 Oct 2026 20:11:47 -0300 Subject: [PATCH 42/68] Link nlohmann-json publicly to network service_node.hpp, session_network.hpp and session_network_types.hpp all include , so it is part of the network target's public interface, not a private detail. It only went unnoticed because testAll adds nlohmann itself, and most build machines have a system copy on the default include path; static-bundle-test, which takes its headers purely from network's usage requirements, failed to compile on every static CI job (Android, iOS, macOS, Windows). --- src/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index ffd1702b0..96a5b9880 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -140,8 +140,8 @@ if(ENABLE_NETWORKING) PUBLIC crypto oxen::quic - PRIVATE nlohmann_json::nlohmann_json + PRIVATE sessiondep::libsodium sessiondep::nettle date::date From 74585a0b9874e33752b4395fb01683bebf275d81 Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Wed, 7 Oct 2026 10:54:46 +1100 Subject: [PATCH 43/68] Don't dereference a connection that is already gone when a response arrives --- src/network/transport/quic_transport.cpp | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/network/transport/quic_transport.cpp b/src/network/transport/quic_transport.cpp index 16c73c813..d4bae5023 100644 --- a/src/network/transport/quic_transport.cpp +++ b/src/network/transport/quic_transport.cpp @@ -510,13 +510,21 @@ void QuicTransport::_send_on_connection( // Since the request completed it's round-trip if it isn't the "reserverd" stream // (not used for general requests) then we can either add it back to the pool, or // close it if there are more that the active stream price limit + // + // The connection can already be gone: libquic fires a request's callback from its + // destructor when the connection closes, and the connection's streams go with it. + // Then there is nothing to return to the pool or close, and any ids pooled for it + // are dead too. if (stream_id != 0 && _endpoint) { - auto conn = _endpoint->get_conn(conn_id); - - if (conn && conn->get_streams_available() <= ACTIVE_STREAM_PRUNE_LIMIT) - _available_stream_ids[conn_id].insert(stream_id); - else if (auto stream = conn->get_stream(stream_id)) - stream->close(); + if (auto conn = _endpoint->get_conn(conn_id)) { + if (conn->get_streams_available() <= ACTIVE_STREAM_PRUNE_LIMIT) + _available_stream_ids[conn_id].insert(stream_id); + else if ( + auto stream = + conn->get_stream(stream_id)) + stream->close(); + } else + _available_stream_ids.erase(conn_id); } if (resp.timed_out) { From d72c8bca952e0b91f511e16be29353054a31a5a3 Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Wed, 7 Oct 2026 10:55:02 +1100 Subject: [PATCH 44/68] Clear only the closed connection's state when a connection fails --- .../network/transport/quic_transport.hpp | 3 ++- src/network/transport/quic_transport.cpp | 23 +++++++++++++++---- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/include/session/network/transport/quic_transport.hpp b/include/session/network/transport/quic_transport.hpp index d0281f5ce..990a35294 100644 --- a/include/session/network/transport/quic_transport.hpp +++ b/include/session/network/transport/quic_transport.hpp @@ -93,7 +93,8 @@ class QuicTransport : public ITransport, public std::enable_shared_from_this error_code, - std::optional custom_error); + std::optional custom_error, + std::optional conn_id = std::nullopt); }; } // namespace session::network \ No newline at end of file diff --git a/src/network/transport/quic_transport.cpp b/src/network/transport/quic_transport.cpp index d4bae5023..fa3c8bf56 100644 --- a/src/network/transport/quic_transport.cpp +++ b/src/network/transport/quic_transport.cpp @@ -371,10 +371,14 @@ void QuicTransport::_establish_connection( } }, [weak_self = weak_from_this(), address_pubkey_hex, initiating_req_id]( - oxen::quic::Connection&, uint64_t error_code) { + oxen::quic::Connection& conn, uint64_t error_code) { if (auto self = weak_self.lock()) self->_fail_connection( - address_pubkey_hex, initiating_req_id, error_code, std::nullopt); + address_pubkey_hex, + initiating_req_id, + error_code, + std::nullopt, + conn.reference_id()); }); } catch (const std::exception& e) { _fail_connection(address_pubkey_hex, initiating_req_id, std::nullopt, e.what()); @@ -570,7 +574,8 @@ void QuicTransport::_fail_connection( const std::string& address_pubkey_hex, const std::string& initiating_req_id, std::optional error_code, - std::optional custom_error) { + std::optional custom_error, + std::optional conn_id) { if (error_code == NGTCP2_NO_ERROR) log::info( cat, @@ -613,8 +618,16 @@ void QuicTransport::_fail_connection( address_pubkey_hex, custom_error.value_or("Unknown error")); - // Clear the connection and stream ids - if (auto id = _active_connection_ids.extract(address_pubkey_hex)) + // Clear the connection and stream ids. When the closed connection is known, only its own + // state goes: a newer connection to the same node can be established before an old one's close + // arrives, and clearing by pubkey alone would drop the new connection and orphan the old one's + // stream ids. + if (conn_id) { + _available_stream_ids.erase(*conn_id); + if (auto it = _active_connection_ids.find(address_pubkey_hex); + it != _active_connection_ids.end() && it->second == *conn_id) + _active_connection_ids.erase(it); + } else if (auto id = _active_connection_ids.extract(address_pubkey_hex)) _available_stream_ids.erase(id.mapped()); // Process any waiting verification requests From 0ce0972ecdb1ea11653150bc111828afb70097f6 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Tue, 6 Oct 2026 21:34:50 -0300 Subject: [PATCH 45/68] Say accurately when a response can arrive after its connection is gone On a normal close, libquic fails a stream's pending requests from close_all_streams() while the connection still exists; it only fails them from ~sent_request when a stream outlives its connection. --- src/network/transport/quic_transport.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/network/transport/quic_transport.cpp b/src/network/transport/quic_transport.cpp index fa3c8bf56..d63d3c724 100644 --- a/src/network/transport/quic_transport.cpp +++ b/src/network/transport/quic_transport.cpp @@ -515,10 +515,9 @@ void QuicTransport::_send_on_connection( // (not used for general requests) then we can either add it back to the pool, or // close it if there are more that the active stream price limit // - // The connection can already be gone: libquic fires a request's callback from its - // destructor when the connection closes, and the connection's streams go with it. - // Then there is nothing to return to the pool or close, and any ids pooled for it - // are dead too. + // The connection can be gone by the time this runs, e.g. if the stream outlived it + // (libquic then fails the request from ~sent_request). Then there is nothing to + // return to the pool or close, and any ids pooled for it are dead too. if (stream_id != 0 && _endpoint) { if (auto conn = _endpoint->get_conn(conn_id)) { if (conn->get_streams_available() <= ACTIVE_STREAM_PRUNE_LIMIT) From dac149cd5e21fab9c693c042b0d8d00c0b7677a3 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Fri, 9 Oct 2026 14:13:05 -0300 Subject: [PATCH 46/68] Fix missing direct linking to libzstd Static builds were getting this via implicit deps, but shared builds were failing to pick up libzstd headers. --- src/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 96a5b9880..2497bc19b 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -100,6 +100,7 @@ target_link_libraries(crypto util PRIVATE sessiondep::libsodium + sessiondep::libzstd nlohmann_json::nlohmann_json libsession::protos ) From 3721688e9bc5efdc760bb01af667ea535436cfe8 Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Wed, 4 Nov 2026 09:41:07 +1100 Subject: [PATCH 47/68] Add opt::quic_congestion_control Lets a client choose BBR, cubic or Reno for its QUIC connections, through the C++ options, Config, the C API (session_network_config.quic_congestion_control) and QuicTransport's connect(). Unset leaves libquic's default. libquic 1.13 changed that default from BBR to cubic (libquic e285bf4), and Session iOS wants to stay on BBR. Needs libquic 1.13 or later, so it won't build against dev's libquic v1.11.0 pin until the session-router bump for libquic 1.14.0 lands. --- include/session/network/network_config.hpp | 2 ++ include/session/network/network_opt.hpp | 25 +++++++++++++++++++ include/session/network/session_network.h | 8 ++++++ .../network/transport/quic_transport.hpp | 1 + src/network/network_config.cpp | 18 +++++++++++++ src/network/session_network.cpp | 17 ++++++++++++- src/network/transport/quic_transport.cpp | 17 +++++++++++++ tests/test_network_config.cpp | 16 ++++++++++++ tests/test_quic_transport.cpp | 5 +++- 9 files changed, 107 insertions(+), 2 deletions(-) diff --git a/include/session/network/network_config.hpp b/include/session/network/network_config.hpp index c1b0bcf65..83ff2188e 100644 --- a/include/session/network/network_config.hpp +++ b/include/session/network/network_config.hpp @@ -65,6 +65,7 @@ struct Config { std::chrono::milliseconds quic_handshake_timeout{3s}; std::chrono::seconds quic_keep_alive{10s}; std::optional quic_max_udp_payload; + std::optional quic_congestion_control; template requires(sizeof...(Opt) > 0 && (opt::is_option> && ...)) @@ -117,6 +118,7 @@ struct Config { void handle_config_opt(opt::quic_keep_alive qka); void handle_config_opt(opt::quic_max_udp_payload qmup); void handle_config_opt(opt::quic_disable_mtu_discovery qdmd); + void handle_config_opt(opt::quic_congestion_control qcc); // Onion request router options void handle_config_opt(opt::onionreq_path_strike_threshold pst); diff --git a/include/session/network/network_opt.hpp b/include/session/network/network_opt.hpp index 10ee3170b..a819060a8 100644 --- a/include/session/network/network_opt.hpp +++ b/include/session/network/network_opt.hpp @@ -387,6 +387,30 @@ namespace opt { /// probe. struct quic_disable_mtu_discovery {}; + /// Can be used to choose the congestion control algorithm Quic connections use for what they + /// send; without it libquic's default is used. BBR keeps its sending rate through loss that + /// isn't caused by congestion, which suits jittery mobile networks, while cubic and reno back + /// off on any loss. + struct quic_congestion_control { + enum class Algorithm { + bbr, + cubic, + reno, + }; + + Algorithm algorithm; + + private: + quic_congestion_control(Algorithm a) : algorithm{a} {} + + public: + quic_congestion_control() = delete; + + static quic_congestion_control bbr() { return quic_congestion_control(Algorithm::bbr); } + static quic_congestion_control cubic() { return quic_congestion_control(Algorithm::cubic); } + static quic_congestion_control reno() { return quic_congestion_control(Algorithm::reno); } + }; + // MARK: Onion Request Router Options /// Can be used to override the default (3) number of times a path can receive an error before @@ -477,6 +501,7 @@ namespace opt { quic_keep_alive, quic_max_udp_payload, quic_disable_mtu_discovery, + quic_congestion_control, // Onion request router options onionreq_path_strike_threshold, diff --git a/include/session/network/session_network.h b/include/session/network/session_network.h index dff3a5025..40b3e76bc 100644 --- a/include/session/network/session_network.h +++ b/include/session/network/session_network.h @@ -34,6 +34,13 @@ typedef enum { SESSION_NETWORK_TRANSPORT_QUIC = 0, } SESSION_NETWORK_TRANSPORT; +typedef enum { + SESSION_NETWORK_QUIC_CONGESTION_CONTROL_DEFAULT = 0, // libquic's default + SESSION_NETWORK_QUIC_CONGESTION_CONTROL_BBR = 1, + SESSION_NETWORK_QUIC_CONGESTION_CONTROL_CUBIC = 2, + SESSION_NETWORK_QUIC_CONGESTION_CONTROL_RENO = 3, +} SESSION_NETWORK_QUIC_CONGESTION_CONTROL; + typedef void (*session_network_request_t)( const char* url, const char* body_data, @@ -98,6 +105,7 @@ typedef struct session_network_config { /// Maximum QUIC UDP payload size; 0 for no cap. Must otherwise be at least 1200. Takes /// precedence over quic_disable_mtu_discovery when non-zero. size_t quic_max_udp_payload; + SESSION_NETWORK_QUIC_CONGESTION_CONTROL quic_congestion_control; } session_network_config; diff --git a/include/session/network/transport/quic_transport.hpp b/include/session/network/transport/quic_transport.hpp index 990a35294..14ff4f36e 100644 --- a/include/session/network/transport/quic_transport.hpp +++ b/include/session/network/transport/quic_transport.hpp @@ -25,6 +25,7 @@ namespace config { std::chrono::seconds keep_alive; std::optional max_udp_payload; + std::optional congestion_control; }; } // namespace config diff --git a/src/network/network_config.cpp b/src/network/network_config.cpp index 392460c01..b01a1260b 100644 --- a/src/network/network_config.cpp +++ b/src/network/network_config.cpp @@ -249,6 +249,24 @@ void Config::handle_config_opt(opt::quic_disable_mtu_discovery) { handle_config_opt(opt::quic_max_udp_payload{1200}); } +void Config::handle_config_opt(opt::quic_congestion_control qcc) { + quic_congestion_control = qcc.algorithm; + + switch (qcc.algorithm) { + case opt::quic_congestion_control::Algorithm::bbr: + log::debug(cat, "Network config quic congestion control set to BBR"); + break; + + case opt::quic_congestion_control::Algorithm::cubic: + log::debug(cat, "Network config quic congestion control set to cubic"); + break; + + case opt::quic_congestion_control::Algorithm::reno: + log::debug(cat, "Network config quic congestion control set to Reno"); + break; + } +} + // MARK: Onion Request Router Options void Config::handle_config_opt(opt::onionreq_path_strike_threshold pst) { diff --git a/src/network/session_network.cpp b/src/network/session_network.cpp index 5d70f1ed3..d4e770517 100644 --- a/src/network/session_network.cpp +++ b/src/network/session_network.cpp @@ -81,7 +81,8 @@ namespace { config::QuicTransport build_quic_transport_config(const config::Config& main_config) { return {main_config.quic_handshake_timeout, main_config.quic_keep_alive, - main_config.quic_max_udp_payload}; + main_config.quic_max_udp_payload, + main_config.quic_congestion_control}; } config::DirectRouter build_direct_router_config( @@ -1351,6 +1352,7 @@ LIBSESSION_C_API session_network_config session_network_config_default() { std::chrono::duration_cast(cpp_defaults.quic_keep_alive).count(); config.quic_disable_mtu_discovery = false; config.quic_max_udp_payload = cpp_defaults.quic_max_udp_payload.value_or(0); + config.quic_congestion_control = SESSION_NETWORK_QUIC_CONGESTION_CONTROL_DEFAULT; return config; } @@ -1542,6 +1544,19 @@ LIBSESSION_C_API bool session_network_init( else if (config->quic_disable_mtu_discovery) cpp_opts.emplace_back(opt::quic_disable_mtu_discovery{}); + switch (config->quic_congestion_control) { + case SESSION_NETWORK_QUIC_CONGESTION_CONTROL_DEFAULT: break; + case SESSION_NETWORK_QUIC_CONGESTION_CONTROL_BBR: + cpp_opts.emplace_back(opt::quic_congestion_control::bbr()); + break; + case SESSION_NETWORK_QUIC_CONGESTION_CONTROL_CUBIC: + cpp_opts.emplace_back(opt::quic_congestion_control::cubic()); + break; + case SESSION_NETWORK_QUIC_CONGESTION_CONTROL_RENO: + cpp_opts.emplace_back(opt::quic_congestion_control::reno()); + break; + } + break; } diff --git a/src/network/transport/quic_transport.cpp b/src/network/transport/quic_transport.cpp index d63d3c724..638961316 100644 --- a/src/network/transport/quic_transport.cpp +++ b/src/network/transport/quic_transport.cpp @@ -29,6 +29,22 @@ namespace { } return false; // Shouldn't happen } + + std::optional to_quic( + std::optional algorithm) { + if (!algorithm) + return std::nullopt; + + switch (*algorithm) { + case opt::quic_congestion_control::Algorithm::bbr: + return quic::opt::congestion_control::bbr; + case opt::quic_congestion_control::Algorithm::cubic: + return quic::opt::congestion_control::cubic; + case opt::quic_congestion_control::Algorithm::reno: + return quic::opt::congestion_control::reno; + } + return std::nullopt; // Shouldn't happen + } } // namespace constexpr auto ALPN = "oxenstorage"sv; @@ -325,6 +341,7 @@ void QuicTransport::_establish_connection( oxen::quic::opt::outbound_alpn(ALPN), oxen::quic::opt::handshake_timeout{_config.handshake_timeout}, oxen::quic::opt::keep_alive{_config.keep_alive}, + to_quic(_config.congestion_control), [weak_self = weak_from_this(), this, address_pubkey_hex, initiating_req_id]( oxen::quic::Connection& conn) { auto self = weak_self.lock(); diff --git a/tests/test_network_config.cpp b/tests/test_network_config.cpp index dc60c9347..755619bcc 100644 --- a/tests/test_network_config.cpp +++ b/tests/test_network_config.cpp @@ -30,3 +30,19 @@ TEST_CASE("Network config: QUIC UDP payload cap", "[network][config][quic]") { CHECK_FALSE(c.quic_disable_mtu_discovery); } } + +TEST_CASE("Network config: QUIC congestion control", "[network][config][quic]") { + SECTION("unset by default") { + config::Config cfg{opt::quic_keep_alive{std::chrono::seconds{10}}}; + CHECK_FALSE(cfg.quic_congestion_control.has_value()); + } + SECTION("explicit algorithm") { + config::Config cfg{opt::quic_congestion_control::bbr()}; + REQUIRE(cfg.quic_congestion_control.has_value()); + CHECK(*cfg.quic_congestion_control == opt::quic_congestion_control::Algorithm::bbr); + } + SECTION("C defaults leave libquic's default") { + auto c = session_network_config_default(); + CHECK(c.quic_congestion_control == SESSION_NETWORK_QUIC_CONGESTION_CONTROL_DEFAULT); + } +} diff --git a/tests/test_quic_transport.cpp b/tests/test_quic_transport.cpp index 33fcde945..f1dfb0d32 100644 --- a/tests/test_quic_transport.cpp +++ b/tests/test_quic_transport.cpp @@ -10,7 +10,10 @@ namespace { std::shared_ptr make_transport(std::shared_ptr loop) { return std::make_shared( config::QuicTransport{ - .handshake_timeout = 1s, .keep_alive = 10s, .max_udp_payload = std::nullopt}, + .handshake_timeout = 1s, + .keep_alive = 10s, + .max_udp_payload = std::nullopt, + .congestion_control = std::nullopt}, std::move(loop)); } From 3cf6c45326311e1490bac4ca1d094d630fe6ca5f Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Wed, 4 Nov 2026 16:29:18 +1100 Subject: [PATCH 48/68] Use libquic's congestion_control enum for opt::quic_congestion_control network_opt.hpp already has libquic's headers, so the option is now an alias for oxen::quic::opt::congestion_control instead of a wrapper struct with its own enum, and QuicTransport passes the configured value to connect() without converting it. The header includes itself rather than relying on , which libquic 1.14 removes. --- include/session/network/network_config.hpp | 2 +- include/session/network/network_opt.hpp | 21 ++----------------- .../network/transport/quic_transport.hpp | 2 +- src/network/network_config.cpp | 10 ++++----- src/network/session_network.cpp | 6 +++--- src/network/transport/quic_transport.cpp | 18 +--------------- tests/test_network_config.cpp | 4 ++-- 7 files changed, 15 insertions(+), 48 deletions(-) diff --git a/include/session/network/network_config.hpp b/include/session/network/network_config.hpp index 83ff2188e..24a31ded9 100644 --- a/include/session/network/network_config.hpp +++ b/include/session/network/network_config.hpp @@ -65,7 +65,7 @@ struct Config { std::chrono::milliseconds quic_handshake_timeout{3s}; std::chrono::seconds quic_keep_alive{10s}; std::optional quic_max_udp_payload; - std::optional quic_congestion_control; + std::optional quic_congestion_control; template requires(sizeof...(Opt) > 0 && (opt::is_option> && ...)) diff --git a/include/session/network/network_opt.hpp b/include/session/network/network_opt.hpp index a819060a8..83d0beacf 100644 --- a/include/session/network/network_opt.hpp +++ b/include/session/network/network_opt.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include @@ -391,25 +392,7 @@ namespace opt { /// send; without it libquic's default is used. BBR keeps its sending rate through loss that /// isn't caused by congestion, which suits jittery mobile networks, while cubic and reno back /// off on any loss. - struct quic_congestion_control { - enum class Algorithm { - bbr, - cubic, - reno, - }; - - Algorithm algorithm; - - private: - quic_congestion_control(Algorithm a) : algorithm{a} {} - - public: - quic_congestion_control() = delete; - - static quic_congestion_control bbr() { return quic_congestion_control(Algorithm::bbr); } - static quic_congestion_control cubic() { return quic_congestion_control(Algorithm::cubic); } - static quic_congestion_control reno() { return quic_congestion_control(Algorithm::reno); } - }; + using quic_congestion_control = oxen::quic::opt::congestion_control; // MARK: Onion Request Router Options diff --git a/include/session/network/transport/quic_transport.hpp b/include/session/network/transport/quic_transport.hpp index 14ff4f36e..3fc683d2f 100644 --- a/include/session/network/transport/quic_transport.hpp +++ b/include/session/network/transport/quic_transport.hpp @@ -25,7 +25,7 @@ namespace config { std::chrono::seconds keep_alive; std::optional max_udp_payload; - std::optional congestion_control; + std::optional congestion_control; }; } // namespace config diff --git a/src/network/network_config.cpp b/src/network/network_config.cpp index b01a1260b..4103f1abd 100644 --- a/src/network/network_config.cpp +++ b/src/network/network_config.cpp @@ -250,18 +250,18 @@ void Config::handle_config_opt(opt::quic_disable_mtu_discovery) { } void Config::handle_config_opt(opt::quic_congestion_control qcc) { - quic_congestion_control = qcc.algorithm; + quic_congestion_control = qcc; - switch (qcc.algorithm) { - case opt::quic_congestion_control::Algorithm::bbr: + switch (qcc) { + case opt::quic_congestion_control::bbr: log::debug(cat, "Network config quic congestion control set to BBR"); break; - case opt::quic_congestion_control::Algorithm::cubic: + case opt::quic_congestion_control::cubic: log::debug(cat, "Network config quic congestion control set to cubic"); break; - case opt::quic_congestion_control::Algorithm::reno: + case opt::quic_congestion_control::reno: log::debug(cat, "Network config quic congestion control set to Reno"); break; } diff --git a/src/network/session_network.cpp b/src/network/session_network.cpp index d4e770517..9d605de80 100644 --- a/src/network/session_network.cpp +++ b/src/network/session_network.cpp @@ -1547,13 +1547,13 @@ LIBSESSION_C_API bool session_network_init( switch (config->quic_congestion_control) { case SESSION_NETWORK_QUIC_CONGESTION_CONTROL_DEFAULT: break; case SESSION_NETWORK_QUIC_CONGESTION_CONTROL_BBR: - cpp_opts.emplace_back(opt::quic_congestion_control::bbr()); + cpp_opts.emplace_back(opt::quic_congestion_control::bbr); break; case SESSION_NETWORK_QUIC_CONGESTION_CONTROL_CUBIC: - cpp_opts.emplace_back(opt::quic_congestion_control::cubic()); + cpp_opts.emplace_back(opt::quic_congestion_control::cubic); break; case SESSION_NETWORK_QUIC_CONGESTION_CONTROL_RENO: - cpp_opts.emplace_back(opt::quic_congestion_control::reno()); + cpp_opts.emplace_back(opt::quic_congestion_control::reno); break; } diff --git a/src/network/transport/quic_transport.cpp b/src/network/transport/quic_transport.cpp index 638961316..9807b95fc 100644 --- a/src/network/transport/quic_transport.cpp +++ b/src/network/transport/quic_transport.cpp @@ -29,22 +29,6 @@ namespace { } return false; // Shouldn't happen } - - std::optional to_quic( - std::optional algorithm) { - if (!algorithm) - return std::nullopt; - - switch (*algorithm) { - case opt::quic_congestion_control::Algorithm::bbr: - return quic::opt::congestion_control::bbr; - case opt::quic_congestion_control::Algorithm::cubic: - return quic::opt::congestion_control::cubic; - case opt::quic_congestion_control::Algorithm::reno: - return quic::opt::congestion_control::reno; - } - return std::nullopt; // Shouldn't happen - } } // namespace constexpr auto ALPN = "oxenstorage"sv; @@ -341,7 +325,7 @@ void QuicTransport::_establish_connection( oxen::quic::opt::outbound_alpn(ALPN), oxen::quic::opt::handshake_timeout{_config.handshake_timeout}, oxen::quic::opt::keep_alive{_config.keep_alive}, - to_quic(_config.congestion_control), + _config.congestion_control, [weak_self = weak_from_this(), this, address_pubkey_hex, initiating_req_id]( oxen::quic::Connection& conn) { auto self = weak_self.lock(); diff --git a/tests/test_network_config.cpp b/tests/test_network_config.cpp index 755619bcc..e75810cf7 100644 --- a/tests/test_network_config.cpp +++ b/tests/test_network_config.cpp @@ -37,9 +37,9 @@ TEST_CASE("Network config: QUIC congestion control", "[network][config][quic]") CHECK_FALSE(cfg.quic_congestion_control.has_value()); } SECTION("explicit algorithm") { - config::Config cfg{opt::quic_congestion_control::bbr()}; + config::Config cfg{opt::quic_congestion_control::bbr}; REQUIRE(cfg.quic_congestion_control.has_value()); - CHECK(*cfg.quic_congestion_control == opt::quic_congestion_control::Algorithm::bbr); + CHECK(*cfg.quic_congestion_control == opt::quic_congestion_control::bbr); } SECTION("C defaults leave libquic's default") { auto c = session_network_config_default(); From a12da1761365470c640d36008ca3619069809080 Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Thu, 5 Nov 2026 11:05:54 +1100 Subject: [PATCH 49/68] Bump session-router to v1.1.1 for libquic 1.14.0 libquic 1.14 drops the oxen/quic.hpp umbrella header, so the files that included it, and the ones that only compiled through what it pulled in, now include the libquic, oxenc and standard headers they use directly. --- external/session-router | 2 +- include/session/network/routing/onion_request_router.hpp | 1 + include/session/network/service_node.hpp | 2 +- include/session/network/session_network.hpp | 2 +- include/session/network/snode_pool.hpp | 1 + include/session/network/transport/quic_transport.hpp | 4 ++++ src/network/request_queue.cpp | 1 - src/network/service_node.cpp | 2 +- src/network/snode_pool.cpp | 4 +++- src/network/transport/quic_transport.cpp | 2 ++ src/onionreq/response_parser.cpp | 1 + 11 files changed, 16 insertions(+), 6 deletions(-) diff --git a/external/session-router b/external/session-router index 1f5da8692..710e15829 160000 --- a/external/session-router +++ b/external/session-router @@ -1 +1 @@ -Subproject commit 1f5da86924d49278ada9e926eff38f78d8c9a25e +Subproject commit 710e15829966d85136c20298b00a3adc0d9d9f89 diff --git a/include/session/network/routing/onion_request_router.hpp b/include/session/network/routing/onion_request_router.hpp index da17f3c40..30e7f773f 100644 --- a/include/session/network/routing/onion_request_router.hpp +++ b/include/session/network/routing/onion_request_router.hpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include "session/network/backends/session_file_server.hpp" diff --git a/include/session/network/service_node.hpp b/include/session/network/service_node.hpp index 6f26e8c92..55f25e415 100644 --- a/include/session/network/service_node.hpp +++ b/include/session/network/service_node.hpp @@ -4,7 +4,7 @@ #include #include -#include +#include #include "session/network/service_node.h" #include "session/network/swarm.hpp" diff --git a/include/session/network/session_network.hpp b/include/session/network/session_network.hpp index cb1ce2099..634c7d63e 100644 --- a/include/session/network/session_network.hpp +++ b/include/session/network/session_network.hpp @@ -3,7 +3,7 @@ #include #include #include -#include +#include #include "session/network/backends/session_file_server.hpp" #include "session/network/network_config.hpp" diff --git a/include/session/network/snode_pool.hpp b/include/session/network/snode_pool.hpp index 4ebd252aa..87f898001 100644 --- a/include/session/network/snode_pool.hpp +++ b/include/session/network/snode_pool.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include "session/network/key_types.hpp" diff --git a/include/session/network/transport/quic_transport.hpp b/include/session/network/transport/quic_transport.hpp index 3fc683d2f..1dab20287 100644 --- a/include/session/network/transport/quic_transport.hpp +++ b/include/session/network/transport/quic_transport.hpp @@ -3,6 +3,10 @@ #include #include #include +#include +#include +#include +#include #include #include #include diff --git a/src/network/request_queue.cpp b/src/network/request_queue.cpp index ee64dcfab..814a774e8 100644 --- a/src/network/request_queue.cpp +++ b/src/network/request_queue.cpp @@ -5,7 +5,6 @@ #include #include -#include #include using namespace oxen; diff --git a/src/network/service_node.cpp b/src/network/service_node.cpp index 4335e3451..d4dcd977a 100644 --- a/src/network/service_node.cpp +++ b/src/network/service_node.cpp @@ -3,7 +3,7 @@ #include #include -#include +#include #include using namespace oxen; diff --git a/src/network/snode_pool.cpp b/src/network/snode_pool.cpp index 6614c85c6..9a020a07e 100644 --- a/src/network/snode_pool.cpp +++ b/src/network/snode_pool.cpp @@ -11,9 +11,11 @@ #include #include #include -#include +#include +#include #include #include +#include #include "session/file.hpp" #include "session/hash.hpp" diff --git a/src/network/transport/quic_transport.cpp b/src/network/transport/quic_transport.cpp index 9807b95fc..453282e98 100644 --- a/src/network/transport/quic_transport.cpp +++ b/src/network/transport/quic_transport.cpp @@ -2,6 +2,8 @@ #include #include +#include +#include #include #include "session/ed25519.hpp" diff --git a/src/onionreq/response_parser.cpp b/src/onionreq/response_parser.cpp index 89230aee4..b50f22cd9 100644 --- a/src/onionreq/response_parser.cpp +++ b/src/onionreq/response_parser.cpp @@ -1,6 +1,7 @@ #include "session/onionreq/response_parser.hpp" #include +#include #include #include From caf65c17dea4dcdb62e384a3f123aa22e82a4343 Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Thu, 5 Nov 2026 11:05:54 +1100 Subject: [PATCH 50/68] Bump version to 1.9.5 --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 31aca0caa..464be92e0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -17,7 +17,7 @@ if(CCACHE_PROGRAM) endif() project(libsession-util - VERSION 1.9.4 + VERSION 1.9.5 DESCRIPTION "Session client utility library" LANGUAGES ${LANGS}) From c4e37f7eac650312ebe5efc426a69a7e907a4529 Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Thu, 5 Nov 2026 11:24:59 +1100 Subject: [PATCH 51/68] Bump session-deps to 1.38 Built with the 27 SDK, dependencies called strchrnul and pipe2 without an availability check and crashed on older iOS. session-deps now keeps them off anything newer than the deployment target. Also takes ngtcp2 1.26.0. --- cmake/session-deps | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/session-deps b/cmake/session-deps index 67d347c3a..ca13cd441 160000 --- a/cmake/session-deps +++ b/cmake/session-deps @@ -1 +1 @@ -Subproject commit 67d347c3ae0bddcffadf8b1231a772798eacd640 +Subproject commit ca13cd441c289bed15b62d6d71cf8e2c33b7c7b1 From 4339312100f33b2cc389f2e2484a48a153e8c0ca Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Thu, 5 Nov 2026 11:38:02 +1100 Subject: [PATCH 52/68] Include where std::variant and std::visit are used These came through oxen/quic.hpp before. libc++ still pulls in by other routes, but libstdc++ against the system liboxenquic does not, so the Debian and Ubuntu builds failed. --- include/session/network/session_network_types.hpp | 1 + src/network/session_network_internal.cpp | 1 + 2 files changed, 2 insertions(+) diff --git a/include/session/network/session_network_types.hpp b/include/session/network/session_network_types.hpp index efecd7e01..d62724ed4 100644 --- a/include/session/network/session_network_types.hpp +++ b/include/session/network/session_network_types.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include "session/network/key_types.hpp" diff --git a/src/network/session_network_internal.cpp b/src/network/session_network_internal.cpp index ec93e2138..dbeb67665 100644 --- a/src/network/session_network_internal.cpp +++ b/src/network/session_network_internal.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include "session/network/service_node.hpp" From 84d147fb2e0abdbe2cc20d355bbe1cc6d74a6944 Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Fri, 13 Nov 2026 11:30:44 +1100 Subject: [PATCH 53/68] Don't throw from QuicTransport::resume when the endpoint can't be created Resuming recreates the endpoint, whose socket setup throws on any failed socket call, and that exception escaped through session_network_resume to a caller that can't catch it: on iOS 2.15.6 this terminates the app on returning to the foreground or starting a background fetch. The failure is now logged with its errno and the transport resumes without an endpoint, which its next connection attempt creates. --- src/network/transport/quic_transport.cpp | 30 ++++++++-- tests/test_quic_transport.cpp | 72 ++++++++++++++++++++++++ 2 files changed, 98 insertions(+), 4 deletions(-) diff --git a/src/network/transport/quic_transport.cpp b/src/network/transport/quic_transport.cpp index 453282e98..81667493e 100644 --- a/src/network/transport/quic_transport.cpp +++ b/src/network/transport/quic_transport.cpp @@ -5,6 +5,8 @@ #include #include #include +#include +#include #include "session/ed25519.hpp" #include "session/network/session_network_types.hpp" @@ -22,6 +24,14 @@ namespace { static constexpr uint16_t ACTIVE_STREAM_PRUNE_LIMIT = 32; + // The errno is what says why a socket couldn't be opened, and a system_error's message + // doesn't always make it recoverable + std::string describe(const std::exception& e) { + if (const auto* se = dynamic_cast(&e)) + return "{} (errno {})"_format(se->what(), se->code().value()); + return e.what(); + } + inline bool use_reserved_stream(RequestCategory category) { switch (category) { case RequestCategory::standard: return false; @@ -66,8 +76,20 @@ void QuicTransport::resume(bool /*automatically_reconnect*/) { // Use 'call_get' to force this to be synchronous _loop->call_get([this] { // Recreate the endpoint before updating the `_suspended` flag to avoid the chance that - // something will try to use it before we are ready - _recreate_endpoint(); + // something will try to use it before we are ready. + // + // Opening its socket can fail, and an exception from here reaches the caller of + // `session_network_resume`, which generally can't catch it (it terminates an iOS app). + // Left without an endpoint, the transport creates one on its next connection attempt. + try { + _recreate_endpoint(); + } catch (const std::exception& e) { + log::error( + cat, + "Unable to recreate the endpoint on resume, will retry on the next " + "connection: {}", + describe(e)); + } _suspended = false; log::info(cat, "Resumed."); }); @@ -305,7 +327,7 @@ void QuicTransport::_establish_connection( if (_suspended) throw std::runtime_error{"QuickTransport is suspended"}; if (!_endpoint) - throw std::runtime_error{"Network is invalid"}; + _recreate_endpoint(); auto conn_key_pair = ed25519::ed25519_key_pair(); auto creds = quic::GNUTLSCreds::make_from_ed_seckey(to_string_view(conn_key_pair.second)); @@ -384,7 +406,7 @@ void QuicTransport::_establish_connection( conn.reference_id()); }); } catch (const std::exception& e) { - _fail_connection(address_pubkey_hex, initiating_req_id, std::nullopt, e.what()); + _fail_connection(address_pubkey_hex, initiating_req_id, std::nullopt, describe(e)); } } diff --git a/tests/test_quic_transport.cpp b/tests/test_quic_transport.cpp index f1dfb0d32..d8aa9b8e3 100644 --- a/tests/test_quic_transport.cpp +++ b/tests/test_quic_transport.cpp @@ -1,12 +1,53 @@ +#include +#include +#include +#include + +#include #include #include #include #include +#include using namespace session::network; using namespace std::literals; namespace { +// Takes every file descriptor the process may open, under a lowered limit, so that the next +// socket() fails with EMFILE - a real failure of the endpoint's own socket setup, rather than an +// injected one. The descriptors and the limit are given back on destruction. +class exhausted_file_descriptors { + rlimit _original{}; + std::vector _fds; + + public: + exhausted_file_descriptors() { + getrlimit(RLIMIT_NOFILE, &_original); + auto lowered = _original; + lowered.rlim_cur = std::min(_original.rlim_cur, 1024); + setrlimit(RLIMIT_NOFILE, &lowered); + + for (int fd; (fd = ::open("/dev/null", O_RDONLY)) >= 0;) + _fds.push_back(fd); + } + + ~exhausted_file_descriptors() { + for (int fd : _fds) + ::close(fd); + setrlimit(RLIMIT_NOFILE, &_original); + } + + // Whether a socket can't be opened, which is what the tests below rely on + static bool socket_fails() { + int sock = ::socket(AF_INET6, SOCK_DGRAM, 0); + if (sock < 0) + return true; + ::close(sock); + return false; + } +}; + std::shared_ptr make_transport(std::shared_ptr loop) { return std::make_shared( config::QuicTransport{ @@ -81,3 +122,34 @@ TEST_CASE("Network", "[network][quic_transport][close_connections]") { CHECK_FALSE(success); CHECK_FALSE(error_code); } + +TEST_CASE("Network", "[network][quic_transport][resume]") { + auto loop = std::make_shared(); + auto transport = make_transport(loop); + transport->suspend(); + + { + exhausted_file_descriptors no_fds; + REQUIRE(exhausted_file_descriptors::socket_fails()); + + // Throwing here would reach the C API's caller, which can't catch it + CHECK_NOTHROW(transport->resume(true)); + } + + // Once sockets can be opened again a connection attempt rebuilds the endpoint, so it is made + // and times out with an error code; without an endpoint it would fail at once with none + std::promise> error_code; + transport->verify_connectivity( + test_node(), + 3s, + "AAAA", + RequestCategory::standard, + [&error_code, answered = false](bool, std::optional e) mutable { + if (!std::exchange(answered, true)) + error_code.set_value(e); + }); + + auto answer = error_code.get_future(); + REQUIRE(answer.wait_for(10s) == std::future_status::ready); + CHECK(answer.get().has_value()); +} From e7aadd5aefbce6a268ae0bc9cdc732551f0e79a0 Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Fri, 13 Nov 2026 11:30:44 +1100 Subject: [PATCH 54/68] Keep exceptions inside the blocking network C API calls session_network_suspend, _resume, _close_connections and _clear_cache block on a loop job and rethrow whatever it throws, so any exception there reaches the C caller. They now log it instead. --- src/network/session_network.cpp | 23 ++++++++++++++++++---- tests/test_quic_transport.cpp | 35 +++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 4 deletions(-) diff --git a/src/network/session_network.cpp b/src/network/session_network.cpp index 9d605de80..c2742d750 100644 --- a/src/network/session_network.cpp +++ b/src/network/session_network.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include "session/blinding.hpp" @@ -1258,6 +1259,18 @@ inline bool set_error(char* error, const std::exception& e) { return false; } +// For the entry points that block on the network's loop: whatever the loop job throws is rethrown +// in the caller, and callers of the C API (Swift, JNI) generally can't catch a C++ exception, so +// one escaping terminates the app. +template +void without_throwing(std::string_view action, F&& f) { + try { + f(); + } catch (const std::exception& e) { + log::error(cat, "Failed to {}: {}", action, e.what()); + } +} + } // namespace extern "C" { @@ -1583,20 +1596,22 @@ LIBSESSION_C_API void session_request_params_free(session_request_params* params } LIBSESSION_C_API void session_network_suspend(network_object* network) { - unbox(network)->suspend(); + without_throwing("suspend the network", [&] { unbox(network)->suspend(); }); } LIBSESSION_C_API void session_network_resume( network_object* network, bool automatically_reconnect) { - unbox(network)->resume(automatically_reconnect); + without_throwing( + "resume the network", [&] { unbox(network)->resume(automatically_reconnect); }); } LIBSESSION_C_API void session_network_close_connections(network_object* network) { - unbox(network)->close_connections(); + without_throwing( + "close the network's connections", [&] { unbox(network)->close_connections(); }); } LIBSESSION_C_API void session_network_clear_cache(network_object* network) { - unbox(network)->clear_cache(); + without_throwing("clear the network's cache", [&] { unbox(network)->clear_cache(); }); } LIBSESSION_C_API bool session_network_has_retrieved_time_offset(network_object* network) { diff --git a/tests/test_quic_transport.cpp b/tests/test_quic_transport.cpp index d8aa9b8e3..bc292dc90 100644 --- a/tests/test_quic_transport.cpp +++ b/tests/test_quic_transport.cpp @@ -1,10 +1,12 @@ #include +#include #include #include #include #include #include +#include #include #include #include @@ -153,3 +155,36 @@ TEST_CASE("Network", "[network][quic_transport][resume]") { REQUIRE(answer.wait_for(10s) == std::future_status::ready); CHECK(answer.get().has_value()); } + +TEST_CASE("Network", "[network][c_api][resume]") { + // Devnet with a local seed node keeps the network's own startup requests off the internet + network_service_node seed{}; + std::strcpy( + seed.ed25519_pubkey_hex, + "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7"); + seed.ip[0] = 127; + seed.ip[3] = 1; + seed.https_port = 20001; + seed.omq_port = 30001; + seed.version[0] = 2; + seed.version[1] = 11; + + auto config = session_network_config_default(); + config.netid = SESSION_NETWORK_DEVNET; + config.router = SESSION_NETWORK_ROUTER_DIRECT; + config.devnet_seed_nodes = &seed; + config.devnet_seed_nodes_size = 1; + + network_object* network = nullptr; + char error[256] = {}; + REQUIRE(session_network_init(&network, &config, error)); + + session_network_suspend(network); + { + exhausted_file_descriptors no_fds; + REQUIRE(exhausted_file_descriptors::socket_fails()); + CHECK_NOTHROW(session_network_resume(network, false)); + } + + session_network_free(network); +} From f4d22fc7f133de543b71701443853e8bddff8b66 Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Tue, 17 Nov 2026 10:00:21 +1100 Subject: [PATCH 55/68] Bump version to 1.9.6 --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 464be92e0..d1c5bd462 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -17,7 +17,7 @@ if(CCACHE_PROGRAM) endif() project(libsession-util - VERSION 1.9.5 + VERSION 1.9.6 DESCRIPTION "Session client utility library" LANGUAGES ${LANGS}) From c3a76399fa2fbd00f1e0c2b5609e82bc163ca52b Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Sat, 21 Nov 2026 17:04:46 -0400 Subject: [PATCH 56/68] Fix includes for fmt 12 and GCC 16 fmt 12 made fmt/core.h equivalent to fmt/base.h, which doesn't declare fmt::format, so files using it now include fmt/format.h. GCC 16's libstdc++ no longer pulls in , or transitively, which types.cpp relied on. --- include/session/network/backends/backend_util.hpp | 2 ++ include/session/parse_error.hpp | 2 +- src/json_parser.hpp | 2 +- src/pro_backend.cpp | 2 +- src/session_protocol.cpp | 2 +- src/types.cpp | 5 ++++- 6 files changed, 10 insertions(+), 5 deletions(-) diff --git a/include/session/network/backends/backend_util.hpp b/include/session/network/backends/backend_util.hpp index 5a2a9d2b6..b0b71ae48 100644 --- a/include/session/network/backends/backend_util.hpp +++ b/include/session/network/backends/backend_util.hpp @@ -1,5 +1,7 @@ #pragma once +#include + #include #include #include diff --git a/include/session/parse_error.hpp b/include/session/parse_error.hpp index 7af204e86..9547e9628 100644 --- a/include/session/parse_error.hpp +++ b/include/session/parse_error.hpp @@ -1,6 +1,6 @@ #pragma once -#include +#include #include #include diff --git a/src/json_parser.hpp b/src/json_parser.hpp index 9ec65b62a..c018118d0 100644 --- a/src/json_parser.hpp +++ b/src/json_parser.hpp @@ -1,6 +1,6 @@ #pragma once -#include +#include #include #include diff --git a/src/pro_backend.cpp b/src/pro_backend.cpp index 9ee501303..1bd92e27d 100644 --- a/src/pro_backend.cpp +++ b/src/pro_backend.cpp @@ -1,4 +1,4 @@ -#include +#include #include #include #include diff --git a/src/session_protocol.cpp b/src/session_protocol.cpp index 0f9d50c1a..d4e19cc21 100644 --- a/src/session_protocol.cpp +++ b/src/session_protocol.cpp @@ -1,4 +1,4 @@ -#include +#include #include #include #include diff --git a/src/types.cpp b/src/types.cpp index 230dee60d..78de692f6 100644 --- a/src/types.cpp +++ b/src/types.cpp @@ -1,8 +1,11 @@ -#include +#include #include #include +#include +#include #include +#include namespace session { span_u8 span_u8_alloc_or_throw(size_t size) { From 72dfa7aaaf61a9db828f1cfeb8083932685a07f7 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Wed, 30 Sep 2026 15:43:47 -0300 Subject: [PATCH 57/68] Fix uninitialized requested_unlock_height usage Forward-port of dev commit 348b778e; line-for-line identical to dev's. from_json left requested_unlock_height uninitialized whenever the JSON omitted it, which swarm responses and 421 bodies always do, and an oxend node dump does for a node with no unlock requested. The field becomes int64_t defaulting to -1 so "we were not told" is distinguishable from "not requested", and the snode_pool filter tests `> 0` rather than truthiness. --- include/session/network/service_node.h | 2 +- include/session/network/service_node.hpp | 5 ++++- src/network/service_node.cpp | 6 +++--- src/network/snode_pool.cpp | 2 +- 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/include/session/network/service_node.h b/include/session/network/service_node.h index 8462f6e64..ae09ba4c6 100644 --- a/include/session/network/service_node.h +++ b/include/session/network/service_node.h @@ -13,7 +13,7 @@ typedef struct network_service_node { uint16_t omq_port; uint16_t version[3]; uint64_t swarm_id; - uint64_t requested_unlock_height; + int64_t requested_unlock_height; // -1 if unknown; 0 if no unlock has been requested. } network_service_node; #ifdef __cplusplus diff --git a/include/session/network/service_node.hpp b/include/session/network/service_node.hpp index 2e0a94950..4073038e7 100644 --- a/include/session/network/service_node.hpp +++ b/include/session/network/service_node.hpp @@ -42,7 +42,10 @@ struct service_node { uint16_t omq_port; std::array storage_server_version; swarm_id_t swarm_id; - uint64_t requested_unlock_height; + + // -1 when we don't know: most sources (the binary pool format, the on-disk cache, swarm + // responses) carry no unlock information at all, and 0 would claim they said "not requested". + int64_t requested_unlock_height = -1; oxen::quic::RemoteAddress to_https_address() const { return oxen::quic::RemoteAddress{remote_pubkey.view(), ip, https_port}; diff --git a/src/network/service_node.cpp b/src/network/service_node.cpp index 8b9908cf8..1e864354b 100644 --- a/src/network/service_node.cpp +++ b/src/network/service_node.cpp @@ -121,9 +121,9 @@ service_node service_node::from_json(nlohmann::json json) { if (!quic::parse_int(json["swarm"].get(), swarm_id, 16)) throw std::runtime_error{"Invalid swarm id"}; - uint64_t requested_unlock_height; - if (json.contains("requested_unlock_height")) - requested_unlock_height = json["requested_unlock_height"].get(); + // Swarm responses (the `get_swarm` endpoint and 421 bodies) omit this entirely, and an oxend + // node dump omits it for a node with no unlock requested; neither case is distinguishable here + auto requested_unlock_height = json.value("requested_unlock_height", -1); return {ed25519_pubkey::from_bytes(pubkey), quic::ipv4{ip}, diff --git a/src/network/snode_pool.cpp b/src/network/snode_pool.cpp index 6e7048cb0..5fa58d5d5 100644 --- a/src/network/snode_pool.cpp +++ b/src/network/snode_pool.cpp @@ -503,7 +503,7 @@ void SnodePool::_launch_next_refresh_request( // possible that the node is offline so don't both including it in the // initial cache (if we get a successful connection and refresh the // cache then it would be added back at that point) - if (snode.requested_unlock_height && + if (snode.requested_unlock_height > 0 && snode.requested_unlock_height <= expected_current_height) { unlocked_count++; continue; From 37455aa395de231f974f2b26923148574f860459 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Wed, 30 Sep 2026 16:37:03 -0300 Subject: [PATCH 58/68] Port swarm invalidation on 421 from dev (#154) Brings client's snode pool, network and routers to dev's #154 behaviour: swarm redirects taken from a 421's own swarm list (resolved only against nodes we already know), evidence-driven refreshes with global exponential backoff, overrides kept apart from the calculated swarm and dropped on refresh, refresh callbacks that report whether a refresh happened, strike expiry applied everywhere strikes are counted, a stale check on every get_swarm, per-account rejection parsing for batch/sequence requests, undecryptable responses reported as ERROR_UNAUTHENTICATED_RESPONSE, ERROR_INSUFFICIENT_NODES, and the QUIC suspend/close fixes. The one piece of client's design kept is that 421 retries belong to Core, not Network. Network therefore corrects the swarm but does not retry: it reports ERROR_MISDIRECTED_REQUEST once re-resolving the swarm would give a better answer (immediately when a redirect was taken, after the refresh otherwise), and the new ERROR_SWARM_UNRESOLVED when it could not be corrected, so Core ends the operation instead of retrying against the swarm that just rejected it. This replaces client's set_swarm-based adoption of a 421's swarm. Tests are dev's, adapted to client's JobQueue/Loop& and std::byte idioms. --- .../network/routing/onion_request_router.hpp | 1 + include/session/network/session_network.hpp | 21 +- .../session/network/session_network_types.h | 4 +- .../session/network/session_network_types.hpp | 76 +- include/session/network/snode_pool.hpp | 62 +- src/core.cpp | 10 +- src/core/swarm_request.hpp | 4 +- src/network/routing/onion_request_router.cpp | 184 +++-- src/network/routing/session_router_router.cpp | 77 +- src/network/session_network.cpp | 269 +++++-- src/network/session_network_types.cpp | 173 +++- src/network/snode_pool.cpp | 374 +++++++-- src/network/transport/quic_transport.cpp | 43 +- tests/CMakeLists.txt | 1 + tests/test_config_userprofile.cpp | 1 + tests/test_helper.hpp | 2 +- tests/test_network_swarm.cpp | 184 +++++ tests/test_onion_request_router.cpp | 350 +++++++- tests/test_quic_transport.cpp | 78 ++ tests/test_snode_pool.cpp | 757 ++++++++++++++++-- tests/utils.hpp | 2 + 21 files changed, 2282 insertions(+), 391 deletions(-) create mode 100644 tests/test_quic_transport.cpp diff --git a/include/session/network/routing/onion_request_router.hpp b/include/session/network/routing/onion_request_router.hpp index c2f622d2c..bfc29e5c2 100644 --- a/include/session/network/routing/onion_request_router.hpp +++ b/include/session/network/routing/onion_request_router.hpp @@ -202,6 +202,7 @@ class OnionRequestRouter : public IRouter, public std::enable_shared_from_this> headers, + std::optional body, + network_response_callback_t final_callback); void _resync_clock( std::optional original_request, network_response_callback_t request_callback); @@ -198,7 +209,7 @@ class Network { const uint8_t index, const service_node& node, const uint8_t total_requests); - void _on_clock_resync_complete(const uint8_t total_requests); + void _on_clock_resync_complete(); Request _preprocess_request(Request request); }; diff --git a/include/session/network/session_network_types.h b/include/session/network/session_network_types.h index 13a259dc2..93fe2dec2 100644 --- a/include/session/network/session_network_types.h +++ b/include/session/network/session_network_types.h @@ -67,7 +67,9 @@ typedef struct { // The account whose swarm this request addresses, as 64 hex chars of its X25519 pubkey — the // same value passed to session_network_get_swarm() to choose the destination node. Null for a // request aimed at a node rather than about an account (a cache refresh, a clock resync) or at - // a server, which no swarm membership applies to. + // a server, which no swarm membership applies to. For a `batch` or `sequence` request each + // sub-request's account is read from the body instead, and this is used only if the body + // can't be parsed. // // Set it whenever there is one: a storage server rejects a request whose pubkey is outside its // swarm with a 421, and recovering means re-resolving this account's swarm. Left null, such a diff --git a/include/session/network/session_network_types.hpp b/include/session/network/session_network_types.hpp index 6fe3ed4a5..b17197f11 100644 --- a/include/session/network/session_network_types.hpp +++ b/include/session/network/session_network_types.hpp @@ -4,7 +4,9 @@ #include #include #include +#include #include +#include #include #include @@ -33,9 +35,14 @@ constexpr int16_t ERROR_FAILED_TO_QUEUE_REQUEST = -10008; constexpr int16_t ERROR_INVALID_DESTINATION = -10009; constexpr int16_t ERROR_FAILED_GENERATE_ONION_PAYLOAD = -10010; constexpr int16_t ERROR_FAILED_TO_GET_STREAM = -10011; +constexpr int16_t ERROR_UNAUTHENTICATED_RESPONSE = -10012; +constexpr int16_t ERROR_INSUFFICIENT_NODES = -10013; constexpr int16_t ERROR_BUILD_TIMEOUT = -10100; constexpr int16_t ERROR_REQUEST_CANCELLED = -10200; constexpr int16_t ERROR_FILE_SERVER_UNAVAILABLE = -10300; +// A 421 whose swarm could not be corrected, so re-resolving would return the one that rejected us; +// distinct from ERROR_MISDIRECTED_REQUEST, which means re-resolving now gives a better answer. +constexpr int16_t ERROR_SWARM_UNRESOLVED = -10400; constexpr int16_t ERROR_UNKNOWN = -11000; const std::pair content_type_plain_text = { @@ -200,16 +207,17 @@ struct Request { /// Any extra request details which may modify the structure of the request. RequestDetails details; - /// The account whose swarm this request addresses, when it addresses one: the X25519 pubkey of - /// a session ID, group ID, etc. Set it for anything sent to a swarm member *about* that - /// account, and leave it unset for a request merely aimed at a node (a snode cache refresh, a - /// clock resync), which no swarm membership applies to. + /// The accounts this request addresses: one entry per sub-request of a `batch` or `sequence`, + /// in order, or a single entry for any other request. Each is the 32-byte pubkey an account's + /// swarm is computed from (a session ID or group ID without its prefix); an entry is empty for + /// a sub-request that isn't about an account. A single entry applies to every sub-request. + /// Leave it empty for a request merely aimed at a node (a snode cache refresh, a clock resync). /// - /// Set it to have a 421's correction applied: the swarm the storage server reports in the - /// rejection is written into the cache for *this account*, which cannot be derived from the - /// node we happened to ask. Recovering from the 421 is still the caller's -- see + /// Required to recover from a 421: it is what says whose swarm the redirect a 421 carries is + /// for. The account a storage server names in a 421 is only checked against it, never trusted + /// in its place. Network corrects the swarm but does not retry; that is the caller's -- see /// `Network::send_request`. - std::optional swarm_pubkey; + std::vector> swarm_pubkeys; /// The time the request was created, this is used primarily for determining whether the /// `overall_timeout` has been exceeded. @@ -322,9 +330,61 @@ using network_response_callback_t = std::function> headers, std::optional response)>; +/// The accounts of each sub-request in a pregenerated `batch`/`sequence` body, in the form +/// `Request::swarm_pubkeys` takes, for a request whose body was built by the caller. A +/// sub-request whose params name no account gets `fallback` instead: the account the caller said +/// the request is for. Returns nullopt when `endpoint` is neither or the body can't be parsed. +std::optional>> batch_request_accounts( + std::string_view endpoint, + std::span body, + std::optional fallback = std::nullopt); + namespace response { std::optional> parse_text_error(std::string_view body); std::optional find_uniform_batch_error(std::string_view body); + + /// As `find_uniform_batch_error`, for a body that has already been parsed. + std::optional uniform_batch_error(const nlohmann::json& json); + + /// The status to report for a proxied response that could not be decrypted, whose status + /// therefore came from whichever node on the way answered rather than from the destination. + /// Statuses that are acted on as the destination's verdict (406, 421, 425) become + /// `ERROR_UNAUTHENTICATED_RESPONSE`, since any node on the path could have sent them; anything + /// else is returned unchanged. + int16_t undecrypted_status(int16_t status); + + /// One result of a `batch`/`sequence` response, or the whole of any other response. + struct subresponse { + /// The result's own status code; nullopt for a response that isn't a batch, whose status + /// is the one it came back with. + std::optional code; + + /// The result's body when it is a JSON object. Points into the parsed response. + const nlohmann::json* body = nullptr; + }; + + /// The sub-responses of a parsed response: one per entry of `results` for a batch or sequence, + /// otherwise the response itself as the only one. The returned bodies point into `json`. + std::vector subresponses(const nlohmann::json& json); + + /// The accounts a response's 421s rejected. + struct swarm_rejections { + /// Each rejected account, with the ed25519 pubkeys of the swarm its 421 redirected it to: + /// empty when the 421 named no swarm. An account with several 421s takes the first. + std::unordered_map> accounts; + + /// Whether a 421 could not be attributed to any account. + bool unattributed = false; + }; + + /// Finds the 421s in a storage server response. `json` is its parsed body, or null when the + /// body isn't JSON. `status_code` is the response's own status, which is the only status a + /// response that isn't a batch has. `accounts` is the request's `swarm_pubkeys`, which each + /// 421 is attributed by; a 421 naming a different account than its position does is ignored. + swarm_rejections find_swarm_rejections( + const nlohmann::json* json, + int16_t status_code, + std::span> accounts); } // namespace response /// One hop of a route, for showing a user where their traffic goes. Identity and location, which diff --git a/include/session/network/snode_pool.hpp b/include/session/network/snode_pool.hpp index 1b387a4f5..4d68ebb02 100644 --- a/include/session/network/snode_pool.hpp +++ b/include/session/network/snode_pool.hpp @@ -56,6 +56,12 @@ class SnodePool : public std::enable_shared_from_this { public: using network_fetcher_t = std::function; + + // `refreshed` is false when the pool could not be refreshed at all - suspended, no candidate + // nodes, no fetcher. Callers that retry their work on this callback have to check it: without + // it the only way to signal "that didn't happen" was to never call back, which leaves whatever + // the caller set up beforehand set up forever. + using refresh_callback_t = std::function; using fetcher_connectivity_check_t = std::function; SnodePool( @@ -83,29 +89,44 @@ class SnodePool : public std::enable_shared_from_this { virtual void record_node_failure(const ed25519_pubkey& key, bool permanent = false); uint16_t node_strike_count(const service_node& node); uint16_t node_strike_count(const ed25519_pubkey& key); + + // Whether the node has collected enough unexpired strikes to be kept out of node selection. + // Callers that pick a node by some other route - a cached one, say - need this to apply the + // same bar `get_unused_nodes` does, rather than comparing a raw count to a threshold they'd + // have to know about. + virtual bool node_struck_out(const service_node& node); + virtual bool node_struck_out(const ed25519_pubkey& key); void clear_node_strikes(); // Checks if the pool is empty or stale and triggers a refresh if needed virtual void refresh_if_needed( const std::vector& in_use_nodes, - std::function on_refresh_complete = nullptr); + refresh_callback_t on_refresh_complete = nullptr); + + // Re-resolves `swarm_pubkey` after a node we believed was in its swarm has told us the account + // isn't there. Where `refresh_if_needed` decides on the cache's age, this decides on that + // rejection, so a mapping we have direct proof is wrong can be replaced long before + // `cache_expiration`. `on_complete` runs once the swarm can be resolved again. + virtual void invalidate_swarm( + session::network::x25519_pubkey swarm_pubkey, refresh_callback_t on_complete = nullptr); + + // Records the swarm a node named when it rejected a request for `swarm_pubkey`, so the mapping + // can be corrected without refreshing the whole pool - a swarm change would otherwise have + // every client of that swarm fetch the full node list, where nothing made them before. + // + // Only the node pubkeys are taken from the response, and only ones that resolve against the + // pool we fetched ourselves, so a redirect can reach registered service nodes we already know + // and nothing else. Returns false when the redirect is unusable, which is the caller's cue to + // fall back to `invalidate_swarm`. + virtual bool record_swarm_redirect( + session::network::x25519_pubkey swarm_pubkey, + const std::vector& swarm_node_keys); virtual void get_swarm( session::network::x25519_pubkey swarm_pubkey, bool ignore_strike_count, std::function)> callback); - /// Replaces the cached swarm for an account with one a storage server told us authoritatively, - /// as a 421 body does. - /// - /// Overrides the locally computed membership, which is only as fresh as the snode cache - /// (`cache_expiration`, hours) and is exactly what a 421 says was wrong. The override lives - /// until the next snode cache refresh recomputes everything. - virtual void set_swarm( - session::network::x25519_pubkey swarm_pubkey, - swarm::swarm_id_t swarm_id, - std::vector nodes); - virtual std::vector get_unused_nodes( size_t count, const std::vector& exclude = {}); @@ -126,6 +147,13 @@ class SnodePool : public std::enable_shared_from_this { std::vector>> _all_swarms; std::unordered_map>> _swarm_cache; + + // Swarms a node has redirected us to, which `get_swarm` prefers over its own calculation. Kept + // apart from `_swarm_cache` deliberately: that is a memo of `_all_swarms` and stays one, where + // these are claims from outside that outrank it until the pool is refreshed. The count is the + // account's redirects since that refresh, which past a limit also ask for the next one. + std::unordered_map, uint8_t>> + _swarm_overrides; std::map> _snode_strikes; bool _strikes_flush_scheduled = false; @@ -135,11 +163,18 @@ class SnodePool : public std::enable_shared_from_this { // Refresh logic std::chrono::system_clock::time_point _last_snode_cache_update; + std::chrono::system_clock::time_point _last_evidence_refresh; + std::chrono::seconds _evidence_refresh_backoff{0}; std::optional _current_snode_cache_refresh_id; int _snode_cache_refresh_failure_count = 0; std::vector _refresh_candidate_nodes; std::vector> _snode_refresh_results; - std::vector> _after_snode_cache_refresh; + std::vector _after_snode_cache_refresh; + + // Counts a node's strikes that haven't expired yet. `record_node_failure` only appends, so the + // raw vector answers a different question - every strike the node has ever collected. + size_t _active_strike_count(const ed25519_pubkey& key) const; + bool _node_struck_out(const ed25519_pubkey& key) const; /// This pool's own jobs, rather than the loop's shared queue, so that ~SnodePool can take them /// away from the loop before anything is torn down: `stop()` waits out whatever is running and @@ -179,6 +214,7 @@ class SnodePool : public std::enable_shared_from_this { const bool use_direct_fetcher, const uint8_t total_requests); void _update_cache(std::string refresh_id, std::vector nodes); + void _run_pending_refresh_callbacks(bool refreshed); }; } // namespace session::network diff --git a/src/core.cpp b/src/core.cpp index 69aa105e4..a54a5f86d 100644 --- a/src/core.cpp +++ b/src/core.cpp @@ -553,15 +553,15 @@ void Core::_swarm_response( bool timeout, int16_t status, std::optional body) { - // Not this member's swarm. Network has already taken the corrected membership - // out of the rejection, so resolving again gets the new one -- and whatever we - // were sticking to is exactly what was wrong. + // Not this member's swarm. Network reports this only once the swarm has been corrected -- from + // the rejection's redirect, or by a refresh -- so resolving again gets the new one, and + // whatever we were sticking to is exactly what was wrong. A rejection it could not correct + // arrives as ERROR_SWARM_UNRESOLVED instead, and ends the operation below. if (status == network::ERROR_MISDIRECTED_REQUEST) { op->prefer.reset(); // Spent, not merely wrong to stick to: a member that says the account is not its own will - // say so again, and the corrected swarm may not have arrived -- an older server sends no - // swarm with the rejection, and then re-resolving returns the very same membership. + // say so again, and a refreshed pool can still place it in the account's swarm. op->spent.push_back(node); if (++op->redirects > SWARM_REDIRECT_LIMIT) diff --git a/src/core/swarm_request.hpp b/src/core/swarm_request.hpp index f08f1440d..21bdc2803 100644 --- a/src/core/swarm_request.hpp +++ b/src/core/swarm_request.hpp @@ -99,7 +99,9 @@ inline network::Request swarm_request( std::move(body), network::RequestCategory::standard_small, SWARM_REQUEST_TIMEOUT}; - req.swarm_pubkey = swarm_pubkey; + // A single entry: every Core request is about one account, including its batches, whose + // sub-requests all address the same swarm + req.swarm_pubkeys = {swarm_pubkey}; req.overall_timeout = SWARM_OVERALL_TIMEOUT; return req; } diff --git a/src/network/routing/onion_request_router.cpp b/src/network/routing/onion_request_router.cpp index 70f368a0a..7f7ff2eec 100644 --- a/src/network/routing/onion_request_router.cpp +++ b/src/network/routing/onion_request_router.cpp @@ -349,7 +349,12 @@ void OnionRequestRouter::_start_setup() { if (snode_pool->size() == 0) // The pool outlives us, so this one keeps a weak guard rather than a bare `this`. - snode_pool->refresh_if_needed({}, [weak_self = weak_from_this(), this] { + snode_pool->refresh_if_needed({}, [weak_self = weak_from_this(), this](bool refreshed) { + // Setup finishes either way: not finishing leaves the router permanently unusable, + // where finishing with an empty pool just means the first request refreshes again + if (!refreshed) + log::warning(cat, "Finishing router setup without a refreshed snode pool."); + if (auto self = weak_self.lock()) _jq.call([this] { _finish_setup(); }); }); @@ -683,9 +688,37 @@ void OnionRequestRouter::_finish_setup() { } } +// A cached edge node is handed to `_build_path` as a forced first hop, so it is the one node in a +// path that never passes the strike filter `get_unused_nodes` applies to the rest, and the only +// thing that dropped it was `edge_node_cache_duration` (10 days). +// +// Being struck out costs it the cached-edge-node role, not its place in the pool: it stays a node +// like any other and `get_unused_nodes` can pick it again once its strikes expire. Keeping the +// entry and merely skipping it would hand the role back at that expiry, by which point we have been +// running on a different edge node for two days - that is a second change of first hop, not a +// return to a stable one. +void OnionRequestRouter::_drop_struck_cached_edge_nodes() { + auto snode_pool = _snode_pool.lock(); + + if (!snode_pool) + return; + + std::erase_if(_cached_edge_nodes, [&snode_pool](const auto& cached) { + if (!snode_pool->node_struck_out(cached.node)) + return false; + + log::debug( + cat, + "Dropping cached edge node {}, it has been struck out.", + cached.node.to_string()); + return true; + }); +} + void OnionRequestRouter::_pre_build_paths_if_needed() { if (!_config.disable_pre_build_paths) { log::info(cat, "Pre-building initial paths."); + _drop_struck_cached_edge_nodes(); std::vector edge_nodes = _cached_edge_nodes; if (_config.single_path_mode) { @@ -1239,15 +1272,61 @@ void OnionRequestRouter::_build_path( snode_pool->refresh_if_needed( nodes_to_exclude, - [weak_self = weak_from_this(), - this, - category, - initiating_req_id, - nodes_to_exclude]() { + [weak_self = weak_from_this(), this, category, initiating_req_id, nodes_to_exclude]( + bool refreshed) { auto self = weak_self.lock(); if (!self) return; + // Rebuilding lands back in this same branch unless the pool can now fill a + // path, and `refreshed` includes nothing having needed refreshing, which calls + // back inline - so rebuilding without checking first recurses until the stack + // gives out + std::optional cannot_build; + if (!refreshed) + cannot_build = "the snode pool could not be refreshed"; + else if (auto pool = _snode_pool.lock(); + !pool || + pool->get_unused_nodes(_config.path_length, nodes_to_exclude).size() < + _config.path_length) + cannot_build = "the snode pool has too few usable nodes"; + + if (cannot_build) { + log::error( + cat, + "[Request {}]: Cannot build a path, {}.", + initiating_req_id.value_or("internal"), + *cannot_build); + _update_status(); + + auto queue_it = _request_queues.find(category); + if (queue_it == _request_queues.end()) { + log::critical( + cat, + "No request queue for category '{}'.", + to_string(category, _config.single_path_mode)); + return; + } + + if (!queue_it->second->is_empty()) { + auto to_fail = queue_it->second->pop_all(); + log::error( + cat, + "Failing {} queued requests for '{}' paths; {}.", + to_fail.size(), + to_string(category, _config.single_path_mode), + *cannot_build); + + for (const auto& [req, cb] : to_fail) + cb(false, + false, + ERROR_INSUFFICIENT_NODES, + {content_type_plain_text}, + "Cannot build a path: {}."_format(*cannot_build)); + } + return; + } + log::info( cat, "[Request {}]: SnodePool refresh complete, retrying path build.", @@ -1652,51 +1731,49 @@ void OnionRequestRouter::_send_on_path( return; } - auto decryption_callback = [weak_self = weak_from_this(), - this, - parser = std::move(parser), - path_id = path.id, - original_request = std::move(request), - cb = std::move(callback)]( - bool success, - bool timeout, - int16_t status, - auto headers, - auto response) { - auto self = weak_self.lock(); - if (!self) - return; + auto decryption_callback = + [weak_self = weak_from_this(), + this, + parser = std::move(parser), + path_id = path.id, + original_request = std::move(request), + cb = std::move(callback)]( + bool success, bool timeout, int16_t status, auto headers, auto response) { + auto self = weak_self.lock(); + if (!self) + return; - try { - if (!success) - throw std::runtime_error{response.value_or("Unknown request failure")}; - if (timeout) - throw std::runtime_error{response.value_or("Timed out")}; - if (!response) - throw std::runtime_error{"Unexpected empty response"}; - - onionreq::DecryptedResponse decrypted = parser->decrypted_response(*response); - _handle_transport_response( - path_id, - std::move(original_request), - true, - false, - decrypted.status_code, - std::move(decrypted.headers), - std::move(decrypted.body), - std::move(cb)); - } catch (const std::exception& e) { - _handle_transport_response( - path_id, - std::move(original_request), - false, - timeout, - status, - std::move(headers), - std::move("Failed to handle onion response due to error: {}"_format(e.what())), - std::move(cb)); - } - }; + try { + if (!success) + throw std::runtime_error{response.value_or("Unknown request failure")}; + if (timeout) + throw std::runtime_error{response.value_or("Timed out")}; + if (!response) + throw std::runtime_error{"Unexpected empty response"}; + + onionreq::DecryptedResponse decrypted = parser->decrypted_response(*response); + _handle_transport_response( + path_id, + std::move(original_request), + true, + false, + decrypted.status_code, + std::move(decrypted.headers), + std::move(decrypted.body), + std::move(cb)); + } catch (const std::exception& e) { + _handle_transport_response( + path_id, + std::move(original_request), + false, + timeout, + response::undecrypted_status(status), + std::move(headers), + "Failed to handle onion response (status {}) due to error: {}"_format( + status, e.what()), + std::move(cb)); + } + }; transport->send_request(std::move(onion_request), std::move(decryption_callback)); } @@ -2220,13 +2297,14 @@ void OnionRequestRouter::_rotate_path(const std::string& path_id, PathCategory c } // Get enough nodes for the path (if the edge node has been used for longer than the cache - // duration then we should create an entirely new path, otherwise we should try to reuse the - // edge node) + // duration, or has been struck out since we connected to it, then we should create an entirely + // new path, otherwise we should try to reuse the edge node) auto now = std::chrono::system_clock::now(); auto rotate_at = (std::chrono::steady_clock::now() + _config.path_rotation_frequency); std::vector rotated_path_nodes; - if (now > path.edge_first_connected_at + _config.edge_node_cache_duration) + if (now > path.edge_first_connected_at + _config.edge_node_cache_duration || + snode_pool->node_struck_out(edge_node)) rotated_path_nodes = snode_pool->get_unused_nodes(_config.path_length, nodes_to_exclude); else { rotated_path_nodes = diff --git a/src/network/routing/session_router_router.cpp b/src/network/routing/session_router_router.cpp index 7198ea901..323351071 100644 --- a/src/network/routing/session_router_router.cpp +++ b/src/network/routing/session_router_router.cpp @@ -156,7 +156,15 @@ void SessionRouter::_init() { if (snode_pool->size() == 0) // The pool outlives us, so this one keeps its weak guard. - snode_pool->refresh_if_needed({}, [weak_self, this] { + snode_pool->refresh_if_needed({}, [weak_self, this](bool refreshed) { + // Setup finishes either way: not finishing leaves the router + // permanently unusable, where finishing with an empty pool just means + // the first request refreshes again + if (!refreshed) + log::warning( + cat, + "Finishing router setup without a refreshed snode pool."); + if (auto self = weak_self.lock()) _jq.call([this] { _finish_setup(); }); }); @@ -653,11 +661,19 @@ void SessionRouter::_send_proxy_request(Request request, network_response_callba [weak_self = weak_from_this(), this, req = std::move(request), - cb = std::move(callback)]() { + cb = std::move(callback)](bool refreshed) { auto self = weak_self.lock(); if (!self) return; + if (!refreshed) + return cb( + false, + false, + ERROR_INSUFFICIENT_NODES, + {content_type_plain_text}, + "Failed to refresh the snode pool to find a proxy."); + auto snode_pool = _snode_pool.lock(); if (!snode_pool) return cb( @@ -671,7 +687,7 @@ void SessionRouter::_send_proxy_request(Request request, network_response_callba return cb( false, false, - -1, + ERROR_INSUFFICIENT_NODES, {content_type_plain_text}, "SnodePool refresh failed."); @@ -718,32 +734,35 @@ void SessionRouter::_send_proxy_request(Request request, network_response_callba request.time_remaining(), request.overall_timeout}; - auto proxy_callback = - [parser = std::move(parser), cb = std::move(callback)]( - bool success, bool timeout, int16_t status, auto headers, auto response) { - try { - if (!success) - throw std::runtime_error{response.value_or("Unknown request failure")}; - if (timeout) - throw std::runtime_error{response.value_or("Timed out")}; - if (!response) - throw std::runtime_error{"Unexpected empty response"}; - - onionreq::DecryptedResponse decrypted = parser->decrypted_response(*response); - cb(true, - false, - decrypted.status_code, - std::move(decrypted.headers), - std::move(decrypted.body)); - } catch (const std::exception& e) { - cb(false, - timeout, - status, - std::move(headers), - "Failed to handle proxied request response due to error: {}"_format( - e.what())); - } - }; + auto proxy_callback = [parser = std::move(parser), cb = std::move(callback)]( + bool success, + bool timeout, + int16_t status, + auto headers, + auto response) { + try { + if (!success) + throw std::runtime_error{response.value_or("Unknown request failure")}; + if (timeout) + throw std::runtime_error{response.value_or("Timed out")}; + if (!response) + throw std::runtime_error{"Unexpected empty response"}; + + onionreq::DecryptedResponse decrypted = parser->decrypted_response(*response); + cb(true, + false, + decrypted.status_code, + std::move(decrypted.headers), + std::move(decrypted.body)); + } catch (const std::exception& e) { + cb(false, + timeout, + response::undecrypted_status(status), + std::move(headers), + "Failed to handle proxied request response (status {}) due to error: {}"_format( + status, e.what())); + } + }; // Now that we have a service_node destination we can send a direct request _send_direct_request(std::move(proxy_request), std::move(proxy_callback)); diff --git a/src/network/session_network.cpp b/src/network/session_network.cpp index 0ce2efe1f..fceacc95d 100644 --- a/src/network/session_network.cpp +++ b/src/network/session_network.cpp @@ -1,6 +1,7 @@ #include "session/network/session_network.hpp" #include +#include #include #include @@ -372,12 +373,14 @@ void Network::suspend() { _jq->call_get([this] { _suspended = true; + // The router before the transport, so that it has let go of its path builds and failure + // listeners before the transport closes the connections they're attached to if (_snode_pool) _snode_pool->suspend(); - if (_transport) - _transport->suspend(); if (_router) _router->suspend(); + if (_transport) + _transport->suspend(); _close_connections(); }); @@ -489,8 +492,30 @@ void Network::get_random_nodes( std::vector nodes_to_exclude = _router->get_all_used_nodes(); return _snode_pool->refresh_if_needed( - nodes_to_exclude, - [this, count, cb = std::move(cb)] { get_random_nodes(count, cb); }); + nodes_to_exclude, [this, count, cb = std::move(cb)](bool refreshed) { + if (!refreshed) { + log::warning( + cat, + "Cannot get {} random nodes: the pool could not be refreshed.", + count); + return cb({}); + } + + // `refreshed` includes nothing having needed refreshing, which calls back + // inline, so asking again of a pool that can't supply `count` would + // re-enter this branch until the stack gives out + auto nodes = _snode_pool->get_unused_nodes(count); + if (nodes.size() < count) { + log::warning( + cat, + "Cannot get {} random nodes: the pool has only {} to give.", + count, + nodes.size()); + return cb({}); + } + + cb(std::move(nodes)); + }); } cb(unused_nodes); }); @@ -534,20 +559,34 @@ void Network::send_request(Request request, network_response_callback_t callback const auto dest_is_snode = std::holds_alternative(original_req.destination); + // Parsed once for everything below, since a retrieve's body can be large + std::optional json; + if (body) + if (auto parsed = nlohmann::json::parse(*body, nullptr, false); + !parsed.is_discarded()) + json = std::move(parsed); + // If we got a successful response (with a body) and the request was sent to a // service node then we should update the network state based on the response // (Note: we don't want to do this for server requests because they could // include values in different formats, eg. the "Session Network" API returns // `t` in seconds) - if (success && body && dest_is_snode) - _update_network_state(*body); + if (success && json && dest_is_snode) + _update_network_state(*json); int16_t final_status_code = status_code; - if (body) - if (auto uniform_error = response::find_uniform_batch_error(*body)) + if (json) + if (auto uniform_error = response::uniform_batch_error(*json)) final_status_code = *uniform_error; + // Taken from every snode response rather than only a 421 one: a batch can be + // rejected for some accounts and answered for others + response::swarm_rejections rejections; + if (dest_is_snode) + rejections = + _take_swarm_redirects(original_req, json ? &*json : nullptr, status_code); + // If we got a 406 from a snode, or a 425 from a server, then the device clock // is out of sync so we need to kick off a clock resync request if ((final_status_code == ERROR_NOT_ACCEPTABLE && dest_is_snode) || @@ -556,13 +595,17 @@ void Network::send_request(Request request, network_response_callback_t callback return; } - // A 421 says this node does not hold the account we asked about, and its body - // carries the swarm that does. Take the correction -- it is our cache and the - // answer is authoritative -- but do not act on it: which member to ask next, - // and whether to ask at all, is the caller's to decide, and only the caller - // can know which node it ended up talking to. - if (final_status_code == 421 && dest_is_snode && original_req.swarm_pubkey && body) - _adopt_swarm_from_421(*original_req.swarm_pubkey, *body); + if (final_status_code == ERROR_MISDIRECTED_REQUEST) { + _handle_421( + std::move(original_req), + std::move(rejections), + std::move(headers), + std::move(body), + std::move(cb)); + return; + } + + _refresh_if_unredirected(rejections); // `final_status_code`, not the raw one: a batch whose subrequests all failed // the same way arrives here as a transport-level 200, and reporting that @@ -688,10 +731,13 @@ void Network::download(DownloadRequest request) { // MARK: Internal Logic void Network::_close_connections() { - if (_transport) - _transport->close_connections(); + // The router first, for the same reason as in `suspend`: otherwise each edge connection the + // transport closes fires a failure listener into a live router, which retires the path and + // starts rebuilding it if (_router) _router->close_connections(); + if (_transport) + _transport->close_connections(); _recalculate_status(); log::info(cat, "Closed all connections."); @@ -784,44 +830,22 @@ Request Network::_preprocess_request(Request request) { return request; } -void Network::_update_network_state(const std::string& body) { - // Not every storage server endpoint answers in JSON: `monitor` is handled outside the RPC - // dispatch and replies with bt, which carries no clock or fork versions to read anyway. - // Recognised rather than parsed and complained about, since a subscription renews on a timer - // and would otherwise log a warning every time. - if (!body.empty() && (body.front() == 'd' || body.front() == 'l')) - return; - +void Network::_update_network_state(const nlohmann::json& json) { try { - auto json = nlohmann::json::parse(body); const nlohmann::json* target_json = &json; // If it was a batch/sequence request then take the one with the highest "t" value as that // would have been the one which was returned last - if (json.contains("results") && json["results"].is_array()) { - log::trace(cat, "Parsing batch response for latest network state."); - - int64_t max_t = -1; - const nlohmann::json* latest_body = nullptr; - - for (const auto& result : json["results"]) { - if (!result.is_object() || !result.contains("body") || !result["body"].is_object()) - continue; - - const auto& result_body = result["body"]; - - if (result_body.contains("t") && result_body["t"].is_number()) { - int64_t current_t = result_body["t"].get(); - - if (current_t > max_t) { - max_t = current_t; - latest_body = &result_body; - } + int64_t max_t = -1; + for (const auto& sub : response::subresponses(json)) { + if (!sub.body) + continue; + + if (auto t = sub.body->find("t"); t != sub.body->end() && t->is_number()) + if (auto current_t = t->get(); current_t > max_t) { + max_t = current_t; + target_json = sub.body; } - } - - if (latest_body) - target_json = latest_body; } // Update hardfork/softfork versions @@ -870,46 +894,99 @@ void Network::_update_network_state(const std::string& body) { // MARK: Specific Error Handling -// Takes the swarm a 421 hands back and writes it into the cache, so that whoever decides to try -// again resolves against the corrected membership rather than the stale one that misdirected us. -// -// Only the cache is touched. Choosing another member, or giving up, is the caller's: it is the -// only party that can know which node it ended up talking to, and a substitution made down here -// is invisible to it. -void Network::_adopt_swarm_from_421(const x25519_pubkey& swarm_pubkey, std::string_view body) { - try { - auto json = nlohmann::json::parse(body); +// A node that rejects a request for an account usually names the swarm it actually belongs to. +// Taking its word (bounded - see `record_swarm_redirect`) fixes the one mapping we know is wrong, +// where refreshing has every client of a changed swarm fetch the full node list for it. +response::swarm_rejections Network::_take_swarm_redirects( + const Request& request, const nlohmann::json* json, int16_t status_code) { + auto rejections = response::find_swarm_rejections(json, status_code, request.swarm_pubkeys); - // A batch collapses to a uniform 421, in which case the swarm sits inside the first - // subrequest's body rather than at the top level. - if (auto results = json.find("results"); - results != json.end() && results->is_array() && !results->empty()) - if (auto b = results->front().find("body"); b != results->front().end()) - json = *b; + for (auto& [account, keys] : rejections.accounts) + if (!keys.empty() && !_snode_pool->record_swarm_redirect(account, keys)) + keys.clear(); - auto snodes = json.find("snodes"); - if (snodes == json.end() || !snodes->is_array() || snodes->empty()) - return; + return rejections; +} - std::vector nodes; - nodes.reserve(snodes->size()); - for (const auto& n : *snodes) - nodes.push_back(service_node::from_json(n)); +// With no usable redirect the pool itself is the only thing that can put a rejection right, and +// one refresh re-resolves every account at once +void Network::_refresh_if_unredirected(const response::swarm_rejections& rejections) { + for (const auto& [account, keys] : rejections.accounts) + if (keys.empty()) + return _snode_pool->invalidate_swarm(account); +} - swarm::swarm_id_t swarm_id = swarm::INVALID_SWARM_ID; - if (auto s = json.find("swarm"); s != json.end() && s->is_string()) - swarm_id = std::stoull(s->get(), nullptr, 16); +// The caller retries a 421 by re-resolving the account's swarm, so the 421 is reported only once +// that would give a different answer: straight away when a redirect was taken, and after the +// refresh when one has to run. A rejection nothing can correct is reported as +// ERROR_SWARM_UNRESOLVED instead, because re-resolving it would return the swarm that just +// rejected us. +void Network::_handle_421( + Request original_request, + response::swarm_rejections rejections, + std::vector> headers, + std::optional body, + network_response_callback_t final_callback) { + // Only a node's rejection says anything about a swarm + if (!std::holds_alternative(original_request.destination)) + return final_callback( + false, false, ERROR_MISDIRECTED_REQUEST, std::move(headers), std::move(body)); + + if (rejections.accounts.empty()) { + log::warning( + cat, + "Request {} received 421 but names no account to re-resolve.", + original_request.request_id); + return final_callback( + false, + false, + ERROR_SWARM_UNRESOLVED, + {content_type_plain_text}, + "421 Misdirected Request for a request with no swarm"); + } + // A retry goes to a single swarm, which a batch spanning several accounts doesn't have. Their + // redirects are already taken, so the next request for each goes to the right place. + if (rejections.accounts.size() > 1 || rejections.unattributed) { log::info( cat, - "Adopting the {}-node swarm a 421 reported for {}", - nodes.size(), - swarm_pubkey.hex()); - - _snode_pool->set_swarm(swarm_pubkey, swarm_id, std::move(nodes)); - } catch (const std::exception& e) { - log::warning(cat, "Could not read the swarm out of a 421 response: {}", e.what()); + "Request {} received 421s for {} accounts.", + original_request.request_id, + rejections.accounts.size()); + _refresh_if_unredirected(rejections); + return final_callback( + false, false, ERROR_MISDIRECTED_REQUEST, std::move(headers), std::move(body)); } + + auto [swarm_pubkey, redirect] = *rejections.accounts.begin(); + + if (!redirect.empty()) + return final_callback( + false, false, ERROR_MISDIRECTED_REQUEST, std::move(headers), std::move(body)); + + log::info( + cat, + "Request {} received 421 with no usable redirect; re-resolving the swarm of {}.", + original_request.request_id, + swarm_pubkey.hex()); + + _snode_pool->invalidate_swarm( + swarm_pubkey, + [cb = std::move(final_callback), headers = std::move(headers), body = std::move(body)]( + bool swarm_resolved) mutable { + // Without a re-resolve there is nothing better than the mapping the 421 disproved + // - a redirect naming any node we know would have been taken instead. The + // refresh has been asked for, and the account's next rejection asks again. + if (!swarm_resolved) + return cb( + false, + false, + ERROR_SWARM_UNRESOLVED, + {content_type_plain_text}, + "421 Misdirected Request, and the swarm could not be re-resolved"); + + cb(false, false, ERROR_MISDIRECTED_REQUEST, std::move(headers), std::move(body)); + }); } void Network::_resync_clock( @@ -965,7 +1042,20 @@ void Network::_resync_clock( // Refresh the snode pool if needed to ensure we have the most up-to-date cache std::vector nodes_to_exclude = _router->get_all_used_nodes(); - _snode_pool->refresh_if_needed(std::move(nodes_to_exclude), [this, request_id] { + _snode_pool->refresh_if_needed(std::move(nodes_to_exclude), [this, request_id](bool refreshed) { + // `_current_clock_resync_id` was set before this call, so giving up without clearing it + // blocks every later resync attempt for the life of the process and strands everything + // queued behind it. Completing with no results takes the existing "resync finished, + // successful or not" path, which does both and leaves the offset we already had alone - + // an old offset beats none, and this says nothing about whether it was right. + if (!refreshed) { + log::warning( + cat, + "[Request {}] Abandoning clock resync: the snode pool could not be refreshed.", + request_id); + return _on_clock_resync_complete(); + } + // Pick the random nodes we want to use for retrying (these won't change for this resync // attempt) auto resync_nodes = @@ -1072,7 +1162,7 @@ void Network::_launch_next_clock_out_of_sync_request( // If we've received all the results then we need to process them and complete the // resync if (_clock_resync_results.size() >= total_requests) - _on_clock_resync_complete(total_requests); + _on_clock_resync_complete(); }); } @@ -1105,7 +1195,7 @@ std::optional detail::resync_offset( return median; } -void Network::_on_clock_resync_complete(const uint8_t /*total_requests*/) { +void Network::_on_clock_resync_complete() { auto raw_results = std::move(_clock_resync_results); auto refresh_id = std::move(*_current_clock_resync_id); @@ -1695,8 +1785,17 @@ LIBSESSION_C_API void session_network_send_request( std::nullopt, request_id}; + std::optional swarm_pubkey; if (params->swarm_pubkey_hex) - request.swarm_pubkey = x25519_pubkey::from_hex({params->swarm_pubkey_hex, 64}); + swarm_pubkey = x25519_pubkey::from_hex({params->swarm_pubkey_hex, 64}); + + std::optional>> batch_accounts; + if (request.body) + batch_accounts = batch_request_accounts(request.endpoint, *request.body, swarm_pubkey); + if (batch_accounts) + request.swarm_pubkeys = std::move(*batch_accounts); + else if (swarm_pubkey) + request.swarm_pubkeys = {*swarm_pubkey}; auto cpp_callback = [c_cb = callback, c_ctx = ctx]( bool success, diff --git a/src/network/session_network_types.cpp b/src/network/session_network_types.cpp index b49c8deec..b41080d07 100644 --- a/src/network/session_network_types.cpp +++ b/src/network/session_network_types.cpp @@ -73,35 +73,170 @@ std::optional> response::parse_text_error(std::string_v return std::nullopt; } +namespace { + inline auto cat = log::Cat("network"); + + const nlohmann::json* field( + const nlohmann::json& j, + std::string_view key, + bool (nlohmann::json::*is_kind)() const noexcept) { + auto it = j.find(key); + return it != j.end() && ((*it).*is_kind)() ? &*it : nullptr; + } + + std::optional account_in(const nlohmann::json& obj) { + auto pk = field(obj, "pubkey", &nlohmann::json::is_string); + if (!pk) + return std::nullopt; + + // Prefixed with the network id, except on testnet + auto hex = pk->get(); + if (hex.size() == 66) + hex.remove_prefix(2); + return x25519_pubkey::maybe_from_hex(hex); + } + + // Only the pubkeys: the rest of each record is contact information we deliberately don't read, + // so a redirect can't put us in touch with anything the pool hasn't already told us about. + std::vector redirect_keys(const nlohmann::json& body) { + std::vector keys; + + if (auto snodes = field(body, "snodes", &nlohmann::json::is_array)) + for (const auto& snode : *snodes) + if (auto pk = field(snode, "pubkey_ed25519", &nlohmann::json::is_string)) + if (auto key = ed25519_pubkey::maybe_from_hex(pk->get())) + keys.push_back(*key); + + return keys; + } + + std::optional account_by_position( + std::span> accounts, size_t index) { + if (accounts.size() == 1) + return accounts.front(); + return index < accounts.size() ? accounts[index] : std::nullopt; + } +} // namespace + +int16_t response::undecrypted_status(int16_t status) { + switch (status) { + case ERROR_NOT_ACCEPTABLE: + case ERROR_MISDIRECTED_REQUEST: + case ERROR_TOO_EARLY: return ERROR_UNAUTHENTICATED_RESPONSE; + default: return status; + } +} + std::optional response::find_uniform_batch_error(std::string_view body) { try { - auto json = nlohmann::json::parse(body); + return uniform_batch_error(nlohmann::json::parse(body)); + } catch (...) { /* Do nothing */ + } + + return std::nullopt; +} - // If it wasn't a batch response then just handle the non-batch status code - if (json.contains("results") && json["results"].is_array() && !json["results"].empty()) { - int16_t first_status_code = -1; +std::optional response::uniform_batch_error(const nlohmann::json& json) { + std::optional uniform; - for (const auto& result : json["results"]) { - if (!result.contains("code") || !result["code"].is_number()) - return std::nullopt; + // A response that isn't a batch has no per-result codes, so its own status stands + for (const auto& sub : subresponses(json)) { + if (!sub.code || (*sub.code >= 200 && *sub.code <= 299)) + return std::nullopt; + if (uniform && *uniform != *sub.code) + return std::nullopt; + uniform = sub.code; + } - // If we got a success then we can just use the original status code - int16_t code = result["code"].get(); - if (code >= 200 && code <= 299) - return std::nullopt; + return uniform; +} - if (first_status_code == -1) - first_status_code = code; - else if (first_status_code != code) - return std::nullopt; - } +std::vector response::subresponses(const nlohmann::json& json) { + auto results = field(json, "results", &nlohmann::json::is_array); + if (!results) + return {{std::nullopt, json.is_object() ? &json : nullptr}}; - return first_status_code; + std::vector subs; + subs.reserve(results->size()); + + for (const auto& result : *results) { + auto& sub = subs.emplace_back(); + if (auto code = field(result, "code", &nlohmann::json::is_number)) + sub.code = code->get(); + sub.body = field(result, "body", &nlohmann::json::is_object); + } + + return subs; +} + +std::optional>> batch_request_accounts( + std::string_view endpoint, + std::span body, + std::optional fallback) { + if (endpoint != "batch" && endpoint != "sequence") + return std::nullopt; + + auto json = nlohmann::json::parse(to_string_view(body), nullptr, false); + auto requests = field(json, "requests", &nlohmann::json::is_array); + if (!requests) + return std::nullopt; + + std::vector> accounts; + accounts.reserve(requests->size()); + + for (const auto& req : *requests) { + auto& account = accounts.emplace_back(); + if (auto params = field(req, "params", &nlohmann::json::is_object)) + account = account_in(*params); + if (!account) + account = fallback; + } + + return accounts; +} + +response::swarm_rejections response::find_swarm_rejections( + const nlohmann::json* json, + int16_t status_code, + std::span> accounts) { + swarm_rejections result; + + // A body that isn't JSON still leaves the response's own status to act on, just with no + // redirect to go with it + auto subs = json ? subresponses(*json) : std::vector{{}}; + + for (size_t i = 0; i < subs.size(); ++i) { + const auto& [code, sub_body] = subs[i]; + if (code.value_or(status_code) != ERROR_MISDIRECTED_REQUEST) + continue; + + // Attributed by position in our own request, never by the account the 421 names: that is + // the responding node's word, and taking it would let any node we talk to redirect any + // account it likes - not just the ones it was asked about - onto nodes of its choosing + auto account = account_by_position(accounts, i); + if (!account) { + result.unattributed = true; + continue; } - } catch (...) { /* Do nothing */ + + if (auto echoed = sub_body ? account_in(*sub_body) : std::nullopt; + echoed && *echoed != *account) { + log::warning( + cat, + "Ignoring a 421 for {} that names {} as the rejected account.", + account->hex(), + echoed->hex()); + result.unattributed = true; + continue; + } + + // Several sub-requests for one account (a retrieve per namespace, say) all name its swarm, + // so the first is as good as any + if (auto [it, inserted] = result.accounts.try_emplace(*account); inserted && sub_body) + it->second = redirect_keys(*sub_body); } - return std::nullopt; + return result; } } // namespace session::network diff --git a/src/network/snode_pool.cpp b/src/network/snode_pool.cpp index 5fa58d5d5..85d63b9cc 100644 --- a/src/network/snode_pool.cpp +++ b/src/network/snode_pool.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -45,6 +46,25 @@ namespace { const std::chrono::seconds STRIKE_EXPIRY = 48h; const std::chrono::seconds SAVE_THROTTLE = 5min; + + // A swarm rejection is evidence against the pool snapshot the swarm was derived from, so it is + // only worth acting on once that snapshot is old enough for a refresh to plausibly return + // something different. + const std::chrono::seconds EVIDENCE_REFRESH_MIN_POOL_AGE = 1min; + + // A rejection arriving *after* we already refreshed on one is the refresh telling us it didn't + // help - the network hasn't settled, or the node is lying - so each successive one waits twice + // as long, up to `cache_expiration`. A single 3-node refresh per minute sustained indefinitely + // is not an acceptable resting state for a client on a bad connection, and without this it is + // exactly what a persistent rejection source would produce. + const std::chrono::seconds EVIDENCE_REFRESH_BASE_BACKOFF = 1min; + + // An account redirected more than this many times within one pool generation is being bounced + // between nodes that disagree, or its swarm has moved on too far for our pool to keep up. A + // redirect is still the best information we have, so past it each one is still followed, and + // also asks for the refresh that can settle it. Legitimate rearrangements count too (nothing + // resets this short of a refresh), hence the headroom. + constexpr uint8_t SWARM_REDIRECTS_BEFORE_REFRESH = 8; } // namespace SnodePool::SnodePool( @@ -346,6 +366,10 @@ void SnodePool::_refresh_snode_cache(std::optional request_id_opt) _jq.call([this, request_id_opt] { if (_suspended) { log::info(cat, "Ignoring refresh as pool is suspended."); + + // Anything queued against a refresh we are declining to start has nothing left to wait + // for: suspending abandons any refresh in progress, so none can answer it later + _run_pending_refresh_callbacks(false); return; } @@ -423,6 +447,7 @@ void SnodePool::_refresh_snode_cache(std::optional request_id_opt) (use_seed_nodes ? "No seed nodes are configured!" : "Found no nodes and decided not to use seed nodes!")); _current_snode_cache_refresh_id.reset(); + _run_pending_refresh_callbacks(false); return; } @@ -445,7 +470,9 @@ void SnodePool::_launch_next_refresh_request( refreshing_from_seed_nodes, use_direct_fetcher, total_requests] { - if (!_current_snode_cache_refresh_id) + // A retry scheduled for a refresh that has since been abandoned or replaced mustn't touch + // the one in its place - its candidates in particular + if (_current_snode_cache_refresh_id != request_id) return; const auto target_request_id = "{}-{}"_format(request_id, index); @@ -551,10 +578,16 @@ void SnodePool::_launch_next_refresh_request( "trying again in {}ms.", target_request_id, delay.count()); - _jq.call_later(delay, [this] { + _jq.call_later(delay, [this, request_id] { // We need to wait until after the `call_later` to reset the `refresh_id` (and clear // previous results) as if we don't then additional refreshes could be triggered // during the delay + + // Abandoned (by a suspend) or replaced during the delay: resetting the id would + // wipe out whichever refresh has it now, and there is nothing of ours to restart + if (_current_snode_cache_refresh_id != request_id) + return; + _current_snode_cache_refresh_id.reset(); _snode_refresh_results.clear(); _refresh_snode_cache(); @@ -573,6 +606,7 @@ void SnodePool::_launch_next_refresh_request( cat, "[Request {}] No fetcher available, aborting refresh.", target_request_id); _current_snode_cache_refresh_id.reset(); _refresh_candidate_nodes.clear(); + _run_pending_refresh_callbacks(false); return; } @@ -879,6 +913,11 @@ void SnodePool::_update_cache(std::string refresh_id, std::vector _snode_cache = std::move(nodes); _all_swarms = swarm::generate_swarms(_snode_cache); _swarm_cache.clear(); + + // The pool these redirects were correcting has been replaced, so they have outlived what + // they were for. Keeping them would let one node's claim outlast the ground truth that + // would have overruled it. + _swarm_overrides.clear(); _last_snode_cache_update = std::chrono::system_clock::now(); // Reset all failure and refresh-in-progress state @@ -891,28 +930,35 @@ void SnodePool::_update_cache(std::string refresh_id, std::vector SnodePool::_perform_cache_write(path, cache); }); - // Trigger any callbacks - // - // These must be moved out of the member before being run: a callback can re-enter the pool - // and register another post-refresh callback (`get_swarm` does exactly that if the cache is - // still empty), which would reallocate the vector we're iterating and leave us calling - // through a freed `std::function`. Anything registered while we're here accumulates in the - // now-empty member and runs after the next refresh instead of being silently discarded. - if (!_after_snode_cache_refresh.empty()) { - auto callbacks = std::move(_after_snode_cache_refresh); - _after_snode_cache_refresh.clear(); // A moved-from vector is valid but unspecified + _run_pending_refresh_callbacks(true); + }); +} + +void SnodePool::_run_pending_refresh_callbacks(bool refreshed) { + if (_after_snode_cache_refresh.empty()) + return; - log::debug(cat, "Executing {} post-refresh callbacks.", callbacks.size()); + // These must be moved out of the member before being run: a callback can re-enter the pool and + // register another post-refresh callback (`get_swarm` does exactly that if the cache is still + // empty), which would reallocate the vector we're iterating and leave us calling through a + // freed `std::function`. Anything registered while we're here accumulates in the now-empty + // member and runs after the next refresh instead of being silently discarded. + auto callbacks = std::move(_after_snode_cache_refresh); + _after_snode_cache_refresh.clear(); // A moved-from vector is valid but unspecified - for (const auto& cb : callbacks) { - try { - cb(); - } catch (const std::exception& e) { - log::error(cat, "Exception thrown in a post-refresh callback: {}", e.what()); - } - } + log::debug( + cat, + "Executing {} post-refresh callbacks ({}).", + callbacks.size(), + (refreshed ? "refreshed" : "refresh did not happen")); + + for (const auto& cb : callbacks) { + try { + cb(refreshed); + } catch (const std::exception& e) { + log::error(cat, "Exception thrown in a post-refresh callback: {}", e.what()); } - }); + } } // MARK: Public Functions @@ -922,6 +968,22 @@ void SnodePool::suspend() { _jq.call_get([this] { _suspended = true; + // A refresh in progress can only fail from here on, since every fetch is refused while + // suspended, so it is abandoned rather than left to work its way through the candidates, + // and whatever waits on it is answered now. The failures it built up are dropped too: + // they say nothing about the network we resume on. + if (_current_snode_cache_refresh_id) { + log::info( + cat, + "[Request {}] Abandoning cache refresh for suspension.", + *_current_snode_cache_refresh_id); + _current_snode_cache_refresh_id.reset(); + _refresh_candidate_nodes.clear(); + _snode_refresh_results.clear(); + _snode_cache_refresh_failure_count = 0; + _run_pending_refresh_callbacks(false); + } + // Force a strike write immediately if we had one scheduled if (_strikes_flush_scheduled) _disk_loop.call([path = _strikes_file_path, strikes = _snode_strikes] { @@ -960,11 +1022,31 @@ void SnodePool::clear_cache() { _snode_cache = {}; _all_swarms = {}; _swarm_cache = {}; + _swarm_overrides = {}; _disk_loop.call([path = _snode_cache_file_path] { SnodePool::_clear_disk_cache(path); }); }); } +size_t SnodePool::_active_strike_count(const ed25519_pubkey& key) const { + auto it = _snode_strikes.find(key); + + if (it == _snode_strikes.end()) + return 0; + + auto threshold = clock_now_s() - STRIKE_EXPIRY; + + return std::ranges::count_if(it->second, [threshold](auto t) { return t > threshold; }); +} + +bool SnodePool::_node_struck_out(const ed25519_pubkey& key) const { + auto strikes = _active_strike_count(key); + + // The `strikes > 0` is what keeps a threshold of 0 meaning "drop a node on its first strike"; + // comparing straight against 0 also drops every node that has never failed at all + return (strikes > 0 && strikes >= _config.cache_node_strike_threshold); +} + void SnodePool::record_node_failure(const service_node& node, bool permanent) { record_node_failure(node.remote_pubkey, permanent); } @@ -972,18 +1054,17 @@ void SnodePool::record_node_failure(const service_node& node, bool permanent) { void SnodePool::record_node_failure(const ed25519_pubkey& key, bool permanent) { _jq.call([this, key, permanent] { auto now = clock_now_s(); + auto& stamps = _snode_strikes[key]; + std::erase_if(stamps, [threshold = now - STRIKE_EXPIRY](auto t) { return t <= threshold; }); - if (permanent) - for (int i = 0; i < _config.cache_node_strike_threshold; ++i) - _snode_strikes[key].push_back(now); - else - _snode_strikes[key].push_back(now); + // A permanent failure has to strike the node out whatever the threshold is - looping up to + // a threshold of 0 records nothing and leaves the node in rotation + auto strikes = (permanent ? std::max(1, _config.cache_node_strike_threshold) : 1); - log::trace( - cat, - "Recorded strike for node {}, total: {}", - key.hex(), - _snode_strikes[key].size()); + for (uint16_t i = 0; i < strikes; ++i) + stamps.push_back(now); + + log::trace(cat, "Recorded strike for node {}, total: {}", key.hex(), stamps.size()); // Throttle persisting the strikes to disk to at most every X minutes if (!_strikes_flush_scheduled && !_suspended) { @@ -1008,22 +1089,15 @@ uint16_t SnodePool::node_strike_count(const service_node& node) { } uint16_t SnodePool::node_strike_count(const ed25519_pubkey& key) { - return _jq.call_get([this, &key] { - auto it = _snode_strikes.find(key); - if (it == _snode_strikes.end()) - return uint16_t{0}; - - const auto& stamps = it->second; - - const auto threshold = clock_now_s() - STRIKE_EXPIRY; + return _jq.call_get([this, &key] { return static_cast(_active_strike_count(key)); }); +} - uint16_t count = 0; - for (auto t : stamps) - if (t > threshold) - count++; +bool SnodePool::node_struck_out(const service_node& node) { + return node_struck_out(node.remote_pubkey); +} - return count; - }); +bool SnodePool::node_struck_out(const ed25519_pubkey& key) { + return _jq.call_get([this, &key] { return _node_struck_out(key); }); } void SnodePool::clear_node_strikes() { @@ -1039,10 +1113,13 @@ void SnodePool::clear_node_strikes() { } void SnodePool::refresh_if_needed( - const std::vector& in_use_nodes, std::function on_refresh_complete) { + const std::vector& in_use_nodes, refresh_callback_t on_refresh_complete) { _jq.call([this, in_use_nodes, cb = std::move(on_refresh_complete)] { if (_suspended) { log::info(cat, "Ignoring refresh as pool is suspended."); + + if (cb) + cb(false); return; } @@ -1067,9 +1144,7 @@ void SnodePool::refresh_if_needed( in_use_keys.insert(node.remote_pubkey); for (const auto& node : _snode_cache) { - auto it = _snode_strikes.find(node.remote_pubkey); - if (it != _snode_strikes.end() && - it->second.size() >= _config.cache_node_strike_threshold) + if (_node_struck_out(node.remote_pubkey)) continue; // If the caller considers the node as already in use then it wouldn't be @@ -1105,7 +1180,159 @@ void SnodePool::refresh_if_needed( } else _refresh_snode_cache(); else if (!already_running && cb) - cb(); + // Nothing needed refreshing, which is the answer the caller wanted rather than a + // failure to get one + cb(true); + }); +} + +void SnodePool::invalidate_swarm(x25519_pubkey swarm_pubkey, refresh_callback_t on_complete) { + _jq.call([this, swarm_pubkey, cb = std::move(on_complete)]() mutable { + if (_suspended) { + log::info(cat, "Ignoring swarm invalidation as pool is suspended."); + + if (cb) + cb(false); + return; + } + + // The swarm cache only ever memoises `swarm::get_swarm(pubkey, _all_swarms)`, and + // `_all_swarms` is generated from the pool, so dropping the single entry would recompute + // the same rejected answer. What the rejection actually disproves is the pool snapshot, + // and a refresh is the only thing that replaces it - clearing the swarm cache as it goes. + auto now = std::chrono::system_clock::now(); + + if (!_current_snode_cache_refresh_id) { + // The backoff is deliberately global rather than per-swarm: a refresh replaces the pool + // every swarm is derived from, so a rejection for one swarm is exactly as unhelpful to + // act on right after a refresh as a second rejection for the swarm that prompted it + auto pool_age = now - _last_snode_cache_update; + auto since_last = now - _last_evidence_refresh; + + // Quiet for twice the interval we were holding means whatever caused the last run is + // over, so the next incident starts from the base delay rather than inheriting it + if (since_last > 2 * _evidence_refresh_backoff) + _evidence_refresh_backoff = 0s; + + if (pool_age < EVIDENCE_REFRESH_MIN_POOL_AGE || since_last < _evidence_refresh_backoff) + log::debug( + cat, + "Swarm {} was rejected, but the pool is {}s old and the last refresh on a " + "rejection was {}s ago (backoff {}s); leaving it alone.", + swarm_pubkey.hex(), + std::chrono::duration_cast(pool_age).count(), + std::chrono::duration_cast(since_last).count(), + _evidence_refresh_backoff.count()); + else { + _evidence_refresh_backoff = std::min( + std::chrono::seconds{_config.cache_expiration}, + (_evidence_refresh_backoff == 0s ? EVIDENCE_REFRESH_BASE_BACKOFF + : _evidence_refresh_backoff * 2)); + _last_evidence_refresh = now; + + log::info( + cat, + "Swarm {} was rejected by a node we had in it, refreshing the pool (next " + "rejection-driven refresh no sooner than {}s from now).", + swarm_pubkey.hex(), + _evidence_refresh_backoff.count()); + _refresh_snode_cache(); + } + } + + if (!cb) + return; + + // `_refresh_snode_cache` runs inline here (we are on the loop thread) and can decline to + // start, so it is the refresh id - not the call above - that says whether there is anything + // to wait for. A callback queued against a refresh that never started never runs, and on + // this path that would strand the request that triggered the rejection. + if (_current_snode_cache_refresh_id) + _after_snode_cache_refresh.push_back(std::move(cb)); + else + // No refresh started, so the caller is holding the same swarm answer it came in with + cb(false); + }); +} + +bool SnodePool::record_swarm_redirect( + x25519_pubkey swarm_pubkey, const std::vector& swarm_node_keys) { + return _jq.call_get([this, swarm_pubkey, &swarm_node_keys] { + if (_snode_cache.empty() || _all_swarms.empty()) + return false; + + // Resolving the names against our own pool is what makes a redirect safe to act on: the + // responding node chooses which registered nodes we end up talking to, but it cannot invent + // a node or point us at an address of its own choosing, because we never read the contact + // details it sent + std::unordered_set named{swarm_node_keys.begin(), swarm_node_keys.end()}; + std::vector resolved; + + for (const auto& node : _snode_cache) + if (named.count(node.remote_pubkey)) + resolved.push_back(node); + + if (resolved.empty()) { + log::debug( + cat, + "Ignoring redirect for {}: none of the {} named nodes are in our pool.", + swarm_pubkey.hex(), + swarm_node_keys.size()); + return false; + } + + // Too few of the named nodes resolved to call the result a swarm: either our pool is too + // old to know the rest, or the redirect isn't describing one. Only a refresh settles + // which, and the nodes we do have still beat the swarm that just rejected us, so they are + // followed meanwhile. Deliberately not also requiring that some names were unknown - a + // redirect naming one node we do know is the shape with no stale pool to explain it. + const bool too_few_resolved = resolved.size() < _config.cache_min_swarm_size; + + auto& [nodes, redirects] = _swarm_overrides[swarm_pubkey]; + nodes = std::move(resolved); + + // Saturating, because counting carries on past the limit for as long as the refresh it + // asks for is throttled, and wrapping would stop it asking + if (redirects < std::numeric_limits::max()) + ++redirects; + + log::debug( + cat, + "Redirected to a swarm of {} nodes for {} (redirect {} since the pool was " + "refreshed).", + nodes.size(), + swarm_pubkey.hex(), + redirects); + + if (too_few_resolved) { + log::warning( + cat, + "Asking for a refresh for {}: only {} of the {} nodes its redirect named are " + "ones we know.", + swarm_pubkey.hex(), + nodes.size(), + named.size()); + invalidate_swarm(swarm_pubkey); + } else if (redirects > SWARM_REDIRECTS_BEFORE_REFRESH) { + // Past the limit every redirect asks again, for as long as the refresh stays + // throttled, so only crossing it is worth a warning + if (redirects == SWARM_REDIRECTS_BEFORE_REFRESH + 1) + log::warning( + cat, + "Asking for a refresh for {}: {} redirects since the pool was refreshed.", + swarm_pubkey.hex(), + redirects); + else + log::debug( + cat, + "Asking again for a refresh for {}: {} redirects since the pool was " + "refreshed.", + swarm_pubkey.hex(), + redirects); + invalidate_swarm(swarm_pubkey); + } + + return true; }); } @@ -1151,9 +1378,7 @@ std::vector SnodePool::get_unused_nodes( continue; // Skip nodes with too many failures - auto it = _snode_strikes.find(node.remote_pubkey); - if (it != _snode_strikes.end() && - it->second.size() >= _config.cache_node_strike_threshold) + if (_node_struck_out(node.remote_pubkey)) continue; // Skip nodes whos IP addresses are in the exclusion list @@ -1176,20 +1401,6 @@ std::vector SnodePool::get_unused_nodes( }); } -void SnodePool::set_swarm( - session::network::x25519_pubkey swarm_pubkey, - swarm_id_t swarm_id, - std::vector nodes) { - _jq.call([this, swarm_pubkey, swarm_id, nodes = std::move(nodes)]() mutable { - log::info( - cat, - "Overriding cached swarm for {} with {} authoritative node(s).", - swarm_pubkey.hex(), - nodes.size()); - _swarm_cache[swarm_pubkey] = {swarm_id, std::move(nodes)}; - }); -} - void SnodePool::get_swarm( session::network::x25519_pubkey swarm_pubkey, bool ignore_strike_count, @@ -1197,14 +1408,18 @@ void SnodePool::get_swarm( log::trace(cat, "{} called for {}.", __PRETTY_FUNCTION__, swarm_pubkey.hex()); _jq.call([this, swarm_pubkey, ignore_strike_count, cb = std::move(callback)] { + // Trigger a non-blocking background refresh if the data is stale. Up here so that it runs + // for every call: answers from an override or the swarm cache below return early, and + // they are most of them. + _jq.call_soon([this] { refresh_if_needed({}); }); + auto filter_by_strikes = [this](std::vector nodes) -> std::vector { // Shuffle everything to start with std::ranges::shuffle(nodes, csrng); auto get_strike_count = [this](const service_node& node) -> size_t { - auto it = _snode_strikes.find(node.remote_pubkey); - return (it != _snode_strikes.end() ? it->second.size() : 0); + return _active_strike_count(node.remote_pubkey); }; // Partition into below-threshold and above-thresold. This keeps the shuffled order of @@ -1245,6 +1460,17 @@ void SnodePool::get_swarm( return nodes; }; + // A node that rejected a request for this account told us where it belongs, which beats + // anything we can work out from a pool we now know is behind. There is no swarm id to give + // back - a redirect names members, not an id - and nothing downstream reads it. + if (auto it = _swarm_overrides.find(swarm_pubkey); it != _swarm_overrides.end()) { + const auto& swarm_nodes = it->second.first; + + return cb( + swarm::INVALID_SWARM_ID, + (ignore_strike_count ? swarm_nodes : filter_by_strikes(swarm_nodes))); + } + // Check the in-memory swarm cache first if (auto it = _swarm_cache.find(swarm_pubkey); it != _swarm_cache.end()) { const auto& swarm_nodes = it->second.second; @@ -1261,7 +1487,12 @@ void SnodePool::get_swarm( // Queue this entire function call to be re-run after the refresh. _after_snode_cache_refresh.push_back( - [this, swarm_pubkey, ignore_strike_count, cb = std::move(cb)]() { + [this, swarm_pubkey, ignore_strike_count, cb = std::move(cb)](bool refreshed) { + // Re-deferring when the refresh never happened would just queue against the + // next one that doesn't either; there is no swarm to give back + if (!refreshed) + return cb(swarm::INVALID_SWARM_ID, {}); + this->get_swarm(swarm_pubkey, ignore_strike_count, std::move(cb)); }); @@ -1272,9 +1503,6 @@ void SnodePool::get_swarm( return; } - // Trigger a non-blocking background refresh if the data is stale - _jq.call_soon([this] { refresh_if_needed({}); }); - // Perform the swarm calculation using our local copy of the data auto swarm = swarm::get_swarm(swarm_pubkey, _all_swarms); _swarm_cache[swarm_pubkey] = swarm; diff --git a/src/network/transport/quic_transport.cpp b/src/network/transport/quic_transport.cpp index 1b57afd36..1068c2f8d 100644 --- a/src/network/transport/quic_transport.cpp +++ b/src/network/transport/quic_transport.cpp @@ -66,7 +66,7 @@ QuicTransport::~QuicTransport() { void QuicTransport::suspend() { // Use 'call_get' to force this to be synchronous _jq.call_get([this] { - if (!_suspended) + if (_suspended) return; _suspended = true; @@ -155,34 +155,41 @@ void QuicTransport::_recreate_endpoint() { } void QuicTransport::_close_connections() { - // Explicitly close all connections then reset the endpoint + // Taken out before the endpoint goes. Resetting it destroys it on the spot (close_conns() + // only defers), and its destructor closes every connection with code 0 through the handler + // that fails whatever is pending on it - so left in place, our own close would reach each + // pending verification as an error code, which is what gets a node struck. Answering copies + // also keeps a callback that calls back into the transport from changing the maps being walked. + auto verifications = std::exchange(_pending_verification_callbacks, {}); + auto requests = std::exchange(_pending_requests, {}); + if (_endpoint) _endpoint->close_conns(); _endpoint.reset(); - // Cancel any pending verifications (they can't succeed once the connection is closed) - for (const auto& [pubkey, callbacks] : _pending_verification_callbacks) + // Clear all storage of requests, paths and connections so that we are in a fresh state on + // relaunch + _active_connection_ids.clear(); + _available_stream_ids.clear(); + _update_status(ConnectionStatus::disconnected); + + // Answered only now the transport is fully closed, so anything a callback asks of it fails + // cleanly, without an error code, rather than meeting half-closed state. A verification gets + // no error code either: a close we asked for is no evidence against the node. + for (const auto& [pubkey, callbacks] : verifications) for (const auto& callback : callbacks) - callback(false, -1); + callback(false, std::nullopt); - // Cancel any pending requests (they can't succeed once the connection is closed) - for (const auto& [pubkey, pupkey_requests] : _pending_requests) - for (const auto& [info, callback] : pupkey_requests) + for (const auto& [pubkey, pubkey_requests] : requests) + for (const auto& [info, callback] : pubkey_requests) callback( false, false, - ERROR_NETWORK_SUSPENDED, + (_suspended ? ERROR_NETWORK_SUSPENDED : ERROR_CONNECTION_CLOSED), {content_type_plain_text}, - "QuickTransport is suspended."); + (_suspended ? "QuickTransport is suspended." + : "QuickTransport closed its connections.")); - // Clear all storage of requests, paths and connections so that we are in a fresh state on - // relaunch - _active_connection_ids.clear(); - _available_stream_ids.clear(); - _pending_verification_callbacks.clear(); - _pending_requests.clear(); - - _update_status(ConnectionStatus::disconnected); log::info(cat, "Closed all connections."); } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index e989495f8..942d83b9f 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -74,6 +74,7 @@ list(APPEND LIB_SESSION_UTESTS_SOURCES test_network_swarm.cpp test_onionreq.cpp test_onion_request_router.cpp + test_quic_transport.cpp test_snode_pool.cpp test_core_network.cpp test_poll.cpp diff --git a/tests/test_config_userprofile.cpp b/tests/test_config_userprofile.cpp index 677072495..f82680606 100644 --- a/tests/test_config_userprofile.cpp +++ b/tests/test_config_userprofile.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include "../src/config/internal.hpp" #include "utils.hpp" diff --git a/tests/test_helper.hpp b/tests/test_helper.hpp index de7041d15..b28926863 100644 --- a/tests/test_helper.hpp +++ b/tests/test_helper.hpp @@ -402,7 +402,7 @@ class TestHelper { net._loop->call_get([&] { net._current_clock_resync_id = "test"; net._clock_resync_results = std::move(measured); - net._on_clock_resync_complete(static_cast(net._clock_resync_results.size())); + net._on_clock_resync_complete(); }); } diff --git a/tests/test_network_swarm.cpp b/tests/test_network_swarm.cpp index d4f41e48d..87a77868d 100644 --- a/tests/test_network_swarm.cpp +++ b/tests/test_network_swarm.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include @@ -198,3 +199,186 @@ TEST_CASE("Swarm", "[network][swarm][get_swarm]") { "05000000000000000000000000000000000000000000000000fffffffffffffffe", swarms) == 0); } + +namespace { +using json = nlohmann::json; + +x25519_pubkey account(char c) { + return x25519_pubkey::from_hex(std::string(64, c)); +} + +std::vector nodes(std::string_view chars) { + std::vector keys; + for (char c : chars) + keys.push_back(ed25519_pubkey::from_hex(std::string(64, c))); + return keys; +} + +json rejection(std::optional echoed, std::string_view node_chars) { + auto snodes = json::array(); + for (char c : node_chars) + snodes.push_back({{"pubkey_ed25519", std::string(64, c)}, {"ip", "10.0.0.1"}}); + + json body = {{"snodes", std::move(snodes)}, {"swarm", "abc"}}; + if (echoed) + body["pubkey"] = *echoed; + return body; +} + +json batch(std::vector> results) { + auto list = json::array(); + for (auto& [code, body] : results) + list.push_back({{"code", code}, {"body", std::move(body)}}); + return {{"results", std::move(list)}}; +} + +response::swarm_rejections rejections( + const json& body, + int16_t status_code, + std::vector> accounts = {}) { + return response::find_swarm_rejections(&body, status_code, accounts); +} + +const std::string A = "05" + std::string(64, 'a'); +const std::string B = "03" + std::string(64, 'b'); +} // namespace + +TEST_CASE("Swarm", "[network][swarm][batch_error]") { + CHECK(response::find_uniform_batch_error(batch({{421, {}}, {421, {}}}).dump()) == 421); + CHECK_FALSE(response::find_uniform_batch_error(batch({{421, {}}, {406, {}}}).dump())); + CHECK_FALSE(response::find_uniform_batch_error(batch({{421, {}}, {200, {}}}).dump())); + CHECK_FALSE(response::find_uniform_batch_error(batch({}).dump())); + CHECK_FALSE(response::find_uniform_batch_error(rejection(A, "12").dump())); + CHECK_FALSE(response::find_uniform_batch_error("not json")); +} + +TEST_CASE("Swarm", "[network][swarm][rejections]") { + SECTION("A plain 421 is attributed to the request's account") { + auto r = rejections(rejection(A, "123"), 421, {account('a')}); + CHECK_FALSE(r.unattributed); + REQUIRE(r.accounts.size() == 1); + CHECK(r.accounts.at(account('a')) == nodes("123")); + } + + SECTION("An account echoed in testnet form, without a prefix, still matches") { + auto r = rejections(rejection(std::string(64, 'a'), "12"), 421, {account('a')}); + REQUIRE(r.accounts.count(account('a'))); + CHECK(r.accounts.at(account('a')) == nodes("12")); + } + + SECTION("A 421 needn't name its account") { + auto r = rejections( + batch({{421, rejection(std::nullopt, "12")}, {421, rejection(std::nullopt, "34")}}), + 421, + {account('a'), account('b')}); + CHECK_FALSE(r.unattributed); + REQUIRE(r.accounts.size() == 2); + CHECK(r.accounts.at(account('a')) == nodes("12")); + CHECK(r.accounts.at(account('b')) == nodes("34")); + } + + SECTION("Nothing is found in a response that isn't a 421") { + auto r = rejections(json{{"t", 1}}, 200, {account('a')}); + CHECK(r.accounts.empty()); + CHECK_FALSE(r.unattributed); + } + + SECTION("A batch can reject some accounts and answer others") { + auto r = rejections( + batch({{421, rejection(A, "12")}, + {200, json{{"messages", json::array()}}}, + {421, rejection(B, "34")}}), + 200, + {account('a'), account('c'), account('b')}); + CHECK_FALSE(r.unattributed); + REQUIRE(r.accounts.size() == 2); + CHECK(r.accounts.at(account('a')) == nodes("12")); + CHECK(r.accounts.at(account('b')) == nodes("34")); + } + + SECTION("Several rejections of one account are one redirect") { + auto r = rejections( + batch({{421, rejection(A, "12")}, {421, rejection(A, "12")}}), 421, {account('a')}); + REQUIRE(r.accounts.size() == 1); + CHECK(r.accounts.at(account('a')) == nodes("12")); + } + + SECTION("A single account applies to every sub-request") { + auto r = rejections( + batch({{421, rejection(std::nullopt, "12")}, {421, rejection(std::nullopt, "12")}}), + 421, + {account('a')}); + REQUIRE(r.accounts.size() == 1); + CHECK(r.accounts.at(account('a')) == nodes("12")); + } + + SECTION("A sequence that stopped early is still attributed by position") { + auto r = rejections( + batch({{200, json::object()}, {421, rejection(std::nullopt, "34")}}), + 200, + {account('a'), account('b'), account('c')}); + REQUIRE(r.accounts.size() == 1); + CHECK(r.accounts.at(account('b')) == nodes("34")); + } + + // The account a 421 names is the responding node's word; taking it would let any node redirect + // any account it likes, not just those it was asked about + SECTION("The account a 421 names is never trusted in place of the request's") { + auto r = rejections(rejection(A, "12"), 421, {account('b')}); + CHECK(r.accounts.empty()); + CHECK(r.unattributed); + + r = rejections( + batch({{421, rejection("05" + std::string(64, 'c'), "12")}, + {421, rejection(B, "34")}}), + 421, + {account('a'), account('b')}); + CHECK(r.unattributed); + REQUIRE(r.accounts.size() == 1); + CHECK(r.accounts.at(account('b')) == nodes("34")); + + CHECK(rejections(rejection(A, "12"), 421).accounts.empty()); + } + + SECTION("A sub-request with no account leaves its 421 unattributed") { + auto r = rejections( + batch({{200, json::object()}, {421, rejection(std::nullopt, "12")}}), + 200, + {account('a'), std::nullopt}); + CHECK(r.accounts.empty()); + CHECK(r.unattributed); + } + + SECTION("A 421 whose body isn't JSON has no redirect") { + std::vector> accounts{account('a')}; + auto r = response::find_swarm_rejections(nullptr, 421, accounts); + REQUIRE(r.accounts.size() == 1); + CHECK(r.accounts.at(account('a')).empty()); + CHECK(response::find_swarm_rejections(nullptr, 200, accounts).accounts.empty()); + } +} + +TEST_CASE("Swarm", "[network][swarm][batch_request_accounts]") { + SECTION("A pregenerated batch body gives each sub-request's account") { + auto body = json{{"requests", + {{{"method", "retrieve"}, {"params", {{"pubkey", A}}}}, + {{"method", "info"}, {"params", json::object()}}, + {{"method", "retrieve"}, {"params", {{"pubkey", B}}}}}}} + .dump(); + auto bytes = to_span(body); + + auto accounts = batch_request_accounts("batch", bytes); + REQUIRE(accounts); + CHECK(*accounts == + std::vector>{account('a'), std::nullopt, account('b')}); + CHECK(batch_request_accounts("sequence", bytes) == accounts); + CHECK_FALSE(batch_request_accounts("retrieve", bytes)); + + // A sub-request naming no account takes the one the caller gave for the whole request, + // while those that name their own keep it + CHECK(batch_request_accounts("batch", bytes, account('c')) == + std::vector>{account('a'), account('c'), account('b')}); + + CHECK_FALSE(batch_request_accounts("batch", to_span("not json"))); + } +} diff --git a/tests/test_onion_request_router.cpp b/tests/test_onion_request_router.cpp index 234c0c050..c1216855a 100644 --- a/tests/test_onion_request_router.cpp +++ b/tests/test_onion_request_router.cpp @@ -29,7 +29,7 @@ class TestOnionRequestRouter { std::shared_ptr router, PathCategory category, std::vector paths) { - router->_paths.emplace(category, paths); + router->_paths[category] = std::move(paths); } static std::vector get_paths( @@ -54,6 +54,20 @@ class TestOnionRequestRouter { return 0; } + static void set_cached_edge_nodes( + std::shared_ptr router, std::vector nodes) { + router->_cached_edge_nodes = std::move(nodes); + } + + static std::vector cached_edge_nodes( + std::shared_ptr router) { + return router->_cached_edge_nodes; + } + + static void drop_struck_cached_edge_nodes(std::shared_ptr router) { + router->_drop_struck_cached_edge_nodes(); + } + static void build_path( std::shared_ptr router, PathCategory category, @@ -68,6 +82,21 @@ class TestOnionRequestRouter { return router->_find_valid_path(request); } + static void send_on_path( + std::shared_ptr router, + OnionPath& path, + Request request, + network_response_callback_t callback) { + router->_send_on_path(path, std::move(request), std::move(callback)); + } + + static void rotate_path( + std::shared_ptr router, + const std::string& path_id, + PathCategory category) { + router->_rotate_path(path_id, category); + } + static void handle_transport_response( std::shared_ptr router, std::string path_id, @@ -152,16 +181,28 @@ namespace { SnodePool::record_node_failure(key, permanent); } - // Kept rather than run, so a test can decide when the refresh "completes". - std::function on_refresh_complete; + // Without `refresh_result`, the callback is kept rather than run, so a test can decide when + // the refresh "completes". + refresh_callback_t on_refresh_complete; + + // When set, `refresh_if_needed` calls back with it straight away - as the real one does, on + // the loop thread, when nothing needs refreshing. Only the first `max_refresh_callbacks` + // calls do, so code that asks again on every callback stops there instead of recursing + // until the stack gives out. + std::optional refresh_result; + int max_refresh_callbacks = 20; void refresh_if_needed( const std::vector& /*in_use_nodes*/, - std::function on_refresh_complete = nullptr) override { - if (on_refresh_complete) + refresh_callback_t on_refresh_complete = nullptr) override { + // Kept before the call is recorded: a test waiting on the call then reads the callback + if (on_refresh_complete && !refresh_result) this->on_refresh_complete = std::move(on_refresh_complete); func_called("refresh_if_needed"); - // Do nothing (don't want to trigger a cache refresh) + // Don't trigger a real cache refresh + if (refresh_result && on_refresh_complete && + get_call_count("refresh_if_needed") <= max_refresh_callbacks) + on_refresh_complete(*refresh_result); } void get_swarm( @@ -173,8 +214,12 @@ namespace { // Do nothing (don't want to trigger a cache refresh) } + // The `count` of each `get_unused_nodes` call, which the mock result doesn't reflect + std::vector unused_node_counts; + std::vector get_unused_nodes( size_t count, const std::vector& exclude = {}) override { + unused_node_counts.push_back(count); if (check_should_ignore_and_log_call("get_unused_nodes")) return {}; @@ -208,8 +253,19 @@ namespace { func_called("remove_failure_listeners"); } - void send_request(Request, network_response_callback_t) override { + // Answered the way a node on the path does when it fails a request itself: a status of its + // own and a plaintext body, which is nothing the destination encrypted + std::optional> plaintext_reply; + + void send_request(Request /*request*/, network_response_callback_t callback) override { func_called("send_request"); + if (plaintext_reply) + callback( + false, + false, + plaintext_reply->first, + {content_type_plain_text}, + plaintext_reply->second); } }; @@ -220,6 +276,60 @@ namespace { std::vector> headers; std::optional response; }; + + config::SnodePool test_pool_config() { + return {.cache_directory = std::nullopt, + .fallback_snode_pool_path = std::nullopt, + .cache_expiration = std::chrono::minutes{5}, + .cache_min_lifetime = std::chrono::minutes{5}, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .seed_nodes = {}, + .cache_min_size = 0, + .cache_min_swarm_size = 0, + .cache_num_nodes_to_use_for_refresh = 3, + .cache_min_num_refresh_presence_to_include_node = 2, + .cache_node_strike_threshold = 3}; + } + + config::OnionRequestRouter test_router_config() { + return {.file_server_config = file_server::DEFAULT_CONFIG, + .cache_directory = std::nullopt, + .edge_node_cache_duration = std::chrono::days{10}, + .netid = opt::netid::Target::testnet, + .seed_nodes = {}, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .path_length = 3, + .path_strike_threshold = 3, + .path_build_retry_limit = 10, + .path_rotation_frequency = 10min, + .node_strike_threshold = 3, + .disable_pre_build_paths = true, + .single_path_mode = true, + .min_path_counts = {{PathCategory::standard, 1}}}; + } + + service_node test_node(std::string_view pk_hex, uint16_t port) { + return service_node{ + ed25519_pubkey::from_hex(pk_hex), + oxen::quic::ipv4{"127.0.0.1"}, + port, + static_cast(port + 10000), + {2, 11, 0}, + 0}; + } + + network_response_callback_t record_into(std::optional& result) { + return [&result]( + bool success, + bool timeout, + int16_t status_code, + std::vector> headers, + std::optional response) { + result = {success, timeout, status_code, headers, response}; + }; + } } // namespace TEST_CASE("Network", "[network][onion_request_router][handle_errors]") { @@ -885,7 +995,7 @@ TEST_CASE("Network", "[network][onion_request_router][setup]") { REQUIRE(snode_pool->called("refresh_if_needed", 1s)); REQUIRE(snode_pool->on_refresh_complete); CHECK_FALSE(TestOnionRequestRouter::ready(made)); - snode_pool->on_refresh_complete(); + snode_pool->on_refresh_complete(true); bool became_ready = false; for (int i = 0; i < 100 && !became_ready; ++i) { became_ready = TestOnionRequestRouter::ready(made); @@ -914,4 +1024,228 @@ TEST_CASE("Network", "[network][onion_request_router][short_string]") { CHECK(path.to_string() == "j15s9zdp⟷m4twhhi5⟷hf7g1ebu"); } +TEST_CASE("Network", "[network][onion_request_router][cached_edge_nodes]") { + const auto node_strike_threshold = 3; + config::SnodePool pool_config = { + .cache_directory = std::nullopt, + .fallback_snode_pool_path = std::nullopt, + .cache_expiration = std::chrono::minutes{5}, + .cache_min_lifetime = std::chrono::minutes{5}, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .seed_nodes = {}, + .cache_min_size = 0, + .cache_min_swarm_size = 0, + .cache_num_nodes_to_use_for_refresh = 3, + .cache_min_num_refresh_presence_to_include_node = 2, + .cache_node_strike_threshold = node_strike_threshold}; + config::OnionRequestRouter config = { + file_server::DEFAULT_CONFIG, + std::nullopt, + std::chrono::days{10}, + opt::netid::Target::testnet, + {}, + network::opt::retry_delay{50ms, 200ms}, + 3, + 3, + 10, + 10min, + node_strike_threshold, + true, + true, + {{PathCategory::standard, 1}}}; + + auto ed_pk = "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7"_hex_b; + auto ed_pk2 = "5ea34e72bb044654a6a23675690ef5ffaaf1656b02f93fb76655f9cbdbe89876"_hex_b; + auto healthy = service_node{ + ed25519_pubkey::from_bytes(ed_pk), + oxen::quic::ipv4{"127.0.0.1"}, + 20001, + 30001, + {2, 11, 0}, + 0}; + auto struck = service_node{ + ed25519_pubkey::from_bytes(ed_pk2), + oxen::quic::ipv4{"127.0.0.2"}, + 20002, + 30002, + {2, 11, 0}, + 0}; + + auto loop = std::make_shared(); + auto disk_loop = std::make_shared(); + auto snode_pool = std::make_shared(pool_config, *loop, *disk_loop); + auto transport = std::make_shared(); + auto router = + std::make_shared(config, *loop, *disk_loop, snode_pool, transport); + + auto now = std::chrono::system_clock::now(); + TestOnionRequestRouter::set_cached_edge_nodes( + router, {cached_edge_node{healthy, now}, cached_edge_node{struck, now}}); + + // Both are well inside `edge_node_cache_duration`, which is the only thing that used to matter + TestOnionRequestRouter::drop_struck_cached_edge_nodes(router); + CHECK(TestOnionRequestRouter::cached_edge_nodes(router).size() == 2); + + // A cached edge node is forced as a path's first hop without going through `get_unused_nodes`, + // so nothing else would apply the strike filter to it. Striking it out has to cost it the + // cached-edge role outright - skipping it while keeping the entry would hand the role back when + // the strikes expire, long after we moved to another edge node. + snode_pool->SnodePool::record_node_failure(struck, true); + REQUIRE(snode_pool->node_struck_out(struck)); + + // Only the cached-edge role is lost; nothing here touches `_snode_cache`, so it stays a node + // like any other and `get_unused_nodes` can pick it again when its strikes expire + TestOnionRequestRouter::drop_struck_cached_edge_nodes(router); + auto remaining = TestOnionRequestRouter::cached_edge_nodes(router); + REQUIRE(remaining.size() == 1); + CHECK(remaining.front().node == healthy); +} + +TEST_CASE("Network", "[network][onion_request_router][undecrypted_response]") { + auto target = + test_node("4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7", 20001); + auto path_nodes = std::vector{ + test_node("5ea34e72bb044654a6a23675690ef5ffaaf1656b02f93fb76655f9cbdbe89876", 20002), + test_node("e17a692033200ae41350df9709754edde7343e2cf2f23e88f993319e0720e5e5", 20003), + test_node("7b633fa6fb462b90db6f0f50384190ce7715e31b7aa93d87dbd7e94e33d4251f", 20004)}; + + auto loop = std::make_shared(); + auto disk_loop = std::make_shared(); + auto snode_pool = std::make_shared(test_pool_config(), *loop, *disk_loop); + auto transport = std::make_shared(); + auto router = std::make_shared( + test_router_config(), *loop, *disk_loop, snode_pool, transport); + + // The router is driven on the loop, as its own code is, and checked from here + loop->call_get([&] { + TestOnionRequestRouter::set_paths( + router, PathCategory::standard, {OnionPath{"Test", path_nodes}}); + }); + + auto send_with_reply = [&](int16_t status) { + transport->plaintext_reply.emplace(status, "Forged by a node on the path"); + auto request = Request{ + "AAAA", target, "retrieve", to_vector("{}"), RequestCategory::standard, 10s}; + + bool have_path = false; + std::optional result; + loop->call_get([&] { + if (auto* path = TestOnionRequestRouter::find_valid_path(router, request)) { + have_path = true; + TestOnionRequestRouter::send_on_path(router, *path, request, record_into(result)); + } + }); + REQUIRE(have_path); + REQUIRE(result); + return *result; + }; + + // Each of these is acted on as the destination's verdict (a swarm redirect, a clock resync), + // which only the destination can give; a node on the path sending one mustn't pass for it + for (int16_t status : {ERROR_MISDIRECTED_REQUEST, ERROR_NOT_ACCEPTABLE, ERROR_TOO_EARLY}) { + CAPTURE(status); + auto result = send_with_reply(status); + CHECK_FALSE(result.success); + CHECK(result.status_code == ERROR_UNAUTHENTICATED_RESPONSE); + CHECK(result.response.value_or("").find("status {}"_format(status)) != std::string::npos); + } + + // Anything else a node on the path says about its own failure is reported as it was + auto result = send_with_reply(502); + CHECK_FALSE(result.success); + CHECK(result.status_code == 502); +} + +TEST_CASE("Network", "[network][onion_request_router][build_path_too_few_nodes]") { + auto loop = std::make_shared(); + auto disk_loop = std::make_shared(); + auto snode_pool = std::make_shared(test_pool_config(), *loop, *disk_loop); + auto transport = std::make_shared(); + auto router = std::make_shared( + test_router_config(), *loop, *disk_loop, snode_pool, transport); + + // Run on the loop, as the router's own code is: that also puts it after the router's setup, + // which asks for the (empty) pool to be refreshed and mustn't be counted below + std::optional result; + loop->call_get([&] { + snode_pool->reset_calls(); + + auto queue = std::make_shared(*loop); + TestOnionRequestRouter::set_request_queues(router, {{PathCategory::standard, queue}}); + queue->add( + Request{"AAAA", + test_node( + "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7", + 20001), + "retrieve", + to_vector("{}"), + RequestCategory::standard, + 10s}, + record_into(result)); + + // A path needs three nodes and the pool can only offer one, while saying nothing needs + // refreshing - which is a pool too concentrated in a few subnets to fill a path, say + snode_pool->mock_unused_nodes = std::vector{test_node( + "5ea34e72bb044654a6a23675690ef5ffaaf1656b02f93fb76655f9cbdbe89876", 20002)}; + snode_pool->refresh_result = true; + + TestOnionRequestRouter::build_path(router, PathCategory::standard, "AAAA"); + }); + + // Asking for a refresh once and then giving up; without checking that the pool can now fill a + // path, every "refreshed" rebuilt straight into another refresh request, and only the mock's + // limit stops it + CHECK(snode_pool->get_call_count("refresh_if_needed") == 1); + REQUIRE(result); + CHECK_FALSE(result->success); + CHECK(result->status_code == ERROR_INSUFFICIENT_NODES); + CHECK(result->response.value_or("").find("too few usable nodes") != std::string::npos); +} + +TEST_CASE("Network", "[network][onion_request_router][rotate_path]") { + auto key1 = "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7"sv; + auto key2 = "5ea34e72bb044654a6a23675690ef5ffaaf1656b02f93fb76655f9cbdbe89876"sv; + auto key3 = "e17a692033200ae41350df9709754edde7343e2cf2f23e88f993319e0720e5e5"sv; + auto key4 = "7b633fa6fb462b90db6f0f50384190ce7715e31b7aa93d87dbd7e94e33d4251f"sv; + auto edge = test_node(key1, 20001); + auto path_nodes = std::vector{edge, test_node(key2, 20002), test_node(key3, 20003)}; + + auto loop = std::make_shared(); + auto disk_loop = std::make_shared(); + auto snode_pool = std::make_shared(test_pool_config(), *loop, *disk_loop); + auto transport = std::make_shared(); + auto config = test_router_config(); + auto router = + std::make_shared(config, *loop, *disk_loop, snode_pool, transport); + snode_pool->mock_unused_nodes = + std::vector{test_node(key2, 20012), test_node(key3, 20013), test_node(key4, 20014)}; + + // Rotates a path whose edge node was connected just now, so well inside + // `edge_node_cache_duration`, and returns what the rotation asked the pool for. The first + // request says which it chose: a whole new path, or the rest of one that keeps the edge node. + auto rotate = [&] { + std::vector counts; + loop->call_get([&] { + auto now = std::chrono::system_clock::now(); + TestOnionRequestRouter::set_paths( + router, PathCategory::standard, {OnionPath{"Test", path_nodes, now, now}}); + snode_pool->unused_node_counts.clear(); + TestOnionRequestRouter::rotate_path(router, "Test", PathCategory::standard); + counts = snode_pool->unused_node_counts; + }); + return counts; + }; + + auto kept = rotate(); + REQUIRE_FALSE(kept.empty()); + CHECK(kept.front() == config.path_length - 1u); + + // Struck out since we connected to it, the edge node is replaced along with the rest + snode_pool->record_node_failure(edge, true); + auto replaced = rotate(); + REQUIRE_FALSE(replaced.empty()); + CHECK(replaced.front() == config.path_length); +} } // namespace session::network diff --git a/tests/test_quic_transport.cpp b/tests/test_quic_transport.cpp new file mode 100644 index 000000000..4c72de858 --- /dev/null +++ b/tests/test_quic_transport.cpp @@ -0,0 +1,78 @@ +#include +#include +#include +#include + +using namespace session::network; +using namespace std::literals; + +namespace { +std::shared_ptr make_transport(oxen::quic::Loop& loop) { + return std::make_shared( + config::QuicTransport{.handshake_timeout = 1s, .keep_alive = 10s}, loop); +} + +service_node test_node() { + auto pubkey = "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7"sv; + return service_node{ + ed25519_pubkey::from_hex(pubkey), + oxen::quic::ipv4{"127.0.0.1"}, + 20001, + 30001, + {2, 11, 0}, + 0}; +} +} // namespace + +TEST_CASE("Network", "[network][quic_transport][suspend]") { + auto loop = std::make_shared(); + auto transport = make_transport(*loop); + transport->suspend(); + + std::promise status; + transport->send_request( + Request{"AAAA", test_node(), "info", std::nullopt, RequestCategory::standard, 1s}, + [&status, answered = false](bool, bool, int16_t status_code, auto, auto) mutable { + if (!std::exchange(answered, true)) + status.set_value(status_code); + }); + + // Refused outright rather than attempted: a suspended transport sends nothing + auto answer = status.get_future(); + REQUIRE(answer.wait_for(5s) == std::future_status::ready); + CHECK(answer.get() == ERROR_NETWORK_SUSPENDED); +} + +TEST_CASE("Network", "[network][quic_transport][close_connections]") { + auto loop = std::make_shared(); + auto transport = make_transport(*loop); + + // Verified and closed within one loop job, so nothing from the network can settle the + // verification before the close does + int answers = 0; + bool success = true; + std::optional error_code; + loop->call_get([&] { + transport->verify_connectivity( + test_node(), + 3s, + "AAAA", + RequestCategory::standard, + [&](bool s, std::optional e) { + ++answers; + success = s; + error_code = e; + }); + transport->close_connections(); + }); + + // Anything the close deferred has run by the time a later job does + loop->call_get([] {}); + + // One answer, from the close, and with no error code: a close we asked for is no evidence + // against the node, which is what an error code would say - the router strikes a node whose + // verification fails with one + CHECK(answers == 1); + CHECK_FALSE(success); + CHECK_FALSE(error_code); +} diff --git a/tests/test_snode_pool.cpp b/tests/test_snode_pool.cpp index e7446b13b..c962bb073 100644 --- a/tests/test_snode_pool.cpp +++ b/tests/test_snode_pool.cpp @@ -1,5 +1,6 @@ #include #include +#include #include "utils.hpp" @@ -26,13 +27,18 @@ class TestSnodePool : public SnodePool { }); } + // How often the pool was asked to check whether it needs refreshing; read it only after a + // loop job has run, since the checks are scheduled onto the loop + int refresh_checks = 0; + void refresh_if_needed( const std::vector& /*in_use_nodes*/, - std::function /*on_refresh_complete*/ = nullptr) override { - // Do nothing (don't want to trigger a cache refresh) + refresh_callback_t /*on_refresh_complete*/ = nullptr) override { + // Don't trigger a cache refresh + ++refresh_checks; } - void debug_queue_post_refresh_callback(std::function cb) { + void debug_queue_post_refresh_callback(refresh_callback_t cb) { _jq.call_get([this, cb = std::move(cb)]() mutable { _after_snode_cache_refresh.push_back(std::move(cb)); }); @@ -73,6 +79,86 @@ class TestSnodePool : public SnodePool { }); } + bool debug_refresh_in_progress() { + return _jq.call_get([this] { return _current_snode_cache_refresh_id.has_value(); }); + } + + void debug_start_refresh() { + _jq.call_get([this] { _refresh_snode_cache(); }); + } + + std::optional debug_refresh_id() { + return _jq.call_get([this] { return _current_snode_cache_refresh_id; }); + } + + size_t debug_refresh_candidate_count() { + return _jq.call_get([this] { return _refresh_candidate_nodes.size(); }); + } + + void debug_clear_refresh_candidates() { + _jq.call_get([this] { _refresh_candidate_nodes.clear(); }); + } + + int debug_refresh_failure_count() { + return _jq.call_get([this] { return _snode_cache_refresh_failure_count; }); + } + + void debug_set_refresh_failure_count(int count) { + _jq.call_get([this, count] { _snode_cache_refresh_failure_count = count; }); + } + + // Launches one of the refresh `request_id`'s fetches, as its retries do + void debug_launch_refresh_request(const std::string& request_id) { + _jq.call_get([this, request_id] { + _launch_next_refresh_request(request_id, 0, false, true, 1); + }); + } + + // Backdates the pool snapshot so the age-based policies can be exercised without waiting + void debug_age_pool(std::chrono::seconds by) { + _jq.call_get([this, by] { _last_snode_cache_update -= by; }); + } + + void debug_age_evidence_refresh(std::chrono::seconds by) { + _jq.call_get([this, by] { _last_evidence_refresh -= by; }); + } + + std::chrono::seconds debug_evidence_backoff() { + return _jq.call_get([this] { return _evidence_refresh_backoff; }); + } + + // Runs `fn` on the loop thread, which is what makes `get_swarm` / `invalidate_swarm` resolve + // inline rather than being queued: a test observing them from off the loop has no ordering + // guarantee at all + void debug_run_on_loop(std::function fn) { + _jq.call_get([fn = std::move(fn)] { fn(); }); + } + + // Backdates every recorded strike so `STRIKE_EXPIRY` can be crossed without a 48h wait + void debug_age_strikes(std::chrono::seconds by) { + _jq.call_get([this, by] { + for (auto& [key, stamps] : _snode_strikes) + for (auto& stamp : stamps) + stamp -= by; + }); + } + + // Every strike on record, expired or not - which is what the decision sites used to count + size_t debug_recorded_strikes(const ed25519_pubkey& key) { + return _jq.call_get([this, &key] { + auto it = _snode_strikes.find(key); + return (it == _snode_strikes.end() ? size_t{0} : it->second.size()); + }); + } + + // Reaches past the no-op override above to the real age-based policy, on the loop thread so it + // resolves inline + void debug_refresh_if_needed(refresh_callback_t cb) { + _jq.call_get([this, cb = std::move(cb)]() mutable { + SnodePool::refresh_if_needed({}, std::move(cb)); + }); + } + void debug_on_refresh_complete(std::vector> raw_results) { auto total_requests = static_cast(raw_results.size()); _jq.call_get([&] { @@ -81,6 +167,19 @@ class TestSnodePool : public SnodePool { } }; +// `TestSnodePool` stubs out `refresh_if_needed` so tests don't kick off real refreshes; the swarm +// invalidation test needs the real age-based policy to compare against, so it uses this instead +class TestSnodePoolAgePolicy : public TestSnodePool { + public: + using TestSnodePool::TestSnodePool; + + void refresh_if_needed( + const std::vector& in_use_nodes, + refresh_callback_t on_refresh_complete = nullptr) override { + SnodePool::refresh_if_needed(in_use_nodes, std::move(on_refresh_complete)); + } +}; + // Encodes nodes the way the storage server returns them, so they can be fed to // `_on_refresh_complete`: 51 bytes per node, all multi-byte fields big-endian static std::vector to_snode_cache_bin(const std::vector& nodes) { @@ -111,18 +210,12 @@ static std::vector to_snode_cache_bin(const std::vector TEST_CASE("Network", "[network][get_unused_nodes]") { session::network::config::SnodePool pool_config = { - std::nullopt, - std::nullopt, - std::chrono::minutes{5}, - std::chrono::minutes{5}, - false, // enforce_subnet_diversity - network::opt::retry_delay{50ms, 200ms}, - opt::netid::Target::testnet, - {}, - 0, - 0, - 3, // cache_node_strike_threshold - false}; + .cache_expiration = std::chrono::minutes{5}, + .cache_min_lifetime = std::chrono::minutes{5}, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .cache_node_strike_threshold = 3}; auto ed_pk = "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7"_hex_b; auto ed_pk2 = "5ea34e72bb044654a6a23675690ef5ffaaf1656b02f93fb76655f9cbdbe89876"_hex_b; auto ed_pk3 = "e17a692033200ae41350df9709754edde7343e2cf2f23e88f993319e0720e5e5"_hex_b; @@ -207,20 +300,31 @@ TEST_CASE("Network", "[network][get_unused_nodes]") { std::sort(unused_nodes.begin(), unused_nodes.end()); CHECK(unused_nodes == remaining); + // ... but only once they have passed it: ordinary strikes below the threshold leave a node in + // use (strikes are per pubkey, so these apply to every node sharing the struck node's key) + snode_pool->reset_state_with_cache(snode_cache); + auto struck_key = snode_cache[0].remote_pubkey; + auto uses_struck_key = [&struck_key](const service_node& n) { + return n.remote_pubkey == struck_key; + }; + auto with_struck_key = std::ranges::count_if(snode_cache, uses_struck_key); + + snode_pool->record_node_failure(snode_cache[0]); + snode_pool->record_node_failure(snode_cache[0]); + CHECK(std::ranges::count_if(snode_pool->get_unused_nodes(20), uses_struck_key) == + with_struck_key); + + snode_pool->record_node_failure(snode_cache[0]); + CHECK(std::ranges::none_of(snode_pool->get_unused_nodes(20), uses_struck_key)); + // Should exclude nodes which have the same subnet pool_config = { - std::nullopt, - std::nullopt, - std::chrono::minutes{5}, - std::chrono::minutes{5}, - true, // enforce_subnet_diversity - network::opt::retry_delay{50ms, 200ms}, - opt::netid::Target::testnet, - {}, - 0, - 0, - 3, // cache_node_strike_threshold - false}; + .cache_expiration = std::chrono::minutes{5}, + .cache_min_lifetime = std::chrono::minutes{5}, + .enforce_subnet_diversity = true, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .cache_node_strike_threshold = 3}; snode_pool = std::make_shared(pool_config, *loop, *disk_loop); snode_pool->reset_state_with_cache(snode_cache); unused_nodes = snode_pool->get_unused_nodes(20); @@ -235,18 +339,12 @@ TEST_CASE("Network", "[network][get_unused_nodes]") { TEST_CASE("Network", "[network][update_cache]") { session::network::config::SnodePool pool_config = { - std::nullopt, - std::nullopt, - 5min, - 5min, - false, // enforce_subnet_diversity - network::opt::retry_delay{50ms, 200ms}, - opt::netid::Target::testnet, - {}, - 0, - 0, - 3, // cache_node_strike_threshold - false}; + .cache_expiration = 5min, + .cache_min_lifetime = 5min, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .cache_node_strike_threshold = 3}; auto ed_pk = "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7"_hex_b; std::vector snode_cache; @@ -267,12 +365,12 @@ TEST_CASE("Network", "[network][update_cache]") { // what a deferred `get_swarm` does when the refresh left the cache empty) rather than // invalidating the vector it's iterating std::vector callbacks_run; - snode_pool->debug_queue_post_refresh_callback([&] { + snode_pool->debug_queue_post_refresh_callback([&](bool) { callbacks_run.push_back(0); - snode_pool->debug_queue_post_refresh_callback([&] { callbacks_run.push_back(3); }); + snode_pool->debug_queue_post_refresh_callback([&](bool) { callbacks_run.push_back(3); }); }); - snode_pool->debug_queue_post_refresh_callback([&] { callbacks_run.push_back(1); }); - snode_pool->debug_queue_post_refresh_callback([&] { callbacks_run.push_back(2); }); + snode_pool->debug_queue_post_refresh_callback([&](bool) { callbacks_run.push_back(1); }); + snode_pool->debug_queue_post_refresh_callback([&](bool) { callbacks_run.push_back(2); }); REQUIRE(snode_pool->debug_remove_post_refresh_callback_spare_capacity()); snode_pool->update_cache({}); CHECK(callbacks_run == std::vector{0, 1, 2}); @@ -290,19 +388,13 @@ TEST_CASE("Network", "[network][update_cache]") { TEST_CASE("Network", "[network][refresh_min_cache_size]") { session::network::config::SnodePool pool_config = { - std::nullopt, - std::nullopt, - 5min, - 5min, - false, // enforce_subnet_diversity - network::opt::retry_delay{50ms, 200ms}, - opt::netid::Target::testnet, - {}, - 12, // cache_min_size - 0, - 0, - 3, // cache_node_strike_threshold - false}; + .cache_expiration = 5min, + .cache_min_lifetime = 5min, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .cache_min_size = 12, + .cache_node_strike_threshold = 3}; auto ed_pk = "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7"_hex_b; std::vector snode_cache; @@ -346,22 +438,15 @@ TEST_CASE("Network", "[network][swarm_version_preference]") { constexpr std::array new_ss{2, 11, 1}; auto make_config = [](std::optional> prefer) { - session::network::config::SnodePool config = { - std::nullopt, - std::nullopt, - std::chrono::minutes{5}, - std::chrono::minutes{5}, - false, - network::opt::retry_delay{50ms, 200ms}, - opt::netid::Target::testnet, - {}, - 0, - 0, - 3, - 0, - 3}; - config.prefer_min_version = prefer; - return config; + return session::network::config::SnodePool{ + .cache_expiration = std::chrono::minutes{5}, + .cache_min_lifetime = std::chrono::minutes{5}, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .cache_num_nodes_to_use_for_refresh = 3, + .cache_node_strike_threshold = 3, + .prefer_min_version = prefer}; }; // Alternating, so that grouping by version can only come from the preference rather than from @@ -440,3 +525,531 @@ TEST_CASE("Network", "[network][swarm_version_preference]") { CHECK(got.front().storage_server_version == old_ss); } } + +TEST_CASE("Network", "[network][invalidate_swarm]") { + session::network::config::SnodePool pool_config{ + .cache_expiration = 2h, + .cache_min_lifetime = 2s, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .cache_min_size = 12, + .cache_min_swarm_size = 3, + .cache_num_nodes_to_use_for_refresh = 1, + .cache_min_num_refresh_presence_to_include_node = 1, + .cache_node_strike_threshold = 3}; + + auto ed_pk_before = "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7"_hex_b; + auto ed_pk_after = "5ea34e72bb044654a6a23675690ef5ffaaf1656b02f93fb76655f9cbdbe89876"_hex_b; + + // Two snapshots of the same two swarms, with an entirely different set of nodes serving them. + // Which swarm the pubkey lands in doesn't matter; what matters is that the correct answer + // changed and no node is common to both. + auto pool_snapshot = [](std::span ed_pk, uint8_t subnet) { + std::vector nodes; + + for (uint16_t i = 0; i < 12; ++i) + nodes.emplace_back(service_node{ + ed25519_pubkey::from_bytes(ed_pk), + oxen::quic::ipv4{"192.168.{}.{}"_format(subnet, i)}, + static_cast(20000 + i), + static_cast(30000 + i), + {2, 11, 0}, + static_cast(i < 6 ? 0 : 1)}); + + return nodes; + }; + auto nodes_before = pool_snapshot(ed_pk_before, 0); + auto nodes_after = pool_snapshot(ed_pk_after, 1); + + auto loop = std::make_shared(); + auto disk_loop = std::make_shared(); + auto snode_pool = std::make_shared(pool_config, *loop, *disk_loop); + snode_pool->update_cache(nodes_before); + snode_pool->debug_age_pool(10min); + + auto swarm_pubkey = x25519_pubkey::from_hex( + "0000000000000000000000000000000000000000000000000000000000000000"); + + std::vector rejected_swarm, recovered_swarm; + bool age_policy_started_refresh = false, recovery_ran = false; + + snode_pool->debug_run_on_loop([&] { + snode_pool->get_swarm( + swarm_pubkey, true, [&](swarm::swarm_id_t, std::vector nodes) { + rejected_swarm = std::move(nodes); + }); + + // Asking by age is what the 421 path used to do, and on a cache this far short of + // `cache_expiration` it declines - which is what left the disproven mapping in place + snode_pool->refresh_if_needed({}); + age_policy_started_refresh = snode_pool->debug_refresh_in_progress(); + + snode_pool->invalidate_swarm(swarm_pubkey, [&](bool refreshed) { + recovery_ran = true; + CHECK(refreshed); + snode_pool->get_swarm( + swarm_pubkey, true, [&](swarm::swarm_id_t, std::vector nodes) { + recovered_swarm = std::move(nodes); + }); + }); + }); + + REQUIRE_FALSE(rejected_swarm.empty()); + CHECK_FALSE(age_policy_started_refresh); + + // The rejection has to produce a refresh, and the retry has to wait for it rather than being + // handed the answer that was just rejected + REQUIRE(snode_pool->debug_refresh_in_progress()); + CHECK_FALSE(recovery_ran); + + snode_pool->update_cache(nodes_after); + REQUIRE(recovery_ran); + REQUIRE_FALSE(recovered_swarm.empty()); + + for (const auto& node : recovered_swarm) + CHECK(std::ranges::find(rejected_swarm, node) == rejected_swarm.end()); + + // A rejection that arrives after we already refreshed on one has to be held off, or a node that + // rejects everything keeps a client refreshing from three nodes forever + CHECK(snode_pool->debug_evidence_backoff() == 1min); + snode_pool->debug_age_pool(10min); + snode_pool->debug_run_on_loop([&] { snode_pool->invalidate_swarm(swarm_pubkey); }); + CHECK_FALSE(snode_pool->debug_refresh_in_progress()); + + // Once it has elapsed the next one runs, and the one after it waits twice as long again + snode_pool->debug_age_evidence_refresh(90s); + snode_pool->debug_run_on_loop([&] { snode_pool->invalidate_swarm(swarm_pubkey); }); + CHECK(snode_pool->debug_refresh_in_progress()); + CHECK(snode_pool->debug_evidence_backoff() == 2min); + + // Staying quiet for twice the interval means the next incident starts from the base delay + // rather than inheriting an escalated one + snode_pool->update_cache(nodes_after); + snode_pool->debug_age_pool(10min); + snode_pool->debug_age_evidence_refresh(10min); + snode_pool->debug_run_on_loop([&] { snode_pool->invalidate_swarm(swarm_pubkey); }); + CHECK(snode_pool->debug_refresh_in_progress()); + CHECK(snode_pool->debug_evidence_backoff() == 1min); +} + +TEST_CASE("Network", "[network][swarm_redirect]") { + session::network::config::SnodePool pool_config{ + .cache_expiration = 2h, + .cache_min_lifetime = 2s, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .cache_min_size = 12, + .cache_min_swarm_size = 3, + .cache_num_nodes_to_use_for_refresh = 1, + .cache_min_num_refresh_presence_to_include_node = 1, + .cache_node_strike_threshold = 3}; + + // A redirect is resolved by node pubkey, so every node needs its own + auto key_for = [](uint16_t i) { + return ed25519_pubkey::from_hex( + "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46a{:02x}"_format(i)); + }; + std::vector snode_cache; + + for (uint16_t i = 0; i < 12; ++i) + snode_cache.emplace_back(service_node{ + key_for(i), + oxen::quic::ipv4{"192.168.0.{}"_format(i)}, + static_cast(20000 + i), + static_cast(30000 + i), + {2, 11, 0}, + static_cast(i < 6 ? 0 : 1)}); + + auto loop = std::make_shared(); + auto disk_loop = std::make_shared(); + auto snode_pool = std::make_shared(pool_config, *loop, *disk_loop); + snode_pool->update_cache(snode_cache); + + // Old enough that the fallback would refresh, so "no refresh happened" below means the redirect + // was taken rather than the pool being too fresh to bother + snode_pool->debug_age_pool(10min); + + auto swarm_pubkey = x25519_pubkey::from_hex( + "0000000000000000000000000000000000000000000000000000000000000000"); + + std::vector calculated; + snode_pool->debug_run_on_loop([&] { + snode_pool->get_swarm( + swarm_pubkey, true, [&](swarm::swarm_id_t, std::vector nodes) { + calculated = std::move(nodes); + }); + }); + REQUIRE(calculated.size() == 6); + + // Everything the calculation didn't pick, which is what a real redirect would be naming + std::vector elsewhere; + for (const auto& node : snode_cache) + if (std::ranges::find(calculated, node) == calculated.end()) + elsewhere.push_back(node); + REQUIRE(elsewhere.size() == 6); + + // Membership is the claim in every comparison below; the pool is reshuffled on each refresh and + // a redirect is resolved in pool order, so neither side has an order worth asserting + auto sorted = [](std::vector nodes) { + std::ranges::sort(nodes); + return nodes; + }; + auto keys_of = [](const std::vector& nodes, size_t count) { + std::vector keys; + for (size_t i = 0; i < count && i < nodes.size(); ++i) + keys.push_back(nodes[i].remote_pubkey); + return keys; + }; + + // Nodes we've never heard of can't redirect us anywhere - this is what stops a response putting + // us in touch with something that isn't a registered service node + CHECK_FALSE(snode_pool->record_swarm_redirect(swarm_pubkey, {key_for(200), key_for(201)})); + + auto current_swarm = [&] { + std::vector swarm; + snode_pool->debug_run_on_loop([&] { + snode_pool->get_swarm( + swarm_pubkey, true, [&](swarm::swarm_id_t, std::vector nodes) { + swarm = std::move(nodes); + }); + }); + return sorted(std::move(swarm)); + }; + auto overridden = sorted(std::vector(elsewhere.begin(), elsewhere.begin() + 4)); + + // A usable redirect is taken, and - the point of all this - no pool refresh is started for it + REQUIRE(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 4))); + CHECK_FALSE(snode_pool->debug_refresh_in_progress()); + CHECK(current_swarm() == overridden); + CHECK_FALSE(snode_pool->debug_refresh_in_progress()); + + // How the named swarm relates to the one we sent to says nothing, since swarms can be + // rearranged any way at all: a node that has left the overridden swarm names its current + // members, and one in it naming the calculated swarm is how a wrong redirect gets put right + CHECK(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 4))); + CHECK(current_swarm() == overridden); + CHECK(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(calculated, 6))); + CHECK(current_swarm() == sorted(calculated)); + + // Two sets of nodes that disagree, each redirecting to the other + auto bounce = [&](int times) { + for (int i = 0; i < times; ++i) + REQUIRE(snode_pool->record_swarm_redirect( + swarm_pubkey, i % 2 == 0 ? keys_of(elsewhere, 4) : keys_of(calculated, 6))); + }; + + // Every redirect counts, but none is refused for it - refusing would only fail the request. + // Up to the limit nothing else happens... + bounce(5); + CHECK(current_swarm() == overridden); + CHECK_FALSE(snode_pool->debug_refresh_in_progress()); + + // ... and past it the redirect is still followed, but also asks for a refresh, which the pool + // being old enough lets start + CHECK(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(calculated, 6))); + CHECK(current_swarm() == sorted(calculated)); + CHECK(snode_pool->debug_refresh_in_progress()); + + // A refreshed pool is ground truth again, so redirects correcting the old one are dropped + REQUIRE(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 4))); + snode_pool->update_cache(snode_cache); + CHECK(current_swarm() == sorted(calculated)); + + // ... and the calculated swarm itself, or part of it, is followed like any other + CHECK(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(calculated, 6))); + CHECK(current_swarm() == sorted(calculated)); + auto remaining = std::vector(calculated.begin() + 1, calculated.end()); + CHECK(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(remaining, 5))); + CHECK(current_swarm() == sorted(remaining)); + + // Past the limit with the refresh throttled - the pool was only just refreshed - redirects are + // still followed, rather than leaving the account on a swarm already known to be wrong + bounce(6); + CHECK(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 4))); + CHECK(current_swarm() == overridden); + CHECK_FALSE(snode_pool->debug_refresh_in_progress()); + + // A redirect naming nodes we mostly haven't heard of is followed with the ones we have - they + // are the right swarm, where the one we had just rejected us - and asks for the refresh that + // can fill in the rest (from a fresh count, so the limit plays no part) + snode_pool->update_cache(snode_cache); + snode_pool->debug_age_pool(10min); + snode_pool->debug_age_evidence_refresh(10min); + auto partial = keys_of(elsewhere, 2); + partial.push_back(key_for(200)); + partial.push_back(key_for(201)); + CHECK(snode_pool->record_swarm_redirect(swarm_pubkey, partial)); + CHECK(current_swarm() == + sorted(std::vector(elsewhere.begin(), elsewhere.begin() + 2))); + CHECK(snode_pool->debug_refresh_in_progress()); + + // A redirect naming too few nodes to be a swarm asks for the refresh whether or not any of the + // names were unknown. One naming a single node we do know has no stale pool to explain it, and + // is the only thing serving the account until a refresh drops it, so it is the case that most + // wants one + snode_pool->update_cache(snode_cache); + snode_pool->debug_age_pool(10min); + snode_pool->debug_age_evidence_refresh(10min); + CHECK(snode_pool->record_swarm_redirect(swarm_pubkey, keys_of(elsewhere, 1))); + CHECK(current_swarm() == + sorted(std::vector(elsewhere.begin(), elsewhere.begin() + 1))); + CHECK(snode_pool->debug_refresh_in_progress()); +} + +TEST_CASE("Network", "[network][get_swarm_checks_age]") { + session::network::config::SnodePool pool_config{ + .cache_expiration = 2h, + .cache_min_lifetime = 2s, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .cache_min_swarm_size = 3, + .cache_node_strike_threshold = 3}; + + std::vector snode_cache; + for (uint16_t i = 0; i < 6; ++i) + snode_cache.emplace_back(service_node{ + ed25519_pubkey::from_hex( + "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46a{:02x}"_format( + i)), + oxen::quic::ipv4{"192.168.0.{}"_format(i)}, + static_cast(20000 + i), + static_cast(30000 + i), + {2, 11, 0}, + static_cast(i < 3 ? 0 : 1)}); + + auto loop = std::make_shared(); + auto disk_loop = std::make_shared(); + auto snode_pool = std::make_shared(pool_config, *loop, *disk_loop); + snode_pool->update_cache(snode_cache); + + auto swarm_pubkey = x25519_pubkey::from_hex( + "0000000000000000000000000000000000000000000000000000000000000000"); + + // The check is scheduled onto the loop, so it has run by the time a later loop job does + auto checks_for_one_get_swarm = [&] { + snode_pool->debug_run_on_loop([&] { + snode_pool->refresh_checks = 0; + snode_pool->get_swarm(swarm_pubkey, true, [](auto, auto) {}); + }); + snode_pool->debug_run_on_loop([] {}); + return snode_pool->refresh_checks; + }; + + // Worked out from the pool and cached... + CHECK(checks_for_one_get_swarm() == 1); + + // ... then answered from that cache, and from an override, each of which returns before the + // swarm is worked out, and neither of which may skip checking whether the pool is stale + CHECK(checks_for_one_get_swarm() == 1); + + std::vector redirect; + for (const auto& node : snode_cache) + redirect.push_back(node.remote_pubkey); + REQUIRE(snode_pool->record_swarm_redirect(swarm_pubkey, redirect)); + CHECK(checks_for_one_get_swarm() == 1); +} + +TEST_CASE("Network", "[network][strike_expiry]") { + session::network::config::SnodePool pool_config{ + .cache_expiration = 5min, + .cache_min_lifetime = 5min, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .cache_min_size = 0, + .cache_min_swarm_size = 0, + .cache_num_nodes_to_use_for_refresh = 0, + .cache_min_num_refresh_presence_to_include_node = 0, + .cache_node_strike_threshold = 3}; + + // Strikes are keyed by node pubkey, so these have to differ per node or striking one strikes + // every node sharing its key + std::vector> ed_pks{ + "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7"_hex_b, + "5ea34e72bb044654a6a23675690ef5ffaaf1656b02f93fb76655f9cbdbe89876"_hex_b, + "e17a692033200ae41350df9709754edde7343e2cf2f23e88f993319e0720e5e5"_hex_b, + "7b633fa6fb462b90db6f0f50384190ce7715e31b7aa93d87dbd7e94e33d4251f"_hex_b}; + std::vector snode_cache; + + for (uint16_t i = 0; i < ed_pks.size(); ++i) + snode_cache.emplace_back(service_node{ + ed25519_pubkey::from_bytes(ed_pks[i]), + oxen::quic::ipv4{"192.168.0.{}"_format(i)}, + static_cast(20000 + i), + static_cast(30000 + i), + {2, 11, 0}, + 0}); + + auto loop = std::make_shared(); + auto disk_loop = std::make_shared(); + auto snode_pool = std::make_shared(pool_config, *loop, *disk_loop); + snode_pool->reset_state_with_cache(snode_cache); + + snode_pool->record_node_failure(snode_cache[0], true); + snode_pool->record_node_failure(snode_cache[1], true); + REQUIRE(snode_pool->node_strike_count(snode_cache[0]) == 3); + REQUIRE(snode_pool->get_unused_nodes(4).size() == 2); + + // Once the strikes are older than `STRIKE_EXPIRY` the node has to become selectable again; a + // node dropped for a blip two days ago is not evidence about the node now + snode_pool->debug_age_strikes(49h); + CHECK(snode_pool->node_strike_count(snode_cache[0]) == 0); + CHECK(snode_pool->get_unused_nodes(4).size() == 4); + + // ... and a fresh failure starts from one rather than stacking onto the expired ones, which is + // also what stops the vector growing for the life of the process + snode_pool->record_node_failure(snode_cache[0]); + CHECK(snode_pool->node_strike_count(snode_cache[0]) == 1); + CHECK(snode_pool->debug_recorded_strikes(snode_cache[0].remote_pubkey) == 1); +} + +TEST_CASE("Network", "[network][refresh_callback_contract]") { + session::network::config::SnodePool pool_config{ + .cache_expiration = 2h, + .cache_min_lifetime = 2s, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .seed_nodes = {}, + .cache_min_size = 0, + .cache_min_swarm_size = 0, + .cache_num_nodes_to_use_for_refresh = 0, + .cache_min_num_refresh_presence_to_include_node = 0, + .cache_node_strike_threshold = 3}; + auto ed_pk = "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46ab7"_hex_b; + std::vector snode_cache; + + for (uint16_t i = 0; i < 5; ++i) + snode_cache.emplace_back(service_node{ + ed25519_pubkey::from_bytes(ed_pk), + oxen::quic::ipv4{"192.168.0.{}"_format(i)}, + static_cast(20000 + i), + static_cast(30000 + i), + {2, 11, 0}, + 0}); + + auto loop = std::make_shared(); + auto disk_loop = std::make_shared(); + auto snode_pool = std::make_shared(pool_config, *loop, *disk_loop); + + auto run = [&snode_pool] { + std::pair result{false, true}; // {called, refreshed} + snode_pool->debug_refresh_if_needed( + [&result](bool refreshed) { result = {true, refreshed}; }); + return result; + }; + + // An empty cache and no seed nodes means the refresh cannot even start. The callback still has + // to run: callers set state up before calling (`_resync_clock` sets its in-progress id) and + // never hearing back leaves that set for the life of the process. + auto [called, refreshed] = run(); + CHECK(called); + CHECK_FALSE(refreshed); + + // Nothing needing a refresh is the answer the caller asked for, not a failure to get one + snode_pool->update_cache(snode_cache); + std::tie(called, refreshed) = run(); + CHECK(called); + CHECK(refreshed); + + // ... and a suspended pool reports that it didn't refresh rather than going quiet + snode_pool->suspend(); + std::tie(called, refreshed) = run(); + CHECK(called); + CHECK_FALSE(refreshed); +} + +TEST_CASE("Network", "[network][suspend_refresh]") { + session::network::config::SnodePool pool_config{ + .cache_expiration = 2h, + .cache_min_lifetime = 2s, + .enforce_subnet_diversity = false, + .retry_delay = network::opt::retry_delay{50ms, 200ms}, + .netid = opt::netid::Target::testnet, + .cache_min_size = 1, + .cache_min_swarm_size = 1, + .cache_num_nodes_to_use_for_refresh = 1, + .cache_min_num_refresh_presence_to_include_node = 1, + .cache_node_strike_threshold = 3}; + + std::vector snode_cache; + for (uint16_t i = 0; i < 4; ++i) + snode_cache.emplace_back(service_node{ + ed25519_pubkey::from_hex( + "4cb76fdc6d32278e3f83dbf608360ecc6b65727934b85d2fb86862ff98c46a{:02x}"_format( + i)), + oxen::quic::ipv4{"192.168.0.{}"_format(i)}, + static_cast(20000 + i), + static_cast(30000 + i), + {2, 11, 0}, + 0}); + + // The default fetcher never answers, so a refresh stays in progress until the test ends it + auto loop = std::make_shared(); + auto disk_loop = std::make_shared(); + auto snode_pool = std::make_shared(pool_config, *loop, *disk_loop); + snode_pool->update_cache(snode_cache); + + SECTION("Suspending abandons a refresh in progress, and answers what waits on it") { + snode_pool->debug_start_refresh(); + REQUIRE(snode_pool->debug_refresh_in_progress()); + + std::optional answer; + snode_pool->debug_queue_post_refresh_callback( + [&answer](bool refreshed) { answer = refreshed; }); + snode_pool->debug_set_refresh_failure_count(3); + + snode_pool->suspend(); + CHECK(answer == false); + CHECK_FALSE(snode_pool->debug_refresh_in_progress()); + CHECK(snode_pool->debug_refresh_failure_count() == 0); + } + + SECTION("A fetch belonging to an abandoned refresh leaves the next refresh alone") { + snode_pool->debug_start_refresh(); + auto abandoned = snode_pool->debug_refresh_id(); + REQUIRE(abandoned); + snode_pool->suspend(); + snode_pool->resume(); + + snode_pool->debug_start_refresh(); + auto current = snode_pool->debug_refresh_id(); + REQUIRE(current); + REQUIRE(current != abandoned); + auto candidates = snode_pool->debug_refresh_candidate_count(); + + snode_pool->debug_launch_refresh_request(*abandoned); + CHECK(snode_pool->debug_refresh_id() == current); + CHECK(snode_pool->debug_refresh_candidate_count() == candidates); + } + + SECTION("An abandoned refresh's retry after running out of candidates restarts nothing") { + // Running out schedules a retry of the whole refresh, after the retry delay + auto run_out_then_suspend = [&] { + snode_pool->debug_start_refresh(); + auto id = snode_pool->debug_refresh_id(); + REQUIRE(id); + snode_pool->debug_clear_refresh_candidates(); + snode_pool->debug_launch_refresh_request(*id); + snode_pool->suspend(); + snode_pool->resume(); + }; + auto past_retry_delay = [] { std::this_thread::sleep_for(500ms); }; + + // Once it was the refresh that used to restart itself here + run_out_then_suspend(); + past_retry_delay(); + CHECK_FALSE(snode_pool->debug_refresh_in_progress()); + + // ... and with another refresh started by the time it fires, that one is left running + run_out_then_suspend(); + snode_pool->debug_start_refresh(); + auto current = snode_pool->debug_refresh_id(); + REQUIRE(current); + past_retry_delay(); + CHECK(snode_pool->debug_refresh_id() == current); + } +} diff --git a/tests/utils.hpp b/tests/utils.hpp index 08886bdae..34b771280 100644 --- a/tests/utils.hpp +++ b/tests/utils.hpp @@ -6,8 +6,10 @@ #include #include +#include #include #include +#include #include #include #include From f988c89abbce8abaec2799ffbe79144d03d61085 Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Wed, 7 Oct 2026 10:54:46 +1100 Subject: [PATCH 59/68] Don't dereference a connection that is already gone when a response arrives --- src/network/transport/quic_transport.cpp | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/network/transport/quic_transport.cpp b/src/network/transport/quic_transport.cpp index 1068c2f8d..b11779c1a 100644 --- a/src/network/transport/quic_transport.cpp +++ b/src/network/transport/quic_transport.cpp @@ -546,13 +546,21 @@ void QuicTransport::_send_on_connection( // Since the request completed it's round-trip if it isn't the "reserverd" stream // (not used for general requests) then we can either add it back to the pool, or // close it if there are more that the active stream price limit + // + // The connection can already be gone: libquic fires a request's callback from its + // destructor when the connection closes, and the connection's streams go with it. + // Then there is nothing to return to the pool or close, and any ids pooled for it + // are dead too. if (stream_id != 0 && _endpoint) { - auto conn = _endpoint->get_conn(conn_id); - - if (conn && conn->get_streams_available() <= ACTIVE_STREAM_PRUNE_LIMIT) - _available_stream_ids[conn_id].insert(stream_id); - else if (auto stream = conn->get_stream(stream_id)) - stream->close(); + if (auto conn = _endpoint->get_conn(conn_id)) { + if (conn->get_streams_available() <= ACTIVE_STREAM_PRUNE_LIMIT) + _available_stream_ids[conn_id].insert(stream_id); + else if ( + auto stream = + conn->get_stream(stream_id)) + stream->close(); + } else + _available_stream_ids.erase(conn_id); } if (resp.timed_out) { From 845d4f57f753b0f2cca5ba4b6ee8af3ac7525296 Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Wed, 7 Oct 2026 10:55:02 +1100 Subject: [PATCH 60/68] Clear only the closed connection's state when a connection fails --- .../network/transport/quic_transport.hpp | 3 ++- src/network/transport/quic_transport.cpp | 23 +++++++++++++++---- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/include/session/network/transport/quic_transport.hpp b/include/session/network/transport/quic_transport.hpp index 301ee9868..0e19fe028 100644 --- a/include/session/network/transport/quic_transport.hpp +++ b/include/session/network/transport/quic_transport.hpp @@ -104,7 +104,8 @@ class QuicTransport : public ITransport { const std::string& address_pubkey_hex, const std::string& initiating_req_id, std::optional error_code, - std::optional custom_error); + std::optional custom_error, + std::optional conn_id = std::nullopt); }; } // namespace session::network diff --git a/src/network/transport/quic_transport.cpp b/src/network/transport/quic_transport.cpp index b11779c1a..685e6f6dc 100644 --- a/src/network/transport/quic_transport.cpp +++ b/src/network/transport/quic_transport.cpp @@ -413,9 +413,13 @@ void QuicTransport::_establish_connection( } }, [this, address_pubkey_hex, initiating_req_id]( - oxen::quic::Connection&, uint64_t error_code) { + oxen::quic::Connection& conn, uint64_t error_code) { _fail_connection( - address_pubkey_hex, initiating_req_id, error_code, std::nullopt); + address_pubkey_hex, + initiating_req_id, + error_code, + std::nullopt, + conn.reference_id()); }); } catch (const std::exception& e) { _fail_connection(address_pubkey_hex, initiating_req_id, std::nullopt, e.what()); @@ -606,7 +610,8 @@ void QuicTransport::_fail_connection( const std::string& address_pubkey_hex, const std::string& initiating_req_id, std::optional error_code, - std::optional custom_error) { + std::optional custom_error, + std::optional conn_id) { if (error_code == 0) log::info( cat, @@ -649,8 +654,16 @@ void QuicTransport::_fail_connection( address_pubkey_hex, custom_error.value_or("Unknown error")); - // Clear the connection and stream ids - if (auto id = _active_connection_ids.extract(address_pubkey_hex)) + // Clear the connection and stream ids. When the closed connection is known, only its own + // state goes: a newer connection to the same node can be established before an old one's close + // arrives, and clearing by pubkey alone would drop the new connection and orphan the old one's + // stream ids. + if (conn_id) { + _available_stream_ids.erase(*conn_id); + if (auto it = _active_connection_ids.find(address_pubkey_hex); + it != _active_connection_ids.end() && it->second == *conn_id) + _active_connection_ids.erase(it); + } else if (auto id = _active_connection_ids.extract(address_pubkey_hex)) _available_stream_ids.erase(id.mapped()); // Process any waiting verification requests From 212367fa40b66b9e22b9a07d7a00230ce6d69f8b Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Tue, 6 Oct 2026 21:34:50 -0300 Subject: [PATCH 61/68] Say accurately when a response can arrive after its connection is gone On a normal close, libquic fails a stream's pending requests from close_all_streams() while the connection still exists; it only fails them from ~sent_request when a stream outlives its connection. --- src/network/transport/quic_transport.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/network/transport/quic_transport.cpp b/src/network/transport/quic_transport.cpp index 685e6f6dc..5fe8c325d 100644 --- a/src/network/transport/quic_transport.cpp +++ b/src/network/transport/quic_transport.cpp @@ -551,10 +551,9 @@ void QuicTransport::_send_on_connection( // (not used for general requests) then we can either add it back to the pool, or // close it if there are more that the active stream price limit // - // The connection can already be gone: libquic fires a request's callback from its - // destructor when the connection closes, and the connection's streams go with it. - // Then there is nothing to return to the pool or close, and any ids pooled for it - // are dead too. + // The connection can be gone by the time this runs, e.g. if the stream outlived it + // (libquic then fails the request from ~sent_request). Then there is nothing to + // return to the pool or close, and any ids pooled for it are dead too. if (stream_id != 0 && _endpoint) { if (auto conn = _endpoint->get_conn(conn_id)) { if (conn->get_streams_available() <= ACTIVE_STREAM_PRUNE_LIMIT) From 916e6218d5846f1be90e511ccf505e86e53b798d Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Fri, 9 Oct 2026 14:13:05 -0300 Subject: [PATCH 62/68] Fix missing direct linking to libzstd Static builds were getting this via implicit deps, but shared builds were failing to pick up libzstd headers. --- src/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 68c929ab2..f478c2fa9 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -113,6 +113,7 @@ target_link_libraries(crypto session::secure_buffer PRIVATE sessiondep::libsodium + sessiondep::libzstd # AES-CBC for legacy attachment decryption, which libsodium has no equivalent of: it exposes # AES only as GCM, and only where the hardware supports it. sessiondep::nettle From 158349e73d99132ca640978415305d471f725cd2 Mon Sep 17 00:00:00 2001 From: Morgan Pretty Date: Fri, 13 Nov 2026 11:30:44 +1100 Subject: [PATCH 63/68] Don't throw from QuicTransport::resume when the endpoint can't be created Resuming recreates the endpoint, whose socket setup throws on any failed socket call, and that exception escaped through session_network_resume to a caller that can't catch it: on iOS 2.15.6 this terminates the app on returning to the foreground or starting a background fetch. The failure is now logged with its errno and the transport resumes without an endpoint, which its next connection attempt creates. --- src/network/transport/quic_transport.cpp | 31 ++++++++-- tests/test_quic_transport.cpp | 72 ++++++++++++++++++++++++ 2 files changed, 99 insertions(+), 4 deletions(-) diff --git a/src/network/transport/quic_transport.cpp b/src/network/transport/quic_transport.cpp index 5fe8c325d..7cc6aa7b9 100644 --- a/src/network/transport/quic_transport.cpp +++ b/src/network/transport/quic_transport.cpp @@ -8,6 +8,8 @@ #include #include #include +#include +#include #include "session/crypto/ed25519.hpp" #include "session/network/session_network_types.hpp" @@ -25,6 +27,14 @@ namespace { static constexpr uint16_t ACTIVE_STREAM_PRUNE_LIMIT = 32; + // The errno is what says why a socket couldn't be opened, and a system_error's message + // doesn't always make it recoverable + std::string describe(const std::exception& e) { + if (const auto* se = dynamic_cast(&e)) + return "{} (errno {})"_format(se->what(), se->code().value()); + return e.what(); + } + inline bool use_reserved_stream(RequestCategory category) { switch (category) { case RequestCategory::standard: return false; @@ -79,8 +89,21 @@ void QuicTransport::resume(bool /*automatically_reconnect*/) { // Use 'call_get' to force this to be synchronous _jq.call_get([this] { // Recreate the endpoint before updating the `_suspended` flag to avoid the chance that - // something will try to use it before we are ready - _recreate_endpoint(); + // something will try to use it before we are ready. + // + // Opening its socket can fail, and an exception from here would escape `Network::resume` + // before the router resumes, into an app coming back to the foreground (on iOS it + // terminated the app). Left without an endpoint, the transport creates one on its next + // connection attempt. + try { + _recreate_endpoint(); + } catch (const std::exception& e) { + log::error( + cat, + "Unable to recreate the endpoint on resume, will retry on the next " + "connection: {}", + describe(e)); + } _suspended = false; log::info(cat, "Resumed."); }); @@ -305,7 +328,7 @@ void QuicTransport::_establish_connection( if (_suspended) throw std::runtime_error{"QuickTransport is suspended"}; if (!_endpoint) - throw std::runtime_error{"Network is invalid"}; + _recreate_endpoint(); auto [conn_pk, conn_sk] = ed25519::keypair(); auto creds = quic::GNUTLSCreds::make_from_ed_seckey(to_string_view(conn_sk)); @@ -422,7 +445,7 @@ void QuicTransport::_establish_connection( conn.reference_id()); }); } catch (const std::exception& e) { - _fail_connection(address_pubkey_hex, initiating_req_id, std::nullopt, e.what()); + _fail_connection(address_pubkey_hex, initiating_req_id, std::nullopt, describe(e)); } } diff --git a/tests/test_quic_transport.cpp b/tests/test_quic_transport.cpp index 4c72de858..c510e7ecf 100644 --- a/tests/test_quic_transport.cpp +++ b/tests/test_quic_transport.cpp @@ -1,12 +1,53 @@ +#include +#include +#include +#include + +#include #include #include #include #include +#include using namespace session::network; using namespace std::literals; namespace { +// Takes every file descriptor the process may open, under a lowered limit, so that the next +// socket() fails with EMFILE - a real failure of the endpoint's own socket setup, rather than an +// injected one. The descriptors and the limit are given back on destruction. +class exhausted_file_descriptors { + rlimit _original{}; + std::vector _fds; + + public: + exhausted_file_descriptors() { + getrlimit(RLIMIT_NOFILE, &_original); + auto lowered = _original; + lowered.rlim_cur = std::min(_original.rlim_cur, 1024); + setrlimit(RLIMIT_NOFILE, &lowered); + + for (int fd; (fd = ::open("/dev/null", O_RDONLY)) >= 0;) + _fds.push_back(fd); + } + + ~exhausted_file_descriptors() { + for (int fd : _fds) + ::close(fd); + setrlimit(RLIMIT_NOFILE, &_original); + } + + // Whether a socket can't be opened, which is what the tests below rely on + static bool socket_fails() { + int sock = ::socket(AF_INET6, SOCK_DGRAM, 0); + if (sock < 0) + return true; + ::close(sock); + return false; + } +}; + std::shared_ptr make_transport(oxen::quic::Loop& loop) { return std::make_shared( config::QuicTransport{.handshake_timeout = 1s, .keep_alive = 10s}, loop); @@ -76,3 +117,34 @@ TEST_CASE("Network", "[network][quic_transport][close_connections]") { CHECK_FALSE(success); CHECK_FALSE(error_code); } + +TEST_CASE("Network", "[network][quic_transport][resume]") { + auto loop = std::make_shared(); + auto transport = make_transport(*loop); + transport->suspend(); + + { + exhausted_file_descriptors no_fds; + REQUIRE(exhausted_file_descriptors::socket_fails()); + + // Throwing here would escape `Network::resume` before its router resumes + CHECK_NOTHROW(transport->resume(true)); + } + + // Once sockets can be opened again a connection attempt rebuilds the endpoint, so it is made + // and times out with an error code; without an endpoint it would fail at once with none + std::promise> error_code; + transport->verify_connectivity( + test_node(), + 3s, + "AAAA", + RequestCategory::standard, + [&error_code, answered = false](bool, std::optional e) mutable { + if (!std::exchange(answered, true)) + error_code.set_value(e); + }); + + auto answer = error_code.get_future(); + REQUIRE(answer.wait_for(10s) == std::future_status::ready); + CHECK(answer.get().has_value()); +} From 186bda76fa0e1828d738816161b0a0ada6a4f387 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 26 Nov 2026 13:05:47 -0400 Subject: [PATCH 64/68] Add opt::quic_congestion_control Lets a client choose BBR, cubic or Reno for its QUIC connections, through the C++ options, Config and QuicTransport's connect(). Unset leaves libquic's default, which libquic 1.13 changed from BBR to cubic; Session iOS wants to stay on BBR. The option is an alias for libquic's own oxen::quic::opt::congestion_control. Port of 1.x #211 (3721688e, 3cf6c453, by Morgan Pretty), without its C API additions. --- include/session/network/network_config.hpp | 2 ++ include/session/network/network_opt.hpp | 8 ++++++++ .../network/transport/quic_transport.hpp | 1 + src/network/network_config.cpp | 18 ++++++++++++++++++ src/network/session_network.cpp | 3 ++- src/network/transport/quic_transport.cpp | 1 + tests/CMakeLists.txt | 1 + tests/test_network_config.cpp | 16 ++++++++++++++++ 8 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 tests/test_network_config.cpp diff --git a/include/session/network/network_config.hpp b/include/session/network/network_config.hpp index c52247ee4..d3f8976cf 100644 --- a/include/session/network/network_config.hpp +++ b/include/session/network/network_config.hpp @@ -85,6 +85,7 @@ struct Config { std::chrono::seconds quic_keep_alive{10s}; std::optional quic_max_udp_payload; + std::optional quic_congestion_control; template requires(sizeof...(Opt) > 0 && (opt::is_option> && ...)) @@ -143,6 +144,7 @@ struct Config { void handle_config_opt(opt::quic_tunnel_handshake_timeout qtht); void handle_config_opt(opt::quic_keep_alive qka); void handle_config_opt(opt::quic_max_udp_payload qmup); + void handle_config_opt(opt::quic_congestion_control qcc); // Onion request router options void handle_config_opt(opt::onionreq_path_strike_threshold pst); diff --git a/include/session/network/network_opt.hpp b/include/session/network/network_opt.hpp index 021e98172..7f38f5a29 100644 --- a/include/session/network/network_opt.hpp +++ b/include/session/network/network_opt.hpp @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -435,6 +436,12 @@ namespace opt { explicit quic_max_udp_payload(size_t s) : size{s} {} }; + /// Can be used to choose the congestion control algorithm Quic connections use for what they + /// send; without it libquic's default is used. BBR keeps its sending rate through loss that + /// isn't caused by congestion, which suits jittery mobile networks, while cubic and reno back + /// off on any loss. + using quic_congestion_control = oxen::quic::opt::congestion_control; + // MARK: Onion Request Router Options /// Can be used to override the default (3) number of times a path can receive an error before @@ -531,6 +538,7 @@ namespace opt { quic_tunnel_handshake_timeout, quic_keep_alive, quic_max_udp_payload, + quic_congestion_control, // Onion request router options onionreq_path_strike_threshold, diff --git a/include/session/network/transport/quic_transport.hpp b/include/session/network/transport/quic_transport.hpp index 0e19fe028..d58be59f0 100644 --- a/include/session/network/transport/quic_transport.hpp +++ b/include/session/network/transport/quic_transport.hpp @@ -26,6 +26,7 @@ namespace config { std::chrono::seconds keep_alive; std::optional max_udp_payload; + std::optional congestion_control; }; } // namespace config diff --git a/src/network/network_config.cpp b/src/network/network_config.cpp index 8245a50bf..beda56044 100644 --- a/src/network/network_config.cpp +++ b/src/network/network_config.cpp @@ -272,6 +272,24 @@ void Config::handle_config_opt(opt::quic_max_udp_payload qmup) { log::debug(cat, "Network config max QUIC UDP payload set to {} bytes", qmup.size); } +void Config::handle_config_opt(opt::quic_congestion_control qcc) { + quic_congestion_control = qcc; + + switch (qcc) { + case opt::quic_congestion_control::bbr: + log::debug(cat, "Network config quic congestion control set to BBR"); + break; + + case opt::quic_congestion_control::cubic: + log::debug(cat, "Network config quic congestion control set to cubic"); + break; + + case opt::quic_congestion_control::reno: + log::debug(cat, "Network config quic congestion control set to Reno"); + break; + } +} + // MARK: Onion Request Router Options void Config::handle_config_opt(opt::onionreq_path_strike_threshold pst) { diff --git a/src/network/session_network.cpp b/src/network/session_network.cpp index fceacc95d..dba7909a4 100644 --- a/src/network/session_network.cpp +++ b/src/network/session_network.cpp @@ -105,7 +105,8 @@ namespace { return {main_config.quic_handshake_timeout, main_config.quic_tunnel_handshake_timeout, main_config.quic_keep_alive, - main_config.quic_max_udp_payload}; + main_config.quic_max_udp_payload, + main_config.quic_congestion_control}; } config::DirectRouter build_direct_router_config( diff --git a/src/network/transport/quic_transport.cpp b/src/network/transport/quic_transport.cpp index 7cc6aa7b9..f47e09284 100644 --- a/src/network/transport/quic_transport.cpp +++ b/src/network/transport/quic_transport.cpp @@ -351,6 +351,7 @@ void QuicTransport::_establish_connection( oxen::quic::opt::handshake_timeout{ tunnelled ? _config.tunnel_handshake_timeout : _config.handshake_timeout}, oxen::quic::opt::keep_alive{_config.keep_alive}, + _config.congestion_control, // libquic hands these a live Connection, so they run inline on the loop rather than // as jobs of ours. ~QuicTransport destroys the endpoint on the loop before the // members below are touched, so there is no window in which this can fire late. diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 942d83b9f..0c0a478fe 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -71,6 +71,7 @@ list(APPEND LIB_SESSION_UTESTS_SOURCES test_backed_session_open_group_server.cpp test_ip_country.cpp test_network_clock.cpp + test_network_config.cpp test_network_swarm.cpp test_onionreq.cpp test_onion_request_router.cpp diff --git a/tests/test_network_config.cpp b/tests/test_network_config.cpp new file mode 100644 index 000000000..2f666f576 --- /dev/null +++ b/tests/test_network_config.cpp @@ -0,0 +1,16 @@ +#include +#include + +using namespace session::network; + +TEST_CASE("Network config: QUIC congestion control", "[network][config][quic]") { + SECTION("unset by default") { + config::Config cfg{opt::quic_keep_alive{std::chrono::seconds{10}}}; + CHECK_FALSE(cfg.quic_congestion_control.has_value()); + } + SECTION("explicit algorithm") { + config::Config cfg{opt::quic_congestion_control::bbr}; + REQUIRE(cfg.quic_congestion_control.has_value()); + CHECK(*cfg.quic_congestion_control == opt::quic_congestion_control::bbr); + } +} From da4443ed8ad7304165a1006fabc2069683b76b2d Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 26 Nov 2026 13:08:41 -0400 Subject: [PATCH 65/68] Build the static bundle from one walk of the link closure The bundle's archive list came from libsession_static_bundle() calls scattered across src/, proto/ and external/, each of which also tried to recurse into the target's dependencies at a point (right after add_library) where it had none yet. On 1.x that silently lost libquic, oxen-logging, fmt, spdlog, ngtcp2, gnutls, nettle and the rest when dependencies stopped being registered by hand, and the 1.9.3 iOS build failed to link. Replace all of that with a single walk, run once every target is linked, from the libraries we export: every static library in their link closure goes into the bundle, so it can no longer drift from what is actually linked. Everything else in the closure (system libraries, frameworks, imported non-static targets such as Threads::Threads) is returned separately, since it has to be supplied by whatever links the bundle. A generator expression or imported target the walk cannot see into is a configure error rather than a silent omission. static-bundle-test now links the bundle and nothing but the system requirements the walk reports, calls into config, the network and image code, and is defined alongside the bundle rather than under tests/ so it does not need WITH_TESTS. static-bundle.sh, which every static job goes through, builds it after the bundle, so a dependency missing from the bundle fails the build that produces it. The iOS modulemap autolinks iconv: libunistring needs it, and session-deps takes it from the system on Apple. Port of 1.x #181 (867ea7bb, 741df684, 6824566e, by Morgan Pretty and Jason Rhinelander), with dev's libvips, libheif and jpegli covered by the walk and exercised by the test. --- CMakeLists.txt | 29 +++++++++-- cmake/AddStaticBundleLib.cmake | 93 ++++++++++++++++++++++++---------- external/CMakeLists.txt | 7 --- proto/CMakeLists.txt | 5 -- src/CMakeLists.txt | 3 -- tests/CMakeLists.txt | 7 --- tests/static_bundle.cpp | 12 ++++- utils/ios.sh | 4 ++ utils/static-bundle.sh | 4 +- 9 files changed, 108 insertions(+), 56 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 809a33068..eef65b807 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -78,9 +78,9 @@ if(STATIC_BUNDLE AND NOT BUILD_STATIC_DEPS) message(FATAL_ERROR "STATIC_BUNDLE requires BUILD_STATIC_DEPS to be enabled") endif() -# A shared build has no static archives for our own libraries, and libsession_static_bundle() -# silently skips non-static targets: the bundle would come out holding only the dependencies, which -# only shows up as undefined libsession symbols when something links against it. +# A shared build has no static archives for our own libraries, and the bundle walk only collects +# static ones: the bundle would come out holding only the dependencies, which only shows up as +# undefined libsession symbols when something links against it. if(STATIC_BUNDLE AND BUILD_SHARED_LIBS) message(FATAL_ERROR "STATIC_BUNDLE is incompatible with BUILD_SHARED_LIBS") endif() @@ -188,7 +188,28 @@ if(STATIC_BUNDLE) include(combine_archives) - combine_archives(session-util libsession-static-bundle "${LIBSESSION_STATIC_BUNDLE_LIBS}") + # Threads::Threads comes from find_package() calls in subdirectories, which make it visible only + # there; the bundle walk has to be able to see it. + find_package(Threads REQUIRED) + libsession_static_bundle_libs(bundle_archives bundle_system_libs ${libsession_export_targets}) + message(STATUS "Static bundle libsession-util.a combines: ${bundle_archives}") + message(STATUS "Static bundle libsession-util.a also needs: ${bundle_system_libs}") + combine_archives(session-util libsession-static-bundle ${bundle_archives}) + + # Links the bundle and only what the walk says it needs from the system, so that a library + # missing from the bundle fails here rather than in whatever consumes it. Headers come from our + # targets' usage requirements, without linking them. + add_executable(static-bundle-test tests/static_bundle.cpp) + foreach(header_target network image) + target_include_directories(static-bundle-test PRIVATE + $) + target_compile_definitions(static-bundle-test PRIVATE + $) + endforeach() + target_link_libraries(static-bundle-test PRIVATE + "${CMAKE_CURRENT_BINARY_DIR}/libsession-util.a" ${bundle_system_libs}) + add_dependencies(static-bundle-test session-util) + set(lib_folder lib) if(IOS) set(lib_folder "${lib_folder}-${ARCH}") diff --git a/cmake/AddStaticBundleLib.cmake b/cmake/AddStaticBundleLib.cmake index 2e37c0b67..e357f30a7 100644 --- a/cmake/AddStaticBundleLib.cmake +++ b/cmake/AddStaticBundleLib.cmake @@ -1,36 +1,73 @@ - -set(LIBSESSION_STATIC_BUNDLE_LIBS "" CACHE INTERNAL "list of libs to go into the static bundle lib") - -function(_libsession_static_bundle_append tgt) - list(APPEND LIBSESSION_STATIC_BUNDLE_LIBS "${tgt}") - set(LIBSESSION_STATIC_BUNDLE_LIBS "${LIBSESSION_STATIC_BUNDLE_LIBS}" CACHE INTERNAL "") -endfunction() - # Call as: # -# libsession_static_bundle(target [target2 ...]) +# libsession_static_bundle_libs(ARCHIVES_VAR SYSTEM_VAR target [target2 ...]) # -# to append the given target(s) to the list of libraries that will be combined to make the static -# bundled libsession-util.a. -function(libsession_static_bundle) - foreach(tgt IN LISTS ARGN) - if(TARGET "${tgt}" AND NOT "${tgt}" IN_LIST LIBSESSION_STATIC_BUNDLE_LIBS) - get_target_property(tgt_type ${tgt} TYPE) - - if(tgt_type STREQUAL STATIC_LIBRARY) - message(STATUS "Adding ${tgt} to libsession-util bundled library list") - _libsession_static_bundle_append("${tgt}") +# to walk the link closure of the given targets. ARCHIVES_VAR is set to every static library in +# it: the archives that combine into the STATIC_BUNDLE libsession-util.a. SYSTEM_VAR is set to +# everything else the closure links: system libraries such as iconv, Apple frameworks, linker flags +# and imported non-static targets such as Threads::Threads. None of those can go into an archive, +# so whatever links the bundle has to supply them. +# +# The closure is read from the targets' link properties, so this has to be called after every +# target_link_libraries() it depends on. +function(libsession_static_bundle_libs archives_out system_out) + set(pending ${ARGN}) + set(visited) + set(archives) + set(system) + while(NOT "${pending}" STREQUAL "") + list(POP_FRONT pending tgt) + if(tgt MATCHES "^\\$$") + set(tgt "${CMAKE_MATCH_1}") + endif() + if(NOT TARGET "${tgt}") + # Silently skipping either of these could drop a library from the bundle, which then + # only shows up when something links against it. A `::` name is an imported target + # created in some subdirectory without GLOBAL, which we cannot see (let alone look + # inside) from here: find_package() it before calling this. + if(tgt MATCHES "\\$<") + message(FATAL_ERROR "Static bundle: don't know how to follow link item ${tgt}") endif() - - if(tgt_type STREQUAL INTERFACE_LIBRARY) - get_target_property(tgt_link_deps ${tgt} INTERFACE_LINK_LIBRARIES) - else() - get_target_property(tgt_link_deps ${tgt} LINK_LIBRARIES) + if(tgt MATCHES "::") + message(FATAL_ERROR "Static bundle: imported target ${tgt} is not visible here") endif() + list(APPEND system "${tgt}") + continue() + endif() + get_target_property(aliased ${tgt} ALIASED_TARGET) + if(aliased) + set(tgt "${aliased}") + endif() + if(tgt IN_LIST visited) + continue() + endif() + list(APPEND visited "${tgt}") - if(tgt_link_deps) - libsession_static_bundle(${tgt_link_deps}) - endif() + get_target_property(type ${tgt} TYPE) + get_target_property(imported ${tgt} IMPORTED) + if(type STREQUAL STATIC_LIBRARY) + list(APPEND archives "${tgt}") + elseif(imported) + # Something the system provides (Threads::Threads). Linking it by name brings + # everything it carries, including link options, which this walk does not read. + list(APPEND system "${tgt}") + continue() + endif() + + # An imported target (which is what session-deps produces for each static dependency) + # carries its dependencies only in INTERFACE_LINK_LIBRARIES; one built here also has its + # private ones in LINK_LIBRARIES. + get_target_property(deps ${tgt} INTERFACE_LINK_LIBRARIES) + if(NOT type STREQUAL INTERFACE_LIBRARY AND NOT imported) + get_target_property(link_deps ${tgt} LINK_LIBRARIES) + list(APPEND deps ${link_deps}) endif() - endforeach() + # ::@(dir) ... ::@ are cmake's own markers around items that target_link_libraries() added + # from another directory, not link items themselves. + list(FILTER deps EXCLUDE REGEX "-NOTFOUND$|^::@") + list(APPEND pending ${deps}) + endwhile() + list(REMOVE_DUPLICATES system) + set(${archives_out} "${archives}" PARENT_SCOPE) + set(${system_out} "${system}" PARENT_SCOPE) endfunction() diff --git a/external/CMakeLists.txt b/external/CMakeLists.txt index 25296dced..834de7e00 100644 --- a/external/CMakeLists.txt +++ b/external/CMakeLists.txt @@ -29,7 +29,6 @@ function(static_sessiondep_or_submodule) endfunction() session_dep(libsodium 1.0.21) -libsession_static_bundle(sessiondep::libsodium) if(NOT TARGET oxenc::oxenc) set(OXENC_BUILD_TESTS OFF CACHE BOOL "") @@ -83,7 +82,6 @@ set(SROUTER_JEMALLOC OFF CACHE BOOL "") # 1.1.1 is the first release with session::mlkem768 and installed headers. static_sessiondep_or_submodule(libsessionrouter-core 1.1.1 session-router session-router::core) -libsession_static_bundle(session-router::core) # The session-router submodule has already provided oxen::quic; this is for a system session-router, # for which the check above has made sure this finds the system libquic. @@ -130,7 +128,6 @@ sessiondep_or_submodule(protobuf-lite 3.21 protobuf protobuf::libprotobuf-lite) # configs get deduplicated at the swarm. set(BUILD_STATIC_libzstd ON CACHE BOOL "" FORCE) session_dep(libzstd 1.5) -libsession_static_bundle(sessiondep::libzstd) if(NOT TARGET nlohmann_json::nlohmann_json) set(JSON_BuildTests OFF CACHE INTERNAL "") @@ -140,24 +137,20 @@ endif() session_dep(simdutf 7) -libsession_static_bundle(sessiondep::simdutf) # 8.13 added vips_operation_block_set(), which the loader whitelist in src/image/vips.cpp needs: a # system libvips may carry loaders (svg, pdf, tiff, ...) that our static build leaves out. session_dep(vips 8.13) -libsession_static_bundle(sessiondep::vips) # libvips' own HEIF support cannot say which codec a HEIF file uses (it guesses from the brand), # so libsession::image asks libheif directly; 1.19 is the first with the grid tile API it needs. session_dep(libheif 1.19) -libsession_static_bundle(sessiondep::libheif) if(SESSION_ENABLE_JPEGLI) # Always our own build, even when everything else comes from the system: distributions do not # package jpegli, and we want every client encoding JPEGs the same way whatever libvips it has. set(BUILD_STATIC_jpegli ON CACHE BOOL "" FORCE) session_dep(jpegli 0) - libsession_static_bundle(sessiondep::jpegli) endif() diff --git a/proto/CMakeLists.txt b/proto/CMakeLists.txt index 52c3a6c37..944cd3142 100644 --- a/proto/CMakeLists.txt +++ b/proto/CMakeLists.txt @@ -1,7 +1,4 @@ -libsession_static_bundle(protobuf::libprotobuf-lite) - - add_library(protos SessionProtos.pb.cc WebSocketResources.pb.cc @@ -23,8 +20,6 @@ else() target_compile_options(protos PUBLIC -Wno-error=unused-parameter) endif() -libsession_static_bundle(protos) - add_library(libsession::protos ALIAS protos) list(APPEND libsession_export_targets protos) set(libsession_export_targets "${libsession_export_targets}" PARENT_SCOPE) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index f478c2fa9..35e972071 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -44,8 +44,6 @@ macro(add_libsession_util_library name) OUTPUT_NAME session-${name} SOVERSION ${LIBSESSION_LIBVERSION}) - libsession_static_bundle(${name}) - list(APPEND export_targets ${name}) endmacro() @@ -318,7 +316,6 @@ else() endif() endif() add_library(version STATIC version.c) -libsession_static_bundle(version) target_include_directories(version PRIVATE ../include) target_link_libraries(common INTERFACE version) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 0c0a478fe..de8a6a909 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -174,10 +174,3 @@ endif() add_executable(swarm-auth-test EXCLUDE_FROM_ALL swarm-auth-test.cpp) target_link_libraries(swarm-auth-test PRIVATE config) - -if(STATIC_BUNDLE) - add_executable(static-bundle-test static_bundle.cpp) - target_include_directories(static-bundle-test PUBLIC ../include) - target_link_libraries(static-bundle-test PRIVATE "${PROJECT_BINARY_DIR}/libsession-util.a" oxenc::oxenc oxen::quic) - add_dependencies(static-bundle-test session-util) -endif() diff --git a/tests/static_bundle.cpp b/tests/static_bundle.cpp index b90084b1c..89933ad55 100644 --- a/tests/static_bundle.cpp +++ b/tests/static_bundle.cpp @@ -1,12 +1,22 @@ // This file isn't designed to do anything useful, but just to test that we can compile and link -// against the combined static bundle (when using cmake ... -DSTATIC_BUILD=ON) +// against the combined static bundle (when using cmake ... -DSTATIC_BUNDLE=ON) with nothing else. +// The calls are there to make the linker pull in the code that needs the bundle's dependencies: +// config for libsodium/protobuf/zstd, the network for libquic, gnutls, ngtcp2 and libevent, and +// image for libvips and libheif. #include #include +#include +#include +#include int main() { if (std::mt19937_64{}() == 123) { auto& k = *reinterpret_cast(12345); k.encrypt_message(std::span{}); + auto& n = *reinterpret_cast(12345); + n.close_connections(); + session::image::init(); + (void)session::image::probe(*reinterpret_cast(12345)); } } diff --git a/utils/ios.sh b/utils/ios.sh index 46b1ef2de..d07bee64f 100755 --- a/utils/ios.sh +++ b/utils/ios.sh @@ -215,6 +215,10 @@ if [ "${SHOULD_CREATE_FRAMEWORK}" == "SHOULD_CREATE_FRAMEWORK" ]; then # The 'module.modulemap' is needed for XCode to be able to find the headers modmap="${OUTPUT_DIR}/module.modulemap" echo "module SessionUtil {" >"$modmap" + # libunistring (via gnutls -> libidn2) calls iconv, which session-deps takes from the system on + # Apple rather than bundling. An SPM binary target can't declare linker flags, so autolink it + # from the module instead. + echo " link \"iconv\"" >>"$modmap" echo " module capi {" >>"$modmap" for x in $(cd include && find session -name '*.h'); do echo " header \"$x\"" >>"$modmap" diff --git a/utils/static-bundle.sh b/utils/static-bundle.sh index e179dd3ba..cee8c49e3 100755 --- a/utils/static-bundle.sh +++ b/utils/static-bundle.sh @@ -66,7 +66,9 @@ cmake -G 'Unix Makefiles' \ "$@" \ "$projdir" -make -j${JOBS:-$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 1)} VERBOSE=1 session-util +# static-bundle-test links against nothing but the bundle and its declared system libraries, so +# building it is what catches a dependency missing from the bundle. +make -j${JOBS:-$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 1)} VERBOSE=1 session-util static-bundle-test if [ -z "$archive" ]; then exit 0 From f996e00abab0f2e082b3cfd8bfce9685935f2dd9 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 26 Nov 2026 17:30:16 -0400 Subject: [PATCH 66/68] Refuse shared libraries with static dependencies Each of our shared libraries, and each executable linking them, is a separate final link, so every one that uses a static dependency gets its own copy of it. With BUILD_SHARED_LIBS and BUILD_STATIC_DEPS both on, gnutls (with libtasn1, nettle, gmp and libidn2) went into libsession-crypto.so through session-router, and again into any executable linking libsession-network.so, whose public oxen::quic brings libquic.a and its whole chain onto the consumer's link line. The copies export the same symbols, so crypto's gnutls bound to the executable's _gnutls_pkix1_asn, found it already filled in, and failed to initialize ("ASN1 parser: Generic parsing error"); every TLS credential after that failed. No test created one until the resume test, which is what the Ubuntu 22.04 job's failure was. Nothing ships that combination: packages build shared against system libraries, and apps link static libraries or the static bundle, where everything is linked once. Make it a configure error, and build the Ubuntu 22.04 job's libraries static, which is what its static dependencies are there to test. --- .woodpecker/build.star | 10 ++++++++-- CMakeLists.txt | 11 +++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/.woodpecker/build.star b/.woodpecker/build.star index 5a6c8cfc4..45e4f3a01 100644 --- a/.woodpecker/build.star +++ b/.woodpecker/build.star @@ -431,8 +431,14 @@ def main(ctx): # The one build that compiles every dependency itself rather than taking the distro's, on # the oldest distro we support: what the release artifacts do, and the only thing that - # notices when a dependency we vendor stops building. - linux("Ubuntu 22.04 (static deps)", "ubuntu-jammy", cmake = {"BUILD_STATIC_DEPS": True}, meson = "pip"), + # notices when a dependency we vendor stops building. Static libraries as well, because + # shared ones cannot take static dependencies (see the top-level CMakeLists.txt). + linux( + "Ubuntu 22.04 (static deps)", + "ubuntu-jammy", + cmake = {"BUILD_STATIC_DEPS": True, "BUILD_SHARED_LIBS": False}, + meson = "pip", + ), # ARM builds; armhf builds in a 32-bit image on the arm64 agents. linux("Debian sid (ARM64)", "debian-sid", arch = "arm64", jobs = 4), diff --git a/CMakeLists.txt b/CMakeLists.txt index eef65b807..682518628 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -70,6 +70,17 @@ endif() # defaults to the same value as BUILD_SHARED_LIBS (i.e. static by default). set(BUILD_STATIC_DEPS ${static_default} CACHE BOOL "Build all dependencies statically rather than trying to link to them on the system") +# Each of our shared libraries, and anything linking them, is a separate final link, so every one of +# them that uses a static dependency gets its own copy: gnutls ends up in libsession-crypto.so and +# again in an executable that links oxen::quic through libsession-network.so. The copies export the +# same symbols, so in one process they bind to each other's globals: the second gnutls finds its +# ASN.1 tables already filled in by the first and fails to initialize. +if(BUILD_SHARED_LIBS AND BUILD_STATIC_DEPS) + message(FATAL_ERROR "BUILD_SHARED_LIBS is incompatible with BUILD_STATIC_DEPS: shared libraries " + "need shared (system) dependencies. Configure with -DBUILD_STATIC_DEPS=OFF, or build static " + "libraries.") +endif() + include(cmake/session-deps/Deps.cmake) option(STATIC_BUNDLE "Build a single static .a containing everything (both code and dependencies)" OFF) From 171fc2ea5c6dd83469cc4c421b93fcb7ac0efe72 Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 26 Nov 2026 18:47:23 -0400 Subject: [PATCH 67/68] Bump session-deps for libheif's static define in its public Cflags session-foundation/session-deps#11: libvips built with a meson older than 1.11 compiled its HEIF loader and saver against libheif's DLL declarations, which left the mingw static bundle with 74 undefined __imp_heif_* symbols. --- cmake/session-deps | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/session-deps b/cmake/session-deps index 83c2166db..70e586fc0 160000 --- a/cmake/session-deps +++ b/cmake/session-deps @@ -1 +1 @@ -Subproject commit 83c2166dbc9803b0b9de49b0180352e5cc9327db +Subproject commit 70e586fc025dd82f7bb02877e3ba18b396ad6d01 From ddc32f59d02cb44457fed101d414c2f5cd5b456f Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Thu, 26 Nov 2026 19:50:49 -0400 Subject: [PATCH 68/68] Bump session-router to drop win32::error and to_wide() from core session-foundation/session-router#79: core's util/str.cpp threw win32::error, which only the full build compiles, so the mingw static bundle failed to link on srouter::win32::error::error(). --- external/session-router | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/external/session-router b/external/session-router index dcd97d51d..265832a03 160000 --- a/external/session-router +++ b/external/session-router @@ -1 +1 @@ -Subproject commit dcd97d51de6398460d9761cefa9e402282387af4 +Subproject commit 265832a03a9b7ffa523900eab1bd5c3aaa4e41ee