Cut 9a: public server directory API, stateless RTDP UDP ping/pong, and authoritative MatchPhase.Lobby

This commit is contained in:
Meta Vens 2026-12-05 17:37:39 +01:00
commit e6d96c88dc
19 changed files with 2606 additions and 36 deletions

View file

@ -4,6 +4,7 @@
<Project Path="src/RustToDust.Ymir/RustToDust.Ymir.csproj" />
<Project Path="src/RustToDust.Net/RustToDust.Net.csproj" />
<Project Path="src/RustToDust.Server/RustToDust.Server.csproj" />
<Project Path="src/RustToDust.Directory/RustToDust.Directory.csproj" />
</Folder>
<Folder Name="/tests/">
<Project Path="tests/RustToDust.Tests/RustToDust.Tests.csproj" />

View file

@ -47,6 +47,7 @@ namespace RustToDust.Core
IReadOnlyList<OrbitalPod> ActivePods { get; }
DropWaveState DropWaveState { get; }
IReadOnlyList<DropPodLifecycleEvent> PodEvents { get; }
LobbySnapshotDto? LobbyState => null;
bool IsContenderVisible(int contenderId);
bool IsSpectatorVisible(int spectatorId);
@ -56,6 +57,9 @@ namespace RustToDust.Core
void DrainSimEvents(List<ISimEvent> dest);
bool RequestEquipCargo(int cargoIndex, string hardpointId);
void RequestNewMatch(int seed, ArenaMapKind mapKind);
bool SetLobbyReady(bool ready) => false;
bool RequestLobbyConfig(int seed, ArenaMapKind mapKind) => false;
bool RequestLobbyStart() => false;
(Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha);
(Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedSpectatorPose(int spectatorId, float alpha);

View file

@ -6,8 +6,47 @@ namespace RustToDust.Core
{
public enum MatchPhase
{
Active,
Completed
Active = 0,
Completed = 1,
Lobby = 2
}
public sealed class LobbySlotState
{
public int SlotId { get; init; }
public string Callsign { get; set; } = string.Empty;
public bool IsHuman { get; set; }
public bool IsReady { get; set; }
}
public sealed class LobbyState
{
public const float DefaultCountdownSeconds = 5.0f;
public LobbyState(int contenderCount, ArenaMapKind mapKind, int seed, int? hostSlotId = null, int minHumansToAutoStart = 1)
{
SelectedMap = mapKind;
SelectedSeed = seed;
HostSlotId = hostSlotId;
MinHumansToAutoStart = Math.Max(1, minHumansToAutoStart);
Slots = new LobbySlotState[contenderCount];
for (int i = 0; i < contenderCount; i++)
{
Slots[i] = new LobbySlotState
{
SlotId = i,
Callsign = $"Contender {i + 1:00}"
};
}
}
public int? HostSlotId { get; set; }
public int MinHumansToAutoStart { get; set; } = 1;
public float? CountdownSeconds { get; set; }
public bool ForceLaunched { get; set; }
public ArenaMapKind SelectedMap { get; set; }
public int SelectedSeed { get; set; }
public LobbySlotState[] Slots { get; }
}
public readonly record struct PlayerInput(
@ -289,11 +328,15 @@ namespace RustToDust.Core
private int _nextDropId = 1;
private long _nextHitEventId = 1;
private int _nextTracerId = 1;
private readonly bool _pendingSkipInitialDrop;
private readonly List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)> _pendingLootTargets;
private readonly List<(int ContenderId, float X, float Z, float Yaw)> _pendingContenderTargets;
public MatchState(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool skipInitialDrop = false)
public MatchState(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool skipInitialDrop = false, bool startInLobby = false)
{
Seed = seed;
MapKind = mapKind;
_pendingSkipInitialDrop = skipInitialDrop;
Rng = new Random(seed);
Broadcast = new BroadcastFeed();
OrbitalDrop = new OrbitalDropSystem(this);
@ -335,7 +378,24 @@ namespace RustToDust.Core
lootTargets = BuildInitialLootTargetsDesert();
}
if (skipInitialDrop)
_pendingLootTargets = lootTargets;
_pendingContenderTargets = new List<(int ContenderId, float X, float Z, float Yaw)>(Contenders.Count);
for (int i = 0; i < Contenders.Count; i++)
{
var c = Contenders[i];
_pendingContenderTargets.Add((c.Id, c.X, c.Z, c.Yaw));
}
if (startInLobby)
{
Phase = MatchPhase.Lobby;
Lobby = new LobbyState(ContenderCount, mapKind, seed);
for (int i = 0; i < Contenders.Count; i++)
{
Contenders[i].Lifecycle = ContenderLifecycle.Deploying;
}
}
else if (skipInitialDrop)
{
for (int i = 0; i < Contenders.Count; i++)
{
@ -347,19 +407,51 @@ namespace RustToDust.Core
if (t.Chassis is not null) SpawnChassisDrop(t.X, t.Z, t.Chassis);
else if (t.Module is not null) SpawnModuleDrop(t.X, t.Z, t.Module);
}
Broadcast.EmitMatchStart(0f, mapKind);
}
else
{
var contenderTargets = new List<(int ContenderId, float X, float Z, float Yaw)>(Contenders.Count);
for (int i = 0; i < Contenders.Count; i++)
{
var c = Contenders[i];
contenderTargets.Add((c.Id, c.X, c.Z, c.Yaw));
}
OrbitalDrop.BeginWave0(contenderTargets, lootTargets, DefaultDropSurfaceQuery);
OrbitalDrop.BeginWave0(_pendingContenderTargets, _pendingLootTargets, DefaultDropSurfaceQuery);
Broadcast.EmitMatchStart(0f, mapKind);
}
}
public bool StartFromLobby(DropSurfaceQuery? surfaceQuery = null)
{
if (Phase != MatchPhase.Lobby)
{
return false;
}
Broadcast.EmitMatchStart(0f, mapKind);
Phase = MatchPhase.Active;
Time = 0f;
WinnerContenderId = null;
if (Lobby is not null)
{
Lobby.CountdownSeconds = null;
Lobby.ForceLaunched = false;
}
if (_pendingSkipInitialDrop)
{
for (int i = 0; i < Contenders.Count; i++)
{
Contenders[i].Lifecycle = ContenderLifecycle.Active;
}
for (int i = 0; i < _pendingLootTargets.Count; i++)
{
var t = _pendingLootTargets[i];
if (t.Chassis is not null) SpawnChassisDrop(t.X, t.Z, t.Chassis);
else if (t.Module is not null) SpawnModuleDrop(t.X, t.Z, t.Module);
}
}
else
{
OrbitalDrop.BeginWave0(_pendingContenderTargets, _pendingLootTargets, surfaceQuery ?? DefaultDropSurfaceQuery);
}
Broadcast.EmitMatchStart(0f, MapKind);
return true;
}
public int Seed { get; }
@ -368,6 +460,7 @@ namespace RustToDust.Core
public Random Rng { get; }
public float Time { get; set; }
public MatchPhase Phase { get; set; } = MatchPhase.Active;
public LobbyState? Lobby { get; set; }
public int? WinnerContenderId { get; set; }
public TerrainField Terrain { get; }

View file

@ -33,6 +33,7 @@ namespace RustToDust.Core
[Union(11, typeof(MatchResetEvent))]
[Union(12, typeof(DropPodEvent))]
// Reserved [Union(13)] OrdnanceNodeEvent (Cut 7)
[Union(14, typeof(MatchStartedEvent))]
public interface ISimEvent
{
}
@ -295,6 +296,36 @@ namespace RustToDust.Core
[Key(12)] public int CurrentWaveIndex { get; set; }
[Key(13)] public bool RespawnCutoffReached { get; set; }
[Key(14)] public List<OrbitalPodDto> ActivePods { get; set; } = new();
[Key(15)] public LobbySnapshotDto? Lobby { get; set; }
}
[MessagePackObject]
public sealed class LobbySlotDto
{
[Key(0)] public int SlotId { get; set; }
[Key(1)] public string Callsign { get; set; } = string.Empty;
[Key(2)] public bool IsHuman { get; set; }
[Key(3)] public bool IsReady { get; set; }
}
[MessagePackObject]
public sealed class LobbySnapshotDto
{
[Key(0)] public int? HostSlotId { get; set; }
[Key(1)] public int MinHumansToAutoStart { get; set; } = 1;
[Key(2)] public float? CountdownSeconds { get; set; }
[Key(3)] public bool ForceLaunched { get; set; }
[Key(4)] public byte SelectedMap { get; set; }
[Key(5)] public int SelectedSeed { get; set; }
[Key(6)] public List<LobbySlotDto> Slots { get; set; } = new();
}
[MessagePackObject]
public sealed class MatchStartedEvent : ISimEvent
{
[Key(0)] public uint MatchGeneration { get; set; }
[Key(1)] public byte MapKind { get; set; }
[Key(2)] public int Seed { get; set; }
}
[MessagePackObject]
@ -316,6 +347,11 @@ namespace RustToDust.Core
[Union(6, typeof(SimEventBatchMsg))]
[Union(7, typeof(EntitySyncSnapshotMsg))]
[Union(8, typeof(InteractCmdMsg))]
[Union(9, typeof(LobbyReadyCmdMsg))]
[Union(10, typeof(LobbyConfigCmdMsg))]
[Union(11, typeof(LobbyStartCmdMsg))]
[Union(12, typeof(LobbySnapshotMsg))]
[Union(13, typeof(ClientKeepaliveMsg))]
public interface ISchemaWireMessage
{
}
@ -397,4 +433,38 @@ namespace RustToDust.Core
[Key(9)] public byte[] ArmorBytes { get; set; } = Array.Empty<byte>();
[Key(10)] public ContenderLoadoutEvent? ContenderLoadout { get; set; }
}
[MessagePackObject]
public sealed class LobbyReadyCmdMsg : ISchemaWireMessage
{
[Key(0)] public uint ReqSeq { get; set; }
[Key(1)] public bool IsReady { get; set; }
}
[MessagePackObject]
public sealed class LobbyConfigCmdMsg : ISchemaWireMessage
{
[Key(0)] public uint ReqSeq { get; set; }
[Key(1)] public int Seed { get; set; }
[Key(2)] public byte MapKind { get; set; }
}
[MessagePackObject]
public sealed class LobbyStartCmdMsg : ISchemaWireMessage
{
[Key(0)] public uint ReqSeq { get; set; }
}
[MessagePackObject]
public sealed class LobbySnapshotMsg : ISchemaWireMessage
{
[Key(0)] public uint MatchGeneration { get; set; }
[Key(1)] public LobbySnapshotDto Snapshot { get; set; } = new();
}
[MessagePackObject]
public sealed class ClientKeepaliveMsg : ISchemaWireMessage
{
[Key(0)] public uint ClientSendMs { get; set; }
}
}

View file

@ -0,0 +1,45 @@
using System;
namespace RustToDust.DirectoryService
{
public sealed class DirectoryHeartbeatRequest
{
public Guid? ServerId { get; set; }
public string? LeaseToken { get; set; }
public string Name { get; set; } = "Rust to Dust";
public string? PublicHost { get; set; }
public int UdpPort { get; set; }
public string Map { get; set; } = "desert";
public int Seed { get; set; } = 42;
public int Humans { get; set; }
public int MaxHumans { get; set; } = 12;
public string Phase { get; set; } = "Active";
public int Wave { get; set; }
public int ProtocolVersion { get; set; } = 1;
public bool HasPassword { get; set; }
}
public sealed class DirectoryHeartbeatResponse
{
public Guid ServerId { get; set; }
public string LeaseToken { get; set; } = string.Empty;
public int TtlSeconds { get; set; }
}
public sealed class DirectoryServerView
{
public Guid ServerId { get; set; }
public string Name { get; set; } = string.Empty;
public string PublicHost { get; set; } = string.Empty;
public int UdpPort { get; set; }
public string Map { get; set; } = string.Empty;
public int Seed { get; set; }
public int Humans { get; set; }
public int MaxHumans { get; set; }
public string Phase { get; set; } = string.Empty;
public int Wave { get; set; }
public int ProtocolVersion { get; set; }
public bool HasPassword { get; set; }
public DateTimeOffset ExpiresAtUtc { get; set; }
}
}

View file

