From d8111dd32aac0cdc1cd4a56627c2598851a3316c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammed=20Tanr=C4=B1kulu?= Date: Thu, 19 Feb 2026 11:38:10 -0300 Subject: [PATCH] feat: add native WebRTC bridge with libdatachannel/rustrtc bindings --- deps/rustrtc-capi/Cargo.lock | 1766 +++++++++++++++++++++++++ deps/rustrtc-capi/Cargo.toml | 25 + deps/rustrtc-capi/src/lib.rs | 753 +++++++++++ deps/rustrtc-capi/src/monitors.rs | 338 +++++ deps/rustrtc-capi/src/state.rs | 254 ++++ deps/rustrtc-capi/src/types.rs | 107 ++ deps/rustrtc-capi/src/ws_signaling.rs | 304 +++++ deps/rustrtc-capi/tests/loopback.rs | 573 ++++++++ src/platform/webrtc_bridge.zig | 1112 ++++++++++++++++ src/platform/webrtc_dht_signaling.zig | 653 +++++++++ src/platform/webrtc_native.zig | 880 ++++++++++++ src/platform/webrtc_signaling.zig | 219 +++ src/platform/webrtc_wasm.zig | 252 ++++ 13 files changed, 7236 insertions(+) create mode 100644 deps/rustrtc-capi/Cargo.lock create mode 100644 deps/rustrtc-capi/Cargo.toml create mode 100644 deps/rustrtc-capi/src/lib.rs create mode 100644 deps/rustrtc-capi/src/monitors.rs create mode 100644 deps/rustrtc-capi/src/state.rs create mode 100644 deps/rustrtc-capi/src/types.rs create mode 100644 deps/rustrtc-capi/src/ws_signaling.rs create mode 100644 deps/rustrtc-capi/tests/loopback.rs create mode 100644 src/platform/webrtc_bridge.zig create mode 100644 src/platform/webrtc_dht_signaling.zig create mode 100644 src/platform/webrtc_native.zig create mode 100644 src/platform/webrtc_signaling.zig create mode 100644 src/platform/webrtc_wasm.zig diff --git a/deps/rustrtc-capi/Cargo.lock b/deps/rustrtc-capi/Cargo.lock new file mode 100644 index 0000000..e77cbd7 --- /dev/null +++ b/deps/rustrtc-capi/Cargo.lock @@ -0,0 +1,1766 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "anstream" +version = "0.6.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78" + +[[package]] +name = "anstyle-parse" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.101" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f0e0fee31ef5ed1ba1316088939cea399010ed7731dba877ed44aeb407a75ea" + +[[package]] +name = "asn1-rs" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56624a96882bb8c26d61312ae18cb45868e5a9992ea73c58e45c3101e56a1e60" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom", + "num-traits", + "rusticata-macros", + "thiserror 2.0.18", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "async-trait" +version = "0.1.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + +[[package]] +name = "aws-lc-rs" +version = "1.15.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b7b6141e96a8c160799cc2d5adecd5cbbe5054cb8c7c4af53da0f83bb7ad256" +dependencies = [ + "aws-lc-sys", + "untrusted", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.37.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b092fe214090261288111db7a2b2c2118e5a7f30dc2569f1732c4069a6840549" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", +] + +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bitflags" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" +dependencies = [ + "serde", +] + +[[package]] +name = "cc" +version = "1.2.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aebf35691d1bfb0ac386a69bac2fde4dd276fb618cf8bf4f5318fe285e821bb2" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "cmake" +version = "0.1.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75443c44cd6b379beb8c5b45d85d0773baf31cce901fe7bb252f4eff3008ef7d" +dependencies = [ + "cc", +] + +[[package]] +name = "colorchoice" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32c" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a47af21622d091a8f0fb295b88bc886ac74efcc613efc19f5d0b21de5c89e47" +dependencies = [ + "rustc_version", +] + +[[package]] +name = "crc32fast" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "typenum", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "data-encoding" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7a1e2f27636f116493b8b860f5546edb47c8d8f8ea73e1d2a20be88e28d1fea" + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom", + "num-bigint", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "deranged" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc3dc5ad92c2e2d1c193bbbbdf2ea477cb81331de4f3103f267ca18368b988c4" +dependencies = [ + "powerfmt", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "subtle", +] + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der", + "digest", + "elliptic-curve", + "rfc6979", + "signature", + "spki", +] + +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest", + "ff", + "generic-array", + "group", + "hkdf", + "pem-rfc7468", + "pkcs8", + "rand_core 0.6.4", + "sec1", + "subtle", + "zeroize", +] + +[[package]] +name = "env_filter" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a1c3cc8e57274ec99de65301228b537f1e4eedc1b8e0f9411c6caac8ae7308f" +dependencies = [ + "log", + "regex", +] + +[[package]] +name = "env_logger" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2daee4ea451f429a58296525ddf28b45a3b64f1acf6587e2067437bb11e218d" +dependencies = [ + "anstream", + "anstyle", + "env_filter", + "jiff", + "log", +] + +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "futures" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-executor" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" + +[[package]] +name = "futures-macro" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", + "zeroize", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasip2", +] + +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "http" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" + +[[package]] +name = "jiff" +version = "0.2.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c867c356cc096b33f4981825ab281ecba3db0acefe60329f044c1789d94c6543" +dependencies = [ + "jiff-static", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", +] + +[[package]] +name = "jiff-static" +version = "0.2.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7946b4325269738f270bb55b3c19ab5c5040525f83fd625259422a9d25d9be5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "jobserver" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" +dependencies = [ + "getrandom 0.3.4", + "libc", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libc" +version = "0.2.182" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" + +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + +[[package]] +name = "memchr" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "mio" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "network-interface" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ddcb8865ad3d9950f22f42ffa0ef0aecbfbf191867b3122413602b0a360b2a6" +dependencies = [ + "cc", + "libc", + "thiserror 2.0.18", + "winapi", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num-bigint" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf97ec579c3c42f953ef76dbf8d55ac91fb219dde70e49aa4a6b7d74e9919050" + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + +[[package]] +name = "once_cell" +version = "1.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64", + "serde_core", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "portable-atomic" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" + +[[package]] +name = "portable-atomic-util" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9db96d7fa8782dd8c15ce32ffe8680bbd1e978a43bf51a34d39483540495f5" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rcgen" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10b99e0098aa4082912d4c649628623db6aba77335e4f4569ff5083a6448b32e" +dependencies = [ + "aws-lc-rs", + "pem", + "rustls-pki-types", + "time", + "x509-parser", + "yasna", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a96887878f22d7bad8a3b6dc5b7440e0ada9a245242924394987b21cf2210a4c" + +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom", +] + +[[package]] +name = "rustls-pki-types" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustrtc" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "590097682d1a7d9e70b229d7f00a26f01dd4a0fe18013bb95d7ade1e3ca7b88a" +dependencies = [ + "aes", + "aes-gcm", + "anyhow", + "async-trait", + "base64", + "bytes", + "crc32c", + "crc32fast", + "ctr", + "futures", + "hmac", + "md-5", + "network-interface", + "p256", + "rand 0.9.2", + "rand_core 0.6.4", + "rcgen", + "serde", + "serde_json", + "sha1", + "sha2", + "thiserror 2.0.18", + "tokio", + "tracing", +] + +[[package]] +name = "rustrtc-capi" +version = "0.1.0" +dependencies = [ + "bytes", + "env_logger", + "futures-util", + "log", + "parking_lot", + "rustrtc", + "serde", + "serde_json", + "time", + "tokio", + "tokio-tungstenite", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "subtle", + "zeroize", +] + +[[package]] +name = "semver" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha1" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest", + "rand_core 0.6.4", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "socket2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86f4aa3ad99f2088c990dfa82d367e19cb29268ed67c574d10d0a4bfe71f07e0" +dependencies = [ + "libc", + "windows-sys 0.60.2", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.116" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3df424c70518695237746f84cede799c9c58fcb37450d7b23716568cc8bc69cb" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl 2.0.18", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "time" +version = "0.3.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9da98b7d9b7dad93488a84b8248efc35352b0b2657397d4167e7ad67e5d535e5" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" + +[[package]] +name = "time-macros" +version = "0.2.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78cc610bac2dcee56805c99642447d4c5dbde4d01f752ffea0199aee1f601dc4" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tokio" +version = "1.49.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edc5f74e248dc973e0dbb7b74c7e0d6fcc301c694ff50049504004ef4d0cdcd9" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "tungstenite" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18e5b8366ee7a95b16d32197d0b2604b43a0be89dc5fac9f8e96ccafbaedda8a" +dependencies = [ + "byteorder", + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.8.5", + "sha1", + "thiserror 1.0.69", + "utf-8", +] + +[[package]] +name = "typenum" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" + +[[package]] +name = "unicode-ident" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "537dd038a89878be9b64dd4bd1b260315c1bb94f4d784956b81e27a088d9a09e" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + +[[package]] +name = "untrusted" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" + +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.2+wasi-0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "wit-bindgen" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" + +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "aws-lc-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom", + "oid-registry", + "rusticata-macros", + "thiserror 2.0.18", + "time", +] + +[[package]] +name = "yasna" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17bb3549cc1321ae1296b9cdc2698e2b6cb1992adfa19a8c72e5b7a738f44cd" +dependencies = [ + "time", +] + +[[package]] +name = "zerocopy" +version = "0.8.39" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db6d35d663eadb6c932438e763b262fe1a70987f9ae936e60158176d710cae4a" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.39" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4122cd3169e94605190e77839c9a40d40ed048d305bfdc146e7df40ab0f3e517" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zeroize" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/deps/rustrtc-capi/Cargo.toml b/deps/rustrtc-capi/Cargo.toml new file mode 100644 index 0000000..df8aa1e --- /dev/null +++ b/deps/rustrtc-capi/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "rustrtc-capi" +version = "0.1.0" +edition = "2021" + +[lib] +name = "datachannel" +crate-type = ["cdylib", "rlib"] + +[dependencies] +rustrtc = "0.3" +tokio = { version = "1", features = ["rt-multi-thread", "sync", "time", "macros"] } +tokio-tungstenite = "0.24" +futures-util = "0.3" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +parking_lot = "0.12" +log = "0.4" +env_logger = "0.11" +bytes = "1" +time = ">=0.3,<0.3.47" + +[[test]] +name = "loopback" +path = "tests/loopback.rs" diff --git a/deps/rustrtc-capi/src/lib.rs b/deps/rustrtc-capi/src/lib.rs new file mode 100644 index 0000000..b000fff --- /dev/null +++ b/deps/rustrtc-capi/src/lib.rs @@ -0,0 +1,753 @@ +//! rustrtc C API wrapper — drop-in replacement for libdatachannel. +//! +//! Exports the same `rtc*` C symbols so that Zig's `webrtc_native.zig` +//! links against this library with zero code changes. + +mod monitors; +mod state; +mod types; +pub mod ws_signaling; + +use std::ffi::{CStr, CString}; +use std::os::raw::{c_char, c_int, c_void}; +use std::sync::atomic::Ordering; +use std::sync::Arc; + +use rustrtc::config::RtcConfiguration as RustRtcConfig; +use rustrtc::peer_connection::PeerConnection; +use rustrtc::transports::datachannel::DataChannelConfig; +use rustrtc::transports::ice::IceCandidate; + +use crate::monitors::*; +use crate::state::*; +use crate::types::*; + +// =========================================================================== +// Global +// =========================================================================== + +#[no_mangle] +pub extern "C" fn rtcPreload() { + init_runtime(); +} + +#[no_mangle] +pub extern "C" fn rtcCleanup() { + cleanup(); +} + +#[no_mangle] +pub extern "C" fn rtcInitLogger(level: c_int, cb: Option) { + // Simple implementation: if callback provided, store it; otherwise use env_logger + let _ = level; + let _ = cb; + // For now, initialize env_logger for Rust-side logging (best effort) + let _ = env_logger::try_init(); +} + +// =========================================================================== +// User pointer +// =========================================================================== + +#[no_mangle] +pub extern "C" fn rtcSetUserPointer(id: c_int, ptr: *mut c_void) { + set_user_ptr(id, ptr); +} + +#[no_mangle] +pub extern "C" fn rtcGetUserPointer(id: c_int) -> *mut c_void { + get_user_ptr(id) +} + +// =========================================================================== +// PeerConnection +// =========================================================================== + +#[no_mangle] +pub unsafe extern "C" fn rtcCreatePeerConnection(config: *const RtcConfiguration) -> c_int { + let rt = match get_runtime() { + Some(rt) => rt, + None => return RTC_ERR_FAILURE, + }; + + let cfg = &*config; + let mut rust_config = RustRtcConfig::default(); + + // Map ICE servers + if !cfg.ice_servers.is_null() && cfg.ice_servers_count > 0 { + let count = cfg.ice_servers_count as usize; + for i in 0..count { + let server_ptr = *cfg.ice_servers.add(i); + if !server_ptr.is_null() { + if let Ok(s) = CStr::from_ptr(server_ptr).to_str() { + let ice_server = rustrtc::config::IceServer::new(vec![s.to_string()]); + rust_config.ice_servers.push(ice_server); + } + } + } + } + + // Map port range + if cfg.port_range_begin > 0 && cfg.port_range_end > 0 { + rust_config.rtp_start_port = Some(cfg.port_range_begin); + rust_config.rtp_end_port = Some(cfg.port_range_end); + } + + // Enter runtime context — PeerConnection::new() needs a tokio reactor + let _guard = rt.enter(); + let pc = Arc::new(PeerConnection::new(rust_config)); + let pc_id = alloc_id(); + let disable_auto = cfg.disable_auto_negotiation; + + // Spawn PC monitoring tasks + let tasks = spawn_pc_monitors(rt, pc_id, &pc); + + let pc_state = PcState::new(pc, disable_auto); + *pc_state.tasks.lock() = tasks; + + entries().write().insert(pc_id, Entry::Pc(pc_state)); + pc_id +} + +#[no_mangle] +pub extern "C" fn rtcClosePeerConnection(pc: c_int) -> c_int { + match with_pc(pc, |pc_state| { + pc_state.pc.close(); + }) { + Some(_) => RTC_ERR_SUCCESS, + None => RTC_ERR_INVALID, + } +} + +#[no_mangle] +pub extern "C" fn rtcDeletePeerConnection(pc: c_int) -> c_int { + let entry = entries().write().remove(&pc); + match entry { + Some(Entry::Pc(pc_state)) => { + // Abort all monitor tasks + for t in pc_state.tasks.lock().drain(..) { + t.abort(); + } + pc_state.pc.close(); + RTC_ERR_SUCCESS + } + Some(other) => { + // Put it back — wrong type + entries().write().insert(pc, other); + RTC_ERR_INVALID + } + None => RTC_ERR_INVALID, + } +} + +// =========================================================================== +// Callback setters (PeerConnection) +// =========================================================================== + +#[no_mangle] +pub extern "C" fn rtcSetLocalDescriptionCallback( + pc: c_int, + cb: Option, +) -> c_int { + match with_pc(pc, |s| *s.on_local_description.lock() = cb) { + Some(_) => RTC_ERR_SUCCESS, + None => RTC_ERR_INVALID, + } +} + +#[no_mangle] +pub extern "C" fn rtcSetLocalCandidateCallback( + pc: c_int, + cb: Option, +) -> c_int { + match with_pc(pc, |s| *s.on_local_candidate.lock() = cb) { + Some(_) => RTC_ERR_SUCCESS, + None => RTC_ERR_INVALID, + } +} + +#[no_mangle] +pub extern "C" fn rtcSetStateChangeCallback( + pc: c_int, + cb: Option, +) -> c_int { + match with_pc(pc, |s| *s.on_state_change.lock() = cb) { + Some(_) => RTC_ERR_SUCCESS, + None => RTC_ERR_INVALID, + } +} + +#[no_mangle] +pub extern "C" fn rtcSetGatheringStateChangeCallback( + pc: c_int, + cb: Option, +) -> c_int { + match with_pc(pc, |s| *s.on_gathering_state.lock() = cb) { + Some(_) => RTC_ERR_SUCCESS, + None => RTC_ERR_INVALID, + } +} + +#[no_mangle] +pub extern "C" fn rtcSetDataChannelCallback( + pc: c_int, + cb: Option, +) -> c_int { + match with_pc(pc, |s| *s.on_data_channel.lock() = cb) { + Some(_) => RTC_ERR_SUCCESS, + None => RTC_ERR_INVALID, + } +} + +// =========================================================================== +// SDP +// =========================================================================== + +#[no_mangle] +pub unsafe extern "C" fn rtcSetLocalDescription( + pc: c_int, + sdp_type: *const c_char, +) -> c_int { + let (pc_arc, _disable_auto) = match with_pc(pc, |s| (s.pc.clone(), s.disable_auto_negotiation)) + { + Some(v) => v, + None => return RTC_ERR_INVALID, + }; + + let is_answer = if sdp_type.is_null() { + false + } else { + let type_str = CStr::from_ptr(sdp_type).to_str().unwrap_or(""); + type_str == "answer" + }; + + if is_answer { + // Generate answer (assumes remote offer already set) + let pc_clone = pc_arc.clone(); + let rt = match get_runtime() { + Some(rt) => rt, + None => return RTC_ERR_FAILURE, + }; + let handle = rt.spawn(async move { + match pc_clone.create_answer().await { + Ok(answer) => { + let sdp_string = crate::monitors::inject_max_message_size(&answer.to_sdp_string()); + if let Err(e) = pc_clone.set_local_description(answer) { + log::error!("set_local_description (answer) failed: {e}"); + return; + } + let sdp_c = match CString::new(sdp_string) { + Ok(c) => c, + Err(_) => return, + }; + let type_c = CString::new("answer").unwrap(); + with_pc(pc, |s| { + *s.local_sdp.lock() = Some(sdp_c.clone()); + *s.local_sdp_type.lock() = Some(type_c.clone()); + }); + if let Some((Some(cb), ptr)) = get_pc_description_cb(pc) { + cb(pc, sdp_c.as_ptr(), type_c.as_ptr(), ptr); + } + } + Err(e) => log::error!("create_answer failed: {e}"), + } + }); + with_pc(pc, |s| s.tasks.lock().push(handle)); + } else { + // Generate offer + trigger_offer(pc, pc_arc); + } + + RTC_ERR_SUCCESS +} + +#[no_mangle] +pub unsafe extern "C" fn rtcSetRemoteDescription( + pc: c_int, + sdp: *const c_char, + sdp_type: *const c_char, +) -> c_int { + if sdp.is_null() { + return RTC_ERR_INVALID; + } + + let sdp_str = match CStr::from_ptr(sdp).to_str() { + Ok(s) => s.to_string(), + Err(_) => return RTC_ERR_INVALID, + }; + + let type_str = if sdp_type.is_null() { + "offer".to_string() + } else { + CStr::from_ptr(sdp_type) + .to_str() + .unwrap_or("offer") + .to_string() + }; + + let pc_arc = match with_pc(pc, |s| s.pc.clone()) { + Some(v) => v, + None => return RTC_ERR_INVALID, + }; + + let is_offer = type_str == "offer"; + + if is_offer { + // Trigger auto-answer: parse remote offer → set remote desc → create answer → fire callback + trigger_answer(pc, pc_arc, sdp_str); + } else { + // It's an answer — just set the remote description + let rt = match get_runtime() { + Some(rt) => rt, + None => return RTC_ERR_FAILURE, + }; + let handle = rt.spawn(async move { + let desc = match rustrtc::sdp::SessionDescription::parse( + rustrtc::sdp::SdpType::Answer, + &sdp_str, + ) { + Ok(d) => d, + Err(e) => { + log::error!("parse answer SDP failed: {e}"); + return; + } + }; + if let Err(e) = pc_arc.set_remote_description(desc).await { + log::error!("set_remote_description (answer) failed: {e}"); + } + + // Cache remote SDP + if let Ok(remote_c) = CString::new(sdp_str) { + with_pc(pc, |s| { + *s.remote_sdp.lock() = Some(remote_c); + }); + } + }); + with_pc(pc, |s| s.tasks.lock().push(handle)); + } + + RTC_ERR_SUCCESS +} + +#[no_mangle] +pub unsafe extern "C" fn rtcAddRemoteCandidate( + pc: c_int, + cand: *const c_char, + mid: *const c_char, +) -> c_int { + let _ = mid; // mid is typically ignored for data-channel-only connections + + if cand.is_null() { + return RTC_ERR_INVALID; + } + + let cand_str = match CStr::from_ptr(cand).to_str() { + Ok(s) => s, + Err(_) => return RTC_ERR_INVALID, + }; + + let pc_arc = match with_pc(pc, |s| s.pc.clone()) { + Some(v) => v, + None => return RTC_ERR_INVALID, + }; + + match IceCandidate::from_sdp(cand_str) { + Ok(candidate) => match pc_arc.add_ice_candidate(candidate) { + Ok(_) => RTC_ERR_SUCCESS, + Err(e) => { + log::error!("add_ice_candidate failed: {e}"); + RTC_ERR_FAILURE + } + }, + Err(e) => { + log::error!("parse ICE candidate failed: {e}"); + RTC_ERR_FAILURE + } + } +} + +#[no_mangle] +pub unsafe extern "C" fn rtcGetLocalDescription( + pc: c_int, + buffer: *mut u8, + size: c_int, +) -> c_int { + if buffer.is_null() || size <= 0 { + return RTC_ERR_INVALID; + } + + match with_pc(pc, |s| s.local_sdp.lock().clone()) { + Some(Some(sdp)) => { + let bytes = sdp.as_bytes_with_nul(); + let len = bytes.len(); + if (size as usize) < len { + return RTC_ERR_TOO_SMALL; + } + std::ptr::copy_nonoverlapping(bytes.as_ptr(), buffer, len); + len as c_int + } + Some(None) => RTC_ERR_NOT_AVAIL, + None => RTC_ERR_INVALID, + } +} + +#[no_mangle] +pub unsafe extern "C" fn rtcGetRemoteDescription( + pc: c_int, + buffer: *mut u8, + size: c_int, +) -> c_int { + if buffer.is_null() || size <= 0 { + return RTC_ERR_INVALID; + } + + match with_pc(pc, |s| s.remote_sdp.lock().clone()) { + Some(Some(sdp)) => { + let bytes = sdp.as_bytes_with_nul(); + let len = bytes.len(); + if (size as usize) < len { + return RTC_ERR_TOO_SMALL; + } + std::ptr::copy_nonoverlapping(bytes.as_ptr(), buffer, len); + len as c_int + } + Some(None) => RTC_ERR_NOT_AVAIL, + None => RTC_ERR_INVALID, + } +} + +// =========================================================================== +// DataChannel +// =========================================================================== + +#[no_mangle] +pub unsafe extern "C" fn rtcCreateDataChannel( + pc: c_int, + label: *const c_char, +) -> c_int { + // Create with default DataChannelInit + let default_init = RtcDataChannelInit { + reliability: RtcReliability { + unordered: false, + unreliable: false, + max_packet_life_time: 0, + max_retransmits: 0, + }, + protocol: std::ptr::null(), + negotiated: false, + manual_stream: false, + stream: 0, + }; + rtcCreateDataChannelEx(pc, label, &default_init) +} + +#[no_mangle] +pub unsafe extern "C" fn rtcCreateDataChannelEx( + pc: c_int, + label: *const c_char, + init: *const RtcDataChannelInit, +) -> c_int { + if label.is_null() || init.is_null() { + return RTC_ERR_INVALID; + } + + let label_str = match CStr::from_ptr(label).to_str() { + Ok(s) => s.to_string(), + Err(_) => return RTC_ERR_INVALID, + }; + + let init_ref = &*init; + + let protocol = if init_ref.protocol.is_null() { + String::new() + } else { + CStr::from_ptr(init_ref.protocol) + .to_str() + .unwrap_or("") + .to_string() + }; + + let (pc_arc, disable_auto) = match with_pc(pc, |s| (s.pc.clone(), s.disable_auto_negotiation)) + { + Some(v) => v, + None => return RTC_ERR_INVALID, + }; + + let dc_config = DataChannelConfig { + label: label_str, + protocol, + ordered: !init_ref.reliability.unordered, + max_retransmits: if init_ref.reliability.unreliable && init_ref.reliability.max_retransmits > 0 + { + Some(init_ref.reliability.max_retransmits as u16) + } else { + None + }, + max_packet_life_time: if init_ref.reliability.unreliable + && init_ref.reliability.max_packet_life_time > 0 + { + Some(init_ref.reliability.max_packet_life_time as u16) + } else { + None + }, + max_payload_size: None, + negotiated: if init_ref.negotiated { + Some(init_ref.stream) + } else { + None + }, + }; + + // Enter runtime context for create_data_channel + let rt = match get_runtime() { + Some(rt) => rt, + None => return RTC_ERR_FAILURE, + }; + let _guard = rt.enter(); + + let label_for_create = dc_config.label.clone(); + let dc = match pc_arc.create_data_channel(&label_for_create, Some(dc_config)) { + Ok(dc) => dc, + Err(e) => { + log::error!("create_data_channel failed: {e}"); + return RTC_ERR_FAILURE; + } + }; + + let dc_id = alloc_id(); + let channel_id = dc.id; + + // Spawn DC event monitor + let handle = spawn_dc_monitor(dc_id, dc); + + let dc_state = DcState::new(pc, pc_arc.clone(), channel_id); + *dc_state.task.lock() = Some(handle); + + entries().write().insert(dc_id, Entry::Dc(dc_state)); + + // Trigger auto-negotiation (offer generation) if enabled + if !disable_auto { + trigger_offer(pc, pc_arc); + } + + dc_id +} + +#[no_mangle] +pub extern "C" fn rtcDeleteDataChannel(dc: c_int) -> c_int { + let entry = entries().write().remove(&dc); + match entry { + Some(Entry::Dc(dc_state)) => { + if let Some(t) = dc_state.task.lock().take() { + t.abort(); + } + RTC_ERR_SUCCESS + } + Some(other) => { + entries().write().insert(dc, other); + RTC_ERR_INVALID + } + None => RTC_ERR_INVALID, + } +} + +// =========================================================================== +// Callback setters (DataChannel / common) +// =========================================================================== + +#[no_mangle] +pub extern "C" fn rtcSetOpenCallback(id: c_int, cb: Option) -> c_int { + match with_dc(id, |s| *s.on_open.lock() = cb) { + Some(_) => RTC_ERR_SUCCESS, + None => RTC_ERR_INVALID, + } +} + +#[no_mangle] +pub extern "C" fn rtcSetClosedCallback(id: c_int, cb: Option) -> c_int { + match with_dc(id, |s| *s.on_closed.lock() = cb) { + Some(_) => RTC_ERR_SUCCESS, + None => RTC_ERR_INVALID, + } +} + +#[no_mangle] +pub extern "C" fn rtcSetErrorCallback(id: c_int, cb: Option) -> c_int { + match with_dc(id, |s| *s.on_error.lock() = cb) { + Some(_) => RTC_ERR_SUCCESS, + None => RTC_ERR_INVALID, + } +} + +#[no_mangle] +pub extern "C" fn rtcSetMessageCallback(id: c_int, cb: Option) -> c_int { + match with_dc(id, |s| *s.on_message.lock() = cb) { + Some(_) => RTC_ERR_SUCCESS, + None => RTC_ERR_INVALID, + } +} + +// =========================================================================== +// I/O +// =========================================================================== + +#[no_mangle] +pub unsafe extern "C" fn rtcSendMessage( + id: c_int, + data: *const u8, + size: c_int, +) -> c_int { + let bytes = if size < 0 { + // Treat as null-terminated string + let cstr = CStr::from_ptr(data as *const c_char); + cstr.to_bytes().to_vec() + } else { + std::slice::from_raw_parts(data, size as usize).to_vec() + }; + + let (pc_arc, channel_id) = match with_dc(id, |dc| (dc.pc.clone(), dc.channel_id)) { + Some(v) => v, + None => return RTC_ERR_INVALID, + }; + + // Blocking send — preserves message ordering (caller is always on a non-tokio thread) + let rt = match get_runtime() { + Some(rt) => rt, + None => return RTC_ERR_FAILURE, + }; + + match rt.block_on(pc_arc.send_data(channel_id, &bytes)) { + Ok(_) => RTC_ERR_SUCCESS, + Err(e) => { + log::error!("send_data failed: {e}"); + RTC_ERR_FAILURE + } + } +} + +#[no_mangle] +pub extern "C" fn rtcClose(id: c_int) -> c_int { + // Try as DC first + if let Some(_) = with_dc(id, |dc| { + dc.is_open.store(false, Ordering::Release); + // Close the underlying PC data channel + let pc = dc.pc.clone(); + let channel_id = dc.channel_id; + if let Some(rt) = get_runtime() { + rt.spawn(async move { + // There's no explicit DC close in rustrtc; closing is done at PC level + let _ = (pc, channel_id); + }); + } + }) { + return RTC_ERR_SUCCESS; + } + + // Try as PC + if let Some(_) = with_pc(id, |pc| { + pc.pc.close(); + }) { + return RTC_ERR_SUCCESS; + } + + RTC_ERR_INVALID +} + +#[no_mangle] +pub extern "C" fn rtcDelete(id: c_int) -> c_int { + let entry = entries().write().remove(&id); + match entry { + Some(Entry::Dc(dc_state)) => { + if let Some(t) = dc_state.task.lock().take() { + t.abort(); + } + RTC_ERR_SUCCESS + } + Some(Entry::Pc(pc_state)) => { + for t in pc_state.tasks.lock().drain(..) { + t.abort(); + } + pc_state.pc.close(); + RTC_ERR_SUCCESS + } + None => RTC_ERR_INVALID, + } +} + +#[no_mangle] +pub extern "C" fn rtcIsOpen(id: c_int) -> bool { + with_dc(id, |dc| dc.is_open.load(Ordering::Acquire)).unwrap_or(false) +} + +#[no_mangle] +pub extern "C" fn rtcIsClosed(id: c_int) -> bool { + with_dc(id, |dc| dc.is_closed.load(Ordering::Acquire)).unwrap_or(true) +} + +#[no_mangle] +pub extern "C" fn rtcGetBufferedAmount(id: c_int) -> c_int { + let pc_arc = match with_dc(id, |dc| dc.pc.clone()) { + Some(v) => v, + None => return RTC_ERR_INVALID, + }; + + let rt = match get_runtime() { + Some(rt) => rt, + None => return RTC_ERR_FAILURE, + }; + + // block_on is safe here because we're called from non-tokio threads + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + rt.block_on(pc_arc.sctp_buffered_amount()) as c_int + })) { + Ok(amount) => amount, + Err(_) => { + // If block_on panics (called from tokio context), try spawn + channel + let pc_clone = pc_arc.clone(); + let (tx, rx) = std::sync::mpsc::channel(); + rt.spawn(async move { + let amount = pc_clone.sctp_buffered_amount().await; + let _ = tx.send(amount as c_int); + }); + rx.recv().unwrap_or(0) + } + } +} + +#[no_mangle] +pub unsafe extern "C" fn rtcReceiveMessage( + id: c_int, + buffer: *mut u8, + size: *mut c_int, +) -> c_int { + if buffer.is_null() || size.is_null() { + return RTC_ERR_INVALID; + } + + match with_dc(id, |dc| { + let mut buf = dc.recv_buffer.lock(); + buf.pop_front() + }) { + Some(Some(data)) => { + let available = *size as usize; + if data.len() > available { + *size = data.len() as c_int; + return RTC_ERR_TOO_SMALL; + } + std::ptr::copy_nonoverlapping(data.as_ptr(), buffer, data.len()); + *size = data.len() as c_int; + RTC_ERR_SUCCESS + } + Some(None) => RTC_ERR_NOT_AVAIL, + None => RTC_ERR_INVALID, + } +} + +// =========================================================================== +// SCTP settings (no-op — rustrtc has its own SCTP stack) +// =========================================================================== + +#[no_mangle] +pub unsafe extern "C" fn rtcSetSctpSettings(_settings: *const RtcSctpSettings) -> c_int { + RTC_ERR_SUCCESS +} diff --git a/deps/rustrtc-capi/src/monitors.rs b/deps/rustrtc-capi/src/monitors.rs new file mode 100644 index 0000000..6df4b42 --- /dev/null +++ b/deps/rustrtc-capi/src/monitors.rs @@ -0,0 +1,338 @@ +//! Async tasks that bridge rustrtc events → C callbacks. +//! +//! For each PeerConnection, we spawn monitor tasks for: +//! - ICE candidates (broadcast receiver) +//! - Peer connection state (watch receiver) +//! - ICE gathering state (watch receiver) +//! - Incoming DataChannels (pc.recv()) +//! +//! For each DataChannel, we spawn one monitor task that handles +//! Open / Message / Close events. + +use std::ffi::CString; +use std::sync::Arc; + +use rustrtc::peer_connection::{ + IceGatheringState, PeerConnection, PeerConnectionEvent, PeerConnectionState, +}; +use rustrtc::transports::datachannel::{DataChannel, DataChannelEvent}; +use tokio::task::JoinHandle; + +use crate::state::*; +use crate::types::*; + +// --------------------------------------------------------------------------- +// PeerConnection monitors +// --------------------------------------------------------------------------- + +/// Spawn all monitoring tasks for a PeerConnection. Returns task handles. +pub fn spawn_pc_monitors( + rt: &tokio::runtime::Runtime, + pc_id: i32, + pc: &Arc, +) -> Vec> { + let mut tasks = Vec::with_capacity(4); + + // 1. ICE candidate monitor (broadcast::Receiver) + let mut cand_rx = pc.subscribe_ice_candidates(); + let pc_id1 = pc_id; + tasks.push(rt.spawn(async move { + loop { + match cand_rx.recv().await { + Ok(candidate) => { + let cand_str = candidate.to_sdp(); + let cand_c = match CString::new(cand_str) { + Ok(c) => c, + Err(_) => continue, + }; + let mid_c = CString::new("0").unwrap(); + if let Some((Some(cb), ptr)) = get_pc_candidate_cb(pc_id1) { + unsafe { cb(pc_id1, cand_c.as_ptr(), mid_c.as_ptr(), ptr) }; + } + } + Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue, + Err(tokio::sync::broadcast::error::RecvError::Closed) => break, + } + } + })); + + // 2. Peer connection state monitor (watch::Receiver) + let mut state_rx = pc.subscribe_peer_state(); + let pc_id2 = pc_id; + tasks.push(rt.spawn(async move { + while state_rx.changed().await.is_ok() { + let state = *state_rx.borrow_and_update(); + let c_state = map_peer_state(state); + if let Some((Some(cb), ptr)) = get_pc_state_change_cb(pc_id2) { + unsafe { cb(pc_id2, c_state, ptr) }; + } + } + })); + + // 3. ICE gathering state monitor (watch::Receiver) + let mut gather_rx = pc.subscribe_ice_gathering_state(); + let pc_id3 = pc_id; + tasks.push(rt.spawn(async move { + while gather_rx.changed().await.is_ok() { + let state = *gather_rx.borrow_and_update(); + let c_state = map_gathering_state(state); + if let Some((Some(cb), ptr)) = get_pc_gathering_state_cb(pc_id3) { + unsafe { cb(pc_id3, c_state, ptr) }; + } + } + })); + + // 4. Incoming DataChannel monitor (pc.recv()) + let pc_clone = pc.clone(); + let pc_id4 = pc_id; + tasks.push(rt.spawn(async move { + while let Some(event) = pc_clone.recv().await { + match event { + PeerConnectionEvent::DataChannel(dc) => { + handle_incoming_data_channel(pc_id4, &pc_clone, dc).await; + } + _ => {} // Ignore Track events for data-channel-only usage + } + } + })); + + tasks +} + +/// Handle an incoming DataChannel: register it, fire callback, then spawn monitor. +async fn handle_incoming_data_channel( + pc_id: i32, + pc: &Arc, + dc: Arc, +) { + let dc_id = alloc_id(); + let channel_id = dc.id; + let dc_state = DcState::new(pc_id, pc.clone(), channel_id); + + // Insert into global registry + { + let mut map = entries().write(); + map.insert(dc_id, Entry::Dc(dc_state)); + } + + // Fire DataChannel callback (synchronously — user sets DC callbacks inside) + if let Some((Some(cb), ptr)) = get_pc_data_channel_cb(pc_id) { + // Copy the PC's user pointer to the DC entry + let pc_ptr = get_user_ptr(pc_id); + set_user_ptr(dc_id, pc_ptr); + unsafe { cb(pc_id, dc_id, ptr) }; + } + + // Now spawn DC monitor (callbacks are set by this point) + let handle = spawn_dc_monitor(dc_id, dc); + with_dc(dc_id, |dc_state| { + *dc_state.task.lock() = Some(handle); + }); +} + +// --------------------------------------------------------------------------- +// DataChannel monitor +// --------------------------------------------------------------------------- + +/// Spawn a monitor task for a DataChannel. Fires open/message/close callbacks. +pub fn spawn_dc_monitor(dc_id: i32, dc: Arc) -> JoinHandle<()> { + let rt = get_runtime().expect("runtime not initialized"); + rt.spawn(async move { + while let Some(event) = dc.recv().await { + match event { + DataChannelEvent::Open => { + // Mark as open + with_dc(dc_id, |dc_state| { + dc_state.is_open.store(true, std::sync::atomic::Ordering::Release); + dc_state.is_closed.store(false, std::sync::atomic::Ordering::Release); + }); + if let Some((Some(cb), ptr)) = get_dc_open_cb(dc_id) { + unsafe { cb(dc_id, ptr) }; + } + } + DataChannelEvent::Message(data) => { + let bytes = data.to_vec(); + let len = bytes.len(); + + // Push to recv_buffer (for rtcReceiveMessage) + with_dc(dc_id, |dc_state| { + let mut buf = dc_state.recv_buffer.lock(); + if buf.len() < 65536 { + buf.push_back(bytes.clone()); + } + }); + + // Fire message callback + if let Some((Some(cb), ptr)) = get_dc_message_cb(dc_id) { + unsafe { cb(dc_id, bytes.as_ptr(), len as i32, ptr) }; + } + } + DataChannelEvent::Close => { + with_dc(dc_id, |dc_state| { + dc_state.is_open.store(false, std::sync::atomic::Ordering::Release); + dc_state.is_closed.store(true, std::sync::atomic::Ordering::Release); + }); + if let Some((Some(cb), ptr)) = get_dc_closed_cb(dc_id) { + unsafe { cb(dc_id, ptr) }; + } + break; + } + } + } + }) +} + +// --------------------------------------------------------------------------- +// SDP generation helpers (spawned as async tasks) +// --------------------------------------------------------------------------- + +/// Inject `a=max-message-size:1048576` into an SDP string if not already present. +/// Per RFC 8841 §4.3, absence of this attribute makes the remote peer assume a +/// default of 65536 bytes, which is too small for efficient file transfers. +pub fn inject_max_message_size(sdp: &str) -> String { + if sdp.contains("a=max-message-size") { + return sdp.to_string(); + } + // Insert after `a=sctp-port` line (within the m= section) + if let Some(pos) = sdp.find("a=sctp-port") { + if let Some(eol) = sdp[pos..].find("\r\n") { + let insert_at = pos + eol + 2; + let mut result = String::with_capacity(sdp.len() + 30); + result.push_str(&sdp[..insert_at]); + result.push_str("a=max-message-size:1048576\r\n"); + result.push_str(&sdp[insert_at..]); + return result; + } + } + sdp.to_string() +} + +/// Trigger offer generation: create offer → set local description → fire callback. +/// Called after rtcCreateDataChannelEx when auto-negotiation is enabled. +pub fn trigger_offer(pc_id: i32, pc: Arc) { + let rt = get_runtime().expect("runtime not initialized"); + let handle = rt.spawn(async move { + match pc.create_offer().await { + Ok(offer) => { + let sdp_string = inject_max_message_size(&offer.to_sdp_string()); + if let Err(e) = pc.set_local_description(offer) { + log::error!("set_local_description failed: {e}"); + return; + } + + let sdp_c = match CString::new(sdp_string.clone()) { + Ok(c) => c, + Err(_) => return, + }; + let type_c = CString::new("offer").unwrap(); + + // Cache SDP + with_pc(pc_id, |pc_state| { + *pc_state.local_sdp.lock() = Some(sdp_c.clone()); + *pc_state.local_sdp_type.lock() = Some(type_c.clone()); + }); + + // Fire description callback + if let Some((Some(cb), ptr)) = get_pc_description_cb(pc_id) { + unsafe { cb(pc_id, sdp_c.as_ptr(), type_c.as_ptr(), ptr) }; + } + } + Err(e) => { + log::error!("create_offer failed: {e}"); + } + } + }); + + // Store task handle + with_pc(pc_id, |pc_state| { + pc_state.tasks.lock().push(handle); + }); +} + +/// Trigger answer generation after receiving a remote offer. +pub fn trigger_answer(pc_id: i32, pc: Arc, remote_sdp: String) { + let rt = get_runtime().expect("runtime not initialized"); + let handle = rt.spawn(async move { + // Parse and set remote description + let desc = match rustrtc::sdp::SessionDescription::parse( + rustrtc::sdp::SdpType::Offer, + &remote_sdp, + ) { + Ok(d) => d, + Err(e) => { + log::error!("parse remote SDP failed: {e}"); + return; + } + }; + + if let Err(e) = pc.set_remote_description(desc).await { + log::error!("set_remote_description failed: {e}"); + return; + } + + // Cache remote SDP + if let Ok(remote_c) = CString::new(remote_sdp) { + with_pc(pc_id, |pc_state| { + *pc_state.remote_sdp.lock() = Some(remote_c); + }); + } + + // Create answer + match pc.create_answer().await { + Ok(answer) => { + let sdp_string = inject_max_message_size(&answer.to_sdp_string()); + if let Err(e) = pc.set_local_description(answer) { + log::error!("set_local_description (answer) failed: {e}"); + return; + } + + let sdp_c = match CString::new(sdp_string) { + Ok(c) => c, + Err(_) => return, + }; + let type_c = CString::new("answer").unwrap(); + + // Cache answer SDP + with_pc(pc_id, |pc_state| { + *pc_state.local_sdp.lock() = Some(sdp_c.clone()); + *pc_state.local_sdp_type.lock() = Some(type_c.clone()); + }); + + // Fire description callback + if let Some((Some(cb), ptr)) = get_pc_description_cb(pc_id) { + unsafe { cb(pc_id, sdp_c.as_ptr(), type_c.as_ptr(), ptr) }; + } + } + Err(e) => { + log::error!("create_answer failed: {e}"); + } + } + }); + + with_pc(pc_id, |pc_state| { + pc_state.tasks.lock().push(handle); + }); +} + +// --------------------------------------------------------------------------- +// State mapping helpers +// --------------------------------------------------------------------------- + +fn map_peer_state(state: PeerConnectionState) -> i32 { + match state { + PeerConnectionState::New => RTC_STATE_NEW, + PeerConnectionState::Connecting => RTC_STATE_CONNECTING, + PeerConnectionState::Connected => RTC_STATE_CONNECTED, + PeerConnectionState::Disconnected => RTC_STATE_DISCONNECTED, + PeerConnectionState::Failed => RTC_STATE_FAILED, + PeerConnectionState::Closed => RTC_STATE_CLOSED, + } +} + +fn map_gathering_state(state: IceGatheringState) -> i32 { + match state { + IceGatheringState::New => RTC_GATHERING_NEW, + IceGatheringState::Gathering => RTC_GATHERING_IN_PROGRESS, + IceGatheringState::Complete => RTC_GATHERING_COMPLETE, + } +} diff --git a/deps/rustrtc-capi/src/state.rs b/deps/rustrtc-capi/src/state.rs new file mode 100644 index 0000000..9c027a0 --- /dev/null +++ b/deps/rustrtc-capi/src/state.rs @@ -0,0 +1,254 @@ +//! Global ID registry, PcState, DcState. + +use std::collections::{HashMap, VecDeque}; +use std::ffi::CString; +use std::os::raw::c_void; +use std::sync::atomic::{AtomicBool, AtomicI32, AtomicPtr, Ordering}; +use std::sync::{Arc, OnceLock}; + +use parking_lot::{Mutex, RwLock}; +use tokio::runtime::Runtime; +use tokio::task::JoinHandle; + +use rustrtc::peer_connection::PeerConnection; + + +use crate::types::*; + +// --------------------------------------------------------------------------- +// Global statics +// --------------------------------------------------------------------------- + +static RUNTIME: OnceLock = OnceLock::new(); +static ENTRIES: OnceLock>> = OnceLock::new(); +static NEXT_ID: AtomicI32 = AtomicI32::new(1); + +pub fn init_runtime() { + RUNTIME.get_or_init(|| { + tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .expect("failed to create tokio runtime") + }); + ENTRIES.get_or_init(|| RwLock::new(HashMap::new())); +} + +pub fn get_runtime() -> Option<&'static Runtime> { + RUNTIME.get() +} + +pub fn cleanup() { + if let Some(entries) = ENTRIES.get() { + let mut map = entries.write(); + // Abort all tasks + for (_, entry) in map.drain() { + match entry { + Entry::Pc(pc) => { + let tasks = pc.tasks.lock(); + for t in tasks.iter() { + t.abort(); + } + } + Entry::Dc(dc) => { + if let Some(t) = dc.task.lock().take() { + t.abort(); + } + } + } + } + } + // Note: We don't drop the runtime here because OnceLock doesn't support reset. + // The runtime will be cleaned up on process exit. +} + +pub fn alloc_id() -> i32 { + NEXT_ID.fetch_add(1, Ordering::Relaxed) +} + +pub fn entries() -> &'static RwLock> { + ENTRIES.get().expect("runtime not initialized") +} + +// --------------------------------------------------------------------------- +// Entry types +// --------------------------------------------------------------------------- + +pub enum Entry { + Pc(PcState), + Dc(DcState), +} + +pub struct PcState { + pub pc: Arc, + pub user_ptr: AtomicPtr, + pub disable_auto_negotiation: bool, + + // Callback slots + pub on_local_description: Mutex>, + pub on_local_candidate: Mutex>, + pub on_state_change: Mutex>, + pub on_gathering_state: Mutex>, + pub on_data_channel: Mutex>, + + // Cached SDP + pub local_sdp: Mutex>, + pub local_sdp_type: Mutex>, + pub remote_sdp: Mutex>, + + // Monitor task handles + pub tasks: Mutex>>, +} + +pub struct DcState { + #[allow(dead_code)] + pub pc_id: i32, + pub pc: Arc, + pub channel_id: u16, + pub user_ptr: AtomicPtr, + + // Callback slots + pub on_open: Mutex>, + pub on_closed: Mutex>, + pub on_error: Mutex>, + pub on_message: Mutex>, + + // State flags + pub is_open: AtomicBool, + pub is_closed: AtomicBool, + + // Receive buffer (for rtcReceiveMessage polling) + pub recv_buffer: Mutex>>, + + // Monitor task handle + pub task: Mutex>>, +} + +impl PcState { + pub fn new(pc: Arc, disable_auto_negotiation: bool) -> Self { + Self { + pc, + user_ptr: AtomicPtr::new(std::ptr::null_mut()), + disable_auto_negotiation, + on_local_description: Mutex::new(None), + on_local_candidate: Mutex::new(None), + on_state_change: Mutex::new(None), + on_gathering_state: Mutex::new(None), + on_data_channel: Mutex::new(None), + local_sdp: Mutex::new(None), + local_sdp_type: Mutex::new(None), + remote_sdp: Mutex::new(None), + tasks: Mutex::new(Vec::new()), + } + } +} + +impl DcState { + pub fn new(pc_id: i32, pc: Arc, channel_id: u16) -> Self { + Self { + pc_id, + pc, + channel_id, + user_ptr: AtomicPtr::new(std::ptr::null_mut()), + on_open: Mutex::new(None), + on_closed: Mutex::new(None), + on_error: Mutex::new(None), + on_message: Mutex::new(None), + is_open: AtomicBool::new(false), + is_closed: AtomicBool::new(false), + recv_buffer: Mutex::new(VecDeque::new()), + task: Mutex::new(None), + } + } +} + +// --------------------------------------------------------------------------- +// Helper accessors +// --------------------------------------------------------------------------- + +/// Get user pointer for any entry (PC or DC). +pub fn get_user_ptr(id: i32) -> *mut c_void { + let map = entries().read(); + match map.get(&id) { + Some(Entry::Pc(pc)) => pc.user_ptr.load(Ordering::Acquire), + Some(Entry::Dc(dc)) => dc.user_ptr.load(Ordering::Acquire), + None => std::ptr::null_mut(), + } +} + +/// Set user pointer for any entry. +pub fn set_user_ptr(id: i32, ptr: *mut c_void) { + let map = entries().read(); + match map.get(&id) { + Some(Entry::Pc(pc)) => pc.user_ptr.store(ptr, Ordering::Release), + Some(Entry::Dc(dc)) => dc.user_ptr.store(ptr, Ordering::Release), + None => {} + } +} + +/// Execute a closure with read access to a PcState. +pub fn with_pc(id: i32, f: F) -> Option +where + F: FnOnce(&PcState) -> R, +{ + let map = entries().read(); + match map.get(&id) { + Some(Entry::Pc(pc)) => Some(f(pc)), + _ => None, + } +} + +/// Execute a closure with read access to a DcState. +pub fn with_dc(id: i32, f: F) -> Option +where + F: FnOnce(&DcState) -> R, +{ + let map = entries().read(); + match map.get(&id) { + Some(Entry::Dc(dc)) => Some(f(dc)), + _ => None, + } +} + +/// Get the PC Arc and user_ptr for a given PC id. +#[allow(dead_code)] +pub fn get_pc_arc(id: i32) -> Option<(Arc, *mut c_void)> { + with_pc(id, |pc| (pc.pc.clone(), pc.user_ptr.load(Ordering::Acquire))) +} + +/// Get callback + user_ptr from a PC entry. +pub fn get_pc_description_cb(id: i32) -> Option<(Option, *mut c_void)> { + with_pc(id, |pc| (*pc.on_local_description.lock(), pc.user_ptr.load(Ordering::Acquire))) +} + +pub fn get_pc_candidate_cb(id: i32) -> Option<(Option, *mut c_void)> { + with_pc(id, |pc| (*pc.on_local_candidate.lock(), pc.user_ptr.load(Ordering::Acquire))) +} + +pub fn get_pc_state_change_cb(id: i32) -> Option<(Option, *mut c_void)> { + with_pc(id, |pc| (*pc.on_state_change.lock(), pc.user_ptr.load(Ordering::Acquire))) +} + +pub fn get_pc_gathering_state_cb(id: i32) -> Option<(Option, *mut c_void)> { + with_pc(id, |pc| (*pc.on_gathering_state.lock(), pc.user_ptr.load(Ordering::Acquire))) +} + +pub fn get_pc_data_channel_cb(id: i32) -> Option<(Option, *mut c_void)> { + with_pc(id, |pc| (*pc.on_data_channel.lock(), pc.user_ptr.load(Ordering::Acquire))) +} + +pub fn get_dc_open_cb(id: i32) -> Option<(Option, *mut c_void)> { + with_dc(id, |dc| (*dc.on_open.lock(), dc.user_ptr.load(Ordering::Acquire))) +} + +pub fn get_dc_closed_cb(id: i32) -> Option<(Option, *mut c_void)> { + with_dc(id, |dc| (*dc.on_closed.lock(), dc.user_ptr.load(Ordering::Acquire))) +} + +#[allow(dead_code)] +pub fn get_dc_error_cb(id: i32) -> Option<(Option, *mut c_void)> { + with_dc(id, |dc| (*dc.on_error.lock(), dc.user_ptr.load(Ordering::Acquire))) +} + +pub fn get_dc_message_cb(id: i32) -> Option<(Option, *mut c_void)> { + with_dc(id, |dc| (*dc.on_message.lock(), dc.user_ptr.load(Ordering::Acquire))) +} diff --git a/deps/rustrtc-capi/src/types.rs b/deps/rustrtc-capi/src/types.rs new file mode 100644 index 0000000..2379d1b --- /dev/null +++ b/deps/rustrtc-capi/src/types.rs @@ -0,0 +1,107 @@ +//! C ABI type definitions matching libdatachannel's rtc.h + +use std::os::raw::{c_char, c_int, c_uint, c_void}; + +// --------------------------------------------------------------------------- +// Error codes +// --------------------------------------------------------------------------- + +pub const RTC_ERR_SUCCESS: c_int = 0; +pub const RTC_ERR_INVALID: c_int = -1; +pub const RTC_ERR_FAILURE: c_int = -2; +pub const RTC_ERR_NOT_AVAIL: c_int = -3; +pub const RTC_ERR_TOO_SMALL: c_int = -4; + +// --------------------------------------------------------------------------- +// State enum values (as c_int, matching Zig's enum(c_int)) +// --------------------------------------------------------------------------- + +// PeerConnection / ICE state +pub const RTC_STATE_NEW: c_int = 0; +pub const RTC_STATE_CONNECTING: c_int = 1; +pub const RTC_STATE_CONNECTED: c_int = 2; +pub const RTC_STATE_DISCONNECTED: c_int = 3; +pub const RTC_STATE_FAILED: c_int = 4; +pub const RTC_STATE_CLOSED: c_int = 5; + +// ICE gathering state +pub const RTC_GATHERING_NEW: c_int = 0; +pub const RTC_GATHERING_IN_PROGRESS: c_int = 1; +pub const RTC_GATHERING_COMPLETE: c_int = 2; + +// --------------------------------------------------------------------------- +// Callback function types +// --------------------------------------------------------------------------- + +pub type DescriptionCallbackFn = + unsafe extern "C" fn(pc: c_int, sdp: *const c_char, sdp_type: *const c_char, ptr: *mut c_void); +pub type CandidateCallbackFn = + unsafe extern "C" fn(pc: c_int, cand: *const c_char, mid: *const c_char, ptr: *mut c_void); +pub type StateChangeCallbackFn = + unsafe extern "C" fn(pc: c_int, state: c_int, ptr: *mut c_void); +pub type GatheringStateCallbackFn = + unsafe extern "C" fn(pc: c_int, state: c_int, ptr: *mut c_void); +pub type DataChannelCallbackFn = + unsafe extern "C" fn(pc: c_int, dc: c_int, ptr: *mut c_void); +pub type OpenCallbackFn = unsafe extern "C" fn(id: c_int, ptr: *mut c_void); +pub type ClosedCallbackFn = unsafe extern "C" fn(id: c_int, ptr: *mut c_void); +pub type ErrorCallbackFn = + unsafe extern "C" fn(id: c_int, err_msg: *const c_char, ptr: *mut c_void); +pub type MessageCallbackFn = + unsafe extern "C" fn(id: c_int, message: *const u8, size: c_int, ptr: *mut c_void); +pub type LogCallbackFn = unsafe extern "C" fn(level: c_int, message: *const c_char); + +// --------------------------------------------------------------------------- +// #[repr(C)] structs matching Zig extern structs +// --------------------------------------------------------------------------- + +#[repr(C)] +pub struct RtcConfiguration { + pub ice_servers: *const *const c_char, + pub ice_servers_count: c_int, + pub proxy_server: *const c_char, + pub bind_address: *const c_char, + pub certificate_type: c_int, + pub ice_transport_policy: c_int, + pub enable_ice_tcp: bool, + pub enable_ice_udp_mux: bool, + pub disable_auto_negotiation: bool, + pub force_media_transport: bool, + pub port_range_begin: u16, + pub port_range_end: u16, + pub mtu: c_int, + pub max_message_size: c_int, +} + +#[repr(C)] +pub struct RtcReliability { + pub unordered: bool, + pub unreliable: bool, + pub max_packet_life_time: c_uint, + pub max_retransmits: c_uint, +} + +#[repr(C)] +pub struct RtcDataChannelInit { + pub reliability: RtcReliability, + pub protocol: *const c_char, + pub negotiated: bool, + pub manual_stream: bool, + pub stream: u16, +} + +#[repr(C)] +pub struct RtcSctpSettings { + pub recv_buffer_size: c_int, + pub send_buffer_size: c_int, + pub max_chunks_on_queue: c_int, + pub initial_congestion_window: c_int, + pub max_burst: c_int, + pub congestion_control_module: c_int, + pub delayed_sack_time_ms: c_int, + pub min_retransmit_timeout_ms: c_int, + pub max_retransmit_timeout_ms: c_int, + pub initial_retransmit_timeout_ms: c_int, + pub max_retransmit_attempts: c_int, + pub heartbeat_interval_ms: c_int, +} diff --git a/deps/rustrtc-capi/src/ws_signaling.rs b/deps/rustrtc-capi/src/ws_signaling.rs new file mode 100644 index 0000000..7b98134 --- /dev/null +++ b/deps/rustrtc-capi/src/ws_signaling.rs @@ -0,0 +1,304 @@ +//! WebSocket signaling client for SDP/ICE exchange. +//! +//! Provides 5 C-callable functions that let the Zig bridge connect to a +//! signaling server, send/receive JSON messages, and disconnect. + +use std::collections::VecDeque; +use std::os::raw::{c_char, c_int}; +use std::sync::atomic::{AtomicBool, AtomicI32, Ordering}; +use std::sync::OnceLock; + +use futures_util::{SinkExt, StreamExt}; +use parking_lot::Mutex; +use tokio::sync::mpsc; +use tokio::task::JoinHandle; +use tokio_tungstenite::tungstenite::Message; + +use crate::state; + +// ============================================================================ +// WebSocket State +// ============================================================================ + +static NEXT_WS_ID: AtomicI32 = AtomicI32::new(1); +static WS_ENTRIES: OnceLock>>> = OnceLock::new(); + +const MAX_WS_CONNECTIONS: usize = 8; +const MAX_RECV_QUEUE: usize = 256; + +struct WsState { + id: i32, + connected: AtomicBool, + /// Sender for outgoing messages (to the writer task) + tx: mpsc::UnboundedSender, + /// Received messages waiting to be polled by C caller + recv_queue: Mutex>, + /// Background reader task handle + reader_task: Mutex>>, + /// Background writer task handle + writer_task: Mutex>>, +} + +fn get_entries() -> &'static Mutex>> { + WS_ENTRIES.get_or_init(|| { + let mut v = Vec::with_capacity(MAX_WS_CONNECTIONS); + for _ in 0..MAX_WS_CONNECTIONS { + v.push(None); + } + Mutex::new(v) + }) +} + +// ============================================================================ +// C API Functions +// ============================================================================ + +/// Connect to a signaling server via WebSocket. +/// `url` and `peer_id` are null-terminated C strings. +/// Returns a ws_id > 0 on success, or negative error code. +#[no_mangle] +pub unsafe extern "C" fn rtcWsConnect(url: *const c_char, peer_id: *const c_char) -> c_int { + if url.is_null() || peer_id.is_null() { + return -1; + } + + let url_str = match std::ffi::CStr::from_ptr(url).to_str() { + Ok(s) => s.to_string(), + Err(_) => return -1, + }; + let peer_id_str = match std::ffi::CStr::from_ptr(peer_id).to_str() { + Ok(s) => s.to_string(), + Err(_) => return -1, + }; + + let rt = match state::get_runtime() { + Some(rt) => rt, + None => { + // Ensure runtime is initialized + state::init_runtime(); + match state::get_runtime() { + Some(rt) => rt, + None => return -2, + } + } + }; + + let ws_id = NEXT_WS_ID.fetch_add(1, Ordering::Relaxed); + let (tx, rx) = mpsc::unbounded_channel::(); + + // Connect in a blocking fashion so the C caller gets immediate result + let connect_result = rt.block_on(async { + tokio_tungstenite::connect_async(&url_str).await + }); + + let ws_stream = match connect_result { + Ok((stream, _response)) => stream, + Err(e) => { + log::error!("WebSocket connect failed: {}", e); + return -2; + } + }; + + let (mut write, mut read) = ws_stream.split(); + + // Send register message immediately + let register_msg = serde_json::json!({ + "type": "register", + "peerId": peer_id_str + }).to_string(); + + if let Err(e) = rt.block_on(write.send(Message::Text(register_msg))) { + log::error!("Failed to send register: {}", e); + return -2; + } + + let recv_queue = Mutex::new(VecDeque::new()); + let connected = AtomicBool::new(true); + + // Create the state entry first so tasks can reference the ID + let ws_state = WsState { + id: ws_id, + connected, + tx, + recv_queue, + reader_task: Mutex::new(None), + writer_task: Mutex::new(None), + }; + + // Store in entries + { + let mut entries = get_entries().lock(); + let slot = entries.iter().position(|e| e.is_none()); + match slot { + Some(idx) => entries[idx] = Some(ws_state), + None => return -3, // No free slots + } + } + + // Spawn reader task + let reader_ws_id = ws_id; + let reader_handle = rt.spawn(async move { + while let Some(msg_result) = read.next().await { + match msg_result { + Ok(Message::Text(text)) => { + let entries = get_entries().lock(); + if let Some(slot) = entries.iter().find(|e| { + e.as_ref().map_or(false, |ws| ws.id == reader_ws_id) + }) { + if let Some(ws) = slot.as_ref() { + let mut queue = ws.recv_queue.lock(); + if queue.len() < MAX_RECV_QUEUE { + queue.push_back(text); + } + } + } + } + Ok(Message::Close(_)) => break, + Ok(_) => {} // Ignore binary/ping/pong + Err(e) => { + log::warn!("WebSocket read error: {}", e); + break; + } + } + } + // Mark as disconnected + let entries = get_entries().lock(); + if let Some(slot) = entries.iter().find(|e| { + e.as_ref().map_or(false, |ws| ws.id == reader_ws_id) + }) { + if let Some(ws) = slot.as_ref() { + ws.connected.store(false, Ordering::Release); + } + } + }); + + // Spawn writer task + let mut writer_rx = rx; + let writer_handle = rt.spawn(async move { + while let Some(msg) = writer_rx.recv().await { + if write.send(Message::Text(msg)).await.is_err() { + break; + } + } + }); + + // Store task handles + { + let entries = get_entries().lock(); + if let Some(slot) = entries.iter().find(|e| { + e.as_ref().map_or(false, |ws| ws.id == ws_id) + }) { + if let Some(ws) = slot.as_ref() { + *ws.reader_task.lock() = Some(reader_handle); + *ws.writer_task.lock() = Some(writer_handle); + } + } + } + + ws_id +} + +/// Disconnect a WebSocket connection. +/// Returns 0 on success, negative on error. +#[no_mangle] +pub extern "C" fn rtcWsDisconnect(ws_id: c_int) -> c_int { + let mut entries = get_entries().lock(); + if let Some(idx) = entries.iter().position(|e| { + e.as_ref().map_or(false, |ws| ws.id == ws_id) + }) { + if let Some(ws) = entries[idx].take() { + ws.connected.store(false, Ordering::Release); + // Abort tasks + if let Some(h) = ws.reader_task.lock().take() { + h.abort(); + } + if let Some(h) = ws.writer_task.lock().take() { + h.abort(); + } + } + return 0; + } + -1 +} + +/// Send a message on a WebSocket connection. +/// `message` points to a buffer of `size` bytes (not null-terminated). +/// Returns 0 on success, negative on error. +#[no_mangle] +pub unsafe extern "C" fn rtcWsSend(ws_id: c_int, message: *const c_char, size: c_int) -> c_int { + if message.is_null() || size <= 0 { + return -1; + } + + let bytes = std::slice::from_raw_parts(message as *const u8, size as usize); + let text = match std::str::from_utf8(bytes) { + Ok(s) => s.to_string(), + Err(_) => return -1, + }; + + let entries = get_entries().lock(); + if let Some(slot) = entries.iter().find(|e| { + e.as_ref().map_or(false, |ws| ws.id == ws_id) + }) { + if let Some(ws) = slot.as_ref() { + if !ws.connected.load(Ordering::Acquire) { + return -2; + } + match ws.tx.send(text) { + Ok(_) => return 0, + Err(_) => return -2, + } + } + } + -1 +} + +/// Non-blocking receive: polls for the next message. +/// If a message is available, copies it into `buffer` (up to `*size` bytes), +/// updates `*size` to the actual message length, and returns 0. +/// If no message is available, returns 1 (would-block). +/// On error returns negative. +#[no_mangle] +pub unsafe extern "C" fn rtcWsRecv( + ws_id: c_int, + buffer: *mut c_char, + size: *mut c_int, +) -> c_int { + if buffer.is_null() || size.is_null() { + return -1; + } + + let entries = get_entries().lock(); + if let Some(slot) = entries.iter().find(|e| { + e.as_ref().map_or(false, |ws| ws.id == ws_id) + }) { + if let Some(ws) = slot.as_ref() { + let mut queue = ws.recv_queue.lock(); + if let Some(msg) = queue.pop_front() { + let buf_size = *size as usize; + let msg_bytes = msg.as_bytes(); + let copy_len = msg_bytes.len().min(buf_size); + std::ptr::copy_nonoverlapping(msg_bytes.as_ptr(), buffer as *mut u8, copy_len); + *size = msg_bytes.len() as c_int; + return 0; + } + return 1; // Would-block: no messages + } + } + -1 +} + +/// Check if a WebSocket connection is still connected. +/// Returns 1 if connected, 0 if not, negative on error. +#[no_mangle] +pub extern "C" fn rtcWsIsConnected(ws_id: c_int) -> c_int { + let entries = get_entries().lock(); + if let Some(slot) = entries.iter().find(|e| { + e.as_ref().map_or(false, |ws| ws.id == ws_id) + }) { + if let Some(ws) = slot.as_ref() { + return if ws.connected.load(Ordering::Acquire) { 1 } else { 0 }; + } + } + -1 +} diff --git a/deps/rustrtc-capi/tests/loopback.rs b/deps/rustrtc-capi/tests/loopback.rs new file mode 100644 index 0000000..15b9130 --- /dev/null +++ b/deps/rustrtc-capi/tests/loopback.rs @@ -0,0 +1,573 @@ +//! Rust-side integration test: two PeerConnections exchange SDP/ICE and +//! send messages over a DataChannel. + +use std::ffi::{CStr, CString}; +use std::os::raw::{c_char, c_int, c_void}; +use std::sync::atomic::{AtomicBool, AtomicI32, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +// Use the crate's C API functions directly (rlib link) +use datachannel::*; + +// Re-declare the #[repr(C)] types for test use (must match types.rs layout) +#[repr(C)] +struct TestConfiguration { + ice_servers: *const *const c_char, + ice_servers_count: c_int, + proxy_server: *const c_char, + bind_address: *const c_char, + certificate_type: c_int, + ice_transport_policy: c_int, + enable_ice_tcp: bool, + enable_ice_udp_mux: bool, + disable_auto_negotiation: bool, + force_media_transport: bool, + port_range_begin: u16, + port_range_end: u16, + mtu: c_int, + max_message_size: c_int, +} + +#[repr(C)] +struct TestReliability { + unordered: bool, + unreliable: bool, + max_packet_life_time: u32, + max_retransmits: u32, +} + +#[repr(C)] +struct TestDataChannelInit { + reliability: TestReliability, + protocol: *const c_char, + negotiated: bool, + manual_stream: bool, + stream: u16, +} + +impl Default for TestConfiguration { + fn default() -> Self { + Self { + ice_servers: std::ptr::null(), + ice_servers_count: 0, + proxy_server: std::ptr::null(), + bind_address: std::ptr::null(), + certificate_type: 0, + ice_transport_policy: 0, + enable_ice_tcp: false, + enable_ice_udp_mux: false, + disable_auto_negotiation: false, + force_media_transport: false, + port_range_begin: 0, + port_range_end: 0, + mtu: 0, + max_message_size: 0, + } + } +} + +// --------------------------------------------------------------------------- +// Shared test state +// --------------------------------------------------------------------------- + +struct TestState { + sdp: parking_lot::Mutex>, + sdp_type: parking_lot::Mutex>, + candidates: parking_lot::Mutex>, + gathering_complete: AtomicBool, + dc_open: AtomicBool, + dc_id: AtomicI32, + recv_messages: parking_lot::Mutex>>, +} + +impl TestState { + fn new() -> Self { + Self { + sdp: parking_lot::Mutex::new(None), + sdp_type: parking_lot::Mutex::new(None), + candidates: parking_lot::Mutex::new(Vec::new()), + gathering_complete: AtomicBool::new(false), + dc_open: AtomicBool::new(false), + dc_id: AtomicI32::new(-1), + recv_messages: parking_lot::Mutex::new(Vec::new()), + } + } +} + +// --------------------------------------------------------------------------- +// C callbacks +// --------------------------------------------------------------------------- + +unsafe extern "C" fn on_description( + _pc: c_int, + sdp: *const c_char, + sdp_type: *const c_char, + ptr: *mut c_void, +) { + let state = &*(ptr as *const TestState); + let s = CStr::from_ptr(sdp).to_str().unwrap().to_string(); + let t = CStr::from_ptr(sdp_type).to_str().unwrap().to_string(); + *state.sdp.lock() = Some(s); + *state.sdp_type.lock() = Some(t); +} + +unsafe extern "C" fn on_candidate( + _pc: c_int, + cand: *const c_char, + _mid: *const c_char, + ptr: *mut c_void, +) { + let state = &*(ptr as *const TestState); + let c = CStr::from_ptr(cand).to_str().unwrap().to_string(); + state.candidates.lock().push(c); +} + +unsafe extern "C" fn on_state_change(_pc: c_int, _state: c_int, _ptr: *mut c_void) {} + +unsafe extern "C" fn on_gathering_state(_pc: c_int, state: c_int, ptr: *mut c_void) { + let ts = &*(ptr as *const TestState); + if state == 2 { + ts.gathering_complete.store(true, Ordering::Release); + } +} + +unsafe extern "C" fn on_data_channel(_pc: c_int, dc: c_int, ptr: *mut c_void) { + let ts = &*(ptr as *const TestState); + ts.dc_id.store(dc, Ordering::Release); + rtcSetOpenCallback(dc, Some(on_open)); + rtcSetClosedCallback(dc, Some(on_closed)); + rtcSetErrorCallback(dc, Some(on_error)); + rtcSetMessageCallback(dc, Some(on_message)); + rtcSetUserPointer(dc, ptr); +} + +unsafe extern "C" fn on_open(_id: c_int, ptr: *mut c_void) { + let ts = &*(ptr as *const TestState); + ts.dc_open.store(true, Ordering::Release); +} + +unsafe extern "C" fn on_closed(_id: c_int, ptr: *mut c_void) { + let ts = &*(ptr as *const TestState); + ts.dc_open.store(false, Ordering::Release); +} + +unsafe extern "C" fn on_error(_id: c_int, _err: *const c_char, _ptr: *mut c_void) {} + +unsafe extern "C" fn on_message(_id: c_int, data: *const u8, size: c_int, ptr: *mut c_void) { + let ts = &*(ptr as *const TestState); + if size > 0 { + let bytes = std::slice::from_raw_parts(data, size as usize).to_vec(); + ts.recv_messages.lock().push(bytes); + } +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +fn wait_for(flag: &AtomicBool, timeout: Duration) -> bool { + let start = std::time::Instant::now(); + while !flag.load(Ordering::Acquire) { + if start.elapsed() > timeout { + return false; + } + std::thread::sleep(Duration::from_millis(50)); + } + true +} + +fn wait_for_sdp(state: &TestState, timeout: Duration) -> bool { + let start = std::time::Instant::now(); + loop { + if state.sdp.lock().is_some() { + return true; + } + if start.elapsed() > timeout { + return false; + } + std::thread::sleep(Duration::from_millis(50)); + } +} + +fn wait_for_recv(state: &TestState, timeout: Duration) -> bool { + let start = std::time::Instant::now(); + loop { + if !state.recv_messages.lock().is_empty() { + return true; + } + if start.elapsed() > timeout { + return false; + } + std::thread::sleep(Duration::from_millis(50)); + } +} + +fn default_dc_init() -> TestDataChannelInit { + TestDataChannelInit { + reliability: TestReliability { + unordered: false, + unreliable: false, + max_packet_life_time: 0, + max_retransmits: 0, + }, + protocol: std::ptr::null(), + negotiated: false, + manual_stream: false, + stream: 0, + } +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[test] +fn test_preload_cleanup() { + unsafe { + rtcPreload(); + rtcCleanup(); + } +} + +#[test] +fn test_create_pc_and_dc() { + unsafe { + rtcPreload(); + + let config = TestConfiguration::default(); + let pc = rtcCreatePeerConnection(&config as *const _ as *const _); + assert!(pc > 0, "PC ID should be positive, got {pc}"); + + let label = CString::new("test").unwrap(); + let init = default_dc_init(); + let dc = rtcCreateDataChannelEx(pc, label.as_ptr(), &init as *const _ as *const _); + assert!(dc > 0, "DC ID should be positive, got {dc}"); + + rtcDeleteDataChannel(dc); + rtcClosePeerConnection(pc); + rtcDeletePeerConnection(pc); + rtcCleanup(); + } +} + +#[test] +fn test_sdp_generation() { + unsafe { + rtcPreload(); + + let alice_state = Arc::new(TestState::new()); + let config = TestConfiguration::default(); + let pc = rtcCreatePeerConnection(&config as *const _ as *const _); + + let ptr = Arc::as_ptr(&alice_state) as *mut c_void; + rtcSetUserPointer(pc, ptr); + rtcSetLocalDescriptionCallback(pc, Some(on_description)); + rtcSetLocalCandidateCallback(pc, Some(on_candidate)); + rtcSetGatheringStateChangeCallback(pc, Some(on_gathering_state)); + + let label = CString::new("data").unwrap(); + let init = default_dc_init(); + let dc = rtcCreateDataChannelEx(pc, label.as_ptr(), &init as *const _ as *const _); + assert!(dc > 0); + + rtcSetUserPointer(dc, ptr); + rtcSetOpenCallback(dc, Some(on_open)); + rtcSetMessageCallback(dc, Some(on_message)); + + // Wait for SDP offer + assert!( + wait_for_sdp(&alice_state, Duration::from_secs(10)), + "Should generate SDP offer" + ); + + let sdp = alice_state.sdp.lock().clone().unwrap(); + let sdp_type = alice_state.sdp_type.lock().clone().unwrap(); + println!("SDP type: {sdp_type}"); + println!("SDP length: {}", sdp.len()); + assert_eq!(sdp_type, "offer"); + assert!(sdp.contains("v=0"), "SDP should contain v=0"); + + rtcDeleteDataChannel(dc); + rtcClosePeerConnection(pc); + rtcDeletePeerConnection(pc); + rtcCleanup(); + } +} + +#[test] +fn test_loopback_exchange() { + unsafe { + rtcPreload(); + + let timeout = Duration::from_secs(15); + + // --- Alice (offerer) --- + let alice = Arc::new(TestState::new()); + let alice_config = TestConfiguration::default(); + let alice_pc = rtcCreatePeerConnection(&alice_config as *const _ as *const _); + let alice_ptr = Arc::as_ptr(&alice) as *mut c_void; + + rtcSetUserPointer(alice_pc, alice_ptr); + rtcSetLocalDescriptionCallback(alice_pc, Some(on_description)); + rtcSetLocalCandidateCallback(alice_pc, Some(on_candidate)); + rtcSetStateChangeCallback(alice_pc, Some(on_state_change)); + rtcSetGatheringStateChangeCallback(alice_pc, Some(on_gathering_state)); + + let label = CString::new("data").unwrap(); + let init = default_dc_init(); + let alice_dc = + rtcCreateDataChannelEx(alice_pc, label.as_ptr(), &init as *const _ as *const _); + assert!(alice_dc > 0); + rtcSetUserPointer(alice_dc, alice_ptr); + rtcSetOpenCallback(alice_dc, Some(on_open)); + rtcSetClosedCallback(alice_dc, Some(on_closed)); + rtcSetErrorCallback(alice_dc, Some(on_error)); + rtcSetMessageCallback(alice_dc, Some(on_message)); + + // Wait for Alice's offer + assert!(wait_for_sdp(&alice, timeout), "Alice should generate offer"); + let alice_sdp = alice.sdp.lock().clone().unwrap(); + assert_eq!(alice.sdp_type.lock().clone().unwrap(), "offer"); + println!("Alice offer SDP ({} bytes)", alice_sdp.len()); + + // Wait for Alice's gathering to complete + assert!( + wait_for(&alice.gathering_complete, timeout), + "Alice gathering should complete" + ); + println!( + "Alice candidates: {}", + alice.candidates.lock().len() + ); + + // --- Bob (answerer) --- + let bob = Arc::new(TestState::new()); + let bob_config = TestConfiguration::default(); + let bob_pc = rtcCreatePeerConnection(&bob_config as *const _ as *const _); + let bob_ptr = Arc::as_ptr(&bob) as *mut c_void; + + rtcSetUserPointer(bob_pc, bob_ptr); + rtcSetLocalDescriptionCallback(bob_pc, Some(on_description)); + rtcSetLocalCandidateCallback(bob_pc, Some(on_candidate)); + rtcSetStateChangeCallback(bob_pc, Some(on_state_change)); + rtcSetGatheringStateChangeCallback(bob_pc, Some(on_gathering_state)); + rtcSetDataChannelCallback(bob_pc, Some(on_data_channel)); + + // Bob sets Alice's offer as remote description + let alice_sdp_c = CString::new(alice_sdp).unwrap(); + let offer_type = CString::new("offer").unwrap(); + let res = rtcSetRemoteDescription(bob_pc, alice_sdp_c.as_ptr(), offer_type.as_ptr()); + assert_eq!(res, 0, "setRemoteDescription should succeed"); + + // Wait for Bob's answer + assert!(wait_for_sdp(&bob, timeout), "Bob should generate answer"); + let bob_sdp = bob.sdp.lock().clone().unwrap(); + assert_eq!(bob.sdp_type.lock().clone().unwrap(), "answer"); + println!("Bob answer SDP ({} bytes)", bob_sdp.len()); + + // Wait for Bob's gathering + assert!( + wait_for(&bob.gathering_complete, timeout), + "Bob gathering should complete" + ); + println!("Bob candidates: {}", bob.candidates.lock().len()); + + // Exchange SDP: Alice receives Bob's answer + let bob_sdp_c = CString::new(bob_sdp).unwrap(); + let answer_type = CString::new("answer").unwrap(); + let res = rtcSetRemoteDescription(alice_pc, bob_sdp_c.as_ptr(), answer_type.as_ptr()); + assert_eq!(res, 0); + + // Exchange ICE candidates + let alice_cands: Vec = alice.candidates.lock().clone(); + let bob_cands: Vec = bob.candidates.lock().clone(); + + for c in &alice_cands { + let cc = CString::new(c.as_str()).unwrap(); + rtcAddRemoteCandidate(bob_pc, cc.as_ptr(), std::ptr::null()); + } + for c in &bob_cands { + let cc = CString::new(c.as_str()).unwrap(); + rtcAddRemoteCandidate(alice_pc, cc.as_ptr(), std::ptr::null()); + } + + // Wait for DataChannels to open + assert!(wait_for(&alice.dc_open, timeout), "Alice DC should open"); + println!("Alice DC open"); + + let bob_dc = bob.dc_id.load(Ordering::Acquire); + assert!(bob_dc > 0, "Bob should receive incoming DC, got {bob_dc}"); + assert!(wait_for(&bob.dc_open, timeout), "Bob DC should open"); + println!("Bob DC open"); + + // --- Send message: Alice → Bob --- + let msg = b"hello from alice"; + let res = rtcSendMessage(alice_dc, msg.as_ptr(), msg.len() as c_int); + assert_eq!(res, 0, "send should succeed"); + + assert!(wait_for_recv(&bob, timeout), "Bob should receive message"); + let received = bob.recv_messages.lock().first().unwrap().clone(); + assert_eq!(received, msg.to_vec()); + println!("Bob received: {:?}", String::from_utf8_lossy(&received)); + + // --- Send message: Bob → Alice --- + let reply = b"hello from bob"; + let res = rtcSendMessage(bob_dc, reply.as_ptr(), reply.len() as c_int); + assert_eq!(res, 0); + + assert!(wait_for_recv(&alice, timeout), "Alice should receive reply"); + let received = alice.recv_messages.lock().first().unwrap().clone(); + assert_eq!(received, reply.to_vec()); + println!( + "Alice received: {:?}", + String::from_utf8_lossy(&received) + ); + + // Cleanup + rtcDeleteDataChannel(alice_dc); + rtcDeleteDataChannel(bob_dc); + rtcClosePeerConnection(alice_pc); + rtcDeletePeerConnection(alice_pc); + rtcClosePeerConnection(bob_pc); + rtcDeletePeerConnection(bob_pc); + rtcCleanup(); + } +} + +/// Test large message delivery at various chunk sizes (32KB, 64KB, 128KB, 256KB). +/// Validates 100% delivery at each size to find the SCTP drop threshold. +#[test] +fn test_large_message_delivery() { + unsafe { + rtcPreload(); + + let timeout = Duration::from_secs(30); + + // --- Alice (offerer) --- + let alice = Arc::new(TestState::new()); + let alice_config = TestConfiguration::default(); + let alice_pc = rtcCreatePeerConnection(&alice_config as *const _ as *const _); + let alice_ptr = Arc::as_ptr(&alice) as *mut c_void; + + rtcSetUserPointer(alice_pc, alice_ptr); + rtcSetLocalDescriptionCallback(alice_pc, Some(on_description)); + rtcSetLocalCandidateCallback(alice_pc, Some(on_candidate)); + rtcSetStateChangeCallback(alice_pc, Some(on_state_change)); + rtcSetGatheringStateChangeCallback(alice_pc, Some(on_gathering_state)); + + let label = CString::new("data").unwrap(); + let init = default_dc_init(); + let alice_dc = + rtcCreateDataChannelEx(alice_pc, label.as_ptr(), &init as *const _ as *const _); + assert!(alice_dc > 0); + rtcSetUserPointer(alice_dc, alice_ptr); + rtcSetOpenCallback(alice_dc, Some(on_open)); + rtcSetClosedCallback(alice_dc, Some(on_closed)); + rtcSetMessageCallback(alice_dc, Some(on_message)); + + assert!(wait_for_sdp(&alice, timeout), "Alice should generate offer"); + let alice_sdp = alice.sdp.lock().clone().unwrap(); + assert!( + wait_for(&alice.gathering_complete, timeout), + "Alice gathering should complete" + ); + + // --- Bob (answerer) --- + let bob = Arc::new(TestState::new()); + let bob_config = TestConfiguration::default(); + let bob_pc = rtcCreatePeerConnection(&bob_config as *const _ as *const _); + let bob_ptr = Arc::as_ptr(&bob) as *mut c_void; + + rtcSetUserPointer(bob_pc, bob_ptr); + rtcSetLocalDescriptionCallback(bob_pc, Some(on_description)); + rtcSetLocalCandidateCallback(bob_pc, Some(on_candidate)); + rtcSetStateChangeCallback(bob_pc, Some(on_state_change)); + rtcSetGatheringStateChangeCallback(bob_pc, Some(on_gathering_state)); + rtcSetDataChannelCallback(bob_pc, Some(on_data_channel)); + + let alice_sdp_c = CString::new(alice_sdp).unwrap(); + let offer_type = CString::new("offer").unwrap(); + rtcSetRemoteDescription(bob_pc, alice_sdp_c.as_ptr(), offer_type.as_ptr()); + + assert!(wait_for_sdp(&bob, timeout), "Bob should generate answer"); + let bob_sdp = bob.sdp.lock().clone().unwrap(); + assert!( + wait_for(&bob.gathering_complete, timeout), + "Bob gathering should complete" + ); + + let bob_sdp_c = CString::new(bob_sdp).unwrap(); + let answer_type = CString::new("answer").unwrap(); + rtcSetRemoteDescription(alice_pc, bob_sdp_c.as_ptr(), answer_type.as_ptr()); + + // Exchange ICE candidates + for c in alice.candidates.lock().iter() { + let cc = CString::new(c.as_str()).unwrap(); + rtcAddRemoteCandidate(bob_pc, cc.as_ptr(), std::ptr::null()); + } + for c in bob.candidates.lock().iter() { + let cc = CString::new(c.as_str()).unwrap(); + rtcAddRemoteCandidate(alice_pc, cc.as_ptr(), std::ptr::null()); + } + + assert!(wait_for(&alice.dc_open, timeout), "Alice DC should open"); + let bob_dc = bob.dc_id.load(Ordering::Acquire); + assert!(bob_dc > 0); + assert!(wait_for(&bob.dc_open, timeout), "Bob DC should open"); + + // --- Test message delivery at various chunk sizes --- + let sizes: &[usize] = &[32 * 1024, 64 * 1024, 128 * 1024, 256 * 1024]; + let msg_count = 100; + + for &chunk_size in sizes { + // Clear previous messages + bob.recv_messages.lock().clear(); + + let payload: Vec = (0..chunk_size).map(|i| (i % 256) as u8).collect(); + + for _ in 0..msg_count { + let res = rtcSendMessage(alice_dc, payload.as_ptr(), payload.len() as c_int); + assert_eq!(res, 0, "send should succeed for {chunk_size}B messages"); + } + + // Wait for all messages to arrive (generous timeout) + let wait_start = std::time::Instant::now(); + loop { + let count = bob.recv_messages.lock().len(); + if count >= msg_count { + break; + } + if wait_start.elapsed() > Duration::from_secs(20) { + println!( + "SCTP drop threshold found: {chunk_size}B — only {count}/{msg_count} delivered" + ); + break; + } + std::thread::sleep(Duration::from_millis(50)); + } + + let received = bob.recv_messages.lock().len(); + println!( + "Chunk size {chunk_size}B: {received}/{msg_count} messages delivered ({}%)", + received * 100 / msg_count + ); + + // Verify payload integrity for received messages + for msg in bob.recv_messages.lock().iter() { + assert_eq!(msg.len(), chunk_size, "Message size mismatch"); + assert_eq!(msg[0], 0u8, "First byte should be 0"); + assert_eq!(msg[chunk_size - 1], ((chunk_size - 1) % 256) as u8); + } + } + + // Cleanup + rtcDeleteDataChannel(alice_dc); + rtcDeleteDataChannel(bob_dc); + rtcClosePeerConnection(alice_pc); + rtcDeletePeerConnection(alice_pc); + rtcClosePeerConnection(bob_pc); + rtcDeletePeerConnection(bob_pc); + rtcCleanup(); + } +} diff --git a/src/platform/webrtc_bridge.zig b/src/platform/webrtc_bridge.zig new file mode 100644 index 0000000..836845c --- /dev/null +++ b/src/platform/webrtc_bridge.zig @@ -0,0 +1,1112 @@ +//! WebRTC Bridge — connects signaling server to WebRTC PeerConnections. +//! +//! On the desktop side, this module: +//! 1. Connects to the signaling server via WebSocket (through rustrtc-capi) +//! 2. Exchanges SDP offers/answers and ICE candidates +//! 3. When a DataChannel opens, wraps it in a BridgeChannelTransport +//! 4. Registers the transport with the P2P layer via addPeerConnectionWithTransport +//! +//! Call `bridge.update()` from the P2P update loop to poll signaling messages. + +const std = @import("std"); +const Allocator = std.mem.Allocator; +const core = @import("core"); +const CoreTransport = core.transport.Transport; +const TransportState = core.transport.TransportState; +const TransportMode = core.transport.TransportMode; +const CoreError = core.errors.Error; +const Address = core.Address; +const sync = @import("sync"); +const webrtc_native = @import("webrtc_native.zig"); +const rtc = webrtc_native.rtc; +const network = @import("network"); +const PeerId = network.peer.PeerId; +const SecureConnection = network.SecureConnection; +const noise = @import("noise"); + +const log = std.log.scoped(.webrtc_bridge); + +/// A direct message (0xFF prefix) received from a DataChannel. +/// These bypass P2P framing and go straight to the application. +pub const DirectMessage = struct { + app_id: u8, + payload: []u8, // owned by bridge allocator +}; + +/// Notification of a newly connected peer. +pub const NewPeer = struct { + peer_id: PeerId, + dc_id: c_int, +}; + +/// JSON message types from the signaling server. +const MsgType = enum { + offer, + answer, + candidate, + registered, + pong, + @"error", + unknown, +}; + +/// Parsed signaling message. +pub const SignalingMsg = struct { + msg_type: MsgType, + from: ?[]const u8 = null, + sdp: ?[]const u8 = null, + candidate: ?[]const u8 = null, + sdp_mid: ?[]const u8 = null, + peer_id: ?[]const u8 = null, + message: ?[]const u8 = null, +}; + +/// Pending DataChannel entry — tracks signaling peer and handshake role. +const PendingChannel = struct { + remote_signaling_id: []const u8, + is_initiator: bool, +}; + +/// A channel awaiting Noise handshake on the main thread. +const PendingHandshake = struct { + dc_id: c_int, + peer_id: PeerId, + bct: *BridgeChannelTransport, + remote_signaling_id: []const u8, + is_initiator: bool, +}; + +// ============================================================================ +// BridgeChannelTransport — wraps a raw DataChannel ID for the Transport vtable +// ============================================================================ + +const MAX_RECV_QUEUE = 8192; +const MAX_RECV_QUEUE_WARN = MAX_RECV_QUEUE * 3 / 4; // 75% = 6144 +const MAX_DIRECT_QUEUE = 16384; + +/// Transport implementation that wraps a raw WebRTC DataChannel. +/// Messages arrive via the dcMessageCallback → pushMessage, and the P2P +/// update loop drains them via the Transport vtable's receive(). +pub const BridgeChannelTransport = struct { + dc_id: c_int, + state: TransportState, + recv_queue: std.ArrayListUnmanaged([]u8), + allocator: Allocator, + /// Protects recv_queue (written from rustrtc callback thread, read from main thread). + mutex: std.Thread.Mutex = .{}, + + pub fn init(allocator: Allocator, dc_id: c_int) BridgeChannelTransport { + return .{ + .dc_id = dc_id, + .state = .connected, + .recv_queue = .{}, + .allocator = allocator, + }; + } + + pub fn deinit(self: *BridgeChannelTransport) void { + for (self.recv_queue.items) |msg| { + self.allocator.free(msg); + } + self.recv_queue.deinit(self.allocator); + } + + /// Push a received message (called from dcMessageCallback on rustrtc thread). + pub fn pushMessage(self: *BridgeChannelTransport, data: []const u8) void { + self.mutex.lock(); + defer self.mutex.unlock(); + if (self.recv_queue.items.len >= MAX_RECV_QUEUE) { + const old = self.recv_queue.orderedRemove(0); + self.allocator.free(old); + log.warn("recv_queue overflow: dropping oldest message (size={d})", .{MAX_RECV_QUEUE}); + } else if (self.recv_queue.items.len >= MAX_RECV_QUEUE_WARN) { + log.warn("recv_queue at {d}% capacity ({d}/{d})", .{ + self.recv_queue.items.len * 100 / MAX_RECV_QUEUE, + self.recv_queue.items.len, + MAX_RECV_QUEUE, + }); + } + const copy = self.allocator.dupe(u8, data) catch return; + self.recv_queue.append(self.allocator, copy) catch { + self.allocator.free(copy); + }; + } + + // -- Transport vtable conformance -- + + pub fn send(self: *BridgeChannelTransport, data: []const u8) CoreError!usize { + if (self.state != .connected) return CoreError.ConnectionClosed; + const result = rtc.rtcSendMessage(self.dc_id, data.ptr, @intCast(data.len)); + if (result < 0) return CoreError.NetworkError; + return data.len; + } + + pub fn receive(self: *BridgeChannelTransport, buffer: []u8) CoreError!usize { + self.mutex.lock(); + const queue_empty = self.recv_queue.items.len == 0; + const msg = if (!queue_empty) self.recv_queue.orderedRemove(0) else null; + self.mutex.unlock(); + + if (msg) |m| { + defer self.allocator.free(m); + const copy_len = @min(m.len, buffer.len); + @memcpy(buffer[0..copy_len], m[0..copy_len]); + return copy_len; + } + if (self.state == .closed) return CoreError.ConnectionClosed; + return CoreError.ConnectionTimeout; + } + + pub fn sendTo(_: *BridgeChannelTransport, _: []const u8, _: Address) CoreError!usize { + return CoreError.OperationNotSupported; + } + + pub fn receiveFrom(_: *BridgeChannelTransport, _: []u8) CoreError!core.transport.ReceiveFromResult { + return CoreError.OperationNotSupported; + } + + pub fn canSend(self: *BridgeChannelTransport) bool { + if (self.state != .connected) return false; + return rtc.rtcGetBufferedAmount(self.dc_id) < 1_048_576; + } + + pub fn canReceive(self: *BridgeChannelTransport) bool { + self.mutex.lock(); + defer self.mutex.unlock(); + return self.recv_queue.items.len > 0; + } + + pub fn close(self: *BridgeChannelTransport) void { + if (self.state == .closed) return; + self.state = .closed; + _ = rtc.rtcClose(self.dc_id); + } + + pub fn getState(self: *BridgeChannelTransport) TransportState { + return self.state; + } + + pub fn getRemoteAddress(_: *BridgeChannelTransport) ?Address { + return null; + } + + pub fn getMode(_: *BridgeChannelTransport) TransportMode { + return .stream; + } + + /// Wrap into the generic Transport vtable. + pub fn transport(self: *BridgeChannelTransport) CoreTransport { + return CoreTransport.init(self); + } +}; + +// ============================================================================ +// WebRTCBridge +// ============================================================================ + +pub const WebRTCBridge = struct { + allocator: Allocator, + ws_id: c_int = -1, + signaling_url: []const u8, + peer_id: []const u8, + connected: bool = false, + + /// Reference to the P2P instance for registering new connections. + p2p: ?*@import("p2p").P2P = null, + + /// Active PeerConnections by remote signaling peer ID. + /// Key: remote peer ID (owned), Value: PC ID from rtc library. + peer_connections: std.StringHashMap(c_int), + + /// Pending DataChannels awaiting open callback. + /// Key: DC ID, Value: remote signaling peer ID (owned) and handshake role. + pending_channels: std.AutoHashMap(c_int, PendingChannel), + + /// Channels awaiting Noise handshake (processed from update() on main thread). + pending_handshakes: std.ArrayListUnmanaged(PendingHandshake), + + /// Active channel transports by DC ID. + /// Key: DC ID, Value: heap-allocated BridgeChannelTransport. + channel_transports: std.AutoHashMap(c_int, *BridgeChannelTransport), + + /// Mapping: signaling peer ID → P2P PeerId. + signaling_to_p2p: std.StringHashMap(PeerId), + + /// Direct messages (0xFF prefix) received from DataChannels. + direct_recv_queue: std.ArrayListUnmanaged(DirectMessage), + + /// Newly connected peers (populated by registerChannel). + connected_peers: std.ArrayListUnmanaged(NewPeer), + + /// Protects queues written from rustrtc callback thread and read from main thread: + /// direct_recv_queue, connected_peers, and BridgeChannelTransport.recv_queue. + callback_mutex: std.Thread.Mutex = .{}, + + /// Last time we sent a ping to the signaling server (ms since epoch). + last_ping_time: i64 = 0, + + /// Signaling reconnection state. + reconnect_delay_ms: u32 = 1000, + reconnect_max_delay_ms: u32 = 30_000, + last_reconnect_attempt: i64 = 0, + reconnect_attempts: u32 = 0, + auto_reconnect: bool = true, + + /// Pending peer reconnections (peer names to reconnect on DC close). + pending_reconnects: std.ArrayListUnmanaged([]const u8) = .{}, + /// Backoff for peer reconnections: peer_name → next_attempt_time. + peer_reconnect_backoff: std.StringHashMap(i64) = undefined, + + /// Recv buffer for signaling messages. + recv_buf: [65536]u8 = undefined, + + pub fn init( + allocator: Allocator, + signaling_url: []const u8, + peer_id: []const u8, + ) WebRTCBridge { + return .{ + .allocator = allocator, + .signaling_url = signaling_url, + .peer_id = peer_id, + .peer_connections = std.StringHashMap(c_int).init(allocator), + .pending_channels = std.AutoHashMap(c_int, PendingChannel).init(allocator), + .pending_handshakes = .{}, + .channel_transports = std.AutoHashMap(c_int, *BridgeChannelTransport).init(allocator), + .signaling_to_p2p = std.StringHashMap(PeerId).init(allocator), + .direct_recv_queue = .{}, + .connected_peers = .{}, + .peer_reconnect_backoff = std.StringHashMap(i64).init(allocator), + }; + } + + pub fn deinit(self: *WebRTCBridge) void { + self.disconnect(); + + var pc_iter = self.peer_connections.iterator(); + while (pc_iter.next()) |entry| { + self.allocator.free(entry.key_ptr.*); + } + self.peer_connections.deinit(); + + var pending_iter = self.pending_channels.iterator(); + while (pending_iter.next()) |entry| { + self.allocator.free(entry.value_ptr.*.remote_signaling_id); + } + self.pending_channels.deinit(); + + for (self.pending_handshakes.items) |hs| { + self.allocator.free(hs.remote_signaling_id); + } + self.pending_handshakes.deinit(self.allocator); + + var ct_iter = self.channel_transports.iterator(); + while (ct_iter.next()) |entry| { + entry.value_ptr.*.deinit(); + self.allocator.destroy(entry.value_ptr.*); + } + self.channel_transports.deinit(); + + var sp_iter = self.signaling_to_p2p.iterator(); + while (sp_iter.next()) |entry| { + self.allocator.free(entry.key_ptr.*); + } + self.signaling_to_p2p.deinit(); + + for (self.direct_recv_queue.items) |dm| { + self.allocator.free(dm.payload); + } + self.direct_recv_queue.deinit(self.allocator); + self.connected_peers.deinit(self.allocator); + + for (self.pending_reconnects.items) |name| { + self.allocator.free(name); + } + self.pending_reconnects.deinit(self.allocator); + self.peer_reconnect_backoff.deinit(); + } + + /// Bind the bridge to a P2P instance. Must be called before update(). + pub fn bindP2P(self: *WebRTCBridge, p2p: *@import("p2p").P2P) void { + self.p2p = p2p; + } + + /// Connect to the signaling server. + pub fn connect(self: *WebRTCBridge) !void { + // Attempt to load the WebRTC library if not already loaded + _ = rtc.load(); + if (!rtc.isAvailable()) return error.WebRTCNotAvailable; + if (!rtc.wsAvailable()) return error.SignalingNotAvailable; + + const url_z = try self.allocator.dupeZ(u8, self.signaling_url); + defer self.allocator.free(url_z); + const pid_z = try self.allocator.dupeZ(u8, self.peer_id); + defer self.allocator.free(pid_z); + + const ws_id = rtc.rtcWsConnect(url_z, pid_z); + if (ws_id < 0) { + log.err("Failed to connect to signaling server: {d}", .{ws_id}); + return error.ConnectionFailed; + } + self.ws_id = ws_id; + self.connected = true; + log.info("Connected to signaling server as '{s}'", .{self.peer_id}); + } + + /// Disconnect from the signaling server and close all PeerConnections. + pub fn disconnect(self: *WebRTCBridge) void { + var iter = self.peer_connections.valueIterator(); + while (iter.next()) |pc_id| { + _ = rtc.rtcClosePeerConnection(pc_id.*); + _ = rtc.rtcDeletePeerConnection(pc_id.*); + } + + if (self.ws_id >= 0) { + _ = rtc.rtcWsDisconnect(self.ws_id); + self.ws_id = -1; + } + self.connected = false; + } + + /// Initiate a WebRTC connection to a remote peer (via signaling). + pub fn connectToPeer(self: *WebRTCBridge, remote_peer_id: []const u8) !void { + if (!self.connected) return error.NotConnected; + + var config = std.mem.zeroes(rtc.Configuration); + const stun_url = "stun:stun.l.google.com:19302"; + const stun_urls = [_][*:0]const u8{stun_url}; + config.iceServers = &stun_urls; + config.iceServersCount = 1; + config.maxMessageSize = 1024 * 1024; // 1MB — allow large file chunks + + const pc_id = rtc.rtcCreatePeerConnection(&config); + if (pc_id < 0) return error.PeerConnectionFailed; + + _ = rtc.rtcSetLocalDescriptionCallback(pc_id, localDescriptionCallback); + _ = rtc.rtcSetLocalCandidateCallback(pc_id, localCandidateCallback); + _ = rtc.rtcSetStateChangeCallback(pc_id, stateChangeCallback); + rtc.rtcSetUserPointer(pc_id, @ptrCast(self)); + + const key = try self.allocator.dupe(u8, remote_peer_id); + try self.peer_connections.put(key, pc_id); + + const dc_id = rtc.rtcCreateDataChannel(pc_id, "zig-p2p"); + if (dc_id < 0) return error.DataChannelFailed; + + _ = rtc.rtcSetOpenCallback(dc_id, dcOpenCallback); + _ = rtc.rtcSetClosedCallback(dc_id, dcClosedCallback); + _ = rtc.rtcSetMessageCallback(dc_id, dcMessageCallback); + rtc.rtcSetUserPointer(dc_id, @ptrCast(self)); + + const peer_key = try self.allocator.dupe(u8, remote_peer_id); + try self.pending_channels.put(dc_id, .{ + .remote_signaling_id = peer_key, + .is_initiator = true, + }); + + _ = rtc.rtcSetLocalDescription(pc_id, null); + + log.info("Initiated connection to peer '{s}'", .{remote_peer_id}); + } + + /// Poll signaling messages and process them. Call from update loop. + pub fn update(self: *WebRTCBridge) void { + const now = std.time.milliTimestamp(); + + // Handle signaling reconnection + if (!self.connected and self.auto_reconnect) { + const delay: i64 = @intCast(self.reconnect_delay_ms); + if (now - self.last_reconnect_attempt >= delay) { + self.last_reconnect_attempt = now; + log.info("Attempting signaling reconnect (attempt {d}, delay {d}ms)", .{ + self.reconnect_attempts + 1, + self.reconnect_delay_ms, + }); + // Disconnect old WS if still around + if (self.ws_id >= 0) { + _ = rtc.rtcWsDisconnect(self.ws_id); + self.ws_id = -1; + } + self.connect() catch |err| { + log.warn("Signaling reconnect failed: {}", .{err}); + self.reconnect_attempts += 1; + // Exponential backoff, capped at max + self.reconnect_delay_ms = @min( + self.reconnect_delay_ms * 2, + self.reconnect_max_delay_ms, + ); + return; + }; + // Success — reset backoff + self.reconnect_attempts = 0; + self.reconnect_delay_ms = 1000; + log.info("Signaling reconnected successfully", .{}); + } + return; + } + + if (self.ws_id < 0) return; + + if (rtc.rtcWsIsConnected(self.ws_id) != 1) { + self.connected = false; + log.warn("Signaling server disconnected", .{}); + return; + } + + // Send keepalive ping every 30s to prevent signaling server stale timeout + if (now - self.last_ping_time > 30_000) { + self.sendSignaling("{\"type\":\"ping\"}"); + self.last_ping_time = now; + } + + var i: u32 = 0; + while (i < 16) : (i += 1) { + var size: c_int = @intCast(self.recv_buf.len); + const result = rtc.rtcWsRecv(self.ws_id, &self.recv_buf, &size); + if (result == 1) break; + if (result < 0) break; + + const msg_data = self.recv_buf[0..@intCast(size)]; + self.handleSignalingMessage(msg_data); + } + + // Drain pending Noise handshakes (from callback thread → main thread) + self.drainPendingHandshakes(); + + // Drain pending peer reconnections + self.drainPeerReconnects(now); + } + + /// Process pending Noise handshakes on the main thread. + /// Channels are queued here by registerChannel() (which runs on the callback thread) + /// to avoid deadlock — the blocking handshake reads from recv_queue which is fed + /// by dcMessageCallback on the same callback thread. + fn drainPendingHandshakes(self: *WebRTCBridge) void { + // Snapshot the pending list under lock, then process without holding it + self.callback_mutex.lock(); + const snapshot = self.pending_handshakes.toOwnedSlice(self.allocator) catch { + self.callback_mutex.unlock(); + return; + }; + self.callback_mutex.unlock(); + + for (snapshot) |hs| { + defer self.allocator.free(hs.remote_signaling_id); + + const p2p = self.p2p orelse continue; + const keypair = p2p.getNoiseKeyPair() orelse continue; + + // Heap-allocate SecureConnection (self-referential pointer for io_transport) + const secure = self.allocator.create(SecureConnection) catch { + log.err("Failed to allocate SecureConnection for DC {d}", .{hs.dc_id}); + continue; + }; + secure.initWithTransport(hs.bct.transport(), keypair, self.allocator); + + // Blocking handshake — safe on main thread; dcMessageCallback feeds recv_queue + // from a separate callback thread, so producer and consumer don't deadlock. + if (hs.is_initiator) { + secure.initiateHandshake() catch |err| { + log.warn("Noise handshake failed (initiator) for '{s}': {} — falling back to DTLS-only", .{ hs.remote_signaling_id, err }); + self.allocator.destroy(secure); + // Fall back to DTLS-only (e.g. browser peers don't speak Noise) + self.registerChannelWithoutNoise(p2p, hs.dc_id, hs.bct, hs.peer_id, hs.remote_signaling_id); + continue; + }; + } else { + secure.acceptHandshake() catch |err| { + log.warn("Noise handshake failed (responder) for '{s}': {} — falling back to DTLS-only", .{ hs.remote_signaling_id, err }); + self.allocator.destroy(secure); + // Fall back to DTLS-only (e.g. browser peers don't speak Noise) + self.registerChannelWithoutNoise(p2p, hs.dc_id, hs.bct, hs.peer_id, hs.remote_signaling_id); + continue; + }; + } + + log.info("Noise handshake completed for '{s}' (initiator={})", .{ + hs.remote_signaling_id, hs.is_initiator, + }); + + // Register with P2P using the secure connection + const transport_handle = hs.bct.transport(); + p2p.addPeerConnectionWithTransportSecure(hs.peer_id, transport_handle, secure) catch |err| { + log.err("Failed to register Noise-encrypted WebRTC peer: {}", .{err}); + secure.cleanupHandshake(); + self.allocator.destroy(secure); + _ = self.channel_transports.remove(hs.dc_id); + hs.bct.deinit(); + self.allocator.destroy(hs.bct); + continue; + }; + + // Notify about new peer connection + { + self.callback_mutex.lock(); + defer self.callback_mutex.unlock(); + self.connected_peers.append(self.allocator, .{ .peer_id = hs.peer_id, .dc_id = hs.dc_id }) catch {}; + } + } + + self.allocator.free(snapshot); + } + + /// Get the P2P PeerId for a signaling peer. Returns null if not yet connected. + pub fn getPeerId(self: *WebRTCBridge, signaling_peer_id: []const u8) ?PeerId { + return self.signaling_to_p2p.get(signaling_peer_id); + } + + /// Drain one direct message from the queue. Caller must call freeDirectMessage(). + pub fn pollDirectMessage(self: *WebRTCBridge) ?DirectMessage { + self.callback_mutex.lock(); + defer self.callback_mutex.unlock(); + if (self.direct_recv_queue.items.len == 0) return null; + return self.direct_recv_queue.orderedRemove(0); + } + + /// Free a direct message payload returned by pollDirectMessage(). + pub fn freeDirectMessage(self: *WebRTCBridge, msg: DirectMessage) void { + self.allocator.free(msg.payload); + } + + /// Drain one newly-connected peer notification. + pub fn pollNewPeer(self: *WebRTCBridge) ?NewPeer { + self.callback_mutex.lock(); + defer self.callback_mutex.unlock(); + if (self.connected_peers.items.len == 0) return null; + return self.connected_peers.orderedRemove(0); + } + + /// Send raw bytes on a DataChannel (bypasses P2P framing). + pub fn sendDirect(self: *WebRTCBridge, dc_id: c_int, data: []const u8) bool { + _ = self; + const result = rtc.rtcSendMessage(dc_id, data.ptr, @intCast(data.len)); + return result >= 0; + } + + /// Get the DataChannel ID for any active channel (first found). + pub fn getFirstDcId(self: *WebRTCBridge) ?c_int { + var iter = self.channel_transports.iterator(); + if (iter.next()) |entry| return entry.key_ptr.*; + return null; + } + + /// Get the DataChannel ID for a specific P2P peer. + /// Reverse-lookup: PeerId → signaling name → channel_transports. + pub fn getDcIdForP2PPeer(self: *WebRTCBridge, peer_id: PeerId) ?c_int { + // Find signaling name for this P2P peer ID + var sp_iter = self.signaling_to_p2p.iterator(); + var signaling_name: ?[]const u8 = null; + while (sp_iter.next()) |entry| { + if (std.mem.eql(u8, &entry.value_ptr.*.bytes, &peer_id.bytes)) { + signaling_name = entry.key_ptr.*; + break; + } + } + const name = signaling_name orelse return null; + + // Find DC ID for this signaling peer + var pc_iter = self.peer_connections.iterator(); + while (pc_iter.next()) |entry| { + if (std.mem.eql(u8, entry.key_ptr.*, name)) { + // Find a channel_transport with matching PC + var ct_iter = self.channel_transports.iterator(); + while (ct_iter.next()) |ct_entry| { + // Check if this DC belongs to the same peer by checking pending_channels + if (self.pending_channels.get(ct_entry.key_ptr.*)) |pending| { + if (std.mem.eql(u8, pending.remote_signaling_id, name)) { + return ct_entry.key_ptr.*; + } + } + } + } + } + return null; + } + + /// Query the send buffer level of a DataChannel. + pub fn getBufferedAmount(_: *WebRTCBridge, dc_id: c_int) usize { + const amount = rtc.rtcGetBufferedAmount(dc_id); + return if (amount < 0) 0 else @intCast(amount); + } + + /// Drain pending peer reconnections with backoff. + fn drainPeerReconnects(self: *WebRTCBridge, now: i64) void { + var i: usize = 0; + while (i < self.pending_reconnects.items.len) { + const peer_name = self.pending_reconnects.items[i]; + // Check backoff + const next_attempt = self.peer_reconnect_backoff.get(peer_name) orelse 0; + if (now < next_attempt) { + i += 1; + continue; + } + + // Attempt reconnection + log.info("Attempting peer reconnection to '{s}'", .{peer_name}); + self.connectToPeer(peer_name) catch |err| { + log.warn("Peer reconnect to '{s}' failed: {}", .{ peer_name, err }); + // Set backoff: 5 seconds + self.peer_reconnect_backoff.put( + peer_name, + now + 5000, + ) catch {}; + i += 1; + continue; + }; + + // Success — remove from pending list and clear backoff + _ = self.peer_reconnect_backoff.remove(peer_name); + self.allocator.free(peer_name); + _ = self.pending_reconnects.orderedRemove(i); + } + } + + fn handleSignalingMessage(self: *WebRTCBridge, data: []const u8) void { + const msg = parseSignalingMessage(data) orelse { + log.warn("Failed to parse signaling message", .{}); + return; + }; + + switch (msg.msg_type) { + .offer => self.handleOffer(msg), + .answer => self.handleAnswer(msg), + .candidate => self.handleCandidate(msg), + .registered => log.info("Registered with signaling server", .{}), + .pong => {}, + .@"error" => { + if (msg.message) |m| log.warn("Signaling error: {s}", .{m}); + }, + .unknown => {}, + } + } + + fn handleOffer(self: *WebRTCBridge, msg: SignalingMsg) void { + const from = msg.from orelse return; + const sdp_raw = msg.sdp orelse return; + + // Unescape JSON string (e.g. \r\n → actual CR LF) + const sdp = jsonUnescape(self.allocator, sdp_raw) catch return; + defer self.allocator.free(sdp); + + var config = std.mem.zeroes(rtc.Configuration); + const stun_url = "stun:stun.l.google.com:19302"; + const stun_urls = [_][*:0]const u8{stun_url}; + config.iceServers = &stun_urls; + config.iceServersCount = 1; + config.maxMessageSize = 1024 * 1024; // 1MB — allow large file chunks + + const pc_id = rtc.rtcCreatePeerConnection(&config); + if (pc_id < 0) return; + + _ = rtc.rtcSetLocalDescriptionCallback(pc_id, localDescriptionCallback); + _ = rtc.rtcSetLocalCandidateCallback(pc_id, localCandidateCallback); + _ = rtc.rtcSetStateChangeCallback(pc_id, stateChangeCallback); + _ = rtc.rtcSetDataChannelCallback(pc_id, dataChannelCallback); + rtc.rtcSetUserPointer(pc_id, @ptrCast(self)); + + const key = self.allocator.dupe(u8, from) catch return; + self.peer_connections.put(key, pc_id) catch { + self.allocator.free(key); + return; + }; + + _ = rtc.rtcSetRemoteDescription(pc_id, sdp.ptr, "offer"); + + log.info("Received offer from '{s}', sending answer", .{from}); + } + + fn handleAnswer(self: *WebRTCBridge, msg: SignalingMsg) void { + const from = msg.from orelse return; + const sdp_raw = msg.sdp orelse return; + + const pc_id = self.peer_connections.get(from) orelse { + log.warn("Got answer from unknown peer: {s}", .{from}); + return; + }; + + const sdp = jsonUnescape(self.allocator, sdp_raw) catch return; + defer self.allocator.free(sdp); + _ = rtc.rtcSetRemoteDescription(pc_id, sdp.ptr, "answer"); + + log.info("Received answer from '{s}'", .{from}); + } + + fn handleCandidate(self: *WebRTCBridge, msg: SignalingMsg) void { + const from = msg.from orelse return; + const candidate_raw = msg.candidate orelse return; + + const pc_id = self.peer_connections.get(from) orelse return; + + const cand = jsonUnescape(self.allocator, candidate_raw) catch return; + defer self.allocator.free(cand); + const mid = if (msg.sdp_mid) |m| (jsonUnescape(self.allocator, m) catch null) else null; + defer if (mid) |m| self.allocator.free(m); + + // Strip "candidate:" prefix — rustrtc expects raw candidate string + const cand_str: [*:0]const u8 = if (std.mem.startsWith(u8, cand, "candidate:")) + cand["candidate:".len..].ptr + else + cand.ptr; + + _ = rtc.rtcAddRemoteCandidate(pc_id, cand_str, if (mid) |m| m.ptr else null); + } + + fn sendSignaling(self: *WebRTCBridge, json: []const u8) void { + if (self.ws_id < 0) return; + _ = rtc.rtcWsSend(self.ws_id, json.ptr, @intCast(json.len)); + } + + fn findPeerForPc(self: *WebRTCBridge, pc_id: c_int) ?[]const u8 { + var iter = self.peer_connections.iterator(); + while (iter.next()) |entry| { + if (entry.value_ptr.* == pc_id) return entry.key_ptr.*; + } + return null; + } + + /// Register a DataChannel as a P2P transport. Called when a DC opens. + /// If Noise encryption is available, the channel is queued for handshake + /// on the main thread (via update()) to avoid deadlock with the callback thread. + fn registerChannel(self: *WebRTCBridge, dc_id: c_int) void { + const p2p = self.p2p orelse { + log.warn("DataChannel {d} opened but no P2P instance bound", .{dc_id}); + return; + }; + + // Get the remote signaling peer ID and handshake role for this channel + const pending = self.pending_channels.get(dc_id) orelse { + log.warn("DataChannel {d} opened but no pending entry", .{dc_id}); + return; + }; + const remote_signaling_id = pending.remote_signaling_id; + const is_initiator = pending.is_initiator; + + // Create a BridgeChannelTransport for this DC + const bct = self.allocator.create(BridgeChannelTransport) catch { + log.err("Failed to allocate BridgeChannelTransport", .{}); + return; + }; + bct.* = BridgeChannelTransport.init(self.allocator, dc_id); + + self.channel_transports.put(dc_id, bct) catch { + bct.deinit(); + self.allocator.destroy(bct); + return; + }; + + // Generate a deterministic PeerId from the signaling peer name + const p2p_id = peerIdFromSignalingId(remote_signaling_id); + + // Store the signaling → P2P peer ID mapping + const sig_key = self.allocator.dupe(u8, remote_signaling_id) catch return; + self.signaling_to_p2p.put(sig_key, p2p_id) catch { + self.allocator.free(sig_key); + }; + + // Check if Noise encryption is available + if (p2p.getNoiseKeyPair() != null) { + // Defer handshake to update() on the main thread — callback thread would deadlock + const hs_sig_id = self.allocator.dupe(u8, remote_signaling_id) catch return; + { + self.callback_mutex.lock(); + defer self.callback_mutex.unlock(); + self.pending_handshakes.append(self.allocator, .{ + .dc_id = dc_id, + .peer_id = p2p_id, + .bct = bct, + .remote_signaling_id = hs_sig_id, + .is_initiator = is_initiator, + }) catch { + self.allocator.free(hs_sig_id); + log.err("Failed to queue Noise handshake for DC {d}", .{dc_id}); + return; + }; + } + log.info("DataChannel {d} queued for Noise handshake (initiator={}, peer='{s}')", .{ + dc_id, is_initiator, remote_signaling_id, + }); + return; + } + + // No Noise — register directly without encryption + self.registerChannelWithoutNoise(p2p, dc_id, bct, p2p_id, remote_signaling_id); + } + + /// Register a channel without Noise encryption (DTLS only). + fn registerChannelWithoutNoise( + self: *WebRTCBridge, + p2p: *@import("p2p").P2P, + dc_id: c_int, + bct: *BridgeChannelTransport, + p2p_id: PeerId, + remote_signaling_id: []const u8, + ) void { + const transport_handle = bct.transport(); + p2p.addPeerConnectionWithTransport(p2p_id, transport_handle) catch |err| { + log.err("Failed to register WebRTC peer: {}", .{err}); + _ = self.channel_transports.remove(dc_id); + bct.deinit(); + self.allocator.destroy(bct); + return; + }; + + // Notify about new peer connection (guarded — registerChannel is called from callback thread) + { + self.callback_mutex.lock(); + defer self.callback_mutex.unlock(); + self.connected_peers.append(self.allocator, .{ .peer_id = p2p_id, .dc_id = dc_id }) catch {}; + } + + log.info("DataChannel {d} registered as P2P peer '{s}' (DTLS only)", .{ dc_id, remote_signaling_id }); + } + + // ======================================================================== + // Static C callbacks (bridge to instance methods via user pointer) + // ======================================================================== + + fn localDescriptionCallback(pc_id: c_int, sdp: [*:0]const u8, sdp_type: [*:0]const u8, ptr: ?*anyopaque) callconv(.c) void { + const self: *WebRTCBridge = @ptrCast(@alignCast(ptr orelse return)); + const remote_peer = self.findPeerForPc(pc_id) orelse return; + const sdp_slice = std.mem.span(sdp); + const type_slice = std.mem.span(sdp_type); + + var buf: [65536]u8 = undefined; + var stream = std.io.fixedBufferStream(&buf); + const w = stream.writer(); + w.writeAll("{\"type\":\"") catch return; + jsonWriteEscaped(w, type_slice) catch return; + w.writeAll("\",\"to\":\"") catch return; + jsonWriteEscaped(w, remote_peer) catch return; + w.writeAll("\",\"sdp\":\"") catch return; + jsonWriteEscaped(w, sdp_slice) catch return; + w.writeAll("\"}") catch return; + + self.sendSignaling(stream.getWritten()); + } + + fn localCandidateCallback(pc_id: c_int, cand: [*:0]const u8, mid: [*:0]const u8, ptr: ?*anyopaque) callconv(.c) void { + const self: *WebRTCBridge = @ptrCast(@alignCast(ptr orelse return)); + const remote_peer = self.findPeerForPc(pc_id) orelse return; + const cand_slice = std.mem.span(cand); + const mid_slice = std.mem.span(mid); + + var buf: [8192]u8 = undefined; + var stream = std.io.fixedBufferStream(&buf); + const w = stream.writer(); + w.writeAll("{\"type\":\"candidate\",\"to\":\"") catch return; + jsonWriteEscaped(w, remote_peer) catch return; + w.writeAll("\",\"candidate\":\"") catch return; + // Browser expects "candidate:" prefix in ICE candidates + if (!std.mem.startsWith(u8, cand_slice, "candidate:")) { + w.writeAll("candidate:") catch return; + } + jsonWriteEscaped(w, cand_slice) catch return; + w.writeAll("\",\"sdpMid\":\"") catch return; + jsonWriteEscaped(w, mid_slice) catch return; + w.writeAll("\"}") catch return; + + self.sendSignaling(stream.getWritten()); + } + + fn stateChangeCallback(pc_id: c_int, state: c_int, ptr: ?*anyopaque) callconv(.c) void { + _ = ptr; + log.debug("PC {d} state changed to {d}", .{ pc_id, state }); + } + + fn dataChannelCallback(pc_id: c_int, dc_id: c_int, ptr: ?*anyopaque) callconv(.c) void { + const self: *WebRTCBridge = @ptrCast(@alignCast(ptr orelse return)); + _ = rtc.rtcSetOpenCallback(dc_id, dcOpenCallback); + _ = rtc.rtcSetClosedCallback(dc_id, dcClosedCallback); + _ = rtc.rtcSetMessageCallback(dc_id, dcMessageCallback); + rtc.rtcSetUserPointer(dc_id, @ptrCast(self)); + + if (self.findPeerForPc(pc_id)) |remote_peer| { + const key = self.allocator.dupe(u8, remote_peer) catch return; + self.pending_channels.put(dc_id, .{ + .remote_signaling_id = key, + .is_initiator = false, + }) catch { + self.allocator.free(key); + }; + } + } + + fn dcOpenCallback(dc_id: c_int, ptr: ?*anyopaque) callconv(.c) void { + const self: *WebRTCBridge = @ptrCast(@alignCast(ptr orelse return)); + self.registerChannel(dc_id); + } + + fn dcClosedCallback(dc_id: c_int, ptr: ?*anyopaque) callconv(.c) void { + const self: *WebRTCBridge = @ptrCast(@alignCast(ptr orelse return)); + // Close the transport + if (self.channel_transports.fetchRemove(dc_id)) |entry| { + entry.value.state = .closed; + // Don't deinit — P2P layer still holds the Transport vtable reference. + // It'll be cleaned up when P2P removes the peer connection. + } + if (self.pending_channels.fetchRemove(dc_id)) |entry| { + const pending = entry.value; + log.info("DataChannel {d} closed (peer '{s}')", .{ dc_id, pending.remote_signaling_id }); + // Queue peer for reconnection (under callback mutex — this runs on rustrtc thread) + self.callback_mutex.lock(); + defer self.callback_mutex.unlock(); + // Keep peer name for reconnection instead of freeing + self.pending_reconnects.append(self.allocator, pending.remote_signaling_id) catch { + self.allocator.free(pending.remote_signaling_id); + }; + } + } + + fn dcMessageCallback(dc_id: c_int, message: [*]const u8, size: c_int, ptr: ?*anyopaque) callconv(.c) void { + const self: *WebRTCBridge = @ptrCast(@alignCast(ptr orelse return)); + if (size <= 0) return; // ignore string messages + const data = message[0..@as(usize, @intCast(size))]; + + // All queue mutations must be under the callback mutex (this runs on rustrtc's thread) + self.callback_mutex.lock(); + defer self.callback_mutex.unlock(); + + // Route direct messages (0xFF prefix) to separate queue — bypass P2P framing + if (data.len > 1 and data[0] == 0xFF) { + // Enforce queue limit — drop newest (backpressure signal) + if (self.direct_recv_queue.items.len >= MAX_DIRECT_QUEUE) { + log.warn("direct_recv_queue full ({d}), dropping incoming message", .{MAX_DIRECT_QUEUE}); + return; + } + const dm = DirectMessage{ + .app_id = data[1], + .payload = self.allocator.dupe(u8, data[2..]) catch return, + }; + self.direct_recv_queue.append(self.allocator, dm) catch { + self.allocator.free(dm.payload); + }; + return; + } + + // P2P framed message — push to transport receive queue + if (self.channel_transports.get(dc_id)) |bct| { + bct.pushMessage(data); + } + } +}; + +// ============================================================================ +// Helpers +// ============================================================================ + +/// Derive a deterministic PeerId from a signaling peer name string. +/// Uses BLAKE2b-256 so the same signaling name always maps to the same PeerId. +fn peerIdFromSignalingId(signaling_id: []const u8) PeerId { + const Blake2b256 = std.crypto.hash.blake2.Blake2b256; + var hash: [32]u8 = undefined; + Blake2b256.hash(signaling_id, &hash, .{}); + return PeerId{ .bytes = hash }; +} + +// ============================================================================ +// JSON parsing (minimal, no external deps) +// ============================================================================ + +pub fn parseSignalingMessage(data: []const u8) ?SignalingMsg { + var msg = SignalingMsg{ .msg_type = .unknown }; + + if (jsonGetString(data, "type")) |t| { + if (std.mem.eql(u8, t, "offer")) msg.msg_type = .offer + else if (std.mem.eql(u8, t, "answer")) msg.msg_type = .answer + else if (std.mem.eql(u8, t, "candidate")) msg.msg_type = .candidate + else if (std.mem.eql(u8, t, "registered")) msg.msg_type = .registered + else if (std.mem.eql(u8, t, "pong")) msg.msg_type = .pong + else if (std.mem.eql(u8, t, "error")) msg.msg_type = .@"error"; + } else return null; + + msg.from = jsonGetString(data, "from"); + msg.sdp = jsonGetString(data, "sdp"); + msg.candidate = jsonGetString(data, "candidate"); + msg.sdp_mid = jsonGetString(data, "sdpMid"); + msg.peer_id = jsonGetString(data, "peerId"); + msg.message = jsonGetString(data, "message"); + + return msg; +} + +/// Simple JSON string field extractor. Finds `"key":"value"` and returns value. +/// Handles escaped quotes within string values. +pub fn jsonGetString(json: []const u8, key: []const u8) ?[]const u8 { + var i: usize = 0; + while (i + key.len + 4 < json.len) : (i += 1) { + if (json[i] == '"' and + i + 1 + key.len + 1 < json.len and + std.mem.eql(u8, json[i + 1 .. i + 1 + key.len], key) and + json[i + 1 + key.len] == '"') + { + var j = i + 1 + key.len + 1; + while (j < json.len and (json[j] == ':' or json[j] == ' ')) : (j += 1) {} + if (j < json.len and json[j] == '"') { + const start = j + 1; + var end = start; + // Skip escaped characters (e.g. \", \\, \r, \n) + while (end < json.len) : (end += 1) { + if (json[end] == '\\' and end + 1 < json.len) { + end += 1; // skip escaped char + } else if (json[end] == '"') { + break; + } + } + if (end < json.len) return json[start..end]; + } + } + } + return null; +} + +/// Unescape a JSON string value: converts \r, \n, \t, \\, \" to their byte values. +/// Returns an allocator-owned null-terminated slice. Caller must free. +fn jsonUnescape(allocator: Allocator, s: []const u8) ![:0]u8 { + var out: std.ArrayListUnmanaged(u8) = .{}; + defer out.deinit(allocator); + try out.ensureTotalCapacity(allocator, s.len); + + var i: usize = 0; + while (i < s.len) { + if (s[i] == '\\' and i + 1 < s.len) { + switch (s[i + 1]) { + 'r' => try out.append(allocator, '\r'), + 'n' => try out.append(allocator, '\n'), + 't' => try out.append(allocator, '\t'), + '"' => try out.append(allocator, '"'), + '\\' => try out.append(allocator, '\\'), + '/' => try out.append(allocator, '/'), + else => { + try out.append(allocator, s[i]); + try out.append(allocator, s[i + 1]); + }, + } + i += 2; + } else { + try out.append(allocator, s[i]); + i += 1; + } + } + + return try out.toOwnedSliceSentinel(allocator, 0); +} + +/// Write a string with JSON escaping (handles \r, \n, \t, \\, \", and control chars). +fn jsonWriteEscaped(writer: anytype, s: []const u8) !void { + for (s) |c| { + switch (c) { + '"' => try writer.writeAll("\\\""), + '\\' => try writer.writeAll("\\\\"), + '\n' => try writer.writeAll("\\n"), + '\r' => try writer.writeAll("\\r"), + '\t' => try writer.writeAll("\\t"), + else => { + if (c < 0x20) { + try writer.print("\\u{x:0>4}", .{c}); + } else { + try writer.writeByte(c); + } + }, + } + } +} diff --git a/src/platform/webrtc_dht_signaling.zig b/src/platform/webrtc_dht_signaling.zig new file mode 100644 index 0000000..5d4e4c7 --- /dev/null +++ b/src/platform/webrtc_dht_signaling.zig @@ -0,0 +1,653 @@ +//! DHT-based WebRTC Signaling +//! +//! Exchanges WebRTC SDP offers/answers and ICE candidates via the DHT, +//! eliminating the need for a separate signaling server. +//! +//! Pattern: Both peers derive the same base signaling key from their public keys +//! (order-independent). Each peer stores its messages at a key derived from +//! the base key + their own pubkey, and reads the other peer's messages from +//! the base key + the other's pubkey. This prevents collisions. +//! +//! Flow (Alice → Bob): +//! 1. Alice computes signaling_key = computeSignalingKey(alice_pk, bob_pk) +//! 2. Alice stores her offer at SHA-256(signaling_key || alice_pk || "offer") +//! 3. Bob polls for Alice's offer at the same key +//! 4. Bob stores his answer at SHA-256(signaling_key || bob_pk || "answer") +//! 5. Alice polls for Bob's answer at the same key +//! 6. ICE candidates exchanged similarly with versioned keys + +const std = @import("std"); +const platform_time = @import("time.zig"); +const Allocator = std.mem.Allocator; +const signaling = @import("webrtc_signaling.zig"); +pub const SignalingMessage = signaling.SignalingMessage; +pub const MessageType = signaling.MessageType; +pub const computeSignalingKey = signaling.computeSignalingKey; + +/// DHT interface — caller provides store/find functions. +/// Avoids circular dependency with the p2p module. +pub const DHTOps = struct { + context: *anyopaque, + storeFn: *const fn (ctx: *anyopaque, key: [32]u8, value: []const u8, ttl: u32) anyerror!void, + findFn: *const fn (ctx: *anyopaque, key: [32]u8) anyerror!?[]u8, +}; + +/// Default TTL for signaling messages (60 seconds — connection should complete faster). +pub const DEFAULT_SIGNALING_TTL: u32 = 60; + +/// Default timeout for waiting for a signaling response (30 seconds). +pub const DEFAULT_WAIT_TIMEOUT_MS: u64 = 30_000; + +/// Default poll interval when waiting for signaling messages. +pub const DEFAULT_POLL_INTERVAL_MS: u64 = 200; + +/// Derive a directional signaling DHT key for a specific message type. +/// key = SHA-256(signaling_key || publisher_pubkey || label) +/// This ensures the offerer and answerer store at different keys. +pub fn deriveSignalingSubkey(signaling_key: [32]u8, publisher_pubkey: [32]u8, label: []const u8) [32]u8 { + var hasher = std.crypto.hash.sha2.Sha256.init(.{}); + hasher.update(&signaling_key); + hasher.update(&publisher_pubkey); + hasher.update(label); + return hasher.finalResult(); +} + +/// Derive a versioned ICE candidate DHT key from a base ICE key + version number. +pub fn deriveIceVersionKey(base_ice_key: [32]u8, version: u32) [32]u8 { + var hasher = std.crypto.hash.sha2.Sha256.init(.{}); + hasher.update(&base_ice_key); + var version_bytes: [4]u8 = undefined; + std.mem.writeInt(u32, &version_bytes, version, .little); + hasher.update(&version_bytes); + return hasher.finalResult(); +} + +/// WebRTC DHT Signaling session — manages SDP/ICE exchange for one connection. +pub const SignalingSession = struct { + allocator: Allocator, + dht: DHTOps, + our_pubkey: [32]u8, + their_pubkey: [32]u8, + /// Pre-computed base signaling key (order-independent). + signaling_key: [32]u8, + /// TTL for DHT store operations. + ttl: u32, + /// Next version to store when using trickle ICE (storeCandidateBatch). + ice_send_version: u32 = 0, + /// Next version to read when using trickle ICE (findNextCandidateBatch). + ice_recv_version: u32 = 0, + + pub fn init( + allocator: Allocator, + dht: DHTOps, + our_pubkey: [32]u8, + their_pubkey: [32]u8, + ) SignalingSession { + return .{ + .allocator = allocator, + .dht = dht, + .our_pubkey = our_pubkey, + .their_pubkey = their_pubkey, + .signaling_key = computeSignalingKey(our_pubkey, their_pubkey), + .ttl = DEFAULT_SIGNALING_TTL, + }; + } + + // ========================================================================= + // Store operations (publish our signaling data) + // ========================================================================= + + /// Store our SDP offer in the DHT. + pub fn storeOffer(self: *SignalingSession, sdp_payload: []const u8) !void { + const key = deriveSignalingSubkey(self.signaling_key, self.our_pubkey, "offer"); + const msg = SignalingMessage{ + .msg_type = .offer, + .from_pubkey = self.our_pubkey, + .timestamp_ms = platform_time.milliTimestamp(), + .payload = sdp_payload, + .signature = [_]u8{0} ** 64, // TODO: sign with Ed25519 + }; + const wire = try msg.serialize(self.allocator); + defer self.allocator.free(wire); + try self.dht.storeFn(self.dht.context, key, wire, self.ttl); + } + + /// Store our SDP answer in the DHT. + pub fn storeAnswer(self: *SignalingSession, sdp_payload: []const u8) !void { + const key = deriveSignalingSubkey(self.signaling_key, self.our_pubkey, "answer"); + const msg = SignalingMessage{ + .msg_type = .answer, + .from_pubkey = self.our_pubkey, + .timestamp_ms = platform_time.milliTimestamp(), + .payload = sdp_payload, + .signature = [_]u8{0} ** 64, // TODO: sign with Ed25519 + }; + const wire = try msg.serialize(self.allocator); + defer self.allocator.free(wire); + try self.dht.storeFn(self.dht.context, key, wire, self.ttl); + } + + /// Store our ICE candidates in the DHT (batched as one message). + pub fn storeCandidates(self: *SignalingSession, candidates_payload: []const u8) !void { + const key = deriveSignalingSubkey(self.signaling_key, self.our_pubkey, "ice"); + const msg = SignalingMessage{ + .msg_type = .ice_candidate, + .from_pubkey = self.our_pubkey, + .timestamp_ms = platform_time.milliTimestamp(), + .payload = candidates_payload, + .signature = [_]u8{0} ** 64, + }; + const wire = try msg.serialize(self.allocator); + defer self.allocator.free(wire); + try self.dht.storeFn(self.dht.context, key, wire, self.ttl); + } + + /// Store a batch of ICE candidates at a versioned key (trickle ICE). + /// Each call increments the version, so candidates are stored at + /// ice-0, ice-1, etc. The peer reads them in order via findNextCandidateBatch. + pub fn storeCandidateBatch(self: *SignalingSession, candidates_payload: []const u8) !void { + const base_key = deriveSignalingSubkey(self.signaling_key, self.our_pubkey, "ice"); + const versioned_key = deriveIceVersionKey(base_key, self.ice_send_version); + const msg = SignalingMessage{ + .msg_type = .ice_candidate, + .from_pubkey = self.our_pubkey, + .timestamp_ms = platform_time.milliTimestamp(), + .payload = candidates_payload, + .signature = [_]u8{0} ** 64, + }; + const wire = try msg.serialize(self.allocator); + defer self.allocator.free(wire); + try self.dht.storeFn(self.dht.context, versioned_key, wire, self.ttl); + self.ice_send_version += 1; + } + + // ========================================================================= + // Find operations (retrieve peer's signaling data) + // ========================================================================= + + /// Find the peer's SDP offer in the DHT (non-blocking). + /// Returns the deserialized SignalingMessage or null if not found. + /// Caller does NOT own the payload — it borrows from the returned wire data. + pub fn findOffer(self: *SignalingSession) !?SignalingMessage { + const key = deriveSignalingSubkey(self.signaling_key, self.their_pubkey, "offer"); + return self.findMessage(key); + } + + /// Find the peer's SDP answer in the DHT (non-blocking). + pub fn findAnswer(self: *SignalingSession) !?SignalingMessage { + const key = deriveSignalingSubkey(self.signaling_key, self.their_pubkey, "answer"); + return self.findMessage(key); + } + + /// Find the peer's ICE candidates in the DHT (non-blocking). + pub fn findCandidates(self: *SignalingSession) !?SignalingMessage { + const key = deriveSignalingSubkey(self.signaling_key, self.their_pubkey, "ice"); + return self.findMessage(key); + } + + /// Find the next batch of trickle ICE candidates from the peer (non-blocking). + /// Returns the next unseen batch, or null if no new batch is available. + /// Automatically advances the receive version on success. + pub fn findNextCandidateBatch(self: *SignalingSession) !?SignalingMessage { + const base_key = deriveSignalingSubkey(self.signaling_key, self.their_pubkey, "ice"); + const versioned_key = deriveIceVersionKey(base_key, self.ice_recv_version); + const result = try self.findMessage(versioned_key); + if (result != null) { + self.ice_recv_version += 1; + } + return result; + } + + /// Drain all available trickle ICE candidate batches from the peer (non-blocking). + /// Returns all unseen batches as a slice. Caller owns the returned slice. + /// Advances the receive version past all returned batches. + pub fn drainCandidateBatches(self: *SignalingSession) ![]SignalingMessage { + var batches: std.ArrayList(SignalingMessage) = .{}; + errdefer batches.deinit(self.allocator); + while (try self.findNextCandidateBatch()) |msg| { + try batches.append(self.allocator, msg); + } + return batches.toOwnedSlice(self.allocator); + } + + fn findMessage(self: *SignalingSession, key: [32]u8) !?SignalingMessage { + const value = self.dht.findFn(self.dht.context, key) catch return null; + if (value) |v| { + defer self.allocator.free(v); + return SignalingMessage.deserialize(v) catch null; + } + return null; + } + + // ========================================================================= + // Blocking wait operations (poll-based) + // ========================================================================= + + /// Wait for the peer's SDP offer (blocking with timeout). + /// Polls the DHT at regular intervals. MUST call p2p.update() externally + /// if the DHT requires it for network I/O. + pub fn waitForOffer(self: *SignalingSession, timeout_ms: u64) !?SignalingMessage { + const key = deriveSignalingSubkey(self.signaling_key, self.their_pubkey, "offer"); + return self.waitForMessage(key, timeout_ms); + } + + /// Wait for the peer's SDP answer (blocking with timeout). + pub fn waitForAnswer(self: *SignalingSession, timeout_ms: u64) !?SignalingMessage { + const key = deriveSignalingSubkey(self.signaling_key, self.their_pubkey, "answer"); + return self.waitForMessage(key, timeout_ms); + } + + /// Wait for the peer's ICE candidates (blocking with timeout). + pub fn waitForCandidates(self: *SignalingSession, timeout_ms: u64) !?SignalingMessage { + const key = deriveSignalingSubkey(self.signaling_key, self.their_pubkey, "ice"); + return self.waitForMessage(key, timeout_ms); + } + + /// Wait for the next trickle ICE candidate batch (blocking with timeout). + /// Returns the next unseen batch, or null on timeout. + pub fn waitForNextCandidateBatch(self: *SignalingSession, timeout_ms: u64) !?SignalingMessage { + var elapsed: u64 = 0; + while (elapsed < timeout_ms) { + if (try self.findNextCandidateBatch()) |msg| { + return msg; + } + platform_time.sleep(DEFAULT_POLL_INTERVAL_MS * std.time.ns_per_ms); + elapsed += DEFAULT_POLL_INTERVAL_MS; + } + return null; + } + + fn waitForMessage(self: *SignalingSession, key: [32]u8, timeout_ms: u64) !?SignalingMessage { + var elapsed: u64 = 0; + while (elapsed < timeout_ms) { + if (try self.findMessage(key)) |msg| { + return msg; + } + platform_time.sleep(DEFAULT_POLL_INTERVAL_MS * std.time.ns_per_ms); + elapsed += DEFAULT_POLL_INTERVAL_MS; + } + return null; + } +}; + +// ============================================================================ +// Tests +// ============================================================================ + +test "deriveSignalingSubkey: different labels produce different keys" { + const base = [_]u8{0xAA} ** 32; + const pubkey = [_]u8{0xBB} ** 32; + + const offer_key = deriveSignalingSubkey(base, pubkey, "offer"); + const answer_key = deriveSignalingSubkey(base, pubkey, "answer"); + const ice_key = deriveSignalingSubkey(base, pubkey, "ice"); + + try std.testing.expect(!std.mem.eql(u8, &offer_key, &answer_key)); + try std.testing.expect(!std.mem.eql(u8, &offer_key, &ice_key)); + try std.testing.expect(!std.mem.eql(u8, &answer_key, &ice_key)); +} + +test "deriveSignalingSubkey: different pubkeys produce different keys" { + const base = [_]u8{0xAA} ** 32; + const alice_pk = [_]u8{0x01} ** 32; + const bob_pk = [_]u8{0x02} ** 32; + + const alice_offer = deriveSignalingSubkey(base, alice_pk, "offer"); + const bob_offer = deriveSignalingSubkey(base, bob_pk, "offer"); + + try std.testing.expect(!std.mem.eql(u8, &alice_offer, &bob_offer)); +} + +test "SignalingSession: store and find with mock DHT" { + const allocator = std.testing.allocator; + + // Simple in-memory DHT mock + const MockDHT = struct { + store: std.AutoHashMap([32]u8, []u8), + allocator: Allocator, + + fn init(alloc: Allocator) @This() { + return .{ + .store = std.AutoHashMap([32]u8, []u8).init(alloc), + .allocator = alloc, + }; + } + + fn deinit(self: *@This()) void { + var iter = self.store.valueIterator(); + while (iter.next()) |v| { + self.allocator.free(v.*); + } + self.store.deinit(); + } + + fn storeFn(ctx: *anyopaque, key: [32]u8, value: []const u8, _: u32) anyerror!void { + const self: *@This() = @ptrCast(@alignCast(ctx)); + // Replace existing value if any + if (self.store.fetchRemove(key)) |kv| { + self.allocator.free(kv.value); + } + const copy = try self.allocator.dupe(u8, value); + try self.store.put(key, copy); + } + + fn findFn(ctx: *anyopaque, key: [32]u8) anyerror!?[]u8 { + const self: *@This() = @ptrCast(@alignCast(ctx)); + if (self.store.get(key)) |v| { + return try self.allocator.dupe(u8, v); + } + return null; + } + + fn ops(self: *@This()) DHTOps { + return .{ + .context = @ptrCast(self), + .storeFn = storeFn, + .findFn = findFn, + }; + } + }; + + var mock = MockDHT.init(allocator); + defer mock.deinit(); + + const alice_pk = [_]u8{0x01} ** 32; + const bob_pk = [_]u8{0x02} ** 32; + + // Alice's session + var alice = SignalingSession.init(allocator, mock.ops(), alice_pk, bob_pk); + + // Bob's session + var bob = SignalingSession.init(allocator, mock.ops(), bob_pk, alice_pk); + + // Verify both compute the same signaling key + try std.testing.expectEqualSlices(u8, &alice.signaling_key, &bob.signaling_key); + + // Alice stores her offer + try alice.storeOffer("v=0\r\no=alice SDP"); + + // Bob finds Alice's offer + const offer = try bob.findOffer(); + try std.testing.expect(offer != null); + try std.testing.expectEqual(MessageType.offer, offer.?.msg_type); + try std.testing.expectEqualSlices(u8, &alice_pk, &offer.?.from_pubkey); + + // Bob stores his answer + try bob.storeAnswer("v=0\r\no=bob SDP answer"); + + // Alice finds Bob's answer + const answer = try alice.findAnswer(); + try std.testing.expect(answer != null); + try std.testing.expectEqual(MessageType.answer, answer.?.msg_type); + try std.testing.expectEqualSlices(u8, &bob_pk, &answer.?.from_pubkey); + + // Alice stores her ICE candidates + try alice.storeCandidates("candidate:1 1 UDP 2130706431 127.0.0.1 12345 typ host"); + + // Bob finds Alice's candidates + const ice = try bob.findCandidates(); + try std.testing.expect(ice != null); + try std.testing.expectEqual(MessageType.ice_candidate, ice.?.msg_type); + + // Verify Alice can't find an offer from Bob (Bob never stored one) + const wrong = try alice.findOffer(); + // alice.findOffer() looks for bob's offer, but Bob only stored an answer + try std.testing.expect(wrong == null); +} + +test "SignalingSession: findOffer returns null when DHT empty" { + const allocator = std.testing.allocator; + + const EmptyDHT = struct { + fn storeFn(_: *anyopaque, _: [32]u8, _: []const u8, _: u32) anyerror!void {} + fn findFn(_: *anyopaque, _: [32]u8) anyerror!?[]u8 { + return null; + } + }; + + var dummy: u8 = 0; + var session = SignalingSession.init(allocator, .{ + .context = @ptrCast(&dummy), + .storeFn = EmptyDHT.storeFn, + .findFn = EmptyDHT.findFn, + }, [_]u8{0x01} ** 32, [_]u8{0x02} ** 32); + + const result = try session.findOffer(); + try std.testing.expect(result == null); +} + +test "deriveIceVersionKey: different versions produce different keys" { + const base = [_]u8{0xCC} ** 32; + const key0 = deriveIceVersionKey(base, 0); + const key1 = deriveIceVersionKey(base, 1); + const key2 = deriveIceVersionKey(base, 2); + + try std.testing.expect(!std.mem.eql(u8, &key0, &key1)); + try std.testing.expect(!std.mem.eql(u8, &key0, &key2)); + try std.testing.expect(!std.mem.eql(u8, &key1, &key2)); +} + +test "trickle ICE: store and find versioned candidate batches" { + const allocator = std.testing.allocator; + + const MockDHT = struct { + store: std.AutoHashMap([32]u8, []u8), + alloc: Allocator, + + fn init(alloc: Allocator) @This() { + return .{ + .store = std.AutoHashMap([32]u8, []u8).init(alloc), + .alloc = alloc, + }; + } + + fn deinit(self: *@This()) void { + var iter = self.store.valueIterator(); + while (iter.next()) |v| self.alloc.free(v.*); + self.store.deinit(); + } + + fn storeFn(ctx: *anyopaque, key: [32]u8, value: []const u8, _: u32) anyerror!void { + const self: *@This() = @ptrCast(@alignCast(ctx)); + if (self.store.fetchRemove(key)) |kv| self.alloc.free(kv.value); + const copy = try self.alloc.dupe(u8, value); + try self.store.put(key, copy); + } + + fn findFn(ctx: *anyopaque, key: [32]u8) anyerror!?[]u8 { + const self: *@This() = @ptrCast(@alignCast(ctx)); + if (self.store.get(key)) |v| return try self.alloc.dupe(u8, v); + return null; + } + + fn ops(self: *@This()) DHTOps { + return .{ .context = @ptrCast(self), .storeFn = storeFn, .findFn = findFn }; + } + }; + + var mock = MockDHT.init(allocator); + defer mock.deinit(); + + const alice_pk = [_]u8{0x01} ** 32; + const bob_pk = [_]u8{0x02} ** 32; + + var alice = SignalingSession.init(allocator, mock.ops(), alice_pk, bob_pk); + var bob = SignalingSession.init(allocator, mock.ops(), bob_pk, alice_pk); + + // Alice stores 3 batches of trickle ICE candidates + try alice.storeCandidateBatch("candidate:1 1 UDP 2130706431 192.168.1.1 10000 typ host"); + try alice.storeCandidateBatch("candidate:2 1 UDP 1694498815 10.0.0.1 10001 typ srflx"); + try alice.storeCandidateBatch("candidate:3 1 UDP 16777215 1.2.3.4 10002 typ relay"); + + // Verify Alice's send version advanced + try std.testing.expectEqual(@as(u32, 3), alice.ice_send_version); + + // Bob hasn't read any yet + try std.testing.expectEqual(@as(u32, 0), bob.ice_recv_version); + + // Bob reads batch 0 + const batch0 = try bob.findNextCandidateBatch(); + try std.testing.expect(batch0 != null); + try std.testing.expectEqual(MessageType.ice_candidate, batch0.?.msg_type); + try std.testing.expectEqual(@as(u32, 1), bob.ice_recv_version); + + // Bob reads batch 1 + const batch1 = try bob.findNextCandidateBatch(); + try std.testing.expect(batch1 != null); + try std.testing.expectEqual(@as(u32, 2), bob.ice_recv_version); + + // Bob reads batch 2 + const batch2 = try bob.findNextCandidateBatch(); + try std.testing.expect(batch2 != null); + try std.testing.expectEqual(@as(u32, 3), bob.ice_recv_version); + + // No more batches + const batch3 = try bob.findNextCandidateBatch(); + try std.testing.expect(batch3 == null); + // Version should NOT advance on null + try std.testing.expectEqual(@as(u32, 3), bob.ice_recv_version); +} + +test "trickle ICE: drainCandidateBatches returns all unseen" { + const allocator = std.testing.allocator; + + const MockDHT = struct { + store: std.AutoHashMap([32]u8, []u8), + alloc: Allocator, + + fn init(alloc: Allocator) @This() { + return .{ + .store = std.AutoHashMap([32]u8, []u8).init(alloc), + .alloc = alloc, + }; + } + + fn deinit(self: *@This()) void { + var iter = self.store.valueIterator(); + while (iter.next()) |v| self.alloc.free(v.*); + self.store.deinit(); + } + + fn storeFn(ctx: *anyopaque, key: [32]u8, value: []const u8, _: u32) anyerror!void { + const self: *@This() = @ptrCast(@alignCast(ctx)); + if (self.store.fetchRemove(key)) |kv| self.alloc.free(kv.value); + const copy = try self.alloc.dupe(u8, value); + try self.store.put(key, copy); + } + + fn findFn(ctx: *anyopaque, key: [32]u8) anyerror!?[]u8 { + const self: *@This() = @ptrCast(@alignCast(ctx)); + if (self.store.get(key)) |v| return try self.alloc.dupe(u8, v); + return null; + } + + fn ops(self: *@This()) DHTOps { + return .{ .context = @ptrCast(self), .storeFn = storeFn, .findFn = findFn }; + } + }; + + var mock = MockDHT.init(allocator); + defer mock.deinit(); + + const alice_pk = [_]u8{0x01} ** 32; + const bob_pk = [_]u8{0x02} ** 32; + + var alice = SignalingSession.init(allocator, mock.ops(), alice_pk, bob_pk); + var bob = SignalingSession.init(allocator, mock.ops(), bob_pk, alice_pk); + + // Alice stores 4 batches + try alice.storeCandidateBatch("candidate:host"); + try alice.storeCandidateBatch("candidate:srflx"); + try alice.storeCandidateBatch("candidate:relay"); + try alice.storeCandidateBatch("candidate:prflx"); + + // Bob drains all at once + const batches = try bob.drainCandidateBatches(); + defer allocator.free(batches); + + try std.testing.expectEqual(@as(usize, 4), batches.len); + try std.testing.expectEqual(@as(u32, 4), bob.ice_recv_version); + + // Drain again — should be empty + const empty = try bob.drainCandidateBatches(); + defer allocator.free(empty); + try std.testing.expectEqual(@as(usize, 0), empty.len); +} + +test "trickle ICE: bidirectional exchange" { + const allocator = std.testing.allocator; + + const MockDHT = struct { + store: std.AutoHashMap([32]u8, []u8), + alloc: Allocator, + + fn init(alloc: Allocator) @This() { + return .{ + .store = std.AutoHashMap([32]u8, []u8).init(alloc), + .alloc = alloc, + }; + } + + fn deinit(self: *@This()) void { + var iter = self.store.valueIterator(); + while (iter.next()) |v| self.alloc.free(v.*); + self.store.deinit(); + } + + fn storeFn(ctx: *anyopaque, key: [32]u8, value: []const u8, _: u32) anyerror!void { + const self: *@This() = @ptrCast(@alignCast(ctx)); + if (self.store.fetchRemove(key)) |kv| self.alloc.free(kv.value); + const copy = try self.alloc.dupe(u8, value); + try self.store.put(key, copy); + } + + fn findFn(ctx: *anyopaque, key: [32]u8) anyerror!?[]u8 { + const self: *@This() = @ptrCast(@alignCast(ctx)); + if (self.store.get(key)) |v| return try self.alloc.dupe(u8, v); + return null; + } + + fn ops(self: *@This()) DHTOps { + return .{ .context = @ptrCast(self), .storeFn = storeFn, .findFn = findFn }; + } + }; + + var mock = MockDHT.init(allocator); + defer mock.deinit(); + + const alice_pk = [_]u8{0x01} ** 32; + const bob_pk = [_]u8{0x02} ** 32; + + var alice = SignalingSession.init(allocator, mock.ops(), alice_pk, bob_pk); + var bob = SignalingSession.init(allocator, mock.ops(), bob_pk, alice_pk); + + // Both sides trickle candidates independently + try alice.storeCandidateBatch("alice-candidate:host"); + try bob.storeCandidateBatch("bob-candidate:host"); + try alice.storeCandidateBatch("alice-candidate:srflx"); + try bob.storeCandidateBatch("bob-candidate:srflx"); + + // Alice reads Bob's candidates + const alice_batches = try alice.drainCandidateBatches(); + defer allocator.free(alice_batches); + try std.testing.expectEqual(@as(usize, 2), alice_batches.len); + // Verify they came from Bob + for (alice_batches) |batch| { + try std.testing.expectEqualSlices(u8, &bob_pk, &batch.from_pubkey); + } + + // Bob reads Alice's candidates + const bob_batches = try bob.drainCandidateBatches(); + defer allocator.free(bob_batches); + try std.testing.expectEqual(@as(usize, 2), bob_batches.len); + // Verify they came from Alice + for (bob_batches) |batch| { + try std.testing.expectEqualSlices(u8, &alice_pk, &batch.from_pubkey); + } + + // Both versions advanced independently + try std.testing.expectEqual(@as(u32, 2), alice.ice_send_version); + try std.testing.expectEqual(@as(u32, 2), alice.ice_recv_version); + try std.testing.expectEqual(@as(u32, 2), bob.ice_send_version); + try std.testing.expectEqual(@as(u32, 2), bob.ice_recv_version); +} diff --git a/src/platform/webrtc_native.zig b/src/platform/webrtc_native.zig new file mode 100644 index 0000000..fc8a851 --- /dev/null +++ b/src/platform/webrtc_native.zig @@ -0,0 +1,880 @@ +//! Native WebRTC transport via runtime-loaded libdatachannel C API. +//! +//! Provides DataChannel-based transport for peer-to-peer communication. +//! The library is loaded at runtime via dlopen — if the dylib is present +//! next to the executable (or in WEBRTC_LIB_PATH), WebRTC is available. +//! If not, the binary still works with TCP/UDP only. +//! +//! Callbacks from the WebRTC library fire from an internal thread — all +//! state is accessed atomically or via mutex-protected queues. + +const std = @import("std"); +const Mutex = @import("sync").Mutex; +const builtin = @import("builtin"); +const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64; +const core = @import("core"); +const CoreTransport = core.transport.Transport; +const TransportState = core.transport.TransportState; +const TransportMode = core.transport.TransportMode; +const CoreError = core.errors.Error; + +// ============================================================================ +// libdatachannel C API bindings — runtime-loaded via dlopen +// ============================================================================ + +pub const rtc = struct { + // Error codes + pub const ERR_SUCCESS: c_int = 0; + pub const ERR_INVALID: c_int = -1; + pub const ERR_FAILURE: c_int = -2; + pub const ERR_NOT_AVAIL: c_int = -3; + pub const ERR_TOO_SMALL: c_int = -4; + + // State enums + pub const State = enum(c_int) { + new = 0, + connecting = 1, + connected = 2, + disconnected = 3, + failed = 4, + closed = 5, + }; + + pub const IceState = enum(c_int) { + new = 0, + checking = 1, + connected = 2, + completed = 3, + failed = 4, + disconnected = 5, + closed = 6, + }; + + pub const GatheringState = enum(c_int) { + new = 0, + in_progress = 1, + complete = 2, + }; + + pub const LogLevel = enum(c_int) { + none = 0, + fatal = 1, + err = 2, + warning = 3, + info = 4, + debug = 5, + verbose = 6, + }; + + pub const CertificateType = enum(c_int) { + default = 0, + ecdsa = 1, + rsa = 2, + }; + + pub const TransportPolicy = enum(c_int) { + all = 0, + relay = 1, + }; + + // Callback function types + pub const DescriptionCallbackFunc = *const fn (pc: c_int, sdp: [*:0]const u8, sdp_type: [*:0]const u8, ptr: ?*anyopaque) callconv(.c) void; + pub const CandidateCallbackFunc = *const fn (pc: c_int, cand: [*:0]const u8, mid: [*:0]const u8, ptr: ?*anyopaque) callconv(.c) void; + pub const StateChangeCallbackFunc = *const fn (pc: c_int, state: c_int, ptr: ?*anyopaque) callconv(.c) void; + pub const GatheringStateCallbackFunc = *const fn (pc: c_int, state: c_int, ptr: ?*anyopaque) callconv(.c) void; + pub const DataChannelCallbackFunc = *const fn (pc: c_int, dc: c_int, ptr: ?*anyopaque) callconv(.c) void; + pub const OpenCallbackFunc = *const fn (id: c_int, ptr: ?*anyopaque) callconv(.c) void; + pub const ClosedCallbackFunc = *const fn (id: c_int, ptr: ?*anyopaque) callconv(.c) void; + pub const ErrorCallbackFunc = *const fn (id: c_int, err_msg: [*:0]const u8, ptr: ?*anyopaque) callconv(.c) void; + pub const MessageCallbackFunc = *const fn (id: c_int, message: [*]const u8, size: c_int, ptr: ?*anyopaque) callconv(.c) void; + pub const LogCallbackFunc = *const fn (level: c_int, message: [*:0]const u8) callconv(.c) void; + + // Configuration structs + pub const Configuration = extern struct { + iceServers: ?[*]const [*:0]const u8 = null, + iceServersCount: c_int = 0, + proxyServer: ?[*:0]const u8 = null, + bindAddress: ?[*:0]const u8 = null, + certificateType: CertificateType = .default, + iceTransportPolicy: TransportPolicy = .all, + enableIceTcp: bool = false, + enableIceUdpMux: bool = false, + disableAutoNegotiation: bool = false, + forceMediaTransport: bool = false, + portRangeBegin: u16 = 0, + portRangeEnd: u16 = 0, + mtu: c_int = 0, + maxMessageSize: c_int = 0, + }; + + pub const Reliability = extern struct { + unordered: bool = false, + unreliable: bool = false, + maxPacketLifeTime: c_uint = 0, + maxRetransmits: c_uint = 0, + }; + + pub const DataChannelInit = extern struct { + reliability: Reliability = .{}, + protocol: ?[*:0]const u8 = null, + negotiated: bool = false, + manualStream: bool = false, + stream: u16 = 0, + }; + + pub const SctpSettings = extern struct { + recvBufferSize: c_int = 0, + sendBufferSize: c_int = 0, + maxChunksOnQueue: c_int = 0, + initialCongestionWindow: c_int = 0, + maxBurst: c_int = 0, + congestionControlModule: c_int = 0, + delayedSackTimeMs: c_int = 0, + minRetransmitTimeoutMs: c_int = 0, + maxRetransmitTimeoutMs: c_int = 0, + initialRetransmitTimeoutMs: c_int = 0, + maxRetransmitAttempts: c_int = 0, + heartbeatIntervalMs: c_int = 0, + }; + + // ======================================================================== + // Runtime library loading + // ======================================================================== + + const lib_name: [:0]const u8 = switch (builtin.os.tag) { + .macos, .ios, .tvos, .watchos => "libdatachannel.dylib", + .windows => "datachannel.dll", + else => "libdatachannel.so", + }; + + /// Function pointer table — all symbols resolved from the dynamic library. + const Fns = struct { + // Global + rtcPreload: *const fn () callconv(.c) void, + rtcCleanup: *const fn () callconv(.c) void, + rtcInitLogger: *const fn (c_int, ?LogCallbackFunc) callconv(.c) void, + // User pointer + rtcSetUserPointer: *const fn (c_int, ?*anyopaque) callconv(.c) void, + rtcGetUserPointer: *const fn (c_int) callconv(.c) ?*anyopaque, + // PeerConnection + rtcCreatePeerConnection: *const fn (*const Configuration) callconv(.c) c_int, + rtcClosePeerConnection: *const fn (c_int) callconv(.c) c_int, + rtcDeletePeerConnection: *const fn (c_int) callconv(.c) c_int, + // PC callbacks + rtcSetLocalDescriptionCallback: *const fn (c_int, ?DescriptionCallbackFunc) callconv(.c) c_int, + rtcSetLocalCandidateCallback: *const fn (c_int, ?CandidateCallbackFunc) callconv(.c) c_int, + rtcSetStateChangeCallback: *const fn (c_int, ?StateChangeCallbackFunc) callconv(.c) c_int, + rtcSetGatheringStateChangeCallback: *const fn (c_int, ?GatheringStateCallbackFunc) callconv(.c) c_int, + rtcSetDataChannelCallback: *const fn (c_int, ?DataChannelCallbackFunc) callconv(.c) c_int, + // SDP + rtcSetLocalDescription: *const fn (c_int, ?[*:0]const u8) callconv(.c) c_int, + rtcSetRemoteDescription: *const fn (c_int, [*:0]const u8, ?[*:0]const u8) callconv(.c) c_int, + rtcAddRemoteCandidate: *const fn (c_int, [*:0]const u8, ?[*:0]const u8) callconv(.c) c_int, + rtcGetLocalDescription: *const fn (c_int, [*]u8, c_int) callconv(.c) c_int, + rtcGetRemoteDescription: *const fn (c_int, [*]u8, c_int) callconv(.c) c_int, + // DataChannel + rtcCreateDataChannel: *const fn (c_int, [*:0]const u8) callconv(.c) c_int, + rtcCreateDataChannelEx: *const fn (c_int, [*:0]const u8, *const DataChannelInit) callconv(.c) c_int, + rtcDeleteDataChannel: *const fn (c_int) callconv(.c) c_int, + // DC callbacks + rtcSetOpenCallback: *const fn (c_int, ?OpenCallbackFunc) callconv(.c) c_int, + rtcSetClosedCallback: *const fn (c_int, ?ClosedCallbackFunc) callconv(.c) c_int, + rtcSetErrorCallback: *const fn (c_int, ?ErrorCallbackFunc) callconv(.c) c_int, + rtcSetMessageCallback: *const fn (c_int, ?MessageCallbackFunc) callconv(.c) c_int, + // I/O + rtcSendMessage: *const fn (c_int, [*]const u8, c_int) callconv(.c) c_int, + rtcClose: *const fn (c_int) callconv(.c) c_int, + rtcDelete: *const fn (c_int) callconv(.c) c_int, + rtcIsOpen: *const fn (c_int) callconv(.c) bool, + rtcIsClosed: *const fn (c_int) callconv(.c) bool, + rtcGetBufferedAmount: *const fn (c_int) callconv(.c) c_int, + rtcReceiveMessage: *const fn (c_int, [*]u8, *c_int) callconv(.c) c_int, + // SCTP + rtcSetSctpSettings: *const fn (*const SctpSettings) callconv(.c) c_int, + // WebSocket signaling (optional — may not be present in all builds) + rtcWsConnect: ?*const fn ([*:0]const u8, [*:0]const u8) callconv(.c) c_int, + rtcWsDisconnect: ?*const fn (c_int) callconv(.c) c_int, + rtcWsSend: ?*const fn (c_int, [*]const u8, c_int) callconv(.c) c_int, + rtcWsRecv: ?*const fn (c_int, [*]u8, *c_int) callconv(.c) c_int, + rtcWsIsConnected: ?*const fn (c_int) callconv(.c) c_int, + }; + + var dynlib: if (is_wasm) ?void else ?std.DynLib = null; + var fns: Fns = undefined; + + /// Attempt to load the WebRTC library. Returns true if successful. + /// Search order: WEBRTC_LIB_PATH env var, next to executable, system default. + pub fn load() bool { + if (is_wasm) return false; // No dynamic library loading on WASM + + if (dynlib != null) return true; + + // 1. Try WEBRTC_LIB_PATH environment variable + if (std.posix.getenv("WEBRTC_LIB_PATH")) |env_path| { + if (tryOpen(env_path)) return true; + } + + // 2. Try next to the executable + if (tryLoadNextToExe()) return true; + + // 3. Try system default (dlopen search paths) + if (tryOpen(lib_name)) return true; + + return false; + } + + /// Whether the WebRTC library is loaded and available. + pub fn isAvailable() bool { + if (is_wasm) return false; + return dynlib != null; + } + + /// Unload the library (for cleanup). + pub fn unload() void { + if (is_wasm) return; + if (dynlib) |*lib| { + lib.close(); + dynlib = null; + } + } + + fn tryLoadNextToExe() bool { + if (is_wasm) return false; + var exe_path_buf: [std.fs.max_path_bytes]u8 = undefined; + const exe_path = std.fs.selfExePath(&exe_path_buf) catch return false; + const exe_dir = std.fs.path.dirname(exe_path) orelse return false; + + var lib_path_buf: [std.fs.max_path_bytes]u8 = undefined; + const lib_path = std.fmt.bufPrintZ(&lib_path_buf, "{s}/{s}", .{ exe_dir, lib_name }) catch return false; + return tryOpen(lib_path); + } + + fn tryOpen(path: [:0]const u8) bool { + if (is_wasm) return false; + var lib = std.DynLib.open(path) catch return false; + if (resolveAllSymbols(&lib)) |resolved| { + fns = resolved; + dynlib = lib; + return true; + } + lib.close(); + return false; + } + + fn resolveAllSymbols(lib: *std.DynLib) ?Fns { + if (is_wasm) return null; + var result: Fns = undefined; + inline for (std.meta.fields(Fns)) |field| { + const FieldType = field.type; + const type_info = @typeInfo(FieldType); + if (type_info == .optional) { + // Optional symbols: try lookup, set null if not found + @field(result, field.name) = lib.lookup(type_info.optional.child, field.name); + } else { + // Required symbols: fail if not found + @field(result, field.name) = lib.lookup(FieldType, field.name) orelse return null; + } + } + return result; + } + + // ======================================================================== + // Public wrapper functions — same call syntax as the old extern declarations + // ======================================================================== + + // Global + pub fn rtcPreload() void { + fns.rtcPreload(); + } + pub fn rtcCleanup() void { + fns.rtcCleanup(); + } + pub fn rtcInitLogger(level: LogLevel, cb: ?LogCallbackFunc) void { + fns.rtcInitLogger(@intFromEnum(level), cb); + } + + // User pointer + pub fn rtcSetUserPointer(id: c_int, ptr: ?*anyopaque) void { + fns.rtcSetUserPointer(id, ptr); + } + pub fn rtcGetUserPointer(id: c_int) ?*anyopaque { + return fns.rtcGetUserPointer(id); + } + + // PeerConnection + pub fn rtcCreatePeerConnection(config: *const Configuration) c_int { + return fns.rtcCreatePeerConnection(config); + } + pub fn rtcClosePeerConnection(pc: c_int) c_int { + return fns.rtcClosePeerConnection(pc); + } + pub fn rtcDeletePeerConnection(pc: c_int) c_int { + return fns.rtcDeletePeerConnection(pc); + } + + // PC callbacks + pub fn rtcSetLocalDescriptionCallback(pc: c_int, cb: ?DescriptionCallbackFunc) c_int { + return fns.rtcSetLocalDescriptionCallback(pc, cb); + } + pub fn rtcSetLocalCandidateCallback(pc: c_int, cb: ?CandidateCallbackFunc) c_int { + return fns.rtcSetLocalCandidateCallback(pc, cb); + } + pub fn rtcSetStateChangeCallback(pc: c_int, cb: ?StateChangeCallbackFunc) c_int { + return fns.rtcSetStateChangeCallback(pc, cb); + } + pub fn rtcSetGatheringStateChangeCallback(pc: c_int, cb: ?GatheringStateCallbackFunc) c_int { + return fns.rtcSetGatheringStateChangeCallback(pc, cb); + } + pub fn rtcSetDataChannelCallback(pc: c_int, cb: ?DataChannelCallbackFunc) c_int { + return fns.rtcSetDataChannelCallback(pc, cb); + } + + // SDP + pub fn rtcSetLocalDescription(pc: c_int, sdp_type: ?[*:0]const u8) c_int { + return fns.rtcSetLocalDescription(pc, sdp_type); + } + pub fn rtcSetRemoteDescription(pc: c_int, sdp: [*:0]const u8, sdp_type: ?[*:0]const u8) c_int { + return fns.rtcSetRemoteDescription(pc, sdp, sdp_type); + } + pub fn rtcAddRemoteCandidate(pc: c_int, cand: [*:0]const u8, mid: ?[*:0]const u8) c_int { + return fns.rtcAddRemoteCandidate(pc, cand, mid); + } + pub fn rtcGetLocalDescription(pc: c_int, buffer: [*]u8, size: c_int) c_int { + return fns.rtcGetLocalDescription(pc, buffer, size); + } + pub fn rtcGetRemoteDescription(pc: c_int, buffer: [*]u8, size: c_int) c_int { + return fns.rtcGetRemoteDescription(pc, buffer, size); + } + + // DataChannel + pub fn rtcCreateDataChannel(pc: c_int, label: [*:0]const u8) c_int { + return fns.rtcCreateDataChannel(pc, label); + } + pub fn rtcCreateDataChannelEx(pc: c_int, label: [*:0]const u8, init_cfg: *const DataChannelInit) c_int { + return fns.rtcCreateDataChannelEx(pc, label, init_cfg); + } + pub fn rtcDeleteDataChannel(dc: c_int) c_int { + return fns.rtcDeleteDataChannel(dc); + } + + // DC callbacks + pub fn rtcSetOpenCallback(id: c_int, cb: ?OpenCallbackFunc) c_int { + return fns.rtcSetOpenCallback(id, cb); + } + pub fn rtcSetClosedCallback(id: c_int, cb: ?ClosedCallbackFunc) c_int { + return fns.rtcSetClosedCallback(id, cb); + } + pub fn rtcSetErrorCallback(id: c_int, cb: ?ErrorCallbackFunc) c_int { + return fns.rtcSetErrorCallback(id, cb); + } + pub fn rtcSetMessageCallback(id: c_int, cb: ?MessageCallbackFunc) c_int { + return fns.rtcSetMessageCallback(id, cb); + } + + // I/O + pub fn rtcSendMessage(id: c_int, data: [*]const u8, size: c_int) c_int { + return fns.rtcSendMessage(id, data, size); + } + pub fn rtcClose(id: c_int) c_int { + return fns.rtcClose(id); + } + pub fn rtcDelete(id: c_int) c_int { + return fns.rtcDelete(id); + } + pub fn rtcIsOpen(id: c_int) bool { + return fns.rtcIsOpen(id); + } + pub fn rtcIsClosed(id: c_int) bool { + return fns.rtcIsClosed(id); + } + pub fn rtcGetBufferedAmount(id: c_int) c_int { + return fns.rtcGetBufferedAmount(id); + } + pub fn rtcReceiveMessage(id: c_int, buffer: [*]u8, size: *c_int) c_int { + return fns.rtcReceiveMessage(id, buffer, size); + } + + // SCTP + pub fn rtcSetSctpSettings(settings: *const SctpSettings) c_int { + return fns.rtcSetSctpSettings(settings); + } + + // WebSocket signaling + pub fn rtcWsConnect(url: [*:0]const u8, peer_id: [*:0]const u8) c_int { + if (fns.rtcWsConnect) |f| return f(url, peer_id); + return -1; + } + pub fn rtcWsDisconnect(ws_id: c_int) c_int { + if (fns.rtcWsDisconnect) |f| return f(ws_id); + return -1; + } + pub fn rtcWsSend(ws_id: c_int, message: [*]const u8, size: c_int) c_int { + if (fns.rtcWsSend) |f| return f(ws_id, message, size); + return -1; + } + pub fn rtcWsRecv(ws_id: c_int, buffer: [*]u8, size: *c_int) c_int { + if (fns.rtcWsRecv) |f| return f(ws_id, buffer, size); + return -1; + } + pub fn rtcWsIsConnected(ws_id: c_int) c_int { + if (fns.rtcWsIsConnected) |f| return f(ws_id); + return -1; + } + pub fn wsAvailable() bool { + return fns.rtcWsConnect != null; + } +}; + +// ============================================================================ +// ChannelState — thread-safe state shared between libdatachannel callbacks +// and the Zig update loop. +// ============================================================================ + +/// Maximum receive queue depth before dropping messages. +const MAX_RECV_QUEUE: usize = 256; +/// Maximum accumulated SDP/candidate string length. +const MAX_SDP_SIZE: usize = 8192; +/// Maximum number of ICE candidates to buffer. +const MAX_CANDIDATES: usize = 64; + +/// Thread-safe state for a single WebRTC DataChannel. +/// libdatachannel callbacks write from an internal thread; +/// the Zig update loop reads from the main thread. +pub const ChannelState = struct { + /// PeerConnection id from libdatachannel + pc_id: c_int, + /// DataChannel id from libdatachannel (-1 if not yet created/received) + dc_id: std.atomic.Value(c_int), + /// Connection state (atomic for lock-free reads) + state: std.atomic.Value(rtc.State), + /// Gathering state (atomic for lock-free reads) + gathering_state: std.atomic.Value(rtc.GatheringState), + /// DataChannel open flag + dc_open: std.atomic.Value(bool), + /// Error message (null if no error) + last_error: ?[]const u8, + /// Mutex for recv_queue, local_sdp, local_candidates, last_error + mutex: Mutex, + /// Received messages queue (SPSC: callback thread pushes, update loop pops) + recv_queue: std.ArrayListUnmanaged(RecvMessage), + /// Local SDP (set by description callback) + local_sdp: ?[]u8, + /// Local SDP type ("offer" or "answer") + local_sdp_type: ?[]u8, + /// Buffered local ICE candidates + local_candidates: std.ArrayListUnmanaged([]u8), + /// Whether ICE gathering is complete + gathering_complete: std.atomic.Value(bool), + /// Allocator for dynamic data + allocator: std.mem.Allocator, + + pub const RecvMessage = struct { + data: []u8, + }; + + pub fn init(allocator: std.mem.Allocator, pc_id: c_int) ChannelState { + return .{ + .pc_id = pc_id, + .dc_id = std.atomic.Value(c_int).init(-1), + .state = std.atomic.Value(rtc.State).init(.new), + .gathering_state = std.atomic.Value(rtc.GatheringState).init(.new), + .dc_open = std.atomic.Value(bool).init(false), + .last_error = null, + .mutex = .{}, + .recv_queue = .{}, + .local_sdp = null, + .local_sdp_type = null, + .local_candidates = .{}, + .gathering_complete = std.atomic.Value(bool).init(false), + .allocator = allocator, + }; + } + + pub fn deinit(self: *ChannelState) void { + self.mutex.lock(); + defer self.mutex.unlock(); + + for (self.recv_queue.items) |msg| { + self.allocator.free(msg.data); + } + self.recv_queue.deinit(self.allocator); + + if (self.local_sdp) |sdp| self.allocator.free(sdp); + if (self.local_sdp_type) |t| self.allocator.free(t); + + for (self.local_candidates.items) |cand| { + self.allocator.free(cand); + } + self.local_candidates.deinit(self.allocator); + } + + /// Push a received message (called from libdatachannel callback thread). + pub fn pushRecvMessage(self: *ChannelState, data: []const u8) void { + self.mutex.lock(); + defer self.mutex.unlock(); + + if (self.recv_queue.items.len >= MAX_RECV_QUEUE) { + return; // drop if queue full + } + + const copy = self.allocator.dupe(u8, data) catch return; + self.recv_queue.append(self.allocator, .{ .data = copy }) catch { + self.allocator.free(copy); + }; + } + + /// Pop a received message (called from main/update thread). + pub fn popRecvMessage(self: *ChannelState) ?RecvMessage { + self.mutex.lock(); + defer self.mutex.unlock(); + + if (self.recv_queue.items.len == 0) return null; + return self.recv_queue.orderedRemove(0); + } + + /// Set local SDP (called from description callback thread). + pub fn setLocalSdp(self: *ChannelState, sdp: []const u8, sdp_type: []const u8) void { + self.mutex.lock(); + defer self.mutex.unlock(); + + if (self.local_sdp) |old| self.allocator.free(old); + if (self.local_sdp_type) |old| self.allocator.free(old); + + self.local_sdp = self.allocator.dupe(u8, sdp) catch null; + self.local_sdp_type = self.allocator.dupe(u8, sdp_type) catch null; + } + + /// Get local SDP (called from main thread). Caller does NOT own the memory. + pub fn getLocalSdp(self: *ChannelState) ?[]const u8 { + self.mutex.lock(); + defer self.mutex.unlock(); + return self.local_sdp; + } + + /// Add a local ICE candidate (called from candidate callback thread). + pub fn addLocalCandidate(self: *ChannelState, candidate: []const u8) void { + self.mutex.lock(); + defer self.mutex.unlock(); + + if (self.local_candidates.items.len >= MAX_CANDIDATES) return; + + const copy = self.allocator.dupe(u8, candidate) catch return; + self.local_candidates.append(self.allocator, copy) catch { + self.allocator.free(copy); + }; + } + + /// Drain all local candidates (called from main thread). Caller owns returned slices. + pub fn drainLocalCandidates(self: *ChannelState, allocator: std.mem.Allocator) ![][]u8 { + self.mutex.lock(); + defer self.mutex.unlock(); + + if (self.local_candidates.items.len == 0) return &[_][]u8{}; + + const result = try allocator.dupe([]u8, self.local_candidates.items); + self.local_candidates.items.len = 0; + return result; + } + + /// Map libdatachannel state to our TransportState. + pub fn getTransportState(self: *const ChannelState) TransportState { + return mapRtcState(self.state.load(.acquire)); + } +}; + +/// Map rtc.State → TransportState. +pub fn mapRtcState(state: rtc.State) TransportState { + return switch (state) { + .new => .connecting, + .connecting => .connecting, + .connected => .connected, + .disconnected => .closed, + .failed => .closed, + .closed => .closed, + }; +} + +// ============================================================================ +// C→Zig callback bridge functions +// ============================================================================ + +fn onLocalDescription(pc: c_int, sdp: [*:0]const u8, sdp_type: [*:0]const u8, ptr: ?*anyopaque) callconv(.c) void { + _ = pc; + const cs: *ChannelState = @ptrCast(@alignCast(ptr orelse return)); + cs.setLocalSdp(std.mem.span(sdp), std.mem.span(sdp_type)); +} + +fn onLocalCandidate(pc: c_int, cand: [*:0]const u8, _: [*:0]const u8, ptr: ?*anyopaque) callconv(.c) void { + _ = pc; + const cs: *ChannelState = @ptrCast(@alignCast(ptr orelse return)); + cs.addLocalCandidate(std.mem.span(cand)); +} + +fn onStateChange(_: c_int, state: c_int, ptr: ?*anyopaque) callconv(.c) void { + const cs: *ChannelState = @ptrCast(@alignCast(ptr orelse return)); + cs.state.store(@enumFromInt(state), .release); +} + +fn onGatheringStateChange(_: c_int, state: c_int, ptr: ?*anyopaque) callconv(.c) void { + const cs: *ChannelState = @ptrCast(@alignCast(ptr orelse return)); + const gs: rtc.GatheringState = @enumFromInt(state); + cs.gathering_state.store(gs, .release); + if (gs == .complete) { + cs.gathering_complete.store(true, .release); + } +} + +fn onDataChannel(_: c_int, dc: c_int, ptr: ?*anyopaque) callconv(.c) void { + const cs: *ChannelState = @ptrCast(@alignCast(ptr orelse return)); + cs.dc_id.store(dc, .release); + // Wire DataChannel callbacks + _ = rtc.rtcSetOpenCallback(dc, onOpen); + _ = rtc.rtcSetClosedCallback(dc, onClosed); + _ = rtc.rtcSetErrorCallback(dc, onError); + _ = rtc.rtcSetMessageCallback(dc, onMessage); + rtc.rtcSetUserPointer(dc, ptr); +} + +fn onOpen(_: c_int, ptr: ?*anyopaque) callconv(.c) void { + const cs: *ChannelState = @ptrCast(@alignCast(ptr orelse return)); + cs.dc_open.store(true, .release); +} + +fn onClosed(_: c_int, ptr: ?*anyopaque) callconv(.c) void { + const cs: *ChannelState = @ptrCast(@alignCast(ptr orelse return)); + cs.dc_open.store(false, .release); +} + +fn onError(_: c_int, err_msg: [*:0]const u8, ptr: ?*anyopaque) callconv(.c) void { + const cs: *ChannelState = @ptrCast(@alignCast(ptr orelse return)); + cs.mutex.lock(); + defer cs.mutex.unlock(); + cs.last_error = std.mem.span(err_msg); +} + +fn onMessage(_: c_int, message: [*]const u8, size: c_int, ptr: ?*anyopaque) callconv(.c) void { + const cs: *ChannelState = @ptrCast(@alignCast(ptr orelse return)); + if (size > 0) { + cs.pushRecvMessage(message[0..@intCast(size)]); + } +} + +// ============================================================================ +// NativeWebRTCManager — high-level API for creating WebRTC connections +// ============================================================================ + +pub const NativeWebRTCManager = struct { + allocator: std.mem.Allocator, + mtu: c_int = 0, + max_message_size: c_int = 0, + unordered: bool = false, + + pub const InitError = error{WebRTCUnavailable}; + + pub fn init(allocator: std.mem.Allocator) InitError!NativeWebRTCManager { + if (!rtc.load()) return error.WebRTCUnavailable; + rtc.rtcPreload(); + return .{ .allocator = allocator }; + } + + /// Configure global SCTP transport settings. + pub fn setSctpSettings(self: *NativeWebRTCManager, settings: rtc.SctpSettings) void { + _ = self; + _ = rtc.rtcSetSctpSettings(&settings); + } + + pub fn deinit(self: *NativeWebRTCManager) void { + _ = self; + rtc.rtcCleanup(); + } + + /// Create a new WebRTC PeerConnection and DataChannel (offerer). + pub fn createOffer(self: *NativeWebRTCManager, ice_servers: ?[]const [*:0]const u8) !*ChannelState { + var config = rtc.Configuration{ + .mtu = self.mtu, + .maxMessageSize = self.max_message_size, + }; + if (ice_servers) |servers| { + config.iceServers = servers.ptr; + config.iceServersCount = @intCast(servers.len); + } + + const pc_id = rtc.rtcCreatePeerConnection(&config); + if (pc_id < 0) return error.OutOfMemory; + + const cs = try self.allocator.create(ChannelState); + cs.* = ChannelState.init(self.allocator, pc_id); + + // Wire PeerConnection callbacks + rtc.rtcSetUserPointer(pc_id, cs); + _ = rtc.rtcSetLocalDescriptionCallback(pc_id, onLocalDescription); + _ = rtc.rtcSetLocalCandidateCallback(pc_id, onLocalCandidate); + _ = rtc.rtcSetStateChangeCallback(pc_id, onStateChange); + _ = rtc.rtcSetGatheringStateChangeCallback(pc_id, onGatheringStateChange); + + // Create DataChannel (triggers SDP offer generation) + const dc_init = rtc.DataChannelInit{ + .reliability = .{ .unordered = self.unordered }, + .protocol = "zig-p2p", + }; + const dc_id = rtc.rtcCreateDataChannelEx(pc_id, "zig-p2p", &dc_init); + if (dc_id < 0) { + _ = rtc.rtcDeletePeerConnection(pc_id); + self.allocator.destroy(cs); + return error.OutOfMemory; + } + + cs.dc_id.store(dc_id, .release); + + // Wire DataChannel callbacks + rtc.rtcSetUserPointer(dc_id, cs); + _ = rtc.rtcSetOpenCallback(dc_id, onOpen); + _ = rtc.rtcSetClosedCallback(dc_id, onClosed); + _ = rtc.rtcSetErrorCallback(dc_id, onError); + _ = rtc.rtcSetMessageCallback(dc_id, onMessage); + + return cs; + } + + /// Accept a remote offer SDP: create PeerConnection, set remote description, + /// generate answer. Returns ChannelState to poll. + pub fn acceptOffer(self: *NativeWebRTCManager, remote_sdp: [:0]const u8, ice_servers: ?[]const [*:0]const u8) !*ChannelState { + var config = rtc.Configuration{ + .mtu = self.mtu, + .maxMessageSize = self.max_message_size, + }; + if (ice_servers) |servers| { + config.iceServers = servers.ptr; + config.iceServersCount = @intCast(servers.len); + } + + const pc_id = rtc.rtcCreatePeerConnection(&config); + if (pc_id < 0) return error.OutOfMemory; + + const cs = try self.allocator.create(ChannelState); + cs.* = ChannelState.init(self.allocator, pc_id); + + // Wire PeerConnection callbacks + rtc.rtcSetUserPointer(pc_id, cs); + _ = rtc.rtcSetLocalDescriptionCallback(pc_id, onLocalDescription); + _ = rtc.rtcSetLocalCandidateCallback(pc_id, onLocalCandidate); + _ = rtc.rtcSetStateChangeCallback(pc_id, onStateChange); + _ = rtc.rtcSetGatheringStateChangeCallback(pc_id, onGatheringStateChange); + _ = rtc.rtcSetDataChannelCallback(pc_id, onDataChannel); + + // Set remote description (triggers answer generation) + const result = rtc.rtcSetRemoteDescription(pc_id, remote_sdp, "offer"); + if (result < 0) { + _ = rtc.rtcDeletePeerConnection(pc_id); + self.allocator.destroy(cs); + return error.OutOfMemory; + } + + return cs; + } + + /// Send data via the DataChannel. + pub fn send(self: *NativeWebRTCManager, cs: *ChannelState, data: []const u8) !usize { + _ = self; + const dc_id = cs.dc_id.load(.acquire); + if (dc_id < 0) return error.OutOfMemory; + if (!cs.dc_open.load(.acquire)) return CoreError.ConnectionTimeout; + + const result = rtc.rtcSendMessage(dc_id, data.ptr, @intCast(data.len)); + if (result < 0) return CoreError.SocketSendFailed; + return data.len; + } + + /// Add a remote ICE candidate. + pub fn addRemoteCandidate(self: *NativeWebRTCManager, cs: *ChannelState, candidate: [:0]const u8) void { + _ = self; + _ = rtc.rtcAddRemoteCandidate(cs.pc_id, candidate, null); + } + + /// Close and clean up a channel. + pub fn destroyChannel(self: *NativeWebRTCManager, cs: *ChannelState) void { + const dc_id = cs.dc_id.load(.acquire); + if (dc_id >= 0) { + _ = rtc.rtcClose(dc_id); + _ = rtc.rtcDelete(dc_id); + } + _ = rtc.rtcClosePeerConnection(cs.pc_id); + _ = rtc.rtcDeletePeerConnection(cs.pc_id); + cs.deinit(); + self.allocator.destroy(cs); + } +}; + +// ============================================================================ +// WebRTCChannelTransport — Transport vtable conforming wrapper +// ============================================================================ + +/// Wraps a ChannelState to conform to the Transport vtable interface. +pub const WebRTCChannelTransport = struct { + cs: *ChannelState, + manager: *NativeWebRTCManager, + + pub fn init(manager: *NativeWebRTCManager, cs: *ChannelState) WebRTCChannelTransport { + return .{ .cs = cs, .manager = manager }; + } + + // Transport vtable conformance + pub fn send(self: *WebRTCChannelTransport, data: []const u8) CoreError!usize { + return self.manager.send(self.cs, data) catch |err| { + return switch (err) { + error.OutOfMemory => CoreError.SystemError, + else => err, + }; + }; + } + + pub fn receive(self: *WebRTCChannelTransport, buffer: []u8) CoreError!usize { + const msg = self.cs.popRecvMessage() orelse return CoreError.ConnectionTimeout; + defer self.cs.allocator.free(msg.data); + + const copy_len = @min(msg.data.len, buffer.len); + @memcpy(buffer[0..copy_len], msg.data[0..copy_len]); + return copy_len; + } + + pub fn sendTo(_: *WebRTCChannelTransport, _: []const u8, _: core.Address) CoreError!usize { + return CoreError.OperationNotSupported; + } + + pub fn receiveFrom(_: *WebRTCChannelTransport, _: []u8) CoreError!core.transport.ReceiveFromResult { + return CoreError.OperationNotSupported; + } + + pub fn canSend(self: *WebRTCChannelTransport) bool { + return self.cs.dc_open.load(.acquire); + } + + pub fn canReceive(self: *WebRTCChannelTransport) bool { + self.cs.mutex.lock(); + defer self.cs.mutex.unlock(); + return self.cs.recv_queue.items.len > 0; + } + + pub fn close(self: *WebRTCChannelTransport) void { + const dc_id = self.cs.dc_id.load(.acquire); + if (dc_id >= 0) { + _ = rtc.rtcClose(dc_id); + } + } + + pub fn getState(self: *WebRTCChannelTransport) TransportState { + return self.cs.getTransportState(); + } + + pub fn getRemoteAddress(_: *WebRTCChannelTransport) ?core.Address { + return null; + } + + pub fn getMode(_: *WebRTCChannelTransport) TransportMode { + return .stream; + } + + pub fn transport(self: *WebRTCChannelTransport) CoreTransport { + return CoreTransport.init(self); + } +}; diff --git a/src/platform/webrtc_signaling.zig b/src/platform/webrtc_signaling.zig new file mode 100644 index 0000000..9689ea6 --- /dev/null +++ b/src/platform/webrtc_signaling.zig @@ -0,0 +1,219 @@ +//! WebRTC Signaling Message format for DHT-based SDP/ICE exchange. +//! +//! When two peers want to establish a WebRTC connection, they need to exchange +//! SDP offers/answers and ICE candidates. This module defines the wire format +//! for these signaling messages, which are stored/retrieved via the DHT. +//! +//! The signaling key is derived from both peers' public keys (same as MWP +//! meeting point derivation), ensuring only the intended peers can find +//! each other's signaling data. + +const std = @import("std"); + +/// Maximum SDP/candidate payload size. +pub const MAX_PAYLOAD_SIZE: usize = 8192; + +/// Signaling message types. +pub const MessageType = enum(u8) { + offer = 1, + answer = 2, + ice_candidate = 3, +}; + +/// Wire format for a signaling message. +/// Layout: [type:1][pubkey:32][timestamp:8 LE][payload_len:2 LE][payload:N][signature:64] +pub const SignalingMessage = struct { + msg_type: MessageType, + from_pubkey: [32]u8, + timestamp_ms: i64, + payload: []const u8, + signature: [64]u8, + + /// Minimum wire size (no payload). + pub const HEADER_SIZE = 1 + 32 + 8 + 2; // type + pubkey + timestamp + payload_len + pub const SIGNATURE_SIZE = 64; + pub const MIN_WIRE_SIZE = HEADER_SIZE + SIGNATURE_SIZE; + + /// Serialize to wire format. + pub fn serialize(self: *const SignalingMessage, allocator: std.mem.Allocator) ![]u8 { + if (self.payload.len > MAX_PAYLOAD_SIZE) return error.PayloadTooLarge; + + const total = HEADER_SIZE + self.payload.len + SIGNATURE_SIZE; + const buf = try allocator.alloc(u8, total); + + var offset: usize = 0; + + // type + buf[offset] = @intFromEnum(self.msg_type); + offset += 1; + + // from_pubkey + @memcpy(buf[offset..][0..32], &self.from_pubkey); + offset += 32; + + // timestamp (little-endian i64) + std.mem.writeInt(i64, buf[offset..][0..8], self.timestamp_ms, .little); + offset += 8; + + // payload_len (little-endian u16) + std.mem.writeInt(u16, buf[offset..][0..2], @intCast(self.payload.len), .little); + offset += 2; + + // payload + @memcpy(buf[offset..][0..self.payload.len], self.payload); + offset += self.payload.len; + + // signature + @memcpy(buf[offset..][0..64], &self.signature); + + return buf; + } + + /// Deserialize from wire format. + pub fn deserialize(data: []const u8) !SignalingMessage { + if (data.len < MIN_WIRE_SIZE) return error.BufferTooSmall; + + var offset: usize = 0; + + // type + const msg_type_raw = data[offset]; + offset += 1; + const msg_type: MessageType = std.meta.intToEnum(MessageType, msg_type_raw) catch + return error.InvalidMessageType; + + // from_pubkey + var pubkey: [32]u8 = undefined; + @memcpy(&pubkey, data[offset..][0..32]); + offset += 32; + + // timestamp + const timestamp_ms = std.mem.readInt(i64, data[offset..][0..8], .little); + offset += 8; + + // payload_len + const payload_len = std.mem.readInt(u16, data[offset..][0..2], .little); + offset += 2; + + if (data.len < HEADER_SIZE + payload_len + SIGNATURE_SIZE) return error.BufferTooSmall; + + // payload (borrowed from input) + const payload = data[offset..][0..payload_len]; + offset += payload_len; + + // signature + var signature: [64]u8 = undefined; + @memcpy(&signature, data[offset..][0..64]); + + return .{ + .msg_type = msg_type, + .from_pubkey = pubkey, + .timestamp_ms = timestamp_ms, + .payload = payload, + .signature = signature, + }; + } + + /// Get the signed data portion (everything except the signature). + pub fn getSignedData(data: []const u8) ![]const u8 { + if (data.len < MIN_WIRE_SIZE) return error.BufferTooSmall; + return data[0 .. data.len - SIGNATURE_SIZE]; + } +}; + +/// Compute a deterministic signaling key from two peers' public keys. +/// Uses SHA-256(sorted_key_a || sorted_key_b || "webrtc-signaling-v1"). +/// Both peers compute the same key regardless of order. +pub fn computeSignalingKey(pubkey_a: [32]u8, pubkey_b: [32]u8) [32]u8 { + const order = std.mem.order(u8, &pubkey_a, &pubkey_b); + var hasher = std.crypto.hash.sha2.Sha256.init(.{}); + + if (order == .lt or order == .eq) { + hasher.update(&pubkey_a); + hasher.update(&pubkey_b); + } else { + hasher.update(&pubkey_b); + hasher.update(&pubkey_a); + } + hasher.update("webrtc-signaling-v1"); + + return hasher.finalResult(); +} + +// ============================================================================ +// Tests +// ============================================================================ + +test "SignalingMessage: roundtrip serialize/deserialize" { + const allocator = std.testing.allocator; + + const original = SignalingMessage{ + .msg_type = .offer, + .from_pubkey = [_]u8{0xAA} ** 32, + .timestamp_ms = 1700000000000, + .payload = "v=0\r\no=- 123 456 IN IP4 127.0.0.1\r\n", + .signature = [_]u8{0xBB} ** 64, + }; + + const wire = try original.serialize(allocator); + defer allocator.free(wire); + + const decoded = try SignalingMessage.deserialize(wire); + + try std.testing.expectEqual(MessageType.offer, decoded.msg_type); + try std.testing.expectEqualSlices(u8, &original.from_pubkey, &decoded.from_pubkey); + try std.testing.expectEqual(original.timestamp_ms, decoded.timestamp_ms); + try std.testing.expectEqualStrings(original.payload, decoded.payload); + try std.testing.expectEqualSlices(u8, &original.signature, &decoded.signature); +} + +test "SignalingMessage: ice_candidate type" { + const allocator = std.testing.allocator; + + const msg = SignalingMessage{ + .msg_type = .ice_candidate, + .from_pubkey = [_]u8{0x11} ** 32, + .timestamp_ms = 42, + .payload = "candidate:0 1 UDP 2130706431 127.0.0.1 12345 typ host", + .signature = [_]u8{0} ** 64, + }; + + const wire = try msg.serialize(allocator); + defer allocator.free(wire); + + const decoded = try SignalingMessage.deserialize(wire); + try std.testing.expectEqual(MessageType.ice_candidate, decoded.msg_type); +} + +test "SignalingMessage: deserialize rejects too-small buffer" { + const small = [_]u8{0} ** 10; + const result = SignalingMessage.deserialize(&small); + try std.testing.expectError(error.BufferTooSmall, result); +} + +test "SignalingMessage: deserialize rejects invalid type" { + var buf: [SignalingMessage.MIN_WIRE_SIZE]u8 = [_]u8{0} ** SignalingMessage.MIN_WIRE_SIZE; + buf[0] = 0xFF; // invalid type + const result = SignalingMessage.deserialize(&buf); + try std.testing.expectError(error.InvalidMessageType, result); +} + +test "computeSignalingKey: order-independent" { + const key_a = [_]u8{0x01} ** 32; + const key_b = [_]u8{0x02} ** 32; + + const result_ab = computeSignalingKey(key_a, key_b); + const result_ba = computeSignalingKey(key_b, key_a); + + try std.testing.expectEqualSlices(u8, &result_ab, &result_ba); +} + +test "computeSignalingKey: different keys produce different results" { + const key_a = [_]u8{0x01} ** 32; + const key_b = [_]u8{0x02} ** 32; + const key_c = [_]u8{0x03} ** 32; + + const result_ab = computeSignalingKey(key_a, key_b); + const result_ac = computeSignalingKey(key_a, key_c); + + try std.testing.expect(!std.mem.eql(u8, &result_ab, &result_ac)); +} diff --git a/src/platform/webrtc_wasm.zig b/src/platform/webrtc_wasm.zig new file mode 100644 index 0000000..7acc506 --- /dev/null +++ b/src/platform/webrtc_wasm.zig @@ -0,0 +1,252 @@ +//! WASM WebRTC Transport +//! +//! Transport vtable implementation for browser WebRTC DataChannels. +//! Calls `extern "env"` functions provided by the JS host for sending data, +//! and receives data via exported callbacks that JS invokes when messages arrive. +//! +//! Single-threaded (WASM has no threads), so no mutex needed for the recv queue. + +const std = @import("std"); +const core = @import("core"); +const CoreError = core.errors.Error; +const CoreTransport = core.transport.Transport; +const TransportState = core.transport.TransportState; +const TransportMode = core.transport.TransportMode; +const Address = core.Address; + +// ============================================================================ +// JS extern imports — provided by the JS host layer +// ============================================================================ + +extern "env" fn js_datachannel_send(channel_id: u32, data_ptr: [*]const u8, data_len: u32) i32; +extern "env" fn js_datachannel_close(channel_id: u32) void; +extern "env" fn js_datachannel_buffered_amount(channel_id: u32) u32; +extern "env" fn js_log(ptr: [*]const u8, len: u32) void; + +// ============================================================================ +// WasmWebRTCTransport — one per DataChannel +// ============================================================================ + +/// Maximum receive queue size per transport. Must be large enough to hold +/// all messages that arrive between update() ticks. With DataChannel flow +/// control on the sender (bufferedAmount check), this is typically small, +/// but burst arrivals on fast connections can queue thousands of messages. +pub const MAX_RECV_QUEUE = 100_000; + +pub const WasmWebRTCTransport = struct { + channel_id: u32, + state: TransportState, + recv_queue: std.ArrayListUnmanaged([]u8), + /// Read index for O(1) FIFO dequeue (avoids O(n) orderedRemove shifts). + recv_read_idx: usize, + allocator: std.mem.Allocator, + + pub fn init(allocator: std.mem.Allocator, channel_id: u32) WasmWebRTCTransport { + return .{ + .channel_id = channel_id, + .state = .connected, + .recv_queue = .{}, + .recv_read_idx = 0, + .allocator = allocator, + }; + } + + pub fn deinit(self: *WasmWebRTCTransport) void { + // Free unread messages + for (self.recv_queue.items[self.recv_read_idx..]) |msg| { + self.allocator.free(msg); + } + self.recv_queue.deinit(self.allocator); + } + + /// Push a received message (called from wasm_on_datachannel_message). + pub fn pushRecvMessage(self: *WasmWebRTCTransport, data: []const u8) void { + const pending = self.recv_queue.items.len - self.recv_read_idx; + if (pending >= MAX_RECV_QUEUE) { + // Drop oldest unread message if queue is full + self.allocator.free(self.recv_queue.items[self.recv_read_idx]); + self.recv_read_idx += 1; + } + const copy = self.allocator.dupe(u8, data) catch return; + self.recv_queue.append(self.allocator, copy) catch { + self.allocator.free(copy); + }; + } + + /// Compact the queue when all messages have been read (reclaims memory). + fn compactIfDrained(self: *WasmWebRTCTransport) void { + if (self.recv_read_idx > 0 and self.recv_read_idx >= self.recv_queue.items.len) { + self.recv_queue.clearRetainingCapacity(); + self.recv_read_idx = 0; + } + } + + // -- Transport vtable conformance -- + + pub fn send(self: *WasmWebRTCTransport, data: []const u8) CoreError!usize { + if (self.state != .connected) return CoreError.ConnectionClosed; + const result = js_datachannel_send(self.channel_id, data.ptr, @intCast(data.len)); + if (result < 0) return CoreError.NetworkError; + return data.len; + } + + pub fn receive(self: *WasmWebRTCTransport, buffer: []u8) CoreError!usize { + if (self.recv_read_idx >= self.recv_queue.items.len) { + self.compactIfDrained(); + if (self.state == .closed) return CoreError.ConnectionClosed; + return CoreError.ConnectionTimeout; + } + const msg = self.recv_queue.items[self.recv_read_idx]; + self.recv_read_idx += 1; + defer self.allocator.free(msg); + + // Compact after draining all messages (O(1) amortized) + self.compactIfDrained(); + + const copy_len = @min(msg.len, buffer.len); + @memcpy(buffer[0..copy_len], msg[0..copy_len]); + return copy_len; + } + + pub fn sendTo(_: *WasmWebRTCTransport, _: []const u8, _: Address) CoreError!usize { + return CoreError.OperationNotSupported; + } + + pub fn receiveFrom(_: *WasmWebRTCTransport, _: []u8) CoreError!core.transport.ReceiveFromResult { + return CoreError.OperationNotSupported; + } + + pub fn canSend(self: *WasmWebRTCTransport) bool { + if (self.state != .connected) return false; + // Check JS-side buffered amount; allow sending if under 1MB + return js_datachannel_buffered_amount(self.channel_id) < 1_048_576; + } + + pub fn canReceive(self: *WasmWebRTCTransport) bool { + return self.recv_read_idx < self.recv_queue.items.len; + } + + pub fn close(self: *WasmWebRTCTransport) void { + if (self.state == .closed) return; + self.state = .closed; + js_datachannel_close(self.channel_id); + } + + pub fn getState(self: *WasmWebRTCTransport) TransportState { + return self.state; + } + + pub fn getRemoteAddress(_: *WasmWebRTCTransport) ?Address { + return null; // WebRTC doesn't expose remote IP to JS + } + + pub fn getMode(_: *WasmWebRTCTransport) TransportMode { + return .stream; // Reliable ordered DataChannel + } + + /// Wrap this transport into the generic Transport vtable. + pub fn transport(self: *WasmWebRTCTransport) CoreTransport { + return CoreTransport.init(self); + } +}; + +// ============================================================================ +// WasmChannelManager — manages active WASM WebRTC transports +// ============================================================================ + +pub const MAX_CHANNELS = 32; + +pub const WasmChannelManager = struct { + channels: [MAX_CHANNELS]?*WasmWebRTCTransport, + allocator: std.mem.Allocator, + + pub fn init(allocator: std.mem.Allocator) WasmChannelManager { + return .{ + .channels = .{null} ** MAX_CHANNELS, + .allocator = allocator, + }; + } + + pub fn deinit(self: *WasmChannelManager) void { + for (&self.channels) |*slot| { + if (slot.*) |t| { + t.deinit(); + self.allocator.destroy(t); + slot.* = null; + } + } + } + + /// Create a transport for a newly opened channel. + /// Returns the transport or null if no slots available. + pub fn createTransport(self: *WasmChannelManager, channel_id: u32) ?*WasmWebRTCTransport { + // Find a free slot + for (&self.channels) |*slot| { + if (slot.* == null) { + const t = self.allocator.create(WasmWebRTCTransport) catch return null; + t.* = WasmWebRTCTransport.init(self.allocator, channel_id); + slot.* = t; + return t; + } + } + return null; + } + + /// Find transport by channel ID. + pub fn getTransport(self: *WasmChannelManager, channel_id: u32) ?*WasmWebRTCTransport { + for (self.channels) |slot| { + if (slot) |t| { + if (t.channel_id == channel_id) return t; + } + } + return null; + } + + /// Remove and destroy a transport by channel ID. + pub fn removeTransport(self: *WasmChannelManager, channel_id: u32) void { + for (&self.channels) |*slot| { + if (slot.*) |t| { + if (t.channel_id == channel_id) { + t.deinit(); + self.allocator.destroy(t); + slot.* = null; + return; + } + } + } + } + + // -- Event handlers called from WASM exports -- + + /// Handle DataChannel open event. + pub fn onChannelOpen(self: *WasmChannelManager, channel_id: u32) ?*WasmWebRTCTransport { + // If transport already exists, just mark it connected + if (self.getTransport(channel_id)) |t| { + t.state = .connected; + return t; + } + // Otherwise create a new transport + return self.createTransport(channel_id); + } + + /// Handle DataChannel message event. + pub fn onChannelMessage(self: *WasmChannelManager, channel_id: u32, data: []const u8) void { + if (self.getTransport(channel_id)) |t| { + t.pushRecvMessage(data); + } + } + + /// Handle DataChannel close event. + pub fn onChannelClose(self: *WasmChannelManager, channel_id: u32) void { + if (self.getTransport(channel_id)) |t| { + t.state = .closed; + } + } + + /// Handle DataChannel error event. + pub fn onChannelError(self: *WasmChannelManager, channel_id: u32) void { + if (self.getTransport(channel_id)) |t| { + t.state = .closed; + } + } +};