A generic network layer for Ace of Spades style games and servers, in C.
- ENet for native UDP players (classic ENet 1.3 or enet6).
- WebRTC DataChannels for browser players (libdatachannel, one UDP port). A browser joins a listed server by
WebRTC direct: it builds the server's answer from the list row (address,
webrtc_port,dtls_fingerprint), so nothing is signalled. - Rooms by join code (Atyha, the
deps/atyhasubmodule): a friend types the match's code (HK4M-7TRW, optionally a password) and joins through public Nostr relays, with no forwarded port and no server of ours in between. Browsers and the desktop client join; the server hosts the room. - The client of a master server, a list only: signed announce,
/serverlist.json.
It carries bytes. It has no game types and no protocol knowledge: the uint32 connect data is opaque (it is
ENet's connect data, or the n of the DataChannel's connect <n> line), the list of masters is passed in by the
program, and nothing is allow-listed. It is written so that third-party servers such as
LSD and SpadesX can use it with a handful of changed lines.
Licence: MIT (until 2026-11-30 it was GPL-3.0-or-later; every line is the project's own, and the one file that carried code moved from the game, src/transport_enet.c, was rewritten). GPL programs (LSD, SpadesX, piqueserver) use it as before.
| Level | For | What you write |
|---|---|---|
ENet shim (ngnet/enet.h) |
a server that already speaks ENet | nothing in the code: compile with -include ngnet/enet.h |
Lua binding (ngnet/lua.h) |
a server with an embedded Lua config | #include <ngnet/lua.h> and one ngnet_lua_open(L) |
Native API (ngnet/ngnet.h) |
a new game or a server that wants full control | ngnet_server_start(port, &events), ngnet_service() every tick |
cc -include ngnet/enet.h $(pkg-config --cflags ngnet) -c server.c
cc server.o ... $(pkg-config --libs ngnet)-include puts macros after ENet's header that redirect enet_host_create, enet_host_destroy,
enet_host_service, enet_host_check_events, enet_host_broadcast, enet_host_flush, enet_host_connect,
enet_peer_send, enet_peer_disconnect, enet_peer_disconnect_now, enet_peer_disconnect_later,
enet_peer_reset, enet_peer_timeout and enet_peer_ping to ngnet_* wrappers with the same signatures. The
program's ENet code is unchanged. What the wrappers add:
- A host created with a bind address is the game server: the library attaches to it. It starts on the
program's first
enet_host_service, so settings made after the host exists (a Lua config) are in time. It opens WebRTC ongame port + 1, announces to the masters (signed), answers the master's UDPHELLOINFOprobe, andenet_host_destroydetaches (browsers getdisconnect, the masters getleave). A host created with aNULLaddress is passed through untouched.ngnet_attach(host)/ngnet_detach(host)do it explicitly. - Each browser player is a real
ENetPeerthe library allocates (outsidehost->peers): stateCONNECTED,address= the browser's real IP (its STUN request, or what ICE found for a room's friend),roundTripTimekept updated,datafree for the program.enet_host_servicereturns itsCONNECT(event.data= the browser's connect data),RECEIVE(a realENetPacket, destroyed withenet_packet_destroy) andDISCONNECTevents like any other peer's.enet_peer_sendto it goes over the DataChannel and frees the packet as ENet would;enet_host_broadcastreaches native and browser peers. A reliable packet goes on the reliable DataChannel, an unreliable one on the unreliable DataChannel.ngnet_peer_is_browser(peer)tells them apart. - Timeouts of
enet_host_serviceare honoured: it waits on ENet's socket and wakes for browser events. - Zero-config announce. A program that announces to a classic 0.75 master (a second host created with a
NULLaddress, connect data31, first reliable packetu8 max_players, u16 port LE, name\0, mode\0, map\0, then single byte player counts) needs nongnet_setat all: the library reads those bytes and uses the name, mode, map, max players and player count for its own signed announce, with protocol0.75. Explicitngnet_setvalues win. - HELLOINFO: the library installs
host->interceptand answers the master's probe with{"kind":"info",...}built from what it knows. A program that installs its own intercept keeps it; it can callngnet_intercept(host, event)first to keep the answer.
ENet header selection: NGNET_ENET_HEADER (default <enet/enet.h>); define NGNET_ENET6 for enet6, whose
enet_host_create takes an address type first.
int ngnet_set(const char* key, const char* value); /* 0 ok, -1 unknown key */| key | default | |
|---|---|---|
off |
1: the library does nothing |
|
webrtc |
shim: off; native API: 1 |
the shim's opt-in: without webrtc=1 a program built with -include ngnet/enet.h is plain ENet (no thread, no socket, no announce, no intercept). 0: no browsers (no WebRTC port, no offers); the server still announces and answers HELLOINFO |
ipv6 |
0 |
1: WebRTC direct joins from IPv6 addresses are taken and the announce goes over IPv6 too. Default IPv4 only: an IPv6 direct join is refused ("this server takes IPv4 players only"); a room's friend comes over whatever path ICE found. With a classic (IPv4) ENet an IPv6 browser's peer->address is 0.0.0.0, so leave it off there |
webrtc_port |
game port + 1 | UDP port of every browser |
master |
https://master.shootanddestroy.obex.pw |
a master URL; repeatable (several masters at once); the first call replaces the default; - or empty: none |
stun |
stun:stun.l.google.com:19302 |
comma separated |
turn, turn_username, turn_credential |
TURN relays for players behind symmetric NATs | |
name, map, mode |
from the classic announce, else ngnet server |
clipped to 64, 32, 16 bytes on a UTF-8 boundary (the master refuses longer) |
protocol |
0.75 after a classic announce, else the master's default |
any [0-9A-Za-z._-]{1,16} |
max_players |
from the classic announce, else 32 | |
country |
the master finds it from the address when absent | |
key_file |
empty: in memory | the Ed25519 identity on the master. Empty: a new key at every start (a new row id; the old row drops off within 90 s). A path: read from it, or made once and written there (kept in memory if it cannot be written) |
cert_file |
empty: in memory | the DTLS certificate WebRTC needs. Empty: made at every start. A path: read from it, or made once and written there |
join_code |
opens the match's room (Atyha) on public relays: friends join by this code, no forwarded port. Eight symbols of ABCDEFHJKMNPRTUVWXYZ34579, any pasted form (hk4m 7trw, ngspades://HK4M-7TRW); p2p_code_generate() makes one. Never sent to the master |
|
join_password |
the room's password (NGNET_JOIN_PASSWORD); empty: the code alone |
|
room_app |
ngspades |
Atyha's application id of the room |
relays |
Atyha's list | the room's relays, wss:// URLs separated by spaces |
unlisted |
1: never announced to a master |
|
bind |
any | local address for ICE (multi-homed hosts, tests) |
The environment variable NGNET_<KEY> (upper case) overrides ngnet_set; NGNET_MASTER is a list separated by
spaces or commas. ngnet_set_info() updates name, map, mode, protocol, player counts and the HELLOINFO JSON at
runtime.
Lua (5.1 to 5.4, LuaJIT), header only, compiled against the program's own Lua headers:
#include <ngnet/lua.h>
ngnet_lua_open(L); /* registers ngnet_set(key, value) and ngnet_get(key) */ngnet_set("master", "https://master.example.org")
ngnet_set("name", "My server")#include <ngnet/ngnet.h>
static void on_connect(void* user, conn_t* conn, uint32_t connect_data) { conn->owner = my_player_for(conn); }
static void on_receive(void* user, conn_t* conn, uint8_t channel, const uint8_t* data, size_t len) { ... }
static void on_closed(void* user, conn_t* conn) { ... }
ngnet_set("name", "My server");
ngnet_server_events_t ev = { .user = game, .connect = on_connect, .receive = on_receive, .closed = on_closed };
ngnet_server_start(32887, &ev);
for (;;) { ngnet_service(); /* ... the tick ... */ }
ngnet_server_stop();conn_send(conn, channel, data, len, reliable), conn_disconnect(conn, reason, how), conn_rtt, conn_pending
are in ngnet/conn.h. Everything runs on the caller's thread: HTTP (libcurl) and libdatachannel use threads
of their own and only queue; their results are delivered as callbacks from ngnet_service().
With join_code set the server also opens its room: ngnet_room_state() (NGNET_ROOM_OFF, _OPENING, _OPEN),
ngnet_join_code(), and the log line Room HK4M7TRW open: friends join by its code HK4M-7TRW (INFO). The
offer event decides who may join (bans, full): see docs/master.md.
ngnet/transport.h is the client's one connection to a server: transport_connect (ENet),
transport_connect_endpoint (WebRTC), transport_service, transport_send, transport_disconnect, ...
/* a friend's room (browser and desktop) */
transport_connect_endpoint(&(ngnet_endpoint_t){.join_code = "hk4m 7trw", .password = pw}, 2, connect_data);
/* a listed server by WebRTC direct (browser only) */
transport_connect_endpoint(&(ngnet_endpoint_t){.address = "203.0.113.5", .webrtc_port = row.webrtc_port,
.fingerprint = row.dtls_fingerprint}, 2, connect_data);ngnet_endpoint_t also has app (default ngspades), relays, ice_json / stun (ICE when a room's host sends
none) and bind_address. The desktop WebRTC transport is libdatachannel's C API with Atyha's joiner on its worker
thread; it cannot do WebRTC direct (the C API cannot set its own ICE credentials) and answers
NGNET_ERR_BAD_ENDPOINT. The browser one is src/transport_web.c with web/ngnet_web.js and Atyha's browser
bundle web/atyha.global.js (npm atyha@0.2.0, the global Atyha): link with
--js-library web/ngnet_web.js --pre-js web/atyha.global.js, or load atyha.global.js with a <script> before
the program. Errors are codes (transport_error_code(): a room adds NGNET_ERR_WRONG_PASSWORD,
NGNET_ERR_NO_RELAY, NGNET_ERR_CODE_NOT_FOUND, NGNET_ERR_SERVER_REFUSED with the host's words) with an English
default text (transport_error()), and an optional ngnet_set_tr() hook translates them.
ngnet/masterlist.h reads /serverlist.json from the masters the program names, each row remembering which
master listed it; ngnet_list_parse needs no network (a browser feeds it its own fetch).
git submodule update --init # deps/atyha
make # build/libngnet.a (+ libdatachannel and libsecp256k1, fetched the first time)
make install PREFIX=/usr/local
make test # ctestor CMake directly:
cmake -S . -B build && cmake --build build && ctest --test-dir buildOptions: NGNET_WEBRTC (libdatachannel, Atyha), NGNET_MASTER (libcurl, OpenSSL), NGNET_SHIM, NGNET_CLIENT,
NGNET_TESTS, NGNET_ENET_HEADER (enet/enet.h or enet6/enet.h; with NGNET_ENET_INCLUDE_DIR and
NGNET_ENET_LIBRARY when ENet is not found by pkg-config), NGNET_FETCH_LIBDATACHANNEL.
libdatachannel is found with find_package(LibDataChannel), otherwise fetched (v0.24.6, as the game server
does) with its WebSocket client on (NO_WEBSOCKET OFF: Atyha's relays; an installed libdatachannel must have it
too); offline builds set FETCHCONTENT_SOURCE_DIR_LIBDATACHANNEL to a checkout with its submodules. With
NGNET_WEBRTC (the default) Atyha's C library is built from deps/atyha/c (git submodule update --init); it needs
libsodium (brew install libsodium, apt install libsodium-dev, or -DSODIUM_ROOT=...) and fetches
bitcoin-core/libsecp256k1 v0.8.0. A build with NGNET_WEBRTC=OFF, and the Emscripten (browser) build of
ngnet.cmake, need neither. Needs OpenSSL (Ed25519, DTLS certificate, the relays' TLS), libcurl, a C11 and a C++17
compiler (libdatachannel's face is C++), POSIX threads and sockets (Linux, macOS; not Windows yet).
A project that compiles sources itself includes ngnet.cmake and uses NGNET_SOURCES, NGNET_INCLUDE_DIR,
NGNET_DEFINITIONS, NGNET_LIBRARIES (and NGNET_BROWSER_JS, NGNET_BROWSER_ATYHA_JS for Emscripten). A POSIX
make project links -lngnet -latyha_libdatachannel -latyha -lsecp256k1 -ldatachannel -ljuice -lusrsctp -lstdc++ -lsodium -lcurl -lcrypto -lpthread (pkg-config --libs ngnet gives it; make install installs Atyha's archives
next to libngnet.a).
If the master runs with -keys (an allow list of server keys), the key must be listed, so set a key_file (a key in memory changes at every start). The key is
printed in the log at start (Announcing to ... (key <base64>)); ngnet_public_key() returns it. Keep
ngnet.key between restarts: it is the server's identity on the list. Locally, the master refuses private
addresses unless it runs with MASTER_ALLOW_PRIVATE_IPS=1.
LSD (pyspades derived, POSIX Makefile, Lua config) gets browser players and a signed listing with:
--- a/Makefile
+++ b/Makefile
-PKGCONF_MODULES=luajit libenet libisal
+PKGCONF_MODULES=luajit libenet libisal ngnet
...
-CPPFLAGS=`pkg-config --cflags $(PKGCONF_MODULES)` $(OPTS)
+CPPFLAGS=`pkg-config --cflags $(PKGCONF_MODULES)` -include ngnet/enet.h $(OPTS)(LIBS already takes pkg-config --libs $(PKGCONF_MODULES), which brings Atyha, libsecp256k1 and libsodium
along; without pkg-config: LDLIBS += -lngnet -latyha_libdatachannel -latyha -lsecp256k1 -ldatachannel -ljuice -lusrsctp -lstdc++ -lcurl -lsodium -lcrypto, and CFLAGS += -include ngnet/enet.h.)
--- a/src/lua.c
+++ b/src/lua.c
#include <lualib.h>
+#include <ngnet/lua.h>
...
luaL_openlibs(l);
+ ngnet_lua_open(l);The shim does nothing until the operator opts in, in config.lua:
ngnet_set("webrtc", "1") -- the opt-in: browsers, signed announce
ngnet_set("master", "https://master.shootanddestroy.obex.pw")
ngnet_set("webrtc_port", 32888)or with no file change at all: NGNET_WEBRTC=1 ./server. Everything else is the environment's too, so the
program's code never changes: browsers join the listed server by WebRTC direct as soon as WebRTC is on, and a
match joined by a room code (no port forwarded) is NGNET_WEBRTC=1 NGNET_JOIN_CODE=HK4M-7TRW NGNET_JOIN_PASSWORD=123 ./server (NGNET_UNLISTED=1 keeps it off the master's list, NGNET_RELAYS picks the
relays). Every ngnet_set key has its NGNET_<KEY> variable. Without it the server runs as before (one thread, its own
sockets, its classic announce only). Then: its enet_host_create(addr, ...) becomes the attached game host, its masterlist host (created with
NULL) is sniffed for the name, mode, map and player count, its peer->data, peer->address,
peer->roundTripTime, enet_peer_send, enet_host_broadcast, enet_peer_disconnect(_now) and
enet_peer_reset calls work on browser peers as on UDP ones. LSD installs its own host->intercept (it answers
HELLO and HELLOLAN), so it keeps it; to answer the master's HELLOINFO probe as well, end its intercept with
return ngnet_intercept(host, event); (the master falls back to probing over ENet when HELLOINFO is not
answered). The whole of LSD was built against the shim and
run on macOS with a local master: idle without the opt-in, and with NGNET_WEBRTC=1 a real WebRTC client joined
with connect data 3 and received the map. LSD's Linux sandbox (seccomp without clone/pipe, pivot_root
without /etc/ssl) kills the process once the library starts threads: an opted-in LSD on Linux has to be built with
-DWITHOUT_SECCOMP -DWITHOUT_UNSHARE until its sandbox allows them.
- The manual: https://ngspades.github.io/ngnet/ (HTML and PDF), made from this file and
docs/bymanual/(make -C manual site pdf;make -C manual publishpushes it to thegh-pagesbranch). docs/wire.md: the DataChannel wire (labels, control lines, limits).docs/master.md: how the library uses the master's API.docs/porting.md: old server and client symbols to the new ones.
include/ngnet/ ngnet.h (server API, configuration) enet.h (shim) lua.h conn.h host.h (log/event hooks)
transport.h (client) masterlist.h p2p.h (join codes)
src/ the library; internal.h is private
web/ngnet_web.js the browser transport (Emscripten --js-library)
web/atyha.global.js Atyha's browser bundle (npm atyha@0.2.0, MIT): the global Atyha (--pre-js)
deps/atyha/ Atyha (submodule): rooms by join code, its C library in c/
tests/ ctest suite (docs in tests/CMakeLists.txt)
ctest runs: test_core (configuration and environment, JSON, the signed envelope verified with OpenSSL, the
classic announce parser, the list reader, the join code rule against Atyha's own reader), test_shim (the shim,
compiled with -include ngnet/enet.h, with a native ENet client and simulated browsers), test_hello (HELLOINFO
intercept and the zero-config sniffer), test_lua, test_room (a server's room joined by the desktop client
through Atyha's in-memory hub, real WebRTC: right and wrong password, a refusal, a code nobody hosts),
test_direct (a libdatachannel peer doing what a browser's WebRTC direct join does: no signalling, a refusal, a
wrong fingerprint), test_room_live (test_room over the public Nostr relays; skipped unless
NGNET_LIVE_RELAYS=1) and, when the master server is available (NGNET_MASTER_BIN, a built binary, or
NGNET_MASTER_DIR, its checkout and Go), test_e2e (a real master, real signed announces, the row's
webrtc_port and dtls_fingerprint, unlisted) and test_e2e_shim (the zero-config shim listed, and a friend
joining its room). They bind ICE to 127.0.0.1 (bind), so they work without a LAN.