Skip to content

Commit 1aa510b

Browse files
committed
fix: keep LAN hosts reachable, refuse to reconnect a stopped host, and only lift a blackout the CLI set (MTT-16534)
- config set address and session start --address move a default listen address with the connect address, as create_network_manager sets it, so a host on a LAN address listens on 0.0.0.0. A listen address set on purpose stays. - reconnect refuses a host or server the CLI started and that has since stopped, instead of starting it again as a client. - The simulator lifts leftover 100% packet loss only when the CLI applied it (tracked in SessionState), so loss set on purpose in a Network Simulator component stays. - UnityTransport exposes an internal TransportId, used for its driver events and by the CLI simulator, instead of the simulator copying the computation. - config set no longer creates a missing NetworkConfig before the dry-run check; it refuses instead.
1 parent 07f3ae6 commit 1aa510b

6 files changed

Lines changed: 119 additions & 31 deletions

File tree

‎com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Config.cs‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,10 @@ internal static ConfigSetResult SetConfig(string field, string value, string man
7070
throw new InvalidOperationException($"{manager.name} is running; its configuration is read when it starts. Stop it (netcode.gameobjects.session stop), set the field, then start it again.");
7171
}
7272

73-
manager.NetworkConfig ??= new NetworkConfig();
73+
if (manager.NetworkConfig == null)
74+
{
75+
throw new InvalidOperationException($"{manager.name} has no NetworkConfig. Add a NetworkManager with netcode.gameobjects create_network_manager.");
76+
}
7477
var result = new ConfigSetResult
7578
{
7679
DryRun = dryRun,
@@ -116,7 +119,12 @@ internal static ConfigSetResult SetConfig(string field, string value, string man
116119
var address = RequireText(value, name);
117120
result.Previous = data.Address;
118121
result.Value = address;
119-
apply = () => SetConnectionAddress(utp, address, data.Port, data.ServerListenAddress);
122+
var listen = ListenAddressFor(data.Address, data.ServerListenAddress, address);
123+
if (listen != (data.ServerListenAddress ?? string.Empty))
124+
{
125+
result.Notes.Add(DescribeListenAddress(listen));
126+
}
127+
apply = () => SetConnectionAddress(utp, address, data.Port, listen);
120128
}
121129
else
122130
{

‎com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Session.cs‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ internal enum SessionMode
2424
/// address and port first. Returns once the start call returns; use <see cref="WaitReadyAsync"/> to wait
2525
/// for the connection.
2626
/// </summary>
27+
// The role each NetworkManager last started as through the CLI: once it has stopped, it no longer says.
28+
private static readonly Dictionary<NetworkManager, SessionMode> s_StartedAs = new Dictionary<NetworkManager, SessionMode>();
29+
2730
internal static SessionResult Start(SessionMode mode, string managerFilter, string address, int port)
2831
{
2932
RequireDefined(mode, "mode");
@@ -55,8 +58,14 @@ internal static SessionResult Start(SessionMode mode, string managerFilter, stri
5558
}
5659
RequireDirectConnection(utp, "address and port");
5760
var data = utp.ConnectionData;
58-
SetConnectionAddress(utp, string.IsNullOrWhiteSpace(address) ? data.Address : address.Trim(), port > 0 ? (ushort)port : data.Port, data.ServerListenAddress);
61+
var connectAddress = string.IsNullOrWhiteSpace(address) ? data.Address : address.Trim();
62+
var listen = string.IsNullOrWhiteSpace(address) ? data.ServerListenAddress ?? string.Empty : ListenAddressFor(data.Address, data.ServerListenAddress, connectAddress);
63+
SetConnectionAddress(utp, connectAddress, port > 0 ? (ushort)port : data.Port, listen);
5964
result.Notes.Add($"Transport set to {utp.ConnectionData.Address}:{utp.ConnectionData.Port} for this session.");
65+
if (mode != SessionMode.Client && listen != (data.ServerListenAddress ?? string.Empty))
66+
{
67+
result.Notes.Add(DescribeListenAddress(listen));
68+
}
6069
}
6170

6271
bool started;
@@ -73,6 +82,7 @@ internal static SessionResult Start(SessionMode mode, string managerFilter, stri
7382
throw new InvalidOperationException($"{manager.name} failed to start as {mode.ToString().ToLowerInvariant()}{errors.Describe()}");
7483
}
7584
}
85+
s_StartedAs[manager] = mode;
7686

7787
result.Status = DescribeManager(manager);
7888
if (mode == SessionMode.Client)
@@ -142,6 +152,11 @@ internal static async Task<WaitReadyResult> ReconnectAsync(string managerFilter,
142152
{
143153
throw new InvalidOperationException($"{manager.name} is the {GetRole(manager)}. reconnect is for clients; restart a server with netcode.gameobjects.session stop, then start.");
144154
}
155+
// A stopped host or server no longer reports IsServer, and would otherwise start again as a client.
156+
if (!manager.IsListening && s_StartedAs.TryGetValue(manager, out var startedAs) && startedAs != SessionMode.Client)
157+
{
158+
throw new InvalidOperationException($"{manager.name} was stopped as the {startedAs.ToString().ToLowerInvariant()}. reconnect is for clients; start it again with netcode.gameobjects.session start --mode {startedAs}.");
159+
}
145160

146161
var started = EditorApplication.timeSinceStartup;
147162
// A client that was kicked or timed out has already shut down; connect it again as it is.
@@ -158,6 +173,7 @@ internal static async Task<WaitReadyResult> ReconnectAsync(string managerFilter,
158173
throw new InvalidOperationException($"{manager.name} shut down but failed to start again{errors.Describe()}");
159174
}
160175
}
176+
s_StartedAs[manager] = SessionMode.Client;
161177

162178
var remaining = timeoutSeconds - (float)(EditorApplication.timeSinceStartup - started);
163179
var ready = await WaitReadyAsync(manager, Math.Max(remaining, 0.1f), 0);

‎com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Simulator.cs‎

Lines changed: 24 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ private struct Baseline
8787
public NetworkSimulatorParameter Global;
8888
}
8989

