#define NOMINMAX #include #include #include #include #include "lan_session.hpp" #include "lan_wire.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; }; } // 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 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::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(&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; 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(); 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 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."); 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) { 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; 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; } }; LanSession::LanSession() : impl_(std::make_unique()) {} 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::unique_ptr LanSession::poll(World& world) { auto& connection = *impl_; std::unique_ptr 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 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