@ -0,0 +1,421 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Security.Cryptography;
using System.Text;
namespace RustToDust.DirectoryService
{
public sealed class DirectoryRegistryOptions
{
public TimeSpan EntryTtl { get; set; } = TimeSpan.FromSeconds(25);
public TimeSpan ReaperInterval { get; set; } = TimeSpan.FromSeconds(5);
public int MaxEntries { get; set; } = 256;
public int MaxEntriesPerIp { get; set; } = 8;
public int HeartbeatLimitPerMinute { get; set; } = 120;
public int ListLimitPerMinute { get; set; } = 60;
public Func<DateTimeOffset> UtcNow { get; set; } = () => DateTimeOffset.UtcNow;
}
public enum DirectoryOpStatus
{
Ok = 200,
NoContent = 204,
BadRequest = 400,
Forbidden = 403,
NotFound = 404,
Conflict = 409,
TooManyRequests = 429,
ServiceUnavailable = 503
}
public readonly record struct DirectoryOpResult<T>(DirectoryOpStatus Status, T? Value, string? Error = null);
public sealed class DirectoryRegistry
{
private sealed class RegistryEntry
{
public Guid ServerId;
public string LeaseToken = string.Empty;
public byte[] LeaseTokenBytes = Array.Empty<byte>();
public string OwnerIp = string.Empty;
public string Name = string.Empty;
public string PublicHost = string.Empty;
public int UdpPort;
public string Map = string.Empty;
public int Seed;
public int Humans;
public int MaxHumans;
public string Phase = string.Empty;
public int Wave;
public int ProtocolVersion;
public bool HasPassword;
public DateTimeOffset ExpiresAtUtc;
}
private sealed class RateWindow
{
public long MinuteBucket;
public int Count;
}
private readonly object _gate = new();
private readonly Dictionary<Guid, RegistryEntry> _entries = new();
private readonly Dictionary<string, RateWindow> _heartbeatRates = new(StringComparer.Ordinal);
private readonly Dictionary<string, RateWindow> _listRates = new(StringComparer.Ordinal);
private readonly DirectoryRegistryOptions _options;
public DirectoryRegistry(DirectoryRegistryOptions? options = null)
{
_options = options ?? new DirectoryRegistryOptions();
}
public int Count
{
get
{
lock (_gate)
{
PurgeExpiredLocked(_options.UtcNow());
return _entries.Count;
}
}
}
public DirectoryOpResult<DirectoryHeartbeatResponse> UpsertHeartbeat(DirectoryHeartbeatRequest req, IPAddress callerIp)
{
if (req is null)
{
return new(DirectoryOpStatus.BadRequest, null, "Request body required.");
}
IPAddress normalizedCaller = NormalizeIp(callerIp);
string callerKey = normalizedCaller.ToString();
DateTimeOffset now = _options.UtcNow();
lock (_gate)
{
PurgeExpiredLocked(now);
if (!AllowRateLocked(_heartbeatRates, callerKey, now, _options.HeartbeatLimitPerMinute))
{
return new(DirectoryOpStatus.TooManyRequests, null, "Heartbeat rate limit exceeded.");
}
if (req.UdpPort < 1 || req.UdpPort > 65535)
{
return new(DirectoryOpStatus.BadRequest, null, "udpPort must be in 1..65535.");
}
string resolvedHost;
if (string.IsNullOrWhiteSpace(req.PublicHost) ||
string.Equals(req.PublicHost.Trim(), "auto", StringComparison.OrdinalIgnoreCase))
{
resolvedHost = callerKey;
}
else
{
resolvedHost = req.PublicHost.Trim();
if (resolvedHost.Length > 253 || ContainsWhitespaceOrControl(resolvedHost))
{
return new(DirectoryOpStatus.BadRequest, null, "Invalid publicHost.");
}
if (!IPAddress.IsLoopback(normalizedCaller) && IsLoopbackOrWildcardHost(resolvedHost))
{
return new(DirectoryOpStatus.BadRequest, null, "Non-loopback callers cannot advertise a loopback or wildcard publicHost.");
}
}
string cleanName = SanitizeLabel(req.Name, "Rust to Dust", 48);
string cleanMap = SanitizeLabel(req.Map, "desert", 24).ToLowerInvariant();
string cleanPhase = SanitizeLabel(req.Phase, "Active", 16);
int maxHumans = Math.Clamp(req.MaxHumans, 1, 12);
int humans = Math.Clamp(req.Humans, 0, maxHumans);
int wave = Math.Max(0, req.Wave);
int protocolVersion = Math.Max(1, req.ProtocolVersion);
if (req.ServerId is { } serverId && serverId != Guid.Empty)
{
if (!_entries.TryGetValue(serverId, out var existing))
{
return new(DirectoryOpStatus.Conflict, null, "Unknown or expired serverId.");
}
if (!VerifyLeaseToken(existing, req.LeaseToken))
{
return new(DirectoryOpStatus.Forbidden, null, "Invalid leaseToken.");
}
existing.Name = cleanName;
existing.PublicHost = resolvedHost;
existing.UdpPort = req.UdpPort;
existing.Map = cleanMap;
existing.Seed = req.Seed;
existing.Humans = humans;
existing.MaxHumans = maxHumans;
existing.Phase = cleanPhase;
existing.Wave = wave;
existing.ProtocolVersion = protocolVersion;
existing.HasPassword = req.HasPassword;
existing.ExpiresAtUtc = now + _options.EntryTtl;
return new(DirectoryOpStatus.Ok, new DirectoryHeartbeatResponse
{
ServerId = existing.ServerId,
LeaseToken = existing.LeaseToken,
TtlSeconds = Math.Max(1, (int)Math.Ceiling(_options.EntryTtl.TotalSeconds))
});
}
if (_entries.Count >= _options.MaxEntries)
{
return new(DirectoryOpStatus.ServiceUnavailable, null, "Directory capacity reached.");
}
int ipCount = 0;
foreach (var entry in _entries.Values)
{
if (string.Equals(entry.OwnerIp, callerKey, StringComparison.Ordinal))
{
ipCount++;
}
}
if (ipCount >= _options.MaxEntriesPerIp)
{
return new(DirectoryOpStatus.TooManyRequests, null, "Per-IP server registration limit reached.");
}
Guid newId = Guid.NewGuid();
string token = Convert.ToHexString(RandomNumberGenerator.GetBytes(24)).ToLowerInvariant();
var created = new RegistryEntry
{
ServerId = newId,
LeaseToken = token,
LeaseTokenBytes = Encoding.UTF8.GetBytes(token),
OwnerIp = callerKey,
Name = cleanName,
PublicHost = resolvedHost,
UdpPort = req.UdpPort,
Map = cleanMap,
Seed = req.Seed,
Humans = humans,
MaxHumans = maxHumans,
Phase = cleanPhase,
Wave = wave,
ProtocolVersion = protocolVersion,
HasPassword = req.HasPassword,
ExpiresAtUtc = now + _options.EntryTtl
};
_entries[newId] = created;
return new(DirectoryOpStatus.Ok, new DirectoryHeartbeatResponse
{
ServerId = created.ServerId,
LeaseToken = created.LeaseToken,
TtlSeconds = Math.Max(1, (int)Math.Ceiling(_options.EntryTtl.TotalSeconds))
});
}
}
public DirectoryOpResult<object> DeleteServer(Guid serverId, string? leaseToken)
{
if (serverId == Guid.Empty)
{
return new(DirectoryOpStatus.BadRequest, null, "Invalid serverId.");
}
DateTimeOffset now = _options.UtcNow();
lock (_gate)
{
PurgeExpiredLocked(now);
if (!_entries.TryGetValue(serverId, out var existing))
{
return new(DirectoryOpStatus.NotFound, null, "Server not found.");
}
if (!VerifyLeaseToken(existing, leaseToken))
{
return new(DirectoryOpStatus.Forbidden, null, "Invalid leaseToken.");
}
_entries.Remove(serverId);
return new(DirectoryOpStatus.NoContent, null);
}
}
public DirectoryOpResult<IReadOnlyList<DirectoryServerView>> ListServers(IPAddress callerIp)
{
string callerKey = NormalizeIp(callerIp).ToString();
DateTimeOffset now = _options.UtcNow();
lock (_gate)
{
PurgeExpiredLocked(now);
if (!AllowRateLocked(_listRates, callerKey, now, _options.ListLimitPerMinute))
{
return new(DirectoryOpStatus.TooManyRequests, null, "List rate limit exceeded.");
}
var list = new List<DirectoryServerView>(_entries.Count);
foreach (var entry in _entries.Values)
{
list.Add(new DirectoryServerView
{
ServerId = entry.ServerId,
Name = entry.Name,
PublicHost = entry.PublicHost,
UdpPort = entry.UdpPort,
Map = entry.Map,
Seed = entry.Seed,
Humans = entry.Humans,
MaxHumans = entry.MaxHumans,
Phase = entry.Phase,
Wave = entry.Wave,
ProtocolVersion = entry.ProtocolVersion,
HasPassword = entry.HasPassword,
ExpiresAtUtc = entry.ExpiresAtUtc
});
}
list.Sort((a, b) =>
{
int cmp = b.Humans.CompareTo(a.Humans);
return cmp != 0 ? cmp : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase);
});
return new(DirectoryOpStatus.Ok, list);
}
}
public int SweepExpired()
{
DateTimeOffset now = _options.UtcNow();
lock (_gate)
{
return PurgeExpiredLocked(now);
}
}
private int PurgeExpiredLocked(DateTimeOffset now)
{
List<Guid>? expired = null;
foreach (var kv in _entries)
{
if (kv.Value.ExpiresAtUtc <= now)
{
expired ??= new List<Guid>();
expired.Add(kv.Key);
}
}
if (expired is not null)
{
for (int i = 0; i < expired.Count; i++)
{
_entries.Remove(expired[i]);
}
}
long currentBucket = now.ToUnixTimeSeconds() / 60;
PruneRateBucketsLocked(_heartbeatRates, currentBucket);
PruneRateBucketsLocked(_listRates, currentBucket);
return expired?.Count ?? 0;
}
private static void PruneRateBucketsLocked(Dictionary<string, RateWindow> buckets, long currentBucket)
{
if (buckets.Count == 0) return;
List<string>? stale = null;
foreach (var kv in buckets)
{
if (kv.Value.MinuteBucket < currentBucket)
{
stale ??= new List<string>();
stale.Add(kv.Key);
}
}
if (stale is not null)
{
for (int i = 0; i < stale.Count; i++)
{
buckets.Remove(stale[i]);
}
}
}
private static bool AllowRateLocked(Dictionary<string, RateWindow> buckets, string key, DateTimeOffset now, int limit)
{
if (limit <= 0) return true;
long bucket = now.ToUnixTimeSeconds() / 60;
if (!buckets.TryGetValue(key, out var win) || win.MinuteBucket != bucket)
{
win = new RateWindow { MinuteBucket = bucket, Count = 0 };
buckets[key] = win;
}
win.Count++;
return win.Count <= limit;
}
private static bool VerifyLeaseToken(RegistryEntry entry, string? suppliedToken)
{
if (string.IsNullOrEmpty(suppliedToken)) return false;
byte[] suppliedBytes = Encoding.UTF8.GetBytes(suppliedToken);
return suppliedBytes.Length == entry.LeaseTokenBytes.Length &&
CryptographicOperations.FixedTimeEquals(entry.LeaseTokenBytes, suppliedBytes);
}
private static IPAddress NormalizeIp(IPAddress ip) =>
ip.IsIPv4MappedToIPv6 ? ip.MapToIPv4() : ip;
private static bool IsLoopbackOrWildcardHost(string host)
{
if (string.Equals(host, "localhost", StringComparison.OrdinalIgnoreCase) ||
host.EndsWith(".localhost", StringComparison.OrdinalIgnoreCase))
{
return true;
}
if (IPAddress.TryParse(host, out var ip))
{
ip = NormalizeIp(ip);
return IPAddress.IsLoopback(ip) ||
ip.Equals(IPAddress.Any) ||
ip.Equals(IPAddress.IPv6Any);
}
return false;
}
private static bool ContainsWhitespaceOrControl(string value)
{
for (int i = 0; i < value.Length; i++)
{
char ch = value[i];
if (char.IsWhiteSpace(ch) || char.IsControl(ch))
{
return true;
}
}
return false;
}
private static string SanitizeLabel(string? raw, string fallback, int maxLen)
{
if (string.IsNullOrWhiteSpace(raw)) return fallback;
var sb = new StringBuilder(Math.Min(raw.Length, maxLen));
string trimmed = raw.Trim();
for (int i = 0; i < trimmed.Length && sb.Length < maxLen; i++)
{
char ch = trimmed[i];
if (!char.IsControl(ch))
{
sb.Append(ch);
}
}
return sb.Length == 0 ? fallback : sb.ToString();
}
}
}

View file