90-
// Keyed by the id UnityTransport passes to TransportInitialized (see TransportId).
90+
// Keyed by the id UnityTransport passes to TransportInitialized (UnityTransport.TransportId).
9191
private static readonly Dictionary<int, Baseline> s_Baselines = new Dictionary<int, Baseline>();
9292
private static bool s_WarnedThisPlaySession;
9393

@@ -135,6 +135,8 @@ private static void OnPlayModeStateChanged(PlayModeStateChange change)
135135
TimeoutActive = false;
136136
s_LagSpikeEnd = 0;
137137
s_WarnedThisPlaySession = false;
138+
// The drivers are disposed with play mode.
139+
BlackoutApplied = false;
138140
EditorApplication.update -= EndLagSpikeWhenDue;
139141
s_Baselines.Clear();
140142
}
@@ -165,30 +167,22 @@ internal static List<UnityTransport> LiveTransports()
165167
return transports;
166168
}
167169

168-
/// <summary>
169-
/// The id UnityTransport passes to TransportInitialized and TransportDisposed for this transport. Mirrors
170-
/// UnityTransport's own computation; keep the two in step.
171-
/// </summary>
172-
private static int TransportId(UnityTransport utp)
173-
{
174-
#if UNITY_6000_2_OR_NEWER
175-
return utp.GetEntityId().GetHashCode();
176-
#else
177-
return utp.GetInstanceID();
178-
#endif
179-
}
180-
181170
/// <summary>Pushes the current settings to every running driver and returns the transports updated.</summary>
182171
internal static List<string> ApplyToLiveTransports(List<UnityTransport> live = null, bool clearBlackout = false)
183172
{
184173
var applied = new List<string>();
185174
foreach (var utp in live ?? LiveTransports())
186175
{
187-
if (Apply(TransportId(utp), utp.GetNetworkDriver(), clearBlackout))
176+
if (Apply(utp.TransportId, utp.GetNetworkDriver(), clearBlackout))
188177
{
189178
applied.Add(NgoCliQueries.GetHierarchyPath(utp.transform));
190179
}
191180
}
181+
if (!Blackout)
182+
{
183+
// Every live driver is back to its own loss, or the simulator's.
184+
BlackoutApplied = false;
185+
}
192186
return applied;
193187
}
194188

