diff --git a/src/RatioMaster.Core.Tests/Networking/PeerListenerTests.cs b/src/RatioMaster.Core.Tests/Networking/PeerListenerTests.cs index a4c9460..6ecc47e 100644 --- a/src/RatioMaster.Core.Tests/Networking/PeerListenerTests.cs +++ b/src/RatioMaster.Core.Tests/Networking/PeerListenerTests.cs @@ -73,6 +73,35 @@ public async Task AnswersWithThePeerIdBytesRatherThanTheirEscapedForm() Assert.Equal(expected, response[48..68]); } + [Fact] + public async Task DuplicateInfoHashesAnswerWithTheFirstRegisteredPeerId() + { + var pool = new PeerListenerPool(); + var port = GetFreePort(); + var infoHash = MakeInfoHash(5); + var first = pool.Join(port, infoHash, PeerId)!; + await using var second = pool.Join(port, infoHash, OtherPeerId); + + Assert.Equal(PeerId, Encoding.ASCII.GetString(await HandshakeAsync(port, infoHash), 48, 20)); + + await first.DisposeAsync(); + Assert.Equal(OtherPeerId, Encoding.ASCII.GetString(await HandshakeAsync(port, infoHash), 48, 20)); + } + + [Fact] + public async Task IgnoresAnInfoHashThatOnlyAppearsInTheRemotePeerId() + { + var port = GetFreePort(); + var infoHash = MakeInfoHash(15); + await using var registration = new PeerListenerPool().Join(port, infoHash, PeerId); + Assert.NotNull(registration); + + var handshake = BuildHandshake(MakeInfoHash(60), "-OTHERPEER-1234567890"); + infoHash.CopyTo(handshake, 48); + + await AssertNoReplyAsync(port, infoHash, handshake); + } + [Fact] public async Task IgnoresAHandshakeForAnotherTorrent() { @@ -160,12 +189,12 @@ private static async Task HandshakeAsync(int port, byte[] infoHash) return response; } - private static async Task AssertNoReplyAsync(int port, byte[] infoHash) + private static async Task AssertNoReplyAsync(int port, byte[] infoHash, byte[]? handshake = null) { using var client = new TcpClient(); await client.ConnectAsync(IPAddress.Loopback, port, Ct); await using var stream = client.GetStream(); - await stream.WriteAsync(BuildHandshake(infoHash, "-OTHERPEER-1234567890"), Ct); + await stream.WriteAsync(handshake ?? BuildHandshake(infoHash, "-OTHERPEER-1234567890"), Ct); // The listener must not reply. The connection is closed instead, which surfaces either as a // zero-byte read or, on Windows, as a connection reset. Both mean no handshake was returned. diff --git a/src/RatioMaster.Core.Tests/Sessions/TorrentSessionFactoryTests.cs b/src/RatioMaster.Core.Tests/Sessions/TorrentSessionFactoryTests.cs index 1e71188..3eb25e9 100644 --- a/src/RatioMaster.Core.Tests/Sessions/TorrentSessionFactoryTests.cs +++ b/src/RatioMaster.Core.Tests/Sessions/TorrentSessionFactoryTests.cs @@ -70,6 +70,89 @@ public void TheTorrentsOfAClientShareItsPort() Assert.NotEqual(first.PeerId, second.PeerId); // the rest stays each torrent's own } + [Fact] + public void SameTorrentWithTwoTrackersSharesItsAutomaticIdentity() + { + var factory = CreateFactory(); + var settings = new TorrentSettings { ClientName = "uTorrent 3.6.0" }; + var first = factory.Create(Descriptor, settings); + var second = factory.Create(Descriptor with { TrackerUrl = "http://another.test/announce" }, settings); + + Assert.Equal(first.Identity.PeerId, second.Identity.PeerId); + Assert.Equal(first.Identity.Key, second.Identity.Key); + Assert.Equal(first.Identity.Port, second.Identity.Port); + } + + [Fact] + public void DifferentInfoHashesAndClientsKeepSeparateIdentities() + { + var factory = CreateFactory(); + var settings = new TorrentSettings { ClientName = "uTorrent 3.6.0" }; + var first = factory.Create(Descriptor, settings); + var differentHash = factory.Create(Descriptor with { InfoHash = Enumerable.Repeat((byte)7, 20).ToArray() }, settings); + var differentClient = factory.Create(Descriptor, settings with { ClientName = "qBittorrent 5.2.4" }); + + Assert.NotEqual(first.Identity.PeerId, differentHash.Identity.PeerId); + Assert.NotEqual(first.Identity.PeerId, differentClient.Identity.PeerId); + } + + [Fact] + public void ExplicitCustomIdentityIsNotReplacedByTheAutomaticIdentity() + { + var factory = CreateFactory(); + var automatic = new TorrentSettings { ClientName = "uTorrent 3.6.0" }; + factory.Create(Descriptor, automatic); + + var custom = factory.Create(Descriptor, automatic with + { + IdentityMode = IdentityMode.Custom, + CustomPeerId = "-RM1000-abcdefghijkl", + CustomKey = "CUSTOM123", + }); + + Assert.Equal("-RM1000-abcdefghijkl", custom.Identity.PeerId); + Assert.Equal("CUSTOM123", custom.Identity.Key); + } + + [Fact] + public async Task AGeneratedKeyRotationIsSharedAcrossTrackerRows() + { + var tracker = new FakeTrackerClient { Interval = 60 }; + var factory = new TorrentSessionFactory( + Catalog, + tracker, + new ClientValueScanner(NullProcessMemoryScanner.Instance), + new FakeLocalIpProvider(), + new DeterministicRandomSource(99)); + var settings = new TorrentSettings + { + ClientName = "uTorrent 3.6.0", + IntervalSeconds = 60, + UseTcpListener = false, + }; + var first = factory.Create(Descriptor, settings); + var second = factory.Create(Descriptor with { TrackerUrl = "http://another.test/announce" }, settings); + var originalKey = first.Identity.Key; + await first.StartAsync(TestContext.Current.CancellationToken); + await second.StartAsync(TestContext.Current.CancellationToken); + + for (var i = 0; i < 11 * 60; i++) + { + await first.TickAsync(TestContext.Current.CancellationToken); + } + + Assert.NotEqual(originalKey, first.Identity.Key); + Assert.Equal(first.Identity.Key, second.Identity.Key); + var rotatedKey = first.Identity.Key; + + for (var i = 0; i < 11 * 60; i++) + { + await second.TickAsync(TestContext.Current.CancellationToken); + } + + Assert.Equal(rotatedKey, second.Identity.Key); + } + [Fact] public void EachClientHasAPortOfItsOwn() { diff --git a/src/RatioMaster.Core/Networking/PeerListener.cs b/src/RatioMaster.Core/Networking/PeerListener.cs index 3b1a71e..a99cb96 100644 --- a/src/RatioMaster.Core/Networking/PeerListener.cs +++ b/src/RatioMaster.Core/Networking/PeerListener.cs @@ -201,21 +201,24 @@ private async Task HandleClientAsync(Socket socket, CancellationToken cancellati } } - /// Gets the torrent a handshake asks for; when one torrent is on the port twice, the later one answers. + /// Matches only the info hash in a valid BitTorrent handshake. private PeerListenerRegistration? FindTorrent(ReadOnlySpan data) { - if (data.IndexOf(Protocol) < 0) + if (data.Length < HandshakeReadLength || + data[0] != Protocol.Length || + !data.Slice(1, Protocol.Length).SequenceEqual(Protocol)) { return null; } + var infoHash = data.Slice(1 + Protocol.Length + 8, 20); lock (this.gate) { - for (var i = this.torrents.Count - 1; i >= 0; i--) + foreach (var torrent in this.torrents) { - if (data.IndexOf(this.torrents[i].InfoHash) >= 0) + if (infoHash.SequenceEqual(torrent.InfoHash)) { - return this.torrents[i]; + return torrent; } } } diff --git a/src/RatioMaster.Core/Sessions/SharedTorrentIdentity.cs b/src/RatioMaster.Core/Sessions/SharedTorrentIdentity.cs new file mode 100644 index 0000000..b80f74d --- /dev/null +++ b/src/RatioMaster.Core/Sessions/SharedTorrentIdentity.cs @@ -0,0 +1,46 @@ +namespace RatioMaster.Core.Sessions +{ + using RatioMaster.Core.Abstractions; + using RatioMaster.Core.Clients; + + internal sealed class SharedTorrentIdentity + { + private readonly Lock gate = new(); + private ClientIdentity current; + private int lastKeyRotationSecond; + + public SharedTorrentIdentity(ClientIdentity identity) => this.current = identity; + + public ClientIdentity Current + { + get + { + lock (this.gate) + { + return this.current; + } + } + } + + public bool RefreshKeyIfDue(ClientProfile profile, IRandomSource random, int runningSeconds) + { + lock (this.gate) + { + if (this.current.Source != ClientIdentitySource.Generated || profile.KeyRefresh != KeyRefreshPolicy.Timed) + { + return false; + } + + var interval = Math.Max(1, profile.KeyRefreshMinutes) * 60; + if (runningSeconds - this.lastKeyRotationSecond < interval) + { + return false; + } + + this.lastKeyRotationSecond = runningSeconds; + this.current = this.current with { Key = new ClientIdentityGenerator(random).GenerateValue(profile.Key) }; + return true; + } + } + } +} diff --git a/src/RatioMaster.Core/Sessions/TorrentSession.cs b/src/RatioMaster.Core/Sessions/TorrentSession.cs index 64f8ce3..81daeec 100644 --- a/src/RatioMaster.Core/Sessions/TorrentSession.cs +++ b/src/RatioMaster.Core/Sessions/TorrentSession.cs @@ -33,6 +33,7 @@ public sealed class TorrentSession : IAsyncDisposable private readonly Lock gate = new(); private ClientIdentity identity; + private SharedTorrentIdentity? sharedIdentity; private TorrentSettings settings; private TorrentSessionState state = TorrentSessionState.Idle; private string? stopReason; @@ -106,11 +107,13 @@ public TorrentSession( public event EventHandler? Adjusted; + internal void UseSharedIdentity(SharedTorrentIdentity identity) => this.sharedIdentity = identity; + public TorrentDescriptor Descriptor => this.descriptor; public ClientProfile Profile => this.profile; - public ClientIdentity Identity => this.identity; + public ClientIdentity Identity => this.sharedIdentity?.Current ?? this.identity; public TorrentSettings Settings => this.settings; @@ -144,7 +147,7 @@ public TorrentStats Snapshot ? null : TimeSpan.FromSeconds(Math.Max(0, this.currentInterval - this.elapsedInInterval)), StopAfterRemaining = this.ComputeStopAfterRemaining(), - Key = this.identity.Key, + Key = this.Identity.Key, }; } } @@ -521,6 +524,11 @@ private long RandomRateBytes(int minKb, int maxKb) /// private bool RefreshKeyIfDue() { + if (this.sharedIdentity is { } shared) + { + return shared.RefreshKeyIfDue(this.profile, this.random, this.totalRunningSeconds); + } + if (this.profile.KeyRefresh != KeyRefreshPolicy.Timed || this.identity.Source != ClientIdentitySource.Generated) { @@ -545,9 +553,9 @@ private bool RefreshKeyIfDue() private string CurrentNumWant() => this.left == 0 && this.profile.SeedingNumWant is { } seeding - && this.identity.NumWant == this.profile.DefaultNumWant.ToString(CultureInfo.InvariantCulture) + && this.Identity.NumWant == this.profile.DefaultNumWant.ToString(CultureInfo.InvariantCulture) ? seeding.ToString(CultureInfo.InvariantCulture) - : this.identity.NumWant; + : this.Identity.NumWant; private AnnounceValues BuildAnnounceValues() { @@ -564,15 +572,16 @@ private AnnounceValues BuildAnnounceValues() this.left = this.totalSize - this.downloaded; } + var identity = this.Identity; values = new AnnounceValues { InfoHashEncoded = InfoHashEncoder.Encode(this.descriptor.InfoHash, this.profile.HashUpperCase, this.profile.Unreserved), - PeerId = this.identity.PeerId, - Port = this.identity.Port, + PeerId = identity.PeerId, + Port = identity.Port, Uploaded = this.uploaded, Downloaded = this.downloaded, Left = this.left, - Key = this.identity.Key, + Key = identity.Key, NumWant = this.CurrentNumWant(), LocalIp = this.LocalIp, }; @@ -854,13 +863,13 @@ private void OpenListener() return; } - if (!int.TryParse(this.identity.Port, NumberStyles.Integer, CultureInfo.InvariantCulture, out var port)) + if (!int.TryParse(this.Identity.Port, NumberStyles.Integer, CultureInfo.InvariantCulture, out var port)) { return; } // Shared with every other torrent announced with this port, as a real client's one listening port is. - this.listener = this.listeners.Join(port, this.descriptor.InfoHash, this.identity.PeerId, message => this.Log(LogLevel.Info, message)); + this.listener = this.listeners.Join(port, this.descriptor.InfoHash, this.Identity.PeerId, message => this.Log(LogLevel.Info, message)); } private async Task CloseListenerAsync() diff --git a/src/RatioMaster.Core/Sessions/TorrentSessionFactory.cs b/src/RatioMaster.Core/Sessions/TorrentSessionFactory.cs index edb67b7..7adb39d 100644 --- a/src/RatioMaster.Core/Sessions/TorrentSessionFactory.cs +++ b/src/RatioMaster.Core/Sessions/TorrentSessionFactory.cs @@ -1,5 +1,7 @@ namespace RatioMaster.Core.Sessions { + using System.Collections.Generic; + using RatioMaster.Core.Abstractions; using RatioMaster.Core.Clients; using RatioMaster.Core.MemoryScan; @@ -22,6 +24,8 @@ public sealed class TorrentSessionFactory private readonly IRandomSource random; private readonly ISystemClock clock; private readonly PeerListenerPool listeners; + private readonly Lock identityGate = new(); + private readonly Dictionary<(string ClientName, string InfoHash), SharedTorrentIdentity> torrentIdentities = []; public TorrentSessionFactory( ClientProfileCatalog catalog, @@ -64,7 +68,23 @@ public TorrentSession Create(TorrentDescriptor descriptor, TorrentSettings setti // Torrents started together look for the running client once, not once each. var identity = this.BuildIdentity(settings, log, ignoreRecentMiss: false); - return new TorrentSession(descriptor, profile, identity, settings, this.tracker, this.localIpProvider, this.random, this.clock, this.listeners); + var session = new TorrentSession(descriptor, profile, identity, settings, this.tracker, this.localIpProvider, this.random, this.clock, this.listeners); + if (settings.IdentityMode == IdentityMode.Automatic) + { + var key = (profile.Name, Convert.ToHexString(descriptor.InfoHash)); + lock (this.identityGate) + { + if (!this.torrentIdentities.TryGetValue(key, out var shared)) + { + shared = new SharedTorrentIdentity(identity); + this.torrentIdentities[key] = shared; + } + + session.UseSharedIdentity(shared); + } + } + + return session; } private static string Or(string? value, string fallback) => string.IsNullOrWhiteSpace(value) ? fallback : value;