Files
shadow-over-bishkek001/src/game_server/WebsocketGameClient.cpp
T

656 lines
18 KiB
C++

#include "WebsocketGameClient.h"
#include "NetworkProtocol.h"
#include "LockstepApply.h"
#include "../utils/Utils.h"
#ifdef __EMSCRIPTEN__
#include <emscripten/websocket.h>
#else
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#ifdef NETWORK_TLS
#include <wincrypt.h>
// wincrypt.h defines macros that collide with OpenSSL identifiers.
#undef X509_NAME
#undef X509_EXTENSIONS
#undef X509_CERT_PAIR
#undef PKCS7_ISSUER_AND_SERIAL
#undef OCSP_REQUEST
#undef OCSP_RESPONSE
#include <boost/asio/ssl.hpp>
#include <boost/beast/ssl.hpp>
#include <openssl/err.h>
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>
#endif
#endif
#include <atomic>
#include <deque>
#include <iostream>
#include <mutex>
#include <thread>
#include <type_traits>
#include <utility>
#include <vector>
namespace FRG {
namespace {
#ifndef __EMSCRIPTEN__
namespace asio = boost::asio;
namespace beast = boost::beast;
namespace websocket = beast::websocket;
using tcp = asio::ip::tcp;
#ifdef NETWORK_TLS
// Loads the Windows "ROOT" certificate store into the OpenSSL context.
void loadWindowsRootCertificates(asio::ssl::context& context)
{
HCERTSTORE store = CertOpenSystemStoreA(0, "ROOT");
if (!store) {
std::cerr << "[network] Could not open the Windows root certificate store\n";
return;
}
X509_STORE* x509Store = SSL_CTX_get_cert_store(context.native_handle());
PCCERT_CONTEXT cert = nullptr;
while ((cert = CertEnumCertificatesInStore(store, cert)) != nullptr) {
const unsigned char* data = cert->pbCertEncoded;
X509* x509 = d2i_X509(nullptr, &data, static_cast<long>(cert->cbCertEncoded));
if (x509) {
X509_STORE_add_cert(x509Store, x509);
X509_free(x509);
}
}
CertCloseStore(store, 0);
}
// Certificate problems are logged but deliberately do not abort the connection.
bool logAndAcceptCertificate(bool preverified, asio::ssl::verify_context& context)
{
if (!preverified) {
X509_STORE_CTX* storeContext = context.native_handle();
const int error = X509_STORE_CTX_get_error(storeContext);
const int depth = X509_STORE_CTX_get_error_depth(storeContext);
char subject[256] = "?";
if (X509* cert = X509_STORE_CTX_get_current_cert(storeContext))
X509_NAME_oneline(X509_get_subject_name(cert), subject, sizeof(subject));
std::cerr << "[network] TLS certificate warning (depth " << depth
<< ", subject " << subject << "): "
<< X509_verify_cert_error_string(error)
<< " - continuing anyway\n";
}
return true;
}
#endif
#endif
} // namespace
bool WebsocketEndpoint::parse(const std::string& url)
{
bool tls = false;
std::string rest;
if (url.rfind("wss://", 0) == 0) {
tls = true;
rest = url.substr(6);
} else if (url.rfind("ws://", 0) == 0) {
rest = url.substr(5);
} else {
return false;
}
std::string authority = rest;
std::string newPath = "/";
const std::size_t slash = rest.find('/');
if (slash != std::string::npos) {
authority = rest.substr(0, slash);
newPath = rest.substr(slash);
}
std::string newHost = authority;
std::string newPort = tls ? "443" : "80";
if (!authority.empty() && authority.front() == '[') { // [ipv6]:port
const std::size_t close = authority.find(']');
if (close == std::string::npos) return false;
newHost = authority.substr(1, close - 1);
if (close + 1 < authority.size()) {
if (authority[close + 1] != ':') return false;
newPort = authority.substr(close + 2);
}
} else {
const std::size_t colon = authority.rfind(':');
if (colon != std::string::npos) {
newHost = authority.substr(0, colon);
newPort = authority.substr(colon + 1);
}
}
if (newHost.empty() || newPort.empty()) return false;
host = std::move(newHost);
port = std::move(newPort);
path = std::move(newPath);
useTls = tls;
return true;
}
class WebsocketGameClient::Impl {
public:
#ifdef __EMSCRIPTEN__
Impl(std::string host, std::string port, std::string path, bool useTls)
: host_(std::move(host))
, port_(std::move(port))
, path_(std::move(path))
{
url_ = std::string(useTls ? "wss://" : "ws://") + host_ + ':' + port_ +
(path_.empty() || path_.front() == '/' ? path_ : "/" + path_);
std::cout << "[network] Opening " << url_ << std::endl;
EmscriptenWebSocketCreateAttributes attributes = {};
attributes.url = url_.c_str();
attributes.protocols = nullptr;
attributes.createOnMainThread = EM_TRUE;
socket_ = emscripten_websocket_new(&attributes);
if (socket_ <= 0) {
fail("create WebSocket", socket_);
return;
}
emscripten_websocket_set_onopen_callback(
socket_, this, &Impl::onOpen);
emscripten_websocket_set_onerror_callback(
socket_, this, &Impl::onError);
emscripten_websocket_set_onclose_callback(
socket_, this, &Impl::onClose);
emscripten_websocket_set_onmessage_callback(
socket_, this, &Impl::onMessage);
}
~Impl()
{
if (socket_ > 0) {
closing_ = true;
emscripten_websocket_close(socket_, 1000, "client shutdown");
emscripten_websocket_delete(socket_);
}
}
std::vector<std::string> takeMessages()
{
std::vector<std::string> result;
result.swap(messages_);
return result;
}
bool connected() const { return connected_; }
bool connectionFailed() const { return connectionFailed_; }
void send(std::string message)
{
if (!connected_ || socket_ <= 0) return;
const EMSCRIPTEN_RESULT result =
emscripten_websocket_send_utf8_text(socket_, message.c_str());
if (result != EMSCRIPTEN_RESULT_SUCCESS)
fail("send WebSocket message");
}
private:
static EM_BOOL onOpen(
int, const EmscriptenWebSocketOpenEvent*, void* userData)
{
auto* self = static_cast<Impl*>(userData);
self->connected_ = true;
std::cout << "[network] Connected to " << self->url_ << std::endl;
return EM_TRUE;
}
static EM_BOOL onError(
int, const EmscriptenWebSocketErrorEvent*, void* userData)
{
static_cast<Impl*>(userData)->fail("WebSocket");
return EM_TRUE;
}
static EM_BOOL onClose(
int, const EmscriptenWebSocketCloseEvent* event, void* userData)
{
auto* self = static_cast<Impl*>(userData);
self->connected_ = false;
if (!self->closing_) {
std::cerr << "[network] WebSocket closed";
if (event) {
std::cerr << " (code " << event->code;
if (event->reason[0] != '\0')
std::cerr << ", reason: " << event->reason;
std::cerr << ')';
}
std::cerr << '\n';
self->connectionFailed_ = true;
}
return EM_TRUE;
}
static EM_BOOL onMessage(
int, const EmscriptenWebSocketMessageEvent* event, void* userData)
{
auto* self = static_cast<Impl*>(userData);
if (!event || event->isText != EM_TRUE) {
self->fail("binary WebSocket message");
return EM_TRUE;
}
self->messages_.emplace_back(
reinterpret_cast<const char*>(event->data), event->numBytes);
return EM_TRUE;
}
void fail(const char* operation, int result = 0)
{
connected_ = false;
connectionFailed_ = true;
std::cerr << "[network] " << operation << " failed";
if (result != 0) std::cerr << " (result " << result << ')';
std::cerr << std::endl;
}
std::string host_;
std::string port_;
std::string path_;
std::string url_;
EMSCRIPTEN_WEBSOCKET_T socket_ = 0;
bool connected_ = false;
bool connectionFailed_ = false;
bool closing_ = false;
std::vector<std::string> messages_;
#else
Impl(std::string host, std::string port, std::string path, bool useTls)
:
#ifdef NETWORK_TLS
sslContext_(asio::ssl::context::tls_client)
, resolver_(io_)
, secureSocket_(io_, sslContext_)
#else
resolver_(io_)
#endif
, socket_(io_)
, host_(std::move(host))
, port_(std::move(port))
, path_(std::move(path))
, useTls_(useTls)
{
#ifdef NETWORK_TLS
sslContext_.set_options(
asio::ssl::context::default_workarounds |
asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3 |
asio::ssl::context::no_tlsv1 | asio::ssl::context::no_tlsv1_1);
loadWindowsRootCertificates(sslContext_);
sslContext_.set_verify_mode(asio::ssl::verify_peer);
sslContext_.set_verify_callback(&logAndAcceptCertificate);
#else
if (useTls_) {
std::cerr << "[network] wss:// requested but TLS support was not "
"compiled in (NETWORK_TLS)" << std::endl;
connectionFailed_.store(true);
return;
}
#endif
std::cout << "[network] Resolving " << scheme() << host_ << ':' << port_
<< path_ << std::endl;
resolve();
thread_ = std::thread([this]() { io_.run(); });
}
~Impl()
{
io_.stop();
if (thread_.joinable()) thread_.join();
}
std::vector<std::string> takeMessages()
{
std::lock_guard<std::mutex> lock(messagesMutex_);
std::vector<std::string> result;
result.swap(messages_);
return result;
}
bool connected() const { return connected_.load(); }
bool connectionFailed() const { return connectionFailed_.load(); }
void send(std::string message)
{
asio::post(io_, [this, message = std::move(message)]() mutable {
if (!connected_.load()) return;
const bool writeInProgress = !outbound_.empty();
outbound_.push_back(std::move(message));
if (!writeInProgress) write();
});
}
private:
const char* scheme() const { return useTls_ ? "wss://" : "ws://"; }
template <class F>
void withStream(F&& f)
{
#ifdef NETWORK_TLS
if (useTls_) {
f(secureSocket_);
return;
}
#endif
f(socket_);
}
void resolve()
{
resolver_.async_resolve(
host_, port_,
[this](beast::error_code error, tcp::resolver::results_type results) {
if (error) return fail("resolve", error);
std::cout << "[network] WebSocket host resolved; connecting"
<< std::endl;
withStream([&](auto& stream) {
asio::async_connect(
beast::get_lowest_layer(stream), results,
[this](beast::error_code connectError,
const tcp::endpoint&) {
if (connectError) return fail("connect", connectError);
std::cout << "[network] TCP connected" << std::endl;
startTlsOrWebsocketHandshake();
});
});
});
}
void startTlsOrWebsocketHandshake()
{
#ifdef NETWORK_TLS
if (useTls_) {
SSL* ssl = secureSocket_.next_layer().native_handle();
// SNI, and hostname verification (failures are only logged).
SSL_set_tlsext_host_name(ssl, const_cast<char*>(host_.c_str()));
SSL_set1_host(ssl, host_.c_str());
std::cout << "[network] Starting TLS handshake" << std::endl;
secureSocket_.next_layer().async_handshake(
asio::ssl::stream_base::client,
[this](beast::error_code tlsError) {
if (tlsError) return fail("TLS handshake", tlsError);
std::cout << "[network] TLS established" << std::endl;
startWebsocketHandshake();
});
return;
}
#endif
startWebsocketHandshake();
}
void startWebsocketHandshake()
{
const bool defaultPort = port_ == (useTls_ ? "443" : "80");
const std::string hostHeader = defaultPort ? host_ : host_ + ':' + port_;
std::cout << "[network] Starting WebSocket handshake" << std::endl;
withStream([&](auto& stream) {
stream.set_option(
websocket::stream_base::timeout::suggested(
beast::role_type::client));
stream.async_handshake(
hostHeader, path_,
[this](beast::error_code handshakeError) {
if (handshakeError)
return fail("handshake", handshakeError);
connected_.store(true);
std::cout
<< "[network] Connected to " << scheme()
<< host_ << ':' << port_ << path_ << std::endl;
read();
});
});
}
void read()
{
withStream([this](auto& stream) {
stream.async_read(
buffer_,
[this](beast::error_code error, std::size_t) {
if (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());
buffer_.consume(buffer_.size());
{
std::lock_guard<std::mutex> lock(messagesMutex_);
messages_.push_back(std::move(message));
}
read();
});
});
}
void write()
{
withStream([this](auto& stream) {
stream.async_write(
asio::buffer(outbound_.front()),
[this](beast::error_code error, std::size_t) {
if (error) return fail("write", error);
outbound_.pop_front();
if (!outbound_.empty()) write();
});
});
}
void fail(const char* operation, beast::error_code error)
{
connected_.store(false);
connectionFailed_.store(true);
std::cerr << "[network] WebSocket " << operation << " failed: "
<< error.message() << '\n';
}
asio::io_context io_;
#ifdef NETWORK_TLS
asio::ssl::context sslContext_;
#endif
tcp::resolver resolver_;
#ifdef NETWORK_TLS
websocket::stream<beast::ssl_stream<tcp::socket>> secureSocket_;
#endif
websocket::stream<tcp::socket> socket_;
beast::flat_buffer buffer_;
std::thread thread_;
std::string host_;
std::string port_;
std::string path_;
bool useTls_ = false;
std::atomic_bool connected_{false};
std::atomic_bool connectionFailed_{false};
std::mutex messagesMutex_;
std::vector<std::string> messages_;
std::deque<std::string> outbound_;
#endif
};
WebsocketGameClient::WebsocketGameClient(
std::string host, std::string port, std::string path, bool useTls)
: impl_(std::make_unique<Impl>(
std::move(host), std::move(port), std::move(path), useTls))
{
}
WebsocketGameClient::WebsocketGameClient(const WebsocketEndpoint& endpoint)
: WebsocketGameClient(
endpoint.host, endpoint.port, endpoint.path, endpoint.useTls)
{
}
WebsocketGameClient::~WebsocketGameClient() = default;
std::shared_ptr<const GameSnapshot> WebsocketGameClient::snapshot() const
{
return replica_.snapshot();
}
const std::string& WebsocketGameClient::localPlayerId() const
{
return replica_.localPlayerId();
}
void WebsocketGameClient::submit(const GameCommand& command)
{
if (!initialized_) return;
if (const auto* destination =
std::get_if<SetCharacterDestinationCommand>(&command)) {
impl_->send(signInputMessage(makeDestinationInputMessage(
{nextClientSequence_++, destination->target}), sessionSecret_));
} else if (const auto* target =
std::get_if<SetCharacterTargetCommand>(&command)) {
impl_->send(signInputMessage(makeCharacterActionInputMessage(
{nextClientSequence_++, "set_target", target->targetId}), sessionSecret_));
} else if (std::holds_alternative<ClearCharacterAttackTargetCommand>(command)) {
impl_->send(signInputMessage(makeCharacterActionInputMessage(
{nextClientSequence_++, "clear_attack_target", {}}), sessionSecret_));
} else if (std::holds_alternative<TryCharacterAttackComboCommand>(command)) {
impl_->send(signInputMessage(makeCharacterActionInputMessage(
{nextClientSequence_++, "try_attack_combo", {}}), sessionSecret_));
}
}
std::vector<GameServerEvent> WebsocketGameClient::drainEvents()
{
std::vector<GameServerEvent> result;
result.swap(pendingEvents_);
return result;
}
void WebsocketGameClient::update(std::int64_t)
{
std::vector<std::string> messages = impl_->takeMessages();
for (const std::string& text : messages) {
std::string error;
InitialStateMessage initial;
if (parseInitialStateMessage(text, initial, error)) {
//logger() << text << std::endl;
if (!expectedCompatibilityFingerprint_.empty() &&
initial.compatibilityFingerprint !=
expectedCompatibilityFingerprint_) {
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();
initialized_ = true;
logger() << "[network] Applied initial state at tick "
<< initial.snapshotTick << " as player '"
<< initial.assignedPlayerId << "' (delay "
<< initial.inputDelayTicks << " ticks)" << std::endl;
} catch (const std::exception& exception) {
logger() << "[network] Invalid initial state: "
<< exception.what() << '\n';
}
continue;
}
TickMessage tick;
if (parseTickMessage(text, tick, error)) {
if (initialized_ && tick.tickId >= nextExpectedTick_) {
if (!loggedFirstTick_) {
logger() << "[network] Received first lockstep tick "
<< tick.tickId << std::endl;
loggedFirstTick_ = true;
}
pendingTicks_.emplace(tick.tickId, std::move(tick));
}
continue;
}
std::string errorCode;
std::string errorDetail;
if (parseErrorMessage(text, errorCode, errorDetail)) {
logger() << "[network] Server rejected request (" << errorCode
<< "): " << errorDetail << '\n';
// Everything except a recoverable malformed-input report ends the
// session (server_full, incompatible, rate_limited, kicked, ...).
if (errorCode != "invalid_input")
rejected_ = true;
continue;
}
logger() << "[network] Ignoring WebSocket message: "
<< error << '\n';
}
while (initialized_) {
auto next = pendingTicks_.find(nextExpectedTick_);
if (next == pendingTicks_.end()) break;
TickMessage tick = std::move(next->second);
pendingTicks_.erase(next);
const std::string locationId =
replica_.snapshot()->currentLocationId;
for (const ScheduledCommand& scheduled : tick.commands) {
applyScheduledCommand(replica_, locationId, scheduled);
}
replica_.update(kSimulationTickMs);
completedSimulationTicks_.push_back({
replica_.pendingSimulationLocationId_,
replica_.pendingSimulationEvents_});
std::vector<GameServerEvent> events = replica_.drainEvents();
pendingEvents_.insert(
pendingEvents_.end(),
std::make_move_iterator(events.begin()),
std::make_move_iterator(events.end()));
if (!tick.stateHash.empty()) {
nlohmann::json state;
replica_.save(state);
const std::string localHash = canonicalStateHash(std::move(state));
if (localHash != tick.stateHash) {
logger() << "[network] Lockstep divergence at tick "
<< tick.tickId << ": server=" << tick.stateHash
<< ", client=" << localHash << '\n';
}
}
++nextExpectedTick_;
}
}
std::vector<WebsocketGameClient::CompletedSimulationTick>
WebsocketGameClient::takeCompletedSimulationTicks()
{
std::vector<CompletedSimulationTick> result;
result.swap(completedSimulationTicks_);
return result;
}
void WebsocketGameClient::save(nlohmann::json&) const
{
// Persistence remains server-side.
}
void WebsocketGameClient::load(const nlohmann::json&)
{
// Persistence remains server-side.
}
bool WebsocketGameClient::connected() const
{
return impl_->connected();
}
bool WebsocketGameClient::connectionFailed() const
{
// Rejection (server full / incompatible content) is also a failed connection.
return rejected_ || impl_->connectionFailed();
}
} // namespace FRG