@@ -197,8 +191,8 @@ internal static List<string> ApplyToLiveTransports(List<UnityTransport> live = n
197191
/// and restores the saved ones once none is. Returns false when the driver was left alone.
198192
/// </summary>
199193
/// <param name="clearBlackout">
200-
/// With nothing saved and nothing on, still lift a blackout (100% loss both ways) left on the driver, e.g.
201-
/// after a script recompile in play mode reset the saved state.
194+
/// With nothing saved and nothing on, still lift a blackout (100% loss both ways) the CLI left on the driver,
195+
/// e.g. after a script recompile in play mode reset the saved state.
202196
/// </param>
203197
private static bool Apply(int transportId, NetworkDriver driver, bool clearBlackout = false)
204198
{
@@ -233,6 +227,7 @@ private static bool Apply(int transportId, NetworkDriver driver, bool clearBlack
233227
{
234228
parameters.ReceivePacketLossPercent = 100f;
235229
parameters.SendPacketLossPercent = 100f;
230+
BlackoutApplied = true;
236231
}
237232
driver.ModifyNetworkSimulatorParameters(parameters);
238233
if (!Active)
@@ -257,9 +252,20 @@ private static void WarnOncePerPlaySession()
257252
Debug.LogWarning($"[Netcode] The Unity CLI network simulator is on for this editor session: {DelayMs} ms delay, {JitterMs} ms jitter and {DropPercent}% packet loss on every UnityTransport. Turn it off with netcode.gameobjects.simulator set --enable false.");
258253
}
259254

255+
/// <summary>
256+
/// True from when the CLI drops every packet on a driver until it lets them through again. Kept in
257+
/// SessionState so it outlasts a script recompile, which resets the saved driver settings.
258+
/// </summary>
259+
private static bool BlackoutApplied
260+
{
261+
get => SessionState.GetBool(k_Prefix + "BlackoutApplied", false);
262+
set => SessionState.SetBool(k_Prefix + "BlackoutApplied", value);
263+
}
264+
265+
// Only a blackout the CLI applied is lifted: 100% loss set on purpose, e.g. in a Network Simulator component, stays.
260266
private static bool ClearLeftoverBlackout(NetworkDriver driver)
261267
{
262-
if (!driver.CurrentSettings.TryGet<NetworkSimulatorParameter>(out var global)
268+
if (!BlackoutApplied || !driver.CurrentSettings.TryGet<NetworkSimulatorParameter>(out var global)
263269
|| global.ReceivePacketLossPercent < 100f || global.SendPacketLossPercent < 100f)
264270
{
265271
return false;

‎com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.cs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -492,6 +492,22 @@ internal static string DefaultListenAddress(string address)
492492
return "0.0.0.0";
493493
}
494494

495+
/// <summary>
496+
/// The listen address to use when the connect address changes from <paramref name="oldAddress"/> to
497+
/// <paramref name="newAddress"/>: one set on purpose stays, while an empty one, or the default for the old
498+
/// address, becomes the default for the new one (<see cref="DefaultListenAddress"/>), as
499+
/// create_network_manager sets it.
500+
/// </summary>
501+
internal static string ListenAddressFor(string oldAddress, string oldListenAddress, string newAddress)
502+
{
503+
var listen = oldListenAddress ?? string.Empty;
504+
return listen.Length == 0 || listen == DefaultListenAddress(oldAddress) ? DefaultListenAddress(newAddress) : listen;
505+
}
506+
507+
internal static string DescribeListenAddress(string listenAddress) => listenAddress.Length == 0
508+
? "The server listens on the loopback address only, matching the local connect address."
509+
: $"The server listens on {listenAddress} (every interface), so clients on other machines can connect. Set listen_address to narrow it.";
510+
495511
/// <summary>Throws when the transport connects through Relay, which ignores the address and port.</summary>
496512
internal static void RequireDirectConnection(UnityTransport utp, string setting)
497513
{

‎com.unity.netcode.gameobjects/Runtime/Transports/UTP/UnityTransport.cs‎

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,19 @@ private struct PacketLossCache
371371
#endif
372372
internal static event Action<int, NetworkDriver> TransportInitialized;
373373
internal static event Action<int> TransportDisposed;
374+
375+
/// <summary>The id <see cref="TransportInitialized"/> and <see cref="TransportDisposed"/> pass for this transport.</summary>
376+
internal int TransportId
377+
{
378+
get
379+
{
380+
#if UNITY_6000_2_OR_NEWER
381+
return GetEntityId().GetHashCode();
382+
#else
383+
return GetInstanceID();
384+
#endif
385+
}
386+
}
374387
#if UNITY_EDITOR
375388
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
376389
private static void ResetStaticsOnLoad()
@@ -461,12 +474,9 @@ private void InitDriver()
461474
out m_UnreliableSequencedFragmentedPipeline,
462475
out m_ReliableSequencedPipeline);
463476
#if UNITY_6000_2_OR_NEWER
464-
var entityId = GetEntityId();
465-
OnDriverInitialized?.Invoke(entityId, m_Driver);
466-
TransportInitialized?.Invoke(entityId.GetHashCode(), m_Driver);
467-
#else
468-
TransportInitialized?.Invoke(GetInstanceID(), m_Driver);
477+
OnDriverInitialized?.Invoke(GetEntityId(), m_Driver);
469478
#endif
479+
TransportInitialized?.Invoke(TransportId, m_Driver);
470480
}
471481

472482
private void DisposeInternals()
@@ -484,12 +494,9 @@ private void DisposeInternals()
484494
m_SendQueue.Clear();
485495

486496
#if UNITY_6000_2_OR_NEWER
487-
var entityId = GetEntityId();
488-
OnDisposingDriver?.Invoke(entityId);
489-
TransportDisposed?.Invoke(entityId.GetHashCode());
490-
#else
491-
TransportDisposed?.Invoke(GetInstanceID());
497+
OnDisposingDriver?.Invoke(GetEntityId());
492498
#endif
499+
TransportDisposed?.Invoke(TransportId);
493500
}
494501

495502
/// <summary>

‎com.unity.netcode.gameobjects/Tests/Editor/Cli/NgoCliQueriesTests.cs‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
using Unity.Netcode.GameObjects.Editor.Cli;
1010
using Unity.Netcode.GameObjects.Editor.Configuration;
1111
using Unity.Netcode.Transports.UTP;
12+
using Unity.Networking.Transport;
1213
using Unity.Networking.Transport.Utilities;
1314
using UnityEditor;
1415
using UnityEditor.SceneManagement;
@@ -485,6 +486,25 @@ public void SetConfig_ValidatesAndApplies()
485486
StringAssert.Contains("Relay", relay.Message);
486487
}
487488

489+
[Test]
490+
public void SetConfig_Address_ListensOnEveryInterfaceForARemoteAddress()
491+
{
492+
var manager = CreateManager();
493+
var transport = (UnityTransport)manager.NetworkConfig.NetworkTransport;
494+
Assert.AreEqual(string.Empty, transport.ConnectionData.ServerListenAddress);
495+
496+
var lan = NgoCliQueries.SetConfig("address", "192.168.1.20", null, false);
497+
Assert.AreEqual("0.0.0.0", transport.ConnectionData.ServerListenAddress, "A LAN host is reachable from other machines.");
498+
StringAssert.Contains("0.0.0.0", lan.Notes.Single());
499+
500+
NgoCliQueries.SetConfig("address", "127.0.0.1", null, false);
501+
Assert.AreEqual(string.Empty, transport.ConnectionData.ServerListenAddress, "A default listen address follows the connect address.");
502+
503+
NgoCliQueries.SetConfig("listen_address", "192.168.1.20", null, false);
504+
CollectionAssert.IsEmpty(NgoCliQueries.SetConfig("address", "10.0.0.5", null, false).Notes);
505+
Assert.AreEqual("192.168.1.20", transport.ConnectionData.ServerListenAddress, "A listen address set on purpose stays.");
506+
}
507+
488508
[Test]
489509
public void SetConfig_RejectsOutOfRangeAndNonFiniteFloats()
490510
{
@@ -686,6 +706,18 @@ public IEnumerator RunningHost_SupportsTheRuntimeQueries()
686706
driver.CurrentSettings.TryGet<SimulatorUtility.Parameters>(out var restored);
687707
Assert.AreEqual(original.PacketDelayMs, restored.PacketDelayMs, "Turning the simulator off restores the transport's own settings.");
688708

709+
// Losing every packet on purpose, e.g. from a Network Simulator component, isn't mistaken for a CLI timeout.
710+
driver.CurrentSettings.TryGet<NetworkSimulatorParameter>(out var userLoss);
711+
userLoss.ReceivePacketLossPercent = 100f;
712+
userLoss.SendPacketLossPercent = 100f;
713+
driver.ModifyNetworkSimulatorParameters(userLoss);
714+
NgoCliQueries.SetTimeout(false);
715+
driver.CurrentSettings.TryGet<NetworkSimulatorParameter>(out var kept);
716+
Assert.AreEqual(100f, kept.ReceivePacketLossPercent, "Loss the CLI didn't set is left alone.");
717+
userLoss.ReceivePacketLossPercent = 0f;
718+
userLoss.SendPacketLossPercent = 0f;
719+
driver.ModifyNetworkSimulatorParameters(userLoss);
720+
689721
var hooks = (IList)typeof(NetworkMessageManager).GetField("m_Hooks", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(NgoCliQueries.ResolveManager(null).MessageManager);
690722
var hookCount = hooks.Count;
691723
var stats = NgoCliQueries.SampleStatsAsync(null, 3, 10);
@@ -777,6 +809,9 @@ public IEnumerator HostWithARemoteClient_SupportsTheClientQueries()
777809

778810
NgoCliQueries.Stop("ClientManager", false);
779811
yield return WaitForCondition(() => !client.IsListening && !client.ShutdownInProgress);
812+
yield return WaitForCondition(() => !host.IsListening && !host.ShutdownInProgress);
813+
var stoppedHost = Assert.ThrowsAsync<InvalidOperationException>(() => NgoCliQueries.ReconnectAsync("NetworkManager", 5), "A stopped host isn't started again as a client.");
814+
StringAssert.Contains("stopped as the host", stoppedHost.Message);
780815
}
781816

782817
/// <summary>

0 commit comments

Comments
 (0)