N1: Transport and connection handshake

ENet over UDP, used directly through ENetConnection, with a handshake before a
connection counts as a player.

- NetProtocol: HELLO, WELCOME and REJECT layouts, the protocol version, name
  cleaning, the reasons a connection ends and a sentence for the player about
  each. Decoders return nothing for malformed input and never raise an error.
- NetServer: listens, takes each guest through the handshake, and reports
  joined, left and refused. It refuses a different protocol version, a full
  server, a malformed HELLO and a guest that stays silent, each with its own
  reason. Handles are never reused; duplicate names get a number.
- NetClient: connects, introduces itself, and ends up joined or closed with a
  reason. Leaving says goodbye so the server knows at once; a client that
  vanishes is dropped by ENet's timeout.
- Tests run a real server and clients over loopback UDP, with bare ENet peers
  sending malformed and random packets.

The headless server doesn't listen yet; N2 connects this to the match.

Closes #32

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-12 05:51:12 -05:00
co-authored by Claude Opus 5.5
parent 1d6a24ab64
commit 98a1a05dc8
12 changed files with 1009 additions and 0 deletions
View File
+167
View File
@@ -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
+1
View File
@@ -0,0 +1 @@
uid://dib03f4cwugrr
+212
View File
@@ -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()
+1
View File
@@ -0,0 +1 @@
uid://cs25yfo41uida
+208
View File
@@ -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
+1
View File
@@ -0,0 +1 @@
uid://6635d4cj3x0x