@ -0,0 +1,164 @@
using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace RustToDust.DirectoryService
{
public static class DirectoryApp
{
public static WebApplication Build(string[] args, DirectoryRegistryOptions? options = null)
{
var builder = WebApplication.CreateBuilder(args);
var resolvedOptions = options ?? new DirectoryRegistryOptions();
var registry = new DirectoryRegistry(resolvedOptions);
builder.Services.AddSingleton(resolvedOptions);
builder.Services.AddSingleton(registry);
builder.Services.AddHostedService<DirectoryReaperService>();
builder.Services.Configure<ForwardedHeadersOptions>(opts =>
{
opts.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
opts.KnownNetworks.Clear();
opts.KnownProxies.Clear();
opts.KnownProxies.Add(IPAddress.Loopback);
opts.KnownProxies.Add(IPAddress.IPv6Loopback);
});
var app = builder.Build();
app.UseForwardedHeaders();
app.MapGet("/healthz", (DirectoryRegistry reg) =>
Results.Ok(new { status = "ok", activeServers = reg.Count }));
app.MapGet("/api/v1/servers", (HttpContext ctx, DirectoryRegistry reg) =>
{
IPAddress callerIp = ResolveCallerIp(ctx);
var result = reg.ListServers(callerIp);
return result.Status switch
{
DirectoryOpStatus.Ok => Results.Ok(result.Value),
DirectoryOpStatus.TooManyRequests => Results.StatusCode(StatusCodes.Status429TooManyRequests),
_ => Results.BadRequest(new { error = result.Error })
};
});
app.MapPost("/api/v1/servers/heartbeat", (HttpContext ctx, DirectoryHeartbeatRequest req, DirectoryRegistry reg) =>
{
IPAddress callerIp = ResolveCallerIp(ctx);
var result = reg.UpsertHeartbeat(req, callerIp);
return result.Status switch
{
DirectoryOpStatus.Ok => Results.Ok(result.Value),
DirectoryOpStatus.Forbidden => Results.StatusCode(StatusCodes.Status403Forbidden),
DirectoryOpStatus.Conflict => Results.Conflict(new { error = result.Error }),
DirectoryOpStatus.TooManyRequests => Results.StatusCode(StatusCodes.Status429TooManyRequests),
DirectoryOpStatus.ServiceUnavailable => Results.StatusCode(StatusCodes.Status503ServiceUnavailable),
_ => Results.BadRequest(new { error = result.Error })
};
});
app.MapDelete("/api/v1/servers/{serverId:guid}", (HttpContext ctx, Guid serverId, DirectoryRegistry reg) =>
{
string? token = ExtractLeaseToken(ctx);
var result = reg.DeleteServer(serverId, token);
return result.Status switch
{
DirectoryOpStatus.NoContent => Results.NoContent(),
DirectoryOpStatus.Forbidden => Results.StatusCode(StatusCodes.Status403Forbidden),
DirectoryOpStatus.NotFound => Results.NotFound(new { error = result.Error }),
_ => Results.BadRequest(new { error = result.Error })
};
});
return app;
}
private static IPAddress ResolveCallerIp(HttpContext ctx)
{
IPAddress remote = ctx.Connection.RemoteIpAddress ?? IPAddress.Loopback;
if (remote.IsIPv4MappedToIPv6) remote = remote.MapToIPv4();
// Only trust X-Real-IP when the immediate TCP peer is loopback (e.g. local nginx).
if (IPAddress.IsLoopback(remote) &&
ctx.Request.Headers.TryGetValue("X-Real-IP", out var realIpValues))
{
string raw = realIpValues.ToString().Trim();
if (IPAddress.TryParse(raw, out var parsed))
{
return parsed.IsIPv4MappedToIPv6 ? parsed.MapToIPv4() : parsed;
}
}
return remote;
}
private static string? ExtractLeaseToken(HttpContext ctx)
{
if (ctx.Request.Headers.TryGetValue("X-Lease-Token", out var headerVal))
{
string t = headerVal.ToString().Trim();
if (!string.IsNullOrEmpty(t)) return t;
}
if (ctx.Request.Headers.TryGetValue("Authorization", out var authVal))
{
string auth = authVal.ToString().Trim();
if (auth.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
{
string t = auth.Substring("Bearer ".Length).Trim();
if (!string.IsNullOrEmpty(t)) return t;
}
}
if (ctx.Request.Query.TryGetValue("leaseToken", out var queryVal))
{
string t = queryVal.ToString().Trim();
if (!string.IsNullOrEmpty(t)) return t;
}
return null;
}
}
internal sealed class DirectoryReaperService : BackgroundService
{
private readonly DirectoryRegistry _registry;
private readonly DirectoryRegistryOptions _options;
public DirectoryReaperService(DirectoryRegistry registry, DirectoryRegistryOptions options)
{
_registry = registry;
_options = options;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
TimeSpan interval = _options.ReaperInterval > TimeSpan.Zero
? _options.ReaperInterval
: TimeSpan.FromSeconds(5);
using var timer = new PeriodicTimer(interval);
try
{
while (await timer.WaitForNextTickAsync(stoppingToken))
{
_registry.SweepExpired();
}
}
catch (OperationCanceledException)
{
}
}
}
public static class Program
{
public static void Main(string[] args)
{
var app = DirectoryApp.Build(args);
app.Run();
}
}
}

View file

@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<RollForward>LatestMajor</RollForward>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,284 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace RustToDust.Net
{
public sealed record DirectoryServerInfo(
Guid ServerId,
string Name,
string PublicHost,
int UdpPort,
string Map,
int Seed,
int Humans,
int MaxHumans,
string Phase,
int Wave,
int ProtocolVersion,
bool HasPassword,
DateTimeOffset ExpiresAtUtc);
public readonly record struct DirectoryHeartbeatSnapshot(
string Name,
string PublicHost,
int UdpPort,
string Map,
int Seed,
int Humans,
int MaxHumans,
string Phase,
int Wave,
int ProtocolVersion = 1,
bool HasPassword = false);
public static class DirectoryBrowserClient
{
private static readonly HttpClient SharedHttp = new()
{
Timeout = TimeSpan.FromSeconds(5)
};
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
public static string NormalizeBaseUrl(string directoryBaseUrl)
{
string trimmed = (directoryBaseUrl ?? string.Empty).Trim();
while (trimmed.EndsWith('/'))
{
trimmed = trimmed.Substring(0, trimmed.Length - 1);
}
return trimmed;
}
public static async Task<IReadOnlyList<DirectoryServerInfo>> FetchServersAsync(
string directoryBaseUrl,
CancellationToken ct = default,
HttpClient? httpClient = null)
{
string baseUrl = NormalizeBaseUrl(directoryBaseUrl);
if (string.IsNullOrEmpty(baseUrl))
{
return Array.Empty<DirectoryServerInfo>();
}
HttpClient client = httpClient ?? SharedHttp;
using var req = new HttpRequestMessage(HttpMethod.Get, $"{baseUrl}/api/v1/servers");
using var resp = await client.SendAsync(req, ct).ConfigureAwait(false);
resp.EnsureSuccessStatusCode();
var list = await resp.Content.ReadFromJsonAsync<List<DirectoryServerInfo>>(JsonOptions, ct).ConfigureAwait(false);
return list ?? (IReadOnlyList<DirectoryServerInfo>)Array.Empty<DirectoryServerInfo>();
}
}
public sealed class DirectoryReporter : IDisposable
{
private sealed record HeartbeatBody(
Guid? ServerId,
string? LeaseToken,
string Name,
string? PublicHost,
int UdpPort,
string Map,
int Seed,
int Humans,
int MaxHumans,
string Phase,
int Wave,
int ProtocolVersion,
bool HasPassword);
private sealed class HeartbeatAck
{
public Guid ServerId { get; set; }
public string LeaseToken { get; set; } = string.Empty;
public int TtlSeconds { get; set; }
}
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly string _baseUrl;
private readonly Func<DirectoryHeartbeatSnapshot> _snapshotProvider;
private readonly TimeSpan _heartbeatInterval;
private readonly HttpClient _http;
private readonly bool _ownsHttp;
private readonly CancellationTokenSource _cts = new();
private readonly SemaphoreSlim _wakeSignal = new(0, 1);
private readonly Task _loopTask;
private Guid? _serverId;
private string? _leaseToken;
private int _disposed;
public DirectoryReporter(
string directoryBaseUrl,
Func<DirectoryHeartbeatSnapshot> snapshotProvider,
TimeSpan? heartbeatInterval = null,
HttpClient? httpClient = null)
{
_baseUrl = DirectoryBrowserClient.NormalizeBaseUrl(directoryBaseUrl);
if (string.IsNullOrEmpty(_baseUrl))
{
throw new ArgumentException("Directory base URL cannot be empty.", nameof(directoryBaseUrl));
}
_snapshotProvider = snapshotProvider ?? throw new ArgumentNullException(nameof(snapshotProvider));
_heartbeatInterval = heartbeatInterval ?? TimeSpan.FromSeconds(10);
if (httpClient is not null)
{
_http = httpClient;
_ownsHttp = false;
}
else
{
_http = new HttpClient { Timeout = TimeSpan.FromSeconds(4) };
_ownsHttp = true;
}
_loopTask = Task.Run(RunLoopAsync);
}
public Guid? CurrentServerId => _serverId;
public string? LastError { get; private set; }
public void NotifyChanged()
{
if (Volatile.Read(ref _disposed) != 0) return;
try
{
if (_wakeSignal.CurrentCount == 0)
{
_wakeSignal.Release();
}
}
catch (ObjectDisposedException)
{
}
catch (SemaphoreFullException)
{
}
}
private async Task RunLoopAsync()
{
while (!_cts.IsCancellationRequested)
{
await SendHeartbeatOnceAsync(_cts.Token).ConfigureAwait(false);
try
{
bool woken = await _wakeSignal.WaitAsync(_heartbeatInterval, _cts.Token).ConfigureAwait(false);
if (woken && !_cts.IsCancellationRequested)
{
await Task.Delay(250, _cts.Token).ConfigureAwait(false);
while (_wakeSignal.CurrentCount > 0)
{
_wakeSignal.Wait(0);
}
}
}
catch (OperationCanceledException)
{
break;
}
}
}
private async Task SendHeartbeatOnceAsync(CancellationToken ct)
{
try
{
var snap = _snapshotProvider();
var body = new HeartbeatBody(
_serverId,
_leaseToken,
snap.Name,
snap.PublicHost,
snap.UdpPort,
snap.Map,
snap.Seed,
snap.Humans,
snap.MaxHumans,
snap.Phase,
snap.Wave,
snap.ProtocolVersion,
snap.HasPassword);
using var resp = await _http.PostAsJsonAsync($"{_baseUrl}/api/v1/servers/heartbeat", body, ct).ConfigureAwait(false);
if (resp.StatusCode == HttpStatusCode.Conflict || resp.StatusCode == HttpStatusCode.NotFound)
{
_serverId = null;
_leaseToken = null;
LastError = $"Directory returned {(int)resp.StatusCode}; resetting lease.";
return;
}
if (!resp.IsSuccessStatusCode)
{
LastError = $"Directory heartbeat HTTP {(int)resp.StatusCode}";
return;
}
var ack = await resp.Content.ReadFromJsonAsync<HeartbeatAck>(JsonOptions, ct).ConfigureAwait(false);
if (ack is not null && ack.ServerId != Guid.Empty && !string.IsNullOrEmpty(ack.LeaseToken))
{
_serverId = ack.ServerId;
_leaseToken = ack.LeaseToken;
LastError = null;
}
}
catch (OperationCanceledException)
{
}
catch (Exception ex)
{
LastError = ex.Message;
}
}
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
_cts.Cancel();
try
{
_loopTask.Wait(TimeSpan.FromMilliseconds(500));
}
catch
{
}
if (_serverId is { } serverId && !string.IsNullOrEmpty(_leaseToken))
{
try
{
using var deleteCts = new CancellationTokenSource(TimeSpan.FromMilliseconds(1500));
using var req = new HttpRequestMessage(HttpMethod.Delete, $"{_baseUrl}/api/v1/servers/{serverId}");
req.Headers.TryAddWithoutValidation("X-Lease-Token", _leaseToken);
_http.SendAsync(req, deleteCts.Token).GetAwaiter().GetResult();
}
catch
{
}
}
_cts.Dispose();
_wakeSignal.Dispose();
if (_ownsHttp)
{
_http.Dispose();
}
}
}
}

View file

@ -15,7 +15,10 @@ namespace RustToDust.Net
int port,
int seed = 42,
ArenaMapKind mapKind = ArenaMapKind.Desert,
int maxHumans = MatchState.ContenderCount)
int maxHumans = MatchState.ContenderCount,
bool startInLobby = false,
string serverName = "Rust to Dust",
int minHumansToStart = 1)
{
_host = new ServerMatchHost(
bindAddress,
@ -25,7 +28,10 @@ namespace RustToDust.Net
maxHumans: maxHumans,
autoRestartSec: 0,
allowClientReset: false,
hostContenderId: 0);
hostContenderId: 0,
startInLobby: startInLobby,
serverName: serverName,
minHumansToStart: minHumansToStart);
}
public ServerMatchHost Host => _host;
@ -34,9 +40,11 @@ namespace RustToDust.Net
public ContenderState LocalContender => _host.Session.State.Contenders[0];
public ClientMatchOutcome LocalOutcome =>
_host.Session.State.Phase == MatchPhase.Active
? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat)
: (_host.Session.State.WinnerContenderId == 0 ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat);
_host.Session.State.Phase == MatchPhase.Lobby
? ClientMatchOutcome.Active
: _host.Session.State.Phase == MatchPhase.Active
? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat)
: (_host.Session.State.WinnerContenderId == 0 ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat);
public int LocalDetectedByCount =>
_host.Session.State.ObserverStates.TryGetValue(0, out var obs) ? obs.DetectedByCount : 0;
@ -59,12 +67,14 @@ namespace RustToDust.Net
public IReadOnlyList<OrbitalPod> ActivePods => _host.Session.State.OrbitalDrop.ActivePods;
public DropWaveState DropWaveState => _host.Session.State.OrbitalDrop.WaveState;
public IReadOnlyList<DropPodLifecycleEvent> PodEvents => _host.Session.State.PodEvents;
public LobbySnapshotDto? LobbyState => _host.BuildLobbySnapshotDto();
public bool IsContenderVisible(int contenderId) => true;
public bool IsSpectatorVisible(int spectatorId) => true;
public void BeginRenderFrame(double dt, float physicsAlpha)
{
_host.PollStatelessPings();
}
public void SubmitLocalInput(in PlayerInput input, bool isPhysicsTick)
@ -82,6 +92,10 @@ namespace RustToDust.Net
public void RequestNewMatch(int seed, ArenaMapKind mapKind) =>
_host.ResetMatch(seed, mapKind);
public bool SetLobbyReady(bool ready) => _host.SetLobbyReady(0, ready);
public bool RequestLobbyConfig(int seed, ArenaMapKind mapKind) => _host.ConfigureLobby(0, seed, mapKind);
public bool RequestLobbyStart() => _host.LaunchFromLobby(0);
public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha) =>
_host.Session.GetInterpolatedContenderPose(contenderId, alpha);

View file

