#define NOMINMAX #include #include #include #include #include "lan_session.hpp" #include "lan_wire.hpp" #include "settlement/core/simulation_runtime.hpp" #include #include #include #include #include #include #include #include #include #include #include namespace settlement::viewer { namespace { using Clock = std::chrono::steady_clock; using namespace std::chrono_literals; using lan_wire::guest_player; using lan_wire::Message; constexpr auto poll_budget = 16; constexpr std::size_t command_queue_limit = 32; 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(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(&enabled), sizeof(enabled)); } 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() + lan_wire::frame_header_size > lan_wire::frame_limit + 1024) { throw std::runtime_error("The peer is not receiving data fast enough."); } lan_wire::append_frame(output, message, payload); } void flush() { if (!pending()) return; const int size = static_cast(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(written); if (sent == output.size()) { output.clear(); sent = 0; } } template void receive(Deliver on_message) { std::array bytes{}; for (int read = 0; read < poll_budget; ++read) { const int count = recv(socket.handle, bytes.data(), static_cast(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(count)); 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 (consumed != 0) input.erase(0, consumed); } } }; 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 digits{}; const auto result = std::to_chars(digits.data(), digits.data() + digits.size(), key, 16); const auto size = static_cast(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; }; void require_legacy_world(const World& world) { if (!world.scenario_active() || world.width() != first_colony_map_size || world.height() != first_colony_map_size) { throw std::runtime_error("Protocol 11 requires a supported 32x32 colony."); } if (!world.legacy_representable()) { throw UnsupportedLegacyState{}; } } } // namespace struct LanSession::Impl { struct PendingCommand { std::future completion; Void::Uuid::Uuid session; std::uint64_t peer_generation; }; bool winsock = false; Socket listener; Channel peer; bool guest = false; bool connecting = false; bool authenticated = false; bool reject_pending = false; std::optional awaiting_receipt; std::uint16_t network_port = 0; std::uint64_t key = 0; std::string host_address; std::string notice; std::deque actions; std::optional rejected_command; std::optional command_result; bool result_backpressure = false; 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; std::uint64_t peer_generation = 0; std::optional runtime_session; std::optional compatibility_rules; std::optional pending_command; LanSessionOptions options; explicit Impl(LanSessionOptions settings) : options(std::move(settings)) { WSADATA data{}; winsock = WSAStartup(MAKEWORD(2, 2), &data) == 0; } ~Impl() { peer.socket.reset(); listener.reset(); if (winsock) WSACleanup(); } void drop_peer() noexcept { ++peer_generation; peer = Channel{}; connecting = authenticated = reject_pending = false; awaiting_receipt.reset(); guest_sequence = 0; actions.clear(); rejected_command.reset(); command_result.reset(); last_snapshot = {}; last_ping = {}; // pending_command belongs to the authenticated guest slot, even after // its socket disappears. A later peer waits for this result to settle. } 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(&code), &length) != 0 || code != 0) { throw std::runtime_error("Could not connect to the host."); } connecting = false; } void authenticate(Message message, std::string_view payload) { if (reject_pending) return; 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; } authenticated = true; notice.clear(); } void handle_host(World& world, Message message, std::string_view payload) { if (!authenticated) { authenticate(message, payload); return; } if (message == Message::Ping && payload.empty()) return; 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 reply(CommandStatus status, const World& world) { const auto bytes = lan_wire::encode_receipt({status, world.next_command_sequence(guest_player)}); peer.queue(Message::Receipt, std::string_view(bytes)); } void handle_runtime_host(SimulationRuntime& runtime, const std::shared_ptr& checked, Message message, std::string_view payload) { const auto& snapshot = *checked; if (!authenticated) { authenticate(message, payload); return; } if (message == Message::Ping && payload.empty()) return; const auto command = message == Message::Command ? lan_wire::decode_command(payload) : std::nullopt; if (!command) throw std::runtime_error("Invalid guest command."); if (pending_command) throw std::runtime_error("A guest command is already pending."); if (command->sequence != snapshot.world->next_command_sequence(guest_player)) { reply(CommandStatus::WrongSequence, *snapshot.world); return; } const auto& identity = snapshot.identity; const CommandEnvelope envelope{ command_envelope_version, identity.world, identity.session, identity.city, snapshot.next_requests[guest_player - 1], CommandPayload{command->kind, command->cell, command->value, command->destination, command->resident} }; if (options.before_command_admission) options.before_command_admission(); auto submitted = runtime.try_submit_if_current({guest_player}, envelope, checked); if (submitted.admission == RuntimeAdmission::Accepted) { pending_command.emplace(std::move(submitted.completion), identity.session, peer_generation); } else if (submitted.admission == RuntimeAdmission::Busy || submitted.admission == RuntimeAdmission::StaleSnapshot) { // Contention/capacity does not certify the old publication either. // Fail closed on incompatible/faulted/replaced state; an ordinary // compatible revision leaves the legacy sequence available to retry. const auto current = current_runtime_snapshot(runtime); reply(CommandStatus::Busy, *current->world); } else { throw std::runtime_error("The authoritative owner cannot accept guest commands."); } } void complete_runtime_command(SimulationRuntime& runtime) { if (!pending_command || pending_command->completion.wait_for(0s) != std::future_status::ready) return; auto pending = std::move(*pending_command); pending_command.reset(); const auto result = pending.completion.get(); if (pending.peer_generation != peer_generation || !authenticated || !runtime_session || pending.session != *runtime_session) return; // A ready receipt can predate a load or an incompatible local change. // Settle its future, but never queue old bytes for the current peer. const auto current = runtime.view(); validate_runtime(current); if (current.snapshot->identity.session != pending.session) return; if (result.outcome != RuntimeOutcome::Completed || !result.receipt || !result.snapshot || result.snapshot->identity.session != pending.session) { throw std::runtime_error("The authoritative guest command did not commit."); } const auto& receipt = *result.receipt; if (receipt.status == DispatchStatus::Completed) { reply(receipt.command_status, *result.snapshot->world); } else if (receipt.status == DispatchStatus::Busy) { reply(CommandStatus::Busy, *result.snapshot->world); } else { throw std::runtime_error("The guest command belongs to an obsolete or conflicting request."); } } void validate_runtime(const RuntimeView& view) { if (!compatibility_rules) { auto rules = default_rules_manifest(); if (!rules) throw std::runtime_error("Could not resolve the legacy LAN rules."); compatibility_rules = std::move(*rules); } if (view.state != RuntimeState::Running || !view.snapshot || !view.snapshot->world) { throw std::runtime_error("The authoritative owner is unavailable."); } const auto& snapshot = *view.snapshot; if (!snapshot.rules || *snapshot.rules != *compatibility_rules) { throw std::runtime_error("Protocol 11 requires the compiled default rules."); } require_legacy_world(*snapshot.world); } void bind_runtime(const RuntimeView& view) { validate_runtime(view); const auto& snapshot = *view.snapshot; if (runtime_session && *runtime_session != snapshot.identity.session) drop_peer(); runtime_session = snapshot.identity.session; } std::shared_ptr current_runtime_snapshot(SimulationRuntime& runtime) { const auto view = runtime.view(); validate_runtime(view); if (!runtime_session || *runtime_session != view.snapshot->identity.session) { throw std::runtime_error("The authoritative session changed. Reconnect to the host."); } return view.snapshot; } void handle_guest(std::unique_ptr& 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::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(guest_player); authenticated = true; notice.clear(); return; } 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 = receipt->status; if (status > CommandStatus::Busy) throw std::runtime_error("Invalid command result."); command_result = LanCommandResult{status, awaiting_receipt->kind, awaiting_receipt->cell, awaiting_receipt->value, awaiting_receipt->destination, awaiting_receipt->resident}; if (status != CommandStatus::Accepted) { rejected_command = LanRejection{status, awaiting_receipt->kind, awaiting_receipt->cell, awaiting_receipt->value, awaiting_receipt->destination}; } guest_sequence = receipt->next_sequence; awaiting_receipt.reset(); } void send_snapshot(const World& world, Clock::time_point now) { require_legacy_world(world); if (peer.pending()) return; const auto host_seq = world.next_command_sequence(1); 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.view()); 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; if (result_backpressure && command_result) return; const Action action = actions.front(); 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; } template void poll_network(Receive receive, SendHost send_host, Validate validate, bool accept_allowed = true) { validate(); if (listener && accept_allowed) accept_guest(); if (!peer.socket) return; const auto now = Clock::now(); if ((!authenticated && now - peer.opened > 8s) || (authenticated && now - peer.last_received > 15s)) { throw std::runtime_error("The peer did not respond."); } if (connecting) finish_connection(); if (connecting) return; peer.receive([&](Message message, std::string_view payload) { // The owner can publish while one receive drains several frames. validate(); receive(message, payload); }); validate(); if (authenticated && guest) { send_action(); if (!peer.pending() && now - last_ping >= 2s) { peer.queue(Message::Ping); last_ping = now; } } else if (authenticated) { send_host(now); } // This includes old snapshots/receipts already waiting in output. validate(); peer.flush(); if (reject_pending && !peer.pending()) drop_peer(); } }; LanSession::LanSession() : LanSession(LanSessionOptions{}) {} LanSession::LanSession(LanSessionOptions options) : impl_(std::make_unique(std::move(options))) {} 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(&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(&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(&local), &length) != 0) { throw std::runtime_error("Could not determine the local LAN port."); } std::uint64_t key = 0; if (BCryptGenRandom(nullptr, reinterpret_cast(&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(&remote), sizeof(remote)) != 0; if (pending && WSAGetLastError() != WSAEWOULDBLOCK) throw std::runtime_error("Could not connect to the host."); const auto identity = lan_wire::encode_hello({lan_wire::protocol_version, key}); Channel channel(std::move(socket)); channel.queue(Message::Hello, std::string_view(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 LanSession::take_rejection() noexcept { return std::exchange(impl_->rejected_command, std::nullopt); } std::optional LanSession::take_result() noexcept { return std::exchange(impl_->command_result, std::nullopt); } std::unique_ptr LanSession::poll(World& world) { auto& connection = *impl_; connection.result_backpressure = false; std::unique_ptr latest; try { if (connection.pending_command) throw std::runtime_error("Continue polling the authoritative owner."); connection.poll_network([&](Message message, std::string_view payload) { if (connection.guest) connection.handle_guest(latest, message, payload); else connection.handle_host(world, message, payload); }, [&](Clock::time_point now) { connection.send_snapshot(world, now); }, [&] { if (connection.listener && !connection.guest) require_legacy_world(world); }); } catch (const std::exception& error) { connection.notice = error.what(); connection.drop_peer(); latest.reset(); } return latest; } void LanSession::poll_host(SimulationRuntime& runtime) { auto& connection = *impl_; if (!connection.listener || connection.guest) return; try { connection.complete_runtime_command(runtime); // Completion may have published a newer next-request number. Re-read it // before admitting a reconnect or decoding any further guest intent. const auto view = runtime.view(); connection.bind_runtime(view); connection.poll_network([&](Message message, std::string_view payload) { const auto snapshot = connection.current_runtime_snapshot(runtime); connection.handle_runtime_host(runtime, snapshot, message, payload); }, [&](Clock::time_point now) { const auto snapshot = connection.current_runtime_snapshot(runtime); if (!connection.pending_command) connection.send_snapshot(*snapshot->world, now); }, [&] { static_cast(connection.current_runtime_snapshot(runtime)); }, !connection.pending_command); } catch (const std::exception& error) { connection.notice = error.what(); connection.drop_peer(); } } std::unique_ptr LanSession::poll_guest() { auto& connection = *impl_; connection.result_backpressure = true; std::unique_ptr latest; if (!connection.guest) return nullptr; try { connection.poll_network([&](Message message, std::string_view payload) { connection.handle_guest(latest, message, payload); }, [](Clock::time_point) {}, [] {}); } 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 buffer(size); auto* addresses = reinterpret_cast(buffer.data()); auto result = GetAdaptersAddresses(AF_INET, flags, nullptr, addresses, &size); if (result == ERROR_BUFFER_OVERFLOW) { buffer.resize(size); addresses = reinterpret_cast(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(addr->Address.lpSockaddr); std::array 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