From 302fb8210b3faebbb9e0ce35c31ff9965f9c77ce Mon Sep 17 00:00:00 2001 From: Benjamin Sergeant Date: Mon, 23 Nov 2026 14:48:46 -0800 Subject: [PATCH 1/7] Add an opt-in self-contained HTTP/2 WebSocket client --- CMakeLists.txt | 4 + docker/Dockerfile.h2-proxy | 5 +- docs/h2-proxy.md | 11 +- docs/http2.md | 100 ++++ docs/usage.md | 7 + ixwebsocket/IXHpack.cpp | 380 +++++++++++++ ixwebsocket/IXHpack.h | 27 + ixwebsocket/IXSocket.h | 12 +- ixwebsocket/IXSocketAppleSSL.cpp | 50 ++ ixwebsocket/IXSocketFactory.cpp | 5 + ixwebsocket/IXSocketHttp2.cpp | 769 +++++++++++++++++++++++++++ ixwebsocket/IXSocketHttp2.h | 62 +++ ixwebsocket/IXSocketMbedTLS.cpp | 39 +- ixwebsocket/IXSocketMbedTLS.h | 1 + ixwebsocket/IXSocketNetwork.cpp | 51 ++ ixwebsocket/IXSocketOpenSSL.cpp | 46 ++ ixwebsocket/IXSocketTLSOptions.cpp | 11 + ixwebsocket/IXSocketTLSOptions.h | 4 + ixwebsocket/IXWebSocket.cpp | 14 +- ixwebsocket/IXWebSocket.h | 3 + ixwebsocket/IXWebSocketHandshake.cpp | 115 +++- ixwebsocket/IXWebSocketHandshake.h | 3 +- ixwebsocket/IXWebSocketTransport.cpp | 27 +- ixwebsocket/IXWebSocketTransport.h | 4 +- makefile.dev | 6 +- test/CMakeLists.txt | 3 + test/IXHttp2Test.cpp | 460 ++++++++++++++++ test/h2_proxy/CMakeLists.txt | 17 +- test/h2_proxy/native_client.cpp | 181 +++++++ test/h2_proxy/native_peer.py | 174 ++++++ test/h2_proxy/run.py | 66 ++- tools/run_h2_proxy.py | 3 +- ws/ws.cpp | 18 +- 33 files changed, 2647 insertions(+), 31 deletions(-) create mode 100644 docs/http2.md create mode 100644 ixwebsocket/IXHpack.cpp create mode 100644 ixwebsocket/IXHpack.h create mode 100644 ixwebsocket/IXSocketHttp2.cpp create mode 100644 ixwebsocket/IXSocketHttp2.h create mode 100644 test/IXHttp2Test.cpp create mode 100644 test/h2_proxy/native_client.cpp create mode 100644 test/h2_proxy/native_peer.py diff --git a/CMakeLists.txt b/CMakeLists.txt index b9052f0c..a9b3b69b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -58,6 +58,7 @@ set( IXWEBSOCKET_SOURCES ixwebsocket/IXGetFreePort.cpp ixwebsocket/IXGzipCodec.cpp ixwebsocket/IXHttp.cpp + ixwebsocket/IXHpack.cpp ixwebsocket/IXHttpClient.cpp ixwebsocket/IXHttpServer.cpp ixwebsocket/IXNetSystem.cpp @@ -66,6 +67,7 @@ set( IXWEBSOCKET_SOURCES ixwebsocket/IXSelectInterruptPipe.cpp ixwebsocket/IXSelectInterruptEvent.cpp ixwebsocket/IXSetThreadName.cpp + ixwebsocket/IXSocketHttp2.cpp ixwebsocket/IXSocket.cpp ixwebsocket/IXSocketConnect.cpp ixwebsocket/IXSocketFactory.cpp @@ -98,6 +100,7 @@ set( IXWEBSOCKET_HEADERS ixwebsocket/IXExponentialBackoff.h ixwebsocket/IXGetFreePort.h ixwebsocket/IXGzipCodec.h + ixwebsocket/IXHpack.h ixwebsocket/IXHttp.h ixwebsocket/IXHttpClient.h ixwebsocket/IXHttpServer.h @@ -109,6 +112,7 @@ set( IXWEBSOCKET_HEADERS ixwebsocket/IXSelectInterruptPipe.h ixwebsocket/IXSelectInterruptEvent.h ixwebsocket/IXSetThreadName.h + ixwebsocket/IXSocketHttp2.h ixwebsocket/IXSocket.h ixwebsocket/IXSocketConnect.h ixwebsocket/IXSocketFactory.h diff --git a/docker/Dockerfile.h2-proxy b/docker/Dockerfile.h2-proxy index 7496eb87..3a4d9f7e 100644 --- a/docker/Dockerfile.h2-proxy +++ b/docker/Dockerfile.h2-proxy @@ -1,13 +1,13 @@ FROM debian:bookworm-slim AS build RUN apt-get update && apt-get install -y --no-install-recommends \ - g++ cmake ninja-build zlib1g-dev && rm -rf /var/lib/apt/lists/* + g++ cmake ninja-build zlib1g-dev libssl-dev && rm -rf /var/lib/apt/lists/* WORKDIR /src COPY CMakeLists.txt ixwebsocket-config.cmake.in ixwebsocket.pc.in ./ COPY CMake/ CMake/ COPY ixwebsocket/ ixwebsocket/ COPY test/h2_proxy/ test/h2_proxy/ RUN cmake -S test/h2_proxy -B build -GNinja -DCMAKE_BUILD_TYPE=Release \ - -DCMAKE_UNITY_BUILD=ON && cmake --build build --parallel 2 + -DCMAKE_UNITY_BUILD=ON -DH2_PROXY_NATIVE_CLIENT=ON -DUSE_OPEN_SSL=ON && cmake --build build --parallel 2 FROM debian:bookworm-slim RUN apt-get update && apt-get install -y --no-install-recommends \ @@ -17,5 +17,6 @@ COPY test/h2_proxy/requirements.txt /requirements.txt RUN python3 -m venv /venv && /venv/bin/pip install --no-cache-dir -r /requirements.txt COPY test/h2_proxy/ /app/test/h2_proxy/ COPY --from=build /src/build/h2_proxy_server /app/build/h2-proxy/h2_proxy_server +COPY --from=build /src/build/h2_proxy_client /app/build/h2-proxy/h2_proxy_client WORKDIR /app ENTRYPOINT ["/venv/bin/python", "/app/test/h2_proxy/run.py"] diff --git a/docs/h2-proxy.md b/docs/h2-proxy.md index 0099b5fd..b72b43d2 100644 --- a/docs/h2-proxy.md +++ b/docs/h2-proxy.md @@ -34,6 +34,7 @@ normally and checks that it joins its workers and exits successfully. Coverage includes: +- Native IXWebSocket H2 client with compression on/off and both close directions. - TLS certificate validation, ALPN, Extended CONNECT, and HTTP/2 success status. - Forwarded Origin/custom headers, paths, and query strings. - Empty, Unicode and binary messages, fragmentation, and ping/pong. @@ -49,9 +50,13 @@ After the WebSocket Close exchange, nghttpx can retire a stream with when both WebSocket Close frames have been exchanged. Premature resets and other reset codes fail the test. -This is a protocol integration test using Python `h2` and `wsproto`, not browser -automation, an Autobahn run, or a performance benchmark. It adds no native HTTP/2 -support to IXWebSocket. It runs separately from the regular unit suite. +The native C++ client runs through the proxy in four compression/close modes; +it also runs against an independent Python TLS/H2 peer for simultaneous large +transfers, blocked-send cancellation and ALPN rejection. The Python +`h2`/`wsproto` client then checks the proxy/backend flow, +including multiplexing. The C++ client currently uses one stream per connection. +This is protocol integration coverage, not browser automation, an Autobahn run, +or a performance benchmark. It runs separately from the regular unit suite. ## Native run and Envoy reproduction diff --git a/docs/http2.md b/docs/http2.md new file mode 100644 index 00000000..4baafce9 --- /dev/null +++ b/docs/http2.md @@ -0,0 +1,100 @@ +# Experimental WebSocket client over HTTP/2 + +IXWebSocket has an opt-in, self-contained RFC 8441 client. It implements its own +HTTP/2 framing and HPACK codec and adds no HTTP/2 library dependency. +HTTP/1.1 remains the default. + +```cpp +ix::WebSocket socket; +socket.setUrl("wss://example.com/echo"); +socket.setHttp2(true); +socket.setOnMessageCallback([](const ix::WebSocketMessagePtr& message) +{ + // Existing Open, Message, Ping/Pong, Error and Close events are unchanged. +}); +socket.start(); +``` + +The command-line client also supports explicit H2 mode: + +```sh +ws connect wss://example.com/echo --http2 +``` + +Configure before connecting, as with other WebSocket settings. HTTP/2 mode +requires `wss://`, TLS 1.2 or newer, ALPN `h2`, and a peer advertising +`SETTINGS_ENABLE_CONNECT_PROTOCOL`. It uses Extended CONNECT and accepts a +successful 2xx response. If negotiation fails, the connection fails explicitly; +it does not silently switch to HTTP/1.1. The normal automatic-reconnection +setting still applies. + +This first implementation uses **one WebSocket stream per TCP/TLS connection**. +It does not pool connections or multiplex several WebSocket objects on one +connection. The HTTP client and the WebSocket/HTTP servers remain HTTP/1.1. +`connect(HttpClient&, timeout)` cannot transfer an HTTP/1.1 connection into this +mode. Cleartext HTTP/2 (`h2c`) is not implemented. + +The TLS layer negotiates ALPN using the selected existing backend: OpenSSL/ +LibreSSL, mbedTLS when built with ALPN support, Network.framework, or +SecureTransport. Existing backend certificate/trust limitations still apply. +Normal certificate and hostname verification remain enabled by default. + +Existing WebSocket framing, masking, fragmentation, compression, message limits, +callbacks, ping/pong and close handling are reused through an H2 stream adapter. +The adapter handles SETTINGS, HEADERS/CONTINUATION, flow control, PING, +WINDOW_UPDATE, GOAWAY, RST_STREAM and stream termination. Server push is disabled. +HPACK responses support the static/dynamic tables and Huffman coding. Outgoing +fields are literal and never indexed, including credentials. Compressed and +decoded header blocks are bounded at 64 KiB, the dynamic table at 4 KiB, incoming +DATA at the advertised receive window, and pending control frames at 64. + +Extra header names are encoded lowercase; Host is mapped to `:authority`. +HTTP/1.1-only headers such as Connection, Upgrade and Sec-WebSocket-Key are +rejected. Default User-Agent/Origin suppression and redirect credential handling +retain their existing APIs. The HTTP status and response headers remain available +on handshake failures. + +This is an experimental transport path with a deliberately limited connection +model. Rebuild applications against the updated headers/library. + +## Testing + +```sh +make -f makefile.dev test_h2_proxy +``` + +The Docker integration test now also runs the native C++ client through nghttpx +with compression on/off and client/server-initiated closes. It checks Unicode, +empty/binary payloads, 256 KiB messages, ping/pong and close codes/reasons. The +independent Python H2 client continues to exercise the proxy and backend. +Reports and logs remain under `build/h2-proxy/runs/`. + +Fast `IXHttp2Test` unit tests cover RFC 7541 vectors, the complete Huffman byte +alphabet, dynamic tables, malformed/truncated input, fragmented headers/reads, +partial writes, flow-control limits, cancellation and remote half closes. +They use an in-memory peer and have no deliberate sleeps or DNS dependencies. + +For another TLS backend, configure the fixture separately, for example: + +```sh +cmake -S test/h2_proxy -B build/h2-network \ + -DH2_PROXY_NATIVE_CLIENT=ON -DUSE_NETWORK_FRAMEWORK=ON +cmake --build build/h2-network --parallel +``` + +With the test requirements installed in a venv, `test/h2_proxy/native_peer.py` +runs the native executable against an independent Python TLS/H2 peer: + +```sh +python3 test/h2_proxy/native_peer.py \ + build/h2-network/h2_proxy_client server.pem server.key ca.pem +``` + +The certificates should be a server certificate/key and its trusted CA, with +`127.0.0.1` in the server certificate's subject alternative names. This check +also exercises simultaneous large messages in both directions, cancellation while +flow control blocks sending, and compression on/off without requiring a proxy. +Add `--reject-alpn` to verify that a peer without `h2` is rejected before any +HTTP bytes are sent. +See [the proxy test documentation](h2-proxy.md) for native proxy setup and the +known Envoy downgrade-handshake limitation. diff --git a/docs/usage.md b/docs/usage.md index b811be34..07ab61dc 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -204,6 +204,13 @@ call `start()` on each instance. Each connection attempt runs on its own backgro thread, so starting another client does not wait for the first handshake. `connect()` is the synchronous connection API. +### HTTP/2 client (experimental) + +Call `websocket.setHttp2(true)` before connecting to opt into RFC 8441 over +`wss://`. HTTP/1.1 remains the default. This self-contained client opens one H2 +stream per connection; it does not share connections between WebSocket objects. +See [HTTP/2 client support](http2.md) for negotiation requirements and testing. + ### Threading and callbacks `setOnMessageCallback()` handles Open, Message, Close, Error, Ping, Pong, and Fragment diff --git a/ixwebsocket/IXHpack.cpp b/ixwebsocket/IXHpack.cpp new file mode 100644 index 00000000..3af2615a --- /dev/null +++ b/ixwebsocket/IXHpack.cpp @@ -0,0 +1,380 @@ +/* Copyright (c) 2026 Machine Zone, Inc. All rights reserved. + * Static/Huffman tables are protocol constants from RFC 7541, Appendices A/B. + * No external HPACK implementation is used at build time or runtime. + */ +/* RFC 7541 table data: + * Copyright (c) 2015 IETF Trust and the persons identified as the document authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#include "IXHpack.h" + +#include +#include +#include + +namespace +{ + const std::pair staticTable[] = { + {":authority", ""}, + {":method", "GET"}, + {":method", "POST"}, + {":path", "/"}, + {":path", "/index.html"}, + {":scheme", "http"}, + {":scheme", "https"}, + {":status", "200"}, + {":status", "204"}, + {":status", "206"}, + {":status", "304"}, + {":status", "400"}, + {":status", "404"}, + {":status", "500"}, + {"accept-charset", ""}, + {"accept-encoding", "gzip, deflate"}, + {"accept-language", ""}, + {"accept-ranges", ""}, + {"accept", ""}, + {"access-control-allow-origin", ""}, + {"age", ""}, + {"allow", ""}, + {"authorization", ""}, + {"cache-control", ""}, + {"content-disposition", ""}, + {"content-encoding", ""}, + {"content-language", ""}, + {"content-length", ""}, + {"content-location", ""}, + {"content-range", ""}, + {"content-type", ""}, + {"cookie", ""}, + {"date", ""}, + {"etag", ""}, + {"expect", ""}, + {"expires", ""}, + {"from", ""}, + {"host", ""}, + {"if-match", ""}, + {"if-modified-since", ""}, + {"if-none-match", ""}, + {"if-range", ""}, + {"if-unmodified-since", ""}, + {"last-modified", ""}, + {"link", ""}, + {"location", ""}, + {"max-forwards", ""}, + {"proxy-authenticate", ""}, + {"proxy-authorization", ""}, + {"range", ""}, + {"referer", ""}, + {"refresh", ""}, + {"retry-after", ""}, + {"server", ""}, + {"set-cookie", ""}, + {"strict-transport-security", ""}, + {"transfer-encoding", ""}, + {"user-agent", ""}, + {"vary", ""}, + {"via", ""}, + {"www-authenticate", ""}, + }; + const uint32_t codes[] = { + 0x1ff8, 0x7fffd8, 0xfffffe2, 0xfffffe3, 0xfffffe4, 0xfffffe5, 0xfffffe6, 0xfffffe7, + 0xfffffe8, 0xffffea, 0x3ffffffc, 0xfffffe9, 0xfffffea, 0x3ffffffd, 0xfffffeb, 0xfffffec, + 0xfffffed, 0xfffffee, 0xfffffef, 0xffffff0, 0xffffff1, 0xffffff2, 0x3ffffffe, 0xffffff3, + 0xffffff4, 0xffffff5, 0xffffff6, 0xffffff7, 0xffffff8, 0xffffff9, 0xffffffa, 0xffffffb, + 0x14, 0x3f8, 0x3f9, 0xffa, 0x1ff9, 0x15, 0xf8, 0x7fa, + 0x3fa, 0x3fb, 0xf9, 0x7fb, 0xfa, 0x16, 0x17, 0x18, + 0x0, 0x1, 0x2, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, + 0x1e, 0x1f, 0x5c, 0xfb, 0x7ffc, 0x20, 0xffb, 0x3fc, + 0x1ffa, 0x21, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, + 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, + 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, + 0xfc, 0x73, 0xfd, 0x1ffb, 0x7fff0, 0x1ffc, 0x3ffc, 0x22, + 0x7ffd, 0x3, 0x23, 0x4, 0x24, 0x5, 0x25, 0x26, + 0x27, 0x6, 0x74, 0x75, 0x28, 0x29, 0x2a, 0x7, + 0x2b, 0x76, 0x2c, 0x8, 0x9, 0x2d, 0x77, 0x78, + 0x79, 0x7a, 0x7b, 0x7ffe, 0x7fc, 0x3ffd, 0x1ffd, 0xffffffc, + 0xfffe6, 0x3fffd2, 0xfffe7, 0xfffe8, 0x3fffd3, 0x3fffd4, 0x3fffd5, 0x7fffd9, + 0x3fffd6, 0x7fffda, 0x7fffdb, 0x7fffdc, 0x7fffdd, 0x7fffde, 0xffffeb, 0x7fffdf, + 0xffffec, 0xffffed, 0x3fffd7, 0x7fffe0, 0xffffee, 0x7fffe1, 0x7fffe2, 0x7fffe3, + 0x7fffe4, 0x1fffdc, 0x3fffd8, 0x7fffe5, 0x3fffd9, 0x7fffe6, 0x7fffe7, 0xffffef, + 0x3fffda, 0x1fffdd, 0xfffe9, 0x3fffdb, 0x3fffdc, 0x7fffe8, 0x7fffe9, 0x1fffde, + 0x7fffea, 0x3fffdd, 0x3fffde, 0xfffff0, 0x1fffdf, 0x3fffdf, 0x7fffeb, 0x7fffec, + 0x1fffe0, 0x1fffe1, 0x3fffe0, 0x1fffe2, 0x7fffed, 0x3fffe1, 0x7fffee, 0x7fffef, + 0xfffea, 0x3fffe2, 0x3fffe3, 0x3fffe4, 0x7ffff0, 0x3fffe5, 0x3fffe6, 0x7ffff1, + 0x3ffffe0, 0x3ffffe1, 0xfffeb, 0x7fff1, 0x3fffe7, 0x7ffff2, 0x3fffe8, 0x1ffffec, + 0x3ffffe2, 0x3ffffe3, 0x3ffffe4, 0x7ffffde, 0x7ffffdf, 0x3ffffe5, 0xfffff1, 0x1ffffed, + 0x7fff2, 0x1fffe3, 0x3ffffe6, 0x7ffffe0, 0x7ffffe1, 0x3ffffe7, 0x7ffffe2, 0xfffff2, + 0x1fffe4, 0x1fffe5, 0x3ffffe8, 0x3ffffe9, 0xffffffd, 0x7ffffe3, 0x7ffffe4, 0x7ffffe5, + 0xfffec, 0xfffff3, 0xfffed, 0x1fffe6, 0x3fffe9, 0x1fffe7, 0x1fffe8, 0x7ffff3, + 0x3fffea, 0x3fffeb, 0x1ffffee, 0x1ffffef, 0xfffff4, 0xfffff5, 0x3ffffea, 0x7ffff4, + 0x3ffffeb, 0x7ffffe6, 0x3ffffec, 0x3ffffed, 0x7ffffe7, 0x7ffffe8, 0x7ffffe9, 0x7ffffea, + 0x7ffffeb, 0xffffffe, 0x7ffffec, 0x7ffffed, 0x7ffffee, 0x7ffffef, 0x7fffff0, 0x3ffffee, + 0x3fffffff, + }; + const unsigned char codeLengths[] = { + 13, 23, 28, 28, 28, 28, 28, 28, 28, 24, 30, 28, 28, 30, 28, 28, 28, 28, 28, 28, 28, 28, + 30, 28, 28, 28, 28, 28, 28, 28, 28, 28, 6, 10, 10, 12, 13, 6, 8, 11, 10, 10, 8, 11, + 8, 6, 6, 6, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 8, 15, 6, 12, 10, 13, 6, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 8, 7, 8, 13, 19, 13, 14, 6, 15, 5, 6, 5, 6, 5, 6, 6, 6, 5, 7, 7, 6, 6, + 6, 5, 6, 7, 6, 5, 5, 6, 7, 7, 7, 7, 7, 15, 11, 14, 13, 28, 20, 22, 20, 20, + 22, 22, 22, 23, 22, 23, 23, 23, 23, 23, 24, 23, 24, 24, 22, 23, 24, 23, 23, 23, 23, 21, + 22, 23, 22, 23, 23, 24, 22, 21, 20, 22, 22, 23, 23, 21, 23, 22, 22, 24, 21, 22, 23, 23, + 21, 21, 22, 21, 23, 22, 23, 23, 20, 22, 22, 22, 23, 22, 22, 23, 26, 26, 20, 19, 22, 23, + 22, 25, 26, 26, 26, 27, 27, 26, 24, 25, 19, 21, 26, 27, 27, 26, 27, 24, 21, 21, 26, 26, + 28, 27, 27, 27, 20, 24, 20, 21, 22, 21, 21, 23, 22, 22, 25, 25, 24, 24, 26, 23, 26, 27, + 26, 26, 27, 27, 27, 27, 27, 28, 27, 27, 27, 27, 27, 26, 30, + }; + struct HuffmanTree + { + struct Node + { + int child[2] = {-1, -1}; + int symbol = -1; + }; + std::array nodes; + HuffmanTree() + { + int count = 1; + for (int symbol = 0; symbol < 257; ++symbol) + { + int node = 0; + for (int bit = codeLengths[symbol] - 1; bit >= 0; --bit) + { + const int edge = (codes[symbol] >> bit) & 1; + if (nodes[node].child[edge] == -1) + { + nodes[node].child[edge] = count++; + } + node = nodes[node].child[edge]; + } + nodes[node].symbol = symbol; + } + } + }; + bool integer(const std::string& data, size_t& offset, unsigned prefix, size_t& value) + { + if (offset == data.size()) + { + return false; + } + const unsigned mask = (1u << prefix) - 1; + value = static_cast(data[offset++]) & mask; + if (value != mask) + { + return true; + } + unsigned shift = 0; + while (offset < data.size() && shift < sizeof(size_t) * 8) + { + const unsigned byte = static_cast(data[offset++]); + if ((byte & 127) > ((std::numeric_limits::max)() - value) >> shift) + { + return false; + } + value += size_t(byte & 127) << shift; + if (!(byte & 128)) + { + return true; + } + shift += 7; + } + return false; + } + void integer(std::string& data, size_t value, unsigned prefix, unsigned flags) + { + const unsigned mask = (1u << prefix) - 1; + if (value < mask) + { + data += char(flags | value); + return; + } + data += char(flags | mask); + value -= mask; + while (value >= 128) + { + data += char((value & 127) | 128); + value >>= 7; + } + data += char(value); + } + bool string(const std::string& data, size_t& offset, std::string& value) + { + if (offset == data.size()) + { + return false; + } + const bool huffman = (static_cast(data[offset]) & 128) != 0; + size_t length; + if (!integer(data, offset, 7, length) || length > data.size() - offset) + { + return false; + } + value.clear(); + if (!huffman) + { + value.assign(data, offset, length); + offset += length; + return true; + } + static const HuffmanTree tree; + int node = 0; + unsigned trailing = 0; + bool ones = true; + const size_t end = offset + length; + while (offset < end) + { + const unsigned byte = static_cast(data[offset++]); + for (int bit = 7; bit >= 0; --bit) + { + const unsigned edge = (byte >> bit) & 1; + node = tree.nodes[node].child[edge]; + if (node < 0) + { + return false; + } + ++trailing; + ones = ones && edge; + const int symbol = tree.nodes[node].symbol; + if (symbol >= 0) + { + if (symbol == 256 || value.size() == 65536) + { + return false; + } + value += char(symbol); + node = 0; + trailing = 0; + ones = true; + } + } + } + return node == 0 || (trailing <= 7 && ones); + } +} // namespace + +namespace ix +{ + std::string Hpack::encode(const Headers& headers) + { + std::string block; + for (const auto& field : headers) + { + block += char(0x10); // Never indexed, new name. + integer(block, field.first.size(), 7, 0); + block += field.first; + integer(block, field.second.size(), 7, 0); + block += field.second; + } + return block; + } + Hpack::Headers::value_type Hpack::indexed(size_t index) const + { + if (index && index <= 61) + { + return staticTable[index - 1]; + } + if (index > 61 && index - 62 < _dynamic.size()) + { + return _dynamic[index - 62]; + } + return {}; + } + void Hpack::evict() + { + while (_size > _capacity) + { + const auto& field = _dynamic.back(); + _size -= 32 + field.first.size() + field.second.size(); + _dynamic.pop_back(); + } + } + bool Hpack::decode(const std::string& block, Headers& headers) + { + headers.clear(); + if (block.size() > 65536) + { + return false; + } + size_t offset = 0, total = 0; + bool fields = false; + while (offset < block.size()) + { + const unsigned byte = static_cast(block[offset]); + size_t index; + if ((byte & 0xe0) == 0x20) + { + if (fields || !integer(block, offset, 5, index) || index > 4096) + { + return false; + } + _capacity = index; + evict(); + continue; + } + fields = true; + const bool full = (byte & 128) != 0; + const bool insert = !full && (byte & 64); + if (!integer(block, offset, full ? 7 : (insert ? 6 : 4), index)) + { + return false; + } + auto field = indexed(index); + if (full) + { + if (field.first.empty()) + { + return false; + } + } + else + { + if (index && field.first.empty()) + { + return false; + } + if (!index && !string(block, offset, field.first)) + { + return false; + } + if (!string(block, offset, field.second)) + { + return false; + } + } + total += 32 + field.first.size() + field.second.size(); + if (field.first.empty() || total > 65536) + { + return false; + } + if (insert) + { + _size += 32 + field.first.size() + field.second.size(); + _dynamic.push_front(field); + evict(); + } + headers.push_back(std::move(field)); + } + return true; + } +} // namespace ix diff --git a/ixwebsocket/IXHpack.h b/ixwebsocket/IXHpack.h new file mode 100644 index 00000000..d9c70af0 --- /dev/null +++ b/ixwebsocket/IXHpack.h @@ -0,0 +1,27 @@ +/* Copyright (c) 2026 Machine Zone, Inc. All rights reserved. */ +#pragma once +#include +#include +#include +#include +#include + +namespace ix +{ + // RFC 7541. Each decoder belongs to one HTTP/2 connection. + class Hpack + { + public: + using Headers = std::vector>; + // Literal, never-indexed request fields avoid retaining credentials. + static std::string encode(const Headers& headers); + bool decode(const std::string& block, Headers& headers); + + private: + Headers::value_type indexed(size_t index) const; + void evict(); + std::deque _dynamic; + size_t _capacity = 4096; + size_t _size = 0; + }; +} // namespace ix diff --git a/ixwebsocket/IXSocket.h b/ixwebsocket/IXSocket.h index 27027238..3d51d3e5 100644 --- a/ixwebsocket/IXSocket.h +++ b/ixwebsocket/IXSocket.h @@ -43,10 +43,15 @@ namespace ix // Functions to check whether there is activity on the socket PollResultType poll(int timeoutMs = kDefaultPollTimeout); - bool wakeUpFromPoll(uint64_t wakeUpCode); - bool isWakeUpFromPollSupported(); + virtual bool wakeUpFromPoll(uint64_t wakeUpCode); + virtual bool isWakeUpFromPollSupported(); - PollResultType isReadyToRead(int timeoutMs); + virtual PollResultType isReadyToRead(int timeoutMs); + + std::string getNegotiatedProtocol() const + { + return _negotiatedProtocol; + } // Virtual methods virtual bool accept(std::string& errMsg); @@ -93,6 +98,7 @@ namespace ix int port, std::string& error, const CancellationRequest& cancelled); + std::string _negotiatedProtocol; ProxyOptions _proxyOptions; std::atomic _sockfd; std::mutex _socketMutex; diff --git a/ixwebsocket/IXSocketAppleSSL.cpp b/ixwebsocket/IXSocketAppleSSL.cpp index 6266e175..2d32ba1d 100644 --- a/ixwebsocket/IXSocketAppleSSL.cpp +++ b/ixwebsocket/IXSocketAppleSSL.cpp @@ -202,6 +202,27 @@ namespace ix } } while (status == errSSLWouldBlock || status == errSSLServerAuthCompleted); + if (status == noErr && !_tlsOptions.alpnProtocols.empty()) + { + if (__builtin_available(macOS 10.13, iOS 11.0, *)) + { + CFArrayRef protocols = nullptr; + if (SSLCopyALPNProtocols(_sslContext, &protocols) == noErr && protocols) + { + if (CFArrayGetCount(protocols)) + { + char selected[256] = {}; + auto value = static_cast(CFArrayGetValueAtIndex(protocols, 0)); + if (CFStringGetCString( + value, selected, sizeof(selected), kCFStringEncodingUTF8)) + { + _negotiatedProtocol = selected; + } + } + CFRelease(protocols); + } + } + } return status; } @@ -210,6 +231,7 @@ namespace ix std::string& errMsg, const CancellationRequest& isCancellationRequested) { + _negotiatedProtocol.clear(); if (_tlsOptions.isUsingInMemoryCert() || _tlsOptions.isUsingInMemoryKey()) { errMsg = "SecureTransport does not support in-memory client credentials; use " @@ -232,6 +254,34 @@ namespace ix _sslContext, SocketAppleSSL::readFromSocket, SocketAppleSSL::writeToSocket); SSLSetConnection(_sslContext, this); SSLSetProtocolVersionMin(_sslContext, kTLSProtocol12); + if (!_tlsOptions.alpnProtocols.empty()) + { + if (__builtin_available(macOS 10.13, iOS 11.0, *)) + { + auto protocols = + CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); + for (const auto& protocol : _tlsOptions.alpnProtocols) + { + auto value = CFStringCreateWithCString( + kCFAllocatorDefault, protocol.c_str(), kCFStringEncodingUTF8); + CFArrayAppendValue(protocols, value); + CFRelease(value); + } + const auto result = SSLSetALPNProtocols(_sslContext, protocols); + CFRelease(protocols); + if (result != noErr) + { + errMsg = "Cannot configure ALPN"; + return false; + } + } + else + { + errMsg = "ALPN requires macOS 10.13 / iOS 11 or newer"; + return false; + } + } + if (!_tlsOptions.disable_hostname_validation) { diff --git a/ixwebsocket/IXSocketFactory.cpp b/ixwebsocket/IXSocketFactory.cpp index 3ed90570..76bf17b8 100644 --- a/ixwebsocket/IXSocketFactory.cpp +++ b/ixwebsocket/IXSocketFactory.cpp @@ -35,6 +35,11 @@ namespace ix { (void) tlsOptions; errorMsg.clear(); + if (tls && !tlsOptions.alpnProtocols.empty() && !tlsOptions.isValid()) + { + errorMsg = tlsOptions.getErrorMsg(); + return nullptr; + } #if !defined(IXWEBSOCKET_USE_OPEN_SSL) || OPENSSL_VERSION_NUMBER < 0x10101000L || \ defined(LIBRESSL_VERSION_NUMBER) if (tls && !tlsOptions.keyLogFile.empty()) diff --git a/ixwebsocket/IXSocketHttp2.cpp b/ixwebsocket/IXSocketHttp2.cpp new file mode 100644 index 00000000..3da5a9be --- /dev/null +++ b/ixwebsocket/IXSocketHttp2.cpp @@ -0,0 +1,769 @@ +/* Copyright (c) 2026 Machine Zone, Inc. All rights reserved. */ +#include "IXSocketHttp2.h" + +#include +#include +#include + +namespace +{ + uint32_t number(const std::string& data, size_t offset = 0) + { + uint32_t value = 0; + for (size_t i = 0; i < 4; ++i) + { + value = (value << 8) | static_cast(data[offset + i]); + } + return value; + } + std::string number(uint32_t value) + { + std::string data(4, '\0'); + for (int i = 3; i >= 0; --i) + { + data[i] = char(value); + value >>= 8; + } + return data; + } + bool validName(const std::string& name) + { + if (name.empty()) + { + return false; + } + for (unsigned char c : name) + { + if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || + (c && std::strchr("!#$%&'*+-.^_`|~", c))) + { + continue; + } + return false; + } + return true; + } + bool validValue(const std::string& value) + { + for (unsigned char c : value) + { + if (!c || c == '\r' || c == '\n') + { + return false; + } + } + return value.empty() || (value.front() != ' ' && value.front() != '\t' && + value.back() != ' ' && value.back() != '\t'); + } +} // namespace +namespace ix +{ + SocketHttp2::SocketHttp2(std::unique_ptr socket) + : _inner(std::move(socket)) + { + } + SocketHttp2::~SocketHttp2() + { + close(); + } + + bool SocketHttp2::fail(const std::string& message, uint32_t code) + { + if (_error.empty()) + { + _error = "HTTP/2: " + message; + if (_output.size() < 64) + { + Output output; + output.frame = + std::string("\0\0\10\7\0\0\0\0\0", 9) + number(uint32_t(0)) + number(code); + _output.push_back(std::move(output)); + } + } + return false; + } + bool SocketHttp2::queue( + unsigned type, unsigned flags, uint32_t stream, const std::string& payload, size_t accepted) + { + // Bound pending control traffic even if a malicious peer floods PING/SETTINGS. + if (_output.size() >= 64) + { + return fail("outbound control queue limit exceeded"); + } + Output output; + output.frame.resize(9); + output.frame[0] = char(payload.size() >> 16); + output.frame[1] = char(payload.size() >> 8); + output.frame[2] = char(payload.size()); + output.frame[3] = char(type); + output.frame[4] = char(flags); + output.frame.replace(5, 4, number(stream)); + output.frame += payload; + output.accepted = accepted; + _output.push_back(std::move(output)); + return true; + } + bool SocketHttp2::flush() + { + while (!_output.empty()) + { + auto& output = _output.front(); + const auto count = + _inner->send(&output.frame[0] + output.offset, output.frame.size() - output.offset); + if (count < 0 && Socket::isWaitNeeded()) + { + return true; + } + if (count <= 0) + { + return fail("cannot write frame"); + } + output.offset += static_cast(count); + if (output.offset == output.frame.size()) + { + if (output.accepted) + { + _accepted = output.accepted; + _dataPending = false; + _inner->wakeUpFromPoll(SelectInterrupt::kSendRequest); + } + _output.pop_front(); + } + } + return true; + } + bool SocketHttp2::headers() + { + Hpack::Headers fields; + if (!_hpack.decode(_headerBlock, fields)) + { + return fail("invalid HPACK header block", 9); + } + _headerBlock.clear(); + bool ordinary = false; + int status = 0; + WebSocketHttpHeaders headers; + for (const auto& field : fields) + { + if (!validValue(field.second)) + { + return fail("invalid response header value"); + } + if (field.first == ":status" && !_opened && !ordinary && !status) + { + if (field.second.size() != 3) + { + return fail("invalid status"); + } + for (char digit : field.second) + { + if (digit < '0' || digit > '9') + { + return fail("invalid status"); + } + status = status * 10 + digit - '0'; + } + if (status < 100 || status > 599 || status == 101) + { + return fail("invalid HTTP/2 status"); + } + continue; + } + ordinary = true; + if (!validName(field.first) || field.first == "connection" || + field.first == "upgrade" || field.first == "keep-alive" || + field.first == "proxy-connection" || field.first == "transfer-encoding" || + field.first == "te") + { + return fail("invalid response header name"); + } + if (headers.count(field.first)) + { + headers[field.first] += ", " + field.second; + } + else + { + headers[field.first] = field.second; + } + } + if (_opened) + { + if (!_headerEndStream) + { + return fail("trailers must end the stream"); + } + } + else + { + if (!status) + { + return fail("missing status"); + } + if (status < 200) + { + return !_headerEndStream || fail("informational response ended stream"); + } + _headers = std::move(headers); + _status = status; + _opened = status >= 200 && status < 300; + if (_opened && (_headerEndStream || _headers.count("content-length"))) + { + return fail("invalid successful CONNECT response"); + } + } + _ended = _headerEndStream; + return true; + } + void SocketHttp2::credit(size_t count) + { + if (!count || _ended) + { + return; + } + _receiveConnection += count; + _receiveStream += count; + queue(8, 0, 0, number(static_cast(count))); + queue(8, 0, 1, number(static_cast(count))); + } + bool SocketHttp2::frame(unsigned type, + unsigned flags, + uint32_t stream, + const std::string& payload) + { + if (_firstFrame && (type != 4 || (flags & 1))) + { + return fail("missing initial SETTINGS"); + } + _firstFrame = false; + if (_headerActive && (type != 9 || stream != 1)) + { + return fail("interleaved header block"); + } + if (type == 4) + { + if (stream || (flags & 1 ? !payload.empty() : payload.size() % 6 != 0)) + { + return fail("invalid SETTINGS", stream ? 1 : 6); + } + if (flags & 1) + { + if (!_awaitingAck) + { + return fail("unexpected SETTINGS acknowledgement"); + } + _awaitingAck = false; + return true; + } + for (size_t i = 0; i < payload.size(); i += 6) + { + const unsigned id = (static_cast(payload[i]) << 8) | + static_cast(payload[i + 1]); + const uint32_t value = number(payload, i + 2); + switch (id) + { + case 2: return fail("server sent ENABLE_PUSH"); + case 3: _maxConcurrent = value; break; + case 4: + if (value > 0x7fffffff) + { + return fail("invalid initial window", 3); + } + _sendStream += int64_t(value) - _initialWindow; + if (_sendStream > 0x7fffffff) + { + return fail("stream window overflow", 3); + } + _initialWindow = value; + break; + case 5: + if (value < 16384 || value > 0xffffff) + { + return fail("invalid frame size setting"); + } + break; + case 6: _peerHeaderLimit = value; break; + case 8: + if (value > 1 || (_extendedConnect && !value)) + { + return fail("invalid extended CONNECT setting"); + } + _extendedConnect = value != 0; + break; + default: break; + } + } + _settingsReceived = true; + return queue(4, 1, 0, ""); + } + if (type == 6) + { + if (stream || payload.size() != 8) + { + return fail("invalid PING", stream ? 1 : 6); + } + return (flags & 1) || queue(6, 1, 0, payload); + } + if (type == 7) + { + if (stream || payload.size() < 8) + { + return fail("invalid GOAWAY", stream ? 1 : 6); + } + if (!_requestSent || (number(payload) & 0x7fffffff) < 1 || number(payload, 4)) + { + return fail("peer refused or terminated the connection"); + } + return true; // Stream 1 may finish while the connection drains. + } + if (type == 8) + { + if (payload.size() != 4 || (stream && (stream != 1 || !_requestSent))) + { + return fail("invalid WINDOW_UPDATE", payload.size() != 4 ? 6 : 1); + } + const uint32_t count = number(payload) & 0x7fffffff; + auto& window = stream ? _sendStream : _sendConnection; + if (!count || window + count > 0x7fffffff) + { + return fail("invalid flow-control credit", count ? 3 : 1); + } + window += count; + _inner->wakeUpFromPoll(SelectInterrupt::kSendRequest); + return true; + } + if (type == 2) + { + if (!stream || payload.size() != 5 || (number(payload) & 0x7fffffff) == stream) + { + return fail("invalid PRIORITY", payload.size() != 5 ? 6 : 1); + } + return true; + } + if (type == 5) + { + return fail("server push is disabled"); + } + if (type == 3) + { + if (stream != 1 || !_requestSent || payload.size() != 4) + { + return fail("invalid RST_STREAM", payload.size() != 4 ? 6 : 1); + } + _ended = _reset = true; + return number(payload) == 0 || fail("peer reset the stream"); + } + if (type != 0 && type != 1 && type != 9) + { + return true; + } // Extension frame. + if (stream != 1 || !_requestSent) + { + return fail("frame on an idle or unexpected stream"); + } + if (_ended) + { + return fail("frame after END_STREAM"); + } + size_t begin = 0, end = payload.size(); + if (type != 9 && (flags & 8)) + { + if (payload.empty() || static_cast(payload[0]) >= payload.size()) + { + return fail("invalid padding"); + } + begin = 1; + end -= static_cast(payload[0]); + } + if (type == 0) + { + if (!_opened) + { + // An unsuccessful CONNECT may carry an ordinary HTTP error body. + // This dedicated connection will be discarded by the caller. + if (_status >= 300) + { + _ended = (flags & 1) != 0; + return true; + } + return fail("DATA before successful CONNECT"); + } + _receiveConnection -= payload.size(); + _receiveStream -= payload.size(); + if (_receiveConnection < 0 || _receiveStream < 0) + { + return fail("receive window exceeded", 3); + } + if (_dataOffset) + { + _data.erase(0, _dataOffset); + _dataOffset = 0; + } + _data.append(payload, begin, end - begin); + credit(payload.size() - (end - begin)); + if (flags & 1) + { + _ended = true; + } + return true; + } + if (type == 1) + { + if (_headerActive) + { + return fail("nested HEADERS"); + } + if (flags & 32) + { + if (end - begin < 5 || (number(payload, begin) & 0x7fffffff) == stream) + { + return fail("invalid HEADERS priority", end - begin < 5 ? 6 : 1); + } + begin += 5; + } + _headerEndStream = (flags & 1) != 0; + _headerActive = true; + } + else if (!_headerActive) + { + return fail("unexpected CONTINUATION"); + } + if (end - begin > 65536 - _headerBlock.size()) + { + return fail("header block too large", 11); + } + _headerBlock.append(payload, begin, end - begin); + if (flags & 4) + { + _headerActive = false; + return headers(); + } + return true; + } + bool SocketHttp2::read() + { + char buffer[16384]; + const auto count = _inner->recv(buffer, sizeof(buffer)); + if (count < 0 && Socket::isWaitNeeded()) + { + return true; + } + if (count < 0) + { + return fail("cannot read frame"); + } + if (!count) + { + _ended = true; + return _input.empty() || fail("truncated frame"); + } + _input.append(buffer, static_cast(count)); + size_t offset = 0; + while (_input.size() - offset >= 9) + { + const auto* bytes = reinterpret_cast(_input.data() + offset); + const size_t length = (size_t(bytes[0]) << 16) | (size_t(bytes[1]) << 8) | bytes[2]; + if (length > 16384) + { + return fail("frame exceeds advertised maximum", 6); + } + if (_input.size() - offset < length + 9) + { + break; + } + const uint32_t stream = number(_input, offset + 5) & 0x7fffffff; + if (!frame(bytes[3], bytes[4], stream, _input.substr(offset + 9, length))) + { + return false; + } + offset += length + 9; + } + _input.erase(0, offset); + return flush(); + } + WebSocketInitResult SocketHttp2::handshake(const Hpack::Headers& fields, + const CancellationRequest& cancelled) + { + std::lock_guard lock(_mutex); + const std::string preface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"; + if (!_inner->writeBytes(preface, cancelled)) + { + return WebSocketInitResult(false, 0, "Cannot send HTTP/2 preface"); + } + // Disable server push, and bound the decoded response header list. + queue(4, 0, 0, std::string("\0\2\0\0\0\0\0\6\0\1\0\0", 12)); + while (_error.empty() && !_status && !_ended) + { + if (cancelled && cancelled()) + { + fail("handshake cancelled or timed out"); + break; + } + if (_settingsReceived && !_requestSent) + { + if (!_extendedConnect) + { + fail("peer does not enable extended CONNECT", 0); + break; + } + if (_maxConcurrent) + { + size_t headerSize = 0; + for (const auto& field : fields) + { + headerSize += 32 + field.first.size() + field.second.size(); + } + if (headerSize > _peerHeaderLimit || headerSize > 65536) + { + fail("request headers exceed peer limit"); + break; + } + const std::string block = Hpack::encode(fields); + for (size_t offset = 0; offset < block.size(); offset += 16384) + { + const size_t length = (std::min) (size_t(16384), block.size() - offset); + queue(offset ? 9 : 1, + offset + length == block.size() ? 4 : 0, + 1, + block.substr(offset, length)); + } + _requestSent = true; + } + } + if (!flush()) + { + break; + } + if (!_output.empty()) + { + if (_inner->isReadyToWrite(10) == PollResultType::Error) + { + fail("socket write error"); + } + continue; + } + const auto ready = _inner->isReadyToRead(10); + if (ready == PollResultType::Error || ready == PollResultType::CloseRequest) + { + fail("socket closed during handshake"); + break; + } + if (ready == PollResultType::ReadyForRead && !read()) + { + break; + } + } + const bool success = _opened && _error.empty(); + return WebSocketInitResult(success, + _status, + success ? "" + : (_error.empty() ? "HTTP/2 CONNECT rejected (status " + + std::to_string(_status) + ")" + : _error), + _headers); + } + std::ptrdiff_t SocketHttp2::send(char* buffer, size_t length) + { + std::lock_guard lock(_mutex); + if (_closed || !_error.empty() || _reset) + { + Socket::setErrno(EINVAL); + return -1; + } + if (!_accepted && (_sendConnection <= 0 || _sendStream <= 0)) + { + if (!read() || _reset) + { + Socket::setErrno(EINVAL); + return -1; + } + } + if (!_accepted && !_dataPending && length) + { + const int64_t count = (std::min) ({int64_t(length > 16384 ? 16384 : length), + _sendConnection, + _sendStream}); + if (count > 0) + { + _sendConnection -= count; + _sendStream -= count; + _dataPending = true; + queue(0, + 0, + 1, + std::string(buffer, static_cast(count)), + static_cast(count)); + } + } + if (!flush()) + { + Socket::setErrno(EINVAL); + return -1; + } + if (_accepted) + { + const size_t count = _accepted; + _accepted = 0; + return static_cast(count); + } + Socket::setErrno(EWOULDBLOCK); + return -1; + } + std::ptrdiff_t SocketHttp2::recv(void* buffer, size_t length) + { + std::lock_guard lock(_mutex); + if (_dataOffset == _data.size() && !_closed && _error.empty() && !_ended) + { + read(); + } + const size_t count = (std::min) (length, _data.size() - _dataOffset); + if (count) + { + std::memcpy(buffer, _data.data() + _dataOffset, count); + _dataOffset += count; + credit(count); + flush(); + if (_dataOffset == _data.size()) + { + _data.clear(); + _dataOffset = 0; + if (_ended) + { + _deferEnd = true; + } + } + return static_cast(count); + } + if (_deferEnd) + { + // Let the WebSocket parser dispatch the last bytes and send its + // Close reply before exposing the stream's read-half closure. + _deferEnd = false; + Socket::setErrno(EWOULDBLOCK); + return -1; + } + if (_closed || _ended) + { + return 0; + } + Socket::setErrno(_error.empty() ? EWOULDBLOCK : EINVAL); + return -1; + } + PollResultType SocketHttp2::isReadyToRead(int timeoutMs) + { + bool writing, buffered; + { + std::lock_guard lock(_mutex); + if (_closed || _ended || !_error.empty()) + { + return PollResultType::ReadyForRead; + } + if (!flush()) + { + return PollResultType::Error; + } + if (_accepted) + { + return PollResultType::SendRequest; + } + buffered = _dataOffset != _data.size(); + writing = !_output.empty(); + } + if (buffered) + { + // Do not starve write/cancel interrupts under continuous inbound DATA. + const auto ready = _inner->isReadyToRead(0); + if (ready == PollResultType::SendRequest || ready == PollResultType::CloseRequest) + { + return ready; + } + return PollResultType::ReadyForRead; + } + if (writing) + { + const auto ready = _inner->isReadyToWrite(10); + return ready == PollResultType::ReadyForWrite ? PollResultType::SendRequest : ready; + } + return _inner->isReadyToRead(timeoutMs); + } + PollResultType SocketHttp2::isReadyToWrite(int timeoutMs) + { + bool blocked, buffered, writing; + { + std::lock_guard lock(_mutex); + buffered = _dataOffset != _data.size(); + if (buffered && (_ended || !_error.empty())) + { + return PollResultType::ReadyForRead; + } + if (_closed || _reset || !_error.empty()) + { + return PollResultType::Error; + } + // Control frames must make progress even while DATA is blocked by + // flow control. Async TLS backends may need several send attempts. + if (!flush()) + { + return PollResultType::Error; + } + if (_accepted) + { + return PollResultType::ReadyForWrite; + } + writing = !_output.empty(); + blocked = _sendConnection <= 0 || _sendStream <= 0; + if (blocked && _ended) + { + return PollResultType::ReadyForRead; + } + } + if (!blocked || writing) + { + const auto ready = _inner->isReadyToWrite(timeoutMs); + return buffered && ready == PollResultType::Timeout ? PollResultType::ReadyForRead + : ready; + } + if (buffered) + { + return PollResultType::ReadyForRead; + } + const auto ready = _inner->isReadyToRead(timeoutMs); + if (ready == PollResultType::ReadyForRead) + { + std::lock_guard lock(_mutex); + if (!read() || _reset) + { + return PollResultType::Error; + } + if (_dataOffset != _data.size()) + { + return PollResultType::ReadyForRead; + } + return _accepted || (_sendConnection > 0 && _sendStream > 0) + ? PollResultType::ReadyForWrite + : PollResultType::Timeout; + } + return ready; + } + bool SocketHttp2::wakeUpFromPoll(uint64_t code) + { + return _inner->wakeUpFromPoll(code); + } + bool SocketHttp2::isWakeUpFromPollSupported() + { + return _inner->isWakeUpFromPollSupported(); + } + void SocketHttp2::close() + { + std::lock_guard lock(_mutex); + if (!_closed) + { + _closed = true; + if (_opened && _error.empty() && !_reset) + { + queue(0, 1, 1, ""); + } + flush(); + _inner->close(); + } + } +} // namespace ix diff --git a/ixwebsocket/IXSocketHttp2.h b/ixwebsocket/IXSocketHttp2.h new file mode 100644 index 00000000..4fb4d63d --- /dev/null +++ b/ixwebsocket/IXSocketHttp2.h @@ -0,0 +1,62 @@ +/* Copyright (c) 2026 Machine Zone, Inc. All rights reserved. */ +#pragma once +#include "IXHpack.h" +#include "IXSocket.h" +#include "IXWebSocketInitResult.h" +#include + +namespace ix +{ + // One RFC 8441 stream (1) on an exclusively owned HTTP/2 connection. + // The TLS socket owns the descriptor and its poll interruption mechanism. + class SocketHttp2 final : public Socket + { + public: + explicit SocketHttp2(std::unique_ptr socket); + ~SocketHttp2() override; + WebSocketInitResult handshake(const Hpack::Headers& headers, + const CancellationRequest& cancelled); + std::ptrdiff_t send(char* buffer, size_t length) override; + std::ptrdiff_t recv(void* buffer, size_t length) override; + PollResultType isReadyToRead(int timeoutMs) override; + PollResultType isReadyToWrite(int timeoutMs) override; + bool wakeUpFromPoll(uint64_t code) override; + bool isWakeUpFromPollSupported() override; + void close() override; + + private: + struct Output + { + std::string frame; + size_t offset = 0; + size_t accepted = 0; + }; + std::unique_ptr _inner; + std::mutex _mutex; + Hpack _hpack; + std::deque _output; + std::string _input, _data, _headerBlock, _error; + size_t _dataOffset = 0, _accepted = 0; + int64_t _sendConnection = 65535, _sendStream = 65535; + int64_t _receiveConnection = 65535, _receiveStream = 65535; + uint32_t _initialWindow = 65535, _maxConcurrent = 0xffffffffu; + uint32_t _peerHeaderLimit = 0xffffffffu; + WebSocketHttpHeaders _headers; + int _status = 0; + bool _firstFrame = true, _settingsReceived = false, _awaitingAck = true; + bool _extendedConnect = false, _requestSent = false, _headerActive = false; + bool _headerEndStream = false, _opened = false, _ended = false; + bool _dataPending = false, _closed = false, _reset = false, _deferEnd = false; + bool queue(unsigned type, + unsigned flags, + uint32_t stream, + const std::string& payload, + size_t accepted = 0); + bool flush(); + bool read(); + bool frame(unsigned type, unsigned flags, uint32_t stream, const std::string& payload); + bool headers(); + bool fail(const std::string& message, uint32_t code = 1); + void credit(size_t count); + }; +} // namespace ix diff --git a/ixwebsocket/IXSocketMbedTLS.cpp b/ixwebsocket/IXSocketMbedTLS.cpp index f376985a..4b6b416d 100644 --- a/ixwebsocket/IXSocketMbedTLS.cpp +++ b/ixwebsocket/IXSocketMbedTLS.cpp @@ -242,6 +242,34 @@ namespace ix mbedtls_ssl_conf_ca_chain(&_conf, &_cacert, NULL); } + if (isClient && !_tlsOptions.alpnProtocols.empty()) + { +#ifdef MBEDTLS_SSL_ALPN + _alpnProtocols.clear(); + for (const auto& protocol : _tlsOptions.alpnProtocols) + { + _alpnProtocols.push_back(protocol.c_str()); + if (protocol == "h2") + { +#if MBEDTLS_VERSION_NUMBER >= 0x03020000 + mbedtls_ssl_conf_min_tls_version(&_conf, MBEDTLS_SSL_VERSION_TLS1_2); +#else + mbedtls_ssl_conf_min_version( + &_conf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3); +#endif + } + } + _alpnProtocols.push_back(nullptr); + if (mbedtls_ssl_conf_alpn_protocols(&_conf, _alpnProtocols.data()) != 0) + { + errMsg = "Cannot configure ALPN"; + return false; + } +#else + errMsg = "This MbedTLS build does not support ALPN"; + return false; +#endif + } if (mbedtls_ssl_setup(&_ssl, &_conf) != 0) { errMsg = "SSL setup failed"; @@ -286,6 +314,7 @@ namespace ix std::string& errMsg, const CancellationRequest& isCancellationRequested) { + _negotiatedProtocol.clear(); { std::lock_guard lock(_mutex); _sockfd = connectToHost(host, port, errMsg, isCancellationRequested); @@ -305,7 +334,15 @@ namespace ix mbedtls_ssl_set_bio(&_ssl, &_sockfd, mbedtls_net_send, mbedtls_net_recv, NULL); - return handshake(errMsg, isCancellationRequested); + const bool connected = handshake(errMsg, isCancellationRequested); +#ifdef MBEDTLS_SSL_ALPN + if (connected) + { + const char* selected = mbedtls_ssl_get_alpn_protocol(&_ssl); + _negotiatedProtocol = selected ? selected : ""; + } +#endif + return connected; } bool SocketMbedTLS::handshake(std::string& errMsg, diff --git a/ixwebsocket/IXSocketMbedTLS.h b/ixwebsocket/IXSocketMbedTLS.h index 0841ca82..712f9f43 100644 --- a/ixwebsocket/IXSocketMbedTLS.h +++ b/ixwebsocket/IXSocketMbedTLS.h @@ -57,6 +57,7 @@ namespace ix std::mutex _mutex; SocketTLSOptions _tlsOptions; + std::vector _alpnProtocols; bool _mbedtlsInitialized = false; bool init(const std::string& host, bool isClient, std::string& errMsg); diff --git a/ixwebsocket/IXSocketNetwork.cpp b/ixwebsocket/IXSocketNetwork.cpp index 82cb835d..740444e6 100644 --- a/ixwebsocket/IXSocketNetwork.cpp +++ b/ixwebsocket/IXSocketNetwork.cpp @@ -22,6 +22,29 @@ namespace ix { namespace { + std::string negotiatedApplicationProtocol(sec_protocol_metadata_t metadata) + { +#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 150500 + if (__builtin_available(macOS 15.5, *)) + { + const char* value = sec_protocol_metadata_copy_negotiated_protocol(metadata); + if (value) + { + const std::string protocol(value); + free(const_cast(value)); + return protocol; + } + } +#endif + // Some macOS versions return null from the copy API while the + // legacy getter correctly exposes the negotiated protocol. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + const char* value = sec_protocol_metadata_get_negotiated_protocol(metadata); +#pragma clang diagnostic pop + return value ? value : ""; + } + // Level-triggered notification: one byte remains until all buffered input // is consumed. The descriptor carries notifications, never TLS payloads. struct NetworkSignal @@ -292,6 +315,11 @@ namespace ix if (!server) { sec_protocol_options_set_tls_server_name(security, host.c_str()); + for (const auto& protocol : options.alpnProtocols) + { + sec_protocol_options_add_tls_application_protocol(security, + protocol.c_str()); + } } sec_protocol_options_set_peer_authentication_required( security, !options.isPeerVerifyDisabled()); @@ -382,6 +410,7 @@ namespace ix bool started = false; bool server = false; std::string error; + std::string negotiatedProtocol; ~State() { if (connection) @@ -472,6 +501,7 @@ namespace ix std::string& error, const CancellationRequest& cancelled) { + _negotiatedProtocol.clear(); if (port < 1 || port > 65535) { error = "Invalid TLS port"; @@ -525,6 +555,7 @@ namespace ix s->started = true; std::weak_ptr weak = s; nw_connection_set_queue(s->connection, s->queue); + const bool useAlpn = !_options.alpnProtocols.empty(); nw_connection_set_state_changed_handler( s->connection, ^(nw_connection_state_t state, nw_error_t err) { auto current = weak.lock(); @@ -539,6 +570,24 @@ namespace ix } if (state == nw_connection_state_ready) { + if (useAlpn) + { + auto definition = nw_protocol_copy_tls_definition(); + auto metadata = + nw_connection_copy_protocol_metadata(current->connection, definition); + nw_release(definition); + if (metadata) + { + auto security = nw_tls_copy_sec_protocol_metadata(metadata); + if (security) + { + current->negotiatedProtocol = + negotiatedApplicationProtocol(security); + sec_release(security); + } + nw_release(metadata); + } + } current->ready = true; State::receive(current); } @@ -569,6 +618,7 @@ namespace ix } if (s->ready && !s->closed && s->error.empty()) { + _negotiatedProtocol = s->negotiatedProtocol; return true; } error = s->error.empty() ? "TLS connection closed during handshake" : s->error; @@ -732,6 +782,7 @@ namespace ix bool ready = false; bool stopped = false; std::string error; + std::string negotiatedProtocol; ~State() { if (listener) diff --git a/ixwebsocket/IXSocketOpenSSL.cpp b/ixwebsocket/IXSocketOpenSSL.cpp index 0a70b0d0..016c681e 100644 --- a/ixwebsocket/IXSocketOpenSSL.cpp +++ b/ixwebsocket/IXSocketOpenSSL.cpp @@ -899,6 +899,7 @@ namespace ix std::string& errMsg, const CancellationRequest& isCancellationRequested) { + _negotiatedProtocol.clear(); bool handshakeSuccessful = false; { std::lock_guard lock(_mutex); @@ -936,6 +937,41 @@ namespace ix } SSL_set_fd(_ssl_connection, _sockfd); +#if OPENSSL_VERSION_NUMBER >= 0x10002000L + std::string alpn; + for (const auto& protocol : _tlsOptions.alpnProtocols) + { + alpn += static_cast(protocol.size()); + alpn += protocol; + if (protocol == "h2") + { +#if OPENSSL_VERSION_NUMBER >= 0x10100000L + if (SSL_set_min_proto_version(_ssl_connection, TLS1_2_VERSION) != 1) + { + errMsg = "HTTP/2 requires TLS 1.2 or newer"; + return false; + } +#else + SSL_set_options(_ssl_connection, SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1); +#endif + } + } + if (!alpn.empty() && + SSL_set_alpn_protos(_ssl_connection, + reinterpret_cast(alpn.data()), + static_cast(alpn.size())) != 0) + { + errMsg = "Cannot configure ALPN"; + return false; + } +#else + if (!_tlsOptions.alpnProtocols.empty()) + { + errMsg = "ALPN requires OpenSSL 1.0.2 or newer"; + return false; + } +#endif + // SNI support SSL_set_tlsext_host_name(_ssl_connection, host.c_str()); @@ -965,6 +1001,16 @@ namespace ix } #endif handshakeSuccessful = openSSLClientHandshake(host, errMsg, isCancellationRequested); +#if OPENSSL_VERSION_NUMBER >= 0x10002000L + if (handshakeSuccessful) + { + const unsigned char* selected = nullptr; + unsigned length = 0; + SSL_get0_alpn_selected(_ssl_connection, &selected, &length); + _negotiatedProtocol = + length ? std::string(reinterpret_cast(selected), length) : ""; + } +#endif } if (!handshakeSuccessful) diff --git a/ixwebsocket/IXSocketTLSOptions.cpp b/ixwebsocket/IXSocketTLSOptions.cpp index 19a93c2a..4c6617ab 100644 --- a/ixwebsocket/IXSocketTLSOptions.cpp +++ b/ixwebsocket/IXSocketTLSOptions.cpp @@ -19,6 +19,17 @@ namespace ix bool SocketTLSOptions::isValid() const { + size_t alpnSize = 0; + for (const auto& protocol : alpnProtocols) + { + alpnSize += protocol.size() + 1; + if (protocol.empty() || protocol.size() > 255 || + protocol.find('\0') != std::string::npos || alpnSize > 65535) + { + _errMsg = "Invalid ALPN protocol list"; + return false; + } + } if (!_validated) { if (!certFile.empty() && !isUsingInMemoryCert() && !std::ifstream(certFile)) diff --git a/ixwebsocket/IXSocketTLSOptions.h b/ixwebsocket/IXSocketTLSOptions.h index 3bd41cb5..7d6c47fc 100644 --- a/ixwebsocket/IXSocketTLSOptions.h +++ b/ixwebsocket/IXSocketTLSOptions.h @@ -7,6 +7,7 @@ #pragma once #include +#include namespace ix { @@ -30,6 +31,9 @@ namespace ix // leverage the system defaults, use 'NONE' to disable peer verification std::string caFile = "SYSTEM"; + // Client ALPN offers. Empty preserves the backend's default behavior. + std::vector alpnProtocols; + // list of ciphers (rsa, etc...) std::string ciphers = "DEFAULT"; diff --git a/ixwebsocket/IXWebSocket.cpp b/ixwebsocket/IXWebSocket.cpp index 0636679a..9a83242c 100644 --- a/ixwebsocket/IXWebSocket.cpp +++ b/ixwebsocket/IXWebSocket.cpp @@ -100,6 +100,12 @@ namespace ix _perMessageDeflateOptions = perMessageDeflateOptions; } + void WebSocket::setHttp2(bool enabled) + { + std::lock_guard lock(_configMutex); + _http2 = enabled; + } + void WebSocket::setTLSOptions(const SocketTLSOptions& socketTLSOptions) { std::lock_guard lock(_configMutex); @@ -280,6 +286,11 @@ namespace ix url = _url; if (httpClient) { + if (_http2) + { + return WebSocketInitResult( + false, 0, "HTTP/2 cannot adopt an HTTP/1.1 connection"); + } std::string protocol, host, path, query; int port; if (!UrlParser::parse(url, protocol, host, path, query, port) || @@ -305,7 +316,8 @@ namespace ix _enablePong, _pingIntervalSecs, _proxyOptions, - _maxMessageSize); + _maxMessageSize, + _http2); headers = _extraHeaders; disabledDefaultHeaders = _disabledDefaultHeaders; subProtocols = _subProtocols; diff --git a/ixwebsocket/IXWebSocket.h b/ixwebsocket/IXWebSocket.h index 03ec8f75..c1bcf237 100644 --- a/ixwebsocket/IXWebSocket.h +++ b/ixwebsocket/IXWebSocket.h @@ -61,6 +61,8 @@ namespace ix void setPerMessageDeflateOptions( const WebSocketPerMessageDeflateOptions& perMessageDeflateOptions); void setTLSOptions(const SocketTLSOptions& socketTLSOptions); + // Opt-in RFC 8441 client, one stream per connection. Requires wss:// and ALPN h2. + void setHttp2(bool enabled); // Incoming payload bytes, before and after decompression. 0 means unlimited. // Configure before connecting; applies to subsequent connections. void setMaxMessageSize(uint64_t bytes); @@ -166,6 +168,7 @@ namespace ix SocketTLSOptions _socketTLSOptions; ProxyOptions _proxyOptions; + bool _http2 = false; mutable std::mutex _configMutex; // protect all config variables access diff --git a/ixwebsocket/IXWebSocketHandshake.cpp b/ixwebsocket/IXWebSocketHandshake.cpp index e4a1529a..3f3b39c3 100644 --- a/ixwebsocket/IXWebSocketHandshake.cpp +++ b/ixwebsocket/IXWebSocketHandshake.cpp @@ -9,11 +9,14 @@ #include "IXBase64.h" #include "IXHttp.h" #include "IXSocketConnect.h" +#include "IXSocketHttp2.h" #include "IXStrCaseCompare.h" +#include "IXUniquePtr.h" #include "IXUrlParser.h" #include "IXUserAgent.h" #include "IXWebSocketHandshakeKeyGen.h" #include +#include #include #include #include @@ -100,13 +103,18 @@ namespace ix int port, int timeoutSecs, const std::vector& disabledDefaultHeaders, - bool alreadyConnected) + bool alreadyConnected, + bool http2) { _requestInitCancellation = false; auto isCancellationRequested = makeCancellationRequestWithTimeout(timeoutSecs, _requestInitCancellation); + if (http2 && (protocol != "wss" || alreadyConnected)) + { + return WebSocketInitResult(false, 0, "HTTP/2 requires a new wss:// connection"); + } std::string errMsg; if (!alreadyConnected && !_socket->connect(host, port, errMsg, isCancellationRequested)) { @@ -115,6 +123,111 @@ namespace ix return WebSocketInitResult(false, 0, ss.str()); } + if (http2) + { + if (protocol != "wss" || _socket->getNegotiatedProtocol() != "h2" || alreadyConnected) + { + return WebSocketInitResult( + false, + 0, + "HTTP/2 requires wss:// and negotiated ALPN h2 (selected: " + + _socket->getNegotiatedProtocol() + ")"); + } + const std::string authority = + (host.find(':') != std::string::npos ? "[" + host + "]" : host) + ":" + + std::to_string(port); + const std::set disabled( + disabledDefaultHeaders.begin(), disabledDefaultHeaders.end()); + WebSocketHttpHeaders regular(extraHeaders); + if (!regular.count("User-Agent") && !disabled.count("User-Agent")) + { + regular["User-Agent"] = userAgent(); + } + if (!regular.count("Origin") && !disabled.count("Origin")) + { + regular["Origin"] = "https://" + authority; + } + regular["Sec-WebSocket-Version"] = "13"; + if (_enablePerMessageDeflate) + { + regular["Sec-WebSocket-Extensions"] = _perMessageDeflateOptions.generateHeader(); + } + Hpack::Headers fields {{":method", "CONNECT"}, + {":protocol", "websocket"}, + {":scheme", "https"}, + {":authority", authority}, + {":path", path}}; + for (const auto& field : regular) + { + std::string name = field.first; + for (auto& c : name) + { + if (c >= 'A' && c <= 'Z') + { + c += 'a' - 'A'; + } + } + if (name.empty() || name[0] == ':' || name == "connection" || name == "upgrade" || + name == "keep-alive" || name == "proxy-connection" || + name == "content-length" || name == "transfer-encoding" || + name == "sec-websocket-key" || name == "sec-websocket-accept") + { + return WebSocketInitResult(false, 0, "Header is not valid for HTTP/2: " + name); + } + for (unsigned char c : name) + { + if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || + (c && std::strchr("!#$%&'*+-.^_`|~", c)))) + { + return WebSocketInitResult(false, 0, "Invalid HTTP/2 header name"); + } + } + if (field.second.find_first_of(std::string("\0\r\n", 3)) != std::string::npos) + { + return WebSocketInitResult(false, 0, "Invalid HTTP/2 header value"); + } + if (!field.second.empty() && + (field.second.front() == ' ' || field.second.front() == '\t' || + field.second.back() == ' ' || field.second.back() == '\t')) + { + return WebSocketInitResult(false, 0, "Invalid whitespace in HTTP/2 header"); + } + if (name == "te" && field.second != "trailers") + { + return WebSocketInitResult(false, 0, "HTTP/2 TE only supports trailers"); + } + if (name == "host") + { + fields[3].second = field.second; + continue; + } + fields.emplace_back(name, field.second); + } + auto socket = ix::make_unique(std::move(_socket)); + auto result = socket->handshake(fields, isCancellationRequested); + _socket = std::move(socket); + result.uri = path; + if (!result.success) + { + return result; + } + if (_enablePerMessageDeflate) + { + WebSocketPerMessageDeflateOptions options( + result.headers["sec-websocket-extensions"]); + if (!options.enabled()) + { + _enablePerMessageDeflate = false; + } + else if (!_perMessageDeflate->init(options)) + { + return WebSocketInitResult( + false, 0, "Failed to initialize per message deflate engine"); + } + } + return result; + } + // Generate a random 16 bytes string and base64 encode it. // // See https://stackoverflow.com/questions/18265128/what-is-sec-websocket-key-for diff --git a/ixwebsocket/IXWebSocketHandshake.h b/ixwebsocket/IXWebSocketHandshake.h index 58260ef4..de32029e 100644 --- a/ixwebsocket/IXWebSocketHandshake.h +++ b/ixwebsocket/IXWebSocketHandshake.h @@ -39,7 +39,8 @@ namespace ix int port, int timeoutSecs, const std::vector& disabledDefaultHeaders = {}, - bool alreadyConnected = false); + bool alreadyConnected = false, + bool http2 = false); WebSocketInitResult serverHandshake(int timeoutSecs, bool enablePerMessageDeflate, diff --git a/ixwebsocket/IXWebSocketTransport.cpp b/ixwebsocket/IXWebSocketTransport.cpp index 0613937c..4ecadf8f 100644 --- a/ixwebsocket/IXWebSocketTransport.cpp +++ b/ixwebsocket/IXWebSocketTransport.cpp @@ -95,11 +95,17 @@ namespace ix bool enablePong, int pingIntervalSecs, const ProxyOptions& proxyOptions, - uint64_t maxMessageSize) + uint64_t maxMessageSize, + bool http2) { _perMessageDeflateOptions = perMessageDeflateOptions; _enablePerMessageDeflate = _perMessageDeflateOptions.enabled(); _socketTLSOptions = socketTLSOptions; + _http2 = http2; + if (http2) + { + _socketTLSOptions.alpnProtocols = {"h2"}; + } _proxyOptions = proxyOptions; _enablePong = enablePong; _pingIntervalSecs = pingIntervalSecs; @@ -115,6 +121,10 @@ namespace ix std::unique_ptr connectedSocket) { resetConnectionState(); + if (_http2) + { + _blockingSend = false; + } std::lock_guard lock(_socketMutex); std::string protocol, host, path, query; @@ -161,7 +171,8 @@ namespace ix port, timeoutSecs, disabledDefaultHeaders, - alreadyConnected); + alreadyConnected, + _http2); if (!alreadyConnected && result.http_status >= 300 && result.http_status < 400) { @@ -1504,6 +1515,18 @@ namespace ix WebSocketCloseConstants::kAbnormalCloseMessage); return false; } + else if (_http2 && result == PollResultType::ReadyForRead) + { + // H2 DATA in the other direction must be consumed before more + // receive-window credit is issued. Yield to WebSocket dispatch + // rather than blocking both ends on their send windows. + const bool received = receiveFromSocket(); + if (!isSendBufferEmpty()) + { + wakeUpFromPoll(SelectInterrupt::kSendRequest); + } + return received; + } else if (result == PollResultType::ReadyForWrite) { if (!sendOnSocket()) diff --git a/ixwebsocket/IXWebSocketTransport.h b/ixwebsocket/IXWebSocketTransport.h index 2c5810f6..6c7be97a 100644 --- a/ixwebsocket/IXWebSocketTransport.h +++ b/ixwebsocket/IXWebSocketTransport.h @@ -83,7 +83,8 @@ namespace ix bool enablePong, int pingIntervalSecs, const ProxyOptions& proxyOptions = {}, - uint64_t maxMessageSize = 0); + uint64_t maxMessageSize = 0, + bool http2 = false); // Client WebSocketInitResult connectToUrl( @@ -235,6 +236,7 @@ namespace ix // Used to control TLS connection behavior SocketTLSOptions _socketTLSOptions; + bool _http2 = false; ProxyOptions _proxyOptions; // Used to cancel dns lookup + socket connect + http upgrade diff --git a/makefile.dev b/makefile.dev index 0832b323..65838ec7 100644 --- a/makefile.dev +++ b/makefile.dev @@ -287,8 +287,8 @@ test_h2_proxy: python3 tools/run_h2_proxy.py $(H2_PROXY_ARGS) test_h2_proxy_native: - cmake -S test/h2_proxy -B build/h2-proxy -DCMAKE_UNITY_BUILD=ON - cmake --build build/h2-proxy --target h2_proxy_server --parallel + cmake -S test/h2_proxy -B build/h2-proxy -DCMAKE_UNITY_BUILD=ON -DH2_PROXY_NATIVE_CLIENT=ON + cmake --build build/h2-proxy --target h2_proxy_server h2_proxy_client --parallel python3 -m venv build/h2-proxy/venv build/h2-proxy/venv/bin/python -m pip install --disable-pip-version-check -r test/h2_proxy/requirements.txt - build/h2-proxy/venv/bin/python test/h2_proxy/run.py $(H2_PROXY_ARGS) + build/h2-proxy/venv/bin/python test/h2_proxy/run.py --native-client build/h2-proxy/h2_proxy_client $(H2_PROXY_ARGS) diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index acdcf9f1..1c894a7c 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -22,6 +22,7 @@ set (TEST_TARGET_NAMES IXHttpServerStaticTest IXUnityBuildsTest IXHttpTest + IXHttp2Test IXHttpClientResponseTest IXHttpClientReuseTest IXHttpWebSocketUpgradeTest @@ -208,3 +209,5 @@ if (USE_NETWORK_FRAMEWORK) add_test(NAME IXSocketNetworkTest COMMAND IXSocketNetworkTest) set_tests_properties(IXSocketNetworkTest PROPERTIES TIMEOUT 45) endif() + +set_tests_properties(IXHttp2Test PROPERTIES TIMEOUT 10) diff --git a/test/IXHttp2Test.cpp b/test/IXHttp2Test.cpp new file mode 100644 index 00000000..54518827 --- /dev/null +++ b/test/IXHttp2Test.cpp @@ -0,0 +1,460 @@ +/* Copyright (c) 2026 Machine Zone, Inc. All rights reserved. */ +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + std::string hex(const std::string& value) + { + std::string result; + for (size_t i = 0; i < value.size(); i += 2) + { + result += static_cast(std::stoul(value.substr(i, 2), nullptr, 16)); + } + return result; + } + std::string frame(unsigned type, unsigned flags, unsigned stream, const std::string& payload) + { + std::string result(9, '\0'); + result[0] = char(payload.size() >> 16); + result[1] = char(payload.size() >> 8); + result[2] = char(payload.size()); + result[3] = char(type); + result[4] = char(flags); + result[8] = char(stream); + return result + payload; + } + class Peer final : public ix::Socket + { + public: + std::deque incoming; + std::string sent; + size_t fragment = 16384; + bool partial = false; + unsigned writes = 0; + Peer() + { + incoming.push_back(frame(4, 0, 0, hex("000800000001"))); + incoming.push_back(frame(4, 1, 0, "")); + incoming.push_back(frame(1, 4, 1, hex("88"))); + } + std::ptrdiff_t send(char* data, size_t size) override + { + if (partial && ++writes % 2 == 0) + { + setErrno(EWOULDBLOCK); + return -1; + } + size = (std::min) (size, partial ? size_t(3) : size); + sent.append(data, size); + return static_cast(size); + } + std::ptrdiff_t recv(void* data, size_t size) override + { + if (incoming.empty()) + { + setErrno(EWOULDBLOCK); + return -1; + } + auto& bytes = incoming.front(); + size = (std::min) ({size, bytes.size(), fragment}); + std::memcpy(data, bytes.data(), size); + bytes.erase(0, size); + if (bytes.empty()) + { + incoming.pop_front(); + } + return static_cast(size); + } + ix::PollResultType isReadyToRead(int) override + { + return incoming.empty() ? ix::PollResultType::Timeout + : ix::PollResultType::ReadyForRead; + } + ix::PollResultType isReadyToWrite(int) override + { + return ix::PollResultType::ReadyForWrite; + } + bool wakeUpFromPoll(uint64_t) override + { + return true; + } + }; + ix::Hpack::Headers request {{":method", "CONNECT"}, + {":protocol", "websocket"}, + {":scheme", "https"}, + {":authority", "example.com"}, + {":path", "/"}}; +} // namespace + +TEST_CASE("HPACK decodes RFC 7541 requests with and without Huffman coding", "[http2][hpack]") +{ + const bool huffman = GENERATE(false, true); + ix::Hpack decoder; + ix::Hpack::Headers fields; + REQUIRE(decoder.decode(hex(huffman ? "828684418cf1e3c2e5f23a6ba0ab90f4ff" + : "828684410f7777772e6578616d706c652e636f6d"), + fields)); + REQUIRE(fields.size() == 4); + CHECK(fields[0] == std::make_pair(std::string(":method"), std::string("GET"))); + CHECK(fields[3].second == "www.example.com"); + // The authority in the second block references the first block's dynamic table. + REQUIRE(decoder.decode(hex("828684be58086e6f2d6361636865"), fields)); + CHECK(fields[3].second == "www.example.com"); + CHECK(fields[4].second == "no-cache"); + REQUIRE(decoder.decode(ix::Hpack::encode(request), fields)); + CHECK(fields == request); +} + +TEST_CASE("HPACK rejects invalid indexes, lengths, padding and EOS", "[http2][hpack]") +{ + const std::string bad = GENERATE( + "80", "ff", "be", "000561", "000181", "000184ffffffff", "00810000", "3fe21f", "820020"); + ix::Hpack decoder; + ix::Hpack::Headers fields; + INFO(bad); + CHECK_FALSE(decoder.decode(hex(bad), fields)); +} + +TEST_CASE("HTTP2 handshake validates settings, response headers and frame ordering", "[http2]") +{ + const int failure = GENERATE(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); + auto peer = new Peer; + if (failure == 0) + { + peer->incoming.front() = frame(6, 0, 0, "12345678"); + } + if (failure == 1) + { + peer->incoming.front() = frame(4, 0, 0, ""); + } + if (failure == 2) + { + peer->incoming.front() = frame(4, 0, 0, hex("000800000002")); + } + if (failure == 3) + { + peer->incoming.back() = hex("004001000000000001"); + } + if (failure == 4) + { + peer->incoming.back() = frame(1, 4, 1, hex("80")); + } + if (failure == 5) + { + peer->incoming.back() = frame(1, 0, 1, hex("88")); + peer->incoming.push_back(frame(6, 0, 0, "12345678")); + } + if (failure == 6) + { + peer->incoming.back() = frame(1, 4, 1, ix::Hpack::encode({{":status", "101"}})); + } + if (failure == 7) + { + peer->incoming.back() = + frame(1, 4, 1, ix::Hpack::encode({{":status", "200"}, {"connection", "upgrade"}})); + } + if (failure == 8) + { + peer->incoming.back() = frame(1, 5, 1, hex("88")); + } + if (failure == 9) + { + peer->incoming.back() = + frame(1, 4, 1, ix::Hpack::encode({{":status", "200"}, {"content-length", "0"}})); + } + ix::SocketHttp2 stream {std::unique_ptr(peer)}; + const auto result = stream.handshake(request, [] { return false; }); + CHECK_FALSE(result.success); + CHECK_FALSE(result.errorStr.empty()); +} + +TEST_CASE("HTTP2 preserves byte streams through fragmented reads and partial writes", "[http2]") +{ + const bool fragmented = GENERATE(false, true); + auto peer = new Peer; + peer->partial = fragmented; + peer->fragment = fragmented ? 1 : 16384; + ix::SocketHttp2 stream {std::unique_ptr(peer)}; + REQUIRE(stream.handshake(request, [] { return false; }).success); + std::string body = "websocket bytes"; + std::ptrdiff_t sent; + do + { + sent = stream.send(&body[0], body.size()); + } while (sent < 0 && ix::Socket::isWaitNeeded()); + CHECK(sent == body.size()); + const auto encoded = frame(0, 0, 1, body); + CHECK(peer->sent.find(encoded) != std::string::npos); + CHECK(peer->sent.find(encoded, peer->sent.find(encoded) + 1) == std::string::npos); + peer->incoming.push_back(frame(0, 8, 1, std::string("\2") + body + "xx")); + std::string received; + char buffer[3]; + while (received.size() < body.size()) + { + const auto count = stream.recv(buffer, sizeof(buffer)); + if (count > 0) + { + received.append(buffer, static_cast(count)); + } + else + { + REQUIRE(ix::Socket::isWaitNeeded()); + } + } + CHECK(received == body); + peer->incoming.push_back(frame(0, 1, 1, "")); + while (stream.recv(buffer, sizeof(buffer)) != 0) + { + REQUIRE(ix::Socket::isWaitNeeded()); + } +} + +TEST_CASE("HTTP2 WebSockets reject plaintext and HTTP1 connection handoff", "[http2]") +{ + ix::WebSocket socket; + socket.setHttp2(true); + socket.setOnMessageCallback([](const ix::WebSocketMessagePtr&) { }); + socket.setUrl("ws://127.0.0.1:1/"); + CHECK_FALSE(socket.connect(1).success); + ix::HttpClient http; + socket.setUrl("wss://127.0.0.1:1/"); + auto result = socket.connect(http, 1); + CHECK_FALSE(result.success); + CHECK(result.errorStr.find("cannot adopt") != std::string::npos); +} + +TEST_CASE("HPACK decodes the complete byte alphabet and rejects truncated literals", + "[http2][hpack]") +{ + const std::string block = hex( + "4086f2b47e92547fffc803ffc7fffd8fffffe2fffffe3fffffe4fffffe5fffffe6fffffe7fffffe8ffffeaffff" + "fff3fffffa" + "7fffffabffffffdfffffebfffffecfffffedfffffeefffffefffffff0ffffff1ffffff2fffffffbfffffcfffff" + "fd3fffffd7" + "fffffdbfffffdffffffe3fffffe7fffffebfffffed4fe3f9ffaffcabf1febfafefe7fdfd2cbb00089969b71d79" + "fb9f7fff20" + "ffbff3ff50ddbd7f061c58f265cd9f469d5af66dddbf871e5f9cff7ff7fffc3ff9ffe45fff4719242cb34e6e9d" + "68a6a3d7da" + "c426defe3cfaf7fffbfe7ffbffdffffffcfffe6ffff4bfff9ffffa3fffd3ffff53fffd5ffffb3fffeb7fffdaff" + "ffb7ffff73" + "fffeeffffdeffffebffffbfffffd9ffffdbfffebffffe0ffffeeffffc3ffff8bffff1ffffe4fffee7fffb1ffff" + "97fffd9fff" + "fcdffff9fffffbffffdafffeeffff4ffffb7fffee7fffe8ffffd3fffdeffffd5fffeeffffbdffffe1fffdfffff" + "7fffff5fff" + "fecffff07fff87fffe0ffff17fffedffff87ffff77fffeffffeaffff8bfffe3ffff93ffff87fffcbffff37ffff" + "1fffff83ff" + "ffe1fffebfffe3ffff3fffff2ffffa3ffffd9fffff17ffffc7fffff27ffffdefffffbffffff2fffff8fffffb7f" + "ff97fff8ff" + "fffe6fffffc1fffff87ffffe7fffffc5ffffe5fffe4ffff2fffffd1fffff4ffffffefffffe3fffffc9fffff97f" + "ffb3ffffcf" + "fffb7fffcdffff4ffff9ffffd1ffffcffffeaffffafffffddffffeffffff4fffff5fffffabffffa7ffffd7ffff" + "f9bffffecf" + "ffffb7fffff3fffffe8fffffd3fffffabfffff5fffffff7ffffecfffffdbfffffbbfffff7ffffff0fffffbbf"); + ix::Hpack decoder; + ix::Hpack::Headers fields; + REQUIRE(decoder.decode(block, fields)); + REQUIRE(fields.size() == 1); + REQUIRE(fields[0].second.size() == 256); + for (unsigned i = 0; i < 256; ++i) + { + CHECK(static_cast(fields[0].second[i]) == i); + } + for (size_t i = 1; i < block.size(); ++i) + { + ix::Hpack partial; + REQUIRE_FALSE(partial.decode(block.substr(0, i), fields)); + } + CHECK_FALSE(decoder.decode(hex("0084ffffffff00"), fields)); // EOS inside a string. + REQUIRE(decoder.decode(hex("20"), fields)); // Evict all dynamic entries. + CHECK_FALSE(decoder.decode(hex("be"), fields)); +} + +TEST_CASE("HTTP2 validates stream control and receive windows", "[http2]") +{ + const int failure = GENERATE(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); + auto peer = new Peer; + ix::SocketHttp2 stream {std::unique_ptr(peer)}; + REQUIRE(stream.handshake(request, [] { return false; }).success); + if (failure == 0) + { + peer->incoming.push_back(frame(8, 0, 1, hex("00000000"))); + } + if (failure == 1) + { + peer->incoming.push_back(frame(8, 0, 0, hex("7fffffff"))); + } + if (failure == 2) + { + peer->incoming.push_back(frame(8, 0, 2, hex("00000001"))); + } + if (failure == 3) + { + peer->incoming.push_back(frame(0, 0, 0, "bad")); + } + if (failure == 4) + { + peer->incoming.push_back(frame(0, 8, 1, hex("03"))); + } + if (failure == 5) + { + peer->incoming.push_back(frame(6, 0, 0, "short")); + } + if (failure == 6) + { + peer->incoming.push_back(frame(5, 0, 1, "")); + } + if (failure == 7) + { + peer->incoming.push_back(frame(9, 4, 1, "")); + } + if (failure == 8) + { + peer->incoming.push_back(frame(2, 0, 1, hex("0000000100"))); + } + if (failure == 9) + { + peer->incoming.push_back(frame(3, 0, 1, hex("00000001"))); + } + char byte; + CHECK(stream.recv(&byte, 1) <= 0); + stream.close(); + CHECK(peer->sent.find(hex("000008070000000000")) != std::string::npos); // GOAWAY. +} + +TEST_CASE("HTTP2 supports continuation, extension frames and a remote half close", "[http2]") +{ + auto peer = new Peer; + const auto block = ix::Hpack::encode({{":status", "200"}, {"x-test", "present"}}); + peer->incoming.back() = frame(1, 0, 1, block.substr(0, 1)); + peer->incoming.push_back(frame(9, 4, 1, block.substr(1))); + ix::SocketHttp2 stream {std::unique_ptr(peer)}; + auto result = stream.handshake(request, [] { return false; }); + REQUIRE(result.success); + CHECK(result.headers["x-test"] == "present"); + peer->incoming.push_back(frame(0xfe, 0, 0, "extension")); + peer->incoming.push_back(frame(0, 1, 1, "last")); + char buffer[4]; + CHECK(stream.recv(buffer, sizeof(buffer)) == -1); // Ignored extension frame. + REQUIRE(stream.recv(buffer, sizeof(buffer)) == 4); + CHECK(std::string(buffer, 4) == "last"); + CHECK(stream.recv(buffer, sizeof(buffer)) == -1); // Dispatch before EOF. + std::string reply = "close reply"; + CHECK(stream.send(&reply[0], reply.size()) == reply.size()); + CHECK(stream.recv(buffer, sizeof(buffer)) == 0); +} + +TEST_CASE("HTTP2 handles zero flow-control windows without losing bytes", "[http2]") +{ + auto peer = new Peer; + peer->incoming.front() = frame(4, 0, 0, hex("000800000001000400000000")); + ix::SocketHttp2 stream {std::unique_ptr(peer)}; + REQUIRE(stream.handshake(request, [] { return false; }).success); + std::string body = "payload"; + CHECK(stream.send(&body[0], body.size()) == -1); + CHECK(ix::Socket::isWaitNeeded()); + peer->incoming.push_back(frame(8, 0, 1, hex("00000007"))); + CHECK(stream.isReadyToWrite(0) == ix::PollResultType::ReadyForWrite); + CHECK(stream.send(&body[0], body.size()) == body.size()); + CHECK(stream.isReadyToWrite(0) == ix::PollResultType::Timeout); +} + +TEST_CASE("HTTP2 handshake cancellation is bounded without sleeping", "[http2]") +{ + auto peer = new Peer; + peer->incoming.clear(); + ix::SocketHttp2 stream {std::unique_ptr(peer)}; + unsigned checks = 0; + const auto result = stream.handshake(request, [&] { return ++checks > 30; }); + CHECK_FALSE(result.success); + CHECK(result.errorStr.find("cancelled") != std::string::npos); + CHECK(checks <= 32); +} + +TEST_CASE("HTTP2 unsuccessful CONNECT preserves the HTTP status and headers", "[http2]") +{ + auto peer = new Peer; + peer->incoming.back() = + frame(1, 4, 1, ix::Hpack::encode({{":status", "403"}, {"x-error", "denied"}})) + + frame(0, 1, 1, "error body"); + ix::SocketHttp2 stream {std::unique_ptr(peer)}; + const auto result = stream.handshake(request, [] { return false; }); + CHECK_FALSE(result.success); + CHECK(result.http_status == 403); + CHECK(result.headers.at("x-error") == "denied"); + CHECK(result.errorStr.find("403") != std::string::npos); +} + +TEST_CASE("ALPN protocol offers are length bounded", "[http2][tls]") +{ + ix::SocketTLSOptions options; + options.alpnProtocols = {"h2"}; + REQUIRE(options.isValid()); + options.alpnProtocols = {""}; + CHECK_FALSE(options.isValid()); + options.alpnProtocols = {std::string(256, 'x')}; + CHECK_FALSE(options.isValid()); +} + +TEST_CASE("HTTP2 enforces its receive window while an application is sending", "[http2]") +{ + auto peer = new Peer; + peer->incoming.front() = frame(4, 0, 0, hex("000800000001000400000000")); + ix::SocketHttp2 stream {std::unique_ptr(peer)}; + REQUIRE(stream.handshake(request, [] { return false; }).success); + for (unsigned i = 0; i < 4; ++i) + { + peer->incoming.push_back(frame(0, 0, 1, std::string(16384, 'x'))); + } + // The app is blocked on its send window, so incoming payload isn't consumed. + // Credit is replenished only when recv() delivers bytes to the app. + bool rejected = false; + for (unsigned i = 0; i < 8; ++i) + { + char byte = 'x'; + if (stream.send(&byte, 1) < 0 && !ix::Socket::isWaitNeeded()) + { + rejected = true; + break; + } + } + CHECK(rejected); +} + +TEST_CASE("HTTP2 flushes partial control writes while its DATA window is blocked", "[http2]") +{ + auto peer = new Peer; + peer->incoming.front() = frame(4, 0, 0, hex("000800000001000400000000")); + ix::SocketHttp2 stream {std::unique_ptr(peer)}; + REQUIRE(stream.handshake(request, [] { return false; }).success); + peer->sent.clear(); + peer->partial = true; + peer->incoming.push_back(frame(0, 0, 1, "x")); + char byte; + REQUIRE(stream.recv(&byte, 1) == 1); + const auto updates = frame(8, 0, 0, hex("00000001")) + frame(8, 0, 1, hex("00000001")); + for (unsigned attempt = 0; attempt < 32 && peer->sent.size() < updates.size(); ++attempt) + { + stream.isReadyToWrite(0); + } + CHECK(peer->sent == updates); + CHECK(stream.isReadyToWrite(0) == ix::PollResultType::Timeout); +} + +TEST_CASE("HTTP2 exposes EOF while a send is blocked on flow control", "[http2]") +{ + auto peer = new Peer; + peer->incoming.front() = frame(4, 0, 0, hex("000800000001000400000000")); + ix::SocketHttp2 stream {std::unique_ptr(peer)}; + REQUIRE(stream.handshake(request, [] { return false; }).success); + peer->incoming.push_back(frame(0, 1, 1, "")); + stream.isReadyToWrite(0); + CHECK(stream.isReadyToWrite(0) == ix::PollResultType::ReadyForRead); + char byte; + CHECK(stream.recv(&byte, 1) == 0); +} diff --git a/test/h2_proxy/CMakeLists.txt b/test/h2_proxy/CMakeLists.txt index cf44e228..1c5bda16 100644 --- a/test/h2_proxy/CMakeLists.txt +++ b/test/h2_proxy/CMakeLists.txt @@ -5,8 +5,16 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) # This fixture is an HTTP/1.1 backend. Envoy terminates downstream TLS/H2. -set(USE_TLS OFF CACHE BOOL "" FORCE) -set(USE_NETWORK_FRAMEWORK OFF CACHE BOOL "" FORCE) +option(H2_PROXY_NATIVE_CLIENT "Also build the IXWebSocket HTTP/2 client" OFF) +if (H2_PROXY_NATIVE_CLIENT) + set(USE_TLS ON CACHE BOOL "" FORCE) + if (APPLE AND NOT USE_OPEN_SSL AND NOT USE_LIBRE_SSL AND NOT USE_MBED_TLS AND NOT USE_SECURE_TRANSPORT) + set(USE_NETWORK_FRAMEWORK ON CACHE BOOL "" FORCE) + endif() +else() + set(USE_TLS OFF CACHE BOOL "" FORCE) + set(USE_NETWORK_FRAMEWORK OFF CACHE BOOL "" FORCE) +endif() set(USE_ZLIB ON CACHE BOOL "" FORCE) set(USE_TEST OFF CACHE BOOL "" FORCE) set(USE_WS OFF CACHE BOOL "" FORCE) @@ -14,3 +22,8 @@ set(IXWEBSOCKET_INSTALL OFF CACHE BOOL "" FORCE) add_subdirectory(../.. ixwebsocket) add_executable(h2_proxy_server server.cpp) target_link_libraries(h2_proxy_server PRIVATE ixwebsocket::ixwebsocket) + +if (H2_PROXY_NATIVE_CLIENT) + add_executable(h2_proxy_client native_client.cpp) + target_link_libraries(h2_proxy_client PRIVATE ixwebsocket::ixwebsocket) +endif() diff --git a/test/h2_proxy/native_client.cpp b/test/h2_proxy/native_client.cpp new file mode 100644 index 00000000..fc063a6b --- /dev/null +++ b/test/h2_proxy/native_client.cpp @@ -0,0 +1,181 @@ +/* Copyright (c) 2026 Machine Zone, Inc. All rights reserved. */ +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char** argv) +{ + if (argc != 5) + { + return 2; + } + if (!ix::initNetSystem()) + { + return 1; + } + struct Cleanup + { + ~Cleanup() + { + ix::uninitNetSystem(); + } + } cleanup; + const bool compression = std::string(argv[3]) == "on"; + const bool serverClose = std::string(argv[4]) == "server"; + std::string large(256 * 1024, '\0'); + std::mt19937 random(0); + for (auto& byte : large) + { + byte = static_cast(random()); + } + const bool cancel = std::string(argv[4]) == "cancel"; + const bool duplex = std::string(argv[4]) == "duplex"; + std::vector> messages {{"", false}, + {"Bonjour — 中文 👋", false}, + {"", true}, + {std::string("\0\xff\x80" + "binary", + 9), + true}, + {large, true}}; + if (duplex) + { + uint32_t state = 0x12345678; + std::string prefill(256 * 1024, '\0'); + for (auto& byte : prefill) + { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + byte = static_cast(state); + } + messages.insert(messages.begin(), {prefill, true}); + } + std::promise finished; + auto result = finished.get_future(); + std::atomic done {false}; + size_t received = 0; + bool pong = false, closing = false; + ix::WebSocket client; + client.setUrl(argv[1]); + client.setHttp2(true); + client.disableAutomaticReconnection(); + client.setHandshakeTimeout(5); + ix::SocketTLSOptions options; + options.caFile = argv[2]; + client.setTLSOptions(options); + if (!compression) + { + client.disablePerMessageDeflate(); + } + auto finish = [&](bool success) + { + if (!done.exchange(true)) + { + finished.set_value(success); + } + }; + if (duplex) + { + client.setExtraHeaders({{"Origin", "https://client.example"}, + {"X-Proxy-Test", "h2-integration"}, + {"X-H2-Duplex", "1"}}); + } + else + { + client.setExtraHeaders( + {{"Origin", "https://client.example"}, {"X-Proxy-Test", "h2-integration"}}); + } + client.setOnMessageCallback( + [&](const ix::WebSocketMessagePtr& message) + { + if (message->type == ix::WebSocketMessageType::Open) + { + if (cancel) + { + finish(client.sendBinary(large).success); + return; + } + for (size_t i = duplex ? 1 : 0; i < messages.size(); ++i) + { + const auto& payload = messages[i]; + if (!client.send(payload.first, payload.second).success) + { + finish(false); + return; + } + } + client.ping("native-ping"); + } + else if (message->type == ix::WebSocketMessageType::Message) + { + if (received == messages.size() || message->str != messages[received].first || + message->binary != messages[received].second) + { + std::cerr << "Message mismatch at " << received << ": got " + << message->str.size() << " bytes binary=" << message->binary << '\n'; + finish(false); + return; + } + ++received; + } + else if (message->type == ix::WebSocketMessageType::Pong) + { + if (message->str != "native-ping") + { + finish(false); + return; + } + pong = true; + } + else if (message->type == ix::WebSocketMessageType::Error) + { + std::cerr << message->errorInfo.reason << '\n'; + finish(false); + } + else if (message->type == ix::WebSocketMessageType::Close) + { + finish(received == messages.size() && pong && + message->closeInfo.code == (serverClose ? 4000 : 1000) && + message->closeInfo.reason == + (serverClose ? "server close test" : "native close")); + } + if (!closing && received == messages.size() && pong) + { + closing = true; + if (serverClose) + { + client.sendText("close-from-server"); + } + else + { + client.close(1000, "native close"); + } + } + }); + client.start(); + const bool ready = result.wait_for(std::chrono::seconds(5)) == std::future_status::ready; + bool success = ready && result.get(); + const auto stopping = std::chrono::steady_clock::now(); + client.stop(); + if (cancel) + { + const auto elapsed = std::chrono::steady_clock::now() - stopping; + success = success && elapsed < std::chrono::seconds(2); + } + if (!success) + { + std::cerr << "Native HTTP/2 client failed; received " << received + << " messages (completed=" << ready << ")\n"; + } + else + { + std::cout << "PASS native HTTP/2 client compression=" << compression << " close=" << argv[4] + << '\n'; + } + return success ? 0 : 1; +} diff --git a/test/h2_proxy/native_peer.py b/test/h2_proxy/native_peer.py new file mode 100644 index 00000000..dc283d33 --- /dev/null +++ b/test/h2_proxy/native_peer.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +"""Independent Python H2/WebSocket peer for native TLS-backend interoperability.""" +import argparse +from collections import deque +from pathlib import Path +import socket +import ssl +import subprocess +import threading +import traceback + +from h2.config import H2Configuration +from h2.connection import H2Connection +from h2.events import DataReceived, RequestReceived, StreamEnded, StreamReset +from h2.settings import Settings, SettingCodes +from wsproto import Connection, ConnectionType +from wsproto.connection import ConnectionState +from wsproto.events import BytesMessage, CloseConnection, Ping, TextMessage +from wsproto.extensions import PerMessageDeflate + + +def serve(listener, context, errors): + try: + for connection_index in range(7): + raw, _ = listener.accept() + with context.wrap_socket(raw, server_side=True) as transport: + transport.settimeout(10) + assert transport.selected_alpn_protocol() == "h2" + h2 = H2Connection(config=H2Configuration(client_side=False, header_encoding="utf-8")) + h2.local_settings = Settings(client=False, initial_values={ + SettingCodes.ENABLE_CONNECT_PROTOCOL: 1}) + if connection_index == 6: + h2.local_settings[SettingCodes.INITIAL_WINDOW_SIZE] = 0 + h2.local_settings.acknowledge() + del h2.local_settings[SettingCodes.ENABLE_PUSH] + h2.initiate_connection() + transport.sendall(h2.data_to_send()) + ws, outgoing, chunks, pending = None, deque(), [], deque() + ending, duplex = False, False + + def receive(event): + nonlocal ending + h2.acknowledge_received_data(event.flow_controlled_length, 1) + if not event.data: + return + ws.receive_data(event.data) + for frame in ws.events(): + if isinstance(frame, (TextMessage, BytesMessage)): + chunks.append(frame.data) + if frame.message_finished: + value = ("" if isinstance(frame, TextMessage) else b"").join(chunks) + chunks.clear() + if value == "close-from-server": + outgoing.append(ws.send(CloseConnection(code=4000, reason="server close test"))) + else: + outgoing.append(ws.send(type(frame)(data=value))) + elif isinstance(frame, Ping): + outgoing.append(ws.send(frame.response())) + elif isinstance(frame, CloseConnection): + if ws.state == ConnectionState.REMOTE_CLOSING: + outgoing.append(ws.send(frame.response())) + ending = True + + while True: + data = transport.recv(65536) + if not data: + break + for event in h2.receive_data(data): + if isinstance(event, RequestReceived): + headers = dict(event.headers) + assert headers[":method"] == "CONNECT" and headers[":protocol"] == "websocket" + assert "sec-websocket-key" not in headers + extensions = [] + response = [(":status", "200")] + if "sec-websocket-extensions" in headers: + extension = PerMessageDeflate() + accepted = extension.accept(headers["sec-websocket-extensions"]) + assert accepted is not None + response.append(("sec-websocket-extensions", "permessage-deflate; " + accepted)) + extensions.append(extension) + ws = Connection(ConnectionType.SERVER, extensions=extensions) + h2.send_headers(1, response) + duplex = "x-h2-duplex" in headers + if duplex: + # Fill both directions before consuming application data. + # Keep the queued incoming DATA bounded by the H2 window. + state, payload = 0x12345678, bytearray() + for _ in range(256 * 1024): + state ^= (state << 13) & 0xffffffff + state ^= state >> 17 + state ^= (state << 5) & 0xffffffff + payload.append(state & 255) + outgoing.append(ws.send(BytesMessage(data=bytes(payload)))) + elif isinstance(event, DataReceived): + if duplex and outgoing: + pending.append(event) + else: + receive(event) + elif isinstance(event, (StreamEnded, StreamReset)): + ending = True + while True: + while outgoing: + size = min(len(outgoing[0]), h2.local_flow_control_window(1), h2.max_outbound_frame_size) + if not size: + break + h2.send_data(1, outgoing[0][:size]) + outgoing[0] = outgoing[0][size:] + if not outgoing[0]: + outgoing.popleft() + if outgoing or not pending: + break + while pending: + receive(pending.popleft()) + if ending and not outgoing: + h2.end_stream(1) + transport.sendall(h2.data_to_send()) + if ending and not outgoing: + break + except Exception as error: + errors.append(error) + traceback.print_exc() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("client", type=Path) + parser.add_argument("certificate", type=Path) + parser.add_argument("key", type=Path) + parser.add_argument("ca", type=Path) + parser.add_argument("--reject-alpn", action="store_true") + args = parser.parse_args() + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.load_cert_chain(args.certificate, args.key) + context.set_alpn_protocols(["h2"]) + errors = [] + if args.reject_alpn: + context.set_alpn_protocols(["http/1.1"]) + with socket.socket() as listener: + listener.bind(("127.0.0.1", 0)) + listener.listen() + listener.settimeout(10) + def reject(): + try: + raw, _ = listener.accept() + with context.wrap_socket(raw, server_side=True) as transport: + transport.settimeout(5) + assert not transport.recv(65536), "Client sent bytes without negotiating h2" + except Exception as error: + errors.append(error) + worker = threading.Thread(target=reject if args.reject_alpn else serve, + args=() if args.reject_alpn else (listener, context, errors), + daemon=True) + worker.start() + if args.reject_alpn: + result = subprocess.run([str(args.client), "wss://127.0.0.1:" + str(listener.getsockname()[1]) + "/native", + str(args.ca), "off", "client"], timeout=10, capture_output=True) + assert result.returncode != 0, "Client accepted HTTP/1.1 fallback" + print("PASS native client rejects missing ALPN h2 without sending HTTP bytes") + else: + for compression in ("off", "on"): + for close in ("client", "server", "duplex"): + subprocess.run([str(args.client), "wss://127.0.0.1:" + str(listener.getsockname()[1]) + "/native", + str(args.ca), compression, close], check=True, timeout=10) + if not args.reject_alpn: + subprocess.run([str(args.client), "wss://127.0.0.1:" + str(listener.getsockname()[1]) + "/native", + str(args.ca), "off", "cancel"], check=True, timeout=10) + worker.join(timeout=10) + assert not worker.is_alive(), "TLS peer did not stop" + if errors: + raise errors[0] + + +if __name__ == "__main__": + main() diff --git a/test/h2_proxy/run.py b/test/h2_proxy/run.py index 62a6c16e..6189cded 100644 --- a/test/h2_proxy/run.py +++ b/test/h2_proxy/run.py @@ -102,14 +102,15 @@ def backend_port(): if line.startswith("READY "): return int(line.split()[1]) port = wait_for(backend_port, processes) - certificate, key = output / "cert.pem", output / "key.pem" + ca, ca_key = output / "ca.pem", output / "ca.key" + certificate, key = output / "server.pem", output / "server.key" config = output / "openssl.cnf" config.write_text("""[req] distinguished_name = dn x509_extensions = extensions prompt = no [dn] - CN = localhost + CN = IXWebSocket-H2-Test-CA [extensions] subjectAltName = DNS:localhost,IP:127.0.0.1 basicConstraints = critical,CA:TRUE @@ -119,16 +120,59 @@ def backend_port(): """) with (output / "certificate.log").open("w") as log: subprocess.run([args.openssl, "req", "-x509", "-newkey", "rsa:2048", "-nodes", - "-days", "1", "-config", str(config), "-keyout", str(key), + "-days", "1", "-config", str(config), "-keyout", str(ca_key), + "-out", str(ca)], check=True, stdout=log, + stderr=subprocess.STDOUT, timeout=15) + leaf_config = output / "server.cnf" + leaf_config.write_text("""[req] + distinguished_name = dn + prompt = no + [dn] + CN = localhost + [extensions] + basicConstraints = critical,CA:FALSE + keyUsage = critical,digitalSignature,keyEncipherment + extendedKeyUsage = serverAuth + subjectAltName = DNS:localhost,IP:127.0.0.1 + subjectKeyIdentifier = hash + authorityKeyIdentifier = keyid:always + """) + with (output / "certificate.log").open("a") as log: + subprocess.run([args.openssl, "req", "-new", "-newkey", "rsa:2048", "-nodes", + "-config", str(leaf_config), "-keyout", str(key), + "-out", str(output / "server.csr")], check=True, + stdout=log, stderr=subprocess.STDOUT, timeout=15) + subprocess.run([args.openssl, "x509", "-req", "-days", "1", "-CA", str(ca), + "-CAkey", str(ca_key), "-CAcreateserial", "-extfile", str(leaf_config), + "-extensions", "extensions", "-in", str(output / "server.csr"), "-out", str(certificate)], check=True, stdout=log, stderr=subprocess.STDOUT, timeout=15) if args.proxy == "envoy": port = start_envoy(args, output, certificate, key, port, processes, logs) else: port = start_nghttpx(args, output, certificate, key, port, processes, logs) - client = wait_for(lambda: Client(port, certificate), processes) + client = wait_for(lambda: Client(port, ca), processes) + if args.native_client: + for compression in ("off", "on"): + for close in ("client", "server"): + with (output / ("native-" + compression + "-" + close + ".log")).open("w") as log: + subprocess.run([str(args.native_client), "wss://127.0.0.1:" + str(port) + "/native", + str(ca), compression, close], stdout=log, + stderr=subprocess.STDOUT, timeout=15, check=True) + print("PASS native IXWebSocket H2 compression=" + compression + " close=" + close, flush=True) + report["native_client"] = "4 combinations passed" + for reject in (False, True): + with (output / ("native-peer-reject.log" if reject else "native-peer.log")).open("w") as log: + command = [sys.executable, str(ROOT / "test/h2_proxy/native_peer.py"), + str(args.native_client), str(certificate), str(key), str(ca)] + if reject: + command.append("--reject-alpn") + subprocess.run(command, check=True, stdout=log, stderr=subprocess.STDOUT, timeout=45) + report["independent_native_peer"] = "6 exchange combinations, blocked-send cancellation, and ALPN rejection passed" + print("PASS native H2 client: independent peer, bidirectional backpressure and ALPN rejection", flush=True) report["alpn"] = "h2" - report["downstream_connections"] = 1 + report["python_downstream_connections"] = 1 + report["downstream_connections"] = 5 if args.native_client else 1 def passed(name): print("PASS " + name, flush=True) @@ -215,6 +259,17 @@ def passed(name): if processes[0].returncode != 0: report["success"] = False report.setdefault("error", "Backend did not stop cleanly") + if report.get("success") and args.native_client: + access = (output / "access.log").read_text().splitlines() + native_h2 = [line for line in access if "HTTP/2" in line and + ("ixwebsocket/" in line if args.proxy == "nghttpx" else "/native" in line)] + if len(native_h2) != 4: + report["success"] = False + report["error"] = "Proxy did not log four native HTTP/2 connections" + print("FAIL " + report["error"], file=sys.stderr) + else: + report["native_h2_connections_verified"] = 4 + print("PASS proxy access log confirms all native clients used HTTP/2", flush=True) report["elapsed_seconds"] = round(time.monotonic() - started, 3) (output / "report.json").write_text(json.dumps(report, indent=2) + "\n") return 0 if report.get("success") else 1 @@ -223,6 +278,7 @@ def passed(name): def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--server", type=Path, default=ROOT / "build/h2-proxy/h2_proxy_server") + parser.add_argument("--native-client", type=Path) parser.add_argument("--proxy", choices=("nghttpx", "envoy"), default="nghttpx") parser.add_argument("--nghttpx", default="nghttpx") parser.add_argument("--envoy", default="envoy") diff --git a/tools/run_h2_proxy.py b/tools/run_h2_proxy.py index 1decffc2..c911eba5 100644 --- a/tools/run_h2_proxy.py +++ b/tools/run_h2_proxy.py @@ -24,7 +24,8 @@ def main(): "--user", "{}:{}".format(os.getuid(), os.getgid()), "--env", "PYTHONUNBUFFERED=1", "--volume", str(runs) + ":/app/build/h2-proxy/runs", - image_id.read_text().strip()] + sys.argv[1:] + image_id.read_text().strip(), "--native-client", + "/app/build/h2-proxy/h2_proxy_client"] + sys.argv[1:] return subprocess.run(command).returncode except (OSError, subprocess.CalledProcessError) as error: print("H2 proxy test failed: {}. Build log: {}".format(error, output / "build.log"), diff --git a/ws/ws.cpp b/ws/ws.cpp index f2daea61..a96370d5 100644 --- a/ws/ws.cpp +++ b/ws/ws.cpp @@ -647,7 +647,8 @@ namespace ix const ix::ProxyOptions& proxyOptions, const std::string& subprotocol, int pingIntervalSecs, - bool decompressGzipMessages); + bool decompressGzipMessages, + bool http2); void subscribe(const std::string& channel); void start(); @@ -688,7 +689,8 @@ namespace ix const ix::ProxyOptions& proxyOptions, const std::string& subprotocol, int pingIntervalSecs, - bool decompressGzipMessages) + bool decompressGzipMessages, + bool http2) : _url(url) , _disablePerMessageDeflate(disablePerMessageDeflate) , _binaryMode(binaryMode) @@ -702,6 +704,7 @@ namespace ix } _webSocket.setMaxWaitBetweenReconnectionRetries(maxWaitBetweenReconnectionRetries); _webSocket.setTLSOptions(tlsOptions); + _webSocket.setHttp2(http2); _webSocket.setProxyOptions(proxyOptions); _webSocket.setPingInterval(pingIntervalSecs); @@ -879,7 +882,8 @@ namespace ix const ix::ProxyOptions& proxyOptions, const std::string& subprotocol, int pingIntervalSecs, - bool decompressGzipMessages) + bool decompressGzipMessages, + bool http2) { std::cout << "Type Ctrl-D to exit prompt..." << std::endl; WebSocketConnect webSocketChat(url, @@ -892,7 +896,8 @@ namespace ix proxyOptions, subprotocol, pingIntervalSecs, - decompressGzipMessages); + decompressGzipMessages, + http2); webSocketChat.start(); while (true) @@ -2771,6 +2776,7 @@ int main(int argc, char** argv) int pingIntervalSecs = 30; int runCount = 1; bool decompressGzipMessages = false; + bool http2 = false; auto addGenericOptions = [&pidfile](CLI::App* subcommand) { subcommand->add_option("--pidfile", pidfile, "Pid file"); }; @@ -2848,6 +2854,7 @@ int main(int argc, char** argv) connectApp->add_flag("-d", disableAutomaticReconnection, "Disable Automatic Reconnection"); connectApp->add_flag("-x", disablePerMessageDeflate, "Disable per message deflate"); connectApp->add_flag("-b", binaryMode, "Send in binary mode"); + connectApp->add_flag("--http2", http2, "Experimental RFC 8441 over wss (requires ALPN h2)"); connectApp->add_option("--max_wait", maxWaitBetweenReconnectionRetries, "Max Wait Time between reconnection retries"); @@ -3105,7 +3112,8 @@ int main(int argc, char** argv) proxyOptions, subprotocol, pingIntervalSecs, - decompressGzipMessages); + decompressGzipMessages, + http2); } else if (app.got_subcommand("bench")) { From f4643f2dc4695830e1d79f5f7948fc1461506fa1 Mon Sep 17 00:00:00 2001 From: Benjamin Sergeant Date: Mon, 23 Nov 2026 14:50:27 -0800 Subject: [PATCH 2/7] Keep Windows unity includes safe and validate Apple ALPN strings --- ixwebsocket/IXSetThreadName.cpp | 2 ++ ixwebsocket/IXSocketAppleSSL.cpp | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/ixwebsocket/IXSetThreadName.cpp b/ixwebsocket/IXSetThreadName.cpp index 2f4ee75b..b3f2ccbe 100644 --- a/ixwebsocket/IXSetThreadName.cpp +++ b/ixwebsocket/IXSetThreadName.cpp @@ -21,6 +21,8 @@ // Windows #ifdef _WIN32 +#include + #include #endif diff --git a/ixwebsocket/IXSocketAppleSSL.cpp b/ixwebsocket/IXSocketAppleSSL.cpp index 2d32ba1d..b4a443ad 100644 --- a/ixwebsocket/IXSocketAppleSSL.cpp +++ b/ixwebsocket/IXSocketAppleSSL.cpp @@ -264,6 +264,12 @@ namespace ix { auto value = CFStringCreateWithCString( kCFAllocatorDefault, protocol.c_str(), kCFStringEncodingUTF8); + if (!value) + { + CFRelease(protocols); + errMsg = "SecureTransport ALPN protocols must be valid UTF-8"; + return false; + } CFArrayAppendValue(protocols, value); CFRelease(value); } From 7f078cde0792afbce5f621d1578149403f0efbab Mon Sep 17 00:00:00 2001 From: Benjamin Sergeant Date: Mon, 23 Nov 2026 15:22:51 -0800 Subject: [PATCH 3/7] Retain failed test output and Autobahn container exit diagnostics --- makefile.dev | 2 +- tools/run_autobahn.py | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/makefile.dev b/makefile.dev index 65838ec7..bdae1a4b 100644 --- a/makefile.dev +++ b/makefile.dev @@ -164,7 +164,7 @@ test_asan: test_tsan_mbedtls: mkdir -p build && (cd build ; cmake -GNinja -DCMAKE_INSTALL_MESSAGE=LAZY -DCMAKE_UNITY_BUILD=ON -DCMAKE_BUILD_TYPE=Debug -DUSE_TLS=1 -DUSE_MBED_TLS=1 -DUSE_TEST=1 $(MBEDTLS_CMAKE_PREFIX) .. -DCMAKE_C_FLAGS="-fsanitize=thread -fno-omit-frame-pointer" -DCMAKE_CXX_FLAGS="-fsanitize=thread -fno-omit-frame-pointer") (cd build ; ninja) - (cd build ; ninja test) + ctest --test-dir build --output-on-failure test_tsan_openssl: mkdir -p build && (cd build ; cmake -GNinja -DCMAKE_INSTALL_MESSAGE=LAZY -DCMAKE_UNITY_BUILD=ON -DCMAKE_BUILD_TYPE=Debug -DUSE_TLS=1 -DUSE_OPEN_SSL=1 -DUSE_TEST=1 .. -DCMAKE_C_FLAGS="-fsanitize=thread -fno-omit-frame-pointer" -DCMAKE_CXX_FLAGS="-fsanitize=thread -fno-omit-frame-pointer") diff --git a/tools/run_autobahn.py b/tools/run_autobahn.py index 45d96220..bb5d0dac 100644 --- a/tools/run_autobahn.py +++ b/tools/run_autobahn.py @@ -71,6 +71,10 @@ def ready(self, peer, port): def collect_logs(self): for name in self.containers: + # Retain the reason for exit 137 (OOM kill versus timeout/signal). + with (self.output / "logs" / (name + "-state.json")).open("w") as state: + subprocess.run(["docker", "inspect", "--format", "{{json .State}}", name], + stdout=state, stderr=subprocess.STDOUT, text=True, timeout=30) with (self.output / "logs" / (name + ".log")).open("w") as log: try: subprocess.run(["docker", "logs", name], stdout=log, From 610fba41d161435596a78e40575a6d9222428c96 Mon Sep 17 00:00:00 2001 From: Benjamin Sergeant Date: Mon, 23 Nov 2026 15:29:20 -0800 Subject: [PATCH 4/7] Bound Autobahn server runner memory with complete checked batches --- docs/autobahn.md | 6 ++- test/autobahn/test_batches.py | 29 +++++++++++++++ tools/run_autobahn.py | 69 +++++++++++++++++++++++------------ 3 files changed, 80 insertions(+), 24 deletions(-) create mode 100644 test/autobahn/test_batches.py diff --git a/docs/autobahn.md b/docs/autobahn.md index 9891dd0b..f6b02b1d 100644 --- a/docs/autobahn.md +++ b/docs/autobahn.md @@ -43,7 +43,11 @@ missing cases, malformed reports, unknown statuses, non-strict results, and closing failures fail the check. Process success alone is insufficient. Reports are recreated under `build/autobahn/reports/client` and -`build/autobahn/reports/server`. Open each `index.html` for detailed results. +`build/autobahn/reports/server` (or `server-1`, `server-2`, etc. for large runs). +Open each `index.html` for detailed results. Server cases run in batches of at +most 64 with a fresh test runner, avoiding memory accumulation in the Python +suite. Every selected case still runs and every batch's complete report is checked; +the per-role timeout applies across all batches. Container logs and the selected suite/image IDs are also saved under `build/autobahn`. CI uploads these as the `autobahn-reports` artifact even when tests fail. Each role has a 30-minute limit; the whole CI job has a 75-minute diff --git a/test/autobahn/test_batches.py b/test/autobahn/test_batches.py new file mode 100644 index 00000000..c7bb116e --- /dev/null +++ b/test/autobahn/test_batches.py @@ -0,0 +1,29 @@ +"""Batching must preserve the full selected compliance suite without duplicates.""" +from pathlib import Path +import sys +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from run_autobahn import case_batches + + +class BatchesTest(unittest.TestCase): + def test_full_suite_runs_once_per_role(self): + expected = ["case-" + str(i) for i in range(517)] + runs = list(case_batches(["client", "server"], expected)) + self.assertEqual(len({name for _, name, _ in runs}), len(runs)) + for role in ("client", "server"): + self.assertEqual([case for kind, _, batch in runs if kind == role + for case in batch], expected) + self.assertEqual(runs[0], ("client", "client", expected)) + self.assertTrue(all(len(batch) <= 64 for role, _, batch in runs if role == "server")) + + def test_small_selection_keeps_standard_report_name_and_order(self): + expected = ["13.4.13", "1.1.1", "6.4.1"] + self.assertEqual(list(case_batches(["server"], expected)), + [("server", "server", expected)]) + + def test_exact_batch_boundary(self): + expected = list(range(64)) + self.assertEqual(list(case_batches(["server"], expected)), + [("server", "server", expected)]) diff --git a/tools/run_autobahn.py b/tools/run_autobahn.py index bb5d0dac..6af690b7 100644 --- a/tools/run_autobahn.py +++ b/tools/run_autobahn.py @@ -8,6 +8,7 @@ import signal import subprocess import sys +import time import uuid from check_autobahn import check_report @@ -23,6 +24,18 @@ def command(args, **kwargs): return subprocess.run(args, check=True, text=True, **kwargs) +def case_batches(roles, expected): + # The fuzzing client retains state across cases. Restart it between bounded + # batches so a full server run does not exhaust a small CI runner's memory. + # Every selected case still runs exactly once, and every report is checked. + for role in roles: + batches = ([expected] if role == "client" else + [expected[i:i + 64] for i in range(0, len(expected), 64)]) + for i, batch in enumerate(batches): + name = role if len(batches) == 1 else role + "-" + str(i + 1) + yield role, name, batch + + class Runner: def __init__(self, output, timeout, interactive=False): self.output = output @@ -49,9 +62,9 @@ def start(self, name, image, args, suite=False, alias=None): command(options + [image] + args, stdout=subprocess.DEVNULL) return container - def wait(self, container): + def wait(self, container, timeout): result = command(["docker", "wait", container], capture_output=True, - timeout=self.timeout + 30) + timeout=timeout + 30) return int(result.stdout.strip()) def ready(self, peer, port): @@ -64,7 +77,7 @@ def ready(self, peer, port): " except OSError:\n" " if time.monotonic()>deadline: raise\n" " time.sleep(0.2)\n" % (peer, port)) - container = self.start("probe-" + str(port), self.image, ["python3", "-c", probe]) + container = self.start("probe-" + str(port) + "-" + str(len(self.containers)), self.image, ["python3", "-c", probe]) status = command(["docker", "wait", container], capture_output=True, timeout=45) if int(status.stdout.strip()): raise RuntimeError("Server did not become ready: " + peer) @@ -72,11 +85,11 @@ def ready(self, peer, port): def collect_logs(self): for name in self.containers: # Retain the reason for exit 137 (OOM kill versus timeout/signal). - with (self.output / "logs" / (name + "-state.json")).open("w") as state: - subprocess.run(["docker", "inspect", "--format", "{{json .State}}", name], - stdout=state, stderr=subprocess.STDOUT, text=True, timeout=30) with (self.output / "logs" / (name + ".log")).open("w") as log: try: + with (self.output / "logs" / (name + "-state.json")).open("w") as state: + subprocess.run(["docker", "inspect", "--format", "{{json .State}}", name], + stdout=state, stderr=subprocess.STDOUT, text=True, timeout=30) subprocess.run(["docker", "logs", name], stdout=log, stderr=subprocess.STDOUT, text=True, timeout=30) except (OSError, subprocess.SubprocessError) as error: @@ -133,54 +146,64 @@ def run(self, roles, patterns): command(["docker", "network", "create", self.network], stdout=subprocess.DEVNULL) failed = False results = [] + deadlines = {} try: - for role in roles: - print("Running {} compliance: {} cases".format(role, len(expected)), flush=True) + for role, name, batch in case_batches(roles, expected): + deadline = deadlines.setdefault(role, time.monotonic() + self.timeout) + remaining = int(deadline - time.monotonic()) + if remaining <= 0: + raise RuntimeError(role + " compliance timed out") + print("Running {} compliance: {} cases".format(name, len(batch)), flush=True) if role == "client": peer = self.start("fuzzer", SUITE, [ "wstest", "-m", "fuzzingserver", "-s", "/config/fuzzingserver.json"], suite=True, alias="autobahn") self.ready("autobahn", 9001) test = self.start("client", self.image, [ - "timeout", "--kill-after=10s", str(self.timeout), + "timeout", "--kill-after=10s", str(remaining), "ws", "autobahn", "-q", "--url", "ws://autobahn:9001"]) else: - peer = self.start("echo", self.image, [ + spec = json.loads((self.output / "config/fuzzingclient.json").read_text()) + spec["cases"] = batch + spec["outdir"] = "/reports/" + name + config_name = name + ".json" + (self.output / "config" / config_name).write_text(json.dumps(spec) + "\n") + peer = self.start("echo-" + name, self.image, [ "ws", "echo_server", "--host", "0.0.0.0", "--port", "9002", "-q"], alias="ixwebsocket") self.ready("ixwebsocket", 9002) - test = self.start("server", SUITE, [ - "timeout", "--kill-after=10s", str(self.timeout), - "wstest", "-m", "fuzzingclient", "-s", "/config/fuzzingclient.json"], + test = self.start(name, SUITE, [ + "timeout", "--kill-after=10s", str(remaining), + "wstest", "-m", "fuzzingclient", "-s", "/config/" + config_name], suite=True) if self.interactive: status = wait_with_progress(test, peer if role == "client" else test, - role, expected, self.timeout + 30) + name, batch, remaining + 30) else: - status = self.wait(test) + status = self.wait(test, remaining) if status: - print("{} runner failed with exit {}".format(role, status), flush=True) + print("{} runner failed with exit {}".format(name, status), flush=True) failed = True - report_file = self.output / "reports" / role / "index.json" + report_file = self.output / "reports" / name / "index.json" try: - errors = check_report(json.loads(report_file.read_text()), expected) + errors = check_report(json.loads(report_file.read_text()), batch) except (OSError, ValueError, TypeError) as error: errors = [str(error)] for error in errors: - print("{}: {}".format(role, error), flush=True) + print("{}: {}".format(name, error), flush=True) failed = failed or bool(errors) - results.append((role, status == 0 and not errors)) + results.append((name, status == 0 and not errors, len(batch))) print("{}: {} expected cases, {} report failures".format( - role, len(expected), len(errors)), flush=True) + name, len(batch), len(errors)), flush=True) self.collect_logs() command(["docker", "stop", "--time", "5", peer], stdout=subprocess.DEVNULL) finally: self.cleanup() if self.interactive: print("\nAutobahn summary", flush=True) - for role, passed in results: + for name, passed, count in results: print(" {}: {} ({} expected cases)".format( - role, "PASS" if passed else "FAIL", len(expected)), flush=True) + name, "PASS" if passed else "FAIL", count), flush=True) print("Reports: " + str(self.output / "reports"), flush=True) return int(failed) From ffea69c57fb1b3fd7d78f6e68957c02ea16cb6ed Mon Sep 17 00:00:00 2001 From: Benjamin Sergeant Date: Mon, 23 Nov 2026 16:26:59 -0800 Subject: [PATCH 5/7] Enforce blank lines between definitions with clang-format --- .clang-format | 1 + ixwebsocket/IXHpack.cpp | 9 +++++++++ ixwebsocket/IXHttpClient.cpp | 1 + ixwebsocket/IXSetThreadName.cpp | 2 ++ ixwebsocket/IXSocketAppleSSL.cpp | 1 - ixwebsocket/IXSocketHttp2.cpp | 19 +++++++++++++++++++ ixwebsocket/IXSocketHttp2.h | 1 + ixwebsocket/IXSocketNetwork.cpp | 9 +++++++++ ixwebsocket/IXUuid.cpp | 1 - ixwebsocket/IXWebSocket.cpp | 4 ++-- ixwebsocket/IXWebSocketHandshakeKeyGen.h | 1 + ixwebsocket/IXWebSocketSendData.h | 12 ++++++++++++ ixwebsocket/IXWebSocketTransport.cpp | 1 - ixwebsocket/IXWebSocketTransport.h | 2 ++ test/IXDNSLookupTest.cpp | 1 - test/IXHttp2Test.cpp | 9 +++++++++ test/IXHttpClientAsyncTest.cpp | 3 +++ test/IXHttpClientResponseTest.cpp | 7 +++++++ test/IXHttpClientReuseTest.cpp | 10 ++++++++++ test/IXHttpClientUploadTest.cpp | 12 ++++++++++++ test/IXHttpServerStaticTest.cpp | 2 ++ test/IXHttpTest.cpp | 6 ++++++ test/IXHttpWebSocketUpgradeTest.cpp | 12 ++++++++++++ test/IXSocketAppleSSLReadTest.cpp | 5 +++++ test/IXSocketConnectTest.cpp | 1 - test/IXSocketMbedTLSWriteTest.cpp | 2 ++ test/IXSocketNetworkTest.cpp | 4 ++++ test/IXSocketOpenSSLWriteTest.cpp | 6 ++++++ test/IXSocks5Test.cpp | 10 ++++++++++ test/IXTest.cpp | 1 - test/IXUrlParserTest.cpp | 4 ++++ test/IXWebSocketDispatchTest.cpp | 1 + test/IXWebSocketMessageLimitTest.cpp | 7 +++++++ test/h2_proxy/native_client.cpp | 2 ++ ws/ws.cpp | 1 + 35 files changed, 162 insertions(+), 8 deletions(-) diff --git a/.clang-format b/.clang-format index ff779389..6d158de4 100644 --- a/.clang-format +++ b/.clang-format @@ -41,6 +41,7 @@ IndentWidth: 4 InsertBraces: true KeepEmptyLinesAtTheStartOfBlocks: false MaxEmptyLinesToKeep: 2 +SeparateDefinitionBlocks: Always NamespaceIndentation: All PenaltyReturnTypeOnItsOwnLine: 1000 PointerAlignment: Left diff --git a/ixwebsocket/IXHpack.cpp b/ixwebsocket/IXHpack.cpp index 3af2615a..8c23c3b5 100644 --- a/ixwebsocket/IXHpack.cpp +++ b/ixwebsocket/IXHpack.cpp @@ -145,6 +145,7 @@ namespace 28, 27, 27, 27, 20, 24, 20, 21, 22, 21, 21, 23, 22, 22, 25, 25, 24, 24, 26, 23, 26, 27, 26, 26, 27, 27, 27, 27, 27, 28, 27, 27, 27, 27, 27, 26, 30, }; + struct HuffmanTree { struct Node @@ -152,7 +153,9 @@ namespace int child[2] = {-1, -1}; int symbol = -1; }; + std::array nodes; + HuffmanTree() { int count = 1; @@ -172,6 +175,7 @@ namespace } } }; + bool integer(const std::string& data, size_t& offset, unsigned prefix, size_t& value) { if (offset == data.size()) @@ -201,6 +205,7 @@ namespace } return false; } + void integer(std::string& data, size_t value, unsigned prefix, unsigned flags) { const unsigned mask = (1u << prefix) - 1; @@ -218,6 +223,7 @@ namespace } data += char(value); } + bool string(const std::string& data, size_t& offset, std::string& value) { if (offset == data.size()) @@ -288,6 +294,7 @@ namespace ix } return block; } + Hpack::Headers::value_type Hpack::indexed(size_t index) const { if (index && index <= 61) @@ -300,6 +307,7 @@ namespace ix } return {}; } + void Hpack::evict() { while (_size > _capacity) @@ -309,6 +317,7 @@ namespace ix _dynamic.pop_back(); } } + bool Hpack::decode(const std::string& block, Headers& headers) { headers.clear(); diff --git a/ixwebsocket/IXHttpClient.cpp b/ixwebsocket/IXHttpClient.cpp index d6821f5f..93b03b26 100644 --- a/ixwebsocket/IXHttpClient.cpp +++ b/ixwebsocket/IXHttpClient.cpp @@ -45,6 +45,7 @@ namespace copy->cancel = args.cancel.load(); return copy; } + bool parseSize(const std::string& text, unsigned base, size_t& value) { if (text.empty()) diff --git a/ixwebsocket/IXSetThreadName.cpp b/ixwebsocket/IXSetThreadName.cpp index b3f2ccbe..493f3943 100644 --- a/ixwebsocket/IXSetThreadName.cpp +++ b/ixwebsocket/IXSetThreadName.cpp @@ -32,6 +32,7 @@ namespace ix const DWORD MS_VC_EXCEPTION = 0x406D1388; #pragma pack(push, 8) + typedef struct tagTHREADNAME_INFO { DWORD dwType; // Must be 0x1000. @@ -39,6 +40,7 @@ namespace ix DWORD dwThreadID; // Thread ID (-1=caller thread). DWORD dwFlags; // Reserved for future use, must be zero. } THREADNAME_INFO; + #pragma pack(pop) void SetThreadName(DWORD dwThreadID, const char* threadName) diff --git a/ixwebsocket/IXSocketAppleSSL.cpp b/ixwebsocket/IXSocketAppleSSL.cpp index b4a443ad..a6be4e00 100644 --- a/ixwebsocket/IXSocketAppleSSL.cpp +++ b/ixwebsocket/IXSocketAppleSSL.cpp @@ -169,7 +169,6 @@ namespace ix } } - bool SocketAppleSSL::accept(std::string& errMsg) { errMsg = "TLS not supported yet in server mode with apple ssl backend"; diff --git a/ixwebsocket/IXSocketHttp2.cpp b/ixwebsocket/IXSocketHttp2.cpp index 3da5a9be..1df6541d 100644 --- a/ixwebsocket/IXSocketHttp2.cpp +++ b/ixwebsocket/IXSocketHttp2.cpp @@ -16,6 +16,7 @@ namespace } return value; } + std::string number(uint32_t value) { std::string data(4, '\0'); @@ -26,6 +27,7 @@ namespace } return data; } + bool validName(const std::string& name) { if (name.empty()) @@ -43,6 +45,7 @@ namespace } return true; } + bool validValue(const std::string& value) { for (unsigned char c : value) @@ -56,12 +59,14 @@ namespace value.back() != ' ' && value.back() != '\t'); } } // namespace + namespace ix { SocketHttp2::SocketHttp2(std::unique_ptr socket) : _inner(std::move(socket)) { } + SocketHttp2::~SocketHttp2() { close(); @@ -82,6 +87,7 @@ namespace ix } return false; } + bool SocketHttp2::queue( unsigned type, unsigned flags, uint32_t stream, const std::string& payload, size_t accepted) { @@ -103,6 +109,7 @@ namespace ix _output.push_back(std::move(output)); return true; } + bool SocketHttp2::flush() { while (!_output.empty()) @@ -132,6 +139,7 @@ namespace ix } return true; } + bool SocketHttp2::headers() { Hpack::Headers fields; @@ -214,6 +222,7 @@ namespace ix _ended = _headerEndStream; return true; } + void SocketHttp2::credit(size_t count) { if (!count || _ended) @@ -225,6 +234,7 @@ namespace ix queue(8, 0, 0, number(static_cast(count))); queue(8, 0, 1, number(static_cast(count))); } + bool SocketHttp2::frame(unsigned type, unsigned flags, uint32_t stream, @@ -439,6 +449,7 @@ namespace ix } return true; } + bool SocketHttp2::read() { char buffer[16384]; @@ -480,6 +491,7 @@ namespace ix _input.erase(0, offset); return flush(); } + WebSocketInitResult SocketHttp2::handshake(const Hpack::Headers& fields, const CancellationRequest& cancelled) { @@ -561,6 +573,7 @@ namespace ix : _error), _headers); } + std::ptrdiff_t SocketHttp2::send(char* buffer, size_t length) { std::lock_guard lock(_mutex); @@ -608,6 +621,7 @@ namespace ix Socket::setErrno(EWOULDBLOCK); return -1; } + std::ptrdiff_t SocketHttp2::recv(void* buffer, size_t length) { std::lock_guard lock(_mutex); @@ -648,6 +662,7 @@ namespace ix Socket::setErrno(_error.empty() ? EWOULDBLOCK : EINVAL); return -1; } + PollResultType SocketHttp2::isReadyToRead(int timeoutMs) { bool writing, buffered; @@ -685,6 +700,7 @@ namespace ix } return _inner->isReadyToRead(timeoutMs); } + PollResultType SocketHttp2::isReadyToWrite(int timeoutMs) { bool blocked, buffered, writing; @@ -744,14 +760,17 @@ namespace ix } return ready; } + bool SocketHttp2::wakeUpFromPoll(uint64_t code) { return _inner->wakeUpFromPoll(code); } + bool SocketHttp2::isWakeUpFromPollSupported() { return _inner->isWakeUpFromPollSupported(); } + void SocketHttp2::close() { std::lock_guard lock(_mutex); diff --git a/ixwebsocket/IXSocketHttp2.h b/ixwebsocket/IXSocketHttp2.h index 4fb4d63d..fca801e5 100644 --- a/ixwebsocket/IXSocketHttp2.h +++ b/ixwebsocket/IXSocketHttp2.h @@ -31,6 +31,7 @@ namespace ix size_t offset = 0; size_t accepted = 0; }; + std::unique_ptr _inner; std::mutex _mutex; Hpack _hpack; diff --git a/ixwebsocket/IXSocketNetwork.cpp b/ixwebsocket/IXSocketNetwork.cpp index 740444e6..80efc89b 100644 --- a/ixwebsocket/IXSocketNetwork.cpp +++ b/ixwebsocket/IXSocketNetwork.cpp @@ -52,6 +52,7 @@ namespace ix int readFd = -1; int writeFd = -1; bool signalled = false; // guarded by the owning state's mutex + NetworkSignal() { int fds[2]; @@ -74,6 +75,7 @@ namespace ix } } } + ~NetworkSignal() { if (readFd != -1) @@ -85,6 +87,7 @@ namespace ix ::close(writeFd); } } + void notify() { if (!signalled && writeFd != -1) @@ -98,6 +101,7 @@ namespace ix signalled = written == 1; } } + void clear() { char byte; @@ -411,6 +415,7 @@ namespace ix bool server = false; std::string error; std::string negotiatedProtocol; + ~State() { if (connection) @@ -420,6 +425,7 @@ namespace ix } dispatch_release(queue); } + // Called under mutex. At most 64 KiB is outstanding or buffered. static void receive(const std::shared_ptr& state) { @@ -631,6 +637,7 @@ namespace ix { return accept(error, CancellationRequest()); } + bool SocketNetwork::accept(std::string& error, const CancellationRequest& cancelled) { return start(error, cancelled); @@ -783,6 +790,7 @@ namespace ix bool stopped = false; std::string error; std::string negotiatedProtocol; + ~State() { if (listener) @@ -803,6 +811,7 @@ namespace ix : _state(std::make_shared()) { } + SocketNetworkListener::~SocketNetworkListener() { stop(); diff --git a/ixwebsocket/IXUuid.cpp b/ixwebsocket/IXUuid.cpp index dc7fb0df..5649dd1b 100644 --- a/ixwebsocket/IXUuid.cpp +++ b/ixwebsocket/IXUuid.cpp @@ -22,7 +22,6 @@ #include #include - namespace ix { class Uuid diff --git a/ixwebsocket/IXWebSocket.cpp b/ixwebsocket/IXWebSocket.cpp index 9a83242c..610134eb 100644 --- a/ixwebsocket/IXWebSocket.cpp +++ b/ixwebsocket/IXWebSocket.cpp @@ -17,13 +17,11 @@ #include #include - namespace { const std::string emptyMsg; } // namespace - namespace ix { OnTrafficTrackerCallback WebSocket::_onTrafficTrackerCallback = nullptr; @@ -142,11 +140,13 @@ namespace ix _pingMessage = sendMessage; _ws.setPingMessage(_pingMessage, pingType); } + const std::string WebSocket::getPingMessage() const { std::lock_guard lock(_configMutex); return _pingMessage; } + void WebSocket::setPingInterval(int pingIntervalSecs) { std::lock_guard lock(_configMutex); diff --git a/ixwebsocket/IXWebSocketHandshakeKeyGen.h b/ixwebsocket/IXWebSocketHandshakeKeyGen.h index 56528fcf..5717149e 100644 --- a/ixwebsocket/IXWebSocketHandshakeKeyGen.h +++ b/ixwebsocket/IXWebSocketHandshakeKeyGen.h @@ -50,6 +50,7 @@ class WebSocketHandshakeKeyGen { return (value << bits) | (value >> (32 - bits)); } + static inline uint32_t blk(uint32_t b[16], size_t i) { return rol(b[(i + 13) & 15] ^ b[(i + 8) & 15] ^ b[(i + 2) & 15] ^ b[i], 1); diff --git a/ixwebsocket/IXWebSocketSendData.h b/ixwebsocket/IXWebSocketSendData.h index 0946dc0b..91cca4cb 100644 --- a/ixwebsocket/IXWebSocketSendData.h +++ b/ixwebsocket/IXWebSocketSendData.h @@ -39,10 +39,12 @@ namespace ix : _ptr(nullptr) { } + IXWebSocketSendData_const_iterator(pointer ptr) : _ptr(ptr) { } + ~IXWebSocketSendData_const_iterator() { } @@ -51,44 +53,54 @@ namespace ix { return const_iterator(_ptr++); } + const_iterator& operator++() { ++_ptr; return *this; } + reference operator*() const { return *_ptr; } + pointer operator->() const { return _ptr; } + const_iterator operator+(const difference_type offset) const { return const_iterator(_ptr + offset); } + const_iterator operator-(const difference_type offset) const { return const_iterator(_ptr - offset); } + difference_type operator-(const const_iterator& rhs) const { return _ptr - rhs._ptr; } + bool operator==(const const_iterator& rhs) const { return _ptr == rhs._ptr; } + bool operator!=(const const_iterator& rhs) const { return _ptr != rhs._ptr; } + const_iterator& operator+=(const difference_type offset) { _ptr += offset; return *this; } + const_iterator& operator-=(const difference_type offset) { _ptr -= offset; diff --git a/ixwebsocket/IXWebSocketTransport.cpp b/ixwebsocket/IXWebSocketTransport.cpp index 4ecadf8f..989cbeef 100644 --- a/ixwebsocket/IXWebSocketTransport.cpp +++ b/ixwebsocket/IXWebSocketTransport.cpp @@ -51,7 +51,6 @@ #include #include - namespace ix { const int WebSocketTransport::kDefaultPingIntervalSecs(-1); diff --git a/ixwebsocket/IXWebSocketTransport.h b/ixwebsocket/IXWebSocketTransport.h index 6c7be97a..2b719c12 100644 --- a/ixwebsocket/IXWebSocketTransport.h +++ b/ixwebsocket/IXWebSocketTransport.h @@ -142,6 +142,7 @@ namespace ix bool rsv2; bool rsv3; bool mask; + enum opcode_type { CONTINUATION = 0x0, @@ -151,6 +152,7 @@ namespace ix PING = 9, PONG = 0xa, } opcode; + int N0; uint64_t N; uint8_t masking_key[4]; diff --git a/test/IXDNSLookupTest.cpp b/test/IXDNSLookupTest.cpp index 23a1d613..71b99a1f 100644 --- a/test/IXDNSLookupTest.cpp +++ b/test/IXDNSLookupTest.cpp @@ -11,7 +11,6 @@ using namespace ix; - TEST_CASE("dns", "[net]") { SECTION("Test resolving a loopback address") diff --git a/test/IXHttp2Test.cpp b/test/IXHttp2Test.cpp index 54518827..0f1df975 100644 --- a/test/IXHttp2Test.cpp +++ b/test/IXHttp2Test.cpp @@ -18,6 +18,7 @@ namespace } return result; } + std::string frame(unsigned type, unsigned flags, unsigned stream, const std::string& payload) { std::string result(9, '\0'); @@ -29,6 +30,7 @@ namespace result[8] = char(stream); return result + payload; } + class Peer final : public ix::Socket { public: @@ -37,12 +39,14 @@ namespace size_t fragment = 16384; bool partial = false; unsigned writes = 0; + Peer() { incoming.push_back(frame(4, 0, 0, hex("000800000001"))); incoming.push_back(frame(4, 1, 0, "")); incoming.push_back(frame(1, 4, 1, hex("88"))); } + std::ptrdiff_t send(char* data, size_t size) override { if (partial && ++writes % 2 == 0) @@ -54,6 +58,7 @@ namespace sent.append(data, size); return static_cast(size); } + std::ptrdiff_t recv(void* data, size_t size) override { if (incoming.empty()) @@ -71,20 +76,24 @@ namespace } return static_cast(size); } + ix::PollResultType isReadyToRead(int) override { return incoming.empty() ? ix::PollResultType::Timeout : ix::PollResultType::ReadyForRead; } + ix::PollResultType isReadyToWrite(int) override { return ix::PollResultType::ReadyForWrite; } + bool wakeUpFromPoll(uint64_t) override { return true; } }; + ix::Hpack::Headers request {{":method", "CONNECT"}, {":protocol", "websocket"}, {":scheme", "https"}, diff --git a/test/IXHttpClientAsyncTest.cpp b/test/IXHttpClientAsyncTest.cpp index 5e651703..ab39dfa4 100644 --- a/test/IXHttpClientAsyncTest.cpp +++ b/test/IXHttpClientAsyncTest.cpp @@ -189,14 +189,17 @@ TEST_CASE("Active HTTP cancellation survives redirects", "[http][async]") std::promise completed; auto result = completed.get_future(); ix::HttpClient client(true); + struct OpenOnExit { ReleaseGate& gate; + ~OpenOnExit() { gate.open(); } } release {responseGate}; + auto args = client.createRequest(url(server) + (redirect ? "/redirect" : "/slow"), ix::HttpClient::kGet); REQUIRE(client.performRequest(args, diff --git a/test/IXHttpClientResponseTest.cpp b/test/IXHttpClientResponseTest.cpp index 2bf05b81..daad56db 100644 --- a/test/IXHttpClientResponseTest.cpp +++ b/test/IXHttpClientResponseTest.cpp @@ -15,24 +15,29 @@ namespace { public: using Script = std::function; + explicit ResponseServer(Script script) : SocketServer(ix::getFreePort(), "127.0.0.1") , _script(std::move(script)) { } + ~ResponseServer() override { stop(); } + void startServing() { REQUIRE(listen().first); start(); } + std::string url() { return "http://127.0.0.1:" + std::to_string(getPort()) + "/"; } + std::vector requests() { std::lock_guard lock(_mutex); @@ -66,10 +71,12 @@ namespace } state->setTerminated(); } + size_t getConnectedClientsCount() override { return 0; } + Script _script; std::mutex _mutex; std::vector _requests; diff --git a/test/IXHttpClientReuseTest.cpp b/test/IXHttpClientReuseTest.cpp index d4bd3661..0b02ac9c 100644 --- a/test/IXHttpClientReuseTest.cpp +++ b/test/IXHttpClientReuseTest.cpp @@ -31,6 +31,7 @@ namespace { std::string bytes; bool close = false; + explicit Reply(std::string wire, bool closeConnection = false) : bytes(std::move(wire)) , close(closeConnection) @@ -48,6 +49,7 @@ namespace { public: using Script = std::function; + struct Request { ix::HttpRequestPtr http; @@ -73,15 +75,18 @@ namespace REQUIRE(listen().first); start(); } + ~PersistentServer() override { stop(); } + std::string url() { return std::string(_tls ? "https" : "http") + "://127.0.0.1:" + std::to_string(getPort()) + "/"; } + std::vector requests() { std::lock_guard lock(_mutex); @@ -119,10 +124,12 @@ namespace } state->setTerminated(); } + size_t getConnectedClientsCount() override { return 0; } + Script _script; bool _tls; std::atomic _connections {0}; @@ -140,6 +147,7 @@ namespace (void) client; #endif } + ix::HttpRequestArgsPtr options(ix::HttpClient& client) { auto args = client.createRequest(); @@ -157,6 +165,7 @@ namespace : _failure(std::move(failure)) { } + std::ptrdiff_t recv(void* data, size_t) override { if (!_probed) @@ -185,6 +194,7 @@ namespace } return 0; } + std::ptrdiff_t send(char*, size_t size) override { return _failure == "send" ? 0 : static_cast(size); diff --git a/test/IXHttpClientUploadTest.cpp b/test/IXHttpClientUploadTest.cpp index a342cf28..18f52ffd 100644 --- a/test/IXHttpClientUploadTest.cpp +++ b/test/IXHttpClientUploadTest.cpp @@ -41,15 +41,18 @@ namespace REQUIRE(listen().first); start(); } + ~UploadServer() override { stop(); } + std::string url() { return std::string(_tls ? "https://127.0.0.1:" : "http://127.0.0.1:") + std::to_string(getPort()) + "/"; } + std::future headers = _headers.get_future(); private: @@ -57,6 +60,7 @@ namespace { return 0; } + void handleConnection(std::unique_ptr socket, std::shared_ptr state) override { @@ -91,6 +95,7 @@ namespace } state->setTerminated(); } + const bool _headersOnly; const bool _redirect; const bool _tls; @@ -104,6 +109,7 @@ namespace std::string method, body, wire, connection; ix::WebSocketHttpHeaders headers; }; + explicit ChunkedUploadServer(bool tls = false, int redirect = 0) : SocketServer(ix::getFreePort(), "127.0.0.1") , _tls(tls) @@ -123,20 +129,24 @@ namespace REQUIRE(listen().first); start(); } + ~ChunkedUploadServer() override { stop(); } + std::string url() { return std::string(_tls ? "https" : "http") + "://127.0.0.1:" + std::to_string(getPort()) + "/"; } + std::vector requests() { std::lock_guard lock(_mutex); return _requests; } + std::atomic connections {0}; private: @@ -144,6 +154,7 @@ namespace { return 0; } + void handleConnection(std::unique_ptr socket, std::shared_ptr state) override { @@ -234,6 +245,7 @@ namespace } state->setTerminated(); } + bool _tls; int _redirect; std::mutex _mutex; diff --git a/test/IXHttpServerStaticTest.cpp b/test/IXHttpServerStaticTest.cpp index 7b6cc6f3..8cb3dcc2 100644 --- a/test/IXHttpServerStaticTest.cpp +++ b/test/IXHttpServerStaticTest.cpp @@ -18,6 +18,7 @@ namespace std::string name = "static-test-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()) + ".bin"; + explicit File(const std::string& bytes) { std::ofstream file(name, std::ios::binary); @@ -25,6 +26,7 @@ namespace file.write(bytes.data(), static_cast(bytes.size())); REQUIRE(file.good()); } + ~File() { std::remove(name.c_str()); diff --git a/test/IXHttpTest.cpp b/test/IXHttpTest.cpp index 6cbd757a..c29ceb7e 100644 --- a/test/IXHttpTest.cpp +++ b/test/IXHttpTest.cpp @@ -23,14 +23,17 @@ namespace ix HttpClient client; CHECK(client.urlEncode("AZaz09-._~ /+") == "AZaz09-._~%20%2F%2B"); CHECK(client.urlEncode(std::string("\0\x7f\x80\xc4\xe4\xff", 6)) == "%00%7F%80%C4%E4%FF"); + struct RestoreLocale { std::string name = std::setlocale(LC_CTYPE, nullptr); + ~RestoreLocale() { std::setlocale(LC_CTYPE, name.c_str()); } } restore; + if (!std::setlocale(LC_CTYPE, "en_US.ISO8859-1") && !std::setlocale(LC_CTYPE, "tr_TR.ISO8859-9")) { @@ -122,6 +125,7 @@ namespace : _input(input) { } + std::ptrdiff_t recv(void* buffer, size_t length) override { const size_t size = (std::min) (length, _input.size() - _offset); @@ -129,11 +133,13 @@ namespace _offset += size; return static_cast(size); } + std::ptrdiff_t send(char* buffer, size_t length) override { output.append(buffer, length); return static_cast(length); } + std::string output; private: diff --git a/test/IXHttpWebSocketUpgradeTest.cpp b/test/IXHttpWebSocketUpgradeTest.cpp index 1dcc00e2..c75d88c2 100644 --- a/test/IXHttpWebSocketUpgradeTest.cpp +++ b/test/IXHttpWebSocketUpgradeTest.cpp @@ -21,6 +21,7 @@ namespace std::string uri; ix::WebSocketHttpHeaders headers; }; + explicit UpgradeServer(bool tls = false, std::string mode = "normal", std::function beforeAuthReply = {}, @@ -45,23 +46,28 @@ namespace REQUIRE(listen().first); start(); } + ~UpgradeServer() override { stop(); } + std::string httpUrl() { return std::string(_tls ? "https" : "http") + "://127.0.0.1:" + std::to_string(getPort()); } + std::string wsUrl() { return std::string(_tls ? "wss" : "ws") + "://127.0.0.1:" + std::to_string(getPort()); } + unsigned connections() const { return _connections; } + std::vector requests() { std::lock_guard lock(_mutex); @@ -172,10 +178,12 @@ namespace } state->setTerminated(); } + size_t getConnectedClientsCount() override { return 0; } + bool _tls; std::string _mode; std::function _beforeAuthReply; @@ -193,6 +201,7 @@ namespace args->compress = false; return args; } + void configure(ix::HttpClient& client) { #ifdef IX_HTTP_UPGRADE_TEST_CERTS @@ -217,6 +226,7 @@ namespace std::atomic opens {0}, welcomes {0}, echoes {0}, closes {0}; std::thread::id openThread; ix::WebSocket ws; + Client() { ws.setExtraHeaders({{"Authorization", "Bearer token"}}); @@ -248,10 +258,12 @@ namespace } }); } + ~Client() { ws.stop(); } + void checkEcho() { ws.start(); diff --git a/test/IXSocketAppleSSLReadTest.cpp b/test/IXSocketAppleSSLReadTest.cpp index 1b0dbe9d..b69ad3d2 100644 --- a/test/IXSocketAppleSSLReadTest.cpp +++ b/test/IXSocketAppleSSLReadTest.cpp @@ -17,27 +17,32 @@ namespace ix *size = 0; return errSecIO; } + static OSStatus write(SSLConnectionRef, const void*, size_t* size) { *size = 0; return errSecIO; } + static OSStatus readBlocked(SSLConnectionRef, void*, size_t* size) { *size = 0; return errSSLWouldBlock; } + static OSStatus writeBlocked(SSLConnectionRef, const void*, size_t* size) { *size = 0; return errSSLWouldBlock; } + static OSStatus handshake(SocketAppleSSL& socket, std::string& error, const CancellationRequest& cancelled) { return socket.tlsHandShake(error, cancelled); } + static void install(SocketAppleSSL& socket, bool blocked = false, bool reading = true) { socket._sslContext = diff --git a/test/IXSocketConnectTest.cpp b/test/IXSocketConnectTest.cpp index f602d168..90c155a1 100644 --- a/test/IXSocketConnectTest.cpp +++ b/test/IXSocketConnectTest.cpp @@ -21,7 +21,6 @@ TEST_CASE("Write polling reports invalid socket errors", "[net][connect]") CHECK(Socket::getErrno() != 0); } - TEST_CASE("socket_connect", "[net]") { SECTION("Test connecting to a known hostname") diff --git a/test/IXSocketMbedTLSWriteTest.cpp b/test/IXSocketMbedTLSWriteTest.cpp index 52bc4aac..6ecf9b8c 100644 --- a/test/IXSocketMbedTLSWriteTest.cpp +++ b/test/IXSocketMbedTLSWriteTest.cpp @@ -40,10 +40,12 @@ namespace ix { return socket.handshake(error, cancelled); } + static int reset(SocketMbedTLS& socket) { return mbedtls_ssl_session_reset(&socket._ssl); } + static void install(SocketMbedTLS& socket, mbedtls_ssl_context& session) { socket.initMBedTLS(); diff --git a/test/IXSocketNetworkTest.cpp b/test/IXSocketNetworkTest.cpp index 4827152b..cc997f02 100644 --- a/test/IXSocketNetworkTest.cpp +++ b/test/IXSocketNetworkTest.cpp @@ -9,12 +9,14 @@ #include using namespace ix; + namespace { std::string credential(const std::string& name) { return std::string(IX_NETWORK_TEST_CERTS) + "/" + name; } + SocketTLSOptions serverOptions(const std::string& name = "server") { SocketTLSOptions options; @@ -24,12 +26,14 @@ namespace options.caFile = "NONE"; return options; } + SocketTLSOptions clientOptions() { SocketTLSOptions options; options.caFile = credential("ca.pem"); return options; } + void checkRequest(SocketTLSOptions serverTLS, SocketTLSOptions clientTLS, bool expected, diff --git a/test/IXSocketOpenSSLWriteTest.cpp b/test/IXSocketOpenSSLWriteTest.cpp index 6f18f92f..301cb413 100644 --- a/test/IXSocketOpenSSLWriteTest.cpp +++ b/test/IXSocketOpenSSLWriteTest.cpp @@ -25,16 +25,19 @@ namespace ix { return socket.configureKeyLogging(context, error); } + static bool handshake(SocketOpenSSL& socket, std::string& error, const CancellationRequest& cancelled) { return socket.openSSLClientHandshake("memory.invalid", error, cancelled); } + static int reset(SocketOpenSSL& socket) { return SSL_clear(socket._ssl_connection); } + static void install(SocketOpenSSL& socket, SSL*& session, SSL_CTX*& context) { std::swap(socket._ssl_connection, session); @@ -393,16 +396,19 @@ namespace { std::string name = std::string(IX_OPENSSL_TEST_OUTPUT_DIR) + "/keylog-" + ix::uuid4() + ".log"; + KeyLogFile() { std::ofstream file(name, std::ios::binary); REQUIRE(file.is_open()); file << "# existing content\n"; } + ~KeyLogFile() { std::remove(name.c_str()); } + std::vector lines() const { std::ifstream file(name, std::ios::binary); diff --git a/test/IXSocks5Test.cpp b/test/IXSocks5Test.cpp index 0fac01cc..0dbc9cac 100644 --- a/test/IXSocks5Test.cpp +++ b/test/IXSocks5Test.cpp @@ -46,6 +46,7 @@ namespace std::string username; std::string password; }; + explicit SocksProxy(Reply reply = Reply::IPv4, bool auth = false, bool tunnel = false) : SocketServer(ix::getFreePort(), "127.0.0.1") , _reply(reply) @@ -53,20 +54,24 @@ namespace , _tunnel(tunnel) { } + ~SocksProxy() override { stop(); } + void stop() override { _stopping = true; SocketServer::stop(); } + void listenAndStart() { REQUIRE(listen().first); start(); } + ix::ProxyOptions options() { ix::ProxyOptions result; @@ -79,11 +84,13 @@ namespace } return result; } + Request request() { std::lock_guard lock(_mutex); return _request; } + std::atomic connections {0}; std::atomic greetings {0}; @@ -92,6 +99,7 @@ namespace { return 0; } + void handleConnection(std::unique_ptr socket, std::shared_ptr state) override { @@ -99,6 +107,7 @@ namespace serve(*socket); state->setTerminated(); } + void serve(ix::Socket& socket) { const auto deadline = Clock::now() + std::chrono::seconds(5); @@ -298,6 +307,7 @@ namespace std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } + Reply _reply; bool _auth; bool _tunnel; diff --git a/test/IXTest.cpp b/test/IXTest.cpp index 305f4bd6..4f615738 100644 --- a/test/IXTest.cpp +++ b/test/IXTest.cpp @@ -20,7 +20,6 @@ #include #include - namespace ix { std::atomic incomingBytes(0); diff --git a/test/IXUrlParserTest.cpp b/test/IXUrlParserTest.cpp index d07f1938..aabc1bb9 100644 --- a/test/IXUrlParserTest.cpp +++ b/test/IXUrlParserTest.cpp @@ -287,14 +287,17 @@ TEST_CASE("URL schemes stay ASCII in single byte locales", "[url][components]") { const char* current = std::setlocale(LC_CTYPE, nullptr); const std::string saved = current ? current : "C"; + struct RestoreLocale { std::string name; + ~RestoreLocale() { std::setlocale(LC_CTYPE, name.c_str()); } } restore {saved}; + if (!std::setlocale(LC_CTYPE, "en_US.ISO8859-1")) { SKIP("Single-byte test locale is unavailable"); @@ -327,6 +330,7 @@ TEST_CASE("URL origins compare scheme, hostname and effective port", "[url][orig const char* second; bool same; }; + const Example examples[] = { {"HTTP://EXAMPLE.com/a", "http://example.COM:80/b?query#fragment", true}, {"https://example.com/a", "https://example.com:443/b", true}, diff --git a/test/IXWebSocketDispatchTest.cpp b/test/IXWebSocketDispatchTest.cpp index b4432ec1..c0c3dcb6 100644 --- a/test/IXWebSocketDispatchTest.cpp +++ b/test/IXWebSocketDispatchTest.cpp @@ -374,6 +374,7 @@ namespace void close() override { } + std::string sent; }; diff --git a/test/IXWebSocketMessageLimitTest.cpp b/test/IXWebSocketMessageLimitTest.cpp index 21c5dac3..7494853c 100644 --- a/test/IXWebSocketMessageLimitTest.cpp +++ b/test/IXWebSocketMessageLimitTest.cpp @@ -27,18 +27,22 @@ namespace ix } transport.setReadyState(WebSocketTransport::ReadyState::OPEN); } + static void append(WebSocketTransport& transport, const std::string& data) { transport._rxbuf.insert(transport._rxbuf.end(), data.begin(), data.end()); } + static uint64_t wanted(const WebSocketTransport& transport) { return transport._rxbufWanted; } + static size_t chunks(const WebSocketTransport& transport) { return transport._chunks.size(); } + static size_t decodedCapacity(const WebSocketTransport& transport) { return transport._decompressedMessage.capacity(); @@ -83,6 +87,7 @@ namespace sent.append(data, size); return static_cast(size); } + std::string sent; }; @@ -101,6 +106,7 @@ namespace socket = capture.get(); Access::install(transport, std::move(capture), compression); } + void receive(const std::string& bytes) { Access::append(transport, bytes); @@ -120,6 +126,7 @@ namespace } }); } + uint16_t closeCode() const { const auto& bytes = socket->sent; diff --git a/test/h2_proxy/native_client.cpp b/test/h2_proxy/native_client.cpp index fc063a6b..4131e365 100644 --- a/test/h2_proxy/native_client.cpp +++ b/test/h2_proxy/native_client.cpp @@ -17,6 +17,7 @@ int main(int argc, char** argv) { return 1; } + struct Cleanup { ~Cleanup() @@ -24,6 +25,7 @@ int main(int argc, char** argv) ix::uninitNetSystem(); } } cleanup; + const bool compression = std::string(argv[3]) == "on"; const bool serverClose = std::string(argv[4]) == "server"; std::string large(256 * 1024, '\0'); diff --git a/ws/ws.cpp b/ws/ws.cpp index a96370d5..22ff106b 100644 --- a/ws/ws.cpp +++ b/ws/ws.cpp @@ -658,6 +658,7 @@ namespace ix { return _sentBytes; } + int getReceivedBytes() { return _receivedBytes; From 9ddc42227556f1a56da2c7367b2efa0ce620d2ad Mon Sep 17 00:00:00 2001 From: Benjamin Sergeant Date: Mon, 23 Nov 2026 16:43:10 -0800 Subject: [PATCH 6/7] Separate WebSocket byte streams from TCP and TLS sockets --- CMakeLists.txt | 8 +- docs/http2.md | 18 +++- ...XSocketHttp2.cpp => IXHttp2Connection.cpp} | 44 +++++----- .../{IXSocketHttp2.h => IXHttp2Connection.h} | 24 +++--- ixwebsocket/IXHttp2Stream.cpp | 45 ++++++++++ ixwebsocket/IXHttp2Stream.h | 24 ++++++ ixwebsocket/IXWebSocketHandshake.cpp | 17 +++- ixwebsocket/IXWebSocketHandshake.h | 5 ++ ixwebsocket/IXWebSocketStream.cpp | 45 ++++++++++ ixwebsocket/IXWebSocketStream.h | 38 +++++++++ ixwebsocket/IXWebSocketTransport.cpp | 84 ++++++++++--------- ixwebsocket/IXWebSocketTransport.h | 11 +-- test/IXHttp2Test.cpp | 75 ++++++++++++++--- test/IXWebSocketDispatchTest.cpp | 3 +- test/IXWebSocketMessageLimitTest.cpp | 3 +- test/IXWebSocketSendBufferTest.h | 5 +- test/IXWebSocketSendFailureTest.cpp | 3 +- 17 files changed, 350 insertions(+), 102 deletions(-) rename ixwebsocket/{IXSocketHttp2.cpp => IXHttp2Connection.cpp} (95%) rename ixwebsocket/{IXSocketHttp2.h => IXHttp2Connection.h} (73%) create mode 100644 ixwebsocket/IXHttp2Stream.cpp create mode 100644 ixwebsocket/IXHttp2Stream.h create mode 100644 ixwebsocket/IXWebSocketStream.cpp create mode 100644 ixwebsocket/IXWebSocketStream.h diff --git a/CMakeLists.txt b/CMakeLists.txt index a9b3b69b..fe8919b8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -67,7 +67,9 @@ set( IXWEBSOCKET_SOURCES ixwebsocket/IXSelectInterruptPipe.cpp ixwebsocket/IXSelectInterruptEvent.cpp ixwebsocket/IXSetThreadName.cpp - ixwebsocket/IXSocketHttp2.cpp + ixwebsocket/IXHttp2Connection.cpp + ixwebsocket/IXHttp2Stream.cpp + ixwebsocket/IXWebSocketStream.cpp ixwebsocket/IXSocket.cpp ixwebsocket/IXSocketConnect.cpp ixwebsocket/IXSocketFactory.cpp @@ -112,7 +114,9 @@ set( IXWEBSOCKET_HEADERS ixwebsocket/IXSelectInterruptPipe.h ixwebsocket/IXSelectInterruptEvent.h ixwebsocket/IXSetThreadName.h - ixwebsocket/IXSocketHttp2.h + ixwebsocket/IXHttp2Connection.h + ixwebsocket/IXHttp2Stream.h + ixwebsocket/IXWebSocketStream.h ixwebsocket/IXSocket.h ixwebsocket/IXSocketConnect.h ixwebsocket/IXSocketFactory.h diff --git a/docs/http2.md b/docs/http2.md index 4baafce9..8f6b6580 100644 --- a/docs/http2.md +++ b/docs/http2.md @@ -40,8 +40,22 @@ SecureTransport. Existing backend certificate/trust limitations still apply. Normal certificate and hostname verification remain enabled by default. Existing WebSocket framing, masking, fragmentation, compression, message limits, -callbacks, ping/pong and close handling are reused through an H2 stream adapter. -The adapter handles SETTINGS, HEADERS/CONTINUATION, flow control, PING, +callbacks, ping/pong and close handling consume a `WebSocketStream` byte stream: + +```text +WebSocketTransport + -> SocketStream -> Socket (TCP/TLS, after HTTP/1.1 Upgrade) + -> Http2Stream -> Http2Connection -> Socket (TCP/TLS) +``` + +The handshake transfers ownership of the appropriate stream to the transport. +`Socket` and its TLS subclasses keep their Unix socket responsibilities; neither +HTTP/2 class inherits from `Socket` or owns a placeholder descriptor. +`Http2Connection` owns HTTP/2 framing and flow control, while `Http2Stream` +exposes the WebSocket bytes through the same interface as `SocketStream`. +This keeps the existing one-connection-per-WebSocket behavior in both modes. + +The connection handles SETTINGS, HEADERS/CONTINUATION, flow control, PING, WINDOW_UPDATE, GOAWAY, RST_STREAM and stream termination. Server push is disabled. HPACK responses support the static/dynamic tables and Huffman coding. Outgoing fields are literal and never indexed, including credentials. Compressed and diff --git a/ixwebsocket/IXSocketHttp2.cpp b/ixwebsocket/IXHttp2Connection.cpp similarity index 95% rename from ixwebsocket/IXSocketHttp2.cpp rename to ixwebsocket/IXHttp2Connection.cpp index 1df6541d..351562a8 100644 --- a/ixwebsocket/IXSocketHttp2.cpp +++ b/ixwebsocket/IXHttp2Connection.cpp @@ -1,5 +1,5 @@ /* Copyright (c) 2026 Machine Zone, Inc. All rights reserved. */ -#include "IXSocketHttp2.h" +#include "IXHttp2Connection.h" #include #include @@ -62,17 +62,17 @@ namespace namespace ix { - SocketHttp2::SocketHttp2(std::unique_ptr socket) + Http2Connection::Http2Connection(std::unique_ptr socket) : _inner(std::move(socket)) { } - SocketHttp2::~SocketHttp2() + Http2Connection::~Http2Connection() { close(); } - bool SocketHttp2::fail(const std::string& message, uint32_t code) + bool Http2Connection::fail(const std::string& message, uint32_t code) { if (_error.empty()) { @@ -88,7 +88,7 @@ namespace ix return false; } - bool SocketHttp2::queue( + bool Http2Connection::queue( unsigned type, unsigned flags, uint32_t stream, const std::string& payload, size_t accepted) { // Bound pending control traffic even if a malicious peer floods PING/SETTINGS. @@ -110,7 +110,7 @@ namespace ix return true; } - bool SocketHttp2::flush() + bool Http2Connection::flush() { while (!_output.empty()) { @@ -140,7 +140,7 @@ namespace ix return true; } - bool SocketHttp2::headers() + bool Http2Connection::headers() { Hpack::Headers fields; if (!_hpack.decode(_headerBlock, fields)) @@ -223,7 +223,7 @@ namespace ix return true; } - void SocketHttp2::credit(size_t count) + void Http2Connection::credit(size_t count) { if (!count || _ended) { @@ -235,10 +235,10 @@ namespace ix queue(8, 0, 1, number(static_cast(count))); } - bool SocketHttp2::frame(unsigned type, - unsigned flags, - uint32_t stream, - const std::string& payload) + bool Http2Connection::frame(unsigned type, + unsigned flags, + uint32_t stream, + const std::string& payload) { if (_firstFrame && (type != 4 || (flags & 1))) { @@ -450,7 +450,7 @@ namespace ix return true; } - bool SocketHttp2::read() + bool Http2Connection::read() { char buffer[16384]; const auto count = _inner->recv(buffer, sizeof(buffer)); @@ -492,8 +492,8 @@ namespace ix return flush(); } - WebSocketInitResult SocketHttp2::handshake(const Hpack::Headers& fields, - const CancellationRequest& cancelled) + WebSocketInitResult Http2Connection::handshake(const Hpack::Headers& fields, + const CancellationRequest& cancelled) { std::lock_guard lock(_mutex); const std::string preface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"; @@ -574,7 +574,7 @@ namespace ix _headers); } - std::ptrdiff_t SocketHttp2::send(char* buffer, size_t length) + std::ptrdiff_t Http2Connection::send(char* buffer, size_t length) { std::lock_guard lock(_mutex); if (_closed || !_error.empty() || _reset) @@ -622,7 +622,7 @@ namespace ix return -1; } - std::ptrdiff_t SocketHttp2::recv(void* buffer, size_t length) + std::ptrdiff_t Http2Connection::recv(void* buffer, size_t length) { std::lock_guard lock(_mutex); if (_dataOffset == _data.size() && !_closed && _error.empty() && !_ended) @@ -663,7 +663,7 @@ namespace ix return -1; } - PollResultType SocketHttp2::isReadyToRead(int timeoutMs) + PollResultType Http2Connection::isReadyToRead(int timeoutMs) { bool writing, buffered; { @@ -701,7 +701,7 @@ namespace ix return _inner->isReadyToRead(timeoutMs); } - PollResultType SocketHttp2::isReadyToWrite(int timeoutMs) + PollResultType Http2Connection::isReadyToWrite(int timeoutMs) { bool blocked, buffered, writing; { @@ -761,17 +761,17 @@ namespace ix return ready; } - bool SocketHttp2::wakeUpFromPoll(uint64_t code) + bool Http2Connection::wakeUpFromPoll(uint64_t code) { return _inner->wakeUpFromPoll(code); } - bool SocketHttp2::isWakeUpFromPollSupported() + bool Http2Connection::isWakeUpFromPollSupported() { return _inner->isWakeUpFromPollSupported(); } - void SocketHttp2::close() + void Http2Connection::close() { std::lock_guard lock(_mutex); if (!_closed) diff --git a/ixwebsocket/IXSocketHttp2.h b/ixwebsocket/IXHttp2Connection.h similarity index 73% rename from ixwebsocket/IXSocketHttp2.h rename to ixwebsocket/IXHttp2Connection.h index fca801e5..ec7f3c62 100644 --- a/ixwebsocket/IXSocketHttp2.h +++ b/ixwebsocket/IXHttp2Connection.h @@ -7,22 +7,22 @@ namespace ix { - // One RFC 8441 stream (1) on an exclusively owned HTTP/2 connection. - // The TLS socket owns the descriptor and its poll interruption mechanism. - class SocketHttp2 final : public Socket + // HTTP/2 framing, HPACK and flow control for one RFC 8441 stream (1). + // Owns the real TLS socket; this connection is not itself a socket. + class Http2Connection final { public: - explicit SocketHttp2(std::unique_ptr socket); - ~SocketHttp2() override; + explicit Http2Connection(std::unique_ptr socket); + ~Http2Connection(); WebSocketInitResult handshake(const Hpack::Headers& headers, const CancellationRequest& cancelled); - std::ptrdiff_t send(char* buffer, size_t length) override; - std::ptrdiff_t recv(void* buffer, size_t length) override; - PollResultType isReadyToRead(int timeoutMs) override; - PollResultType isReadyToWrite(int timeoutMs) override; - bool wakeUpFromPoll(uint64_t code) override; - bool isWakeUpFromPollSupported() override; - void close() override; + std::ptrdiff_t send(char* buffer, size_t length); + std::ptrdiff_t recv(void* buffer, size_t length); + PollResultType isReadyToRead(int timeoutMs); + PollResultType isReadyToWrite(int timeoutMs); + bool wakeUpFromPoll(uint64_t code); + bool isWakeUpFromPollSupported(); + void close(); private: struct Output diff --git a/ixwebsocket/IXHttp2Stream.cpp b/ixwebsocket/IXHttp2Stream.cpp new file mode 100644 index 00000000..79fff284 --- /dev/null +++ b/ixwebsocket/IXHttp2Stream.cpp @@ -0,0 +1,45 @@ +/* Copyright (c) 2026 Machine Zone, Inc. All rights reserved. */ +#include "IXHttp2Stream.h" + +namespace ix +{ + Http2Stream::Http2Stream(std::unique_ptr transport) + : _connection(std::move(transport)) + { + } + + std::ptrdiff_t Http2Stream::send(char* buffer, size_t length) + { + return _connection->send(buffer, length); + } + + std::ptrdiff_t Http2Stream::recv(void* buffer, size_t length) + { + return _connection->recv(buffer, length); + } + + PollResultType Http2Stream::isReadyToRead(int timeoutMs) + { + return _connection->isReadyToRead(timeoutMs); + } + + PollResultType Http2Stream::isReadyToWrite(int timeoutMs) + { + return _connection->isReadyToWrite(timeoutMs); + } + + bool Http2Stream::wakeUpFromPoll(uint64_t code) + { + return _connection->wakeUpFromPoll(code); + } + + bool Http2Stream::isWakeUpFromPollSupported() + { + return _connection->isWakeUpFromPollSupported(); + } + + void Http2Stream::close() + { + _connection->close(); + } +} // namespace ix diff --git a/ixwebsocket/IXHttp2Stream.h b/ixwebsocket/IXHttp2Stream.h new file mode 100644 index 00000000..24fb5910 --- /dev/null +++ b/ixwebsocket/IXHttp2Stream.h @@ -0,0 +1,24 @@ +/* Copyright (c) 2026 Machine Zone, Inc. All rights reserved. */ +#pragma once +#include "IXHttp2Connection.h" +#include "IXWebSocketStream.h" + +namespace ix +{ + // WebSocket bytes carried by the exclusively owned HTTP/2 stream. + class Http2Stream final : public WebSocketStream + { + public: + explicit Http2Stream(std::unique_ptr connection); + std::ptrdiff_t send(char* buffer, size_t length) override; + std::ptrdiff_t recv(void* buffer, size_t length) override; + PollResultType isReadyToRead(int timeoutMs) override; + PollResultType isReadyToWrite(int timeoutMs) override; + bool wakeUpFromPoll(uint64_t code) override; + bool isWakeUpFromPollSupported() override; + void close() override; + + private: + std::unique_ptr _connection; + }; +} // namespace ix diff --git a/ixwebsocket/IXWebSocketHandshake.cpp b/ixwebsocket/IXWebSocketHandshake.cpp index 3f3b39c3..e2eb99eb 100644 --- a/ixwebsocket/IXWebSocketHandshake.cpp +++ b/ixwebsocket/IXWebSocketHandshake.cpp @@ -8,8 +8,8 @@ #include "IXBase64.h" #include "IXHttp.h" +#include "IXHttp2Stream.h" #include "IXSocketConnect.h" -#include "IXSocketHttp2.h" #include "IXStrCaseCompare.h" #include "IXUniquePtr.h" #include "IXUrlParser.h" @@ -94,6 +94,15 @@ namespace ix return WebSocketInitResult(false, code, reason); } + std::unique_ptr WebSocketHandshake::takeStream() + { + if (!_stream && _socket) + { + _stream = ix::make_unique(std::move(_socket)); + } + return std::move(_stream); + } + WebSocketInitResult WebSocketHandshake::clientHandshake( const std::string& url, const WebSocketHttpHeaders& extraHeaders, @@ -203,9 +212,9 @@ namespace ix } fields.emplace_back(name, field.second); } - auto socket = ix::make_unique(std::move(_socket)); - auto result = socket->handshake(fields, isCancellationRequested); - _socket = std::move(socket); + auto connection = ix::make_unique(std::move(_socket)); + auto result = connection->handshake(fields, isCancellationRequested); + _stream = ix::make_unique(std::move(connection)); result.uri = path; if (!result.success) { diff --git a/ixwebsocket/IXWebSocketHandshake.h b/ixwebsocket/IXWebSocketHandshake.h index de32029e..7e712cb4 100644 --- a/ixwebsocket/IXWebSocketHandshake.h +++ b/ixwebsocket/IXWebSocketHandshake.h @@ -13,6 +13,7 @@ #include "IXWebSocketInitResult.h" #include "IXWebSocketPerMessageDeflate.h" #include "IXWebSocketPerMessageDeflateOptions.h" +#include "IXWebSocketStream.h" #include #include #include @@ -46,6 +47,9 @@ namespace ix bool enablePerMessageDeflate, HttpRequestPtr request = nullptr); + // Transfer the TCP/TLS or HTTP/2 byte stream after the handshake. + std::unique_ptr takeStream(); + private: std::string genRandomString(const int len); @@ -58,6 +62,7 @@ namespace ix std::atomic& _requestInitCancellation; std::unique_ptr& _socket; + std::unique_ptr _stream; WebSocketPerMessageDeflatePtr& _perMessageDeflate; WebSocketPerMessageDeflateOptions& _perMessageDeflateOptions; std::atomic& _enablePerMessageDeflate; diff --git a/ixwebsocket/IXWebSocketStream.cpp b/ixwebsocket/IXWebSocketStream.cpp new file mode 100644 index 00000000..fd4a93c4 --- /dev/null +++ b/ixwebsocket/IXWebSocketStream.cpp @@ -0,0 +1,45 @@ +/* Copyright (c) 2026 Machine Zone, Inc. All rights reserved. */ +#include "IXWebSocketStream.h" + +namespace ix +{ + SocketStream::SocketStream(std::unique_ptr transport) + : _socket(std::move(transport)) + { + } + + std::ptrdiff_t SocketStream::send(char* buffer, size_t length) + { + return _socket->send(buffer, length); + } + + std::ptrdiff_t SocketStream::recv(void* buffer, size_t length) + { + return _socket->recv(buffer, length); + } + + PollResultType SocketStream::isReadyToRead(int timeoutMs) + { + return _socket->isReadyToRead(timeoutMs); + } + + PollResultType SocketStream::isReadyToWrite(int timeoutMs) + { + return _socket->isReadyToWrite(timeoutMs); + } + + bool SocketStream::wakeUpFromPoll(uint64_t code) + { + return _socket->wakeUpFromPoll(code); + } + + bool SocketStream::isWakeUpFromPollSupported() + { + return _socket->isWakeUpFromPollSupported(); + } + + void SocketStream::close() + { + _socket->close(); + } +} // namespace ix diff --git a/ixwebsocket/IXWebSocketStream.h b/ixwebsocket/IXWebSocketStream.h new file mode 100644 index 00000000..0f522f48 --- /dev/null +++ b/ixwebsocket/IXWebSocketStream.h @@ -0,0 +1,38 @@ +/* Copyright (c) 2026 Machine Zone, Inc. All rights reserved. */ +#pragma once +#include "IXSocket.h" + +namespace ix +{ + // The WebSocket byte stream. Implementations own their transport and use + // Socket's would-block convention, without exposing a descriptor or connect API. + class WebSocketStream + { + public: + virtual ~WebSocketStream() = default; + virtual std::ptrdiff_t send(char* buffer, size_t length) = 0; + virtual std::ptrdiff_t recv(void* buffer, size_t length) = 0; + virtual PollResultType isReadyToRead(int timeoutMs) = 0; + virtual PollResultType isReadyToWrite(int timeoutMs) = 0; + virtual bool wakeUpFromPoll(uint64_t code) = 0; + virtual bool isWakeUpFromPollSupported() = 0; + virtual void close() = 0; + }; + + // HTTP/1.1 Upgrade leaves WebSocket bytes directly on the TCP/TLS socket. + class SocketStream final : public WebSocketStream + { + public: + explicit SocketStream(std::unique_ptr socket); + std::ptrdiff_t send(char* buffer, size_t length) override; + std::ptrdiff_t recv(void* buffer, size_t length) override; + PollResultType isReadyToRead(int timeoutMs) override; + PollResultType isReadyToWrite(int timeoutMs) override; + bool wakeUpFromPoll(uint64_t code) override; + bool isWakeUpFromPollSupported() override; + void close() override; + + private: + std::unique_ptr _socket; + }; +} // namespace ix diff --git a/ixwebsocket/IXWebSocketTransport.cpp b/ixwebsocket/IXWebSocketTransport.cpp index 989cbeef..2f087d9b 100644 --- a/ixwebsocket/IXWebSocketTransport.cpp +++ b/ixwebsocket/IXWebSocketTransport.cpp @@ -124,7 +124,7 @@ namespace ix { _blockingSend = false; } - std::lock_guard lock(_socketMutex); + std::lock_guard lock(_streamMutex); std::string protocol, host, path, query; int port; @@ -146,18 +146,19 @@ namespace ix std::string errorMsg; bool tls = protocol == "wss"; - _socket = alreadyConnected - ? std::move(connectedSocket) - : createSocket(tls, -1, errorMsg, _socketTLSOptions, _proxyOptions); + _stream.reset(); + auto socket = alreadyConnected + ? std::move(connectedSocket) + : createSocket(tls, -1, errorMsg, _socketTLSOptions, _proxyOptions); _perMessageDeflate = ix::make_unique(); - if (!_socket) + if (!socket) { return WebSocketInitResult(false, 0, errorMsg); } WebSocketHandshake webSocketHandshake(_requestInitCancellation, - _socket, + socket, _perMessageDeflate, _perMessageDeflateOptions, _enablePerMessageDeflate); @@ -172,6 +173,7 @@ namespace ix disabledDefaultHeaders, alreadyConnected, _http2); + _stream = webSocketHandshake.takeStream(); if (!alreadyConnected && result.http_status >= 300 && result.http_status < 400) { @@ -201,7 +203,7 @@ namespace ix else if (alreadyConnected) { // An unsuccessful upgrade cannot return to HTTP or reconnect implicitly. - _socket.reset(); + _stream.reset(); } return result; } @@ -217,24 +219,25 @@ namespace ix int sendTimeoutSecs) { resetConnectionState(); - std::lock_guard lock(_socketMutex); + std::lock_guard lock(_streamMutex); // Server should not mask the data it sends to the client _useMask = false; _blockingSend = true; _sendTimeoutSecs = sendTimeoutSecs; - _socket = std::move(socket); + _stream.reset(); _perMessageDeflate = ix::make_unique(); WebSocketHandshake webSocketHandshake(_requestInitCancellation, - _socket, + socket, _perMessageDeflate, _perMessageDeflateOptions, _enablePerMessageDeflate); auto result = webSocketHandshake.serverHandshake(timeoutSecs, enablePerMessageDeflate, request); + _stream = webSocketHandshake.takeStream(); if (result.success) { setReadyState(ReadyState::OPEN); @@ -401,7 +404,7 @@ namespace ix } // The platform may not have select interrupt capabilities, so wait with a small timeout - if (lastingTimeoutDelayInMs <= 0 && !_socket->isWakeUpFromPollSupported()) + if (lastingTimeoutDelayInMs <= 0 && !_stream->isWakeUpFromPollSupported()) { lastingTimeoutDelayInMs = 20; } @@ -413,8 +416,8 @@ namespace ix lastingTimeoutDelayInMs = 100; } - // poll the socket - PollResultType pollResult = _socket->isReadyToRead(lastingTimeoutDelayInMs); + // Poll the WebSocket byte stream. + PollResultType pollResult = _stream->isReadyToRead(lastingTimeoutDelayInMs); // Make sure we send all the buffered data // there can be a lot of it for large messages. @@ -427,7 +430,7 @@ namespace ix } else if (pollResult == PollResultType::ReadyForRead) { - if (!receiveFromSocket()) + if (!receiveFromStream()) { return PollResult::AbnormalClose; } @@ -458,7 +461,7 @@ namespace ix void WebSocketTransport::resetConnectionState() { // Frames and fragments belong to one connection and cannot be replayed on another. - // Take this lock before _socketMutex, matching sendOnSocket()'s lock order. + // Take this lock before _streamMutex, matching sendOnStream()'s lock order. std::lock_guard lock(_txbufMutex); _txbuf.clear(); _txbufPending.clear(); @@ -892,13 +895,13 @@ namespace ix wakeUpFromPoll(SelectInterrupt::kCloseRequest); bool remote = true; - closeSocketAndSwitchToClosedState(code, reason, _rxbuf.size(), remote); + closeStreamAndSwitchToClosedState(code, reason, _rxbuf.size(), remote); } else { // A peer may reply with a different status/reason. Receiving its Close // completes the handshake; retain our original local close notification. - closeSocketAndSwitchToClosedState( + closeStreamAndSwitchToClosedState( _closeCode, getCloseReason(), _rxbuf.size(), false); } } @@ -930,7 +933,7 @@ namespace ix // if we weren't closing, then close using abnormal close code and message else if (_readyState != ReadyState::CLOSED) { - closeSocketAndSwitchToClosedState(WebSocketCloseConstants::kAbnormalCloseCode, + closeStreamAndSwitchToClosedState(WebSocketCloseConstants::kAbnormalCloseCode, WebSocketCloseConstants::kAbnormalCloseMessage, 0, false); @@ -1209,7 +1212,7 @@ namespace ix appendToSendBuffer(header, message_begin, message_end, message_size, masking_key); // Now actually send this data - return sendOnSocket(); + return sendOnStream(); } WebSocketSendInfo WebSocketTransport::sendPing(const IXWebSocketSendData& message) @@ -1248,7 +1251,7 @@ namespace ix _closeCode == WebSocketCloseConstants::kAbnormalCloseCode; } - bool WebSocketTransport::sendOnSocket() + bool WebSocketTransport::sendOnStream() { std::unique_lock lock(_txbufMutex); if (isAbnormalClose() || _readyState == ReadyState::CLOSED) @@ -1268,8 +1271,8 @@ namespace ix } std::ptrdiff_t ret = 0; { - std::lock_guard socketLock(_socketMutex); - ret = _socket->send((char*) _txbufPending.data() + _txbufPendingOffset, + std::lock_guard streamLock(_streamMutex); + ret = _stream->send((char*) _txbufPending.data() + _txbufPendingOffset, _txbufPending.size() - _txbufPendingOffset); } @@ -1299,7 +1302,7 @@ namespace ix return true; } - bool WebSocketTransport::receiveFromSocket() + bool WebSocketTransport::receiveFromStream() { while (true) { @@ -1321,7 +1324,7 @@ namespace ix break; } - std::ptrdiff_t ret = _socket->recv((char*) &_readbuf[0], _readbuf.size()); + std::ptrdiff_t ret = _stream->recv((char*) &_readbuf[0], _readbuf.size()); if (ret < 0 && Socket::isWaitNeeded()) { @@ -1374,17 +1377,20 @@ namespace ix void WebSocketTransport::closeSocket() { - std::lock_guard lock(_socketMutex); - _socket->close(); + std::lock_guard lock(_streamMutex); + if (_stream) + { + _stream->close(); + } } bool WebSocketTransport::wakeUpFromPoll(uint64_t wakeUpCode) { - std::lock_guard lock(_socketMutex); - return _socket->wakeUpFromPoll(wakeUpCode); + std::lock_guard lock(_streamMutex); + return _stream && _stream->wakeUpFromPoll(wakeUpCode); } - void WebSocketTransport::closeSocketAndSwitchToClosedState(uint16_t code, + void WebSocketTransport::closeStreamAndSwitchToClosedState(uint16_t code, const std::string& reason, size_t closeWireSize, bool remote) @@ -1461,8 +1467,8 @@ namespace ix // interrupt event to happen. bool wakeUpPoll = false; { - std::lock_guard lock(_socketMutex); - wakeUpPoll = (_socket && _socket->isWakeUpFromPollSupported()); + std::lock_guard lock(_streamMutex); + wakeUpPoll = (_stream && _stream->isWakeUpFromPollSupported()); } if (wakeUpPoll) { @@ -1504,9 +1510,9 @@ namespace ix while (!isSendBufferEmpty() && !_requestInitCancellation) { - // Wait with a 10ms timeout until the socket is ready to write. + // Wait with a 10ms timeout until the stream is ready to write. // This way we are not busy looping - PollResultType result = _socket->isReadyToWrite(10); + PollResultType result = _stream->isReadyToWrite(10); if (result == PollResultType::Error) { @@ -1514,12 +1520,12 @@ namespace ix WebSocketCloseConstants::kAbnormalCloseMessage); return false; } - else if (_http2 && result == PollResultType::ReadyForRead) + else if (result == PollResultType::ReadyForRead) { - // H2 DATA in the other direction must be consumed before more - // receive-window credit is issued. Yield to WebSocket dispatch - // rather than blocking both ends on their send windows. - const bool received = receiveFromSocket(); + // A stream may need incoming bytes consumed before writes can + // proceed. Yield to WebSocket dispatch so bidirectional + // backpressure cannot block both ends indefinitely. + const bool received = receiveFromStream(); if (!isSendBufferEmpty()) { wakeUpFromPoll(SelectInterrupt::kSendRequest); @@ -1528,7 +1534,7 @@ namespace ix } else if (result == PollResultType::ReadyForWrite) { - if (!sendOnSocket()) + if (!sendOnStream()) { return false; } diff --git a/ixwebsocket/IXWebSocketTransport.h b/ixwebsocket/IXWebSocketTransport.h index 2b719c12..0c8ac607 100644 --- a/ixwebsocket/IXWebSocketTransport.h +++ b/ixwebsocket/IXWebSocketTransport.h @@ -113,6 +113,7 @@ namespace ix size_t closeWireSize = 0, bool remote = false); + // Historical name: closes the complete WebSocket byte stream. void closeSocket(); ReadyState getReadyState() const; @@ -213,8 +214,8 @@ namespace ix static constexpr size_t kChunkSize = 1 << 15; // Underlying TCP socket - std::unique_ptr _socket; - std::mutex _socketMutex; + std::unique_ptr _stream; + std::mutex _streamMutex; // Hold the state of the connection (OPEN, CLOSED, etc...) std::atomic _readyState; @@ -277,7 +278,7 @@ namespace ix void sendCloseFrame(uint16_t code, const std::string& reason); - void closeSocketAndSwitchToClosedState(uint16_t code, + void closeStreamAndSwitchToClosedState(uint16_t code, const std::string& reason, size_t closeWireSize, bool remote); @@ -286,8 +287,8 @@ namespace ix bool isAbnormalClose() const; bool flushSendBuffer(); - bool sendOnSocket(); - bool receiveFromSocket(); + bool sendOnStream(); + bool receiveFromStream(); WebSocketSendInfo sendData(wsheader_type::opcode_type type, const IXWebSocketSendData& message, diff --git a/test/IXHttp2Test.cpp b/test/IXHttp2Test.cpp index 0f1df975..5829c21d 100644 --- a/test/IXHttp2Test.cpp +++ b/test/IXHttp2Test.cpp @@ -3,9 +3,11 @@ #include #include #include +#include +#include #include -#include #include +#include namespace { @@ -177,7 +179,7 @@ TEST_CASE("HTTP2 handshake validates settings, response headers and frame orderi peer->incoming.back() = frame(1, 4, 1, ix::Hpack::encode({{":status", "200"}, {"content-length", "0"}})); } - ix::SocketHttp2 stream {std::unique_ptr(peer)}; + ix::Http2Connection stream {std::unique_ptr(peer)}; const auto result = stream.handshake(request, [] { return false; }); CHECK_FALSE(result.success); CHECK_FALSE(result.errorStr.empty()); @@ -189,7 +191,7 @@ TEST_CASE("HTTP2 preserves byte streams through fragmented reads and partial wri auto peer = new Peer; peer->partial = fragmented; peer->fragment = fragmented ? 1 : 16384; - ix::SocketHttp2 stream {std::unique_ptr(peer)}; + ix::Http2Connection stream {std::unique_ptr(peer)}; REQUIRE(stream.handshake(request, [] { return false; }).success); std::string body = "websocket bytes"; std::ptrdiff_t sent; @@ -288,7 +290,7 @@ TEST_CASE("HTTP2 validates stream control and receive windows", "[http2]") { const int failure = GENERATE(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); auto peer = new Peer; - ix::SocketHttp2 stream {std::unique_ptr(peer)}; + ix::Http2Connection stream {std::unique_ptr(peer)}; REQUIRE(stream.handshake(request, [] { return false; }).success); if (failure == 0) { @@ -342,7 +344,7 @@ TEST_CASE("HTTP2 supports continuation, extension frames and a remote half close const auto block = ix::Hpack::encode({{":status", "200"}, {"x-test", "present"}}); peer->incoming.back() = frame(1, 0, 1, block.substr(0, 1)); peer->incoming.push_back(frame(9, 4, 1, block.substr(1))); - ix::SocketHttp2 stream {std::unique_ptr(peer)}; + ix::Http2Connection stream {std::unique_ptr(peer)}; auto result = stream.handshake(request, [] { return false; }); REQUIRE(result.success); CHECK(result.headers["x-test"] == "present"); @@ -362,7 +364,7 @@ TEST_CASE("HTTP2 handles zero flow-control windows without losing bytes", "[http { auto peer = new Peer; peer->incoming.front() = frame(4, 0, 0, hex("000800000001000400000000")); - ix::SocketHttp2 stream {std::unique_ptr(peer)}; + ix::Http2Connection stream {std::unique_ptr(peer)}; REQUIRE(stream.handshake(request, [] { return false; }).success); std::string body = "payload"; CHECK(stream.send(&body[0], body.size()) == -1); @@ -377,7 +379,7 @@ TEST_CASE("HTTP2 handshake cancellation is bounded without sleeping", "[http2]") { auto peer = new Peer; peer->incoming.clear(); - ix::SocketHttp2 stream {std::unique_ptr(peer)}; + ix::Http2Connection stream {std::unique_ptr(peer)}; unsigned checks = 0; const auto result = stream.handshake(request, [&] { return ++checks > 30; }); CHECK_FALSE(result.success); @@ -391,7 +393,7 @@ TEST_CASE("HTTP2 unsuccessful CONNECT preserves the HTTP status and headers", "[ peer->incoming.back() = frame(1, 4, 1, ix::Hpack::encode({{":status", "403"}, {"x-error", "denied"}})) + frame(0, 1, 1, "error body"); - ix::SocketHttp2 stream {std::unique_ptr(peer)}; + ix::Http2Connection stream {std::unique_ptr(peer)}; const auto result = stream.handshake(request, [] { return false; }); CHECK_FALSE(result.success); CHECK(result.http_status == 403); @@ -414,7 +416,7 @@ TEST_CASE("HTTP2 enforces its receive window while an application is sending", " { auto peer = new Peer; peer->incoming.front() = frame(4, 0, 0, hex("000800000001000400000000")); - ix::SocketHttp2 stream {std::unique_ptr(peer)}; + ix::Http2Connection stream {std::unique_ptr(peer)}; REQUIRE(stream.handshake(request, [] { return false; }).success); for (unsigned i = 0; i < 4; ++i) { @@ -439,7 +441,7 @@ TEST_CASE("HTTP2 flushes partial control writes while its DATA window is blocked { auto peer = new Peer; peer->incoming.front() = frame(4, 0, 0, hex("000800000001000400000000")); - ix::SocketHttp2 stream {std::unique_ptr(peer)}; + ix::Http2Connection stream {std::unique_ptr(peer)}; REQUIRE(stream.handshake(request, [] { return false; }).success); peer->sent.clear(); peer->partial = true; @@ -459,7 +461,7 @@ TEST_CASE("HTTP2 exposes EOF while a send is blocked on flow control", "[http2]" { auto peer = new Peer; peer->incoming.front() = frame(4, 0, 0, hex("000800000001000400000000")); - ix::SocketHttp2 stream {std::unique_ptr(peer)}; + ix::Http2Connection stream {std::unique_ptr(peer)}; REQUIRE(stream.handshake(request, [] { return false; }).success); peer->incoming.push_back(frame(0, 1, 1, "")); stream.isReadyToWrite(0); @@ -467,3 +469,54 @@ TEST_CASE("HTTP2 exposes EOF while a send is blocked on flow control", "[http2]" char byte; CHECK(stream.recv(&byte, 1) == 0); } + +TEST_CASE("WebSocket stream implementations preserve I/O and own no socket descriptor", + "[http2][stream]") +{ + STATIC_REQUIRE_FALSE(std::is_base_of::value); + STATIC_REQUIRE_FALSE(std::is_base_of::value); + STATIC_REQUIRE_FALSE(std::is_base_of::value); + const bool http2 = GENERATE(false, true); + auto peer = new Peer; + std::unique_ptr stream; + if (http2) + { + std::unique_ptr connection( + new ix::Http2Connection(std::unique_ptr(peer))); + REQUIRE(connection->handshake(request, [] { return false; }).success); + stream.reset(new ix::Http2Stream(std::move(connection))); + } + else + { + peer->incoming.clear(); + stream.reset(new ix::SocketStream(std::unique_ptr(peer))); + } + peer->sent.clear(); + std::string body("hello\0world", 11); + REQUIRE(stream->send(&body[0], body.size()) == body.size()); + CHECK(peer->sent == (http2 ? frame(0, 0, 1, body) : body)); + peer->incoming.push_back(http2 ? frame(0, 0, 1, body) : body); + CHECK(stream->isReadyToRead(0) == ix::PollResultType::ReadyForRead); + char buffer[32]; + std::ptrdiff_t count; + do + { + count = stream->recv(buffer, sizeof(buffer)); + } while (count < 0 && ix::Socket::isWaitNeeded()); + REQUIRE(count == body.size()); + CHECK(std::string(buffer, static_cast(count)) == body); + CHECK(stream->isReadyToWrite(0) == ix::PollResultType::ReadyForWrite); + CHECK(stream->wakeUpFromPoll(ix::SelectInterrupt::kSendRequest)); + CHECK(stream->isWakeUpFromPollSupported() == peer->isWakeUpFromPollSupported()); + if (http2) + { + peer->sent.clear(); + stream->close(); + CHECK(peer->sent == frame(0, 1, 1, "")); + CHECK(stream->recv(buffer, sizeof(buffer)) == 0); + } + else + { + stream->close(); + } +} diff --git a/test/IXWebSocketDispatchTest.cpp b/test/IXWebSocketDispatchTest.cpp index c0c3dcb6..968f7101 100644 --- a/test/IXWebSocketDispatchTest.cpp +++ b/test/IXWebSocketDispatchTest.cpp @@ -338,7 +338,8 @@ namespace ix { static void install(WebSocketTransport& transport, std::unique_ptr socket) { - transport._socket = std::move(socket); + transport._stream = + std::unique_ptr(new ix::SocketStream(std::move(socket))); transport._useMask = false; transport.setReadyState(WebSocketTransport::ReadyState::OPEN); } diff --git a/test/IXWebSocketMessageLimitTest.cpp b/test/IXWebSocketMessageLimitTest.cpp index 7494853c..0b40a98b 100644 --- a/test/IXWebSocketMessageLimitTest.cpp +++ b/test/IXWebSocketMessageLimitTest.cpp @@ -17,7 +17,8 @@ namespace ix std::unique_ptr socket, bool compression) { - transport._socket = std::move(socket); + transport._stream = + std::unique_ptr(new ix::SocketStream(std::move(socket))); transport._useMask = false; if (compression) { diff --git a/test/IXWebSocketSendBufferTest.h b/test/IXWebSocketSendBufferTest.h index 87f8e4fb..fc707d7e 100644 --- a/test/IXWebSocketSendBufferTest.h +++ b/test/IXWebSocketSendBufferTest.h @@ -16,7 +16,8 @@ namespace ix { static void install(WebSocketTransport& transport, std::unique_ptr socket) { - transport._socket = std::move(socket); + transport._stream = + std::unique_ptr(new ix::SocketStream(std::move(socket))); transport.setReadyState(WebSocketTransport::ReadyState::OPEN); } @@ -28,7 +29,7 @@ namespace ix static bool flush(WebSocketTransport& transport) { - return transport.sendOnSocket(); + return transport.sendOnStream(); } static void reset(WebSocketTransport& transport) diff --git a/test/IXWebSocketSendFailureTest.cpp b/test/IXWebSocketSendFailureTest.cpp index c24ca784..ddc26517 100644 --- a/test/IXWebSocketSendFailureTest.cpp +++ b/test/IXWebSocketSendFailureTest.cpp @@ -21,7 +21,8 @@ namespace ix std::unique_ptr socket, bool blocking) { - transport._socket = std::move(socket); + transport._stream = + std::unique_ptr(new ix::SocketStream(std::move(socket))); transport._useMask = false; transport._blockingSend = blocking; transport._sendTimeoutSecs = 1; From 8f5cc11bed504732ce9d02afce75ba5bf8404f7a Mon Sep 17 00:00:00 2001 From: Benjamin Sergeant Date: Mon, 23 Nov 2026 17:01:24 -0800 Subject: [PATCH 7/7] Keep WebSocket dispatch running while stop initiates close --- ixwebsocket/IXWebSocket.cpp | 8 ++- ixwebsocket/IXWebSocket.h | 1 + ixwebsocket/IXWebSocketTransport.h | 1 + test/IXHttpWebSocketUpgradeTest.cpp | 80 +++++++++++++++++++++++++++++ 4 files changed, 85 insertions(+), 5 deletions(-) diff --git a/ixwebsocket/IXWebSocket.cpp b/ixwebsocket/IXWebSocket.cpp index 610134eb..224677ce 100644 --- a/ixwebsocket/IXWebSocket.cpp +++ b/ixwebsocket/IXWebSocket.cpp @@ -535,11 +535,9 @@ namespace ix break; } - // We can avoid to poll if we want to stop and are not closing - if (_stop && !isClosing()) - { - break; - } + // stop() sets _stop before starting close() to prevent reconnection. + // The connection may still be OPEN at this point. Keep polling and + // dispatching until CLOSED so its terminal callback is not skipped. // 2. Poll to see if there's any new data available WebSocketTransport::PollResult pollResult = _ws.poll(); diff --git a/ixwebsocket/IXWebSocket.h b/ixwebsocket/IXWebSocket.h index c1bcf237..6108f453 100644 --- a/ixwebsocket/IXWebSocket.h +++ b/ixwebsocket/IXWebSocket.h @@ -213,5 +213,6 @@ namespace ix bool _autoThreadName; friend class WebSocketServer; + friend struct WebSocketStopTestAccess; }; } // namespace ix diff --git a/ixwebsocket/IXWebSocketTransport.h b/ixwebsocket/IXWebSocketTransport.h index 0c8ac607..af3cb0e3 100644 --- a/ixwebsocket/IXWebSocketTransport.h +++ b/ixwebsocket/IXWebSocketTransport.h @@ -131,6 +131,7 @@ namespace ix private: friend struct WebSocketTransportTestAccess; + friend struct WebSocketStopTestAccess; std::string _url; Utf8Validator _utf8Validator; size_t _validatedBytes = 0; diff --git a/test/IXHttpWebSocketUpgradeTest.cpp b/test/IXHttpWebSocketUpgradeTest.cpp index c75d88c2..93a78f62 100644 --- a/test/IXHttpWebSocketUpgradeTest.cpp +++ b/test/IXHttpWebSocketUpgradeTest.cpp @@ -10,6 +10,22 @@ #include #include +namespace ix +{ + struct WebSocketStopTestAccess + { + static void runWithStopRequested(WebSocket& client, std::unique_ptr stream) + { + client._ws._stream = std::move(stream); + client._ws.setReadyState(WebSocketTransport::ReadyState::OPEN); + // The valid interleaving inside stop(): _stop is set before close() + // transitions OPEN to CLOSING. Run the worker at that exact point. + client._stop = true; + client.run(); + } + }; +} // namespace ix + namespace { class UpgradeServer final : public ix::SocketServer @@ -521,3 +537,67 @@ TEST_CASE("Closing cancels an HTTP-to-WebSocket handshake without reconnecting", CHECK(client.opens == 0); CHECK(server.connections() == 1); } + +TEST_CASE("A stop request cannot bypass terminal WebSocket dispatch", "[websocket][close]") +{ + class ClosingStream final : public ix::WebSocketStream + { + public: + unsigned polls = 0; + bool closed = false; + + std::ptrdiff_t send(char*, size_t count) override + { + return static_cast(count); + } + + std::ptrdiff_t recv(void*, size_t) override + { + return 0; + } + + ix::PollResultType isReadyToRead(int) override + { + ++polls; + return ix::PollResultType::CloseRequest; + } + + ix::PollResultType isReadyToWrite(int) override + { + return ix::PollResultType::ReadyForWrite; + } + + bool wakeUpFromPoll(uint64_t) override + { + return true; + } + + bool isWakeUpFromPollSupported() override + { + return true; + } + + void close() override + { + closed = true; + } + }; + + unsigned closes = 0; + ix::WebSocket client; + client.setOnMessageCallback( + [&](const ix::WebSocketMessagePtr& message) + { + if (message->type == ix::WebSocketMessageType::Close) + { + ++closes; + } + }); + auto stream = new ClosingStream; + ix::WebSocketStopTestAccess::runWithStopRequested(client, + std::unique_ptr(stream)); + CHECK(stream->polls == 1); + CHECK(stream->closed); + CHECK(client.getReadyState() == ix::ReadyState::Closed); + CHECK(closes == 1); +}