@ -78,6 +78,8 @@ namespace RustToDust.Net
private int _pingMs;
private int _connectedHumans = 1;
private long _lastServerPacketUtcMs;
private long _lastKeepaliveUtcMs;
private LobbySnapshotDto? _lobbyState;
private float _podStepAccum;
private float _timeSinceLastPhysicsPodStep;
private bool _physicsPodSteppingActive;
@ -138,9 +140,11 @@ namespace RustToDust.Net
public ContenderState LocalContender => _viewState.Contenders[_localContenderId];
public ClientMatchOutcome LocalOutcome =>
_viewState.Phase == MatchPhase.Active
? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat)
: (_viewState.WinnerContenderId == _localContenderId ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat);
_viewState.Phase == MatchPhase.Lobby
? ClientMatchOutcome.Active
: _viewState.Phase == MatchPhase.Active
? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat)
: (_viewState.WinnerContenderId == _localContenderId ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat);
public int LocalDetectedByCount => _localDetectedByCount;
@ -165,6 +169,7 @@ namespace RustToDust.Net
public IReadOnlyList<OrbitalPod> ActivePods => _viewState.OrbitalDrop.ActivePods;
public DropWaveState DropWaveState => _viewState.OrbitalDrop.WaveState;
public IReadOnlyList<DropPodLifecycleEvent> PodEvents => _viewState.PodEvents;
public LobbySnapshotDto? LobbyState => _viewState.Phase == MatchPhase.Lobby ? _lobbyState : null;
public bool IsContenderVisible(int contenderId) =>
contenderId >= 0 && contenderId < _contenderVisible.Length && _contenderVisible[contenderId];
@ -342,6 +347,39 @@ namespace RustToDust.Net
});
}
public bool SetLobbyReady(bool ready)
{
if (!_joined || _viewState.Phase != MatchPhase.Lobby) return false;
SendSchemaMessage(new LobbyReadyCmdMsg
{
ReqSeq = _nextCmdSeq++,
IsReady = ready
});
return true;
}
public bool RequestLobbyConfig(int seed, ArenaMapKind mapKind)
{
if (!_joined || _viewState.Phase != MatchPhase.Lobby) return false;
SendSchemaMessage(new LobbyConfigCmdMsg
{
ReqSeq = _nextCmdSeq++,
Seed = seed,
MapKind = (byte)mapKind
});
return true;
}
public bool RequestLobbyStart()
{
if (!_joined || _viewState.Phase != MatchPhase.Lobby) return false;
SendSchemaMessage(new LobbyStartCmdMsg
{
ReqSeq = _nextCmdSeq++
});
return true;
}
public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha)
{
if (contenderId < 0 || contenderId >= _viewState.Contenders.Count)
@ -574,6 +612,12 @@ namespace RustToDust.Net
}
}
if (_joined && _conn.Connected && _viewState.Phase == MatchPhase.Lobby && (nowUtcMs - _lastKeepaliveUtcMs) >= 1000)
{
_lastKeepaliveUtcMs = nowUtcMs;
SendSchemaMessage(new ClientKeepaliveMsg { ClientSendMs = unchecked((uint)nowUtcMs) });
}
try
{
_conn.PollResends();
@ -659,9 +703,35 @@ namespace RustToDust.Net
case EntitySyncSnapshotMsg sync:
ApplyEntitySync(sync);
break;
case LobbySnapshotMsg lobbySnap:
if (lobbySnap.MatchGeneration == _matchGeneration)
{
ApplyLobbySnapshot(lobbySnap.Snapshot);
}
break;
}
}
private void ApplyLobbySnapshot(LobbySnapshotDto? snapshot)
{
_lobbyState = snapshot;
if (snapshot is null) return;
for (int i = 0; i < snapshot.Slots.Count && i < _viewState.Contenders.Count; i++)
{
var slot = snapshot.Slots[i];
if (slot.SlotId >= 0 && slot.SlotId < _viewState.Contenders.Count)
{
var c = _viewState.Contenders[slot.SlotId];
c.IsHuman = slot.IsHuman;
if (!string.IsNullOrWhiteSpace(slot.Callsign))
{
c.Name = slot.Callsign;
}
}
}
_connectedHumans = CountHumanContenders();
}
private static bool ContainsMatchReset(List<ISimEvent> events)
{
for (int i = 0; i < events.Count; i++)
@ -724,9 +794,16 @@ namespace RustToDust.Net
_viewState = new MatchState(dto.Seed, (ArenaMapKind)dto.MapKind, skipInitialDrop: true)
{
Time = dto.SimTime,
Phase = dto.Phase == 1 ? MatchPhase.Completed : MatchPhase.Active,
Phase = dto.Phase switch
{
1 => MatchPhase.Completed,
2 => MatchPhase.Lobby,
_ => MatchPhase.Active
},
WinnerContenderId = dto.WinnerContenderId
};
_lobbyState = _viewState.Phase == MatchPhase.Lobby ? dto.Lobby : null;
_lastKeepaliveUtcMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
_viewState.Spectators.SetReplicatedSafeRadius(dto.SafeRadius);
_viewState.OrbitalDrop.ApplyReplicatedWaveState(
dto.CurrentWaveIndex,
@ -1074,6 +1151,10 @@ namespace RustToDust.Net
private void ApplyCorePvsSnapshot(DecodedCorePvsSnapshot pkt)
{
_viewState.Time = pkt.SimTime;
if (_viewState.Phase == MatchPhase.Lobby && pkt.Phase != MatchPhase.Lobby)
{
_lobbyState = null;
}
_viewState.Phase = pkt.Phase;
_viewState.WinnerContenderId = pkt.WinnerContenderId;
_viewState.Spectators.SetReplicatedSafeRadius(pkt.SafeRadius);
@ -1595,6 +1676,13 @@ namespace RustToDust.Net
case MatchResetEvent reset:
ApplyInitialMatchState(reset.FullInitialState, reset.AssignedContenderId);
break;
case MatchStartedEvent started:
if (started.MatchGeneration == _matchGeneration || started.MatchGeneration == 0)
{
_viewState.Phase = MatchPhase.Active;
_lobbyState = null;
}
break;
}
_pendingClientEvents.Add(batch.Events[i]);
}

View file

@ -54,6 +54,10 @@ namespace RustToDust.Net
private readonly double _autoRestartSec;
private readonly bool _allowClientReset;
private readonly int? _hostContenderId;
private readonly string _serverName;
private readonly int _minHumansToStart;
private readonly bool _restartToLobby;
private readonly byte[] _udpPeekBuf = new byte[65535];
private ArenaSession _session;
private string _hostCallsign = "Host";
@ -65,6 +69,7 @@ namespace RustToDust.Net
private long _latestOutSeq = 1;
private uint _nextPeerId = 1;
private float _roundCompletedElapsed;
private int _lastBroadcastCountdownSec = -1;
private bool _disposed;
public ServerMatchHost(
@ -75,12 +80,19 @@ namespace RustToDust.Net
int maxHumans = MatchState.ContenderCount,
double autoRestartSec = 8.0,
bool allowClientReset = false,
int? hostContenderId = null)
int? hostContenderId = null,
bool startInLobby = false,
string serverName = "Rust to Dust",
int minHumansToStart = 1,
bool restartToLobby = false)
{
_maxHumans = Math.Clamp(maxHumans, 1, MatchState.ContenderCount);
_autoRestartSec = autoRestartSec;
_allowClientReset = allowClientReset;
_hostContenderId = hostContenderId;
_serverName = string.IsNullOrWhiteSpace(serverName) ? "Rust to Dust" : serverName.Trim();
_minHumansToStart = Math.Clamp(minHumansToStart, 1, _maxHumans);
_restartToLobby = restartToLobby;
_socket = new Socket(bindAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp)
{
@ -101,18 +113,25 @@ namespace RustToDust.Net
});
_server.PeerDisconnected += OnTransportPeerDisconnected;
_session = new ArenaSession(seed, mapKind, slot0Human: hostContenderId == 0);
_session = new ArenaSession(seed, mapKind, slot0Human: hostContenderId == 0, startInLobby: startInLobby);
if (hostContenderId.HasValue)
{
_session.SetHumanSlot(hostContenderId.Value, true, "Host");
}
InitLobbyMetadata(_session);
}
public int BoundPort { get; }
public ArenaSession Session => _session;
public uint MatchGeneration => _matchGeneration;
public uint SimTick => _simTick;
public string ServerName => _serverName;
public int MaxHumans => _maxHumans;
public int ConnectedHumanCount => _peersByEndpoint.Count + (_hostContenderId.HasValue ? 1 : 0);
public bool AcceptingJoin => ConnectedHumanCount < _maxHumans && (_session.State.Phase == MatchPhase.Lobby || _session.State.Phase == MatchPhase.Active);
public long TransportPacketsDropped => _server.Stats.PacketsDropped;
public CultNetTransportStats TransportStats => _server.Stats;
public LobbyState? Lobby => _session.State.Lobby;
public event Action<string>? LogMessage;
public void SetHostInput(in PlayerInput input)
@ -144,17 +163,21 @@ namespace RustToDust.Net
return ok;
}
public void ResetMatch(int seed, ArenaMapKind mapKind)
public void ResetMatch(int seed, ArenaMapKind mapKind) =>
ResetMatch(seed, mapKind, startInLobby: false);
public void ResetMatch(int seed, ArenaMapKind mapKind, bool startInLobby)
{
if (_hostContenderId.HasValue && _hostContenderId.Value >= 0 && _hostContenderId.Value < _session.State.Contenders.Count)
{
_hostCallsign = _session.State.Contenders[_hostContenderId.Value].Name;
}
_session.Dispose();
_session = new ArenaSession(seed, mapKind, slot0Human: _hostContenderId == 0);
_session = new ArenaSession(seed, mapKind, slot0Human: _hostContenderId == 0, startInLobby: startInLobby);
_matchGeneration++;
_simTick = 0;
_roundCompletedElapsed = 0f;
_lastBroadcastCountdownSec = -1;
_terrainStampHistory.Clear();
_stepEvents.Clear();
_hostPendingEvents.Clear();
@ -164,6 +187,7 @@ namespace RustToDust.Net
{
_session.SetHumanSlot(_hostContenderId.Value, true, _hostCallsign);
}
InitLobbyMetadata(_session);
foreach (var peer in _peersByEndpoint.Values)
{
@ -173,6 +197,12 @@ namespace RustToDust.Net
peer.LastInteractSeq = 0;
_session.SetHumanSlot(slot, true, peer.Callsign);
_reconnectTokens[peer.ReconnectToken] = (slot, peer.Callsign);
}
foreach (var peer in _peersByEndpoint.Values)
{
if (!peer.Active) continue;
int slot = peer.AssignedContenderId;
InitPeerTrackers(peer);
var reset = new MatchResetEvent
{
@ -193,6 +223,246 @@ namespace RustToDust.Net
}
}
public bool SetLobbyReady(int contenderId, bool ready)
{
if (_session.State.Phase != MatchPhase.Lobby || _session.State.Lobby is not { } lobby)
{
return false;
}
if (contenderId < 0 || contenderId >= lobby.Slots.Length || !lobby.Slots[contenderId].IsHuman)
{
return false;
}
lobby.Slots[contenderId].IsReady = ready;
ReevaluateLobbyCountdown(lobby);
BroadcastLobbySnapshot();
return true;
}
public bool ConfigureLobby(int requesterContenderId, int seed, ArenaMapKind mapKind)
{
if (_session.State.Phase != MatchPhase.Lobby)
{
return false;
}
if (!IsLobbyAuthority(requesterContenderId))
{
return false;
}
ResetMatch(seed, mapKind, startInLobby: true);
return true;
}
public bool LaunchFromLobby(int requesterContenderId)
{
if (_session.State.Phase != MatchPhase.Lobby || _session.State.Lobby is not { } lobby)
{
return false;
}
if (!IsLobbyAuthority(requesterContenderId))
{
return false;
}
if (lobby.ForceLaunched)
{
lobby.CountdownSeconds = 0f;
}
else
{
lobby.ForceLaunched = true;
lobby.CountdownSeconds ??= LobbyState.DefaultCountdownSeconds;
_lastBroadcastCountdownSec = (int)MathF.Ceiling(lobby.CountdownSeconds.Value);
BroadcastLobbySnapshot();
}
return true;
}
private bool IsLobbyAuthority(int requesterContenderId) =>
_hostContenderId.HasValue
? requesterContenderId == _hostContenderId.Value
: _allowClientReset;
private void InitLobbyMetadata(ArenaSession session)
{
if (session.State.Lobby is not { } lobby) return;
lobby.HostSlotId = _hostContenderId;
lobby.MinHumansToAutoStart = _minHumansToStart;
lobby.SelectedMap = session.State.MapKind;
lobby.SelectedSeed = session.State.Seed;
lobby.CountdownSeconds = null;
lobby.ForceLaunched = false;
for (int i = 0; i < session.State.Contenders.Count && i < lobby.Slots.Length; i++)
{
var c = session.State.Contenders[i];
lobby.Slots[i].IsHuman = c.IsHuman;
lobby.Slots[i].Callsign = c.Name;
lobby.Slots[i].IsReady = false;
}
}
private void ReevaluateLobbyCountdown(LobbyState lobby)
{
if (lobby.ForceLaunched)
{
lobby.CountdownSeconds ??= LobbyState.DefaultCountdownSeconds;
return;
}
int humanCount = 0;
bool allReady = true;
for (int i = 0; i < lobby.Slots.Length; i++)
{
if (!lobby.Slots[i].IsHuman) continue;
humanCount++;
if (!lobby.Slots[i].IsReady)
{
allReady = false;
}
}
if (humanCount >= lobby.MinHumansToAutoStart && allReady)
{
if (!lobby.CountdownSeconds.HasValue)
{
lobby.CountdownSeconds = LobbyState.DefaultCountdownSeconds;
_lastBroadcastCountdownSec = -1;
}
}
else
{
lobby.CountdownSeconds = null;
_lastBroadcastCountdownSec = -1;
}
}
public LobbySnapshotDto? BuildLobbySnapshotDto()
{
if (_session.State.Phase != MatchPhase.Lobby || _session.State.Lobby is not { } lobby)
{
return null;
}
var dto = new LobbySnapshotDto
{
HostSlotId = lobby.HostSlotId,
MinHumansToAutoStart = lobby.MinHumansToAutoStart,
CountdownSeconds = lobby.CountdownSeconds,
ForceLaunched = lobby.ForceLaunched,
SelectedMap = (byte)lobby.SelectedMap,
SelectedSeed = lobby.SelectedSeed,
Slots = new List<LobbySlotDto>(lobby.Slots.Length)
};
for (int i = 0; i < lobby.Slots.Length; i++)
{
var s = lobby.Slots[i];
dto.Slots.Add(new LobbySlotDto
{
SlotId = s.SlotId,
Callsign = s.Callsign,
IsHuman = s.IsHuman,
IsReady = s.IsReady
});
}
return dto;
}
private void BroadcastLobbySnapshot()
{
var dto = BuildLobbySnapshotDto();
if (dto is null || _peersByEndpoint.Count == 0) return;
var msg = new LobbySnapshotMsg
{
MatchGeneration = _matchGeneration,
Snapshot = dto
};
foreach (var peer in _peersByEndpoint.Values)
{
if (peer.Active)
{
SendSchemaToPeer(peer, msg);
}
}
}
public void PollStatelessPings()
{
if (_disposed) return;
for (int i = 0; i < 64; i++)
{
try
{
if (!_socket.Poll(0, SelectMode.SelectRead))
{
break;
}
// Note: Use Socket.Receive(..., SocketFlags.Peek) rather than ReceiveFrom(byte[], ..., Peek, ref EndPoint);
// on .NET 8/10 Windows, ReceiveFrom(byte[], ..., Peek, ref EndPoint) consumes the datagram instead of peeking.
int peeked = _socket.Receive(_udpPeekBuf, 0, _udpPeekBuf.Length, SocketFlags.Peek);
if (peeked <= 0)
{
break;
}
if (!SnapshotCodec.HasPingMagic(_udpPeekBuf.AsSpan(0, peeked)))
{
// Leave CultNet RUDP / other traffic untouched for _server.TryReceiveOnce.
break;
}
EndPoint consumeRemote = _socket.AddressFamily == AddressFamily.InterNetworkV6
? new IPEndPoint(IPAddress.IPv6Any, 0)
: new IPEndPoint(IPAddress.Any, 0);
int received = _socket.ReceiveFrom(_udpPeekBuf, 0, _udpPeekBuf.Length, SocketFlags.None, ref consumeRemote);
if (received > 0 && SnapshotCodec.TryDecodePing(_udpPeekBuf.AsSpan(0, received), out ulong clientNonce))
{
var summary = new ServerPingSummary(
clientNonce,
ProtocolVersion: 1,
MapKind: _session.State.MapKind,
Phase: _session.State.Phase,
Humans: (byte)Math.Clamp(ConnectedHumanCount, 0, byte.MaxValue),
MaxHumans: (byte)Math.Clamp(_maxHumans, 1, byte.MaxValue),
WaveIndex: (byte)Math.Clamp(_session.State.OrbitalDrop.CurrentWaveIndex, 0, byte.MaxValue),
AcceptingJoin: AcceptingJoin,
HasPassword: false,
Seed: _session.State.Seed,
ServerName: _serverName);
byte[] pong = SnapshotCodec.EncodePong(in summary);
_socket.SendTo(pong, consumeRemote);
}
}
catch (SocketException ex) when (
ex.SocketErrorCode == SocketError.WouldBlock ||
ex.SocketErrorCode == SocketError.TimedOut)
{
break;
}
catch (SocketException ex) when (
ex.SocketErrorCode == SocketError.ConnectionReset ||
ex.SocketErrorCode == SocketError.ConnectionAborted ||
ex.SocketErrorCode == SocketError.Shutdown)
{
try
{
EndPoint drainRemote = _socket.AddressFamily == AddressFamily.InterNetworkV6
? new IPEndPoint(IPAddress.IPv6Any, 0)
: new IPEndPoint(IPAddress.Any, 0);
_socket.ReceiveFrom(_udpPeekBuf, 0, _udpPeekBuf.Length, SocketFlags.None, ref drainRemote);
}
catch
{
}
break;
}
}
}
public void StepOnce(long nowUtcMs)
{
ObjectDisposedException.ThrowIf(_disposed, this);
@ -201,6 +471,27 @@ namespace RustToDust.Net
PollIncoming(nowUtcMs);
SweepTimeouts(nowUtcMs);
if (_session.State.Phase == MatchPhase.Lobby &&
_session.State.Lobby is { } lobby &&
lobby.CountdownSeconds.HasValue)
{
lobby.CountdownSeconds = MathF.Max(0f, lobby.CountdownSeconds.Value - ArenaSession.FixedDt);
if (lobby.CountdownSeconds.Value <= 0f)
{
_lastBroadcastCountdownSec = -1;
_session.StartFromLobby(_matchGeneration);
}
else
{
int wholeSec = (int)MathF.Ceiling(lobby.CountdownSeconds.Value);
if (wholeSec != _lastBroadcastCountdownSec)
{
_lastBroadcastCountdownSec = wholeSec;
BroadcastLobbySnapshot();
}
}
}
_session.Step();
_simTick++;
@ -236,7 +527,7 @@ namespace RustToDust.Net
_roundCompletedElapsed += ArenaSession.FixedDt;
if (_roundCompletedElapsed >= _autoRestartSec)
{
ResetMatch(_session.State.Seed + 1, _session.State.MapKind);
ResetMatch(_session.State.Seed + 1, _session.State.MapKind, startInLobby: _restartToLobby);
}
}
}
@ -246,6 +537,8 @@ namespace RustToDust.Net
int processed = 0;
while (processed < 256)
{
PollStatelessPings();
CultNetRudpSocketServerFrame? serverFrame;
try
{
@ -338,6 +631,33 @@ namespace RustToDust.Net
}
}
break;
case LobbyReadyCmdMsg readyCmd:
if (_peersByEndpoint.TryGetValue(epKey, out var readyPeer) && readyPeer.Active && ReferenceEquals(readyPeer.TransportPeer, transportPeer))
{
readyPeer.LastHeardUtcMs = nowUtcMs;
SetLobbyReady(readyPeer.AssignedContenderId, readyCmd.IsReady);
}
break;
case LobbyConfigCmdMsg cfgCmd:
if (_peersByEndpoint.TryGetValue(epKey, out var cfgPeer) && cfgPeer.Active && ReferenceEquals(cfgPeer.TransportPeer, transportPeer))
{
cfgPeer.LastHeardUtcMs = nowUtcMs;
ConfigureLobby(cfgPeer.AssignedContenderId, cfgCmd.Seed, (ArenaMapKind)cfgCmd.MapKind);
}
break;
case LobbyStartCmdMsg:
if (_peersByEndpoint.TryGetValue(epKey, out var startPeer) && startPeer.Active && ReferenceEquals(startPeer.TransportPeer, transportPeer))
{
startPeer.LastHeardUtcMs = nowUtcMs;
LaunchFromLobby(startPeer.AssignedContenderId);
}
break;
case ClientKeepaliveMsg:
if (_peersByEndpoint.TryGetValue(epKey, out var keepPeer) && keepPeer.Active && ReferenceEquals(keepPeer.TransportPeer, transportPeer))
{
keepPeer.LastHeardUtcMs = nowUtcMs;
}
break;
}
}
@ -424,6 +744,15 @@ namespace RustToDust.Net
_peersByEndpoint[epKey] = peer;
SendJoinAccepted(peer);
if (_session.State.Phase == MatchPhase.Lobby && _session.State.Lobby is { } lobby)
{
if (!lobby.ForceLaunched)
{
lobby.CountdownSeconds = null;
_lastBroadcastCountdownSec = -1;
}
BroadcastLobbySnapshot();
}
LogMessage?.Invoke($"[tick {_simTick}] Peer #{peer.PeerId} '{callsign}' joined slot {slotId} ({epKey}), humans={ConnectedHumanCount}/{_maxHumans}");
_stepEvents.Add(new EntitySlotControlEvent
@ -533,6 +862,11 @@ namespace RustToDust.Net
Reason = (byte)reason
});
}
if (_session.State.Phase == MatchPhase.Lobby && _session.State.Lobby is { } lobby)
{
ReevaluateLobbyCountdown(lobby);
BroadcastLobbySnapshot();
}
LogMessage?.Invoke($"[tick {_simTick}] Peer #{peer.PeerId} '{peer.Callsign}' disconnected from slot {slot} ({reason}), humans={ConnectedHumanCount}/{_maxHumans}");
}
@ -1238,11 +1572,12 @@ namespace RustToDust.Net
MapKind = (byte)_session.State.MapKind,
SimTime = _session.State.Time,
SafeRadius = _session.State.Spectators.SafeRadius,
Phase = (byte)(_session.State.Phase == MatchPhase.Completed ? 1 : 0),
Phase = (byte)(_session.State.Phase == MatchPhase.Completed ? 1 : _session.State.Phase == MatchPhase.Lobby ? 2 : 0),
WinnerContenderId = _session.State.WinnerContenderId,
ConnectedHumans = ConnectedHumanCount,
CurrentWaveIndex = _session.State.OrbitalDrop.CurrentWaveIndex,
RespawnCutoffReached = _session.State.OrbitalDrop.RespawnCutoffReached
RespawnCutoffReached = _session.State.OrbitalDrop.RespawnCutoffReached,
Lobby = BuildLobbySnapshotDto()
};
var activePods = _session.State.OrbitalDrop.ActivePods;

