513 lines
21 KiB
C++
513 lines
21 KiB
C++
#define NOMINMAX
|
|
#include <winsock2.h>
|
|
#include <ws2tcpip.h>
|
|
#include <bcrypt.h>
|
|
#include <iphlpapi.h>
|
|
|
|
#include "lan_session.hpp"
|
|
|
|
#include <algorithm>
|
|
#include <array>
|
|
#include <bit>
|
|
#include <charconv>
|
|
#include <chrono>
|
|
#include <deque>
|
|
#include <limits>
|
|
#include <sstream>
|
|
#include <stdexcept>
|
|
#include <string_view>
|
|
#include <utility>
|
|
#include <vector>
|
|
|
|
namespace settlement::viewer {
|
|
namespace {
|
|
|
|
using Clock = std::chrono::steady_clock;
|
|
using namespace std::chrono_literals;
|
|
constexpr std::uint32_t protocol_version = 8;
|
|
constexpr std::size_t frame_limit = 4 * 1024 * 1024;
|
|
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;
|
|
|
|
Socket() = default;
|
|
explicit Socket(SOCKET raw) : handle(raw) {}
|
|
~Socket() { reset(); }
|
|
Socket(const Socket&) = delete;
|
|
Socket& operator=(const Socket&) = delete;
|
|
Socket(Socket&& other) noexcept : handle(std::exchange(other.handle, INVALID_SOCKET)) {}
|
|
Socket& operator=(Socket&& other) noexcept {
|
|
if (this != &other) {
|
|
reset();
|
|
handle = std::exchange(other.handle, INVALID_SOCKET);
|
|
}
|
|
return *this;
|
|
}
|
|
explicit operator bool() const noexcept { return handle != INVALID_SOCKET; }
|
|
void reset() noexcept {
|
|
if (*this) closesocket(std::exchange(handle, INVALID_SOCKET));
|
|
}
|
|
};
|
|
|
|
void set_nonblocking(SOCKET socket) {
|
|
u_long enabled = 1;
|
|
if (ioctlsocket(socket, static_cast<long>(FIONBIO), &enabled) != 0) {
|
|
throw std::runtime_error("Could not configure the socket.");
|
|
}
|
|
}
|
|
|
|
void tune_stream(SOCKET socket) {
|
|
const int enabled = 1;
|
|
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;
|
|
std::string output;
|
|
std::size_t sent = 0;
|
|
Clock::time_point opened = Clock::now();
|
|
Clock::time_point last_received = Clock::now();
|
|
|
|
Channel() = default;
|
|
explicit Channel(Socket incoming) : socket(std::move(incoming)) {}
|
|
|
|
bool pending() const noexcept { return sent < output.size(); }
|
|
|
|
void queue(Message message, std::string_view payload = {}) {
|
|
if (sent != 0) {
|
|
output.erase(0, sent);
|
|
sent = 0;
|
|
}
|
|
if (output.size() + payload.size() + 5 > frame_limit + 1024) {
|
|
throw std::runtime_error("The peer is not receiving data fast enough.");
|
|
}
|
|
output += frame(message, payload);
|
|
}
|
|
|
|
void flush() {
|
|
if (!pending()) return;
|
|
const int size = static_cast<int>(std::min(output.size() - sent, std::size_t{64 * 1024}));
|
|
const int written = send(socket.handle, output.data() + sent, size, 0);
|
|
if (written == SOCKET_ERROR) {
|
|
if (WSAGetLastError() != WSAEWOULDBLOCK) throw std::runtime_error("Connection interrupted.");
|
|
return;
|
|
}
|
|
if (written == 0) throw std::runtime_error("Connection closed.");
|
|
sent += static_cast<std::size_t>(written);
|
|
if (sent == output.size()) {
|
|
output.clear();
|
|
sent = 0;
|
|
}
|
|
}
|
|
|
|
template<class Deliver>
|
|
void receive(Deliver on_message) {
|
|
std::array<char, 8192> bytes{};
|
|
for (int read = 0; read < poll_budget; ++read) {
|
|
const int count = recv(socket.handle, bytes.data(), static_cast<int>(bytes.size()), 0);
|
|
if (count == SOCKET_ERROR) {
|
|
if (WSAGetLastError() != WSAEWOULDBLOCK) throw std::runtime_error("Connection interrupted.");
|
|
break;
|
|
}
|
|
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;
|
|
}
|
|
if (cursor != 0) input.erase(0, cursor);
|
|
}
|
|
}
|
|
};
|
|
|
|
std::uint64_t parse_code(std::string_view code) {
|
|
std::uint64_t key = 0;
|
|
const auto end = code.data() + code.size();
|
|
const auto result = std::from_chars(code.data(), end, key, 16);
|
|
if (code.size() != 16 || result.ec != std::errc{} || result.ptr != end || key == 0) {
|
|
throw std::invalid_argument("Enter the 16-character game code from the host.");
|
|
}
|
|
return key;
|
|
}
|
|
|
|
std::string format_code(std::uint64_t key) {
|
|
std::array<char, 16> digits{};
|
|
const auto result = std::to_chars(digits.data(), digits.data() + digits.size(), key, 16);
|
|
const auto size = static_cast<std::size_t>(result.ptr - digits.data());
|
|
return std::string(16 - size, '0') + std::string(digits.data(), size);
|
|
}
|
|
|
|
struct Action {
|
|
CommandKind kind;
|
|
GridPosition cell;
|
|
std::uint8_t value;
|
|
GridPosition destination;
|
|
AgentId resident;
|
|
};
|
|
|
|
} // namespace
|
|
|
|
struct LanSession::Impl {
|
|
bool winsock = false;
|
|
Socket listener;
|
|
Channel peer;
|
|
bool guest = false;
|
|
bool connecting = false;
|
|
bool authenticated = false;
|
|
bool reject_pending = false;
|
|
std::optional<Action> awaiting_receipt;
|
|
std::uint16_t network_port = 0;
|
|
std::uint64_t key = 0;
|
|
std::string host_address;
|
|
std::string notice;
|
|
std::deque<Action> actions;
|
|
std::optional<LanRejection> rejected_command;
|
|
std::uint64_t guest_sequence = 0;
|
|
Clock::time_point last_ping{};
|
|
Clock::time_point last_snapshot{};
|
|
std::uint64_t sent_tick = 0;
|
|
std::uint64_t sent_host_sequence = 0;
|
|
std::uint64_t sent_guest_sequence = 0;
|
|
|
|
Impl() {
|
|
WSADATA data{};
|
|
winsock = WSAStartup(MAKEWORD(2, 2), &data) == 0;
|
|
}
|
|
~Impl() {
|
|
peer.socket.reset();
|
|
listener.reset();
|
|
if (winsock) WSACleanup();
|
|
}
|
|
|
|
void drop_peer() noexcept {
|
|
peer = Channel{};
|
|
connecting = authenticated = reject_pending = false;
|
|
awaiting_receipt.reset();
|
|
guest_sequence = 0;
|
|
actions.clear();
|
|
rejected_command.reset();
|
|
last_snapshot = {};
|
|
last_ping = {};
|
|
}
|
|
|
|
void accept_guest() {
|
|
if (peer.socket) return;
|
|
Socket socket(accept(listener.handle, nullptr, nullptr));
|
|
if (!socket) return;
|
|
set_nonblocking(socket.handle);
|
|
tune_stream(socket.handle);
|
|
drop_peer();
|
|
peer = Channel(std::move(socket));
|
|
}
|
|
|
|
void finish_connection() {
|
|
fd_set write{}, error{};
|
|
FD_SET(peer.socket.handle, &write);
|
|
FD_SET(peer.socket.handle, &error);
|
|
timeval instant{};
|
|
const int ready = select(0, nullptr, &write, &error, &instant);
|
|
if (ready == SOCKET_ERROR) throw std::runtime_error("Could not connect to the host.");
|
|
if (ready == 0) return;
|
|
int code = 0;
|
|
int length = sizeof(code);
|
|
if (FD_ISSET(peer.socket.handle, &error) ||
|
|
getsockopt(peer.socket.handle, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&code), &length) != 0 ||
|
|
code != 0) {
|
|
throw std::runtime_error("Could not connect to the host.");
|
|
}
|
|
connecting = false;
|
|
}
|
|
|
|
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) {
|
|
peer.queue(Message::Reject);
|
|
reject_pending = true;
|
|
return;
|
|
}
|
|
authenticated = true;
|
|
notice.clear();
|
|
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);
|
|
}
|
|
|
|
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);
|
|
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);
|
|
authenticated = true;
|
|
notice.clear();
|
|
return;
|
|
}
|
|
if (message != Message::Receipt || payload.size() != 9 || !awaiting_receipt) {
|
|
throw std::runtime_error("Invalid message from the host.");
|
|
}
|
|
const auto status = static_cast<CommandStatus>(static_cast<unsigned char>(payload[0]));
|
|
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));
|
|
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 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());
|
|
last_snapshot = now;
|
|
sent_tick = world.tick();
|
|
sent_host_sequence = host_seq;
|
|
sent_guest_sequence = guest_seq;
|
|
}
|
|
|
|
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);
|
|
actions.pop_front();
|
|
awaiting_receipt = action;
|
|
}
|
|
};
|
|
|
|
LanSession::LanSession() : impl_(std::make_unique<Impl>()) {}
|
|
LanSession::~LanSession() = default;
|
|
|
|
void LanSession::host(std::uint16_t port, bool loopback_only) {
|
|
if (!impl_->winsock) throw std::runtime_error("Windows networking is unavailable.");
|
|
Socket socket(::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP));
|
|
if (!socket) throw std::runtime_error("Could not open the LAN listener.");
|
|
const int exclusive = 1;
|
|
setsockopt(socket.handle, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
|
|
reinterpret_cast<const char*>(&exclusive), sizeof(exclusive));
|
|
sockaddr_in local{};
|
|
local.sin_family = AF_INET;
|
|
local.sin_addr.s_addr = htonl(loopback_only ? INADDR_LOOPBACK : INADDR_ANY);
|
|
local.sin_port = htons(port);
|
|
if (bind(socket.handle, reinterpret_cast<const sockaddr*>(&local), sizeof(local)) != 0 ||
|
|
listen(socket.handle, 1) != 0) {
|
|
throw std::runtime_error("Could not listen on the selected LAN port.");
|
|
}
|
|
int length = sizeof(local);
|
|
if (getsockname(socket.handle, reinterpret_cast<sockaddr*>(&local), &length) != 0) {
|
|
throw std::runtime_error("Could not determine the local LAN port.");
|
|
}
|
|
std::uint64_t key = 0;
|
|
if (BCryptGenRandom(nullptr, reinterpret_cast<PUCHAR>(&key), sizeof(key), BCRYPT_USE_SYSTEM_PREFERRED_RNG) != 0 ||
|
|
key == 0) throw std::runtime_error("Could not generate a join code.");
|
|
set_nonblocking(socket.handle);
|
|
leave();
|
|
impl_->listener = std::move(socket);
|
|
impl_->key = key;
|
|
impl_->network_port = ntohs(local.sin_port);
|
|
}
|
|
|
|
void LanSession::join(std::string address, std::string code, std::uint16_t port) {
|
|
if (!impl_->winsock) throw std::runtime_error("Windows networking is unavailable.");
|
|
const auto key = parse_code(code);
|
|
sockaddr_in remote{};
|
|
remote.sin_family = AF_INET;
|
|
remote.sin_port = htons(port);
|
|
if (InetPtonA(AF_INET, address.c_str(), &remote.sin_addr) != 1 || port == 0) {
|
|
throw std::invalid_argument("Enter a valid IPv4 address for the host.");
|
|
}
|
|
Socket socket(::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP));
|
|
if (!socket) throw std::runtime_error("Could not open the guest connection.");
|
|
set_nonblocking(socket.handle);
|
|
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);
|
|
Channel channel(std::move(socket));
|
|
channel.queue(Message::Hello, identity);
|
|
leave();
|
|
impl_->guest = true;
|
|
impl_->connecting = pending;
|
|
impl_->network_port = port;
|
|
impl_->key = key;
|
|
impl_->host_address = std::move(address);
|
|
impl_->peer = std::move(channel);
|
|
}
|
|
|
|
void LanSession::reconnect() {
|
|
if (state() == LanState::GuestDisconnected) join(impl_->host_address, join_code(), impl_->network_port);
|
|
}
|
|
|
|
void LanSession::leave() noexcept {
|
|
impl_->drop_peer();
|
|
impl_->listener.reset();
|
|
impl_->guest = false;
|
|
impl_->notice.clear();
|
|
impl_->network_port = 0;
|
|
impl_->key = 0;
|
|
impl_->host_address.clear();
|
|
}
|
|
|
|
LanState LanSession::state() const noexcept {
|
|
if (impl_->listener) return impl_->authenticated ? LanState::HostConnected : LanState::Hosting;
|
|
if (!impl_->guest) return LanState::Offline;
|
|
if (!impl_->peer.socket) return LanState::GuestDisconnected;
|
|
return impl_->authenticated ? LanState::GuestConnected : LanState::Connecting;
|
|
}
|
|
|
|
bool LanSession::is_guest() const noexcept { return impl_->guest; }
|
|
std::string LanSession::join_code() const { return format_code(impl_->key); }
|
|
std::uint16_t LanSession::port() const noexcept { return impl_->network_port; }
|
|
const std::string& LanSession::detail() const noexcept { return impl_->notice; }
|
|
|
|
bool LanSession::submit(CommandKind kind, GridPosition cell, std::uint8_t value, GridPosition destination,
|
|
AgentId resident) {
|
|
if (state() != LanState::GuestConnected || impl_->guest_sequence == 0 || kind == CommandKind::SetPaused ||
|
|
impl_->actions.size() >= command_queue_limit) return false;
|
|
impl_->actions.push_back({kind, cell, value, destination, resident});
|
|
return true;
|
|
}
|
|
|
|
std::optional<LanRejection> LanSession::take_rejection() noexcept {
|
|
return std::exchange(impl_->rejected_command, std::nullopt);
|
|
}
|
|
|
|
std::unique_ptr<World> LanSession::poll(World& world) {
|
|
auto& connection = *impl_;
|
|
std::unique_ptr<World> latest;
|
|
try {
|
|
if (connection.listener) connection.accept_guest();
|
|
if (!connection.peer.socket) return nullptr;
|
|
const auto now = Clock::now();
|
|
if ((!connection.authenticated && now - connection.peer.opened > 8s) ||
|
|
(connection.authenticated && now - connection.peer.last_received > 15s)) {
|
|
throw std::runtime_error("The peer did not respond.");
|
|
}
|
|
if (connection.connecting) connection.finish_connection();
|
|
if (connection.connecting) return nullptr;
|
|
connection.peer.receive([&](Message message, std::string_view payload) {
|
|
if (connection.guest) connection.handle_guest(latest, message, payload);
|
|
else connection.handle_host(world, message, payload);
|
|
});
|
|
if (connection.authenticated && connection.guest) {
|
|
connection.send_action();
|
|
if (!connection.peer.pending() && now - connection.last_ping >= 2s) {
|
|
connection.peer.queue(Message::Ping);
|
|
connection.last_ping = now;
|
|
}
|
|
} else if (connection.authenticated) {
|
|
connection.send_snapshot(world, now);
|
|
}
|
|
connection.peer.flush();
|
|
if (connection.reject_pending && !connection.peer.pending()) connection.drop_peer();
|
|
} catch (const std::exception& error) {
|
|
connection.notice = error.what();
|
|
connection.drop_peer();
|
|
latest.reset();
|
|
}
|
|
return latest;
|
|
}
|
|
|
|
std::string local_lan_addresses() {
|
|
constexpr ULONG flags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER;
|
|
ULONG size = 15 * 1024;
|
|
std::vector<std::byte> buffer(size);
|
|
auto* addresses = reinterpret_cast<IP_ADAPTER_ADDRESSES*>(buffer.data());
|
|
auto result = GetAdaptersAddresses(AF_INET, flags, nullptr, addresses, &size);
|
|
if (result == ERROR_BUFFER_OVERFLOW) {
|
|
buffer.resize(size);
|
|
addresses = reinterpret_cast<IP_ADAPTER_ADDRESSES*>(buffer.data());
|
|
result = GetAdaptersAddresses(AF_INET, flags, nullptr, addresses, &size);
|
|
}
|
|
std::string usable;
|
|
if (result != NO_ERROR) return usable;
|
|
for (auto* adapter = addresses; adapter != nullptr; adapter = adapter->Next) {
|
|
if (adapter->OperStatus != IfOperStatusUp || adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK) continue;
|
|
for (auto* addr = adapter->FirstUnicastAddress; addr != nullptr; addr = addr->Next) {
|
|
if (addr->Address.lpSockaddr == nullptr || addr->Address.lpSockaddr->sa_family != AF_INET) continue;
|
|
const auto* ipv4 = reinterpret_cast<const sockaddr_in*>(addr->Address.lpSockaddr);
|
|
std::array<char, INET_ADDRSTRLEN> digits{};
|
|
if (!InetNtopA(AF_INET, &ipv4->sin_addr, digits.data(), digits.size())) continue;
|
|
if (!usable.empty()) usable += ", ";
|
|
usable += digits.data();
|
|
}
|
|
}
|
|
return usable;
|
|
}
|
|
|
|
} // namespace settlement::viewer
|