small refactor and void library
Signed-off-by: Aleksei (Faumaray) Selikhov <contact@faumaray.com>
This commit is contained in:
1 parent
74b89ae3ca
commit
083b84e11a
12 files changed
+646
-343
No files matched your search
+31
-80
@@ -5,14 +5,14 @@
|
||||
#include <iphlpapi.h>
|
||||
|
||||
#include "lan_session.hpp"
|
||||
#include "lan_wire.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <bit>
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <deque>
|
||||
#include <limits>
|
||||
#include <spanstream>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <string_view>
|
||||
@@ -24,11 +24,10 @@ namespace {
|
||||
|
||||
using Clock = std::chrono::steady_clock;
|
||||
using namespace std::chrono_literals;
|
||||
constexpr std::uint32_t protocol_version = 11;
|
||||
constexpr std::size_t frame_limit = 4 * 1024 * 1024;
|
||||
using lan_wire::guest_player;
|
||||
using lan_wire::Message;
|
||||
constexpr auto poll_budget = 16;
|
||||
constexpr std::size_t command_queue_limit = 32;
|
||||
enum class Message : std::uint8_t { Hello = 1, Snapshot, Command, Receipt, Reject, Ping };
|
||||
|
||||
struct Socket {
|
||||
SOCKET handle = INVALID_SOCKET;
|
||||
@@ -64,31 +63,6 @@ void tune_stream(SOCKET socket) {
|
||||
setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<const char*>(&enabled), sizeof(enabled));
|
||||
}
|
||||
|
||||
void append_number(std::string& bytes, std::uint64_t value, unsigned length) {
|
||||
for (unsigned i = 0; i < length; ++i) {
|
||||
bytes.push_back(std::bit_cast<char>(static_cast<std::uint8_t>(value)));
|
||||
value >>= 8U;
|
||||
}
|
||||
}
|
||||
|
||||
std::uint64_t number(std::string_view bytes) noexcept {
|
||||
std::uint64_t value = 0;
|
||||
for (std::size_t i = 0; i < bytes.size(); ++i) {
|
||||
value |= static_cast<std::uint64_t>(static_cast<unsigned char>(bytes[i])) << (8U * i);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
std::string frame(Message message, std::string_view payload = {}) {
|
||||
if (payload.size() >= frame_limit) throw std::runtime_error("The colony snapshot is too large for LAN play.");
|
||||
std::string bytes;
|
||||
bytes.reserve(5 + payload.size());
|
||||
append_number(bytes, 1 + payload.size(), 4);
|
||||
bytes.push_back(static_cast<char>(message));
|
||||
bytes.append(payload);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
struct Channel {
|
||||
Socket socket;
|
||||
std::string input;
|
||||
@@ -107,10 +81,10 @@ struct Channel {
|
||||
output.erase(0, sent);
|
||||
sent = 0;
|
||||
}
|
||||
if (output.size() + payload.size() + 5 > frame_limit + 1024) {
|
||||
if (output.size() + payload.size() + lan_wire::frame_header_size > lan_wire::frame_limit + 1024) {
|
||||
throw std::runtime_error("The peer is not receiving data fast enough.");
|
||||
}
|
||||
output += frame(message, payload);
|
||||
lan_wire::append_frame(output, message, payload);
|
||||
}
|
||||
|
||||
void flush() {
|
||||
@@ -141,18 +115,12 @@ struct Channel {
|
||||
if (count == 0) throw std::runtime_error("Connection closed.");
|
||||
last_received = Clock::now();
|
||||
input.append(bytes.data(), static_cast<std::size_t>(count));
|
||||
std::size_t cursor = 0;
|
||||
while (input.size() - cursor >= 4) {
|
||||
const std::string_view remaining(input.data() + cursor, input.size() - cursor);
|
||||
const auto length = number(remaining.substr(0, 4));
|
||||
if (length == 0 || length > frame_limit) throw std::runtime_error("Invalid LAN message size.");
|
||||
const auto end = 4 + static_cast<std::size_t>(length);
|
||||
if (remaining.size() < end) break;
|
||||
on_message(static_cast<Message>(static_cast<unsigned char>(remaining[4])),
|
||||
remaining.substr(5, static_cast<std::size_t>(length - 1)));
|
||||
cursor += end;
|
||||
std::size_t consumed = 0;
|
||||
while (const auto frame = lan_wire::next_frame(std::string_view(input).substr(consumed))) {
|
||||
on_message(frame->message, frame->payload);
|
||||
consumed += frame->size;
|
||||
}
|
||||
if (cursor != 0) input.erase(0, cursor);
|
||||
if (consumed != 0) input.erase(0, consumed);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -258,8 +226,8 @@ struct LanSession::Impl {
|
||||
void handle_host(World& world, Message message, std::string_view payload) {
|
||||
if (!authenticated) {
|
||||
if (reject_pending) return;
|
||||
if (message != Message::Hello || payload.size() != 12 ||
|
||||
number(payload.substr(0, 4)) != protocol_version || number(payload.substr(4)) != key) {
|
||||
const auto hello = message == Message::Hello ? lan_wire::decode_hello(payload) : std::nullopt;
|
||||
if (!hello || hello->version != lan_wire::protocol_version || hello->key != key) {
|
||||
peer.queue(Message::Reject);
|
||||
reject_pending = true;
|
||||
return;
|
||||
@@ -269,60 +237,52 @@ struct LanSession::Impl {
|
||||
return;
|
||||
}
|
||||
if (message == Message::Ping && payload.empty()) return;
|
||||
if (message != Message::Command || payload.size() != 34) throw std::runtime_error("Invalid guest command.");
|
||||
const PlayerCommand command{2, number(payload.substr(0, 8)),
|
||||
static_cast<CommandKind>(static_cast<unsigned char>(payload[8])),
|
||||
{std::bit_cast<std::int32_t>(static_cast<std::uint32_t>(number(payload.substr(9, 4)))),
|
||||
std::bit_cast<std::int32_t>(static_cast<std::uint32_t>(number(payload.substr(13, 4))))},
|
||||
static_cast<std::uint8_t>(payload[17]),
|
||||
{std::bit_cast<std::int32_t>(static_cast<std::uint32_t>(number(payload.substr(18, 4)))),
|
||||
std::bit_cast<std::int32_t>(static_cast<std::uint32_t>(number(payload.substr(22, 4))))},
|
||||
number(payload.substr(26, 8))};
|
||||
const auto result = world.apply_command(command);
|
||||
std::string reply;
|
||||
append_number(reply, static_cast<std::uint8_t>(result.status), 1);
|
||||
append_number(reply, world.next_command_sequence(2), 8);
|
||||
peer.queue(Message::Receipt, reply);
|
||||
const auto command = message == Message::Command ? lan_wire::decode_command(payload) : std::nullopt;
|
||||
if (!command) throw std::runtime_error("Invalid guest command.");
|
||||
const auto result = world.apply_command(*command);
|
||||
const auto reply = lan_wire::encode_receipt({result.status, world.next_command_sequence(guest_player)});
|
||||
peer.queue(Message::Receipt, std::string_view(reply));
|
||||
}
|
||||
|
||||
void handle_guest(std::unique_ptr<World>& latest, Message message, std::string_view payload) {
|
||||
if (message == Message::Reject) throw std::runtime_error("Wrong game code or incompatible version.");
|
||||
if (message == Message::Snapshot) {
|
||||
std::istringstream data(std::string(payload), std::ios::binary);
|
||||
std::ispanstream data(payload);
|
||||
latest = World::read_save(data);
|
||||
if (!latest->scenario_active() || latest->width() != first_colony_map_size ||
|
||||
latest->height() != first_colony_map_size) {
|
||||
throw std::runtime_error("The host sent an unsupported colony.");
|
||||
}
|
||||
if (!authenticated) guest_sequence = latest->next_command_sequence(2);
|
||||
if (!authenticated) guest_sequence = latest->next_command_sequence(guest_player);
|
||||
authenticated = true;
|
||||
notice.clear();
|
||||
return;
|
||||
}
|
||||
if (message != Message::Receipt || payload.size() != 9 || !awaiting_receipt) {
|
||||
const auto receipt = message == Message::Receipt ? lan_wire::decode_receipt(payload) : std::nullopt;
|
||||
if (!receipt || !awaiting_receipt) {
|
||||
throw std::runtime_error("Invalid message from the host.");
|
||||
}
|
||||
const auto status = static_cast<CommandStatus>(static_cast<unsigned char>(payload[0]));
|
||||
const auto status = receipt->status;
|
||||
if (status > CommandStatus::Busy) throw std::runtime_error("Invalid command result.");
|
||||
if (status != CommandStatus::Accepted) {
|
||||
rejected_command = LanRejection{status, awaiting_receipt->kind, awaiting_receipt->cell,
|
||||
awaiting_receipt->value, awaiting_receipt->destination};
|
||||
}
|
||||
guest_sequence = number(payload.substr(1));
|
||||
guest_sequence = receipt->next_sequence;
|
||||
awaiting_receipt.reset();
|
||||
}
|
||||
|
||||
void send_snapshot(const World& world, Clock::time_point now) {
|
||||
if (peer.pending()) return;
|
||||
const auto host_seq = world.next_command_sequence(1);
|
||||
const auto guest_seq = world.next_command_sequence(2);
|
||||
const auto guest_seq = world.next_command_sequence(guest_player);
|
||||
const bool changed = world.tick() != sent_tick || host_seq != sent_host_sequence || guest_seq != sent_guest_sequence;
|
||||
const auto elapsed = now - last_snapshot;
|
||||
if (last_snapshot != Clock::time_point{} && elapsed < 2s &&
|
||||
(!changed || (elapsed < 120ms && host_seq == sent_host_sequence && guest_seq == sent_guest_sequence))) return;
|
||||
std::ostringstream data(std::ios::binary);
|
||||
world.write_save(data);
|
||||
peer.queue(Message::Snapshot, data.str());
|
||||
peer.queue(Message::Snapshot, data.view());
|
||||
last_snapshot = now;
|
||||
sent_tick = world.tick();
|
||||
sent_host_sequence = host_seq;
|
||||
@@ -332,16 +292,9 @@ struct LanSession::Impl {
|
||||
void send_action() {
|
||||
if (awaiting_receipt || actions.empty() || guest_sequence == 0 || peer.pending()) return;
|
||||
const Action action = actions.front();
|
||||
std::string payload;
|
||||
append_number(payload, guest_sequence, 8);
|
||||
append_number(payload, static_cast<std::uint8_t>(action.kind), 1);
|
||||
append_number(payload, std::bit_cast<std::uint32_t>(action.cell.x), 4);
|
||||
append_number(payload, std::bit_cast<std::uint32_t>(action.cell.y), 4);
|
||||
append_number(payload, action.value, 1);
|
||||
append_number(payload, std::bit_cast<std::uint32_t>(action.destination.x), 4);
|
||||
append_number(payload, std::bit_cast<std::uint32_t>(action.destination.y), 4);
|
||||
append_number(payload, action.resident, 8);
|
||||
peer.queue(Message::Command, payload);
|
||||
const auto payload = lan_wire::encode_command(
|
||||
{guest_player, guest_sequence, action.kind, action.cell, action.value, action.destination, action.resident});
|
||||
peer.queue(Message::Command, std::string_view(payload));
|
||||
actions.pop_front();
|
||||
awaiting_receipt = action;
|
||||
}
|
||||
@@ -394,11 +347,9 @@ void LanSession::join(std::string address, std::string code, std::uint16_t port)
|
||||
tune_stream(socket.handle);
|
||||
const bool pending = connect(socket.handle, reinterpret_cast<const sockaddr*>(&remote), sizeof(remote)) != 0;
|
||||
if (pending && WSAGetLastError() != WSAEWOULDBLOCK) throw std::runtime_error("Could not connect to the host.");
|
||||
std::string identity;
|
||||
append_number(identity, protocol_version, 4);
|
||||
append_number(identity, key, 8);
|
||||
const auto identity = lan_wire::encode_hello({lan_wire::protocol_version, key});
|
||||
Channel channel(std::move(socket));
|
||||
channel.queue(Message::Hello, identity);
|
||||
channel.queue(Message::Hello, std::string_view(identity));
|
||||
leave();
|
||||
impl_->guest = true;
|
||||
impl_->connecting = pending;
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
#include "lan_wire.hpp"
|
||||
|
||||
#include <Void/Binary/Reader.hpp>
|
||||
#include <Void/Binary/Writer.hpp>
|
||||
|
||||
#include <span>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace settlement::viewer::lan_wire {
|
||||
namespace {
|
||||
|
||||
template<std::size_t Size, class... Fields>
|
||||
std::array<char, Size> encode(Fields... fields) {
|
||||
static_assert((sizeof(Fields) + ...) == Size);
|
||||
std::array<char, Size> payload{};
|
||||
Void::Binary::Writer writer(std::as_writable_bytes(std::span{payload}));
|
||||
(writer.writeLittle(fields).value(), ...);
|
||||
return payload;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void append_frame(std::string& output, Message message, std::string_view payload) {
|
||||
if (payload.size() >= frame_limit) throw std::runtime_error("The colony snapshot is too large for LAN play.");
|
||||
const auto length = static_cast<std::uint32_t>(payload.size() + 1);
|
||||
const auto header = encode<frame_header_size>(length, static_cast<std::uint8_t>(message));
|
||||
output.reserve(output.size() + header.size() + payload.size());
|
||||
output.append(header.data(), header.size());
|
||||
output.append(payload);
|
||||
}
|
||||
|
||||
std::optional<Frame> next_frame(std::string_view input) {
|
||||
if (input.size() < sizeof(std::uint32_t)) return std::nullopt;
|
||||
Void::Binary::Reader reader(std::as_bytes(std::span{input}));
|
||||
const auto length = reader.readLittle<std::uint32_t>().value();
|
||||
if (length == 0 || length > frame_limit) throw std::runtime_error("Invalid LAN message size.");
|
||||
if (reader.remaining() < length) return std::nullopt;
|
||||
|
||||
const auto message = static_cast<Message>(reader.readLittle<std::uint8_t>().value());
|
||||
const auto payload = input.substr(reader.position(), length - 1);
|
||||
return Frame{message, payload, reader.position() + payload.size()};
|
||||
}
|
||||
|
||||
std::array<char, 12> encode_hello(Hello hello) {
|
||||
return encode<12>(hello.version, hello.key);
|
||||
}
|
||||
|
||||
std::optional<Hello> decode_hello(std::string_view payload) {
|
||||
if (payload.size() != 12) return std::nullopt;
|
||||
Void::Binary::Reader reader(std::as_bytes(std::span{payload}));
|
||||
return Hello{reader.readLittle<std::uint32_t>().value(), reader.readLittle<std::uint64_t>().value()};
|
||||
}
|
||||
|
||||
std::array<char, 34> encode_command(const PlayerCommand& command) {
|
||||
return encode<34>(command.sequence, static_cast<std::uint8_t>(command.kind), command.cell.x, command.cell.y,
|
||||
command.value, command.destination.x, command.destination.y, command.resident);
|
||||
}
|
||||
|
||||
std::optional<PlayerCommand> decode_command(std::string_view payload) {
|
||||
if (payload.size() != 34) return std::nullopt;
|
||||
Void::Binary::Reader reader(std::as_bytes(std::span{payload}));
|
||||
return PlayerCommand{guest_player,
|
||||
reader.readLittle<std::uint64_t>().value(),
|
||||
static_cast<CommandKind>(reader.readLittle<std::uint8_t>().value()),
|
||||
{reader.readLittle<std::int32_t>().value(), reader.readLittle<std::int32_t>().value()},
|
||||
reader.readLittle<std::uint8_t>().value(),
|
||||
{reader.readLittle<std::int32_t>().value(), reader.readLittle<std::int32_t>().value()},
|
||||
reader.readLittle<std::uint64_t>().value()};
|
||||
}
|
||||
|
||||
std::array<char, 9> encode_receipt(Receipt receipt) {
|
||||
return encode<9>(static_cast<std::uint8_t>(receipt.status), receipt.next_sequence);
|
||||
}
|
||||
|
||||
std::optional<Receipt> decode_receipt(std::string_view payload) {
|
||||
if (payload.size() != 9) return std::nullopt;
|
||||
Void::Binary::Reader reader(std::as_bytes(std::span{payload}));
|
||||
return Receipt{static_cast<CommandStatus>(reader.readLittle<std::uint8_t>().value()),
|
||||
reader.readLittle<std::uint64_t>().value()};
|
||||
}
|
||||
|
||||
} // namespace settlement::viewer::lan_wire
|
||||
@@ -0,0 +1,52 @@
|
||||
#pragma once
|
||||
|
||||
#include "settlement/core/world.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace settlement::viewer::lan_wire {
|
||||
|
||||
inline constexpr std::uint32_t protocol_version = 11;
|
||||
inline constexpr std::uint8_t guest_player = 2;
|
||||
inline constexpr std::size_t frame_limit = 4 * 1024 * 1024;
|
||||
inline constexpr std::size_t frame_header_size = sizeof(std::uint32_t) + sizeof(std::uint8_t);
|
||||
|
||||
enum class Message : std::uint8_t { Hello = 1, Snapshot, Command, Receipt, Reject, Ping };
|
||||
|
||||
struct Frame {
|
||||
Message message;
|
||||
std::string_view payload;
|
||||
std::size_t size;
|
||||
};
|
||||
|
||||
struct Hello {
|
||||
std::uint32_t version;
|
||||
std::uint64_t key;
|
||||
};
|
||||
|
||||
struct Receipt {
|
||||
CommandStatus status;
|
||||
std::uint64_t next_sequence;
|
||||
};
|
||||
|
||||
// The payload must be backed by storage separate from output.
|
||||
void append_frame(std::string& output, Message message, std::string_view payload = {});
|
||||
|
||||
// A complete frame borrows its payload from input. Invalid lengths throw even before the body arrives.
|
||||
[[nodiscard]] std::optional<Frame> next_frame(std::string_view input);
|
||||
|
||||
[[nodiscard]] std::array<char, 12> encode_hello(Hello hello);
|
||||
[[nodiscard]] std::optional<Hello> decode_hello(std::string_view payload);
|
||||
|
||||
[[nodiscard]] std::array<char, 34> encode_command(const PlayerCommand& command);
|
||||
[[nodiscard]] std::optional<PlayerCommand> decode_command(std::string_view payload);
|
||||
|
||||
[[nodiscard]] std::array<char, 9> encode_receipt(Receipt receipt);
|
||||
[[nodiscard]] std::optional<Receipt> decode_receipt(std::string_view payload);
|
||||
|
||||
} // namespace settlement::viewer::lan_wire
|
||||
Reference in new issue
Block a user