View file

@ -0,0 +1,151 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
namespace RustToDust.Net
{
public sealed record ServerPingResult(
string Host,
int Port,
IPEndPoint? ResolvedEndPoint,
bool Success,
int RttMs,
ServerPingSummary? Summary);
public static class ServerPingProbe
{
public static async Task<ServerPingResult> ProbeAsync(
string host,
int port,
TimeSpan timeout,
CancellationToken ct = default)
{
if (string.IsNullOrWhiteSpace(host) || port < 1 || port > 65535)
{
return new ServerPingResult(host ?? string.Empty, port, null, false, -1, null);
}
IPAddress? resolvedIp = null;
if (IPAddress.TryParse(host.Trim(), out var parsed))
{
resolvedIp = parsed;
}
else
{
try
{
var addrs = await Dns.GetHostAddressesAsync(host.Trim(), ct).ConfigureAwait(false);
for (int i = 0; i < addrs.Length; i++)
{
if (addrs[i].AddressFamily == AddressFamily.InterNetwork)
{
resolvedIp = addrs[i];
break;
}
}
if (resolvedIp is null && addrs.Length > 0)
{
resolvedIp = addrs[0];
}
}
catch
{
return new ServerPingResult(host, port, null, false, -1, null);
}
}
if (resolvedIp is null)
{
return new ServerPingResult(host, port, null, false, -1, null);
}
var ep = new IPEndPoint(resolvedIp, port);
var res = await ProbeAsync(ep, timeout, ct).ConfigureAwait(false);
return res with { Host = host };
}
public static async Task<ServerPingResult> ProbeAsync(
IPEndPoint target,
TimeSpan timeout,
CancellationToken ct = default)
{
using var socket = new Socket(target.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
socket.Bind(new IPEndPoint(
target.AddressFamily == AddressFamily.InterNetworkV6 ? IPAddress.IPv6Any : IPAddress.Any,
0));
ulong nonce = BitConverter.ToUInt64(RandomNumberGenerator.GetBytes(8), 0);
byte[] ping = SnapshotCodec.EncodePing(nonce);
byte[] recvBuf = new byte[512];
using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeoutCts.CancelAfter(timeout);
try
{
long startTs = Stopwatch.GetTimestamp();
await socket.SendToAsync(ping, SocketFlags.None, target, timeoutCts.Token).ConfigureAwait(false);
EndPoint anyRemote = target.AddressFamily == AddressFamily.InterNetworkV6
? new IPEndPoint(IPAddress.IPv6Any, 0)
: new IPEndPoint(IPAddress.Any, 0);
while (!timeoutCts.IsCancellationRequested)
{
var res = await socket.ReceiveFromAsync(recvBuf, SocketFlags.None, anyRemote, timeoutCts.Token).ConfigureAwait(false);
if (SnapshotCodec.TryDecodePong(recvBuf.AsSpan(0, res.ReceivedBytes), out var summary) &&
summary.ClientNonce == nonce)
{
int rttMs = Math.Max(1, (int)Math.Round(Stopwatch.GetElapsedTime(startTs).TotalMilliseconds));
return new ServerPingResult(target.Address.ToString(), target.Port, target, true, rttMs, summary);
}
}
}
catch (OperationCanceledException)
{
}
catch (SocketException)
{
}
return new ServerPingResult(target.Address.ToString(), target.Port, target, false, -1, null);
}
public static async Task<ServerPingResult[]> ProbeManyAsync(
IReadOnlyList<(string Host, int Port)> targets,
TimeSpan timeout,
int maxConcurrency = 16,
CancellationToken ct = default)
{
var results = new ServerPingResult[targets.Count];
using var gate = new SemaphoreSlim(Math.Max(1, maxConcurrency));
var tasks = new Task[targets.Count];
for (int i = 0; i < targets.Count; i++)
{
int idx = i;
var target = targets[i];
tasks[i] = Task.Run(async () =>
{
await gate.WaitAsync(ct).ConfigureAwait(false);
try
{
results[idx] = await ProbeAsync(target.Host, target.Port, timeout, ct).ConfigureAwait(false);
}
finally
{
gate.Release();
}
}, ct);
}
await Task.WhenAll(tasks).ConfigureAwait(false);
return results;
}
}
}

View file

@ -2,6 +2,7 @@ using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
using GameCult.Mesh;
using MessagePack;
using RustToDust.Core;
@ -130,9 +131,26 @@ namespace RustToDust.Net
public List<NetRadarContact> Spectators = new();
}
public readonly record struct ServerPingSummary(
ulong ClientNonce,
ushort ProtocolVersion,
ArenaMapKind MapKind,
MatchPhase Phase,
byte Humans,
byte MaxHumans,
byte WaveIndex,
bool AcceptingJoin,
bool HasPassword,
int Seed,
string ServerName);
public static class SnapshotCodec
{
public const int MaxLatestDatagramBytes = 1152;
public const int PingPacketBytes = 32;
public const byte PingWireVersion = 1;
public const byte PingKindRequest = 1;
public const byte PingKindResponse = 2;
public const string ChannelLatest = "latest";
public const string ChannelSchema = "schema";
public const string SchemaLatestId = "rtd.snap";
@ -333,8 +351,13 @@ namespace RustToDust.Net
BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), echoSendMs); offset += 4;
BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), safeRadius); offset += 4;
byte phaseByte = (byte)(phase == MatchPhase.Completed ? 1 : 0);
if (winnerContenderId.HasValue) phaseByte |= 2;
byte phaseByte = phase switch
{
MatchPhase.Completed => 1,
MatchPhase.Lobby => 2,
_ => 0
};
if (winnerContenderId.HasValue) phaseByte |= 0x04;
buf[offset++] = phaseByte;
buf[offset++] = (byte)(sbyte)(winnerContenderId ?? -1);
buf[offset++] = detectedByCount;
@ -501,9 +524,14 @@ namespace RustToDust.Net
decoded.SafeRadius = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)); offset += 4;
byte phaseByte = span[offset++];
decoded.Phase = (phaseByte & 1) != 0 ? MatchPhase.Completed : MatchPhase.Active;
decoded.Phase = (phaseByte & 0x03) switch
{
1 => MatchPhase.Completed,
2 => MatchPhase.Lobby,
_ => MatchPhase.Active
};
sbyte winnerRaw = (sbyte)span[offset++];
decoded.WinnerContenderId = (phaseByte & 2) != 0 ? winnerRaw : null;
decoded.WinnerContenderId = (phaseByte & 0x04) != 0 ? winnerRaw : null;
decoded.DetectedByCount = span[offset++];
ushort arc = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(offset)); offset += 2;
@ -972,5 +1000,140 @@ namespace RustToDust.Net
var v = new Vector3(ox, ny, oy);
return v.LengthSquared() < 1e-6f ? Vector3.UnitY : Vector3.Normalize(v);
}
public static bool HasPingMagic(ReadOnlySpan<byte> buf) =>
buf.Length >= 4 &&
buf[0] == (byte)'R' &&
buf[1] == (byte)'T' &&
buf[2] == (byte)'D' &&
buf[3] == (byte)'P';
public static byte[] EncodePing(ulong clientNonce)
{
byte[] buf = new byte[PingPacketBytes];
buf[0] = (byte)'R';
buf[1] = (byte)'T';
buf[2] = (byte)'D';
buf[3] = (byte)'P';
buf[4] = PingWireVersion;
buf[5] = PingKindRequest;
BinaryPrimitives.WriteUInt64LittleEndian(buf.AsSpan(8, 8), clientNonce);
return buf;
}
public static bool TryDecodePing(ReadOnlySpan<byte> buf, out ulong clientNonce)
{
if (buf.Length < 16 ||
!HasPingMagic(buf) ||
buf[4] != PingWireVersion ||
buf[5] != PingKindRequest)
{
clientNonce = 0;
return false;
}
clientNonce = BinaryPrimitives.ReadUInt64LittleEndian(buf.Slice(8, 8));
return true;
}
public static byte[] EncodePong(in ServerPingSummary summary)
{
string rawName = string.IsNullOrWhiteSpace(summary.ServerName) ? "Rust to Dust" : summary.ServerName.Trim();
Span<byte> 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--;
}
}
byte[] buf = new byte[27 + nameBytes];
var span = buf.AsSpan();
span[0] = (byte)'R';
span[1] = (byte)'T';
span[2] = (byte)'D';
span[3] = (byte)'P';
span[4] = PingWireVersion;
span[5] = PingKindResponse;
BinaryPrimitives.WriteUInt16LittleEndian(span.Slice(6, 2), summary.ProtocolVersion);
BinaryPrimitives.WriteUInt64LittleEndian(span.Slice(8, 8), summary.ClientNonce);
span[16] = (byte)summary.MapKind;
span[17] = summary.Phase switch
{
MatchPhase.Completed => 1,
MatchPhase.Lobby => 2,
_ => 0
};
span[18] = summary.Humans;
span[19] = summary.MaxHumans;
span[20] = summary.WaveIndex;
byte flags = 0;
if (summary.AcceptingJoin) flags |= 1;
if (summary.HasPassword) flags |= 2;
span[21] = flags;
BinaryPrimitives.WriteInt32LittleEndian(span.Slice(22, 4), summary.Seed);
span[26] = (byte)nameBytes;
if (nameBytes > 0)
{
utf8Buf.Slice(0, nameBytes).CopyTo(span.Slice(27));
}
return buf;
}
public static bool TryDecodePong(ReadOnlySpan<byte> buf, out ServerPingSummary summary)
{
if (buf.Length < 27 ||
!HasPingMagic(buf) ||
buf[4] != PingWireVersion ||
buf[5] != PingKindResponse)
{
summary = default;
return false;
}
int nameLen = buf[26];
if (nameLen > 64 || 27 + nameLen > buf.Length)
{
summary = default;
return false;
}
ushort proto = BinaryPrimitives.ReadUInt16LittleEndian(buf.Slice(6, 2));
ulong nonce = BinaryPrimitives.ReadUInt64LittleEndian(buf.Slice(8, 8));
ArenaMapKind mapKind = (ArenaMapKind)buf[16];
MatchPhase phase = buf[17] switch
{
1 => MatchPhase.Completed,
2 => MatchPhase.Lobby,
_ => MatchPhase.Active
};
byte humans = buf[18];
byte maxHumans = buf[19];
byte waveIndex = buf[20];
byte flags = buf[21];
int seed = BinaryPrimitives.ReadInt32LittleEndian(buf.Slice(22, 4));
string name = nameLen > 0 ? Encoding.UTF8.GetString(buf.Slice(27, nameLen)) : "Rust to Dust";
summary = new ServerPingSummary(
nonce,
proto,
mapKind,
phase,
humans,
maxHumans,
waveIndex,
AcceptingJoin: (flags & 1) != 0,
HasPassword: (flags & 2) != 0,
seed,
name);
return true;
}
}
}

