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
+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()