diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index e202f61..bd5aa42 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -114,6 +114,35 @@ so a scripted match covers the drop, loot, combat, harvesting, building and the from a player's seat. `ServerLoop.play_humans_by_script()` turns it on; no shipped mode uses it. +## Transport and handshake + +The transport is ENet over UDP, used directly through `ENetConnection` (not Godot's +high-level multiplayer API, so the server controls every byte it accepts). Channel 0 +is reliable control traffic; channel 1 is for commands and snapshots. + +`NetServer` and `NetClient` (`src/net/`) own the two ends, and `NetProtocol` the +message layouts and the protocol version. A new connection is a guest until its HELLO +is accepted: + +1. The client sends HELLO: a magic number, its protocol version and the name it wants. +2. The server answers WELCOME (the player's handle, the match seed, tick rate, player + limit and the name as accepted) or REJECT with a reason, then disconnects. + +A guest gets one try. A HELLO that is malformed, on the wrong channel or too long is +refused as such; a different protocol version, a full server and silence past the +handshake timeout each have their own reason, and the client turns the reason into a +sentence for the player (`NetProtocol.reason_text`). The reason also rides on the +disconnect itself, in case the REJECT is lost. Names are cleaned on both ends: control +and invisible characters removed, 16 characters at most, never empty, and a number +added if someone already has it. Handles are positive, count up and are never reused +while the server runs. + +Leaving cleanly tells the server at once. A client that vanishes is dropped by ENet's +timeout (5 to 15 seconds without an acknowledgement), and the owner sees the same +"left" event with a different reason. Decoders return nothing for bad input and never +raise an engine error; anything a joined player sends that isn't understood is counted +and dropped. + ## Snapshot format A snapshot is a binary, little-endian packet: diff --git a/src/net/.gitkeep b/src/net/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/src/net/net_client.gd b/src/net/net_client.gd new file mode 100644 index 0000000..aa82b41 --- /dev/null +++ b/src/net/net_client.gd @@ -0,0 +1,167 @@ +## The client's end of the transport: connects to a server with ENet, introduces itself +## and reports whether it was let in. Call poll() every frame and read `state`. +class_name NetClient +extends RefCounted + +const IDLE: int = 0 +## Waiting for the server to answer at all. +const CONNECTING: int = 1 +## Connected; HELLO sent, waiting for WELCOME or REJECT. +const HANDSHAKING: int = 2 +const JOINED: int = 3 +## Over. `close_reason` says why. +const CLOSED: int = 4 +const STATE_NAMES: Array[String] = ["idle", "connecting", "handshaking", "joined", "closed"] + +## Milliseconds to wait for the server to answer, and then for its verdict. +var connect_timeout_msec: int = 5000 +var handshake_timeout_msec: int = 5000 +var peer_timeout_min_msec: int = 5000 +var peer_timeout_max_msec: int = 15000 +## The protocol version to claim. Only tests change it. +var protocol_version: int = NetProtocol.VERSION + +var state: int = IDLE +## A NetProtocol.REASON_* once closed. +var close_reason: int = NetProtocol.REASON_NONE +## The server's protocol version, once it has said. +var server_version: int = 0 +## From the server's WELCOME. +var handle: int = 0 +var player_name: String = "" +var match_seed: int = 0 +var max_players: int = 0 +var tick_rate: int = 0 + +var _host: ENetConnection = null +var _peer: ENetPacketPeer = null +var _wanted_name: String = "" +var _since_msec: int = 0 + + +func state_name() -> String: + return STATE_NAMES[state] + + +## Starts connecting. Returns OK if the attempt began; the outcome comes through poll(). +func connect_to(address: String, port: int, wanted_name: String, now_msec: int = -1) -> Error: + _drop() + state = IDLE + close_reason = NetProtocol.REASON_NONE + server_version = 0 + handle = 0 + var host: ENetConnection = ENetConnection.new() + var error: Error = host.create_host(1, NetProtocol.CHANNEL_COUNT) + if error != OK: + return error + var peer: ENetPacketPeer = host.connect_to_host(address, port, NetProtocol.CHANNEL_COUNT) + if peer == null: + host.destroy() + return ERR_CANT_CONNECT + _host = host + _peer = peer + _wanted_name = wanted_name + _since_msec = now_msec if now_msec >= 0 else Time.get_ticks_msec() + state = CONNECTING + return OK + + +func poll(now_msec: int = -1) -> void: + if _host == null: + return + var now: int = now_msec if now_msec >= 0 else Time.get_ticks_msec() + while _host != null: + var event: Array = _host.service(0) + var kind: int = event[0] + if kind == ENetConnection.EVENT_NONE or kind == ENetConnection.EVENT_ERROR: + break + match kind: + ENetConnection.EVENT_CONNECT: + _peer.set_timeout(0, peer_timeout_min_msec, peer_timeout_max_msec) + _peer.send(NetProtocol.CHANNEL_CONTROL, NetProtocol.encode_hello(_wanted_name, protocol_version), ENetPacketPeer.FLAG_RELIABLE) + state = HANDSHAKING + _since_msec = now + ENetConnection.EVENT_RECEIVE: + _received(int(event[3]), _peer.get_packet()) + ENetConnection.EVENT_DISCONNECT: + var data: int = int(event[2]) + var reason: int = close_reason + if reason == NetProtocol.REASON_NONE: + reason = data if data > NetProtocol.REASON_NONE and data <= NetProtocol.REASON_KICKED \ + else (NetProtocol.REASON_NO_ANSWER if state == CONNECTING else NetProtocol.REASON_LOST) + _close(reason) + if state == CONNECTING and now - _since_msec >= connect_timeout_msec: + _close(NetProtocol.REASON_NO_ANSWER) + elif state == HANDSHAKING and now - _since_msec >= handshake_timeout_msec: + _close(NetProtocol.REASON_NO_ANSWER) + + +## Sends `bytes` to the server once joined. Returns false otherwise. +func send(channel: int, bytes: PackedByteArray, reliable: bool) -> bool: + if state != JOINED: + return false + return _peer.send(channel, bytes, ENetPacketPeer.FLAG_RELIABLE if reliable else ENetPacketPeer.FLAG_UNSEQUENCED) == OK + + +## Says goodbye and closes. The server learns at once rather than by timeout. +func leave() -> void: + if _host == null: + return + if _peer != null and _peer.is_active(): + _peer.peer_disconnect_now(NetProtocol.REASON_LEFT) + _host.flush() + _close(NetProtocol.REASON_LEFT) + + +## A sentence for the player about where the connection stands. +func status_text() -> String: + match state: + CONNECTING: + return "Connecting..." + HANDSHAKING: + return "Joining..." + JOINED: + return "Joined as %s." % player_name + CLOSED: + return NetProtocol.reason_text(close_reason, server_version, protocol_version) + return "Not connected." + + +func _received(channel: int, bytes: PackedByteArray) -> void: + if channel != NetProtocol.CHANNEL_CONTROL or bytes.is_empty(): + return + if state == HANDSHAKING and bytes[0] == NetProtocol.MSG_WELCOME: + var welcome: Dictionary = NetProtocol.decode_welcome(bytes) + if welcome.is_empty() or int(welcome["version"]) != protocol_version: + server_version = int(welcome.get("version", 0)) + _peer.peer_disconnect_now(NetProtocol.REASON_LEFT) + _host.flush() + _close(NetProtocol.REASON_VERSION if not welcome.is_empty() else NetProtocol.REASON_BAD_HELLO) + return + server_version = int(welcome["version"]) + handle = int(welcome["handle"]) + player_name = String(welcome["name"]) + match_seed = int(welcome["seed"]) + max_players = int(welcome["max_players"]) + tick_rate = int(welcome["tick_rate"]) + state = JOINED + elif bytes[0] == NetProtocol.MSG_REJECT: + var reject: Dictionary = NetProtocol.decode_reject(bytes) + if reject.is_empty(): + return + # Remember why; the server's disconnect follows and closes the connection. + server_version = int(reject["server_version"]) + close_reason = int(reject["reason"]) + + +func _close(reason: int) -> void: + _drop() + state = CLOSED + close_reason = reason + + +func _drop() -> void: + if _host != null: + _host.destroy() + _host = null + _peer = null diff --git a/src/net/net_client.gd.uid b/src/net/net_client.gd.uid new file mode 100644 index 0000000..3ede160 --- /dev/null +++ b/src/net/net_client.gd.uid @@ -0,0 +1 @@ +uid://dib03f4cwugrr diff --git a/src/net/net_protocol.gd b/src/net/net_protocol.gd new file mode 100644 index 0000000..41a3b1a --- /dev/null +++ b/src/net/net_protocol.gd @@ -0,0 +1,212 @@ +## The wire protocol's handshake: message layouts, the protocol version, the reasons a +## server turns a client away, and what to tell the player about each. +## +## Everything is little-endian. The handshake runs on channel 0, reliable: +## +## client -> HELLO u8 type, 4 bytes "TDWL", u16 protocol version, u8 name length, +## name in UTF-8 +## server -> WELCOME u8 type, u16 protocol version, u32 handle, u8 tick rate, +## u8 max players, u64 match seed, u8 name length, name as accepted +## server -> REJECT u8 type, u8 reason, u16 the server's protocol version +## +## After a REJECT the server disconnects, with the reason again as the disconnect's +## data, so a client that lost the message still learns why. Decoders return an empty +## Dictionary for anything malformed and never raise an error. +class_name NetProtocol +extends RefCounted + +## Raised whenever the wire format changes in a way old clients can't read. +const VERSION: int = 1 +const MAGIC: String = "TDWL" +const CHANNEL_CONTROL: int = 0 +## Unreliable game traffic: commands up, snapshots down. +const CHANNEL_STATE: int = 1 +const CHANNEL_COUNT: int = 2 + +const MSG_HELLO: int = 1 +const MSG_WELCOME: int = 2 +const MSG_REJECT: int = 3 + +## Why a connection ended. Sent in REJECT and as disconnect data. +const REASON_NONE: int = 0 +const REASON_VERSION: int = 1 +const REASON_FULL: int = 2 +const REASON_BAD_HELLO: int = 3 +const REASON_HANDSHAKE_TIMEOUT: int = 4 +const REASON_SHUTDOWN: int = 5 +const REASON_KICKED: int = 6 +const REASON_LEFT: int = 7 +## Client-side only: nothing answered, or the connection went quiet. +const REASON_NO_ANSWER: int = 8 +const REASON_LOST: int = 9 + +const NAME_MAX_CHARS: int = 16 +const NAME_MAX_BYTES: int = 64 +const DEFAULT_NAME: String = "Castaway" +## No handshake message is longer than this; anything bigger is refused unread. +const MAX_HANDSHAKE_BYTES: int = 96 + + +## A name fit to show: no control or formatting characters, single spaces, at most +## NAME_MAX_CHARS characters, and never empty. +static func clean_name(raw: String) -> String: + var kept: String = "" + var spaced: bool = true + for index: int in raw.length(): + var code: int = raw.unicode_at(index) + var space: bool = code == 0x20 or code == 0x09 or code == 0xA0 + # Control characters, bidirectional overrides, zero-width marks and private use. + var hidden: bool = code < 0x20 or (code >= 0x7F and code < 0xA0) \ + or (code >= 0x200B and code <= 0x200F) or (code >= 0x202A and code <= 0x202E) \ + or (code >= 0x2060 and code <= 0x206F) or code == 0xFEFF or (code >= 0xE000 and code <= 0xF8FF) \ + or code == 0xFFFD or code > 0x2FFFF + if space: + if not spaced: + kept += " " + spaced = true + elif not hidden: + kept += String.chr(code) + spaced = false + if kept.length() >= NAME_MAX_CHARS: + break + kept = kept.strip_edges() + while kept.to_utf8_buffer().size() > NAME_MAX_BYTES: + kept = kept.substr(0, kept.length() - 1) + return kept if not kept.is_empty() else DEFAULT_NAME + + +static func encode_hello(player_name: String, version: int = VERSION) -> PackedByteArray: + var name_bytes: PackedByteArray = clean_name(player_name).to_utf8_buffer() + var out: StreamPeerBuffer = _writer() + out.put_u8(MSG_HELLO) + out.put_data(MAGIC.to_ascii_buffer()) + out.put_u16(version) + out.put_u8(name_bytes.size()) + out.put_data(name_bytes) + return out.data_array + + +## {"version", "name"} or an empty Dictionary. The name is returned cleaned. +static func decode_hello(bytes: PackedByteArray) -> Dictionary: + if bytes.size() < 8 or bytes.size() > MAX_HANDSHAKE_BYTES or bytes[0] != MSG_HELLO: + return {} + if bytes.slice(1, 5) != MAGIC.to_ascii_buffer(): + return {} + var name_size: int = bytes[7] + if name_size > NAME_MAX_BYTES or bytes.size() != 8 + name_size: + return {} + var player_name: String = _utf8(bytes.slice(8)) + if name_size > 0 and player_name.is_empty(): + return {} + return {"version": bytes.decode_u16(5), "name": clean_name(player_name)} + + +static func encode_welcome(handle: int, match_seed: int, max_players: int, player_name: String) -> PackedByteArray: + var name_bytes: PackedByteArray = clean_name(player_name).to_utf8_buffer() + var out: StreamPeerBuffer = _writer() + out.put_u8(MSG_WELCOME) + out.put_u16(VERSION) + out.put_u32(handle) + out.put_u8(Tuning.TICK_RATE_HZ) + out.put_u8(clampi(max_players, 0, 255)) + out.put_64(match_seed) + out.put_u8(name_bytes.size()) + out.put_data(name_bytes) + return out.data_array + + +## {"version", "handle", "tick_rate", "max_players", "seed", "name"} or empty. +static func decode_welcome(bytes: PackedByteArray) -> Dictionary: + if bytes.size() < 18 or bytes.size() > MAX_HANDSHAKE_BYTES or bytes[0] != MSG_WELCOME: + return {} + var name_size: int = bytes[17] + if name_size > NAME_MAX_BYTES or bytes.size() != 18 + name_size: + return {} + var handle: int = bytes.decode_u32(3) + if handle <= 0: + return {} + return { + "version": bytes.decode_u16(1), "handle": handle, "tick_rate": bytes[7], "max_players": bytes[8], + "seed": bytes.decode_s64(9), "name": clean_name(_utf8(bytes.slice(18))), + } + + +static func encode_reject(reason: int) -> PackedByteArray: + var out: StreamPeerBuffer = _writer() + out.put_u8(MSG_REJECT) + out.put_u8(reason) + out.put_u16(VERSION) + return out.data_array + + +## {"reason", "server_version"} or empty. +static func decode_reject(bytes: PackedByteArray) -> Dictionary: + if bytes.size() != 4 or bytes[0] != MSG_REJECT: + return {} + return {"reason": bytes[1], "server_version": bytes.decode_u16(2)} + + +## What to tell the player when a connection ends for `reason`. `server_version` is +## the server's protocol version if it said, or 0. +static func reason_text(reason: int, server_version: int = 0, own_version: int = VERSION) -> String: + match reason: + REASON_VERSION: + if server_version > own_version: + return "This server runs a newer version of Tidewall (protocol %d; this game speaks %d). Update the game to join." % [server_version, own_version] + if server_version > 0: + return "This server runs an older version of Tidewall (protocol %d; this game speaks %d). It needs updating before you can join." % [server_version, own_version] + return "This server runs a different version of Tidewall (this game speaks protocol %d)." % own_version + REASON_FULL: + return "The server is full." + REASON_BAD_HELLO: + return "The server didn't understand this game's greeting. It may not be a Tidewall server." + REASON_HANDSHAKE_TIMEOUT: + return "The server gave up waiting for this game to introduce itself." + REASON_SHUTDOWN: + return "The server shut down." + REASON_KICKED: + return "The server removed you from the game." + REASON_LEFT: + return "You left the game." + REASON_NO_ANSWER: + return "No answer from the server. Check the address and port, and that the server is running." + REASON_LOST: + return "The connection to the server was lost." + return "Disconnected." + + +static func _writer() -> StreamPeerBuffer: + var out: StreamPeerBuffer = StreamPeerBuffer.new() + out.big_endian = false + return out + + +## Strict UTF-8: an empty string for bytes that aren't valid, with no engine error. +static func _utf8(bytes: PackedByteArray) -> String: + var index: int = 0 + while index < bytes.size(): + var lead: int = bytes[index] + var extra: int = 0 + if lead < 0x80: + extra = 0 + elif lead >= 0xC2 and lead < 0xE0: + extra = 1 + elif lead >= 0xE0 and lead < 0xF0: + extra = 2 + elif lead >= 0xF0 and lead < 0xF5: + extra = 3 + else: + return "" + if index + extra > bytes.size() - 1: + return "" + for offset: int in range(1, extra + 1): + if bytes[index + offset] & 0xC0 != 0x80: + return "" + # Overlong forms, surrogates and code points past the end of Unicode. + if extra >= 2: + var second: int = bytes[index + 1] + if (lead == 0xE0 and second < 0xA0) or (lead == 0xED and second >= 0xA0) \ + or (lead == 0xF0 and second < 0x90) or (lead == 0xF4 and second >= 0x90): + return "" + index += extra + 1 + return bytes.get_string_from_utf8() diff --git a/src/net/net_protocol.gd.uid b/src/net/net_protocol.gd.uid new file mode 100644 index 0000000..c5ad493 --- /dev/null +++ b/src/net/net_protocol.gd.uid @@ -0,0 +1 @@ +uid://cs25yfo41uida diff --git a/src/net/net_server.gd b/src/net/net_server.gd new file mode 100644 index 0000000..8ff81e8 --- /dev/null +++ b/src/net/net_server.gd @@ -0,0 +1,208 @@ +## The server's end of the transport: listens with ENet, takes each new connection +## through the handshake, and reports who joined and who left. It decides nothing about +## the match; whoever owns it reads `events` after each poll(). +## +## A connection is a guest until its HELLO is accepted. Guests can't do anything else, +## get one try, and are dropped if they stay silent past the handshake timeout. Player +## handles are positive, count up from 1 and are never reused while the server runs. +class_name NetServer +extends RefCounted + +## Milliseconds a new connection has to send its HELLO. +var handshake_timeout_msec: int = 5000 +## ENet drops a peer that acknowledges nothing for between these two times. +var peer_timeout_min_msec: int = 5000 +var peer_timeout_max_msec: int = 15000 +## Players allowed at once. Further clients are told the server is full. +var max_players: int = Tuning.SOLO_PLAYERS +## Sent to each client in its WELCOME, so it can generate the same island. +var match_seed: int = 0 +## What happened during the last poll(): {"type": "joined", "handle", "name"}, +## {"type": "left", "handle", "name", "reason"} and {"type": "refused", "reason"}. +var events: Array[Dictionary] = [] +## Malformed or unexpected packets dropped so far. +var bad_packets: int = 0 + +var _host: ENetConnection = null +## Peers that haven't finished the handshake: ENetPacketPeer -> msec they connected. +var _guests: Dictionary = {} +## Peers being turned away: ENetPacketPeer -> the reason, until ENet reports them gone. +var _leaving: Dictionary = {} +## Handle -> {"peer": ENetPacketPeer, "name": String}. +var _players: Dictionary = {} +## ENetPacketPeer -> handle. +var _handle_of: Dictionary = {} +var _next_handle: int = 1 + + +## Starts listening on UDP `port` (0 picks a free one) on `address`. Returns OK or the +## error, and leaves the server closed on failure. +func listen(port: int, address: String = "*") -> Error: + close() + var host: ENetConnection = ENetConnection.new() + # Room for a few guests beyond the player limit, so a full server can say so. + var error: Error = host.create_host_bound(address, port, max_players + 8, NetProtocol.CHANNEL_COUNT) + if error != OK: + return error + _host = host + return OK + + +func is_listening() -> bool: + return _host != null + + +## The UDP port in use, or 0 when closed. +func port() -> int: + return _host.get_local_port() if _host != null else 0 + + +func player_count() -> int: + return _players.size() + + +func guest_count() -> int: + return _guests.size() + + +func handles() -> Array[int]: + var result: Array[int] = [] + for handle: int in _players: + result.append(handle) + result.sort() + return result + + +## The accepted name of a player, or an empty string. +func name_of(handle: int) -> String: + return String(_players[handle]["name"]) if _players.has(handle) else "" + + +## Services the socket: accepts connections, runs handshakes, notices departures. +## Call it every frame. `now_msec` is for tests; it defaults to the engine's clock. +func poll(now_msec: int = -1) -> void: + events.clear() + if _host == null: + return + var now: int = now_msec if now_msec >= 0 else Time.get_ticks_msec() + while true: + var event: Array = _host.service(0) + var kind: int = event[0] + if kind == ENetConnection.EVENT_NONE or kind == ENetConnection.EVENT_ERROR: + break + var peer: ENetPacketPeer = event[1] + match kind: + ENetConnection.EVENT_CONNECT: + peer.set_timeout(0, peer_timeout_min_msec, peer_timeout_max_msec) + _guests[peer] = now + ENetConnection.EVENT_DISCONNECT: + _gone(peer, int(event[2])) + ENetConnection.EVENT_RECEIVE: + _received(peer, int(event[3]), peer.get_packet()) + for peer: ENetPacketPeer in _guests.keys(): + if now - int(_guests[peer]) >= handshake_timeout_msec: + _refuse(peer, NetProtocol.REASON_HANDSHAKE_TIMEOUT) + + +## Sends `bytes` to a player. Returns false if they aren't connected. +func send(handle: int, channel: int, bytes: PackedByteArray, reliable: bool) -> bool: + if not _players.has(handle): + return false + var peer: ENetPacketPeer = _players[handle]["peer"] + var flags: int = ENetPacketPeer.FLAG_RELIABLE if reliable else ENetPacketPeer.FLAG_UNSEQUENCED + return peer.send(channel, bytes, flags) == OK + + +## Removes a player, telling them why. They are reported as "left" at once. +func kick(handle: int, reason: int = NetProtocol.REASON_KICKED) -> bool: + if not _players.has(handle): + return false + var peer: ENetPacketPeer = _players[handle]["peer"] + events.append({"type": "left", "handle": handle, "name": name_of(handle), "reason": reason}) + _players.erase(handle) + _handle_of.erase(peer) + _leaving[peer] = reason + peer.send(NetProtocol.CHANNEL_CONTROL, NetProtocol.encode_reject(reason), ENetPacketPeer.FLAG_RELIABLE) + peer.peer_disconnect_later(reason) + return true + + +## Stops listening. Everyone connected is told the server shut down. +func close() -> void: + if _host == null: + return + for peer: ENetPacketPeer in _guests.keys() + _handle_of.keys() + _leaving.keys(): + if peer.is_active(): + peer.peer_disconnect_now(NetProtocol.REASON_SHUTDOWN) + _host.flush() + _host.destroy() + _host = null + _guests.clear() + _leaving.clear() + _players.clear() + _handle_of.clear() + + +func _received(peer: ENetPacketPeer, channel: int, bytes: PackedByteArray) -> void: + if _leaving.has(peer): + return + if _handle_of.has(peer): + # Game traffic arrives with N2. A second HELLO, or anything else, is dropped. + bad_packets += 1 + return + if not _guests.has(peer): + return + var hello: Dictionary = NetProtocol.decode_hello(bytes) if channel == NetProtocol.CHANNEL_CONTROL else {} + if hello.is_empty(): + bad_packets += 1 + _refuse(peer, NetProtocol.REASON_BAD_HELLO) + elif int(hello["version"]) != NetProtocol.VERSION: + _refuse(peer, NetProtocol.REASON_VERSION) + elif _players.size() >= max_players: + _refuse(peer, NetProtocol.REASON_FULL) + else: + _guests.erase(peer) + var handle: int = _next_handle + _next_handle += 1 + var player_name: String = _unique_name(String(hello["name"])) + _players[handle] = {"peer": peer, "name": player_name} + _handle_of[peer] = handle + peer.send(NetProtocol.CHANNEL_CONTROL, NetProtocol.encode_welcome(handle, match_seed, max_players, player_name), ENetPacketPeer.FLAG_RELIABLE) + events.append({"type": "joined", "handle": handle, "name": player_name}) + + +## Turns a guest away: tells it why, then disconnects once that has been delivered. +func _refuse(peer: ENetPacketPeer, reason: int) -> void: + _guests.erase(peer) + _leaving[peer] = reason + events.append({"type": "refused", "reason": reason}) + peer.send(NetProtocol.CHANNEL_CONTROL, NetProtocol.encode_reject(reason), ENetPacketPeer.FLAG_RELIABLE) + peer.peer_disconnect_later(reason) + + +func _gone(peer: ENetPacketPeer, data: int) -> void: + _guests.erase(peer) + _leaving.erase(peer) + if not _handle_of.has(peer): + return + var handle: int = _handle_of[peer] + # A client that says goodbye sends REASON_LEFT; one that just vanishes sends nothing. + var reason: int = NetProtocol.REASON_LEFT if data == NetProtocol.REASON_LEFT else NetProtocol.REASON_LOST + events.append({"type": "left", "handle": handle, "name": name_of(handle), "reason": reason}) + _players.erase(handle) + _handle_of.erase(peer) + + +## `wanted`, or `wanted` with a number after it if someone here already has that name. +func _unique_name(wanted: String) -> String: + var taken: Dictionary = {} + for handle: int in _players: + taken[String(_players[handle]["name"]).to_lower()] = true + if not taken.has(wanted.to_lower()): + return wanted + for number: int in range(2, max_players + 2): + var suffix: String = " %d" % number + var candidate: String = wanted.substr(0, NetProtocol.NAME_MAX_CHARS - suffix.length()).strip_edges() + suffix + if not taken.has(candidate.to_lower()): + return candidate + return wanted diff --git a/src/net/net_server.gd.uid b/src/net/net_server.gd.uid new file mode 100644 index 0000000..98b211e --- /dev/null +++ b/src/net/net_server.gd.uid @@ -0,0 +1 @@ +uid://6635d4cj3x0x diff --git a/test/net/test_net_handshake.gd b/test/net/test_net_handshake.gd new file mode 100644 index 0000000..0ebb8ec --- /dev/null +++ b/test/net/test_net_handshake.gd @@ -0,0 +1,296 @@ +extends TestCase + +## Issue N1: a real NetServer and NetClients over loopback UDP. Handshake, refusals, +## clean leaves, timeouts, and hostile or broken peers. + +const HOST: String = "127.0.0.1" + +var server: NetServer +var clients: Array[NetClient] = [] +## Every server event since the test began. +var seen: Array[Dictionary] = [] +var raw_hosts: Array[ENetConnection] = [] + + +func before_each() -> void: + server = NetServer.new() + server.match_seed = 4242 + clients.clear() + seen.clear() + raw_hosts.clear() + assert_eq(server.listen(0, HOST), OK) + assert_true(server.port() > 0) + + +func after_each() -> void: + for client: NetClient in clients: + client.leave() + for host: ENetConnection in raw_hosts: + host.destroy() + server.close() + + +func _client(wanted: String) -> NetClient: + var client: NetClient = NetClient.new() + clients.append(client) + assert_eq(client.connect_to(HOST, server.port(), wanted), OK) + return client + + +## Polls everything until `done` is true or `limit_msec` passes. Returns `done`'s answer. +func _pump(done: Callable, limit_msec: int = 4000) -> bool: + var started: int = Time.get_ticks_msec() + while Time.get_ticks_msec() - started < limit_msec: + server.poll() + seen.append_array(server.events) + for client: NetClient in clients: + client.poll() + for host: ENetConnection in raw_hosts: + _service_raw(host) + if done.call(): + return true + OS.delay_msec(2) + return bool(done.call()) + + +func _events(type: String) -> Array[Dictionary]: + var found: Array[Dictionary] = [] + for event: Dictionary in seen: + if event["type"] == type: + found.append(event) + return found + + +# A bare ENet peer, for sending what a real client never would. + +var _raw_state: Dictionary = {} + + +func _raw() -> ENetPacketPeer: + var host: ENetConnection = ENetConnection.new() + assert_eq(host.create_host(1, NetProtocol.CHANNEL_COUNT), OK) + var peer: ENetPacketPeer = host.connect_to_host(HOST, server.port(), NetProtocol.CHANNEL_COUNT) + raw_hosts.append(host) + _raw_state[host] = {"connected": false, "disconnect_data": -1, "packets": []} + assert_true(_pump(func() -> bool: return _raw_state[host]["connected"]), "the raw peer connected") + return peer + + +func _service_raw(host: ENetConnection) -> void: + while true: + var event: Array = host.service(0) + if event[0] == ENetConnection.EVENT_NONE or event[0] == ENetConnection.EVENT_ERROR: + return + var state: Dictionary = _raw_state[host] + if event[0] == ENetConnection.EVENT_CONNECT: + state["connected"] = true + elif event[0] == ENetConnection.EVENT_DISCONNECT: + state["disconnect_data"] = int(event[2]) + elif event[0] == ENetConnection.EVENT_RECEIVE: + state["packets"].append((event[1] as ENetPacketPeer).get_packet()) + + +func test_a_client_joins() -> void: + var client: NetClient = _client(" Mara\tof the Reef ") + assert_eq(client.state, NetClient.CONNECTING) + assert_true(_pump(func() -> bool: return client.state == NetClient.JOINED), client.status_text()) + assert_eq(client.handle, 1) + assert_eq(client.player_name, "Mara of the Reef") + assert_eq(client.match_seed, 4242) + assert_eq(client.max_players, Tuning.SOLO_PLAYERS) + assert_eq(client.tick_rate, Tuning.TICK_RATE_HZ) + assert_eq(client.server_version, NetProtocol.VERSION) + assert_eq(_events("joined"), [{"type": "joined", "handle": 1, "name": "Mara of the Reef"}] as Array[Dictionary]) + assert_eq(server.player_count(), 1) + assert_eq(server.guest_count(), 0) + assert_eq(server.name_of(1), "Mara of the Reef") + assert_eq(client.status_text(), "Joined as Mara of the Reef.") + + +func test_a_version_mismatch_is_refused_clearly() -> void: + var client: NetClient = NetClient.new() + client.protocol_version = NetProtocol.VERSION + 1 + clients.append(client) + assert_eq(client.connect_to(HOST, server.port(), "Mara"), OK) + assert_true(_pump(func() -> bool: return client.state == NetClient.CLOSED), client.state_name()) + assert_eq(client.close_reason, NetProtocol.REASON_VERSION) + assert_eq(client.server_version, NetProtocol.VERSION) + var text: String = client.status_text() + assert_true(text.contains("older version") and text.contains("protocol %d" % NetProtocol.VERSION), text) + assert_eq(server.player_count(), 0) + assert_eq(_events("refused"), [{"type": "refused", "reason": NetProtocol.REASON_VERSION}] as Array[Dictionary]) + assert_true(_events("joined").is_empty()) + + +func test_a_full_server_says_so() -> void: + server.max_players = 2 + var first: NetClient = _client("One") + var second: NetClient = _client("Two") + assert_true(_pump(func() -> bool: return first.state == NetClient.JOINED and second.state == NetClient.JOINED)) + var third: NetClient = _client("Three") + assert_true(_pump(func() -> bool: return third.state == NetClient.CLOSED)) + assert_eq(third.close_reason, NetProtocol.REASON_FULL) + assert_eq(third.status_text(), "The server is full.") + assert_eq(server.player_count(), 2) + # A place opens when someone leaves. + first.leave() + assert_true(_pump(func() -> bool: return server.player_count() == 1)) + var fourth: NetClient = _client("Four") + assert_true(_pump(func() -> bool: return fourth.state == NetClient.JOINED)) + assert_eq(fourth.handle, 3, "handles are never reused") + + +func test_duplicate_names_get_a_number() -> void: + var first: NetClient = _client("Mara") + assert_true(_pump(func() -> bool: return first.state == NetClient.JOINED)) + var second: NetClient = _client("mara") + var third: NetClient = _client("Mara") + assert_true(_pump(func() -> bool: return second.state == NetClient.JOINED and third.state == NetClient.JOINED)) + var names: Array[String] = [first.player_name, second.player_name, third.player_name] + names.sort() + assert_eq(names.size(), 3) + assert_true(names.has("Mara") and (names.has("mara 2") or names.has("Mara 2")), "names %s" % [names]) + assert_ne(second.player_name.to_lower(), third.player_name.to_lower()) + + +func test_a_clean_leave_is_seen_at_once() -> void: + server.peer_timeout_min_msec = 60000 + server.peer_timeout_max_msec = 60000 + var client: NetClient = _client("Mara") + assert_true(_pump(func() -> bool: return client.state == NetClient.JOINED)) + client.leave() + assert_eq(client.state, NetClient.CLOSED) + assert_eq(client.close_reason, NetProtocol.REASON_LEFT) + assert_true(_pump(func() -> bool: return not _events("left").is_empty(), 2000), "the server heard the goodbye, not a timeout") + assert_eq(_events("left"), [{"type": "left", "handle": 1, "name": "Mara", "reason": NetProtocol.REASON_LEFT}] as Array[Dictionary]) + assert_eq(server.player_count(), 0) + + +func test_a_client_that_vanishes_times_out() -> void: + server.close() + server.peer_timeout_min_msec = 300 + server.peer_timeout_max_msec = 600 + assert_eq(server.listen(0, HOST), OK) + var client: NetClient = _client("Mara") + assert_true(_pump(func() -> bool: return client.state == NetClient.JOINED)) + # Pull the plug: no goodbye. + client._drop() + clients.clear() + assert_true(_pump(func() -> bool: return not _events("left").is_empty(), 8000), "the server noticed") + assert_eq(_events("left")[0]["reason"], NetProtocol.REASON_LOST) + assert_eq(server.player_count(), 0) + + +func test_a_silent_guest_is_dropped() -> void: + server.handshake_timeout_msec = 200 + _raw() + var host: ENetConnection = raw_hosts[0] + assert_true(_pump(func() -> bool: return server.guest_count() == 1 or _raw_state[host]["disconnect_data"] >= 0)) + assert_true(_pump(func() -> bool: return _raw_state[host]["disconnect_data"] >= 0), "the guest was disconnected") + assert_eq(_raw_state[host]["disconnect_data"], NetProtocol.REASON_HANDSHAKE_TIMEOUT) + assert_eq(NetProtocol.decode_reject(_raw_state[host]["packets"][0])["reason"], NetProtocol.REASON_HANDSHAKE_TIMEOUT) + assert_eq(server.guest_count(), 0) + assert_eq(server.player_count(), 0) + + +func test_malformed_handshakes_are_refused_and_the_server_carries_on() -> void: + var good: PackedByteArray = NetProtocol.encode_hello("Mara") + var huge: PackedByteArray = PackedByteArray() + huge.resize(60000) + huge.fill(0x41) + var wrong_magic: PackedByteArray = good.duplicate() + wrong_magic[1] = 0x00 + var bad_name: PackedByteArray = good.slice(0, 7) + bad_name.append_array(PackedByteArray([2, 0xC3, 0x28])) + var packets: Array[PackedByteArray] = [ + PackedByteArray([0]), PackedByteArray([NetProtocol.MSG_HELLO]), good.slice(0, 6), wrong_magic, huge, bad_name, + NetProtocol.encode_welcome(1, 1, 24, "Mara"), NetProtocol.encode_reject(NetProtocol.REASON_FULL), + ] + for bytes: PackedByteArray in packets: + var peer: ENetPacketPeer = _raw() + peer.send(NetProtocol.CHANNEL_CONTROL, bytes, ENetPacketPeer.FLAG_RELIABLE) + # A good HELLO on the wrong channel is no handshake either. + var stray: ENetPacketPeer = _raw() + stray.send(NetProtocol.CHANNEL_STATE, good, ENetPacketPeer.FLAG_RELIABLE) + var expected: int = packets.size() + 1 + assert_true(_pump(func() -> bool: return _events("refused").size() >= expected), "refused %d of %d" % [_events("refused").size(), expected]) + for event: Dictionary in _events("refused"): + assert_eq(event["reason"], NetProtocol.REASON_BAD_HELLO) + assert_eq(server.bad_packets, expected) + assert_true(_pump(func() -> bool: + for host: ENetConnection in raw_hosts: + if _raw_state[host]["disconnect_data"] < 0: + return false + return true), "every bad peer was disconnected") + assert_eq(server.guest_count(), 0) + assert_eq(server.player_count(), 0) + # Still serving. + var client: NetClient = _client("Mara") + assert_true(_pump(func() -> bool: return client.state == NetClient.JOINED)) + + +func test_random_packets_from_guests_and_players_never_crash_the_server() -> void: + var rng: RandomNumberGenerator = RandomNumberGenerator.new() + rng.seed = 77 + var member: NetClient = _client("Mara") + assert_true(_pump(func() -> bool: return member.state == NetClient.JOINED)) + for _round: int in 12: + var peer: ENetPacketPeer = _raw() + for _packet: int in 6: + var bytes: PackedByteArray = PackedByteArray() + bytes.resize(rng.randi_range(0, 300)) + for index: int in bytes.size(): + bytes[index] = rng.randi_range(0, 255) + peer.send(rng.randi_range(0, 1), bytes, ENetPacketPeer.FLAG_RELIABLE) + # A player who keeps sending HELLOs and junk stays a player and changes nothing. + for _packet: int in 20: + member._peer.send(NetProtocol.CHANNEL_CONTROL, NetProtocol.encode_hello("Someone Else"), ENetPacketPeer.FLAG_RELIABLE) + member._peer.send(NetProtocol.CHANNEL_STATE, PackedByteArray([1, 2, 3]), ENetPacketPeer.FLAG_RELIABLE) + assert_true(_pump(func() -> bool: return _events("refused").size() >= 12 and server.bad_packets >= 52), "refused %d, dropped %d" % [_events("refused").size(), server.bad_packets]) + assert_eq(server.player_count(), 1) + assert_eq(server.name_of(1), "Mara") + assert_eq(_events("joined").size(), 1) + assert_eq(member.state, NetClient.JOINED) + + +func test_no_server_means_no_answer() -> void: + var port: int = server.port() + server.close() + var client: NetClient = NetClient.new() + client.connect_timeout_msec = 300 + clients.append(client) + assert_eq(client.connect_to(HOST, port, "Mara"), OK) + assert_true(_pump(func() -> bool: return client.state == NetClient.CLOSED, 3000)) + assert_eq(client.close_reason, NetProtocol.REASON_NO_ANSWER) + assert_true(client.status_text().contains("No answer")) + + +func test_a_server_shutting_down_tells_its_players() -> void: + var client: NetClient = _client("Mara") + assert_true(_pump(func() -> bool: return client.state == NetClient.JOINED)) + server.close() + assert_false(server.is_listening()) + assert_eq(server.port(), 0) + assert_true(_pump(func() -> bool: return client.state == NetClient.CLOSED)) + assert_eq(client.close_reason, NetProtocol.REASON_SHUTDOWN) + assert_eq(client.status_text(), "The server shut down.") + + +func test_a_kicked_player_is_told_and_removed() -> void: + var client: NetClient = _client("Mara") + assert_true(_pump(func() -> bool: return client.state == NetClient.JOINED)) + assert_true(server.kick(1)) + assert_eq(server.events[-1], {"type": "left", "handle": 1, "name": "Mara", "reason": NetProtocol.REASON_KICKED}) + assert_false(server.kick(1)) + assert_eq(server.player_count(), 0) + assert_true(_pump(func() -> bool: return client.state == NetClient.CLOSED)) + assert_eq(client.close_reason, NetProtocol.REASON_KICKED) + assert_false(client.send(NetProtocol.CHANNEL_STATE, PackedByteArray([1]), false)) + + +func test_two_servers_cannot_share_a_port() -> void: + var other: NetServer = NetServer.new() + expect_error("Couldn't create an ENet host") + assert_ne(other.listen(server.port(), HOST), OK) + assert_false(other.is_listening()) + assert_true(server.is_listening()) diff --git a/test/net/test_net_handshake.gd.uid b/test/net/test_net_handshake.gd.uid new file mode 100644 index 0000000..492cbb5 --- /dev/null +++ b/test/net/test_net_handshake.gd.uid @@ -0,0 +1 @@ +uid://cnttr6v30diwi diff --git a/test/net/test_net_protocol.gd b/test/net/test_net_protocol.gd new file mode 100644 index 0000000..314bf2e --- /dev/null +++ b/test/net/test_net_protocol.gd @@ -0,0 +1,92 @@ +extends TestCase + +## The handshake's messages (issue N1): they round-trip, and nothing malformed decodes. + + +func test_hello_round_trips() -> void: + var hello: Dictionary = NetProtocol.decode_hello(NetProtocol.encode_hello("Mara")) + assert_eq(hello, {"version": NetProtocol.VERSION, "name": "Mara"}) + assert_eq(NetProtocol.decode_hello(NetProtocol.encode_hello("Ægir Þór", 7)), {"version": 7, "name": "Ægir Þór"}) + + +func test_welcome_and_reject_round_trip() -> void: + var welcome: Dictionary = NetProtocol.decode_welcome(NetProtocol.encode_welcome(70000, 0x7FFFFFFFFFFFFFF1, 24, "Mara 2")) + assert_eq(welcome["handle"], 70000) + assert_eq(welcome["seed"], 0x7FFFFFFFFFFFFFF1) + assert_eq(welcome["max_players"], 24) + assert_eq(welcome["tick_rate"], Tuning.TICK_RATE_HZ) + assert_eq(welcome["name"], "Mara 2") + assert_eq(welcome["version"], NetProtocol.VERSION) + assert_eq(NetProtocol.decode_reject(NetProtocol.encode_reject(NetProtocol.REASON_FULL)), + {"reason": NetProtocol.REASON_FULL, "server_version": NetProtocol.VERSION}) + + +func test_names_are_cleaned() -> void: + assert_eq(NetProtocol.clean_name(" Mara of the\tReef "), "Mara of the Reef") + assert_eq(NetProtocol.clean_name(""), NetProtocol.DEFAULT_NAME) + assert_eq(NetProtocol.clean_name(" \n\t "), NetProtocol.DEFAULT_NAME) + assert_eq(NetProtocol.clean_name("a" + String.chr(1) + "b" + String.chr(0x1B) + "c" + String.chr(0x7F)), "abc", "control characters go") + assert_eq(NetProtocol.clean_name("ab" + String.chr(0x202E) + "cd" + String.chr(0x200B)), "abcd", "direction overrides and zero-width marks go") + assert_eq(NetProtocol.clean_name("x".repeat(40)).length(), NetProtocol.NAME_MAX_CHARS) + assert_true(NetProtocol.clean_name("語".repeat(40)).to_utf8_buffer().size() <= NetProtocol.NAME_MAX_BYTES) + assert_eq(NetProtocol.clean_name("Line\nBreak"), "LineBreak") + + +func test_malformed_hellos_decode_to_nothing() -> void: + var good: PackedByteArray = NetProtocol.encode_hello("Mara") + assert_eq(NetProtocol.decode_hello(PackedByteArray()), {}) + for size: int in good.size(): + assert_eq(NetProtocol.decode_hello(good.slice(0, size)), {}, "cut to %d bytes" % size) + var long: PackedByteArray = good.duplicate() + long.append(0x41) + assert_eq(NetProtocol.decode_hello(long), {}, "bytes after the name") + var wrong_magic: PackedByteArray = good.duplicate() + wrong_magic[2] = 0x58 + assert_eq(NetProtocol.decode_hello(wrong_magic), {}) + var wrong_type: PackedByteArray = good.duplicate() + wrong_type[0] = NetProtocol.MSG_WELCOME + assert_eq(NetProtocol.decode_hello(wrong_type), {}) + var huge: PackedByteArray = good.duplicate() + huge.resize(4000) + assert_eq(NetProtocol.decode_hello(huge), {}) + # Names that aren't UTF-8: a stray continuation byte, a cut sequence, an overlong + # form, a surrogate. None of them may reach the engine's decoder. + for bad: Array in [[0x80], [0xC3], [0xE2, 0x82], [0xC0, 0xAF], [0xE0, 0x80, 0xAF], [0xED, 0xA0, 0x80], [0xF5, 0x80, 0x80, 0x80], [0xFF]]: + var bytes: PackedByteArray = good.slice(0, 7) + bytes.append(bad.size()) + bytes.append_array(PackedByteArray(bad)) + assert_eq(NetProtocol.decode_hello(bytes), {}, "name bytes %s" % [bad]) + + +func test_random_bytes_never_raise_an_error() -> void: + var rng: RandomNumberGenerator = RandomNumberGenerator.new() + rng.seed = 20261112 + var decoded: int = 0 + for _round: int in 4000: + var bytes: PackedByteArray = PackedByteArray() + bytes.resize(rng.randi_range(0, 120)) + for index: int in bytes.size(): + bytes[index] = rng.randi_range(0, 255) + if rng.randf() < 0.5 and bytes.size() >= 8: + # Past the cheap checks: a right type and magic, and often a right length. + bytes[0] = NetProtocol.MSG_HELLO + for index: int in 4: + bytes[1 + index] = NetProtocol.MAGIC.to_ascii_buffer()[index] + if rng.randf() < 0.7: + bytes[7] = mini(bytes.size() - 8, 255) + var hello: Dictionary = NetProtocol.decode_hello(bytes) + if not hello.is_empty(): + decoded += 1 + assert_true(String(hello["name"]).length() >= 1 and String(hello["name"]).length() <= NetProtocol.NAME_MAX_CHARS) + NetProtocol.decode_welcome(bytes) + NetProtocol.decode_reject(bytes) + assert_true(decoded > 0, "some random hellos have valid names, and those decode") + + +func test_a_version_refusal_says_which_side_is_behind() -> void: + var newer: String = NetProtocol.reason_text(NetProtocol.REASON_VERSION, NetProtocol.VERSION + 1) + assert_true(newer.contains("newer version") and newer.contains("Update the game"), newer) + var older: String = NetProtocol.reason_text(NetProtocol.REASON_VERSION, 3, 5) + assert_true(older.contains("older version") and older.contains("protocol 3") and older.contains("speaks 5"), older) + for reason: int in range(NetProtocol.REASON_NONE, NetProtocol.REASON_LOST + 1): + assert_false(NetProtocol.reason_text(reason).is_empty()) diff --git a/test/net/test_net_protocol.gd.uid b/test/net/test_net_protocol.gd.uid new file mode 100644 index 0000000..2cbdf1f --- /dev/null +++ b/test/net/test_net_protocol.gd.uid @@ -0,0 +1 @@ +uid://2aj3limc0m18