diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 51072ff..e5ce877 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,7 +37,7 @@ jobs: sudo apt-get update sudo apt-get install -y --no-install-recommends build-essential cmake pkg-config \ libjson-c-dev libssl-dev libcurl4-openssl-dev zlib1g-dev libreadline-dev \ - liblua5.4-dev + liblua5.4-dev libsodium-dev - name: Cache the fetched dependencies (libdatachannel) uses: actions/cache@v4 @@ -85,7 +85,7 @@ jobs: submodules: recursive - name: Dependencies - run: brew install json-c openssl@3 lua pkg-config + run: brew install json-c openssl@3 lua pkg-config libsodium - name: Build (Release, -Werror) run: make server diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4d5202f..d1f5d0c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -169,6 +169,7 @@ jobs: mingw-w64-ucrt-x86_64-gcc mingw-w64-ucrt-x86_64-cmake mingw-w64-ucrt-x86_64-pkgconf mingw-w64-ucrt-x86_64-json-c mingw-w64-ucrt-x86_64-readline mingw-w64-ucrt-x86_64-lua54 mingw-w64-ucrt-x86_64-curl mingw-w64-ucrt-x86_64-openssl mingw-w64-ucrt-x86_64-zlib + mingw-w64-ucrt-x86_64-libsodium - name: Build the static server run: | diff --git a/.gitmodules b/.gitmodules index 8b0cbc1..687106c 100644 --- a/.gitmodules +++ b/.gitmodules @@ -8,3 +8,6 @@ [submodule "server/Extern/tomlc99/tomlc99"] path = server/Extern/tomlc99/tomlc99 url = https://github.com/cktan/tomlc99 +[submodule "common/atyha"] + path = common/atyha + url = https://github.com/ngspades/atyha diff --git a/common/atyha b/common/atyha new file mode 160000 index 0000000..c96b71d --- /dev/null +++ b/common/atyha @@ -0,0 +1 @@ +Subproject commit c96b71da0385cce2718938ff681bc4d023f60a55 diff --git a/netlib/include/ngnet/p2p.h b/netlib/include/ngnet/p2p.h index 7c4328d..8f7ad50 100644 --- a/netlib/include/ngnet/p2p.h +++ b/netlib/include/ngnet/p2p.h @@ -3,16 +3,16 @@ #include -/* the join code's contract is the master's README ("join codes"): six - unambiguous letters and digits, `XXX - XXX` to read out */ +/* the join code's contract is atyha's spec (atyha-v1.md section 3): eight + unambiguous letters and digits, `XXXX - XXXX` to read out */ -/* 1 when the read takes the code (pasted alone or "XXX-XXX"), "" when not +/* 1 when the read takes the code (pasted alone or "XXXX-XXXX"), "" when not out when it is not one */ int p2p_code_norm(const char* pasted, char* out, size_t size_out); /* any text that begins a code: the server list's address box may take the friend's message's code as it is */ int p2p_code_loose(const char* pasted, char* out, size_t size_out); -/* as a friend reads it out over the phone: `XXX - XXX` */ +/* as a friend reads it out over the phone: `XXXX - XXXX` */ void p2p_code_display(const char* code, char* out, size_t size_out); /* a fresh code for this match, handed to the started server (--join-code) */ diff --git a/netlib/include/ngnet/transport.h b/netlib/include/ngnet/transport.h index 7e0d3de..03f96c5 100644 --- a/netlib/include/ngnet/transport.h +++ b/netlib/include/ngnet/transport.h @@ -128,8 +128,18 @@ extern const struct transport_impl transport_web_rtc_impl; extern const struct transport_impl transport_rtc_native_impl; extern const struct transport_impl transport_worker_impl; -/* does this build carry the join code at all (a desktop with WebRTC) */ +/* does this build carry the join code at all (a desktop with WebRTC, or + the browser) */ int transport_has_code_join(void); +/* the room's password for the next join by code ("" none: most rooms have + none). Kept until changed */ +void transport_set_code_password(const char* password); +const char* transport_code_password(void); +/* the last join by code failed on its password (wrong, or none given to + a room that has one): the player is asked for it. Set by the code + transports, cleared at every connect */ +int transport_code_wrong_password(void); +void transport_code_mark_wrong_password(void); /* how long a native connect waits for its CONNECT event (the join by code's signalling, ICE and DTLS take seconds longer than ENet's look) */ float transport_connect_wait(void); diff --git a/netlib/src/p2p.c b/netlib/src/p2p.c index 08811a8..a694899 100644 --- a/netlib/src/p2p.c +++ b/netlib/src/p2p.c @@ -19,10 +19,11 @@ /* The match's join code, the way a player runs its own multiplayer for its friends with no port to forward: the host shows it, - a friend types or pastes it and the join finds the host's machine. The - code is six letters and digits, shown as `XXX - XXX`, and its letters - and digits are only the ones nobody misreads: no I, L, O, Q, 0 or 1 - (the rest of it the master refuses). Everything a player may read of + a friend types or pastes it and the join finds the host's machine + through public relays (Atyha, github.com/ngspades/atyha: its + spec/atyha-v1.md section 3 is the rule here). The code is eight + letters and digits, shown as `XXXX - XXXX`, and its letters and digits + are only the ones nobody misreads: no I, L, O, Q, G, S, 0, 1, 2, 6 or 8. Everything a player may read of it goes through the game's own language texts, never as a technical word */ @@ -48,38 +49,57 @@ #include "ngnet/p2p.h" enum { - /* the code's length and the separators: XXX-XXX, spaces to spare */ - P2P_CODE_LENGTH = 6, - P2P_HALF = 3, + /* the code's length and the separators: XXXX-XXXX, spaces to spare */ + P2P_CODE_LENGTH = 8, + P2P_HALF = 4, }; /* what a code may hold, as the pasted one reads: every message may be either hand */ +static const char p2p_alphabet[] = "ABCDEFHJKMNPRTUVWXYZ34579"; + static int p2p_code_char(char c) { c = (char)(c >= 'a' && c <= 'z' ? c - 32 : c); - if((c >= 'A' && c <= 'Z') && c != 'I' && c != 'L' && c != 'O' && c != 'Q') - return 1; - if(c >= '2' && c <= '9') - return 1; - return 0; + return c != 0 && strchr(p2p_alphabet, c) != NULL; +} + +/* "ngspades://" at c, in any case: a room link (the desktop builds + register the scheme) */ +static int p2p_link_scheme(const char* c) { + static const char scheme[] = "ngspades://"; + for(size_t k = 0; k < sizeof(scheme) - 1; k++) { + char ch = (char)(c[k] >= 'A' && c[k] <= 'Z' ? c[k] + 32 : c[k]); + if(ch != scheme[k]) + return 0; + } + return 1; +} + +static int p2p_space(char c) { + return c == ' ' || c == '\t' || c == '\r' || c == '\n'; } -/* the master's rule (its README): "ABC-DEF", "ABC DEF", "ABCDEF" and - "abc-def" are the same code; 0 when it is not one */ +/* atyha's rule: "ABCD-EFHJ", "ABCD EFHJ", "ABCDEFHJ" and "abcd-efhj" + are the same code; 0 when it is not one */ int p2p_code_norm(const char* pasted, char* out, size_t size_out) { if(out == NULL || size_out < P2P_CODE_LENGTH + 1 || pasted == NULL) return 0; size_t n = 0; - for(const char* c = pasted; *c && n < size_out - 1; c++) { + const char* end = pasted + strlen(pasted); + while(p2p_space(*pasted)) + pasted++; + while(end > pasted && p2p_space(end[-1])) + end--; + for(const char* c = pasted; c < end && n < size_out - 1; c++) { /* a code may be told apart even in whatever message a friend - sent: the separators and the scheme that came with a - shortcut are out */ - if(*c == '-' || *c == ' ' || *c == '\t') + sent: the separators and a link's ngspades:// are out + (a trailing slash too: a browser may add one) */ + if(*c == '-' || *c == ' ' || *c == '\t' || *c == '/') continue; /* strncmp, not memcmp: it stops at the text's end, and a pasted text shorter than the scheme was read past its NUL */ - if(!strncmp(c, "sadcode://", 10)) { - c += 9; + if(p2p_link_scheme(c)) { + c += 10; continue; } if(!p2p_code_char(*c)) @@ -99,7 +119,7 @@ int p2p_code_loose(const char* pasted, char* out, size_t size_out) { return p2p_code_norm(pasted, out, size_out); } -/* draws it as a friend reads it out on the phone: `XXX - XXX`, +/* draws it as a friend reads it out on the phone: `XXXX - XXXX`, space-hyphen-space in the middle */ void p2p_code_display(const char* code, char* out, size_t size_out) { if(code == NULL || strlen(code) != P2P_CODE_LENGTH) { @@ -107,7 +127,7 @@ void p2p_code_display(const char* code, char* out, size_t size_out) { out[0] = 0; return; } - snprintf(out, size_out, "%c%c%c - %c%c%c", code[0], code[1], code[2], code[3], code[4], code[5]); + snprintf(out, size_out, "%.4s - %.4s", code, code + 4); } /* the client picks the code and hands it over with the server (its @@ -142,11 +162,10 @@ static int p2p_os_random(unsigned char* buf, size_t n) { } const char* p2p_code_generate(void) { - /* exactly the master's own clear letters and digits, and one step - stricter (no G, S, 2, 6, 8): always checked below, so a character - the master would refuse can never reach the wire */ - static const char alphabet[] = "ABCDEFHJKMNPRTUVWXYZ34579"; - enum { ALPHABET = sizeof(alphabet) - 1 }; + /* atyha's alphabet: always checked below, so a character the + other side would refuse can never be shown */ + static const char* alphabet = p2p_alphabet; + enum { ALPHABET = sizeof(p2p_alphabet) - 1 }; /* a byte at or over the largest multiple of the alphabet is thrown away: taken modulo, the first letters would come up more often */ enum { BYTE_LIMIT = 256 - 256 % ALPHABET }; diff --git a/server/CMakeLists.txt b/server/CMakeLists.txt index bfc639d..8cac039 100644 --- a/server/CMakeLists.txt +++ b/server/CMakeLists.txt @@ -103,6 +103,13 @@ if(NOT SERVER_WEB_HOST) # and LTO below, which would apply to its C++ too. Offline builds (Flatpak) # point FETCHCONTENT_SOURCE_DIR_LIBDATACHANNEL at a checkout with submodules. include(cmake/libdatachannel.cmake) +# Atyha (common/atyha, a submodule of github.com/ngspades/atyha, MIT; its C +# library is c/): the match's room on public Nostr relays +# (Net/Room.c), its WebSocket libdatachannel's own. Needs libsodium. +set(ATYHA_TESTS OFF CACHE BOOL "" FORCE) +set(ATYHA_CURL OFF CACHE BOOL "" FORCE) +set(ATYHA_WITH_LIBDATACHANNEL ON CACHE BOOL "" FORCE) +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../common/atyha/c ${CMAKE_BINARY_DIR}/atyha) endif() # NOT SERVER_WEB_HOST set(CMAKE_EXPORT_COMPILE_COMMANDS ON) @@ -163,7 +170,7 @@ include_directories(${CURL_INCLUDE_DIRS}) set(SERVER_JSONC_LIBS json-c) set(SERVER_READLINE_LIBS readline) -set(SERVER_NET_LIBS datachannel OpenSSL::Crypto) +set(SERVER_NET_LIBS datachannel OpenSSL::Crypto atyha_libdatachannel) endif() # a static library does not bring its own dependencies: pkg-config's static # lists name them (libcurl's TLS, compression and IDN libraries, readline's diff --git a/server/Source/CMakeLists.txt b/server/Source/CMakeLists.txt index b7d9724..987cd66 100755 --- a/server/Source/CMakeLists.txt +++ b/server/Source/CMakeLists.txt @@ -5,6 +5,12 @@ set(SPADESX_SOURCES Main.c ) +# netlib's join code (p2p.c, with its log hook host.c): --join-code is read +# by its rule. Not on the Switch, whose game already links them (it links +# this server in as a library) +if(NOT SERVER_SWITCH_HOST) + list(APPEND SPADESX_SOURCES ${NGNET_COMMON_SOURCES}) +endif() target_sources(SpadesX PRIVATE diff --git a/server/Source/Main.c b/server/Source/Main.c index ca236d8..3ef5d01 100644 --- a/server/Source/Main.c +++ b/server/Source/Main.c @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -821,23 +822,18 @@ int main(int argc, char** argv) } } if (join_code_arg != NULL) { - /* the player's paste: separators and the case out */ - char out[sizeof(get_server()->join_code)]; - size_t n = 0; - for (const char* c = join_code_arg; *c && n + 1 < sizeof(out); c++) { - if (*c == '-' || *c == ' ') { - continue; - } - out[n++] = (char) (*c >= 'a' && *c <= 'z' ? *c - 32 : *c); - } - out[n] = '\0'; - if (n == 6) { + /* the player's paste, read by atyha's rule (netlib's p2p.c): + eight letters and digits nobody misreads */ + char out[sizeof(get_server()->join_code)]; + if (p2p_code_norm(join_code_arg, out, sizeof out)) { snprintf(get_server()->join_code, sizeof(get_server()->join_code), "%s", out); /* the host sees in the log what its friends will type (and a - test reads it without the master) */ - LOG_STATUS("Join code: %c%c%c-%c%c%c", out[0], out[1], out[2], out[3], out[4], out[5]); + test reads it) */ + char shown[16]; + p2p_code_display(out, shown, sizeof shown); + LOG_STATUS("Join code: %s", shown); } else { - LOG_WARNING("--join-code %s: a code is six letters and digits (like ABC-DEF)", join_code_arg); + LOG_WARNING("--join-code %s: a code is eight letters and digits (like HK4M-7TRW)", join_code_arg); } } diff --git a/server/Source/Server/CMakeLists.txt b/server/Source/Server/CMakeLists.txt index ad51205..d18203a 100755 --- a/server/Source/Server/CMakeLists.txt +++ b/server/Source/Server/CMakeLists.txt @@ -247,6 +247,7 @@ set(SERVER_SOURCES Net/Conn.c Net/EnetConn.c Net/WebRtc.c + Net/Room.c Net/RtcPeer.cpp Net/Master.c Plugins.c @@ -267,6 +268,7 @@ if(SERVER_WEB_HOST) list(REMOVE_ITEM SERVER_SOURCES Net/EnetConn.c Net/WebRtc.c + Net/Room.c Net/RtcPeer.cpp Net/Master.c Ping.c diff --git a/server/Source/Server/Net/Master.c b/server/Source/Server/Net/Master.c index 0322c76..0b17661 100644 --- a/server/Source/Server/Net/Master.c +++ b/server/Source/Server/Net/Master.c @@ -30,10 +30,6 @@ #define MASTER_PERIOD_NS (30ULL * NANO_IN_SECOND) /* a change (a player in or out) is announced, at most this often */ #define MASTER_CHANGE_NS (5ULL * NANO_IN_SECOND) -/* a failed poll waits before the next: a master that is down is not - hammered 60 times a second */ -#define MASTER_RETRY_NS (5ULL * NANO_IN_SECOND) -#define MASTER_POLL_TIMEOUT_S 40 /* the master holds a poll up to 25 s */ #define MASTER_075_MAX_PLAYERS 32 /* the 0.75 profile's row, as the public 0.75 list */ static struct @@ -54,9 +50,6 @@ static struct char last_error[96]; char state[256]; /* what its last announce said, to see a change */ } family[2]; /* IPv4, IPv6 */ - uint32_t poll_call; - int poll_family; - uint64_t poll_after; /* connect tokens (master_token_*): 0 off, 1 from the internet, 2 from local addresses too (SP_CONNECT_TOKENS=all, tests on one machine) */ int tokens; @@ -217,19 +210,8 @@ static void _announce(server_t* server, int f) json_object_object_add(b, "ice_servers", list); } json_object_object_add(b, "info", ping_info(server)); - /* a listen server whose host ticked "friends join by code" - (--join-code): the master maps the code to this server and every - player that asks for it is relayed here (its row off the public - list unless --public asked). A 0.75 profile server joins the - ENet way and never uncovers the code */ - if (server->join_code[0] && !profile_is_075()) { - json_object_object_add(b, "join_code", json_object_new_string(server->join_code)); - if (server->listen_private) { - json_object_object_add(b, "unlisted", json_object_new_boolean(1)); - } - evt_log(NULL, "master", "action=announce join_code=%s unlisted=%d", server->join_code, - (int) server->listen_private); - } + /* the join code is never told to the master: friends find the match + through its room on the public relays (Net/Room.c) */ master.family[f].call = _post(NET_LANE_MASTER, "/v1/announce", b, f == 0 ? 4 : 6, 10); master.family[f].sent = get_real_nanos(); json_object_put(b); @@ -318,60 +300,6 @@ static void _on_announced(int f, const plugin_net_result_t* r) evt_log(NULL, "master", "action=error call=announce family=%d why=\"%s\"", fam, why); } -/* ---- offers ---- */ - -static void _on_poll(const plugin_net_result_t* r) -{ - master.poll_call = 0; - if (r->status != 200) { - char why[96]; - _why(r, why, sizeof why); - evt_log(NULL, "master", "action=error call=poll family=%d why=\"%s\"", master.poll_family, why); - master.poll_after = get_real_nanos() + MASTER_RETRY_NS; - return; - } - json_object* j = r->body != NULL ? json_tokener_parse(r->body) : NULL; - json_object* offers = NULL; - if (j != NULL && json_object_object_get_ex(j, "offers", &offers) && json_object_is_type(offers, json_type_array)) - { - for (size_t k = 0; k < json_object_array_length(offers); k++) { - json_object *o = json_object_array_get_idx(offers, k), *id = NULL, *sdp = NULL, *ip = NULL; - if (json_object_object_get_ex(o, "id", &id) && json_object_object_get_ex(o, "sdp", &sdp)) { - json_object_object_get_ex(o, "ip", &ip); - webrtc_offer(master.server, json_object_get_string(id), json_object_get_string(sdp), - ip != NULL ? json_object_get_string(ip) : ""); - } - } - } - json_object_put(j); -} - -static void _offer_call(const char* offer_id, const char* type, const char* key, const char* value) -{ - if (!master.on) { - return; - } - json_object* b = json_object_new_object(); - json_object_object_add(b, "type", json_object_new_string(type)); - json_object_object_add(b, "offer", json_object_new_string(offer_id)); - json_object_object_add(b, key, json_object_new_string(value)); - /* over the family the offer came by: the master knows this server by it */ - if (_post(NET_LANE_MASTER_ANSWER, "/v1/answer", b, master.poll_family, 8) == 0) { - evt_log(NULL, "master", "action=error call=%s why=queue_full", type); - } - json_object_put(b); -} - -void master_answer(const char* offer_id, const char* sdp) -{ - _offer_call(offer_id, "answer", "sdp", sdp); -} - -void master_reject(const char* offer_id, const char* reason) -{ - _offer_call(offer_id, "reject", "reason", reason); -} - /* ---- lifecycle ---- */ void master_start(server_t* server) @@ -441,13 +369,9 @@ void master_start(server_t* server) /* a listen server (a player's own match with its bots, started from the menu) stays off the public list unless its host asked for it (--public): every singleplayer match was listed, and anyone could - join it. One with a join code still announces: the code, not the - list, is where its players find it */ - if (server->join_code[0] && profile_is_075()) { - LOG_WARNING("master: the join code is the 1.0 profile's (a 0.75 profile join needs a forwarded port)"); - return; - } - if (server->listen_private && !server->join_code[0]) { + join it. A join code changes nothing here: its friends come through + the match's room (Net/Room.c), not the master */ + if (server->listen_private) { LOG_INFO("master: not listed (a listen server; --public lists it)"); return; } @@ -500,20 +424,6 @@ void master_tick(server_t* server) } free(r.body); } - while (net_done(NET_LANE_MASTER_POLL, &r)) { - if (r.id == master.poll_call) { - _on_poll(&r); - } - free(r.body); - } - while (net_done(NET_LANE_MASTER_ANSWER, &r)) { - if (r.status != 200) { - char why[96]; - _why(&r, why, sizeof why); - evt_log(NULL, "master", "action=error call=answer why=\"%s\"", why); - } - free(r.body); - } if (server->map_name[0] == '\0') { return; /* between maps */ } @@ -532,20 +442,6 @@ void master_tick(server_t* server) snprintf(master.family[f].state, sizeof master.family[f].state, "%s", state); } } - - /* one poll waiting, over a family the master lists */ - if (webrtc_port() != 0 && master.poll_call == 0 && now >= master.poll_after && - (master.family[0].listed || master.family[1].listed)) - { - master.poll_family = master.family[0].listed ? 4 : 6; - json_object* b = json_object_new_object(); - json_object_object_add(b, "type", json_object_new_string("poll")); - master.poll_call = _post(NET_LANE_MASTER_POLL, "/v1/poll", b, master.poll_family, MASTER_POLL_TIMEOUT_S); - json_object_put(b); - if (master.poll_call == 0) { - master.poll_after = now + MASTER_RETRY_NS; - } - } } void master_stop(void) diff --git a/server/Source/Server/Net/Master.h b/server/Source/Server/Net/Master.h index 4a19206..344e4ee 100644 --- a/server/Source/Server/Net/Master.h +++ b/server/Source/Server/Net/Master.h @@ -11,8 +11,9 @@ * - announce: at start, every 30 s and when the name, map, mode or player * count changes, once over IPv4 and once over IPv6 (the master lists the * address each call came from); - * - poll: one long poll waiting for browsers' offers, handed to WebRTC - * (Net/WebRtc.cpp), whose answer or refusal goes back within 10 s; + * - no offers: a browser joins a listed server by WebRTC direct (it builds + * the server's answer from the row's address, webrtc_port and + * dtls_fingerprint, Net/WebRtc.c), a friend's match by its room (Net/Room.c); * - leave: on shutdown. * * Every body is signed with the server's Ed25519 key, made once and kept in @@ -37,11 +38,6 @@ void master_tick(struct server* server); /* sends leave (waits up to 3 s for it) */ void master_stop(void); -/* WebRTC's answer to an offer, or its refusal (the reason is shown to the - player) */ -void master_answer(const char* offer_id, const char* sdp); -void master_reject(const char* offer_id, const char* reason); - /* connect tokens: the reason a ClientCertificate must carry one from this connection ("internet"), NULL when it need not (tokens off, no key from the master lately, a local address, WebRTC) */ diff --git a/server/Source/Server/Net/Room.c b/server/Source/Server/Net/Room.c new file mode 100644 index 0000000..89e433a --- /dev/null +++ b/server/Source/Server/Net/Room.c @@ -0,0 +1,177 @@ +// Copyright (c) 2026 ngspades contributors +// SPDX-License-Identifier: GPL-3.0-or-later +/* + * The match's room over Atyha (Room.h): the host side of + * spec/atyha-v1.md, polled on the tick. The relays' WebSocket is + * libdatachannel's own (the library WebRTC already links), so nothing new + * is linked for it. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* the application id every client of ours joins with (atyha's `app`): + a room of another game never answers ours */ +#define ROOM_APP "ngspades" +/* no relay confirmed the room by then: the host is told (it may still open later) */ +#define ROOM_OPEN_WAIT_NS (30ULL * 1000000000ULL) + +static struct +{ + atyha_ws_backend* ws; + atyha_host* host; + char code[12]; + uint64_t started; + int open; + int said_closed; +} room; + +static void _log_open(void) +{ + char shown[16]; + atyha_code_display(room.code, shown); + LOG_STATUS("Room %s open: friends join by its code %s", room.code, shown); + evt_log(NULL, "room", "action=open code=%s", room.code); +} + +void room_start(server_t* server) +{ + memset(&room, 0, sizeof room); + if (!server->join_code[0]) { + return; + } + snprintf(room.code, sizeof room.code, "%s", server->join_code); + if (profile_is_075()) { + LOG_WARNING("Room %s closed: the room is the 1.0 profile's (a 0.75 profile join needs a forwarded port)", + room.code); + return; + } + if (webrtc_port() == 0) { + LOG_WARNING("Room %s closed: WebRTC did not start", room.code); + return; + } + room.ws = atyha_libdatachannel_backend_create(NULL); + if (room.ws == NULL) { + LOG_WARNING("Room %s closed: no WebSocket for the relays", room.code); + return; + } + + /* the friend uses the same STUN and TURN servers as this side */ + size_t n_ice = 0; + const webrtc_ice_t* list = webrtc_ice_servers(&n_ice); + const char* urls[WEBRTC_MAX_ICE]; + atyha_ice_server ice[WEBRTC_MAX_ICE]; + for (size_t i = 0; i < n_ice && i < WEBRTC_MAX_ICE; i++) { + urls[i] = list[i].url; + ice[i].urls = &urls[i]; + ice[i].url_count = 1; + ice[i].username = list[i].username[0] ? list[i].username : NULL; + ice[i].credential = list[i].credential[0] ? list[i].credential : NULL; + } + + /* what a friend sees before it joins: the match's name, map and mode */ + json_object* meta = json_object_new_object(); + json_object_object_add(meta, "name", json_object_new_string(server->server_name)); + json_object_object_add(meta, "map", json_object_new_string(server->map_name)); + json_object_object_add(meta, "mode", json_object_new_string(server->gamemode_name)); + json_object_object_add(meta, "max_players", json_object_new_int(server->protocol.max_players)); + json_object_object_add(meta, "protocol", json_object_new_string("1.0")); + + const char* password = getenv("SP_JOIN_PASSWORD"); + atyha_host_config config; + memset(&config, 0, sizeof config); + config.app = ROOM_APP; + config.code = room.code; + config.password = password != NULL ? password : ""; + config.meta = json_object_to_json_string_ext(meta, JSON_C_TO_STRING_PLAIN | JSON_C_TO_STRING_NOSLASHESCAPE); + config.ice = n_ice > 0 ? ice : NULL; + config.ice_count = (int) (n_ice < WEBRTC_MAX_ICE ? n_ice : WEBRTC_MAX_ICE); + config.transport.ws = room.ws; + room.host = atyha_host_create(&config); + json_object_put(meta); + if (room.host == NULL) { + LOG_WARNING("Room %s closed: Atyha refused the room", room.code); + atyha_libdatachannel_backend_destroy(room.ws); + room.ws = NULL; + return; + } + room.started = get_real_nanos(); + LOG_INFO("Room %s: opening on the public relays%s", room.code, + password != NULL && *password ? " (with a password)" : ""); + evt_log(NULL, "room", "action=start code=%s password=%d", room.code, password != NULL && *password); +} + +void room_poll(server_t* server) +{ + if (room.host == NULL) { + return; + } + atyha_event ev; + while (atyha_host_poll(room.host, atyha_now_ms(), &ev)) { + switch (ev.type) { + case ATYHA_EV_OPEN: + room.open = 1; + _log_open(); + break; + case ATYHA_EV_OFFER: { + char id[96]; + snprintf(id, sizeof id, "%s%s", ROOM_OFFER_PREFIX, ev.attempt); + evt_log(NULL, "room", "action=offer attempt=%s", ev.attempt); + /* no address yet: Net/WebRtc.c takes the friend's from ICE */ + webrtc_offer(server, id, ev.sdp, ""); + break; + } + case ATYHA_EV_LOG: + LOG_DEBUG("Room: %s", ev.text); + break; + default: + break; + } + } + if (!room.open && !room.said_closed && get_real_nanos() - room.started > ROOM_OPEN_WAIT_NS) { + room.said_closed = 1; + LOG_WARNING("Room %s closed: no relay could be reached (still trying)", room.code); + evt_log(NULL, "room", "action=unreached code=%s", room.code); + } +} + +void room_stop(void) +{ + if (room.host != NULL) { + atyha_host_destroy(room.host); + } + if (room.ws != NULL) { + atyha_libdatachannel_backend_destroy(room.ws); + } + memset(&room, 0, sizeof room); +} + +int room_offer(const char* offer_id) +{ + return offer_id != NULL && strncmp(offer_id, ROOM_OFFER_PREFIX, sizeof ROOM_OFFER_PREFIX - 1) == 0; +} + +void room_answer(const char* offer_id, const char* sdp) +{ + if (room.host != NULL && room_offer(offer_id)) { + atyha_host_answer(room.host, offer_id + sizeof ROOM_OFFER_PREFIX - 1, sdp); + } +} + +void room_reject(const char* offer_id, const char* reason) +{ + if (room.host != NULL && room_offer(offer_id)) { + atyha_host_reject(room.host, offer_id + sizeof ROOM_OFFER_PREFIX - 1, reason); + } +} diff --git a/server/Source/Server/Net/Room.h b/server/Source/Server/Net/Room.h new file mode 100644 index 0000000..d4bb4fd --- /dev/null +++ b/server/Source/Server/Net/Room.h @@ -0,0 +1,35 @@ +// Copyright (c) 2026 ngspades contributors +// SPDX-License-Identifier: GPL-3.0-or-later +#ifndef SERVER_NET_ROOM_H +#define SERVER_NET_ROOM_H + +/* + * The match's room (--join-code, and SP_JOIN_PASSWORD when it has one): a + * friend joins by the code alone, with no port forwarded and no server of + * ours in between. Atyha (common/atyha, github.com/ngspades/atyha) opens + * the room on public Nostr relays; a friend's offer comes from there, is + * answered by Net/WebRtc.c as a master's would be, and the answer goes back + * through the relays. The code alone or the code and the password + * authenticate the friend (CPace), so the relays learn nothing they could + * join or tamper with. + * + * The log says "Room open" once a relay confirmed the room (the + * listen server's client reads it, listenserver.c) and "Room closed: + * " when it could not be opened. + */ + +struct server; + +void room_start(struct server* server); +/* on the tick: the relays' messages, the friends' offers */ +void room_poll(struct server* server); +void room_stop(void); + +/* the offers Net/WebRtc.c got from the room carry this prefix in their id */ +#define ROOM_OFFER_PREFIX "room:" +/* 1 when the offer id is the room's (its answer goes back there) */ +int room_offer(const char* offer_id); +void room_answer(const char* offer_id, const char* sdp); +void room_reject(const char* offer_id, const char* reason); + +#endif diff --git a/server/Source/Server/Net/RtcPeer.cpp b/server/Source/Server/Net/RtcPeer.cpp index 73bef72..472f49e 100644 --- a/server/Source/Server/Net/RtcPeer.cpp +++ b/server/Source/Server/Net/RtcPeer.cpp @@ -21,6 +21,7 @@ struct Peer }; std::mutex g_mu; +std::unique_ptr g_listener; std::unordered_map> g_peers; std::deque g_events; rtc::Configuration g_config; @@ -136,6 +137,13 @@ extern "C" int rtcw_init(uint16_t port, const rtcw_ice_t* ice, size_t n_ice, con extern "C" void rtcw_shutdown(void) { + if (g_listener != nullptr) { + try { + g_listener->stop(); + } catch (...) { + } + g_listener.reset(); + } std::unordered_map> peers; { std::lock_guard lock(g_mu); @@ -159,12 +167,10 @@ extern "C" void rtcw_shutdown(void) g_ready = false; } -extern "C" uint32_t rtcw_peer_create(const char* offer_sdp, char* err, size_t err_size) +/* a peer with every callback set, registered under a new id; the caller + gives it its descriptions. 0 when the connection could not be made */ +static uint32_t make_peer(const rtc::Configuration& config, std::shared_ptr& out, char* err, size_t err_size) { - if (!g_ready) { - set_error(err, err_size, "webrtc not started"); - return 0; - } uint32_t id; auto peer = std::make_shared(); { @@ -175,7 +181,7 @@ extern "C" uint32_t rtcw_peer_create(const char* offer_sdp, char* err, size_t er } } try { - peer->pc = std::make_shared(g_config); + peer->pc = std::make_shared(config); /* not trickled: the answer goes out once it holds every candidate */ peer->pc->onGatheringStateChange([id](rtc::PeerConnection::GatheringState state) { if (state == rtc::PeerConnection::GatheringState::Complete) { @@ -228,12 +234,126 @@ extern "C" uint32_t rtcw_peer_create(const char* offer_sdp, char* err, size_t er std::lock_guard lock(g_mu); g_peers[id] = peer; } + out = peer; + return id; + } catch (const std::exception& e) { + set_error(err, err_size, e.what()); + return 0; + } +} + +static void forget(uint32_t id) +{ + std::lock_guard lock(g_mu); + g_peers.erase(id); +} + +extern "C" uint32_t rtcw_peer_create(const char* offer_sdp, char* err, size_t err_size) +{ + if (!g_ready) { + set_error(err, err_size, "webrtc not started"); + return 0; + } + std::shared_ptr peer; + uint32_t id = make_peer(g_config, peer, err, err_size); + if (id == 0) { + return 0; + } + try { peer->pc->setRemoteDescription(rtc::Description(std::string(offer_sdp), rtc::Description::Type::Offer)); return id; } catch (const std::exception& e) { set_error(err, err_size, e.what()); - std::lock_guard lock(g_mu); - g_peers.erase(id); + forget(id); + return 0; + } +} + +extern "C" int rtcw_direct_listen(uint16_t port, char* err, size_t err_size) +{ + if (!g_ready) { + set_error(err, err_size, "webrtc not started"); + return 0; + } + try { + g_listener = std::make_unique(port); + g_listener->OnUnhandledStunRequest([](rtc::IceUdpMuxRequest request) { + /* the browser's ufrag is ours too (it set both): the request's + local and remote ufrags are the same; anything else is no + WebRTC direct browser */ + if (request.remoteUfrag.empty() || request.remoteUfrag.size() > 256 || + request.localUfrag != request.remoteUfrag) { + return; + } + std::string line = + request.remoteUfrag + "\n" + request.remoteAddress + "\n" + std::to_string(request.remotePort); + push(RTCW_INCOMING, 0, 0, line.data(), line.size(), 1, nullptr); + }); + return 1; + } catch (const std::exception& e) { + set_error(err, err_size, e.what()); + return 0; + } +} + +/* the offer the browser would have sent: its ufrag and password (the same + string), its address as the one candidate, DTLS client (setup:active), a + fingerprint nobody checks */ +static std::string synthetic_offer(const std::string& ufrag, const std::string& address, uint16_t port) +{ + bool v6 = address.find(':') != std::string::npos; + std::string ip = v6 ? "IP6" : "IP4"; + std::string fp = "sha-256 "; + for (int i = 0; i < 32; i++) { + fp += i ? ":00" : "00"; + } + std::string sdp; + sdp += "v=0\r\n"; + sdp += "o=- 0 0 IN " + ip + " " + address + "\r\n"; + sdp += "s=-\r\n"; + sdp += "t=0 0\r\n"; + sdp += "a=group:BUNDLE 0\r\n"; + sdp += "m=application " + std::to_string(port) + " UDP/DTLS/SCTP webrtc-datachannel\r\n"; + sdp += "c=IN " + ip + " " + address + "\r\n"; + sdp += "a=mid:0\r\n"; + sdp += "a=ice-ufrag:" + ufrag + "\r\n"; + sdp += "a=ice-pwd:" + ufrag + "\r\n"; + sdp += "a=fingerprint:" + fp + "\r\n"; + sdp += "a=setup:active\r\n"; + sdp += "a=sctp-port:5000\r\n"; + sdp += "a=max-message-size:262144\r\n"; + sdp += "a=candidate:1 1 UDP 2113937151 " + address + " " + std::to_string(port) + " typ host\r\n"; + sdp += "a=end-of-candidates\r\n"; + return sdp; +} + +extern "C" uint32_t rtcw_peer_create_direct(const char* ufrag, const char* address, uint16_t port, char* err, + size_t err_size) +{ + if (!g_ready) { + set_error(err, err_size, "webrtc not started"); + return 0; + } + rtc::Configuration config = g_config; + config.disableFingerprintVerification = true; + config.disableAutoNegotiation = true; + std::shared_ptr peer; + uint32_t id = make_peer(config, peer, err, err_size); + if (id == 0) { + return 0; + } + try { + std::string u(ufrag); + peer->pc->setRemoteDescription( + rtc::Description(synthetic_offer(u, std::string(address), port), rtc::Description::Type::Offer)); + rtc::LocalDescriptionInit init; + init.iceUfrag = u; + init.icePwd = u; + peer->pc->setLocalDescription(rtc::Description::Type::Answer, init); + return id; + } catch (const std::exception& e) { + set_error(err, err_size, e.what()); + forget(id); return 0; } } @@ -357,7 +477,7 @@ extern "C" int rtcw_poll(rtcw_event_t* ev) while (!g_events.empty()) { rtcw_event_t e = g_events.front(); g_events.pop_front(); - if (g_peers.find(e.peer) == g_peers.end()) { + if (e.peer != 0 && g_peers.find(e.peer) == g_peers.end()) { std::free(e.data); /* closed since */ continue; } diff --git a/server/Source/Server/Net/RtcPeer.h b/server/Source/Server/Net/RtcPeer.h index 859811d..ae9f7cd 100644 --- a/server/Source/Server/Net/RtcPeer.h +++ b/server/Source/Server/Net/RtcPeer.h @@ -27,6 +27,8 @@ enum RTCW_CHANNEL_OPEN, /* channel 0 (reliable) or 1 (unreliable) */ RTCW_MESSAGE, /* data/len on channel; text when text is 1 */ RTCW_CLOSED, /* the connection or a channel closed or failed: why */ + RTCW_INCOMING, /* WebRTC direct: a browser's first STUN request, peer 0; data is + "\n
\n" (rtcw_direct_listen) */ }; typedef struct @@ -62,6 +64,18 @@ void rtcw_shutdown(void); /* a peer answering the browser's offer; 0 when the offer was refused */ uint32_t rtcw_peer_create(const char* offer_sdp, char* err, size_t err_size); + +/* WebRTC direct (the browser has no signalling: it built this server's + answer from the master's list, the way libp2p's webrtc-direct does): + every STUN request of an unknown ufrag on the port becomes an + RTCW_INCOMING event. 0 when the listener could not start */ +int rtcw_direct_listen(uint16_t port, char* err, size_t err_size); +/* the peer for one RTCW_INCOMING: a synthetic offer from the browser's + ufrag (its ICE password too) and address, answered with that same ufrag + and password; the browser's DTLS certificate is not checked (anyone may + join a public server), the server's is the one the list gave it. 0 when + it failed */ +uint32_t rtcw_peer_create_direct(const char* ufrag, const char* address, uint16_t port, char* err, size_t err_size); /* the answer, malloc'd; NULL before RTCW_GATHERED */ char* rtcw_local_sdp(uint32_t peer); /* 0 queued, -1 not open or failed */ diff --git a/server/Source/Server/Net/WebHostStubs.c b/server/Source/Server/Net/WebHostStubs.c index 25a8322..6dfc68e 100644 --- a/server/Source/Server/Net/WebHostStubs.c +++ b/server/Source/Server/Net/WebHostStubs.c @@ -15,6 +15,7 @@ #include #include #include +#include #include /* ---- ENet (Net/EnetConn.c): no UDP host in a worker ---- */ @@ -35,6 +36,20 @@ void webrtc_start(struct server* server) void webrtc_stop(void) {} +/* ---- the room (Net/Room.c): the page itself opens it (workerbridge.js) ---- */ + +void room_start(struct server* server) +{ + (void) server; +} + +void room_poll(struct server* server) +{ + (void) server; +} + +void room_stop(void) {} + int webrtc_count_from(uint32_t key, const conn_t* except) { (void) key; diff --git a/server/Source/Server/Net/WebRtc.c b/server/Source/Server/Net/WebRtc.c index 68b4d4e..8ae52ba 100644 --- a/server/Source/Server/Net/WebRtc.c +++ b/server/Source/Server/Net/WebRtc.c @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -466,12 +467,69 @@ void webrtc_start(server_t* server) } LOG_STATUS("WebRTC (browsers) on UDP port %u, ICE servers: %s", (unsigned) rtc_port, rtc_ice_count ? ice_text : "none"); + LOG_INFO("WebRTC certificate: %s", webrtc_fingerprint()); + /* WebRTC direct: a browser that read this server's address, port and + fingerprint in the master's list connects with no offer at all */ + if (!rtcw_direct_listen(rtc_port, err, sizeof err)) { + LOG_WARNING("webrtc: no direct joins (%s): browsers join through a room only", err); + } evt_log(NULL, "webrtc", "action=start port=%u ice=%zu ice_servers=\"%s\"", (unsigned) rtc_port, rtc_ice_count, ice_text); } /* ---- offers ---- */ +/* an offer's answer goes back the way it came: the match's room on the + public relays (Net/Room.c), the one source of offers. A direct join has + none (its peers are answered) */ +static void _reply_answer(const char* offer_id, const char* sdp) +{ + if (room_offer(offer_id)) { + room_answer(offer_id, sdp); + } +} + +static void _reply_reject(const char* offer_id, const char* reason) +{ + if (room_offer(offer_id)) { + room_reject(offer_id, reason); + } +} + +/* a room's friend has no address until ICE found it: a key of its own + meanwhile (FNV-1a of the offer's id), never 0, which every one of them + would share and so count against one address's limit */ +static uint32_t _offer_key(const char* offer_id) +{ + uint32_t h = 2166136261u; + for (const char* c = offer_id; *c; c++) { + h = (h ^ (uint8_t) *c) * 16777619u; + } + return h | 1u; +} + +/* "1.2.3.4:5678", "2804:...:6229:5678" or "[::1]:5678" (libdatachannel's remoteAddress) -> the address alone */ +static void _host_part(const char* remote, char* out, size_t size) +{ + const char* start = remote; + size_t n; + if (*start == '[') { + start++; + const char* end = strchr(start, ']'); + n = end != NULL ? (size_t) (end - start) : strlen(start); + } else { + /* libdatachannel writes "address:port" for IPv6 as well, without + brackets: the port is always after the last colon */ + const char* colon = strrchr(start, ':'); + n = colon != NULL ? (size_t) (colon - start) : strlen(start); + } + if (n >= size) { + n = size - 1; + } + memcpy(out, start, n); + out[n] = '\0'; +} + static int _pending(void) { int n = 0; @@ -492,17 +550,43 @@ static int _offer_banned(const char* ip, int v4, const uint8_t ip4[4]) return player_banned(&probe); } +/* a peer of ours for libdatachannel's id: its conn, its address, its place + in the list. answered: nothing is waiting for its answer (direct joins) */ +static webrtc_peer_t* _peer_add(uint32_t id, const char* offer_id, const char* ip, uint32_t key, int v4, + const uint8_t ip4[4], int answered) +{ + webrtc_peer_t* p = calloc(1, sizeof *p); + if (p == NULL) { + rtcw_close(id); + return NULL; + } + p->id = id; + p->created = get_real_nanos(); + p->answered = (uint8_t) answered; + p->conn.transport = &webrtc_transport; + p->conn.handle = p; + p->conn.player_id = CONN_NO_PLAYER; + p->conn.family = v4 ? 4 : 6; + memcpy(p->conn.ip4, ip4, 4); + snprintf(p->conn.address, sizeof p->conn.address, "%s", ip); + p->conn.key = key; + snprintf(p->offer_id, sizeof p->offer_id, "%s", offer_id); + p->next = rtc_peers; + rtc_peers = p; + return p; +} + void webrtc_offer(server_t* server, const char* offer_id, const char* sdp, const char* ip) { const char* why = NULL; - uint32_t key = conn_key_of(ip); + uint32_t key = *ip ? conn_key_of(ip) : _offer_key(offer_id); uint8_t ip4[4] = {0, 0, 0, 0}; int v4 = sscanf(ip, "%hhu.%hhu.%hhu.%hhu", &ip4[0], &ip4[1], &ip4[2], &ip4[3]) == 4; if (rtc_port == 0) { why = "this server takes no browsers now"; } else if (server->protocol.num_players >= server->protocol.max_players) { why = "server full"; - } else if (_offer_banned(ip, v4, ip4)) { + } else if (*ip && _offer_banned(ip, v4, ip4)) { why = "banned"; } else if (_pending() >= WEBRTC_MAX_PENDING) { why = "too many joining, try again"; @@ -515,30 +599,79 @@ void webrtc_offer(server_t* server, const char* offer_id, const char* sdp, const } if (why != NULL) { evt_log(NULL, "webrtc", "action=offer offer=%s ip=%s ok=0 why=\"%s\"", offer_id, ip, why); - master_reject(offer_id, why); + _reply_reject(offer_id, why); return; } - webrtc_peer_t* p = calloc(1, sizeof *p); - if (p == NULL) { - rtcw_close(id); - master_reject(offer_id, "server error"); + if (_peer_add(id, offer_id, ip, key, v4, ip4, 0) == NULL) { + _reply_reject(offer_id, "server error"); return; } - p->id = id; - p->created = get_real_nanos(); - p->conn.transport = &webrtc_transport; - p->conn.handle = p; - p->conn.player_id = CONN_NO_PLAYER; - p->conn.family = v4 ? 4 : 6; - memcpy(p->conn.ip4, ip4, 4); - snprintf(p->conn.address, sizeof p->conn.address, "%s", ip); - p->conn.key = key; - snprintf(p->offer_id, sizeof p->offer_id, "%s", offer_id); - p->next = rtc_peers; - rtc_peers = p; evt_log(NULL, "webrtc", "action=offer offer=%s ip=%s ok=1 peer=%u", offer_id, ip, id); } +/* WebRTC direct (rtcw_direct_listen): a browser's first STUN request, + "\n
\n". Its address is known before anything is + made, so bans and the limits are read now; the peer answers nothing (the + browser built this server's answer itself) */ +#define WEBRTC_DIRECT_PREFIX "direct:" +/* peers one address may have joining at once */ +#define WEBRTC_DIRECT_PER_ADDRESS 4 + +static void _direct(server_t* server, const char* line) +{ + char ufrag[260], ip[64]; + unsigned port = 0; + const char* a = strchr(line, '\n'); + const char* b = a != NULL ? strchr(a + 1, '\n') : NULL; + if (a == NULL || b == NULL || (size_t) (a - line) >= sizeof ufrag || (size_t) (b - a - 1) >= sizeof ip || + sscanf(b + 1, "%u", &port) != 1 || port == 0 || port > 65535) { + return; + } + memcpy(ufrag, line, (size_t) (a - line)); + ufrag[a - line] = '\0'; + memcpy(ip, a + 1, (size_t) (b - a - 1)); + ip[b - a - 1] = '\0'; + + char offer_id[64]; + snprintf(offer_id, sizeof offer_id, WEBRTC_DIRECT_PREFIX "%.48s", ufrag); + /* the browser repeats its request until it is answered: one peer */ + int from_here = 0; + uint32_t key = conn_key_of(ip); + for (webrtc_peer_t* p = rtc_peers; p != NULL; p = p->next) { + if (!p->dead && !strcmp(p->offer_id, offer_id)) { + return; + } + from_here += !p->dead && !p->connected && p->conn.key == key; + } + uint8_t ip4[4] = {0, 0, 0, 0}; + int v4 = sscanf(ip, "%hhu.%hhu.%hhu.%hhu", &ip4[0], &ip4[1], &ip4[2], &ip4[3]) == 4; + const char* why = NULL; + if (server->protocol.num_players >= server->protocol.max_players) { + why = "server full"; + } else if (_offer_banned(ip, v4, ip4)) { + why = "banned"; + } else if (_pending() >= WEBRTC_MAX_PENDING || from_here >= WEBRTC_DIRECT_PER_ADDRESS) { + why = "too many joining"; + } + if (why != NULL) { + /* nothing to send back: its STUN request goes unanswered and the + browser gives up (it says "no response") */ + evt_log(NULL, "webrtc", "action=direct ip=%s ok=0 why=\"%s\"", ip, why); + return; + } + char err[256] = ""; + uint32_t id = rtcw_peer_create_direct(ufrag, ip, (uint16_t) port, err, sizeof err); + if (id == 0) { + LOG_WARNING("webrtc: direct join from %s refused: %s", ip, err); + return; + } + if (_peer_add(id, offer_id, ip, key, v4, ip4, 1) == NULL) { + rtcw_close(id); + return; + } + evt_log(NULL, "webrtc", "action=direct ip=%s ok=1 peer=%u", ip, id); +} + /* ---- events ---- */ static webrtc_peer_t* _peer(uint32_t id) @@ -584,6 +717,23 @@ static void _on_text(server_t* server, webrtc_peer_t* p, const char* text) p->connected = 1; char remote[96]; rtcw_remote_address(p->id, remote, sizeof remote); + /* a room's friend came with no address (Net/Room.c): ICE found it, and + bans and the per-address limit read it from now on */ + if (!p->conn.address[0] && remote[0]) { + char ip[64]; + uint8_t ip4[4] = {0, 0, 0, 0}; + _host_part(remote, ip, sizeof ip); + int v4 = sscanf(ip, "%hhu.%hhu.%hhu.%hhu", &ip4[0], &ip4[1], &ip4[2], &ip4[3]) == 4; + snprintf(p->conn.address, sizeof p->conn.address, "%s", ip); + p->conn.family = v4 ? 4 : 6; + memcpy(p->conn.ip4, ip4, 4); + p->conn.key = conn_key_of(ip) ? conn_key_of(ip) : p->conn.key; + if (_offer_banned(ip, v4, ip4)) { + evt_log(NULL, "webrtc", "action=refused peer=%u ip=%s why=banned", p->id, ip); + _gone(server, p, 1, "banned"); + return; + } + } server_conn_connect(server, &p->conn, (uint32_t) data); /* after: the player it became, -1 when it was refused */ evt_log(NULL, "webrtc", "action=connected peer=%u player=%d ip=%s ice=%s data=%lu channels=%u", p->id, @@ -605,12 +755,12 @@ static void _on_event(server_t* server, rtcw_event_t* ev) } char* sdp = rtcw_local_sdp(p->id); if (sdp == NULL) { - master_reject(p->offer_id, "server error"); + _reply_reject(p->offer_id, "server error"); _gone(server, p, 0, "no_answer"); break; } p->answered = 1; - master_answer(p->offer_id, sdp); + _reply_answer(p->offer_id, sdp); evt_log(NULL, "webrtc", "action=answer peer=%u offer=%s after_ms=%llu", p->id, p->offer_id, (unsigned long long) ((get_real_nanos() - p->created) / NANO_IN_MILLI)); free(sdp); @@ -655,7 +805,13 @@ void webrtc_poll(server_t* server) } rtcw_event_t ev; while (rtcw_poll(&ev)) { - _on_event(server, &ev); + if (ev.kind == RTCW_INCOMING) { + if (ev.data != NULL) { + _direct(server, (const char*) ev.data); + } + } else { + _on_event(server, &ev); + } free(ev.data); } uint64_t now = get_real_nanos(); @@ -663,7 +819,7 @@ void webrtc_poll(server_t* server) while (*at != NULL) { webrtc_peer_t* p = *at; if (!p->dead && !p->answered && now - p->created > WEBRTC_ANSWER_NS) { - master_reject(p->offer_id, "the server could not answer in time"); + _reply_reject(p->offer_id, "the server could not answer in time"); _gone(server, p, 0, "answer_timeout"); } else if (!p->dead && !p->connected && !p->closing && now - p->created > WEBRTC_CONNECT_NS) { _gone(server, p, 0, "no_connect"); diff --git a/server/Source/Server/Net/WebRtc.h b/server/Source/Server/Net/WebRtc.h index b177901..862af71 100644 --- a/server/Source/Server/Net/WebRtc.h +++ b/server/Source/Server/Net/WebRtc.h @@ -6,8 +6,11 @@ /* * The browsers' transport (docs/web.md phase 2, docs/protocol-1.0.md * "WebRTC transport"): libdatachannel, every peer on one UDP port (ICE UDP - * mux, [webrtc] port, default the game port + 1). A browser's offer comes - * through the master (Net/Master.c), the answer goes back through it. Two + * mux, [webrtc] port, default the game port + 1). A browser joins a listed + * server by WebRTC direct: it builds this server's answer from the master's + * row (address, webrtc_port, dtls_fingerprint) and its first STUN request + * makes the peer (rtcw_direct_listen); a friend's match takes offers from + * its room (Net/Room.c), answered through it. Two * DataChannels the browser opens, "reliable" (ENet channel 0) and * "unreliable" (channel 1); text messages are control ("connect ", * "disconnect "), binary ones are game packets, one a message, of @@ -58,8 +61,9 @@ const webrtc_ice_t* webrtc_ice_servers(size_t* n); empty until known */ const char* webrtc_fingerprint(void); -/* a browser's offer from the master: answered (or rejected) through - master_answer / master_reject from webrtc_poll, within the master's 10 s */ +/* a friend's offer from the match's room (Net/Room.c): answered (or + rejected) through the room from webrtc_poll. A listed server's browsers + join with no offer (WebRTC direct, rtcw_direct_listen) */ void webrtc_offer(struct server* server, const char* offer_id, const char* sdp, const char* ip); int webrtc_count_from(uint32_t key, const conn_t* except); diff --git a/server/Source/Server/PluginNet.h b/server/Source/Server/PluginNet.h index eddcec9..84eb7ff 100644 --- a/server/Source/Server/PluginNet.h +++ b/server/Source/Server/PluginNet.h @@ -24,9 +24,7 @@ typedef enum { NET_LANE_PLUGINS, - NET_LANE_MASTER, /* announce and leave */ - NET_LANE_MASTER_POLL, /* the long poll for offers */ - NET_LANE_MASTER_ANSWER, /* answers to offers: due within 10 s */ + NET_LANE_MASTER, /* announce and leave */ NET_LANES } net_lane_t; diff --git a/server/Source/Server/Server.c b/server/Source/Server/Server.c index cafe703..4109af3 100644 --- a/server/Source/Server/Server.c +++ b/server/Source/Server/Server.c @@ -43,6 +43,7 @@ #include #include #include +#include #include #include #include @@ -595,6 +596,7 @@ static void _server_update(server_t* server) #else conn_enet_poll(server); webrtc_poll(server); + room_poll(server); #endif } @@ -890,6 +892,7 @@ static void _server_shutdown(void) master075_stop(&server); } master_stop(); + room_stop(); webrtc_stop(); rcon_stop(); plugins_shutdown(&server); @@ -1001,6 +1004,7 @@ void server_start(server_args args, int startup_bots) bots_init(&server); rcon_start(&server); webrtc_start(&server); + room_start(&server); master_start(&server); if (profile_is_075()) { master075_start(&server); /* the public 0.75 masters */ diff --git a/server/cmake/libdatachannel.cmake b/server/cmake/libdatachannel.cmake index 773a2bc..302d395 100644 --- a/server/cmake/libdatachannel.cmake +++ b/server/cmake/libdatachannel.cmake @@ -28,7 +28,7 @@ FetchContent_Declare( ) set(NO_MEDIA ON CACHE BOOL "" FORCE) -set(NO_WEBSOCKET ON CACHE BOOL "" FORCE) +set(NO_WEBSOCKET OFF CACHE BOOL "" FORCE) # atyha's relays (common/atyha, ws_libdatachannel.c) set(NO_EXAMPLES ON CACHE BOOL "" FORCE) set(NO_TESTS ON CACHE BOOL "" FORCE) # its own static library (and its submodules'), whatever the project builds diff --git a/tools/build_server_static.sh b/tools/build_server_static.sh index 7607f86..4de4658 100755 --- a/tools/build_server_static.sh +++ b/tools/build_server_static.sh @@ -21,6 +21,7 @@ apk add --no-cache \ build-base cmake git linux-headers perl pkgconf file ca-certificates \ openssl-dev openssl-libs-static zlib-dev zlib-static \ json-c-dev lua5.4-dev readline-dev readline-static ncurses-dev ncurses-static \ + libsodium-dev libsodium-static \ curl-dev curl-static brotli-static zstd-static libpsl-static libidn2-static \ libunistring-static nghttp2-static c-ares-dev >/dev/null diff --git a/tools/server_deps_macos.sh b/tools/server_deps_macos.sh index c7ca0c8..92230af 100755 --- a/tools/server_deps_macos.sh +++ b/tools/server_deps_macos.sh @@ -6,7 +6,7 @@ # # tools/server_deps_macos.sh (MACOSX_DEPLOYMENT_TARGET, default 12.0) # -# OpenSSL (libdatachannel's DTLS, the master's signatures), json-c and Lua +# OpenSSL (libdatachannel's DTLS, the master's signatures), json-c, Lua and libsodium # 5.4 land in as .a only (no .dylib, so the linker can only take # the archive), with their pkg-config files. libcurl, zlib and readline # (libedit) are the system's, present on every Mac. Then: @@ -38,6 +38,8 @@ fetch json-c https://s3.amazonaws.com/json-c_releases/releases/json-c-0.18.tar.g 876ab046479166b869afc6896d288183bbc0e5843f141200c677b3e8dfb11724 fetch lua https://www.lua.org/ftp/lua-5.4.7.tar.gz \ 9fbf5e28ef86c69858f6d3d34eccc32e911c1a28b4120ff3e84aaa70cfbf1e30 +fetch libsodium https://github.com/jedisct1/libsodium/releases/download/1.0.20-RELEASE/libsodium-1.0.20.tar.gz \ + ebb65ef6ca439333c2bb41a0c1990587288da07f6c7fd07cb3a18cc18d30ce19 # OpenSSL: libcrypto and libssl only, no shared libraries, no docs; its # certificates are never read (libcurl is the system's) @@ -71,5 +73,12 @@ Libs: -L\${prefix}/lib -llua5.4 Libs.private: -lm EOF +# libsodium: Atyha's crypto (common/atyha: the match's room), static +(cd "$work/libsodium" && + ./configure --disable-shared --enable-static --prefix="$prefix" \ + CFLAGS="-O2 -mmacosx-version-min=$MACOSX_DEPLOYMENT_TARGET" >/dev/null && + make -j"$jobs" >/dev/null && + make install >/dev/null) + rm -f "$prefix"/lib/*.dylib ls -l "$prefix/lib"