From 7c796ceb0b1b67e58fa83962db9de3646f3606da Mon Sep 17 00:00:00 2001 From: R Date: Mon, 23 Nov 2026 06:52:52 -0300 Subject: [PATCH 1/6] build: libdatachannel's build applies two patches to its staged copy, for two races of 0.24.6 that failed a native connection about once in 300 runs under load webcpp::webrtc's native test failed once on MSVC 14.3 (a_full_exchange: no channel, the state never connected). Under load on macOS the native tests failed 6 of 2100 runs, each an exchange whose connection went to failed, and libdatachannel's log named two races of the offerer, whose ICE transport starts while rtcSetRemoteDescription applies the answer: - DtlsTransport::start() registered its incoming callback, which replays the records the ICE transport kept, before setting the DTLS MTU; doRecv could answer the peer's ClientHello first, and OpenSSL, with SSL_OP_NO_QUERY_MTU and no MTU, failed the write (SSL_ERROR_SYSCALL, "Handshake failed: fatal I/O error"). dtls-mtu-before-incoming.patch sets the MTU first. - initSctpTransport() checked and created without a lock, so the DTLS Connected callback and processRemoteDescription() each made an SCTP transport, and the replaced one, destroyed, stopped DTLS. sctp-init-once.patch gives it a mutex, as initDtlsTransport() has. build.py applies tools/libdatachannel/patches/*.patch, by name, to the verified staged copy alone (the checkout and the archive stay upstream's), refuses one that touches anything but src/, one the sources hold already and one that no longer applies; the patches are inputs of the configuration's key. With both, 12000 runs under the same load failed none. Each patch is under libdatachannel's MPL-2.0. The guidelines' "unmodified" decision (D16) is amended pending the owner's approval. --- CODING-GUIDELINES.md | 30 ++++++++++--- libs/webrtc | 2 +- third_party/Jamfile | 8 +++- tools/libdatachannel/build.py | 35 +++++++++++++++ tools/libdatachannel/build_test.py | 44 ++++++++++++++++++ .../patches/dtls-mtu-before-incoming.patch | 45 +++++++++++++++++++ .../patches/sctp-init-once.patch | 40 +++++++++++++++++ 7 files changed, 194 insertions(+), 10 deletions(-) create mode 100644 tools/libdatachannel/patches/dtls-mtu-before-incoming.patch create mode 100644 tools/libdatachannel/patches/sctp-init-once.patch diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 58a299e..326e112 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -991,7 +991,7 @@ update --init third_party/libs/`; a build that needs none never looks. | `ctaes` | `src/crypto/ctaes` of `bitcoin/bitcoin` v31.1 at `9be056a` (commit `9be056a8a72b624dae9623b2f7bded92c2a21c91`), the submodule `third_party/libs/bitcoin`, shallow; `third_party/Jamfile` compiles its `ctaes.c` alone, with webcpp::crypto's canary, on every target (`WEBCPP_CRYPTO_HAS_CTAES=1`); the tree's `src/secp256k1/` subtree is never on an include path and no glob over `third_party/libs` reaches it | MIT | | `ed25519-speccheck` | `novifinancial/ed25519-speccheck` at `65519336` (2021-02-26), shallow, test data: crypto's tests read the twelve Ed25519 edge cases of "Taming the many EdDSAs", its `cases.json`, at run time under the directory its define `WEBCPP_TEST_ED25519_SPECCHECK` gives, on every target (wasmtime is given it, `webcpp.data`), and run again when it changes | Apache-2.0 | | `json-schema-test-suite` | the JSON Schema Test Suite at `5b0ee16` (2026-09-21), test data: a test that names it reads the suite at run time from the directory its define `WEBCPP_TEST_JSON_SCHEMA_TEST_SUITE` gives, on every target (wasmtime is given it, `webcpp.data`), and runs again when a file of the suite changes | MIT | -| `libdatachannel` | libdatachannel 0.24.6 at `6b1e2e620f1e37f0eafeee702eaea0043cb305fd`, with pinned libjuice, libsrtp, plog and usrsctp sources; static native archives built by upstream CMake through B2 against the same source-built OpenSSL | MPL-2.0 and the nested dependencies' own licences | +| `libdatachannel` | libdatachannel 0.24.6 at `6b1e2e620f1e37f0eafeee702eaea0043cb305fd`, with pinned libjuice, libsrtp, plog and usrsctp sources; static native archives built by upstream CMake through B2 against the same source-built OpenSSL, from a staged copy the patches of `tools/libdatachannel/patches` correct | MPL-2.0 and the nested dependencies' own licences | | `nativejson-benchmark` | Milo Yip's nativejson-benchmark at `478d572` (2022-10-28), test data: document's benchmarks (`libs/document/bench`) read its `data/canada.json`, `data/citm_catalog.json` and `data/twitter.json` at run time under the directory its define `WEBCPP_TEST_NATIVEJSON_BENCHMARK` gives, on every target (wasmtime is given it, `webcpp.data`), and run again when one of them changes; its own submodules are never checked out | MIT | | `openssl` | OpenSSL 3.5.9 at `45e844fa2a14ec92d146bd8f5778ac130b6625fb`; static libssl/libcrypto and matching generated headers, built by upstream Configure/Make through B2 for native Clang/GCC/MSVC, WASIp2 single and WASIp3 single/cooperative | Apache-2.0 | | `secp256k1` | libsecp256k1 v0.8.0 at `6e2c8bc`; a static library built file by file by `third_party/Jamfile` (`src/secp256k1.c` and its two precomputed tables, every module on) with webcpp::crypto's canary, on every target; its tables by `webcpp-secp256k1-tables` (`auto`: small on Emscripten, large elsewhere); `WEBCPP_CRYPTO_HAS_SECP256K1=1` | MIT | @@ -1021,6 +1021,18 @@ provider's headers and archive hashes checked first. Native consumers select permits Asio, Beast and native Trystero in one program; it does not complete Trystero's later API migration or prove libdatachannel's upstream test suite. +The checkout and the archive stay upstream's bytes: `tools/libdatachannel/build.py` +applies the patches of `tools/libdatachannel/patches`, in the order of their +names, to its verified staged copy alone, each correcting a defect of the +pinned release until upstream fixes it, each changing only `src/`, each under +libdatachannel's MPL-2.0, and each an input of the configuration's key. A patch +the sources hold already, or one that no longer applies, fails the build by +name, so that it is removed or updated rather than skipped. The first two +correct the native connection races found on 2026-11-23: +`dtls-mtu-before-incoming.patch` (the DTLS server answered a ClientHello kept +before its start while its MTU was unset, and failed) and `sctp-init-once.patch` +(two threads each started an SCTP transport, and the replaced one stopped DTLS). + The CA bundle is an authorized exception to the source-submodule rule: curl publishes dated PEM artifacts, preserved byte-for-byte with source URL, SHA-256, certificate inventory and MPL notices. It is data, not copied implementation @@ -8620,12 +8632,16 @@ trystero on it (built, trystero's branch `webrtc-backend`, in its page tells a program to read or close every channel, and closing or destroying a channel drains its queue. Source: `libraries/webrtc/openspec/changes/genesis/design.md` D9 (proposals). -- **libdatachannel is the superproject's pinned, source-built copy, unmodified, - justified in the documentation, with nothing of it in a public header; its - MPL-2.0 is accepted for this library.** The owner's decision of 2026-11-14, - as trystero already distributes it; no WebRTC exists in webcpp, Boost, the - C++ Alliance or the standard library, and libdatachannel is the smallest - complete implementation. +- **libdatachannel is the superproject's pinned, source-built copy, unmodified + but for the build's patches of `tools/libdatachannel/patches`, justified in + the documentation, with nothing of it in a public header; its MPL-2.0 is + accepted for this library.** The owner's decision of 2026-11-14, as trystero + already distributes it; no WebRTC exists in webcpp, Boost, the C++ Alliance or + the standard library, and libdatachannel is the smallest complete + implementation. The patches (2026-11-23, pending the owner's approval) correct + two races of the pinned release that failed a native connection about once in + 300 runs under load; each is under MPL-2.0 and is removed once upstream + carries its fix. Source: `libraries/webrtc/openspec/changes/genesis/design.md` D16 (proposals). - **webcpp::webrtc knows nothing of xactor: an actor that needs a peer holds a `peer_connection` made on the executor its driver runs on, and turns each diff --git a/libs/webrtc b/libs/webrtc index eb77667..8863afc 160000 --- a/libs/webrtc +++ b/libs/webrtc @@ -1 +1 @@ -Subproject commit eb7766704e4fac703f894e88145cbaf1dcdaf1ee +Subproject commit 8863afc6d33f2b4fbb6fc32d81a9c1df9f1410de diff --git a/third_party/Jamfile b/third_party/Jamfile index ee9d026..591ae7a 100644 --- a/third_party/Jamfile +++ b/third_party/Jamfile @@ -218,13 +218,17 @@ explicit botan botan_test ; # libdatachannel and its pinned nested dependencies use upstream CMake, with # the exact OpenSSL archives above. Each archive reaches the program once. Its # configurations are named as OpenSSL's are, by the bytes of the inputs below, -# the build command and OpenSSL's configuration. +# the build command and OpenSSL's configuration. The patches of +# tools/libdatachannel/patches, which build.py applies to its staged copy of +# the sources, are inputs too. import webcpp-libdatachannel ; .libdatachannel-headers = [ glob libs/libdatachannel/include/rtc/*.hpp libs/libdatachannel/include/rtc/*.h ] ; +.libdatachannel-patches = [ glob ../tools/libdatachannel/patches/*.patch ] ; webcpp-libdatachannel.declare $(WEBCPP_ROOT) : $(.libdatachannel-headers:BS) : tools/libdatachannel/build.py tools/libdatachannel/source.py - tools/libdatachannel/pin.json tools/libdatachannel/msvc.cmake ; + tools/libdatachannel/pin.json tools/libdatachannel/msvc.cmake + $(.libdatachannel-patches:D=tools/libdatachannel/patches) ; explicit libdatachannel ; # A dated, digest-pinned Mozilla/curl data export, not third-party source code. diff --git a/tools/libdatachannel/build.py b/tools/libdatachannel/build.py index cf4874f..6dd9182 100644 --- a/tools/libdatachannel/build.py +++ b/tools/libdatachannel/build.py @@ -38,6 +38,40 @@ def run(command: list[str], directory: Path, env: dict[str, str], log: Path) -> raise RuntimeError(f'command failed ({result.returncode}); full log: {log}') +def patches() -> list[Path]: + """The corrections patches/ holds, in the order of their names.""" + return sorted((HERE / 'patches').glob('*.patch')) + + +def patch_source(staged: Path) -> None: + """Apply each patch to the verified staged copy, never to the pinned checkout. + + Each patch corrects a defect of the pinned libdatachannel until a release fixes it upstream, + and changes only its sources under src/. One that is applied already (the pin holds the fix) + or that no longer applies fails the build, naming it, so that it is removed or updated rather + than skipped. git looks for no repository above the staged copy. + """ + env = os.environ.copy() + env['GIT_CEILING_DIRECTORIES'] = str(staged.parent) + for patch in patches(): + name = f'tools/libdatachannel/patches/{patch.name}' + touched = [line.split(' ', 1)[1] for line in patch.read_text().splitlines() + if line.startswith(('--- ', '+++ '))] + if any(not path.startswith(('a/src/', 'b/src/')) for path in touched): + raise RuntimeError(f'{name} patches a file outside src/') + + def apply(*arguments: str) -> bool: + return subprocess.run(['git', '-C', str(staged), 'apply', *arguments, str(patch)], + env=env, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL).returncode == 0 + + if apply('--reverse', '--check'): + raise RuntimeError(f'{name} is applied already: the pinned libdatachannel holds ' + 'its fix, remove the patch') + if not apply('--check') or not apply(): + raise RuntimeError(f'{name} no longer applies: update or remove it') + + def provider(root: Path, windows: bool) -> dict: """Require the source-built threaded provider, never a discovered system library.""" record = json.loads((root / 'build.json').read_text()) @@ -107,6 +141,7 @@ def build(args: argparse.Namespace) -> None: with tempfile.TemporaryDirectory(prefix='webcpp-libdatachannel-') as temporary: scratch = Path(temporary) stage_source(source, scratch / 'source', pin) + patch_source(scratch / 'source') # Upstream's macOS workaround constructs ROOT/lib paths. Supply an # isolated prefix with exactly the already-verified B2 provider bytes. ssl_prefix = scratch / 'openssl' diff --git a/tools/libdatachannel/build_test.py b/tools/libdatachannel/build_test.py index 295f254..e81fcaf 100644 --- a/tools/libdatachannel/build_test.py +++ b/tools/libdatachannel/build_test.py @@ -9,6 +9,7 @@ from pathlib import Path import argparse import json +import shutil import subprocess import sys import tempfile @@ -92,6 +93,7 @@ def publish(path: Path, target: Path) -> Path: headers_only=False, flags=['--cxx-flags']) with patch.object(build, 'check_checkout'), \ patch.object(build, 'stage_source', side_effect=stage), \ + patch.object(build, 'patch_source'), \ patch.object(build, 'provider', return_value={'sha256': {}}), \ patch.object(build, 'run', side_effect=command), \ patch.object(Path, 'replace', publish): @@ -123,5 +125,47 @@ def test_the_build_record_is_published_whole_and_last(self) -> None: self.assertEqual([path.name for path in output.glob('*.new')], []) +class PatchTest(unittest.TestCase): + """patch_source() over a copy of the pinned checkout's sources.""" + + SOURCE = Path(__file__).resolve().parents[2] / 'third_party/libs/libdatachannel' + + def setUp(self) -> None: + if not (self.SOURCE / 'src').is_dir(): + self.skipTest('third_party/libs/libdatachannel is not checked out') + self.directory = tempfile.TemporaryDirectory(prefix='libdatachannel patches ') + self.staged = Path(self.directory.name) / 'source' + shutil.copytree(self.SOURCE / 'src', self.staged / 'src') + + def tearDown(self) -> None: + self.directory.cleanup() + + def test_each_patch_applies_to_the_pinned_sources(self) -> None: + self.assertTrue(build.patches()) + build.patch_source(self.staged) + start = (self.staged / 'src/impl/dtlstransport.cpp').read_text() + # OpenSSL's start(), the last of the three backends' in the file. + body = start[start.rindex('void DtlsTransport::start()'):] + self.assertLess(body.index('SSL_set_mtu('), body.index('registerIncoming();')) + connection = (self.staged / 'src/impl/peerconnection.cpp').read_text() + sctp = connection[connection.index('PeerConnection::initSctpTransport() {'):] + self.assertLess(sctp.index('std::lock_guard lock(mSctpTransportInitMutex);'), + sctp.index('std::atomic_load(&mSctpTransport)')) + + def test_a_patch_the_sources_hold_already_fails_the_build(self) -> None: + build.patch_source(self.staged) + with self.assertRaisesRegex(RuntimeError, 'is applied already'): + build.patch_source(self.staged) + + def test_a_patch_outside_src_fails_the_build(self) -> None: + patches = Path(self.directory.name) / 'patches' + patches.mkdir() + (patches / 'outside.patch').write_text( + '--- a/CMakeLists.txt\n+++ b/CMakeLists.txt\n@@ -1 +1 @@\n-x\n+y\n') + with patch.object(build, 'patches', return_value=[patches / 'outside.patch']): + with self.assertRaisesRegex(RuntimeError, 'outside src/'): + build.patch_source(self.staged) + + if __name__ == '__main__': unittest.main() diff --git a/tools/libdatachannel/patches/dtls-mtu-before-incoming.patch b/tools/libdatachannel/patches/dtls-mtu-before-incoming.patch new file mode 100644 index 0000000..d463ead --- /dev/null +++ b/tools/libdatachannel/patches/dtls-mtu-before-incoming.patch @@ -0,0 +1,45 @@ +libdatachannel 0.24.6's DtlsTransport::start() (the OpenSSL backend) registers its incoming +callback, which replays at once onto the thread pool the records the ICE transport kept while no +DTLS transport listened, before it sets the DTLS MTU under the SSL mutex. When the peer's +ClientHello arrived before this side's ICE transport connected, doRecv can take the mutex first +and answer it while the MTU is still unset: with SSL_OP_NO_QUERY_MTU, OpenSSL's dtls1_query_mtu +fails the write without an error on its queue, SSL_get_error gives SSL_ERROR_SYSCALL, and the +handshake fails ("DTLS recv: Handshake failed: fatal I/O error"), so the connection goes to +failed. webcpp::webrtc's native tests met it about once in 300 runs under load (the native +run's a_full_exchange on MSVC 14.3, 2026-11-23). This patch sets the MTU before the callback is +registered. Remove this file once the libdatachannel that tools/libdatachannel/pin.json pins +sets the MTU first: build.py then fails, saying so. + +This patch changes files of libdatachannel, which the Mozilla Public License 2.0 covers, and is +itself under that licence. + +diff --git a/src/impl/dtlstransport.cpp b/src/impl/dtlstransport.cpp +--- a/src/impl/dtlstransport.cpp ++++ b/src/impl/dtlstransport.cpp +@@ -856,16 +856,22 @@ DtlsTransport::~DtlsTransport() { + + void DtlsTransport::start() { + PLOG_DEBUG << "Starting DTLS transport"; +- registerIncoming(); +- changeState(State::Connecting); +- +- int ret, err; + { ++ // The MTU is set before any incoming record can reach doRecv: registerIncoming() replays ++ // the records the ICE transport kept, and a peer's ClientHello among them would otherwise ++ // make the handshake write before the MTU exists, which fails it. + std::lock_guard lock(mSslMutex); + + size_t mtu = mMtu.value_or(DEFAULT_MTU) - 8 - 40; // UDP/IPv6 + SSL_set_mtu(mSsl, static_cast(mtu)); + PLOG_VERBOSE << "DTLS MTU set to " << mtu; ++ } ++ registerIncoming(); ++ changeState(State::Connecting); ++ ++ int ret, err; ++ { ++ std::lock_guard lock(mSslMutex); + + // Initiate the handshake + ret = SSL_do_handshake(mSsl); diff --git a/tools/libdatachannel/patches/sctp-init-once.patch b/tools/libdatachannel/patches/sctp-init-once.patch new file mode 100644 index 0000000..92d2155 --- /dev/null +++ b/tools/libdatachannel/patches/sctp-init-once.patch @@ -0,0 +1,40 @@ +libdatachannel 0.24.6's PeerConnection::initSctpTransport() checks for an SCTP transport and +creates one without a lock, unlike initDtlsTransport(). When ICE connects before the remote +description is committed (the offerer, whose ICE transport starts on the answer before +processRemoteDescription() stores it), processRemoteDescription() starts the DTLS transport and +then the SCTP transport once DTLS is connected, while the DTLS transport's Connected callback +starts it too, on another thread: both create one, the second replaces the first, and the first, +destroyed, stops the DTLS transport under it ("SCTP early shutdown", "DTLS closed"), so the +connection goes to failed. webcpp::webrtc's native tests met it about once in 3000 runs under +load (2026-11-23). This patch gives initSctpTransport() a mutex of its own, as +initDtlsTransport() has. Remove this file once the libdatachannel that +tools/libdatachannel/pin.json pins serializes initSctpTransport(): build.py then fails, saying so. + +This patch changes files of libdatachannel, which the Mozilla Public License 2.0 covers, and is +itself under that licence. + +diff --git a/src/impl/peerconnection.hpp b/src/impl/peerconnection.hpp +--- a/src/impl/peerconnection.hpp ++++ b/src/impl/peerconnection.hpp +@@ -154,6 +154,7 @@ private: + shared_ptr mIceTransport; + shared_ptr mDtlsTransport; + std::mutex mDtlsTransportInitMutex; ++ std::mutex mSctpTransportInitMutex; + shared_ptr mSctpTransport; + + std::unordered_map> mDataChannels; // by stream ID +diff --git a/src/impl/peerconnection.cpp b/src/impl/peerconnection.cpp +--- a/src/impl/peerconnection.cpp ++++ b/src/impl/peerconnection.cpp +@@ -304,6 +304,10 @@ shared_ptr PeerConnection::initDtlsTransport() { + + shared_ptr PeerConnection::initSctpTransport() { + try { ++ // The DTLS transport's Connected callback and processRemoteDescription() may both start ++ // the SCTP transport: the second must find the first's rather than replace it, which ++ // would destroy the first and stop the DTLS transport under it. ++ std::lock_guard lock(mSctpTransportInitMutex); + if (auto transport = std::atomic_load(&mSctpTransport)) + return transport; + From 9ffb4b910756768fb2c8f1faaa2638d8c9fe9078 Mon Sep 17 00:00:00 2001 From: R Date: Mon, 23 Nov 2026 17:06:50 -0300 Subject: [PATCH 2/6] libs/hash, libs/webrtc: the gitlinks at the merges of hash's C4324 and constinit fixes and of webrtc's libdatachannel notes (eed3aab, fc1f57a) --- libs/hash | 2 +- libs/webrtc | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/libs/hash b/libs/hash index 3af42a2..eed3aab 160000 --- a/libs/hash +++ b/libs/hash @@ -1 +1 @@ -Subproject commit 3af42a2a9abb617524d7c38e0c53beaa46ff3b66 +Subproject commit eed3aab4954871060b00ac59f9f10eb4b3b40226 diff --git a/libs/webrtc b/libs/webrtc index 8863afc..fc1f57a 160000 --- a/libs/webrtc +++ b/libs/webrtc @@ -1 +1 @@ -Subproject commit 8863afc6d33f2b4fbb6fc32d81a9c1df9f1410de +Subproject commit fc1f57ae0c63f13ef0a62da397b5f1e4585bb4f8 From 4fd3a88555efcd412e95b24961d4636c33ec3362 Mon Sep 17 00:00:00 2001 From: R Date: Mon, 23 Nov 2026 21:51:23 -0300 Subject: [PATCH 3/6] build: libdatachannel's build bounds its SCTP cleanup and restarts usrsctp's iterator thread, for a native test that hung about once in 3000 runs on MSVC webcpp::webrtc's native test makes and destroys a runtime per test. On MSVC 14.5 x64 it hung about once in 3000 to 4000 runs, without the earlier patches too. The dumps showed the main thread in rtcPreload() waiting for libdatachannel's initialization lock, and the cleanup thread holding that lock in SctpTransport::Cleanup(), which calls usrsctp_finish() until it succeeds while usrsctp holds one endpoint it never frees: - usrsctp keeps its iterator thread's MUST_EXIT and EXITED flags across usrsctp_finish() and usrsctp_init(), so after the first cleanup each new iterator thread exits at once, and an iterator queued afterwards (the address work queue) holds its endpoint forever. The dumps showed the flags at 3, no iterator thread and an iterator holding that endpoint; a small program over the pinned libusrsctp.a reads the flags at 3 after a second usrsctp_init(), and at 0 with usrsctp-iterator-restart.patch, which clears them when the thread starts. - With that fixed, an association whose free began on the SHUTDOWN-ACK path was still left, in one run of about 9600, with no timer and no reference to free it (the dumps show states no single path reaches; upstream is told, with no fix). sctp-cleanup-bounded.patch bounds the SCTP cleanup to five seconds, within rtcCleanup()'s ten: usrsctp then stays initialized for the next initialization, which uses it, and the endpoint leaks instead of the process hanging. build.py lets a patch change the pinned usrsctp's sources (deps/usrsctp/usrsctplib/) besides libdatachannel's src/; each patch is under the licence of the files it changes. --- CODING-GUIDELINES.md | 23 +++++-- tools/libdatachannel/build.py | 18 +++-- tools/libdatachannel/build_test.py | 11 ++- .../patches/sctp-cleanup-bounded.patch | 68 +++++++++++++++++++ .../patches/usrsctp-iterator-restart.patch | 33 +++++++++ 5 files changed, 138 insertions(+), 15 deletions(-) create mode 100644 tools/libdatachannel/patches/sctp-cleanup-bounded.patch create mode 100644 tools/libdatachannel/patches/usrsctp-iterator-restart.patch diff --git a/CODING-GUIDELINES.md b/CODING-GUIDELINES.md index 326e112..b3a1cb7 100644 --- a/CODING-GUIDELINES.md +++ b/CODING-GUIDELINES.md @@ -1024,14 +1024,23 @@ Trystero's later API migration or prove libdatachannel's upstream test suite. The checkout and the archive stay upstream's bytes: `tools/libdatachannel/build.py` applies the patches of `tools/libdatachannel/patches`, in the order of their names, to its verified staged copy alone, each correcting a defect of the -pinned release until upstream fixes it, each changing only `src/`, each under -libdatachannel's MPL-2.0, and each an input of the configuration's key. A patch +pinned release until upstream fixes it, each changing only sources +(libdatachannel's `src/` or the pinned usrsctp's `deps/usrsctp/usrsctplib/`), +each under the licence of the files it changes (libdatachannel's MPL-2.0, +usrsctp's BSD-3-Clause), and each an input of the configuration's key. A patch the sources hold already, or one that no longer applies, fails the build by -name, so that it is removed or updated rather than skipped. The first two -correct the native connection races found on 2026-11-23: +name, so that it is removed or updated rather than skipped. They correct what +webcpp::webrtc's native tests met on 2026-11-23: two connection races, `dtls-mtu-before-incoming.patch` (the DTLS server answered a ClientHello kept before its start while its MTU was unset, and failed) and `sctp-init-once.patch` -(two threads each started an SCTP transport, and the replaced one stopped DTLS). +(two threads each started an SCTP transport, and the replaced one stopped +DTLS), and a hang of a process that makes a second runtime, which waited +forever for a cleanup that could not finish while usrsctp held an endpoint: +`sctp-cleanup-bounded.patch` (the SCTP cleanup gives up after five seconds and +leaves usrsctp initialized for the next runtime) and +`usrsctp-iterator-restart.patch` (after a first cleanup, usrsctp's iterator +thread exited as soon as it started, and an iterator queued later held its +endpoint forever). The CA bundle is an authorized exception to the source-submodule rule: curl publishes dated PEM artifacts, preserved byte-for-byte with source URL, SHA-256, @@ -8640,7 +8649,9 @@ trystero on it (built, trystero's branch `webrtc-backend`, in its the standard library, and libdatachannel is the smallest complete implementation. The patches (2026-11-23, pending the owner's approval) correct two races of the pinned release that failed a native connection about once in - 300 runs under load; each is under MPL-2.0 and is removed once upstream + 300 runs under load, and two defects, of its SCTP cleanup and of its usrsctp, + that hung a process making a second runtime about once in 3000 runs on MSVC; + each is under the licence of the files it changes and is removed once upstream carries its fix. Source: `libraries/webrtc/openspec/changes/genesis/design.md` D16 (proposals). - **webcpp::webrtc knows nothing of xactor: an actor that needs a peer holds a diff --git a/tools/libdatachannel/build.py b/tools/libdatachannel/build.py index 6dd9182..db8c535 100644 --- a/tools/libdatachannel/build.py +++ b/tools/libdatachannel/build.py @@ -38,6 +38,10 @@ def run(command: list[str], directory: Path, env: dict[str, str], log: Path) -> raise RuntimeError(f'command failed ({result.returncode}); full log: {log}') +# The source trees a patch may change: libdatachannel's own and the pinned usrsctp's. +SOURCES = ('src/', 'deps/usrsctp/usrsctplib/') + + def patches() -> list[Path]: """The corrections patches/ holds, in the order of their names.""" return sorted((HERE / 'patches').glob('*.patch')) @@ -46,10 +50,11 @@ def patches() -> list[Path]: def patch_source(staged: Path) -> None: """Apply each patch to the verified staged copy, never to the pinned checkout. - Each patch corrects a defect of the pinned libdatachannel until a release fixes it upstream, - and changes only its sources under src/. One that is applied already (the pin holds the fix) - or that no longer applies fails the build, naming it, so that it is removed or updated rather - than skipped. git looks for no repository above the staged copy. + Each patch corrects a defect of the pinned libdatachannel, or of the usrsctp it pins, until a + release fixes it upstream, and changes only sources: libdatachannel's under src/ or usrsctp's + under deps/usrsctp/usrsctplib/. One that is applied already (the pin holds the fix) or that + no longer applies fails the build, naming it, so that it is removed or updated rather than + skipped. git looks for no repository above the staged copy. """ env = os.environ.copy() env['GIT_CEILING_DIRECTORIES'] = str(staged.parent) @@ -57,8 +62,9 @@ def patch_source(staged: Path) -> None: name = f'tools/libdatachannel/patches/{patch.name}' touched = [line.split(' ', 1)[1] for line in patch.read_text().splitlines() if line.startswith(('--- ', '+++ '))] - if any(not path.startswith(('a/src/', 'b/src/')) for path in touched): - raise RuntimeError(f'{name} patches a file outside src/') + if any(not path.startswith(tuple(f'{side}/{tree}' for side in 'ab' for tree in SOURCES)) + for path in touched): + raise RuntimeError(f'{name} patches a file outside {" and ".join(SOURCES)}') def apply(*arguments: str) -> bool: return subprocess.run(['git', '-C', str(staged), 'apply', *arguments, str(patch)], diff --git a/tools/libdatachannel/build_test.py b/tools/libdatachannel/build_test.py index e81fcaf..bb57521 100644 --- a/tools/libdatachannel/build_test.py +++ b/tools/libdatachannel/build_test.py @@ -131,11 +131,12 @@ class PatchTest(unittest.TestCase): SOURCE = Path(__file__).resolve().parents[2] / 'third_party/libs/libdatachannel' def setUp(self) -> None: - if not (self.SOURCE / 'src').is_dir(): + if not all((self.SOURCE / tree).is_dir() for tree in build.SOURCES): self.skipTest('third_party/libs/libdatachannel is not checked out') self.directory = tempfile.TemporaryDirectory(prefix='libdatachannel patches ') self.staged = Path(self.directory.name) / 'source' - shutil.copytree(self.SOURCE / 'src', self.staged / 'src') + for tree in build.SOURCES: + shutil.copytree(self.SOURCE / tree, self.staged / tree) def tearDown(self) -> None: self.directory.cleanup() @@ -151,6 +152,10 @@ def test_each_patch_applies_to_the_pinned_sources(self) -> None: sctp = connection[connection.index('PeerConnection::initSctpTransport() {'):] self.assertLess(sctp.index('std::lock_guard lock(mSctpTransportInitMutex);'), sctp.index('std::atomic_load(&mSctpTransport)')) + iterator = (self.staged / 'deps/usrsctp/usrsctplib/netinet/sctp_bsd_addr.c').read_text() + startup = iterator[iterator.index('sctp_startup_iterator(void)'):] + self.assertLess(startup.index('sctp_it_ctl.iterator_flags = 0;'), + startup.index('sctp_userspace_thread_create(')) def test_a_patch_the_sources_hold_already_fails_the_build(self) -> None: build.patch_source(self.staged) @@ -163,7 +168,7 @@ def test_a_patch_outside_src_fails_the_build(self) -> None: (patches / 'outside.patch').write_text( '--- a/CMakeLists.txt\n+++ b/CMakeLists.txt\n@@ -1 +1 @@\n-x\n+y\n') with patch.object(build, 'patches', return_value=[patches / 'outside.patch']): - with self.assertRaisesRegex(RuntimeError, 'outside src/'): + with self.assertRaisesRegex(RuntimeError, 'outside src/ and deps/usrsctp/usrsctplib/'): build.patch_source(self.staged) diff --git a/tools/libdatachannel/patches/sctp-cleanup-bounded.patch b/tools/libdatachannel/patches/sctp-cleanup-bounded.patch new file mode 100644 index 0000000..b0a744e --- /dev/null +++ b/tools/libdatachannel/patches/sctp-cleanup-bounded.patch @@ -0,0 +1,68 @@ +libdatachannel 0.24.6's SctpTransport::Cleanup() calls usrsctp_finish() until it succeeds, which +it does only once usrsctp holds no endpoint, and it runs under the global initialization lock. +When usrsctp keeps an endpoint it never frees, the cleanup never ends: rtcCleanup() gives up after +ten seconds, and the next rtcPreload(), or any call that initializes libdatachannel again, waits +forever for that lock. webcpp::webrtc's native test, which makes and destroys a runtime per test, +hung so about once in 3000 runs on MSVC 14.5 x64 (2026-11-23): its dumps showed the cleanup in +this loop, the main thread in rtcPreload(), and usrsctp holding one endpoint whose association, +past its SHUTDOWN, had no timer and no reference left to free it. This patch bounds the wait to +five seconds, within rtcCleanup()'s ten: past it usrsctp stays initialized, with the set of +transports, and the next initialization uses it rather than initializing it again. Remove this +file once the libdatachannel that tools/libdatachannel/pin.json pins bounds its SCTP cleanup: +build.py then fails, saying so. + +This patch changes files of libdatachannel, which the Mozilla Public License 2.0 covers, and is +itself under that licence. + +diff --git a/src/impl/sctptransport.cpp b/src/impl/sctptransport.cpp +--- a/src/impl/sctptransport.cpp ++++ b/src/impl/sctptransport.cpp +@@ -84,8 +84,12 @@ + + SctpTransport::InstancesSet* SctpTransport::Instances = nullptr; + ++// Whether usrsctp is initialized: Cleanup() leaves it so when it cannot finish. ++static bool UsrsctpInitialized = false; ++ + void SctpTransport::Init() { +- usrsctp_init(0, SctpTransport::WriteCallback, SctpTransport::DebugCallback); ++ if (!std::exchange(UsrsctpInitialized, true)) ++ usrsctp_init(0, SctpTransport::WriteCallback, SctpTransport::DebugCallback); + usrsctp_sysctl_set_sctp_pr_enable(1); // Enable Partial Reliability Extension (RFC 3758) + usrsctp_sysctl_set_sctp_ecn_enable(0); // Disable Explicit Congestion Notification + #ifndef SCTP_ACCEPT_ZERO_CHECKSUM +@@ -95,7 +99,8 @@ + usrsctp_sysctl_set_sctp_debug_on(SCTP_DEBUG_ALL); + #endif + +- Instances = new InstancesSet; ++ if (!Instances) ++ Instances = new InstancesSet; + } + + void SctpTransport::SetSettings(const SctpSettings &s) { +@@ -148,11 +153,20 @@ + } + + void SctpTransport::Cleanup() { +- while (usrsctp_finish()) ++ // usrsctp_finish() fails while usrsctp still holds an endpoint, and an endpoint whose ++ // association usrsctp never frees is held forever. Waiting for it would hold the global lock ++ // forever, and the next initialization would wait for it too: after a bound, usrsctp stays ++ // initialized, with the instances, for the next initialization to use. ++ for (int attempt = 0; attempt < 50; ++attempt) { ++ if (usrsctp_finish() == 0) { ++ UsrsctpInitialized = false; ++ delete Instances; ++ Instances = nullptr; ++ return; ++ } + std::this_thread::sleep_for(100ms); +- +- delete Instances; +- Instances = nullptr; ++ } ++ PLOG_WARNING << "SCTP cleanup incomplete: usrsctp still holds an endpoint, it stays initialized"; + } + + SctpTransport::SctpTransport(shared_ptr lower, const Configuration &config, Ports ports, diff --git a/tools/libdatachannel/patches/usrsctp-iterator-restart.patch b/tools/libdatachannel/patches/usrsctp-iterator-restart.patch new file mode 100644 index 0000000..8061ea6 --- /dev/null +++ b/tools/libdatachannel/patches/usrsctp-iterator-restart.patch @@ -0,0 +1,33 @@ +usrsctp, as libdatachannel 0.24.6 pins it (deps/usrsctp at fec583d), keeps the iterator thread's +flags across usrsctp_finish() and usrsctp_init(): sctp_pcb_finish() sets SCTP_ITERATOR_MUST_EXIT, +the exiting thread sets SCTP_ITERATOR_EXITED, and sctp_startup_iterator() never clears them, so +every initialization after the first finish starts an iterator thread that exits at once. An +iterator queued afterwards, as the address work queue does after usrsctp_register_address() or +usrsctp_deregister_address(), which every SCTP transport of libdatachannel calls, then never runs +and keeps its reference to an endpoint forever: that endpoint is never freed, usrsctp_finish() +never succeeds, libdatachannel's SctpTransport::Cleanup() loops, rtcCleanup() gives up after ten +seconds and the next rtcPreload() waits forever for the cleanup's lock. A process that destroys +its webcpp::webrtc::runtime and makes another one met it: webcpp::webrtc's native test hung about +once in 3000 runs on MSVC 14.5 (2026-11-23; the dumps showed the flags at 3, the thread gone and +an iterator holding the last endpoint). This patch clears the flags when the thread is started. +Remove this file once the usrsctp that libdatachannel pins clears them: build.py then fails, saying +so. + +This patch changes files of usrsctp, which the BSD 3-Clause License covers, and is itself under +that licence. + +diff --git a/deps/usrsctp/usrsctplib/netinet/sctp_bsd_addr.c b/deps/usrsctp/usrsctplib/netinet/sctp_bsd_addr.c +--- a/deps/usrsctp/usrsctplib/netinet/sctp_bsd_addr.c ++++ b/deps/usrsctp/usrsctplib/netinet/sctp_bsd_addr.c +@@ -180,6 +180,11 @@ + SCTP_ITERATOR_LOCK_INIT(); + SCTP_IPI_ITERATOR_WQ_INIT(); + TAILQ_INIT(&sctp_it_ctl.iteratorhead); ++ /* ++ * A previous sctp_pcb_finish() left SCTP_ITERATOR_MUST_EXIT and SCTP_ITERATOR_EXITED set: ++ * a thread started with them would exit at once and never run an iterator. ++ */ ++ sctp_it_ctl.iterator_flags = 0; + #if defined(__Userspace__) + if (sctp_userspace_thread_create(&sctp_it_ctl.thread_proc, &sctp_iterator_thread)) { + SCTP_PRINTF("ERROR: Creating sctp_iterator_thread failed.\n"); From f3ac5ff75cbbf062d181bab894085bcd1763fc3f Mon Sep 17 00:00:00 2001 From: R Date: Mon, 23 Nov 2026 21:54:16 -0300 Subject: [PATCH 4/6] libs/webrtc: the gitlink at the native page's note on the cleanup and usrsctp corrections (local, for the lanes) --- libs/webrtc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/webrtc b/libs/webrtc index fc1f57a..0687506 160000 --- a/libs/webrtc +++ b/libs/webrtc @@ -1 +1 @@ -Subproject commit fc1f57ae0c63f13ef0a62da397b5f1e4585bb4f8 +Subproject commit 0687506c9d04b00279ee34b305fbd02212adc91a From d05b12a965c067598d50464c7993b7d6ee9e6770 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 24 Nov 2026 02:58:30 -0300 Subject: [PATCH 5/6] libs/webrtc: the gitlink at the native test's guarded checks (local, for the lanes) --- libs/webrtc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/webrtc b/libs/webrtc index 0687506..bcedd4a 160000 --- a/libs/webrtc +++ b/libs/webrtc @@ -1 +1 @@ -Subproject commit 0687506c9d04b00279ee34b305fbd02212adc91a +Subproject commit bcedd4ade78aa7c0b2d709e90fcbb599ac62d92d From 8f6584f22d018d5daf1d41965da869924e66c6d5 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 24 Nov 2026 03:49:46 -0300 Subject: [PATCH 6/6] libs/webrtc: the gitlink at the merge of webrtc's notes on the cleanup and usrsctp corrections and the native test's guarded checks (d8bcf37) --- libs/webrtc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/webrtc b/libs/webrtc index bcedd4a..d8bcf37 160000 --- a/libs/webrtc +++ b/libs/webrtc @@ -1 +1 @@ -Subproject commit bcedd4ade78aa7c0b2d709e90fcbb599ac62d92d +Subproject commit d8bcf3723b9ddb14c7a8c285c6127899e6d85498