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

236 lines
7.7 KiB
C++
Raw Normal View History

/*****************************************************************************
2024-12-31 20:30:04 +01:00
* Copyright (c) 2014-2025 OpenRCT2 developers
*
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
*
2018-06-15 14:07:34 +02:00
* OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/
2016-05-28 22:27:08 +01:00
#ifndef DISABLE_NETWORK
#include "NetworkConnection.h"
#include "../core/String.hpp"
#include "../localisation/Formatting.h"
#include "../platform/Platform.h"
2025-02-24 04:43:06 -05:00
#include "Network.h"
#include "Socket.h"
2024-12-11 21:27:08 +02:00
#include <sfl/small_vector.hpp>
namespace OpenRCT2::Network
{
static constexpr size_t kNetworkDisconnectReasonBufSize = 256;
static constexpr size_t kNetworkBufferSize = (1024 * 64) - 1; // 64 KiB, maximum packet size.
#ifndef DEBUG
static constexpr size_t kNetworkNoDataTimeout = 20; // Seconds.
#endif
static_assert(kNetworkBufferSize <= std::numeric_limits<uint16_t>::max(), "kNetworkBufferSize too big, uint16_t is max.");
NetworkConnection::NetworkConnection() noexcept
{
ResetLastPacketTime();
}
2020-08-02 23:34:02 +02:00
NetworkReadPacket NetworkConnection::ReadPacket()
{
size_t bytesRead = 0;
2020-08-02 23:34:02 +02:00
// Read packet header.
auto& header = InboundPacket.Header;
if (InboundPacket.BytesTransferred < sizeof(InboundPacket.Header))
{
const size_t missingLength = sizeof(header) - InboundPacket.BytesTransferred;
uint8_t* buffer = reinterpret_cast<uint8_t*>(&InboundPacket.Header);
NetworkReadPacket status = Socket->ReceiveData(buffer, missingLength, &bytesRead);
if (status != NetworkReadPacket::success)
{
2016-06-01 22:58:21 +01:00
return status;
}
2016-06-01 22:58:21 +01:00
2020-08-02 23:34:02 +02:00
InboundPacket.BytesTransferred += bytesRead;
if (InboundPacket.BytesTransferred < sizeof(InboundPacket.Header))
{
// If still not enough data for header, keep waiting.
return NetworkReadPacket::moreData;
}
// Normalise values.
header.Size = Convert::NetworkToHost(header.Size);
header.Id = ByteSwapBE(header.Id);
// NOTE: For compatibility reasons for the master server we need to remove sizeof(Header.Id) from the size.
// Previously the Id field was not part of the header rather part of the body.
header.Size -= std::min<uint16_t>(header.Size, sizeof(header.Id));
// Fall-through: Read rest of packet.
}
2020-08-02 23:34:02 +02:00
// Read packet body.
{
// NOTE: BytesTransfered includes the header length, this will not underflow.
const size_t missingLength = header.Size - (InboundPacket.BytesTransferred - sizeof(header));
2019-01-29 16:35:19 +01:00
uint8_t buffer[kNetworkBufferSize];
2019-01-29 16:35:19 +01:00
if (missingLength > 0)
{
NetworkReadPacket status = Socket->ReceiveData(buffer, std::min(missingLength, kNetworkBufferSize), &bytesRead);
if (status != NetworkReadPacket::success)
{
return status;
}
InboundPacket.BytesTransferred += bytesRead;
InboundPacket.Write(buffer, bytesRead);
}
if (InboundPacket.Data.size() == header.Size)
{
// Received complete packet.
_lastPacketTime = Platform::GetTicks();
RecordPacketStats(InboundPacket, false);
return NetworkReadPacket::success;
}
}
return NetworkReadPacket::moreData;
}
static sfl::small_vector<uint8_t, 512> serializePacket(const NetworkPacket& packet)
{
// NOTE: For compatibility reasons for the master server we need to add sizeof(Header.Id) to the size.
// Previously the Id field was not part of the header rather part of the body.
const auto bodyLength = packet.Data.size() + sizeof(packet.Header.Id);
Guard::Assert(bodyLength <= std::numeric_limits<uint16_t>::max(), "Packet size too large");
auto header = packet.Header;
header.Size = static_cast<uint16_t>(bodyLength);
header.Size = Convert::HostToNetwork(header.Size);
header.Id = ByteSwapBE(header.Id);
sfl::small_vector<uint8_t, 512> buffer;
buffer.reserve(sizeof(header) + packet.Data.size());
buffer.insert(buffer.end(), reinterpret_cast<uint8_t*>(&header), reinterpret_cast<uint8_t*>(&header) + sizeof(header));
buffer.insert(buffer.end(), packet.Data.begin(), packet.Data.end());
return buffer;
}
void NetworkConnection::QueuePacket(const NetworkPacket& packet, bool front)
{
if (AuthStatus == Auth::ok || !packet.CommandRequiresAuth())
{
const auto payload = serializePacket(packet);
if (front)
{
_outboundBuffer.insert(_outboundBuffer.begin(), payload.begin(), payload.end());
}
else
{
_outboundBuffer.insert(_outboundBuffer.end(), payload.begin(), payload.end());
}
RecordPacketStats(packet, true);
}
}
2020-08-02 23:34:02 +02:00
void NetworkConnection::Disconnect() noexcept
{
ShouldDisconnect = true;
}
bool NetworkConnection::IsValid() const
{
return !ShouldDisconnect && Socket->GetStatus() == SocketStatus::connected;
}
void NetworkConnection::SendQueuedData()
{
if (_outboundBuffer.empty())
{
return;
}
const auto bytesSent = Socket->SendData(_outboundBuffer.data(), _outboundBuffer.size());
if (bytesSent > 0)
{
_outboundBuffer.erase(_outboundBuffer.begin(), _outboundBuffer.begin() + bytesSent);
}
}
void NetworkConnection::ResetLastPacketTime() noexcept
{
_lastPacketTime = Platform::GetTicks();
}
bool NetworkConnection::ReceivedPacketRecently() const noexcept
{
#ifndef DEBUG
constexpr auto kTimeoutMs = kNetworkNoDataTimeout * 1000;
if (Platform::GetTicks() > _lastPacketTime + kTimeoutMs)
{
return false;
}
#endif
return true;
}
const utf8* NetworkConnection::GetLastDisconnectReason() const noexcept
{
return this->_lastDisconnectReason.c_str();
}
void NetworkConnection::SetLastDisconnectReason(std::string_view src)
{
_lastDisconnectReason = src;
}
void NetworkConnection::SetLastDisconnectReason(const StringId string_id, void* args)
{
char buffer[kNetworkDisconnectReasonBufSize];
2025-08-31 15:31:19 +02:00
FormatStringLegacy(buffer, kNetworkDisconnectReasonBufSize, string_id, args);
SetLastDisconnectReason(buffer);
}
void NetworkConnection::RecordPacketStats(const NetworkPacket& packet, bool sending)
{
uint32_t packetSize = static_cast<uint32_t>(packet.BytesTransferred);
StatisticsGroup trafficGroup;
switch (packet.GetCommand())
{
case Command::gameAction:
trafficGroup = StatisticsGroup::Commands;
break;
case Command::map:
trafficGroup = StatisticsGroup::MapData;
break;
default:
trafficGroup = StatisticsGroup::Base;
break;
}
if (sending)
{
stats.bytesSent[EnumValue(trafficGroup)] += packetSize;
stats.bytesSent[EnumValue(StatisticsGroup::Total)] += packetSize;
}
else
{
stats.bytesReceived[EnumValue(trafficGroup)] += packetSize;
stats.bytesReceived[EnumValue(StatisticsGroup::Total)] += packetSize;
}
}
} // namespace OpenRCT2::Network
2019-01-29 16:35:19 +01:00
2016-05-28 22:27:08 +01:00
#endif