From fe9bbcb6acbd829d6432712f8d78cb3c8559b183 Mon Sep 17 00:00:00 2001 From: mischa Date: Mon, 14 Oct 2024 15:10:05 +0200 Subject: [PATCH] fix: #2536 NetworkServer won't accept connections while listen=false --- Assets/Mirror/Core/NetworkServer.cs | 14 ++++++++------ .../Editor/NetworkServer/NetworkServerTest.cs | 18 +++++++++++++++++- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/Assets/Mirror/Core/NetworkServer.cs b/Assets/Mirror/Core/NetworkServer.cs index 4650d278e..5d545e15f 100644 --- a/Assets/Mirror/Core/NetworkServer.cs +++ b/Assets/Mirror/Core/NetworkServer.cs @@ -71,12 +71,7 @@ public static partial class NetworkServer new Dictionary(); /// Single player mode can set listen=false to not accept incoming connections. - static bool _listen = true; - public static bool listen - { - get { return _listen; } - set { _listen = value; } - } + public static bool listen; // DEPRECATED 2024-10-14 [Obsolete("NetworkServer.dontListen was replaced with NetworkServer.listen. The new value is the opposite, and avoids double negatives like 'dontListen=false'")] @@ -685,6 +680,13 @@ static void OnTransportConnectedWithAddress(int connectionId, string clientAddre static bool IsConnectionAllowed(int connectionId, string address) { + // only accept connections while listening + if (!listen) + { + Debug.Log($"Server not listening, rejecting connectionId={connectionId} with address={address}"); + return false; + } + // connectionId needs to be != 0 because 0 is reserved for local player // note that some transports like kcp generate connectionId by // hashing which can be < 0 as well, so we need to allow < 0! diff --git a/Assets/Mirror/Tests/Editor/NetworkServer/NetworkServerTest.cs b/Assets/Mirror/Tests/Editor/NetworkServer/NetworkServerTest.cs index 25b1ccf99..b431fe65f 100644 --- a/Assets/Mirror/Tests/Editor/NetworkServer/NetworkServerTest.cs +++ b/Assets/Mirror/Tests/Editor/NetworkServer/NetworkServerTest.cs @@ -1107,6 +1107,22 @@ public void UnSpawnAndClearAuthority() Assert.That(comp.onStopAuthorityCalled, Is.EqualTo(1)); } + // test to prevent https://github.com/MirrorNetworking/Mirror/issues/2536 + [Test] + public void SetListenToFalse() + { + // start the server with listen=true + NetworkServer.Listen(1); + + // set listen=false at runtime + NetworkServer.listen = false; + + // try connecting a client. should be reject while not listening. + NetworkClient.Connect("127.0.0.1"); + UpdateTransport(); + Assert.That(NetworkServer.connections.Count, Is.EqualTo(0)); + } + // test to reproduce a bug where stopping the server would not call // OnStopServer on scene objects: // https://github.com/vis2k/Mirror/issues/2119 @@ -1152,7 +1168,7 @@ public void ShutdownCleanup() NetworkServer.Shutdown(); // state cleared? - Assert.That(NetworkServer.dontListen, Is.False); + Assert.That(NetworkServer.listen, Is.True); Assert.That(NetworkServer.active, Is.False); Assert.That(NetworkServer.isLoadingScene, Is.False);