Files
OpenRCT2-Web/src/openrct2/network/NetworkBase.cpp
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

4403 lines
141 KiB
C++
Raw Normal View History

2015-02-12 02:01:02 +00:00
/*****************************************************************************
2026-01-05 14:42:59 +01:00
* Copyright (c) 2014-2026 OpenRCT2 developers
2015-02-12 02:01:02 +00:00
*
2018-06-15 14:07:34 +02:00
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
2015-02-12 02:01:02 +00:00
*
2018-06-15 14:07:34 +02:00
* OpenRCT2 is licensed under the GNU General Public License version 3.
2015-02-12 02:01:02 +00:00
*****************************************************************************/
2020-07-26 16:13:46 +02:00
#include "NetworkBase.h"
2018-06-22 23:02:47 +02:00
#include "../Context.h"
2024-07-09 16:23:31 +02:00
#include "../Diagnostic.h"
#include "../Game.h"
#include "../GameState.h"
2019-05-11 21:31:34 +02:00
#include "../GameStateSnapshots.h"
2017-02-08 12:53:00 +00:00
#include "../OpenRCT2.h"
2017-06-06 17:55:13 +01:00
#include "../PlatformEnvironment.h"
#include "../Version.h"
2026-02-09 15:07:42 +01:00
#include "../actions/GameActionRunner.h"
#include "../actions/general/LoadOrQuitAction.h"
#include "../actions/network/NetworkModifyGroupAction.h"
#include "../actions/peep/PeepPickupAction.h"
#include "../core/File.h"
2018-06-22 23:02:47 +02:00
#include "../core/Guard.hpp"
#include "../core/Json.hpp"
#include "../drawing/Drawing.Screen.h"
2021-11-24 16:58:01 +02:00
#include "../entity/EntityRegistry.h"
2021-11-24 16:48:33 +02:00
#include "../entity/EntityTweener.h"
2021-12-11 18:06:06 -05:00
#include "../localisation/Formatter.h"
#include "../localisation/Formatting.h"
#include "../localisation/LocalisationService.h"
#include "../park/ParkFile.h"
2022-02-18 21:57:00 +01:00
#include "../platform/Platform.h"
2019-07-25 22:59:26 +01:00
#include "../scripting/ScriptEngine.h"
#include "../ui/WindowManager.h"
2024-12-15 17:39:52 +01:00
#include "../util/Util.h"
2018-03-19 23:34:37 +01:00
#include "../world/Location.hpp"
#include "../world/MapAnimation.h"
2025-02-24 04:43:06 -05:00
#include "Network.h"
2024-07-09 16:43:03 +02:00
#include <cassert>
2018-11-21 23:16:04 +01:00
#include <iterator>
2018-06-22 23:02:47 +02:00
#include <stdexcept>
// This string specifies which version of network stream current build uses.
// It is used for making sure only compatible builds get connected, even within
// single OpenRCT2 version.
2026-09-06 11:28:06 +02:00
constexpr uint8_t kStreamVersion = 0;
const std::string kStreamID = std::string(kOpenRCT2Version) + "-" + std::to_string(kStreamVersion);
static OpenRCT2::Peep* _pickup_peep = nullptr;
2024-07-26 18:23:25 +10:00
static int32_t _pickup_peep_old_x = kLocationNull;
2016-10-17 14:26:19 -06:00
#ifndef DISABLE_NETWORK
2019-05-11 21:31:34 +02:00
// General chunk size is 63 KiB, this can not be any larger because the packet size is encoded
// with uint16_t and needs some spare room for other data in the packet.
static constexpr uint32_t kChunkSize = 1024 * 63;
2019-05-11 21:31:34 +02:00
// If data is sent fast enough it would halt the entire server, process only a maximum amount.
2021-07-29 20:08:57 +03:00
// This limit is per connection, the current value was determined by tests with fuzzing.
static constexpr uint32_t kMaxPacketsPerTick = 100;
#include "../ParkImporter.h"
2026-02-09 15:07:42 +01:00
#include "../actions/GameAction.hpp"
#include "../config/Config.h"
#include "../core/Console.hpp"
2024-12-15 17:39:52 +01:00
#include "../core/EnumUtils.hpp"
#include "../core/FileStream.h"
#include "../core/MemoryStream.h"
#include "../core/Path.hpp"
#include "../core/String.hpp"
#include "../interface/Chat.h"
#include "../object/ObjectManager.h"
#include "../object/ObjectRepository.h"
2026-07-31 20:33:22 +01:00
#include "../scenario/Scenario.h"
#include "NetworkAction.h"
#include "NetworkConnection.h"
#include "NetworkGroup.h"
#include "NetworkKey.h"
#include "NetworkPacket.h"
#include "NetworkPlayer.h"
#include "NetworkServerAdvertiser.h"
#include "NetworkUser.h"
#include "Socket.h"
2016-05-28 18:29:56 +01:00
#include <array>
#include <fstream>
#include <functional>
#include <list>
#include <map>
#include <memory>
#include <string>
#include <vector>
2018-06-22 23:02:47 +02:00
namespace OpenRCT2::Network
{
static void ChatShowConnectedMessage();
static void ChatShowServerGreeting();
static u8string GetKeysDirectory();
static u8string GetPrivateKeyPath(u8string_view playerName);
static u8string GetPublicKeyPath(u8string_view playerName, u8string_view hash);
NetworkBase::NetworkBase(IContext& context)
: System(context)
{
mode = Mode::none;
status = Status::none;
last_ping_sent_time = 0;
_actionId = 0;
client_command_handlers[Command::auth] = &NetworkBase::Client_Handle_AUTH;
client_command_handlers[Command::beginMap] = &NetworkBase::Client_Handle_BEGINMAP;
client_command_handlers[Command::map] = &NetworkBase::Client_Handle_MAP;
client_command_handlers[Command::chat] = &NetworkBase::Client_Handle_CHAT;
client_command_handlers[Command::gameAction] = &NetworkBase::Client_Handle_GAME_ACTION;
client_command_handlers[Command::tick] = &NetworkBase::Client_Handle_TICK;
client_command_handlers[Command::playerList] = &NetworkBase::Client_Handle_PLAYERLIST;
client_command_handlers[Command::playerInfo] = &NetworkBase::Client_Handle_PLAYERINFO;
client_command_handlers[Command::ping] = &NetworkBase::Client_Handle_PING;
client_command_handlers[Command::pingList] = &NetworkBase::Client_Handle_PINGLIST;
client_command_handlers[Command::disconnectMessage] = &NetworkBase::Client_Handle_SETDISCONNECTMSG;
client_command_handlers[Command::showError] = &NetworkBase::Client_Handle_SHOWERROR;
client_command_handlers[Command::groupList] = &NetworkBase::Client_Handle_GROUPLIST;
client_command_handlers[Command::event] = &NetworkBase::Client_Handle_EVENT;
client_command_handlers[Command::gameInfo] = &NetworkBase::Client_Handle_GAMEINFO;
client_command_handlers[Command::token] = &NetworkBase::Client_Handle_TOKEN;
client_command_handlers[Command::objectsList] = &NetworkBase::Client_Handle_OBJECTS_LIST;
client_command_handlers[Command::scriptsData] = &NetworkBase::Client_Handle_SCRIPTS_DATA;
client_command_handlers[Command::gameState] = &NetworkBase::Client_Handle_GAMESTATE;
server_command_handlers[Command::auth] = &NetworkBase::ServerHandleAuth;
server_command_handlers[Command::chat] = &NetworkBase::ServerHandleChat;
server_command_handlers[Command::gameAction] = &NetworkBase::ServerHandleGameAction;
server_command_handlers[Command::ping] = &NetworkBase::ServerHandlePing;
server_command_handlers[Command::gameInfo] = &NetworkBase::ServerHandleGameInfo;
server_command_handlers[Command::token] = &NetworkBase::ServerHandleToken;
server_command_handlers[Command::mapRequest] = &NetworkBase::ServerHandleMapRequest;
server_command_handlers[Command::requestGameState] = &NetworkBase::ServerHandleRequestGamestate;
server_command_handlers[Command::heartbeat] = &NetworkBase::ServerHandleHeartbeat;
_chat_log_fs << std::unitbuf;
_server_log_fs << std::unitbuf;
2017-06-06 23:24:18 +02:00
}
2015-02-12 02:01:02 +00:00
bool NetworkBase::Init()
2018-06-22 23:02:47 +02:00
{
status = Status::ready;
2018-12-17 12:58:12 +01:00
ServerName.clear();
ServerDescription.clear();
ServerGreeting.clear();
2018-12-17 12:58:12 +01:00
ServerProviderName.clear();
ServerProviderEmail.clear();
ServerProviderWebsite.clear();
return true;
2019-05-11 21:31:34 +02:00
}
2019-03-12 21:07:48 +01:00
2019-05-10 22:00:38 +02:00
void NetworkBase::Reconnect()
2018-06-22 23:02:47 +02:00
{
if (status != Status::none)
2018-06-22 23:02:47 +02:00
{
Close();
}
if (_requireClose)
{
_requireReconnect = true;
return;
}
BeginClient(_host, _port);
}
void NetworkBase::Close()
{
if (status != Status::none)
{
2018-03-23 18:29:45 +00:00
// HACK Because Close() is closed all over the place, it sometimes gets called inside an Update
// call. This then causes disposed data to be accessed. Therefore, save closing until the
// end of the update loop.
if (_closeLock)
{
2018-03-23 18:29:45 +00:00
_requireClose = true;
return;
}
CloseChatLog();
CloseServerLog();
2017-06-06 23:24:18 +02:00
CloseConnection();
2018-03-23 18:29:45 +00:00
client_connection_list.clear();
GameActions::ClearQueue();
GameActions::ResumeQueue();
2018-03-23 18:29:45 +00:00
player_list.clear();
group_list.clear();
_serverTickData.clear();
_pendingPlayerLists.clear();
2019-03-24 15:16:57 -07:00
_pendingPlayerInfo.clear();
#ifdef ENABLE_SCRIPTING
2022-03-21 22:56:21 +00:00
auto& scriptEngine = GetContext().GetScriptEngine();
scriptEngine.RemoveNetworkPlugins();
#endif
Drawing::GfxInvalidateScreen();
2018-03-23 18:29:45 +00:00
_requireClose = false;
}
}
void NetworkBase::DecayCooldown(Player* player)
{
if (player == nullptr)
return; // No valid connection yet.
2026-05-17 14:57:47 +02:00
for (auto it = std::begin(player->cooldownTime); it != std::end(player->cooldownTime);)
{
it->second -= _currentDeltaTime;
if (it->second <= 0)
2026-05-17 14:57:47 +02:00
it = player->cooldownTime.erase(it);
else
it++;
}
}
void NetworkBase::CloseConnection()
{
if (mode == Mode::client)
{
2018-12-17 12:58:12 +01:00
_serverConnection.reset();
}
else if (mode == Mode::server)
{
2018-12-17 12:58:12 +01:00
_listenSocket.reset();
_advertiser.reset();
}
mode = Mode::none;
status = Status::none;
_lastConnectStatus = SocketStatus::closed;
}
bool NetworkBase::BeginClient(const std::string& host, uint16_t port)
{
if (GetMode() != Mode::none)
{
2017-06-06 23:24:18 +02:00
return false;
}
Close();
2017-06-06 23:24:18 +02:00
if (!Init())
return false;
mode = Mode::client;
LOG_INFO("Connecting to %s:%u", host.c_str(), port);
_host = host;
_port = port;
_serverConnection = std::make_unique<Connection>();
2026-05-17 14:57:47 +02:00
_serverConnection->socket = CreateTcpSocket();
_serverConnection->socket->ConnectAsync(host, port);
2019-05-11 21:31:34 +02:00
_serverState.gamestateSnapshotsEnabled = false;
status = Status::connecting;
_lastConnectStatus = SocketStatus::closed;
_clientMapLoaded = false;
2019-03-12 21:07:48 +01:00
_serverTickData.clear();
2017-06-06 23:24:18 +02:00
BeginChatLog();
BeginServerLog();
// We need to wait for the map load before we execute any actions.
2021-01-10 18:23:35 +00:00
// If the client has the title screen running then there's a potential
// risk of tick collision with the server map and title screen map.
GameActions::SuspendQueue();
2025-10-07 20:14:37 +02:00
auto keyPath = GetPrivateKeyPath(Config::Get().network.playerName);
if (!File::Exists(keyPath))
{
2017-06-06 23:24:18 +02:00
Console::WriteLine("Generating key... This may take a while");
Console::WriteLine("Need to collect enough entropy from the system");
_key.Generate();
Console::WriteLine("Key generated, saving private bits as %s", keyPath.c_str());
const auto keysDirectory = GetKeysDirectory();
2023-05-09 21:08:46 +02:00
if (!Path::CreateDirectory(keysDirectory))
{
LOG_ERROR("Unable to create directory %s.", keysDirectory.c_str());
2017-06-06 23:24:18 +02:00
return false;
}
try
{
2025-03-25 18:23:36 +01:00
auto fs = FileStream(keyPath, FileMode::write);
2017-06-06 23:24:18 +02:00
_key.SavePrivate(&fs);
}
2018-06-22 23:02:47 +02:00
catch (const std::exception&)
{
LOG_ERROR("Unable to save private key at %s.", keyPath.c_str());
2017-06-06 23:24:18 +02:00
return false;
}
2017-06-06 23:24:18 +02:00
const std::string hash = _key.PublicKeyHash();
2018-06-22 23:02:47 +02:00
const utf8* publicKeyHash = hash.c_str();
2025-10-07 20:14:37 +02:00
keyPath = GetPublicKeyPath(Config::Get().network.playerName, publicKeyHash);
Console::WriteLine("Key generated, saving public bits as %s", keyPath.c_str());
try
{
2025-03-25 18:23:36 +01:00
auto fs = FileStream(keyPath, FileMode::write);
2017-06-06 23:24:18 +02:00
_key.SavePublic(&fs);
}
2018-06-22 23:02:47 +02:00
catch (const std::exception&)
{
LOG_ERROR("Unable to save public key at %s.", keyPath.c_str());
2017-06-06 23:24:18 +02:00
return false;
}
}
else
{
2017-06-06 23:24:18 +02:00
// LoadPrivate returns validity of loaded key
bool ok = false;
try
{
LOG_VERBOSE("Loading key from %s", keyPath.c_str());
2025-03-25 18:23:36 +01:00
auto fs = FileStream(keyPath, FileMode::open);
2017-06-06 23:24:18 +02:00
ok = _key.LoadPrivate(&fs);
}
2018-06-22 23:02:47 +02:00
catch (const std::exception&)
{
LOG_ERROR("Unable to read private key from %s.", keyPath.c_str());
2017-06-06 23:24:18 +02:00
return false;
}
2017-06-06 23:24:18 +02:00
// Don't store private key in memory when it's not in use.
_key.Unload();
return ok;
}
2019-05-11 21:31:34 +02:00
return true;
}
2019-05-11 21:31:34 +02:00
bool NetworkBase::BeginServer(uint16_t port, const std::string& address)
2018-06-22 23:02:47 +02:00
{
Close();
if (!Init())
2017-10-03 00:00:32 +02:00
return false;
2015-11-01 17:28:53 -07:00
mode = Mode::server;
2015-11-01 17:28:53 -07:00
2026-05-17 14:57:47 +02:00
_userManager.load();
2015-11-03 16:31:09 -07:00
2017-06-06 23:24:18 +02:00
LOG_VERBOSE("Begin listening for clients");
2015-11-07 23:56:16 +00:00
2018-06-22 23:02:47 +02:00
_listenSocket = CreateTcpSocket();
2017-06-06 23:24:18 +02:00
try
{
_listenSocket->Listen(address, port);
2017-06-06 23:24:18 +02:00
}
2018-06-22 23:02:47 +02:00
catch (const std::exception& ex)
2017-06-06 23:24:18 +02:00
{
Console::Error::WriteLine(ex.what());
Close();
2017-06-06 23:24:18 +02:00
return false;
}
2016-01-23 18:05:53 -07:00
2025-10-07 20:14:37 +02:00
ServerName = Config::Get().network.serverName;
ServerDescription = Config::Get().network.serverDescription;
ServerGreeting = Config::Get().network.serverGreeting;
ServerProviderName = Config::Get().network.providerName;
ServerProviderEmail = Config::Get().network.providerEmail;
ServerProviderWebsite = Config::Get().network.providerWebsite;
2019-02-20 22:30:12 +01:00
IsServerPlayerInvisible = gOpenRCT2Headless;
2019-02-20 22:30:12 +01:00
2018-05-12 15:13:48 +02:00
LoadGroups();
BeginChatLog();
BeginServerLog();
2019-02-20 22:30:12 +01:00
2025-10-07 20:14:37 +02:00
Player* player = AddPlayer(Config::Get().network.playerName, "");
2026-05-17 14:57:47 +02:00
player->flags |= PlayerFlags::kIsServer;
player->group = 0;
player_id = player->id;
if (GetMode() == Mode::server)
2018-06-22 23:02:47 +02:00
{
// Add SERVER to users.json and save.
2026-05-17 14:57:47 +02:00
User* networkUser = _userManager.getOrAddUser(player->keyHash);
networkUser->groupId = player->group;
networkUser->name = player->name;
_userManager.save();
2017-06-06 23:24:18 +02:00
}
2021-02-11 21:17:15 +00:00
auto* szAddress = address.empty() ? "*" : address.c_str();
2021-02-13 00:15:27 +00:00
Console::WriteLine("Listening for clients on %s:%hu", szAddress, port);
ChatShowConnectedMessage();
ChatShowServerGreeting();
status = Status::connected;
2017-06-06 23:24:18 +02:00
listening_port = port;
2025-10-07 20:14:37 +02:00
_serverState.gamestateSnapshotsEnabled = Config::Get().network.desyncDebugging;
2019-05-05 01:02:20 +00:00
_advertiser = CreateServerAdvertiser(listening_port);
GameLoadScripts();
GameNotifyMapChanged();
2017-06-06 23:24:18 +02:00
return true;
}
Mode NetworkBase::GetMode() const noexcept
2018-06-22 23:02:47 +02:00
{
2017-06-06 23:24:18 +02:00
return mode;
2018-06-22 23:02:47 +02:00
}
Status NetworkBase::GetStatus() const noexcept
2018-06-22 23:02:47 +02:00
{
return status;
}
Auth NetworkBase::GetAuthStatus()
{
if (GetMode() == Mode::client)
2018-06-22 23:02:47 +02:00
{
2026-05-17 14:57:47 +02:00
return _serverConnection->authStatus;
}
if (GetMode() == Mode::server)
{
return Auth::ok;
}
return Auth::none;
}
2022-02-10 05:57:25 +09:00
uint32_t NetworkBase::GetServerTick() const noexcept
{
2019-05-11 21:31:34 +02:00
return _serverState.tick;
}
PlayerId_t NetworkBase::GetPlayerID() const noexcept
{
2017-06-06 23:24:18 +02:00
return player_id;
}
Connection* NetworkBase::GetPlayerConnection(uint8_t id) const
{
auto player = GetPlayerByID(id);
if (player != nullptr)
{
2020-04-30 02:14:33 +01:00
auto clientIt = std::find_if(
2020-04-30 17:12:02 +01:00
client_connection_list.begin(), client_connection_list.end(),
[player](const auto& conn) -> bool { return conn->player == player; });
return clientIt != client_connection_list.end() ? clientIt->get() : nullptr;
}
2020-04-30 02:14:33 +01:00
return nullptr;
}
void NetworkBase::Update()
{
switch (GetMode())
{
case Mode::server:
UpdateServer();
break;
case Mode::client:
UpdateClient();
break;
default:
break;
}
}
void NetworkBase::Tick()
{
2017-06-06 23:24:18 +02:00
_closeLock = true;
// Update is not necessarily called per game tick, maintain our own delta time
2022-02-18 21:57:00 +01:00
uint32_t ticks = Platform::GetTicks();
_currentDeltaTime = std::max<uint32_t>(ticks - _lastUpdateTime, 1);
_lastUpdateTime = ticks;
2018-06-22 23:02:47 +02:00
switch (GetMode())
{
case Mode::server:
TickServer();
break;
case Mode::client:
TickClient();
break;
default:
break;
}
// If the Close() was called during the update, close it for real
2017-06-06 23:24:18 +02:00
_closeLock = false;
2018-06-22 23:02:47 +02:00
if (_requireClose)
{
Close();
if (_requireReconnect)
{
Reconnect();
}
2017-06-06 23:24:18 +02:00
}
}
void NetworkBase::Flush()
{
if (GetMode() == Mode::client)
2018-06-22 23:02:47 +02:00
{
2026-05-17 14:57:47 +02:00
_serverConnection->sendQueuedData();
2021-10-27 14:21:14 +02:00
}
else
{
for (auto& it : client_connection_list)
{
2026-05-17 14:57:47 +02:00
it->sendQueuedData();
}
2021-10-27 14:21:14 +02:00
}
2017-06-06 23:24:18 +02:00
}
2016-10-14 07:29:45 +02:00
void NetworkBase::UpdateServer()
{
for (auto& connection : client_connection_list)
{
// This can be called multiple times before the connection is removed.
2026-05-17 14:57:47 +02:00
if (!connection->isValid())
continue;
connection->update();
}
}
void NetworkBase::TickServer()
2019-01-29 16:35:19 +01:00
{
for (auto& connection : client_connection_list)
{
// This can be called multiple times before the connection is removed.
2026-05-17 14:57:47 +02:00
if (!connection->isValid())
continue;
if (!ProcessConnection(*connection))
2019-01-29 16:35:19 +01:00
{
if (connection->player != nullptr)
2026-05-17 14:57:47 +02:00
LOG_INFO("Disconnecting player %s", connection->player->name.c_str());
else
LOG_INFO("Disconnecting unknown player");
2026-05-17 14:57:47 +02:00
connection->disconnect();
}
2019-01-29 16:35:19 +01:00
else
{
DecayCooldown(connection->player);
2019-01-29 16:35:19 +01:00
}
}
uint32_t ticks = Platform::GetTicks();
2017-06-06 23:24:18 +02:00
if (ticks > last_ping_sent_time + 3000)
2018-06-22 23:02:47 +02:00
{
ServerSendPing();
2017-06-06 23:24:18 +02:00
ServerSendPingList();
}
2021-09-24 20:05:50 +02:00
if (_advertiser != nullptr)
2018-06-22 23:02:47 +02:00
{
2026-05-17 14:57:47 +02:00
_advertiser->update();
2018-06-22 23:02:47 +02:00
}
2018-12-17 12:58:12 +01:00
std::unique_ptr<ITcpSocket> tcpSocket = _listenSocket->Accept();
2018-06-22 23:02:47 +02:00
if (tcpSocket != nullptr)
{
AddClient(std::move(tcpSocket));
2017-06-06 23:24:18 +02:00
}
}
2016-10-13 14:57:40 +02:00
void NetworkBase::UpdateClient()
{
_serverConnection->update();
}
void NetworkBase::TickClient()
2018-06-22 23:02:47 +02:00
{
assert(_serverConnection != nullptr);
2015-07-15 00:23:04 -06:00
switch (status)
2020-04-28 22:02:14 +01:00
{
case Status::connecting:
2020-04-28 22:02:14 +01:00
{
2026-05-17 14:57:47 +02:00
switch (_serverConnection->socket->GetStatus())
2018-06-22 23:02:47 +02:00
{
case SocketStatus::resolving:
{
if (_lastConnectStatus != SocketStatus::resolving)
{
_lastConnectStatus = SocketStatus::resolving;
char str_resolving[256];
FormatStringLegacy(str_resolving, 256, STR_MULTIPLAYER_RESOLVING, nullptr);
auto intent = Intent(WindowClass::networkStatus);
2023-01-17 20:46:55 +01:00
intent.PutExtra(INTENT_EXTRA_MESSAGE, std::string{ str_resolving });
intent.PutExtra(
INTENT_EXTRA_CALLBACK, []() -> void { OpenRCT2::GetContext()->GetNetwork().Close(); });
2022-11-06 20:49:07 +00:00
ContextOpenIntent(&intent);
}
break;
}
case SocketStatus::connecting:
{
if (_lastConnectStatus != SocketStatus::connecting)
{
_lastConnectStatus = SocketStatus::connecting;
2018-06-22 23:02:47 +02:00
char str_connecting[256];
FormatStringLegacy(str_connecting, 256, STR_MULTIPLAYER_CONNECTING, nullptr);
auto intent = Intent(WindowClass::networkStatus);
2023-01-17 20:46:55 +01:00
intent.PutExtra(INTENT_EXTRA_MESSAGE, std::string{ str_connecting });
intent.PutExtra(
INTENT_EXTRA_CALLBACK, []() -> void { OpenRCT2::GetContext()->GetNetwork().Close(); });
2022-11-06 20:49:07 +00:00
ContextOpenIntent(&intent);
2022-02-18 21:57:00 +01:00
server_connect_time = Platform::GetTicks();
}
break;
}
case SocketStatus::connected:
{
status = Status::connected;
2018-06-22 23:02:47 +02:00
Client_Send_TOKEN();
char str_authenticating[256];
FormatStringLegacy(str_authenticating, 256, STR_MULTIPLAYER_AUTHENTICATING, nullptr);
auto intent = Intent(WindowClass::networkStatus);
2023-01-17 20:46:55 +01:00
intent.PutExtra(INTENT_EXTRA_MESSAGE, std::string{ str_authenticating });
intent.PutExtra(INTENT_EXTRA_CALLBACK, []() -> void { OpenRCT2::GetContext()->GetNetwork().Close(); });
2022-11-06 20:49:07 +00:00
ContextOpenIntent(&intent);
break;
}
default:
{
2026-05-17 14:57:47 +02:00
const char* error = _serverConnection->socket->GetError();
2018-06-22 23:02:47 +02:00
if (error != nullptr)
{
2018-06-22 23:02:47 +02:00
Console::Error::WriteLine(error);
}
Close();
ContextForceCloseWindowByClass(WindowClass::networkStatus);
2025-01-19 16:59:45 +01:00
ContextShowError(STR_UNABLE_TO_CONNECT_TO_SERVER, kStringIdNone, {});
break;
}
}
break;
}
case Status::connected:
{
2018-12-17 12:58:12 +01:00
if (!ProcessConnection(*_serverConnection))
{
2018-06-22 23:02:47 +02:00
// Do not show disconnect message window when password window closed/canceled
2026-05-17 14:57:47 +02:00
if (_serverConnection->authStatus == Auth::requirePassword)
{
ContextForceCloseWindowByClass(WindowClass::networkStatus);
}
else
{
2018-06-22 23:02:47 +02:00
char str_disconnected[256];
2026-05-17 14:57:47 +02:00
if (_serverConnection->getLastDisconnectReason())
{
2026-05-17 14:57:47 +02:00
const char* disconnect_reason = _serverConnection->getLastDisconnectReason();
FormatStringLegacy(
str_disconnected, 256, STR_MULTIPLAYER_DISCONNECTED_WITH_REASON, &disconnect_reason);
}
else
{
FormatStringLegacy(str_disconnected, 256, STR_MULTIPLAYER_DISCONNECTED_NO_REASON, nullptr);
}
auto intent = Intent(WindowClass::networkStatus);
2023-01-17 20:46:55 +01:00
intent.PutExtra(INTENT_EXTRA_MESSAGE, std::string{ str_disconnected });
2022-11-06 20:49:07 +00:00
ContextOpenIntent(&intent);
}
auto* windowMgr = Ui::GetWindowManager();
windowMgr->CloseByClass(WindowClass::multiplayer);
Close();
}
else
{
uint32_t ticks = Platform::GetTicks();
if (ticks - _lastSentHeartbeat >= 3000)
{
Client_Send_HEARTBEAT(*_serverConnection);
_lastSentHeartbeat = ticks;
}
}
break;
}
default:
break;
}
}
auto NetworkBase::GetPlayerIteratorByID(uint8_t id) const
{
return std::find_if(
2026-05-17 14:57:47 +02:00
player_list.begin(), player_list.end(), [id](std::unique_ptr<Player> const& player) { return player->id == id; });
}
Player* NetworkBase::GetPlayerByID(uint8_t id) const
{
2017-06-06 23:24:18 +02:00
auto it = GetPlayerIteratorByID(id);
2018-06-22 23:02:47 +02:00
if (it != player_list.end())
{
2017-06-06 23:24:18 +02:00
return it->get();
}
2017-06-06 23:24:18 +02:00
return nullptr;
}
2022-02-10 05:57:25 +09:00
auto NetworkBase::GetGroupIteratorByID(uint8_t id) const
{
2022-02-10 05:57:25 +09:00
return std::find_if(
2026-05-17 14:57:47 +02:00
group_list.begin(), group_list.end(), [id](std::unique_ptr<NetworkGroup> const& group) { return group->id == id; });
}
2022-02-10 05:57:25 +09:00
NetworkGroup* NetworkBase::GetGroupByID(uint8_t id) const
{
2017-06-06 23:24:18 +02:00
auto it = GetGroupIteratorByID(id);
2020-04-28 19:33:30 +01:00
if (it != group_list.end())
{
2017-06-06 23:24:18 +02:00
return it->get();
}
2017-06-06 23:24:18 +02:00
return nullptr;
}
int32_t NetworkBase::GetTotalNumPlayers() const noexcept
{
return static_cast<int32_t>(player_list.size());
}
int32_t NetworkBase::GetNumVisiblePlayers() const noexcept
{
2022-02-15 14:05:02 +01:00
if (IsServerPlayerInvisible)
return static_cast<int32_t>(player_list.size() - 1);
return static_cast<int32_t>(player_list.size());
}
const char* NetworkBase::FormatChat(Player* fromPlayer, const char* text)
{
2020-10-16 00:13:52 +01:00
static std::string formatted;
formatted.clear();
2020-04-28 19:33:30 +01:00
if (fromPlayer != nullptr)
{
auto& network = OpenRCT2::GetContext()->GetNetwork();
2026-05-17 14:57:47 +02:00
auto it = network.GetGroupByID(fromPlayer->id);
std::string groupName = "";
std::vector<std::string> colours;
if (it != nullptr)
{
2026-05-17 14:57:47 +02:00
groupName = it->getName();
2020-04-28 19:33:30 +01:00
if (groupName[0] != '{')
{
2020-04-28 19:33:30 +01:00
colours.push_back("{WHITE}");
}
}
2020-04-28 19:33:30 +01:00
for (size_t i = 0; i < groupName.size(); ++i)
{
if (groupName[i] == '{')
{
2020-04-28 19:33:30 +01:00
std::string colour = "{";
++i;
2020-04-28 19:33:30 +01:00
while (i < groupName.size() && groupName[i] != '}' && groupName[i] != '{')
{
colour += groupName[i];
++i;
}
colour += '}';
if (groupName[i] == '}' && i < groupName.size())
{
2020-04-28 19:33:30 +01:00
colours.push_back(colour);
}
}
2020-04-28 19:33:30 +01:00
}
if (colours.empty() || (colours.size() == 1 && colours[0] == "{WHITE}"))
2020-04-28 19:33:30 +01:00
{
formatted += "{BABYBLUE}";
2026-05-17 14:57:47 +02:00
formatted += fromPlayer->name;
}
else
{
size_t j = 0;
2026-05-17 14:57:47 +02:00
size_t proportionalSize = fromPlayer->name.size() / colours.size();
for (size_t i = 0; i < colours.size(); ++i)
{
formatted += colours[i];
size_t numCharacters = proportionalSize + j;
2026-05-17 14:57:47 +02:00
for (; j < numCharacters && j < fromPlayer->name.size(); ++j)
{
2026-05-17 14:57:47 +02:00
formatted += fromPlayer->name[j];
}
}
2026-05-17 14:57:47 +02:00
while (j < fromPlayer->name.size())
{
2026-05-17 14:57:47 +02:00
formatted += fromPlayer->name[j];
j++;
}
2020-04-28 19:33:30 +01:00
}
formatted += ": ";
2019-03-24 15:16:57 -07:00
}
2020-10-16 00:13:52 +01:00
formatted += "{WHITE}";
formatted += text;
return formatted.c_str();
}
void NetworkBase::SendPacketToClients(const Packet& packet, bool front, bool gameCmd) const
2019-03-24 15:16:57 -07:00
{
for (auto& client_connection : client_connection_list)
{
2018-06-22 23:02:47 +02:00
if (gameCmd)
{
// If marked as game command we can not send the packet to connections that are not fully connected.
// Sending the packet would cause the client to store a command that is behind the tick where he starts,
// which would be essentially never executed. The clients do not require commands before the server has not sent
// the map data.
if (client_connection->player == nullptr)
{
continue;
}
}
2026-05-17 14:57:47 +02:00
client_connection->queuePacket(packet, front);
2019-03-24 15:16:57 -07:00
}
}
bool NetworkBase::CheckSRAND(uint32_t tick, uint32_t srand0)
{
// We have to wait for the map to be loaded first, ticks may match current loaded map.
2019-05-10 22:00:38 +02:00
if (!_clientMapLoaded)
return true;
2019-03-12 21:07:48 +01:00
auto itTickData = _serverTickData.find(tick);
if (itTickData == std::end(_serverTickData))
2019-03-12 21:07:48 +01:00
return true;
const ServerTickData storedTick = itTickData->second;
2019-03-12 21:07:48 +01:00
_serverTickData.erase(itTickData);
2019-03-12 21:07:48 +01:00
if (storedTick.srand0 != srand0)
{
LOG_INFO("Srand0 mismatch, client = %08X, server = %08X", srand0, storedTick.srand0);
return false;
}
if (!storedTick.spriteHash.empty())
{
EntitiesChecksum checksum = getGameState().entities.getAllEntitiesChecksum();
std::string clientSpriteHash = checksum.toString();
if (clientSpriteHash != storedTick.spriteHash)
{
LOG_INFO(
"Sprite hash mismatch, client = %s, server = %s", clientSpriteHash.c_str(), storedTick.spriteHash.c_str());
return false;
}
}
return true;
}
bool NetworkBase::IsDesynchronised() const noexcept
{
return _serverState.state == ServerStatus::desynced;
}
bool NetworkBase::CheckDesynchronizaton()
2018-06-22 23:02:47 +02:00
{
const auto currentTicks = getGameState().currentTicks;
// Check synchronisation
if (GetMode() == Mode::client && _serverState.state != ServerStatus::desynced
&& !CheckSRAND(currentTicks, ScenarioRandState().s0))
{
_serverState.state = ServerStatus::desynced;
_serverState.desyncTick = currentTicks;
2017-06-06 23:24:18 +02:00
char str_desync[256];
FormatStringLegacy(str_desync, 256, STR_MULTIPLAYER_DESYNC, nullptr);
auto intent = Intent(WindowClass::networkStatus);
2023-01-17 20:46:55 +01:00
intent.PutExtra(INTENT_EXTRA_MESSAGE, std::string{ str_desync });
2022-11-06 20:49:07 +00:00
ContextOpenIntent(&intent);
2025-10-07 20:14:37 +02:00
if (!Config::Get().network.stayConnected)
{
Close();
}
2019-05-11 21:31:34 +02:00
return true;
}
2019-05-11 21:31:34 +02:00
return false;
}
void NetworkBase::RequestStateSnapshot()
{
LOG_INFO("Requesting game state for tick %u", _serverState.desyncTick);
2019-05-11 21:31:34 +02:00
Client_Send_RequestGameState(_serverState.desyncTick);
}
ServerState NetworkBase::GetServerState() const noexcept
{
2019-05-11 21:31:34 +02:00
return _serverState;
}
2017-06-06 23:24:18 +02:00
void NetworkBase::KickPlayer(int32_t playerId)
{
2018-06-22 23:02:47 +02:00
for (auto& client_connection : client_connection_list)
{
2026-05-17 14:57:47 +02:00
if (client_connection->player->id == playerId)
{
2017-06-06 23:24:18 +02:00
// Disconnect the client gracefully
2026-05-17 14:57:47 +02:00
client_connection->setLastDisconnectReason(STR_MULTIPLAYER_KICKED);
2017-06-06 23:24:18 +02:00
char str_disconnect_msg[256];
FormatStringLegacy(str_disconnect_msg, 256, STR_MULTIPLAYER_KICKED_REASON, nullptr);
ServerSendSetDisconnectMsg(*client_connection, str_disconnect_msg);
2026-05-17 14:57:47 +02:00
client_connection->disconnect();
break;
}
}
}
2022-01-27 14:21:46 +01:00
void NetworkBase::SetPassword(u8string_view password)
{
2022-01-27 14:21:46 +01:00
_password = password;
}
void NetworkBase::ServerClientDisconnected()
{
if (GetMode() == Mode::client)
{
2026-05-17 14:57:47 +02:00
_serverConnection->disconnect();
}
}
std::string NetworkBase::GenerateAdvertiseKey()
{
2017-06-06 23:24:18 +02:00
// Generate a string of 16 random hex characters (64-integer key as a hex formatted string)
2021-10-17 15:31:56 +02:00
static char hexChars[] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
};
2017-06-06 23:24:18 +02:00
char key[17];
2018-06-22 23:02:47 +02:00
for (int32_t i = 0; i < 16; i++)
{
int32_t hexCharIndex = UtilRand() % std::size(hexChars);
2017-06-06 23:24:18 +02:00
key[i] = hexChars[hexCharIndex];
}
2018-11-21 23:16:04 +01:00
key[std::size(key) - 1] = 0;
2017-06-06 23:24:18 +02:00
return key;
}
std::string NetworkBase::GetMasterServerUrl()
{
2025-10-07 20:14:37 +02:00
if (Config::Get().network.masterServerUrl.empty())
{
return kMasterServerURL;
}
2025-10-07 20:14:37 +02:00
return Config::Get().network.masterServerUrl;
}
NetworkGroup* NetworkBase::AddGroup()
{
2017-06-06 23:24:18 +02:00
NetworkGroup* addedgroup = nullptr;
int32_t newid = -1;
2017-06-06 23:24:18 +02:00
// Find first unused group id
2018-06-22 23:02:47 +02:00
for (int32_t id = 0; id < 255; id++)
{
if (std::find_if(
2018-07-21 13:51:54 +02:00
group_list.begin(), group_list.end(),
2026-05-17 14:57:47 +02:00
[&id](std::unique_ptr<NetworkGroup> const& group) { return group->id == id; })
2018-06-22 23:02:47 +02:00
== group_list.end())
{
2017-06-06 23:24:18 +02:00
newid = id;
break;
}
}
2018-06-22 23:02:47 +02:00
if (newid != -1)
{
2018-05-12 15:13:48 +02:00
auto group = std::make_unique<NetworkGroup>();
2026-05-17 14:57:47 +02:00
group->id = newid;
group->setName("Group #" + std::to_string(newid));
2017-06-06 23:24:18 +02:00
addedgroup = group.get();
group_list.push_back(std::move(group));
}
2017-06-06 23:24:18 +02:00
return addedgroup;
2018-06-22 23:02:47 +02:00
}
2018-06-22 23:02:47 +02:00
void NetworkBase::RemoveGroup(uint8_t id)
{
2017-06-06 23:24:18 +02:00
auto group = GetGroupIteratorByID(id);
2018-06-22 23:02:47 +02:00
if (group != group_list.end())
{
2017-06-06 23:24:18 +02:00
group_list.erase(group);
}
if (GetMode() == Mode::server)
2018-06-22 23:02:47 +02:00
{
2026-05-17 14:57:47 +02:00
_userManager.unsetUsersOfGroup(id);
_userManager.save();
}
}
2016-05-25 22:01:10 +01:00
2017-06-06 23:24:18 +02:00
uint8_t NetworkBase::GetGroupIDByHash(const std::string& keyhash)
{
2026-05-17 14:57:47 +02:00
const User* networkUser = _userManager.getUserByHash(keyhash);
2016-05-25 22:01:10 +01:00
2017-10-03 00:00:32 +02:00
uint8_t groupId = GetDefaultGroup();
2026-05-17 14:57:47 +02:00
if (networkUser != nullptr && networkUser->groupId.has_value())
{
2026-05-17 14:57:47 +02:00
const uint8_t assignedGroup = *networkUser->groupId;
2018-06-22 23:02:47 +02:00
if (GetGroupByID(assignedGroup) != nullptr)
{
2017-06-06 23:24:18 +02:00
groupId = assignedGroup;
2018-06-22 23:02:47 +02:00
}
else
{
LOG_WARNING(
"User %s is assigned to non-existent group %u. Assigning to default group (%u)", keyhash.c_str(),
assignedGroup, groupId);
2017-06-06 23:24:18 +02:00
}
2018-06-22 23:02:47 +02:00
}
2017-06-06 23:24:18 +02:00
return groupId;
}
2015-07-16 18:24:39 -06:00
uint8_t NetworkBase::GetDefaultGroup() const noexcept
2018-06-22 23:02:47 +02:00
{
2017-06-06 23:24:18 +02:00
return default_group;
}
2016-05-25 22:01:10 +01:00
2017-06-06 23:24:18 +02:00
void NetworkBase::SetDefaultGroup(uint8_t id)
{
2017-06-06 23:24:18 +02:00
if (GetGroupByID(id) != nullptr)
2018-06-22 23:02:47 +02:00
{
2017-06-06 23:24:18 +02:00
default_group = id;
}
}
2024-12-11 22:28:31 +01:00
void NetworkBase::SaveGroups()
{
if (GetMode() == Mode::server)
{
2024-12-11 22:28:31 +01:00
auto& env = GetContext().GetPlatformEnvironment();
auto path = Path::Combine(env.GetDirectoryPath(DirBase::user), u8"groups.json");
2024-12-11 22:28:31 +01:00
json_t jsonGroups = json_t::array();
for (auto& group : group_list)
2018-06-22 23:02:47 +02:00
{
2026-05-17 14:57:47 +02:00
jsonGroups.push_back(group->toJson());
2017-06-06 23:24:18 +02:00
}
json_t jsonGroupsCfg = {
2017-06-06 23:24:18 +02:00
{ "default_group", default_group },
2018-06-22 23:02:47 +02:00
{ "groups", jsonGroups },
};
2017-06-06 23:24:18 +02:00
try
2018-06-22 23:02:47 +02:00
{
2017-06-06 23:24:18 +02:00
Json::WriteToFile(path, jsonGroupsCfg);
}
catch (const std::exception& ex)
2019-05-11 21:31:34 +02:00
{
2020-04-22 17:09:29 +02:00
LOG_ERROR("Unable to save %s: %s", path.c_str(), ex.what());
2021-10-27 14:21:14 +02:00
}
2020-07-25 15:23:26 +02:00
}
}
2020-07-25 15:23:26 +02:00
void NetworkBase::SetupDefaultGroups()
{
2019-02-20 22:30:12 +01:00
// Admin group
2020-07-25 15:27:19 +02:00
auto admin = std::make_unique<NetworkGroup>();
2026-05-17 14:57:47 +02:00
admin->setName("Admin");
admin->actionsAllowed.fill(0xFF);
admin->id = 0;
group_list.push_back(std::move(admin));
2016-10-14 07:29:45 +02:00
2019-02-20 22:30:12 +01:00
// Spectator group
auto spectator = std::make_unique<NetworkGroup>();
2026-05-17 14:57:47 +02:00
spectator->setName("Spectator");
spectator->toggleActionPermission(Permission::chat);
spectator->id = 1;
group_list.push_back(std::move(spectator));
2020-02-23 12:55:48 +00:00
2019-02-20 22:30:12 +01:00
// User group
auto user = std::make_unique<NetworkGroup>();
2026-05-17 14:57:47 +02:00
user->setName("User");
user->actionsAllowed.fill(0xFF);
user->toggleActionPermission(Permission::kickPlayer);
user->toggleActionPermission(Permission::modifyGroups);
user->toggleActionPermission(Permission::setPlayerGroup);
user->toggleActionPermission(Permission::cheat);
user->toggleActionPermission(Permission::passwordlessLogin);
user->toggleActionPermission(Permission::modifyTile);
user->toggleActionPermission(Permission::editScenarioOptions);
user->id = 2;
group_list.push_back(std::move(user));
2020-02-22 22:18:22 +00:00
SetDefaultGroup(1);
2019-05-11 21:31:34 +02:00
}
void NetworkBase::LoadGroups()
2019-05-11 21:31:34 +02:00
{
group_list.clear();
auto& env = GetContext().GetPlatformEnvironment();
auto path = Path::Combine(env.GetDirectoryPath(DirBase::user), u8"groups.json");
2019-05-11 21:31:34 +02:00
json_t jsonGroupConfig;
if (File::Exists(path))
2018-06-22 23:02:47 +02:00
{
2017-06-06 23:24:18 +02:00
try
{
jsonGroupConfig = Json::ReadFromFile(path);
2017-06-06 23:24:18 +02:00
}
2018-06-22 23:02:47 +02:00
catch (const std::exception& e)
2017-06-06 23:24:18 +02:00
{
LOG_ERROR("Failed to read %s as JSON. Setting default groups. %s", path.c_str(), e.what());
2017-06-06 23:24:18 +02:00
}
}
2016-05-19 10:23:42 +02:00
if (!jsonGroupConfig.is_object())
2018-06-22 23:02:47 +02:00
{
2020-08-02 23:34:02 +02:00
SetupDefaultGroups();
2017-06-06 23:24:18 +02:00
}
else
{
2021-10-27 14:21:14 +02:00
json_t jsonGroups = jsonGroupConfig["groups"];
2017-10-02 18:02:50 +02:00
if (jsonGroups.is_array())
2019-03-01 11:01:00 +01:00
{
for (auto& jsonGroup : jsonGroups)
{
2026-05-17 14:57:47 +02:00
group_list.emplace_back(std::make_unique<NetworkGroup>(NetworkGroup::fromJson(jsonGroup)));
}
}
default_group = Json::GetNumber<uint8_t>(jsonGroupConfig["default_group"]);
2019-03-01 11:01:00 +01:00
if (GetGroupByID(default_group) == nullptr)
{
2019-03-01 11:01:00 +01:00
default_group = 0;
}
}
2019-03-01 11:01:00 +01:00
// Host group should always contain all permissions.
2026-05-17 14:57:47 +02:00
group_list.at(0)->actionsAllowed.fill(0xFF);
}
2019-03-01 11:01:00 +01:00
std::string NetworkBase::BeginLog(
const std::string& directory, const std::string& midName, const std::string& filenameFormat)
{
2019-03-01 11:01:00 +01:00
utf8 filename[256];
time_t timer;
2017-06-06 23:24:18 +02:00
time(&timer);
2019-03-01 11:01:00 +01:00
auto tmInfo = localtime(&timer);
if (strftime(filename, sizeof(filename), filenameFormat.c_str(), tmInfo) == 0)
{
throw std::runtime_error("strftime failed");
}
2023-05-09 21:08:46 +02:00
auto directoryMidName = Path::Combine(directory, midName);
Path::CreateDirectory(directoryMidName);
return Path::Combine(directoryMidName, filename);
}
void NetworkBase::AppendLog(std::ostream& fs, std::string_view s)
2018-06-22 23:02:47 +02:00
{
if (fs.fail())
2017-06-06 23:24:18 +02:00
{
2019-03-12 21:07:48 +01:00
LOG_ERROR("bad ostream failed to append log");
return;
2017-06-06 23:24:18 +02:00
}
try
2018-06-22 23:02:47 +02:00
{
utf8 buffer[1024];
time_t timer;
2022-11-06 20:49:07 +00:00
time(&timer);
auto tmInfo = localtime(&timer);
if (strftime(buffer, sizeof(buffer), "[%Y/%m/%d %H:%M:%S] ", tmInfo) != 0)
2018-06-22 23:02:47 +02:00
{
String::append(buffer, sizeof(buffer), std::string(s).c_str());
String::append(buffer, sizeof(buffer), PLATFORM_NEWLINE);
fs.write(buffer, strlen(buffer));
}
}
catch (const std::exception& ex)
{
LOG_ERROR("%s", ex.what());
}
}
void NetworkBase::BeginChatLog()
{
auto& env = GetContext().GetPlatformEnvironment();
auto directory = env.GetDirectoryPath(DirBase::user, DirId::chatLogs);
_chatLogPath = BeginLog(directory, "", _chatLogFilenameFormat);
2022-03-18 23:21:23 +01:00
_chat_log_fs.open(fs::u8path(_chatLogPath), std::ios::out | std::ios::app);
}
void NetworkBase::AppendChatLog(std::string_view s)
{
2025-10-07 20:14:37 +02:00
if (Config::Get().network.logChat && _chat_log_fs.is_open())
{
AppendLog(_chat_log_fs, s);
}
}
void NetworkBase::CloseChatLog()
{
_chat_log_fs.close();
}
void NetworkBase::BeginServerLog()
{
auto& env = GetContext().GetPlatformEnvironment();
auto directory = env.GetDirectoryPath(DirBase::user, DirId::serverLogs);
_serverLogPath = BeginLog(directory, ServerName, _serverLogFilenameFormat);
_server_log_fs.open(fs::u8path(_serverLogPath), std::ios::out | std::ios::app | std::ios::binary);
2017-06-06 23:24:18 +02:00
// Log server start event
utf8 logMessage[256];
if (GetMode() == Mode::client)
{
FormatStringLegacy(logMessage, sizeof(logMessage), STR_LOG_CLIENT_STARTED, nullptr);
}
else if (GetMode() == Mode::server)
{
FormatStringLegacy(logMessage, sizeof(logMessage), STR_LOG_SERVER_STARTED, nullptr);
}
else
{
2019-10-21 00:32:13 -03:00
logMessage[0] = '\0';
Guard::Assert(false, "Unknown network mode!");
}
2017-06-06 23:24:18 +02:00
AppendServerLog(logMessage);
}
void NetworkBase::AppendServerLog(const std::string& s)
{
2025-10-07 20:14:37 +02:00
if (Config::Get().network.logServerActions && _server_log_fs.is_open())
{
AppendLog(_server_log_fs, s);
}
}
void NetworkBase::CloseServerLog()
{
2017-06-06 23:24:18 +02:00
// Log server stopped event
char logMessage[256];
if (GetMode() == Mode::client)
{
FormatStringLegacy(logMessage, sizeof(logMessage), STR_LOG_CLIENT_STOPPED, nullptr);
}
else if (GetMode() == Mode::server)
{
FormatStringLegacy(logMessage, sizeof(logMessage), STR_LOG_SERVER_STOPPED, nullptr);
}
else
{
2019-10-21 00:32:13 -03:00
logMessage[0] = '\0';
Guard::Assert(false, "Unknown network mode!");
}
2017-06-06 23:24:18 +02:00
AppendServerLog(logMessage);
_server_log_fs.close();
}
void NetworkBase::Client_Send_RequestGameState(uint32_t tick)
{
2019-05-11 21:31:34 +02:00
if (_serverState.gamestateSnapshotsEnabled == false)
{
LOG_VERBOSE("Server does not store a gamestate history");
return;
}
LOG_VERBOSE("Requesting gamestate from server for tick %u", tick);
Packet packet(Command::requestGameState);
packet << tick;
2026-05-17 14:57:47 +02:00
_serverConnection->queuePacket(std::move(packet));
}
void NetworkBase::Client_Send_TOKEN()
{
LOG_VERBOSE("requesting token");
Packet packet(Command::token);
2026-05-17 14:57:47 +02:00
_serverConnection->authStatus = Auth::requested;
_serverConnection->queuePacket(std::move(packet));
}
void NetworkBase::Client_Send_AUTH(
const std::string& name, const std::string& password, const std::string& pubkey, const std::vector<uint8_t>& signature)
{
Packet packet(Command::auth);
2026-05-17 14:57:47 +02:00
packet.writeString(GetVersion());
packet.writeString(name);
packet.writeString(password);
packet.writeString(pubkey);
assert(signature.size() <= static_cast<size_t>(UINT32_MAX));
packet << static_cast<uint32_t>(signature.size());
2026-05-17 14:57:47 +02:00
packet.write(signature.data(), signature.size());
_serverConnection->authStatus = Auth::requested;
_serverConnection->queuePacket(std::move(packet));
}
void NetworkBase::Client_Send_MAPREQUEST(const std::vector<ObjectEntryDescriptor>& objects)
{
LOG_VERBOSE("client requests %u objects", uint32_t(objects.size()));
Packet packet(Command::mapRequest);
packet << static_cast<uint32_t>(objects.size());
2018-06-22 23:02:47 +02:00
for (const auto& object : objects)
{
2021-10-27 14:21:14 +02:00
std::string name(object.GetName());
LOG_VERBOSE("client requests object %s", name.c_str());
2026-08-06 18:40:41 +02:00
if (object.Generation == ObjectGeneration::dat)
{
2021-10-27 14:21:14 +02:00
packet << static_cast<uint8_t>(0);
2026-05-17 14:57:47 +02:00
packet.write(&object.Entry, sizeof(RCTObjectEntry));
2018-06-22 23:02:47 +02:00
}
else
{
packet << static_cast<uint8_t>(1);
2026-05-17 14:57:47 +02:00
packet.writeString(name);
2018-06-22 23:02:47 +02:00
}
2017-06-06 23:24:18 +02:00
}
2026-05-17 14:57:47 +02:00
_serverConnection->queuePacket(std::move(packet));
2017-06-06 23:24:18 +02:00
}
void NetworkBase::ServerSendToken(Connection& connection)
2018-06-22 23:02:47 +02:00
{
Packet packet(Command::token);
2026-05-17 14:57:47 +02:00
packet << static_cast<uint32_t>(connection.challenge.size());
packet.write(connection.challenge.data(), connection.challenge.size());
connection.queuePacket(std::move(packet));
}
void NetworkBase::ServerSendObjectsList(
Connection& connection, const std::vector<const ObjectRepositoryItem*>& objects) const
{
LOG_VERBOSE("Server sends objects list with %u items", objects.size());
Packet packet(Command::objectsList);
// Count.
packet << static_cast<uint32_t>(objects.size());
// List
for (size_t i = 0; i < objects.size(); ++i)
2018-06-22 23:02:47 +02:00
{
const auto* object = objects[i];
if (object->Identifier.empty())
{
// DAT
LOG_VERBOSE("Object %.8s (checksum %x)", object->ObjectEntry.name, object->ObjectEntry.checksum);
packet << static_cast<uint8_t>(0);
2026-05-17 14:57:47 +02:00
packet.write(&object->ObjectEntry, sizeof(RCTObjectEntry));
}
else
{
// JSON
LOG_VERBOSE("Object %s", object->Identifier.c_str());
packet << static_cast<uint8_t>(1);
2026-05-17 14:57:47 +02:00
packet.writeString(object->Identifier);
}
}
2026-05-17 14:57:47 +02:00
connection.queuePacket(std::move(packet));
}
void NetworkBase::ServerSendScripts(Connection& connection)
{
Packet packet(Command::scriptsData);
2017-06-06 23:24:18 +02:00
#ifdef ENABLE_SCRIPTING
using namespace OpenRCT2::Scripting;
auto& scriptEngine = GetContext().GetScriptEngine();
2017-06-06 23:24:18 +02:00
// Get remote plugin list.
const auto remotePlugins = scriptEngine.GetRemotePlugins();
2021-08-17 06:20:07 +03:00
LOG_VERBOSE("Server sends %zu scripts", remotePlugins.size());
packet << static_cast<uint32_t>(remotePlugins.size());
for (auto& plugin : remotePlugins)
{
2021-08-17 06:20:07 +03:00
const auto& code = plugin->GetCode();
const auto codeSize = static_cast<uint32_t>(code.size());
packet << codeSize;
2026-05-17 14:57:47 +02:00
packet.write(code.c_str(), code.size());
2017-06-06 23:24:18 +02:00
}
#else
packet << static_cast<uint32_t>(0);
#endif
2026-05-17 14:57:47 +02:00
connection.queuePacket(std::move(packet));
}
void NetworkBase::Client_Send_HEARTBEAT(Connection& connection) const
{
2017-06-06 23:24:18 +02:00
LOG_VERBOSE("Sending heartbeat");
Packet packet(Command::heartbeat);
2026-05-17 14:57:47 +02:00
connection.queuePacket(std::move(packet));
}
Stats NetworkBase::GetStats() const
{
Stats stats = {};
if (mode == Mode::client)
{
stats = _serverConnection->stats;
}
else
{
2019-01-29 16:35:19 +01:00
for (auto& connection : client_connection_list)
{
for (size_t n = 0; n < EnumValue(StatisticsGroup::max); n++)
{
stats.bytesReceived[n] += connection->stats.bytesReceived[n];
stats.bytesSent[n] += connection->stats.bytesSent[n];
}
}
}
2019-01-29 16:35:19 +01:00
return stats;
}
void NetworkBase::ServerSendAuth(Connection& connection)
{
uint8_t new_playerid = 0;
if (connection.player != nullptr)
{
2026-05-17 14:57:47 +02:00
new_playerid = connection.player->id;
}
Packet packet(Command::auth);
2026-05-17 14:57:47 +02:00
packet << static_cast<uint32_t>(connection.authStatus) << new_playerid;
if (connection.authStatus == Auth::badVersion)
{
2026-05-17 14:57:47 +02:00
packet.writeString(GetVersion());
}
2026-05-17 14:57:47 +02:00
connection.queuePacket(std::move(packet));
if (connection.authStatus != Auth::ok && connection.authStatus != Auth::requirePassword)
{
2026-05-17 14:57:47 +02:00
connection.disconnect();
}
}
void NetworkBase::ServerSendMap(Connection* connection)
{
2018-06-22 23:02:47 +02:00
std::vector<const ObjectRepositoryItem*> objects;
2021-09-24 20:05:50 +02:00
if (connection != nullptr)
{
2026-05-17 14:57:47 +02:00
objects = connection->requestedObjects;
}
else
{
2017-06-06 23:24:18 +02:00
// This will send all custom objects to connected clients
// TODO: fix it so custom objects negotiation is performed even in this case.
auto& context = GetContext();
auto& objManager = context.GetObjectManager();
2018-08-29 00:52:10 +02:00
objects = objManager.GetPackableObjects();
}
auto mapContent = SaveForNetwork(objects);
if (mapContent.empty())
{
2021-09-24 20:05:50 +02:00
if (connection != nullptr)
{
2026-05-17 14:57:47 +02:00
connection->setLastDisconnectReason(STR_MULTIPLAYER_CONNECTION_CLOSED);
connection->disconnect();
}
return;
}
Packet packetBeginMap(Command::beginMap);
Packet packetMap(Command::map);
2026-05-17 14:57:47 +02:00
packetMap.write(mapContent.data(), mapContent.size());
if (connection != nullptr)
{
2026-05-17 14:57:47 +02:00
connection->queuePacket(std::move(packetBeginMap));
connection->queuePacket(std::move(packetMap));
}
else
{
SendPacketToClients(packetBeginMap);
SendPacketToClients(packetMap);
}
}
std::vector<uint8_t> NetworkBase::SaveForNetwork(const std::vector<const ObjectRepositoryItem*>& objects) const
{
2021-10-27 14:21:14 +02:00
std::vector<uint8_t> result;
auto ms = MemoryStream();
2021-10-27 14:21:14 +02:00
if (SaveMap(&ms, objects))
{
2021-10-27 14:21:14 +02:00
result.resize(ms.GetLength());
std::memcpy(result.data(), ms.GetData(), result.size());
}
else
{
LOG_WARNING("Failed to export map.");
}
2021-10-27 14:21:14 +02:00
return result;
}
void NetworkBase::Client_Send_CHAT(const char* text)
{
Packet packet(Command::chat);
2026-05-17 14:57:47 +02:00
packet.writeString(text);
_serverConnection->queuePacket(std::move(packet));
}
void NetworkBase::ServerSendChat(const char* text, const std::vector<uint8_t>& playerIds)
{
Packet packet(Command::chat);
2026-05-17 14:57:47 +02:00
packet.writeString(text);
2020-04-28 22:02:14 +01:00
if (playerIds.empty())
{
2017-06-06 23:24:18 +02:00
// Empty players / default value means send to all players
SendPacketToClients(packet);
}
else
{
2021-08-17 06:20:07 +03:00
for (auto playerId : playerIds)
{
2021-08-17 06:20:07 +03:00
auto conn = GetPlayerConnection(playerId);
if (conn != nullptr)
{
2026-05-17 14:57:47 +02:00
conn->queuePacket(packet);
}
}
}
}
2021-08-17 06:20:07 +03:00
void NetworkBase::Client_Send_GAME_ACTION(const GameActions::GameAction* action)
{
Packet packet(Command::gameAction);
uint32_t networkId = 0;
networkId = ++_actionId;
// I know its ugly, want basic functionality for now.
2021-08-17 06:20:07 +03:00
const_cast<GameActions::GameAction*>(action)->SetNetworkId(networkId);
2018-06-22 23:02:47 +02:00
if (action->GetCallback())
{
2021-08-17 06:20:07 +03:00
_gameActionCallbacks.insert(std::make_pair(networkId, action->GetCallback()));
}
DataSerialiser stream(true);
action->Serialise(stream);
packet << getGameState().currentTicks << action->GetType() << stream;
2026-05-17 14:57:47 +02:00
_serverConnection->queuePacket(std::move(packet));
}
void NetworkBase::ServerSendGameAction(const GameActions::GameAction* action)
{
Packet packet(Command::gameAction);
DataSerialiser stream(true);
action->Serialise(stream);
packet << getGameState().currentTicks << action->GetType() << stream;
SendPacketToClients(packet);
}
void NetworkBase::ServerSendTick()
{
Packet packet(Command::tick);
packet << getGameState().currentTicks << ScenarioRandState().s0;
2025-09-05 13:24:00 +02:00
uint32_t flags = 0;
2025-09-05 13:24:00 +02:00
2017-06-06 23:24:18 +02:00
// Simple counter which limits how often a sprite checksum gets sent.
// This can get somewhat expensive, so we don't want to push it every tick in release,
// but debug version can check more often.
static int32_t checksum_counter = 0;
2017-06-06 23:24:18 +02:00
checksum_counter++;
2018-06-22 23:02:47 +02:00
if (checksum_counter >= 100)
{
2017-06-06 23:24:18 +02:00
checksum_counter = 0;
2025-09-05 13:24:00 +02:00
flags |= TickFlags::kChecksums;
}
2017-06-06 23:24:18 +02:00
// Send flags always, so we can understand packet structure on the other end,
// and allow for some expansion.
packet << flags;
2025-09-05 13:24:00 +02:00
if (flags & TickFlags::kChecksums)
{
EntitiesChecksum checksum = getGameState().entities.getAllEntitiesChecksum();
packet.writeString(checksum.toString());
}
SendPacketToClients(packet);
}
void NetworkBase::ServerSendPlayerInfo(int32_t playerId)
{
Packet packet(Command::playerInfo);
packet << getGameState().currentTicks;
2021-08-17 06:20:07 +03:00
auto* player = GetPlayerByID(playerId);
if (player == nullptr)
return;
2026-05-17 14:57:47 +02:00
player->write(packet);
SendPacketToClients(packet);
}
2021-08-17 06:20:07 +03:00
void NetworkBase::ServerSendPlayerList()
{
Packet packet(Command::playerList);
packet << getGameState().currentTicks << static_cast<uint8_t>(player_list.size());
2018-06-22 23:02:47 +02:00
for (auto& player : player_list)
{
2026-05-17 14:57:47 +02:00
player->write(packet);
}
SendPacketToClients(packet);
}
void NetworkBase::Client_Send_PING()
{
Packet packet(Command::ping);
2026-05-17 14:57:47 +02:00
_serverConnection->queuePacket(std::move(packet));
}
void NetworkBase::ServerSendPing()
{
last_ping_sent_time = Platform::GetTicks();
Packet packet(Command::ping);
2018-06-22 23:02:47 +02:00
for (auto& client_connection : client_connection_list)
{
2026-05-17 14:57:47 +02:00
client_connection->pingTime = Platform::GetTicks();
}
SendPacketToClients(packet, true);
}
void NetworkBase::ServerSendPingList()
{
Packet packet(Command::pingList);
packet << static_cast<uint8_t>(player_list.size());
2018-06-22 23:02:47 +02:00
for (auto& player : player_list)
{
2026-05-17 14:57:47 +02:00
packet << player->id << player->ping;
}
SendPacketToClients(packet);
}
void NetworkBase::ServerSendSetDisconnectMsg(Connection& connection, const char* msg)
{
Packet packet(Command::disconnectMessage);
2026-05-17 14:57:47 +02:00
packet.writeString(msg);
connection.queuePacket(std::move(packet));
}
json_t NetworkBase::GetServerInfoAsJson() const
{
json_t jsonObj = {
2025-10-07 20:14:37 +02:00
{ "name", Config::Get().network.serverName },
{ "requiresPassword", !_password.empty() },
{ "version", GetVersion() },
{ "players", GetNumVisiblePlayers() },
2025-10-07 20:14:37 +02:00
{ "maxPlayers", Config::Get().network.maxplayers },
{ "description", Config::Get().network.serverDescription },
{ "greeting", Config::Get().network.serverGreeting },
{ "dedicated", gOpenRCT2Headless },
};
return jsonObj;
2017-06-06 23:24:18 +02:00
}
2016-01-20 15:45:09 -07:00
void NetworkBase::ServerSendGameInfo(Connection& connection)
2017-06-06 23:24:18 +02:00
{
Packet packet(Command::gameInfo);
#ifndef DISABLE_HTTP
json_t jsonObj = GetServerInfoAsJson();
2017-06-06 23:24:18 +02:00
// Provider details
json_t jsonProvider = {
2025-10-07 20:14:37 +02:00
{ "name", Config::Get().network.providerName },
{ "email", Config::Get().network.providerEmail },
{ "website", Config::Get().network.providerWebsite },
};
jsonObj["provider"] = jsonProvider;
2026-05-17 14:57:47 +02:00
packet.writeString(jsonObj.dump());
packet << _serverState.gamestateSnapshotsEnabled;
packet << IsServerPlayerInvisible;
#endif
2026-05-17 14:57:47 +02:00
connection.queuePacket(std::move(packet));
}
void NetworkBase::ServerSendShowError(Connection& connection, StringId title, StringId message)
{
Packet packet(Command::showError);
packet << title << message;
2026-05-17 14:57:47 +02:00
connection.queuePacket(std::move(packet));
}
void NetworkBase::ServerSendGroupList(Connection& connection)
{
Packet packet(Command::groupList);
packet << static_cast<uint8_t>(group_list.size()) << default_group;
for (auto& group : group_list)
{
2026-05-17 14:57:47 +02:00
group->write(packet);
2017-06-06 23:24:18 +02:00
}
2026-05-17 14:57:47 +02:00
connection.queuePacket(std::move(packet));
}
void NetworkBase::ServerSendEventPlayerJoined(const char* playerName)
{
Packet packet(Command::event);
2025-09-05 13:24:00 +02:00
packet << static_cast<ServerEvent>(ServerEvent::playerJoined);
2026-05-17 14:57:47 +02:00
packet.writeString(playerName);
SendPacketToClients(packet);
}
void NetworkBase::ServerSendEventPlayerDisconnected(const char* playerName, const char* reason)
{
Packet packet(Command::event);
2025-09-05 13:24:00 +02:00
packet << static_cast<ServerEvent>(ServerEvent::playerDisconnected);
2026-05-17 14:57:47 +02:00
packet.writeString(playerName);
packet.writeString(reason);
SendPacketToClients(packet);
}
bool NetworkBase::UpdateConnection(Connection& connection)
{
connection.update();
2026-05-17 14:57:47 +02:00
return connection.isValid();
}
static void displayNetworkProgress(StringId captionStringId)
{
auto captionString = GetContext()->GetLocalisationService().GetString(captionStringId);
auto intent = Intent(INTENT_ACTION_PROGRESS_OPEN);
intent.PutExtra(INTENT_EXTRA_MESSAGE, captionString);
intent.PutExtra(INTENT_EXTRA_CALLBACK, []() -> void {
LOG_INFO("User aborted network operation");
GetContext()->GetNetwork().Close();
});
ContextOpenIntent(&intent);
}
static void reportPacketProgress(NetworkBase& network, Connection& connection)
{
if (network.GetMode() != Mode::client)
{
return;
}
const auto nextPacketCommand = connection.getPendingPacketCommand();
const auto bytesReceived = connection.getPendingPacketAvailable();
const auto bytesTotal = connection.getPendingPacketSize();
switch (nextPacketCommand)
{
case Command::objectsList:
displayNetworkProgress(STR_MULTIPLAYER_RECEIVING_OBJECTS_LIST);
break;
case Command::map:
displayNetworkProgress(STR_MULTIPLAYER_DOWNLOADING_MAP);
break;
case Command::scriptsData:
displayNetworkProgress(STR_MULTIPLAYER_RECEIVING_SCRIPTS);
break;
default:
// Nothing to report.
return;
}
network.GetContext().SetProgress(
static_cast<uint32_t>(bytesReceived / 1024), static_cast<uint32_t>(bytesTotal / 1024), STR_STRING_M_OF_N_KIB);
}
bool NetworkBase::ProcessConnection(Connection& connection)
{
ReadPacket packetStatus;
uint32_t countProcessed = 0;
do
{
countProcessed++;
packetStatus = connection.readPacket();
switch (packetStatus)
2018-06-22 23:02:47 +02:00
{
case ReadPacket::disconnected:
// closed connection or network error
2026-05-17 14:57:47 +02:00
if (!connection.getLastDisconnectReason())
2018-06-22 23:02:47 +02:00
{
2026-05-17 14:57:47 +02:00
connection.setLastDisconnectReason(STR_MULTIPLAYER_CONNECTION_CLOSED);
}
2018-06-22 23:02:47 +02:00
return false;
case ReadPacket::success:
2018-06-22 23:02:47 +02:00
// done reading in packet
reportPacketProgress(*this, connection);
2026-05-17 14:57:47 +02:00
ProcessPacket(connection, connection.inboundPacket);
if (!connection.isValid())
{
2018-06-22 23:02:47 +02:00
return false;
}
break;
case ReadPacket::moreData:
2018-06-22 23:02:47 +02:00
// more data required to be read
reportPacketProgress(*this, connection);
break;
case ReadPacket::noData:
2018-06-22 23:02:47 +02:00
// could not read anything from socket
break;
}
} while (packetStatus == ReadPacket::success && countProcessed < kMaxPacketsPerTick);
2026-05-17 14:57:47 +02:00
if (!connection.receivedDataRecently())
{
LOG_INFO(
"No data received recently from connection %s, disconnecting connection.",
2026-05-17 14:57:47 +02:00
connection.socket->GetIpAddress().c_str());
2026-05-17 14:57:47 +02:00
if (!connection.getLastDisconnectReason())
{
2026-05-17 14:57:47 +02:00
connection.setLastDisconnectReason(STR_MULTIPLAYER_NO_DATA);
}
2017-06-06 23:24:18 +02:00
return false;
}
2017-06-06 23:24:18 +02:00
return true;
}
void NetworkBase::ProcessPacket(Connection& connection, Packet& packet)
{
const auto& handlerList = GetMode() == Mode::server ? server_command_handlers : client_command_handlers;
2026-05-17 14:57:47 +02:00
auto it = handlerList.find(packet.getCommand());
2021-07-29 20:08:57 +03:00
if (it != handlerList.end())
{
2021-07-29 20:08:57 +03:00
auto commandHandler = it->second;
2026-05-17 14:57:47 +02:00
if (connection.authStatus == Auth::ok || !packet.commandRequiresAuth())
{
try
{
(this->*commandHandler)(connection, packet);
}
2021-07-29 20:08:57 +03:00
catch (const std::exception& ex)
{
LOG_VERBOSE("Exception during packet processing: %s", ex.what());
}
}
else if (GetMode() == Mode::server)
{
LOG_WARNING(
"Connection %s sent command %u that requires authentication, disconnecting.",
2026-05-17 14:57:47 +02:00
connection.socket->GetIpAddress().c_str(), static_cast<uint32_t>(packet.getCommand()));
connection.disconnect();
}
}
2026-05-17 14:57:47 +02:00
packet.clear();
}
// This is called at the end of each game tick, this where things should be processed that affects the game state.
void NetworkBase::PostTick()
{
if (GetMode() == Mode::server)
{
ProcessDisconnectedClients();
}
else if (GetMode() == Mode::client)
{
ProcessPlayerInfo();
}
ProcessPlayerList();
}
2020-04-28 19:33:30 +01:00
static bool ProcessPlayerAuthenticatePluginHooks(
const Connection& connection, std::string_view name, std::string_view publicKeyHash)
{
#ifdef ENABLE_SCRIPTING
2020-04-28 19:33:30 +01:00
using namespace OpenRCT2::Scripting;
2020-04-28 19:33:30 +01:00
auto& hookEngine = GetContext()->GetScriptEngine().GetHookEngine();
if (hookEngine.HasSubscriptions(HookType::networkAuthenticate))
{
2020-04-28 19:33:30 +01:00
auto ctx = GetContext()->GetScriptEngine().GetContext();
2020-04-28 19:33:30 +01:00
// Create event args object
2025-09-29 02:05:00 +10:00
JSValue obj = JS_NewObject(ctx);
JS_SetPropertyStr(ctx, obj, "name", JSFromStdString(ctx, name));
JS_SetPropertyStr(ctx, obj, "publicKeyHash", JSFromStdString(ctx, publicKeyHash));
2026-05-17 14:57:47 +02:00
JS_SetPropertyStr(ctx, obj, "ipAddress", JSFromStdString(ctx, connection.socket->GetIpAddress()));
2025-09-29 02:05:00 +10:00
JS_SetPropertyStr(ctx, obj, "cancel", JS_NewBool(ctx, false));
2020-04-28 19:33:30 +01:00
// Call the subscriptions
2025-09-29 02:05:00 +10:00
hookEngine.Call(HookType::networkAuthenticate, obj, false, true);
2020-04-28 19:33:30 +01:00
// Check if any hook has cancelled the join
2025-09-29 02:05:00 +10:00
const bool canceled = AsOrDefault(ctx, obj, "cancel", false);
JS_FreeValue(ctx, obj);
if (canceled)
{
2020-04-28 19:33:30 +01:00
return false;
}
}
#endif
2020-04-28 19:33:30 +01:00
return true;
}
2020-04-28 19:33:30 +01:00
static void ProcessPlayerJoinedPluginHooks(uint8_t playerId)
{
#ifdef ENABLE_SCRIPTING
2020-04-28 19:33:30 +01:00
using namespace OpenRCT2::Scripting;
2020-04-28 19:33:30 +01:00
auto& hookEngine = GetContext()->GetScriptEngine().GetHookEngine();
if (hookEngine.HasSubscriptions(HookType::networkJoin))
{
2020-04-28 19:33:30 +01:00
auto ctx = GetContext()->GetScriptEngine().GetContext();
2020-04-28 19:33:30 +01:00
// Create event args object
2025-09-29 02:05:00 +10:00
JSValue obj = JS_NewObject(ctx);
JS_SetPropertyStr(ctx, obj, "player", JS_NewInt32(ctx, playerId));
2020-04-28 19:33:30 +01:00
// Call the subscriptions
2025-09-29 02:05:00 +10:00
hookEngine.Call(HookType::networkJoin, obj, false);
}
#endif
}
2020-04-28 19:33:30 +01:00
static void ProcessPlayerLeftPluginHooks(uint8_t playerId)
{
#ifdef ENABLE_SCRIPTING
2020-04-28 19:33:30 +01:00
using namespace OpenRCT2::Scripting;
2020-04-28 19:33:30 +01:00
auto& hookEngine = GetContext()->GetScriptEngine().GetHookEngine();
if (hookEngine.HasSubscriptions(HookType::networkLeave))
{
2020-04-28 19:33:30 +01:00
auto ctx = GetContext()->GetScriptEngine().GetContext();
2020-04-28 19:33:30 +01:00
// Create event args object
2025-09-29 02:05:00 +10:00
JSValue obj = JS_NewObject(ctx);
JS_SetPropertyStr(ctx, obj, "player", JS_NewInt32(ctx, playerId));
2020-04-28 19:33:30 +01:00
// Call the subscriptions
2026-04-01 01:47:26 +11:00
hookEngine.Call(HookType::networkLeave, obj, false);
}
#endif
}
void NetworkBase::ProcessPlayerList()
{
if (GetMode() == Mode::server)
{
// Avoid sending multiple times the player list, we mark the list invalidated on modifications
// and then send at the end of the tick the final player list.
if (_playerListInvalidated)
{
_playerListInvalidated = false;
ServerSendPlayerList();
if (!gOpenRCT2Headless)
{
// Update player list window
auto intent = Intent(INTENT_ACTION_REFRESH_PLAYER_LIST);
ContextBroadcastIntent(&intent);
}
}
}
else
{
2019-05-13 19:49:06 +01:00
// As client we have to keep things in order so the update is tick bound.
// Commands/Actions reference players and so this list needs to be in sync with those.
auto itPending = _pendingPlayerLists.begin();
if (itPending != _pendingPlayerLists.end())
{
while (itPending != _pendingPlayerLists.end())
{
if (itPending->first > getGameState().currentTicks)
break;
// List of active players found in the list.
std::vector<uint8_t> activePlayerIds;
std::vector<uint8_t> newPlayers;
std::vector<uint8_t> removedPlayers;
for (const auto& pendingPlayer : itPending->second.players)
{
activePlayerIds.push_back(pendingPlayer.id);
auto* player = GetPlayerByID(pendingPlayer.id);
if (player == nullptr)
2018-06-22 23:02:47 +02:00
{
// Add new player.
player = AddPlayer("", "");
if (player != nullptr)
2018-06-22 23:02:47 +02:00
{
*player = pendingPlayer;
if (player->flags & PlayerFlags::kIsServer)
{
_serverConnection->player = player;
}
newPlayers.push_back(player->id);
2018-06-22 23:02:47 +02:00
}
}
else
{
// Update.
*player = pendingPlayer;
2018-06-22 23:02:47 +02:00
}
}
// Remove any players that are not in newly received list
for (const auto& player : player_list)
2018-06-22 23:02:47 +02:00
{
if (std::find(activePlayerIds.begin(), activePlayerIds.end(), player->id) == activePlayerIds.end())
{
removedPlayers.push_back(player->id);
}
}
// Run player removed hooks (must be before players removed from list)
for (auto playerId : removedPlayers)
{
ProcessPlayerLeftPluginHooks(playerId);
}
// Run player joined hooks (must be after players added to list)
for (auto playerId : newPlayers)
{
ProcessPlayerJoinedPluginHooks(playerId);
}
// Now actually remove removed players from player list
player_list.erase(
std::remove_if(
player_list.begin(), player_list.end(),
[&removedPlayers](const std::unique_ptr<Player>& player) {
return std::find(removedPlayers.begin(), removedPlayers.end(), player->id)
!= removedPlayers.end();
}),
player_list.end());
_pendingPlayerLists.erase(itPending);
itPending = _pendingPlayerLists.begin();
}
// Update player list window
auto intent = Intent(INTENT_ACTION_REFRESH_PLAYER_LIST);
ContextBroadcastIntent(&intent);
}
}
}
void NetworkBase::ProcessPlayerInfo()
{
const auto currentTicks = getGameState().currentTicks;
auto range = _pendingPlayerInfo.equal_range(currentTicks);
2019-03-24 15:16:57 -07:00
for (auto it = range.first; it != range.second; it++)
{
2026-05-17 14:57:47 +02:00
auto* player = GetPlayerByID(it->second.id);
2019-03-24 15:16:57 -07:00
if (player != nullptr)
{
const Player& networkedInfo = it->second;
2026-05-17 14:57:47 +02:00
player->flags = networkedInfo.flags;
player->group = networkedInfo.group;
player->lastAction = networkedInfo.lastAction;
player->lastActionCoord = networkedInfo.lastActionCoord;
player->moneySpent = networkedInfo.moneySpent;
player->commandsRan = networkedInfo.commandsRan;
}
}
_pendingPlayerInfo.erase(currentTicks);
}
void NetworkBase::ProcessDisconnectedClients()
{
for (auto it = client_connection_list.begin(); it != client_connection_list.end();)
{
auto& connection = *it;
2026-05-17 14:57:47 +02:00
if (!connection->shouldDisconnect)
{
it++;
continue;
}
// Make sure to send all remaining packets out before disconnecting.
2026-05-17 14:57:47 +02:00
connection->sendQueuedData();
connection->socket->Disconnect();
ServerClientDisconnected(connection);
RemovePlayer(connection);
it = client_connection_list.erase(it);
}
}
void NetworkBase::AddClient(std::unique_ptr<ITcpSocket>&& socket)
{
// Log connection info.
2017-06-06 23:24:18 +02:00
char addr[128];
snprintf(addr, sizeof(addr), "Client joined from %s", socket->GetHostName());
AppendServerLog(addr);
2018-12-17 12:58:12 +01:00
// Store connection
auto connection = std::make_unique<Connection>();
2026-05-17 14:57:47 +02:00
connection->socket = std::move(socket);
2017-06-06 23:24:18 +02:00
client_connection_list.push_back(std::move(connection));
}
void NetworkBase::ServerClientDisconnected(std::unique_ptr<Connection>& connection)
{
Player* connection_player = connection->player;
if (connection_player == nullptr)
return;
char text[256];
const char* has_disconnected_args[2] = {
2026-05-17 14:57:47 +02:00
connection_player->name.c_str(),
connection->getLastDisconnectReason(),
};
2021-09-24 20:05:50 +02:00
if (has_disconnected_args[1] != nullptr)
{
FormatStringLegacy(text, 256, STR_MULTIPLAYER_PLAYER_HAS_DISCONNECTED_WITH_REASON, has_disconnected_args);
}
else
{
FormatStringLegacy(text, 256, STR_MULTIPLAYER_PLAYER_HAS_DISCONNECTED_NO_REASON, &(has_disconnected_args[0]));
}
2023-01-16 21:14:50 +01:00
ChatAddHistory(text);
2026-05-17 14:57:47 +02:00
Peep* pickup_peep = GetPickupPeep(connection_player->id);
2021-09-24 20:05:50 +02:00
if (pickup_peep != nullptr)
{
GameActions::PeepPickupAction pickupAction{ GameActions::PeepPickupType::cancel,
pickup_peep->id,
2026-05-17 14:57:47 +02:00
{ GetPickupPeepOldX(connection_player->id), 0, 0 },
GetCurrentPlayerId() };
auto res = GameActions::Execute(&pickupAction, getGameState());
}
ServerSendEventPlayerDisconnected(
2026-05-17 14:57:47 +02:00
const_cast<char*>(connection_player->name.c_str()), connection->getLastDisconnectReason());
// Log player disconnected event
AppendServerLog(text);
2026-05-17 14:57:47 +02:00
ProcessPlayerLeftPluginHooks(connection_player->id);
}
void NetworkBase::RemovePlayer(std::unique_ptr<Connection>& connection)
{
Player* connection_player = connection->player;
if (connection_player == nullptr)
return;
2018-06-22 23:02:47 +02:00
player_list.erase(
std::remove_if(
2018-07-21 13:51:54 +02:00
player_list.begin(), player_list.end(),
[connection_player](std::unique_ptr<Player>& player) { return player.get() == connection_player; }),
2018-06-22 23:02:47 +02:00
player_list.end());
// Send new player list.
_playerListInvalidated = true;
}
Player* NetworkBase::AddPlayer(const std::string& name, const std::string& keyhash)
{
Player* addedplayer = nullptr;
int32_t newid = -1;
if (GetMode() == Mode::server)
{
2017-06-06 23:24:18 +02:00
// Find first unused player id
2018-06-22 23:02:47 +02:00
for (int32_t id = 0; id < 255; id++)
{
2018-06-22 23:02:47 +02:00
if (std::find_if(
2018-07-21 13:51:54 +02:00
player_list.begin(), player_list.end(),
2026-05-17 14:57:47 +02:00
[&id](std::unique_ptr<Player> const& player) { return player->id == id; })
2021-08-17 06:20:07 +03:00
== player_list.end())
{
2017-06-06 23:24:18 +02:00
newid = id;
break;
}
}
}
else
{
newid = 0;
}
if (newid != -1)
{
std::unique_ptr<Player> player;
if (GetMode() == Mode::server)
{
2017-06-06 23:24:18 +02:00
// Load keys host may have added manually
2026-05-17 14:57:47 +02:00
_userManager.load();
2017-06-06 23:24:18 +02:00
// Check if the key is registered
2026-05-17 14:57:47 +02:00
const User* networkUser = _userManager.getUserByHash(keyhash);
player = std::make_unique<Player>();
2026-05-17 14:57:47 +02:00
player->id = newid;
player->keyHash = keyhash;
2024-05-10 12:10:21 +02:00
if (networkUser == nullptr)
{
2026-05-17 14:57:47 +02:00
player->group = GetDefaultGroup();
2019-05-10 22:00:38 +02:00
if (!name.empty())
{
2026-05-17 14:57:47 +02:00
player->setName(MakePlayerNameUnique(String::trim(name)));
}
}
else
{
2026-05-17 14:57:47 +02:00
player->group = networkUser->groupId.has_value() ? *networkUser->groupId : GetDefaultGroup();
player->setName(networkUser->name);
}
// Send new player list.
_playerListInvalidated = true;
}
else
{
player = std::make_unique<Player>();
2026-05-17 14:57:47 +02:00
player->id = newid;
player->group = GetDefaultGroup();
player->setName(String::trim(std::string(name)));
}
2017-06-06 23:24:18 +02:00
addedplayer = player.get();
player_list.push_back(std::move(player));
}
2017-06-06 23:24:18 +02:00
return addedplayer;
}
std::string NetworkBase::MakePlayerNameUnique(const std::string& name)
{
2017-06-06 23:24:18 +02:00
// Note: Player names are case-insensitive
2017-06-06 23:24:18 +02:00
std::string new_name = name.substr(0, 31);
int32_t counter = 1;
2017-06-06 23:24:18 +02:00
bool unique;
do
{
2017-06-06 23:24:18 +02:00
unique = true;
2017-06-06 23:24:18 +02:00
// Check if there is already a player with this name in the server
2018-06-22 23:02:47 +02:00
for (const auto& player : player_list)
{
2026-05-17 14:57:47 +02:00
if (String::iequals(player->name, new_name))
{
2017-06-06 23:24:18 +02:00
unique = false;
break;
}
}
2018-06-22 23:02:47 +02:00
if (unique)
{
2017-06-06 23:24:18 +02:00
// Check if there is already a registered player with this name
2026-05-17 14:57:47 +02:00
if (_userManager.getUserByName(new_name) != nullptr)
{
2017-06-06 23:24:18 +02:00
unique = false;
}
}
2018-06-22 23:02:47 +02:00
if (!unique)
{
2017-06-06 23:24:18 +02:00
// Increment name counter
counter++;
new_name = name.substr(0, 31) + " #" + std::to_string(counter);
}
2017-06-06 23:24:18 +02:00
} while (!unique);
return new_name;
}
void NetworkBase::Client_Handle_TOKEN(Connection& connection, Packet& packet)
{
2025-10-07 20:14:37 +02:00
auto keyPath = GetPrivateKeyPath(Config::Get().network.playerName);
if (!File::Exists(keyPath))
{
LOG_ERROR("Key file (%s) was not found. Restart client to re-generate it.", keyPath.c_str());
return;
}
try
{
2025-03-25 18:23:36 +01:00
auto fs = FileStream(keyPath, FileMode::open);
2017-06-06 23:24:18 +02:00
if (!_key.LoadPrivate(&fs))
{
2018-01-02 19:23:22 +00:00
throw std::runtime_error("Failed to load private key.");
}
}
2018-06-22 23:02:47 +02:00
catch (const std::exception&)
{
LOG_ERROR("Failed to load key %s", keyPath.c_str());
2026-05-17 14:57:47 +02:00
connection.setLastDisconnectReason(STR_MULTIPLAYER_VERIFICATION_FAILURE);
connection.disconnect();
return;
}
uint32_t challenge_size;
2017-06-06 23:24:18 +02:00
packet >> challenge_size;
2026-05-17 14:57:47 +02:00
const char* challenge = reinterpret_cast<const char*>(packet.read(challenge_size));
std::vector<uint8_t> signature;
2021-08-17 06:20:07 +03:00
const std::string pubkey = _key.PublicKeyString();
2017-06-06 23:24:18 +02:00
_challenge.resize(challenge_size);
std::memcpy(_challenge.data(), challenge, challenge_size);
bool ok = _key.Sign(_challenge.data(), _challenge.size(), signature);
if (!ok)
{
LOG_ERROR("Failed to sign server's challenge.");
2026-05-17 14:57:47 +02:00
connection.setLastDisconnectReason(STR_MULTIPLAYER_VERIFICATION_FAILURE);
connection.disconnect();
return;
}
2017-06-06 23:24:18 +02:00
// Don't keep private key in memory. There's no need and it may get leaked
// when process dump gets collected at some point in future.
_key.Unload();
2025-10-07 20:14:37 +02:00
Client_Send_AUTH(Config::Get().network.playerName, gCustomPassword, pubkey, signature);
}
void NetworkBase::ServerHandleRequestGamestate(Connection& connection, Packet& packet)
{
2019-05-11 21:31:34 +02:00
uint32_t tick;
packet >> tick;
2019-05-11 21:31:34 +02:00
if (_serverState.gamestateSnapshotsEnabled == false)
{
2019-05-11 21:31:34 +02:00
// Ignore this if this is off.
return;
}
IGameStateSnapshots* snapshots = GetContext().GetGameStateSnapshots();
2019-05-11 21:31:34 +02:00
const GameStateSnapshot_t* snapshot = snapshots->GetLinkedSnapshot(tick);
2021-09-24 20:05:50 +02:00
if (snapshot != nullptr)
{
2019-05-11 21:31:34 +02:00
MemoryStream snapshotMemory;
DataSerialiser ds(true, snapshotMemory);
2019-05-11 21:31:34 +02:00
snapshots->SerialiseSnapshot(const_cast<GameStateSnapshot_t&>(*snapshot), ds);
2019-05-11 21:31:34 +02:00
uint32_t bytesSent = 0;
2020-04-22 17:09:29 +02:00
uint32_t length = static_cast<uint32_t>(snapshotMemory.GetLength());
2019-05-11 21:31:34 +02:00
while (bytesSent < length)
{
uint32_t dataSize = kChunkSize;
2019-05-11 21:31:34 +02:00
if (bytesSent + dataSize > snapshotMemory.GetLength())
{
2019-05-11 21:31:34 +02:00
dataSize = snapshotMemory.GetLength() - bytesSent;
}
Packet packetGameStateChunk(Command::gameState);
packetGameStateChunk << tick << length << bytesSent << dataSize;
2026-05-17 14:57:47 +02:00
packetGameStateChunk.write(static_cast<const uint8_t*>(snapshotMemory.GetData()) + bytesSent, dataSize);
2026-05-17 14:57:47 +02:00
connection.queuePacket(std::move(packetGameStateChunk));
2019-05-11 21:31:34 +02:00
bytesSent += dataSize;
}
}
}
void NetworkBase::ServerHandleHeartbeat(Connection& connection, Packet& packet)
{
2026-05-17 14:57:47 +02:00
LOG_VERBOSE("Client %s heartbeat", connection.socket->GetIpAddress().c_str());
}
void NetworkBase::Client_Handle_AUTH(Connection& connection, Packet& packet)
{
uint32_t auth_status;
2020-04-22 17:09:29 +02:00
packet >> auth_status >> const_cast<uint8_t&>(player_id);
2026-05-17 14:57:47 +02:00
connection.authStatus = static_cast<Auth>(auth_status);
switch (connection.authStatus)
{
case Auth::ok:
2018-06-22 23:02:47 +02:00
Client_Send_GAMEINFO();
break;
case Auth::badName:
2026-05-17 14:57:47 +02:00
connection.setLastDisconnectReason(STR_MULTIPLAYER_BAD_PLAYER_NAME);
connection.disconnect();
break;
case Auth::badVersion:
{
2026-05-17 14:57:47 +02:00
auto version = std::string(packet.readString());
auto versionp = version.c_str();
2026-05-17 14:57:47 +02:00
connection.setLastDisconnectReason(STR_MULTIPLAYER_INCORRECT_SOFTWARE_VERSION, &versionp);
connection.disconnect();
break;
}
case Auth::badPassword:
2026-05-17 14:57:47 +02:00
connection.setLastDisconnectReason(STR_MULTIPLAYER_BAD_PASSWORD);
connection.disconnect();
break;
case Auth::verificationFailure:
2026-05-17 14:57:47 +02:00
connection.setLastDisconnectReason(STR_MULTIPLAYER_VERIFICATION_FAILURE);
connection.disconnect();
break;
case Auth::full:
2026-05-17 14:57:47 +02:00
connection.setLastDisconnectReason(STR_MULTIPLAYER_SERVER_FULL);
connection.disconnect();
break;
case Auth::requirePassword:
2025-09-17 23:49:17 +02:00
ContextOpenWindowView(WindowView::networkPassword);
break;
case Auth::unknownKeyDisallowed:
2026-05-17 14:57:47 +02:00
connection.setLastDisconnectReason(STR_MULTIPLAYER_UNKNOWN_KEY_DISALLOWED);
connection.disconnect();
break;
default:
2026-05-17 14:57:47 +02:00
connection.setLastDisconnectReason(STR_MULTIPLAYER_RECEIVED_INVALID_DATA);
connection.disconnect();
break;
}
}
void NetworkBase::ServerClientJoined(std::string_view name, const std::string& keyhash, Connection& connection)
{
auto player = AddPlayer(std::string(name), keyhash);
connection.player = player;
2020-04-28 19:33:30 +01:00
if (player != nullptr)
{
2017-06-06 23:24:18 +02:00
char text[256];
2026-05-17 14:57:47 +02:00
const char* player_name = static_cast<const char*>(player->name.c_str());
FormatStringLegacy(text, 256, STR_MULTIPLAYER_PLAYER_HAS_JOINED_THE_GAME, &player_name);
2023-01-16 21:14:50 +01:00
ChatAddHistory(text);
auto& context = GetContext();
auto& objManager = context.GetObjectManager();
2018-08-29 00:52:10 +02:00
auto objects = objManager.GetPackableObjects();
ServerSendObjectsList(connection, objects);
ServerSendScripts(connection);
2017-06-06 23:24:18 +02:00
// Log player joining event
2026-05-17 14:57:47 +02:00
std::string playerNameHash = player->name + " (" + keyhash + ")";
2020-04-22 17:09:29 +02:00
player_name = static_cast<const char*>(playerNameHash.c_str());
FormatStringLegacy(text, 256, STR_MULTIPLAYER_PLAYER_HAS_JOINED_THE_GAME, &player_name);
2017-06-06 23:24:18 +02:00
AppendServerLog(text);
2026-05-17 14:57:47 +02:00
ProcessPlayerJoinedPluginHooks(player->id);
}
}
void NetworkBase::ServerHandleToken(Connection& connection, [[maybe_unused]] Packet& packet)
{
uint8_t token_size = 10 + (rand() & 0x7f);
2026-05-17 14:57:47 +02:00
connection.challenge.resize(token_size);
2018-06-22 23:02:47 +02:00
for (int32_t i = 0; i < token_size; i++)
{
2026-05-17 14:57:47 +02:00
connection.challenge[i] = static_cast<uint8_t>(rand() & 0xff);
}
ServerSendToken(connection);
}
void NetworkBase::Client_Handle_OBJECTS_LIST(Connection& connection, Packet& packet)
{
auto& repo = GetContext().GetObjectRepository();
uint32_t objectCount{};
packet >> objectCount;
std::vector<ObjectEntryDescriptor> missingObjects;
for (uint32_t i = 0; i < objectCount; ++i)
{
2021-10-27 14:21:14 +02:00
uint8_t objectType{};
packet >> objectType;
2021-10-27 14:21:14 +02:00
if (objectType == 0)
{
// DAT
2026-05-17 14:57:47 +02:00
auto entry = reinterpret_cast<const RCTObjectEntry*>(packet.read(sizeof(RCTObjectEntry)));
2021-10-27 14:21:14 +02:00
if (entry != nullptr)
{
2021-10-27 14:21:14 +02:00
const auto* object = repo.FindObject(entry);
if (object == nullptr)
{
2021-10-27 14:21:14 +02:00
auto objectName = std::string(entry->GetName());
LOG_VERBOSE("Requesting object %s with checksum %x from server", objectName.c_str(), entry->checksum);
missingObjects.push_back(ObjectEntryDescriptor(*entry));
}
2021-10-27 14:21:14 +02:00
else if (object->ObjectEntry.checksum != entry->checksum || object->ObjectEntry.flags != entry->flags)
{
2021-10-27 14:21:14 +02:00
auto objectName = std::string(entry->GetName());
LOG_WARNING(
2021-10-27 14:21:14 +02:00
"Object %s has different checksum/flags (%x/%x) than server (%x/%x).", objectName.c_str(),
object->ObjectEntry.checksum, object->ObjectEntry.flags, entry->checksum, entry->flags);
}
}
}
else
{
// JSON
2026-05-17 14:57:47 +02:00
auto identifier = packet.readString();
2021-10-27 14:21:14 +02:00
if (!identifier.empty())
{
2021-10-27 14:21:14 +02:00
const auto* object = repo.FindObject(identifier);
if (object == nullptr)
{
2021-10-27 14:21:14 +02:00
auto objectName = std::string(identifier);
LOG_VERBOSE("Requesting object %s from server", objectName.c_str());
missingObjects.push_back(ObjectEntryDescriptor(objectName));
2018-06-22 23:02:47 +02:00
}
}
}
2017-06-06 23:24:18 +02:00
}
LOG_VERBOSE("client received object list, it has %u entries, %zu missing", objectCount, missingObjects.size());
Client_Send_MAPREQUEST(missingObjects);
}
void NetworkBase::Client_Handle_SCRIPTS_DATA(Connection& connection, Packet& packet)
{
#ifdef ENABLE_SCRIPTING
auto& scriptEngine = GetContext().GetScriptEngine();
uint32_t count{};
packet >> count;
for (uint32_t i = 0; i < count; ++i)
{
uint32_t codeSize{};
packet >> codeSize;
2026-05-17 14:57:47 +02:00
const uint8_t* scriptData = packet.read(codeSize);
auto code = std::string_view(reinterpret_cast<const char*>(scriptData), codeSize);
scriptEngine.AddNetworkPlugin(code);
LOG_VERBOSE("Received and loaded network script plugin %u/%u", i + 1, count);
}
#else
2026-05-17 14:57:47 +02:00
connection.setLastDisconnectReason("The client requires plugin support.");
2018-06-22 23:02:47 +02:00
Close();
#endif
}
2018-06-22 23:02:47 +02:00
void NetworkBase::Client_Handle_GAMESTATE(Connection& connection, Packet& packet)
{
2019-05-11 21:31:34 +02:00
uint32_t tick;
uint32_t totalSize;
uint32_t offset;
uint32_t dataSize;
2019-05-11 21:31:34 +02:00
packet >> tick >> totalSize >> offset >> dataSize;
if (offset == 0)
{
// Reset
_serverGameState = MemoryStream();
}
2019-05-11 21:31:34 +02:00
_serverGameState.SetPosition(offset);
2026-05-17 14:57:47 +02:00
const uint8_t* data = packet.read(dataSize);
2019-05-11 21:31:34 +02:00
_serverGameState.Write(data, dataSize);
LOG_VERBOSE(
"Received Game State %.02f%%",
(static_cast<float>(_serverGameState.GetLength()) / static_cast<float>(totalSize)) * 100.0f);
if (_serverGameState.GetLength() == totalSize)
{
2019-05-11 21:31:34 +02:00
_serverGameState.SetPosition(0);
DataSerialiser ds(false, _serverGameState);
IGameStateSnapshots* snapshots = GetContext().GetGameStateSnapshots();
2019-05-11 21:31:34 +02:00
GameStateSnapshot_t& serverSnapshot = snapshots->CreateSnapshot();
snapshots->SerialiseSnapshot(serverSnapshot, ds);
2019-05-11 21:31:34 +02:00
const GameStateSnapshot_t* desyncSnapshot = snapshots->GetLinkedSnapshot(tick);
if (desyncSnapshot != nullptr)
2018-06-22 23:02:47 +02:00
{
GameStateCompareData cmpData = snapshots->Compare(serverSnapshot, *desyncSnapshot);
2018-06-22 23:02:47 +02:00
std::string outputPath = GetContext().GetPlatformEnvironment().GetDirectoryPath(
DirBase::user, DirId::desyncLogs);
2018-06-22 23:02:47 +02:00
Path::CreateDirectory(outputPath);
2019-05-11 21:31:34 +02:00
char uniqueFileName[128] = {};
snprintf(
2019-05-11 21:31:34 +02:00
uniqueFileName, sizeof(uniqueFileName), "desync_%llu_%u.txt",
static_cast<long long unsigned>(Platform::GetDatetimeNowUTC()), tick);
2019-05-13 19:49:06 +01:00
std::string outputFile = Path::Combine(outputPath, uniqueFileName);
2019-05-13 19:49:06 +01:00
if (snapshots->LogCompareDataToFile(outputFile, cmpData))
2018-06-22 23:02:47 +02:00
{
LOG_INFO("Wrote desync report to '%s'", outputFile.c_str());
auto ft = Formatter();
ft.Add<char*>(uniqueFileName);
2019-05-11 21:31:34 +02:00
char str_desync[1024];
FormatStringLegacy(str_desync, sizeof(str_desync), STR_DESYNC_REPORT, ft.Data());
auto intent = Intent(WindowClass::networkStatus);
intent.PutExtra(INTENT_EXTRA_MESSAGE, std::string{ str_desync });
2022-11-06 20:49:07 +00:00
ContextOpenIntent(&intent);
2018-06-22 23:02:47 +02:00
}
}
}
}
void NetworkBase::ServerHandleMapRequest(Connection& connection, Packet& packet)
{
uint32_t size;
2017-06-06 23:24:18 +02:00
packet >> size;
LOG_VERBOSE("Client requested %u objects", size);
auto& repo = GetContext().GetObjectRepository();
for (uint32_t i = 0; i < size; i++)
{
2021-10-27 14:21:14 +02:00
uint8_t generation{};
packet >> generation;
2021-10-27 14:21:14 +02:00
std::string objectName;
const ObjectRepositoryItem* item{};
2026-08-06 18:40:41 +02:00
if (generation == static_cast<uint8_t>(ObjectGeneration::dat))
2018-06-22 23:02:47 +02:00
{
2026-05-17 14:57:47 +02:00
const auto* entry = reinterpret_cast<const RCTObjectEntry*>(packet.read(sizeof(RCTObjectEntry)));
2026-05-16 21:30:00 -04:00
if (entry == nullptr)
break;
2026-05-17 14:57:47 +02:00
2025-01-19 16:59:45 +01:00
objectName = std::string(entry->GetName());
LOG_VERBOSE("Client requested object %s", objectName.c_str());
item = repo.FindObject(entry);
2018-06-22 23:02:47 +02:00
}
else
2018-06-22 23:02:47 +02:00
{
2026-05-17 14:57:47 +02:00
auto name = packet.readString();
2026-05-16 21:30:00 -04:00
if (name.empty())
break;
2026-05-17 14:57:47 +02:00
2026-05-16 21:30:00 -04:00
objectName = std::string(name);
2021-08-17 06:20:07 +03:00
LOG_VERBOSE("Client requested object %s", objectName.c_str());
2021-10-27 14:21:14 +02:00
item = repo.FindObject(objectName);
}
2021-08-17 06:20:07 +03:00
if (item == nullptr)
{
2021-08-17 06:20:07 +03:00
LOG_WARNING("Client tried getting non-existent object %s from us.", objectName.c_str());
}
else
{
2026-05-17 14:57:47 +02:00
connection.requestedObjects.push_back(item);
2018-06-22 23:02:47 +02:00
}
}
if (connection.player == nullptr)
{
LOG_WARNING(
2026-05-17 14:57:47 +02:00
"Connection %s requested map but has no player, disconnecting.", connection.socket->GetIpAddress().c_str());
connection.disconnect();
return;
}
2026-05-17 14:57:47 +02:00
auto player_name = connection.player->name.c_str();
ServerSendMap(&connection);
ServerSendEventPlayerJoined(player_name);
ServerSendGroupList(connection);
}
void NetworkBase::ServerHandleAuth(Connection& connection, Packet& packet)
{
2026-05-17 14:57:47 +02:00
if (connection.authStatus != Auth::ok)
{
2026-05-17 14:57:47 +02:00
auto* hostName = connection.socket->GetHostName();
auto gameversion = packet.readString();
auto name = packet.readString();
auto password = packet.readString();
auto pubkey = packet.readString();
uint32_t sigsize;
2017-06-06 23:24:18 +02:00
packet >> sigsize;
if (pubkey.empty())
{
2026-05-17 14:57:47 +02:00
connection.authStatus = Auth::verificationFailure;
}
else
{
try
{
// RSA technically supports keys up to 65536 bits, so this is the
// maximum signature size for now.
constexpr auto MaxRSASignatureSizeInBytes = 8192;
if (sigsize == 0 || sigsize > MaxRSASignatureSizeInBytes)
{
throw std::runtime_error("Invalid signature size");
}
std::vector<uint8_t> signature;
signature.resize(sigsize);
2026-05-17 14:57:47 +02:00
const uint8_t* signatureData = packet.read(sigsize);
if (signatureData == nullptr)
{
2018-01-02 19:23:22 +00:00
throw std::runtime_error("Failed to read packet.");
}
std::memcpy(signature.data(), signatureData, sigsize);
auto ms = MemoryStream(pubkey.data(), pubkey.size());
if (!connection.key.LoadPublic(&ms))
{
2018-01-02 19:23:22 +00:00
throw std::runtime_error("Failed to load public key.");
}
2026-05-17 14:57:47 +02:00
bool verified = connection.key.Verify(connection.challenge.data(), connection.challenge.size(), signature);
const std::string hash = connection.key.PublicKeyHash();
2017-06-06 23:24:18 +02:00
if (verified)
{
LOG_VERBOSE("Connection %s: Signature verification ok. Hash %s", hostName, hash.c_str());
2026-05-17 14:57:47 +02:00
if (Config::Get().network.knownKeysOnly && _userManager.getUserByHash(hash) == nullptr)
{
LOG_VERBOSE("Connection %s: Hash %s, not known", hostName, hash.c_str());
2026-05-17 14:57:47 +02:00
connection.authStatus = Auth::unknownKeyDisallowed;
}
else
{
2026-05-17 14:57:47 +02:00
connection.authStatus = Auth::verified;
}
}
else
{
2026-05-17 14:57:47 +02:00
connection.authStatus = Auth::verificationFailure;
LOG_VERBOSE("Connection %s: Signature verification failed!", hostName);
}
}
2018-06-22 23:02:47 +02:00
catch (const std::exception&)
{
2026-05-17 14:57:47 +02:00
connection.authStatus = Auth::verificationFailure;
LOG_VERBOSE("Connection %s: Signature verification failed, invalid data!", hostName);
}
}
2017-06-06 23:24:18 +02:00
bool passwordless = false;
2026-05-17 14:57:47 +02:00
if (connection.authStatus == Auth::verified)
{
const NetworkGroup* group = GetGroupByID(GetGroupIDByHash(connection.key.PublicKeyHash()));
if (group != nullptr)
{
2026-05-17 14:57:47 +02:00
passwordless = group->canPerformAction(Permission::passwordlessLogin);
}
}
if (gameversion != GetVersion())
{
2026-05-17 14:57:47 +02:00
connection.authStatus = Auth::badVersion;
LOG_INFO("Connection %s: Bad version.", hostName);
}
else if (name.empty())
{
2026-05-17 14:57:47 +02:00
connection.authStatus = Auth::badName;
LOG_INFO("Connection %s: Bad name.", connection.socket->GetHostName());
}
2018-06-22 23:02:47 +02:00
else if (!passwordless)
{
if (password.empty() && !_password.empty())
{
2026-05-17 14:57:47 +02:00
connection.authStatus = Auth::requirePassword;
LOG_INFO("Connection %s: Requires password.", hostName);
}
else if (!password.empty() && _password != password)
{
2026-05-17 14:57:47 +02:00
connection.authStatus = Auth::badPassword;
LOG_INFO("Connection %s: Bad password.", hostName);
}
}
2025-10-07 20:14:37 +02:00
if (GetNumVisiblePlayers() >= Config::Get().network.maxplayers)
{
2026-05-17 14:57:47 +02:00
connection.authStatus = Auth::full;
LOG_INFO("Connection %s: Server is full.", hostName);
}
2026-05-17 14:57:47 +02:00
else if (connection.authStatus == Auth::verified)
{
const std::string hash = connection.key.PublicKeyHash();
2020-04-28 19:33:30 +01:00
if (ProcessPlayerAuthenticatePluginHooks(connection, name, hash))
{
2026-05-17 14:57:47 +02:00
connection.authStatus = Auth::ok;
ServerClientJoined(name, hash, connection);
}
else
{
2026-05-17 14:57:47 +02:00
connection.authStatus = Auth::verificationFailure;
LOG_INFO("Connection %s: Denied by plugin.", hostName);
}
}
ServerSendAuth(connection);
}
}
void NetworkBase::Client_Handle_BEGINMAP([[maybe_unused]] Connection& connection, Packet& packet)
{
// Start of a new map load, clear the queue now as we have to buffer them
// until the map is fully loaded.
GameActions::ClearQueue();
GameActions::SuspendQueue();
displayNetworkProgress(STR_LOADING_SAVED_GAME);
}
void NetworkBase::Client_Handle_MAP([[maybe_unused]] Connection& connection, Packet& packet)
{
// Allow queue processing of game actions again.
GameActions::ResumeQueue();
// This prevents invoking the callback for when the window closes which would close the connection.
GetContext().CloseProgress();
GameUnloadScripts();
GameNotifyMapChange();
2026-05-17 14:57:47 +02:00
auto ms = MemoryStream(packet.data.data(), packet.data.size());
if (LoadMap(&ms))
{
2026-06-27 14:59:08 +02:00
GameLoadInit(); // NB: calls `setActiveScene`
GameLoadScripts();
GameNotifyMapChanged();
// This seems wrong, we want to catch up to that tick so we shouldn't mess with this.
//_serverState.tick = getGameState().currentTicks;
_serverState.state = ServerStatus::ok;
_clientMapLoaded = true;
gFirstTimeSaving = true;
// Notify user he is now online and which shortcut key enables chat
ChatShowConnectedMessage();
// Fix invalid vehicle sprite sizes, thus preventing visual corruption of sprites
FixInvalidVehicleSpriteSizes();
// NOTE: Game actions are normally processed before processing the player list.
// Given that during map load game actions are buffered we have to process the
// player list first to have valid players for the queued game actions.
ProcessPlayerList();
}
else
{
// Something went wrong, game is not loaded. Return to main screen.
auto loadOrQuitAction = GameActions::LoadOrQuitAction(
GameActions::LoadOrQuitModes::openSavePrompt, PromptMode::saveBeforeQuit);
2026-02-13 13:59:47 +01:00
auto& gameState = getGameState();
loadOrQuitAction.Execute(gameState, gameState.park);
}
}
bool NetworkBase::LoadMap(IStream* stream)
{
2017-06-06 23:24:18 +02:00
bool result = false;
try
{
auto& context = GetContext();
auto& objManager = context.GetObjectManager();
2021-10-27 14:21:14 +02:00
auto importer = ParkImporter::CreateParkFile(context.GetObjectRepository());
auto loadResult = importer->LoadFromStream(stream, false);
2021-09-12 21:25:22 +02:00
objManager.LoadObjects(loadResult.RequiredObjects);
MapAnimations::ClearAll();
// TODO: Have a separate GameState and exchange once loaded.
auto& gameState = getGameState();
importer->Import(gameState);
EntityTweener::get().reset();
MapAnimations::MarkAllTiles();
gLastAutoSaveUpdate = kAutosavePause;
2017-06-06 23:24:18 +02:00
result = true;
}
2021-10-27 14:21:14 +02:00
catch (const std::exception& e)
{
2021-10-27 14:21:14 +02:00
Console::Error::WriteLine("Unable to read map from server: %s", e.what());
}
2017-06-06 23:24:18 +02:00
return result;
}
bool NetworkBase::SaveMap(IStream* stream, const std::vector<const ObjectRepositoryItem*>& objects) const
{
2017-06-06 23:24:18 +02:00
bool result = false;
2022-03-07 20:40:48 +00:00
PrepareMapForSave();
try
{
2021-10-27 14:21:14 +02:00
auto exporter = std::make_unique<ParkFileExporter>();
exporter->ExportObjectsList = objects;
auto& gameState = getGameState();
exporter->Export(gameState, *stream, kParkFileNetCompressionLevel);
2017-06-06 23:24:18 +02:00
result = true;
}
2021-10-27 14:21:14 +02:00
catch (const std::exception& e)
{
2021-10-27 14:21:14 +02:00
Console::Error::WriteLine("Unable to serialise map: %s", e.what());
}
2017-06-06 23:24:18 +02:00
return result;
}
void NetworkBase::Client_Handle_CHAT([[maybe_unused]] Connection& connection, Packet& packet)
{
2026-05-17 14:57:47 +02:00
auto text = packet.readString();
if (!text.empty())
{
ChatAddHistory(std::string(text));
}
}
static bool ProcessChatMessagePluginHooks(uint8_t playerId, std::string& text)
{
#ifdef ENABLE_SCRIPTING
2020-04-22 22:53:32 +01:00
auto& hookEngine = GetContext()->GetScriptEngine().GetHookEngine();
if (hookEngine.HasSubscriptions(Scripting::HookType::networkChat))
{
2020-04-22 22:53:32 +01:00
auto ctx = GetContext()->GetScriptEngine().GetContext();
2020-04-22 22:53:32 +01:00
// Create event args object
2025-09-29 02:05:00 +10:00
JSValue obj = JS_NewObject(ctx);
JS_SetPropertyStr(ctx, obj, "player", JS_NewInt32(ctx, playerId));
JS_SetPropertyStr(ctx, obj, "message", Scripting::JSFromStdString(ctx, text));
2020-04-22 22:53:32 +01:00
// Call the subscriptions
2025-09-29 02:05:00 +10:00
hookEngine.Call(Scripting::HookType::networkChat, obj, false, true);
2020-04-22 22:53:32 +01:00
// Update text from object if subscriptions changed it
2025-09-29 02:05:00 +10:00
auto message = Scripting::JSToOptionalStdString(ctx, obj, "message");
JS_FreeValue(ctx, obj);
if (!message.has_value())
{
2020-04-22 22:53:32 +01:00
// Subscription set text to non-string, do not relay message
return false;
}
2025-09-29 02:05:00 +10:00
text = message.value();
2020-04-22 22:53:32 +01:00
if (text.empty())
{
2020-04-22 22:53:32 +01:00
// Subscription set text to empty string, do not relay message
return false;
}
}
#endif
2020-04-22 22:53:32 +01:00
return true;
}
void NetworkBase::ServerHandleChat(Connection& connection, Packet& packet)
{
2026-05-17 14:57:47 +02:00
auto szText = packet.readString();
if (szText.empty())
return;
if (connection.player != nullptr)
{
2026-05-17 14:57:47 +02:00
NetworkGroup* group = GetGroupByID(connection.player->group);
if (group == nullptr || !group->canPerformAction(Permission::chat))
{
return;
}
}
std::string text(szText);
if (connection.player != nullptr)
{
2026-05-17 14:57:47 +02:00
if (!ProcessChatMessagePluginHooks(connection.player->id, text))
{
2020-04-22 22:53:32 +01:00
// Message not to be relayed
return;
}
}
const char* formatted = FormatChat(connection.player, text.c_str());
2023-01-16 21:14:50 +01:00
ChatAddHistory(formatted);
ServerSendChat(formatted);
}
void NetworkBase::Client_Handle_GAME_ACTION([[maybe_unused]] Connection& connection, Packet& packet)
{
uint32_t tick;
GameCommand actionType;
packet >> tick >> actionType;
2017-07-21 18:21:18 +01:00
MemoryStream stream;
2026-05-17 14:57:47 +02:00
const size_t size = packet.header.size - packet.bytesRead;
stream.WriteArray(packet.read(size), size);
2017-07-21 18:21:18 +01:00
stream.SetPosition(0);
DataSerialiser ds(false, stream);
GameActions::GameAction::Ptr action = GameActions::Create(actionType);
if (action == nullptr)
{
LOG_ERROR("Received unregistered game action type: 0x%08X", actionType);
return;
}
action->Serialise(ds);
2018-11-20 06:04:42 +01:00
if (player_id == action->GetPlayer().id)
{
2018-03-24 05:50:59 +01:00
// Only execute callbacks that belong to us,
2017-10-02 18:02:50 +02:00
// clients can have identical network ids assigned.
auto itr = _gameActionCallbacks.find(action->GetNetworkId());
if (itr != _gameActionCallbacks.end())
{
2017-10-02 18:02:50 +02:00
action->SetCallback(itr->second);
_gameActionCallbacks.erase(itr);
}
}
GameActions::Enqueue(std::move(action), tick);
}
void NetworkBase::ServerHandleGameAction(Connection& connection, Packet& packet)
{
uint32_t tick;
GameCommand actionType;
Player* player = connection.player;
if (player == nullptr)
{
return;
}
packet >> tick >> actionType;
// Don't let clients send pause or quit
2026-08-06 18:40:41 +02:00
if (actionType == GameCommand::togglePause || actionType == GameCommand::loadOrQuit)
{
return;
}
2026-08-06 18:40:41 +02:00
if (actionType != GameCommand::custom)
{
2020-03-01 21:56:49 +00:00
// Check if player's group permission allows command to run
2026-05-17 14:57:47 +02:00
NetworkGroup* group = GetGroupByID(connection.player->group);
if (group == nullptr || group->canPerformCommand(actionType) == false)
{
ServerSendShowError(connection, STR_CANT_DO_THIS, STR_PERMISSION_DENIED);
return;
}
}
// Create and enqueue the action.
GameActions::GameAction::Ptr ga = GameActions::Create(actionType);
if (ga == nullptr)
{
LOG_ERROR(
2026-05-17 14:57:47 +02:00
"Received unregistered game action type: 0x%08X from player: (%d) %s", actionType, connection.player->id,
connection.player->name.c_str());
return;
}
2019-03-01 11:01:00 +01:00
// Player who is hosting is not affected by cooldowns.
2026-05-17 14:57:47 +02:00
if ((player->flags & PlayerFlags::kIsServer) == 0)
{
2026-05-17 14:57:47 +02:00
auto cooldownIt = player->cooldownTime.find(actionType);
if (cooldownIt != std::end(player->cooldownTime))
{
2019-03-01 11:01:00 +01:00
if (cooldownIt->second > 0)
{
ServerSendShowError(connection, STR_CANT_DO_THIS, STR_NETWORK_ACTION_RATE_LIMIT_MESSAGE);
return;
}
}
2019-03-01 11:01:00 +01:00
uint32_t cooldownTime = ga->GetCooldownTime();
if (cooldownTime > 0)
{
2026-05-17 14:57:47 +02:00
player->cooldownTime[actionType] = cooldownTime;
}
}
DataSerialiser stream(false);
2026-05-17 14:57:47 +02:00
const size_t size = packet.header.size - packet.bytesRead;
2026-09-06 13:39:03 +03:00
stream.getStream().WriteArray(packet.read(size), size);
stream.getStream().SetPosition(0);
ga->Serialise(stream);
// Set player to sender, should be 0 if sent from client.
2026-05-17 14:57:47 +02:00
ga->SetPlayer(PlayerId_t{ connection.player->id });
GameActions::Enqueue(std::move(ga), tick);
}
void NetworkBase::Client_Handle_TICK([[maybe_unused]] Connection& connection, Packet& packet)
{
uint32_t srand0;
uint32_t flags;
2019-05-11 21:31:34 +02:00
uint32_t serverTick;
2019-05-11 21:31:34 +02:00
packet >> serverTick >> srand0 >> flags;
ServerTickData tickData;
2019-03-12 21:07:48 +01:00
tickData.srand0 = srand0;
2019-05-11 21:31:34 +02:00
tickData.tick = serverTick;
2025-09-05 13:24:00 +02:00
if (flags & TickFlags::kChecksums)
{
2026-05-17 14:57:47 +02:00
auto text = packet.readString();
if (!text.empty())
{
2019-03-12 21:07:48 +01:00
tickData.spriteHash = text;
}
}
2019-03-12 21:07:48 +01:00
// Don't let the history grow too much.
while (_serverTickData.size() >= 100)
{
2019-03-12 21:07:48 +01:00
_serverTickData.erase(_serverTickData.begin());
}
2019-05-11 21:31:34 +02:00
_serverState.tick = serverTick;
_serverTickData.emplace(serverTick, tickData);
}
void NetworkBase::Client_Handle_PLAYERINFO([[maybe_unused]] Connection& connection, Packet& packet)
{
2019-03-24 15:16:57 -07:00
uint32_t tick;
packet >> tick;
Player playerInfo;
2026-05-17 14:57:47 +02:00
playerInfo.read(packet);
2019-03-24 15:16:57 -07:00
_pendingPlayerInfo.emplace(tick, playerInfo);
}
void NetworkBase::Client_Handle_PLAYERLIST([[maybe_unused]] Connection& connection, Packet& packet)
{
uint32_t tick;
uint8_t size;
packet >> tick >> size;
auto& pending = _pendingPlayerLists[tick];
pending.players.clear();
2018-06-22 23:02:47 +02:00
for (uint32_t i = 0; i < size; i++)
{
Player tempplayer;
2026-05-17 14:57:47 +02:00
tempplayer.read(packet);
pending.players.push_back(std::move(tempplayer));
}
}
void NetworkBase::Client_Handle_PING([[maybe_unused]] Connection& connection, [[maybe_unused]] Packet& packet)
{
2017-06-06 23:24:18 +02:00
Client_Send_PING();
}
void NetworkBase::ServerHandlePing(Connection& connection, [[maybe_unused]] Packet& packet)
{
2026-05-17 14:57:47 +02:00
int32_t ping = Platform::GetTicks() - connection.pingTime;
2018-06-22 23:02:47 +02:00
if (ping < 0)
{
2017-06-06 23:24:18 +02:00
ping = 0;
}
if (connection.player != nullptr)
{
2026-05-17 14:57:47 +02:00
connection.player->ping = ping;
auto* windowMgr = Ui::GetWindowManager();
2026-05-17 14:57:47 +02:00
windowMgr->InvalidateByNumber(WindowClass::player, connection.player->id);
}
}
void NetworkBase::Client_Handle_PINGLIST([[maybe_unused]] Connection& connection, Packet& packet)
{
uint8_t size;
2017-06-06 23:24:18 +02:00
packet >> size;
2018-06-22 23:02:47 +02:00
for (uint32_t i = 0; i < size; i++)
{
uint8_t id;
uint16_t ping;
2017-06-06 23:24:18 +02:00
packet >> id >> ping;
Player* player = GetPlayerByID(id);
2021-09-24 20:05:50 +02:00
if (player != nullptr)
{
2026-05-17 14:57:47 +02:00
player->ping = ping;
}
}
auto* windowMgr = Ui::GetWindowManager();
windowMgr->InvalidateByClass(WindowClass::player);
}
void NetworkBase::Client_Handle_SETDISCONNECTMSG(Connection& connection, Packet& packet)
{
2026-05-17 14:57:47 +02:00
auto disconnectmsg = packet.readString();
if (!disconnectmsg.empty())
{
2026-05-17 14:57:47 +02:00
connection.setLastDisconnectReason(disconnectmsg);
}
}
void NetworkBase::ServerHandleGameInfo(Connection& connection, [[maybe_unused]] Packet& packet)
{
ServerSendGameInfo(connection);
}
void NetworkBase::Client_Handle_SHOWERROR([[maybe_unused]] Connection& connection, Packet& packet)
{
2022-07-31 14:22:58 +02:00
StringId title, message;
2017-06-06 23:24:18 +02:00
packet >> title >> message;
2022-11-06 20:49:07 +00:00
ContextShowError(title, message, {});
}
void NetworkBase::Client_Handle_GROUPLIST([[maybe_unused]] Connection& connection, Packet& packet)
{
2017-06-06 23:24:18 +02:00
group_list.clear();
uint8_t size;
2017-06-06 23:24:18 +02:00
packet >> size >> default_group;
2018-06-22 23:02:47 +02:00
for (uint32_t i = 0; i < size; i++)
{
2017-06-06 23:24:18 +02:00
NetworkGroup group;
2026-05-17 14:57:47 +02:00
group.read(packet);
2018-05-12 15:13:48 +02:00
auto newgroup = std::make_unique<NetworkGroup>(group);
2017-06-06 23:24:18 +02:00
group_list.push_back(std::move(newgroup));
}
}
void NetworkBase::Client_Handle_EVENT([[maybe_unused]] Connection& connection, Packet& packet)
{
2025-09-05 13:24:00 +02:00
ServerEvent eventType;
2017-06-06 23:24:18 +02:00
packet >> eventType;
2018-06-22 23:02:47 +02:00
switch (eventType)
{
2025-09-05 13:24:00 +02:00
case ServerEvent::playerJoined:
{
2026-05-17 14:57:47 +02:00
auto playerName = packet.readString();
auto message = FormatStringID(STR_MULTIPLAYER_PLAYER_HAS_JOINED_THE_GAME, playerName);
2023-01-16 21:14:50 +01:00
ChatAddHistory(message);
break;
}
2025-09-05 13:24:00 +02:00
case ServerEvent::playerDisconnected:
{
2026-05-17 14:57:47 +02:00
auto playerName = packet.readString();
auto reason = packet.readString();
std::string message;
if (reason.empty())
{
message = FormatStringID(STR_MULTIPLAYER_PLAYER_HAS_DISCONNECTED_NO_REASON, playerName);
}
else
{
message = FormatStringID(STR_MULTIPLAYER_PLAYER_HAS_DISCONNECTED_WITH_REASON, playerName, reason);
}
2023-01-16 21:14:50 +01:00
ChatAddHistory(message);
break;
}
}
}
void NetworkBase::Client_Send_GAMEINFO()
{
LOG_VERBOSE("requesting gameinfo");
Packet packet(Command::gameInfo);
2026-05-17 14:57:47 +02:00
_serverConnection->queuePacket(std::move(packet));
}
void NetworkBase::Client_Handle_GAMEINFO([[maybe_unused]] Connection& connection, Packet& packet)
{
2026-05-17 14:57:47 +02:00
auto jsonString = packet.readString();
2019-05-11 21:31:34 +02:00
packet >> _serverState.gamestateSnapshotsEnabled;
packet >> IsServerPlayerInvisible;
json_t jsonData = Json::FromString(jsonString);
if (jsonData.is_object())
{
ServerName = Json::GetString(jsonData["name"]);
ServerDescription = Json::GetString(jsonData["description"]);
ServerGreeting = Json::GetString(jsonData["greeting"]);
json_t jsonProvider = jsonData["provider"];
if (jsonProvider.is_object())
{
ServerProviderName = Json::GetString(jsonProvider["name"]);
ServerProviderEmail = Json::GetString(jsonProvider["email"]);
ServerProviderWebsite = Json::GetString(jsonProvider["website"]);
}
}
ChatShowServerGreeting();
}
void Reconnect()
{
GetContext()->GetNetwork().Reconnect();
}
void ShutdownClient()
{
GetContext()->GetNetwork().ServerClientDisconnected();
}
int32_t BeginClient(const std::string& host, int32_t port)
{
return GetContext()->GetNetwork().BeginClient(host, port);
}
int32_t BeginServer(int32_t port, const std::string& address)
{
return GetContext()->GetNetwork().BeginServer(port, address);
}
void Update()
{
GetContext()->GetNetwork().Update();
}
void Tick()
{
GetContext()->GetNetwork().Tick();
}
void PostTick()
{
GetContext()->GetNetwork().PostTick();
}
void Flush()
{
GetContext()->GetNetwork().Flush();
}
Mode GetMode()
{
return GetContext()->GetNetwork().GetMode();
}
Status GetStatus()
{
return GetContext()->GetNetwork().GetStatus();
}
bool IsDesynchronised()
{
return GetContext()->GetNetwork().IsDesynchronised();
}
bool CheckDesynchronisation()
{
return GetContext()->GetNetwork().CheckDesynchronizaton();
}
void RequestGamestateSnapshot()
{
return GetContext()->GetNetwork().RequestStateSnapshot();
}
void SendTick()
{
GetContext()->GetNetwork().ServerSendTick();
}
Auth GetAuthstatus()
{
return GetContext()->GetNetwork().GetAuthStatus();
}
uint32_t GetServerTick()
{
return GetContext()->GetNetwork().GetServerTick();
}
uint8_t GetCurrentPlayerId()
{
return GetContext()->GetNetwork().GetPlayerID();
}
int32_t GetNumPlayers()
{
return GetContext()->GetNetwork().GetTotalNumPlayers();
}
int32_t GetNumVisiblePlayers()
{
return GetContext()->GetNetwork().GetNumVisiblePlayers();
}
const char* GetPlayerName(uint32_t index)
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
Guard::IndexInRange(index, network.player_list);
2026-05-17 14:57:47 +02:00
return static_cast<const char*>(network.player_list[index]->name.c_str());
}
uint32_t GetPlayerFlags(uint32_t index)
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
Guard::IndexInRange(index, network.player_list);
2026-05-17 14:57:47 +02:00
return network.player_list[index]->flags;
}
int32_t GetPlayerPing(uint32_t index)
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
Guard::IndexInRange(index, network.player_list);
2026-05-17 14:57:47 +02:00
return network.player_list[index]->ping;
}
int32_t GetPlayerID(uint32_t index)
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
Guard::IndexInRange(index, network.player_list);
2026-05-17 14:57:47 +02:00
return network.player_list[index]->id;
}
money64 GetPlayerMoneySpent(uint32_t index)
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
Guard::IndexInRange(index, network.player_list);
2026-05-17 14:57:47 +02:00
return network.player_list[index]->moneySpent;
}
std::string GetPlayerIPAddress(uint32_t id)
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
auto conn = network.GetPlayerConnection(id);
2026-05-17 14:57:47 +02:00
if (conn != nullptr && conn->socket != nullptr)
{
2026-05-17 14:57:47 +02:00
return conn->socket->GetIpAddress();
}
return {};
}
std::string GetPlayerPublicKeyHash(uint32_t id)
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
auto player = network.GetPlayerByID(id);
if (player != nullptr)
{
2026-05-17 14:57:47 +02:00
return player->keyHash;
}
return {};
}
void IncrementPlayerNumCommands(uint32_t playerIndex)
{
auto& network = GetContext()->GetNetwork();
Guard::IndexInRange(playerIndex, network.player_list);
2026-05-17 14:57:47 +02:00
network.player_list[playerIndex]->incrementNumCommands();
}
void AddPlayerMoneySpent(uint32_t index, money64 cost)
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
Guard::IndexInRange(index, network.player_list);
2026-05-17 14:57:47 +02:00
network.player_list[index]->addMoneySpent(cost);
}
int32_t GetPlayerLastAction(uint32_t index, int32_t time)
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
Guard::IndexInRange(index, network.player_list);
2026-05-17 14:57:47 +02:00
if (time && Platform::GetTicks() > network.player_list[index]->lastActionTime + time)
{
2017-06-06 23:24:18 +02:00
return -999;
}
2026-05-17 14:57:47 +02:00
return network.player_list[index]->lastAction;
}
void SetPlayerLastAction(uint32_t index, GameCommand command)
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
Guard::IndexInRange(index, network.player_list);
2026-05-17 14:57:47 +02:00
network.player_list[index]->lastAction = static_cast<int32_t>(NetworkActions::findCommand(command));
network.player_list[index]->lastActionTime = Platform::GetTicks();
}
CoordsXYZ GetPlayerLastActionCoord(uint32_t index)
{
auto& network = GetContext()->GetNetwork();
Guard::IndexInRange(index, GetContext()->GetNetwork().player_list);
2026-05-17 14:57:47 +02:00
return network.player_list[index]->lastActionCoord;
}
void SetPlayerLastActionCoord(uint32_t index, const CoordsXYZ& coord)
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
Guard::IndexInRange(index, network.player_list);
2021-08-17 06:20:07 +03:00
if (index < network.player_list.size())
{
2026-05-17 14:57:47 +02:00
network.player_list[index]->lastActionCoord = coord;
}
}
uint32_t GetPlayerCommandsRan(uint32_t index)
{
auto& network = GetContext()->GetNetwork();
Guard::IndexInRange(index, GetContext()->GetNetwork().player_list);
2026-05-17 14:57:47 +02:00
return network.player_list[index]->commandsRan;
}
int32_t GetPlayerIndex(uint32_t id)
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
auto it = network.GetPlayerIteratorByID(id);
if (it == network.player_list.end())
{
2017-06-06 23:24:18 +02:00
return -1;
}
2021-08-17 06:20:07 +03:00
return static_cast<int32_t>(network.GetPlayerIteratorByID(id) - network.player_list.begin());
}
uint8_t GetPlayerGroup(uint32_t index)
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
Guard::IndexInRange(index, network.player_list);
2026-05-17 14:57:47 +02:00
return network.player_list[index]->group;
}
void SetPlayerGroup(uint32_t index, uint32_t groupindex)
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
Guard::IndexInRange(index, network.player_list);
Guard::IndexInRange(groupindex, network.group_list);
2026-05-17 14:57:47 +02:00
network.player_list[index]->group = network.group_list[groupindex]->id;
}
int32_t GetGroupIndex(uint8_t id)
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
auto it = network.GetGroupIteratorByID(id);
if (it == network.group_list.end())
{
2017-06-06 23:24:18 +02:00
return -1;
}
return static_cast<int32_t>(network.GetGroupIteratorByID(id) - network.group_list.begin());
}
uint8_t GetGroupID(uint32_t index)
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
Guard::IndexInRange(index, network.group_list);
2026-05-17 14:57:47 +02:00
return network.group_list[index]->id;
}
int32_t GetNumGroups()
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
return static_cast<int32_t>(network.group_list.size());
}
const char* GetGroupName(uint32_t index)
{
auto& network = GetContext()->GetNetwork();
2026-05-17 14:57:47 +02:00
return network.group_list[index]->getName().c_str();
}
void ChatShowConnectedMessage()
{
auto windowManager = Ui::GetWindowManager();
2021-01-16 18:04:58 +00:00
std::string s = windowManager->GetKeyboardShortcutString("interface.misc.multiplayer_chat");
2018-06-22 23:02:47 +02:00
const char* sptr = s.c_str();
2017-06-06 23:24:18 +02:00
utf8 buffer[256];
FormatStringLegacy(buffer, sizeof(buffer), STR_MULTIPLAYER_CONNECTED_CHAT_HINT, &sptr);
Player server;
2026-05-17 14:57:47 +02:00
server.name = "Server";
const char* formatted = NetworkBase::FormatChat(&server, buffer);
2023-01-16 21:14:50 +01:00
ChatAddHistory(formatted);
}
// Display server greeting if one exists
void ChatShowServerGreeting()
{
const auto& greeting = GetServerGreeting();
2023-01-07 15:39:55 +01:00
if (!greeting.empty())
{
2020-10-13 23:34:18 +01:00
thread_local std::string greeting_formatted;
greeting_formatted.assign("{OUTLINE}{GREEN}");
greeting_formatted += greeting;
2023-01-16 21:14:50 +01:00
ChatAddHistory(greeting_formatted);
}
}
GameActions::Result SetPlayerGroup(PlayerId_t actionPlayerId, PlayerId_t playerId, uint8_t groupId, bool isExecuting)
{
auto& network = GetContext()->GetNetwork();
Player* player = network.GetPlayerByID(playerId);
2021-08-17 06:20:07 +03:00
NetworkGroup* fromgroup = network.GetGroupByID(actionPlayerId);
2019-05-01 16:54:12 +01:00
if (player == nullptr)
{
2025-12-12 11:41:49 +01:00
return GameActions::Result(GameActions::Status::invalidParameters, STR_CANT_DO_THIS, kStringIdNone);
}
2021-09-24 20:05:50 +02:00
if (network.GetGroupByID(groupId) == nullptr)
{
2025-12-12 11:41:49 +01:00
return GameActions::Result(GameActions::Status::invalidParameters, STR_CANT_DO_THIS, kStringIdNone);
}
2026-05-17 14:57:47 +02:00
if (player->flags & PlayerFlags::kIsServer)
{
2024-01-22 02:29:08 -08:00
return GameActions::Result(
2025-12-12 11:41:49 +01:00
GameActions::Status::invalidParameters, STR_CANT_CHANGE_GROUP_THAT_THE_HOST_BELONGS_TO, kStringIdNone);
2017-06-06 23:24:18 +02:00
}
2016-01-23 18:05:53 -07:00
2026-05-17 14:57:47 +02:00
if (groupId == 0 && fromgroup != nullptr && fromgroup->id != 0)
2018-06-22 23:02:47 +02:00
{
2025-12-12 11:41:49 +01:00
return GameActions::Result(GameActions::Status::invalidParameters, STR_CANT_SET_TO_THIS_GROUP, kStringIdNone);
}
2019-05-01 16:54:12 +01:00
if (isExecuting)
{
2026-05-17 14:57:47 +02:00
player->group = groupId;
if (GetMode() == Mode::server)
{
2017-06-06 23:24:18 +02:00
// Add or update saved user
UserManager& userManager = network._userManager;
2026-05-17 14:57:47 +02:00
User* networkUser = userManager.getOrAddUser(player->keyHash);
networkUser->groupId = groupId;
networkUser->name = player->name;
userManager.save();
}
auto* windowMgr = Ui::GetWindowManager();
windowMgr->InvalidateByNumber(WindowClass::player, playerId);
2017-06-06 23:24:18 +02:00
// Log set player group event
Player* game_command_player = network.GetPlayerByID(actionPlayerId);
2021-08-17 06:20:07 +03:00
NetworkGroup* new_player_group = network.GetGroupByID(groupId);
2017-06-06 23:24:18 +02:00
char log_msg[256];
const char* args[3] = {
2026-05-17 14:57:47 +02:00
player->name.c_str(),
new_player_group->getName().c_str(),
game_command_player->name.c_str(),
};
FormatStringLegacy(log_msg, 256, STR_LOG_SET_PLAYER_GROUP, args);
AppendServerLog(log_msg);
}
return GameActions::Result();
}
GameActions::Result ModifyGroups(
PlayerId_t actionPlayerId, GameActions::ModifyGroupType type, uint8_t groupId, const std::string& name,
uint32_t permissionIndex, GameActions::PermissionState permissionState, bool isExecuting)
{
auto& network = GetContext()->GetNetwork();
switch (type)
{
case GameActions::ModifyGroupType::addGroup:
{
if (isExecuting)
{
2021-08-17 06:20:07 +03:00
NetworkGroup* newgroup = network.AddGroup();
2019-05-13 19:49:06 +01:00
if (newgroup == nullptr)
{
2025-12-12 11:41:49 +01:00
return GameActions::Result(GameActions::Status::unknown, STR_CANT_DO_THIS, kStringIdNone);
}
}
}
break;
case GameActions::ModifyGroupType::removeGroup:
{
if (groupId == 0)
{
return GameActions::Result(
2025-12-12 11:41:49 +01:00
GameActions::Status::disallowed, STR_THIS_GROUP_CANNOT_BE_MODIFIED, kStringIdNone);
}
2021-08-17 06:20:07 +03:00
for (const auto& it : network.player_list)
{
2026-05-17 14:57:47 +02:00
if ((it.get())->group == groupId)
{
return GameActions::Result(
2025-12-12 11:41:49 +01:00
GameActions::Status::disallowed, STR_CANT_REMOVE_GROUP_THAT_PLAYERS_BELONG_TO, kStringIdNone);
}
}
if (isExecuting)
{
2021-08-17 06:20:07 +03:00
network.RemoveGroup(groupId);
}
}
break;
case GameActions::ModifyGroupType::setPermissions:
{
if (groupId == 0)
2021-01-10 18:23:35 +00:00
{ // can't change admin group permissions
return GameActions::Result(
2025-12-12 11:41:49 +01:00
GameActions::Status::disallowed, STR_THIS_GROUP_CANNOT_BE_MODIFIED, kStringIdNone);
}
2018-06-22 23:02:47 +02:00
NetworkGroup* mygroup = nullptr;
Player* player = network.GetPlayerByID(actionPlayerId);
auto networkPermission = static_cast<Permission>(permissionIndex);
if (player != nullptr && permissionState == GameActions::PermissionState::toggle)
{
2026-05-17 14:57:47 +02:00
mygroup = network.GetGroupByID(player->group);
if (mygroup == nullptr || !mygroup->canPerformAction(networkPermission))
{
return GameActions::Result(
2025-12-12 11:41:49 +01:00
GameActions::Status::disallowed, STR_CANT_MODIFY_PERMISSION_THAT_YOU_DO_NOT_HAVE_YOURSELF,
2025-01-19 16:59:45 +01:00
kStringIdNone);
}
}
if (isExecuting)
{
2021-08-17 06:20:07 +03:00
NetworkGroup* group = network.GetGroupByID(groupId);
2019-05-13 19:49:06 +01:00
if (group != nullptr)
{
if (permissionState != GameActions::PermissionState::toggle)
{
2019-05-13 19:49:06 +01:00
if (mygroup != nullptr)
{
if (permissionState == GameActions::PermissionState::setAll)
{
2026-05-17 14:57:47 +02:00
group->actionsAllowed = mygroup->actionsAllowed;
}
else
{
2026-05-17 14:57:47 +02:00
group->actionsAllowed.fill(0x00);
}
}
}
else
{
2026-05-17 14:57:47 +02:00
group->toggleActionPermission(networkPermission);
}
}
}
}
break;
case GameActions::ModifyGroupType::setName:
{
2021-08-17 06:20:07 +03:00
NetworkGroup* group = network.GetGroupByID(groupId);
2019-05-13 19:49:06 +01:00
if (group == nullptr)
{
2025-12-12 11:41:49 +01:00
return GameActions::Result(GameActions::Status::invalidParameters, STR_CANT_RENAME_GROUP, kStringIdNone);
}
2026-05-17 14:57:47 +02:00
const char* oldName = group->getName().c_str();
2018-06-22 23:02:47 +02:00
if (strcmp(oldName, name.c_str()) == 0)
{
return GameActions::Result();
}
if (name.empty())
{
return GameActions::Result(
2025-12-12 11:41:49 +01:00
GameActions::Status::invalidParameters, STR_CANT_RENAME_GROUP, STR_INVALID_GROUP_NAME);
}
if (isExecuting)
{
2019-05-13 19:49:06 +01:00
if (group != nullptr)
{
2026-05-17 14:57:47 +02:00
group->setName(name);
}
}
}
break;
case GameActions::ModifyGroupType::setDefault:
{
if (groupId == 0)
{
2025-12-12 11:41:49 +01:00
return GameActions::Result(GameActions::Status::disallowed, STR_CANT_SET_TO_THIS_GROUP, kStringIdNone);
}
if (isExecuting)
{
2021-08-17 06:20:07 +03:00
network.SetDefaultGroup(groupId);
}
}
break;
default:
LOG_ERROR("Invalid Modify Group Type: %u", static_cast<uint8_t>(type));
2024-01-22 02:29:08 -08:00
return GameActions::Result(
2025-12-12 11:41:49 +01:00
GameActions::Status::invalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_VALUE_OUT_OF_RANGE);
}
2021-08-17 06:20:07 +03:00
network.SaveGroups();
return GameActions::Result();
}
GameActions::Result KickPlayer(PlayerId_t playerId, bool isExecuting)
{
auto& network = GetContext()->GetNetwork();
Player* player = network.GetPlayerByID(playerId);
2019-05-01 16:54:12 +01:00
if (player == nullptr)
{
2020-02-10 23:33:00 +00:00
// Player might be already removed by the PLAYERLIST command, need to refactor non-game commands executing too
// early.
2024-01-22 02:29:08 -08:00
return GameActions::Result(
2025-12-12 11:41:49 +01:00
GameActions::Status::invalidParameters, STR_ERR_INVALID_PARAMETER, STR_ERR_PLAYER_NOT_FOUND);
}
2026-05-17 14:57:47 +02:00
if (player->flags & PlayerFlags::kIsServer)
{
2025-12-12 11:41:49 +01:00
return GameActions::Result(GameActions::Status::disallowed, STR_CANT_KICK_THE_HOST, kStringIdNone);
}
if (isExecuting)
{
if (network.GetMode() == Mode::server)
{
2021-08-17 06:20:07 +03:00
network.KickPlayer(playerId);
UserManager& networkUserManager = network._userManager;
2026-05-17 14:57:47 +02:00
networkUserManager.load();
networkUserManager.removeUser(player->keyHash);
networkUserManager.save();
}
}
return GameActions::Result();
}
uint8_t GetDefaultGroup()
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
return network.GetDefaultGroup();
}
int32_t GetNumActions()
{
2026-05-17 14:57:47 +02:00
return static_cast<int32_t>(NetworkActions::kActions.size());
}
StringId GetActionNameStringID(uint32_t index)
{
2026-05-17 14:57:47 +02:00
if (index < NetworkActions::kActions.size())
{
2026-05-17 14:57:47 +02:00
return NetworkActions::kActions[index].name;
}
2025-01-19 16:59:45 +01:00
return kStringIdNone;
}
bool CanPerformAction(uint32_t groupindex, Permission index)
{
auto& network = GetContext()->GetNetwork();
if (groupindex >= network.group_list.size())
return false;
2026-05-17 14:57:47 +02:00
return network.group_list[groupindex]->canPerformAction(index);
}
bool CanPerformCommand(uint32_t groupindex, int32_t index)
{
auto& network = GetContext()->GetNetwork();
if (groupindex >= network.group_list.size())
return false;
2026-05-17 14:57:47 +02:00
return network.group_list[groupindex]->canPerformCommand(static_cast<GameCommand>(index)); // TODO
}
void SetPickupPeep(uint8_t playerid, Peep* peep)
{
auto& network = GetContext()->GetNetwork();
if (network.GetMode() == Mode::none)
{
2017-07-22 11:56:46 +02:00
_pickup_peep = peep;
}
else
{
Player* player = network.GetPlayerByID(playerid);
2021-09-24 20:05:50 +02:00
if (player != nullptr)
{
2026-05-17 14:57:47 +02:00
player->pickupPeep = peep;
}
2017-06-06 23:24:18 +02:00
}
}
2016-01-21 23:32:40 -07:00
Peep* GetPickupPeep(uint8_t playerid)
2017-06-06 23:24:18 +02:00
{
auto& network = GetContext()->GetNetwork();
if (network.GetMode() == Mode::none)
{
2017-06-06 23:24:18 +02:00
return _pickup_peep;
}
Player* player = network.GetPlayerByID(playerid);
2021-09-24 20:05:50 +02:00
if (player != nullptr)
{
2026-05-17 14:57:47 +02:00
return player->pickupPeep;
}
2021-09-15 22:22:15 +02:00
return nullptr;
2018-06-22 23:02:47 +02:00
}
2021-09-15 22:22:15 +02:00
void SetPickupPeepOldX(uint8_t playerid, int32_t x)
{
2025-01-19 16:59:45 +01:00
auto& network = GetContext()->GetNetwork();
if (network.GetMode() == Mode::none)
{
2017-07-22 11:56:46 +02:00
_pickup_peep_old_x = x;
}
else
{
Player* player = network.GetPlayerByID(playerid);
2025-01-19 16:59:45 +01:00
if (player != nullptr)
{
2026-05-17 14:57:47 +02:00
player->pickupPeepOldX = x;
}
}
}
int32_t GetPickupPeepOldX(uint8_t playerid)
{
auto& network = GetContext()->GetNetwork();
if (network.GetMode() == Mode::none)
{
return _pickup_peep_old_x;
}
Player* player = network.GetPlayerByID(playerid);
2021-09-24 20:05:50 +02:00
if (player != nullptr)
{
2026-05-17 14:57:47 +02:00
return player->pickupPeepOldX;
}
2021-09-15 22:22:15 +02:00
return -1;
}
bool IsServerPlayerInvisible()
{
return GetContext()->GetNetwork().IsServerPlayerInvisible;
}
int32_t GetCurrentPlayerGroupIndex()
{
auto& network = GetContext()->GetNetwork();
Player* player = network.GetPlayerByID(network.GetPlayerID());
2021-09-24 20:05:50 +02:00
if (player != nullptr)
{
2026-05-17 14:57:47 +02:00
return GetGroupIndex(player->group);
}
2017-07-22 11:56:46 +02:00
return -1;
}
void SendChat(const char* text, const std::vector<uint8_t>& playerIds)
{
auto& network = GetContext()->GetNetwork();
if (network.GetMode() == Mode::client)
{
2021-08-17 06:20:07 +03:00
network.Client_Send_CHAT(text);
}
else if (network.GetMode() == Mode::server)
{
std::string message = text;
2021-08-17 06:20:07 +03:00
if (ProcessChatMessagePluginHooks(network.GetPlayerID(), message))
{
2021-08-17 06:20:07 +03:00
auto player = network.GetPlayerByID(network.GetPlayerID());
if (player != nullptr)
{
auto formatted = network.FormatChat(player, message.c_str());
2020-04-28 22:02:14 +01:00
if (playerIds.empty()
2021-08-17 06:20:07 +03:00
|| std::find(playerIds.begin(), playerIds.end(), network.GetPlayerID()) != playerIds.end())
{
2020-04-30 02:18:32 +01:00
// Server is one of the recipients
2023-01-16 21:14:50 +01:00
ChatAddHistory(formatted);
}
network.ServerSendChat(formatted, playerIds);
}
}
}
}
void SendGameAction(const GameActions::GameAction* action)
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
switch (network.GetMode())
{
case Mode::server:
network.ServerSendGameAction(action);
break;
case Mode::client:
2021-08-17 06:20:07 +03:00
network.Client_Send_GAME_ACTION(action);
break;
default:
break;
}
}
void SendPassword(const std::string& password)
{
auto& network = GetContext()->GetNetwork();
2025-10-07 20:14:37 +02:00
const auto keyPath = GetPrivateKeyPath(Config::Get().network.playerName);
if (!File::Exists(keyPath))
{
LOG_ERROR("Private key %s missing! Restart the game to generate it.", keyPath.c_str());
return;
}
try
{
2025-03-25 18:23:36 +01:00
auto fs = FileStream(keyPath, FileMode::open);
2021-08-17 06:20:07 +03:00
network._key.LoadPrivate(&fs);
}
2018-06-22 23:02:47 +02:00
catch (const std::exception&)
{
LOG_ERROR("Error reading private key from %s.", keyPath.c_str());
return;
}
2021-08-17 06:20:07 +03:00
const std::string pubkey = network._key.PublicKeyString();
std::vector<uint8_t> signature;
2021-08-17 06:20:07 +03:00
network._key.Sign(network._challenge.data(), network._challenge.size(), signature);
// Don't keep private key in memory. There's no need and it may get leaked
2017-06-06 23:24:18 +02:00
// when process dump gets collected at some point in future.
2021-08-17 06:20:07 +03:00
network._key.Unload();
2025-10-07 20:14:37 +02:00
network.Client_Send_AUTH(Config::Get().network.playerName, password, pubkey, signature);
}
void SetPassword(const char* password)
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
network.SetPassword(password);
}
void AppendChatLog(std::string_view text)
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
network.AppendChatLog(text);
}
void AppendServerLog(const utf8* text)
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
network.AppendServerLog(text);
}
static u8string GetKeysDirectory()
{
auto& env = GetContext()->GetPlatformEnvironment();
return Path::Combine(env.GetDirectoryPath(DirBase::user), u8"keys");
}
static u8string GetPrivateKeyPath(u8string_view playerName)
{
return Path::Combine(GetKeysDirectory(), u8string(playerName) + u8".privkey");
}
static u8string GetPublicKeyPath(u8string_view playerName, u8string_view hash)
{
2022-02-27 22:23:35 +01:00
const auto filename = u8string(playerName) + u8"-" + u8string(hash) + u8".pubkey";
return Path::Combine(GetKeysDirectory(), filename);
}
u8string GetServerName()
{
auto& network = GetContext()->GetNetwork();
2023-01-07 15:39:55 +01:00
return network.ServerName;
}
u8string GetServerDescription()
{
auto& network = GetContext()->GetNetwork();
2023-01-07 15:39:55 +01:00
return network.ServerDescription;
}
u8string GetServerGreeting()
{
auto& network = GetContext()->GetNetwork();
2023-01-07 15:39:55 +01:00
return network.ServerGreeting;
}
u8string GetServerProviderName()
{
auto& network = GetContext()->GetNetwork();
2023-01-07 15:39:55 +01:00
return network.ServerProviderName;
}
u8string GetServerProviderEmail()
{
auto& network = GetContext()->GetNetwork();
2023-01-07 15:39:55 +01:00
return network.ServerProviderEmail;
}
u8string GetServerProviderWebsite()
{
auto& network = GetContext()->GetNetwork();
2023-01-07 15:39:55 +01:00
return network.ServerProviderWebsite;
}
std::string GetVersion()
{
return kStreamID;
}
Stats GetStats()
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
return network.GetStats();
}
ServerState GetServerState()
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
return network.GetServerState();
}
bool GamestateSnapshotsEnabled()
{
return GetServerState().gamestateSnapshotsEnabled;
}
json_t GetServerInfoAsJson()
{
auto& network = GetContext()->GetNetwork();
2021-08-17 06:20:07 +03:00
return network.GetServerInfoAsJson();
}
2020-04-28 19:33:30 +01:00
} // namespace OpenRCT2::Network
#else // DISABLE_NETWORK
2020-04-28 19:33:30 +01:00
namespace OpenRCT2::Network
{
Mode GetMode()
{
return Mode::none;
}
Status GetStatus()
{
return Status::none;
}
Auth GetAuthstatus()
{
return Auth::none;
}
uint32_t GetServerTick()
{
return getGameState().currentTicks;
}
void Flush()
{
}
void SendTick()
{
}
bool IsDesynchronised()
{
2019-05-11 21:31:34 +02:00
return false;
}
bool GamestateSnapshotsEnabled()
{
2019-05-11 21:31:34 +02:00
return false;
}
bool CheckDesynchronisation()
{
2019-05-11 21:31:34 +02:00
return false;
}
void RequestGamestateSnapshot()
{
}
void SendGameAction(const GameActions::GameAction* action)
{
}
void Tick()
{
}
void Update()
{
}
void PostTick()
{
}
int32_t BeginClient(const std::string& host, int32_t port)
{
return 1;
}
int32_t BeginServer(int32_t port, const std::string& address)
{
return 1;
}
int32_t GetNumPlayers()
{
return 1;
}
int32_t GetNumVisiblePlayers()
{
return 1;
}
const char* GetPlayerName(uint32_t index)
{
2021-08-17 06:20:07 +03:00
return "local (OpenRCT2 compiled without MP)";
}
uint32_t GetPlayerFlags(uint32_t index)
{
2018-06-22 23:02:47 +02:00
return 0;
}
int32_t GetPlayerPing(uint32_t index)
{
2018-06-22 23:02:47 +02:00
return 0;
}
int32_t GetPlayerID(uint32_t index)
{
2018-06-22 23:02:47 +02:00
return 0;
}
money64 GetPlayerMoneySpent(uint32_t index)
{
return 0.00_GBP;
}
std::string GetPlayerIPAddress(uint32_t id)
{
return {};
}
std::string GetPlayerPublicKeyHash(uint32_t id)
{
return {};
}
void IncrementPlayerNumCommands(uint32_t playerIndex)
{
}
void AddPlayerMoneySpent(uint32_t index, money64 cost)
{
}
int32_t GetPlayerLastAction(uint32_t index, int32_t time)
{
2018-06-22 23:02:47 +02:00
return -999;
}
void SetPlayerLastAction(uint32_t index, GameCommand command)
{
}
CoordsXYZ GetPlayerLastActionCoord(uint32_t index)
{
2018-06-22 23:02:47 +02:00
return { 0, 0, 0 };
}
void SetPlayerLastActionCoord(uint32_t index, const CoordsXYZ& coord)
{
}
uint32_t GetPlayerCommandsRan(uint32_t index)
{
2018-06-22 23:02:47 +02:00
return 0;
}
int32_t GetPlayerIndex(uint32_t id)
{
2018-06-22 23:02:47 +02:00
return -1;
}
uint8_t GetPlayerGroup(uint32_t index)
{
2018-06-22 23:02:47 +02:00
return 0;
}
void SetPlayerGroup(uint32_t index, uint32_t groupindex)
{
}
int32_t GetGroupIndex(uint8_t id)
{
2018-06-22 23:02:47 +02:00
return -1;
}
uint8_t GetGroupID(uint32_t index)
{
2018-06-22 23:02:47 +02:00
return 0;
}
int32_t GetNumGroups()
{
2018-06-22 23:02:47 +02:00
return 0;
}
const char* GetGroupName(uint32_t index)
{
2018-06-22 23:02:47 +02:00
return "";
};
2020-08-10 15:35:54 +02:00
GameActions::Result SetPlayerGroup(PlayerId_t actionPlayerId, PlayerId_t playerId, uint8_t groupId, bool isExecuting)
{
2021-08-17 06:20:07 +03:00
return GameActions::Result();
}
GameActions::Result ModifyGroups(
PlayerId_t actionPlayerId, GameActions::ModifyGroupType type, uint8_t groupId, const std::string& name,
2021-08-17 06:20:07 +03:00
uint32_t permissionIndex, GameActions::PermissionState permissionState, bool isExecuting)
{
return GameActions::Result();
}
GameActions::Result KickPlayer(PlayerId_t playerId, bool isExecuting)
{
return GameActions::Result();
}
uint8_t GetDefaultGroup()
{
2018-06-22 23:02:47 +02:00
return 0;
}
int32_t GetNumActions()
{
2018-06-22 23:02:47 +02:00
return 0;
}
StringId GetActionNameStringID(uint32_t index)
{
2018-06-22 23:02:47 +02:00
return -1;
}
bool CanPerformAction(uint32_t groupindex, Permission index)
{
return false;
}
bool CanPerformCommand(uint32_t groupindex, int32_t index)
{
return false;
}
void SetPickupPeep(uint8_t playerid, Peep* peep)
2018-06-22 23:02:47 +02:00
{
2017-07-22 11:56:46 +02:00
_pickup_peep = peep;
2018-06-22 23:02:47 +02:00
}
Peep* GetPickupPeep(uint8_t playerid)
2018-06-22 23:02:47 +02:00
{
2017-07-22 11:56:46 +02:00
return _pickup_peep;
2018-06-22 23:02:47 +02:00
}
void SetPickupPeepOldX(uint8_t playerid, int32_t x)
2018-06-22 23:02:47 +02:00
{
2017-07-22 11:56:46 +02:00
_pickup_peep_old_x = x;
2018-06-22 23:02:47 +02:00
}
int32_t GetPickupPeepOldX(uint8_t playerid)
2018-06-22 23:02:47 +02:00
{
2017-07-22 11:56:46 +02:00
return _pickup_peep_old_x;
2018-06-22 23:02:47 +02:00
}
void SendChat(const char* text, const std::vector<uint8_t>& playerIds)
2018-06-22 23:02:47 +02:00
{
2017-07-22 11:56:46 +02:00
}
void SendPassword(const std::string& password)
2018-06-22 23:02:47 +02:00
{
2017-07-22 11:56:46 +02:00
}
void Reconnect()
2018-06-22 23:02:47 +02:00
{
}
void ShutdownClient()
2018-06-22 23:02:47 +02:00
{
2017-06-06 23:24:18 +02:00
}
void SetPassword(const char* password)
2018-06-22 23:02:47 +02:00
{
2017-07-21 18:21:18 +01:00
}
uint8_t GetCurrentPlayerId()
2018-06-22 23:02:47 +02:00
{
2017-06-06 23:24:18 +02:00
return 0;
}
int32_t GetCurrentPlayerGroupIndex()
2017-06-06 23:24:18 +02:00
{
2021-08-17 06:20:07 +03:00
return 0;
2017-06-06 23:24:18 +02:00
}
bool IsServerPlayerInvisible()
2017-06-06 23:24:18 +02:00
{
return false;
}
void AppendChatLog(std::string_view)
{
}
void AppendServerLog(const utf8* text)
{
}
u8string GetServerName()
{
2021-08-17 06:20:07 +03:00
return u8string();
}
u8string GetServerDescription()
{
2023-01-07 15:39:55 +01:00
return u8string();
}
u8string GetServerGreeting()
{
2023-01-07 15:39:55 +01:00
return u8string();
}
u8string GetServerProviderName()
{
2023-01-07 15:39:55 +01:00
return u8string();
}
u8string GetServerProviderEmail()
{
2023-01-07 15:39:55 +01:00
return u8string();
}
u8string GetServerProviderWebsite()
{
2023-01-07 15:39:55 +01:00
return u8string();
}
std::string GetVersion()
{
2021-08-17 06:20:07 +03:00
return "Multiplayer disabled";
}
Stats GetStats()
{
return Stats{};
}
ServerState GetServerState()
{
return ServerState{};
}
json_t GetServerInfoAsJson()
{
return {};
}
2020-04-28 19:33:30 +01:00
} // namespace OpenRCT2::Network
#endif /* DISABLE_NETWORK */