Working on server side stuff

This commit is contained in:
Vladislav Khorev committed 2026-11-17 15:28:21 +06:00
1 parent a784da9fb4
commit 542fc191fa
12 files changed
+757 -64

No files matched your search

+44
View File
@@ -0,0 +1,44 @@
#pragma once
#include "IGameServer.h"
#include "NetworkProtocol.h"
#include <string>
#include <type_traits>
#include <variant>
namespace FRG {
// Applies one globally sequenced lockstep command. Shared by the server and
// every replica so they cannot diverge.
// - destination: cancels any attack target, then walks to the point;
// - set_target: cancels the current walk, then attacks (update() plans the chase);
// - clear_attack_target: clears the attack target only.
inline void applyScheduledCommand(
IGameServer& server, const std::string& locationId,
const ScheduledCommand& scheduled)
{
std::visit([&](const auto& command) {
using T = std::decay_t<decltype(command)>;
if constexpr (std::is_same_v<T, ScheduledDestinationCommand>) {
server.submit(ClearCharacterAttackTargetCommand{
locationId, command.playerId});
server.submit(SetCharacterDestinationCommand{
locationId, command.playerId, command.target, {}});
} else if constexpr (std::is_same_v<T, ScheduledCharacterEnabledCommand>) {
server.submit(SetCharacterEnabledCommand{
command.locationId, command.characterId, command.enabled});
} else if (command.action == "set_target") {
server.submit(StopCharacterCommand{locationId, command.playerId});
server.submit(SetCharacterTargetCommand{
locationId, command.playerId, command.targetId});
} else if (command.action == "clear_attack_target") {
server.submit(ClearCharacterAttackTargetCommand{
locationId, command.playerId});
} else if (command.action == "try_attack_combo") {
server.submit(TryCharacterAttackComboCommand{
locationId, command.playerId});
}
}, scheduled);
}
} // namespace FRG
+259
View File
@@ -0,0 +1,259 @@
#pragma once
// Portable, dependency-free SHA-256 / HMAC-SHA256 and the helpers used to sign
// client input messages. Header-only so every platform target (Windows, web,
// standalone server) shares one implementation without OpenSSL.
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <random>
#include <string>
#include <vector>
namespace FRG {
namespace auth {
using Bytes = std::vector<std::uint8_t>;
using Digest = std::array<std::uint8_t, 32>;
inline constexpr std::size_t kSessionSecretBytes = 32;
namespace detail {
inline std::uint32_t rotr(std::uint32_t value, unsigned count)
{
return (value >> count) | (value << (32u - count));
}
} // namespace detail
inline Digest sha256(const Bytes& data)
{
static const std::uint32_t k[64] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x7632ff20,
0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585,
0x106aa070, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x609bbfa4, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x01010103, 0x391c0cb3, 0x4ed8aa4a,
0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f1};
std::uint32_t h[8] = {
0x6a09e667, 0xb0fa3350, 0x3c6ef372, 0xa54ff53a,
0x0010023f, 0x9b05688c, 0x1f83d9ab, 0xbe5f012a};
Bytes message = data;
const std::uint64_t bitLength = static_cast<std::uint64_t>(data.size()) * 8u;
message.push_back(0x80);
while (message.size() % 64 != 56) message.push_back(0);
for (int shift = 56; shift >= 0; shift -= 8)
message.push_back(static_cast<std::uint8_t>(bitLength >> shift));
for (std::size_t offset = 0; offset < message.size(); offset += 64) {
std::uint32_t w[64];
for (std::size_t i = 0; i < 16; ++i) {
const std::size_t at = offset + i * 4;
w[i] = (static_cast<std::uint32_t>(message[at]) << 24) |
(static_cast<std::uint32_t>(message[at + 1]) << 16) |
(static_cast<std::uint32_t>(message[at + 2]) << 8) |
static_cast<std::uint32_t>(message[at + 3]);
}
for (std::size_t i = 16; i < 64; ++i) {
const std::uint32_t s0 = detail::rotr(w[i - 15], 7) ^
detail::rotr(w[i - 15], 18) ^ (w[i - 15] >> 3);
const std::uint32_t s1 = detail::rotr(w[i - 2], 17) ^
detail::rotr(w[i - 2], 19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
}
std::uint32_t a = h[0], b = h[1], c = h[2], d = h[3];
std::uint32_t e = h[4], f = h[5], g = h[6], hh = h[7];
for (std::size_t i = 0; i < 64; ++i) {
const std::uint32_t s1 = detail::rotr(e, 6) ^ detail::rotr(e, 11) ^
detail::rotr(e, 25);
const std::uint32_t choose = (e & f) ^ (~e & g);
const std::uint32_t t1 = hh + s1 + choose + k[i] + w[i];
const std::uint32_t s0 = detail::rotr(a, 2) ^ detail::rotr(a, 13) ^
detail::rotr(a, 22);
const std::uint32_t majority = (a & b) ^ (a & c) ^ (b & c);
const std::uint32_t t2 = s0 + majority;
hh = g; g = f; f = e; e = d + t1;
d = c; c = b; b = a; a = t1 + t2;
}
h[0] += a; h[1] += b; h[2] += c; h[3] += d;
h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
}
Digest digest{};
for (std::size_t i = 0; i < 8; ++i) {
digest[i * 4] = static_cast<std::uint8_t>(h[i] >> 24);
digest[i * 4 + 1] = static_cast<std::uint8_t>(h[i] >> 16);
digest[i * 4 + 2] = static_cast<std::uint8_t>(h[i] >> 8);
digest[i * 4 + 3] = static_cast<std::uint8_t>(h[i]);
}
return digest;
}
inline Bytes toBytes(const std::string& text)
{
return Bytes(text.begin(), text.end());
}
inline Digest hmacSha256(const Bytes& key, const Bytes& message)
{
Bytes block(64, 0);
if (key.size() > 64) {
const Digest hashed = sha256(key);
std::copy(hashed.begin(), hashed.end(), block.begin());
} else {
std::copy(key.begin(), key.end(), block.begin());
}
Bytes inner(64), outer(64);
for (std::size_t i = 0; i < 64; ++i) {
inner[i] = block[i] ^ 0x36;
outer[i] = block[i] ^ 0x5c;
}
inner.insert(inner.end(), message.begin(), message.end());
const Digest innerDigest = sha256(inner);
outer.insert(outer.end(), innerDigest.begin(), innerDigest.end());
return sha256(outer);
}
inline std::string hexEncode(const std::uint8_t* data, std::size_t size)
{
static const char digits[] = "0123456789abcdef";
std::string result;
result.reserve(size * 2);
for (std::size_t i = 0; i < size; ++i) {
result.push_back(digits[data[i] >> 4]);
result.push_back(digits[data[i] & 0x0f]);
}
return result;
}
inline std::string hexEncode(const Bytes& bytes)
{
return hexEncode(bytes.data(), bytes.size());
}
inline bool hexDecode(const std::string& text, Bytes& out)
{
if (text.size() % 2 != 0) return false;
auto nibble = [](char c) -> int {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
};
out.clear();
out.reserve(text.size() / 2);
for (std::size_t i = 0; i < text.size(); i += 2) {
const int high = nibble(text[i]);
const int low = nibble(text[i + 1]);
if (high < 0 || low < 0) return false;
out.push_back(static_cast<std::uint8_t>(high * 16 + low));
}
return true;
}
// Compares in time independent of where the first difference occurs.
inline bool constantTimeEquals(const std::string& left, const std::string& right)
{
if (left.size() != right.size()) return false;
std::uint8_t difference = 0;
for (std::size_t i = 0; i < left.size(); ++i)
difference |= static_cast<std::uint8_t>(left[i] ^ right[i]);
return difference == 0;
}
// 32 bytes from the OS entropy source, hex encoded (64 characters).
inline std::string generateSessionSecretHex()
{
std::random_device device;
Bytes secret(kSessionSecretBytes);
for (std::size_t i = 0; i < secret.size(); i += 4) {
const std::uint32_t value = device();
for (std::size_t j = 0; j < 4 && i + j < secret.size(); ++j)
secret[i + j] = static_cast<std::uint8_t>(value >> (8 * j));
}
return hexEncode(secret);
}
// ---- App pepper ----------------------------------------------------------
// The pepper is never present as one contiguous constant: three masked
// fragments live in separate functions and are recombined at run time. This
// only raises the cost of extracting it from the binary; anything shipped to
// the client can ultimately be recovered, so signatures deter casual
// tampering and replay, not a determined reverse engineer.
#if defined(_MSC_VER)
#define FRG_AUTH_NOINLINE __declspec(noinline)
#else
#define FRG_AUTH_NOINLINE __attribute__((noinline))
#endif
namespace detail {
FRG_AUTH_NOINLINE inline Bytes ppc()
{
static const std::uint8_t masked[] = {0x6f, 0x5d, 0xe1, 0x07, 0x3b, 0xc4, 0x01, 0x1c, 0x92, 0x34, 0x12};
Bytes out;
for (std::size_t i = 0; i < sizeof(masked); ++i)
out.push_back(static_cast<std::uint8_t>(masked[i] ^ (0x5a + i * 7)));
return out;
}
FRG_AUTH_NOINLINE inline Bytes ppb()
{
static const std::uint8_t masked[] = {0xbb, 0xfa, 0x84, 0x10, 0x6c, 0xa0, 0xd3, 0x48, 0x0e, 0xb0, 0x71};
Bytes out;
for (std::size_t i = 0; i < sizeof(masked); ++i)
out.push_back(static_cast<std::uint8_t>(masked[i] ^ (0xc3 - i * 11)));
return out;
}
FRG_AUTH_NOINLINE inline Bytes ppa()
{
static const std::uint8_t masked[] = {0xc8, 0x09, 0x31, 0xf4, 0xf1, 0x80, 0xe5, 0x5b, 0x9d, 0x03};
Bytes out;
for (std::size_t i = 0; i < sizeof(masked); ++i)
out.push_back(static_cast<std::uint8_t>(masked[i] ^ (0x19 + i * 13)));
return out;
}
} // namespace detail
inline Bytes appPepper()
{
Bytes a = detail::ppc();
const Bytes b = detail::ppb();
const Bytes c = detail::bba();
// Interleave instead of concatenating so no fragment order is obvious.
Bytes pepper;
const std::size_t longest = (std::max)({a.size(), b.size(), c.size()});
for (std::size_t i = 0; i < longest; ++i) {
if (i < a.size()) pepper.push_back(a[i]);
if (i < b.size()) pepper.push_back(b[i]);
if (i < c.size()) pepper.push_back(c[i]);
}
return pepper;
}
// key(seq) = SHA-256(sessionSecret || pepper || big-endian seq)
inline Bytes deriveMessageKey(
const Bytes& sessionSecret, const Bytes& pepper, std::uint64_t sequence)
{
Bytes material = sessionSecret;
material.insert(material.end(), pepper.begin(), pepper.end());
for (int shift = 56; shift >= 0; shift -= 8)
material.push_back(static_cast<std::uint8_t>(sequence >> shift));
const Digest key = sha256(material);
return Bytes(key.begin(), key.end());
}
} // namespace auth
} // namespace FRG
+115 -1
View File
@@ -1,4 +1,6 @@
#include "NetworkProtocol.h"
#include "MessageAuth.h"
#include <algorithm>
#include <cmath>
#include <exception>
#include <iomanip>
@@ -165,10 +167,79 @@ std::string makeInitialStateMessage(const InitialStateMessage& message)
{"snapshotTick", message.snapshotTick},
{"tickMs", message.tickMs},
{"inputDelayTicks", message.inputDelayTicks},
{"compatibilityFingerprint", message.compatibilityFingerprint}
{"compatibilityFingerprint", message.compatibilityFingerprint},
{"sessionSecret", message.sessionSecret}
});
}
namespace {
std::string signedText(
const std::string& type, std::uint64_t sequence,
const nlohmann::json& payload)
{
return type + "|" + std::to_string(sequence) + "|" + payload.dump();
}
std::string computeSignature(
const std::string& sessionSecretHex, std::uint64_t sequence,
const std::string& text)
{
auth::Bytes secret;
if (!auth::hexDecode(sessionSecretHex, secret) ||
secret.size() != auth::kSessionSecretBytes)
return {};
const auth::Bytes key =
auth::deriveMessageKey(secret, auth::appPepper(), sequence);
const auth::Digest mac = auth::hmacSha256(key, auth::toBytes(text));
return auth::hexEncode(mac.data(), mac.size());
}
} // namespace
std::string signInputMessage(
const std::string& unsignedMessage, const std::string& sessionSecretHex)
{
nlohmann::json message = nlohmann::json::parse(unsignedMessage);
const nlohmann::json& payload = message.at("payload");
const std::uint64_t sequence = payload.at("clientSequence").get<std::uint64_t>();
message["signature"] = computeSignature(
sessionSecretHex, sequence,
signedText(message.at("type").get<std::string>(), sequence, payload));
return message.dump();
}
bool verifyInputMessage(
const std::string& text, const std::string& sessionSecretHex,
std::uint64_t& clientSequence, std::string& error)
{
try {
const nlohmann::json message = nlohmann::json::parse(text);
if (!message.is_object() || !message.contains("payload") ||
!message["payload"].is_object() || !message.contains("type") ||
!message["type"].is_string() || !message.contains("signature") ||
!message["signature"].is_string()) {
error = "unsigned or malformed message";
return false;
}
const nlohmann::json& payload = message["payload"];
if (!readTick(payload, "clientSequence", clientSequence, error))
return false;
const std::string expected = computeSignature(
sessionSecretHex, clientSequence,
signedText(message["type"].get<std::string>(), clientSequence, payload));
if (expected.empty() ||
!auth::constantTimeEquals(
expected, message["signature"].get<std::string>())) {
error = "invalid signature";
return false;
}
error.clear();
return true;
} catch (const std::exception& exception) {
error = exception.what();
return false;
}
}
bool parseInitialStateMessage(
const std::string& text, InitialStateMessage& message, std::string& error)
{
@@ -191,6 +262,20 @@ bool parseInitialStateMessage(
error = "unsupported lockstep timing";
return false;
}
if (!payload.contains("sessionSecret") ||
!payload["sessionSecret"].is_string()) {
error = "initial state is missing the session secret";
return false;
}
message.sessionSecret = payload["sessionSecret"].get<std::string>();
{
auth::Bytes decoded;
if (!auth::hexDecode(message.sessionSecret, decoded) ||
decoded.size() != auth::kSessionSecretBytes) {
error = "invalid session secret";
return false;
}
}
message.state = payload["state"];
message.assignedPlayerId = payload["assignedPlayerId"].get<std::string>();
message.compatibilityFingerprint =
@@ -198,10 +283,37 @@ bool parseInitialStateMessage(
return !message.assignedPlayerId.empty();
}
namespace {
bool isOrderCommand(const ScheduledCommand& command, const std::string& playerId)
{
if (const auto* destination = std::get_if<ScheduledDestinationCommand>(&command))
return destination->playerId == playerId;
if (const auto* action = std::get_if<ScheduledCharacterActionCommand>(&command))
return action->playerId == playerId &&
(action->action == "set_target" ||
action->action == "clear_attack_target");
return false;
}
// Within one tick only the player's last order (destination, set_target or
// clear_attack_target) survives; combos and presence commands are untouched.
void dropSupersededOrders(
std::vector<ScheduledCommand>& commands, const std::string& playerId)
{
commands.erase(
std::remove_if(commands.begin(), commands.end(),
[&](const ScheduledCommand& command) {
return isOrderCommand(command, playerId);
}),
commands.end());
}
} // namespace
std::uint64_t LockstepTimeline::schedule(
const std::string& playerId, const Vec3fp& target)
{
const std::uint64_t sequence = nextCommandSequence_++;
dropSupersededOrders(pending_[currentTick_ + inputDelayTicks_], playerId);
pending_[currentTick_ + inputDelayTicks_].push_back(
ScheduledDestinationCommand{sequence, playerId, target});
return sequence;
@@ -222,6 +334,8 @@ std::uint64_t LockstepTimeline::scheduleCharacterAction(
const std::string& playerId, std::string action, std::string targetId)
{
const std::uint64_t sequence = nextCommandSequence_++;
if (action == "set_target" || action == "clear_attack_target")
dropSupersededOrders(pending_[currentTick_ + inputDelayTicks_], playerId);
pending_[currentTick_ + inputDelayTicks_].push_back(
ScheduledCharacterActionCommand{
sequence, playerId, std::move(action), std::move(targetId)});
+18
View File
@@ -22,8 +22,14 @@ struct InitialStateMessage {
std::int64_t tickMs = kSimulationTickMs;
std::uint32_t inputDelayTicks = kDefaultInputDelayTicks;
std::string compatibilityFingerprint;
// 32 random bytes (64 hex chars) issued per connection; used with the app
// pepper to derive per-message HMAC keys.
std::string sessionSecret;
};
// Server-side limit on client messages; exceeding it gets the player kicked.
inline constexpr std::size_t kMaxCommandsPerSecond = 20;
struct DestinationInputMessage {
std::uint64_t clientSequence = 0;
Vec3fp target;
@@ -101,6 +107,18 @@ std::string makeCharacterActionInputMessage(
bool parseCharacterActionInputMessage(
const std::string& text, CharacterActionInputMessage& message,
std::string& error);
// Adds an HMAC-SHA256 "signature" to a client input envelope. The key is
// SHA-256(sessionSecret || appPepper || clientSequence); the signed text is
// "type|clientSequence|payload". Unsigned make*InputMessage output is what the
// parse* functions consume, so signing is layered on top.
std::string signInputMessage(
const std::string& unsignedMessage, const std::string& sessionSecretHex);
// Verifies the signature and extracts the clientSequence. Returns false (with
// an error) for a missing/invalid signature or malformed envelope.
bool verifyInputMessage(
const std::string& text, const std::string& sessionSecretHex,
std::uint64_t& clientSequence, std::string& error);
std::string makeTickMessage(const TickMessage& message);
bool parseTickMessage(
const std::string& text, TickMessage& message, std::string& error);
+26 -32
View File
@@ -1,5 +1,6 @@
#include "WebsocketGameClient.h"
#include "NetworkProtocol.h"
#include "LockstepApply.h"
#include "../utils/Utils.h"
#ifdef __EMSCRIPTEN__
#include <emscripten/websocket.h>
@@ -408,8 +409,14 @@ private:
buffer_,
[this](beast::error_code error, std::size_t) {
if (error) {
connected_.store(false);
if (error != websocket::error::closed) fail("read", error);
// A clean close is also a lost connection for the game.
if (error == websocket::error::closed) {
connected_.store(false);
connectionFailed_.store(true);
std::cerr << "[network] Server closed the connection\n";
} else {
fail("read", error);
}
return;
}
std::string message = beast::buffers_to_string(buffer_.data());
@@ -497,18 +504,18 @@ void WebsocketGameClient::submit(const GameCommand& command)
if (!initialized_) return;
if (const auto* destination =
std::get_if<SetCharacterDestinationCommand>(&command)) {
impl_->send(makeDestinationInputMessage(
{nextClientSequence_++, destination->target}));
impl_->send(signInputMessage(makeDestinationInputMessage(
{nextClientSequence_++, destination->target}), sessionSecret_));
} else if (const auto* target =
std::get_if<SetCharacterTargetCommand>(&command)) {
impl_->send(makeCharacterActionInputMessage(
{nextClientSequence_++, "set_target", target->targetId}));
impl_->send(signInputMessage(makeCharacterActionInputMessage(
{nextClientSequence_++, "set_target", target->targetId}), sessionSecret_));
} else if (std::holds_alternative<ClearCharacterAttackTargetCommand>(command)) {
impl_->send(makeCharacterActionInputMessage(
{nextClientSequence_++, "clear_attack_target", {}}));
impl_->send(signInputMessage(makeCharacterActionInputMessage(
{nextClientSequence_++, "clear_attack_target", {}}), sessionSecret_));
} else if (std::holds_alternative<TryCharacterAttackComboCommand>(command)) {
impl_->send(makeCharacterActionInputMessage(
{nextClientSequence_++, "try_attack_combo", {}}));
impl_->send(signInputMessage(makeCharacterActionInputMessage(
{nextClientSequence_++, "try_attack_combo", {}}), sessionSecret_));
}
}
@@ -533,12 +540,15 @@ void WebsocketGameClient::update(std::int64_t)
logger() << "[network] Incompatible server content: expected "
<< expectedCompatibilityFingerprint_ << ", received "
<< initial.compatibilityFingerprint << '\n';
rejected_ = true;
continue;
}
try {
replica_.load(initial.state);
replica_.setLocalPlayerId(initial.assignedPlayerId);
nextExpectedTick_ = initial.snapshotTick + 1;
sessionSecret_ = std::move(initial.sessionSecret);
nextClientSequence_ = 1;
compatibilityFingerprint_ =
std::move(initial.compatibilityFingerprint);
pendingTicks_.clear();
@@ -570,8 +580,9 @@ void WebsocketGameClient::update(std::int64_t)
if (parseErrorMessage(text, errorCode, errorDetail)) {
logger() << "[network] Server rejected request (" << errorCode
<< "): " << errorDetail << '\n';
if (errorCode == "server_full" ||
errorCode == "incompatible")
// Everything except a recoverable malformed-input report ends the
// session (server_full, incompatible, rate_limited, kicked, ...).
if (errorCode != "invalid_input")
rejected_ = true;
continue;
}
@@ -587,25 +598,7 @@ void WebsocketGameClient::update(std::int64_t)
const std::string locationId =
replica_.snapshot()->currentLocationId;
for (const ScheduledCommand& scheduled : tick.commands) {
std::visit([&](const auto& command) {
using T = std::decay_t<decltype(command)>;
if constexpr (std::is_same_v<T, ScheduledDestinationCommand>) {
replica_.submit(SetCharacterDestinationCommand{
locationId, command.playerId, command.target, {}});
} else if constexpr (std::is_same_v<T, ScheduledCharacterEnabledCommand>) {
replica_.submit(SetCharacterEnabledCommand{
command.locationId, command.characterId, command.enabled});
} else if (command.action == "set_target") {
replica_.submit(SetCharacterTargetCommand{
locationId, command.playerId, command.targetId});
} else if (command.action == "clear_attack_target") {
replica_.submit(ClearCharacterAttackTargetCommand{
locationId, command.playerId});
} else if (command.action == "try_attack_combo") {
replica_.submit(TryCharacterAttackComboCommand{
locationId, command.playerId});
}
}, scheduled);
applyScheduledCommand(replica_, locationId, scheduled);
}
replica_.update(kSimulationTickMs);
completedSimulationTicks_.push_back({
@@ -655,7 +648,8 @@ bool WebsocketGameClient::connected() const
bool WebsocketGameClient::connectionFailed() const
{
return impl_->connectionFailed();
// Rejection (server full / incompatible content) is also a failed connection.
return rejected_ || impl_->connectionFailed();
}
} // namespace FRG
+1
View File
@@ -68,6 +68,7 @@ private:
std::uint64_t nextExpectedTick_ = 0;
std::uint64_t nextClientSequence_ = 1;
std::string compatibilityFingerprint_;
std::string sessionSecret_;
std::string expectedCompatibilityFingerprint_;
bool initialized_ = false;
bool rejected_ = false;
+81 -25
View File
@@ -1,9 +1,12 @@
#include "WebsocketGameServer.h"
#include "InternalGameServer.h"
#include "NetworkProtocol.h"
#include "LockstepApply.h"
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include "MessageAuth.h"
#include <algorithm>
#include <chrono>
#include <deque>
#include <iostream>
#include <map>
@@ -30,16 +33,53 @@ public:
std::function<void(const std::shared_ptr<ServerSession>&)>;
ServerSession(
tcp::socket socket, std::string playerId,
tcp::socket socket, std::string playerId, std::string sessionSecret,
InputHandler inputHandler, CloseHandler closeHandler)
: socket_(std::move(socket))
, playerId_(std::move(playerId))
, sessionSecret_(std::move(sessionSecret))
, inputHandler_(std::move(inputHandler))
, closeHandler_(std::move(closeHandler))
{
}
const std::string& playerId() const { return playerId_; }
const std::string& sessionSecret() const { return sessionSecret_; }
bool kicked() const { return kicked_; }
// Counts one received message in a sliding one-second window. Returns false
// once the player exceeds kMaxCommandsPerSecond.
bool allowMessage()
{
const auto now = std::chrono::steady_clock::now();
while (!recentMessages_.empty() &&
now - recentMessages_.front() > std::chrono::seconds(1))
recentMessages_.pop_front();
recentMessages_.push_back(now);
return recentMessages_.size() <= kMaxCommandsPerSecond;
}
// Accepts only strictly increasing sequence numbers (replay protection).
bool acceptSequence(std::uint64_t sequence)
{
if (sequence <= lastSequence_) return false;
lastSequence_ = sequence;
return true;
}
// Sends a final error, ignores all further input and ticks, then closes.
// Closing releases the slot, so the character is disabled for everyone.
void kick(const std::string& code, const std::string& detail)
{
if (kicked_ || closed_) return;
kicked_ = true;
std::cout << "[network] Kicking player slot '" << playerId_ << "' ("
<< code << "): " << detail << std::endl;
closeAfterWrite_ = true;
const bool writeInProgress = !outbound_.empty();
outbound_.push_back(makeErrorMessage(code, detail));
if (!writeInProgress) write();
}
void start(std::string initialState, bool closeAfterWrite = false)
{
@@ -62,6 +102,7 @@ public:
void send(std::string message)
{
if (closed_ || kicked_) return;
const bool writeInProgress = !outbound_.empty();
outbound_.push_back(std::move(message));
if (!writeInProgress) write();
@@ -83,7 +124,9 @@ private:
const std::string message =
beast::buffers_to_string(self->inbound_.data());
self->inbound_.consume(self->inbound_.size());
if (self->kicked_) return;
self->inputHandler_(self, message);
if (self->kicked_) return;
self->read();
});
}
@@ -96,6 +139,11 @@ private:
if (error) {
std::cerr << "[network] WebSocket write failed: "
<< error.message() << '\n';
// Release the slot and stop queueing ticks for a dead peer.
self->outbound_.clear();
beast::error_code ignored;
beast::get_lowest_layer(self->socket_).close(ignored);
self->notifyClosed();
return;
}
self->outbound_.pop_front();
@@ -120,10 +168,14 @@ private:
beast::flat_buffer inbound_;
std::deque<std::string> outbound_;
std::string playerId_;
std::string sessionSecret_;
std::deque<std::chrono::steady_clock::time_point> recentMessages_;
std::uint64_t lastSequence_ = 0;
InputHandler inputHandler_;
CloseHandler closeHandler_;
bool closeAfterWrite_ = false;
bool closed_ = false;
bool kicked_ = false;
};
} // namespace
@@ -224,11 +276,30 @@ private:
break;
}
}
const std::string sessionSecret = auth::generateSessionSecretHex();
auto session =
std::make_shared<ServerSession>(
std::move(socket), playerId,
std::move(socket), playerId, sessionSecret,
[this](const std::shared_ptr<ServerSession>& source,
const std::string& message) {
if (!source->allowMessage()) {
source->kick("rate_limited",
"Too many commands per second");
return;
}
std::uint64_t signedSequence = 0;
std::string authError;
if (!verifyInputMessage(
message, source->sessionSecret(),
signedSequence, authError)) {
source->kick("invalid_signature", authError);
return;
}
if (!source->acceptSequence(signedSequence)) {
source->kick("replayed_message",
"Message sequence did not increase");
return;
}
DestinationInputMessage destination;
std::string destinationError;
if (parseDestinationInputMessage(
@@ -283,6 +354,7 @@ private:
initial.snapshotTick = latestTick_;
initial.compatibilityFingerprint =
compatibilityFingerprint_;
initial.sessionSecret = sessionSecret;
session->start(makeInitialStateMessage(initial));
std::cout << "[network] Initial state queued for player '"
<< playerId << "'" << std::endl;
@@ -341,6 +413,11 @@ void WebsocketGameServer::update()
lastClientSequences_.erase(playerId);
for (const Impl::PendingInput& pending : impl_->takeInputs()) {
std::uint64_t& previous = lastClientSequences_[pending.playerId];
// Input queued before the slot was released must not reach a disabled
// character.
if (std::find(releasedPlayers.begin(), releasedPlayers.end(),
pending.playerId) != releasedPlayers.end())
continue;
const std::uint64_t sequence = std::visit(
[](const auto& input) { return input.clientSequence; },
pending.input);
@@ -359,29 +436,8 @@ void WebsocketGameServer::update()
TickMessage tick = timeline_.advance();
for (const ScheduledCommand& scheduled : tick.commands) {
std::visit([this](const auto& command) {
using T = std::decay_t<decltype(command)>;
if constexpr (std::is_same_v<T, ScheduledDestinationCommand>) {
gameServer_.submit(SetCharacterDestinationCommand{
gameServer_.snapshot()->currentLocationId,
command.playerId, command.target, {}});
} else if constexpr (std::is_same_v<T, ScheduledCharacterEnabledCommand>) {
gameServer_.submit(SetCharacterEnabledCommand{
command.locationId, command.characterId, command.enabled});
} else if (command.action == "set_target") {
gameServer_.submit(SetCharacterTargetCommand{
gameServer_.snapshot()->currentLocationId,
command.playerId, command.targetId});
} else if (command.action == "clear_attack_target") {
gameServer_.submit(ClearCharacterAttackTargetCommand{
gameServer_.snapshot()->currentLocationId,
command.playerId});
} else if (command.action == "try_attack_combo") {
gameServer_.submit(TryCharacterAttackComboCommand{
gameServer_.snapshot()->currentLocationId,
command.playerId});
}
}, scheduled);
applyScheduledCommand(
gameServer_, gameServer_.snapshot()->currentLocationId, scheduled);
}
gameServer_.update(kSimulationTickMs);
nlohmann::json state;