View file

@ -21,6 +21,12 @@ namespace RustToDust.Server
double autoRestartSec = 8.0;
double durationSec = 0.0;
bool allowClientReset = false;
string? directoryUrl = Environment.GetEnvironmentVariable("RTD_DIRECTORY_URL");
string serverName = Environment.GetEnvironmentVariable("RTD_SERVER_NAME") ?? "Rust to Dust";
string publicHost = Environment.GetEnvironmentVariable("RTD_PUBLIC_HOST") ?? "auto";
bool startInLobby = TryParseBool(Environment.GetEnvironmentVariable("RTD_LOBBY"), false);
int minHumansToStart = TryParseInt(Environment.GetEnvironmentVariable("RTD_MIN_HUMANS"), 1);
bool restartToLobby = TryParseBool(Environment.GetEnvironmentVariable("RTD_RESTART_TO_LOBBY"), false);
for (int i = 0; i < args.Length; i++)
{
@ -42,6 +48,16 @@ namespace RustToDust.Server
else if (a == "--allow-client-reset") allowClientReset = true;
else if (a == "--assets-dir" && i + 1 < args.Length) Environment.SetEnvironmentVariable("RTD_ASSETS_DIR", args[++i]);
else if (a.StartsWith("--assets-dir=", StringComparison.Ordinal)) Environment.SetEnvironmentVariable("RTD_ASSETS_DIR", a.Substring("--assets-dir=".Length));
else if (a == "--directory-url" && i + 1 < args.Length) directoryUrl = args[++i];
else if (a.StartsWith("--directory-url=", StringComparison.Ordinal)) directoryUrl = a.Substring("--directory-url=".Length);
else if (a == "--server-name" && i + 1 < args.Length) serverName = args[++i];
else if (a.StartsWith("--server-name=", StringComparison.Ordinal)) serverName = a.Substring("--server-name=".Length);
else if (a == "--public-host" && i + 1 < args.Length) publicHost = args[++i];
else if (a.StartsWith("--public-host=", StringComparison.Ordinal)) publicHost = a.Substring("--public-host=".Length);
else if (a == "--lobby") startInLobby = true;
else if (a == "--min-humans" && i + 1 < args.Length) minHumansToStart = TryParseInt(args[++i], minHumansToStart);
else if (a.StartsWith("--min-humans=", StringComparison.Ordinal)) minHumansToStart = TryParseInt(a.Substring("--min-humans=".Length), minHumansToStart);
else if (a == "--restart-to-lobby") restartToLobby = true;
}
if (!IPAddress.TryParse(bindStr, out var bindIp))
@ -64,6 +80,7 @@ namespace RustToDust.Server
Console.CancelKeyPress += cancelHandler;
AppDomain.CurrentDomain.ProcessExit += exitHandler;
DirectoryReporter? reporter = null;
try
{
using var host = new ServerMatchHost(
@ -73,15 +90,38 @@ namespace RustToDust.Server
mapKind,
maxHumans,
autoRestartSec,
allowClientReset);
allowClientReset,
hostContenderId: null,
startInLobby: startInLobby,
serverName: serverName,
minHumansToStart: minHumansToStart,
restartToLobby: restartToLobby);
host.LogMessage += msg => Console.WriteLine(msg);
Console.WriteLine($"RustToDust.Server listening on {bindIp}:{host.BoundPort} (map={mapKind}, seed={seed}, maxHumans={maxHumans})");
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));
}
Console.WriteLine($"RustToDust.Server listening on {bindIp}:{host.BoundPort} (name=\"{host.ServerName}\", map={mapKind}, seed={seed}, maxHumans={maxHumans}, lobby={startInLobby})");
double tickSec = ArenaSession.FixedDt;
var sw = Stopwatch.StartNew();
double nextTickSec = sw.Elapsed.TotalSeconds;
double endSec = durationSec > 0.0 ? durationSec : double.PositiveInfinity;
int lastReportedHumans = host.ConnectedHumanCount;
MatchPhase lastReportedPhase = host.Session.State.Phase;
while (!cts.IsCancellationRequested && sw.Elapsed.TotalSeconds < endSec)
{
@ -89,6 +129,14 @@ namespace RustToDust.Server
if (nowSec >= nextTickSec)
{
host.StepOnce(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
if (reporter is not null &&
(host.ConnectedHumanCount != lastReportedHumans || host.Session.State.Phase != lastReportedPhase))
{
lastReportedHumans = host.ConnectedHumanCount;
lastReportedPhase = host.Session.State.Phase;
reporter.NotifyChanged();
}
nextTickSec += tickSec;
if (nowSec - nextTickSec > 0.25)
{
@ -97,6 +145,7 @@ namespace RustToDust.Server
}
else
{
host.PollStatelessPings();
double remainingMs = (nextTickSec - nowSec) * 1000.0;
if (remainingMs > 2.0)
{
@ -119,6 +168,7 @@ namespace RustToDust.Server
}
finally
{
reporter?.Dispose();
Console.CancelKeyPress -= cancelHandler;
AppDomain.CurrentDomain.ProcessExit -= exitHandler;
}
@ -129,5 +179,13 @@ namespace RustToDust.Server
private static double TryParseDouble(string? s, double fallback) =>
double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out double v) ? v : fallback;
private static bool TryParseBool(string? s, bool fallback)
{
if (string.IsNullOrWhiteSpace(s)) return fallback;
if (s == "1") return true;
if (s == "0") return false;
return bool.TryParse(s, out bool v) ? v : fallback;
}
}
}

View file

@ -34,9 +34,9 @@ namespace RustToDust.Ymir
private long _forwardedPodEventId;
private bool _disposed;
public ArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool slot0Human = false, bool skipInitialDrop = false)
public ArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool slot0Human = false, bool skipInitialDrop = false, bool startInLobby = false)
{
State = new MatchState(seed, mapKind, skipInitialDrop);
State = new MatchState(seed, mapKind, skipInitialDrop, startInLobby);
_spectatorPvs = new bool[MatchState.ContenderCount, State.Spectators.Spectators.Count];
_forwardedPodEventId = State.PodEvents.Count > 0 ? State.PodEvents[^1].EventId : 0;
@ -121,6 +121,15 @@ namespace RustToDust.Ymir
{
State.GetOrCreateObserverState(contenderId);
}
if (State.Lobby is { } lobby && contenderId >= 0 && contenderId < lobby.Slots.Length)
{
lobby.Slots[contenderId].IsHuman = isHuman;
lobby.Slots[contenderId].Callsign = c.Name;
if (!isHuman)
{
lobby.Slots[contenderId].IsReady = false;
}
}
if (c.ActivePodId is { } activePodId)
{
for (int p = 0; p < State.OrbitalDrop.ActivePods.Count; p++)
@ -608,6 +617,14 @@ namespace RustToDust.Ymir
SnapshotPreviousPoses();
if (State.Phase == MatchPhase.Lobby)
{
MatchRules.AdvanceTracers(State, FixedDt);
MatchRules.AdvanceHitEvents(State, FixedDt);
FlushPodEventsToStepEvents();
return;
}
State.Time += FixedDt;
MatchRules.AdvanceTracers(State, FixedDt);
MatchRules.AdvanceHitEvents(State, FixedDt);
@ -682,6 +699,38 @@ namespace RustToDust.Ymir
PerfWeaponsMs += (t7 - t6) * toMs;
}
public bool StartFromLobby(uint matchGeneration = 1)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (State.Phase != MatchPhase.Lobby)
{
return false;
}
foreach (var kv in _contenderBodies)
{
_world.RemoveBody(kv.Value);
}
_contenderBodies.Clear();
_contenderWalkers.Clear();
if (!State.StartFromLobby(QueryDropSurface))
{
return false;
}
SpawnContenderBodies();
FlushPodEventsToStepEvents();
_stepEvents.Add(new MatchStartedEvent
{
MatchGeneration = matchGeneration,
MapKind = (byte)State.MapKind,
Seed = State.Seed
});
UpdateObserverDetectionMemories();
return true;
}
public static void BuildStaticArena(Box3DSoaWorld world, MatchState state)
{
if (state.MapKind == ArenaMapKind.Sion && state.SionMap is { } sion)

View file

@ -27,9 +27,11 @@ namespace RustToDust.Ymir
public ContenderState LocalContender => Inner.State.Contenders[0];
public ClientMatchOutcome LocalOutcome =>
Inner.State.Phase == MatchPhase.Active
? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat)
: (Inner.State.WinnerContenderId == LocalContenderId ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat);
Inner.State.Phase == MatchPhase.Lobby
? ClientMatchOutcome.Active
: Inner.State.Phase == MatchPhase.Active
? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat)
: (Inner.State.WinnerContenderId == LocalContenderId ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat);
public int LocalDetectedByCount =>
Inner.State.ObserverStates.TryGetValue(LocalContenderId, out var obs) ? obs.DetectedByCount : 0;
@ -46,6 +48,7 @@ namespace RustToDust.Ymir
public IReadOnlyList<OrbitalPod> ActivePods => Inner.State.OrbitalDrop.ActivePods;
public DropWaveState DropWaveState => Inner.State.OrbitalDrop.WaveState;
public IReadOnlyList<DropPodLifecycleEvent> PodEvents => Inner.State.PodEvents;
public LobbySnapshotDto? LobbyState => null;
public bool IsContenderVisible(int contenderId) => true;
public bool IsSpectatorVisible(int spectatorId) => true;
@ -104,6 +107,10 @@ namespace RustToDust.Ymir
}
}
public bool SetLobbyReady(bool ready) => false;
public bool RequestLobbyConfig(int seed, ArenaMapKind mapKind) => false;
public bool RequestLobbyStart() => false;
public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha) =>
Inner.GetInterpolatedContenderPose(contenderId, alpha);

