## 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] = [] ## Game packets from joined players during the last poll(), in arrival order: ## {"handle", "bytes"}. Whoever owns the server decodes them. var packets: Array[Dictionary] = [] ## The most game packets kept from one player in one poll(); the rest are dropped. var max_packets_per_poll: int = 32 ## Malformed or unexpected packets dropped so far. var bad_packets: int = 0 ## New connections allowed from one address per window. Generous enough for a LAN ## party behind one router joining at once; a flood from one address is turned away. var connect_limiter: SourceLimiter = SourceLimiter.new(32, 10000, 4096) ## Connections from one address still in the handshake at once. var max_guests_per_address: int = 8 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 ## Handle -> game packets kept from them during this poll(). var _packets_from: Dictionary = {} ## 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() packets.clear() _packets_from.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(NetProtocol.PEER_TIMEOUT_LIMIT, peer_timeout_min_msec, peer_timeout_max_msec) var address: String = peer.get_remote_address() if not connect_limiter.allow(address, now) or _guests_from(address) >= max_guests_per_address: _refuse(peer, NetProtocol.REASON_BUSY) continue _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 goes to the owner. A second HELLO, anything on the control # channel, and a flood are dropped. var handle: int = _handle_of[peer] var count: int = int(_packets_from.get(handle, 0)) if channel != NetProtocol.CHANNEL_STATE or bytes.is_empty() or count >= max_packets_per_poll: bad_packets += 1 return _packets_from[handle] = count + 1 packets.append({"handle": handle, "bytes": bytes}) 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) func _guests_from(address: String) -> int: var count: int = 0 for peer: ENetPacketPeer in _guests: if peer.get_remote_address() == address: count += 1 return count ## `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