From da917c6f5b8b7192267dd3820f4d5d7a11eb4074 Mon Sep 17 00:00:00 2001 From: Gustavo Date: Mon, 30 Nov 2026 17:37:36 -0300 Subject: [PATCH 1/5] Rooms by code over Atyha: no master for a join code, an optional password A listen server's join code (--join-code, now 8 symbols XXXX-XXXX) opens the match's room on public Nostr relays through Atyha (common/atyha, MIT, github.com/ngspades/atyha), Net/Room.c. A friend's offer comes from the room, Net/WebRtc.c answers it as it answers the master's, and the answer goes back through the relays. SP_JOIN_PASSWORD gives the room a password (CPace: the relays cannot test guesses, a host answers 20 hellos a minute). The log says "Room open" once a relay confirmed it. The master is no longer told the code: a private listen server is not announced at all, a public one is listed as before. A room's friend has no address until ICE finds it: a key of its own until then (the per-address limit no longer lumps every friend under 0), the real address from the selected candidate at "connect", where bans and the limit read it. netlib's p2p.c follows Atyha's code rule (8 symbols, the 25-symbol alphabet, white space trimmed); transport.h carries the room's password and the wrong-password flag for the client. The WebSocket to the relays is libdatachannel's own (NO_WEBSOCKET off). libsodium is a new dependency: CI (Ubuntu, macOS), the Alpine and MSYS2 release builds and server_deps_macos.sh (1.0.20, static, SHA-256 checked) install it. --- .github/workflows/ci.yml | 4 +- .github/workflows/release.yml | 1 + common/atyha/CMakeLists.txt | 122 +++ common/atyha/LICENSE | 21 + common/atyha/README.md | 216 +++++ common/atyha/cmake/deps.cmake | 68 ++ common/atyha/cmake/libdatachannel.cmake | 39 + common/atyha/include/atyha.h | 282 ++++++ common/atyha/include/atyha_crypto.h | 69 ++ common/atyha/include/atyha_curl.h | 34 + common/atyha/include/atyha_emscripten.h | 24 + common/atyha/include/atyha_libdatachannel.h | 32 + common/atyha/src/crypto.c | 389 +++++++++ common/atyha/src/internal.h | 81 ++ common/atyha/src/json.c | 360 ++++++++ common/atyha/src/membus.c | 112 +++ common/atyha/src/message.c | 101 +++ common/atyha/src/message.h | 32 + common/atyha/src/nostr.c | 459 ++++++++++ common/atyha/src/session.c | 920 ++++++++++++++++++++ common/atyha/src/util.c | 233 +++++ common/atyha/src/ws_curl.c | 290 ++++++ common/atyha/src/ws_emscripten.c | 198 +++++ common/atyha/src/ws_libdatachannel.c | 241 +++++ netlib/include/ngnet/p2p.h | 8 +- netlib/include/ngnet/transport.h | 12 +- netlib/src/p2p.c | 51 +- server/CMakeLists.txt | 8 +- server/Source/CMakeLists.txt | 6 + server/Source/Main.c | 24 +- server/Source/Server/CMakeLists.txt | 2 + server/Source/Server/Net/Master.c | 25 +- server/Source/Server/Net/Room.c | 177 ++++ server/Source/Server/Net/Room.h | 35 + server/Source/Server/Net/WebHostStubs.c | 15 + server/Source/Server/Net/WebRtc.c | 86 +- server/Source/Server/Server.c | 4 + server/cmake/libdatachannel.cmake | 2 +- tools/build_server_static.sh | 1 + tools/server_deps_macos.sh | 11 +- 40 files changed, 4722 insertions(+), 73 deletions(-) create mode 100644 common/atyha/CMakeLists.txt create mode 100644 common/atyha/LICENSE create mode 100644 common/atyha/README.md create mode 100644 common/atyha/cmake/deps.cmake create mode 100644 common/atyha/cmake/libdatachannel.cmake create mode 100644 common/atyha/include/atyha.h create mode 100644 common/atyha/include/atyha_crypto.h create mode 100644 common/atyha/include/atyha_curl.h create mode 100644 common/atyha/include/atyha_emscripten.h create mode 100644 common/atyha/include/atyha_libdatachannel.h create mode 100644 common/atyha/src/crypto.c create mode 100644 common/atyha/src/internal.h create mode 100644 common/atyha/src/json.c create mode 100644 common/atyha/src/membus.c create mode 100644 common/atyha/src/message.c create mode 100644 common/atyha/src/message.h create mode 100644 common/atyha/src/nostr.c create mode 100644 common/atyha/src/session.c create mode 100644 common/atyha/src/util.c create mode 100644 common/atyha/src/ws_curl.c create mode 100644 common/atyha/src/ws_emscripten.c create mode 100644 common/atyha/src/ws_libdatachannel.c create mode 100644 server/Source/Server/Net/Room.c create mode 100644 server/Source/Server/Net/Room.h 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/common/atyha/CMakeLists.txt b/common/atyha/CMakeLists.txt new file mode 100644 index 0000000..efadd79 --- /dev/null +++ b/common/atyha/CMakeLists.txt @@ -0,0 +1,122 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 ngspades contributors +cmake_minimum_required(VERSION 3.16) +project(atyha VERSION 1.0.0 LANGUAGES C) + +set(ATYHA_TOP_LEVEL OFF) +if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR) + set(ATYHA_TOP_LEVEL ON) +endif() + +option(ATYHA_TESTS "Build the tests (ctest)" ${ATYHA_TOP_LEVEL}) +option(ATYHA_CURL "Build the libcurl WebSocket backend (atyha_curl)" ON) +option(ATYHA_EXAMPLES "Build examples/echo (fetches libdatachannel)" OFF) +option(ATYHA_WITH_LIBDATACHANNEL "Build the libdatachannel WebSocket backend (atyha_libdatachannel)" ${ATYHA_EXAMPLES}) +set(ATYHA_VECTORS "${CMAKE_CURRENT_SOURCE_DIR}/../vectors/atyha-v1.json" CACHE FILEPATH "The protocol's test vectors") + +if(NOT CMAKE_C_STANDARD) + set(CMAKE_C_STANDARD 99) + set(CMAKE_C_STANDARD_REQUIRED ON) +endif() + +include(cmake/deps.cmake) + +# ---- the library: codes, CPace, keys, sealing, messages, the host and joiner +# state machines, the in-memory bus and the Nostr relay pool (no I/O of its +# own: WebSocket backends do it) +add_library(atyha STATIC + src/util.c + src/json.c + src/crypto.c + src/message.c + src/session.c + src/membus.c + src/nostr.c +) +if(EMSCRIPTEN) + target_sources(atyha PRIVATE src/ws_emscripten.c) +endif() +target_include_directories(atyha PUBLIC $) +target_link_libraries(atyha PUBLIC atyha::sodium PRIVATE atyha::secp256k1) +if(MSVC) + target_compile_definitions(atyha PRIVATE _CRT_SECURE_NO_WARNINGS) + target_compile_options(atyha PRIVATE /W3) +else() + target_compile_options(atyha PRIVATE -Wall -Wextra -Wno-unused-parameter) +endif() +add_library(atyha::atyha ALIAS atyha) + +# ---- the libcurl backend +if(ATYHA_CURL AND NOT EMSCRIPTEN) + find_package(CURL 8.11 QUIET) + if(CURL_FOUND) + add_library(atyha_curl STATIC src/ws_curl.c) + target_link_libraries(atyha_curl PUBLIC atyha CURL::libcurl) + if(NOT MSVC) + target_compile_options(atyha_curl PRIVATE -Wall -Wextra -Wno-unused-parameter) + endif() + add_library(atyha::curl ALIAS atyha_curl) + message(STATUS "atyha: libcurl ${CURL_VERSION_STRING} backend") + else() + message(WARNING "atyha: no libcurl 8.11+ found, atyha_curl not built " + "(macOS: -DCMAKE_PREFIX_PATH=$(brew --prefix curl))") + endif() +endif() + +# ---- tests +if(ATYHA_TESTS) + enable_testing() + add_executable(test_vectors tests/test_vectors.c) + target_link_libraries(test_vectors PRIVATE atyha) + target_include_directories(test_vectors PRIVATE src) + add_test(NAME vectors COMMAND test_vectors "${ATYHA_VECTORS}") + + add_executable(test_session tests/test_session.c) + target_link_libraries(test_session PRIVATE atyha) + add_test(NAME session COMMAND test_session) + + add_executable(test_nostr tests/test_nostr.c) + target_link_libraries(test_nostr PRIVATE atyha atyha::secp256k1) + target_include_directories(test_nostr PRIVATE src) + add_test(NAME nostr COMMAND test_nostr) +endif() + +# ---- the libdatachannel backend: the parent project's `datachannel` target +# (built with NO_WEBSOCKET OFF), else the one fetched for the example +if(ATYHA_WITH_LIBDATACHANNEL AND NOT EMSCRIPTEN) + if(NOT TARGET atyha::datachannel) + if(TARGET datachannel) + add_library(atyha::datachannel INTERFACE IMPORTED) + target_link_libraries(atyha::datachannel INTERFACE datachannel) + elseif(TARGET datachannel-static) + add_library(atyha::datachannel INTERFACE IMPORTED) + target_link_libraries(atyha::datachannel INTERFACE datachannel-static) + elseif(ATYHA_EXAMPLES) + include(cmake/libdatachannel.cmake) + endif() + endif() + if(TARGET atyha::datachannel) + add_library(atyha_libdatachannel STATIC src/ws_libdatachannel.c) + target_link_libraries(atyha_libdatachannel PUBLIC atyha atyha::datachannel) + if(NOT WIN32) + find_package(Threads REQUIRED) + target_link_libraries(atyha_libdatachannel PUBLIC Threads::Threads) + endif() + if(NOT MSVC) + target_compile_options(atyha_libdatachannel PRIVATE -Wall -Wextra -Wno-unused-parameter) + endif() + add_library(atyha::libdatachannel ALIAS atyha_libdatachannel) + else() + message(WARNING "atyha: no `datachannel` target, atyha_libdatachannel not built") + endif() +endif() + +# ---- the echo example (libdatachannel for WebRTC; WebSocket by libdatachannel or libcurl) +if(ATYHA_EXAMPLES AND TARGET atyha_libdatachannel) + add_executable(echo examples/echo.c) + target_link_libraries(echo PRIVATE atyha_libdatachannel) + if(TARGET atyha_curl) + target_link_libraries(echo PRIVATE atyha_curl) + target_compile_definitions(echo PRIVATE ATYHA_ECHO_CURL) + endif() +endif() diff --git a/common/atyha/LICENSE b/common/atyha/LICENSE new file mode 100644 index 0000000..459233d --- /dev/null +++ b/common/atyha/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 ngspades contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/common/atyha/README.md b/common/atyha/README.md new file mode 100644 index 0000000..2915902 --- /dev/null +++ b/common/atyha/README.md @@ -0,0 +1,216 @@ +# Atyha for C + +The C library of [Atyha](../spec/atyha-v1.md): join a host by a short room code +(`HK4M-7TRW`) over WebRTC, signalled through public Nostr relays, with an optional +password (CPace). It reproduces `../vectors/atyha-v1.json` byte for byte and +interoperates with the TypeScript reference over the real relays. + +Atyha is signalling only: it carries one complete SDP offer and one complete SDP +answer. Your program makes the peer connection with its own WebRTC stack +(libdatachannel, the browser's, Godot's...). + +- C99; macOS, Linux, Windows (MSVC), iOS, Android, Emscripten. +- Poll-driven and single-threaded: no thread is started, nothing calls you behind + your back. Call `atyha_*_poll(obj, now_ms)` every frame and drain the events. +- No global state of its own (libsodium's `sodium_init` and libcurl's + `curl_global_init` are the libraries' own, called for you). +- MIT. Depends on libsodium and bitcoin-core/libsecp256k1 (MIT, fetched by CMake). + +## Layers + +| layer | files | I/O | +| --- | --- | --- | +| codes, topic, CPace, keys, sealing (`atyha_crypto.h`) | `src/crypto.c`, `src/util.c` | none | +| messages, host and joiner state machines, in-memory bus | `src/message.c`, `src/session.c`, `src/membus.c` | none (through an `atyha_bus`) | +| Nostr relay pool: NIP-01 events, BIP-340 signing, REQ/EVENT/CLOSE/EOSE/OK/CLOSED, retirement and backoff | `src/nostr.c` | none (through an `atyha_ws_backend`) | +| WebSocket backends | `src/ws_curl.c` (target `atyha_curl`), `src/ws_libdatachannel.c` (target `atyha_libdatachannel`), `src/ws_emscripten.c` (in `atyha` under Emscripten), or your own | yes | + +## Build + +```sh +brew install libsodium curl # or apt install libsodium-dev libcurl4-openssl-dev +cmake -S . -B build -DCMAKE_PREFIX_PATH="$(brew --prefix curl);$(brew --prefix)" +cmake --build build +ctest --test-dir build # vectors, session, nostr +``` + +Targets: `atyha` (static: everything but the native backends), `atyha_curl` +(static, the libcurl backend), `atyha_libdatachannel` (static, libdatachannel's +WebSocket). Options: `ATYHA_TESTS` (on when top level), `ATYHA_CURL` (on), +`ATYHA_WITH_LIBDATACHANNEL` (on with the examples; links the parent project's +`datachannel` (or `datachannel-static`) target, which must be built with +`NO_WEBSOCKET OFF`, else the fetched one), `ATYHA_EXAMPLES` (off; fetches +libdatachannel v0.24.6 with `NO_MEDIA ON`, `NO_WEBSOCKET OFF`, and needs OpenSSL: +`-DOPENSSL_ROOT_DIR=$(brew --prefix openssl@3)`), `SODIUM_ROOT` (a +libsodium install to use, e.g. one built with emcc), `ATYHA_VECTORS` (path). +A parent project may define `atyha::sodium` / `atyha::secp256k1` targets itself. + +libsecp256k1 is fetched at `v0.8.0` with the `schnorrsig` and `extrakeys` modules. + +### libcurl version + +The WebSocket API (`curl_ws_send`/`curl_ws_recv`, `CURLOPT_CONNECT_ONLY = 2`) is +stable since **libcurl 8.11.0** and must be compiled in (`ws`/`wss` among the +protocols of `curl -V`). macOS's own libcurl (8.7.1 on this machine) has **no** +WebSocket support; Homebrew's `curl` (8.16.0 here) has it. The backend refuses to +start (returns NULL) when libcurl lacks `wss`. On Windows/Android/iOS build libcurl +with WebSockets enabled (`-DCURL_DISABLE_WEBSOCKETS=OFF`, the default since 8.11) and +give it CA certificates (`atyha_curl_options.ca_file`) where the platform store +is not used. + +### libdatachannel's WebSocket + +For programs that already link libdatachannel and OpenSSL (the game and its +server) and whose libcurl has no WebSocket (macOS's system libcurl 8.7.1): + +```c +#include "atyha_libdatachannel.h" +atyha_ws_backend* ws = atyha_libdatachannel_backend_create(NULL); /* verifies TLS */ +/* ... tr.ws = ws ... */ +atyha_libdatachannel_backend_destroy(ws); /* before rtcCleanup() */ +``` + +libdatachannel calls back on its own threads; the backend only queues there, +under a per-connection lock (pthread mutex, CRITICAL_SECTION on Windows), and +Atyha drains the queue from its poll. Closing deletes the rtc WebSocket first +(`rtcDeleteWebSocket` resets the callbacks) and frees the queue after. +`disable_tls_verification` (default 0) exists for tests only. + +Known limit: libdatachannel's TLS client offers only the P-256 key-exchange group +(`SSL_CTX_set1_groups_list(ctx, "P-256")` in its tlstransport.cpp), and a relay +that refuses P-256 fails the handshake: of the default relays, `wss://nostr.data.haus` +does (checked with `openssl s_client -groups P-256`). The other eight work, and the +pool goes on without it. + +### Emscripten + +Under `emcmake cmake`, `src/ws_emscripten.c` is compiled into `atyha` and the +curl backend is skipped; link the program with `-lwebsocket.js` and give a libsodium +built with emcc via `-DSODIUM_ROOT=...`. + +## API + +Everything is in `include/atyha.h`. Strings are UTF-8; a string an event points to +stays valid until the next poll of the same object. + +### Transport + +```c +#include "atyha.h" +#include "atyha_curl.h" /* native */ +atyha_ws_backend* ws = atyha_curl_backend_create(NULL); /* one for the program */ + +atyha_transport tr = {0}; +tr.ws = ws; /* Nostr, default relays of spec section 8 */ +/* tr.relays = my_list; tr.relay_count = n; a configured relay list */ +/* tr.bus_open = atyha_memory_bus_open; tr.bus_user = hub; tests, no network */ +``` + +### Host (fits an asynchronous "offer in, answer later" server) + +```c +atyha_host_config hc = {0}; +hc.app = "ngspades"; /* 1..64 bytes */ +hc.password = "123"; /* NULL or "": none */ +hc.meta = "{\"name\":\"my server\"}"; /* a JSON object sent to joiners, or NULL */ +hc.ice = ice; hc.ice_count = n; /* optional: STUN/TURN for the joiners */ +hc.transport = tr; +atyha_host* host = atyha_host_create(&hc); +/* atyha_host_code(host) -> "HK4M7TRW"; atyha_code_display() -> "HK4M-7TRW" */ + +for (;;) { /* every tick */ + atyha_event ev; + while (atyha_host_poll(host, now_ms, &ev)) { + if (ev.type == ATYHA_EV_OPEN) { /* the room is reachable: show the code */ } + if (ev.type == ATYHA_EV_OFFER) { + /* ev.sdp, ev.meta (joiner's JSON or NULL), ev.joiner, ev.attempt: + start the peer connection; reply whenever ready, from any tick: */ + remember(ev.attempt); + } + } + /* later: */ + atyha_host_answer(host, attempt, answer_sdp); /* or */ + atyha_host_reject(host, attempt, "server full"); +} +atyha_host_destroy(host); /* closes the room */ +``` + +For ngnet: `attempt` plays the part of `offer_id`; `ATYHA_EV_OFFER` is where +`ngnet_rtc_offer(...)` would be called, and the answer hook calls +`atyha_host_answer` (or `atyha_host_reject` in place of `ngnet_master_reject`). +A reply is kept 60 s and re-sent to every repeat of the same offer; attempts +waiting for the program are kept 5 minutes. + +### Joiner + +```c +atyha_join_config jc = {0}; +jc.app = "ngspades"; jc.code = typed_text; jc.password = pw; jc.meta = "{\"player\":\"p1\"}"; +jc.transport = tr; +atyha_joiner* j = atyha_joiner_create(&jc); + +while (atyha_joiner_poll(j, now_ms, &ev)) switch (ev.type) { +case ATYHA_EV_NEED_OFFER: /* password right. ev.ice/ev.ice_count (host's servers, use + them when > 0; atyha_ice_url_libdatachannel formats them), + ev.meta (host's). Make the peer connection, both channels, + wait for gathering complete (<= 5 s), then: */ + atyha_joiner_set_offer(j, offer_sdp); break; +case ATYHA_EV_ANSWER: /* ev.sdp: set it as the remote description; j is done */ break; +case ATYHA_EV_ERROR: /* ev.error: ATYHA_ERR_BAD_CODE, _NO_RELAY, _NO_ROOM, + _WRONG_PASSWORD, _REJECTED (ev.reason = host's text), + _NO_ANSWER, _CANCELLED; atyha_error_name() gives the + TS JoinError code ("wrong_password"...) */ break; +case ATYHA_EV_LOG: /* ev.text */ break; +} +atyha_joiner_cancel(j); /* any time: the next poll reports cancelled */ +atyha_joiner_destroy(j); +``` + +Timings follow the spec and the TS reference: hello every 2 s from the first EOSE, +`no_relay` when no relay confirmed the subscription in 10 s, `no_room` 25 s after +the first hello, `wrong_password` 4 s after a pake that does not open (unless a +good one comes), offer every 2 s, `no_answer` 25 s after the first offer +(`timeout_ms` changes the 25 s). One addition: if the program never calls +`atyha_joiner_set_offer`, the joiner reports `no_answer` 25 s after +`ATYHA_EV_NEED_OFFER`. + +### Your own WebSocket + +Fill an `atyha_ws_backend` (`connect`, `send`, `poll` returning +`ATYHA_WS_OPEN` / `ATYHA_WS_TEXT` / `ATYHA_WS_CLOSED`, `close`, optional +`update`), or a whole `atyha_bus` (`publish`, `poll`, `destroy`) for another +transport. Both are plain structs of function pointers, embedded as the first +member of your own struct. + +### Building blocks + +`atyha_crypto.h` exposes lv_cat, PRS, CI, the CPace generator string and +generator, shares, `scalar_mult_vfy`, ISK, the HKDF keys, seal/open and base64url, +as the vectors name them. + +## Example: echo + +```sh +cmake -S . -B build -DATYHA_EXAMPLES=ON -DOPENSSL_ROOT_DIR=$(brew --prefix openssl@3) \ + -DCMAKE_PREFIX_PATH="$(brew --prefix curl);$(brew --prefix)" +cmake --build build +build/echo host [--app A] [--password P] [--ws libdatachannel|curl] # CODE XXXX-XXXX, then PEER +build/echo join [--app A] [--password P] [--ws libdatachannel|curl] +``` + +The echo contract of every Atyha example (the same as `ts/tools/peer.ts`): the host +answers a text "x" on `reliable` with "echo x" and sends binary back on its channel; +the joiner sends "hi" and the bytes 1,2,3 and prints `CONNECTED `, +`RELIABLE echo hi`, `UNRELIABLE 1,2,3` (exit 0), or `FAILED `. +`ATYHA_LOG=1` prints the relay log on stderr. `--ws` picks the WebSocket backend +for the relays (default libdatachannel; curl when `atyha_curl` was built). + +## Notes + +- Relays: an `OK false` or `CLOSED` saying `rate-limited:` closes that relay for 60 s; + `blocked:`, `restricted:`, `auth-required:` or `pow:` drops it for the session; a + closed connection reconnects after 2 s, doubling to 30 s. Events are deduplicated + by id (the last 1024), own events and events more than 60 s off the clock are + ignored. Received signatures are not checked (spec section 8 allows it). +- The Nostr `created_at` uses the wall clock (`time()`); the polls' `now_ms` may be + any monotonic millisecond clock (`atyha_now_ms()` is one). diff --git a/common/atyha/cmake/deps.cmake b/common/atyha/cmake/deps.cmake new file mode 100644 index 0000000..add0911 --- /dev/null +++ b/common/atyha/cmake/deps.cmake @@ -0,0 +1,68 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 ngspades contributors +# +# The two crypto libraries: +# - libsodium (ristretto255, SHA-2, HMAC, ChaCha20-Poly1305, randomness): +# an existing target atyha::sodium wins; else pkg-config; else +# find_library. Emscripten builds point SODIUM_ROOT at a libsodium built +# with emcc (its include/ and lib/). +# - bitcoin-core/libsecp256k1 (BIP-340 Schnorr for Nostr events), fetched +# at a pinned release with the schnorrsig and extrakeys modules. +include(FetchContent) + +if(NOT TARGET atyha::sodium) + set(SODIUM_ROOT "" CACHE PATH "A libsodium installation (include/, lib/) to use") + if(SODIUM_ROOT) + find_path(SODIUM_INCLUDE_DIR sodium.h PATHS "${SODIUM_ROOT}/include" NO_DEFAULT_PATH) + find_library(SODIUM_LIBRARY NAMES sodium libsodium PATHS "${SODIUM_ROOT}/lib" NO_DEFAULT_PATH) + else() + find_package(PkgConfig QUIET) + if(PKG_CONFIG_FOUND) + pkg_check_modules(PC_SODIUM QUIET libsodium) + endif() + find_path(SODIUM_INCLUDE_DIR sodium.h HINTS ${PC_SODIUM_INCLUDE_DIRS}) + find_library(SODIUM_LIBRARY NAMES sodium libsodium HINTS ${PC_SODIUM_LIBRARY_DIRS}) + endif() + if(NOT SODIUM_INCLUDE_DIR OR NOT SODIUM_LIBRARY) + message(FATAL_ERROR "atyha: libsodium not found (brew install libsodium / apt install libsodium-dev, " + "or -DSODIUM_ROOT=...)") + endif() + add_library(atyha::sodium INTERFACE IMPORTED) + set_target_properties(atyha::sodium PROPERTIES + INTERFACE_INCLUDE_DIRECTORIES "${SODIUM_INCLUDE_DIR}" + INTERFACE_LINK_LIBRARIES "${SODIUM_LIBRARY}") + if(MSVC) + # a static libsodium on Windows + set_property(TARGET atyha::sodium APPEND PROPERTY INTERFACE_COMPILE_DEFINITIONS SODIUM_STATIC) + endif() + message(STATUS "atyha: libsodium ${SODIUM_LIBRARY}") +endif() + +if(NOT TARGET atyha::secp256k1) + set(ATYHA_SECP256K1_TAG "v0.8.0") + FetchContent_Declare( + secp256k1 + GIT_REPOSITORY https://github.com/bitcoin-core/secp256k1.git + GIT_TAG ${ATYHA_SECP256K1_TAG} + GIT_SHALLOW TRUE + ) + set(SECP256K1_ENABLE_MODULE_SCHNORRSIG ON CACHE BOOL "" FORCE) + set(SECP256K1_ENABLE_MODULE_EXTRAKEYS ON CACHE BOOL "" FORCE) + set(SECP256K1_ENABLE_MODULE_ECDH OFF CACHE BOOL "" FORCE) + set(SECP256K1_ENABLE_MODULE_RECOVERY OFF CACHE BOOL "" FORCE) + set(SECP256K1_ENABLE_MODULE_ELLSWIFT OFF CACHE BOOL "" FORCE) + set(SECP256K1_ENABLE_MODULE_MUSIG OFF CACHE BOOL "" FORCE) + set(SECP256K1_BUILD_TESTS OFF CACHE BOOL "" FORCE) + set(SECP256K1_BUILD_EXHAUSTIVE_TESTS OFF CACHE BOOL "" FORCE) + set(SECP256K1_BUILD_BENCHMARK OFF CACHE BOOL "" FORCE) + set(SECP256K1_BUILD_CTIME_TESTS OFF CACHE BOOL "" FORCE) + set(SECP256K1_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) + set(SECP256K1_INSTALL OFF CACHE BOOL "" FORCE) + set(_atyha_shared "${BUILD_SHARED_LIBS}") + set(BUILD_SHARED_LIBS OFF) + FetchContent_MakeAvailable(secp256k1) + set(BUILD_SHARED_LIBS "${_atyha_shared}") + add_library(atyha::secp256k1 INTERFACE IMPORTED) + target_link_libraries(atyha::secp256k1 INTERFACE secp256k1) + message(STATUS "atyha: libsecp256k1 ${ATYHA_SECP256K1_TAG} (fetched)") +endif() diff --git a/common/atyha/cmake/libdatachannel.cmake b/common/atyha/cmake/libdatachannel.cmake new file mode 100644 index 0000000..c35296e --- /dev/null +++ b/common/atyha/cmake/libdatachannel.cmake @@ -0,0 +1,39 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 ngspades contributors +# +# libdatachannel for the example and the atyha_libdatachannel backend, when +# the parent project provides none: an installed package when there is one, +# else fetched at a pinned release, DataChannels and WebSocket (no media). +# Defines atyha::datachannel. +enable_language(CXX) +if(TARGET atyha::datachannel) + return() +endif() + +find_package(LibDataChannel CONFIG QUIET) +if(LibDataChannel_FOUND) + add_library(atyha::datachannel INTERFACE IMPORTED) + target_link_libraries(atyha::datachannel INTERFACE LibDataChannel::LibDataChannel) + return() +endif() + +include(FetchContent) +set(ATYHA_LIBDATACHANNEL_TAG "v0.24.6") +FetchContent_Declare( + libdatachannel + GIT_REPOSITORY https://github.com/paullouisageneau/libdatachannel.git + GIT_TAG ${ATYHA_LIBDATACHANNEL_TAG} + GIT_SHALLOW TRUE + GIT_SUBMODULES deps/plog deps/usrsctp deps/libjuice deps/json +) +set(NO_MEDIA ON CACHE BOOL "" FORCE) +set(NO_WEBSOCKET OFF CACHE BOOL "" FORCE) # the atyha_libdatachannel backend uses it +set(NO_EXAMPLES ON CACHE BOOL "" FORCE) +set(NO_TESTS ON CACHE BOOL "" FORCE) +set(_atyha_shared "${BUILD_SHARED_LIBS}") +set(BUILD_SHARED_LIBS OFF) +FetchContent_MakeAvailable(libdatachannel) +set(BUILD_SHARED_LIBS "${_atyha_shared}") +add_library(atyha::datachannel INTERFACE IMPORTED) +target_link_libraries(atyha::datachannel INTERFACE datachannel-static) +message(STATUS "atyha: libdatachannel ${ATYHA_LIBDATACHANNEL_TAG} (fetched)") diff --git a/common/atyha/include/atyha.h b/common/atyha/include/atyha.h new file mode 100644 index 0000000..dba2ca3 --- /dev/null +++ b/common/atyha/include/atyha.h @@ -0,0 +1,282 @@ +/* SPDX-License-Identifier: MIT + Copyright (c) 2026 ngspades contributors + + atyha: join a host by a short room code over WebRTC, signalled through + public Nostr relays, with an optional password (CPace). Protocol: + spec/atyha-v1.md. + + This library is signalling only: it carries one SDP offer and one SDP + answer, both complete (no trickle ICE). The program makes the peer + connection with its own WebRTC stack. + + Everything is poll driven and single threaded: no thread is started, no + callback runs behind the program's back (the optional log callback runs + inside the poll that logs). Call atyha_host_poll() / atyha_joiner_poll() + every frame or tick until they return 0. An object is used by one thread + at a time; different objects are independent (no global state, apart + from libsodium's one-time initialisation, which atyha does itself). + + Strings are UTF-8 and NUL-terminated. Every string an event points to + stays valid until the next poll of the same object (or its destruction). */ +#ifndef ATYHA_H +#define ATYHA_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define ATYHA_VERSION "1.0.0" +#define ATYHA_PROTOCOL "atyha/1" +#define ATYHA_KIND 21490 +#define ATYHA_ALPHABET "ABCDEFHJKMNPRTUVWXYZ34579" +#define ATYHA_CODE_LEN 8 + +/* ------------------------------------------------------------------ codes */ + +/* a fresh code in canonical form ("HK4M7TRW"), NUL-terminated */ +void atyha_code_generate(char out[ATYHA_CODE_LEN + 1]); +/* what a person typed or pasted ("hk4m 7trw", "myapp://HK4M-7TRW") to its + canonical form; 1 when it is a code, 0 (out = "") when it is not */ +int atyha_code_parse(const char* text, char out[ATYHA_CODE_LEN + 1]); +/* "HK4M7TRW" -> "HK4M-7TRW" (anything else is copied, truncated to 9) */ +void atyha_code_display(const char* code, char out[ATYHA_CODE_LEN + 2]); +/* the room's Nostr topic, 64 lowercase hex characters */ +void atyha_topic(const char* app, const char* code, char out[65]); + +/* a monotonic clock in milliseconds, for programs without one at hand; any + monotonic millisecond clock may be passed to the polls instead */ +int64_t atyha_now_ms(void); + +/* -------------------------------------------------------------- ICE list */ + +/* an RTCIceServer: urls ("stun:host:port", "turn:host:port?transport=udp"), + and the TURN user and credential, or NULL */ +typedef struct atyha_ice_server { + const char* const* urls; + int url_count; + const char* username; + const char* credential; +} atyha_ice_server; + +/* one URL of an ICE server in libdatachannel's form, with the user and the + credential inside ("turn:user:pass@host:port?transport=udp", both + percent-encoded); returns the length it needs (snprintf-like), writes at + most cap bytes including the NUL */ +size_t atyha_ice_url_libdatachannel(const atyha_ice_server* server, int url_index, char* out, size_t cap); + +/* ------------------------------------------------------ the bus (section 8) */ + +/* What a session needs of a transport: publish a message (the JSON text of + spec section 6) to every other member of the topic, and hand over what + they publish. The Nostr relay pool is one (atyha_nostr_bus_open), the + in-memory hub another (tests); a program may write its own. */ +typedef enum atyha_bus_event_type { + ATYHA_BUS_NONE = 0, + ATYHA_BUS_READY, /* subscribed somewhere: what is published now is heard (once) */ + ATYHA_BUS_MESSAGE, /* text: a message another member published */ + ATYHA_BUS_LOG /* text: something for the log */ +} atyha_bus_event_type; + +typedef struct atyha_bus_event { + atyha_bus_event_type type; + const char* text; /* valid until the next poll of the bus */ +} atyha_bus_event; + +typedef struct atyha_bus atyha_bus; +struct atyha_bus { + void (*publish)(atyha_bus* bus, const char* message, int64_t now_ms); + /* 1 and *ev filled when something happened, 0 otherwise */ + int (*poll)(atyha_bus* bus, int64_t now_ms, atyha_bus_event* ev); + /* unsubscribes and frees */ + void (*destroy)(atyha_bus* bus); +}; + +/* opens a bus for one topic; the sessions call it once */ +typedef atyha_bus* (*atyha_bus_open_fn)(void* user, const char* topic); + +/* the in-memory hub: every bus opened on one hub hears the others of its + topic (delivered at their next poll). For tests. */ +typedef struct atyha_memory_hub atyha_memory_hub; +atyha_memory_hub* atyha_memory_hub_create(void); +/* only once every bus of the hub is destroyed */ +void atyha_memory_hub_destroy(atyha_memory_hub* hub); +/* an atyha_bus_open_fn; user is the hub */ +atyha_bus* atyha_memory_bus_open(void* hub, const char* topic); + +/* ------------------------------------------------ WebSocket backends (8) */ + +/* One WebSocket connection of a backend. The Nostr pool asks a backend for + connections, sends text frames on them and polls each for what happened. + Backends: atyha_curl.h (libcurl, native), atyha_emscripten.h (the + browser's WebSocket), or the program's own. */ +typedef struct atyha_ws atyha_ws; + +typedef enum atyha_ws_event_type { + ATYHA_WS_NONE = 0, + ATYHA_WS_OPEN, /* the connection is up: text can be sent */ + ATYHA_WS_TEXT, /* a whole text message: data, len (binary ones are dropped) */ + ATYHA_WS_CLOSED /* closed or failed (data: a reason, or NULL); no event after it */ +} atyha_ws_event_type; + +typedef struct atyha_ws_event { + atyha_ws_event_type type; + const char* data; /* valid until the next poll of this connection */ + size_t len; +} atyha_ws_event; + +typedef struct atyha_ws_backend atyha_ws_backend; +struct atyha_ws_backend { + /* starts connecting to url (wss://...); NULL when it cannot even start */ + atyha_ws* (*connect)(atyha_ws_backend* backend, const char* url); + /* queues one text message; 0 queued, -1 the connection is not usable */ + int (*send)(atyha_ws* ws, const char* text, size_t len); + /* 1 and *ev filled when something happened, 0 otherwise */ + int (*poll)(atyha_ws* ws, atyha_ws_event* ev); + /* closes (politely when it can) and frees the connection */ + void (*close)(atyha_ws* ws); + /* optional: drives the backend once per pool poll, before the polls */ + void (*update)(atyha_ws_backend* backend); +}; + +/* ------------------------------------------------- the Nostr bus (section 8) */ + +/* the relays of spec section 8, NULL-terminated */ +extern const char* const atyha_default_relays[]; + +typedef struct atyha_nostr_config { + atyha_ws_backend* ws; /* required; the program keeps it alive longer than the bus */ + const char* const* relays; /* NULL: atyha_default_relays */ + int relay_count; /* when relays is set */ +} atyha_nostr_config; + +/* a bus over Nostr relays (spec 8) with a fresh secp256k1 key; copies what + it needs of the config. NULL on a bad config or out of memory. */ +atyha_bus* atyha_nostr_bus_open(const atyha_nostr_config* config, const char* topic); + +/* ------------------------------------------------------------- sessions */ + +typedef enum atyha_error { + ATYHA_OK = 0, + ATYHA_ERR_BAD_CODE, /* not a room code */ + ATYHA_ERR_NO_RELAY, /* no relay could be reached in 10 s */ + ATYHA_ERR_NO_ROOM, /* nobody hosts that code (no pake by the deadline) */ + ATYHA_ERR_WRONG_PASSWORD, /* a host answered, but the password differs */ + ATYHA_ERR_REJECTED, /* the host's application refused: reason */ + ATYHA_ERR_NO_ANSWER, /* the host did not answer the offer by the deadline */ + ATYHA_ERR_CANCELLED /* atyha_joiner_cancel */ +} atyha_error; + +/* "bad_code", "no_relay", ... (the TS JoinError codes); "ok" for ATYHA_OK */ +const char* atyha_error_name(atyha_error error); + +typedef enum atyha_event_type { + ATYHA_EV_NONE = 0, + /* host: the room is reachable (a relay confirmed the subscription) */ + ATYHA_EV_OPEN, + /* host: a joiner with the right code and password sent its offer: sdp, + meta (its JSON object, or NULL), attempt (pass it to + atyha_host_answer / atyha_host_reject), joiner (its peer id) */ + ATYHA_EV_OFFER, + /* joiner: the host answered and the password is right: make the peer + connection (with ice when ice_count > 0, else your own servers), wait + for ICE gathering to complete, then atyha_joiner_set_offer. meta is + the host's JSON object or NULL. */ + ATYHA_EV_NEED_OFFER, + /* joiner: the host's answer sdp; the joiner is done */ + ATYHA_EV_ANSWER, + /* joiner: the join failed: error, reason (the host's text for + ATYHA_ERR_REJECTED, a sentence otherwise); the joiner is done */ + ATYHA_EV_ERROR, + /* either: a line for the log (text) */ + ATYHA_EV_LOG +} atyha_event_type; + +typedef struct atyha_event { + atyha_event_type type; + const char* sdp; + const char* meta; + const char* attempt; + const char* joiner; + const atyha_ice_server* ice; + int ice_count; + const char* ice_json; /* the host's "ice" array as JSON, or NULL */ + atyha_error error; + const char* reason; + const char* text; +} atyha_event; + +/* Where the session's messages travel. Exactly one of: bus_open (a custom + bus, such as atyha_memory_bus_open), or ws (the Nostr relays, through + that WebSocket backend). */ +typedef struct atyha_transport { + atyha_bus_open_fn bus_open; + void* bus_user; + atyha_ws_backend* ws; + const char* const* relays; /* for ws; NULL: atyha_default_relays */ + int relay_count; +} atyha_transport; + +/* ---- host (spec 7.2) ---- */ + +typedef struct atyha_host_config { + const char* app; /* required: 1..64 bytes */ + const char* code; /* NULL: a fresh one; else typed or canonical */ + const char* password; /* NULL or "": the code alone opens the room */ + const char* meta; /* NULL, or a JSON object (at most 2048 bytes) sent to every joiner */ + const atyha_ice_server* ice; /* sent to joiners so they use the same STUN/TURN */ + int ice_count; + int hello_budget; /* hellos answered per 60 s; 0: 20 */ + atyha_transport transport; +} atyha_host_config; + +typedef struct atyha_host atyha_host; + +/* NULL when the config is wrong (no app, bad code, meta not an object...) + or out of memory; the config is copied */ +atyha_host* atyha_host_create(const atyha_host_config* config); +/* the canonical code ("HK4M7TRW"); atyha_code_display for people */ +const char* atyha_host_code(const atyha_host* host); +int atyha_host_is_open(const atyha_host* host); +int atyha_host_poll(atyha_host* host, int64_t now_ms, atyha_event* ev); +/* the reply to an ATYHA_EV_OFFER, whenever the program has it (an answer + SDP with every candidate, or a refusal the joiner is shown). 0 sent; -1 + unknown or expired attempt, or already replied. The reply is sent at once + and again to every repeat of the same offer. */ +int atyha_host_answer(atyha_host* host, const char* attempt, const char* sdp); +int atyha_host_reject(atyha_host* host, const char* attempt, const char* reason); +/* closes the room (unsubscribes) and frees */ +void atyha_host_destroy(atyha_host* host); + +/* ---- joiner (spec 7.1) ---- */ + +typedef struct atyha_join_config { + const char* app; /* required */ + const char* code; /* as typed */ + const char* password; /* NULL or "" */ + const char* meta; /* NULL, or a JSON object sent with the offer */ + int timeout_ms; /* 0: 25000, the deadline for the pake and for the answer */ + atyha_transport transport; +} atyha_join_config; + +typedef struct atyha_joiner atyha_joiner; + +/* NULL only on a missing app or transport, or out of memory: a bad code is + reported by the first poll (ATYHA_ERR_BAD_CODE) */ +atyha_joiner* atyha_joiner_create(const atyha_join_config* config); +int atyha_joiner_poll(atyha_joiner* joiner, int64_t now_ms, atyha_event* ev); +/* the complete offer SDP, after ATYHA_EV_NEED_OFFER; 0 ok, -1 not now */ +int atyha_joiner_set_offer(atyha_joiner* joiner, const char* sdp); +/* the next poll reports ATYHA_ERR_CANCELLED (unless it already finished) */ +void atyha_joiner_cancel(atyha_joiner* joiner); +/* 1 once ANSWER or ERROR was reported */ +int atyha_joiner_done(const atyha_joiner* joiner); +void atyha_joiner_destroy(atyha_joiner* joiner); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/common/atyha/include/atyha_crypto.h b/common/atyha/include/atyha_crypto.h new file mode 100644 index 0000000..977dbad --- /dev/null +++ b/common/atyha/include/atyha_crypto.h @@ -0,0 +1,69 @@ +/* SPDX-License-Identifier: MIT + Copyright (c) 2026 ngspades contributors + + The protocol's building blocks (spec sections 1, 4, 5), exposed for tests + and for other implementations to check against. No I/O. The sessions of + atyha.h use them; most programs never need this header. + + Functions that produce bytes of variable length write at most cap bytes + and return the length the result needs (call with cap 0 to learn it). */ +#ifndef ATYHA_CRYPTO_H +#define ATYHA_CRYPTO_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* libsodium's initialisation (idempotent; every create of atyha.h calls it). + 0 ok, -1 libsodium could not start. */ +int atyha_crypto_init(void); + +/* lv_cat (spec 1): n parts, each preceded by its LEB128 length */ +size_t atyha_lv_cat(uint8_t* out, size_t cap, int n, const uint8_t* const* parts, const size_t* lens); + +/* PRS = lv_cat(code, password), CI = lv_cat("atyha/1", app) */ +size_t atyha_prs(const char* code, const char* password, uint8_t* out, size_t cap); +size_t atyha_ci(const char* app, uint8_t* out, size_t cap); + +/* CPace (draft-irtf-cfrg-cpace-21, CPACE-RISTR255-SHA512) */ +size_t atyha_cpace_generator_string(const uint8_t* prs, size_t prs_len, const uint8_t* ci, size_t ci_len, + const uint8_t* sid, size_t sid_len, uint8_t* out, size_t cap); +/* g = element_derivation(SHA-512(generator_string)); 0 ok */ +int atyha_cpace_generator(const uint8_t* prs, size_t prs_len, const uint8_t* ci, size_t ci_len, + const uint8_t* sid, size_t sid_len, uint8_t g[32]); +/* a secret scalar: 32 random bytes, bits above 252 cleared, never 0 */ +void atyha_cpace_sample_scalar(uint8_t y[32]); +/* Y = y * g; 0 ok, -1 when the result is the identity */ +int atyha_cpace_share(const uint8_t g[32], const uint8_t y[32], uint8_t Y[32]); +/* K = y * X; -1 when X does not decode or K is the identity (abort) */ +int atyha_cpace_scalar_mult_vfy(const uint8_t y[32], const uint8_t X[32], uint8_t K[32]); +/* ISK = SHA-512(lv_cat("CPaceRistretto255_ISK", sid, K) || lv_cat(Ya, "") || lv_cat(Yb, "")) */ +void atyha_cpace_isk(const uint8_t* sid, size_t sid_len, const uint8_t K[32], const uint8_t Ya[32], + const uint8_t Yb[32], uint8_t isk[64]); + +/* k_hj, k_jh = HKDF-SHA-256(ISK, salt sid, "atyha/1 host to joiner" / "... joiner to host", 32) */ +void atyha_keys(const uint8_t isk[64], const uint8_t* sid, size_t sid_len, uint8_t k_hj[32], uint8_t k_jh[32]); + +/* sealing (spec 5): ChaCha20-Poly1305, nonce 11 zero bytes || n, + AD = lv_cat("atyha/1", t, sid). seal returns the length of b64u(c || tag) + (out gets it NUL-terminated when cap > that). open returns the plaintext + length, or -1 when c does not decode or does not open; plain gets at most + cap bytes (plus a NUL when room is left). */ +size_t atyha_seal(const uint8_t key[32], int n, const char* t, const uint8_t sid[16], const uint8_t* plain, + size_t plain_len, char* out, size_t cap); +long atyha_open(const uint8_t key[32], int n, const char* t, const uint8_t sid[16], const char* c, uint8_t* plain, + size_t cap); + +/* base64url without padding (spec 1); decode refuses padding, characters + outside the alphabet and non-zero trailing bits: -1 */ +size_t atyha_b64u_encode(const uint8_t* in, size_t len, char* out, size_t cap); +long atyha_b64u_decode(const char* in, size_t in_len, uint8_t* out, size_t cap); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/common/atyha/include/atyha_curl.h b/common/atyha/include/atyha_curl.h new file mode 100644 index 0000000..6749f39 --- /dev/null +++ b/common/atyha/include/atyha_curl.h @@ -0,0 +1,34 @@ +/* SPDX-License-Identifier: MIT + Copyright (c) 2026 ngspades contributors + + The libcurl WebSocket backend (target atyha_curl): every connection is an + easy handle with CURLOPT_CONNECT_ONLY = 2 driven by one multi handle, so + connecting (DNS, TCP, TLS, the upgrade) never blocks the poll; then + curl_ws_send / curl_ws_recv, non-blocking. Needs libcurl 8.11 or later + built with WebSocket support ("ws"/"wss" in `curl -V`'s protocols). */ +#ifndef ATYHA_CURL_H +#define ATYHA_CURL_H + +#include "atyha.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct atyha_curl_options { + const char* ca_file; /* CURLOPT_CAINFO, or NULL for libcurl's default */ + const char* user_agent; /* NULL: "atyha/1" */ + int connect_timeout_ms; /* 0: 10000 */ +} atyha_curl_options; + +/* NULL when libcurl lacks WebSocket support or out of memory. Calls + curl_global_init(CURL_GLOBAL_DEFAULT) (libcurl's own global state). One + backend serves any number of buses; it must outlive them. */ +atyha_ws_backend* atyha_curl_backend_create(const atyha_curl_options* options); +void atyha_curl_backend_destroy(atyha_ws_backend* backend); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/common/atyha/include/atyha_emscripten.h b/common/atyha/include/atyha_emscripten.h new file mode 100644 index 0000000..272d0b6 --- /dev/null +++ b/common/atyha/include/atyha_emscripten.h @@ -0,0 +1,24 @@ +/* SPDX-License-Identifier: MIT + Copyright (c) 2026 ngspades contributors + + The browser's WebSocket as an atyha backend (Emscripten builds; compiled + into atyha when EMSCRIPTEN is set). Link with -lwebsocket.js. The + browser calls back on the main thread between frames; the callbacks only + queue, the polls drain. */ +#ifndef ATYHA_EMSCRIPTEN_H +#define ATYHA_EMSCRIPTEN_H + +#include "atyha.h" + +#ifdef __cplusplus +extern "C" { +#endif + +atyha_ws_backend* atyha_emscripten_backend_create(void); +void atyha_emscripten_backend_destroy(atyha_ws_backend* backend); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/common/atyha/include/atyha_libdatachannel.h b/common/atyha/include/atyha_libdatachannel.h new file mode 100644 index 0000000..ddbe4b4 --- /dev/null +++ b/common/atyha/include/atyha_libdatachannel.h @@ -0,0 +1,32 @@ +/* SPDX-License-Identifier: MIT + Copyright (c) 2026 ngspades contributors + + libdatachannel's own WebSocket client (rtc/rtc.h) as an atyha backend + (target atyha_libdatachannel), for programs that already link + libdatachannel (built with NO_WEBSOCKET OFF) and OpenSSL, and have no + libcurl with WebSocket support. libdatachannel calls back on its own + threads; those callbacks only queue under a lock, the polls drain. */ +#ifndef ATYHA_LIBDATACHANNEL_H +#define ATYHA_LIBDATACHANNEL_H + +#include "atyha.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct atyha_libdatachannel_options { + int disable_tls_verification; /* 0 (default): verify the relays' certificates */ + int connection_timeout_ms; /* 0: libdatachannel's default */ +} atyha_libdatachannel_options; + +/* options may be NULL. The program keeps libdatachannel initialised (it + calls rtcCleanup itself, after destroying the backend). */ +atyha_ws_backend* atyha_libdatachannel_backend_create(const atyha_libdatachannel_options* options); +void atyha_libdatachannel_backend_destroy(atyha_ws_backend* backend); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/common/atyha/src/crypto.c b/common/atyha/src/crypto.c new file mode 100644 index 0000000..6ec12b3 --- /dev/null +++ b/common/atyha/src/crypto.c @@ -0,0 +1,389 @@ +/* SPDX-License-Identifier: MIT + Copyright (c) 2026 ngspades contributors + + Codes (spec 3), topic (4), CPace, keys and sealing (5), on libsodium. */ +#include +#include + +#include + +#include "internal.h" +#include "atyha_crypto.h" + +int atyha_crypto_init(void) { return sodium_init() < 0 ? -1 : 0; } + +/* ---------------------------------------------------------------- lv_cat */ + +static size_t leb128(size_t n, uint8_t out[10]) +{ + size_t k = 0; + do { + uint8_t b = (uint8_t)(n & 0x7f); + n >>= 7; + if (n) b |= 0x80; + out[k++] = b; + } while (n); + return k; +} + +size_t atyha_lv_cat(uint8_t* out, size_t cap, int n, const uint8_t* const* parts, const size_t* lens) +{ + size_t at = 0; + int i; + for (i = 0; i < n; i++) { + uint8_t l[10]; + size_t k = leb128(lens[i], l), j; + for (j = 0; j < k; j++, at++) + if (at < cap) out[at] = l[j]; + for (j = 0; j < lens[i]; j++, at++) + if (at < cap) out[at] = parts[i][j]; + } + return at; +} + +static size_t lv_str2(const char* a, const char* b, uint8_t* out, size_t cap) +{ + const uint8_t* parts[2]; + size_t lens[2]; + parts[0] = (const uint8_t*)a; + parts[1] = (const uint8_t*)(b ? b : ""); + lens[0] = strlen(a); + lens[1] = strlen((const char*)parts[1]); + return atyha_lv_cat(out, cap, 2, parts, lens); +} + +size_t atyha_prs(const char* code, const char* password, uint8_t* out, size_t cap) +{ + return lv_str2(code, password, out, cap); +} + +size_t atyha_ci(const char* app, uint8_t* out, size_t cap) { return lv_str2(ATYHA_PROTOCOL, app, out, cap); } + +/* ----------------------------------------------------------------- codes */ + +void atyha_code_generate(char out[ATYHA_CODE_LEN + 1]) +{ + int n = 0; + atyha_crypto_init(); + while (n < ATYHA_CODE_LEN) { + uint8_t r[16]; + size_t i; + randombytes_buf(r, sizeof r); + for (i = 0; i < sizeof r && n < ATYHA_CODE_LEN; i++) + if (r[i] < 250) out[n++] = ATYHA_ALPHABET[r[i] % 25]; + sodium_memzero(r, sizeof r); + } + out[ATYHA_CODE_LEN] = 0; +} + +static int is_alpha(char c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); } + +/* the length of a White_Space character at s (UTF-8), or 0 */ +static size_t white_at(const char* s, const char* end) +{ + const unsigned char* u = (const unsigned char*)s; + size_t n = (size_t)(end - s); + unsigned cp; + if (!n) return 0; + if ((u[0] >= 0x09 && u[0] <= 0x0d) || u[0] == 0x20) return 1; + if (n >= 2 && u[0] == 0xc2 && (u[1] == 0x85 || u[1] == 0xa0)) return 2; + if (n >= 3 && (u[0] & 0xf0) == 0xe0 && (u[1] & 0xc0) == 0x80 && (u[2] & 0xc0) == 0x80) { + cp = (unsigned)(u[0] & 0x0f) << 12 | (unsigned)(u[1] & 0x3f) << 6 | (u[2] & 0x3f); + if (cp == 0x1680 || (cp >= 0x2000 && cp <= 0x200a) || cp == 0x2028 || cp == 0x2029 || cp == 0x202f || + cp == 0x205f || cp == 0x3000) + return 3; + } + return 0; +} + +int atyha_code_parse(const char* text, char out[ATYHA_CODE_LEN + 1]) +{ + const char* s = text; + const char* end; + int n = 0; + out[0] = 0; + if (!text) return 0; + /* step 0: surrounding white space (Unicode White_Space) */ + end = s + strlen(s); + for (;;) { + size_t k = white_at(s, end); + if (!k) break; + s += k; + } + while (end > s) { + size_t k = 0, back; + for (back = 1; back <= 3 && (size_t)(end - s) >= back && !k; back++) + if (white_at(end - back, end) == back) k = back; + if (!k) break; + end -= k; + } + /* a URI scheme: [A-Za-z][A-Za-z0-9+.-]*:// */ + if (is_alpha(*s)) { + const char* p = s + 1; + while (p < end && (is_alpha(*p) || (*p >= '0' && *p <= '9') || *p == '+' || *p == '.' || *p == '-')) p++; + if (end - p >= 3 && p[0] == ':' && p[1] == '/' && p[2] == '/') s = p + 3; + } + for (; s < end; s++) { + char c = *s; + if (c == '-' || c == ' ' || c == '\t') continue; + if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A'); + if (!c || !strchr(ATYHA_ALPHABET, c) || n == ATYHA_CODE_LEN) { + out[0] = 0; + return 0; + } + out[n++] = c; + } + if (n != ATYHA_CODE_LEN) { + out[0] = 0; + return 0; + } + out[n] = 0; + return 1; +} + +void atyha_code_display(const char* code, char out[ATYHA_CODE_LEN + 2]) +{ + if (code && strlen(code) == ATYHA_CODE_LEN) { + memcpy(out, code, 4); + out[4] = '-'; + memcpy(out + 5, code + 4, 4); + out[9] = 0; + } else { + size_t n = code ? strlen(code) : 0; + if (n > ATYHA_CODE_LEN + 1) n = ATYHA_CODE_LEN + 1; + if (n) memcpy(out, code, n); + out[n] = 0; + } +} + +void atyha_topic(const char* app, const char* code, char out[65]) +{ + const char* label = "atyha/1 topic"; + const uint8_t* parts[3]; + size_t lens[3], n; + uint8_t* buf; + uint8_t h[32]; + parts[0] = (const uint8_t*)label, lens[0] = strlen(label); + parts[1] = (const uint8_t*)app, lens[1] = strlen(app); + parts[2] = (const uint8_t*)code, lens[2] = strlen(code); + n = atyha_lv_cat(NULL, 0, 3, parts, lens); + buf = (uint8_t*)malloc(n); + if (!buf) { + out[0] = 0; + return; + } + atyha_lv_cat(buf, n, 3, parts, lens); + crypto_hash_sha256(h, buf, n); + free(buf); + nj_hex(h, 32, out); +} + +/* ----------------------------------------------------------------- CPace */ + +static const char DSI[] = "CPaceRistretto255"; +static const char DSI_ISK[] = "CPaceRistretto255_ISK"; +#define S_IN_BYTES 128 + +size_t atyha_cpace_generator_string(const uint8_t* prs, size_t prs_len, const uint8_t* ci, size_t ci_len, + const uint8_t* sid, size_t sid_len, uint8_t* out, size_t cap) +{ + uint8_t l[10]; + size_t dsi_len = sizeof DSI - 1; + size_t pre = leb128(prs_len, l) + prs_len + leb128(dsi_len, l) + dsi_len; + size_t zpad = S_IN_BYTES - 1 > pre ? S_IN_BYTES - 1 - pre : 0; + static const uint8_t zeros[S_IN_BYTES] = {0}; + const uint8_t* parts[5]; + size_t lens[5]; + parts[0] = (const uint8_t*)DSI, lens[0] = dsi_len; + parts[1] = prs, lens[1] = prs_len; + parts[2] = zeros, lens[2] = zpad; + parts[3] = ci, lens[3] = ci_len; + parts[4] = sid, lens[4] = sid_len; + return atyha_lv_cat(out, cap, 5, parts, lens); +} + +int atyha_cpace_generator(const uint8_t* prs, size_t prs_len, const uint8_t* ci, size_t ci_len, + const uint8_t* sid, size_t sid_len, uint8_t g[32]) +{ + size_t n = atyha_cpace_generator_string(prs, prs_len, ci, ci_len, sid, sid_len, NULL, 0); + uint8_t* s = (uint8_t*)malloc(n); + uint8_t h[64]; + if (!s) return -1; + atyha_cpace_generator_string(prs, prs_len, ci, ci_len, sid, sid_len, s, n); + crypto_hash_sha512(h, s, n); + sodium_memzero(s, n); /* holds the password */ + free(s); + /* RFC 9496 element derivation from 64 bytes */ + crypto_core_ristretto255_from_hash(g, h); + sodium_memzero(h, sizeof h); + return 0; +} + +void atyha_cpace_sample_scalar(uint8_t y[32]) +{ + for (;;) { + int i, zero = 1; + randombytes_buf(y, 32); + y[31] &= 0x0f; /* < 2^252 < the group order */ + for (i = 0; i < 32; i++) + if (y[i]) zero = 0; + if (!zero) return; + } +} + +/* libsodium's crypto_scalarmult_ristretto255 clears the scalar's top bit + (a no-op below 2^252), refuses an input that does not decode and a result + that is the identity: CPace's scalar_mult_vfy for our scalars */ +int atyha_cpace_share(const uint8_t g[32], const uint8_t y[32], uint8_t Y[32]) +{ + return crypto_scalarmult_ristretto255(Y, y, g) == 0 ? 0 : -1; +} + +int atyha_cpace_scalar_mult_vfy(const uint8_t y[32], const uint8_t X[32], uint8_t K[32]) +{ + if (y[31] & 0xf0) { + /* a scalar of ours never has these bits; reduce anything else */ + uint8_t wide[64] = {0}, r[32]; + int ok; + memcpy(wide, y, 32); + crypto_core_ristretto255_scalar_reduce(r, wide); + ok = crypto_scalarmult_ristretto255(K, r, X) == 0; + sodium_memzero(r, sizeof r); + return ok ? 0 : -1; + } + return crypto_scalarmult_ristretto255(K, y, X) == 0 ? 0 : -1; +} + +void atyha_cpace_isk(const uint8_t* sid, size_t sid_len, const uint8_t K[32], const uint8_t Ya[32], + const uint8_t Yb[32], uint8_t isk[64]) +{ + uint8_t buf[256]; + const uint8_t* parts[3]; + size_t lens[3], n; + crypto_hash_sha512_state st; + crypto_hash_sha512_init(&st); + parts[0] = (const uint8_t*)DSI_ISK, lens[0] = sizeof DSI_ISK - 1; + parts[1] = sid, lens[1] = sid_len; + parts[2] = K, lens[2] = 32; + n = atyha_lv_cat(NULL, 0, 3, parts, lens); + if (n <= sizeof buf) { + atyha_lv_cat(buf, sizeof buf, 3, parts, lens); + crypto_hash_sha512_update(&st, buf, n); + } else { + uint8_t l[10]; + int i; + for (i = 0; i < 3; i++) { + crypto_hash_sha512_update(&st, l, leb128(lens[i], l)); + crypto_hash_sha512_update(&st, parts[i], lens[i]); + } + } + /* transcript_ir: lv_cat(Ya, ADa) || lv_cat(Yb, ADb), AD empty */ + buf[0] = 32; + memcpy(buf + 1, Ya, 32); + buf[33] = 0; + buf[34] = 32; + memcpy(buf + 35, Yb, 32); + buf[67] = 0; + crypto_hash_sha512_update(&st, buf, 68); + crypto_hash_sha512_final(&st, isk); + sodium_memzero(buf, sizeof buf); +} + +/* ------------------------------------------------------------------ keys */ + +static void hkdf32(const uint8_t* ikm, size_t ikm_len, const uint8_t* salt, size_t salt_len, const char* info, + uint8_t out[32]) +{ + uint8_t prk[32]; + uint8_t one = 1; + crypto_auth_hmacsha256_state st; + /* extract: PRK = HMAC(salt, IKM) */ + crypto_auth_hmacsha256_init(&st, salt, salt_len); + crypto_auth_hmacsha256_update(&st, ikm, ikm_len); + crypto_auth_hmacsha256_final(&st, prk); + /* expand, one block: T(1) = HMAC(PRK, info || 0x01) */ + crypto_auth_hmacsha256_init(&st, prk, sizeof prk); + crypto_auth_hmacsha256_update(&st, (const uint8_t*)info, strlen(info)); + crypto_auth_hmacsha256_update(&st, &one, 1); + crypto_auth_hmacsha256_final(&st, out); + sodium_memzero(prk, sizeof prk); + sodium_memzero(&st, sizeof st); +} + +void atyha_keys(const uint8_t isk[64], const uint8_t* sid, size_t sid_len, uint8_t k_hj[32], uint8_t k_jh[32]) +{ + hkdf32(isk, 64, sid, sid_len, "atyha/1 host to joiner", k_hj); + hkdf32(isk, 64, sid, sid_len, "atyha/1 joiner to host", k_jh); +} + +/* --------------------------------------------------------------- sealing */ + +static size_t aad_of(const char* t, const uint8_t sid[16], uint8_t out[64]) +{ + const uint8_t* parts[3]; + size_t lens[3]; + parts[0] = (const uint8_t*)ATYHA_PROTOCOL, lens[0] = strlen(ATYHA_PROTOCOL); + parts[1] = (const uint8_t*)t, lens[1] = strlen(t); + parts[2] = sid, lens[2] = 16; + return atyha_lv_cat(out, 64, 3, parts, lens); +} + +size_t atyha_seal(const uint8_t key[32], int n, const char* t, const uint8_t sid[16], const uint8_t* plain, + size_t plain_len, char* out, size_t cap) +{ + uint8_t nonce[crypto_aead_chacha20poly1305_ietf_NPUBBYTES] = {0}; + uint8_t aad[64]; + size_t aad_len = aad_of(t, sid, aad); + size_t clen = plain_len + crypto_aead_chacha20poly1305_ietf_ABYTES; + size_t need = clen / 3 * 4 + (clen % 3 ? clen % 3 + 1 : 0); + uint8_t* c; + unsigned long long got = 0; + if (cap <= need) return need; + c = (uint8_t*)malloc(clen); + if (!c) return 0; + nonce[11] = (uint8_t)n; + crypto_aead_chacha20poly1305_ietf_encrypt(c, &got, plain, plain_len, aad, aad_len, NULL, nonce, key); + atyha_b64u_encode(c, (size_t)got, out, cap); + free(c); + return need; +} + +long atyha_open(const uint8_t key[32], int n, const char* t, const uint8_t sid[16], const char* c, uint8_t* plain, + size_t cap) +{ + uint8_t nonce[crypto_aead_chacha20poly1305_ietf_NPUBBYTES] = {0}; + uint8_t aad[64]; + size_t aad_len = aad_of(t, sid, aad), clen_max = strlen(c), mlen; + long clen; + uint8_t *cbuf, *m; + unsigned long long got = 0; + int ok; + cbuf = (uint8_t*)malloc(clen_max + 1); + if (!cbuf) return -1; + clen = atyha_b64u_decode(c, clen_max, cbuf, clen_max); + if (clen < (long)crypto_aead_chacha20poly1305_ietf_ABYTES) { + free(cbuf); + return -1; + } + mlen = (size_t)clen - crypto_aead_chacha20poly1305_ietf_ABYTES; + m = (uint8_t*)malloc(mlen + 1); + if (!m) { + free(cbuf); + return -1; + } + nonce[11] = (uint8_t)n; + ok = crypto_aead_chacha20poly1305_ietf_decrypt(m, &got, NULL, cbuf, (unsigned long long)clen, aad, aad_len, nonce, + key) == 0; + free(cbuf); + if (!ok) { + free(m); + return -1; + } + if (plain && cap) { + size_t k = got < cap ? (size_t)got : cap; + memcpy(plain, m, k); + if (k < cap) plain[k] = 0; + } + free(m); + return (long)got; +} diff --git a/common/atyha/src/internal.h b/common/atyha/src/internal.h new file mode 100644 index 0000000..1e70d91 --- /dev/null +++ b/common/atyha/src/internal.h @@ -0,0 +1,81 @@ +/* SPDX-License-Identifier: MIT + Copyright (c) 2026 ngspades contributors + + Internal helpers shared by the sources: a growable buffer, a strict JSON + parser and writer, hex. Not installed. */ +#ifndef ATYHA_INTERNAL_H +#define ATYHA_INTERNAL_H + +#include +#include + +#include "atyha.h" + +/* ---- growable byte buffer (always NUL-terminated when p != NULL) ---- */ +typedef struct nj_buf { + char* p; + size_t n, cap; + int oom; +} nj_buf; + +void nj_buf_reserve(nj_buf* b, size_t more); +void nj_buf_put(nj_buf* b, const void* data, size_t len); +void nj_buf_puts(nj_buf* b, const char* s); +void nj_buf_putc(nj_buf* b, char c); +void nj_buf_printf(nj_buf* b, const char* fmt, ...); +/* a JSON string literal of s (NIP-01 escaping: \" \\ \b \f \n \r \t, other + bytes below 0x20 as \u00xx, everything else verbatim) */ +void nj_buf_json_str(nj_buf* b, const char* s, size_t len); +/* hands the bytes over (the caller frees); "" when empty or out of memory */ +char* nj_buf_take(nj_buf* b); +void nj_buf_free(nj_buf* b); + +char* nj_strdup(const char* s); +void nj_hex(const uint8_t* in, size_t len, char* out); /* out: 2*len+1 */ +int nj_unhex(const char* in, size_t len, uint8_t* out); /* 0 ok, -1 not hex (len chars -> len/2 bytes) */ + +/* ---- strict JSON (RFC 8259) ---- */ +typedef enum nj_type { NJ_NULL, NJ_FALSE, NJ_TRUE, NJ_NUMBER, NJ_STRING, NJ_ARRAY, NJ_OBJECT } nj_type; + +typedef struct nj_value nj_value; +struct nj_value { + nj_type type; + const char* raw; /* the value's text in the source */ + size_t raw_len; + char* str; /* STRING: decoded, NUL-terminated */ + size_t len; + double num; /* NUMBER */ + nj_value* child; /* ARRAY elements, OBJECT members */ + nj_value* next; + size_t count; + char* key; /* when a member of an object */ + size_t key_len; +}; + +/* NULL when text is not exactly one JSON value (UTF-8 checked, depth <= 64) */ +nj_value* nj_parse(const char* text, size_t len); +void nj_free(nj_value* v); +/* the member named key (the last one when repeated), or NULL */ +nj_value* nj_get(const nj_value* obj, const char* key); +nj_value* nj_at(const nj_value* arr, size_t index); +/* a STRING member, or NULL */ +const char* nj_get_str(const nj_value* obj, const char* key); +/* 1 when text is one JSON object */ +int nj_is_object_text(const char* text); + +/* ---- nostr events (nostr.c), exposed for the tests ---- */ +typedef struct nj_nostr_key { + uint8_t seckey[32]; + char pubkey_hex[65]; + void* ctx; /* secp256k1_context* */ +} nj_nostr_key; + +int nj_nostr_key_new(nj_nostr_key* key); +void nj_nostr_key_free(nj_nostr_key* key); +/* the ["EVENT", {...}] text of a kind-21490 event; also its id (hex) */ +char* nj_nostr_event(const nj_nostr_key* key, const char* topic, const char* content, int64_t created_at, + char id_hex[65]); +/* the NIP-01 serialization [0,pubkey,created_at,kind,tags,content] */ +char* nj_nostr_serialize(const char* pubkey_hex, int64_t created_at, int kind, const char* topic, const char* content); + +#endif diff --git a/common/atyha/src/json.c b/common/atyha/src/json.c new file mode 100644 index 0000000..ea57fef --- /dev/null +++ b/common/atyha/src/json.c @@ -0,0 +1,360 @@ +/* SPDX-License-Identifier: MIT + Copyright (c) 2026 ngspades contributors + + A small strict JSON parser (RFC 8259): one value, no trailing text, UTF-8 + checked, \u escapes decoded (surrogate pairs joined, lone ones refused), + nesting at most 64 deep. Every value keeps its span in the source, so an + object can be handed on as the text it came as. */ +#include +#include + +#include "internal.h" + +#define MAX_DEPTH 64 + +typedef struct { + const char* s; + size_t n, i; + int depth; +} parser; + +static void skip_ws(parser* p) +{ + while (p->i < p->n) { + char c = p->s[p->i]; + if (c == ' ' || c == '\t' || c == '\n' || c == '\r') p->i++; + else break; + } +} + +static nj_value* new_value(nj_type t, parser* p) +{ + nj_value* v = (nj_value*)calloc(1, sizeof *v); + if (v) { + v->type = t; + v->raw = p->s + p->i; + } + return v; +} + +void nj_free(nj_value* v) +{ + while (v) { + nj_value* next = v->next; + nj_free(v->child); + free(v->str); + free(v->key); + free(v); + v = next; + } +} + +/* the length of the UTF-8 sequence at s (n bytes left), or 0 when invalid */ +static size_t utf8_len(const unsigned char* s, size_t n) +{ + unsigned c = s[0]; + if (c < 0x80) return 1; + if (c >= 0xc2 && c <= 0xdf) return n >= 2 && (s[1] & 0xc0) == 0x80 ? 2 : 0; + if (c >= 0xe0 && c <= 0xef) { + if (n < 3 || (s[1] & 0xc0) != 0x80 || (s[2] & 0xc0) != 0x80) return 0; + if (c == 0xe0 && s[1] < 0xa0) return 0; /* overlong */ + if (c == 0xed && s[1] >= 0xa0) return 0; /* surrogate */ + return 3; + } + if (c >= 0xf0 && c <= 0xf4) { + if (n < 4 || (s[1] & 0xc0) != 0x80 || (s[2] & 0xc0) != 0x80 || (s[3] & 0xc0) != 0x80) return 0; + if (c == 0xf0 && s[1] < 0x90) return 0; + if (c == 0xf4 && s[1] >= 0x90) return 0; + return 4; + } + return 0; +} + +static int hex4(parser* p, unsigned* out) +{ + unsigned v = 0; + int k; + if (p->i + 4 > p->n) return -1; + for (k = 0; k < 4; k++) { + char c = p->s[p->i++]; + v <<= 4; + if (c >= '0' && c <= '9') v |= (unsigned)(c - '0'); + else if (c >= 'a' && c <= 'f') v |= (unsigned)(c - 'a' + 10); + else if (c >= 'A' && c <= 'F') v |= (unsigned)(c - 'A' + 10); + else return -1; + } + *out = v; + return 0; +} + +static void put_utf8(nj_buf* b, unsigned cp) +{ + char u[4]; + if (cp < 0x80) { + u[0] = (char)cp; + nj_buf_put(b, u, 1); + } else if (cp < 0x800) { + u[0] = (char)(0xc0 | cp >> 6); + u[1] = (char)(0x80 | (cp & 63)); + nj_buf_put(b, u, 2); + } else if (cp < 0x10000) { + u[0] = (char)(0xe0 | cp >> 12); + u[1] = (char)(0x80 | (cp >> 6 & 63)); + u[2] = (char)(0x80 | (cp & 63)); + nj_buf_put(b, u, 3); + } else { + u[0] = (char)(0xf0 | cp >> 18); + u[1] = (char)(0x80 | (cp >> 12 & 63)); + u[2] = (char)(0x80 | (cp >> 6 & 63)); + u[3] = (char)(0x80 | (cp & 63)); + nj_buf_put(b, u, 4); + } +} + +/* at the opening quote; the decoded string in *out (malloc'd) */ +static int parse_string(parser* p, char** out, size_t* out_len) +{ + nj_buf b = {0}; + p->i++; /* " */ + nj_buf_reserve(&b, 16); + for (;;) { + unsigned char c; + if (p->i >= p->n) goto fail; + c = (unsigned char)p->s[p->i]; + if (c == '"') { + p->i++; + break; + } + if (c < 0x20) goto fail; + if (c == '\\') { + char e; + p->i++; + if (p->i >= p->n) goto fail; + e = p->s[p->i++]; + switch (e) { + case '"': nj_buf_putc(&b, '"'); break; + case '\\': nj_buf_putc(&b, '\\'); break; + case '/': nj_buf_putc(&b, '/'); break; + case 'b': nj_buf_putc(&b, '\b'); break; + case 'f': nj_buf_putc(&b, '\f'); break; + case 'n': nj_buf_putc(&b, '\n'); break; + case 'r': nj_buf_putc(&b, '\r'); break; + case 't': nj_buf_putc(&b, '\t'); break; + case 'u': { + unsigned cp, lo; + if (hex4(p, &cp)) goto fail; + if (cp >= 0xd800 && cp <= 0xdbff) { + if (p->i + 2 > p->n || p->s[p->i] != '\\' || p->s[p->i + 1] != 'u') goto fail; + p->i += 2; + if (hex4(p, &lo) || lo < 0xdc00 || lo > 0xdfff) goto fail; + cp = 0x10000 + ((cp - 0xd800) << 10) + (lo - 0xdc00); + } else if (cp >= 0xdc00 && cp <= 0xdfff) { + goto fail; + } + put_utf8(&b, cp); + break; + } + default: goto fail; + } + } else { + size_t k = utf8_len((const unsigned char*)p->s + p->i, p->n - p->i); + if (!k) goto fail; + nj_buf_put(&b, p->s + p->i, k); + p->i += k; + } + } + if (b.oom) goto fail; + *out_len = b.n; + *out = nj_buf_take(&b); + return *out ? 0 : -1; +fail: + nj_buf_free(&b); + return -1; +} + +static int parse_number(parser* p, double* out) +{ + size_t start = p->i; + double mant = 0, scale = 1; + int neg = 0, eneg = 0, ex = 0; + if (p->s[p->i] == '-') { + neg = 1; + p->i++; + } + if (p->i >= p->n) return -1; + if (p->s[p->i] == '0') { + p->i++; + } else if (p->s[p->i] >= '1' && p->s[p->i] <= '9') { + while (p->i < p->n && p->s[p->i] >= '0' && p->s[p->i] <= '9') mant = mant * 10 + (p->s[p->i++] - '0'); + } else { + return -1; + } + if (p->i < p->n && p->s[p->i] == '.') { + p->i++; + if (p->i >= p->n || p->s[p->i] < '0' || p->s[p->i] > '9') return -1; + while (p->i < p->n && p->s[p->i] >= '0' && p->s[p->i] <= '9') { + scale /= 10; + mant += (p->s[p->i++] - '0') * scale; + } + } + if (p->i < p->n && (p->s[p->i] == 'e' || p->s[p->i] == 'E')) { + p->i++; + if (p->i < p->n && (p->s[p->i] == '+' || p->s[p->i] == '-')) eneg = p->s[p->i++] == '-'; + if (p->i >= p->n || p->s[p->i] < '0' || p->s[p->i] > '9') return -1; + while (p->i < p->n && p->s[p->i] >= '0' && p->s[p->i] <= '9') { + if (ex < 100000) ex = ex * 10 + (p->s[p->i] - '0'); + p->i++; + } + while (ex-- > 0) { + mant = eneg ? mant / 10 : mant * 10; + if (mant == 0 || mant > 1e308) break; + } + } + (void)start; + *out = neg ? -mant : mant; + return 0; +} + +static nj_value* parse_value(parser* p); + +static int literal(parser* p, const char* word) +{ + size_t k = strlen(word); + if (p->n - p->i < k || memcmp(p->s + p->i, word, k)) return -1; + p->i += k; + return 0; +} + +static nj_value* parse_value(parser* p) +{ + nj_value* v = NULL; + char c; + skip_ws(p); + if (p->i >= p->n) return NULL; + c = p->s[p->i]; + if (c == '{' || c == '[') { + nj_value** tail; + int obj = c == '{'; + if (++p->depth > MAX_DEPTH) return NULL; + v = new_value(obj ? NJ_OBJECT : NJ_ARRAY, p); + if (!v) return NULL; + tail = &v->child; + p->i++; + skip_ws(p); + if (p->i < p->n && p->s[p->i] == (obj ? '}' : ']')) { + p->i++; + } else { + for (;;) { + nj_value* item; + char* key = NULL; + size_t key_len = 0; + if (obj) { + skip_ws(p); + if (p->i >= p->n || p->s[p->i] != '"' || parse_string(p, &key, &key_len)) goto fail; + skip_ws(p); + if (p->i >= p->n || p->s[p->i] != ':') { + free(key); + goto fail; + } + p->i++; + } + item = parse_value(p); + if (!item) { + free(key); + goto fail; + } + item->key = key; + item->key_len = key_len; + *tail = item; + tail = &item->next; + v->count++; + skip_ws(p); + if (p->i >= p->n) goto fail; + if (p->s[p->i] == ',') { + p->i++; + continue; + } + if (p->s[p->i] == (obj ? '}' : ']')) { + p->i++; + break; + } + goto fail; + } + } + p->depth--; + } else if (c == '"') { + v = new_value(NJ_STRING, p); + if (!v || parse_string(p, &v->str, &v->len)) goto fail; + } else if (c == '-' || (c >= '0' && c <= '9')) { + v = new_value(NJ_NUMBER, p); + if (!v || parse_number(p, &v->num)) goto fail; + } else if (c == 't') { + v = new_value(NJ_TRUE, p); + if (!v || literal(p, "true")) goto fail; + } else if (c == 'f') { + v = new_value(NJ_FALSE, p); + if (!v || literal(p, "false")) goto fail; + } else if (c == 'n') { + v = new_value(NJ_NULL, p); + if (!v || literal(p, "null")) goto fail; + } else { + return NULL; + } + v->raw_len = (size_t)(p->s + p->i - v->raw); + return v; +fail: + nj_free(v); + return NULL; +} + +nj_value* nj_parse(const char* text, size_t len) +{ + parser p; + nj_value* v; + if (!text) return NULL; + p.s = text; + p.n = len; + p.i = 0; + p.depth = 0; + v = parse_value(&p); + if (!v) return NULL; + skip_ws(&p); + if (p.i != p.n) { + nj_free(v); + return NULL; + } + return v; +} + +nj_value* nj_get(const nj_value* obj, const char* key) +{ + nj_value *c, *found = NULL; + size_t k; + if (!obj || obj->type != NJ_OBJECT) return NULL; + k = strlen(key); + for (c = obj->child; c; c = c->next) + if (c->key_len == k && !memcmp(c->key, key, k)) found = c; + return found; +} + +nj_value* nj_at(const nj_value* arr, size_t index) +{ + nj_value* c; + if (!arr || arr->type != NJ_ARRAY) return NULL; + for (c = arr->child; c && index; c = c->next) index--; + return c; +} + +const char* nj_get_str(const nj_value* obj, const char* key) +{ + nj_value* v = nj_get(obj, key); + return v && v->type == NJ_STRING ? v->str : NULL; +} + +int nj_is_object_text(const char* text) +{ + nj_value* v = text ? nj_parse(text, strlen(text)) : NULL; + int ok = v && v->type == NJ_OBJECT; + nj_free(v); + return ok; +} diff --git a/common/atyha/src/membus.c b/common/atyha/src/membus.c new file mode 100644 index 0000000..37a2d2e --- /dev/null +++ b/common/atyha/src/membus.c @@ -0,0 +1,112 @@ +/* SPDX-License-Identifier: MIT + Copyright (c) 2026 ngspades contributors + + The in-memory hub (tests): every bus of a hub hears the others of its + topic; a message is delivered at the receiver's next poll. */ +#include +#include + +#include "internal.h" + +typedef struct mem_msg { + char* text; + struct mem_msg* next; +} mem_msg; + +typedef struct mem_bus { + atyha_bus base; + atyha_memory_hub* hub; + char topic[65]; + int ready_sent; + mem_msg *head, *tail; + char* current; + struct mem_bus* next; +} mem_bus; + +struct atyha_memory_hub { + mem_bus* members; +}; + +atyha_memory_hub* atyha_memory_hub_create(void) { return (atyha_memory_hub*)calloc(1, sizeof(atyha_memory_hub)); } + +void atyha_memory_hub_destroy(atyha_memory_hub* hub) { free(hub); } + +static void mem_publish(atyha_bus* b, const char* message, int64_t now) +{ + mem_bus* me = (mem_bus*)b; + mem_bus* m; + (void)now; + for (m = me->hub->members; m; m = m->next) { + mem_msg* q; + if (m == me || strcmp(m->topic, me->topic)) continue; + q = (mem_msg*)calloc(1, sizeof *q); + if (!q) continue; + q->text = nj_strdup(message); + if (m->tail) m->tail->next = q; + else m->head = q; + m->tail = q; + } +} + +static int mem_poll(atyha_bus* b, int64_t now, atyha_bus_event* ev) +{ + mem_bus* me = (mem_bus*)b; + mem_msg* q; + (void)now; + free(me->current); + me->current = NULL; + if (!me->ready_sent) { + me->ready_sent = 1; + ev->type = ATYHA_BUS_READY; + ev->text = NULL; + return 1; + } + q = me->head; + if (!q) { + ev->type = ATYHA_BUS_NONE; + ev->text = NULL; + return 0; + } + me->head = q->next; + if (!me->head) me->tail = NULL; + me->current = q->text; + free(q); + ev->type = ATYHA_BUS_MESSAGE; + ev->text = me->current; + return 1; +} + +static void mem_destroy(atyha_bus* b) +{ + mem_bus* me = (mem_bus*)b; + mem_bus** pm; + for (pm = &me->hub->members; *pm; pm = &(*pm)->next) + if (*pm == me) { + *pm = me->next; + break; + } + while (me->head) { + mem_msg* q = me->head; + me->head = q->next; + free(q->text); + free(q); + } + free(me->current); + free(me); +} + +atyha_bus* atyha_memory_bus_open(void* hub, const char* topic) +{ + mem_bus* b; + if (!hub || !topic || strlen(topic) > 64) return NULL; + b = (mem_bus*)calloc(1, sizeof *b); + if (!b) return NULL; + b->base.publish = mem_publish; + b->base.poll = mem_poll; + b->base.destroy = mem_destroy; + b->hub = (atyha_memory_hub*)hub; + strcpy(b->topic, topic); + b->next = b->hub->members; + b->hub->members = b; + return &b->base; +} diff --git a/common/atyha/src/message.c b/common/atyha/src/message.c new file mode 100644 index 0000000..2c23d6d --- /dev/null +++ b/common/atyha/src/message.c @@ -0,0 +1,101 @@ +/* SPDX-License-Identifier: MIT + Copyright (c) 2026 ngspades contributors */ +#include +#include + +#include "internal.h" +#include "message.h" +#include "atyha_crypto.h" + +static const char* const NAMES[] = {"", "hello", "pake", "offer", "answer", "reject"}; + +const char* nj_msg_type_name(int t) { return t >= NJ_HELLO && t <= NJ_REJECT ? NAMES[t] : ""; } + +static int id16(const nj_value* v, char out[NJ_ID_B64], uint8_t bytes[16]) +{ + uint8_t tmp[16]; + if (!v || v->type != NJ_STRING || v->len != 22) return 0; + if (atyha_b64u_decode(v->str, v->len, bytes ? bytes : tmp, 16) != 16) return 0; + memcpy(out, v->str, 23); + return 1; +} + +int nj_msg_parse(const char* text, nj_msg* out) +{ + nj_value *m, *v, *t, *Y, *c; + int i, type = 0; + memset(out, 0, sizeof *out); + m = nj_parse(text, strlen(text)); + if (!m || m->type != NJ_OBJECT) goto fail; + v = nj_get(m, "v"); + if (!v || v->type != NJ_NUMBER || v->num != 1) goto fail; + t = nj_get(m, "t"); + if (!t || t->type != NJ_STRING) goto fail; + for (i = NJ_HELLO; i <= NJ_REJECT; i++) + if (!strcmp(t->str, NAMES[i])) type = i; + if (!type) goto fail; + out->t = type; + if (!id16(nj_get(m, "sid"), out->sid, out->sid_bytes) || !id16(nj_get(m, "from"), out->from, NULL)) goto fail; + if (type != NJ_HELLO && !id16(nj_get(m, "to"), out->to, NULL)) goto fail; + if (type == NJ_HELLO || type == NJ_PAKE) { + Y = nj_get(m, "Y"); + if (!Y || Y->type != NJ_STRING || atyha_b64u_decode(Y->str, Y->len, out->Y, 32) != 32) goto fail; + out->has_Y = 1; + } + if (type != NJ_HELLO) { + long n; + uint8_t* scratch; + c = nj_get(m, "c"); + if (!c || c->type != NJ_STRING) goto fail; + scratch = (uint8_t*)malloc(c->len + 1); + if (!scratch) goto fail; + n = atyha_b64u_decode(c->str, c->len, scratch, c->len); + free(scratch); + if (n < 0) goto fail; + out->c = nj_strdup(c->str); + if (!out->c) goto fail; + } + nj_free(m); + return 0; +fail: + nj_free(m); + nj_msg_free(out); + return -1; +} + +void nj_msg_free(nj_msg* m) +{ + free(m->c); + m->c = NULL; +} + +char* nj_msg_write(int t, const char* sid, const char* from, const char* to, const uint8_t* Y, const char* c) +{ + nj_buf b = {0}; + nj_buf_puts(&b, "{\"v\":1,\"t\":\""); + nj_buf_puts(&b, nj_msg_type_name(t)); + nj_buf_puts(&b, "\",\"sid\":\""); + nj_buf_puts(&b, sid); + nj_buf_puts(&b, "\",\"from\":\""); + nj_buf_puts(&b, from); + nj_buf_putc(&b, '"'); + if (to) { + nj_buf_puts(&b, ",\"to\":\""); + nj_buf_puts(&b, to); + nj_buf_putc(&b, '"'); + } + if (Y) { + char y64[44]; + atyha_b64u_encode(Y, 32, y64, sizeof y64); + nj_buf_puts(&b, ",\"Y\":\""); + nj_buf_puts(&b, y64); + nj_buf_putc(&b, '"'); + } + if (c) { + nj_buf_puts(&b, ",\"c\":\""); + nj_buf_puts(&b, c); + nj_buf_putc(&b, '"'); + } + nj_buf_putc(&b, '}'); + return nj_buf_take(&b); +} diff --git a/common/atyha/src/message.h b/common/atyha/src/message.h new file mode 100644 index 0000000..5a4f231 --- /dev/null +++ b/common/atyha/src/message.h @@ -0,0 +1,32 @@ +/* SPDX-License-Identifier: MIT + Copyright (c) 2026 ngspades contributors + + The messages of spec section 6: parse (checked field by field) and write. */ +#ifndef ATYHA_MESSAGE_H +#define ATYHA_MESSAGE_H + +#include + +enum { NJ_HELLO = 1, NJ_PAKE, NJ_OFFER, NJ_ANSWER, NJ_REJECT }; + +#define NJ_ID_B64 23 /* 16 bytes in b64u (22) + NUL */ + +typedef struct nj_msg { + int t; + char sid[NJ_ID_B64]; + uint8_t sid_bytes[16]; + char from[NJ_ID_B64]; + char to[NJ_ID_B64]; /* "" when absent */ + uint8_t Y[32]; + int has_Y; + char* c; /* malloc'd, or NULL */ +} nj_msg; + +const char* nj_msg_type_name(int t); +/* 0 ok (free with nj_msg_free), -1 not a message */ +int nj_msg_parse(const char* text, nj_msg* out); +void nj_msg_free(nj_msg* m); +/* the JSON text (malloc'd); to, Y and c may be NULL */ +char* nj_msg_write(int t, const char* sid, const char* from, const char* to, const uint8_t* Y, const char* c); + +#endif diff --git a/common/atyha/src/nostr.c b/common/atyha/src/nostr.c new file mode 100644 index 0000000..7fc5073 --- /dev/null +++ b/common/atyha/src/nostr.c @@ -0,0 +1,459 @@ +/* SPDX-License-Identifier: MIT + Copyright (c) 2026 ngspades contributors + + The Nostr transport (spec section 8): one room's topic on several public + relays at once, through any atyha_ws_backend. Publishes the messages as + ephemeral kind-21490 events (NIP-01) signed with BIP-340 by a key drawn + for this bus, and hands every new message of the topic over. */ +#include +#include +#include + +#include +#include +#include +#include + +#include "internal.h" +#include "atyha_crypto.h" + +#define SKEW_S 60 +#define SEEN_MAX 1024 +#define CONNECT_TIMEOUT_MS 15000 +#define RATE_LIMIT_WAIT_MS 60000 +#define BACKOFF_MAX_MS 30000 +#define BACKOFF_BASE_MS 2000 + +const char* const atyha_default_relays[] = { + "wss://nos.lol", + "wss://relay.primal.net", + "wss://relay.nostr.net", + "wss://relay.snort.social", + "wss://nostr.mom", + "wss://nostr.overmind.lol", + "wss://bucket.coracle.social", + NULL, +}; + +/* ------------------------------------------------------------ events */ + +int nj_nostr_key_new(nj_nostr_key* key) +{ + secp256k1_context* ctx; + secp256k1_keypair kp; + secp256k1_xonly_pubkey xpk; + uint8_t seed[32], pk[32]; + memset(key, 0, sizeof *key); + if (atyha_crypto_init()) return -1; + ctx = secp256k1_context_create(SECP256K1_CONTEXT_NONE); + if (!ctx) return -1; + randombytes_buf(seed, sizeof seed); + if (!secp256k1_context_randomize(ctx, seed)) { + secp256k1_context_destroy(ctx); + return -1; + } + do randombytes_buf(key->seckey, 32); + while (!secp256k1_keypair_create(ctx, &kp, key->seckey)); + secp256k1_keypair_xonly_pub(ctx, &xpk, NULL, &kp); + secp256k1_xonly_pubkey_serialize(ctx, pk, &xpk); + nj_hex(pk, 32, key->pubkey_hex); + sodium_memzero(&kp, sizeof kp); + key->ctx = ctx; + return 0; +} + +void nj_nostr_key_free(nj_nostr_key* key) +{ + if (key->ctx) secp256k1_context_destroy((secp256k1_context*)key->ctx); + sodium_memzero(key->seckey, sizeof key->seckey); + key->ctx = NULL; +} + +static void put_tags(nj_buf* b, const char* topic) +{ + nj_buf_puts(b, "[[\"x\","); + nj_buf_json_str(b, topic, strlen(topic)); + nj_buf_puts(b, "]]"); +} + +char* nj_nostr_serialize(const char* pubkey_hex, int64_t created_at, int kind, const char* topic, const char* content) +{ + nj_buf b = {0}; + nj_buf_puts(&b, "[0,\""); + nj_buf_puts(&b, pubkey_hex); + nj_buf_printf(&b, "\",%lld,%d,", (long long)created_at, kind); + put_tags(&b, topic); + nj_buf_putc(&b, ','); + nj_buf_json_str(&b, content, strlen(content)); + nj_buf_putc(&b, ']'); + return nj_buf_take(&b); +} + +char* nj_nostr_event(const nj_nostr_key* key, const char* topic, const char* content, int64_t created_at, + char id_hex[65]) +{ + secp256k1_keypair kp; + uint8_t id[32], sig[64], aux[32]; + char sig_hex[129]; + nj_buf b = {0}; + char* ser = nj_nostr_serialize(key->pubkey_hex, created_at, ATYHA_KIND, topic, content); + if (!ser) return NULL; + crypto_hash_sha256(id, (const uint8_t*)ser, strlen(ser)); + free(ser); + randombytes_buf(aux, sizeof aux); + if (!secp256k1_keypair_create((const secp256k1_context*)key->ctx, &kp, key->seckey) || + !secp256k1_schnorrsig_sign32((const secp256k1_context*)key->ctx, sig, id, &kp, aux)) { + sodium_memzero(&kp, sizeof kp); + return NULL; + } + sodium_memzero(&kp, sizeof kp); + nj_hex(id, 32, id_hex); + nj_hex(sig, 64, sig_hex); + nj_buf_puts(&b, "[\"EVENT\",{\"id\":\""); + nj_buf_puts(&b, id_hex); + nj_buf_puts(&b, "\",\"pubkey\":\""); + nj_buf_puts(&b, key->pubkey_hex); + nj_buf_printf(&b, "\",\"created_at\":%lld,\"kind\":%d,\"tags\":", (long long)created_at, ATYHA_KIND); + put_tags(&b, topic); + nj_buf_puts(&b, ",\"content\":"); + nj_buf_json_str(&b, content, strlen(content)); + nj_buf_puts(&b, ",\"sig\":\""); + nj_buf_puts(&b, sig_hex); + nj_buf_puts(&b, "\"}]"); + return nj_buf_take(&b); +} + +/* -------------------------------------------------------------- pool */ + +enum { R_IDLE, R_CONNECTING, R_OPEN, R_RETIRED }; + +typedef struct relay { + char* url; + atyha_ws* ws; + int state; + int attempt; + int64_t t_retry; + int64_t t_connect; + int retire; /* blocked: restricted: auth-required: pow: */ + int rate_limited; /* the next wait is 60 s */ +} relay; + +typedef struct bus_ev { + atyha_bus_event_type type; + char* text; + struct bus_ev* next; +} bus_ev; + +typedef struct nostr_bus { + atyha_bus base; + atyha_ws_backend* be; + relay* relays; + int n; + char topic[65]; + char sub[17]; + nj_nostr_key key; + uint8_t seen[SEEN_MAX][32]; + int seen_n, seen_at; + int ready; + bus_ev *head, *tail; + char* current; +} nostr_bus; + +static void push(nostr_bus* b, atyha_bus_event_type type, char* text /* owned */) +{ + bus_ev* e = (bus_ev*)calloc(1, sizeof *e); + if (!e) { + free(text); + return; + } + e->type = type; + e->text = text; + if (b->tail) b->tail->next = e; + else b->head = e; + b->tail = e; +} + +static void logf_(nostr_bus* b, const char* url, const char* what, const char* detail) +{ + nj_buf t = {0}; + nj_buf_puts(&t, url); + nj_buf_puts(&t, ": "); + nj_buf_puts(&t, what); + if (detail) nj_buf_puts(&t, detail); + push(b, ATYHA_BUS_LOG, nj_buf_take(&t)); +} + +static int starts(const char* s, const char* prefix) { return !strncmp(s, prefix, strlen(prefix)); } + +static void refusal(relay* r, const char* why) +{ + if (starts(why, "blocked:") || starts(why, "restricted:") || starts(why, "auth-required:") || starts(why, "pow:")) + r->retire = 1; + if (starts(why, "rate-limited:")) r->rate_limited = 1; +} + +static int seen(nostr_bus* b, const uint8_t id[32]) +{ + int i; + for (i = 0; i < b->seen_n; i++) + if (!memcmp(b->seen[i], id, 32)) return 1; + return 0; +} + +static void remember(nostr_bus* b, const uint8_t id[32]) +{ + memcpy(b->seen[b->seen_at], id, 32); + b->seen_at = (b->seen_at + 1) % SEEN_MAX; + if (b->seen_n < SEEN_MAX) b->seen_n++; +} + +static void on_event(nostr_bus* b, const nj_value* ev) +{ + const nj_value *id, *content, *kind, *tags, *created, *pubkey, *t; + uint8_t idb[32]; + int has_topic = 0; + double now_s; + if (!ev || ev->type != NJ_OBJECT) return; + id = nj_get(ev, "id"); + content = nj_get(ev, "content"); + kind = nj_get(ev, "kind"); + if (!id || id->type != NJ_STRING || id->len != 64 || nj_unhex(id->str, 64, idb)) return; + if (!content || content->type != NJ_STRING) return; + if (!kind || kind->type != NJ_NUMBER || kind->num != ATYHA_KIND || seen(b, idb)) return; + tags = nj_get(ev, "tags"); + if (!tags || tags->type != NJ_ARRAY) return; + for (t = tags->child; t; t = t->next) { + const nj_value* k = nj_at(t, 0); + const nj_value* v = nj_at(t, 1); + if (k && v && k->type == NJ_STRING && v->type == NJ_STRING && !strcmp(k->str, "x") && + !strcmp(v->str, b->topic)) + has_topic = 1; + } + if (!has_topic) return; + created = nj_get(ev, "created_at"); + now_s = (double)time(NULL); + if (!created || created->type != NJ_NUMBER || created->num - now_s > SKEW_S || now_s - created->num > SKEW_S) return; + remember(b, idb); + pubkey = nj_get(ev, "pubkey"); + if (pubkey && pubkey->type == NJ_STRING && !strcmp(pubkey->str, b->key.pubkey_hex)) return; /* our own */ + push(b, ATYHA_BUS_MESSAGE, nj_strdup(content->str)); +} + +static void drop(nostr_bus* b, relay* r, int64_t now) +{ + int64_t wait; + if (r->ws) b->be->close(r->ws); + r->ws = NULL; + if (r->retire) { + r->state = R_RETIRED; + logf_(b, r->url, "dropped for this session", NULL); + return; + } + if (r->rate_limited) { + wait = RATE_LIMIT_WAIT_MS; + } else { + wait = (int64_t)BACKOFF_BASE_MS << (r->attempt < 4 ? r->attempt : 4); + if (wait > BACKOFF_MAX_MS) wait = BACKOFF_MAX_MS; + } + r->rate_limited = 0; + r->attempt++; + r->state = R_IDLE; + r->t_retry = now + wait; +} + +static void on_text(nostr_bus* b, relay* r, const char* text, size_t len, int64_t now) +{ + nj_value* m = nj_parse(text, len); + const char* type; + if (!m || m->type != NJ_ARRAY || !m->child || m->child->type != NJ_STRING) { + nj_free(m); + return; + } + type = m->child->str; + if (!strcmp(type, "EOSE")) { + const char* sub = nj_at(m, 1) && nj_at(m, 1)->type == NJ_STRING ? nj_at(m, 1)->str : ""; + if (!strcmp(sub, b->sub)) { + logf_(b, r->url, "subscribed", NULL); + if (!b->ready) { + b->ready = 1; + push(b, ATYHA_BUS_READY, NULL); + } + } + } else if (!strcmp(type, "EVENT")) { + const nj_value* sub = nj_at(m, 1); + if (sub && sub->type == NJ_STRING && !strcmp(sub->str, b->sub)) on_event(b, nj_at(m, 2)); + } else if (!strcmp(type, "OK")) { + const nj_value* ok = nj_at(m, 2); + const nj_value* why = nj_at(m, 3); + if (ok && ok->type == NJ_FALSE) { + const char* w = why && why->type == NJ_STRING ? why->str : ""; + logf_(b, r->url, "refused: ", w); + refusal(r, w); + /* rate-limited: away 60 s; blocked and the like: for the session */ + if (r->retire || r->rate_limited) drop(b, r, now); + } + } else if (!strcmp(type, "CLOSED")) { + const nj_value* sub = nj_at(m, 1); + const nj_value* why = nj_at(m, 2); + if (sub && sub->type == NJ_STRING && !strcmp(sub->str, b->sub)) { + const char* w = why && why->type == NJ_STRING ? why->str : ""; + logf_(b, r->url, "subscription closed: ", w); + refusal(r, w); + drop(b, r, now); + } + } + nj_free(m); +} + +static void send_req(nostr_bus* b, relay* r) +{ + nj_buf t = {0}; + nj_buf_puts(&t, "[\"REQ\",\""); + nj_buf_puts(&t, b->sub); + nj_buf_printf(&t, "\",{\"kinds\":[%d],\"#x\":[\"%s\"],\"since\":%lld}]", ATYHA_KIND, b->topic, + (long long)time(NULL) - SKEW_S); + if (t.p) b->be->send(r->ws, t.p, t.n); + nj_buf_free(&t); +} + +static void pump_relay(nostr_bus* b, relay* r, int64_t now) +{ + atyha_ws_event ev; + int guard = 0; + if (r->state == R_IDLE && now >= r->t_retry) { + r->ws = b->be->connect(b->be, r->url); + if (!r->ws) { + logf_(b, r->url, "cannot connect", NULL); + drop(b, r, now); + return; + } + r->state = R_CONNECTING; + r->t_connect = now; + } + while (r->ws && guard++ < 256 && b->be->poll(r->ws, &ev)) { + if (ev.type == ATYHA_WS_OPEN) { + r->state = R_OPEN; + r->attempt = 0; + send_req(b, r); + } else if (ev.type == ATYHA_WS_TEXT) { + on_text(b, r, ev.data, ev.len, now); + } else if (ev.type == ATYHA_WS_CLOSED) { + logf_(b, r->url, "closed", ev.data ? (ev.data[0] ? ev.data : NULL) : NULL); + drop(b, r, now); + } + } + if (r->state == R_CONNECTING && now - r->t_connect > CONNECT_TIMEOUT_MS) { + logf_(b, r->url, "connection timed out", NULL); + drop(b, r, now); + } +} + +static int nostr_poll(atyha_bus* base, int64_t now, atyha_bus_event* ev) +{ + nostr_bus* b = (nostr_bus*)base; + bus_ev* e; + int i; + free(b->current); + b->current = NULL; + if (!b->head) { + if (b->be->update) b->be->update(b->be); + for (i = 0; i < b->n; i++) + if (b->relays[i].state != R_RETIRED) pump_relay(b, &b->relays[i], now); + } + e = b->head; + if (!e) { + ev->type = ATYHA_BUS_NONE; + ev->text = NULL; + return 0; + } + b->head = e->next; + if (!b->head) b->tail = NULL; + b->current = e->text; + ev->type = e->type; + ev->text = e->text; + free(e); + return 1; +} + +static void nostr_publish(atyha_bus* base, const char* message, int64_t now) +{ + nostr_bus* b = (nostr_bus*)base; + char id[65]; + char* text = nj_nostr_event(&b->key, b->topic, message, (int64_t)time(NULL), id); + int i; + (void)now; + if (!text) return; + for (i = 0; i < b->n; i++) + if (b->relays[i].state == R_OPEN && b->relays[i].ws && !b->be->send(b->relays[i].ws, text, strlen(text))) + continue; + free(text); +} + +static void nostr_destroy(atyha_bus* base) +{ + nostr_bus* b = (nostr_bus*)base; + int i; + char close_msg[40]; + strcpy(close_msg, "[\"CLOSE\",\""); + strcat(close_msg, b->sub); + strcat(close_msg, "\"]"); + for (i = 0; i < b->n; i++) { + relay* r = &b->relays[i]; + if (r->ws) { + if (r->state == R_OPEN) b->be->send(r->ws, close_msg, strlen(close_msg)); + b->be->close(r->ws); + } + free(r->url); + } + free(b->relays); + while (b->head) { + bus_ev* e = b->head; + b->head = e->next; + free(e->text); + free(e); + } + free(b->current); + nj_nostr_key_free(&b->key); + free(b); +} + +atyha_bus* atyha_nostr_bus_open(const atyha_nostr_config* cfg, const char* topic) +{ + nostr_bus* b; + const char* const* urls; + int n, i; + uint8_t sub[8]; + if (!cfg || !cfg->ws || !cfg->ws->connect || !cfg->ws->send || !cfg->ws->poll || !cfg->ws->close || !topic || + strlen(topic) > 64) + return NULL; + urls = cfg->relays ? cfg->relays : atyha_default_relays; + if (cfg->relays) n = cfg->relay_count; + else + for (n = 0; urls[n]; n++) {} + if (n <= 0) return NULL; + b = (nostr_bus*)calloc(1, sizeof *b); + if (!b) return NULL; + if (nj_nostr_key_new(&b->key)) { + free(b); + return NULL; + } + b->base.publish = nostr_publish; + b->base.poll = nostr_poll; + b->base.destroy = nostr_destroy; + b->be = cfg->ws; + strcpy(b->topic, topic); + randombytes_buf(sub, sizeof sub); + nj_hex(sub, sizeof sub, b->sub); + b->relays = (relay*)calloc((size_t)n, sizeof *b->relays); + if (!b->relays) { + nostr_destroy(&b->base); + return NULL; + } + b->n = n; + for (i = 0; i < n; i++) { + b->relays[i].url = nj_strdup(urls[i]); + b->relays[i].state = b->relays[i].url ? R_IDLE : R_RETIRED; + b->relays[i].t_retry = INT64_MIN; + } + return &b->base; +} diff --git a/common/atyha/src/session.c b/common/atyha/src/session.c new file mode 100644 index 0000000..5cde974 --- /dev/null +++ b/common/atyha/src/session.c @@ -0,0 +1,920 @@ +/* SPDX-License-Identifier: MIT + Copyright (c) 2026 ngspades contributors + + The exchange (spec section 7) over any atyha_bus: the host, which answers + hellos and hands offers to the program, and the joiner, which turns a code + and a password into the host's answer SDP. No I/O here: the bus does it, + and time is what the program passes to the polls. */ +#include +#include + +#include + +#include "internal.h" +#include "message.h" +#include "atyha_crypto.h" + +#define RETRY_MS 2000 +#define DEFAULT_DEADLINE_MS 25000 +#define NO_RELAY_MS 10000 +#define WRONG_PASSWORD_WAIT_MS 4000 +#define ATTEMPT_KEEP_MS 60000 +#define ATTEMPT_PENDING_KEEP_MS 300000 +#define HELLO_WINDOW_MS 60000 +#define DEFAULT_HELLO_BUDGET 20 +#define MAX_META 2048 +#define MAX_BUS_EVENTS_PER_POLL 512 + +/* ------------------------------------------------------------ helpers */ + +typedef struct nj_ice_list { + atyha_ice_server* servers; + int count; + char* json; +} nj_ice_list; + +static void ice_list_free(nj_ice_list* l) +{ + int i, k; + for (i = 0; i < l->count; i++) { + for (k = 0; k < l->servers[i].url_count; k++) free((char*)l->servers[i].urls[k]); + free((void*)l->servers[i].urls); + free((char*)l->servers[i].username); + free((char*)l->servers[i].credential); + } + free(l->servers); + free(l->json); + memset(l, 0, sizeof *l); +} + +/* an "ice" array (RTCIceServer objects) to C; entries without a usable url are skipped */ +static void ice_list_from_json(nj_ice_list* l, const nj_value* arr) +{ + const nj_value* e; + memset(l, 0, sizeof *l); + if (!arr || arr->type != NJ_ARRAY || !arr->count) return; + l->servers = (atyha_ice_server*)calloc(arr->count, sizeof *l->servers); + if (!l->servers) return; + l->json = (char*)malloc(arr->raw_len + 1); + if (l->json) { + memcpy(l->json, arr->raw, arr->raw_len); + l->json[arr->raw_len] = 0; + } + for (e = arr->child; e; e = e->next) { + const nj_value* urls = nj_get(e, "urls"); + const char* user = nj_get_str(e, "username"); + const char* cred = nj_get_str(e, "credential"); + atyha_ice_server* s = &l->servers[l->count]; + const char** list; + int n = 0; + if (!urls) continue; + if (urls->type == NJ_STRING) { + list = (const char**)calloc(1, sizeof *list); + if (!list) continue; + list[n++] = nj_strdup(urls->str); + } else if (urls->type == NJ_ARRAY && urls->count) { + const nj_value* u; + list = (const char**)calloc(urls->count, sizeof *list); + if (!list) continue; + for (u = urls->child; u; u = u->next) + if (u->type == NJ_STRING) list[n++] = nj_strdup(u->str); + } else { + continue; + } + if (!n) { + free((void*)list); + continue; + } + s->urls = list; + s->url_count = n; + s->username = user ? nj_strdup(user) : NULL; + s->credential = cred ? nj_strdup(cred) : NULL; + l->count++; + } +} + +/* config ICE servers to their JSON array text */ +static char* ice_to_json(const atyha_ice_server* ice, int count) +{ + nj_buf b = {0}; + int i, k; + nj_buf_putc(&b, '['); + for (i = 0; i < count; i++) { + if (i) nj_buf_putc(&b, ','); + nj_buf_puts(&b, "{\"urls\":"); + if (ice[i].url_count == 1) { + nj_buf_json_str(&b, ice[i].urls[0], strlen(ice[i].urls[0])); + } else { + nj_buf_putc(&b, '['); + for (k = 0; k < ice[i].url_count; k++) { + if (k) nj_buf_putc(&b, ','); + nj_buf_json_str(&b, ice[i].urls[k], strlen(ice[i].urls[k])); + } + nj_buf_putc(&b, ']'); + } + if (ice[i].username) { + nj_buf_puts(&b, ",\"username\":"); + nj_buf_json_str(&b, ice[i].username, strlen(ice[i].username)); + } + if (ice[i].credential) { + nj_buf_puts(&b, ",\"credential\":"); + nj_buf_json_str(&b, ice[i].credential, strlen(ice[i].credential)); + } + nj_buf_putc(&b, '}'); + } + nj_buf_putc(&b, ']'); + return nj_buf_take(&b); +} + +static int pct_unreserved(unsigned char c) +{ + return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '.' || + c == '_' || c == '~'; +} + +static void put_pct(nj_buf* b, const char* s) +{ + static const char hexd[] = "0123456789ABCDEF"; + for (; *s; s++) { + unsigned char c = (unsigned char)*s; + if (pct_unreserved(c)) { + nj_buf_putc(b, (char)c); + } else { + char e[3]; + e[0] = '%', e[1] = hexd[c >> 4], e[2] = hexd[c & 15]; + nj_buf_put(b, e, 3); + } + } +} + +size_t atyha_ice_url_libdatachannel(const atyha_ice_server* s, int index, char* out, size_t cap) +{ + nj_buf b = {0}; + const char *url, *colon; + size_t n; + if (!s || index < 0 || index >= s->url_count) { + if (cap) out[0] = 0; + return 0; + } + url = s->urls[index]; + colon = strchr(url, ':'); + if (colon && s->username && s->credential && !strchr(colon, '@')) { + const char* rest = colon + 1; + while (*rest == '/') rest++; + nj_buf_put(&b, url, (size_t)(colon - url + 1)); + put_pct(&b, s->username); + nj_buf_putc(&b, ':'); + put_pct(&b, s->credential); + nj_buf_putc(&b, '@'); + nj_buf_puts(&b, rest); + } else { + nj_buf_puts(&b, url); + } + if (b.oom) { + nj_buf_free(&b); + if (cap) out[0] = 0; + return 0; + } + n = b.n; + if (cap) { + size_t k = n < cap - 1 ? n : cap - 1; + memcpy(out, b.p, k); + out[k] = 0; + } + nj_buf_free(&b); + return n; +} + +static char* seal_text(const uint8_t key[32], int n, int t, const uint8_t sid[16], const char* plain) +{ + size_t len = strlen(plain); + size_t need = atyha_seal(key, n, nj_msg_type_name(t), sid, (const uint8_t*)plain, len, NULL, 0); + char* out = (char*)malloc(need + 1); + if (!out) return NULL; + atyha_seal(key, n, nj_msg_type_name(t), sid, (const uint8_t*)plain, len, out, need + 1); + return out; +} + +/* the sealed payload as a JSON object, or NULL; *keep holds the plaintext + the values point into (free it with close_object after nj_free) */ +static void close_object(nj_value* v, uint8_t* keep) +{ + nj_free(v); + if (keep) { + sodium_memzero(keep, strlen((const char*)keep)); + free(keep); + } +} + +static nj_value* open_object(const uint8_t key[32], int n, int t, const uint8_t sid[16], const char* c, uint8_t** keep) +{ + size_t cap = strlen(c); + uint8_t* plain = (uint8_t*)malloc(cap + 1); + long got; + nj_value* v = NULL; + if (!plain) return NULL; + got = atyha_open(key, n, nj_msg_type_name(t), sid, c, plain, cap + 1); + if (got >= 0) { + v = nj_parse((const char*)plain, (size_t)got); + if (v && v->type != NJ_OBJECT) { + nj_free(v); + v = NULL; + } + } + if (!v) { + sodium_memzero(plain, cap + 1); + free(plain); + plain = NULL; + } + *keep = plain; + return v; +} + +static char* raw_text(const nj_value* v) +{ + char* s; + if (!v) return NULL; + s = (char*)malloc(v->raw_len + 1); + if (!s) return NULL; + memcpy(s, v->raw, v->raw_len); + s[v->raw_len] = 0; + return s; +} + +static void random_id(char out[NJ_ID_B64]) +{ + uint8_t r[16]; + randombytes_buf(r, sizeof r); + atyha_b64u_encode(r, 16, out, NJ_ID_B64); +} + +/* ---- event queue: each event owns its strings until the next poll ---- */ + +typedef struct nj_qev { + atyha_event ev; + char* owned[6]; + nj_ice_list ice; + struct nj_qev* next; +} nj_qev; + +typedef struct nj_queue { + nj_qev *head, *tail, *current; +} nj_queue; + +static void qev_free(nj_qev* q) +{ + int i; + if (!q) return; + for (i = 0; i < 6; i++) free(q->owned[i]); + ice_list_free(&q->ice); + free(q); +} + +static nj_qev* queue_push(nj_queue* q, atyha_event_type type) +{ + nj_qev* e = (nj_qev*)calloc(1, sizeof *e); + if (!e) return NULL; + e->ev.type = type; + if (q->tail) q->tail->next = e; + else q->head = e; + q->tail = e; + return e; +} + +/* a string the event owns (copied); NULL stays NULL */ +static const char* qev_own(nj_qev* e, int slot, const char* s) +{ + if (!e || !s) return NULL; + e->owned[slot] = nj_strdup(s); + return e->owned[slot]; +} + +static int queue_pop(nj_queue* q, atyha_event* ev) +{ + qev_free(q->current); + q->current = NULL; + if (!q->head) { + memset(ev, 0, sizeof *ev); + return 0; + } + q->current = q->head; + q->head = q->head->next; + if (!q->head) q->tail = NULL; + *ev = q->current->ev; + return 1; +} + +static void queue_free(nj_queue* q) +{ + nj_qev* e = q->head; + while (e) { + nj_qev* n = e->next; + qev_free(e); + e = n; + } + qev_free(q->current); + memset(q, 0, sizeof *q); +} + +static void queue_log(nj_queue* q, const char* text) +{ + nj_qev* e = queue_push(q, ATYHA_EV_LOG); + if (e) e->ev.text = qev_own(e, 0, text); +} + +/* ---- transport ---- */ + +static atyha_bus* open_transport(const atyha_transport* tr, const char* topic) +{ + if (tr->bus_open) return tr->bus_open(tr->bus_user, topic); + if (tr->ws) { + atyha_nostr_config nc; + nc.ws = tr->ws; + nc.relays = tr->relays; + nc.relay_count = tr->relay_count; + return atyha_nostr_bus_open(&nc, topic); + } + return NULL; +} + +static int meta_ok(const char* meta) { return !meta || (strlen(meta) <= MAX_META && nj_is_object_text(meta)); } + +static int app_ok(const char* app) { return app && *app && strlen(app) <= 64; } + +const char* atyha_error_name(atyha_error e) +{ + switch (e) { + case ATYHA_OK: return "ok"; + case ATYHA_ERR_BAD_CODE: return "bad_code"; + case ATYHA_ERR_NO_RELAY: return "no_relay"; + case ATYHA_ERR_NO_ROOM: return "no_room"; + case ATYHA_ERR_WRONG_PASSWORD: return "wrong_password"; + case ATYHA_ERR_REJECTED: return "rejected"; + case ATYHA_ERR_NO_ANSWER: return "no_answer"; + case ATYHA_ERR_CANCELLED: return "cancelled"; + } + return "unknown"; +} + +/* ================================================================ host */ + +typedef struct nj_attempt { + char sid[NJ_ID_B64]; + uint8_t sid_bytes[16]; + char joiner[NJ_ID_B64]; + uint8_t k_hj[32], k_jh[32]; + char* pake; + char* reply; + int pending; /* handed to the program, no reply yet */ + int64_t at; + struct nj_attempt* next; +} nj_attempt; + +struct atyha_host { + char* app; + char code[ATYHA_CODE_LEN + 1]; + char* password; + char* payload; /* the pake's sealed payload, {"ice":[...],"meta":{...}} */ + char id[NJ_ID_B64]; + int budget; + int64_t* hellos; /* ring of the last hello times */ + int hello_head, hello_n; + atyha_bus* bus; + int open; + int64_t now; /* of the last poll */ + nj_attempt* attempts; + nj_queue q; +}; + +static void attempt_free(nj_attempt* a) +{ + sodium_memzero(a->k_hj, 32); + sodium_memzero(a->k_jh, 32); + free(a->pake); + free(a->reply); + free(a); +} + +atyha_host* atyha_host_create(const atyha_host_config* cfg) +{ + atyha_host* h; + nj_buf p = {0}; + char topic[65]; + if (!cfg || !app_ok(cfg->app) || !meta_ok(cfg->meta) || atyha_crypto_init()) return NULL; + if (cfg->ice_count < 0 || (cfg->ice_count && !cfg->ice)) return NULL; + h = (atyha_host*)calloc(1, sizeof *h); + if (!h) return NULL; + if (cfg->code) { + if (!atyha_code_parse(cfg->code, h->code)) { + free(h); + return NULL; + } + } else { + atyha_code_generate(h->code); + } + h->app = nj_strdup(cfg->app); + h->password = nj_strdup(cfg->password ? cfg->password : ""); + random_id(h->id); + h->budget = cfg->hello_budget > 0 ? cfg->hello_budget : DEFAULT_HELLO_BUDGET; + h->hellos = (int64_t*)calloc((size_t)h->budget, sizeof *h->hellos); + nj_buf_putc(&p, '{'); + if (cfg->ice_count > 0) { + char* ice = ice_to_json(cfg->ice, cfg->ice_count); + nj_buf_puts(&p, "\"ice\":"); + nj_buf_puts(&p, ice ? ice : "[]"); + free(ice); + } + if (cfg->meta) { + if (cfg->ice_count > 0) nj_buf_putc(&p, ','); + nj_buf_puts(&p, "\"meta\":"); + nj_buf_puts(&p, cfg->meta); + } + nj_buf_putc(&p, '}'); + h->payload = nj_buf_take(&p); + if (!h->app || !h->password || !h->hellos || !h->payload) { + atyha_host_destroy(h); + return NULL; + } + atyha_topic(h->app, h->code, topic); + h->bus = open_transport(&cfg->transport, topic); + if (!h->bus) { + atyha_host_destroy(h); + return NULL; + } + return h; +} + +const char* atyha_host_code(const atyha_host* h) { return h->code; } +int atyha_host_is_open(const atyha_host* h) { return h->open; } + +static nj_attempt* host_find(atyha_host* h, const char* sid) +{ + nj_attempt* a; + for (a = h->attempts; a; a = a->next) + if (!strcmp(a->sid, sid)) return a; + return NULL; +} + +static void host_hello(atyha_host* h, const nj_msg* m, int64_t now) +{ + nj_attempt* a = host_find(h, m->sid); + uint8_t prs[512 + 16], ci[96], g[32], yb[32], Yb[32], K[32], isk[64]; + size_t prs_len, ci_len; + char* c; + if (a) { + if (!strcmp(a->joiner, m->from)) h->bus->publish(h->bus, a->pake, now); + return; + } + while (h->hello_n && h->hellos[h->hello_head] <= now - HELLO_WINDOW_MS) { + h->hello_head = (h->hello_head + 1) % h->budget; + h->hello_n--; + } + if (h->hello_n >= h->budget) { + queue_log(&h->q, "hello ignored: over the budget"); + return; + } + h->hellos[(h->hello_head + h->hello_n) % h->budget] = now; + h->hello_n++; + + prs_len = atyha_prs(h->code, h->password, NULL, 0); + if (prs_len > sizeof prs) { + /* a password longer than 512 bytes: an allocation */ + uint8_t* big = (uint8_t*)malloc(prs_len); + if (!big) return; + atyha_prs(h->code, h->password, big, prs_len); + ci_len = atyha_ci(h->app, ci, sizeof ci); + atyha_cpace_generator(big, prs_len, ci, ci_len, m->sid_bytes, 16, g); + sodium_memzero(big, prs_len); + free(big); + } else { + atyha_prs(h->code, h->password, prs, sizeof prs); + ci_len = atyha_ci(h->app, ci, sizeof ci); + atyha_cpace_generator(prs, prs_len, ci, ci_len, m->sid_bytes, 16, g); + sodium_memzero(prs, sizeof prs); + } + atyha_cpace_sample_scalar(yb); + if (atyha_cpace_share(g, yb, Yb) || atyha_cpace_scalar_mult_vfy(yb, m->Y, K)) { + sodium_memzero(yb, sizeof yb); + return; /* Ya is no point */ + } + sodium_memzero(yb, sizeof yb); + a = (nj_attempt*)calloc(1, sizeof *a); + if (!a) return; + atyha_cpace_isk(m->sid_bytes, 16, K, m->Y, Yb, isk); + atyha_keys(isk, m->sid_bytes, 16, a->k_hj, a->k_jh); + sodium_memzero(isk, sizeof isk); + sodium_memzero(K, sizeof K); + memcpy(a->sid, m->sid, NJ_ID_B64); + memcpy(a->sid_bytes, m->sid_bytes, 16); + memcpy(a->joiner, m->from, NJ_ID_B64); + a->at = now; + c = seal_text(a->k_hj, 0, NJ_PAKE, a->sid_bytes, h->payload); + a->pake = c ? nj_msg_write(NJ_PAKE, a->sid, h->id, a->joiner, Yb, c) : NULL; + free(c); + if (!a->pake) { + attempt_free(a); + return; + } + a->next = h->attempts; + h->attempts = a; + h->bus->publish(h->bus, a->pake, now); +} + +static void host_offer(atyha_host* h, const nj_msg* m, int64_t now) +{ + nj_attempt* a = host_find(h, m->sid); + nj_value *p, *sdp, *meta; + uint8_t* keep = NULL; + nj_qev* e; + if (!a || strcmp(a->joiner, m->from)) return; + if (a->reply) { + h->bus->publish(h->bus, a->reply, now); + return; + } + if (a->pending) return; + p = open_object(a->k_jh, 0, NJ_OFFER, a->sid_bytes, m->c, &keep); + sdp = nj_get(p, "sdp"); + if (!p || !sdp || sdp->type != NJ_STRING) { + close_object(p, keep); /* wrong password, or forged */ + return; + } + meta = nj_get(p, "meta"); + if (meta && meta->type != NJ_OBJECT) meta = NULL; + a->pending = 1; + e = queue_push(&h->q, ATYHA_EV_OFFER); + if (e) { + e->ev.sdp = qev_own(e, 0, sdp->str); + e->owned[1] = raw_text(meta); + e->ev.meta = e->owned[1]; + e->ev.attempt = qev_own(e, 2, a->sid); + e->ev.joiner = qev_own(e, 3, a->joiner); + } + close_object(p, keep); +} + +static void host_message(atyha_host* h, const char* text, int64_t now) +{ + nj_msg m; + if (nj_msg_parse(text, &m)) return; + if (m.t == NJ_HELLO) host_hello(h, &m, now); + else if (m.t == NJ_OFFER && !strcmp(m.to, h->id)) host_offer(h, &m, now); + nj_msg_free(&m); +} + +int atyha_host_poll(atyha_host* h, int64_t now, atyha_event* ev) +{ + atyha_bus_event be; + nj_attempt** pa; + int i; + h->now = now; + for (i = 0; i < MAX_BUS_EVENTS_PER_POLL && h->bus->poll(h->bus, now, &be); i++) { + if (be.type == ATYHA_BUS_READY) { + if (!h->open) { + h->open = 1; + queue_push(&h->q, ATYHA_EV_OPEN); + } + } else if (be.type == ATYHA_BUS_MESSAGE && be.text) { + host_message(h, be.text, now); + } else if (be.type == ATYHA_BUS_LOG && be.text) { + queue_log(&h->q, be.text); + } + } + for (pa = &h->attempts; *pa;) { + nj_attempt* a = *pa; + if (a->at < now - (a->pending ? ATTEMPT_PENDING_KEEP_MS : ATTEMPT_KEEP_MS)) { + *pa = a->next; + attempt_free(a); + } else { + pa = &a->next; + } + } + return queue_pop(&h->q, ev); +} + +static int host_reply(atyha_host* h, const char* attempt, int t, const char* key, const char* value) +{ + nj_attempt* a = attempt ? host_find(h, attempt) : NULL; + nj_buf b = {0}; + char *plain, *c; + if (!a || a->reply || !value) return -1; + nj_buf_puts(&b, "{\""); + nj_buf_puts(&b, key); + nj_buf_puts(&b, "\":"); + nj_buf_json_str(&b, value, strlen(value)); + nj_buf_putc(&b, '}'); + plain = nj_buf_take(&b); + if (!plain) return -1; + c = seal_text(a->k_hj, 1, t, a->sid_bytes, plain); + free(plain); + if (!c) return -1; + a->reply = nj_msg_write(t, a->sid, h->id, a->joiner, NULL, c); + free(c); + if (!a->reply) return -1; + a->pending = 0; + a->at = h->now; /* refreshed: kept 60 s for repeats of the offer */ + h->bus->publish(h->bus, a->reply, h->now); + return 0; +} + +int atyha_host_answer(atyha_host* h, const char* attempt, const char* sdp) +{ + return host_reply(h, attempt, NJ_ANSWER, "sdp", sdp); +} + +int atyha_host_reject(atyha_host* h, const char* attempt, const char* reason) +{ + return host_reply(h, attempt, NJ_REJECT, "reason", reason ? reason : "refused"); +} + +void atyha_host_destroy(atyha_host* h) +{ + if (!h) return; + if (h->bus) h->bus->destroy(h->bus); + while (h->attempts) { + nj_attempt* a = h->attempts; + h->attempts = a->next; + attempt_free(a); + } + queue_free(&h->q); + if (h->password) sodium_memzero(h->password, strlen(h->password)); + free(h->password); + free(h->app); + free(h->payload); + free(h->hellos); + free(h); +} + +/* ============================================================== joiner */ + +enum { J_START, J_WAIT_BUS, J_HELLO, J_NEED_OFFER, J_OFFER, J_DONE }; + +struct atyha_joiner { + char* app; + char code[ATYHA_CODE_LEN + 1]; + int bad_code; + char* password; + char* meta; + int64_t deadline_ms; + atyha_bus* bus; + int state; + int cancelled; + int64_t t_start, t_next, t_deadline, t_bad; + int64_t now; /* of the last poll */ + int bad_pake; + uint8_t sid[16]; + char sid_b64[NJ_ID_B64]; + char me[NJ_ID_B64]; + char host[NJ_ID_B64]; + uint8_t y[32], Ya[32]; + uint8_t k_hj[32], k_jh[32]; + char* hello; + char* offer; + nj_queue q; +}; + +atyha_joiner* atyha_joiner_create(const atyha_join_config* cfg) +{ + atyha_joiner* j; + if (!cfg || !app_ok(cfg->app) || !meta_ok(cfg->meta) || atyha_crypto_init()) return NULL; + if (!cfg->transport.bus_open && !cfg->transport.ws) return NULL; + j = (atyha_joiner*)calloc(1, sizeof *j); + if (!j) return NULL; + j->app = nj_strdup(cfg->app); + j->password = nj_strdup(cfg->password ? cfg->password : ""); + j->meta = cfg->meta ? nj_strdup(cfg->meta) : NULL; + j->deadline_ms = cfg->timeout_ms > 0 ? cfg->timeout_ms : DEFAULT_DEADLINE_MS; + if (!j->app || !j->password || (cfg->meta && !j->meta)) { + atyha_joiner_destroy(j); + return NULL; + } + if (!atyha_code_parse(cfg->code, j->code)) { + j->bad_code = 1; + return j; + } + { + uint8_t prs[512 + 16], ci[96], g[32]; + uint8_t* pp = prs; + size_t prs_len = atyha_prs(j->code, j->password, NULL, 0), ci_len; + char topic[65]; + if (prs_len > sizeof prs) pp = (uint8_t*)malloc(prs_len); + if (!pp) { + atyha_joiner_destroy(j); + return NULL; + } + atyha_prs(j->code, j->password, pp, prs_len); + ci_len = atyha_ci(j->app, ci, sizeof ci); + randombytes_buf(j->sid, 16); + atyha_b64u_encode(j->sid, 16, j->sid_b64, sizeof j->sid_b64); + random_id(j->me); + atyha_cpace_generator(pp, prs_len, ci, ci_len, j->sid, 16, g); + sodium_memzero(pp, prs_len); + if (pp != prs) free(pp); + do atyha_cpace_sample_scalar(j->y); + while (atyha_cpace_share(g, j->y, j->Ya)); + j->hello = nj_msg_write(NJ_HELLO, j->sid_b64, j->me, NULL, j->Ya, NULL); + atyha_topic(j->app, j->code, topic); + j->bus = j->hello ? open_transport(&cfg->transport, topic) : NULL; + if (!j->bus) { + atyha_joiner_destroy(j); + return NULL; + } + } + return j; +} + +static void joiner_finish(atyha_joiner* j, atyha_error err, const char* reason, const char* sdp) +{ + nj_qev* e; + if (j->state == J_DONE) return; + j->state = J_DONE; + if (j->bus) { + j->bus->destroy(j->bus); + j->bus = NULL; + } + sodium_memzero(j->y, sizeof j->y); + e = queue_push(&j->q, err ? ATYHA_EV_ERROR : ATYHA_EV_ANSWER); + if (!e) return; + e->ev.error = err; + e->ev.reason = qev_own(e, 0, reason); + e->ev.sdp = qev_own(e, 1, sdp); +} + +static void joiner_pake(atyha_joiner* j, const nj_msg* m, int64_t now) +{ + uint8_t K[32], isk[64], k_hj[32], k_jh[32]; + nj_value *p = NULL, *meta; + uint8_t* keep = NULL; + nj_qev* e; + if (!atyha_cpace_scalar_mult_vfy(j->y, m->Y, K)) { + atyha_cpace_isk(j->sid, 16, K, j->Ya, m->Y, isk); + atyha_keys(isk, j->sid, 16, k_hj, k_jh); + sodium_memzero(isk, sizeof isk); + p = open_object(k_hj, 0, NJ_PAKE, j->sid, m->c, &keep); + } + sodium_memzero(K, sizeof K); + if (!p) { + if (!j->bad_pake) { + j->bad_pake = 1; + j->t_bad = now + WRONG_PASSWORD_WAIT_MS; + queue_log(&j->q, "a pake that does not open: wrong password?"); + } + return; + } + memcpy(j->host, m->from, NJ_ID_B64); + memcpy(j->k_hj, k_hj, 32); + memcpy(j->k_jh, k_jh, 32); + j->state = J_NEED_OFFER; + j->t_deadline = now + j->deadline_ms; /* for the program's offer */ + e = queue_push(&j->q, ATYHA_EV_NEED_OFFER); + if (e) { + meta = nj_get(p, "meta"); + if (meta && meta->type == NJ_OBJECT) { + e->owned[0] = raw_text(meta); + e->ev.meta = e->owned[0]; + } + ice_list_from_json(&e->ice, nj_get(p, "ice")); + e->ev.ice = e->ice.count ? e->ice.servers : NULL; + e->ev.ice_count = e->ice.count; + e->ev.ice_json = e->ice.count ? e->ice.json : NULL; + } + close_object(p, keep); +} + +static void joiner_reply(atyha_joiner* j, const nj_msg* m) +{ + uint8_t* keep = NULL; + nj_value* p = open_object(j->k_hj, 1, m->t, j->sid, m->c, &keep); + const char* s; + if (!p) return; + if (m->t == NJ_ANSWER) { + s = nj_get_str(p, "sdp"); + if (s) joiner_finish(j, ATYHA_OK, NULL, s); + } else { + s = nj_get_str(p, "reason"); + joiner_finish(j, ATYHA_ERR_REJECTED, s ? s : "refused", NULL); + } + close_object(p, keep); +} + +static void joiner_message(atyha_joiner* j, const char* text, int64_t now) +{ + nj_msg m; + if (nj_msg_parse(text, &m)) return; + if (!strcmp(m.sid, j->sid_b64) && !strcmp(m.to, j->me)) { + if (m.t == NJ_PAKE && j->state == J_HELLO) joiner_pake(j, &m, now); + else if ((m.t == NJ_ANSWER || m.t == NJ_REJECT) && j->state == J_OFFER && !strcmp(m.from, j->host)) + joiner_reply(j, &m); + } + nj_msg_free(&m); +} + +int atyha_joiner_poll(atyha_joiner* j, int64_t now, atyha_event* ev) +{ + j->now = now; + if (j->state == J_START) { + j->t_start = now; + j->state = J_WAIT_BUS; + if (j->bad_code) joiner_finish(j, ATYHA_ERR_BAD_CODE, "that is not a room code", NULL); + } + if (j->cancelled) joiner_finish(j, ATYHA_ERR_CANCELLED, "cancelled", NULL); + if (j->state != J_DONE) { + atyha_bus_event be; + int i; + for (i = 0; i < MAX_BUS_EVENTS_PER_POLL && j->bus && j->bus->poll(j->bus, now, &be); i++) { + if (be.type == ATYHA_BUS_READY) { + if (j->state == J_WAIT_BUS) { + j->state = J_HELLO; + j->bus->publish(j->bus, j->hello, now); + j->t_next = now + RETRY_MS; + j->t_deadline = now + j->deadline_ms; + } + } else if (be.type == ATYHA_BUS_MESSAGE && be.text) { + joiner_message(j, be.text, now); + } else if (be.type == ATYHA_BUS_LOG && be.text) { + queue_log(&j->q, be.text); + } + if (j->state == J_DONE) break; + } + } + switch (j->state) { + case J_WAIT_BUS: + if (now - j->t_start >= NO_RELAY_MS) joiner_finish(j, ATYHA_ERR_NO_RELAY, "no relay could be reached", NULL); + break; + case J_HELLO: + if (j->bad_pake && now >= j->t_bad) { + joiner_finish(j, ATYHA_ERR_WRONG_PASSWORD, "wrong password", NULL); + } else if (now >= j->t_deadline) { + joiner_finish(j, j->bad_pake ? ATYHA_ERR_WRONG_PASSWORD : ATYHA_ERR_NO_ROOM, + j->bad_pake ? "wrong password" : "nobody is hosting that code", NULL); + } else if (now >= j->t_next) { + j->bus->publish(j->bus, j->hello, now); + j->t_next = now + RETRY_MS; + } + break; + case J_NEED_OFFER: + if (now >= j->t_deadline) joiner_finish(j, ATYHA_ERR_NO_ANSWER, "no offer was made in time", NULL); + break; + case J_OFFER: + if (now >= j->t_deadline) { + joiner_finish(j, ATYHA_ERR_NO_ANSWER, "the host did not answer", NULL); + } else if (now >= j->t_next) { + j->bus->publish(j->bus, j->offer, now); + j->t_next = now + RETRY_MS; + } + break; + default: break; + } + return queue_pop(&j->q, ev); +} + +int atyha_joiner_set_offer(atyha_joiner* j, const char* sdp) +{ + nj_buf b = {0}; + char *plain, *c; + if (!j || j->state != J_NEED_OFFER || !sdp) return -1; + nj_buf_puts(&b, "{\"sdp\":"); + nj_buf_json_str(&b, sdp, strlen(sdp)); + if (j->meta) { + nj_buf_puts(&b, ",\"meta\":"); + nj_buf_puts(&b, j->meta); + } + nj_buf_putc(&b, '}'); + plain = nj_buf_take(&b); + if (!plain) return -1; + c = seal_text(j->k_jh, 0, NJ_OFFER, j->sid, plain); + free(plain); + if (!c) return -1; + j->offer = nj_msg_write(NJ_OFFER, j->sid_b64, j->me, j->host, NULL, c); + free(c); + if (!j->offer) return -1; + j->state = J_OFFER; + /* sent now, again every 2 s; the answer deadline starts (clock of the last poll) */ + j->bus->publish(j->bus, j->offer, j->now); + j->t_next = j->now + RETRY_MS; + j->t_deadline = j->now + j->deadline_ms; + return 0; +} + +void atyha_joiner_cancel(atyha_joiner* j) +{ + if (j) j->cancelled = 1; +} + +int atyha_joiner_done(const atyha_joiner* j) { return j->state == J_DONE; } + +void atyha_joiner_destroy(atyha_joiner* j) +{ + if (!j) return; + if (j->bus) j->bus->destroy(j->bus); + queue_free(&j->q); + sodium_memzero(j->y, sizeof j->y); + sodium_memzero(j->k_hj, sizeof j->k_hj); + sodium_memzero(j->k_jh, sizeof j->k_jh); + if (j->password) sodium_memzero(j->password, strlen(j->password)); + free(j->password); + free(j->app); + free(j->meta); + free(j->hello); + free(j->offer); + free(j); +} diff --git a/common/atyha/src/util.c b/common/atyha/src/util.c new file mode 100644 index 0000000..849eca9 --- /dev/null +++ b/common/atyha/src/util.c @@ -0,0 +1,233 @@ +/* SPDX-License-Identifier: MIT + Copyright (c) 2026 ngspades contributors */ +#include +#include +#include +#include + +#if defined(_WIN32) +#include +#elif defined(__EMSCRIPTEN__) +#include +#else +#include +#endif + +#include "internal.h" +#include "atyha_crypto.h" + +void nj_buf_reserve(nj_buf* b, size_t more) +{ + size_t want, cap; + char* p; + if (b->oom) return; + want = b->n + more + 1; + if (want <= b->cap) return; + cap = b->cap ? b->cap : 64; + while (cap < want) cap *= 2; + p = (char*)realloc(b->p, cap); + if (!p) { + b->oom = 1; + return; + } + b->p = p; + b->cap = cap; + b->p[b->n] = 0; +} + +void nj_buf_put(nj_buf* b, const void* data, size_t len) +{ + nj_buf_reserve(b, len); + if (b->oom) return; + if (len) memcpy(b->p + b->n, data, len); + b->n += len; + b->p[b->n] = 0; +} + +void nj_buf_puts(nj_buf* b, const char* s) { nj_buf_put(b, s, strlen(s)); } +void nj_buf_putc(nj_buf* b, char c) { nj_buf_put(b, &c, 1); } + +void nj_buf_printf(nj_buf* b, const char* fmt, ...) +{ + va_list ap; + int n; + va_start(ap, fmt); + n = vsnprintf(NULL, 0, fmt, ap); + va_end(ap); + if (n < 0) return; + nj_buf_reserve(b, (size_t)n); + if (b->oom) return; + va_start(ap, fmt); + vsnprintf(b->p + b->n, (size_t)n + 1, fmt, ap); + va_end(ap); + b->n += (size_t)n; +} + +void nj_buf_json_str(nj_buf* b, const char* s, size_t len) +{ + static const char hexd[] = "0123456789abcdef"; + size_t i, run = 0; + nj_buf_putc(b, '"'); + for (i = 0; i < len; i++) { + unsigned char c = (unsigned char)s[i]; + const char* esc = NULL; + char u[7]; + if (c == '"') esc = "\\\""; + else if (c == '\\') esc = "\\\\"; + else if (c == '\b') esc = "\\b"; + else if (c == '\f') esc = "\\f"; + else if (c == '\n') esc = "\\n"; + else if (c == '\r') esc = "\\r"; + else if (c == '\t') esc = "\\t"; + else if (c < 0x20) { + u[0] = '\\', u[1] = 'u', u[2] = '0', u[3] = '0', u[4] = hexd[c >> 4], u[5] = hexd[c & 15], u[6] = 0; + esc = u; + } + if (esc) { + nj_buf_put(b, s + i - run, run); + run = 0; + nj_buf_puts(b, esc); + } else { + run++; + } + } + nj_buf_put(b, s + len - run, run); + nj_buf_putc(b, '"'); +} + +char* nj_buf_take(nj_buf* b) +{ + char* p; + if (b->oom || !b->p) { + free(b->p); + memset(b, 0, sizeof *b); + return NULL; + } + p = b->p; + memset(b, 0, sizeof *b); + return p; +} + +void nj_buf_free(nj_buf* b) +{ + free(b->p); + memset(b, 0, sizeof *b); +} + +char* nj_strdup(const char* s) +{ + size_t n; + char* p; + if (!s) return NULL; + n = strlen(s); + p = (char*)malloc(n + 1); + if (p) memcpy(p, s, n + 1); + return p; +} + +void nj_hex(const uint8_t* in, size_t len, char* out) +{ + static const char hexd[] = "0123456789abcdef"; + size_t i; + for (i = 0; i < len; i++) { + out[2 * i] = hexd[in[i] >> 4]; + out[2 * i + 1] = hexd[in[i] & 15]; + } + out[2 * len] = 0; +} + +static int hexval(char c) +{ + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; +} + +int nj_unhex(const char* in, size_t len, uint8_t* out) +{ + size_t i; + if (len % 2) return -1; + for (i = 0; i < len; i += 2) { + int h = hexval(in[i]), l = hexval(in[i + 1]); + if (h < 0 || l < 0) return -1; + out[i / 2] = (uint8_t)(h << 4 | l); + } + return 0; +} + +/* ---- base64url, no padding ---- */ + +static const char B64U[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + +size_t atyha_b64u_encode(const uint8_t* in, size_t len, char* out, size_t cap) +{ + size_t need = len / 3 * 4 + (len % 3 ? len % 3 + 1 : 0); + size_t i, o = 0; + char tmp[4]; + for (i = 0; i < len; i += 3) { + uint32_t v = (uint32_t)in[i] << 16; + size_t k, chunk = len - i < 3 ? len - i : 3; + if (chunk > 1) v |= (uint32_t)in[i + 1] << 8; + if (chunk > 2) v |= in[i + 2]; + tmp[0] = B64U[v >> 18 & 63]; + tmp[1] = B64U[v >> 12 & 63]; + tmp[2] = B64U[v >> 6 & 63]; + tmp[3] = B64U[v & 63]; + for (k = 0; k < chunk + 1; k++, o++) + if (o < cap) out[o] = tmp[k]; + } + if (cap > need) out[need] = 0; + return need; +} + +static int b64val(char c) +{ + if (c >= 'A' && c <= 'Z') return c - 'A'; + if (c >= 'a' && c <= 'z') return c - 'a' + 26; + if (c >= '0' && c <= '9') return c - '0' + 52; + if (c == '-') return 62; + if (c == '_') return 63; + return -1; +} + +long atyha_b64u_decode(const char* in, size_t in_len, uint8_t* out, size_t cap) +{ + size_t i, o = 0, rem = in_len % 4; + size_t need = in_len / 4 * 3 + (rem ? rem - 1 : 0); + if (rem == 1) return -1; + if (need > cap) return -1; + for (i = 0; i < in_len; i += 4) { + uint32_t v = 0; + size_t k, chunk = in_len - i < 4 ? in_len - i : 4; + for (k = 0; k < 4; k++) { + int d = 0; + if (k < chunk) { + d = b64val(in[i + k]); + if (d < 0) return -1; + } + v = v << 6 | (uint32_t)d; + } + if (chunk == 2 && (v & 0xffff)) return -1; /* trailing bits must be zero */ + if (chunk == 3 && (v & 0xff)) return -1; + out[o++] = (uint8_t)(v >> 16); + if (chunk > 2) out[o++] = (uint8_t)(v >> 8); + if (chunk > 3) out[o++] = (uint8_t)v; + } + return (long)o; +} + +/* ---- clock ---- */ + +int64_t atyha_now_ms(void) +{ +#if defined(_WIN32) + return (int64_t)GetTickCount64(); +#elif defined(__EMSCRIPTEN__) + return (int64_t)emscripten_get_now(); +#else + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000; +#endif +} diff --git a/common/atyha/src/ws_curl.c b/common/atyha/src/ws_curl.c new file mode 100644 index 0000000..b95c8a1 --- /dev/null +++ b/common/atyha/src/ws_curl.c @@ -0,0 +1,290 @@ +/* SPDX-License-Identifier: MIT + Copyright (c) 2026 ngspades contributors + + WebSocket backend on libcurl (8.11+): CONNECT_ONLY = 2 easy handles on a + multi handle, so the connection is made without blocking, then + curl_ws_send / curl_ws_recv. */ +#include +#include + +#include + +#include "internal.h" +#include "atyha_curl.h" + +#define MAX_MESSAGE (1u << 20) + +enum { C_CONNECTING, C_OPEN, C_CLOSED }; + +typedef struct out_msg { + char* data; + size_t len, off; + struct out_msg* next; +} out_msg; + +typedef struct curl_backend curl_backend; + +struct atyha_ws { + curl_backend* be; + CURL* easy; + int state; + int open_reported, closed_reported; + out_msg *out_head, *out_tail; + nj_buf in; /* the message being received */ + int in_binary; /* it is binary: dropped */ + int in_oversize; /* too large: dropped */ + char* current; /* the last message handed over */ + char err[CURL_ERROR_SIZE]; + struct atyha_ws* next; +}; + +struct curl_backend { + atyha_ws_backend base; + CURLM* multi; + char* ca_file; + char* user_agent; + long connect_timeout_ms; + atyha_ws* conns; +}; + +static void set_closed(atyha_ws* ws, const char* why) +{ + if (ws->state == C_CLOSED) return; + ws->state = C_CLOSED; + if (why && !ws->err[0]) { + strncpy(ws->err, why, sizeof ws->err - 1); + ws->err[sizeof ws->err - 1] = 0; + } +} + +static void be_update(atyha_ws_backend* base) +{ + curl_backend* be = (curl_backend*)base; + int running = 0, left = 0; + CURLMsg* msg; + curl_multi_perform(be->multi, &running); + while ((msg = curl_multi_info_read(be->multi, &left)) != NULL) { + atyha_ws* ws = NULL; + if (msg->msg != CURLMSG_DONE) continue; + curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, (char**)&ws); + if (!ws || ws->state != C_CONNECTING) continue; + if (msg->data.result == CURLE_OK) { + long code = 0; + curl_easy_getinfo(ws->easy, CURLINFO_RESPONSE_CODE, &code); + if (code == 101) ws->state = C_OPEN; + else set_closed(ws, "the server did not upgrade to WebSocket"); + } else { + set_closed(ws, ws->err[0] ? ws->err : curl_easy_strerror(msg->data.result)); + } + } +} + +static atyha_ws* be_connect(atyha_ws_backend* base, const char* url) +{ + curl_backend* be = (curl_backend*)base; + atyha_ws* ws = (atyha_ws*)calloc(1, sizeof *ws); + if (!ws) return NULL; + ws->be = be; + ws->easy = curl_easy_init(); + if (!ws->easy) { + free(ws); + return NULL; + } + curl_easy_setopt(ws->easy, CURLOPT_URL, url); + curl_easy_setopt(ws->easy, CURLOPT_CONNECT_ONLY, 2L); + curl_easy_setopt(ws->easy, CURLOPT_PRIVATE, (char*)ws); + curl_easy_setopt(ws->easy, CURLOPT_ERRORBUFFER, ws->err); + curl_easy_setopt(ws->easy, CURLOPT_NOSIGNAL, 1L); + curl_easy_setopt(ws->easy, CURLOPT_CONNECTTIMEOUT_MS, be->connect_timeout_ms); + curl_easy_setopt(ws->easy, CURLOPT_USERAGENT, be->user_agent); + if (be->ca_file) curl_easy_setopt(ws->easy, CURLOPT_CAINFO, be->ca_file); + if (curl_multi_add_handle(be->multi, ws->easy) != CURLM_OK) { + curl_easy_cleanup(ws->easy); + free(ws); + return NULL; + } + ws->next = be->conns; + be->conns = ws; + return ws; +} + +static int be_send(atyha_ws* ws, const char* text, size_t len) +{ + out_msg* m; + if (ws->state == C_CLOSED) return -1; + m = (out_msg*)calloc(1, sizeof *m); + if (!m) return -1; + m->data = (char*)malloc(len ? len : 1); + if (!m->data) { + free(m); + return -1; + } + memcpy(m->data, text, len); + m->len = len; + if (ws->out_tail) ws->out_tail->next = m; + else ws->out_head = m; + ws->out_tail = m; + return 0; +} + +static void flush(atyha_ws* ws) +{ + while (ws->state == C_OPEN && ws->out_head) { + out_msg* m = ws->out_head; + size_t sent = 0; + CURLcode rc = curl_ws_send(ws->easy, m->data + m->off, m->len - m->off, &sent, 0, CURLWS_TEXT); + if (rc == CURLE_AGAIN) { + m->off += sent; + return; + } + if (rc != CURLE_OK) { + set_closed(ws, curl_easy_strerror(rc)); + return; + } + m->off += sent; + if (m->off < m->len) continue; + ws->out_head = m->next; + if (!ws->out_head) ws->out_tail = NULL; + free(m->data); + free(m); + } +} + +/* 1 when a whole text message is in ws->in */ +static int receive(atyha_ws* ws) +{ + char buf[16384]; + for (;;) { + size_t n = 0; + const struct curl_ws_frame* meta = NULL; + CURLcode rc = curl_ws_recv(ws->easy, buf, sizeof buf, &n, &meta); + if (rc == CURLE_AGAIN) return 0; + if (rc != CURLE_OK) { + set_closed(ws, rc == CURLE_GOT_NOTHING ? "closed by the server" : curl_easy_strerror(rc)); + return 0; + } + if (!meta) continue; + if (meta->flags & CURLWS_CLOSE) { + set_closed(ws, "closed by the server"); + return 0; + } + if (meta->flags & (CURLWS_PING | CURLWS_PONG)) continue; + if (meta->flags & CURLWS_BINARY) ws->in_binary = 1; + if (!ws->in_binary && !ws->in_oversize) { + if (ws->in.n + n > MAX_MESSAGE) { + ws->in_oversize = 1; + nj_buf_free(&ws->in); + } else { + nj_buf_put(&ws->in, buf, n); + } + } + if (meta->bytesleft == 0 && !(meta->flags & CURLWS_CONT)) { + int whole = !ws->in_binary && !ws->in_oversize && !ws->in.oom; + ws->in_binary = ws->in_oversize = 0; + if (whole) return 1; + nj_buf_free(&ws->in); + } + } +} + +static int be_poll(atyha_ws* ws, atyha_ws_event* ev) +{ + free(ws->current); + ws->current = NULL; + memset(ev, 0, sizeof *ev); + if (ws->state == C_OPEN && !ws->open_reported) { + ws->open_reported = 1; + ev->type = ATYHA_WS_OPEN; + return 1; + } + if (ws->state == C_OPEN) { + flush(ws); + if (ws->state == C_OPEN && receive(ws)) { + if (!ws->in.p) nj_buf_put(&ws->in, "", 0); + ev->type = ATYHA_WS_TEXT; + ev->len = ws->in.n; + ws->current = nj_buf_take(&ws->in); + ev->data = ws->current; + if (!ev->data) { + ev->type = ATYHA_WS_NONE; + return 0; + } + return 1; + } + } + if (ws->state == C_CLOSED && !ws->closed_reported) { + ws->closed_reported = 1; + ev->type = ATYHA_WS_CLOSED; + ev->data = ws->err; + ev->len = strlen(ws->err); + return 1; + } + return 0; +} + +static void be_close(atyha_ws* ws) +{ + curl_backend* be = ws->be; + atyha_ws** p; + if (ws->state == C_OPEN) { + size_t sent = 0; + flush(ws); /* what is queued (a CLOSE of the subscription), if it goes at once */ + curl_ws_send(ws->easy, "", 0, &sent, 0, CURLWS_CLOSE); + } + curl_multi_remove_handle(be->multi, ws->easy); + curl_easy_cleanup(ws->easy); + for (p = &be->conns; *p; p = &(*p)->next) + if (*p == ws) { + *p = ws->next; + break; + } + while (ws->out_head) { + out_msg* m = ws->out_head; + ws->out_head = m->next; + free(m->data); + free(m); + } + nj_buf_free(&ws->in); + free(ws->current); + free(ws); +} + +atyha_ws_backend* atyha_curl_backend_create(const atyha_curl_options* o) +{ + curl_backend* be; + const curl_version_info_data* info; + const char* const* p; + int has_ws = 0; + if (curl_global_init(CURL_GLOBAL_DEFAULT) != CURLE_OK) return NULL; + info = curl_version_info(CURLVERSION_NOW); + for (p = info->protocols; p && *p; p++) + if (!strcmp(*p, "wss")) has_ws = 1; + if (!has_ws) return NULL; + be = (curl_backend*)calloc(1, sizeof *be); + if (!be) return NULL; + be->multi = curl_multi_init(); + be->user_agent = nj_strdup(o && o->user_agent ? o->user_agent : "atyha/1"); + be->ca_file = o && o->ca_file ? nj_strdup(o->ca_file) : NULL; + be->connect_timeout_ms = o && o->connect_timeout_ms > 0 ? o->connect_timeout_ms : 10000; + if (!be->multi || !be->user_agent) { + atyha_curl_backend_destroy(&be->base); + return NULL; + } + be->base.connect = be_connect; + be->base.send = be_send; + be->base.poll = be_poll; + be->base.close = be_close; + be->base.update = be_update; + return &be->base; +} + +void atyha_curl_backend_destroy(atyha_ws_backend* base) +{ + curl_backend* be = (curl_backend*)base; + if (!be) return; + while (be->conns) be_close(be->conns); + if (be->multi) curl_multi_cleanup(be->multi); + free(be->ca_file); + free(be->user_agent); + free(be); +} diff --git a/common/atyha/src/ws_emscripten.c b/common/atyha/src/ws_emscripten.c new file mode 100644 index 0000000..83b99cb --- /dev/null +++ b/common/atyha/src/ws_emscripten.c @@ -0,0 +1,198 @@ +/* SPDX-License-Identifier: MIT + Copyright (c) 2026 ngspades contributors + + WebSocket backend on (the browser's WebSocket). */ +#ifdef __EMSCRIPTEN__ +#include +#include + +#include + +#include "internal.h" +#include "atyha_emscripten.h" + +typedef struct in_msg { + atyha_ws_event_type type; + char* data; + size_t len; + struct in_msg* next; +} in_msg; + +typedef struct em_backend { + atyha_ws_backend base; + struct atyha_ws* conns; +} em_backend; + +struct atyha_ws { + em_backend* be; + EMSCRIPTEN_WEBSOCKET_T sock; + int open, closed; + in_msg *head, *tail; + char* current; + struct atyha_ws* next; +}; + +static void push(struct atyha_ws* ws, atyha_ws_event_type type, const char* data, size_t len) +{ + in_msg* m; + if (ws->closed) return; + m = (in_msg*)calloc(1, sizeof *m); + if (!m) return; + m->type = type; + if (data) { + m->data = (char*)malloc(len + 1); + if (!m->data) { + free(m); + return; + } + memcpy(m->data, data, len); + m->data[len] = 0; + m->len = len; + } + if (type == ATYHA_WS_CLOSED) ws->closed = 1; + if (ws->tail) ws->tail->next = m; + else ws->head = m; + ws->tail = m; +} + +static EM_BOOL on_open(int type, const EmscriptenWebSocketOpenEvent* e, void* user) +{ + struct atyha_ws* ws = (struct atyha_ws*)user; + (void)type, (void)e; + ws->open = 1; + push(ws, ATYHA_WS_OPEN, NULL, 0); + return EM_TRUE; +} + +static EM_BOOL on_message(int type, const EmscriptenWebSocketMessageEvent* e, void* user) +{ + struct atyha_ws* ws = (struct atyha_ws*)user; + (void)type; + /* text arrives NUL-terminated, numBytes counting the NUL */ + if (e->isText && e->numBytes > 0) push(ws, ATYHA_WS_TEXT, (const char*)e->data, e->numBytes - 1); + return EM_TRUE; +} + +static EM_BOOL on_error(int type, const EmscriptenWebSocketErrorEvent* e, void* user) +{ + (void)type, (void)e, (void)user; + return EM_TRUE; /* a close event follows */ +} + +static EM_BOOL on_close(int type, const EmscriptenWebSocketCloseEvent* e, void* user) +{ + struct atyha_ws* ws = (struct atyha_ws*)user; + (void)type; + push(ws, ATYHA_WS_CLOSED, e->reason, strlen(e->reason)); + ws->open = 0; + return EM_TRUE; +} + +static struct atyha_ws* em_connect(atyha_ws_backend* base, const char* url) +{ + em_backend* be = (em_backend*)base; + EmscriptenWebSocketCreateAttributes attr; + struct atyha_ws* ws; + if (!emscripten_websocket_is_supported()) return NULL; + ws = (struct atyha_ws*)calloc(1, sizeof *ws); + if (!ws) return NULL; + emscripten_websocket_init_create_attributes(&attr); + attr.url = url; + attr.protocols = NULL; + attr.createOnMainThread = EM_TRUE; + ws->sock = emscripten_websocket_new(&attr); + if (ws->sock <= 0) { + free(ws); + return NULL; + } + ws->be = be; + emscripten_websocket_set_onopen_callback(ws->sock, ws, on_open); + emscripten_websocket_set_onmessage_callback(ws->sock, ws, on_message); + emscripten_websocket_set_onerror_callback(ws->sock, ws, on_error); + emscripten_websocket_set_onclose_callback(ws->sock, ws, on_close); + ws->next = be->conns; + be->conns = ws; + return ws; +} + +static int em_send(struct atyha_ws* ws, const char* text, size_t len) +{ + char* s; + EMSCRIPTEN_RESULT r; + if (!ws->open || ws->closed) return -1; + /* send_utf8_text takes a NUL-terminated string */ + s = (char*)malloc(len + 1); + if (!s) return -1; + memcpy(s, text, len); + s[len] = 0; + r = emscripten_websocket_send_utf8_text(ws->sock, s); + free(s); + return r == EMSCRIPTEN_RESULT_SUCCESS ? 0 : -1; +} + +static int em_poll(struct atyha_ws* ws, atyha_ws_event* ev) +{ + in_msg* m; + free(ws->current); + ws->current = NULL; + memset(ev, 0, sizeof *ev); + m = ws->head; + if (!m) return 0; + ws->head = m->next; + if (!ws->head) ws->tail = NULL; + ev->type = m->type; + ev->data = m->data; + ev->len = m->len; + ws->current = m->data; + free(m); + return 1; +} + +static void em_close(struct atyha_ws* ws) +{ + em_backend* be = ws->be; + struct atyha_ws** p; + unsigned short state = 0; + emscripten_websocket_get_ready_state(ws->sock, &state); + if (state <= 1) emscripten_websocket_close(ws->sock, 1000, "bye"); + /* no callback may reach the freed connection */ + emscripten_websocket_set_onopen_callback(ws->sock, NULL, NULL); + emscripten_websocket_set_onmessage_callback(ws->sock, NULL, NULL); + emscripten_websocket_set_onerror_callback(ws->sock, NULL, NULL); + emscripten_websocket_set_onclose_callback(ws->sock, NULL, NULL); + emscripten_websocket_delete(ws->sock); + for (p = &be->conns; *p; p = &(*p)->next) + if (*p == ws) { + *p = ws->next; + break; + } + while (ws->head) { + in_msg* m = ws->head; + ws->head = m->next; + free(m->data); + free(m); + } + free(ws->current); + free(ws); +} + +atyha_ws_backend* atyha_emscripten_backend_create(void) +{ + em_backend* be = (em_backend*)calloc(1, sizeof *be); + if (!be) return NULL; + be->base.connect = em_connect; + be->base.send = em_send; + be->base.poll = em_poll; + be->base.close = em_close; + be->base.update = NULL; + return &be->base; +} + +void atyha_emscripten_backend_destroy(atyha_ws_backend* base) +{ + em_backend* be = (em_backend*)base; + if (!be) return; + while (be->conns) em_close(be->conns); + free(be); +} +#endif diff --git a/common/atyha/src/ws_libdatachannel.c b/common/atyha/src/ws_libdatachannel.c new file mode 100644 index 0000000..d536288 --- /dev/null +++ b/common/atyha/src/ws_libdatachannel.c @@ -0,0 +1,241 @@ +/* SPDX-License-Identifier: MIT + Copyright (c) 2026 ngspades contributors + + WebSocket backend on libdatachannel's C API (rtcCreateWebSocketEx...). + Its callbacks run on libdatachannel's threads: they only append to the + connection's queue under the connection's lock; atyha drains the queue + from its poll, on the program's thread. Closing deletes the rtc + WebSocket first (rtcDeleteWebSocket resets its callbacks, waiting for one + in flight), then frees the queue. */ +#include +#include + +#include + +#include "internal.h" +#include "atyha_libdatachannel.h" + +#ifdef _WIN32 +#include +typedef CRITICAL_SECTION nj_lock; +#define LOCK_INIT(l) InitializeCriticalSection(l) +#define LOCK_FREE(l) DeleteCriticalSection(l) +#define LOCK(l) EnterCriticalSection(l) +#define UNLOCK(l) LeaveCriticalSection(l) +#else +#include +typedef pthread_mutex_t nj_lock; +#define LOCK_INIT(l) pthread_mutex_init(l, NULL) +#define LOCK_FREE(l) pthread_mutex_destroy(l) +#define LOCK(l) pthread_mutex_lock(l) +#define UNLOCK(l) pthread_mutex_unlock(l) +#endif + +#define MAX_QUEUED (4u << 20) /* bytes waiting to be polled; beyond, messages are dropped */ + +typedef struct in_msg { + atyha_ws_event_type type; + char* data; + size_t len; + struct in_msg* next; +} in_msg; + +typedef struct ldc_backend { + atyha_ws_backend base; + int disable_tls_verification; + int connection_timeout_ms; + struct atyha_ws* conns; /* program thread only */ +} ldc_backend; + +struct atyha_ws { + ldc_backend* be; + int id; /* the rtc WebSocket */ + nj_lock lock; + /* under lock: */ + in_msg *head, *tail; + size_t queued; + int open, closed; + /* program thread only: */ + char* current; + struct atyha_ws* next; +}; + +/* under ws->lock */ +static void push_locked(struct atyha_ws* ws, atyha_ws_event_type type, const char* data, size_t len) +{ + in_msg* m; + if (ws->closed) return; + if (type == ATYHA_WS_TEXT && ws->queued + len > MAX_QUEUED) return; + m = (in_msg*)calloc(1, sizeof *m); + if (!m) return; + m->type = type; + if (data) { + m->data = (char*)malloc(len + 1); + if (!m->data) { + free(m); + return; + } + memcpy(m->data, data, len); + m->data[len] = 0; + m->len = len; + } + if (type == ATYHA_WS_OPEN) ws->open = 1; + if (type == ATYHA_WS_CLOSED) ws->closed = 1; + if (type == ATYHA_WS_TEXT) ws->queued += len; + if (ws->tail) ws->tail->next = m; + else ws->head = m; + ws->tail = m; +} + +static void push(struct atyha_ws* ws, atyha_ws_event_type type, const char* data, size_t len) +{ + LOCK(&ws->lock); + push_locked(ws, type, data, len); + UNLOCK(&ws->lock); +} + +/* ---- libdatachannel's threads ---- */ + +static void RTC_API on_open(int id, void* ptr) +{ + (void)id; + if (ptr) push((struct atyha_ws*)ptr, ATYHA_WS_OPEN, NULL, 0); +} + +static void RTC_API on_closed(int id, void* ptr) +{ + (void)id; + if (ptr) push((struct atyha_ws*)ptr, ATYHA_WS_CLOSED, "closed", 6); +} + +static void RTC_API on_error(int id, const char* error, void* ptr) +{ + (void)id; + if (ptr) push((struct atyha_ws*)ptr, ATYHA_WS_CLOSED, error ? error : "error", error ? strlen(error) : 5); +} + +static void RTC_API on_message(int id, const char* message, int size, void* ptr) +{ + (void)id; + /* size < 0: a text message, NUL-terminated; binary ones are dropped */ + if (ptr && size < 0 && message) push((struct atyha_ws*)ptr, ATYHA_WS_TEXT, message, strlen(message)); +} + +/* ---- the program's thread ---- */ + +static struct atyha_ws* ldc_connect(atyha_ws_backend* base, const char* url) +{ + ldc_backend* be = (ldc_backend*)base; + rtcWsConfiguration cfg; + struct atyha_ws* ws = (struct atyha_ws*)calloc(1, sizeof *ws); + if (!ws) return NULL; + LOCK_INIT(&ws->lock); + ws->be = be; + memset(&cfg, 0, sizeof cfg); + cfg.disableTlsVerification = be->disable_tls_verification != 0; + cfg.connectionTimeoutMs = be->connection_timeout_ms; + ws->id = rtcCreateWebSocketEx(url, &cfg); + if (ws->id < 0) { + LOCK_FREE(&ws->lock); + free(ws); + return NULL; + } + /* the user pointer first, so that no callback sees a NULL one... */ + rtcSetUserPointer(ws->id, ws); + rtcSetOpenCallback(ws->id, on_open); + rtcSetClosedCallback(ws->id, on_closed); + rtcSetErrorCallback(ws->id, on_error); + rtcSetMessageCallback(ws->id, on_message); + /* ...and an open that happened before the callback was set is not lost */ + if (rtcIsOpen(ws->id)) { + LOCK(&ws->lock); + if (!ws->open) push_locked(ws, ATYHA_WS_OPEN, NULL, 0); + UNLOCK(&ws->lock); + } + ws->next = be->conns; + be->conns = ws; + return ws; +} + +static int ldc_send(struct atyha_ws* ws, const char* text, size_t len) +{ + char* s; + int r; + if (len > 0x7fffffff) return -1; + s = (char*)malloc(len + 1); + if (!s) return -1; + memcpy(s, text, len); + s[len] = 0; + r = rtcSendMessage(ws->id, s, -1); /* thread-safe; size -1: a text message */ + free(s); + return r < 0 ? -1 : 0; +} + +static int ldc_poll(struct atyha_ws* ws, atyha_ws_event* ev) +{ + in_msg* m; + free(ws->current); + ws->current = NULL; + memset(ev, 0, sizeof *ev); + LOCK(&ws->lock); + m = ws->head; + if (m) { + ws->head = m->next; + if (!ws->head) ws->tail = NULL; + if (m->type == ATYHA_WS_TEXT) ws->queued -= m->len; + } + UNLOCK(&ws->lock); + if (!m) return 0; + ev->type = m->type; + ev->data = m->data; + ev->len = m->len; + ws->current = m->data; + free(m); + return 1; +} + +static void ldc_close(struct atyha_ws* ws) +{ + ldc_backend* be = ws->be; + struct atyha_ws** p; + /* not under our lock: deleting may run the closed callback here */ + rtcDeleteWebSocket(ws->id); /* closes, resets the callbacks (waits for one in flight) */ + for (p = &be->conns; *p; p = &(*p)->next) + if (*p == ws) { + *p = ws->next; + break; + } + LOCK(&ws->lock); + while (ws->head) { + in_msg* m = ws->head; + ws->head = m->next; + free(m->data); + free(m); + } + UNLOCK(&ws->lock); + LOCK_FREE(&ws->lock); + free(ws->current); + free(ws); +} + +atyha_ws_backend* atyha_libdatachannel_backend_create(const atyha_libdatachannel_options* o) +{ + ldc_backend* be = (ldc_backend*)calloc(1, sizeof *be); + if (!be) return NULL; + be->disable_tls_verification = o ? o->disable_tls_verification : 0; + be->connection_timeout_ms = o && o->connection_timeout_ms > 0 ? o->connection_timeout_ms : 0; + be->base.connect = ldc_connect; + be->base.send = ldc_send; + be->base.poll = ldc_poll; + be->base.close = ldc_close; + be->base.update = NULL; + return &be->base; +} + +void atyha_libdatachannel_backend_destroy(atyha_ws_backend* base) +{ + ldc_backend* be = (ldc_backend*)base; + if (!be) return; + while (be->conns) ldc_close(be->conns); + free(be); +} 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..12bedc0 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,29 +49,36 @@ #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; +} + +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 */ @@ -99,7 +107,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 +115,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 +150,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..63472b6 100644 --- a/server/CMakeLists.txt +++ b/server/CMakeLists.txt @@ -103,6 +103,12 @@ 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, MIT): 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 ${CMAKE_BINARY_DIR}/atyha) endif() # NOT SERVER_WEB_HOST set(CMAKE_EXPORT_COMPILE_COMMANDS ON) @@ -163,7 +169,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..3fd437b 100644 --- a/server/Source/Server/Net/Master.c +++ b/server/Source/Server/Net/Master.c @@ -217,19 +217,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); @@ -441,13 +430,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; } 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/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..3bcb684 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 @@ -472,6 +473,60 @@ void webrtc_start(server_t* server) /* ---- offers ---- */ +/* an offer's answer goes back the way it came: the master's long poll, or + the match's room on the public relays (Net/Room.c) */ +static void _reply_answer(const char* offer_id, const char* sdp) +{ + if (room_offer(offer_id)) { + room_answer(offer_id, sdp); + } else { + master_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); + } else { + master_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; @@ -495,14 +550,14 @@ static int _offer_banned(const char* ip, int v4, const uint8_t ip4[4]) 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,13 +570,13 @@ 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"); + _reply_reject(offer_id, "server error"); return; } p->id = id; @@ -584,6 +639,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 +677,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); @@ -663,7 +735,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/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" From 7a3eecfbd104fcd012d0fba97fe70c4bf806668c Mon Sep 17 00:00:00 2001 From: Gustavo Date: Mon, 30 Nov 2026 18:30:21 -0300 Subject: [PATCH 2/5] WebRTC direct: browsers join a listed server with no offer, the master is a list A browser builds this server's answer itself from the master's row (address, webrtc_port, dtls_fingerprint), the way libp2p's webrtc-direct does: its offer's ICE username and password are one random string R, and its first STUN request (USERNAME "R:R") reaches libdatachannel's IceUdpMuxListener on the WebRTC port (rtcw_direct_listen). Net/WebRtc.c reads bans, "server full" and the per-address limit (4 joining) on that request, before anything is made; rtcw_peer_create_direct then answers a synthetic offer (R as ufrag and password, the browser's address as its candidate, DTLS client) with R, not checking the browser's certificate (anyone may join a public server); the browser checks ours against the listed fingerprint. From there it is the same peer as before. The master's signalling is gone: no long poll, no /v1/answer, no master_answer/master_reject, the two lanes they used. Offers now come only from a match's room (Net/Room.c). The log shows the certificate's fingerprint. Checked with Chrome, Safari 27.3 and Firefox 153 (connection open in 56 to 194 ms, the 1.0 Greeting received) and with the game's own browser build; a wrong fingerprint fails, as it must. --- server/Source/Server/Net/Master.c | 89 ----------------- server/Source/Server/Net/Master.h | 10 +- server/Source/Server/Net/RtcPeer.cpp | 138 +++++++++++++++++++++++++-- server/Source/Server/Net/RtcPeer.h | 14 +++ server/Source/Server/Net/WebRtc.c | 128 ++++++++++++++++++++----- server/Source/Server/Net/WebRtc.h | 12 ++- server/Source/Server/PluginNet.h | 4 +- 7 files changed, 261 insertions(+), 134 deletions(-) diff --git a/server/Source/Server/Net/Master.c b/server/Source/Server/Net/Master.c index 3fd437b..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; @@ -307,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) @@ -485,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 */ } @@ -517,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/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/WebRtc.c b/server/Source/Server/Net/WebRtc.c index 3bcb684..8ae52ba 100644 --- a/server/Source/Server/Net/WebRtc.c +++ b/server/Source/Server/Net/WebRtc.c @@ -467,20 +467,25 @@ 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 master's long poll, or - the match's room on the public relays (Net/Room.c) */ +/* 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); - } else { - master_answer(offer_id, sdp); } } @@ -488,8 +493,6 @@ static void _reply_reject(const char* offer_id, const char* reason) { if (room_offer(offer_id)) { room_reject(offer_id, reason); - } else { - master_reject(offer_id, reason); } } @@ -547,6 +550,32 @@ 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; @@ -573,27 +602,76 @@ void webrtc_offer(server_t* server, const char* offer_id, const char* sdp, const _reply_reject(offer_id, why); return; } - webrtc_peer_t* p = calloc(1, sizeof *p); - if (p == NULL) { - rtcw_close(id); + 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) @@ -727,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(); 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; From 839db64459654601bc5ead3da69cf07252b5857e Mon Sep 17 00:00:00 2001 From: Gustavo Date: Mon, 30 Nov 2026 18:37:48 -0300 Subject: [PATCH 3/5] Join codes: ngspades:// links in place of sadcode:// p2p_code_norm takes a room link, ngspades://HK4M-7TRW in any case and with the trailing slash a browser may add: the game's desktop builds register the scheme. sadcode:// (Shoot and Destroy's) is gone. --- netlib/src/p2p.c | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/netlib/src/p2p.c b/netlib/src/p2p.c index 12bedc0..a694899 100644 --- a/netlib/src/p2p.c +++ b/netlib/src/p2p.c @@ -63,6 +63,18 @@ static int p2p_code_char(char c) { 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'; } @@ -80,14 +92,14 @@ int p2p_code_norm(const char* pasted, char* out, size_t size_out) { 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)) From 8e06c831394a36db8f9d9f6b6dd2c85636a13d6e Mon Sep 17 00:00:00 2001 From: Gustavo Date: Mon, 30 Nov 2026 18:41:58 -0300 Subject: [PATCH 4/5] Atyha as a submodule (github.com/ngspades/atyha) in place of a copy common/atyha is the Atyha repository at c96b71d (its main), the C library in its c/; the copy it replaces was the same files. CI and the releases already check submodules out recursively. --- .gitmodules | 3 + common/atyha | 1 + common/atyha/CMakeLists.txt | 122 --- common/atyha/LICENSE | 21 - common/atyha/README.md | 216 ----- common/atyha/cmake/deps.cmake | 68 -- common/atyha/cmake/libdatachannel.cmake | 39 - common/atyha/include/atyha.h | 282 ------ common/atyha/include/atyha_crypto.h | 69 -- common/atyha/include/atyha_curl.h | 34 - common/atyha/include/atyha_emscripten.h | 24 - common/atyha/include/atyha_libdatachannel.h | 32 - common/atyha/src/crypto.c | 389 --------- common/atyha/src/internal.h | 81 -- common/atyha/src/json.c | 360 -------- common/atyha/src/membus.c | 112 --- common/atyha/src/message.c | 101 --- common/atyha/src/message.h | 32 - common/atyha/src/nostr.c | 459 ---------- common/atyha/src/session.c | 920 -------------------- common/atyha/src/util.c | 233 ----- common/atyha/src/ws_curl.c | 290 ------ common/atyha/src/ws_emscripten.c | 198 ----- common/atyha/src/ws_libdatachannel.c | 241 ----- 24 files changed, 4 insertions(+), 4323 deletions(-) create mode 160000 common/atyha delete mode 100644 common/atyha/CMakeLists.txt delete mode 100644 common/atyha/LICENSE delete mode 100644 common/atyha/README.md delete mode 100644 common/atyha/cmake/deps.cmake delete mode 100644 common/atyha/cmake/libdatachannel.cmake delete mode 100644 common/atyha/include/atyha.h delete mode 100644 common/atyha/include/atyha_crypto.h delete mode 100644 common/atyha/include/atyha_curl.h delete mode 100644 common/atyha/include/atyha_emscripten.h delete mode 100644 common/atyha/include/atyha_libdatachannel.h delete mode 100644 common/atyha/src/crypto.c delete mode 100644 common/atyha/src/internal.h delete mode 100644 common/atyha/src/json.c delete mode 100644 common/atyha/src/membus.c delete mode 100644 common/atyha/src/message.c delete mode 100644 common/atyha/src/message.h delete mode 100644 common/atyha/src/nostr.c delete mode 100644 common/atyha/src/session.c delete mode 100644 common/atyha/src/util.c delete mode 100644 common/atyha/src/ws_curl.c delete mode 100644 common/atyha/src/ws_emscripten.c delete mode 100644 common/atyha/src/ws_libdatachannel.c 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/common/atyha/CMakeLists.txt b/common/atyha/CMakeLists.txt deleted file mode 100644 index efadd79..0000000 --- a/common/atyha/CMakeLists.txt +++ /dev/null @@ -1,122 +0,0 @@ -# SPDX-License-Identifier: MIT -# Copyright (c) 2026 ngspades contributors -cmake_minimum_required(VERSION 3.16) -project(atyha VERSION 1.0.0 LANGUAGES C) - -set(ATYHA_TOP_LEVEL OFF) -if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR) - set(ATYHA_TOP_LEVEL ON) -endif() - -option(ATYHA_TESTS "Build the tests (ctest)" ${ATYHA_TOP_LEVEL}) -option(ATYHA_CURL "Build the libcurl WebSocket backend (atyha_curl)" ON) -option(ATYHA_EXAMPLES "Build examples/echo (fetches libdatachannel)" OFF) -option(ATYHA_WITH_LIBDATACHANNEL "Build the libdatachannel WebSocket backend (atyha_libdatachannel)" ${ATYHA_EXAMPLES}) -set(ATYHA_VECTORS "${CMAKE_CURRENT_SOURCE_DIR}/../vectors/atyha-v1.json" CACHE FILEPATH "The protocol's test vectors") - -if(NOT CMAKE_C_STANDARD) - set(CMAKE_C_STANDARD 99) - set(CMAKE_C_STANDARD_REQUIRED ON) -endif() - -include(cmake/deps.cmake) - -# ---- the library: codes, CPace, keys, sealing, messages, the host and joiner -# state machines, the in-memory bus and the Nostr relay pool (no I/O of its -# own: WebSocket backends do it) -add_library(atyha STATIC - src/util.c - src/json.c - src/crypto.c - src/message.c - src/session.c - src/membus.c - src/nostr.c -) -if(EMSCRIPTEN) - target_sources(atyha PRIVATE src/ws_emscripten.c) -endif() -target_include_directories(atyha PUBLIC $) -target_link_libraries(atyha PUBLIC atyha::sodium PRIVATE atyha::secp256k1) -if(MSVC) - target_compile_definitions(atyha PRIVATE _CRT_SECURE_NO_WARNINGS) - target_compile_options(atyha PRIVATE /W3) -else() - target_compile_options(atyha PRIVATE -Wall -Wextra -Wno-unused-parameter) -endif() -add_library(atyha::atyha ALIAS atyha) - -# ---- the libcurl backend -if(ATYHA_CURL AND NOT EMSCRIPTEN) - find_package(CURL 8.11 QUIET) - if(CURL_FOUND) - add_library(atyha_curl STATIC src/ws_curl.c) - target_link_libraries(atyha_curl PUBLIC atyha CURL::libcurl) - if(NOT MSVC) - target_compile_options(atyha_curl PRIVATE -Wall -Wextra -Wno-unused-parameter) - endif() - add_library(atyha::curl ALIAS atyha_curl) - message(STATUS "atyha: libcurl ${CURL_VERSION_STRING} backend") - else() - message(WARNING "atyha: no libcurl 8.11+ found, atyha_curl not built " - "(macOS: -DCMAKE_PREFIX_PATH=$(brew --prefix curl))") - endif() -endif() - -# ---- tests -if(ATYHA_TESTS) - enable_testing() - add_executable(test_vectors tests/test_vectors.c) - target_link_libraries(test_vectors PRIVATE atyha) - target_include_directories(test_vectors PRIVATE src) - add_test(NAME vectors COMMAND test_vectors "${ATYHA_VECTORS}") - - add_executable(test_session tests/test_session.c) - target_link_libraries(test_session PRIVATE atyha) - add_test(NAME session COMMAND test_session) - - add_executable(test_nostr tests/test_nostr.c) - target_link_libraries(test_nostr PRIVATE atyha atyha::secp256k1) - target_include_directories(test_nostr PRIVATE src) - add_test(NAME nostr COMMAND test_nostr) -endif() - -# ---- the libdatachannel backend: the parent project's `datachannel` target -# (built with NO_WEBSOCKET OFF), else the one fetched for the example -if(ATYHA_WITH_LIBDATACHANNEL AND NOT EMSCRIPTEN) - if(NOT TARGET atyha::datachannel) - if(TARGET datachannel) - add_library(atyha::datachannel INTERFACE IMPORTED) - target_link_libraries(atyha::datachannel INTERFACE datachannel) - elseif(TARGET datachannel-static) - add_library(atyha::datachannel INTERFACE IMPORTED) - target_link_libraries(atyha::datachannel INTERFACE datachannel-static) - elseif(ATYHA_EXAMPLES) - include(cmake/libdatachannel.cmake) - endif() - endif() - if(TARGET atyha::datachannel) - add_library(atyha_libdatachannel STATIC src/ws_libdatachannel.c) - target_link_libraries(atyha_libdatachannel PUBLIC atyha atyha::datachannel) - if(NOT WIN32) - find_package(Threads REQUIRED) - target_link_libraries(atyha_libdatachannel PUBLIC Threads::Threads) - endif() - if(NOT MSVC) - target_compile_options(atyha_libdatachannel PRIVATE -Wall -Wextra -Wno-unused-parameter) - endif() - add_library(atyha::libdatachannel ALIAS atyha_libdatachannel) - else() - message(WARNING "atyha: no `datachannel` target, atyha_libdatachannel not built") - endif() -endif() - -# ---- the echo example (libdatachannel for WebRTC; WebSocket by libdatachannel or libcurl) -if(ATYHA_EXAMPLES AND TARGET atyha_libdatachannel) - add_executable(echo examples/echo.c) - target_link_libraries(echo PRIVATE atyha_libdatachannel) - if(TARGET atyha_curl) - target_link_libraries(echo PRIVATE atyha_curl) - target_compile_definitions(echo PRIVATE ATYHA_ECHO_CURL) - endif() -endif() diff --git a/common/atyha/LICENSE b/common/atyha/LICENSE deleted file mode 100644 index 459233d..0000000 --- a/common/atyha/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 ngspades contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/common/atyha/README.md b/common/atyha/README.md deleted file mode 100644 index 2915902..0000000 --- a/common/atyha/README.md +++ /dev/null @@ -1,216 +0,0 @@ -# Atyha for C - -The C library of [Atyha](../spec/atyha-v1.md): join a host by a short room code -(`HK4M-7TRW`) over WebRTC, signalled through public Nostr relays, with an optional -password (CPace). It reproduces `../vectors/atyha-v1.json` byte for byte and -interoperates with the TypeScript reference over the real relays. - -Atyha is signalling only: it carries one complete SDP offer and one complete SDP -answer. Your program makes the peer connection with its own WebRTC stack -(libdatachannel, the browser's, Godot's...). - -- C99; macOS, Linux, Windows (MSVC), iOS, Android, Emscripten. -- Poll-driven and single-threaded: no thread is started, nothing calls you behind - your back. Call `atyha_*_poll(obj, now_ms)` every frame and drain the events. -- No global state of its own (libsodium's `sodium_init` and libcurl's - `curl_global_init` are the libraries' own, called for you). -- MIT. Depends on libsodium and bitcoin-core/libsecp256k1 (MIT, fetched by CMake). - -## Layers - -| layer | files | I/O | -| --- | --- | --- | -| codes, topic, CPace, keys, sealing (`atyha_crypto.h`) | `src/crypto.c`, `src/util.c` | none | -| messages, host and joiner state machines, in-memory bus | `src/message.c`, `src/session.c`, `src/membus.c` | none (through an `atyha_bus`) | -| Nostr relay pool: NIP-01 events, BIP-340 signing, REQ/EVENT/CLOSE/EOSE/OK/CLOSED, retirement and backoff | `src/nostr.c` | none (through an `atyha_ws_backend`) | -| WebSocket backends | `src/ws_curl.c` (target `atyha_curl`), `src/ws_libdatachannel.c` (target `atyha_libdatachannel`), `src/ws_emscripten.c` (in `atyha` under Emscripten), or your own | yes | - -## Build - -```sh -brew install libsodium curl # or apt install libsodium-dev libcurl4-openssl-dev -cmake -S . -B build -DCMAKE_PREFIX_PATH="$(brew --prefix curl);$(brew --prefix)" -cmake --build build -ctest --test-dir build # vectors, session, nostr -``` - -Targets: `atyha` (static: everything but the native backends), `atyha_curl` -(static, the libcurl backend), `atyha_libdatachannel` (static, libdatachannel's -WebSocket). Options: `ATYHA_TESTS` (on when top level), `ATYHA_CURL` (on), -`ATYHA_WITH_LIBDATACHANNEL` (on with the examples; links the parent project's -`datachannel` (or `datachannel-static`) target, which must be built with -`NO_WEBSOCKET OFF`, else the fetched one), `ATYHA_EXAMPLES` (off; fetches -libdatachannel v0.24.6 with `NO_MEDIA ON`, `NO_WEBSOCKET OFF`, and needs OpenSSL: -`-DOPENSSL_ROOT_DIR=$(brew --prefix openssl@3)`), `SODIUM_ROOT` (a -libsodium install to use, e.g. one built with emcc), `ATYHA_VECTORS` (path). -A parent project may define `atyha::sodium` / `atyha::secp256k1` targets itself. - -libsecp256k1 is fetched at `v0.8.0` with the `schnorrsig` and `extrakeys` modules. - -### libcurl version - -The WebSocket API (`curl_ws_send`/`curl_ws_recv`, `CURLOPT_CONNECT_ONLY = 2`) is -stable since **libcurl 8.11.0** and must be compiled in (`ws`/`wss` among the -protocols of `curl -V`). macOS's own libcurl (8.7.1 on this machine) has **no** -WebSocket support; Homebrew's `curl` (8.16.0 here) has it. The backend refuses to -start (returns NULL) when libcurl lacks `wss`. On Windows/Android/iOS build libcurl -with WebSockets enabled (`-DCURL_DISABLE_WEBSOCKETS=OFF`, the default since 8.11) and -give it CA certificates (`atyha_curl_options.ca_file`) where the platform store -is not used. - -### libdatachannel's WebSocket - -For programs that already link libdatachannel and OpenSSL (the game and its -server) and whose libcurl has no WebSocket (macOS's system libcurl 8.7.1): - -```c -#include "atyha_libdatachannel.h" -atyha_ws_backend* ws = atyha_libdatachannel_backend_create(NULL); /* verifies TLS */ -/* ... tr.ws = ws ... */ -atyha_libdatachannel_backend_destroy(ws); /* before rtcCleanup() */ -``` - -libdatachannel calls back on its own threads; the backend only queues there, -under a per-connection lock (pthread mutex, CRITICAL_SECTION on Windows), and -Atyha drains the queue from its poll. Closing deletes the rtc WebSocket first -(`rtcDeleteWebSocket` resets the callbacks) and frees the queue after. -`disable_tls_verification` (default 0) exists for tests only. - -Known limit: libdatachannel's TLS client offers only the P-256 key-exchange group -(`SSL_CTX_set1_groups_list(ctx, "P-256")` in its tlstransport.cpp), and a relay -that refuses P-256 fails the handshake: of the default relays, `wss://nostr.data.haus` -does (checked with `openssl s_client -groups P-256`). The other eight work, and the -pool goes on without it. - -### Emscripten - -Under `emcmake cmake`, `src/ws_emscripten.c` is compiled into `atyha` and the -curl backend is skipped; link the program with `-lwebsocket.js` and give a libsodium -built with emcc via `-DSODIUM_ROOT=...`. - -## API - -Everything is in `include/atyha.h`. Strings are UTF-8; a string an event points to -stays valid until the next poll of the same object. - -### Transport - -```c -#include "atyha.h" -#include "atyha_curl.h" /* native */ -atyha_ws_backend* ws = atyha_curl_backend_create(NULL); /* one for the program */ - -atyha_transport tr = {0}; -tr.ws = ws; /* Nostr, default relays of spec section 8 */ -/* tr.relays = my_list; tr.relay_count = n; a configured relay list */ -/* tr.bus_open = atyha_memory_bus_open; tr.bus_user = hub; tests, no network */ -``` - -### Host (fits an asynchronous "offer in, answer later" server) - -```c -atyha_host_config hc = {0}; -hc.app = "ngspades"; /* 1..64 bytes */ -hc.password = "123"; /* NULL or "": none */ -hc.meta = "{\"name\":\"my server\"}"; /* a JSON object sent to joiners, or NULL */ -hc.ice = ice; hc.ice_count = n; /* optional: STUN/TURN for the joiners */ -hc.transport = tr; -atyha_host* host = atyha_host_create(&hc); -/* atyha_host_code(host) -> "HK4M7TRW"; atyha_code_display() -> "HK4M-7TRW" */ - -for (;;) { /* every tick */ - atyha_event ev; - while (atyha_host_poll(host, now_ms, &ev)) { - if (ev.type == ATYHA_EV_OPEN) { /* the room is reachable: show the code */ } - if (ev.type == ATYHA_EV_OFFER) { - /* ev.sdp, ev.meta (joiner's JSON or NULL), ev.joiner, ev.attempt: - start the peer connection; reply whenever ready, from any tick: */ - remember(ev.attempt); - } - } - /* later: */ - atyha_host_answer(host, attempt, answer_sdp); /* or */ - atyha_host_reject(host, attempt, "server full"); -} -atyha_host_destroy(host); /* closes the room */ -``` - -For ngnet: `attempt` plays the part of `offer_id`; `ATYHA_EV_OFFER` is where -`ngnet_rtc_offer(...)` would be called, and the answer hook calls -`atyha_host_answer` (or `atyha_host_reject` in place of `ngnet_master_reject`). -A reply is kept 60 s and re-sent to every repeat of the same offer; attempts -waiting for the program are kept 5 minutes. - -### Joiner - -```c -atyha_join_config jc = {0}; -jc.app = "ngspades"; jc.code = typed_text; jc.password = pw; jc.meta = "{\"player\":\"p1\"}"; -jc.transport = tr; -atyha_joiner* j = atyha_joiner_create(&jc); - -while (atyha_joiner_poll(j, now_ms, &ev)) switch (ev.type) { -case ATYHA_EV_NEED_OFFER: /* password right. ev.ice/ev.ice_count (host's servers, use - them when > 0; atyha_ice_url_libdatachannel formats them), - ev.meta (host's). Make the peer connection, both channels, - wait for gathering complete (<= 5 s), then: */ - atyha_joiner_set_offer(j, offer_sdp); break; -case ATYHA_EV_ANSWER: /* ev.sdp: set it as the remote description; j is done */ break; -case ATYHA_EV_ERROR: /* ev.error: ATYHA_ERR_BAD_CODE, _NO_RELAY, _NO_ROOM, - _WRONG_PASSWORD, _REJECTED (ev.reason = host's text), - _NO_ANSWER, _CANCELLED; atyha_error_name() gives the - TS JoinError code ("wrong_password"...) */ break; -case ATYHA_EV_LOG: /* ev.text */ break; -} -atyha_joiner_cancel(j); /* any time: the next poll reports cancelled */ -atyha_joiner_destroy(j); -``` - -Timings follow the spec and the TS reference: hello every 2 s from the first EOSE, -`no_relay` when no relay confirmed the subscription in 10 s, `no_room` 25 s after -the first hello, `wrong_password` 4 s after a pake that does not open (unless a -good one comes), offer every 2 s, `no_answer` 25 s after the first offer -(`timeout_ms` changes the 25 s). One addition: if the program never calls -`atyha_joiner_set_offer`, the joiner reports `no_answer` 25 s after -`ATYHA_EV_NEED_OFFER`. - -### Your own WebSocket - -Fill an `atyha_ws_backend` (`connect`, `send`, `poll` returning -`ATYHA_WS_OPEN` / `ATYHA_WS_TEXT` / `ATYHA_WS_CLOSED`, `close`, optional -`update`), or a whole `atyha_bus` (`publish`, `poll`, `destroy`) for another -transport. Both are plain structs of function pointers, embedded as the first -member of your own struct. - -### Building blocks - -`atyha_crypto.h` exposes lv_cat, PRS, CI, the CPace generator string and -generator, shares, `scalar_mult_vfy`, ISK, the HKDF keys, seal/open and base64url, -as the vectors name them. - -## Example: echo - -```sh -cmake -S . -B build -DATYHA_EXAMPLES=ON -DOPENSSL_ROOT_DIR=$(brew --prefix openssl@3) \ - -DCMAKE_PREFIX_PATH="$(brew --prefix curl);$(brew --prefix)" -cmake --build build -build/echo host [--app A] [--password P] [--ws libdatachannel|curl] # CODE XXXX-XXXX, then PEER -build/echo join [--app A] [--password P] [--ws libdatachannel|curl] -``` - -The echo contract of every Atyha example (the same as `ts/tools/peer.ts`): the host -answers a text "x" on `reliable` with "echo x" and sends binary back on its channel; -the joiner sends "hi" and the bytes 1,2,3 and prints `CONNECTED `, -`RELIABLE echo hi`, `UNRELIABLE 1,2,3` (exit 0), or `FAILED `. -`ATYHA_LOG=1` prints the relay log on stderr. `--ws` picks the WebSocket backend -for the relays (default libdatachannel; curl when `atyha_curl` was built). - -## Notes - -- Relays: an `OK false` or `CLOSED` saying `rate-limited:` closes that relay for 60 s; - `blocked:`, `restricted:`, `auth-required:` or `pow:` drops it for the session; a - closed connection reconnects after 2 s, doubling to 30 s. Events are deduplicated - by id (the last 1024), own events and events more than 60 s off the clock are - ignored. Received signatures are not checked (spec section 8 allows it). -- The Nostr `created_at` uses the wall clock (`time()`); the polls' `now_ms` may be - any monotonic millisecond clock (`atyha_now_ms()` is one). diff --git a/common/atyha/cmake/deps.cmake b/common/atyha/cmake/deps.cmake deleted file mode 100644 index add0911..0000000 --- a/common/atyha/cmake/deps.cmake +++ /dev/null @@ -1,68 +0,0 @@ -# SPDX-License-Identifier: MIT -# Copyright (c) 2026 ngspades contributors -# -# The two crypto libraries: -# - libsodium (ristretto255, SHA-2, HMAC, ChaCha20-Poly1305, randomness): -# an existing target atyha::sodium wins; else pkg-config; else -# find_library. Emscripten builds point SODIUM_ROOT at a libsodium built -# with emcc (its include/ and lib/). -# - bitcoin-core/libsecp256k1 (BIP-340 Schnorr for Nostr events), fetched -# at a pinned release with the schnorrsig and extrakeys modules. -include(FetchContent) - -if(NOT TARGET atyha::sodium) - set(SODIUM_ROOT "" CACHE PATH "A libsodium installation (include/, lib/) to use") - if(SODIUM_ROOT) - find_path(SODIUM_INCLUDE_DIR sodium.h PATHS "${SODIUM_ROOT}/include" NO_DEFAULT_PATH) - find_library(SODIUM_LIBRARY NAMES sodium libsodium PATHS "${SODIUM_ROOT}/lib" NO_DEFAULT_PATH) - else() - find_package(PkgConfig QUIET) - if(PKG_CONFIG_FOUND) - pkg_check_modules(PC_SODIUM QUIET libsodium) - endif() - find_path(SODIUM_INCLUDE_DIR sodium.h HINTS ${PC_SODIUM_INCLUDE_DIRS}) - find_library(SODIUM_LIBRARY NAMES sodium libsodium HINTS ${PC_SODIUM_LIBRARY_DIRS}) - endif() - if(NOT SODIUM_INCLUDE_DIR OR NOT SODIUM_LIBRARY) - message(FATAL_ERROR "atyha: libsodium not found (brew install libsodium / apt install libsodium-dev, " - "or -DSODIUM_ROOT=...)") - endif() - add_library(atyha::sodium INTERFACE IMPORTED) - set_target_properties(atyha::sodium PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES "${SODIUM_INCLUDE_DIR}" - INTERFACE_LINK_LIBRARIES "${SODIUM_LIBRARY}") - if(MSVC) - # a static libsodium on Windows - set_property(TARGET atyha::sodium APPEND PROPERTY INTERFACE_COMPILE_DEFINITIONS SODIUM_STATIC) - endif() - message(STATUS "atyha: libsodium ${SODIUM_LIBRARY}") -endif() - -if(NOT TARGET atyha::secp256k1) - set(ATYHA_SECP256K1_TAG "v0.8.0") - FetchContent_Declare( - secp256k1 - GIT_REPOSITORY https://github.com/bitcoin-core/secp256k1.git - GIT_TAG ${ATYHA_SECP256K1_TAG} - GIT_SHALLOW TRUE - ) - set(SECP256K1_ENABLE_MODULE_SCHNORRSIG ON CACHE BOOL "" FORCE) - set(SECP256K1_ENABLE_MODULE_EXTRAKEYS ON CACHE BOOL "" FORCE) - set(SECP256K1_ENABLE_MODULE_ECDH OFF CACHE BOOL "" FORCE) - set(SECP256K1_ENABLE_MODULE_RECOVERY OFF CACHE BOOL "" FORCE) - set(SECP256K1_ENABLE_MODULE_ELLSWIFT OFF CACHE BOOL "" FORCE) - set(SECP256K1_ENABLE_MODULE_MUSIG OFF CACHE BOOL "" FORCE) - set(SECP256K1_BUILD_TESTS OFF CACHE BOOL "" FORCE) - set(SECP256K1_BUILD_EXHAUSTIVE_TESTS OFF CACHE BOOL "" FORCE) - set(SECP256K1_BUILD_BENCHMARK OFF CACHE BOOL "" FORCE) - set(SECP256K1_BUILD_CTIME_TESTS OFF CACHE BOOL "" FORCE) - set(SECP256K1_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) - set(SECP256K1_INSTALL OFF CACHE BOOL "" FORCE) - set(_atyha_shared "${BUILD_SHARED_LIBS}") - set(BUILD_SHARED_LIBS OFF) - FetchContent_MakeAvailable(secp256k1) - set(BUILD_SHARED_LIBS "${_atyha_shared}") - add_library(atyha::secp256k1 INTERFACE IMPORTED) - target_link_libraries(atyha::secp256k1 INTERFACE secp256k1) - message(STATUS "atyha: libsecp256k1 ${ATYHA_SECP256K1_TAG} (fetched)") -endif() diff --git a/common/atyha/cmake/libdatachannel.cmake b/common/atyha/cmake/libdatachannel.cmake deleted file mode 100644 index c35296e..0000000 --- a/common/atyha/cmake/libdatachannel.cmake +++ /dev/null @@ -1,39 +0,0 @@ -# SPDX-License-Identifier: MIT -# Copyright (c) 2026 ngspades contributors -# -# libdatachannel for the example and the atyha_libdatachannel backend, when -# the parent project provides none: an installed package when there is one, -# else fetched at a pinned release, DataChannels and WebSocket (no media). -# Defines atyha::datachannel. -enable_language(CXX) -if(TARGET atyha::datachannel) - return() -endif() - -find_package(LibDataChannel CONFIG QUIET) -if(LibDataChannel_FOUND) - add_library(atyha::datachannel INTERFACE IMPORTED) - target_link_libraries(atyha::datachannel INTERFACE LibDataChannel::LibDataChannel) - return() -endif() - -include(FetchContent) -set(ATYHA_LIBDATACHANNEL_TAG "v0.24.6") -FetchContent_Declare( - libdatachannel - GIT_REPOSITORY https://github.com/paullouisageneau/libdatachannel.git - GIT_TAG ${ATYHA_LIBDATACHANNEL_TAG} - GIT_SHALLOW TRUE - GIT_SUBMODULES deps/plog deps/usrsctp deps/libjuice deps/json -) -set(NO_MEDIA ON CACHE BOOL "" FORCE) -set(NO_WEBSOCKET OFF CACHE BOOL "" FORCE) # the atyha_libdatachannel backend uses it -set(NO_EXAMPLES ON CACHE BOOL "" FORCE) -set(NO_TESTS ON CACHE BOOL "" FORCE) -set(_atyha_shared "${BUILD_SHARED_LIBS}") -set(BUILD_SHARED_LIBS OFF) -FetchContent_MakeAvailable(libdatachannel) -set(BUILD_SHARED_LIBS "${_atyha_shared}") -add_library(atyha::datachannel INTERFACE IMPORTED) -target_link_libraries(atyha::datachannel INTERFACE datachannel-static) -message(STATUS "atyha: libdatachannel ${ATYHA_LIBDATACHANNEL_TAG} (fetched)") diff --git a/common/atyha/include/atyha.h b/common/atyha/include/atyha.h deleted file mode 100644 index dba2ca3..0000000 --- a/common/atyha/include/atyha.h +++ /dev/null @@ -1,282 +0,0 @@ -/* SPDX-License-Identifier: MIT - Copyright (c) 2026 ngspades contributors - - atyha: join a host by a short room code over WebRTC, signalled through - public Nostr relays, with an optional password (CPace). Protocol: - spec/atyha-v1.md. - - This library is signalling only: it carries one SDP offer and one SDP - answer, both complete (no trickle ICE). The program makes the peer - connection with its own WebRTC stack. - - Everything is poll driven and single threaded: no thread is started, no - callback runs behind the program's back (the optional log callback runs - inside the poll that logs). Call atyha_host_poll() / atyha_joiner_poll() - every frame or tick until they return 0. An object is used by one thread - at a time; different objects are independent (no global state, apart - from libsodium's one-time initialisation, which atyha does itself). - - Strings are UTF-8 and NUL-terminated. Every string an event points to - stays valid until the next poll of the same object (or its destruction). */ -#ifndef ATYHA_H -#define ATYHA_H - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define ATYHA_VERSION "1.0.0" -#define ATYHA_PROTOCOL "atyha/1" -#define ATYHA_KIND 21490 -#define ATYHA_ALPHABET "ABCDEFHJKMNPRTUVWXYZ34579" -#define ATYHA_CODE_LEN 8 - -/* ------------------------------------------------------------------ codes */ - -/* a fresh code in canonical form ("HK4M7TRW"), NUL-terminated */ -void atyha_code_generate(char out[ATYHA_CODE_LEN + 1]); -/* what a person typed or pasted ("hk4m 7trw", "myapp://HK4M-7TRW") to its - canonical form; 1 when it is a code, 0 (out = "") when it is not */ -int atyha_code_parse(const char* text, char out[ATYHA_CODE_LEN + 1]); -/* "HK4M7TRW" -> "HK4M-7TRW" (anything else is copied, truncated to 9) */ -void atyha_code_display(const char* code, char out[ATYHA_CODE_LEN + 2]); -/* the room's Nostr topic, 64 lowercase hex characters */ -void atyha_topic(const char* app, const char* code, char out[65]); - -/* a monotonic clock in milliseconds, for programs without one at hand; any - monotonic millisecond clock may be passed to the polls instead */ -int64_t atyha_now_ms(void); - -/* -------------------------------------------------------------- ICE list */ - -/* an RTCIceServer: urls ("stun:host:port", "turn:host:port?transport=udp"), - and the TURN user and credential, or NULL */ -typedef struct atyha_ice_server { - const char* const* urls; - int url_count; - const char* username; - const char* credential; -} atyha_ice_server; - -/* one URL of an ICE server in libdatachannel's form, with the user and the - credential inside ("turn:user:pass@host:port?transport=udp", both - percent-encoded); returns the length it needs (snprintf-like), writes at - most cap bytes including the NUL */ -size_t atyha_ice_url_libdatachannel(const atyha_ice_server* server, int url_index, char* out, size_t cap); - -/* ------------------------------------------------------ the bus (section 8) */ - -/* What a session needs of a transport: publish a message (the JSON text of - spec section 6) to every other member of the topic, and hand over what - they publish. The Nostr relay pool is one (atyha_nostr_bus_open), the - in-memory hub another (tests); a program may write its own. */ -typedef enum atyha_bus_event_type { - ATYHA_BUS_NONE = 0, - ATYHA_BUS_READY, /* subscribed somewhere: what is published now is heard (once) */ - ATYHA_BUS_MESSAGE, /* text: a message another member published */ - ATYHA_BUS_LOG /* text: something for the log */ -} atyha_bus_event_type; - -typedef struct atyha_bus_event { - atyha_bus_event_type type; - const char* text; /* valid until the next poll of the bus */ -} atyha_bus_event; - -typedef struct atyha_bus atyha_bus; -struct atyha_bus { - void (*publish)(atyha_bus* bus, const char* message, int64_t now_ms); - /* 1 and *ev filled when something happened, 0 otherwise */ - int (*poll)(atyha_bus* bus, int64_t now_ms, atyha_bus_event* ev); - /* unsubscribes and frees */ - void (*destroy)(atyha_bus* bus); -}; - -/* opens a bus for one topic; the sessions call it once */ -typedef atyha_bus* (*atyha_bus_open_fn)(void* user, const char* topic); - -/* the in-memory hub: every bus opened on one hub hears the others of its - topic (delivered at their next poll). For tests. */ -typedef struct atyha_memory_hub atyha_memory_hub; -atyha_memory_hub* atyha_memory_hub_create(void); -/* only once every bus of the hub is destroyed */ -void atyha_memory_hub_destroy(atyha_memory_hub* hub); -/* an atyha_bus_open_fn; user is the hub */ -atyha_bus* atyha_memory_bus_open(void* hub, const char* topic); - -/* ------------------------------------------------ WebSocket backends (8) */ - -/* One WebSocket connection of a backend. The Nostr pool asks a backend for - connections, sends text frames on them and polls each for what happened. - Backends: atyha_curl.h (libcurl, native), atyha_emscripten.h (the - browser's WebSocket), or the program's own. */ -typedef struct atyha_ws atyha_ws; - -typedef enum atyha_ws_event_type { - ATYHA_WS_NONE = 0, - ATYHA_WS_OPEN, /* the connection is up: text can be sent */ - ATYHA_WS_TEXT, /* a whole text message: data, len (binary ones are dropped) */ - ATYHA_WS_CLOSED /* closed or failed (data: a reason, or NULL); no event after it */ -} atyha_ws_event_type; - -typedef struct atyha_ws_event { - atyha_ws_event_type type; - const char* data; /* valid until the next poll of this connection */ - size_t len; -} atyha_ws_event; - -typedef struct atyha_ws_backend atyha_ws_backend; -struct atyha_ws_backend { - /* starts connecting to url (wss://...); NULL when it cannot even start */ - atyha_ws* (*connect)(atyha_ws_backend* backend, const char* url); - /* queues one text message; 0 queued, -1 the connection is not usable */ - int (*send)(atyha_ws* ws, const char* text, size_t len); - /* 1 and *ev filled when something happened, 0 otherwise */ - int (*poll)(atyha_ws* ws, atyha_ws_event* ev); - /* closes (politely when it can) and frees the connection */ - void (*close)(atyha_ws* ws); - /* optional: drives the backend once per pool poll, before the polls */ - void (*update)(atyha_ws_backend* backend); -}; - -/* ------------------------------------------------- the Nostr bus (section 8) */ - -/* the relays of spec section 8, NULL-terminated */ -extern const char* const atyha_default_relays[]; - -typedef struct atyha_nostr_config { - atyha_ws_backend* ws; /* required; the program keeps it alive longer than the bus */ - const char* const* relays; /* NULL: atyha_default_relays */ - int relay_count; /* when relays is set */ -} atyha_nostr_config; - -/* a bus over Nostr relays (spec 8) with a fresh secp256k1 key; copies what - it needs of the config. NULL on a bad config or out of memory. */ -atyha_bus* atyha_nostr_bus_open(const atyha_nostr_config* config, const char* topic); - -/* ------------------------------------------------------------- sessions */ - -typedef enum atyha_error { - ATYHA_OK = 0, - ATYHA_ERR_BAD_CODE, /* not a room code */ - ATYHA_ERR_NO_RELAY, /* no relay could be reached in 10 s */ - ATYHA_ERR_NO_ROOM, /* nobody hosts that code (no pake by the deadline) */ - ATYHA_ERR_WRONG_PASSWORD, /* a host answered, but the password differs */ - ATYHA_ERR_REJECTED, /* the host's application refused: reason */ - ATYHA_ERR_NO_ANSWER, /* the host did not answer the offer by the deadline */ - ATYHA_ERR_CANCELLED /* atyha_joiner_cancel */ -} atyha_error; - -/* "bad_code", "no_relay", ... (the TS JoinError codes); "ok" for ATYHA_OK */ -const char* atyha_error_name(atyha_error error); - -typedef enum atyha_event_type { - ATYHA_EV_NONE = 0, - /* host: the room is reachable (a relay confirmed the subscription) */ - ATYHA_EV_OPEN, - /* host: a joiner with the right code and password sent its offer: sdp, - meta (its JSON object, or NULL), attempt (pass it to - atyha_host_answer / atyha_host_reject), joiner (its peer id) */ - ATYHA_EV_OFFER, - /* joiner: the host answered and the password is right: make the peer - connection (with ice when ice_count > 0, else your own servers), wait - for ICE gathering to complete, then atyha_joiner_set_offer. meta is - the host's JSON object or NULL. */ - ATYHA_EV_NEED_OFFER, - /* joiner: the host's answer sdp; the joiner is done */ - ATYHA_EV_ANSWER, - /* joiner: the join failed: error, reason (the host's text for - ATYHA_ERR_REJECTED, a sentence otherwise); the joiner is done */ - ATYHA_EV_ERROR, - /* either: a line for the log (text) */ - ATYHA_EV_LOG -} atyha_event_type; - -typedef struct atyha_event { - atyha_event_type type; - const char* sdp; - const char* meta; - const char* attempt; - const char* joiner; - const atyha_ice_server* ice; - int ice_count; - const char* ice_json; /* the host's "ice" array as JSON, or NULL */ - atyha_error error; - const char* reason; - const char* text; -} atyha_event; - -/* Where the session's messages travel. Exactly one of: bus_open (a custom - bus, such as atyha_memory_bus_open), or ws (the Nostr relays, through - that WebSocket backend). */ -typedef struct atyha_transport { - atyha_bus_open_fn bus_open; - void* bus_user; - atyha_ws_backend* ws; - const char* const* relays; /* for ws; NULL: atyha_default_relays */ - int relay_count; -} atyha_transport; - -/* ---- host (spec 7.2) ---- */ - -typedef struct atyha_host_config { - const char* app; /* required: 1..64 bytes */ - const char* code; /* NULL: a fresh one; else typed or canonical */ - const char* password; /* NULL or "": the code alone opens the room */ - const char* meta; /* NULL, or a JSON object (at most 2048 bytes) sent to every joiner */ - const atyha_ice_server* ice; /* sent to joiners so they use the same STUN/TURN */ - int ice_count; - int hello_budget; /* hellos answered per 60 s; 0: 20 */ - atyha_transport transport; -} atyha_host_config; - -typedef struct atyha_host atyha_host; - -/* NULL when the config is wrong (no app, bad code, meta not an object...) - or out of memory; the config is copied */ -atyha_host* atyha_host_create(const atyha_host_config* config); -/* the canonical code ("HK4M7TRW"); atyha_code_display for people */ -const char* atyha_host_code(const atyha_host* host); -int atyha_host_is_open(const atyha_host* host); -int atyha_host_poll(atyha_host* host, int64_t now_ms, atyha_event* ev); -/* the reply to an ATYHA_EV_OFFER, whenever the program has it (an answer - SDP with every candidate, or a refusal the joiner is shown). 0 sent; -1 - unknown or expired attempt, or already replied. The reply is sent at once - and again to every repeat of the same offer. */ -int atyha_host_answer(atyha_host* host, const char* attempt, const char* sdp); -int atyha_host_reject(atyha_host* host, const char* attempt, const char* reason); -/* closes the room (unsubscribes) and frees */ -void atyha_host_destroy(atyha_host* host); - -/* ---- joiner (spec 7.1) ---- */ - -typedef struct atyha_join_config { - const char* app; /* required */ - const char* code; /* as typed */ - const char* password; /* NULL or "" */ - const char* meta; /* NULL, or a JSON object sent with the offer */ - int timeout_ms; /* 0: 25000, the deadline for the pake and for the answer */ - atyha_transport transport; -} atyha_join_config; - -typedef struct atyha_joiner atyha_joiner; - -/* NULL only on a missing app or transport, or out of memory: a bad code is - reported by the first poll (ATYHA_ERR_BAD_CODE) */ -atyha_joiner* atyha_joiner_create(const atyha_join_config* config); -int atyha_joiner_poll(atyha_joiner* joiner, int64_t now_ms, atyha_event* ev); -/* the complete offer SDP, after ATYHA_EV_NEED_OFFER; 0 ok, -1 not now */ -int atyha_joiner_set_offer(atyha_joiner* joiner, const char* sdp); -/* the next poll reports ATYHA_ERR_CANCELLED (unless it already finished) */ -void atyha_joiner_cancel(atyha_joiner* joiner); -/* 1 once ANSWER or ERROR was reported */ -int atyha_joiner_done(const atyha_joiner* joiner); -void atyha_joiner_destroy(atyha_joiner* joiner); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/common/atyha/include/atyha_crypto.h b/common/atyha/include/atyha_crypto.h deleted file mode 100644 index 977dbad..0000000 --- a/common/atyha/include/atyha_crypto.h +++ /dev/null @@ -1,69 +0,0 @@ -/* SPDX-License-Identifier: MIT - Copyright (c) 2026 ngspades contributors - - The protocol's building blocks (spec sections 1, 4, 5), exposed for tests - and for other implementations to check against. No I/O. The sessions of - atyha.h use them; most programs never need this header. - - Functions that produce bytes of variable length write at most cap bytes - and return the length the result needs (call with cap 0 to learn it). */ -#ifndef ATYHA_CRYPTO_H -#define ATYHA_CRYPTO_H - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* libsodium's initialisation (idempotent; every create of atyha.h calls it). - 0 ok, -1 libsodium could not start. */ -int atyha_crypto_init(void); - -/* lv_cat (spec 1): n parts, each preceded by its LEB128 length */ -size_t atyha_lv_cat(uint8_t* out, size_t cap, int n, const uint8_t* const* parts, const size_t* lens); - -/* PRS = lv_cat(code, password), CI = lv_cat("atyha/1", app) */ -size_t atyha_prs(const char* code, const char* password, uint8_t* out, size_t cap); -size_t atyha_ci(const char* app, uint8_t* out, size_t cap); - -/* CPace (draft-irtf-cfrg-cpace-21, CPACE-RISTR255-SHA512) */ -size_t atyha_cpace_generator_string(const uint8_t* prs, size_t prs_len, const uint8_t* ci, size_t ci_len, - const uint8_t* sid, size_t sid_len, uint8_t* out, size_t cap); -/* g = element_derivation(SHA-512(generator_string)); 0 ok */ -int atyha_cpace_generator(const uint8_t* prs, size_t prs_len, const uint8_t* ci, size_t ci_len, - const uint8_t* sid, size_t sid_len, uint8_t g[32]); -/* a secret scalar: 32 random bytes, bits above 252 cleared, never 0 */ -void atyha_cpace_sample_scalar(uint8_t y[32]); -/* Y = y * g; 0 ok, -1 when the result is the identity */ -int atyha_cpace_share(const uint8_t g[32], const uint8_t y[32], uint8_t Y[32]); -/* K = y * X; -1 when X does not decode or K is the identity (abort) */ -int atyha_cpace_scalar_mult_vfy(const uint8_t y[32], const uint8_t X[32], uint8_t K[32]); -/* ISK = SHA-512(lv_cat("CPaceRistretto255_ISK", sid, K) || lv_cat(Ya, "") || lv_cat(Yb, "")) */ -void atyha_cpace_isk(const uint8_t* sid, size_t sid_len, const uint8_t K[32], const uint8_t Ya[32], - const uint8_t Yb[32], uint8_t isk[64]); - -/* k_hj, k_jh = HKDF-SHA-256(ISK, salt sid, "atyha/1 host to joiner" / "... joiner to host", 32) */ -void atyha_keys(const uint8_t isk[64], const uint8_t* sid, size_t sid_len, uint8_t k_hj[32], uint8_t k_jh[32]); - -/* sealing (spec 5): ChaCha20-Poly1305, nonce 11 zero bytes || n, - AD = lv_cat("atyha/1", t, sid). seal returns the length of b64u(c || tag) - (out gets it NUL-terminated when cap > that). open returns the plaintext - length, or -1 when c does not decode or does not open; plain gets at most - cap bytes (plus a NUL when room is left). */ -size_t atyha_seal(const uint8_t key[32], int n, const char* t, const uint8_t sid[16], const uint8_t* plain, - size_t plain_len, char* out, size_t cap); -long atyha_open(const uint8_t key[32], int n, const char* t, const uint8_t sid[16], const char* c, uint8_t* plain, - size_t cap); - -/* base64url without padding (spec 1); decode refuses padding, characters - outside the alphabet and non-zero trailing bits: -1 */ -size_t atyha_b64u_encode(const uint8_t* in, size_t len, char* out, size_t cap); -long atyha_b64u_decode(const char* in, size_t in_len, uint8_t* out, size_t cap); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/common/atyha/include/atyha_curl.h b/common/atyha/include/atyha_curl.h deleted file mode 100644 index 6749f39..0000000 --- a/common/atyha/include/atyha_curl.h +++ /dev/null @@ -1,34 +0,0 @@ -/* SPDX-License-Identifier: MIT - Copyright (c) 2026 ngspades contributors - - The libcurl WebSocket backend (target atyha_curl): every connection is an - easy handle with CURLOPT_CONNECT_ONLY = 2 driven by one multi handle, so - connecting (DNS, TCP, TLS, the upgrade) never blocks the poll; then - curl_ws_send / curl_ws_recv, non-blocking. Needs libcurl 8.11 or later - built with WebSocket support ("ws"/"wss" in `curl -V`'s protocols). */ -#ifndef ATYHA_CURL_H -#define ATYHA_CURL_H - -#include "atyha.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct atyha_curl_options { - const char* ca_file; /* CURLOPT_CAINFO, or NULL for libcurl's default */ - const char* user_agent; /* NULL: "atyha/1" */ - int connect_timeout_ms; /* 0: 10000 */ -} atyha_curl_options; - -/* NULL when libcurl lacks WebSocket support or out of memory. Calls - curl_global_init(CURL_GLOBAL_DEFAULT) (libcurl's own global state). One - backend serves any number of buses; it must outlive them. */ -atyha_ws_backend* atyha_curl_backend_create(const atyha_curl_options* options); -void atyha_curl_backend_destroy(atyha_ws_backend* backend); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/common/atyha/include/atyha_emscripten.h b/common/atyha/include/atyha_emscripten.h deleted file mode 100644 index 272d0b6..0000000 --- a/common/atyha/include/atyha_emscripten.h +++ /dev/null @@ -1,24 +0,0 @@ -/* SPDX-License-Identifier: MIT - Copyright (c) 2026 ngspades contributors - - The browser's WebSocket as an atyha backend (Emscripten builds; compiled - into atyha when EMSCRIPTEN is set). Link with -lwebsocket.js. The - browser calls back on the main thread between frames; the callbacks only - queue, the polls drain. */ -#ifndef ATYHA_EMSCRIPTEN_H -#define ATYHA_EMSCRIPTEN_H - -#include "atyha.h" - -#ifdef __cplusplus -extern "C" { -#endif - -atyha_ws_backend* atyha_emscripten_backend_create(void); -void atyha_emscripten_backend_destroy(atyha_ws_backend* backend); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/common/atyha/include/atyha_libdatachannel.h b/common/atyha/include/atyha_libdatachannel.h deleted file mode 100644 index ddbe4b4..0000000 --- a/common/atyha/include/atyha_libdatachannel.h +++ /dev/null @@ -1,32 +0,0 @@ -/* SPDX-License-Identifier: MIT - Copyright (c) 2026 ngspades contributors - - libdatachannel's own WebSocket client (rtc/rtc.h) as an atyha backend - (target atyha_libdatachannel), for programs that already link - libdatachannel (built with NO_WEBSOCKET OFF) and OpenSSL, and have no - libcurl with WebSocket support. libdatachannel calls back on its own - threads; those callbacks only queue under a lock, the polls drain. */ -#ifndef ATYHA_LIBDATACHANNEL_H -#define ATYHA_LIBDATACHANNEL_H - -#include "atyha.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct atyha_libdatachannel_options { - int disable_tls_verification; /* 0 (default): verify the relays' certificates */ - int connection_timeout_ms; /* 0: libdatachannel's default */ -} atyha_libdatachannel_options; - -/* options may be NULL. The program keeps libdatachannel initialised (it - calls rtcCleanup itself, after destroying the backend). */ -atyha_ws_backend* atyha_libdatachannel_backend_create(const atyha_libdatachannel_options* options); -void atyha_libdatachannel_backend_destroy(atyha_ws_backend* backend); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/common/atyha/src/crypto.c b/common/atyha/src/crypto.c deleted file mode 100644 index 6ec12b3..0000000 --- a/common/atyha/src/crypto.c +++ /dev/null @@ -1,389 +0,0 @@ -/* SPDX-License-Identifier: MIT - Copyright (c) 2026 ngspades contributors - - Codes (spec 3), topic (4), CPace, keys and sealing (5), on libsodium. */ -#include -#include - -#include - -#include "internal.h" -#include "atyha_crypto.h" - -int atyha_crypto_init(void) { return sodium_init() < 0 ? -1 : 0; } - -/* ---------------------------------------------------------------- lv_cat */ - -static size_t leb128(size_t n, uint8_t out[10]) -{ - size_t k = 0; - do { - uint8_t b = (uint8_t)(n & 0x7f); - n >>= 7; - if (n) b |= 0x80; - out[k++] = b; - } while (n); - return k; -} - -size_t atyha_lv_cat(uint8_t* out, size_t cap, int n, const uint8_t* const* parts, const size_t* lens) -{ - size_t at = 0; - int i; - for (i = 0; i < n; i++) { - uint8_t l[10]; - size_t k = leb128(lens[i], l), j; - for (j = 0; j < k; j++, at++) - if (at < cap) out[at] = l[j]; - for (j = 0; j < lens[i]; j++, at++) - if (at < cap) out[at] = parts[i][j]; - } - return at; -} - -static size_t lv_str2(const char* a, const char* b, uint8_t* out, size_t cap) -{ - const uint8_t* parts[2]; - size_t lens[2]; - parts[0] = (const uint8_t*)a; - parts[1] = (const uint8_t*)(b ? b : ""); - lens[0] = strlen(a); - lens[1] = strlen((const char*)parts[1]); - return atyha_lv_cat(out, cap, 2, parts, lens); -} - -size_t atyha_prs(const char* code, const char* password, uint8_t* out, size_t cap) -{ - return lv_str2(code, password, out, cap); -} - -size_t atyha_ci(const char* app, uint8_t* out, size_t cap) { return lv_str2(ATYHA_PROTOCOL, app, out, cap); } - -/* ----------------------------------------------------------------- codes */ - -void atyha_code_generate(char out[ATYHA_CODE_LEN + 1]) -{ - int n = 0; - atyha_crypto_init(); - while (n < ATYHA_CODE_LEN) { - uint8_t r[16]; - size_t i; - randombytes_buf(r, sizeof r); - for (i = 0; i < sizeof r && n < ATYHA_CODE_LEN; i++) - if (r[i] < 250) out[n++] = ATYHA_ALPHABET[r[i] % 25]; - sodium_memzero(r, sizeof r); - } - out[ATYHA_CODE_LEN] = 0; -} - -static int is_alpha(char c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); } - -/* the length of a White_Space character at s (UTF-8), or 0 */ -static size_t white_at(const char* s, const char* end) -{ - const unsigned char* u = (const unsigned char*)s; - size_t n = (size_t)(end - s); - unsigned cp; - if (!n) return 0; - if ((u[0] >= 0x09 && u[0] <= 0x0d) || u[0] == 0x20) return 1; - if (n >= 2 && u[0] == 0xc2 && (u[1] == 0x85 || u[1] == 0xa0)) return 2; - if (n >= 3 && (u[0] & 0xf0) == 0xe0 && (u[1] & 0xc0) == 0x80 && (u[2] & 0xc0) == 0x80) { - cp = (unsigned)(u[0] & 0x0f) << 12 | (unsigned)(u[1] & 0x3f) << 6 | (u[2] & 0x3f); - if (cp == 0x1680 || (cp >= 0x2000 && cp <= 0x200a) || cp == 0x2028 || cp == 0x2029 || cp == 0x202f || - cp == 0x205f || cp == 0x3000) - return 3; - } - return 0; -} - -int atyha_code_parse(const char* text, char out[ATYHA_CODE_LEN + 1]) -{ - const char* s = text; - const char* end; - int n = 0; - out[0] = 0; - if (!text) return 0; - /* step 0: surrounding white space (Unicode White_Space) */ - end = s + strlen(s); - for (;;) { - size_t k = white_at(s, end); - if (!k) break; - s += k; - } - while (end > s) { - size_t k = 0, back; - for (back = 1; back <= 3 && (size_t)(end - s) >= back && !k; back++) - if (white_at(end - back, end) == back) k = back; - if (!k) break; - end -= k; - } - /* a URI scheme: [A-Za-z][A-Za-z0-9+.-]*:// */ - if (is_alpha(*s)) { - const char* p = s + 1; - while (p < end && (is_alpha(*p) || (*p >= '0' && *p <= '9') || *p == '+' || *p == '.' || *p == '-')) p++; - if (end - p >= 3 && p[0] == ':' && p[1] == '/' && p[2] == '/') s = p + 3; - } - for (; s < end; s++) { - char c = *s; - if (c == '-' || c == ' ' || c == '\t') continue; - if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A'); - if (!c || !strchr(ATYHA_ALPHABET, c) || n == ATYHA_CODE_LEN) { - out[0] = 0; - return 0; - } - out[n++] = c; - } - if (n != ATYHA_CODE_LEN) { - out[0] = 0; - return 0; - } - out[n] = 0; - return 1; -} - -void atyha_code_display(const char* code, char out[ATYHA_CODE_LEN + 2]) -{ - if (code && strlen(code) == ATYHA_CODE_LEN) { - memcpy(out, code, 4); - out[4] = '-'; - memcpy(out + 5, code + 4, 4); - out[9] = 0; - } else { - size_t n = code ? strlen(code) : 0; - if (n > ATYHA_CODE_LEN + 1) n = ATYHA_CODE_LEN + 1; - if (n) memcpy(out, code, n); - out[n] = 0; - } -} - -void atyha_topic(const char* app, const char* code, char out[65]) -{ - const char* label = "atyha/1 topic"; - const uint8_t* parts[3]; - size_t lens[3], n; - uint8_t* buf; - uint8_t h[32]; - parts[0] = (const uint8_t*)label, lens[0] = strlen(label); - parts[1] = (const uint8_t*)app, lens[1] = strlen(app); - parts[2] = (const uint8_t*)code, lens[2] = strlen(code); - n = atyha_lv_cat(NULL, 0, 3, parts, lens); - buf = (uint8_t*)malloc(n); - if (!buf) { - out[0] = 0; - return; - } - atyha_lv_cat(buf, n, 3, parts, lens); - crypto_hash_sha256(h, buf, n); - free(buf); - nj_hex(h, 32, out); -} - -/* ----------------------------------------------------------------- CPace */ - -static const char DSI[] = "CPaceRistretto255"; -static const char DSI_ISK[] = "CPaceRistretto255_ISK"; -#define S_IN_BYTES 128 - -size_t atyha_cpace_generator_string(const uint8_t* prs, size_t prs_len, const uint8_t* ci, size_t ci_len, - const uint8_t* sid, size_t sid_len, uint8_t* out, size_t cap) -{ - uint8_t l[10]; - size_t dsi_len = sizeof DSI - 1; - size_t pre = leb128(prs_len, l) + prs_len + leb128(dsi_len, l) + dsi_len; - size_t zpad = S_IN_BYTES - 1 > pre ? S_IN_BYTES - 1 - pre : 0; - static const uint8_t zeros[S_IN_BYTES] = {0}; - const uint8_t* parts[5]; - size_t lens[5]; - parts[0] = (const uint8_t*)DSI, lens[0] = dsi_len; - parts[1] = prs, lens[1] = prs_len; - parts[2] = zeros, lens[2] = zpad; - parts[3] = ci, lens[3] = ci_len; - parts[4] = sid, lens[4] = sid_len; - return atyha_lv_cat(out, cap, 5, parts, lens); -} - -int atyha_cpace_generator(const uint8_t* prs, size_t prs_len, const uint8_t* ci, size_t ci_len, - const uint8_t* sid, size_t sid_len, uint8_t g[32]) -{ - size_t n = atyha_cpace_generator_string(prs, prs_len, ci, ci_len, sid, sid_len, NULL, 0); - uint8_t* s = (uint8_t*)malloc(n); - uint8_t h[64]; - if (!s) return -1; - atyha_cpace_generator_string(prs, prs_len, ci, ci_len, sid, sid_len, s, n); - crypto_hash_sha512(h, s, n); - sodium_memzero(s, n); /* holds the password */ - free(s); - /* RFC 9496 element derivation from 64 bytes */ - crypto_core_ristretto255_from_hash(g, h); - sodium_memzero(h, sizeof h); - return 0; -} - -void atyha_cpace_sample_scalar(uint8_t y[32]) -{ - for (;;) { - int i, zero = 1; - randombytes_buf(y, 32); - y[31] &= 0x0f; /* < 2^252 < the group order */ - for (i = 0; i < 32; i++) - if (y[i]) zero = 0; - if (!zero) return; - } -} - -/* libsodium's crypto_scalarmult_ristretto255 clears the scalar's top bit - (a no-op below 2^252), refuses an input that does not decode and a result - that is the identity: CPace's scalar_mult_vfy for our scalars */ -int atyha_cpace_share(const uint8_t g[32], const uint8_t y[32], uint8_t Y[32]) -{ - return crypto_scalarmult_ristretto255(Y, y, g) == 0 ? 0 : -1; -} - -int atyha_cpace_scalar_mult_vfy(const uint8_t y[32], const uint8_t X[32], uint8_t K[32]) -{ - if (y[31] & 0xf0) { - /* a scalar of ours never has these bits; reduce anything else */ - uint8_t wide[64] = {0}, r[32]; - int ok; - memcpy(wide, y, 32); - crypto_core_ristretto255_scalar_reduce(r, wide); - ok = crypto_scalarmult_ristretto255(K, r, X) == 0; - sodium_memzero(r, sizeof r); - return ok ? 0 : -1; - } - return crypto_scalarmult_ristretto255(K, y, X) == 0 ? 0 : -1; -} - -void atyha_cpace_isk(const uint8_t* sid, size_t sid_len, const uint8_t K[32], const uint8_t Ya[32], - const uint8_t Yb[32], uint8_t isk[64]) -{ - uint8_t buf[256]; - const uint8_t* parts[3]; - size_t lens[3], n; - crypto_hash_sha512_state st; - crypto_hash_sha512_init(&st); - parts[0] = (const uint8_t*)DSI_ISK, lens[0] = sizeof DSI_ISK - 1; - parts[1] = sid, lens[1] = sid_len; - parts[2] = K, lens[2] = 32; - n = atyha_lv_cat(NULL, 0, 3, parts, lens); - if (n <= sizeof buf) { - atyha_lv_cat(buf, sizeof buf, 3, parts, lens); - crypto_hash_sha512_update(&st, buf, n); - } else { - uint8_t l[10]; - int i; - for (i = 0; i < 3; i++) { - crypto_hash_sha512_update(&st, l, leb128(lens[i], l)); - crypto_hash_sha512_update(&st, parts[i], lens[i]); - } - } - /* transcript_ir: lv_cat(Ya, ADa) || lv_cat(Yb, ADb), AD empty */ - buf[0] = 32; - memcpy(buf + 1, Ya, 32); - buf[33] = 0; - buf[34] = 32; - memcpy(buf + 35, Yb, 32); - buf[67] = 0; - crypto_hash_sha512_update(&st, buf, 68); - crypto_hash_sha512_final(&st, isk); - sodium_memzero(buf, sizeof buf); -} - -/* ------------------------------------------------------------------ keys */ - -static void hkdf32(const uint8_t* ikm, size_t ikm_len, const uint8_t* salt, size_t salt_len, const char* info, - uint8_t out[32]) -{ - uint8_t prk[32]; - uint8_t one = 1; - crypto_auth_hmacsha256_state st; - /* extract: PRK = HMAC(salt, IKM) */ - crypto_auth_hmacsha256_init(&st, salt, salt_len); - crypto_auth_hmacsha256_update(&st, ikm, ikm_len); - crypto_auth_hmacsha256_final(&st, prk); - /* expand, one block: T(1) = HMAC(PRK, info || 0x01) */ - crypto_auth_hmacsha256_init(&st, prk, sizeof prk); - crypto_auth_hmacsha256_update(&st, (const uint8_t*)info, strlen(info)); - crypto_auth_hmacsha256_update(&st, &one, 1); - crypto_auth_hmacsha256_final(&st, out); - sodium_memzero(prk, sizeof prk); - sodium_memzero(&st, sizeof st); -} - -void atyha_keys(const uint8_t isk[64], const uint8_t* sid, size_t sid_len, uint8_t k_hj[32], uint8_t k_jh[32]) -{ - hkdf32(isk, 64, sid, sid_len, "atyha/1 host to joiner", k_hj); - hkdf32(isk, 64, sid, sid_len, "atyha/1 joiner to host", k_jh); -} - -/* --------------------------------------------------------------- sealing */ - -static size_t aad_of(const char* t, const uint8_t sid[16], uint8_t out[64]) -{ - const uint8_t* parts[3]; - size_t lens[3]; - parts[0] = (const uint8_t*)ATYHA_PROTOCOL, lens[0] = strlen(ATYHA_PROTOCOL); - parts[1] = (const uint8_t*)t, lens[1] = strlen(t); - parts[2] = sid, lens[2] = 16; - return atyha_lv_cat(out, 64, 3, parts, lens); -} - -size_t atyha_seal(const uint8_t key[32], int n, const char* t, const uint8_t sid[16], const uint8_t* plain, - size_t plain_len, char* out, size_t cap) -{ - uint8_t nonce[crypto_aead_chacha20poly1305_ietf_NPUBBYTES] = {0}; - uint8_t aad[64]; - size_t aad_len = aad_of(t, sid, aad); - size_t clen = plain_len + crypto_aead_chacha20poly1305_ietf_ABYTES; - size_t need = clen / 3 * 4 + (clen % 3 ? clen % 3 + 1 : 0); - uint8_t* c; - unsigned long long got = 0; - if (cap <= need) return need; - c = (uint8_t*)malloc(clen); - if (!c) return 0; - nonce[11] = (uint8_t)n; - crypto_aead_chacha20poly1305_ietf_encrypt(c, &got, plain, plain_len, aad, aad_len, NULL, nonce, key); - atyha_b64u_encode(c, (size_t)got, out, cap); - free(c); - return need; -} - -long atyha_open(const uint8_t key[32], int n, const char* t, const uint8_t sid[16], const char* c, uint8_t* plain, - size_t cap) -{ - uint8_t nonce[crypto_aead_chacha20poly1305_ietf_NPUBBYTES] = {0}; - uint8_t aad[64]; - size_t aad_len = aad_of(t, sid, aad), clen_max = strlen(c), mlen; - long clen; - uint8_t *cbuf, *m; - unsigned long long got = 0; - int ok; - cbuf = (uint8_t*)malloc(clen_max + 1); - if (!cbuf) return -1; - clen = atyha_b64u_decode(c, clen_max, cbuf, clen_max); - if (clen < (long)crypto_aead_chacha20poly1305_ietf_ABYTES) { - free(cbuf); - return -1; - } - mlen = (size_t)clen - crypto_aead_chacha20poly1305_ietf_ABYTES; - m = (uint8_t*)malloc(mlen + 1); - if (!m) { - free(cbuf); - return -1; - } - nonce[11] = (uint8_t)n; - ok = crypto_aead_chacha20poly1305_ietf_decrypt(m, &got, NULL, cbuf, (unsigned long long)clen, aad, aad_len, nonce, - key) == 0; - free(cbuf); - if (!ok) { - free(m); - return -1; - } - if (plain && cap) { - size_t k = got < cap ? (size_t)got : cap; - memcpy(plain, m, k); - if (k < cap) plain[k] = 0; - } - free(m); - return (long)got; -} diff --git a/common/atyha/src/internal.h b/common/atyha/src/internal.h deleted file mode 100644 index 1e70d91..0000000 --- a/common/atyha/src/internal.h +++ /dev/null @@ -1,81 +0,0 @@ -/* SPDX-License-Identifier: MIT - Copyright (c) 2026 ngspades contributors - - Internal helpers shared by the sources: a growable buffer, a strict JSON - parser and writer, hex. Not installed. */ -#ifndef ATYHA_INTERNAL_H -#define ATYHA_INTERNAL_H - -#include -#include - -#include "atyha.h" - -/* ---- growable byte buffer (always NUL-terminated when p != NULL) ---- */ -typedef struct nj_buf { - char* p; - size_t n, cap; - int oom; -} nj_buf; - -void nj_buf_reserve(nj_buf* b, size_t more); -void nj_buf_put(nj_buf* b, const void* data, size_t len); -void nj_buf_puts(nj_buf* b, const char* s); -void nj_buf_putc(nj_buf* b, char c); -void nj_buf_printf(nj_buf* b, const char* fmt, ...); -/* a JSON string literal of s (NIP-01 escaping: \" \\ \b \f \n \r \t, other - bytes below 0x20 as \u00xx, everything else verbatim) */ -void nj_buf_json_str(nj_buf* b, const char* s, size_t len); -/* hands the bytes over (the caller frees); "" when empty or out of memory */ -char* nj_buf_take(nj_buf* b); -void nj_buf_free(nj_buf* b); - -char* nj_strdup(const char* s); -void nj_hex(const uint8_t* in, size_t len, char* out); /* out: 2*len+1 */ -int nj_unhex(const char* in, size_t len, uint8_t* out); /* 0 ok, -1 not hex (len chars -> len/2 bytes) */ - -/* ---- strict JSON (RFC 8259) ---- */ -typedef enum nj_type { NJ_NULL, NJ_FALSE, NJ_TRUE, NJ_NUMBER, NJ_STRING, NJ_ARRAY, NJ_OBJECT } nj_type; - -typedef struct nj_value nj_value; -struct nj_value { - nj_type type; - const char* raw; /* the value's text in the source */ - size_t raw_len; - char* str; /* STRING: decoded, NUL-terminated */ - size_t len; - double num; /* NUMBER */ - nj_value* child; /* ARRAY elements, OBJECT members */ - nj_value* next; - size_t count; - char* key; /* when a member of an object */ - size_t key_len; -}; - -/* NULL when text is not exactly one JSON value (UTF-8 checked, depth <= 64) */ -nj_value* nj_parse(const char* text, size_t len); -void nj_free(nj_value* v); -/* the member named key (the last one when repeated), or NULL */ -nj_value* nj_get(const nj_value* obj, const char* key); -nj_value* nj_at(const nj_value* arr, size_t index); -/* a STRING member, or NULL */ -const char* nj_get_str(const nj_value* obj, const char* key); -/* 1 when text is one JSON object */ -int nj_is_object_text(const char* text); - -/* ---- nostr events (nostr.c), exposed for the tests ---- */ -typedef struct nj_nostr_key { - uint8_t seckey[32]; - char pubkey_hex[65]; - void* ctx; /* secp256k1_context* */ -} nj_nostr_key; - -int nj_nostr_key_new(nj_nostr_key* key); -void nj_nostr_key_free(nj_nostr_key* key); -/* the ["EVENT", {...}] text of a kind-21490 event; also its id (hex) */ -char* nj_nostr_event(const nj_nostr_key* key, const char* topic, const char* content, int64_t created_at, - char id_hex[65]); -/* the NIP-01 serialization [0,pubkey,created_at,kind,tags,content] */ -char* nj_nostr_serialize(const char* pubkey_hex, int64_t created_at, int kind, const char* topic, const char* content); - -#endif diff --git a/common/atyha/src/json.c b/common/atyha/src/json.c deleted file mode 100644 index ea57fef..0000000 --- a/common/atyha/src/json.c +++ /dev/null @@ -1,360 +0,0 @@ -/* SPDX-License-Identifier: MIT - Copyright (c) 2026 ngspades contributors - - A small strict JSON parser (RFC 8259): one value, no trailing text, UTF-8 - checked, \u escapes decoded (surrogate pairs joined, lone ones refused), - nesting at most 64 deep. Every value keeps its span in the source, so an - object can be handed on as the text it came as. */ -#include -#include - -#include "internal.h" - -#define MAX_DEPTH 64 - -typedef struct { - const char* s; - size_t n, i; - int depth; -} parser; - -static void skip_ws(parser* p) -{ - while (p->i < p->n) { - char c = p->s[p->i]; - if (c == ' ' || c == '\t' || c == '\n' || c == '\r') p->i++; - else break; - } -} - -static nj_value* new_value(nj_type t, parser* p) -{ - nj_value* v = (nj_value*)calloc(1, sizeof *v); - if (v) { - v->type = t; - v->raw = p->s + p->i; - } - return v; -} - -void nj_free(nj_value* v) -{ - while (v) { - nj_value* next = v->next; - nj_free(v->child); - free(v->str); - free(v->key); - free(v); - v = next; - } -} - -/* the length of the UTF-8 sequence at s (n bytes left), or 0 when invalid */ -static size_t utf8_len(const unsigned char* s, size_t n) -{ - unsigned c = s[0]; - if (c < 0x80) return 1; - if (c >= 0xc2 && c <= 0xdf) return n >= 2 && (s[1] & 0xc0) == 0x80 ? 2 : 0; - if (c >= 0xe0 && c <= 0xef) { - if (n < 3 || (s[1] & 0xc0) != 0x80 || (s[2] & 0xc0) != 0x80) return 0; - if (c == 0xe0 && s[1] < 0xa0) return 0; /* overlong */ - if (c == 0xed && s[1] >= 0xa0) return 0; /* surrogate */ - return 3; - } - if (c >= 0xf0 && c <= 0xf4) { - if (n < 4 || (s[1] & 0xc0) != 0x80 || (s[2] & 0xc0) != 0x80 || (s[3] & 0xc0) != 0x80) return 0; - if (c == 0xf0 && s[1] < 0x90) return 0; - if (c == 0xf4 && s[1] >= 0x90) return 0; - return 4; - } - return 0; -} - -static int hex4(parser* p, unsigned* out) -{ - unsigned v = 0; - int k; - if (p->i + 4 > p->n) return -1; - for (k = 0; k < 4; k++) { - char c = p->s[p->i++]; - v <<= 4; - if (c >= '0' && c <= '9') v |= (unsigned)(c - '0'); - else if (c >= 'a' && c <= 'f') v |= (unsigned)(c - 'a' + 10); - else if (c >= 'A' && c <= 'F') v |= (unsigned)(c - 'A' + 10); - else return -1; - } - *out = v; - return 0; -} - -static void put_utf8(nj_buf* b, unsigned cp) -{ - char u[4]; - if (cp < 0x80) { - u[0] = (char)cp; - nj_buf_put(b, u, 1); - } else if (cp < 0x800) { - u[0] = (char)(0xc0 | cp >> 6); - u[1] = (char)(0x80 | (cp & 63)); - nj_buf_put(b, u, 2); - } else if (cp < 0x10000) { - u[0] = (char)(0xe0 | cp >> 12); - u[1] = (char)(0x80 | (cp >> 6 & 63)); - u[2] = (char)(0x80 | (cp & 63)); - nj_buf_put(b, u, 3); - } else { - u[0] = (char)(0xf0 | cp >> 18); - u[1] = (char)(0x80 | (cp >> 12 & 63)); - u[2] = (char)(0x80 | (cp >> 6 & 63)); - u[3] = (char)(0x80 | (cp & 63)); - nj_buf_put(b, u, 4); - } -} - -/* at the opening quote; the decoded string in *out (malloc'd) */ -static int parse_string(parser* p, char** out, size_t* out_len) -{ - nj_buf b = {0}; - p->i++; /* " */ - nj_buf_reserve(&b, 16); - for (;;) { - unsigned char c; - if (p->i >= p->n) goto fail; - c = (unsigned char)p->s[p->i]; - if (c == '"') { - p->i++; - break; - } - if (c < 0x20) goto fail; - if (c == '\\') { - char e; - p->i++; - if (p->i >= p->n) goto fail; - e = p->s[p->i++]; - switch (e) { - case '"': nj_buf_putc(&b, '"'); break; - case '\\': nj_buf_putc(&b, '\\'); break; - case '/': nj_buf_putc(&b, '/'); break; - case 'b': nj_buf_putc(&b, '\b'); break; - case 'f': nj_buf_putc(&b, '\f'); break; - case 'n': nj_buf_putc(&b, '\n'); break; - case 'r': nj_buf_putc(&b, '\r'); break; - case 't': nj_buf_putc(&b, '\t'); break; - case 'u': { - unsigned cp, lo; - if (hex4(p, &cp)) goto fail; - if (cp >= 0xd800 && cp <= 0xdbff) { - if (p->i + 2 > p->n || p->s[p->i] != '\\' || p->s[p->i + 1] != 'u') goto fail; - p->i += 2; - if (hex4(p, &lo) || lo < 0xdc00 || lo > 0xdfff) goto fail; - cp = 0x10000 + ((cp - 0xd800) << 10) + (lo - 0xdc00); - } else if (cp >= 0xdc00 && cp <= 0xdfff) { - goto fail; - } - put_utf8(&b, cp); - break; - } - default: goto fail; - } - } else { - size_t k = utf8_len((const unsigned char*)p->s + p->i, p->n - p->i); - if (!k) goto fail; - nj_buf_put(&b, p->s + p->i, k); - p->i += k; - } - } - if (b.oom) goto fail; - *out_len = b.n; - *out = nj_buf_take(&b); - return *out ? 0 : -1; -fail: - nj_buf_free(&b); - return -1; -} - -static int parse_number(parser* p, double* out) -{ - size_t start = p->i; - double mant = 0, scale = 1; - int neg = 0, eneg = 0, ex = 0; - if (p->s[p->i] == '-') { - neg = 1; - p->i++; - } - if (p->i >= p->n) return -1; - if (p->s[p->i] == '0') { - p->i++; - } else if (p->s[p->i] >= '1' && p->s[p->i] <= '9') { - while (p->i < p->n && p->s[p->i] >= '0' && p->s[p->i] <= '9') mant = mant * 10 + (p->s[p->i++] - '0'); - } else { - return -1; - } - if (p->i < p->n && p->s[p->i] == '.') { - p->i++; - if (p->i >= p->n || p->s[p->i] < '0' || p->s[p->i] > '9') return -1; - while (p->i < p->n && p->s[p->i] >= '0' && p->s[p->i] <= '9') { - scale /= 10; - mant += (p->s[p->i++] - '0') * scale; - } - } - if (p->i < p->n && (p->s[p->i] == 'e' || p->s[p->i] == 'E')) { - p->i++; - if (p->i < p->n && (p->s[p->i] == '+' || p->s[p->i] == '-')) eneg = p->s[p->i++] == '-'; - if (p->i >= p->n || p->s[p->i] < '0' || p->s[p->i] > '9') return -1; - while (p->i < p->n && p->s[p->i] >= '0' && p->s[p->i] <= '9') { - if (ex < 100000) ex = ex * 10 + (p->s[p->i] - '0'); - p->i++; - } - while (ex-- > 0) { - mant = eneg ? mant / 10 : mant * 10; - if (mant == 0 || mant > 1e308) break; - } - } - (void)start; - *out = neg ? -mant : mant; - return 0; -} - -static nj_value* parse_value(parser* p); - -static int literal(parser* p, const char* word) -{ - size_t k = strlen(word); - if (p->n - p->i < k || memcmp(p->s + p->i, word, k)) return -1; - p->i += k; - return 0; -} - -static nj_value* parse_value(parser* p) -{ - nj_value* v = NULL; - char c; - skip_ws(p); - if (p->i >= p->n) return NULL; - c = p->s[p->i]; - if (c == '{' || c == '[') { - nj_value** tail; - int obj = c == '{'; - if (++p->depth > MAX_DEPTH) return NULL; - v = new_value(obj ? NJ_OBJECT : NJ_ARRAY, p); - if (!v) return NULL; - tail = &v->child; - p->i++; - skip_ws(p); - if (p->i < p->n && p->s[p->i] == (obj ? '}' : ']')) { - p->i++; - } else { - for (;;) { - nj_value* item; - char* key = NULL; - size_t key_len = 0; - if (obj) { - skip_ws(p); - if (p->i >= p->n || p->s[p->i] != '"' || parse_string(p, &key, &key_len)) goto fail; - skip_ws(p); - if (p->i >= p->n || p->s[p->i] != ':') { - free(key); - goto fail; - } - p->i++; - } - item = parse_value(p); - if (!item) { - free(key); - goto fail; - } - item->key = key; - item->key_len = key_len; - *tail = item; - tail = &item->next; - v->count++; - skip_ws(p); - if (p->i >= p->n) goto fail; - if (p->s[p->i] == ',') { - p->i++; - continue; - } - if (p->s[p->i] == (obj ? '}' : ']')) { - p->i++; - break; - } - goto fail; - } - } - p->depth--; - } else if (c == '"') { - v = new_value(NJ_STRING, p); - if (!v || parse_string(p, &v->str, &v->len)) goto fail; - } else if (c == '-' || (c >= '0' && c <= '9')) { - v = new_value(NJ_NUMBER, p); - if (!v || parse_number(p, &v->num)) goto fail; - } else if (c == 't') { - v = new_value(NJ_TRUE, p); - if (!v || literal(p, "true")) goto fail; - } else if (c == 'f') { - v = new_value(NJ_FALSE, p); - if (!v || literal(p, "false")) goto fail; - } else if (c == 'n') { - v = new_value(NJ_NULL, p); - if (!v || literal(p, "null")) goto fail; - } else { - return NULL; - } - v->raw_len = (size_t)(p->s + p->i - v->raw); - return v; -fail: - nj_free(v); - return NULL; -} - -nj_value* nj_parse(const char* text, size_t len) -{ - parser p; - nj_value* v; - if (!text) return NULL; - p.s = text; - p.n = len; - p.i = 0; - p.depth = 0; - v = parse_value(&p); - if (!v) return NULL; - skip_ws(&p); - if (p.i != p.n) { - nj_free(v); - return NULL; - } - return v; -} - -nj_value* nj_get(const nj_value* obj, const char* key) -{ - nj_value *c, *found = NULL; - size_t k; - if (!obj || obj->type != NJ_OBJECT) return NULL; - k = strlen(key); - for (c = obj->child; c; c = c->next) - if (c->key_len == k && !memcmp(c->key, key, k)) found = c; - return found; -} - -nj_value* nj_at(const nj_value* arr, size_t index) -{ - nj_value* c; - if (!arr || arr->type != NJ_ARRAY) return NULL; - for (c = arr->child; c && index; c = c->next) index--; - return c; -} - -const char* nj_get_str(const nj_value* obj, const char* key) -{ - nj_value* v = nj_get(obj, key); - return v && v->type == NJ_STRING ? v->str : NULL; -} - -int nj_is_object_text(const char* text) -{ - nj_value* v = text ? nj_parse(text, strlen(text)) : NULL; - int ok = v && v->type == NJ_OBJECT; - nj_free(v); - return ok; -} diff --git a/common/atyha/src/membus.c b/common/atyha/src/membus.c deleted file mode 100644 index 37a2d2e..0000000 --- a/common/atyha/src/membus.c +++ /dev/null @@ -1,112 +0,0 @@ -/* SPDX-License-Identifier: MIT - Copyright (c) 2026 ngspades contributors - - The in-memory hub (tests): every bus of a hub hears the others of its - topic; a message is delivered at the receiver's next poll. */ -#include -#include - -#include "internal.h" - -typedef struct mem_msg { - char* text; - struct mem_msg* next; -} mem_msg; - -typedef struct mem_bus { - atyha_bus base; - atyha_memory_hub* hub; - char topic[65]; - int ready_sent; - mem_msg *head, *tail; - char* current; - struct mem_bus* next; -} mem_bus; - -struct atyha_memory_hub { - mem_bus* members; -}; - -atyha_memory_hub* atyha_memory_hub_create(void) { return (atyha_memory_hub*)calloc(1, sizeof(atyha_memory_hub)); } - -void atyha_memory_hub_destroy(atyha_memory_hub* hub) { free(hub); } - -static void mem_publish(atyha_bus* b, const char* message, int64_t now) -{ - mem_bus* me = (mem_bus*)b; - mem_bus* m; - (void)now; - for (m = me->hub->members; m; m = m->next) { - mem_msg* q; - if (m == me || strcmp(m->topic, me->topic)) continue; - q = (mem_msg*)calloc(1, sizeof *q); - if (!q) continue; - q->text = nj_strdup(message); - if (m->tail) m->tail->next = q; - else m->head = q; - m->tail = q; - } -} - -static int mem_poll(atyha_bus* b, int64_t now, atyha_bus_event* ev) -{ - mem_bus* me = (mem_bus*)b; - mem_msg* q; - (void)now; - free(me->current); - me->current = NULL; - if (!me->ready_sent) { - me->ready_sent = 1; - ev->type = ATYHA_BUS_READY; - ev->text = NULL; - return 1; - } - q = me->head; - if (!q) { - ev->type = ATYHA_BUS_NONE; - ev->text = NULL; - return 0; - } - me->head = q->next; - if (!me->head) me->tail = NULL; - me->current = q->text; - free(q); - ev->type = ATYHA_BUS_MESSAGE; - ev->text = me->current; - return 1; -} - -static void mem_destroy(atyha_bus* b) -{ - mem_bus* me = (mem_bus*)b; - mem_bus** pm; - for (pm = &me->hub->members; *pm; pm = &(*pm)->next) - if (*pm == me) { - *pm = me->next; - break; - } - while (me->head) { - mem_msg* q = me->head; - me->head = q->next; - free(q->text); - free(q); - } - free(me->current); - free(me); -} - -atyha_bus* atyha_memory_bus_open(void* hub, const char* topic) -{ - mem_bus* b; - if (!hub || !topic || strlen(topic) > 64) return NULL; - b = (mem_bus*)calloc(1, sizeof *b); - if (!b) return NULL; - b->base.publish = mem_publish; - b->base.poll = mem_poll; - b->base.destroy = mem_destroy; - b->hub = (atyha_memory_hub*)hub; - strcpy(b->topic, topic); - b->next = b->hub->members; - b->hub->members = b; - return &b->base; -} diff --git a/common/atyha/src/message.c b/common/atyha/src/message.c deleted file mode 100644 index 2c23d6d..0000000 --- a/common/atyha/src/message.c +++ /dev/null @@ -1,101 +0,0 @@ -/* SPDX-License-Identifier: MIT - Copyright (c) 2026 ngspades contributors */ -#include -#include - -#include "internal.h" -#include "message.h" -#include "atyha_crypto.h" - -static const char* const NAMES[] = {"", "hello", "pake", "offer", "answer", "reject"}; - -const char* nj_msg_type_name(int t) { return t >= NJ_HELLO && t <= NJ_REJECT ? NAMES[t] : ""; } - -static int id16(const nj_value* v, char out[NJ_ID_B64], uint8_t bytes[16]) -{ - uint8_t tmp[16]; - if (!v || v->type != NJ_STRING || v->len != 22) return 0; - if (atyha_b64u_decode(v->str, v->len, bytes ? bytes : tmp, 16) != 16) return 0; - memcpy(out, v->str, 23); - return 1; -} - -int nj_msg_parse(const char* text, nj_msg* out) -{ - nj_value *m, *v, *t, *Y, *c; - int i, type = 0; - memset(out, 0, sizeof *out); - m = nj_parse(text, strlen(text)); - if (!m || m->type != NJ_OBJECT) goto fail; - v = nj_get(m, "v"); - if (!v || v->type != NJ_NUMBER || v->num != 1) goto fail; - t = nj_get(m, "t"); - if (!t || t->type != NJ_STRING) goto fail; - for (i = NJ_HELLO; i <= NJ_REJECT; i++) - if (!strcmp(t->str, NAMES[i])) type = i; - if (!type) goto fail; - out->t = type; - if (!id16(nj_get(m, "sid"), out->sid, out->sid_bytes) || !id16(nj_get(m, "from"), out->from, NULL)) goto fail; - if (type != NJ_HELLO && !id16(nj_get(m, "to"), out->to, NULL)) goto fail; - if (type == NJ_HELLO || type == NJ_PAKE) { - Y = nj_get(m, "Y"); - if (!Y || Y->type != NJ_STRING || atyha_b64u_decode(Y->str, Y->len, out->Y, 32) != 32) goto fail; - out->has_Y = 1; - } - if (type != NJ_HELLO) { - long n; - uint8_t* scratch; - c = nj_get(m, "c"); - if (!c || c->type != NJ_STRING) goto fail; - scratch = (uint8_t*)malloc(c->len + 1); - if (!scratch) goto fail; - n = atyha_b64u_decode(c->str, c->len, scratch, c->len); - free(scratch); - if (n < 0) goto fail; - out->c = nj_strdup(c->str); - if (!out->c) goto fail; - } - nj_free(m); - return 0; -fail: - nj_free(m); - nj_msg_free(out); - return -1; -} - -void nj_msg_free(nj_msg* m) -{ - free(m->c); - m->c = NULL; -} - -char* nj_msg_write(int t, const char* sid, const char* from, const char* to, const uint8_t* Y, const char* c) -{ - nj_buf b = {0}; - nj_buf_puts(&b, "{\"v\":1,\"t\":\""); - nj_buf_puts(&b, nj_msg_type_name(t)); - nj_buf_puts(&b, "\",\"sid\":\""); - nj_buf_puts(&b, sid); - nj_buf_puts(&b, "\",\"from\":\""); - nj_buf_puts(&b, from); - nj_buf_putc(&b, '"'); - if (to) { - nj_buf_puts(&b, ",\"to\":\""); - nj_buf_puts(&b, to); - nj_buf_putc(&b, '"'); - } - if (Y) { - char y64[44]; - atyha_b64u_encode(Y, 32, y64, sizeof y64); - nj_buf_puts(&b, ",\"Y\":\""); - nj_buf_puts(&b, y64); - nj_buf_putc(&b, '"'); - } - if (c) { - nj_buf_puts(&b, ",\"c\":\""); - nj_buf_puts(&b, c); - nj_buf_putc(&b, '"'); - } - nj_buf_putc(&b, '}'); - return nj_buf_take(&b); -} diff --git a/common/atyha/src/message.h b/common/atyha/src/message.h deleted file mode 100644 index 5a4f231..0000000 --- a/common/atyha/src/message.h +++ /dev/null @@ -1,32 +0,0 @@ -/* SPDX-License-Identifier: MIT - Copyright (c) 2026 ngspades contributors - - The messages of spec section 6: parse (checked field by field) and write. */ -#ifndef ATYHA_MESSAGE_H -#define ATYHA_MESSAGE_H - -#include - -enum { NJ_HELLO = 1, NJ_PAKE, NJ_OFFER, NJ_ANSWER, NJ_REJECT }; - -#define NJ_ID_B64 23 /* 16 bytes in b64u (22) + NUL */ - -typedef struct nj_msg { - int t; - char sid[NJ_ID_B64]; - uint8_t sid_bytes[16]; - char from[NJ_ID_B64]; - char to[NJ_ID_B64]; /* "" when absent */ - uint8_t Y[32]; - int has_Y; - char* c; /* malloc'd, or NULL */ -} nj_msg; - -const char* nj_msg_type_name(int t); -/* 0 ok (free with nj_msg_free), -1 not a message */ -int nj_msg_parse(const char* text, nj_msg* out); -void nj_msg_free(nj_msg* m); -/* the JSON text (malloc'd); to, Y and c may be NULL */ -char* nj_msg_write(int t, const char* sid, const char* from, const char* to, const uint8_t* Y, const char* c); - -#endif diff --git a/common/atyha/src/nostr.c b/common/atyha/src/nostr.c deleted file mode 100644 index 7fc5073..0000000 --- a/common/atyha/src/nostr.c +++ /dev/null @@ -1,459 +0,0 @@ -/* SPDX-License-Identifier: MIT - Copyright (c) 2026 ngspades contributors - - The Nostr transport (spec section 8): one room's topic on several public - relays at once, through any atyha_ws_backend. Publishes the messages as - ephemeral kind-21490 events (NIP-01) signed with BIP-340 by a key drawn - for this bus, and hands every new message of the topic over. */ -#include -#include -#include - -#include -#include -#include -#include - -#include "internal.h" -#include "atyha_crypto.h" - -#define SKEW_S 60 -#define SEEN_MAX 1024 -#define CONNECT_TIMEOUT_MS 15000 -#define RATE_LIMIT_WAIT_MS 60000 -#define BACKOFF_MAX_MS 30000 -#define BACKOFF_BASE_MS 2000 - -const char* const atyha_default_relays[] = { - "wss://nos.lol", - "wss://relay.primal.net", - "wss://relay.nostr.net", - "wss://relay.snort.social", - "wss://nostr.mom", - "wss://nostr.overmind.lol", - "wss://bucket.coracle.social", - NULL, -}; - -/* ------------------------------------------------------------ events */ - -int nj_nostr_key_new(nj_nostr_key* key) -{ - secp256k1_context* ctx; - secp256k1_keypair kp; - secp256k1_xonly_pubkey xpk; - uint8_t seed[32], pk[32]; - memset(key, 0, sizeof *key); - if (atyha_crypto_init()) return -1; - ctx = secp256k1_context_create(SECP256K1_CONTEXT_NONE); - if (!ctx) return -1; - randombytes_buf(seed, sizeof seed); - if (!secp256k1_context_randomize(ctx, seed)) { - secp256k1_context_destroy(ctx); - return -1; - } - do randombytes_buf(key->seckey, 32); - while (!secp256k1_keypair_create(ctx, &kp, key->seckey)); - secp256k1_keypair_xonly_pub(ctx, &xpk, NULL, &kp); - secp256k1_xonly_pubkey_serialize(ctx, pk, &xpk); - nj_hex(pk, 32, key->pubkey_hex); - sodium_memzero(&kp, sizeof kp); - key->ctx = ctx; - return 0; -} - -void nj_nostr_key_free(nj_nostr_key* key) -{ - if (key->ctx) secp256k1_context_destroy((secp256k1_context*)key->ctx); - sodium_memzero(key->seckey, sizeof key->seckey); - key->ctx = NULL; -} - -static void put_tags(nj_buf* b, const char* topic) -{ - nj_buf_puts(b, "[[\"x\","); - nj_buf_json_str(b, topic, strlen(topic)); - nj_buf_puts(b, "]]"); -} - -char* nj_nostr_serialize(const char* pubkey_hex, int64_t created_at, int kind, const char* topic, const char* content) -{ - nj_buf b = {0}; - nj_buf_puts(&b, "[0,\""); - nj_buf_puts(&b, pubkey_hex); - nj_buf_printf(&b, "\",%lld,%d,", (long long)created_at, kind); - put_tags(&b, topic); - nj_buf_putc(&b, ','); - nj_buf_json_str(&b, content, strlen(content)); - nj_buf_putc(&b, ']'); - return nj_buf_take(&b); -} - -char* nj_nostr_event(const nj_nostr_key* key, const char* topic, const char* content, int64_t created_at, - char id_hex[65]) -{ - secp256k1_keypair kp; - uint8_t id[32], sig[64], aux[32]; - char sig_hex[129]; - nj_buf b = {0}; - char* ser = nj_nostr_serialize(key->pubkey_hex, created_at, ATYHA_KIND, topic, content); - if (!ser) return NULL; - crypto_hash_sha256(id, (const uint8_t*)ser, strlen(ser)); - free(ser); - randombytes_buf(aux, sizeof aux); - if (!secp256k1_keypair_create((const secp256k1_context*)key->ctx, &kp, key->seckey) || - !secp256k1_schnorrsig_sign32((const secp256k1_context*)key->ctx, sig, id, &kp, aux)) { - sodium_memzero(&kp, sizeof kp); - return NULL; - } - sodium_memzero(&kp, sizeof kp); - nj_hex(id, 32, id_hex); - nj_hex(sig, 64, sig_hex); - nj_buf_puts(&b, "[\"EVENT\",{\"id\":\""); - nj_buf_puts(&b, id_hex); - nj_buf_puts(&b, "\",\"pubkey\":\""); - nj_buf_puts(&b, key->pubkey_hex); - nj_buf_printf(&b, "\",\"created_at\":%lld,\"kind\":%d,\"tags\":", (long long)created_at, ATYHA_KIND); - put_tags(&b, topic); - nj_buf_puts(&b, ",\"content\":"); - nj_buf_json_str(&b, content, strlen(content)); - nj_buf_puts(&b, ",\"sig\":\""); - nj_buf_puts(&b, sig_hex); - nj_buf_puts(&b, "\"}]"); - return nj_buf_take(&b); -} - -/* -------------------------------------------------------------- pool */ - -enum { R_IDLE, R_CONNECTING, R_OPEN, R_RETIRED }; - -typedef struct relay { - char* url; - atyha_ws* ws; - int state; - int attempt; - int64_t t_retry; - int64_t t_connect; - int retire; /* blocked: restricted: auth-required: pow: */ - int rate_limited; /* the next wait is 60 s */ -} relay; - -typedef struct bus_ev { - atyha_bus_event_type type; - char* text; - struct bus_ev* next; -} bus_ev; - -typedef struct nostr_bus { - atyha_bus base; - atyha_ws_backend* be; - relay* relays; - int n; - char topic[65]; - char sub[17]; - nj_nostr_key key; - uint8_t seen[SEEN_MAX][32]; - int seen_n, seen_at; - int ready; - bus_ev *head, *tail; - char* current; -} nostr_bus; - -static void push(nostr_bus* b, atyha_bus_event_type type, char* text /* owned */) -{ - bus_ev* e = (bus_ev*)calloc(1, sizeof *e); - if (!e) { - free(text); - return; - } - e->type = type; - e->text = text; - if (b->tail) b->tail->next = e; - else b->head = e; - b->tail = e; -} - -static void logf_(nostr_bus* b, const char* url, const char* what, const char* detail) -{ - nj_buf t = {0}; - nj_buf_puts(&t, url); - nj_buf_puts(&t, ": "); - nj_buf_puts(&t, what); - if (detail) nj_buf_puts(&t, detail); - push(b, ATYHA_BUS_LOG, nj_buf_take(&t)); -} - -static int starts(const char* s, const char* prefix) { return !strncmp(s, prefix, strlen(prefix)); } - -static void refusal(relay* r, const char* why) -{ - if (starts(why, "blocked:") || starts(why, "restricted:") || starts(why, "auth-required:") || starts(why, "pow:")) - r->retire = 1; - if (starts(why, "rate-limited:")) r->rate_limited = 1; -} - -static int seen(nostr_bus* b, const uint8_t id[32]) -{ - int i; - for (i = 0; i < b->seen_n; i++) - if (!memcmp(b->seen[i], id, 32)) return 1; - return 0; -} - -static void remember(nostr_bus* b, const uint8_t id[32]) -{ - memcpy(b->seen[b->seen_at], id, 32); - b->seen_at = (b->seen_at + 1) % SEEN_MAX; - if (b->seen_n < SEEN_MAX) b->seen_n++; -} - -static void on_event(nostr_bus* b, const nj_value* ev) -{ - const nj_value *id, *content, *kind, *tags, *created, *pubkey, *t; - uint8_t idb[32]; - int has_topic = 0; - double now_s; - if (!ev || ev->type != NJ_OBJECT) return; - id = nj_get(ev, "id"); - content = nj_get(ev, "content"); - kind = nj_get(ev, "kind"); - if (!id || id->type != NJ_STRING || id->len != 64 || nj_unhex(id->str, 64, idb)) return; - if (!content || content->type != NJ_STRING) return; - if (!kind || kind->type != NJ_NUMBER || kind->num != ATYHA_KIND || seen(b, idb)) return; - tags = nj_get(ev, "tags"); - if (!tags || tags->type != NJ_ARRAY) return; - for (t = tags->child; t; t = t->next) { - const nj_value* k = nj_at(t, 0); - const nj_value* v = nj_at(t, 1); - if (k && v && k->type == NJ_STRING && v->type == NJ_STRING && !strcmp(k->str, "x") && - !strcmp(v->str, b->topic)) - has_topic = 1; - } - if (!has_topic) return; - created = nj_get(ev, "created_at"); - now_s = (double)time(NULL); - if (!created || created->type != NJ_NUMBER || created->num - now_s > SKEW_S || now_s - created->num > SKEW_S) return; - remember(b, idb); - pubkey = nj_get(ev, "pubkey"); - if (pubkey && pubkey->type == NJ_STRING && !strcmp(pubkey->str, b->key.pubkey_hex)) return; /* our own */ - push(b, ATYHA_BUS_MESSAGE, nj_strdup(content->str)); -} - -static void drop(nostr_bus* b, relay* r, int64_t now) -{ - int64_t wait; - if (r->ws) b->be->close(r->ws); - r->ws = NULL; - if (r->retire) { - r->state = R_RETIRED; - logf_(b, r->url, "dropped for this session", NULL); - return; - } - if (r->rate_limited) { - wait = RATE_LIMIT_WAIT_MS; - } else { - wait = (int64_t)BACKOFF_BASE_MS << (r->attempt < 4 ? r->attempt : 4); - if (wait > BACKOFF_MAX_MS) wait = BACKOFF_MAX_MS; - } - r->rate_limited = 0; - r->attempt++; - r->state = R_IDLE; - r->t_retry = now + wait; -} - -static void on_text(nostr_bus* b, relay* r, const char* text, size_t len, int64_t now) -{ - nj_value* m = nj_parse(text, len); - const char* type; - if (!m || m->type != NJ_ARRAY || !m->child || m->child->type != NJ_STRING) { - nj_free(m); - return; - } - type = m->child->str; - if (!strcmp(type, "EOSE")) { - const char* sub = nj_at(m, 1) && nj_at(m, 1)->type == NJ_STRING ? nj_at(m, 1)->str : ""; - if (!strcmp(sub, b->sub)) { - logf_(b, r->url, "subscribed", NULL); - if (!b->ready) { - b->ready = 1; - push(b, ATYHA_BUS_READY, NULL); - } - } - } else if (!strcmp(type, "EVENT")) { - const nj_value* sub = nj_at(m, 1); - if (sub && sub->type == NJ_STRING && !strcmp(sub->str, b->sub)) on_event(b, nj_at(m, 2)); - } else if (!strcmp(type, "OK")) { - const nj_value* ok = nj_at(m, 2); - const nj_value* why = nj_at(m, 3); - if (ok && ok->type == NJ_FALSE) { - const char* w = why && why->type == NJ_STRING ? why->str : ""; - logf_(b, r->url, "refused: ", w); - refusal(r, w); - /* rate-limited: away 60 s; blocked and the like: for the session */ - if (r->retire || r->rate_limited) drop(b, r, now); - } - } else if (!strcmp(type, "CLOSED")) { - const nj_value* sub = nj_at(m, 1); - const nj_value* why = nj_at(m, 2); - if (sub && sub->type == NJ_STRING && !strcmp(sub->str, b->sub)) { - const char* w = why && why->type == NJ_STRING ? why->str : ""; - logf_(b, r->url, "subscription closed: ", w); - refusal(r, w); - drop(b, r, now); - } - } - nj_free(m); -} - -static void send_req(nostr_bus* b, relay* r) -{ - nj_buf t = {0}; - nj_buf_puts(&t, "[\"REQ\",\""); - nj_buf_puts(&t, b->sub); - nj_buf_printf(&t, "\",{\"kinds\":[%d],\"#x\":[\"%s\"],\"since\":%lld}]", ATYHA_KIND, b->topic, - (long long)time(NULL) - SKEW_S); - if (t.p) b->be->send(r->ws, t.p, t.n); - nj_buf_free(&t); -} - -static void pump_relay(nostr_bus* b, relay* r, int64_t now) -{ - atyha_ws_event ev; - int guard = 0; - if (r->state == R_IDLE && now >= r->t_retry) { - r->ws = b->be->connect(b->be, r->url); - if (!r->ws) { - logf_(b, r->url, "cannot connect", NULL); - drop(b, r, now); - return; - } - r->state = R_CONNECTING; - r->t_connect = now; - } - while (r->ws && guard++ < 256 && b->be->poll(r->ws, &ev)) { - if (ev.type == ATYHA_WS_OPEN) { - r->state = R_OPEN; - r->attempt = 0; - send_req(b, r); - } else if (ev.type == ATYHA_WS_TEXT) { - on_text(b, r, ev.data, ev.len, now); - } else if (ev.type == ATYHA_WS_CLOSED) { - logf_(b, r->url, "closed", ev.data ? (ev.data[0] ? ev.data : NULL) : NULL); - drop(b, r, now); - } - } - if (r->state == R_CONNECTING && now - r->t_connect > CONNECT_TIMEOUT_MS) { - logf_(b, r->url, "connection timed out", NULL); - drop(b, r, now); - } -} - -static int nostr_poll(atyha_bus* base, int64_t now, atyha_bus_event* ev) -{ - nostr_bus* b = (nostr_bus*)base; - bus_ev* e; - int i; - free(b->current); - b->current = NULL; - if (!b->head) { - if (b->be->update) b->be->update(b->be); - for (i = 0; i < b->n; i++) - if (b->relays[i].state != R_RETIRED) pump_relay(b, &b->relays[i], now); - } - e = b->head; - if (!e) { - ev->type = ATYHA_BUS_NONE; - ev->text = NULL; - return 0; - } - b->head = e->next; - if (!b->head) b->tail = NULL; - b->current = e->text; - ev->type = e->type; - ev->text = e->text; - free(e); - return 1; -} - -static void nostr_publish(atyha_bus* base, const char* message, int64_t now) -{ - nostr_bus* b = (nostr_bus*)base; - char id[65]; - char* text = nj_nostr_event(&b->key, b->topic, message, (int64_t)time(NULL), id); - int i; - (void)now; - if (!text) return; - for (i = 0; i < b->n; i++) - if (b->relays[i].state == R_OPEN && b->relays[i].ws && !b->be->send(b->relays[i].ws, text, strlen(text))) - continue; - free(text); -} - -static void nostr_destroy(atyha_bus* base) -{ - nostr_bus* b = (nostr_bus*)base; - int i; - char close_msg[40]; - strcpy(close_msg, "[\"CLOSE\",\""); - strcat(close_msg, b->sub); - strcat(close_msg, "\"]"); - for (i = 0; i < b->n; i++) { - relay* r = &b->relays[i]; - if (r->ws) { - if (r->state == R_OPEN) b->be->send(r->ws, close_msg, strlen(close_msg)); - b->be->close(r->ws); - } - free(r->url); - } - free(b->relays); - while (b->head) { - bus_ev* e = b->head; - b->head = e->next; - free(e->text); - free(e); - } - free(b->current); - nj_nostr_key_free(&b->key); - free(b); -} - -atyha_bus* atyha_nostr_bus_open(const atyha_nostr_config* cfg, const char* topic) -{ - nostr_bus* b; - const char* const* urls; - int n, i; - uint8_t sub[8]; - if (!cfg || !cfg->ws || !cfg->ws->connect || !cfg->ws->send || !cfg->ws->poll || !cfg->ws->close || !topic || - strlen(topic) > 64) - return NULL; - urls = cfg->relays ? cfg->relays : atyha_default_relays; - if (cfg->relays) n = cfg->relay_count; - else - for (n = 0; urls[n]; n++) {} - if (n <= 0) return NULL; - b = (nostr_bus*)calloc(1, sizeof *b); - if (!b) return NULL; - if (nj_nostr_key_new(&b->key)) { - free(b); - return NULL; - } - b->base.publish = nostr_publish; - b->base.poll = nostr_poll; - b->base.destroy = nostr_destroy; - b->be = cfg->ws; - strcpy(b->topic, topic); - randombytes_buf(sub, sizeof sub); - nj_hex(sub, sizeof sub, b->sub); - b->relays = (relay*)calloc((size_t)n, sizeof *b->relays); - if (!b->relays) { - nostr_destroy(&b->base); - return NULL; - } - b->n = n; - for (i = 0; i < n; i++) { - b->relays[i].url = nj_strdup(urls[i]); - b->relays[i].state = b->relays[i].url ? R_IDLE : R_RETIRED; - b->relays[i].t_retry = INT64_MIN; - } - return &b->base; -} diff --git a/common/atyha/src/session.c b/common/atyha/src/session.c deleted file mode 100644 index 5cde974..0000000 --- a/common/atyha/src/session.c +++ /dev/null @@ -1,920 +0,0 @@ -/* SPDX-License-Identifier: MIT - Copyright (c) 2026 ngspades contributors - - The exchange (spec section 7) over any atyha_bus: the host, which answers - hellos and hands offers to the program, and the joiner, which turns a code - and a password into the host's answer SDP. No I/O here: the bus does it, - and time is what the program passes to the polls. */ -#include -#include - -#include - -#include "internal.h" -#include "message.h" -#include "atyha_crypto.h" - -#define RETRY_MS 2000 -#define DEFAULT_DEADLINE_MS 25000 -#define NO_RELAY_MS 10000 -#define WRONG_PASSWORD_WAIT_MS 4000 -#define ATTEMPT_KEEP_MS 60000 -#define ATTEMPT_PENDING_KEEP_MS 300000 -#define HELLO_WINDOW_MS 60000 -#define DEFAULT_HELLO_BUDGET 20 -#define MAX_META 2048 -#define MAX_BUS_EVENTS_PER_POLL 512 - -/* ------------------------------------------------------------ helpers */ - -typedef struct nj_ice_list { - atyha_ice_server* servers; - int count; - char* json; -} nj_ice_list; - -static void ice_list_free(nj_ice_list* l) -{ - int i, k; - for (i = 0; i < l->count; i++) { - for (k = 0; k < l->servers[i].url_count; k++) free((char*)l->servers[i].urls[k]); - free((void*)l->servers[i].urls); - free((char*)l->servers[i].username); - free((char*)l->servers[i].credential); - } - free(l->servers); - free(l->json); - memset(l, 0, sizeof *l); -} - -/* an "ice" array (RTCIceServer objects) to C; entries without a usable url are skipped */ -static void ice_list_from_json(nj_ice_list* l, const nj_value* arr) -{ - const nj_value* e; - memset(l, 0, sizeof *l); - if (!arr || arr->type != NJ_ARRAY || !arr->count) return; - l->servers = (atyha_ice_server*)calloc(arr->count, sizeof *l->servers); - if (!l->servers) return; - l->json = (char*)malloc(arr->raw_len + 1); - if (l->json) { - memcpy(l->json, arr->raw, arr->raw_len); - l->json[arr->raw_len] = 0; - } - for (e = arr->child; e; e = e->next) { - const nj_value* urls = nj_get(e, "urls"); - const char* user = nj_get_str(e, "username"); - const char* cred = nj_get_str(e, "credential"); - atyha_ice_server* s = &l->servers[l->count]; - const char** list; - int n = 0; - if (!urls) continue; - if (urls->type == NJ_STRING) { - list = (const char**)calloc(1, sizeof *list); - if (!list) continue; - list[n++] = nj_strdup(urls->str); - } else if (urls->type == NJ_ARRAY && urls->count) { - const nj_value* u; - list = (const char**)calloc(urls->count, sizeof *list); - if (!list) continue; - for (u = urls->child; u; u = u->next) - if (u->type == NJ_STRING) list[n++] = nj_strdup(u->str); - } else { - continue; - } - if (!n) { - free((void*)list); - continue; - } - s->urls = list; - s->url_count = n; - s->username = user ? nj_strdup(user) : NULL; - s->credential = cred ? nj_strdup(cred) : NULL; - l->count++; - } -} - -/* config ICE servers to their JSON array text */ -static char* ice_to_json(const atyha_ice_server* ice, int count) -{ - nj_buf b = {0}; - int i, k; - nj_buf_putc(&b, '['); - for (i = 0; i < count; i++) { - if (i) nj_buf_putc(&b, ','); - nj_buf_puts(&b, "{\"urls\":"); - if (ice[i].url_count == 1) { - nj_buf_json_str(&b, ice[i].urls[0], strlen(ice[i].urls[0])); - } else { - nj_buf_putc(&b, '['); - for (k = 0; k < ice[i].url_count; k++) { - if (k) nj_buf_putc(&b, ','); - nj_buf_json_str(&b, ice[i].urls[k], strlen(ice[i].urls[k])); - } - nj_buf_putc(&b, ']'); - } - if (ice[i].username) { - nj_buf_puts(&b, ",\"username\":"); - nj_buf_json_str(&b, ice[i].username, strlen(ice[i].username)); - } - if (ice[i].credential) { - nj_buf_puts(&b, ",\"credential\":"); - nj_buf_json_str(&b, ice[i].credential, strlen(ice[i].credential)); - } - nj_buf_putc(&b, '}'); - } - nj_buf_putc(&b, ']'); - return nj_buf_take(&b); -} - -static int pct_unreserved(unsigned char c) -{ - return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '.' || - c == '_' || c == '~'; -} - -static void put_pct(nj_buf* b, const char* s) -{ - static const char hexd[] = "0123456789ABCDEF"; - for (; *s; s++) { - unsigned char c = (unsigned char)*s; - if (pct_unreserved(c)) { - nj_buf_putc(b, (char)c); - } else { - char e[3]; - e[0] = '%', e[1] = hexd[c >> 4], e[2] = hexd[c & 15]; - nj_buf_put(b, e, 3); - } - } -} - -size_t atyha_ice_url_libdatachannel(const atyha_ice_server* s, int index, char* out, size_t cap) -{ - nj_buf b = {0}; - const char *url, *colon; - size_t n; - if (!s || index < 0 || index >= s->url_count) { - if (cap) out[0] = 0; - return 0; - } - url = s->urls[index]; - colon = strchr(url, ':'); - if (colon && s->username && s->credential && !strchr(colon, '@')) { - const char* rest = colon + 1; - while (*rest == '/') rest++; - nj_buf_put(&b, url, (size_t)(colon - url + 1)); - put_pct(&b, s->username); - nj_buf_putc(&b, ':'); - put_pct(&b, s->credential); - nj_buf_putc(&b, '@'); - nj_buf_puts(&b, rest); - } else { - nj_buf_puts(&b, url); - } - if (b.oom) { - nj_buf_free(&b); - if (cap) out[0] = 0; - return 0; - } - n = b.n; - if (cap) { - size_t k = n < cap - 1 ? n : cap - 1; - memcpy(out, b.p, k); - out[k] = 0; - } - nj_buf_free(&b); - return n; -} - -static char* seal_text(const uint8_t key[32], int n, int t, const uint8_t sid[16], const char* plain) -{ - size_t len = strlen(plain); - size_t need = atyha_seal(key, n, nj_msg_type_name(t), sid, (const uint8_t*)plain, len, NULL, 0); - char* out = (char*)malloc(need + 1); - if (!out) return NULL; - atyha_seal(key, n, nj_msg_type_name(t), sid, (const uint8_t*)plain, len, out, need + 1); - return out; -} - -/* the sealed payload as a JSON object, or NULL; *keep holds the plaintext - the values point into (free it with close_object after nj_free) */ -static void close_object(nj_value* v, uint8_t* keep) -{ - nj_free(v); - if (keep) { - sodium_memzero(keep, strlen((const char*)keep)); - free(keep); - } -} - -static nj_value* open_object(const uint8_t key[32], int n, int t, const uint8_t sid[16], const char* c, uint8_t** keep) -{ - size_t cap = strlen(c); - uint8_t* plain = (uint8_t*)malloc(cap + 1); - long got; - nj_value* v = NULL; - if (!plain) return NULL; - got = atyha_open(key, n, nj_msg_type_name(t), sid, c, plain, cap + 1); - if (got >= 0) { - v = nj_parse((const char*)plain, (size_t)got); - if (v && v->type != NJ_OBJECT) { - nj_free(v); - v = NULL; - } - } - if (!v) { - sodium_memzero(plain, cap + 1); - free(plain); - plain = NULL; - } - *keep = plain; - return v; -} - -static char* raw_text(const nj_value* v) -{ - char* s; - if (!v) return NULL; - s = (char*)malloc(v->raw_len + 1); - if (!s) return NULL; - memcpy(s, v->raw, v->raw_len); - s[v->raw_len] = 0; - return s; -} - -static void random_id(char out[NJ_ID_B64]) -{ - uint8_t r[16]; - randombytes_buf(r, sizeof r); - atyha_b64u_encode(r, 16, out, NJ_ID_B64); -} - -/* ---- event queue: each event owns its strings until the next poll ---- */ - -typedef struct nj_qev { - atyha_event ev; - char* owned[6]; - nj_ice_list ice; - struct nj_qev* next; -} nj_qev; - -typedef struct nj_queue { - nj_qev *head, *tail, *current; -} nj_queue; - -static void qev_free(nj_qev* q) -{ - int i; - if (!q) return; - for (i = 0; i < 6; i++) free(q->owned[i]); - ice_list_free(&q->ice); - free(q); -} - -static nj_qev* queue_push(nj_queue* q, atyha_event_type type) -{ - nj_qev* e = (nj_qev*)calloc(1, sizeof *e); - if (!e) return NULL; - e->ev.type = type; - if (q->tail) q->tail->next = e; - else q->head = e; - q->tail = e; - return e; -} - -/* a string the event owns (copied); NULL stays NULL */ -static const char* qev_own(nj_qev* e, int slot, const char* s) -{ - if (!e || !s) return NULL; - e->owned[slot] = nj_strdup(s); - return e->owned[slot]; -} - -static int queue_pop(nj_queue* q, atyha_event* ev) -{ - qev_free(q->current); - q->current = NULL; - if (!q->head) { - memset(ev, 0, sizeof *ev); - return 0; - } - q->current = q->head; - q->head = q->head->next; - if (!q->head) q->tail = NULL; - *ev = q->current->ev; - return 1; -} - -static void queue_free(nj_queue* q) -{ - nj_qev* e = q->head; - while (e) { - nj_qev* n = e->next; - qev_free(e); - e = n; - } - qev_free(q->current); - memset(q, 0, sizeof *q); -} - -static void queue_log(nj_queue* q, const char* text) -{ - nj_qev* e = queue_push(q, ATYHA_EV_LOG); - if (e) e->ev.text = qev_own(e, 0, text); -} - -/* ---- transport ---- */ - -static atyha_bus* open_transport(const atyha_transport* tr, const char* topic) -{ - if (tr->bus_open) return tr->bus_open(tr->bus_user, topic); - if (tr->ws) { - atyha_nostr_config nc; - nc.ws = tr->ws; - nc.relays = tr->relays; - nc.relay_count = tr->relay_count; - return atyha_nostr_bus_open(&nc, topic); - } - return NULL; -} - -static int meta_ok(const char* meta) { return !meta || (strlen(meta) <= MAX_META && nj_is_object_text(meta)); } - -static int app_ok(const char* app) { return app && *app && strlen(app) <= 64; } - -const char* atyha_error_name(atyha_error e) -{ - switch (e) { - case ATYHA_OK: return "ok"; - case ATYHA_ERR_BAD_CODE: return "bad_code"; - case ATYHA_ERR_NO_RELAY: return "no_relay"; - case ATYHA_ERR_NO_ROOM: return "no_room"; - case ATYHA_ERR_WRONG_PASSWORD: return "wrong_password"; - case ATYHA_ERR_REJECTED: return "rejected"; - case ATYHA_ERR_NO_ANSWER: return "no_answer"; - case ATYHA_ERR_CANCELLED: return "cancelled"; - } - return "unknown"; -} - -/* ================================================================ host */ - -typedef struct nj_attempt { - char sid[NJ_ID_B64]; - uint8_t sid_bytes[16]; - char joiner[NJ_ID_B64]; - uint8_t k_hj[32], k_jh[32]; - char* pake; - char* reply; - int pending; /* handed to the program, no reply yet */ - int64_t at; - struct nj_attempt* next; -} nj_attempt; - -struct atyha_host { - char* app; - char code[ATYHA_CODE_LEN + 1]; - char* password; - char* payload; /* the pake's sealed payload, {"ice":[...],"meta":{...}} */ - char id[NJ_ID_B64]; - int budget; - int64_t* hellos; /* ring of the last hello times */ - int hello_head, hello_n; - atyha_bus* bus; - int open; - int64_t now; /* of the last poll */ - nj_attempt* attempts; - nj_queue q; -}; - -static void attempt_free(nj_attempt* a) -{ - sodium_memzero(a->k_hj, 32); - sodium_memzero(a->k_jh, 32); - free(a->pake); - free(a->reply); - free(a); -} - -atyha_host* atyha_host_create(const atyha_host_config* cfg) -{ - atyha_host* h; - nj_buf p = {0}; - char topic[65]; - if (!cfg || !app_ok(cfg->app) || !meta_ok(cfg->meta) || atyha_crypto_init()) return NULL; - if (cfg->ice_count < 0 || (cfg->ice_count && !cfg->ice)) return NULL; - h = (atyha_host*)calloc(1, sizeof *h); - if (!h) return NULL; - if (cfg->code) { - if (!atyha_code_parse(cfg->code, h->code)) { - free(h); - return NULL; - } - } else { - atyha_code_generate(h->code); - } - h->app = nj_strdup(cfg->app); - h->password = nj_strdup(cfg->password ? cfg->password : ""); - random_id(h->id); - h->budget = cfg->hello_budget > 0 ? cfg->hello_budget : DEFAULT_HELLO_BUDGET; - h->hellos = (int64_t*)calloc((size_t)h->budget, sizeof *h->hellos); - nj_buf_putc(&p, '{'); - if (cfg->ice_count > 0) { - char* ice = ice_to_json(cfg->ice, cfg->ice_count); - nj_buf_puts(&p, "\"ice\":"); - nj_buf_puts(&p, ice ? ice : "[]"); - free(ice); - } - if (cfg->meta) { - if (cfg->ice_count > 0) nj_buf_putc(&p, ','); - nj_buf_puts(&p, "\"meta\":"); - nj_buf_puts(&p, cfg->meta); - } - nj_buf_putc(&p, '}'); - h->payload = nj_buf_take(&p); - if (!h->app || !h->password || !h->hellos || !h->payload) { - atyha_host_destroy(h); - return NULL; - } - atyha_topic(h->app, h->code, topic); - h->bus = open_transport(&cfg->transport, topic); - if (!h->bus) { - atyha_host_destroy(h); - return NULL; - } - return h; -} - -const char* atyha_host_code(const atyha_host* h) { return h->code; } -int atyha_host_is_open(const atyha_host* h) { return h->open; } - -static nj_attempt* host_find(atyha_host* h, const char* sid) -{ - nj_attempt* a; - for (a = h->attempts; a; a = a->next) - if (!strcmp(a->sid, sid)) return a; - return NULL; -} - -static void host_hello(atyha_host* h, const nj_msg* m, int64_t now) -{ - nj_attempt* a = host_find(h, m->sid); - uint8_t prs[512 + 16], ci[96], g[32], yb[32], Yb[32], K[32], isk[64]; - size_t prs_len, ci_len; - char* c; - if (a) { - if (!strcmp(a->joiner, m->from)) h->bus->publish(h->bus, a->pake, now); - return; - } - while (h->hello_n && h->hellos[h->hello_head] <= now - HELLO_WINDOW_MS) { - h->hello_head = (h->hello_head + 1) % h->budget; - h->hello_n--; - } - if (h->hello_n >= h->budget) { - queue_log(&h->q, "hello ignored: over the budget"); - return; - } - h->hellos[(h->hello_head + h->hello_n) % h->budget] = now; - h->hello_n++; - - prs_len = atyha_prs(h->code, h->password, NULL, 0); - if (prs_len > sizeof prs) { - /* a password longer than 512 bytes: an allocation */ - uint8_t* big = (uint8_t*)malloc(prs_len); - if (!big) return; - atyha_prs(h->code, h->password, big, prs_len); - ci_len = atyha_ci(h->app, ci, sizeof ci); - atyha_cpace_generator(big, prs_len, ci, ci_len, m->sid_bytes, 16, g); - sodium_memzero(big, prs_len); - free(big); - } else { - atyha_prs(h->code, h->password, prs, sizeof prs); - ci_len = atyha_ci(h->app, ci, sizeof ci); - atyha_cpace_generator(prs, prs_len, ci, ci_len, m->sid_bytes, 16, g); - sodium_memzero(prs, sizeof prs); - } - atyha_cpace_sample_scalar(yb); - if (atyha_cpace_share(g, yb, Yb) || atyha_cpace_scalar_mult_vfy(yb, m->Y, K)) { - sodium_memzero(yb, sizeof yb); - return; /* Ya is no point */ - } - sodium_memzero(yb, sizeof yb); - a = (nj_attempt*)calloc(1, sizeof *a); - if (!a) return; - atyha_cpace_isk(m->sid_bytes, 16, K, m->Y, Yb, isk); - atyha_keys(isk, m->sid_bytes, 16, a->k_hj, a->k_jh); - sodium_memzero(isk, sizeof isk); - sodium_memzero(K, sizeof K); - memcpy(a->sid, m->sid, NJ_ID_B64); - memcpy(a->sid_bytes, m->sid_bytes, 16); - memcpy(a->joiner, m->from, NJ_ID_B64); - a->at = now; - c = seal_text(a->k_hj, 0, NJ_PAKE, a->sid_bytes, h->payload); - a->pake = c ? nj_msg_write(NJ_PAKE, a->sid, h->id, a->joiner, Yb, c) : NULL; - free(c); - if (!a->pake) { - attempt_free(a); - return; - } - a->next = h->attempts; - h->attempts = a; - h->bus->publish(h->bus, a->pake, now); -} - -static void host_offer(atyha_host* h, const nj_msg* m, int64_t now) -{ - nj_attempt* a = host_find(h, m->sid); - nj_value *p, *sdp, *meta; - uint8_t* keep = NULL; - nj_qev* e; - if (!a || strcmp(a->joiner, m->from)) return; - if (a->reply) { - h->bus->publish(h->bus, a->reply, now); - return; - } - if (a->pending) return; - p = open_object(a->k_jh, 0, NJ_OFFER, a->sid_bytes, m->c, &keep); - sdp = nj_get(p, "sdp"); - if (!p || !sdp || sdp->type != NJ_STRING) { - close_object(p, keep); /* wrong password, or forged */ - return; - } - meta = nj_get(p, "meta"); - if (meta && meta->type != NJ_OBJECT) meta = NULL; - a->pending = 1; - e = queue_push(&h->q, ATYHA_EV_OFFER); - if (e) { - e->ev.sdp = qev_own(e, 0, sdp->str); - e->owned[1] = raw_text(meta); - e->ev.meta = e->owned[1]; - e->ev.attempt = qev_own(e, 2, a->sid); - e->ev.joiner = qev_own(e, 3, a->joiner); - } - close_object(p, keep); -} - -static void host_message(atyha_host* h, const char* text, int64_t now) -{ - nj_msg m; - if (nj_msg_parse(text, &m)) return; - if (m.t == NJ_HELLO) host_hello(h, &m, now); - else if (m.t == NJ_OFFER && !strcmp(m.to, h->id)) host_offer(h, &m, now); - nj_msg_free(&m); -} - -int atyha_host_poll(atyha_host* h, int64_t now, atyha_event* ev) -{ - atyha_bus_event be; - nj_attempt** pa; - int i; - h->now = now; - for (i = 0; i < MAX_BUS_EVENTS_PER_POLL && h->bus->poll(h->bus, now, &be); i++) { - if (be.type == ATYHA_BUS_READY) { - if (!h->open) { - h->open = 1; - queue_push(&h->q, ATYHA_EV_OPEN); - } - } else if (be.type == ATYHA_BUS_MESSAGE && be.text) { - host_message(h, be.text, now); - } else if (be.type == ATYHA_BUS_LOG && be.text) { - queue_log(&h->q, be.text); - } - } - for (pa = &h->attempts; *pa;) { - nj_attempt* a = *pa; - if (a->at < now - (a->pending ? ATTEMPT_PENDING_KEEP_MS : ATTEMPT_KEEP_MS)) { - *pa = a->next; - attempt_free(a); - } else { - pa = &a->next; - } - } - return queue_pop(&h->q, ev); -} - -static int host_reply(atyha_host* h, const char* attempt, int t, const char* key, const char* value) -{ - nj_attempt* a = attempt ? host_find(h, attempt) : NULL; - nj_buf b = {0}; - char *plain, *c; - if (!a || a->reply || !value) return -1; - nj_buf_puts(&b, "{\""); - nj_buf_puts(&b, key); - nj_buf_puts(&b, "\":"); - nj_buf_json_str(&b, value, strlen(value)); - nj_buf_putc(&b, '}'); - plain = nj_buf_take(&b); - if (!plain) return -1; - c = seal_text(a->k_hj, 1, t, a->sid_bytes, plain); - free(plain); - if (!c) return -1; - a->reply = nj_msg_write(t, a->sid, h->id, a->joiner, NULL, c); - free(c); - if (!a->reply) return -1; - a->pending = 0; - a->at = h->now; /* refreshed: kept 60 s for repeats of the offer */ - h->bus->publish(h->bus, a->reply, h->now); - return 0; -} - -int atyha_host_answer(atyha_host* h, const char* attempt, const char* sdp) -{ - return host_reply(h, attempt, NJ_ANSWER, "sdp", sdp); -} - -int atyha_host_reject(atyha_host* h, const char* attempt, const char* reason) -{ - return host_reply(h, attempt, NJ_REJECT, "reason", reason ? reason : "refused"); -} - -void atyha_host_destroy(atyha_host* h) -{ - if (!h) return; - if (h->bus) h->bus->destroy(h->bus); - while (h->attempts) { - nj_attempt* a = h->attempts; - h->attempts = a->next; - attempt_free(a); - } - queue_free(&h->q); - if (h->password) sodium_memzero(h->password, strlen(h->password)); - free(h->password); - free(h->app); - free(h->payload); - free(h->hellos); - free(h); -} - -/* ============================================================== joiner */ - -enum { J_START, J_WAIT_BUS, J_HELLO, J_NEED_OFFER, J_OFFER, J_DONE }; - -struct atyha_joiner { - char* app; - char code[ATYHA_CODE_LEN + 1]; - int bad_code; - char* password; - char* meta; - int64_t deadline_ms; - atyha_bus* bus; - int state; - int cancelled; - int64_t t_start, t_next, t_deadline, t_bad; - int64_t now; /* of the last poll */ - int bad_pake; - uint8_t sid[16]; - char sid_b64[NJ_ID_B64]; - char me[NJ_ID_B64]; - char host[NJ_ID_B64]; - uint8_t y[32], Ya[32]; - uint8_t k_hj[32], k_jh[32]; - char* hello; - char* offer; - nj_queue q; -}; - -atyha_joiner* atyha_joiner_create(const atyha_join_config* cfg) -{ - atyha_joiner* j; - if (!cfg || !app_ok(cfg->app) || !meta_ok(cfg->meta) || atyha_crypto_init()) return NULL; - if (!cfg->transport.bus_open && !cfg->transport.ws) return NULL; - j = (atyha_joiner*)calloc(1, sizeof *j); - if (!j) return NULL; - j->app = nj_strdup(cfg->app); - j->password = nj_strdup(cfg->password ? cfg->password : ""); - j->meta = cfg->meta ? nj_strdup(cfg->meta) : NULL; - j->deadline_ms = cfg->timeout_ms > 0 ? cfg->timeout_ms : DEFAULT_DEADLINE_MS; - if (!j->app || !j->password || (cfg->meta && !j->meta)) { - atyha_joiner_destroy(j); - return NULL; - } - if (!atyha_code_parse(cfg->code, j->code)) { - j->bad_code = 1; - return j; - } - { - uint8_t prs[512 + 16], ci[96], g[32]; - uint8_t* pp = prs; - size_t prs_len = atyha_prs(j->code, j->password, NULL, 0), ci_len; - char topic[65]; - if (prs_len > sizeof prs) pp = (uint8_t*)malloc(prs_len); - if (!pp) { - atyha_joiner_destroy(j); - return NULL; - } - atyha_prs(j->code, j->password, pp, prs_len); - ci_len = atyha_ci(j->app, ci, sizeof ci); - randombytes_buf(j->sid, 16); - atyha_b64u_encode(j->sid, 16, j->sid_b64, sizeof j->sid_b64); - random_id(j->me); - atyha_cpace_generator(pp, prs_len, ci, ci_len, j->sid, 16, g); - sodium_memzero(pp, prs_len); - if (pp != prs) free(pp); - do atyha_cpace_sample_scalar(j->y); - while (atyha_cpace_share(g, j->y, j->Ya)); - j->hello = nj_msg_write(NJ_HELLO, j->sid_b64, j->me, NULL, j->Ya, NULL); - atyha_topic(j->app, j->code, topic); - j->bus = j->hello ? open_transport(&cfg->transport, topic) : NULL; - if (!j->bus) { - atyha_joiner_destroy(j); - return NULL; - } - } - return j; -} - -static void joiner_finish(atyha_joiner* j, atyha_error err, const char* reason, const char* sdp) -{ - nj_qev* e; - if (j->state == J_DONE) return; - j->state = J_DONE; - if (j->bus) { - j->bus->destroy(j->bus); - j->bus = NULL; - } - sodium_memzero(j->y, sizeof j->y); - e = queue_push(&j->q, err ? ATYHA_EV_ERROR : ATYHA_EV_ANSWER); - if (!e) return; - e->ev.error = err; - e->ev.reason = qev_own(e, 0, reason); - e->ev.sdp = qev_own(e, 1, sdp); -} - -static void joiner_pake(atyha_joiner* j, const nj_msg* m, int64_t now) -{ - uint8_t K[32], isk[64], k_hj[32], k_jh[32]; - nj_value *p = NULL, *meta; - uint8_t* keep = NULL; - nj_qev* e; - if (!atyha_cpace_scalar_mult_vfy(j->y, m->Y, K)) { - atyha_cpace_isk(j->sid, 16, K, j->Ya, m->Y, isk); - atyha_keys(isk, j->sid, 16, k_hj, k_jh); - sodium_memzero(isk, sizeof isk); - p = open_object(k_hj, 0, NJ_PAKE, j->sid, m->c, &keep); - } - sodium_memzero(K, sizeof K); - if (!p) { - if (!j->bad_pake) { - j->bad_pake = 1; - j->t_bad = now + WRONG_PASSWORD_WAIT_MS; - queue_log(&j->q, "a pake that does not open: wrong password?"); - } - return; - } - memcpy(j->host, m->from, NJ_ID_B64); - memcpy(j->k_hj, k_hj, 32); - memcpy(j->k_jh, k_jh, 32); - j->state = J_NEED_OFFER; - j->t_deadline = now + j->deadline_ms; /* for the program's offer */ - e = queue_push(&j->q, ATYHA_EV_NEED_OFFER); - if (e) { - meta = nj_get(p, "meta"); - if (meta && meta->type == NJ_OBJECT) { - e->owned[0] = raw_text(meta); - e->ev.meta = e->owned[0]; - } - ice_list_from_json(&e->ice, nj_get(p, "ice")); - e->ev.ice = e->ice.count ? e->ice.servers : NULL; - e->ev.ice_count = e->ice.count; - e->ev.ice_json = e->ice.count ? e->ice.json : NULL; - } - close_object(p, keep); -} - -static void joiner_reply(atyha_joiner* j, const nj_msg* m) -{ - uint8_t* keep = NULL; - nj_value* p = open_object(j->k_hj, 1, m->t, j->sid, m->c, &keep); - const char* s; - if (!p) return; - if (m->t == NJ_ANSWER) { - s = nj_get_str(p, "sdp"); - if (s) joiner_finish(j, ATYHA_OK, NULL, s); - } else { - s = nj_get_str(p, "reason"); - joiner_finish(j, ATYHA_ERR_REJECTED, s ? s : "refused", NULL); - } - close_object(p, keep); -} - -static void joiner_message(atyha_joiner* j, const char* text, int64_t now) -{ - nj_msg m; - if (nj_msg_parse(text, &m)) return; - if (!strcmp(m.sid, j->sid_b64) && !strcmp(m.to, j->me)) { - if (m.t == NJ_PAKE && j->state == J_HELLO) joiner_pake(j, &m, now); - else if ((m.t == NJ_ANSWER || m.t == NJ_REJECT) && j->state == J_OFFER && !strcmp(m.from, j->host)) - joiner_reply(j, &m); - } - nj_msg_free(&m); -} - -int atyha_joiner_poll(atyha_joiner* j, int64_t now, atyha_event* ev) -{ - j->now = now; - if (j->state == J_START) { - j->t_start = now; - j->state = J_WAIT_BUS; - if (j->bad_code) joiner_finish(j, ATYHA_ERR_BAD_CODE, "that is not a room code", NULL); - } - if (j->cancelled) joiner_finish(j, ATYHA_ERR_CANCELLED, "cancelled", NULL); - if (j->state != J_DONE) { - atyha_bus_event be; - int i; - for (i = 0; i < MAX_BUS_EVENTS_PER_POLL && j->bus && j->bus->poll(j->bus, now, &be); i++) { - if (be.type == ATYHA_BUS_READY) { - if (j->state == J_WAIT_BUS) { - j->state = J_HELLO; - j->bus->publish(j->bus, j->hello, now); - j->t_next = now + RETRY_MS; - j->t_deadline = now + j->deadline_ms; - } - } else if (be.type == ATYHA_BUS_MESSAGE && be.text) { - joiner_message(j, be.text, now); - } else if (be.type == ATYHA_BUS_LOG && be.text) { - queue_log(&j->q, be.text); - } - if (j->state == J_DONE) break; - } - } - switch (j->state) { - case J_WAIT_BUS: - if (now - j->t_start >= NO_RELAY_MS) joiner_finish(j, ATYHA_ERR_NO_RELAY, "no relay could be reached", NULL); - break; - case J_HELLO: - if (j->bad_pake && now >= j->t_bad) { - joiner_finish(j, ATYHA_ERR_WRONG_PASSWORD, "wrong password", NULL); - } else if (now >= j->t_deadline) { - joiner_finish(j, j->bad_pake ? ATYHA_ERR_WRONG_PASSWORD : ATYHA_ERR_NO_ROOM, - j->bad_pake ? "wrong password" : "nobody is hosting that code", NULL); - } else if (now >= j->t_next) { - j->bus->publish(j->bus, j->hello, now); - j->t_next = now + RETRY_MS; - } - break; - case J_NEED_OFFER: - if (now >= j->t_deadline) joiner_finish(j, ATYHA_ERR_NO_ANSWER, "no offer was made in time", NULL); - break; - case J_OFFER: - if (now >= j->t_deadline) { - joiner_finish(j, ATYHA_ERR_NO_ANSWER, "the host did not answer", NULL); - } else if (now >= j->t_next) { - j->bus->publish(j->bus, j->offer, now); - j->t_next = now + RETRY_MS; - } - break; - default: break; - } - return queue_pop(&j->q, ev); -} - -int atyha_joiner_set_offer(atyha_joiner* j, const char* sdp) -{ - nj_buf b = {0}; - char *plain, *c; - if (!j || j->state != J_NEED_OFFER || !sdp) return -1; - nj_buf_puts(&b, "{\"sdp\":"); - nj_buf_json_str(&b, sdp, strlen(sdp)); - if (j->meta) { - nj_buf_puts(&b, ",\"meta\":"); - nj_buf_puts(&b, j->meta); - } - nj_buf_putc(&b, '}'); - plain = nj_buf_take(&b); - if (!plain) return -1; - c = seal_text(j->k_jh, 0, NJ_OFFER, j->sid, plain); - free(plain); - if (!c) return -1; - j->offer = nj_msg_write(NJ_OFFER, j->sid_b64, j->me, j->host, NULL, c); - free(c); - if (!j->offer) return -1; - j->state = J_OFFER; - /* sent now, again every 2 s; the answer deadline starts (clock of the last poll) */ - j->bus->publish(j->bus, j->offer, j->now); - j->t_next = j->now + RETRY_MS; - j->t_deadline = j->now + j->deadline_ms; - return 0; -} - -void atyha_joiner_cancel(atyha_joiner* j) -{ - if (j) j->cancelled = 1; -} - -int atyha_joiner_done(const atyha_joiner* j) { return j->state == J_DONE; } - -void atyha_joiner_destroy(atyha_joiner* j) -{ - if (!j) return; - if (j->bus) j->bus->destroy(j->bus); - queue_free(&j->q); - sodium_memzero(j->y, sizeof j->y); - sodium_memzero(j->k_hj, sizeof j->k_hj); - sodium_memzero(j->k_jh, sizeof j->k_jh); - if (j->password) sodium_memzero(j->password, strlen(j->password)); - free(j->password); - free(j->app); - free(j->meta); - free(j->hello); - free(j->offer); - free(j); -} diff --git a/common/atyha/src/util.c b/common/atyha/src/util.c deleted file mode 100644 index 849eca9..0000000 --- a/common/atyha/src/util.c +++ /dev/null @@ -1,233 +0,0 @@ -/* SPDX-License-Identifier: MIT - Copyright (c) 2026 ngspades contributors */ -#include -#include -#include -#include - -#if defined(_WIN32) -#include -#elif defined(__EMSCRIPTEN__) -#include -#else -#include -#endif - -#include "internal.h" -#include "atyha_crypto.h" - -void nj_buf_reserve(nj_buf* b, size_t more) -{ - size_t want, cap; - char* p; - if (b->oom) return; - want = b->n + more + 1; - if (want <= b->cap) return; - cap = b->cap ? b->cap : 64; - while (cap < want) cap *= 2; - p = (char*)realloc(b->p, cap); - if (!p) { - b->oom = 1; - return; - } - b->p = p; - b->cap = cap; - b->p[b->n] = 0; -} - -void nj_buf_put(nj_buf* b, const void* data, size_t len) -{ - nj_buf_reserve(b, len); - if (b->oom) return; - if (len) memcpy(b->p + b->n, data, len); - b->n += len; - b->p[b->n] = 0; -} - -void nj_buf_puts(nj_buf* b, const char* s) { nj_buf_put(b, s, strlen(s)); } -void nj_buf_putc(nj_buf* b, char c) { nj_buf_put(b, &c, 1); } - -void nj_buf_printf(nj_buf* b, const char* fmt, ...) -{ - va_list ap; - int n; - va_start(ap, fmt); - n = vsnprintf(NULL, 0, fmt, ap); - va_end(ap); - if (n < 0) return; - nj_buf_reserve(b, (size_t)n); - if (b->oom) return; - va_start(ap, fmt); - vsnprintf(b->p + b->n, (size_t)n + 1, fmt, ap); - va_end(ap); - b->n += (size_t)n; -} - -void nj_buf_json_str(nj_buf* b, const char* s, size_t len) -{ - static const char hexd[] = "0123456789abcdef"; - size_t i, run = 0; - nj_buf_putc(b, '"'); - for (i = 0; i < len; i++) { - unsigned char c = (unsigned char)s[i]; - const char* esc = NULL; - char u[7]; - if (c == '"') esc = "\\\""; - else if (c == '\\') esc = "\\\\"; - else if (c == '\b') esc = "\\b"; - else if (c == '\f') esc = "\\f"; - else if (c == '\n') esc = "\\n"; - else if (c == '\r') esc = "\\r"; - else if (c == '\t') esc = "\\t"; - else if (c < 0x20) { - u[0] = '\\', u[1] = 'u', u[2] = '0', u[3] = '0', u[4] = hexd[c >> 4], u[5] = hexd[c & 15], u[6] = 0; - esc = u; - } - if (esc) { - nj_buf_put(b, s + i - run, run); - run = 0; - nj_buf_puts(b, esc); - } else { - run++; - } - } - nj_buf_put(b, s + len - run, run); - nj_buf_putc(b, '"'); -} - -char* nj_buf_take(nj_buf* b) -{ - char* p; - if (b->oom || !b->p) { - free(b->p); - memset(b, 0, sizeof *b); - return NULL; - } - p = b->p; - memset(b, 0, sizeof *b); - return p; -} - -void nj_buf_free(nj_buf* b) -{ - free(b->p); - memset(b, 0, sizeof *b); -} - -char* nj_strdup(const char* s) -{ - size_t n; - char* p; - if (!s) return NULL; - n = strlen(s); - p = (char*)malloc(n + 1); - if (p) memcpy(p, s, n + 1); - return p; -} - -void nj_hex(const uint8_t* in, size_t len, char* out) -{ - static const char hexd[] = "0123456789abcdef"; - size_t i; - for (i = 0; i < len; i++) { - out[2 * i] = hexd[in[i] >> 4]; - out[2 * i + 1] = hexd[in[i] & 15]; - } - out[2 * len] = 0; -} - -static int hexval(char c) -{ - if (c >= '0' && c <= '9') return c - '0'; - if (c >= 'a' && c <= 'f') return c - 'a' + 10; - if (c >= 'A' && c <= 'F') return c - 'A' + 10; - return -1; -} - -int nj_unhex(const char* in, size_t len, uint8_t* out) -{ - size_t i; - if (len % 2) return -1; - for (i = 0; i < len; i += 2) { - int h = hexval(in[i]), l = hexval(in[i + 1]); - if (h < 0 || l < 0) return -1; - out[i / 2] = (uint8_t)(h << 4 | l); - } - return 0; -} - -/* ---- base64url, no padding ---- */ - -static const char B64U[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; - -size_t atyha_b64u_encode(const uint8_t* in, size_t len, char* out, size_t cap) -{ - size_t need = len / 3 * 4 + (len % 3 ? len % 3 + 1 : 0); - size_t i, o = 0; - char tmp[4]; - for (i = 0; i < len; i += 3) { - uint32_t v = (uint32_t)in[i] << 16; - size_t k, chunk = len - i < 3 ? len - i : 3; - if (chunk > 1) v |= (uint32_t)in[i + 1] << 8; - if (chunk > 2) v |= in[i + 2]; - tmp[0] = B64U[v >> 18 & 63]; - tmp[1] = B64U[v >> 12 & 63]; - tmp[2] = B64U[v >> 6 & 63]; - tmp[3] = B64U[v & 63]; - for (k = 0; k < chunk + 1; k++, o++) - if (o < cap) out[o] = tmp[k]; - } - if (cap > need) out[need] = 0; - return need; -} - -static int b64val(char c) -{ - if (c >= 'A' && c <= 'Z') return c - 'A'; - if (c >= 'a' && c <= 'z') return c - 'a' + 26; - if (c >= '0' && c <= '9') return c - '0' + 52; - if (c == '-') return 62; - if (c == '_') return 63; - return -1; -} - -long atyha_b64u_decode(const char* in, size_t in_len, uint8_t* out, size_t cap) -{ - size_t i, o = 0, rem = in_len % 4; - size_t need = in_len / 4 * 3 + (rem ? rem - 1 : 0); - if (rem == 1) return -1; - if (need > cap) return -1; - for (i = 0; i < in_len; i += 4) { - uint32_t v = 0; - size_t k, chunk = in_len - i < 4 ? in_len - i : 4; - for (k = 0; k < 4; k++) { - int d = 0; - if (k < chunk) { - d = b64val(in[i + k]); - if (d < 0) return -1; - } - v = v << 6 | (uint32_t)d; - } - if (chunk == 2 && (v & 0xffff)) return -1; /* trailing bits must be zero */ - if (chunk == 3 && (v & 0xff)) return -1; - out[o++] = (uint8_t)(v >> 16); - if (chunk > 2) out[o++] = (uint8_t)(v >> 8); - if (chunk > 3) out[o++] = (uint8_t)v; - } - return (long)o; -} - -/* ---- clock ---- */ - -int64_t atyha_now_ms(void) -{ -#if defined(_WIN32) - return (int64_t)GetTickCount64(); -#elif defined(__EMSCRIPTEN__) - return (int64_t)emscripten_get_now(); -#else - struct timespec ts; - clock_gettime(CLOCK_MONOTONIC, &ts); - return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000; -#endif -} diff --git a/common/atyha/src/ws_curl.c b/common/atyha/src/ws_curl.c deleted file mode 100644 index b95c8a1..0000000 --- a/common/atyha/src/ws_curl.c +++ /dev/null @@ -1,290 +0,0 @@ -/* SPDX-License-Identifier: MIT - Copyright (c) 2026 ngspades contributors - - WebSocket backend on libcurl (8.11+): CONNECT_ONLY = 2 easy handles on a - multi handle, so the connection is made without blocking, then - curl_ws_send / curl_ws_recv. */ -#include -#include - -#include - -#include "internal.h" -#include "atyha_curl.h" - -#define MAX_MESSAGE (1u << 20) - -enum { C_CONNECTING, C_OPEN, C_CLOSED }; - -typedef struct out_msg { - char* data; - size_t len, off; - struct out_msg* next; -} out_msg; - -typedef struct curl_backend curl_backend; - -struct atyha_ws { - curl_backend* be; - CURL* easy; - int state; - int open_reported, closed_reported; - out_msg *out_head, *out_tail; - nj_buf in; /* the message being received */ - int in_binary; /* it is binary: dropped */ - int in_oversize; /* too large: dropped */ - char* current; /* the last message handed over */ - char err[CURL_ERROR_SIZE]; - struct atyha_ws* next; -}; - -struct curl_backend { - atyha_ws_backend base; - CURLM* multi; - char* ca_file; - char* user_agent; - long connect_timeout_ms; - atyha_ws* conns; -}; - -static void set_closed(atyha_ws* ws, const char* why) -{ - if (ws->state == C_CLOSED) return; - ws->state = C_CLOSED; - if (why && !ws->err[0]) { - strncpy(ws->err, why, sizeof ws->err - 1); - ws->err[sizeof ws->err - 1] = 0; - } -} - -static void be_update(atyha_ws_backend* base) -{ - curl_backend* be = (curl_backend*)base; - int running = 0, left = 0; - CURLMsg* msg; - curl_multi_perform(be->multi, &running); - while ((msg = curl_multi_info_read(be->multi, &left)) != NULL) { - atyha_ws* ws = NULL; - if (msg->msg != CURLMSG_DONE) continue; - curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, (char**)&ws); - if (!ws || ws->state != C_CONNECTING) continue; - if (msg->data.result == CURLE_OK) { - long code = 0; - curl_easy_getinfo(ws->easy, CURLINFO_RESPONSE_CODE, &code); - if (code == 101) ws->state = C_OPEN; - else set_closed(ws, "the server did not upgrade to WebSocket"); - } else { - set_closed(ws, ws->err[0] ? ws->err : curl_easy_strerror(msg->data.result)); - } - } -} - -static atyha_ws* be_connect(atyha_ws_backend* base, const char* url) -{ - curl_backend* be = (curl_backend*)base; - atyha_ws* ws = (atyha_ws*)calloc(1, sizeof *ws); - if (!ws) return NULL; - ws->be = be; - ws->easy = curl_easy_init(); - if (!ws->easy) { - free(ws); - return NULL; - } - curl_easy_setopt(ws->easy, CURLOPT_URL, url); - curl_easy_setopt(ws->easy, CURLOPT_CONNECT_ONLY, 2L); - curl_easy_setopt(ws->easy, CURLOPT_PRIVATE, (char*)ws); - curl_easy_setopt(ws->easy, CURLOPT_ERRORBUFFER, ws->err); - curl_easy_setopt(ws->easy, CURLOPT_NOSIGNAL, 1L); - curl_easy_setopt(ws->easy, CURLOPT_CONNECTTIMEOUT_MS, be->connect_timeout_ms); - curl_easy_setopt(ws->easy, CURLOPT_USERAGENT, be->user_agent); - if (be->ca_file) curl_easy_setopt(ws->easy, CURLOPT_CAINFO, be->ca_file); - if (curl_multi_add_handle(be->multi, ws->easy) != CURLM_OK) { - curl_easy_cleanup(ws->easy); - free(ws); - return NULL; - } - ws->next = be->conns; - be->conns = ws; - return ws; -} - -static int be_send(atyha_ws* ws, const char* text, size_t len) -{ - out_msg* m; - if (ws->state == C_CLOSED) return -1; - m = (out_msg*)calloc(1, sizeof *m); - if (!m) return -1; - m->data = (char*)malloc(len ? len : 1); - if (!m->data) { - free(m); - return -1; - } - memcpy(m->data, text, len); - m->len = len; - if (ws->out_tail) ws->out_tail->next = m; - else ws->out_head = m; - ws->out_tail = m; - return 0; -} - -static void flush(atyha_ws* ws) -{ - while (ws->state == C_OPEN && ws->out_head) { - out_msg* m = ws->out_head; - size_t sent = 0; - CURLcode rc = curl_ws_send(ws->easy, m->data + m->off, m->len - m->off, &sent, 0, CURLWS_TEXT); - if (rc == CURLE_AGAIN) { - m->off += sent; - return; - } - if (rc != CURLE_OK) { - set_closed(ws, curl_easy_strerror(rc)); - return; - } - m->off += sent; - if (m->off < m->len) continue; - ws->out_head = m->next; - if (!ws->out_head) ws->out_tail = NULL; - free(m->data); - free(m); - } -} - -/* 1 when a whole text message is in ws->in */ -static int receive(atyha_ws* ws) -{ - char buf[16384]; - for (;;) { - size_t n = 0; - const struct curl_ws_frame* meta = NULL; - CURLcode rc = curl_ws_recv(ws->easy, buf, sizeof buf, &n, &meta); - if (rc == CURLE_AGAIN) return 0; - if (rc != CURLE_OK) { - set_closed(ws, rc == CURLE_GOT_NOTHING ? "closed by the server" : curl_easy_strerror(rc)); - return 0; - } - if (!meta) continue; - if (meta->flags & CURLWS_CLOSE) { - set_closed(ws, "closed by the server"); - return 0; - } - if (meta->flags & (CURLWS_PING | CURLWS_PONG)) continue; - if (meta->flags & CURLWS_BINARY) ws->in_binary = 1; - if (!ws->in_binary && !ws->in_oversize) { - if (ws->in.n + n > MAX_MESSAGE) { - ws->in_oversize = 1; - nj_buf_free(&ws->in); - } else { - nj_buf_put(&ws->in, buf, n); - } - } - if (meta->bytesleft == 0 && !(meta->flags & CURLWS_CONT)) { - int whole = !ws->in_binary && !ws->in_oversize && !ws->in.oom; - ws->in_binary = ws->in_oversize = 0; - if (whole) return 1; - nj_buf_free(&ws->in); - } - } -} - -static int be_poll(atyha_ws* ws, atyha_ws_event* ev) -{ - free(ws->current); - ws->current = NULL; - memset(ev, 0, sizeof *ev); - if (ws->state == C_OPEN && !ws->open_reported) { - ws->open_reported = 1; - ev->type = ATYHA_WS_OPEN; - return 1; - } - if (ws->state == C_OPEN) { - flush(ws); - if (ws->state == C_OPEN && receive(ws)) { - if (!ws->in.p) nj_buf_put(&ws->in, "", 0); - ev->type = ATYHA_WS_TEXT; - ev->len = ws->in.n; - ws->current = nj_buf_take(&ws->in); - ev->data = ws->current; - if (!ev->data) { - ev->type = ATYHA_WS_NONE; - return 0; - } - return 1; - } - } - if (ws->state == C_CLOSED && !ws->closed_reported) { - ws->closed_reported = 1; - ev->type = ATYHA_WS_CLOSED; - ev->data = ws->err; - ev->len = strlen(ws->err); - return 1; - } - return 0; -} - -static void be_close(atyha_ws* ws) -{ - curl_backend* be = ws->be; - atyha_ws** p; - if (ws->state == C_OPEN) { - size_t sent = 0; - flush(ws); /* what is queued (a CLOSE of the subscription), if it goes at once */ - curl_ws_send(ws->easy, "", 0, &sent, 0, CURLWS_CLOSE); - } - curl_multi_remove_handle(be->multi, ws->easy); - curl_easy_cleanup(ws->easy); - for (p = &be->conns; *p; p = &(*p)->next) - if (*p == ws) { - *p = ws->next; - break; - } - while (ws->out_head) { - out_msg* m = ws->out_head; - ws->out_head = m->next; - free(m->data); - free(m); - } - nj_buf_free(&ws->in); - free(ws->current); - free(ws); -} - -atyha_ws_backend* atyha_curl_backend_create(const atyha_curl_options* o) -{ - curl_backend* be; - const curl_version_info_data* info; - const char* const* p; - int has_ws = 0; - if (curl_global_init(CURL_GLOBAL_DEFAULT) != CURLE_OK) return NULL; - info = curl_version_info(CURLVERSION_NOW); - for (p = info->protocols; p && *p; p++) - if (!strcmp(*p, "wss")) has_ws = 1; - if (!has_ws) return NULL; - be = (curl_backend*)calloc(1, sizeof *be); - if (!be) return NULL; - be->multi = curl_multi_init(); - be->user_agent = nj_strdup(o && o->user_agent ? o->user_agent : "atyha/1"); - be->ca_file = o && o->ca_file ? nj_strdup(o->ca_file) : NULL; - be->connect_timeout_ms = o && o->connect_timeout_ms > 0 ? o->connect_timeout_ms : 10000; - if (!be->multi || !be->user_agent) { - atyha_curl_backend_destroy(&be->base); - return NULL; - } - be->base.connect = be_connect; - be->base.send = be_send; - be->base.poll = be_poll; - be->base.close = be_close; - be->base.update = be_update; - return &be->base; -} - -void atyha_curl_backend_destroy(atyha_ws_backend* base) -{ - curl_backend* be = (curl_backend*)base; - if (!be) return; - while (be->conns) be_close(be->conns); - if (be->multi) curl_multi_cleanup(be->multi); - free(be->ca_file); - free(be->user_agent); - free(be); -} diff --git a/common/atyha/src/ws_emscripten.c b/common/atyha/src/ws_emscripten.c deleted file mode 100644 index 83b99cb..0000000 --- a/common/atyha/src/ws_emscripten.c +++ /dev/null @@ -1,198 +0,0 @@ -/* SPDX-License-Identifier: MIT - Copyright (c) 2026 ngspades contributors - - WebSocket backend on (the browser's WebSocket). */ -#ifdef __EMSCRIPTEN__ -#include -#include - -#include - -#include "internal.h" -#include "atyha_emscripten.h" - -typedef struct in_msg { - atyha_ws_event_type type; - char* data; - size_t len; - struct in_msg* next; -} in_msg; - -typedef struct em_backend { - atyha_ws_backend base; - struct atyha_ws* conns; -} em_backend; - -struct atyha_ws { - em_backend* be; - EMSCRIPTEN_WEBSOCKET_T sock; - int open, closed; - in_msg *head, *tail; - char* current; - struct atyha_ws* next; -}; - -static void push(struct atyha_ws* ws, atyha_ws_event_type type, const char* data, size_t len) -{ - in_msg* m; - if (ws->closed) return; - m = (in_msg*)calloc(1, sizeof *m); - if (!m) return; - m->type = type; - if (data) { - m->data = (char*)malloc(len + 1); - if (!m->data) { - free(m); - return; - } - memcpy(m->data, data, len); - m->data[len] = 0; - m->len = len; - } - if (type == ATYHA_WS_CLOSED) ws->closed = 1; - if (ws->tail) ws->tail->next = m; - else ws->head = m; - ws->tail = m; -} - -static EM_BOOL on_open(int type, const EmscriptenWebSocketOpenEvent* e, void* user) -{ - struct atyha_ws* ws = (struct atyha_ws*)user; - (void)type, (void)e; - ws->open = 1; - push(ws, ATYHA_WS_OPEN, NULL, 0); - return EM_TRUE; -} - -static EM_BOOL on_message(int type, const EmscriptenWebSocketMessageEvent* e, void* user) -{ - struct atyha_ws* ws = (struct atyha_ws*)user; - (void)type; - /* text arrives NUL-terminated, numBytes counting the NUL */ - if (e->isText && e->numBytes > 0) push(ws, ATYHA_WS_TEXT, (const char*)e->data, e->numBytes - 1); - return EM_TRUE; -} - -static EM_BOOL on_error(int type, const EmscriptenWebSocketErrorEvent* e, void* user) -{ - (void)type, (void)e, (void)user; - return EM_TRUE; /* a close event follows */ -} - -static EM_BOOL on_close(int type, const EmscriptenWebSocketCloseEvent* e, void* user) -{ - struct atyha_ws* ws = (struct atyha_ws*)user; - (void)type; - push(ws, ATYHA_WS_CLOSED, e->reason, strlen(e->reason)); - ws->open = 0; - return EM_TRUE; -} - -static struct atyha_ws* em_connect(atyha_ws_backend* base, const char* url) -{ - em_backend* be = (em_backend*)base; - EmscriptenWebSocketCreateAttributes attr; - struct atyha_ws* ws; - if (!emscripten_websocket_is_supported()) return NULL; - ws = (struct atyha_ws*)calloc(1, sizeof *ws); - if (!ws) return NULL; - emscripten_websocket_init_create_attributes(&attr); - attr.url = url; - attr.protocols = NULL; - attr.createOnMainThread = EM_TRUE; - ws->sock = emscripten_websocket_new(&attr); - if (ws->sock <= 0) { - free(ws); - return NULL; - } - ws->be = be; - emscripten_websocket_set_onopen_callback(ws->sock, ws, on_open); - emscripten_websocket_set_onmessage_callback(ws->sock, ws, on_message); - emscripten_websocket_set_onerror_callback(ws->sock, ws, on_error); - emscripten_websocket_set_onclose_callback(ws->sock, ws, on_close); - ws->next = be->conns; - be->conns = ws; - return ws; -} - -static int em_send(struct atyha_ws* ws, const char* text, size_t len) -{ - char* s; - EMSCRIPTEN_RESULT r; - if (!ws->open || ws->closed) return -1; - /* send_utf8_text takes a NUL-terminated string */ - s = (char*)malloc(len + 1); - if (!s) return -1; - memcpy(s, text, len); - s[len] = 0; - r = emscripten_websocket_send_utf8_text(ws->sock, s); - free(s); - return r == EMSCRIPTEN_RESULT_SUCCESS ? 0 : -1; -} - -static int em_poll(struct atyha_ws* ws, atyha_ws_event* ev) -{ - in_msg* m; - free(ws->current); - ws->current = NULL; - memset(ev, 0, sizeof *ev); - m = ws->head; - if (!m) return 0; - ws->head = m->next; - if (!ws->head) ws->tail = NULL; - ev->type = m->type; - ev->data = m->data; - ev->len = m->len; - ws->current = m->data; - free(m); - return 1; -} - -static void em_close(struct atyha_ws* ws) -{ - em_backend* be = ws->be; - struct atyha_ws** p; - unsigned short state = 0; - emscripten_websocket_get_ready_state(ws->sock, &state); - if (state <= 1) emscripten_websocket_close(ws->sock, 1000, "bye"); - /* no callback may reach the freed connection */ - emscripten_websocket_set_onopen_callback(ws->sock, NULL, NULL); - emscripten_websocket_set_onmessage_callback(ws->sock, NULL, NULL); - emscripten_websocket_set_onerror_callback(ws->sock, NULL, NULL); - emscripten_websocket_set_onclose_callback(ws->sock, NULL, NULL); - emscripten_websocket_delete(ws->sock); - for (p = &be->conns; *p; p = &(*p)->next) - if (*p == ws) { - *p = ws->next; - break; - } - while (ws->head) { - in_msg* m = ws->head; - ws->head = m->next; - free(m->data); - free(m); - } - free(ws->current); - free(ws); -} - -atyha_ws_backend* atyha_emscripten_backend_create(void) -{ - em_backend* be = (em_backend*)calloc(1, sizeof *be); - if (!be) return NULL; - be->base.connect = em_connect; - be->base.send = em_send; - be->base.poll = em_poll; - be->base.close = em_close; - be->base.update = NULL; - return &be->base; -} - -void atyha_emscripten_backend_destroy(atyha_ws_backend* base) -{ - em_backend* be = (em_backend*)base; - if (!be) return; - while (be->conns) em_close(be->conns); - free(be); -} -#endif diff --git a/common/atyha/src/ws_libdatachannel.c b/common/atyha/src/ws_libdatachannel.c deleted file mode 100644 index d536288..0000000 --- a/common/atyha/src/ws_libdatachannel.c +++ /dev/null @@ -1,241 +0,0 @@ -/* SPDX-License-Identifier: MIT - Copyright (c) 2026 ngspades contributors - - WebSocket backend on libdatachannel's C API (rtcCreateWebSocketEx...). - Its callbacks run on libdatachannel's threads: they only append to the - connection's queue under the connection's lock; atyha drains the queue - from its poll, on the program's thread. Closing deletes the rtc - WebSocket first (rtcDeleteWebSocket resets its callbacks, waiting for one - in flight), then frees the queue. */ -#include -#include - -#include - -#include "internal.h" -#include "atyha_libdatachannel.h" - -#ifdef _WIN32 -#include -typedef CRITICAL_SECTION nj_lock; -#define LOCK_INIT(l) InitializeCriticalSection(l) -#define LOCK_FREE(l) DeleteCriticalSection(l) -#define LOCK(l) EnterCriticalSection(l) -#define UNLOCK(l) LeaveCriticalSection(l) -#else -#include -typedef pthread_mutex_t nj_lock; -#define LOCK_INIT(l) pthread_mutex_init(l, NULL) -#define LOCK_FREE(l) pthread_mutex_destroy(l) -#define LOCK(l) pthread_mutex_lock(l) -#define UNLOCK(l) pthread_mutex_unlock(l) -#endif - -#define MAX_QUEUED (4u << 20) /* bytes waiting to be polled; beyond, messages are dropped */ - -typedef struct in_msg { - atyha_ws_event_type type; - char* data; - size_t len; - struct in_msg* next; -} in_msg; - -typedef struct ldc_backend { - atyha_ws_backend base; - int disable_tls_verification; - int connection_timeout_ms; - struct atyha_ws* conns; /* program thread only */ -} ldc_backend; - -struct atyha_ws { - ldc_backend* be; - int id; /* the rtc WebSocket */ - nj_lock lock; - /* under lock: */ - in_msg *head, *tail; - size_t queued; - int open, closed; - /* program thread only: */ - char* current; - struct atyha_ws* next; -}; - -/* under ws->lock */ -static void push_locked(struct atyha_ws* ws, atyha_ws_event_type type, const char* data, size_t len) -{ - in_msg* m; - if (ws->closed) return; - if (type == ATYHA_WS_TEXT && ws->queued + len > MAX_QUEUED) return; - m = (in_msg*)calloc(1, sizeof *m); - if (!m) return; - m->type = type; - if (data) { - m->data = (char*)malloc(len + 1); - if (!m->data) { - free(m); - return; - } - memcpy(m->data, data, len); - m->data[len] = 0; - m->len = len; - } - if (type == ATYHA_WS_OPEN) ws->open = 1; - if (type == ATYHA_WS_CLOSED) ws->closed = 1; - if (type == ATYHA_WS_TEXT) ws->queued += len; - if (ws->tail) ws->tail->next = m; - else ws->head = m; - ws->tail = m; -} - -static void push(struct atyha_ws* ws, atyha_ws_event_type type, const char* data, size_t len) -{ - LOCK(&ws->lock); - push_locked(ws, type, data, len); - UNLOCK(&ws->lock); -} - -/* ---- libdatachannel's threads ---- */ - -static void RTC_API on_open(int id, void* ptr) -{ - (void)id; - if (ptr) push((struct atyha_ws*)ptr, ATYHA_WS_OPEN, NULL, 0); -} - -static void RTC_API on_closed(int id, void* ptr) -{ - (void)id; - if (ptr) push((struct atyha_ws*)ptr, ATYHA_WS_CLOSED, "closed", 6); -} - -static void RTC_API on_error(int id, const char* error, void* ptr) -{ - (void)id; - if (ptr) push((struct atyha_ws*)ptr, ATYHA_WS_CLOSED, error ? error : "error", error ? strlen(error) : 5); -} - -static void RTC_API on_message(int id, const char* message, int size, void* ptr) -{ - (void)id; - /* size < 0: a text message, NUL-terminated; binary ones are dropped */ - if (ptr && size < 0 && message) push((struct atyha_ws*)ptr, ATYHA_WS_TEXT, message, strlen(message)); -} - -/* ---- the program's thread ---- */ - -static struct atyha_ws* ldc_connect(atyha_ws_backend* base, const char* url) -{ - ldc_backend* be = (ldc_backend*)base; - rtcWsConfiguration cfg; - struct atyha_ws* ws = (struct atyha_ws*)calloc(1, sizeof *ws); - if (!ws) return NULL; - LOCK_INIT(&ws->lock); - ws->be = be; - memset(&cfg, 0, sizeof cfg); - cfg.disableTlsVerification = be->disable_tls_verification != 0; - cfg.connectionTimeoutMs = be->connection_timeout_ms; - ws->id = rtcCreateWebSocketEx(url, &cfg); - if (ws->id < 0) { - LOCK_FREE(&ws->lock); - free(ws); - return NULL; - } - /* the user pointer first, so that no callback sees a NULL one... */ - rtcSetUserPointer(ws->id, ws); - rtcSetOpenCallback(ws->id, on_open); - rtcSetClosedCallback(ws->id, on_closed); - rtcSetErrorCallback(ws->id, on_error); - rtcSetMessageCallback(ws->id, on_message); - /* ...and an open that happened before the callback was set is not lost */ - if (rtcIsOpen(ws->id)) { - LOCK(&ws->lock); - if (!ws->open) push_locked(ws, ATYHA_WS_OPEN, NULL, 0); - UNLOCK(&ws->lock); - } - ws->next = be->conns; - be->conns = ws; - return ws; -} - -static int ldc_send(struct atyha_ws* ws, const char* text, size_t len) -{ - char* s; - int r; - if (len > 0x7fffffff) return -1; - s = (char*)malloc(len + 1); - if (!s) return -1; - memcpy(s, text, len); - s[len] = 0; - r = rtcSendMessage(ws->id, s, -1); /* thread-safe; size -1: a text message */ - free(s); - return r < 0 ? -1 : 0; -} - -static int ldc_poll(struct atyha_ws* ws, atyha_ws_event* ev) -{ - in_msg* m; - free(ws->current); - ws->current = NULL; - memset(ev, 0, sizeof *ev); - LOCK(&ws->lock); - m = ws->head; - if (m) { - ws->head = m->next; - if (!ws->head) ws->tail = NULL; - if (m->type == ATYHA_WS_TEXT) ws->queued -= m->len; - } - UNLOCK(&ws->lock); - if (!m) return 0; - ev->type = m->type; - ev->data = m->data; - ev->len = m->len; - ws->current = m->data; - free(m); - return 1; -} - -static void ldc_close(struct atyha_ws* ws) -{ - ldc_backend* be = ws->be; - struct atyha_ws** p; - /* not under our lock: deleting may run the closed callback here */ - rtcDeleteWebSocket(ws->id); /* closes, resets the callbacks (waits for one in flight) */ - for (p = &be->conns; *p; p = &(*p)->next) - if (*p == ws) { - *p = ws->next; - break; - } - LOCK(&ws->lock); - while (ws->head) { - in_msg* m = ws->head; - ws->head = m->next; - free(m->data); - free(m); - } - UNLOCK(&ws->lock); - LOCK_FREE(&ws->lock); - free(ws->current); - free(ws); -} - -atyha_ws_backend* atyha_libdatachannel_backend_create(const atyha_libdatachannel_options* o) -{ - ldc_backend* be = (ldc_backend*)calloc(1, sizeof *be); - if (!be) return NULL; - be->disable_tls_verification = o ? o->disable_tls_verification : 0; - be->connection_timeout_ms = o && o->connection_timeout_ms > 0 ? o->connection_timeout_ms : 0; - be->base.connect = ldc_connect; - be->base.send = ldc_send; - be->base.poll = ldc_poll; - be->base.close = ldc_close; - be->base.update = NULL; - return &be->base; -} - -void atyha_libdatachannel_backend_destroy(atyha_ws_backend* base) -{ - ldc_backend* be = (ldc_backend*)base; - if (!be) return; - while (be->conns) ldc_close(be->conns); - free(be); -} From 4a9a59af9223965189ff58b2f14f628c4b11eef8 Mon Sep 17 00:00:00 2001 From: Gustavo Date: Mon, 30 Nov 2026 18:42:25 -0300 Subject: [PATCH 5/5] CMake: Atyha's C library is the submodule's c/ --- server/CMakeLists.txt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/server/CMakeLists.txt b/server/CMakeLists.txt index 63472b6..8cac039 100644 --- a/server/CMakeLists.txt +++ b/server/CMakeLists.txt @@ -103,12 +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, MIT): the match's room on public Nostr relays +# 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 ${CMAKE_BINARY_DIR}/atyha) +add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../common/atyha/c ${CMAKE_BINARY_DIR}/atyha) endif() # NOT SERVER_WEB_HOST set(CMAKE_EXPORT_COMPILE_COMMANDS ON)