Merge upstream

This commit is contained in:
linmeideli committed 2026-11-06 09:07:22 +08:00
commit b844d3d9f3
37 files changed
+839 -484

No files matched your search

+31 -10
View File
@@ -52,7 +52,7 @@ All settings live in `config.json` next to the server binary (a full sample is [
| Section | Purpose |
| --- | --- |
| `Server` | Public IP/port, listen address and the dynamic (delta) UDP port range `DeltaPortStart`..`DeltaPortEnd` |
| `Server` | Public IP/port, listen address and the client verification mode (`VerificationMode`, `DeltaPortStart`..`DeltaPortEnd`) |
| `HttpServer` | Web API, admin panel and matchmaking token endpoint (`Enabled`, `ListenIp`, `ListenPort`) |
| `AntiCheat` | Server-side anticheat, including the [IP request rate limit](#ip-request-rate-limit) |
| `Timeout` | Spawn and connection timeouts |
@@ -62,6 +62,31 @@ All settings live in `config.json` next to the server binary (a full sample is [
| `Admin` | Admin panel password and marketplace URL |
| `HPLP` | HPLP public region listing |
### Verification mode
Empostor has to know which HTTP authentication (`POST /api/user`) belongs to which raw UDP connection, because the game's UDP handshake carries no token, PUID or game code. `Server.VerificationMode` selects how:
| Mode | Behaviour |
| --- | --- |
| `DeltaPort` (default) | Every player gets a unique dynamic UDP port from the `DeltaPortStart`..`DeltaPortEnd` pool. The port itself is the proof of identity. |
| `GameCode` | **No dynamic ports at all** — only the shared listen port (`GameCodePorts[0]`, or `ListenPort`) is used. The lobby list hands out a server-issued **challenge game code** per player, and the `JoinGame` that follows over UDP is authenticated by that code alone. |
| Key | Default | Description |
| --- | --- | --- |
| `VerificationMode` | `DeltaPort` | `DeltaPort` or `GameCode` |
| `GameCodePorts` | `[]` | Ports for `GameCode` mode; only the first is bound. Empty falls back to `ListenPort`/`PublicPort` |
| `TemporaryGameCodeLifetimeSeconds` | `180` | How long an issued challenge code stays valid |
In `GameCode` mode the port pool is disabled (no delta listeners, no per-player firewall rules) and `DeltaPortStart`/`DeltaPortEnd` are ignored.
The game client validates the game code of every message it receives against the code it joined with and silently drops mismatches, and the UDP handshake carries no token/PUID/game code. `GameCode` mode therefore uses the code itself as the token:
1. A lobby listing returns a **challenge code** — a second, server-generated game code (same format, so the client accepts it as a normal join target) bound to `(authenticated user, real game, player name, client version)`.
2. `JoinGame(challenge)` over UDP is resolved by the challenge code alone — no IP, no PUID, no name matching. The challenge is single-use and expires after `TemporaryGameCodeLifetimeSeconds`, so many players can join the same game at the same time without being mixed up.
3. The server then re-keys the client with `Msg00 HostGame` carrying the **real** code (`AmongUsClient.OnGameCreated` is empty, so this only overwrites `GameId`). Everything after that — game data, the in-lobby code display, invites — uses the real code, so no message rewriting is needed.
`HostGame` is the one exception: no code exists before the host message, so the hosting socket is matched against the `PUT /api/games` request by IP, player name and client version (the PUID comes from the HTTP token). Joining an already hosted game with the real code (legacy `POST /api/games`, e.g. Steam invites) still falls back to the same name/version/IP matching.
### AntiCheat
| Key | Default | Description |
@@ -73,21 +98,17 @@ All settings live in `config.json` next to the server binary (a full sample is [
| `EnableColorLimitChecks`, `EnableNameLimitChecks`, `EnableItemLimitChecks` | `true` | Lobby limits (colors, names, items) |
| `ForbidProtocolExtensions` | `true` | Reject unknown/extension protocol messages |
| `EnablePacketSizeChecks`, `PacketSizeLimit` | `true`, `1203` | Maximum inbound packet size |
| `EnableIpRateLimit` | `true` | IP request rate limit (below) |
| `IpRateLimitRequests` | `30` | Max TCP (HTTP) requests per IP per window, `0` disables the limit |
| `IpRateLimitWindowMinutes` | `5` | Length of the rate limit window in minutes |
| `EnableRateLimits` | `true` | IP request rate limit and game-side rate limits (below) |
#### Ip request rate limit
Within one window (5 minutes by default) the same IP may only make `IpRateLimitRequests` (default `30`) TCP (HTTP) requests — this protects the HTTP API against connection/request flooding. When the limit is exceeded:
Within one window (1 minute) the same IP may only make `30` TCP (HTTP) requests — this protects the HTTP API against connection/request flooding. The limit lives in `IpRateLimitService` and is switched by `EnableRateLimits`. When the limit is exceeded:
- Every normal endpoint answers with `429 Too Many Requests` and a localized hint, chosen from the request's `Accept-Language` header, e.g. `请求过于频繁请 5 分钟后重试`. The `Retry-After` header says how many seconds are left.
- `POST /api/user` **and** `PUT`/`GET /api/games` (the whole join flow of the game client: matchmaking token + FindHost) are **never rejected over HTTP** — failing them there would only leave the client on a black screen, which just logs `CoSendRequest failed` and hangs. Both still count against the quota, and while an IP is over quota the server also skips the outbound friend code API calls (a cached/fallback code is used instead) so the endpoint cannot be abused for amplification. To keep a flooding IP from draining the dynamic port range, such joins are **not given a pool port**: they all receive the same shared *reject port*, a single pre-bound UDP socket whose only job is to answer the handshake with the localized hint in the client's own language (`请求过于频繁请 5 分钟后重试`) and close it again — the player is told why they cannot join instead of seeing a black screen, and only one socket is used no matter how many requests arrive. `GamesController` echoes the token's port back, so the client is naturally sent to that reject port. In fixed-port mode (`DeltaPortStart=0`) the main port is used instead.
- **Every** endpoint answers with `429 Too Many Requests` plus the standard matchmaker error body `{"Errors":[{"Reason":116}]}` — `116` is `DisconnectReason.TooManyRequests`, which the client renders as its own localized "too many requests" popup without retrying. The `Retry-After` header says how many seconds are left.
- This includes the whole join flow of the game client (`POST /api/user` matchmaking token and `PUT`/`GET /api/games` FindHost): the client never receives a token or a port, so it never enters the UDP phase and no dynamic pool port is spent on a blocked request — the player gets the popup and returns to the main menu instead of a black screen.
- `/admin` and `/api/admin` are neither counted nor limited, so the dashboard can never lock the operator out.
The message lives under the key `ratelimit.too_frequent` in `Languages/*.json` (and in the built-in defaults in `LanguageService.cs`), so you can reword or translate it there. Set `IpRateLimitRequests` to `0` to turn the whole feature off.
Empostor usually runs behind a CDN or reverse proxy, so the real client IP is taken from the `X-Real-IP` header, then from the first entry of `X-Forwarded-For`, and only afterwards from the socket address. Make sure your CDN/proxy forwards one of these headers — otherwise every player would share the proxy IP's quota. Note that the game client polls some endpoints (e.g. `/api/games`) while you play: if `30` per 5 minutes is too tight for your players, raise `IpRateLimitRequests` (for example to `120`).
Empostor usually runs behind a CDN or reverse proxy, so the real client IP is taken from the `X-Real-IP` header, then from the first entry of `X-Forwarded-For`, and only afterwards from the socket address. Make sure your CDN/proxy forwards one of these headers — otherwise every player would share the proxy IP's quota. Note that the game client polls some endpoints (e.g. `/api/games`) while you play: if `30` per minute is too tight for your players, set `EnableRateLimits` to `false` (that also switches off the game-side RPC/task rate limits).
## Contributing
Please read the [contributing guidelines](https://github.com/Empostor/Empostor/blob/main/CONTRIBUTING.md).
Binary file not shown.
+30
View File
@@ -1,7 +1,19 @@
using System;
using System.Collections.Generic;
using Empostor.Api.Utils;
namespace Empostor.Api.Config
{
// How the HTTP authentication (POST /api/user) session is tied to the UDP connection.
public enum ServerVerificationMode
{
// Allocates a unique dynamic UDP port per player and uses it as a nonce.
DeltaPort = 0,
// Matches connections by a disposable fake GameCode issued per join, without dynamic ports.
GameCode = 1,
}
public class ServerConfig
{
public const string Section = "Server";
@@ -21,12 +33,30 @@ namespace Empostor.Api.Config
public bool UseFirewalld { get; set; } = false;
// DeltaPort (default) or GameCode.
public ServerVerificationMode VerificationMode { get; set; } = ServerVerificationMode.DeltaPort;
// Ports used in GameCode mode. Empty falls back to ListenPort; only the first one is bound.
public List<int> GameCodePorts { get; set; } = new();
// Seconds to keep join/host requests pending; UDP connections arriving in this window are matched against them.
public int TemporaryGameCodeLifetimeSeconds { get; set; } = 180;
public ushort DeltaPortStart { get; set; } = 0;
public ushort DeltaPortEnd { get; set; } = 0;
public ushort DeltaPortLowWaterMark { get; set; } = 5;
public bool UseGameCodeMode => VerificationMode == ServerVerificationMode.GameCode;
public ushort GameCodeListenPort => GameCodePorts.Count > 0 ? (ushort)GameCodePorts[0] : ListenPort;
public ushort GameCodePublicPort => GameCodePorts.Count > 0 ? (ushort)GameCodePorts[0] : PublicPort;
public TimeSpan TemporaryGameCodeLifetime =>
TimeSpan.FromSeconds(Math.Max(1, TemporaryGameCodeLifetimeSeconds));
public string ResolvePublicIp()
{
return _resolvedPublicIp ??= IpUtils.ResolveIp(PublicIp);
+85 -19
View File
@@ -12,6 +12,9 @@ using Empostor.Api.Games.Managers;
using Empostor.Api.Innersloth;
using Empostor.Api.Innersloth.GameFilters;
using Empostor.Server.Extensions;
using Empostor.Server.Net;
using Empostor.Server.Service.Auth;
using Empostor.Server.Service.Ip;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -25,17 +28,23 @@ public sealed class GamesController : ControllerBase
private readonly IGameManager _gameManager;
private readonly ListingManager _listingManager;
private readonly ServerConfig _serverConfig;
private readonly AuthCacheService _authCache;
private readonly GameCodeAuthManager _gameCodeAuth;
private readonly ILogger<GamesController> _logger;
public GamesController(
IGameManager gameManager,
ListingManager listingManager,
IOptions<ServerConfig> serverConfig,
AuthCacheService authCache,
GameCodeAuthManager gameCodeAuth,
ILogger<GamesController> logger)
{
_gameManager = gameManager;
_listingManager = listingManager;
_serverConfig = serverConfig.Value;
_authCache = authCache;
_gameCodeAuth = gameCodeAuth;
_logger = logger;
}
@@ -68,8 +77,8 @@ public sealed class GamesController : ControllerBase
}
var listings = _listingManager.FindListings(HttpContext, mapId, numImpostors, lang, clientVersion);
var port = GetDeltaPort();
return Ok(listings.Select(g => GameListing.From(g, port)));
var auth = TryGetAuthInfo();
return Ok(listings.Select(g => BuildListing(g, auth)));
}
/// <summary>
@@ -78,14 +87,21 @@ public sealed class GamesController : ControllerBase
[HttpPost]
public IActionResult Post(int gameId)
{
var code = new GameCode(gameId);
var requested = new GameCode(gameId);
var code = _gameCodeAuth.TryGetTarget(requested, out var targetCode) ? targetCode : requested;
var game = _gameManager.Find(code);
if (game == null)
{
return NotFound(new MatchmakerResponse(new MatchmakerError(DisconnectReason.GameNotFound)));
}
var port = GetDeltaPort();
if (_serverConfig.UseGameCodeMode && TryGetAuthInfo() is { } auth)
{
// The legacy path cannot return a code, so stash this as a pending join addressed to the real code.
_gameCodeAuth.RegisterPendingJoin(code, auth);
}
var port = GetPort();
return Ok(HostServer.From(IPAddress.Parse(_serverConfig.ResolvePublicIp()), port));
}
@@ -95,22 +111,30 @@ public sealed class GamesController : ControllerBase
[HttpPut]
public IActionResult Put()
{
var port = GetDeltaPort();
if (_serverConfig.UseGameCodeMode && TryGetAuthInfo() is { } auth)
{
// Hosting starts here. The game is created by the next UDP HostGame, so keep the auth info and IP pending.
var ip = RealIpResolver.Resolve(HttpContext)?.ToString();
_gameCodeAuth.RegisterHost(auth, ip);
}
var port = GetPort();
return Ok(HostServer.From(IPAddress.Parse(_serverConfig.ResolvePublicIp()), port));
}
[HttpGet("{gameId}")]
public IActionResult Show([FromRoute] int gameId)
{
var code = new GameCode(gameId);
// The submitted code may be a real code (invite or manual input) or a challenge code.
var requested = new GameCode(gameId);
var code = _gameCodeAuth.TryGetTarget(requested, out var targetCode) ? targetCode : requested;
var game = _gameManager.Find(code);
if (game == null)
{
return NotFound(new FindGameByCodeResponse(new MatchmakerError(DisconnectReason.GameNotFound)));
}
var port = GetDeltaPort();
return Ok(new FindGameByCodeResponse(GameListing.From(game, port)));
return Ok(new FindGameByCodeResponse(BuildListing(game, TryGetAuthInfo())));
}
/// <summary>
@@ -140,8 +164,8 @@ public sealed class GamesController : ControllerBase
}
var filteredGames = _listingManager.FindListingsV2(HttpContext, filtersList);
var port = GetDeltaPort();
var gameListings = filteredGames.Select(g => GameListing.From(g, port)).ToList();
var auth = TryGetAuthInfo();
var gameListings = filteredGames.Select(g => BuildListing(g, auth)).ToList();
var response = new
{
@@ -209,14 +233,16 @@ public sealed class GamesController : ControllerBase
}
/// <summary>
/// Resolves the UDP port the requesting client should connect to.
/// In dynamic delta mode every client is handed a unique UDP port in its
/// auth response (POST /api/user) and echoes that token back as the
/// Authorization bearer header on subsequent requests, so the port is
/// read from the token. Falls back to the configured public port.
/// The UDP port the client should connect to.
/// In GameCode mode returns the shared port, in DeltaPort mode the dedicated port from the token.
/// </summary>
private ushort GetDeltaPort()
private ushort GetPort()
{
if (_serverConfig.UseGameCodeMode)
{
return _serverConfig.GameCodePublicPort;
}
var auth = HttpContext.Request.Headers.Authorization.ToString();
if (!string.IsNullOrEmpty(auth) && auth.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
{
@@ -232,13 +258,53 @@ public sealed class GamesController : ControllerBase
}
catch
{
// Malformed or non-base64 token — fall through to the public port.
// Fall back to the public port if the value is not base64 or is corrupted
}
}
return _serverConfig.PublicPort;
}
// Looks up auth info from the bearer token.
private UserAuthInfo? TryGetAuthInfo()
{
var header = HttpContext.Request.Headers.Authorization.ToString();
if (string.IsNullOrEmpty(header) || !header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
{
return null;
}
try
{
using var doc = JsonDocument.Parse(Convert.FromBase64String(header["Bearer ".Length..]));
if (doc.RootElement.TryGetProperty("Hash", out var hashElement)
&& hashElement.GetString() is { Length: > 0 } hash)
{
return _authCache.FindByToken(hash);
}
}
catch
{
// Treat a corrupted token as unauthenticated
}
return null;
}
// Builds a single listing entry. In GameCode mode the challenge code bound to the auth info is returned as the GameId.
private GameListing BuildListing(IGame game, UserAuthInfo? auth)
{
var port = GetPort();
var listingCode = game.Code;
if (_serverConfig.UseGameCodeMode && auth != null && !game.Code.IsInvalid)
{
listingCode = _gameCodeAuth.CreateChallenge(game.Code, auth);
}
return GameListing.From(game, port, listingCode);
}
private static uint ConvertAddressToNumber(IPAddress address)
{
#pragma warning disable CS0618
@@ -330,14 +396,14 @@ public sealed class GamesController : ControllerBase
[JsonPropertyName("Options")] public required string Options { get; init; }
public static GameListing From(IGame game, ushort port)
public static GameListing From(IGame game, ushort port, GameCode listingCode)
{
var platform = game.Host?.Client.PlatformSpecificData;
return new GameListing
{
Ip = ConvertAddressToNumber(game.PublicIp.Address),
Port = port,
GameId = game.Code,
GameId = listingCode,
PlayerCount = game.PlayerCount,
HostName = game.DisplayName ?? game.Host?.Client.Name ?? "Unknown host",
TrueHostName = game.DisplayName ?? game.Host?.Client.Name ?? "Unknown host",
+35 -63
View File
@@ -37,24 +37,24 @@ public sealed class TokenController : ControllerBase
private readonly AuthApiConfig _authApiConfig;
private readonly PortPoolService _portPool;
private readonly IDeltaListenerManager _deltaListenerManager;
private readonly IpRateLimitService _rateLimit;
private readonly ServerConfig _serverConfig;
public TokenController(
ILogger<TokenController> logger,
IHttpClientFactory httpClientFactory,
AuthCacheService authCache,
IOptions<AuthApiConfig> authApiConfig,
IOptions<ServerConfig> serverConfig,
PortPoolService portPool,
IDeltaListenerManager deltaListenerManager,
IpRateLimitService rateLimit)
IDeltaListenerManager deltaListenerManager)
{
_logger = logger;
_httpClientFactory = httpClientFactory;
_authCache = authCache;
_authApiConfig = authApiConfig.Value;
_serverConfig = serverConfig.Value;
_portPool = portPool;
_deltaListenerManager = deltaListenerManager;
_rateLimit = rateLimit;
}
[HttpPost]
@@ -81,44 +81,14 @@ public sealed class TokenController : ControllerBase
_logger.LogInformation("TokenController request for eosToken={eosToken}", eosToken);
var clientIp = GetClientIp();
var friendCode = await GetFriendCodeAsync(eosToken, productUserId, clientIp);
var friendCode = await GetFriendCodeAsync(eosToken, productUserId);
var matchmakerToken = GenerateMatchmakerToken(productUserId);
if (_rateLimit.IsLimited(clientIp, out var joinRetryAfter))
{
var rejectPort = await _deltaListenerManager.GetRateLimitRejectPortAsync();
if (rejectPort > 0 || !_portPool.IsEnabled)
{
_logger.LogWarning(
"TokenUser {Puid} {Ip} over the request rate limit, sent to reject port {Port} (retry in {Seconds}s).",
productUserId, clientIp, rejectPort,
(int)Math.Ceiling(joinRetryAfter.TotalSeconds));
_authCache.Store(productUserId, matchmakerToken, friendCode, clientIp, eosToken, request.Username, request.ClientVersion);
return Ok(Convert.ToBase64String(JsonSerializer.SerializeToUtf8Bytes(new TokenResponse
{
Content = new TokenContent
{
ProductUserId = productUserId,
FriendCode = friendCode,
},
Hash = matchmakerToken,
Port = rejectPort,
})));
}
// No reject port available (pool exhausted): fall through to
// the normal path, which has its own full/exhausted handling.
_logger.LogWarning(
"TokenUser {Puid} {Ip} over the request rate limit but no reject port available, falling back to a normal port.",
productUserId, clientIp);
}
_authCache.Store(productUserId, matchmakerToken, friendCode, clientIp, eosToken);
// Allocate a delta UDP port to match the TCP auth session to the
// subsequent UDP connection. In fixed-port mode (pool disabled) no
// port is allocated and no PUID/FriendCode matching is performed.
var deltaPort = _portPool.AllocatePort(productUserId);
// In DeltaPort mode, allocate a dedicated port tying the auth session to the UDP connection.
// In GameCode mode nothing is allocated (the UDP side matches via a temporary GameCode).
var deltaPort = _serverConfig.UseGameCodeMode ? 0 : _portPool.AllocatePort(productUserId);
var authInfo = new UserAuthInfo
{
@@ -130,22 +100,25 @@ public sealed class TokenController : ControllerBase
CreatedAt = DateTime.UtcNow,
};
// Extract name from friend code (e.g., "ufolud" from "ufolud#1234")
var playerName = friendCode?.Split('#')[0] ?? productUserId[..Math.Min(8, productUserId.Length)];
authInfo.Name = playerName;
// Display name and version as declared by the client; cross-checked on the UDP side.
authInfo.Name = request.Username ?? string.Empty;
authInfo.ClientVersion = request.ClientVersion;
// Display name for logging (inferred from the friend code when the client declares none).
var playerName = !string.IsNullOrWhiteSpace(authInfo.Name)
? authInfo.Name
: friendCode?.Split('#')[0] ?? productUserId[..Math.Min(8, productUserId.Length)];
if (deltaPort > 0)
{
// Unique per-player port (nonce): the subsequent UDP connection
// is matched by this port.
// Use the dedicated port as a nonce to match the subsequent UDP connection.
_authCache.StoreByPort(deltaPort, authInfo);
_logger.LogInformation(
"TokenUser {Name} {Puid} {FriendCode} {Ip} {Port} added.",
playerName, productUserId, friendCode, clientIp, deltaPort);
// Await the listener bind so the socket is really listening
// before the port is handed back to the client.
// Make sure the listener is actually started before the port is handed back to the client.
var listenerStarted = await _deltaListenerManager.StartDeltaListenerAsync(deltaPort);
if (!listenerStarted)
{
@@ -157,10 +130,16 @@ public sealed class TokenController : ControllerBase
return StatusCode(503, new { error = "Server is full, please try again later." });
}
}
else if (_serverConfig.UseGameCodeMode)
{
// GameCode mode: no port allocation; matching happens via a temporary GameCode.
_logger.LogInformation(
"TokenUser {Name} {Puid} {FriendCode} {Ip} added (gamecode mode, single port).",
playerName, productUserId, friendCode, clientIp);
}
else if (_portPool.IsEnabled)
{
// Dynamic delta mode but the pool is at/below the low-water
// mark: reject the player instead of falling back to IP matching.
// DeltaPort mode but the pool is below its low-water mark: reject instead of falling back to IP matching.
_logger.LogWarning(
"TokenUser {Name} {Puid} rejected: dynamic port pool exhausted.",
playerName, productUserId);
@@ -169,9 +148,7 @@ public sealed class TokenController : ControllerBase
}
else
{
// Fixed-port mode (DeltaPortStart=0, DeltaPortEnd=0): no dynamic
// ports, and PUID/FriendCode matching is intentionally skipped.
// The client connects over the fixed UDP port.
// Fixed-port mode: neither dynamic ports nor PUID / FriendCode matching are used.
_logger.LogInformation(
"TokenUser {Name} {Puid} {FriendCode} {Ip} added (fixed port, no matching).",
playerName, productUserId, friendCode, clientIp);
@@ -218,7 +195,7 @@ public sealed class TokenController : ControllerBase
private static string NormalizeIpString(IPAddress? ip)
=> ip?.IsIPv4MappedToIPv6 == true ? ip.MapToIPv4().ToString() : ip?.ToString() ?? "unknown";
private async Task<string> GetFriendCodeAsync(string eosToken, string productUserId, IPAddress? clientIp)
private async Task<string> GetFriendCodeAsync(string eosToken, string productUserId)
{
var cached = TryGetFriendCodeFromCache(productUserId);
if (cached != null)
@@ -229,17 +206,6 @@ public sealed class TokenController : ControllerBase
return cached;
}
// The join request is never rejected because of the Ip rate limit (the
// player is told in-game instead), so skip the outbound auth calls
// here — otherwise an IP could keep amplifying traffic to us.
if (_rateLimit.IsLimited(clientIp, out _))
{
_logger.LogWarning(
"TokenControllerFriendCode skipped for PUID={Puid}: {Ip} is over the request rate limit, using fallback",
productUserId, clientIp);
return GenerateFallbackFriendCode(productUserId);
}
var mode = _authApiConfig.Mode;
_logger.LogDebug("TokenControllerAuthApi mode: {Mode}", mode);
@@ -484,6 +450,12 @@ public sealed class TokenController : ControllerBase
{
[JsonPropertyName("Puid")]
public required string Puid { get; init; }
[JsonPropertyName("Username")]
public string? Username { get; init; }
[JsonPropertyName("ClientVersion")]
public int ClientVersion { get; init; }
}
public sealed class TokenResponse
+1 -2
View File
@@ -39,6 +39,5 @@
"ban.notice.reason": "Grund: {0}",
"ban.notice.unban": "Entbannungszeit: {0}",
"ban.notice.unban_permanent": "Entbannungszeit: Dauerhaft",
"ban.notice.contact": "Bei Fragen wende dich an den Administrator.",
"ratelimit.too_frequent": "Zu viele Anfragen, bitte versuche es in {0} Minute(n) erneut."
"ban.notice.contact": "Bei Fragen wende dich an den Administrator."
}
+1 -2
View File
@@ -70,6 +70,5 @@
"ban.notice.reason": "Reason: {0}",
"ban.notice.unban": "Unban time: {0}",
"ban.notice.unban_permanent": "Unban time: Permanent",
"ban.notice.contact": "If you have any questions, please contact the administrator.",
"ratelimit.too_frequent": "Too many requests, please try again in {0} minute(s)."
"ban.notice.contact": "If you have any questions, please contact the administrator."
}
+1 -2
View File
@@ -37,6 +37,5 @@
"ban.notice.reason": "Motivo: {0}",
"ban.notice.unban": "Fin del baneo: {0}",
"ban.notice.unban_permanent": "Fin del baneo: Permanente",
"ban.notice.contact": "Si tienes dudas, contacta con un administrador.",
"ratelimit.too_frequent": "Demasiadas solicitudes, inténtalo de nuevo en {0} minuto(s)."
"ban.notice.contact": "Si tienes dudas, contacta con un administrador."
}
+1 -2
View File
@@ -37,6 +37,5 @@
"ban.notice.reason": "Dahilan: {0}",
"ban.notice.unban": "Oras ng pag-unban: {0}",
"ban.notice.unban_permanent": "Oras ng pag-unban: Permanente",
"ban.notice.contact": "Kung may tanong, makipag-ugnayan sa administrator.",
"ratelimit.too_frequent": "Masyaraming request, subukan muli sa {0} minuto."
"ban.notice.contact": "Kung may tanong, makipag-ugnayan sa administrator."
}
+1 -2
View File
@@ -39,6 +39,5 @@
"ban.notice.reason": "Raison : {0}",
"ban.notice.unban": "Débannissement : {0}",
"ban.notice.unban_permanent": "Débannissement : Permanent",
"ban.notice.contact": "En cas de question, contactez un administrateur.",
"ratelimit.too_frequent": "Trop de requêtes, veuillez réessayer dans {0} minute(s)."
"ban.notice.contact": "En cas de question, contactez un administrateur."
}
+1 -2
View File
@@ -37,6 +37,5 @@
"ban.notice.reason": "Cúis: {0}",
"ban.notice.unban": "Am dí-chosc: {0}",
"ban.notice.unban_permanent": "Am dí-chosc: Buan",
"ban.notice.contact": "Má tá ceist agat, déan teagmháil le riarthóir.",
"ratelimit.too_frequent": "Iarraidh ró-mhóra, bain triail eile as i {0} nóiméad."
"ban.notice.contact": "Má tá ceist agat, déan teagmháil le riarthóir."
}
+1 -2
View File
@@ -37,6 +37,5 @@
"ban.notice.reason": "Motivo: {0}",
"ban.notice.unban": "Sbanno: {0}",
"ban.notice.unban_permanent": "Sbanno: Permanente",
"ban.notice.contact": "Per qualsiasi domanda, contatta l'amministratore.",
"ratelimit.too_frequent": "Troppe richieste, riprova tra {0} minuto/i."
"ban.notice.contact": "Per qualsiasi domanda, contatta l'amministratore."
}
+1 -2
View File
@@ -39,6 +39,5 @@
"ban.notice.reason": "理由:{0}",
"ban.notice.unban": "BAN解除日時:{0}",
"ban.notice.unban_permanent": "BAN解除日時:永久",
"ban.notice.contact": "ご不明な点があれば管理者にお問い合わせください。",
"ratelimit.too_frequent": "リクエストが多すぎます。{0}分後に再試行してください。"
"ban.notice.contact": "ご不明な点があれば管理者にお問い合わせください。"
}
+1 -2
View File
@@ -39,6 +39,5 @@
"ban.notice.reason": "사유: {0}",
"ban.notice.unban": "차단 해제 시간: {0}",
"ban.notice.unban_permanent": "차단 해제 시간: 영구",
"ban.notice.contact": "문의 사항이 있으면 관리자에게 연락해 주세요.",
"ratelimit.too_frequent": "요청이 너무 많습니다. {0}분 후에 다시 시도해 주세요."
"ban.notice.contact": "문의 사항이 있으면 관리자에게 연락해 주세요."
}
+1 -2
View File
@@ -37,6 +37,5 @@
"ban.notice.reason": "Reden: {0}",
"ban.notice.unban": "Ontbantijd: {0}",
"ban.notice.unban_permanent": "Ontbantijd: Permanent",
"ban.notice.contact": "Neem bij vragen contact op met de beheerder.",
"ratelimit.too_frequent": "Te veel verzoeken, probeer het over {0} minuut/minuten opnieuw."
"ban.notice.contact": "Neem bij vragen contact op met de beheerder."
}
+1 -2
View File
@@ -39,6 +39,5 @@
"ban.notice.reason": "Motivo: {0}",
"ban.notice.unban": "Desbanimento: {0}",
"ban.notice.unban_permanent": "Desbanimento: Permanente",
"ban.notice.contact": "Em caso de dúvidas, contacte o administrador.",
"ratelimit.too_frequent": "Muitos pedidos, tente novamente em {0} minuto(s)."
"ban.notice.contact": "Em caso de dúvidas, contacte o administrador."
}
+1 -2
View File
@@ -37,6 +37,5 @@
"ban.notice.reason": "Motivo: {0}",
"ban.notice.unban": "Desbanimento: {0}",
"ban.notice.unban_permanent": "Desbanimento: Permanente",
"ban.notice.contact": "Em caso de dúvidas, contate o administrador.",
"ratelimit.too_frequent": "Muitas solicitações, tente novamente em {0} minuto(s)."
"ban.notice.contact": "Em caso de dúvidas, contate o administrador."
}
+1 -2
View File
@@ -39,6 +39,5 @@
"ban.notice.reason": "Причина: {0}",
"ban.notice.unban": "Время разбана: {0}",
"ban.notice.unban_permanent": "Время разбана: навсегда",
"ban.notice.contact": "Если у вас есть вопросы, обратитесь к администратору.",
"ratelimit.too_frequent": "Слишком много запросов, повторите попытку через {0} мин."
"ban.notice.contact": "Если у вас есть вопросы, обратитесь к администратору."
}
+1 -2
View File
@@ -70,6 +70,5 @@
"ban.notice.reason": "理由:{0}",
"ban.notice.unban": "解封时间:{0}",
"ban.notice.unban_permanent": "解封时间:永久",
"ban.notice.contact": "如有问题请联系管理员",
"ratelimit.too_frequent": "请求过于频繁请 {0} 分钟后重试"
"ban.notice.contact": "如有问题请联系管理员"
}
+1 -2
View File
@@ -53,6 +53,5 @@
"ban.notice.reason": "理由:{0}",
"ban.notice.unban": "解封時間:{0}",
"ban.notice.unban_permanent": "解封時間:永久",
"ban.notice.contact": "如有問題請聯絡管理員",
"ratelimit.too_frequent": "請求過於頻繁請 {0} 分鐘後重試"
"ban.notice.contact": "如有問題請聯絡管理員"
}
@@ -1,5 +1,4 @@
{
"ratelimit.too_frequent":"Too many requests, please try again in {0} minute(s).",
"command.error":"An error occurred while executing #{0}.",
"command.usage":"Usage: #{0}",
"command.help.list":"=== Commands ===",
@@ -1,5 +1,4 @@
{
"ratelimit.too_frequent":"请求过于频繁请 {0} 分钟后重试",
"command.error":"执行 #{0} 时发生错误。",
"command.usage":"用法:#{0}",
"command.help.list":"=== 指令列表 ===",
+127 -3
View File
@@ -13,6 +13,7 @@ using Empostor.Api.Net.Messages.C2S;
using Empostor.Api.Net.Messages.S2C;
using Empostor.Server.Events.Player;
using Empostor.Server.Net.Manager;
using Empostor.Server.Service.Auth;
using Empostor.Server.Service.Shared;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -29,8 +30,10 @@ namespace Empostor.Server.Net
private readonly ICustomMessageManager<ICustomRootMessage> _customMessageManager;
private readonly IEventManager _eventManager;
private readonly ReportStore _reportStore;
private readonly GameCodeAuthManager _gameCodeAuth;
private readonly ServerConfig _serverConfig;
public Client(ILogger<Client> logger, IOptions<AntiCheatConfig> antiCheatOptions, ClientManager clientManager, GameManager gameManager, ICustomMessageManager<ICustomRootMessage> customMessageManager, IEventManager eventManager, ReportStore reportStore, string name, GameVersion gameVersion, Language language, QuickChatModes chatMode, PlatformSpecificData platformSpecificData, IHazelConnection connection)
public Client(ILogger<Client> logger, IOptions<AntiCheatConfig> antiCheatOptions, ClientManager clientManager, GameManager gameManager, ICustomMessageManager<ICustomRootMessage> customMessageManager, IEventManager eventManager, ReportStore reportStore, GameCodeAuthManager gameCodeAuth, IOptions<ServerConfig> serverConfig, string name, GameVersion gameVersion, Language language, QuickChatModes chatMode, PlatformSpecificData platformSpecificData, IHazelConnection connection)
: base(name, gameVersion, language, chatMode, platformSpecificData, connection)
{
_logger = logger;
@@ -40,6 +43,8 @@ namespace Empostor.Server.Net
_customMessageManager = customMessageManager;
_eventManager = eventManager;
_reportStore = reportStore;
_gameCodeAuth = gameCodeAuth;
_serverConfig = serverConfig.Value;
}
public override async ValueTask<bool> ReportCheatAsync(CheatContext context, CheatCategory category, string message)
@@ -134,6 +139,17 @@ namespace Empostor.Server.Net
case MessageFlags.HostGame:
case MessageFlags.HostModdedGame:
{
// In GameCode mode the auth info must be bound before the game is created.
if (_serverConfig.UseGameCodeMode && string.IsNullOrEmpty(ProductUserId)
&& !TryBindHostAuth())
{
_logger.LogWarning(
"Client [{Id}] {Name} sent HostGame without a matching auth session (gamecode mode)",
Id, Name);
await DisconnectAsync(DisconnectReason.Custom, "Authentication required. Please reopen the game through the server.");
return;
}
IGameOptions gameOptions;
GameFilterOptions gameFilterOptions;
Guid? modGuid = null;
@@ -176,8 +192,21 @@ namespace Empostor.Server.Net
case MessageFlags.JoinGame:
{
Message01JoinGameC2S.Deserialize(reader, out var gameCode);
var joinCode = gameCode;
var game = _gameManager.Find(gameCode);
if (_serverConfig.UseGameCodeMode)
{
// Resolve auth info from the challenge code handed out by the listing.
var (bound, realCode) = await TryBindJoinAuthAsync(gameCode);
if (!bound)
{
return;
}
joinCode = realCode;
}
var game = _gameManager.Find(joinCode);
if (game == null)
{
await DisconnectAsync(DisconnectReason.GameNotFound);
@@ -488,6 +517,99 @@ namespace Empostor.Server.Net
await _gameManager.OnClientDisconnectAsync(this);
}
// Resolves auth info from the JoinGame code; in GameCode mode the challenge code is the key.
// After resolving, the real code is announced with Msg00. The IP/name/version pending match is kept for the legacy path.
private async ValueTask<(bool Bound, GameCode RealCode)> TryBindJoinAuthAsync(GameCode code)
{
if (_gameCodeAuth.TryResolveChallenge(code, Id, out var user, out var target, out var challengeReason)
&& user != null)
{
BindAuth(user);
_logger.LogInformation(
"Client [{Id}] {Name} joined by challenge code {Challenge} → game {Game} │ FC {FriendCode} │ {Puid}",
Id, Name, code.Code, target.Code, FriendCode ?? "unknown", HashPuid(user.ProductUserId));
using (var writer = MessageWriter.Get(MessageType.Reliable))
{
Message00HostGameS2C.Serialize(writer, target);
await Connection.SendAsync(writer);
}
return (true, target);
}
if (!string.IsNullOrEmpty(ProductUserId))
{
// An already authenticated connection joining with the real code is let through as-is.
return (true, code);
}
if (_gameCodeAuth.TryConsumePendingJoin(
code,
NormalizeIp(Connection.EndPoint?.Address),
Name,
GameVersion.Value,
out var fallbackUser,
out var matchInfo)
&& fallbackUser != null)
{
BindAuth(fallbackUser);
_logger.LogInformation(
"Client [{Id}] {Name} joined by real code {Code} │ FC {FriendCode} │ {Puid} │ matched {Match}",
Id, Name, code.Code, FriendCode ?? "unknown", HashPuid(fallbackUser.ProductUserId), matchInfo);
return (true, code);
}
_logger.LogWarning(
"Client [{Id}] {Name} could not bind JoinGame {Code} (gamecode mode): {Reason}",
Id, Name, code.Code, challengeReason);
await DisconnectAsync(DisconnectReason.Custom, "Authentication required. Please rejoin through the game server.");
return (false, code);
}
// At HostGame time no game code exists yet, so the host is identified by IP + name + version.
private bool TryBindHostAuth()
{
var udpIp = NormalizeIp(Connection.EndPoint?.Address);
if (_gameCodeAuth.TryConsumeHost(udpIp, Name, GameVersion.Value, out var user, out var matchInfo)
&& user != null)
{
BindAuth(user);
_logger.LogInformation(
"Client [{Id}] {Name} hosting (gamecode) │ FC {FriendCode} │ {Puid} │ matched {Match}",
Id, Name, FriendCode ?? "unknown", HashPuid(user.ProductUserId), matchInfo);
return true;
}
_logger.LogWarning(
"Client [{Id}] {Name} could not bind a host session (gamecode): {Reason}",
Id, Name, matchInfo);
return false;
}
private void BindAuth(UserAuthInfo user)
{
FriendCode = string.IsNullOrEmpty(user.FriendCode) ? null : user.FriendCode;
ProductUserId = user.ProductUserId;
}
private static string HashPuid(string? puid) =>
puid is { Length: >= 9 } ? puid[..9] : puid ?? "0";
private static string NormalizeIp(System.Net.IPAddress? address)
{
if (address == null)
{
return "(unknown)";
}
return address.IsIPv4MappedToIPv6 ? address.MapToIPv4().ToString() : address.ToString();
}
private bool IsPacketAllowed(IMessageReader message, bool hostOnly)
{
if (Player == null)
@@ -597,7 +719,9 @@ namespace Empostor.Server.Net
{
using var message = MessageWriter.Get(MessageType.Reliable);
var playerSpecificData = _gameManager.Find(code)?.Players.Select(p => p.Client.PlatformSpecificData) ?? Enumerable.Empty<PlatformSpecificData>();
// The query may arrive with a challenge code, so resolve it to the real code first.
var lookup = _gameCodeAuth.TryGetTarget(code, out var targetCode) ? targetCode : code;
var playerSpecificData = _gameManager.Find(lookup)?.Players.Select(p => p.Client.PlatformSpecificData) ?? Enumerable.Empty<PlatformSpecificData>();
Message22QueryPlatformIdsS2C.Serialize(message, code, playerSpecificData);
@@ -0,0 +1,434 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Empostor.Api.Config;
using Empostor.Api.Games;
using Empostor.Server.Service.Auth;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Empostor.Server.Net;
// GameCode auth mode: ties auth info to UDP connections using server-issued temporary GameCodes
// (challenge codes) instead of dynamic UDP ports.
public sealed class GameCodeAuthManager : IDisposable
{
// Maximum number of legacy-path pending entries kept per real code.
private const int MaxPendingPerCode = 64;
private readonly ILogger<GameCodeAuthManager> _logger;
private readonly TimeSpan _lifetime;
private readonly object _gate = new();
// Challenge code -> challenge
private readonly Dictionary<int, Challenge> _challenges = new();
// Legacy path: real code -> auth info stashed by HTTP join requests
private readonly Dictionary<GameCode, List<PendingJoin>> _pendingJoins = new();
// Legacy path: source IP -> auth info stashed by HTTP host requests
private readonly Dictionary<string, List<PendingHost>> _hosts = new();
private readonly Timer _cleanupTimer;
public GameCodeAuthManager(
ILogger<GameCodeAuthManager> logger,
IOptions<ServerConfig> serverConfig)
{
_logger = logger;
_lifetime = serverConfig.Value.TemporaryGameCodeLifetime;
_cleanupTimer = new Timer(_ => Cleanup(), null, TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(30));
}
private bool Expired(DateTime createdAt) => DateTime.UtcNow - createdAt > _lifetime;
// Issues a challenge code for the listing.
public GameCode CreateChallenge(GameCode targetCode, UserAuthInfo user)
{
lock (_gate)
{
var code = NewChallengeCode();
_challenges[code.Value] = new Challenge
{
Code = code,
TargetCode = targetCode,
User = user,
Name = user.Name,
GameVersion = user.ClientVersion,
CreatedAt = DateTime.UtcNow,
};
return code;
}
}
// Challenge code -> real code (non-consuming). Used to reverse-map listings and PlatformId queries.
public bool TryGetTarget(GameCode code, out GameCode targetCode)
{
lock (_gate)
{
if (_challenges.TryGetValue(code.Value, out var challenge) && !Expired(challenge.CreatedAt))
{
targetCode = challenge.TargetCode;
return true;
}
}
targetCode = default;
return false;
}
// Resolves auth info from the code of a UDP JoinGame.
public bool TryResolveChallenge(GameCode code, int clientId, out UserAuthInfo? user, out GameCode targetCode,
out string reason)
{
user = null;
targetCode = default;
lock (_gate)
{
if (!_challenges.TryGetValue(code.Value, out var challenge))
{
reason = "unknown challenge code";
return false;
}
if (Expired(challenge.CreatedAt))
{
_challenges.Remove(code.Value);
reason = "challenge expired";
return false;
}
if (challenge.OccupiedBy != null && challenge.OccupiedBy != clientId)
{
reason = $"challenge already used by client {challenge.OccupiedBy}";
return false;
}
challenge.OccupiedBy = clientId;
user = challenge.User;
targetCode = challenge.TargetCode;
reason = $"challenge matched (target {challenge.TargetCode.Code})";
return true;
}
}
// Legacy path (POST /api/games): stash auth info as a join request addressed to the real code.
public void RegisterPendingJoin(GameCode realCode, UserAuthInfo user)
{
lock (_gate)
{
if (!_pendingJoins.TryGetValue(realCode, out var list))
{
list = new List<PendingJoin>();
_pendingJoins[realCode] = list;
}
list.RemoveAll(x => Expired(x.CreatedAt));
var existing = list.FindIndex(x => x.User.ProductUserId == user.ProductUserId);
if (existing >= 0)
{
list[existing].CreatedAt = DateTime.UtcNow;
list[existing].Ip = user.ClientIp;
return;
}
if (list.Count >= MaxPendingPerCode)
{
// Drop the oldest entry when the list overflows.
list.RemoveAt(0);
}
list.Add(new PendingJoin
{
User = user,
Name = user.Name,
GameVersion = user.ClientVersion,
Ip = user.ClientIp,
CreatedAt = DateTime.UtcNow,
});
}
}
// Legacy path: match a connection that sent JoinGame with the real code by IP / name / version.
public bool TryConsumePendingJoin(GameCode realCode, string udpIp, string playerName, int gameVersion,
out UserAuthInfo? user, out string matchInfo)
{
user = null;
lock (_gate)
{
if (!_pendingJoins.TryGetValue(realCode, out var list))
{
matchInfo = "no pending join for this code";
return false;
}
list.RemoveAll(x => Expired(x.CreatedAt));
if (list.Count == 0)
{
_pendingJoins.Remove(realCode);
matchInfo = "pending join expired";
return false;
}
var best = PickBest(list.Select(x => (x.Ip, x.Name, x.GameVersion, x.CreatedAt)), udpIp, playerName, gameVersion, out var signals);
if (best < 0)
{
matchInfo = $"no entry matched (ip={Normalize(udpIp) ?? "?"} name=\"{playerName}\" version={gameVersion}, {list.Count} pending)";
return false;
}
user = list[best].User;
matchInfo = $"{signals} of {list.Count} pending";
list.RemoveAt(best);
if (list.Count == 0)
{
_pendingJoins.Remove(realCode);
}
return true;
}
}
// Hosting starts (PUT /api/games). Neither game nor code exists yet, so key the stash by source IP.
public void RegisterHost(UserAuthInfo user, string? ip)
{
var key = Normalize(ip) ?? "(unknown)";
lock (_gate)
{
if (!_hosts.TryGetValue(key, out var list))
{
list = new List<PendingHost>();
_hosts[key] = list;
}
list.RemoveAll(x => Expired(x.CreatedAt));
var existing = list.FindIndex(x => x.User.ProductUserId == user.ProductUserId);
if (existing >= 0)
{
list[existing].CreatedAt = DateTime.UtcNow;
return;
}
list.Add(new PendingHost
{
User = user,
Name = user.Name,
GameVersion = user.ClientVersion,
Ip = key,
CreatedAt = DateTime.UtcNow,
});
}
}
// Takes out one pending host matching the client that connected via HostGame.
public bool TryConsumeHost(string udpIp, string playerName, int gameVersion, out UserAuthInfo? user,
out string matchInfo)
{
user = null;
var key = Normalize(udpIp) ?? "(unknown)";
lock (_gate)
{
if (!_hosts.TryGetValue(key, out var list))
{
matchInfo = $"no pending host for ip={key}";
return false;
}
list.RemoveAll(x => Expired(x.CreatedAt));
if (list.Count == 0)
{
_hosts.Remove(key);
matchInfo = "pending host expired";
return false;
}
var best = PickBest(list.Select(x => (x.Ip, x.Name, x.GameVersion, x.CreatedAt)), udpIp, playerName, gameVersion, out var signals);
if (best < 0)
{
matchInfo = $"no entry matched (name=\"{playerName}\" version={gameVersion}, {list.Count} pending)";
return false;
}
user = list[best].User;
matchInfo = $"{signals} of {list.Count} pending";
list.RemoveAt(best);
if (list.Count == 0)
{
_hosts.Remove(key);
}
return true;
}
}
// Creates a unique challenge code (same V2 format as real codes).
private GameCode NewChallengeCode()
{
for (var i = 0; i < 64; i++)
{
var code = GameCode.Create();
if (!code.IsInvalid && !_challenges.ContainsKey(code.Value))
{
return code;
}
}
throw new InvalidOperationException("failed to allocate a unique challenge code");
}
// Picks the best entry. IP match > name > version; ties go to the older entry.
private static int PickBest(
IEnumerable<(string? Ip, string Name, int GameVersion, DateTime CreatedAt)> candidates,
string udpIp,
string playerName,
int gameVersion,
out string signals)
{
var list = candidates.ToList();
var normalizedIp = Normalize(udpIp);
var bestIndex = -1;
var bestScore = 0;
var bestCreated = DateTime.MinValue;
var bestSignals = string.Empty;
for (var i = 0; i < list.Count; i++)
{
var (ip, name, version, created) = list[i];
var ipMatch = !string.IsNullOrEmpty(ip) && ip == normalizedIp;
var nameMatch = !string.IsNullOrEmpty(name)
&& string.Equals(name, playerName, StringComparison.OrdinalIgnoreCase);
var versionMatch = version > 0 && version == gameVersion;
if (!ipMatch && !(nameMatch && versionMatch))
{
continue;
}
var candidateScore = 0;
if (ipMatch) candidateScore += 4;
if (nameMatch) candidateScore += 2;
if (versionMatch) candidateScore += 1;
if (candidateScore > bestScore
|| (candidateScore == bestScore && (bestIndex < 0 || created < bestCreated)))
{
bestIndex = i;
bestScore = candidateScore;
bestCreated = created;
bestSignals = $"ip{(ipMatch ? "+" : "-")} name{(nameMatch ? "+" : "-")} ver{(versionMatch ? "+" : "-")}";
}
}
signals = bestSignals;
return bestIndex;
}
private void Cleanup()
{
try
{
lock (_gate)
{
foreach (var value in _challenges.Where(x => Expired(x.Value.CreatedAt)).Select(x => x.Key).ToList())
{
_challenges.Remove(value);
}
foreach (var code in _pendingJoins.Keys.ToList())
{
var list = _pendingJoins[code];
list.RemoveAll(x => Expired(x.CreatedAt));
if (list.Count == 0)
{
_pendingJoins.Remove(code);
}
}
foreach (var ip in _hosts.Keys.ToList())
{
var list = _hosts[ip];
list.RemoveAll(x => Expired(x.CreatedAt));
if (list.Count == 0)
{
_hosts.Remove(ip);
}
}
}
}
catch (Exception ex)
{
_logger.LogWarning(ex, "GameCodeAuth cleanup failed");
}
}
private static string? Normalize(string? ip)
{
if (string.IsNullOrEmpty(ip))
{
return null;
}
return ip.StartsWith("::ffff:", StringComparison.OrdinalIgnoreCase) ? ip[7..] : ip;
}
public void Dispose() => _cleanupTimer.Dispose();
private sealed class Challenge
{
public required GameCode Code { get; init; }
public required GameCode TargetCode { get; init; }
public required UserAuthInfo User { get; init; }
public required string Name { get; init; }
public required int GameVersion { get; init; }
public required DateTime CreatedAt { get; set; }
// The connection that consumed the challenge; each challenge can be used by one connection only.
public int? OccupiedBy { get; set; }
}
private sealed class PendingJoin
{
public required UserAuthInfo User { get; init; }
public required string Name { get; init; }
public required int GameVersion { get; init; }
public required string? Ip { get; set; }
public required DateTime CreatedAt { get; set; }
}
private sealed class PendingHost
{
public required UserAuthInfo User { get; init; }
public required string Name { get; init; }
public required int GameVersion { get; init; }
public required string? Ip { get; init; }
public required DateTime CreatedAt { get; set; }
}
}
@@ -18,13 +18,4 @@ public interface IDeltaListenerManager
/// Stops and disposes the UDP listener on a specific port.
/// </summary>
ValueTask StopDeltaListenerAsync(int port);
/// <summary>
/// Returns the single shared UDP port that rate-limited (over-quota) join
/// requests are pointed at, binding it on first use. Its listener never
/// creates a player, it only sends the localized "too frequent" hint, so
/// an over-quota IP cannot consume a pool port per request.
/// </summary>
/// <returns>The reject port, or 0 when the delta pool is unavailable.</returns>
ValueTask<int> GetRateLimitRejectPortAsync();
}
@@ -6,7 +6,6 @@ using System.Threading;
using System.Threading.Tasks;
using Empostor.Api.Config;
using Empostor.Api.Events.Managers;
using Empostor.Api.Localization;
using Empostor.Api.Net;
using Empostor.Api.Net.Manager;
using Empostor.Api.Service;
@@ -37,8 +36,7 @@ namespace Empostor.Server.Net.Manager
private readonly PortPoolService _portPool;
private readonly IpGeolocationService _ipGeo;
private readonly ClientIdStore _clientIdStore;
private readonly IpRateLimitService _rateLimit;
private readonly ILocalizationService _language;
private readonly ServerConfig _serverConfig;
private int _idLast;
public ClientManager(
@@ -52,8 +50,7 @@ namespace Empostor.Server.Net.Manager
PortPoolService portPool,
IpGeolocationService ipGeo,
ClientIdStore clientIdStore,
IpRateLimitService rateLimit,
ILocalizationService language)
IOptions<ServerConfig> serverConfig)
{
_logger = logger;
_eventManager = eventManager;
@@ -66,8 +63,7 @@ namespace Empostor.Server.Net.Manager
_portPool = portPool;
_ipGeo = ipGeo;
_clientIdStore = clientIdStore;
_rateLimit = rateLimit;
_language = language;
_serverConfig = serverConfig.Value;
_idLast = checked((int)_clientIdStore.GetLastId());
if (_compatibilityConfig.AllowFutureGameVersions)
@@ -159,27 +155,14 @@ namespace Empostor.Server.Net.Manager
? $" │ Reactor: {string.Join(", ", System.Linq.Enumerable.Select(mods, m => $"{m.Id} {m.Version}"))}"
: string.Empty;
// Match the auth session to this UDP connection. In dynamic delta
// mode (deltaPort > 0) the connection must match by its unique
// port (nonce); there is no IP fallback anymore. In fixed-port
// mode (deltaPort == 0) matching is skipped entirely: no PUID and
// no FriendCode are bound to the client.
// Match the auth session to the UDP connection: DeltaPort requires an exact match on
// the dedicated port used as a nonce, GameCode settles it in JoinGame / HostGame, fixed port does not match at all.
if (deltaPort > 0)
{
authInfo = _authCache.FindByPort(deltaPort);
if (authInfo == null)
{
// Dynamic delta mode: an active port that has no auth info
// bound to it is an unauthenticated UDP connection — reject
// it instead of admitting an anonymous client. An IP that is
// over the request quota gets the localized hint, everyone
// else the plain authentication notice.
if (IsRateLimited(null, clientIp, out var retryNoAuth))
{
await RejectRateLimitedAsync(connection, 0, language, retryNoAuth, NormalizeIp(clientIp));
return;
}
// A connection to a port with no auth info is unauthenticated: reject it.
_logger.LogWarning(
"#{Id} {Name} │ port {Port} has no auth info │ {Ip} │ rejecting unauthenticated UDP connection",
id, name, deltaPort, NormalizeIp(clientIp));
@@ -187,17 +170,9 @@ namespace Empostor.Server.Net.Manager
return;
}
// Port matched — cancel the allocation timeout
var limited = IsRateLimited(authInfo.ClientIp, clientIp, out var retryAfter);
if (limited)
{
await RejectRateLimitedAsync(connection, deltaPort, language, retryAfter, NormalizeIp(clientIp));
return;
}
// Port matched - stop the allocation timeout.
_portPool.ConfirmPort(deltaPort);
// Mark the auth-cache entry as active so the inactivity
// timer never clears the port while the player is connected.
// Keep the port from being reclaimed by auth-cache expiry while the client is connected.
_authCache.ConfirmPort(deltaPort);
friendCode = authInfo.FriendCode;
@@ -206,15 +181,16 @@ namespace Empostor.Server.Net.Manager
"#{Id} {Name} │ port {Port} │ {Location} │ {Lang} │ {Platform} │ FC {FriendCode} │ {HashPuid}{Reactor}",
id, name, deltaPort, locationStr, lang, platformStr, friendCode ?? "unknown", HashPuid(authInfo.ProductUserId), reactorStr);
}
else if (_serverConfig.UseGameCodeMode)
{
// GameCode mode: no auth info is bound at this point; it is settled in JoinGame / HostGame.
_logger.LogInformation(
"#{Id} {Name} │ gamecode mode │ awaiting challenge │ {Location} │ {Lang} │ {Platform}{Reactor}",
id, name, locationStr, lang, platformStr, reactorStr);
}
else
{
// Fixed-port mode: no auth binding, no PUID/FriendCode.
if (IsRateLimited(null, clientIp, out var retryAfter))
{
await RejectRateLimitedAsync(connection, 0, language, retryAfter, NormalizeIp(clientIp));
return;
}
// Fixed-port mode: no PUID / FriendCode binding.
_logger.LogInformation(
"#{Id} {Name} │ fixed port │ {Location} │ {Lang} │ {Platform}{Reactor}",
id, name, locationStr, lang, platformStr, reactorStr);
@@ -253,55 +229,6 @@ namespace Empostor.Server.Net.Manager
&& _clients.TryGetValue(client.Id, out var c)
&& ReferenceEquals(client, c);
// True when the IP already used up its TCP (HTTP) request quota. The
// IP of the HTTP handshake is preferred: behind a CDN that is the real
// player IP, while the UDP source address may be a proxy node.
private bool IsRateLimited(string? httpIp, IPAddress? udpIp, out TimeSpan retryAfter)
{
retryAfter = TimeSpan.Zero;
IPAddress? ip = null;
if (!string.IsNullOrEmpty(httpIp) && IPAddress.TryParse(httpIp, out var parsed))
{
ip = parsed;
}
ip ??= udpIp;
if (ip == null)
{
return false;
}
return _rateLimit.IsLimited(ip, out retryAfter);
}
// Over-quota players get a localized dialog instead of a black screen:
// the HTTP layer deliberately lets the join request through so the
// client reaches this point and can display the message.
private async ValueTask RejectRateLimitedAsync(
IHazelConnection connection,
int deltaPort,
Language language,
TimeSpan retryAfter,
string ip)
{
var minutes = IpRateLimitService.MinutesUntilRetry(retryAfter);
var message = _language.Get(new LocalizedMessageKey("empostor", IpRateLimitService.MessageKey), language, minutes);
_logger.LogWarning(
"IpRateLimit rejecting game connection from {Ip} │ retry in {Minutes}m",
ip, minutes);
await connection.CustomDisconnectAsync(DisconnectReason.Custom, message);
if (deltaPort > 0)
{
// The port was never confirmed, release it right away instead
// of waiting for the 5-minute allocation timeout.
_portPool.ReturnPort(deltaPort);
}
}
private static string NormalizeIp(IPAddress? addr)
{
if (addr == null)
+1 -107
View File
@@ -2,17 +2,14 @@ using System;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Empostor.Api.Config;
using Empostor.Api.Events.Managers;
using Empostor.Api.Localization;
using Empostor.Server.Events.Client;
using Empostor.Server.Net.Hazel;
using Empostor.Server.Net.Manager;
using Empostor.Server.Service.Auth;
using Empostor.Server.Service.Firewall;
using Empostor.Server.Service.Ip;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.ObjectPool;
using Microsoft.Extensions.Options;
@@ -30,19 +27,12 @@ namespace Empostor.Server.Net
private readonly ILogger<Matchmaker> _logger;
private readonly PortPoolService _portPool;
private readonly IFirewallService _firewall;
private readonly ServerConfig _serverConfig;
private readonly AuthCacheService _authCache;
private readonly IOptions<AntiCheatConfig> _antiCheatOptions;
private readonly IpRateLimitService _rateLimit;
private readonly ILocalizationService _language;
private UdpConnectionListener? _mainListener;
private readonly ConcurrentDictionary<int, UdpConnectionListener> _deltaListeners = new();
// Shared port for over-quota (rate limited) joins; 0 until first use.
private int _rejectPort;
private readonly SemaphoreSlim _rejectPortLock = new(1, 1);
private IPEndPoint? _mainEndPoint;
public Matchmaker(
@@ -53,11 +43,8 @@ namespace Empostor.Server.Net
ILogger<Matchmaker> logger,
PortPoolService portPool,
IFirewallService firewall,
IOptions<ServerConfig> serverConfig,
AuthCacheService authCache,
IOptions<AntiCheatConfig> antiCheatOptions,
IpRateLimitService rateLimit,
ILocalizationService language)
IOptions<AntiCheatConfig> antiCheatOptions)
{
_eventManager = eventManager;
_clientManager = clientManager;
@@ -66,11 +53,8 @@ namespace Empostor.Server.Net
_logger = logger;
_portPool = portPool;
_firewall = firewall;
_serverConfig = serverConfig.Value;
_authCache = authCache;
_antiCheatOptions = antiCheatOptions;
_rateLimit = rateLimit;
_language = language;
// Subscribe to port return events from the pool
_portPool.OnPortReturned += OnPortReturned;
@@ -202,66 +186,6 @@ namespace Empostor.Server.Net
}
}
/// <summary>
/// One shared UDP port for all over-quota joins: reserving it here
/// (once) means rate-limited TCP requests never take a pool port and
/// never start their own listener. The listener above answers every
/// handshake on this port with the localized hint and closes it, so
/// the player is told why they cannot join instead of seeing a black
/// screen — without letting them into a game.
/// </summary>
public async ValueTask<int> GetRateLimitRejectPortAsync()
{
if (!_portPool.IsEnabled)
{
// Fixed-port mode: the main listener is the reject target.
return 0;
}
var existing = Volatile.Read(ref _rejectPort);
if (existing > 0)
{
return existing;
}
await _rejectPortLock.WaitAsync();
try
{
existing = Volatile.Read(ref _rejectPort);
if (existing > 0)
{
return existing;
}
var port = _portPool.AllocatePort("(rate limit reject)");
if (port <= 0)
{
_logger.LogWarning("Matchmaker could not reserve the rate-limit reject port: pool unavailable");
return 0;
}
if (!await StartDeltaListenerAsync(port))
{
// StartDeltaListenerAsync already returned the port.
return 0;
}
// Confirmed so it is never reclaimed by the allocation timeout:
// this port lives for the whole lifetime of the server.
_portPool.ConfirmPort(port);
Volatile.Write(ref _rejectPort, port);
_logger.LogInformation(
"Matchmaker rate-limit reject port reserved on {Port} (one shared port for all over-quota joins)",
port);
return port;
}
finally
{
_rejectPortLock.Release();
}
}
public async ValueTask StopAsync()
{
if (_mainListener != null)
@@ -302,20 +226,6 @@ namespace Empostor.Server.Net
connection = new HazelConnection(e.Connection, _connectionLogger, _antiCheatOptions);
// Shared rate-limit reject port: there is no auth entry and no
// player behind it, so the only thing to do is tell the client
// — in its own language — why it is not let in.
if (port != 0 && port == Volatile.Read(ref _rejectPort))
{
var message = BuildRateLimitMessage(connection.EndPoint?.Address, language);
_logger.LogWarning(
"Matchmaker rate limit rejected {Ip} on reject port {Port} │ {Message}",
connection.EndPoint?.Address?.ToString() ?? "unknown", port, message);
await connection.CustomDisconnectAsync(DisconnectReason.Custom, message);
return;
}
await _eventManager.CallAsync(new ClientConnectionEvent(connection, e.HandshakeData));
await _clientManager.RegisterConnectionAsync(
connection, name, clientVersion, language, chatMode, platformSpecificData,
@@ -332,22 +242,6 @@ namespace Empostor.Server.Net
}
}
// Localized "please try again in N minutes" hint. N is what is actually
// left for that IP when it can be read off the quota, the full window
// otherwise (behind a CDN the UDP source address may not be the key the
// requests were counted with).
private string BuildRateLimitMessage(IPAddress? ip, Language language)
{
var minutes = IpRateLimitService.WindowMinutes;
if (ip != null && _rateLimit.IsLimited(ip, out var retryAfter))
{
minutes = IpRateLimitService.MinutesUntilRetry(retryAfter);
}
return _language.Get(new LocalizedMessageKey("empostor", IpRateLimitService.MessageKey), language, minutes);
}
private void OnPortReturned(int port)
{
_authCache.RemoveByPort(port);
+16 -6
View File
@@ -37,13 +37,22 @@ namespace Empostor.Server.Net
public async Task StartAsync(CancellationToken cancellationToken)
{
var endpoint = new IPEndPoint(IPAddress.Parse(_serverConfig.ResolveListenIp()), _serverConfig.ListenPort);
var listenAddress = IPAddress.Parse(_serverConfig.ResolveListenIp());
if (_portPool.IsEnabled)
if (_serverConfig.UseGameCodeMode)
{
// Dynamic delta mode: no static UDP port is bound at startup.
// Ports are allocated per player on demand; once the pool drops
// to the low-water mark, new players are rejected.
// GameCode mode: dynamic ports are unused; open a single shared UDP port.
var endpoint = new IPEndPoint(listenAddress, _serverConfig.GameCodeListenPort);
await _matchmaker.StartAsync(endpoint);
_logger.LogInformation(
"GameCode Matchmaker enabled: single shared UDP port {Port} (dynamic delta ports disabled).",
endpoint.Port);
}
else if (_portPool.IsEnabled)
{
// Dynamic DeltaPort mode: no static port is opened at startup; ports are allocated on demand.
var endpoint = new IPEndPoint(listenAddress, _serverConfig.ListenPort);
_matchmaker.Initialize(endpoint);
_logger.LogInformation(
"Delta Matchmaker enabled: no static UDP port at startup (pool {Start}-{End}), ports created per player.",
@@ -52,7 +61,8 @@ namespace Empostor.Server.Net
}
else
{
// Static mode: bind the main UDP listener on the configured port.
// Fixed-port mode: open the main listener on the configured port.
var endpoint = new IPEndPoint(listenAddress, _serverConfig.ListenPort);
await _matchmaker.StartAsync(endpoint);
_logger.LogInformation(
+11 -3
View File
@@ -24,8 +24,11 @@ public sealed class PortPoolService : IDisposable
private readonly int _deltaPortEnd;
private readonly int _listenPort;
private readonly int _deltaLowWaterMark;
private readonly bool _useGameCodeMode;
public bool IsEnabled => _deltaPortStart > 0
// GameCode mode uses no dynamic ports at all, only a single shared UDP port.
public bool IsEnabled => !_useGameCodeMode
&& _deltaPortStart > 0
&& _deltaPortEnd >= _deltaPortStart;
/// <summary>
@@ -46,6 +49,7 @@ public sealed class PortPoolService : IDisposable
_deltaPortEnd = cfg.DeltaPortEnd;
_listenPort = cfg.ListenPort;
_deltaLowWaterMark = cfg.DeltaPortLowWaterMark;
_useGameCodeMode = cfg.UseGameCodeMode;
if (IsEnabled)
{
@@ -74,8 +78,12 @@ public sealed class PortPoolService : IDisposable
}
else
{
_logger.LogInformation("PortPool disabled (DeltaPortStart={Start}, DeltaPortEnd={End})",
_deltaPortStart, _deltaPortEnd);
_logger.LogInformation(
_useGameCodeMode
? "PortPool disabled (GameCode verification mode uses the shared UDP port {ListenPort})"
: "PortPool disabled (DeltaPortStart={Start}, DeltaPortEnd={End})",
_useGameCodeMode ? _listenPort : _deltaPortStart,
_useGameCodeMode ? 0 : _deltaPortEnd);
}
}
@@ -134,8 +134,8 @@ namespace Empostor.Server.Net.State
? $" │ Reactor: {string.Join(", ", System.Linq.Enumerable.Select(mods, m => $"{m.Id} {m.Version}"))}"
: string.Empty;
_logger.LogInformation("▶ {Name} ({Id}) joined │ {Lang} │ {Platform} │ v{Version} │ Authority:{Authority} │ port {DeltaPort}{Reactor}",
sender.Client.Name, sender.Client.Id, lang, platformStr, version, authority, deltaPort, reactorStr);
_logger.LogInformation("▶ {Name} ({Id}) joined │ FC {FriendCode} │ {Lang} │ {Platform} │ v{Version} │ Authority:{Authority} │ port {DeltaPort}{Reactor}",
sender.Client.Name, sender.Client.Id, sender.Client.FriendCode ?? "unknown", lang, platformStr, version, authority, deltaPort, reactorStr);
if (isNew)
{
+1
View File
@@ -209,6 +209,7 @@ namespace Empostor.Server
services.AddSingleton<IEventManager, EventManager>();
services.AddSingleton<Matchmaker>();
services.AddSingleton<IDeltaListenerManager>(sp => sp.GetRequiredService<Matchmaker>());
services.AddSingleton<GameCodeAuthManager>();
services.AddHostedService<MatchmakerService>();
})
.UseSerilog((context, logCfg) =>
@@ -19,8 +19,8 @@ namespace Empostor.Server.Recorder
private bool _createdGame;
private bool _recordAfter;
public ClientRecorder(ILogger<Client> logger, IOptions<AntiCheatConfig> antiCheatOptions, ClientManager clientManager, ICustomMessageManager<ICustomRootMessage> customMessageManager, IEventManager eventManager, ReportStore reportStore, GameManager gameManager, string name, GameVersion gameVersion, Language language, QuickChatModes chatMode, PlatformSpecificData platformSpecificData, HazelConnection connection, PacketRecorder recorder)
: base(logger, antiCheatOptions, clientManager, gameManager, customMessageManager, eventManager, reportStore, name, gameVersion, language, chatMode, platformSpecificData, connection)
public ClientRecorder(ILogger<Client> logger, IOptions<AntiCheatConfig> antiCheatOptions, ClientManager clientManager, ICustomMessageManager<ICustomRootMessage> customMessageManager, IEventManager eventManager, ReportStore reportStore, GameManager gameManager, GameCodeAuthManager gameCodeAuth, IOptions<ServerConfig> serverConfig, string name, GameVersion gameVersion, Language language, QuickChatModes chatMode, PlatformSpecificData platformSpecificData, HazelConnection connection, PacketRecorder recorder)
: base(logger, antiCheatOptions, clientManager, gameManager, customMessageManager, eventManager, reportStore, gameCodeAuth, serverConfig, name, gameVersion, language, chatMode, platformSpecificData, connection)
{
_recorder = recorder;
_isFirst = true;
@@ -35,7 +35,9 @@ public sealed class AuthCacheService : IDisposable
TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
}
public void Store(string productUserId, string matchmakerToken, string? friendCode, IPAddress? clientIp, string? eosToken = null)
// Kept together so the UDP side can cross-check the in-game display name and version.
public void Store(string productUserId, string matchmakerToken, string? friendCode, IPAddress? clientIp,
string? eosToken = null, string? name = null, int clientVersion = 0)
{
if (string.IsNullOrEmpty(productUserId) || string.IsNullOrEmpty(matchmakerToken))
{
@@ -48,6 +50,8 @@ public sealed class AuthCacheService : IDisposable
MatchmakerToken = matchmakerToken,
FriendCode = friendCode ?? string.Empty,
ClientIp = clientIp != null ? NormalizeIp(clientIp) : null,
Name = name ?? string.Empty,
ClientVersion = clientVersion,
EosToken = eosToken,
CreatedAt = DateTime.UtcNow,
};
@@ -167,6 +171,9 @@ public sealed class UserAuthInfo
public string Name { get; set; } = string.Empty;
// Broadcast version as declared by the client in POST /api/user.
public int ClientVersion { get; set; }
public string? ClientIp { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
@@ -1,10 +1,7 @@
using System;
using System.Globalization;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Threading.Tasks;
using Empostor.Api.Localization;
using Empostor.Server.Localization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
@@ -12,29 +9,21 @@ namespace Empostor.Server.Service.Ip;
public sealed class IpRateLimitMiddleware
{
private const string MessageKey = IpRateLimitService.MessageKey;
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};
// The client parses a failed matchmaker request as a MatchmakerResponse
// and reads "Errors"; 116 (TooManyRequests) is rendered by the client itself.
private static readonly JsonSerializerOptions MatchmakerJsonOptions = new();
private readonly RequestDelegate _next;
private readonly IpRateLimitService _rateLimit;
private readonly ILocalizationService _language;
private readonly ILogger<IpRateLimitMiddleware> _logger;
public IpRateLimitMiddleware(
RequestDelegate next,
IpRateLimitService rateLimit,
ILocalizationService language,
ILogger<IpRateLimitMiddleware> logger)
{
_next = next;
_rateLimit = rateLimit;
_language = language;
_logger = logger;
}
@@ -50,18 +39,9 @@ public sealed class IpRateLimitMiddleware
var ip = RealIpResolver.Resolve(context);
// Always counted, so the join endpoint cannot be used to burn through
// the quota without being noticed.
var overQuota = !_rateLimit.TryRegister(ip, out var retryAfter);
// The join flow of the game client (POST /api/user, then
// PUT/GET /api/games for FindHost) must never fail over HTTP: the
// client only logs such a failure and then hangs on a black screen.
// These endpoints are therefore counted but never blocked — over-quota
// players still take no pool port and no outbound auth call, and are
// pointed at one shared reject port whose listener sends the localized
// hint in-game (see TokenController / Matchmaker).
if (!overQuota || IsGameFlowPath(context.Request.Path))
// Every non-admin request is counted and rejected over quota, the join
// flow included: no token or port is handed out, so no pool port is spent.
if (_rateLimit.TryRegister(ip, out var retryAfter))
{
await _next(context);
return;
@@ -69,8 +49,6 @@ public sealed class IpRateLimitMiddleware
var minutes = IpRateLimitService.MinutesUntilRetry(retryAfter);
var message = _language.Get(new LocalizedMessageKey("empostor", MessageKey), LanguageCodes.FromTag(ResolveLangCode(context)), minutes);
_logger.LogWarning(
"IpRateLimit blocked {Ip} on {Path} │ retry in {Minutes}m",
ip?.ToString() ?? "unknown",
@@ -81,76 +59,13 @@ public sealed class IpRateLimitMiddleware
context.Response.Headers["Retry-After"] =
((int)Math.Ceiling(retryAfter.TotalSeconds)).ToString(CultureInfo.InvariantCulture);
context.Response.ContentType = "application/json; charset=utf-8";
await context.Response.WriteAsync(JsonSerializer.Serialize(new { error = message }, JsonOptions));
await context.Response.WriteAsync(JsonSerializer.Serialize(
new { Errors = new[] { new { Reason = DisconnectReason.TooManyRequests } } },
MatchmakerJsonOptions));
}
// The admin panel polls its own endpoints, so it is never rate-limited.
private static bool IsAdminPath(PathString path)
=> path.StartsWithSegments("/admin", StringComparison.OrdinalIgnoreCase)
|| path.StartsWithSegments("/api/admin", StringComparison.OrdinalIgnoreCase);
// The join flow of the game client: matchmaking token + FindHost.
// GamesController echoes the token's port back, so the reject port handed
// out by /api/user is what the client connects to.
private static bool IsGameFlowPath(PathString path)
=> path.StartsWithSegments("/api/user", StringComparison.OrdinalIgnoreCase)
|| path.StartsWithSegments("/api/games", StringComparison.OrdinalIgnoreCase);
private static string ResolveLangCode(HttpContext context)
{
var acceptLanguage = context.Request.Headers["Accept-Language"].ToString();
foreach (var entry in acceptLanguage.Split(','))
{
var tag = entry.Split(';')[0].Trim();
if (tag.Length == 0 || tag == "*")
{
continue;
}
var code = MapLangTag(tag);
if (code != null)
{
return code;
}
}
return "en";
}
// Maps a browser/client language tag (zh-CN, pt-BR, ...) to one of the
// server's Languages/*.json codes.
private static string? MapLangTag(string tag)
{
var lower = tag.ToLowerInvariant();
if (lower.StartsWith("zh", StringComparison.Ordinal))
{
return lower.Contains("hant", StringComparison.Ordinal)
|| lower.Contains("tw", StringComparison.Ordinal)
|| lower.Contains("hk", StringComparison.Ordinal)
|| lower.Contains("mo", StringComparison.Ordinal)
? "zh_TW"
: "zh_CN";
}
if (lower.StartsWith("pt-br", StringComparison.Ordinal))
{
return "pt_BR";
}
if (lower.StartsWith("fil", StringComparison.Ordinal) || lower.StartsWith("tl", StringComparison.Ordinal))
{
return "fil";
}
foreach (var code in new[] { "en", "es", "pt", "ko", "ru", "nl", "fr", "de", "it", "ja", "ga" })
{
if (lower.StartsWith(code, StringComparison.Ordinal))
{
return code;
}
}
return null;
}
}
@@ -7,8 +7,6 @@ using Microsoft.Extensions.Options;
namespace Empostor.Server.Service.Ip;
public sealed class IpRateLimitService
{
public const string MessageKey = "ratelimit.too_frequent";
public const int MaxRequestsPerWindow = 30;
public const int WindowMinutes = 1;
@@ -69,42 +67,6 @@ public sealed class IpRateLimitService
}
}
// Reads the quota without counting a request — used to answer the client
// in-game (and to skip expensive work) when the IP is already over quota.
public bool IsLimited(IPAddress? ip, out TimeSpan retryAfter)
{
retryAfter = TimeSpan.Zero;
var config = _options.Value;
var window = GetWindow(config);
if (ip == null || window == null)
{
return false;
}
if (!_windows.TryGetValue(ip.ToString(), out var entry))
{
return false;
}
var now = DateTime.UtcNow;
lock (entry)
{
if (now - entry.StartUtc >= window.Value || entry.Count <= MaxRequestsPerWindow)
{
return false;
}
retryAfter = entry.StartUtc + window.Value - now;
if (retryAfter < TimeSpan.Zero)
{
retryAfter = TimeSpan.Zero;
}
return true;
}
}
private static TimeSpan? GetWindow(AntiCheatConfig config)
{
if (!config.EnableRateLimits)
+13 -6
View File
@@ -58,7 +58,7 @@ internal static class StartupBanner
var version = DotnetUtils.Version;
string[] labelTexts = { "Public IP", "Listen Port", "HTTP API", "Admin Panel", "Port Pool", "AntiCheat", "Log Level", "Log File" };
string[] labelTexts = { "Public IP", "Listen Port", "Verify Mode", "HTTP API", "Admin Panel", "Port Pool", "AntiCheat", "Log Level", "Log File" };
var maxLabel = labelTexts.Max(t => t.Length) + 2;
var width = 62;
@@ -72,14 +72,21 @@ internal static class StartupBanner
sw.WriteLine(C(BoxML + new string(BoxH[0], width - 2) + BoxMR, Cyan));
Row(sw, width, maxLabel, "Public IP", server.PublicIp);
var deltaEnabled = server.DeltaPortStart > 0 && server.DeltaPortEnd >= server.DeltaPortStart;
var actualListenPort = deltaEnabled ? "dynamic" : $"{server.ListenPort} (UDP)";
var gameCodeMode = server.UseGameCodeMode;
var deltaEnabled = !gameCodeMode && server.DeltaPortStart > 0 && server.DeltaPortEnd >= server.DeltaPortStart;
var actualListenPort = gameCodeMode
? $"{server.GameCodeListenPort} (UDP, shared)"
: deltaEnabled ? "dynamic" : $"{server.ListenPort} (UDP)";
Row(sw, width, maxLabel, "Listen Port", actualListenPort);
Row(sw, width, maxLabel, "Verify Mode",
gameCodeMode ? C("GameCode", Green) : C("DeltaPort", Gray));
Row(sw, width, maxLabel, "HTTP API", $"http://{http.ListenIp}:{http.ListenPort}");
Row(sw, width, maxLabel, "Admin Panel", $"http://{server.PublicIp}:{http.ListenPort}/admin");
var poolInfo = deltaEnabled
? $"{server.DeltaPortStart}-{server.DeltaPortEnd} ({server.DeltaPortEnd - server.DeltaPortStart + 1} ports, rejects below low-water mark {server.DeltaPortLowWaterMark})"
: C("disabled", Yellow);
var poolInfo = gameCodeMode
? C("disabled (GameCode mode)", Yellow)
: deltaEnabled
? $"{server.DeltaPortStart}-{server.DeltaPortEnd} ({server.DeltaPortEnd - server.DeltaPortStart + 1} ports, rejects below low-water mark {server.DeltaPortLowWaterMark})"
: C("disabled", Yellow);
Row(sw, width, maxLabel, "Port Pool", poolInfo);
Row(sw, width, maxLabel, "Packet Filter", C("✔ Enabled", Green));
+3
View File
@@ -6,6 +6,9 @@
"ListenPort": 22023,
"UseUfw": false,
"UseFirewalld": false,
"VerificationMode": "DeltaPort",
"GameCodePorts": [],
"TemporaryGameCodeLifetimeSeconds": 180,
"DeltaPortStart": 22024,
"DeltaPortEnd": 42024
},