diff --git a/client/ServerBrowser.cs b/client/ServerBrowser.cs index bed6b3d..eda6536 100644 --- a/client/ServerBrowser.cs +++ b/client/ServerBrowser.cs @@ -31,6 +31,7 @@ public sealed partial class ServerBrowser : CanvasLayer public int? PingMs; public bool TimedOut; public bool Probing = true; + public bool Disposed; public Button? RowButton; public Label? NameLabel; @@ -258,7 +259,7 @@ public sealed partial class ServerBrowser : CanvasLayer var result = await ServerPingProbe.ProbeAsync(row.Host, row.Port, TimeSpan.FromMilliseconds(1400), ct).ConfigureAwait(false); _mainThreadQueue.Enqueue(() => { - if (!IsInsideTree() || seq != _refreshSeq) return; + if (!IsInsideTree() || seq != _refreshSeq || row.Disposed || !_rows.Contains(row) || row.RowButton is null || !IsInstanceValid(row.RowButton)) return; row.Probing = false; if (result.Success && result.Summary is { } summary) { @@ -299,7 +300,7 @@ public sealed partial class ServerBrowser : CanvasLayer { _mainThreadQueue.Enqueue(() => { - if (!IsInsideTree() || seq != _refreshSeq) return; + if (!IsInsideTree() || seq != _refreshSeq || row.Disposed || !_rows.Contains(row) || row.RowButton is null || !IsInstanceValid(row.RowButton)) return; row.Probing = false; row.PingMs = null; row.TimedOut = true; @@ -502,6 +503,10 @@ public sealed partial class ServerBrowser : CanvasLayer private void ClearRows() { + for (int i = 0; i < _rows.Count; i++) + { + _rows[i].Disposed = true; + } _rows.Clear(); if (_rowsContainer is null) return; for (int i = _rowsContainer.GetChildCount() - 1; i >= 0; i--) @@ -517,7 +522,9 @@ public sealed partial class ServerBrowser : CanvasLayer for (int i = _rows.Count - 1; i >= 0; i--) { if (!_rows[i].IsLocalProbe) continue; - var btn = _rows[i].RowButton; + var row = _rows[i]; + row.Disposed = true; + var btn = row.RowButton; _rows.RemoveAt(i); if (btn is not null && IsInstanceValid(btn)) { @@ -615,7 +622,7 @@ public sealed partial class ServerBrowser : CanvasLayer private void SyncRowVisual(ServerRowModel row) { - if (row.RowButton is null) return; + if (row.Disposed || !_rows.Contains(row) || row.RowButton is null || !IsInstanceValid(row.RowButton)) return; bool selected = string.Equals(_selectedKey, row.Key, StringComparison.Ordinal); Color accent = selected diff --git a/src/RustToDust.Net/SnapshotCodec.cs b/src/RustToDust.Net/SnapshotCodec.cs index 8b52cab..0f6a904 100644 --- a/src/RustToDust.Net/SnapshotCodec.cs +++ b/src/RustToDust.Net/SnapshotCodec.cs @@ -1038,21 +1038,8 @@ namespace RustToDust.Net public static byte[] EncodePong(in ServerPingSummary summary) { string rawName = string.IsNullOrWhiteSpace(summary.ServerName) ? "Rust to Dust" : summary.ServerName.Trim(); - Span utf8Buf = stackalloc byte[64]; - int maxUtf8 = Math.Min(48, utf8Buf.Length); - int nameBytes = Encoding.UTF8.GetBytes(rawName.AsSpan(0, Math.Min(rawName.Length, maxUtf8)), utf8Buf); - if (nameBytes > maxUtf8) - { - nameBytes = maxUtf8; - while (nameBytes > 0 && (utf8Buf[nameBytes - 1] & 0xC0) == 0x80) - { - nameBytes--; - } - if (nameBytes > 0 && (utf8Buf[nameBytes - 1] & 0x80) != 0) - { - nameBytes--; - } - } + Span utf8Buf = stackalloc byte[48]; + Encoding.UTF8.GetEncoder().Convert(rawName.AsSpan(), utf8Buf, flush: true, out _, out int nameBytes, out _); byte[] buf = new byte[27 + nameBytes]; var span = buf.AsSpan(); diff --git a/src/RustToDust.Server/Program.cs b/src/RustToDust.Server/Program.cs index 42db20e..2b32013 100644 --- a/src/RustToDust.Server/Program.cs +++ b/src/RustToDust.Server/Program.cs @@ -98,20 +98,32 @@ namespace RustToDust.Server restartToLobby: restartToLobby); host.LogMessage += msg => Console.WriteLine(msg); + static DirectoryHeartbeatSnapshot BuildSnapshot(ServerMatchHost h, string hostAddr) => + new( + h.ServerName, + hostAddr, + h.BoundPort, + h.Session.State.MapKind == ArenaMapKind.Sion ? "sion" : "desert", + h.Session.State.Seed, + h.ConnectedHumanCount, + h.MaxHumans, + h.Session.State.Phase.ToString(), + h.Session.State.OrbitalDrop.CurrentWaveIndex); + + object dirSnapGate = new(); + DirectoryHeartbeatSnapshot cachedDirSnap = BuildSnapshot(host, publicHost); + if (!string.IsNullOrWhiteSpace(directoryUrl)) { reporter = new DirectoryReporter( directoryUrl, - () => new DirectoryHeartbeatSnapshot( - host.ServerName, - publicHost, - host.BoundPort, - host.Session.State.MapKind == ArenaMapKind.Sion ? "sion" : "desert", - host.Session.State.Seed, - host.ConnectedHumanCount, - host.MaxHumans, - host.Session.State.Phase.ToString(), - host.Session.State.OrbitalDrop.CurrentWaveIndex)); + () => + { + lock (dirSnapGate) + { + return cachedDirSnap; + } + }); } Console.WriteLine($"RustToDust.Server listening on {bindIp}:{host.BoundPort} (name=\"{host.ServerName}\", map={mapKind}, seed={seed}, maxHumans={maxHumans}, lobby={startInLobby})"); @@ -122,6 +134,8 @@ namespace RustToDust.Server double endSec = durationSec > 0.0 ? durationSec : double.PositiveInfinity; int lastReportedHumans = host.ConnectedHumanCount; MatchPhase lastReportedPhase = host.Session.State.Phase; + ArenaMapKind lastReportedMap = host.Session.State.MapKind; + int lastReportedSeed = host.Session.State.Seed; while (!cts.IsCancellationRequested && sw.Elapsed.TotalSeconds < endSec) { @@ -129,12 +143,26 @@ namespace RustToDust.Server if (nowSec >= nextTickSec) { host.StepOnce(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); - if (reporter is not null && - (host.ConnectedHumanCount != lastReportedHumans || host.Session.State.Phase != lastReportedPhase)) + if (reporter is not null) { - lastReportedHumans = host.ConnectedHumanCount; - lastReportedPhase = host.Session.State.Phase; - reporter.NotifyChanged(); + var state = host.Session.State; + int curHumans = host.ConnectedHumanCount; + if (curHumans != lastReportedHumans || + state.Phase != lastReportedPhase || + state.MapKind != lastReportedMap || + state.Seed != lastReportedSeed) + { + lastReportedHumans = curHumans; + lastReportedPhase = state.Phase; + lastReportedMap = state.MapKind; + lastReportedSeed = state.Seed; + DirectoryHeartbeatSnapshot updated = BuildSnapshot(host, publicHost); + lock (dirSnapGate) + { + cachedDirSnap = updated; + } + reporter.NotifyChanged(); + } } nextTickSec += tickSec; diff --git a/tests/RustToDust.Tests/LobbyAndDirectoryTests.cs b/tests/RustToDust.Tests/LobbyAndDirectoryTests.cs index 0985026..2787ec9 100644 --- a/tests/RustToDust.Tests/LobbyAndDirectoryTests.cs +++ b/tests/RustToDust.Tests/LobbyAndDirectoryTests.cs @@ -196,7 +196,7 @@ namespace RustToDust.Tests try { - var deadline = DateTime.UtcNow.AddSeconds(3); + var deadline = DateTime.UtcNow.AddSeconds(15); IReadOnlyList servers = Array.Empty(); while (DateTime.UtcNow < deadline) { @@ -213,7 +213,7 @@ namespace RustToDust.Tests phase = "Active"; reporter.NotifyChanged(); - deadline = DateTime.UtcNow.AddSeconds(3); + deadline = DateTime.UtcNow.AddSeconds(15); while (DateTime.UtcNow < deadline) { servers = await DirectoryBrowserClient.FetchServersAsync(baseUrl); @@ -607,5 +607,31 @@ namespace RustToDust.Tests Assert.Equal(MatchPhase.Completed, decodedCompleted.Phase); Assert.Equal(3, decodedCompleted.WinnerContenderId); } + + [Fact] + public async Task StatelessUdpPing_HandlesMultiByteUtf8ServerName_WithoutOverflow() + { + string multiByteName = new string('\u2022', 24); + using var host = new ServerMatchHost( + IPAddress.Loopback, + 0, + seed: 77, + mapKind: ArenaMapKind.Desert, + serverName: multiByteName, + startInLobby: true); + + var target = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + var pingTask = ServerPingProbe.ProbeAsync(target, TimeSpan.FromSeconds(2)); + while (!pingTask.IsCompleted) + { + host.PollStatelessPings(); + await Task.Delay(5); + } + + var res = await pingTask; + Assert.True(res.Success); + Assert.NotNull(res.Summary); + Assert.Equal(new string('\u2022', 16), res.Summary!.Value.ServerName); + } } }