View file

@ -0,0 +1,611 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Net.Sockets;
using System.Numerics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using GameCult.Networking;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using RustToDust.Core;
using RustToDust.DirectoryService;
using RustToDust.Net;
using RustToDust.Ymir;
using Xunit;
namespace RustToDust.Tests
{
public sealed class LobbyAndDirectoryTests
{
private static async Task<(WebApplication App, string BaseUrl)> StartDirectoryServerAsync(DirectoryRegistryOptions? options = null)
{
var opts = options ?? new DirectoryRegistryOptions();
var app = DirectoryApp.Build(Array.Empty<string>(), opts);
app.Urls.Clear();
app.Urls.Add("http://127.0.0.1:0");
await app.StartAsync();
string baseUrl = app.Urls.First();
return (app, baseUrl);
}
private static void PumpHostAndClients(ServerMatchHost host, params RemoteArenaSession[] clients)
{
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
host.StepOnce(nowMs);
for (int i = 0; i < clients.Length; i++)
{
clients[i].PumpNetwork(nowMs);
}
}
private static void PumpListenHostAndClient(ListenHostArenaSession listenHost, RemoteArenaSession client, int ticks = 1)
{
for (int i = 0; i < ticks; i++)
{
listenHost.SubmitLocalInput(default, isPhysicsTick: true);
client.PumpNetwork();
Thread.Sleep(2);
}
}
[Fact]
public async Task Directory_Heartbeat_LeaseTokenSecrecy_AuthRejection_LoopbackSpoof_And_TtlExpiry()
{
var now = DateTimeOffset.UtcNow;
var opts = new DirectoryRegistryOptions
{
EntryTtl = TimeSpan.FromMilliseconds(350),
ReaperInterval = TimeSpan.FromMilliseconds(60),
UtcNow = () => now
};
var (app, baseUrl) = await StartDirectoryServerAsync(opts);
try
{
using var http = new HttpClient { BaseAddress = new Uri(baseUrl) };
// 1. Register with empty publicHost behind simulated nginx X-Real-IP -> auto-resolves to caller IP
using var regReq = new HttpRequestMessage(HttpMethod.Post, "/api/v1/servers/heartbeat")
{
Content = JsonContent.Create(new DirectoryHeartbeatRequest
{
Name = "Yggdrasil Ring",
PublicHost = "",
UdpPort = 3076,
Map = "sion",
Seed = 77,
Humans = 2,
MaxHumans = 12,
Phase = "Lobby",
Wave = 0
})
};
regReq.Headers.TryAddWithoutValidation("X-Real-IP", "203.0.113.42");
using var regResp = await http.SendAsync(regReq);
Assert.Equal(HttpStatusCode.OK, regResp.StatusCode);
var ack = await regResp.Content.ReadFromJsonAsync<DirectoryHeartbeatResponse>();
Assert.NotNull(ack);
Assert.NotEqual(Guid.Empty, ack!.ServerId);
Assert.False(string.IsNullOrWhiteSpace(ack.LeaseToken));
Assert.True(ack.TtlSeconds >= 1);
// 2. GET /api/v1/servers returns resolved publicHost and NEVER exposes leaseToken
string rawListJson = await http.GetStringAsync("/api/v1/servers");
Assert.DoesNotContain(ack.LeaseToken, rawListJson, StringComparison.Ordinal);
var list = await DirectoryBrowserClient.FetchServersAsync(baseUrl, httpClient: http);
Assert.Single(list);
Assert.Equal(ack.ServerId, list[0].ServerId);
Assert.Equal("203.0.113.42", list[0].PublicHost);
Assert.Equal("sion", list[0].Map);
Assert.Equal("Lobby", list[0].Phase);
// 3. Non-loopback X-Real-IP attempting to spoof loopback publicHost is rejected (400)
foreach (string spoofHost in new[] { "127.0.0.1", "localhost", "::1" })
{
using var spoofReq = new HttpRequestMessage(HttpMethod.Post, "/api/v1/servers/heartbeat")
{
Content = JsonContent.Create(new DirectoryHeartbeatRequest
{
Name = "Spoofed",
PublicHost = spoofHost,
UdpPort = 3076
})
};
spoofReq.Headers.TryAddWithoutValidation("X-Real-IP", "203.0.113.42");
using var spoofResp = await http.SendAsync(spoofReq);
Assert.Equal(HttpStatusCode.BadRequest, spoofResp.StatusCode);
}
// 4. Wrong leaseToken on refresh -> 403, entry stays intact
using var badRefresh = await http.PostAsJsonAsync("/api/v1/servers/heartbeat", new DirectoryHeartbeatRequest
{
ServerId = ack.ServerId,
LeaseToken = "wrong-token-value",
Name = "Hijacked",
PublicHost = "203.0.113.42",
UdpPort = 3076
});
Assert.Equal(HttpStatusCode.Forbidden, badRefresh.StatusCode);
// 5. Wrong leaseToken on DELETE -> 403, entry stays intact
using var badDeleteReq = new HttpRequestMessage(HttpMethod.Delete, $"/api/v1/servers/{ack.ServerId}");
badDeleteReq.Headers.TryAddWithoutValidation("X-Lease-Token", "wrong-token-value");
using var badDeleteResp = await http.SendAsync(badDeleteReq);
Assert.Equal(HttpStatusCode.Forbidden, badDeleteResp.StatusCode);
var stillPresent = await DirectoryBrowserClient.FetchServersAsync(baseUrl, httpClient: http);
Assert.Single(stillPresent);
Assert.Equal("Yggdrasil Ring", stillPresent[0].Name);
// 6. Valid leaseToken refresh succeeds and keeps entry alive
using var goodRefresh = await http.PostAsJsonAsync("/api/v1/servers/heartbeat", new DirectoryHeartbeatRequest
{
ServerId = ack.ServerId,
LeaseToken = ack.LeaseToken,
Name = "Yggdrasil Ring Updated",
PublicHost = "203.0.113.42",
UdpPort = 3076,
Humans = 5,
Phase = "Active",
Wave = 1
});
Assert.Equal(HttpStatusCode.OK, goodRefresh.StatusCode);
// 7. Advance clock past TTL -> entry expires cleanly and disappears
now = now + TimeSpan.FromMilliseconds(500);
await Task.Delay(150);
var afterExpiry = await DirectoryBrowserClient.FetchServersAsync(baseUrl, httpClient: http);
Assert.Empty(afterExpiry);
}
finally
{
await app.StopAsync();
await app.DisposeAsync();
}
}
[Fact]
public async Task DirectoryReporter_Registers_Updates_And_DeregistersOnDispose()
{
var (app, baseUrl) = await StartDirectoryServerAsync();
try
{
int humans = 1;
string phase = "Lobby";
var reporter = new DirectoryReporter(
baseUrl,
() => new DirectoryHeartbeatSnapshot(
"Reporter Test Ring",
"127.0.0.1",
3079,
"desert",
42,
humans,
12,
phase,
0),
heartbeatInterval: TimeSpan.FromSeconds(30));
try
{
var deadline = DateTime.UtcNow.AddSeconds(3);
IReadOnlyList<DirectoryServerInfo> servers = Array.Empty<DirectoryServerInfo>();
while (DateTime.UtcNow < deadline)
{
servers = await DirectoryBrowserClient.FetchServersAsync(baseUrl);
if (servers.Count > 0) break;
await Task.Delay(25);
}
Assert.Single(servers);
Assert.Equal("Reporter Test Ring", servers[0].Name);
Assert.Equal(1, servers[0].Humans);
humans = 4;
phase = "Active";
reporter.NotifyChanged();
deadline = DateTime.UtcNow.AddSeconds(3);
while (DateTime.UtcNow < deadline)
{
servers = await DirectoryBrowserClient.FetchServersAsync(baseUrl);
if (servers.Count == 1 && servers[0].Humans == 4 && servers[0].Phase == "Active") break;
await Task.Delay(25);
}
Assert.Equal(4, servers[0].Humans);
Assert.Equal("Active", servers[0].Phase);
}
finally
{
reporter.Dispose();
}
var afterDispose = await DirectoryBrowserClient.FetchServersAsync(baseUrl);
Assert.Empty(afterDispose);
}
finally
{
await app.StopAsync();
await app.DisposeAsync();
}
}
[Fact]
public async Task StatelessUdpPing_CoexistsWithActiveRemoteSession_AndHandlesMalformedPingsSafely()
{
using var host = new ServerMatchHost(
IPAddress.Loopback,
0,
seed: 77,
mapKind: ArenaMapKind.Desert,
serverName: "Ping Coexistence Arena",
startInLobby: false);
using var client = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "ProbePilot");
var joinDeadline = DateTime.UtcNow.AddSeconds(3);
while (!client.IsJoined && DateTime.UtcNow < joinDeadline)
{
PumpHostAndClients(host, client);
await Task.Delay(5);
}
Assert.True(client.IsJoined);
// Drive and fire concurrently on the active RUDP session while probing RTDP pings
for (int i = 0; i < 15; i++)
{
client.SubmitLocalInput(new PlayerInput(1f, 0.25f, 30f, 40f, Fire: true, InteractPickup: false, Brake: false), isPhysicsTick: true);
PumpHostAndClients(host, client);
}
var target = new IPEndPoint(IPAddress.Loopback, host.BoundPort);
var pingTask = Task.Run(async () =>
{
var results = new List<ServerPingResult>(4);
for (int i = 0; i < 4; i++)
{
results.Add(await ServerPingProbe.ProbeAsync(target, TimeSpan.FromSeconds(2)));
}
return results;
});
while (!pingTask.IsCompleted)
{
client.SubmitLocalInput(new PlayerInput(0.8f, -0.1f, 25f, 35f, Fire: true, InteractPickup: false, Brake: false), isPhysicsTick: true);
PumpHostAndClients(host, client);
await Task.Delay(3);
}
var pingResults = await pingTask;
Assert.Equal(4, pingResults.Count);
foreach (var r in pingResults)
{
Assert.True(r.Success, "Expected stateless RTDP ping to succeed alongside active RUDP session");
Assert.True(r.Summary.HasValue);
Assert.Equal("Ping Coexistence Arena", r.Summary!.Value.ServerName);
Assert.Equal(1, r.Summary.Value.Humans);
Assert.Equal(12, r.Summary.Value.MaxHumans);
Assert.Equal(MatchPhase.Active, r.Summary.Value.Phase);
Assert.Equal(ArenaMapKind.Desert, r.Summary.Value.MapKind);
Assert.Equal(77, r.Summary.Value.Seed);
Assert.True(r.Summary.Value.AcceptingJoin);
Assert.True(SnapshotCodec.EncodePong(r.Summary.Value).Length < 110);
}
Assert.Equal(0, host.TransportPacketsDropped);
Assert.True(client.ConnectionStatus.Connected);
// Send truncated "RTDP" packet (< 16B) and bogus magic packet; host must not crash or drop RUDP peer
using (var rawSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
byte[] truncatedPing = Encoding.ASCII.GetBytes("RTDP\x01\x01short"); // 11 bytes
rawSock.SendTo(truncatedPing, target);
for (int i = 0; i < 4; i++)
{
PumpHostAndClients(host, client);
await Task.Delay(2);
}
Assert.Equal(0, host.TransportPacketsDropped);
byte[] bogusMagic = Encoding.ASCII.GetBytes("JUNK_NOT_RTDP_OR_CNR0_PAYLOAD_DATA");
rawSock.SendTo(bogusMagic, target);
for (int i = 0; i < 4; i++)
{
PumpHostAndClients(host, client);
await Task.Delay(2);
}
}
Assert.True(client.IsJoined);
Assert.True(client.ConnectionStatus.Connected);
// Valid ping still succeeds after malformed datagrams
var finalPingTask = ServerPingProbe.ProbeAsync(target, TimeSpan.FromSeconds(2));
while (!finalPingTask.IsCompleted)
{
PumpHostAndClients(host, client);
await Task.Delay(2);
}
var finalPing = await finalPingTask;
Assert.True(finalPing.Success);
}
[Fact]
public void Lobby_NonHostConfigAndStartRejected_AndLocalOutcomeIsActive()
{
using var listenHost = new ListenHostArenaSession(
IPAddress.Loopback,
0,
seed: 42,
mapKind: ArenaMapKind.Desert,
startInLobby: true,
serverName: "Host Authority Lobby");
using var client = new RemoteArenaSession(
new IPEndPoint(IPAddress.Loopback, listenHost.Host.BoundPort),
"Guest");
var joinDeadline = DateTime.UtcNow.AddSeconds(3);
while (!client.IsJoined && DateTime.UtcNow < joinDeadline)
{
PumpListenHostAndClient(listenHost, client);
}
Assert.True(client.IsJoined);
Assert.Equal(MatchPhase.Lobby, listenHost.ViewState.Phase);
Assert.Equal(MatchPhase.Lobby, client.ViewState.Phase);
Assert.Equal(ClientMatchOutcome.Active, listenHost.LocalOutcome);
Assert.Equal(ClientMatchOutcome.Active, client.LocalOutcome);
// Guest attempts unauthorized config change and launch
Assert.True(client.RequestLobbyConfig(999, ArenaMapKind.Sion));
Assert.True(client.RequestLobbyStart());
PumpListenHostAndClient(listenHost, client, ticks: 15);
Assert.Equal(MatchPhase.Lobby, listenHost.ViewState.Phase);
Assert.Equal(ArenaMapKind.Desert, listenHost.ViewState.MapKind);
Assert.Equal(42, listenHost.ViewState.Seed);
Assert.Null(listenHost.LobbyState?.CountdownSeconds);
Assert.Equal(MatchPhase.Lobby, client.ViewState.Phase);
Assert.Equal(ClientMatchOutcome.Active, client.LocalOutcome);
}
[Fact]
public void Lobby_CountdownStartsWhenAllReady_CancelsOnUnready_AndResetsOnMapSwitch()
{
using var host = new ServerMatchHost(
IPAddress.Loopback,
0,
seed: 42,
mapKind: ArenaMapKind.Desert,
allowClientReset: true,
startInLobby: true,
minHumansToStart: 2);
using var peerA = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "Alpha");
using var peerB = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "Bravo");
var deadline = DateTime.UtcNow.AddSeconds(3);
while ((!peerA.IsJoined || !peerB.IsJoined) && DateTime.UtcNow < deadline)
{
PumpHostAndClients(host, peerA, peerB);
Thread.Sleep(3);
}
Assert.True(peerA.IsJoined);
Assert.True(peerB.IsJoined);
// Peer A readies up; Peer B not ready -> no countdown yet
Assert.True(peerA.SetLobbyReady(true));
for (int i = 0; i < 10; i++)
{
PumpHostAndClients(host, peerA, peerB);
Thread.Sleep(2);
}
Assert.Null(host.Lobby?.CountdownSeconds);
// Peer B readies up -> countdown starts
Assert.True(peerB.SetLobbyReady(true));
for (int i = 0; i < 15; i++)
{
PumpHostAndClients(host, peerA, peerB);
Thread.Sleep(2);
}
Assert.NotNull(host.Lobby?.CountdownSeconds);
Assert.True(host.Lobby!.CountdownSeconds!.Value > 0f && host.Lobby.CountdownSeconds.Value < 5.0f);
Assert.NotNull(peerA.LobbyState?.CountdownSeconds);
// Peer B un-readies -> countdown cancels and Wave 0 does NOT launch
Assert.True(peerB.SetLobbyReady(false));
for (int i = 0; i < 15; i++)
{
PumpHostAndClients(host, peerA, peerB);
Thread.Sleep(2);
}
Assert.Null(host.Lobby?.CountdownSeconds);
Assert.Null(peerA.LobbyState?.CountdownSeconds);
Assert.Equal(MatchPhase.Lobby, host.Session.State.Phase);
Assert.Empty(host.Session.State.OrbitalDrop.ActivePods);
// Authorized config switch in Lobby resets ready flags and syncs all peers
Assert.True(peerA.SetLobbyReady(true));
for (int i = 0; i < 6; i++)
{
PumpHostAndClients(host, peerA, peerB);
Thread.Sleep(2);
}
Assert.True(host.ConfigureLobby(peerA.LocalContenderId, 99, ArenaMapKind.Sion));
for (int i = 0; i < 15; i++)
{
PumpHostAndClients(host, peerA, peerB);
Thread.Sleep(2);
}
Assert.Equal(MatchPhase.Lobby, host.Session.State.Phase);
Assert.Equal(ArenaMapKind.Sion, host.Session.State.MapKind);
Assert.Equal(99, host.Session.State.Seed);
Assert.Equal(ArenaMapKind.Sion, peerA.ViewState.MapKind);
Assert.Equal(99, peerA.ViewState.Seed);
Assert.Equal(ArenaMapKind.Sion, peerB.ViewState.MapKind);
Assert.Equal(99, peerB.ViewState.Seed);
Assert.All(host.Lobby!.Slots.Where(s => s.IsHuman), s => Assert.False(s.IsReady));
Assert.Equal(ClientMatchOutcome.Active, peerA.LocalOutcome);
Assert.Equal(ClientMatchOutcome.Active, peerB.LocalOutcome);
}
[Fact]
public void Lobby_IdleClientKeptAlivePastIdleTimeout_WithActiveOutcome()
{
using var host = new ServerMatchHost(
IPAddress.Loopback,
0,
seed: 42,
mapKind: ArenaMapKind.Desert,
startInLobby: true);
using var client = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "IdlePilot");
long simNowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
for (int i = 0; i < 100 && !client.IsJoined; i++)
{
simNowMs += 20;
host.StepOnce(simNowMs);
client.PumpNetwork(simNowMs);
Thread.Sleep(2);
}
Assert.True(client.IsJoined);
// Advance 8.5 seconds (> IdleTimeoutMs 5000ms and > ClientDisconnectTimeoutMs 6000ms) with ZERO SubmitLocalInput
for (int step = 0; step < 170; step++)
{
simNowMs += 50;
host.StepOnce(simNowMs);
client.PumpNetwork(simNowMs);
}
Assert.True(client.IsJoined);
Assert.True(client.ConnectionStatus.Connected);
Assert.Equal(ClientMatchOutcome.Active, client.LocalOutcome);
Assert.Equal(MatchPhase.Lobby, client.ViewState.Phase);
Assert.Equal(1, host.ConnectedHumanCount);
}
[Fact]
public void Lobby_SynchronizedLaunch_TransitionsToActiveAndDropsWave0AcrossHostAndRemote()
{
using var listenHost = new ListenHostArenaSession(
IPAddress.Loopback,
0,
seed: 42,
mapKind: ArenaMapKind.Desert,
startInLobby: true,
minHumansToStart: 2);
using var remote = new RemoteArenaSession(
new IPEndPoint(IPAddress.Loopback, listenHost.Host.BoundPort),
"DropMate");
var deadline = DateTime.UtcNow.AddSeconds(3);
while (!remote.IsJoined && DateTime.UtcNow < deadline)
{
PumpListenHostAndClient(listenHost, remote);
}
Assert.True(remote.IsJoined);
Assert.True(listenHost.SetLobbyReady(true));
Assert.True(remote.SetLobbyReady(true));
// Step 320 ticks (~5.33s at 60Hz) so the 5.0s countdown completes cleanly
for (int tick = 0; tick < 330; tick++)
{
listenHost.SubmitLocalInput(default, isPhysicsTick: true);
remote.PumpNetwork();
if (listenHost.ViewState.Phase == MatchPhase.Active &&
remote.ViewState.Phase == MatchPhase.Active &&
remote.ActivePods.Count > 0)
{
break;
}
Thread.Sleep(1);
}
// Pump a few extra frames to ensure all Wave 0 reliable events arrive on remote
PumpListenHostAndClient(listenHost, remote, ticks: 10);
Assert.Equal(MatchPhase.Active, listenHost.ViewState.Phase);
Assert.Equal(MatchPhase.Active, remote.ViewState.Phase);
Assert.Equal(ClientMatchOutcome.Active, listenHost.LocalOutcome);
Assert.Equal(ClientMatchOutcome.Active, remote.LocalOutcome);
Assert.True(listenHost.ActivePods.Count >= MatchState.ContenderCount);
Assert.Equal(ContenderLifecycle.Deploying, listenHost.LocalContender.Lifecycle);
Assert.Equal(ContenderLifecycle.Deploying, remote.LocalContender.Lifecycle);
Assert.Contains(remote.ActivePods, p => p.PodKind == OrbitalPodKind.Contender && p.ContenderId == remote.LocalContenderId);
var remoteEvents = new List<ISimEvent>();
remote.DrainSimEvents(remoteEvents);
Assert.Contains(remoteEvents, e => e is MatchStartedEvent);
}
[Fact]
public void CorePvs_RoundTripsMatchPhaseLobby_Within1152Bytes()
{
var state = new MatchState(seed: 42, ArenaMapKind.Desert, startInLobby: true);
var local = state.Contenders[0];
local.Grid.SwapChassis(Catalog.Bastion);
var contenders = new List<NetContenderState>(12);
var walkers = new List<NetWalkerEntry>(12);
var specs = new List<NetSpectatorState>(10);
for (int i = 0; i < 12; i++)
{
contenders.Add(new NetContenderState
{
SlotId = (byte)i,
Alive = true,
IsHuman = i < 2,
Lifecycle = ContenderLifecycle.Deploying,
Pos = new Vector3(i * 10f, 3f, -i * 5f),
Rot = Quaternion.Identity,
Vel = Vector3.Zero,
CoreHpRatio = 1f
});
var ws = new WalkerVisualSnapshot { LegCount = 4 };
walkers.Add(new NetWalkerEntry { IsContender = true, EntityId = (byte)i, Snapshot = ws });
}
byte[] payload = SnapshotCodec.EncodeCorePvs(
1, 5, 10, 0f, 0, 0, 772f, MatchPhase.Lobby, null, 0, 0xFFF,
local, Vector3.Zero, contenders, walkers, specs);
byte[] wireFrame = SnapshotCodec.WrapLatest(payload, 1, 5);
byte[] rudpDatagram = CultNetRudpPacketCodec.Encode(new CultNetRudpPacket
{
ConnectionId = 0x52544431,
PacketType = CultNetRudpPacketType.Data,
ChannelId = SnapshotCodec.ChannelLatest,
Sequence = 5,
Sequenced = true,
Payload = wireFrame
});
Assert.True(rudpDatagram.Length <= SnapshotCodec.MaxLatestDatagramBytes,
$"Lobby CorePvs UDP datagram {rudpDatagram.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B");
Assert.True(SnapshotCodec.TryDecodeCorePvs(payload, out var decoded));
Assert.Equal(MatchPhase.Lobby, decoded.Phase);
Assert.Null(decoded.WinnerContenderId);
// Also verify Completed + WinnerContenderId still round-trips via bit 2 (0x04)
byte[] completedPayload = SnapshotCodec.EncodeCorePvs(
1, 6, 12, 100f, 0, 0, 120f, MatchPhase.Completed, 3, 0, 0xFFF,
local, Vector3.Zero, contenders, walkers, specs);
Assert.True(SnapshotCodec.TryDecodeCorePvs(completedPayload, out var decodedCompleted));
Assert.Equal(MatchPhase.Completed, decodedCompleted.Phase);
Assert.Equal(3, decodedCompleted.WinnerContenderId);
}
}
}

View file

@ -9,6 +9,7 @@
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
@ -23,6 +24,7 @@
<ProjectReference Include="..\..\src\RustToDust.Core\RustToDust.Core.csproj" />
<ProjectReference Include="..\..\src\RustToDust.Ymir\RustToDust.Ymir.csproj" />
<ProjectReference Include="..\..\src\RustToDust.Net\RustToDust.Net.csproj" />
<ProjectReference Include="..\..\src\RustToDust.Directory\RustToDust.Directory.csproj" />
<ProjectReference Include="$(YmirRoot)/src/Ymir.Box3D/Ymir.Box3D.csproj" AdditionalProperties="YmirNativeConfiguration=$(YmirNativeConfiguration)" />
</ItemGroup>