chore: misc code cleanups (#6927)

* refactor: avoid repeated subscripting in `announcer-udp.cc`

* chore: remove redundant locking in global ip cache

* chore: misc code cleanup in global ip cache

* fixup! chore: misc code cleanup in global ip cache

* refactor: remove `tr_global_ip_cache::create()`

* refactor: rename `tr_global_ip_cache` to `tr_ip_cache`

* build: sync changes to xcode
This commit is contained in:
Yat Ho
2024-07-14 08:37:55 +08:00
committed by GitHub
parent 7f79cb16ee
commit a76a07ae99
9 changed files with 106 additions and 116 deletions

View File

@@ -456,8 +456,8 @@
ED8A16412735A8AA000D61F9 /* peer-mgr-wishlist.h in Headers */ = {isa = PBXBuildFile; fileRef = ED8A163D2735A8AA000D61F9 /* peer-mgr-wishlist.h */; }; ED8A16412735A8AA000D61F9 /* peer-mgr-wishlist.h in Headers */ = {isa = PBXBuildFile; fileRef = ED8A163D2735A8AA000D61F9 /* peer-mgr-wishlist.h */; };
ED8A16422735A8AA000D61F9 /* peer-mgr-wishlist.cc in Sources */ = {isa = PBXBuildFile; fileRef = ED8A163E2735A8AA000D61F9 /* peer-mgr-wishlist.cc */; }; ED8A16422735A8AA000D61F9 /* peer-mgr-wishlist.cc in Sources */ = {isa = PBXBuildFile; fileRef = ED8A163E2735A8AA000D61F9 /* peer-mgr-wishlist.cc */; };
ED9862972B979AA2002F3035 /* Utils.mm in Sources */ = {isa = PBXBuildFile; fileRef = ED9862962B979AA2002F3035 /* Utils.mm */; }; ED9862972B979AA2002F3035 /* Utils.mm in Sources */ = {isa = PBXBuildFile; fileRef = ED9862962B979AA2002F3035 /* Utils.mm */; };
EDBAAC8C29E486BC00D9495F /* global-ip-cache.h in Headers */ = {isa = PBXBuildFile; fileRef = EDBAAC8B29E486BC00D9495F /* global-ip-cache.h */; }; EDBAAC8C29E486BC00D9495F /* ip-cache.h in Headers */ = {isa = PBXBuildFile; fileRef = EDBAAC8B29E486BC00D9495F /* ip-cache.h */; };
EDBAAC8E29E486C200D9495F /* global-ip-cache.cc in Sources */ = {isa = PBXBuildFile; fileRef = EDBAAC8D29E486C200D9495F /* global-ip-cache.cc */; }; EDBAAC8E29E486C200D9495F /* ip-cache.cc in Sources */ = {isa = PBXBuildFile; fileRef = EDBAAC8D29E486C200D9495F /* ip-cache.cc */; };
EDBDFA9E25AFCCA60093D9C1 /* evutil_time.c in Sources */ = {isa = PBXBuildFile; fileRef = EDBDFA9D25AFCCA60093D9C1 /* evutil_time.c */; }; EDBDFA9E25AFCCA60093D9C1 /* evutil_time.c in Sources */ = {isa = PBXBuildFile; fileRef = EDBDFA9D25AFCCA60093D9C1 /* evutil_time.c */; };
F11545ACA7C4D7A464F703AB /* block-info.h in Headers */ = {isa = PBXBuildFile; fileRef = 6A044CBD8C049AFCBD4DB411 /* block-info.h */; settings = {ATTRIBUTES = (Project, ); }; }; F11545ACA7C4D7A464F703AB /* block-info.h in Headers */ = {isa = PBXBuildFile; fileRef = 6A044CBD8C049AFCBD4DB411 /* block-info.h */; settings = {ATTRIBUTES = (Project, ); }; };
F63480631E1D7274005B9E09 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = F63480621E1D7274005B9E09 /* Images.xcassets */; }; F63480631E1D7274005B9E09 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = F63480621E1D7274005B9E09 /* Images.xcassets */; };
@@ -1376,8 +1376,8 @@
ED8A163E2735A8AA000D61F9 /* peer-mgr-wishlist.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = "peer-mgr-wishlist.cc"; sourceTree = "<group>"; }; ED8A163E2735A8AA000D61F9 /* peer-mgr-wishlist.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = "peer-mgr-wishlist.cc"; sourceTree = "<group>"; };
ED9862952B979AA2002F3035 /* Utils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Utils.h; sourceTree = "<group>"; }; ED9862952B979AA2002F3035 /* Utils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Utils.h; sourceTree = "<group>"; };
ED9862962B979AA2002F3035 /* Utils.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = Utils.mm; sourceTree = "<group>"; }; ED9862962B979AA2002F3035 /* Utils.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = Utils.mm; sourceTree = "<group>"; };
EDBAAC8B29E486BC00D9495F /* global-ip-cache.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 4; path = "global-ip-cache.h"; sourceTree = "<group>"; }; EDBAAC8B29E486BC00D9495F /* ip-cache.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.h; fileEncoding = 4; path = "ip-cache.h"; sourceTree = "<group>"; };
EDBAAC8D29E486C200D9495F /* global-ip-cache.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = "global-ip-cache.cc"; sourceTree = "<group>"; }; EDBAAC8D29E486C200D9495F /* ip-cache.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = "ip-cache.cc"; sourceTree = "<group>"; };
EDBDFA9D25AFCCA60093D9C1 /* evutil_time.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = evutil_time.c; sourceTree = "<group>"; }; EDBDFA9D25AFCCA60093D9C1 /* evutil_time.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = evutil_time.c; sourceTree = "<group>"; };
F63480621E1D7274005B9E09 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = Images/Images.xcassets; sourceTree = "<group>"; }; F63480621E1D7274005B9E09 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = Images/Images.xcassets; sourceTree = "<group>"; };
/* End PBXFileReference section */ /* End PBXFileReference section */
@@ -1838,14 +1838,14 @@
C1077A4C183EB29600634C22 /* file-posix.cc */, C1077A4C183EB29600634C22 /* file-posix.cc */,
C1305EB8186A134000F03351 /* file.cc */, C1305EB8186A134000F03351 /* file.cc */,
C1077A4D183EB29600634C22 /* file.h */, C1077A4D183EB29600634C22 /* file.h */,
EDBAAC8D29E486C200D9495F /* global-ip-cache.cc */,
EDBAAC8B29E486BC00D9495F /* global-ip-cache.h */,
4D36BA630CA2F00800A63CA5 /* handshake.cc */, 4D36BA630CA2F00800A63CA5 /* handshake.cc */,
4D36BA640CA2F00800A63CA5 /* handshake.h */, 4D36BA640CA2F00800A63CA5 /* handshake.h */,
A209EE5B1144B51E002B02D1 /* history.h */, A209EE5B1144B51E002B02D1 /* history.h */,
BEFC1E160C07861A00B0BB3C /* inout.cc */, BEFC1E160C07861A00B0BB3C /* inout.cc */,
BEFC1E150C07861A00B0BB3C /* inout.h */, BEFC1E150C07861A00B0BB3C /* inout.h */,
E23B55A5FC3B557F7746D511 /* interned-string.h */, E23B55A5FC3B557F7746D511 /* interned-string.h */,
EDBAAC8D29E486C200D9495F /* ip-cache.cc */,
EDBAAC8B29E486BC00D9495F /* ip-cache.h */,
A2AF23C616B44FA0003BC59E /* log.cc */, A2AF23C616B44FA0003BC59E /* log.cc */,
A2AF23C716B44FA0003BC59E /* log.h */, A2AF23C716B44FA0003BC59E /* log.h */,
4D80185710BBC0B0008A4AF2 /* magnet-metainfo.cc */, 4D80185710BBC0B0008A4AF2 /* magnet-metainfo.cc */,
@@ -2443,7 +2443,7 @@
CAB35C64252F6F5E00552A55 /* mime-types.h in Headers */, CAB35C64252F6F5E00552A55 /* mime-types.h in Headers */,
2856E0656A49F2665D69E760 /* benc.h in Headers */, 2856E0656A49F2665D69E760 /* benc.h in Headers */,
E975121263DD973CAF4AEBA0 /* timer.h in Headers */, E975121263DD973CAF4AEBA0 /* timer.h in Headers */,
EDBAAC8C29E486BC00D9495F /* global-ip-cache.h in Headers */, EDBAAC8C29E486BC00D9495F /* ip-cache.h in Headers */,
E975121263DD973CAF4AEBA2 /* timer-ev.h in Headers */, E975121263DD973CAF4AEBA2 /* timer-ev.h in Headers */,
C1077A4F183EB29600634C22 /* error.h in Headers */, C1077A4F183EB29600634C22 /* error.h in Headers */,
A2679295130E00A000CB7464 /* tr-utp.h in Headers */, A2679295130E00A000CB7464 /* tr-utp.h in Headers */,
@@ -3158,7 +3158,7 @@
files = ( files = (
BEFC1E2B0C07861A00B0BB3C /* utils.cc in Sources */, BEFC1E2B0C07861A00B0BB3C /* utils.cc in Sources */,
A2AAB65F0DE0CF6200E04DDA /* rpcimpl.cc in Sources */, A2AAB65F0DE0CF6200E04DDA /* rpcimpl.cc in Sources */,
EDBAAC8E29E486C200D9495F /* global-ip-cache.cc in Sources */, EDBAAC8E29E486C200D9495F /* ip-cache.cc in Sources */,
BEFC1E2D0C07861A00B0BB3C /* port-forwarding-upnp.cc in Sources */, BEFC1E2D0C07861A00B0BB3C /* port-forwarding-upnp.cc in Sources */,
A2AAB65C0DE0CF6200E04DDA /* rpc-server.cc in Sources */, A2AAB65C0DE0CF6200E04DDA /* rpc-server.cc in Sources */,
ED8A16402735A8AA000D61F9 /* peer-mgr-active-requests.cc in Sources */, ED8A16402735A8AA000D61F9 /* peer-mgr-active-requests.cc in Sources */,

View File

@@ -59,13 +59,13 @@ target_sources(${TR_NAME}
file-win32.cc file-win32.cc
file.cc file.cc
file.h file.h
global-ip-cache.cc
global-ip-cache.h
handshake.cc handshake.cc
handshake.h handshake.h
history.h history.h
inout.cc inout.cc
inout.h inout.h
ip-cache.cc
ip-cache.h
log.cc log.cc
log.h log.h
lru-cache.h lru-cache.h

View File

@@ -361,14 +361,12 @@ struct tau_tracker
if (action == TAU_ACTION_CONNECT) if (action == TAU_ACTION_CONNECT)
{ {
connection_id[ip_protocol] = buf.to_uint64(); auto& conn_id = connection_id[ip_protocol];
conn_id = buf.to_uint64();
connection_expiration_time[ip_protocol] = tr_time() + TauConnectionTtlSecs; connection_expiration_time[ip_protocol] = tr_time() + TauConnectionTtlSecs;
logdbg( logdbg(
log_name(), log_name(),
fmt::format( fmt::format("Got a new {} connection ID from tracker: {}", tr_ip_protocol_to_sv(ip_protocol), conn_id));
"Got a new {} connection ID from tracker: {}",
tr_ip_protocol_to_sv(ip_protocol),
connection_id[ip_protocol]));
} }
else if (action == TAU_ACTION_ERROR) else if (action == TAU_ACTION_ERROR)
{ {
@@ -406,10 +404,10 @@ struct tau_tracker
for (ipp_t ipp = 0; ipp < NUM_TR_AF_INET_TYPES; ++ipp) for (ipp_t ipp = 0; ipp < NUM_TR_AF_INET_TYPES; ++ipp)
{ {
// update the addr if our lookup is past its shelf date // update the addr if our lookup is past its shelf date
if (!addr_pending_dns_[ipp] && addr_expires_at_[ipp] <= now) if (auto& dns = addr_pending_dns_[ipp]; !dns && addr_expires_at_[ipp] <= now)
{ {
addr_[ipp].reset(); addr_[ipp].reset();
addr_pending_dns_[ipp] = std::async( dns = std::async(
std::launch::async, std::launch::async,
[this](tr_address_type ip_protocol) { return lookup(ip_protocol); }, [this](tr_address_type ip_protocol) { return lookup(ip_protocol); },
static_cast<tr_address_type>(ipp)); static_cast<tr_address_type>(ipp));
@@ -425,6 +423,7 @@ struct tau_tracker
for (ipp_t ipp = 0; ipp < NUM_TR_AF_INET_TYPES; ++ipp) for (ipp_t ipp = 0; ipp < NUM_TR_AF_INET_TYPES; ++ipp)
{ {
auto const ipp_enum = static_cast<tr_address_type>(ipp); auto const ipp_enum = static_cast<tr_address_type>(ipp);
auto& conn_at = connecting_at[ipp];
logtrace( logtrace(
log_name(), log_name(),
fmt::format( fmt::format(
@@ -433,26 +432,24 @@ struct tau_tracker
is_connected(ipp_enum, now), is_connected(ipp_enum, now),
connection_expiration_time[ipp], connection_expiration_time[ipp],
now, now,
connecting_at[ipp])); conn_at));
// also need a valid connection ID... // also need a valid connection ID...
if (auto const& addr = addr_[ipp]; addr && !is_connected(ipp_enum, now) && connecting_at[ipp] == 0) if (auto const& addr = addr_[ipp]; addr && !is_connected(ipp_enum, now) && conn_at == 0)
{ {
TR_ASSERT(addr->first.ss_family == tr_ip_protocol_to_af(ipp_enum)); TR_ASSERT(addr->first.ss_family == tr_ip_protocol_to_af(ipp_enum));
auto& conn_transc_id = connection_transaction_id[ipp];
connecting_at[ipp] = now; conn_at = now;
connection_transaction_id[ipp] = tau_transaction_new(); conn_transc_id = tau_transaction_new();
logtrace( logtrace(
log_name(), log_name(),
fmt::format( fmt::format("Trying to connect {}. Transaction ID is {}", tr_ip_protocol_to_sv(ipp_enum), conn_transc_id));
"Trying to connect {}. Transaction ID is {}",
tr_ip_protocol_to_sv(ipp_enum),
connection_transaction_id[ipp]));
auto buf = PayloadBuffer{}; auto buf = PayloadBuffer{};
buf.add_uint64(0x41727101980LL); buf.add_uint64(0x41727101980LL);
buf.add_uint32(TAU_ACTION_CONNECT); buf.add_uint32(TAU_ACTION_CONNECT);
buf.add_uint32(connection_transaction_id[ipp]); buf.add_uint32(conn_transc_id);
sendto(ipp_enum, std::data(buf), std::size(buf)); sendto(ipp_enum, std::data(buf), std::size(buf));
} }
@@ -561,7 +558,7 @@ private:
{ {
for (ipp_t ipp = 0; ipp < NUM_TR_AF_INET_TYPES; ++ipp) for (ipp_t ipp = 0; ipp < NUM_TR_AF_INET_TYPES; ++ipp)
{ {
if (connecting_at[ipp] != 0 && connecting_at[ipp] + ConnectionRequestTtl < now) if (auto const conn_at = connecting_at[ipp]; conn_at != 0 && conn_at + ConnectionRequestTtl < now)
{ {
auto empty_buf = PayloadBuffer{}; auto empty_buf = PayloadBuffer{};
on_connection_response(static_cast<tr_address_type>(ipp), TAU_ACTION_ERROR, empty_buf); on_connection_response(static_cast<tr_address_type>(ipp), TAU_ACTION_ERROR, empty_buf);
@@ -638,10 +635,11 @@ private:
auto const ipp_enum = static_cast<tr_address_type>(ipp); auto const ipp_enum = static_cast<tr_address_type>(ipp);
if (addr_[ipp] && (ip_protocol == TR_AF_UNSPEC || ipp == ip_protocol) && is_connected(ipp_enum, now)) if (addr_[ipp] && (ip_protocol == TR_AF_UNSPEC || ipp == ip_protocol) && is_connected(ipp_enum, now))
{ {
logdbg(log_name(), fmt::format("sending request w/connection id {}", connection_id[ipp])); auto const conn_id = connection_id[ipp];
logdbg(log_name(), fmt::format("sending request w/connection id {}", conn_id));
auto buf = PayloadBuffer{}; auto buf = PayloadBuffer{};
buf.add_uint64(connection_id[ipp]); buf.add_uint64(conn_id);
buf.add(payload, payload_len); buf.add(payload, payload_len);
sendto(ipp_enum, std::data(buf), std::size(buf)); sendto(ipp_enum, std::data(buf), std::size(buf));

View File

@@ -21,8 +21,8 @@
#include <fmt/core.h> #include <fmt/core.h>
#include "libtransmission/ip-cache.h"
#include "libtransmission/log.h" #include "libtransmission/log.h"
#include "libtransmission/global-ip-cache.h"
#include "libtransmission/tr-assert.h" #include "libtransmission/tr-assert.h"
#include "libtransmission/utils.h" #include "libtransmission/utils.h"
#include "libtransmission/web.h" #include "libtransmission/web.h"
@@ -124,7 +124,7 @@ namespace global_source_ip_helpers
} // namespace global_source_ip_helpers } // namespace global_source_ip_helpers
} // namespace } // namespace
tr_global_ip_cache::tr_global_ip_cache(Mediator& mediator_in) tr_ip_cache::tr_ip_cache(Mediator& mediator_in)
: mediator_{ mediator_in } : mediator_{ mediator_in }
, upkeep_timers_{ mediator_in.timer_maker().create(), mediator_in.timer_maker().create() } , upkeep_timers_{ mediator_in.timer_maker().create(), mediator_in.timer_maker().create() }
{ {
@@ -146,12 +146,7 @@ tr_global_ip_cache::tr_global_ip_cache(Mediator& mediator_in)
++cache_exists; ++cache_exists;
} }
std::unique_ptr<tr_global_ip_cache> tr_global_ip_cache::create(tr_global_ip_cache::Mediator& mediator_in) tr_ip_cache::~tr_ip_cache()
{
return std::unique_ptr<tr_global_ip_cache>(new tr_global_ip_cache(mediator_in));
}
tr_global_ip_cache::~tr_global_ip_cache()
{ {
// Destroying mutex while someone owns it is undefined behaviour, so we acquire it first // Destroying mutex while someone owns it is undefined behaviour, so we acquire it first
auto const locks = std::scoped_lock{ global_addr_mutex_[TR_AF_INET], auto const locks = std::scoped_lock{ global_addr_mutex_[TR_AF_INET],
@@ -170,7 +165,7 @@ tr_global_ip_cache::~tr_global_ip_cache()
--cache_exists; --cache_exists;
} }
bool tr_global_ip_cache::try_shutdown() noexcept bool tr_ip_cache::try_shutdown() noexcept
{ {
for (auto& timer : upkeep_timers_) for (auto& timer : upkeep_timers_)
{ {
@@ -188,7 +183,7 @@ bool tr_global_ip_cache::try_shutdown() noexcept
return true; return true;
} }
tr_address tr_global_ip_cache::bind_addr(tr_address_type type) const noexcept tr_address tr_ip_cache::bind_addr(tr_address_type type) const noexcept
{ {
if (tr_address::is_valid(type)) if (tr_address::is_valid(type))
{ {
@@ -203,7 +198,7 @@ tr_address tr_global_ip_cache::bind_addr(tr_address_type type) const noexcept
return {}; return {};
} }
bool tr_global_ip_cache::set_global_addr(tr_address_type type, tr_address const& addr) noexcept bool tr_ip_cache::set_global_addr(tr_address_type type, tr_address const& addr) noexcept
{ {
if (type == addr.type && addr.is_global_unicast_address()) if (type == addr.type && addr.is_global_unicast_address())
{ {
@@ -215,7 +210,7 @@ bool tr_global_ip_cache::set_global_addr(tr_address_type type, tr_address const&
return false; return false;
} }
void tr_global_ip_cache::update_addr(tr_address_type type) noexcept void tr_ip_cache::update_addr(tr_address_type type) noexcept
{ {
update_source_addr(type); update_source_addr(type);
if (global_source_addr(type)) if (global_source_addr(type))
@@ -224,12 +219,13 @@ void tr_global_ip_cache::update_addr(tr_address_type type) noexcept
} }
} }
void tr_global_ip_cache::update_global_addr(tr_address_type type) noexcept void tr_ip_cache::update_global_addr(tr_address_type type) noexcept
{ {
auto const ix_service = ix_service_[type];
TR_ASSERT(has_ip_protocol_[type]); TR_ASSERT(has_ip_protocol_[type]);
TR_ASSERT(ix_service_[type] < std::size(IPQueryServices[type])); TR_ASSERT(ix_service < std::size(IPQueryServices[type]));
if (ix_service_[type] == 0U && !set_is_updating(type)) if (ix_service == 0U && !set_is_updating(type))
{ {
return; return;
} }
@@ -238,7 +234,7 @@ void tr_global_ip_cache::update_global_addr(tr_address_type type) noexcept
// Update global address // Update global address
static auto constexpr IPProtocolMap = std::array{ tr_web::FetchOptions::IPProtocol::V4, static auto constexpr IPProtocolMap = std::array{ tr_web::FetchOptions::IPProtocol::V4,
tr_web::FetchOptions::IPProtocol::V6 }; tr_web::FetchOptions::IPProtocol::V6 };
auto options = tr_web::FetchOptions{ IPQueryServices[type][ix_service_[type]], auto options = tr_web::FetchOptions{ IPQueryServices[type][ix_service],
[this, type](tr_web::FetchResponse const& response) [this, type](tr_web::FetchResponse const& response)
{ {
// Check to avoid segfault // Check to avoid segfault
@@ -254,11 +250,12 @@ void tr_global_ip_cache::update_global_addr(tr_address_type type) noexcept
mediator_.fetch(std::move(options)); mediator_.fetch(std::move(options));
} }
void tr_global_ip_cache::update_source_addr(tr_address_type type) noexcept void tr_ip_cache::update_source_addr(tr_address_type type) noexcept
{ {
using namespace global_source_ip_helpers; using namespace global_source_ip_helpers;
TR_ASSERT(has_ip_protocol_[type]); auto& has_ip_protocol = has_ip_protocol_[type];
TR_ASSERT(has_ip_protocol);
if (!set_is_updating(type)) if (!set_is_updating(type))
{ {
@@ -287,7 +284,7 @@ void tr_global_ip_cache::update_source_addr(tr_address_type type) noexcept
if (err == EAFNOSUPPORT) if (err == EAFNOSUPPORT)
{ {
stop_timer(type); // No point in retrying stop_timer(type); // No point in retrying
has_ip_protocol_[type] = false; has_ip_protocol = false;
tr_logAddInfo(fmt::format(_("Your machine does not support {protocol}"), fmt::arg("protocol", protocol))); tr_logAddInfo(fmt::format(_("Your machine does not support {protocol}"), fmt::arg("protocol", protocol)));
} }
} }
@@ -295,10 +292,11 @@ void tr_global_ip_cache::update_source_addr(tr_address_type type) noexcept
unset_is_updating(type); unset_is_updating(type);
} }
void tr_global_ip_cache::on_response_ip_query(tr_address_type type, tr_web::FetchResponse const& response) noexcept void tr_ip_cache::on_response_ip_query(tr_address_type type, tr_web::FetchResponse const& response) noexcept
{ {
auto& ix_service = ix_service_[type];
TR_ASSERT(is_updating_[type] == is_updating_t::YES); TR_ASSERT(is_updating_[type] == is_updating_t::YES);
TR_ASSERT(ix_service_[type] < std::size(IPQueryServices[type])); TR_ASSERT(ix_service < std::size(IPQueryServices[type]));
auto const protocol = tr_ip_protocol_to_sv(type); auto const protocol = tr_ip_protocol_to_sv(type);
auto success = false; auto success = false;
@@ -315,14 +313,14 @@ void tr_global_ip_cache::on_response_ip_query(tr_address_type type, tr_web::Fetc
_("Successfully updated global {type} address to {ip} using {url}"), _("Successfully updated global {type} address to {ip} using {url}"),
fmt::arg("type", protocol), fmt::arg("type", protocol),
fmt::arg("ip", addr->display_name()), fmt::arg("ip", addr->display_name()),
fmt::arg("url", IPQueryServices[type][ix_service_[type]]))); fmt::arg("url", IPQueryServices[type][ix_service])));
} }
} }
// Try next IP query URL // Try next IP query URL
if (!success) if (!success)
{ {
if (++ix_service_[type] < std::size(IPQueryServices[type])) if (++ix_service < std::size(IPQueryServices[type]))
{ {
update_global_addr(type); update_global_addr(type);
return; return;
@@ -333,25 +331,25 @@ void tr_global_ip_cache::on_response_ip_query(tr_address_type type, tr_web::Fetc
upkeep_timers_[type]->set_interval(RetryUpkeepInterval); upkeep_timers_[type]->set_interval(RetryUpkeepInterval);
} }
ix_service_[type] = 0U; ix_service = 0U;
unset_is_updating(type); unset_is_updating(type);
} }
void tr_global_ip_cache::unset_global_addr(tr_address_type type) noexcept void tr_ip_cache::unset_global_addr(tr_address_type type) noexcept
{ {
auto const lock = std::scoped_lock{ global_addr_mutex_[type] }; auto const lock = std::scoped_lock{ global_addr_mutex_[type] };
global_addr_[type].reset(); global_addr_[type].reset();
tr_logAddTrace(fmt::format("Unset {} global address cache", tr_ip_protocol_to_sv(type))); tr_logAddTrace(fmt::format("Unset {} global address cache", tr_ip_protocol_to_sv(type)));
} }
void tr_global_ip_cache::set_source_addr(tr_address const& addr) noexcept void tr_ip_cache::set_source_addr(tr_address const& addr) noexcept
{ {
auto const lock = std::scoped_lock{ source_addr_mutex_[addr.type] }; auto const lock = std::scoped_lock{ source_addr_mutex_[addr.type] };
source_addr_[addr.type] = addr; source_addr_[addr.type] = addr;
tr_logAddTrace(fmt::format("Cached source address {}", addr.display_name())); tr_logAddTrace(fmt::format("Cached source address {}", addr.display_name()));
} }
void tr_global_ip_cache::unset_addr(tr_address_type type) noexcept void tr_ip_cache::unset_addr(tr_address_type type) noexcept
{ {
auto const lock = std::scoped_lock{ source_addr_mutex_[type] }; auto const lock = std::scoped_lock{ source_addr_mutex_[type] };
source_addr_[type].reset(); source_addr_[type].reset();
@@ -361,7 +359,7 @@ void tr_global_ip_cache::unset_addr(tr_address_type type) noexcept
unset_global_addr(type); unset_global_addr(type);
} }
bool tr_global_ip_cache::set_is_updating(tr_address_type type) noexcept bool tr_ip_cache::set_is_updating(tr_address_type type) noexcept
{ {
if (is_updating_[type] != is_updating_t::NO) if (is_updating_[type] != is_updating_t::NO)
{ {
@@ -371,7 +369,7 @@ bool tr_global_ip_cache::set_is_updating(tr_address_type type) noexcept
return true; return true;
} }
void tr_global_ip_cache::unset_is_updating(tr_address_type type) noexcept void tr_ip_cache::unset_is_updating(tr_address_type type) noexcept
{ {
TR_ASSERT(is_updating_[type] == is_updating_t::YES); TR_ASSERT(is_updating_[type] == is_updating_t::YES);
is_updating_[type] = is_updating_t::NO; is_updating_[type] = is_updating_t::NO;

View File

@@ -4,7 +4,6 @@
// License text can be found in the licenses/ folder. // License text can be found in the licenses/ folder.
#include <array> #include <array>
#include <atomic>
#include <chrono> // std::chrono::milliseconds #include <chrono> // std::chrono::milliseconds
#include <condition_variable> #include <condition_variable>
#include <memory> // std::unique_ptr #include <memory> // std::unique_ptr
@@ -24,7 +23,7 @@
#endif #endif
/** /**
* Cache global IP addresses. * Cache IP addresses.
* *
* This class caches 3 useful info: * This class caches 3 useful info:
* 1. Whether your machine supports the IP protocol * 1. Whether your machine supports the IP protocol
@@ -34,9 +33,8 @@
* The idea is, if this class successfully cached a source address, that means * The idea is, if this class successfully cached a source address, that means
* you have connectivity to the public internet. And if the global address is * you have connectivity to the public internet. And if the global address is
* the same as the source address, then you are not behind a NAT. * the same as the source address, then you are not behind a NAT.
*
*/ */
class tr_global_ip_cache class tr_ip_cache
{ {
public: public:
struct Mediator struct Mediator
@@ -55,18 +53,14 @@ public:
[[nodiscard]] virtual libtransmission::TimerMaker& timer_maker() = 0; [[nodiscard]] virtual libtransmission::TimerMaker& timer_maker() = 0;
}; };
private: explicit tr_ip_cache(Mediator& mediator_in);
explicit tr_global_ip_cache(Mediator& mediator_in);
public: tr_ip_cache() = delete;
[[nodiscard]] static std::unique_ptr<tr_global_ip_cache> create(Mediator& mediator_in); ~tr_ip_cache();
tr_ip_cache(tr_ip_cache const&) = delete;
tr_global_ip_cache() = delete; tr_ip_cache(tr_ip_cache&&) = delete;
~tr_global_ip_cache(); tr_ip_cache& operator=(tr_ip_cache const&) = delete;
tr_global_ip_cache(tr_global_ip_cache const&) = delete; tr_ip_cache& operator=(tr_ip_cache&&) = delete;
tr_global_ip_cache(tr_global_ip_cache&&) = delete;
tr_global_ip_cache& operator=(tr_global_ip_cache const&) = delete;
tr_global_ip_cache& operator=(tr_global_ip_cache&&) = delete;
bool try_shutdown() noexcept; bool try_shutdown() noexcept;
@@ -121,7 +115,7 @@ private:
Mediator& mediator_; Mediator& mediator_;
enum class is_updating_t enum class is_updating_t : uint8_t
{ {
NO = 0, NO = 0,
YES, YES,
@@ -144,5 +138,5 @@ private:
// Whether this machine supports this IP protocol // Whether this machine supports this IP protocol
array_ip_t<bool> has_ip_protocol_ = { true, true }; array_ip_t<bool> has_ip_protocol_ = { true, true };
array_ip_t<std::atomic_size_t> ix_service_ = {}; array_ip_t<size_t> ix_service_ = {};
}; };

View File

@@ -35,7 +35,7 @@
#include "libtransmission/cache.h" #include "libtransmission/cache.h"
#include "libtransmission/crypto-utils.h" #include "libtransmission/crypto-utils.h"
#include "libtransmission/file.h" #include "libtransmission/file.h"
#include "libtransmission/global-ip-cache.h" #include "libtransmission/ip-cache.h"
#include "libtransmission/interned-string.h" #include "libtransmission/interned-string.h"
#include "libtransmission/log.h" #include "libtransmission/log.h"
#include "libtransmission/net.h" #include "libtransmission/net.h"
@@ -436,7 +436,7 @@ tr_address tr_session::bind_address(tr_address_type type) const noexcept
{ {
// if user provided an address, use it. // if user provided an address, use it.
// otherwise, use any_ipv4 (0.0.0.0). // otherwise, use any_ipv4 (0.0.0.0).
return global_ip_cache_->bind_addr(type); return ip_cache_.bind_addr(type);
} }
if (type == TR_AF_INET6) if (type == TR_AF_INET6)
@@ -783,11 +783,11 @@ void tr_session::setSettings(tr_session::Settings&& settings_in, bool force)
if (auto const& val = new_settings.bind_address_ipv4; force || val != old_settings.bind_address_ipv4) if (auto const& val = new_settings.bind_address_ipv4; force || val != old_settings.bind_address_ipv4)
{ {
global_ip_cache_->update_addr(TR_AF_INET); ip_cache_.update_addr(TR_AF_INET);
} }
if (auto const& val = new_settings.bind_address_ipv6; force || val != old_settings.bind_address_ipv6) if (auto const& val = new_settings.bind_address_ipv6; force || val != old_settings.bind_address_ipv6)
{ {
global_ip_cache_->update_addr(TR_AF_INET6); ip_cache_.update_addr(TR_AF_INET6);
} }
if (auto const& val = new_settings.default_trackers_str; force || val != old_settings.default_trackers_str) if (auto const& val = new_settings.default_trackers_str; force || val != old_settings.default_trackers_str)
@@ -1372,7 +1372,7 @@ void tr_session::closeImplPart1(std::promise<void>* closed_promise, std::chrono:
// ...since global_ip_cache_ relies on web_ to update global addresses, // ...since global_ip_cache_ relies on web_ to update global addresses,
// we tell it to stop updating before web_ starts to refuse new requests. // we tell it to stop updating before web_ starts to refuse new requests.
// But we keep it intact for now, so that udp_core_ can continue. // But we keep it intact for now, so that udp_core_ can continue.
this->global_ip_cache_->try_shutdown(); this->ip_cache_.try_shutdown();
// ...and now that those are done, tell web_ that we're shutting // ...and now that those are done, tell web_ that we're shutting
// down soon. This leaves the `event=stopped` going but refuses any // down soon. This leaves the `event=stopped` going but refuses any
// new tasks. // new tasks.
@@ -1391,7 +1391,7 @@ void tr_session::closeImplPart2(std::promise<void>* closed_promise, std::chrono:
// all the &event=stopped tracker announces. // all the &event=stopped tracker announces.
// also wait for all ip cache updates to finish so that web_ can // also wait for all ip cache updates to finish so that web_ can
// safely destruct. // safely destruct.
if ((!web_->is_idle() || !announcer_udp_->is_idle() || !global_ip_cache_->try_shutdown()) && if ((!web_->is_idle() || !announcer_udp_->is_idle() || !ip_cache_.try_shutdown()) &&
std::chrono::steady_clock::now() < deadline) std::chrono::steady_clock::now() < deadline)
{ {
announcer_->upkeep(); announcer_->upkeep();

View File

@@ -42,8 +42,8 @@
#include "libtransmission/bandwidth.h" #include "libtransmission/bandwidth.h"
#include "libtransmission/blocklist.h" #include "libtransmission/blocklist.h"
#include "libtransmission/cache.h" #include "libtransmission/cache.h"
#include "libtransmission/global-ip-cache.h"
#include "libtransmission/interned-string.h" #include "libtransmission/interned-string.h"
#include "libtransmission/ip-cache.h"
#include "libtransmission/log.h" // for tr_log_level #include "libtransmission/log.h" // for tr_log_level
#include "libtransmission/net.h" // for tr_port, tr_tos_t #include "libtransmission/net.h" // for tr_port, tr_tos_t
#include "libtransmission/open-files.h" #include "libtransmission/open-files.h"
@@ -290,10 +290,10 @@ private:
tr_session& session_; tr_session& session_;
}; };
class GlobalIPCacheMediator final : public tr_global_ip_cache::Mediator class IPCacheMediator final : public tr_ip_cache::Mediator
{ {
public: public:
explicit GlobalIPCacheMediator(tr_session& session) noexcept explicit IPCacheMediator(tr_session& session) noexcept
: session_{ session } : session_{ session }
{ {
} }
@@ -960,7 +960,7 @@ public:
[[nodiscard]] bool has_ip_protocol(tr_address_type type) const noexcept [[nodiscard]] bool has_ip_protocol(tr_address_type type) const noexcept
{ {
TR_ASSERT(tr_address::is_valid(type)); TR_ASSERT(tr_address::is_valid(type));
return global_ip_cache_->has_ip_protocol(type); return ip_cache_.has_ip_protocol(type);
} }
[[nodiscard]] tr_address bind_address(tr_address_type type) const noexcept; [[nodiscard]] tr_address bind_address(tr_address_type type) const noexcept;
@@ -968,18 +968,18 @@ public:
[[nodiscard]] std::optional<tr_address> global_address(tr_address_type type) const noexcept [[nodiscard]] std::optional<tr_address> global_address(tr_address_type type) const noexcept
{ {
TR_ASSERT(tr_address::is_valid(type)); TR_ASSERT(tr_address::is_valid(type));
return global_ip_cache_->global_addr(type); return ip_cache_.global_addr(type);
} }
bool set_global_address(tr_address const& addr) noexcept bool set_global_address(tr_address const& addr) noexcept
{ {
return global_ip_cache_->set_global_addr(addr.type, addr); return ip_cache_.set_global_addr(addr.type, addr);
} }
[[nodiscard]] std::optional<tr_address> global_source_address(tr_address_type type) const noexcept [[nodiscard]] std::optional<tr_address> global_source_address(tr_address_type type) const noexcept
{ {
TR_ASSERT(tr_address::is_valid(type)); TR_ASSERT(tr_address::is_valid(type));
return global_ip_cache_->global_source_addr(type); return ip_cache_.global_source_addr(type);
} }
[[nodiscard]] auto speed_limit(tr_direction const dir) const noexcept [[nodiscard]] auto speed_limit(tr_direction const dir) const noexcept
@@ -1290,8 +1290,8 @@ private:
tr_torrents torrents_; tr_torrents torrents_;
// depends-on: settings_, session_thread_, timer_maker_, web_ // depends-on: settings_, session_thread_, timer_maker_, web_
GlobalIPCacheMediator global_ip_cache_mediator_{ *this }; IPCacheMediator ip_cache_mediator_{ *this };
std::unique_ptr<tr_global_ip_cache> global_ip_cache_ = tr_global_ip_cache::create(global_ip_cache_mediator_); tr_ip_cache ip_cache_{ ip_cache_mediator_ };
// depends-on: settings_, session_thread_, torrents_, global_ip_cache (via tr_session::bind_address()) // depends-on: settings_, session_thread_, torrents_, global_ip_cache (via tr_session::bind_address())
WebMediator web_mediator_{ this }; WebMediator web_mediator_{ this };

View File

@@ -21,9 +21,9 @@ target_sources(libtransmission-test
file-piece-map-test.cc file-piece-map-test.cc
file-test.cc file-test.cc
getopt-test.cc getopt-test.cc
global-ip-cache-test.cc
handshake-test.cc handshake-test.cc
history-test.cc history-test.cc
ip-cache-test.cc
json-test.cc json-test.cc
lpd-test.cc lpd-test.cc
magnet-metainfo-test.cc magnet-metainfo-test.cc

View File

@@ -13,7 +13,7 @@
#include <string_view> #include <string_view>
#include <utility> #include <utility>
#include <libtransmission/global-ip-cache.h> #include <libtransmission/ip-cache.h>
#include <libtransmission/net.h> #include <libtransmission/net.h>
#include <libtransmission/timer.h> #include <libtransmission/timer.h>
#include <libtransmission/web.h> #include <libtransmission/web.h>
@@ -22,7 +22,7 @@
using namespace std::literals; using namespace std::literals;
class GlobalIPCacheTest : public ::testing::Test class IPCacheTest : public ::testing::Test
{ {
protected: protected:
class MockTimerMaker final : public libtransmission::TimerMaker class MockTimerMaker final : public libtransmission::TimerMaker
@@ -67,7 +67,7 @@ protected:
} }
}; };
class MockMediator : public tr_global_ip_cache::Mediator class MockMediator : public tr_ip_cache::Mediator
{ {
public: public:
[[nodiscard]] libtransmission::TimerMaker& timer_maker() override [[nodiscard]] libtransmission::TimerMaker& timer_maker() override
@@ -81,18 +81,18 @@ protected:
void TearDown() override void TearDown() override
{ {
if (global_ip_cache_) if (ip_cache_)
{ {
global_ip_cache_->try_shutdown(); ip_cache_->try_shutdown();
} }
::testing::Test::TearDown(); ::testing::Test::TearDown();
} }
// To be created within the test body // To be created within the test body
std::unique_ptr<tr_global_ip_cache> global_ip_cache_; std::unique_ptr<tr_ip_cache> ip_cache_;
}; };
TEST_F(GlobalIPCacheTest, bindAddr) TEST_F(IPCacheTest, bindAddr)
{ {
static constexpr auto AddrTests = std::array{ static constexpr auto AddrTests = std::array{
std::array<std::pair<std::string_view, std::string_view>, 4>{ { { "8.8.8.8"sv, "8.8.8.8"sv }, std::array<std::pair<std::string_view, std::string_view>, 4>{ { { "8.8.8.8"sv, "8.8.8.8"sv },
@@ -119,20 +119,20 @@ TEST_F(GlobalIPCacheTest, bindAddr)
}; };
auto mediator = LocalMockMediator{}; auto mediator = LocalMockMediator{};
global_ip_cache_ = tr_global_ip_cache::create(mediator); ip_cache_ = std::make_unique<tr_ip_cache>(mediator);
for (std::size_t i = 0; i < NUM_TR_AF_INET_TYPES; ++i) for (std::size_t i = 0; i < NUM_TR_AF_INET_TYPES; ++i)
{ {
mediator.j_ = 0; mediator.j_ = 0;
for (std::size_t& j = mediator.j_; j < std::size(AddrTests[i]); ++j) for (std::size_t& j = mediator.j_; j < std::size(AddrTests[i]); ++j)
{ {
auto const addr = global_ip_cache_->bind_addr(static_cast<tr_address_type>(i)); auto const addr = ip_cache_->bind_addr(static_cast<tr_address_type>(i));
EXPECT_EQ(addr.display_name(), AddrTests[i][j].second); EXPECT_EQ(addr.display_name(), AddrTests[i][j].second);
} }
} }
} }
TEST_F(GlobalIPCacheTest, setGlobalAddr) TEST_F(IPCacheTest, setGlobalAddr)
{ {
static auto constexpr AddrStr = std::array{ "8.8.8.8"sv, static auto constexpr AddrStr = std::array{ "8.8.8.8"sv,
"192.168.133.133"sv, "192.168.133.133"sv,
@@ -148,7 +148,7 @@ TEST_F(GlobalIPCacheTest, setGlobalAddr)
static_assert(std::size(AddrStr) == std::size(AddrTests[TR_AF_INET6])); static_assert(std::size(AddrStr) == std::size(AddrTests[TR_AF_INET6]));
auto mediator = MockMediator{}; auto mediator = MockMediator{};
global_ip_cache_ = tr_global_ip_cache::create(mediator); ip_cache_ = std::make_unique<tr_ip_cache>(mediator);
for (std::size_t i = 0; i < NUM_TR_AF_INET_TYPES; ++i) for (std::size_t i = 0; i < NUM_TR_AF_INET_TYPES; ++i)
{ {
@@ -157,8 +157,8 @@ TEST_F(GlobalIPCacheTest, setGlobalAddr)
auto const type = static_cast<tr_address_type>(i); auto const type = static_cast<tr_address_type>(i);
auto const addr = tr_address::from_string(AddrStr[j]); auto const addr = tr_address::from_string(AddrStr[j]);
ASSERT_TRUE(addr.has_value()); ASSERT_TRUE(addr.has_value());
EXPECT_EQ(global_ip_cache_->set_global_addr(type, *addr), AddrTests[i][j]); EXPECT_EQ(ip_cache_->set_global_addr(type, *addr), AddrTests[i][j]);
if (auto const val = global_ip_cache_->global_addr(type); val && AddrTests[i][j]) if (auto const val = ip_cache_->global_addr(type); val && AddrTests[i][j])
{ {
EXPECT_EQ(val->display_name(), AddrStr[j]); EXPECT_EQ(val->display_name(), AddrStr[j]);
} }
@@ -166,7 +166,7 @@ TEST_F(GlobalIPCacheTest, setGlobalAddr)
} }
} }
TEST_F(GlobalIPCacheTest, globalSourceIPv4) TEST_F(IPCacheTest, globalSourceIPv4)
{ {
struct LocalMockMediator final : public MockMediator struct LocalMockMediator final : public MockMediator
{ {
@@ -176,10 +176,10 @@ TEST_F(GlobalIPCacheTest, globalSourceIPv4)
} }
}; };
auto mediator = LocalMockMediator{}; auto mediator = LocalMockMediator{};
global_ip_cache_ = tr_global_ip_cache::create(mediator); ip_cache_ = std::make_unique<tr_ip_cache>(mediator);
global_ip_cache_->update_source_addr(TR_AF_INET); ip_cache_->update_source_addr(TR_AF_INET);
auto const addr = global_ip_cache_->global_source_addr(TR_AF_INET); auto const addr = ip_cache_->global_source_addr(TR_AF_INET);
if (!addr) if (!addr)
{ {
GTEST_SKIP() << "globalSourceIPv4 did not return an address, either:\n" GTEST_SKIP() << "globalSourceIPv4 did not return an address, either:\n"
@@ -190,7 +190,7 @@ TEST_F(GlobalIPCacheTest, globalSourceIPv4)
EXPECT_TRUE(addr->is_ipv4()); EXPECT_TRUE(addr->is_ipv4());
} }
TEST_F(GlobalIPCacheTest, globalSourceIPv6) TEST_F(IPCacheTest, globalSourceIPv6)
{ {
struct LocalMockMediator final : public MockMediator struct LocalMockMediator final : public MockMediator
{ {
@@ -200,10 +200,10 @@ TEST_F(GlobalIPCacheTest, globalSourceIPv6)
} }
}; };
auto mediator = LocalMockMediator{}; auto mediator = LocalMockMediator{};
global_ip_cache_ = tr_global_ip_cache::create(mediator); ip_cache_ = std::make_unique<tr_ip_cache>(mediator);
global_ip_cache_->update_source_addr(TR_AF_INET6); ip_cache_->update_source_addr(TR_AF_INET6);
auto const addr = global_ip_cache_->global_source_addr(TR_AF_INET6); auto const addr = ip_cache_->global_source_addr(TR_AF_INET6);
if (!addr) if (!addr)
{ {
GTEST_SKIP() << "globalSourceIPv6 did not return an address, either:\n" GTEST_SKIP() << "globalSourceIPv6 did not return an address, either:\n"
@@ -214,7 +214,7 @@ TEST_F(GlobalIPCacheTest, globalSourceIPv6)
EXPECT_TRUE(addr->is_ipv6()); EXPECT_TRUE(addr->is_ipv6());
} }
TEST_F(GlobalIPCacheTest, onResponseIPQuery) TEST_F(IPCacheTest, onResponseIPQuery)
{ {
static auto constexpr AddrStr = std::array{ static auto constexpr AddrStr = std::array{
"8.8.8.8"sv, "192.168.133.133"sv, "172.16.241.133"sv, "2001:1890:1112:1::20"sv, "fd12:3456:789a:1::1"sv, "8.8.8.8"sv, "192.168.133.133"sv, "172.16.241.133"sv, "2001:1890:1112:1::20"sv, "fd12:3456:789a:1::1"sv,
@@ -243,7 +243,7 @@ TEST_F(GlobalIPCacheTest, onResponseIPQuery)
}; };
auto mediator = LocalMockMediator{}; auto mediator = LocalMockMediator{};
global_ip_cache_ = tr_global_ip_cache::create(mediator); ip_cache_ = std::make_unique<tr_ip_cache>(mediator);
mediator.address_type = 0; mediator.address_type = 0;
for (std::size_t& i = mediator.address_type; i < NUM_TR_AF_INET_TYPES; ++i) for (std::size_t& i = mediator.address_type; i < NUM_TR_AF_INET_TYPES; ++i)
@@ -257,9 +257,9 @@ TEST_F(GlobalIPCacheTest, onResponseIPQuery)
{ {
auto const type = static_cast<tr_address_type>(i); auto const type = static_cast<tr_address_type>(i);
global_ip_cache_->update_global_addr(type); ip_cache_->update_global_addr(type);
auto const global_addr = global_ip_cache_->global_addr(type); auto const global_addr = ip_cache_->global_addr(type);
EXPECT_EQ(!!global_addr, j == 200 /* HTTP_OK */ && AddrTests[i][k]); EXPECT_EQ(!!global_addr, j == 200 /* HTTP_OK */ && AddrTests[i][k]);
if (global_addr) if (global_addr)
{ {