diff --git a/CMakeLists.txt b/CMakeLists.txt index afc7ca3ee9..d61f8f704e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -71,7 +71,7 @@ option(BUILD_PLUGIN_NOITOM_MOCAP "Build Noitom mocap plugin (downloads MocapApi option(BUILD_PLUGIN_OGLO "Build OGLO tactile glove plugin (BLE, Linux only; fetches SimpleBLE + nlohmann/json)" OFF) option(BUILD_PLUGIN_WUJI_GLOVE "Build Wuji glove plugin (requires the wuji_sdk C SDK)" OFF) option(BUILD_PLUGIN_SHARPA_AVATAR "Build Sharpa AvatarExo Glove plugin (Linux; skips if the Avatar SDK is missing)" OFF) -option(BUILD_PLUGIN_REMOTE_DEVICE_BRIDGE "Build the remote device bridge wire codec library (Teleop::remote_plugin_session)" ON) +option(BUILD_PLUGIN_REMOTE_DEVICE_BRIDGE "Build the remote device bridge wire codec and TCP/WebSocket transports (Teleop::remote_plugin_session; POSIX sockets, skipped on Windows)" ON) option(BUILD_EXAMPLES "Build examples" ON) option(BUILD_EXAMPLE_TELEOP_ROS2 "Build only the teleop_ros2 ROS 2 reference integration (e.g. for Docker)" OFF) option(BUILD_TESTING "Build unit tests" ON) diff --git a/src/plugins/remote_device_bridge/AGENTS.md b/src/plugins/remote_device_bridge/AGENTS.md index 12e70cd249..70b309a38d 100644 --- a/src/plugins/remote_device_bridge/AGENTS.md +++ b/src/plugins/remote_device_bridge/AGENTS.md @@ -7,7 +7,8 @@ SPDX-License-Identifier: Apache-2.0 **CRITICAL:** Complete the mandatory `AGENTS.md` preflight in [`../../../AGENTS.md`](../../../AGENTS.md) before editing here. -- `session/protocol_frame.*`, `session/protocol_payloads.*` and the `Reader`/`Writer` in `session/protocol_io.hpp` are the only serialization points. Every frame is encoded and decoded there and nowhere else; changing the wire format means changing them and their codec tests together. +- `session/protocol_frame.*`, `session/protocol_payloads.*` and the `Reader`/`Writer` in `session/protocol_io.hpp` are the only serialization points. Every frame is encoded and decoded there and nowhere else; changing the wire format means changing them and their codec tests together. Sessions hold an `ITransport` (`session/inc/remote_plugin_session/transport.hpp`) and only call `send/receive/shutdown` on complete frames; TCP framing lives in `TcpTransport`. - Wire format v1 (`kProtocolVersion` = 1, the only version number): 24-byte header `RPS0` magic, type u8, version u8, channel u16, seq u32, payload size u32, `t_send` i64; frame types 1..13 with no gaps; the hand byte is 0 = left, 1 = right in every payload; PING has no payload and PONG carries the PING's header `t_send` and the client's receive time. Any change to a header, payload or type number bumps `kProtocolVersion`; `decode_header` rejects other versions before reading the type, so old senders and bridges fail with a readable reason instead of mis-decoding. - A frame's `t_send` is its send time for clock exchange: call `stamp_header` where the frame is written to the transport, never when it is queued. +- WebSocket is a second transport, not a second protocol: `WebSocketTransport` carries exactly one wire frame per binary message (no TLS; terminate `wss://` in a proxy). Clients pick it with a `ws://host:port[/path]` address via `parse_remote`/`connect_transport`. A server serves it on its own port; never sniff the protocol on the TCP port. The server-side HTTP upgrade runs in the first `receive()` so an accept loop never blocks on a client. - Never add `OpenXR::openxr_loader`, `Teleop::plugin_utils` or DeviceIO session libraries to `Teleop::remote_plugin_session`: a plugin that talks to a bridge through this library must run without an OpenXR runtime. diff --git a/src/plugins/remote_device_bridge/CMakeLists.txt b/src/plugins/remote_device_bridge/CMakeLists.txt index f7c312b75a..daf8c7aa38 100644 --- a/src/plugins/remote_device_bridge/CMakeLists.txt +++ b/src/plugins/remote_device_bridge/CMakeLists.txt @@ -1,4 +1,9 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 +# The transports use POSIX sockets. +if(WIN32) + return() +endif() + add_subdirectory(session) diff --git a/src/plugins/remote_device_bridge/session/CMakeLists.txt b/src/plugins/remote_device_bridge/session/CMakeLists.txt index c2f76d671f..4a6542aab2 100644 --- a/src/plugins/remote_device_bridge/session/CMakeLists.txt +++ b/src/plugins/remote_device_bridge/session/CMakeLists.txt @@ -7,6 +7,15 @@ add_library(remote_plugin_session STATIC protocol_io.hpp inc/remote_plugin_session/protocol_frame.hpp inc/remote_plugin_session/protocol_payloads.hpp + remote_address.cpp + inc/remote_plugin_session/remote_address.hpp + tcp_socket.cpp + inc/remote_plugin_session/tcp_socket.hpp + tcp_transport.cpp + inc/remote_plugin_session/tcp_transport.hpp + inc/remote_plugin_session/transport.hpp + websocket_transport.cpp + inc/remote_plugin_session/websocket_transport.hpp ) target_include_directories(remote_plugin_session diff --git a/src/plugins/remote_device_bridge/session/inc/remote_plugin_session/remote_address.hpp b/src/plugins/remote_device_bridge/session/inc/remote_plugin_session/remote_address.hpp new file mode 100644 index 0000000000..a02ddbd54d --- /dev/null +++ b/src/plugins/remote_device_bridge/session/inc/remote_plugin_session/remote_address.hpp @@ -0,0 +1,35 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include "tcp_socket.hpp" +#include "transport.hpp" + +#include +#include +#include +#include +#include + +namespace remote_plugin_session +{ + +//! Parses "host[:port]" or "[v6-host][:port]"; a missing port falls back to default_port. Throws +//! std::invalid_argument. +Endpoint parse_endpoint(const std::string& text, uint16_t default_port); + +//! Where a client connects: plain "host[:port]" (TCP) or "ws://host[:port][/path]" (WebSocket). +struct RemoteAddress +{ + Endpoint endpoint; + std::optional ws_path; //!< set for ws:// +}; + +//! Throws std::invalid_argument; wss:// is refused (terminate TLS in a proxy in front of the bridge). +RemoteAddress parse_remote(const std::string& text, uint16_t default_port); +//! Connects (and for ws:// completes the upgrade) within `timeout`; throws std::runtime_error. +std::unique_ptr connect_transport(const RemoteAddress& remote, + std::chrono::milliseconds timeout = kConnectTimeout); + +} // namespace remote_plugin_session diff --git a/src/plugins/remote_device_bridge/session/inc/remote_plugin_session/tcp_socket.hpp b/src/plugins/remote_device_bridge/session/inc/remote_plugin_session/tcp_socket.hpp new file mode 100644 index 0000000000..d3c5cc3074 --- /dev/null +++ b/src/plugins/remote_device_bridge/session/inc/remote_plugin_session/tcp_socket.hpp @@ -0,0 +1,76 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include "transport.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace remote_plugin_session +{ + +struct Endpoint +{ + std::string host; + uint16_t port = 0; +}; + +//! Minimal RAII wrapper over a blocking POSIX TCP socket (IPv4/IPv6 via getaddrinfo). +class TcpSocket +{ +public: + TcpSocket() = default; + explicit TcpSocket(int fd); + ~TcpSocket(); + + TcpSocket(TcpSocket&& other) noexcept; + TcpSocket& operator=(TcpSocket&& other) noexcept; + TcpSocket(const TcpSocket&) = delete; + TcpSocket& operator=(const TcpSocket&) = delete; + + //! Throws std::runtime_error when no address connects within the timeout. + static TcpSocket connect(const Endpoint& endpoint, std::chrono::milliseconds timeout); + //! Throws std::runtime_error when bind/listen fails. Port 0 picks an ephemeral port. + static TcpSocket listen(const Endpoint& endpoint, int backlog); + //! Returns an invalid socket when the timeout expires; throws on a hard error. `peer`, when given, receives + //! the client's numeric host:port. + TcpSocket accept(std::chrono::milliseconds timeout, std::string* peer = nullptr); + + bool valid() const; + int fd() const; + uint16_t local_port() const; + + //! False when the peer closed or the send stalled past the socket send timeout. + bool send_all(const uint8_t* data, size_t size); + //! Timeout applies to the wait for the first byte; a stall mid-message reports Closed. + //! Ok, Timeout or Closed. + ReceiveResult recv_all(uint8_t* data, size_t size, std::chrono::milliseconds timeout); + + //! Unblocks recv/send on other threads; the descriptor stays open until close(). + void shutdown(); + void close(); + +private: + //! Numeric "host:port" of the connected peer; "?" when unavailable. + std::string peer_name() const; + + int m_fd = -1; +}; + +//! Accepts one connection on `listener` and wraps it in `Transport`; null when the poll expires. `peer`, when +//! given, receives the client's numeric host:port. +template +std::unique_ptr accept_transport(TcpSocket& listener, std::chrono::milliseconds poll, std::string* peer) +{ + TcpSocket client = listener.accept(poll, peer); + return client.valid() ? std::make_unique(std::move(client)) : nullptr; +} + +} // namespace remote_plugin_session diff --git a/src/plugins/remote_device_bridge/session/inc/remote_plugin_session/tcp_transport.hpp b/src/plugins/remote_device_bridge/session/inc/remote_plugin_session/tcp_transport.hpp new file mode 100644 index 0000000000..4f90fe411d --- /dev/null +++ b/src/plugins/remote_device_bridge/session/inc/remote_plugin_session/tcp_transport.hpp @@ -0,0 +1,39 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include "tcp_socket.hpp" +#include "transport.hpp" + +#include +#include +#include +#include +#include +#include + +namespace remote_plugin_session +{ + +//! ITransport over one TCP stream; messages are delimited by the wire header's payload_size. +class TcpTransport final : public ITransport +{ +public: + explicit TcpTransport(TcpSocket socket); + + //! One transport per connection accepted on `listener`; null when the poll expires. `peer`, when given, + //! receives the client's numeric host:port. + static std::unique_ptr accept(TcpSocket& listener, + std::chrono::milliseconds poll, + std::string* peer = nullptr); + + bool send(const uint8_t* frame, size_t size) override; + ReceiveResult receive(std::vector& frame, std::chrono::milliseconds timeout) override; + void shutdown() override; + +private: + TcpSocket m_socket; +}; + +} // namespace remote_plugin_session diff --git a/src/plugins/remote_device_bridge/session/inc/remote_plugin_session/transport.hpp b/src/plugins/remote_device_bridge/session/inc/remote_plugin_session/transport.hpp new file mode 100644 index 0000000000..fd8b4cf498 --- /dev/null +++ b/src/plugins/remote_device_bridge/session/inc/remote_plugin_session/transport.hpp @@ -0,0 +1,55 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include +#include +#include +#include + +namespace remote_plugin_session +{ + +//! Default connect/upgrade timeout for client transports. +constexpr std::chrono::milliseconds kConnectTimeout{ 3000 }; +//! A frame that has started arriving must finish within this window, or the peer counts as gone. +constexpr std::chrono::milliseconds kMidMessageStall{ 3000 }; + +enum class ReceiveResult +{ + Ok, + Timeout, + Closed, + Malformed, +}; + +/*! + * @brief Message transport between a RemotePluginSession and the bridge. + * + * A frame is one complete wire message (protocol kHeaderSize header + payload) + * as built by protocol::encode_frame. send() and receive() may run concurrently on two + * threads; shutdown() unblocks both. Framing (TCP is a stream) lives in the + * implementation, not in the callers. Framing checks only magic and size + * (protocol::frame_payload_size): version and type are the decoder's, so a peer + * on another protocol version is reported by split_frame with a readable reason. + */ +class ITransport +{ +public: + virtual ~ITransport() = default; + + //! False once the peer is gone or a send stalled past the transport's timeout. + virtual bool send(const uint8_t* frame, size_t size) = 0; + //! Timeout covers the wait for the first byte; Ok means `frame` holds exactly one complete message. + virtual ReceiveResult receive(std::vector& frame, std::chrono::milliseconds timeout) = 0; + virtual void shutdown() = 0; + //! Server side: finishes the transport's own handshake so send() works without waiting for a frame. Ok at once + //! when there is none (TCP). + virtual ReceiveResult wait_ready(std::chrono::milliseconds /*timeout*/) + { + return ReceiveResult::Ok; + } +}; + +} // namespace remote_plugin_session diff --git a/src/plugins/remote_device_bridge/session/inc/remote_plugin_session/websocket_transport.hpp b/src/plugins/remote_device_bridge/session/inc/remote_plugin_session/websocket_transport.hpp new file mode 100644 index 0000000000..0aa8925d3a --- /dev/null +++ b/src/plugins/remote_device_bridge/session/inc/remote_plugin_session/websocket_transport.hpp @@ -0,0 +1,72 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include "tcp_socket.hpp" +#include "transport.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace remote_plugin_session +{ + +/*! + * @brief RFC 6455 transport: each wire frame travels as one binary WebSocket message. No TLS, no extensions. + * + * The server role answers the HTTP upgrade inside its first receive(), so an accept loop never waits on a + * slow client; send() fails until the upgrade is done. Incoming fragments are reassembled, pings answered. + */ +class WebSocketTransport final : public ITransport +{ +public: + //! Server role over an accepted socket; no I/O until the first receive() or wait_ready(). + explicit WebSocketTransport(TcpSocket socket); + + //! Client role: sends the upgrade for `path` with `host_header` ("host:port") and throws + //! std::runtime_error unless the server answers 101. + WebSocketTransport(TcpSocket socket, + const std::string& host_header, + const std::string& path, + std::chrono::milliseconds timeout = kConnectTimeout); + + //! Like TcpTransport::accept; the upgrade happens on the first receive(). + static std::unique_ptr accept(TcpSocket& listener, + std::chrono::milliseconds poll, + std::string* peer = nullptr); + + bool send(const uint8_t* frame, size_t size) override; + ReceiveResult receive(std::vector& frame, std::chrono::milliseconds timeout) override; + void shutdown() override; + //! Server: answers the HTTP upgrade if receive() has not yet. + ReceiveResult wait_ready(std::chrono::milliseconds timeout) override; + +private: + enum class Role + { + Client, + Server, + }; + + WebSocketTransport(TcpSocket socket, Role role); + void client_upgrade(const std::string& host_header, const std::string& path, std::chrono::milliseconds timeout); + bool send_message(uint8_t opcode, const uint8_t* data, size_t size); + ReceiveResult accept_upgrade(std::chrono::milliseconds timeout); + + TcpSocket m_socket; + Role m_role; + std::atomic m_open{ false }; + std::mutex m_send_mutex; // receive() answers pings and closes concurrently with send() + std::vector m_send_buffer; + std::mt19937 m_mask_rng; +}; + +} // namespace remote_plugin_session diff --git a/src/plugins/remote_device_bridge/session/remote_address.cpp b/src/plugins/remote_device_bridge/session/remote_address.cpp new file mode 100644 index 0000000000..aefc49e827 --- /dev/null +++ b/src/plugins/remote_device_bridge/session/remote_address.cpp @@ -0,0 +1,113 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#include "inc/remote_plugin_session/remote_address.hpp" + +#include "inc/remote_plugin_session/tcp_transport.hpp" +#include "inc/remote_plugin_session/websocket_transport.hpp" + +#include +#include +#include +#include +#include +#include + +namespace remote_plugin_session +{ + +namespace +{ + +//! HTTP Host value: IPv6 literals need brackets before the port. +std::string host_header(const Endpoint& endpoint) +{ + const bool v6 = endpoint.host.find(':') != std::string::npos; + return (v6 ? "[" + endpoint.host + "]" : endpoint.host) + ":" + std::to_string(endpoint.port); +} + +} // namespace + +Endpoint parse_endpoint(const std::string& text, uint16_t default_port) +{ + Endpoint endpoint; + endpoint.port = default_port; + std::string port_text; + bool has_port = false; + if (!text.empty() && text.front() == '[') + { + // "[v6-address]" or "[v6-address]:port" + const size_t close = text.find(']'); + if (close == std::string::npos || (close + 1 < text.size() && text[close + 1] != ':')) + { + throw std::invalid_argument("invalid bracketed host in endpoint '" + text + "'"); + } + endpoint.host = text.substr(1, close - 1); + has_port = close + 1 < text.size(); + port_text = has_port ? text.substr(close + 2) : ""; + } + else if (std::count(text.begin(), text.end(), ':') > 1) + { + endpoint.host = text; // bare IPv6 address, no port + } + else + { + const size_t colon = text.find(':'); + endpoint.host = text.substr(0, colon); + has_port = colon != std::string::npos; + port_text = has_port ? text.substr(colon + 1) : ""; + } + if (has_port) + { + unsigned long port = 0; + const char* end = port_text.data() + port_text.size(); + const auto [stop, error] = std::from_chars(port_text.data(), end, port); + if (error != std::errc{} || stop != end || port == 0 || port > 65535) + { + throw std::invalid_argument("invalid port in endpoint '" + text + "'"); + } + endpoint.port = static_cast(port); + } + if (endpoint.host.empty()) + { + throw std::invalid_argument("missing host in endpoint '" + text + "'"); + } + return endpoint; +} + +RemoteAddress parse_remote(const std::string& text, uint16_t default_port) +{ + const std::string scheme = "ws://"; + if (text.starts_with("wss://")) + { + throw std::invalid_argument("wss:// is not supported ('" + text + "'); terminate TLS in a proxy, use ws://"); + } + RemoteAddress remote; + if (!text.starts_with(scheme)) + { + remote.endpoint = parse_endpoint(text, default_port); + return remote; + } + std::string authority = text.substr(scheme.size()); + const size_t slash = authority.find('/'); + remote.ws_path = slash == std::string::npos ? "/" : authority.substr(slash); + if (slash != std::string::npos) + { + authority.resize(slash); + } + remote.endpoint = parse_endpoint(authority, default_port); + return remote; +} + +std::unique_ptr connect_transport(const RemoteAddress& remote, std::chrono::milliseconds timeout) +{ + TcpSocket socket = TcpSocket::connect(remote.endpoint, timeout); + if (!remote.ws_path) + { + return std::make_unique(std::move(socket)); + } + return std::make_unique( + std::move(socket), host_header(remote.endpoint), *remote.ws_path, timeout); +} + +} // namespace remote_plugin_session diff --git a/src/plugins/remote_device_bridge/session/tcp_socket.cpp b/src/plugins/remote_device_bridge/session/tcp_socket.cpp new file mode 100644 index 0000000000..16e5c2a780 --- /dev/null +++ b/src/plugins/remote_device_bridge/session/tcp_socket.cpp @@ -0,0 +1,359 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#include "inc/remote_plugin_session/tcp_socket.hpp" + +#include "inc/remote_plugin_session/transport.hpp" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace remote_plugin_session +{ + +namespace +{ + +// A send may stall as long as the peer timeout tolerates silence; liveness is decided by the receive side. It +// is independent of kConnectTimeout and kMidMessageStall, which only share its value. +constexpr std::chrono::milliseconds kSendTimeout{ 3000 }; +// Best effort: the kernel clamps to its rmem/wmem maximum. +constexpr int kSocketBufferBytes = 4 * 1024 * 1024; + +std::string errno_string(const char* what) +{ + return std::string(what) + ": " + std::strerror(errno); +} + +void set_blocking(int fd, bool blocking) +{ + const int flags = fcntl(fd, F_GETFL, 0); + if (flags < 0) + { + throw std::runtime_error(errno_string("fcntl(F_GETFL)")); + } + const int updated = blocking ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK); + if (fcntl(fd, F_SETFL, updated) < 0) + { + throw std::runtime_error(errno_string("fcntl(F_SETFL)")); + } +} + +template +void set_option(int fd, int level, int name, const T& value, const char* what) +{ + if (setsockopt(fd, level, name, &value, sizeof(value)) < 0) + { + throw std::runtime_error(errno_string(what)); + } +} + +void configure_stream(int fd) +{ + set_option(fd, IPPROTO_TCP, TCP_NODELAY, 1, "setsockopt(TCP_NODELAY)"); + timeval send_timeout{}; + send_timeout.tv_sec = static_cast(kSendTimeout.count() / 1000); + send_timeout.tv_usec = static_cast((kSendTimeout.count() % 1000) * 1000); + set_option(fd, SOL_SOCKET, SO_SNDTIMEO, send_timeout, "setsockopt(SO_SNDTIMEO)"); + // Buffer sizes are a hint the kernel may clamp; a refusal is not an error. + setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &kSocketBufferBytes, sizeof(kSocketBufferBytes)); + setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &kSocketBufferBytes, sizeof(kSocketBufferBytes)); +} + +int poll_fd(int fd, short events, std::chrono::milliseconds timeout) +{ + pollfd pfd{}; + pfd.fd = fd; + pfd.events = events; + while (true) + { + const int result = ::poll(&pfd, 1, timeout.count() < 0 ? -1 : static_cast(timeout.count())); + if (result < 0 && errno == EINTR) + { + continue; + } + return result; + } +} + +using AddrInfoList = std::unique_ptr; + +AddrInfoList resolve(const Endpoint& endpoint, bool passive) +{ + addrinfo hints{}; + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags = passive ? (AI_PASSIVE | AI_NUMERICSERV) : AI_NUMERICSERV; + addrinfo* head = nullptr; + const std::string service = std::to_string(endpoint.port); + const int rc = getaddrinfo(endpoint.host.empty() ? nullptr : endpoint.host.c_str(), service.c_str(), &hints, &head); + if (rc != 0) + { + throw std::runtime_error("getaddrinfo(" + endpoint.host + "): " + gai_strerror(rc)); + } + return AddrInfoList(head, &freeaddrinfo); +} + +//! Non-blocking connect with a deadline. Throws std::runtime_error with the reason. +void try_connect(TcpSocket& socket, const addrinfo& ai, std::chrono::milliseconds timeout) +{ + set_blocking(socket.fd(), false); + const int rc = ::connect(socket.fd(), ai.ai_addr, ai.ai_addrlen); + if (rc < 0 && errno != EINPROGRESS) + { + throw std::runtime_error(errno_string("connect")); + } + if (rc < 0) + { + const int ready = poll_fd(socket.fd(), POLLOUT, timeout); + if (ready <= 0) + { + throw std::runtime_error(ready == 0 ? "connect timed out" : errno_string("poll")); + } + int so_error = 0; + socklen_t len = sizeof(so_error); + if (getsockopt(socket.fd(), SOL_SOCKET, SO_ERROR, &so_error, &len) < 0 || so_error != 0) + { + throw std::runtime_error(std::string("connect: ") + std::strerror(so_error != 0 ? so_error : errno)); + } + } + set_blocking(socket.fd(), true); + configure_stream(socket.fd()); +} + +//! Throws std::runtime_error with the reason. +void try_listen(TcpSocket& socket, const addrinfo& ai, int backlog) +{ + set_option(socket.fd(), SOL_SOCKET, SO_REUSEADDR, 1, "setsockopt(SO_REUSEADDR)"); + if (::bind(socket.fd(), ai.ai_addr, ai.ai_addrlen) < 0) + { + throw std::runtime_error(errno_string("bind")); + } + if (::listen(socket.fd(), backlog) < 0) + { + throw std::runtime_error(errno_string("listen")); + } +} + +//! Runs `attempt` on a fresh socket for each resolved address; the first that does not throw wins. `what` names +//! the caller. +template +TcpSocket for_each_address(const Endpoint& endpoint, bool passive, const char* what, Attempt attempt) +{ + const AddrInfoList addresses = resolve(endpoint, passive); + std::string errors; + + for (const addrinfo* ai = addresses.get(); ai != nullptr; ai = ai->ai_next) + { + try + { + const int fd = ::socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); + if (fd < 0) + { + throw std::runtime_error(errno_string("socket")); + } + TcpSocket socket(fd); + attempt(socket, *ai); + return socket; + } + catch (const std::runtime_error& e) + { + errors += errors.empty() ? e.what() : std::string("; ") + e.what(); + } + } + + throw std::runtime_error(std::string("TcpSocket::") + what + "(" + endpoint.host + ":" + + std::to_string(endpoint.port) + ") failed: " + (errors.empty() ? "no addresses" : errors)); +} + +} // namespace + +TcpSocket::TcpSocket(int fd) : m_fd(fd) +{ +} + +TcpSocket::~TcpSocket() +{ + close(); +} + +TcpSocket::TcpSocket(TcpSocket&& other) noexcept : m_fd(std::exchange(other.m_fd, -1)) +{ +} + +TcpSocket& TcpSocket::operator=(TcpSocket&& other) noexcept +{ + if (this != &other) + { + close(); + m_fd = std::exchange(other.m_fd, -1); + } + return *this; +} + +TcpSocket TcpSocket::connect(const Endpoint& endpoint, std::chrono::milliseconds timeout) +{ + return for_each_address(endpoint, false, "connect", + [timeout](TcpSocket& socket, const addrinfo& ai) { try_connect(socket, ai, timeout); }); +} + +TcpSocket TcpSocket::listen(const Endpoint& endpoint, int backlog) +{ + return for_each_address(endpoint, true, "listen", + [backlog](TcpSocket& socket, const addrinfo& ai) { try_listen(socket, ai, backlog); }); +} + +TcpSocket TcpSocket::accept(std::chrono::milliseconds timeout, std::string* peer) +{ + const int ready = poll_fd(m_fd, POLLIN, timeout); + if (ready == 0) + { + return TcpSocket(); + } + if (ready < 0) + { + throw std::runtime_error(errno_string("poll(accept)")); + } + const int fd = ::accept(m_fd, nullptr, nullptr); + if (fd < 0) + { + if (errno == ECONNABORTED || errno == EINTR) + { + return TcpSocket(); + } + throw std::runtime_error(errno_string("accept")); + } + TcpSocket client(fd); + configure_stream(fd); + if (peer != nullptr) + { + *peer = client.peer_name(); + } + return client; +} + +bool TcpSocket::valid() const +{ + return m_fd >= 0; +} + +int TcpSocket::fd() const +{ + return m_fd; +} + +uint16_t TcpSocket::local_port() const +{ + sockaddr_storage addr{}; + socklen_t len = sizeof(addr); + if (getsockname(m_fd, reinterpret_cast(&addr), &len) < 0) + { + throw std::runtime_error(errno_string("getsockname")); + } + if (addr.ss_family == AF_INET) + { + return ntohs(reinterpret_cast(&addr)->sin_port); + } + if (addr.ss_family == AF_INET6) + { + return ntohs(reinterpret_cast(&addr)->sin6_port); + } + throw std::runtime_error("getsockname: unsupported address family"); +} + +std::string TcpSocket::peer_name() const +{ + sockaddr_storage addr{}; + socklen_t len = sizeof(addr); + char host[NI_MAXHOST]; + char service[NI_MAXSERV]; + if (getpeername(m_fd, reinterpret_cast(&addr), &len) < 0 || + getnameinfo(reinterpret_cast(&addr), len, host, sizeof(host), service, sizeof(service), + NI_NUMERICHOST | NI_NUMERICSERV) != 0) + { + return "?"; + } + return std::string(host) + ":" + service; +} + +bool TcpSocket::send_all(const uint8_t* data, size_t size) +{ + size_t sent = 0; + while (sent < size) + { + const ssize_t n = ::send(m_fd, data + sent, size - sent, MSG_NOSIGNAL); + if (n < 0) + { + if (errno == EINTR) + { + continue; + } + return false; + } + sent += static_cast(n); + } + return true; +} + +ReceiveResult TcpSocket::recv_all(uint8_t* data, size_t size, std::chrono::milliseconds timeout) +{ + size_t received = 0; + while (received < size) + { + const int ready = poll_fd(m_fd, POLLIN, received == 0 ? timeout : kMidMessageStall); + if (ready == 0) + { + return received == 0 ? ReceiveResult::Timeout : ReceiveResult::Closed; + } + if (ready < 0) + { + return ReceiveResult::Closed; + } + const ssize_t n = ::recv(m_fd, data + received, size - received, 0); + if (n < 0) + { + if (errno == EINTR) + { + continue; + } + return ReceiveResult::Closed; + } + if (n == 0) + { + return ReceiveResult::Closed; + } + received += static_cast(n); + } + return ReceiveResult::Ok; +} + +void TcpSocket::shutdown() +{ + if (m_fd >= 0) + { + ::shutdown(m_fd, SHUT_RDWR); + } +} + +void TcpSocket::close() +{ + if (m_fd >= 0) + { + ::close(m_fd); + m_fd = -1; + } +} + +} // namespace remote_plugin_session diff --git a/src/plugins/remote_device_bridge/session/tcp_transport.cpp b/src/plugins/remote_device_bridge/session/tcp_transport.cpp new file mode 100644 index 0000000000..13772fb958 --- /dev/null +++ b/src/plugins/remote_device_bridge/session/tcp_transport.cpp @@ -0,0 +1,59 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#include "inc/remote_plugin_session/tcp_transport.hpp" + +#include "inc/remote_plugin_session/protocol_frame.hpp" + +#include + +namespace remote_plugin_session +{ + +namespace protocol = remote_plugin_protocol; + +TcpTransport::TcpTransport(TcpSocket socket) : m_socket(std::move(socket)) +{ +} + +bool TcpTransport::send(const uint8_t* frame, size_t size) +{ + return m_socket.send_all(frame, size); +} + +ReceiveResult TcpTransport::receive(std::vector& frame, std::chrono::milliseconds timeout) +{ + frame.resize(protocol::kHeaderSize); + if (const ReceiveResult header = m_socket.recv_all(frame.data(), protocol::kHeaderSize, timeout); + header != ReceiveResult::Ok) + { + return header; + } + + uint32_t payload_size = 0; + try + { + payload_size = protocol::frame_payload_size(frame); + } + catch (const protocol::DecodeError&) + { + return ReceiveResult::Malformed; + } + frame.resize(protocol::kHeaderSize + payload_size); + // A header without its payload within the stall window is a broken peer, not a quiet one. + return m_socket.recv_all(frame.data() + protocol::kHeaderSize, payload_size, kMidMessageStall) == ReceiveResult::Ok ? + ReceiveResult::Ok : + ReceiveResult::Closed; +} + +void TcpTransport::shutdown() +{ + m_socket.shutdown(); +} + +std::unique_ptr TcpTransport::accept(TcpSocket& listener, std::chrono::milliseconds poll, std::string* peer) +{ + return accept_transport(listener, poll, peer); +} + +} // namespace remote_plugin_session diff --git a/src/plugins/remote_device_bridge/session/websocket_transport.cpp b/src/plugins/remote_device_bridge/session/websocket_transport.cpp new file mode 100644 index 0000000000..50e860a3d3 --- /dev/null +++ b/src/plugins/remote_device_bridge/session/websocket_transport.cpp @@ -0,0 +1,451 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#include "inc/remote_plugin_session/websocket_transport.hpp" + +#include "inc/remote_plugin_session/protocol_frame.hpp" + +#include +#include +#include +#include +#include +#include + +namespace remote_plugin_session +{ + +namespace protocol = remote_plugin_protocol; + +namespace +{ + +constexpr size_t kMaxHttpHead = 8192; +constexpr uint64_t kMaxMessage = protocol::kHeaderSize + protocol::kMaxPayloadSize; +constexpr char kAcceptGuid[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + +constexpr uint8_t kFinBit = 0x80; +constexpr uint8_t kRsvBits = 0x70; +constexpr uint8_t kOpcodeMask = 0x0F; +constexpr uint8_t kControlBit = 0x08; +constexpr uint8_t kMaskBit = 0x80; +constexpr uint8_t kLengthMask = 0x7F; + +constexpr uint8_t kContinuation = 0x0; +constexpr uint8_t kBinary = 0x2; +constexpr uint8_t kClose = 0x8; +constexpr uint8_t kPing = 0x9; +constexpr uint8_t kPong = 0xA; + +std::array sha1(const std::string& text) +{ + std::array h{ 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0 }; + std::vector msg(text.begin(), text.end()); + const uint64_t bits = static_cast(msg.size()) * 8; + msg.push_back(0x80); + while (msg.size() % 64 != 56) + { + msg.push_back(0); + } + for (int i = 7; i >= 0; --i) + { + msg.push_back(static_cast(bits >> (i * 8))); + } + const auto rotl = [](uint32_t v, int n) { return (v << n) | (v >> (32 - n)); }; + for (size_t chunk = 0; chunk < msg.size(); chunk += 64) + { + std::array w{}; + for (size_t i = 0; i < 16; ++i) + { + const uint8_t* p = &msg[chunk + 4 * i]; + w[i] = (uint32_t{ p[0] } << 24) | (uint32_t{ p[1] } << 16) | (uint32_t{ p[2] } << 8) | p[3]; + } + for (size_t i = 16; i < 80; ++i) + { + w[i] = rotl(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1); + } + uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4]; + for (size_t i = 0; i < 80; ++i) + { + const uint32_t f = i < 20 ? (b & c) | (~b & d) : + (i < 40 || i >= 60) ? b ^ c ^ d : + (b & c) | (b & d) | (c & d); + const uint32_t k = i < 20 ? 0x5A827999 : i < 40 ? 0x6ED9EBA1 : i < 60 ? 0x8F1BBCDC : 0xCA62C1D6; + const uint32_t t = rotl(a, 5) + f + e + k + w[i]; + e = d; + d = c; + c = rotl(b, 30); + b = a; + a = t; + } + h[0] += a; + h[1] += b; + h[2] += c; + h[3] += d; + h[4] += e; + } + std::array digest{}; + for (size_t i = 0; i < digest.size(); ++i) + { + digest[i] = static_cast(h[i / 4] >> (24 - 8 * (i % 4))); + } + return digest; +} + +std::string base64(const uint8_t* data, size_t size) +{ + static constexpr char kAlphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + std::string out; + for (size_t i = 0; i < size; i += 3) + { + uint32_t n = uint32_t{ data[i] } << 16; + n |= i + 1 < size ? uint32_t{ data[i + 1] } << 8 : 0; + n |= i + 2 < size ? data[i + 2] : 0; + out += kAlphabet[(n >> 18) & 63]; + out += kAlphabet[(n >> 12) & 63]; + out += i + 1 < size ? kAlphabet[(n >> 6) & 63] : '='; + out += i + 2 < size ? kAlphabet[n & 63] : '='; + } + return out; +} + +std::string accept_key(const std::string& key) +{ + const std::array digest = sha1(key + kAcceptGuid); + return base64(digest.data(), digest.size()); +} + +std::string lower(std::string text) +{ + std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c) { return std::tolower(c); }); + return text; +} + +struct HttpHead +{ + std::string start_line; + std::map headers; //!< lowercase names, trimmed values +}; + +//! Reads up to the blank line one byte at a time so no WebSocket bytes that follow are consumed. +ReceiveResult read_http_head(TcpSocket& socket, std::chrono::milliseconds timeout, HttpHead& head) +{ + std::string text; + while (text.size() < 4 || text.compare(text.size() - 4, 4, "\r\n\r\n") != 0) + { + if (text.size() >= kMaxHttpHead) + { + return ReceiveResult::Malformed; + } + uint8_t byte = 0; + const ReceiveResult result = socket.recv_all(&byte, 1, text.empty() ? timeout : kMidMessageStall); + if (result != ReceiveResult::Ok) + { + return result == ReceiveResult::Timeout && text.empty() ? ReceiveResult::Timeout : ReceiveResult::Closed; + } + text.push_back(static_cast(byte)); + } + size_t begin = text.find("\r\n"); + head.start_line = text.substr(0, begin); + for (begin += 2; begin < text.size() - 2;) + { + const size_t end = text.find("\r\n", begin); + const std::string line = text.substr(begin, end - begin); + begin = end + 2; + const size_t colon = line.find(':'); + if (colon == std::string::npos) + { + return ReceiveResult::Malformed; + } + const size_t value = line.find_first_not_of(" \t", colon + 1); + head.headers[lower(line.substr(0, colon))] = + value == std::string::npos ? "" : line.substr(value, line.find_last_not_of(" \t") + 1 - value); + } + return ReceiveResult::Ok; +} + +std::string header(const HttpHead& head, const std::string& name) +{ + const auto it = head.headers.find(name); + return it == head.headers.end() ? "" : it->second; +} + +} // namespace + +WebSocketTransport::WebSocketTransport(TcpSocket socket, Role role) + : m_socket(std::move(socket)), m_role(role), m_mask_rng(std::random_device{}()) +{ +} + +WebSocketTransport::WebSocketTransport(TcpSocket socket) : WebSocketTransport(std::move(socket), Role::Server) +{ +} + +WebSocketTransport::WebSocketTransport(TcpSocket socket, + const std::string& host_header, + const std::string& path, + std::chrono::milliseconds timeout) + : WebSocketTransport(std::move(socket), Role::Client) +{ + client_upgrade(host_header, path, timeout); +} + +void WebSocketTransport::client_upgrade(const std::string& host_header, + const std::string& path, + std::chrono::milliseconds timeout) +{ + std::array nonce{}; + std::generate(nonce.begin(), nonce.end(), [this] { return static_cast(m_mask_rng()); }); + const std::string key = base64(nonce.data(), nonce.size()); + const std::string request = "GET " + path + " HTTP/1.1\r\nHost: " + host_header + + "\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: " + key + + "\r\nSec-WebSocket-Version: 13\r\n\r\n"; + const std::string target = host_header + path; + if (!m_socket.send_all(reinterpret_cast(request.data()), request.size())) + { + throw std::runtime_error("WebSocket upgrade to " + target + ": sending the request failed"); + } + HttpHead response; + switch (read_http_head(m_socket, timeout, response)) + { + case ReceiveResult::Ok: + break; + case ReceiveResult::Timeout: + throw std::runtime_error("WebSocket upgrade to " + target + ": no HTTP response within the timeout"); + case ReceiveResult::Closed: + throw std::runtime_error("WebSocket upgrade to " + target + ": connection closed before the response"); + case ReceiveResult::Malformed: + throw std::runtime_error("WebSocket upgrade to " + target + ": malformed HTTP response"); + } + if (!response.start_line.starts_with("HTTP/1.1 101")) + { + throw std::runtime_error("WebSocket upgrade to " + target + " refused: " + response.start_line); + } + if (header(response, "sec-websocket-accept") != accept_key(key)) + { + throw std::runtime_error("WebSocket upgrade to " + target + ": wrong Sec-WebSocket-Accept"); + } + m_open = true; +} + +std::unique_ptr WebSocketTransport::accept(TcpSocket& listener, + std::chrono::milliseconds poll, + std::string* peer) +{ + return accept_transport(listener, poll, peer); +} + +ReceiveResult WebSocketTransport::accept_upgrade(std::chrono::milliseconds timeout) +{ + HttpHead request; + const ReceiveResult result = read_http_head(m_socket, timeout, request); + if (result == ReceiveResult::Timeout || result == ReceiveResult::Closed) + { + return result; + } + const std::string key = header(request, "sec-websocket-key"); + if (result != ReceiveResult::Ok || !request.start_line.starts_with("GET ") || + lower(header(request, "upgrade")).find("websocket") == std::string::npos || + lower(header(request, "connection")).find("upgrade") == std::string::npos || + header(request, "sec-websocket-version") != "13" || key.empty()) + { + static const std::string kBadRequest = "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n"; + m_socket.send_all(reinterpret_cast(kBadRequest.data()), kBadRequest.size()); + m_socket.shutdown(); + return ReceiveResult::Malformed; + } + const std::string response = + "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: " + + accept_key(key) + "\r\n\r\n"; + if (!m_socket.send_all(reinterpret_cast(response.data()), response.size())) + { + return ReceiveResult::Closed; + } + m_open = true; + return ReceiveResult::Ok; +} + +bool WebSocketTransport::send(const uint8_t* frame, size_t size) +{ + return m_open.load() && send_message(kBinary, frame, size); +} + +bool WebSocketTransport::send_message(uint8_t opcode, const uint8_t* data, size_t size) +{ + std::lock_guard lock(m_send_mutex); + std::vector& out = m_send_buffer; + out.assign(1, static_cast(kFinBit | opcode)); // never fragmented on send + const uint8_t mask_bit = m_role == Role::Client ? kMaskBit : 0x00; + if (size < 126) + { + out.push_back(static_cast(mask_bit | size)); + } + else + { + const int length_bytes = size <= 0xFFFF ? 2 : 8; + out.push_back(static_cast(mask_bit | (length_bytes == 2 ? 126 : 127))); + for (int i = length_bytes - 1; i >= 0; --i) + { + out.push_back(static_cast(static_cast(size) >> (8 * i))); + } + } + const size_t payload_at = out.size() + (mask_bit ? 4 : 0); + if (mask_bit) + { + const uint32_t key = m_mask_rng(); + out.insert(out.end(), { static_cast(key >> 24), static_cast(key >> 16), + static_cast(key >> 8), static_cast(key) }); + } + out.insert(out.end(), data, data + size); + if (mask_bit) + { + for (size_t i = 0; i < size; ++i) + { + out[payload_at + i] ^= out[payload_at - 4 + i % 4]; + } + } + return m_socket.send_all(out.data(), out.size()); +} + +ReceiveResult WebSocketTransport::receive(std::vector& frame, std::chrono::milliseconds timeout) +{ + const auto deadline = std::chrono::steady_clock::now() + timeout; + if (!m_open.load()) + { + const ReceiveResult upgraded = accept_upgrade(timeout); + if (upgraded != ReceiveResult::Ok) + { + return upgraded; + } + } + frame.clear(); + bool in_message = false; + while (true) + { + // The caller's timeout covers the wait for a message to start (pings included); inside one, a stall is a drop. + const auto remaining = timeout.count() < 0 ? timeout : + std::max(std::chrono::milliseconds{ 0 }, + std::chrono::duration_cast( + deadline - std::chrono::steady_clock::now())); + uint8_t head[2]; + const ReceiveResult first = m_socket.recv_all(head, sizeof(head), in_message ? kMidMessageStall : remaining); + if (first != ReceiveResult::Ok) + { + return first == ReceiveResult::Timeout && !in_message ? ReceiveResult::Timeout : ReceiveResult::Closed; + } + const bool fin = (head[0] & kFinBit) != 0; + const uint8_t opcode = head[0] & kOpcodeMask; + const bool masked = (head[1] & kMaskBit) != 0; + const bool control = (opcode & kControlBit) != 0; + uint64_t length = head[1] & kLengthMask; + // RSV bits need an extension we never negotiate; clients must mask and servers must not. + if ((head[0] & kRsvBits) != 0 || masked != (m_role == Role::Server)) + { + return ReceiveResult::Malformed; + } + if (length >= 126) + { + std::array ext{}; + const size_t ext_size = length == 126 ? 2 : 8; + if (m_socket.recv_all(ext.data(), ext_size, kMidMessageStall) != ReceiveResult::Ok) + { + return ReceiveResult::Closed; + } + length = 0; + for (size_t i = 0; i < ext_size; ++i) + { + length = (length << 8) | ext[i]; + } + } + std::array mask{}; + if (masked && m_socket.recv_all(mask.data(), mask.size(), kMidMessageStall) != ReceiveResult::Ok) + { + return ReceiveResult::Closed; + } + + std::vector control_payload; + uint8_t* dest = nullptr; + if (control) + { + if (!fin || length > 125) + { + return ReceiveResult::Malformed; + } + control_payload.resize(length); + dest = control_payload.data(); + } + else + { + if (opcode != (in_message ? kContinuation : kBinary)) + { + return ReceiveResult::Malformed; // text frames, unknown opcodes, broken fragmentation + } + if (length > kMaxMessage - frame.size()) + { + return ReceiveResult::Malformed; + } + const size_t offset = frame.size(); + frame.resize(offset + length); + dest = frame.data() + offset; + } + if (length > 0 && m_socket.recv_all(dest, length, kMidMessageStall) != ReceiveResult::Ok) + { + return ReceiveResult::Closed; + } + for (size_t i = 0; masked && i < length; ++i) + { + dest[i] ^= mask[i % 4]; + } + + if (opcode == kPing) + { + if (!send_message(kPong, control_payload.data(), control_payload.size())) + { + return ReceiveResult::Closed; + } + continue; + } + if (opcode == kPong) + { + continue; + } + if (opcode == kClose) + { + // Echo the status code, then report the peer gone. + send_message(kClose, control_payload.data(), std::min(control_payload.size(), 2)); + return ReceiveResult::Closed; + } + if (control) + { + return ReceiveResult::Malformed; // reserved control opcode + } + in_message = !fin; + if (in_message) + { + continue; + } + try + { + return frame.size() >= protocol::kHeaderSize && + frame.size() == protocol::kHeaderSize + protocol::frame_payload_size(frame) ? + ReceiveResult::Ok : + ReceiveResult::Malformed; + } + catch (const protocol::DecodeError&) + { + return ReceiveResult::Malformed; + } + } +} + +void WebSocketTransport::shutdown() +{ + m_socket.shutdown(); +} + +ReceiveResult WebSocketTransport::wait_ready(std::chrono::milliseconds timeout) +{ + return m_open.load() ? ReceiveResult::Ok : accept_upgrade(timeout); +} + +} // namespace remote_plugin_session diff --git a/tests/cpp/plugins/remote_device_bridge/CMakeLists.txt b/tests/cpp/plugins/remote_device_bridge/CMakeLists.txt index fcac49524b..a513b47b05 100644 --- a/tests/cpp/plugins/remote_device_bridge/CMakeLists.txt +++ b/tests/cpp/plugins/remote_device_bridge/CMakeLists.txt @@ -1,12 +1,18 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 +find_package(Threads REQUIRED) + add_executable(remote_plugin_session_tests + test_remote_address.cpp + test_tcp_transport.cpp + test_websocket_transport.cpp test_wire_codec.cpp ) target_link_libraries(remote_plugin_session_tests PRIVATE Teleop::remote_plugin_session + Threads::Threads Catch2::Catch2WithMain ) diff --git a/tests/cpp/plugins/remote_device_bridge/test_remote_address.cpp b/tests/cpp/plugins/remote_device_bridge/test_remote_address.cpp new file mode 100644 index 0000000000..e6be1f3ad1 --- /dev/null +++ b/tests/cpp/plugins/remote_device_bridge/test_remote_address.cpp @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#include +#include + +#include + +using namespace remote_plugin_session; + +TEST_CASE("parse_remote selects TCP or WebSocket", "[remote_device_bridge][unit]") +{ + const RemoteAddress tcp = parse_remote("10.0.0.2:5000", 47500); + REQUIRE_FALSE(tcp.ws_path); + REQUIRE(tcp.endpoint.host == "10.0.0.2"); + REQUIRE(tcp.endpoint.port == 5000); + + const RemoteAddress ws = parse_remote("ws://bridge.local:8080/teleop", 47500); + REQUIRE(ws.ws_path); + REQUIRE(ws.endpoint.host == "bridge.local"); + REQUIRE(ws.endpoint.port == 8080); + REQUIRE(*ws.ws_path == "/teleop"); + + const RemoteAddress bare = parse_remote("ws://bridge.local", 47500); + REQUIRE(bare.endpoint.port == 47500); + REQUIRE(*bare.ws_path == "/"); + + REQUIRE_THROWS_AS(parse_remote("wss://bridge.local", 47500), std::invalid_argument); + REQUIRE_THROWS_AS(parse_remote("ws:///teleop", 47500), std::invalid_argument); +} + +TEST_CASE("parse_endpoint validates ports and accepts IPv6 hosts", "[remote_device_bridge][unit]") +{ + for (const char* bad : { "host:", "host:0", "host:70000", "host:80x", "[::1", "[::1]x" }) + { + INFO(bad); + REQUIRE_THROWS_AS(parse_endpoint(bad, 47500), std::invalid_argument); + } + const Endpoint bracketed = parse_endpoint("[::1]:8080", 47500); + REQUIRE(bracketed.host == "::1"); + REQUIRE(bracketed.port == 8080); + const Endpoint bare_v6 = parse_endpoint("fe80::1", 47500); + REQUIRE(bare_v6.host == "fe80::1"); + REQUIRE(bare_v6.port == 47500); + REQUIRE(parse_endpoint("[::1]", 47500).port == 47500); +} diff --git a/tests/cpp/plugins/remote_device_bridge/test_tcp_transport.cpp b/tests/cpp/plugins/remote_device_bridge/test_tcp_transport.cpp new file mode 100644 index 0000000000..d6c2a53b72 --- /dev/null +++ b/tests/cpp/plugins/remote_device_bridge/test_tcp_transport.cpp @@ -0,0 +1,97 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +using namespace remote_plugin_session; +namespace protocol = remote_plugin_protocol; + +namespace +{ + +constexpr std::chrono::milliseconds kWait{ 2000 }; +constexpr std::chrono::milliseconds kShort{ 300 }; + +std::pair socket_pair() +{ + int fds[2]; + REQUIRE(socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == 0); + return { TcpSocket(fds[0]), TcpSocket(fds[1]) }; +} + +//! A wire frame of exactly `message_size` bytes. +std::vector frame_of_size(size_t message_size) +{ + return protocol::encode_frame( + protocol::FrameType::SchemaSample, 3, std::vector(message_size - protocol::kHeaderSize, 0x5A)); +} + +void raw_send(TcpSocket& socket, const std::vector& bytes) +{ + REQUIRE(socket.send_all(bytes.data(), bytes.size())); +} + +} // namespace + +TEST_CASE("TcpTransport delimits frames by the header and reports broken peers", "[remote_device_bridge][unit]") +{ + auto [peer, transport_end] = socket_pair(); + TcpTransport transport(std::move(transport_end)); + std::vector frame; + + SECTION("a header-only frame arrives on its own") + { + const std::vector sent = protocol::encode_frame(protocol::FrameType::Heartbeat, 0, {}); + raw_send(peer, sent); + REQUIRE(transport.receive(frame, kWait) == ReceiveResult::Ok); + REQUIRE(frame == sent); + } + SECTION("a frame with a payload arrives whole") + { + const std::vector sent = frame_of_size(protocol::kHeaderSize + 100); + raw_send(peer, sent); + REQUIRE(transport.receive(frame, kWait) == ReceiveResult::Ok); + REQUIRE(frame == sent); + } + SECTION("nothing within the timeout") + { + REQUIRE(transport.receive(frame, kShort) == ReceiveResult::Timeout); + } + SECTION("a bad magic is malformed") + { + std::vector sent = protocol::encode_frame(protocol::FrameType::Heartbeat, 0, {}); + sent[0] ^= 0xFF; + raw_send(peer, sent); + REQUIRE(transport.receive(frame, kWait) == ReceiveResult::Malformed); + } + SECTION("a frame of another protocol version is delivered; the decoder names the version") + { + std::vector sent = frame_of_size(protocol::kHeaderSize + 8); + sent[protocol::kVersionOffset] = 0; + raw_send(peer, sent); + REQUIRE(transport.receive(frame, kWait) == ReceiveResult::Ok); + REQUIRE(frame == sent); + REQUIRE_THROWS_WITH( + protocol::split_frame(frame), Catch::Matchers::ContainsSubstring("peer speaks protocol version 0")); + } + SECTION("a header whose payload never arrives counts as closed") + { + const std::vector sent = frame_of_size(protocol::kHeaderSize + 100); + raw_send(peer, std::vector(sent.begin(), sent.begin() + protocol::kHeaderSize)); + REQUIRE(transport.receive(frame, kWait) == ReceiveResult::Closed); + } + SECTION("peer EOF is closed") + { + peer.shutdown(); + REQUIRE(transport.receive(frame, kWait) == ReceiveResult::Closed); + } +} diff --git a/tests/cpp/plugins/remote_device_bridge/test_websocket_transport.cpp b/tests/cpp/plugins/remote_device_bridge/test_websocket_transport.cpp new file mode 100644 index 0000000000..c8ddb3e225 --- /dev/null +++ b/tests/cpp/plugins/remote_device_bridge/test_websocket_transport.cpp @@ -0,0 +1,281 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +using namespace remote_plugin_session; +namespace protocol = remote_plugin_protocol; + +namespace +{ + +constexpr std::chrono::milliseconds kWait{ 2000 }; +constexpr std::chrono::milliseconds kShort{ 300 }; + +std::pair socket_pair() +{ + int fds[2]; + REQUIRE(socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == 0); + return { TcpSocket(fds[0]), TcpSocket(fds[1]) }; +} + +//! A wire frame whose WebSocket message (header + payload) is exactly `message_size` bytes. +std::vector frame_of_size(size_t message_size) +{ + std::vector payload(message_size - protocol::kHeaderSize); + for (size_t i = 0; i < payload.size(); ++i) + { + payload[i] = static_cast(i * 31 + 7); + } + return protocol::encode_frame(protocol::FrameType::SchemaSample, 3, payload); +} + +//! Hand-built client frame (masked, length < 65536) for driving the server role directly. +std::vector raw_frame(uint8_t opcode, bool fin, const std::vector& payload, bool masked = true) +{ + std::vector out{ static_cast((fin ? 0x80 : 0) | opcode) }; + const uint8_t mask_bit = masked ? 0x80 : 0; + if (payload.size() < 126) + { + out.push_back(static_cast(mask_bit | payload.size())); + } + else + { + out.insert(out.end(), { static_cast(mask_bit | 126), static_cast(payload.size() >> 8), + static_cast(payload.size()) }); + } + const uint8_t key[4] = { 0x12, 0x34, 0x56, 0x78 }; + if (masked) + { + out.insert(out.end(), key, key + 4); + } + for (size_t i = 0; i < payload.size(); ++i) + { + out.push_back(masked ? payload[i] ^ key[i % 4] : payload[i]); + } + return out; +} + +void raw_send(TcpSocket& socket, const std::string& text) +{ + REQUIRE(socket.send_all(reinterpret_cast(text.data()), text.size())); +} + +void raw_send(TcpSocket& socket, const std::vector& bytes) +{ + REQUIRE(socket.send_all(bytes.data(), bytes.size())); +} + +std::vector raw_recv(TcpSocket& socket, size_t size) +{ + std::vector bytes(size); + REQUIRE(socket.recv_all(bytes.data(), size, kWait) == ReceiveResult::Ok); + return bytes; +} + +//! Reads the server's HTTP response head byte by byte. +std::string raw_recv_head(TcpSocket& socket) +{ + std::string text; + while (text.size() < 4 || text.compare(text.size() - 4, 4, "\r\n\r\n") != 0) + { + text.push_back(static_cast(raw_recv(socket, 1)[0])); + } + return text; +} + +// RFC 6455 section 1.3 sample handshake. +const std::string kSampleUpgrade = + "GET /chat HTTP/1.1\r\nHost: server.example.com\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nOrigin: http://example.com\r\nSec-WebSocket-Version: 13\r\n\r\n"; + +//! A server transport upgraded by a raw client using the RFC sample key. +std::unique_ptr upgraded_server(TcpSocket server_end, TcpSocket& raw_client) +{ + auto server = std::make_unique(std::move(server_end)); + raw_send(raw_client, kSampleUpgrade); + REQUIRE(server->wait_ready(kWait) == ReceiveResult::Ok); + const std::string response = raw_recv_head(raw_client); + REQUIRE(response.rfind("HTTP/1.1 101", 0) == 0); + REQUIRE(response.find("Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n") != std::string::npos); + return server; +} + +struct Connected +{ + std::unique_ptr client; + std::unique_ptr server; +}; + +Connected connected_pair() +{ + auto [client_end, server_end] = socket_pair(); + Connected pair; + pair.server = std::make_unique(std::move(server_end)); + std::thread client([&] { pair.client = std::make_unique(std::move(client_end), "h:1", "/x"); }); + REQUIRE(pair.server->wait_ready(kWait) == ReceiveResult::Ok); + client.join(); + REQUIRE(pair.client); + return pair; +} + +} // namespace + +TEST_CASE("WebSocketTransport round-trips frames of every length class", "[remote_device_bridge][unit]") +{ + // 7-bit, 16-bit and 64-bit WebSocket lengths, both directions (client frames are masked). + const size_t message_size = GENERATE(size_t{ 25 }, 125, 126, 65535, 65536, 1024 * 1024); + Connected pair = connected_pair(); + const std::vector sent = frame_of_size(message_size); + + for (auto [from, to] : + { std::pair{ pair.client.get(), pair.server.get() }, std::pair{ pair.server.get(), pair.client.get() } }) + { + bool send_ok = false; + std::thread sender([&, from = from] { send_ok = from->send(sent.data(), sent.size()); }); + std::vector received; + REQUIRE(to->receive(received, kWait) == ReceiveResult::Ok); + sender.join(); + REQUIRE(send_ok); + REQUIRE(received == sent); + } +} + +TEST_CASE("WebSocketTransport server role handles control frames and fragments", "[remote_device_bridge][unit]") +{ + auto [raw, server_end] = socket_pair(); + auto server = upgraded_server(std::move(server_end), raw); + std::vector frame; + + SECTION("ping is answered with a pong carrying the same payload") + { + raw_send(raw, raw_frame(0x9, true, { 'h', 'i' })); + REQUIRE(server->receive(frame, kShort) == ReceiveResult::Timeout); + REQUIRE(raw_recv(raw, 4) == std::vector{ 0x8A, 0x02, 'h', 'i' }); + } + SECTION("a fragmented message with an interleaved ping is reassembled") + { + const std::vector sent = frame_of_size(300); + raw_send(raw, raw_frame(0x2, false, { sent.begin(), sent.begin() + 100 })); + raw_send(raw, raw_frame(0x9, true, {})); + raw_send(raw, raw_frame(0x0, true, { sent.begin() + 100, sent.end() })); + REQUIRE(server->receive(frame, kWait) == ReceiveResult::Ok); + REQUIRE(frame == sent); + REQUIRE(raw_recv(raw, 2) == std::vector{ 0x8A, 0x00 }); + } + SECTION("peer close is echoed and reported as closed") + { + raw_send(raw, raw_frame(0x8, true, { 0x03, 0xE8 })); + REQUIRE(server->receive(frame, kWait) == ReceiveResult::Closed); + REQUIRE(raw_recv(raw, 4) == std::vector{ 0x88, 0x02, 0x03, 0xE8 }); + } + SECTION("an unmasked client frame is malformed") + { + raw_send(raw, raw_frame(0x2, true, frame_of_size(protocol::kHeaderSize), false)); + REQUIRE(server->receive(frame, kWait) == ReceiveResult::Malformed); + } + SECTION("text frames are malformed") + { + raw_send(raw, raw_frame(0x1, true, { 'x' })); + REQUIRE(server->receive(frame, kWait) == ReceiveResult::Malformed); + } + SECTION("a message larger than a wire frame can be is malformed") + { + std::vector head{ 0x82, 0x80 | 127 }; // FIN + binary, masked, 64-bit length + const uint64_t length = protocol::kHeaderSize + protocol::kMaxPayloadSize + 1; + for (int i = 7; i >= 0; --i) + { + head.push_back(static_cast(length >> (8 * i))); + } + head.insert(head.end(), { 0x12, 0x34, 0x56, 0x78 }); + raw_send(raw, head); + REQUIRE(server->receive(frame, kWait) == ReceiveResult::Malformed); + } + SECTION("a reserved control opcode is malformed") + { + raw_send(raw, raw_frame(0xB, true, {})); + REQUIRE(server->receive(frame, kWait) == ReceiveResult::Malformed); + } + SECTION("a message that is not exactly one wire frame is malformed") + { + raw_send(raw, raw_frame(0x2, true, { 0x01 })); + REQUIRE(server->receive(frame, kWait) == ReceiveResult::Malformed); + } + SECTION("a frame of another protocol version is delivered; the decoder names the version") + { + std::vector sent = frame_of_size(protocol::kHeaderSize + 8); + sent[protocol::kVersionOffset] = 0; + raw_send(raw, raw_frame(0x2, true, sent)); + REQUIRE(server->receive(frame, kWait) == ReceiveResult::Ok); + REQUIRE(frame == sent); + } + SECTION("TCP EOF is reported as closed") + { + raw.shutdown(); + REQUIRE(server->receive(frame, kWait) == ReceiveResult::Closed); + } +} + +TEST_CASE("WebSocketTransport rejects bad handshakes", "[remote_device_bridge][unit]") +{ + auto [peer, own_end] = socket_pair(); + SECTION("server answers garbage with 400 and refuses to send") + { + WebSocketTransport server(std::move(own_end)); + raw_send(peer, "hello there\r\n\r\n"); + std::vector frame; + REQUIRE(server.receive(frame, kWait) == ReceiveResult::Malformed); + REQUIRE(raw_recv_head(peer).rfind("HTTP/1.1 400", 0) == 0); + const std::vector sent = frame_of_size(protocol::kHeaderSize); + REQUIRE_FALSE(server.send(sent.data(), sent.size())); + } + SECTION("client throws on a non-101 response") + { + raw_send(peer, "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); + REQUIRE_THROWS_AS(WebSocketTransport(std::move(own_end), "h:1", "/"), std::runtime_error); + } + SECTION("client throws on a wrong Sec-WebSocket-Accept") + { + raw_send(peer, + "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + "Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n"); + REQUIRE_THROWS_AS(WebSocketTransport(std::move(own_end), "h:1", "/"), std::runtime_error); + } +} + +TEST_CASE("connect_transport speaks ws:// to a listening WebSocketTransport", "[remote_device_bridge][unit]") +{ + TcpSocket listener = TcpSocket::listen(Endpoint{ "127.0.0.1", 0 }, 1); + const RemoteAddress remote = parse_remote("ws://127.0.0.1:" + std::to_string(listener.local_port()) + "/t", 1); + std::unique_ptr client; + std::thread connector([&] { client = connect_transport(remote, kWait); }); + std::unique_ptr server; + while (!server) + { + server = WebSocketTransport::accept(listener, kShort); + } + REQUIRE(server->wait_ready(kWait) == ReceiveResult::Ok); + connector.join(); + REQUIRE(client); + std::vector frame; + + const std::vector sent = frame_of_size(200); + REQUIRE(client->send(sent.data(), sent.size())); + REQUIRE(server->receive(frame, kWait) == ReceiveResult::Ok); + REQUIRE(frame == sent); + client->shutdown(); + REQUIRE(server->receive(frame, kWait) == ReceiveResult::Closed); +}