Commit Graph

1816 Commits

Author SHA1 Message Date
Marc-André Moreau c522935ad0 feat(vmconnect): add framebuffer redirection
Implement the private Hyper-V FBR dynamic channel for same-host
VMConnect sessions. Map the host-owned shared DIB and publish frames
through the client output path.

Add native current-user CredSSP and local instance-ID detection so the
agent and viewer can connect without handling a reusable host password.
Gate FBR to Windows loopback VMConnect sessions.
2026-08-21 22:51:28 -04:00
Marc-André Moreau 2cac77e444 feat(graphics): decode ClearCodec NSCodec (#1728)
Decode NSCodec layer-three regions into their ClearCodec destinations.

Validate NSCodec plane lengths and RLE output before converting and
blitting BGRA pixels.
2026-08-21 16:26:21 -04:00
Greg Lamberson ac7800c989 feat(server): expose session-lifetime baseline RTT to the embedder (#1737)
## Summary

- RttSnapshot.min_ms is a sliding-window low that can rise as low
samples
  age out of the window, and is explicitly documented as not baseRTT per
  MS-RDPBCGR 2.2.14.1.5, which defines baseRTT as the session-lifetime
  lowest. AutoDetectManager already tracks that true low internally as
  min_rtt_ms for the wire NetworkCharacteristicsResult, but nothing
  exposed it as its own value: an embedder reading snapshot() or
  autodetect_rtt_handle() alone cannot derive averageRTT - baseRTT as a
  queueing-delay signal, since that relationship only holds when the
  floor cannot rise.
- Adds AutoDetectManager::baseline_rtt_ms() as the public getter for the
  existing field, and mirrors the autodetect_rtt_handle plumbing on
  RdpServer: a new autodetect_baseline_rtt: Arc<AtomicU32> field,
  autodetect_baseline_rtt_handle() accessor, and
  with_autodetect_baseline_rtt_handle() builder method.
- A matched RTT sample always updates min_rtt_ms in the same
  handle_response call that returns it, so the store site reads the new
  getter unconditionally right after storing the RTT sample, with no
  before/after comparison needed (unlike the bandwidth case in #1734,
  where the underlying value can be cleared to None on an unusable
  measurement).
- Adds a manager-level test pinning the session-low-not-window-low
  property on the new getter directly, plus the usual pair of
  handle-plumbing tests (sentinel default, injected-handle round trip).

## Validation

`cargo xtask check fmt/lints/tests/typos/locks` all pass, including the
3 new tests.

## Notes

No public API break: `RdpServer::new` is crate-private, and the public
surface (`RdpServerBuilder`) only gains an additive optional field and a
new method.
2026-08-21 16:24:13 -04:00
Greg Lamberson 59be2d8e33 test(core): move DecodedFrame and AVC helper tests into testsuite-core (#1736)
ironrdp-egfx sets [lib] test = false commented out with a FIXME to turn
it back on once its tests move into the testsuite crates. Two of its
five inline test files test only public API and can move cleanly:
DecodedFrame's constructor and getters in decode.rs, and
Avc420Region/align_to_16/annex_b_to_avc/encode_avc420_bitmap_stream in
pdu/avc.rs. Moved both, verbatim apart from a couple of renamed test
functions: this directory's existing files split between a test_ prefix
(decode.rs, server.rs) and plain descriptive names (capabilities.rs,
client.rs), and the moved tests follow the latter.

DecodedFrame's tests go in a new, unconditional decoded_frame.rs: the
type itself needs no feature flag, unlike the existing decode.rs test
file which is gated on openh264-bundled for the OpenH264Decoder tests it
already covers.

The remaining three files (client.rs, server.rs, compositor.rs) test
private internals and stay inline; this does not change the crate's test
= false state, which is unrelated to this move and stays as it was.
2026-08-21 16:22:55 -04:00
Marc-André Moreau 77689c3439 feat(mstsgu): add RPC-over-HTTP request framing (#1727)
Add internal codecs for raw RPCH HTTP request and response framing.

They validate bounded request and response heads without enabling a live
RPC-over-HTTP gateway transport.
2026-08-21 16:22:03 -04:00
Marc-André Moreau 64375e78cc feat(client): resolve gateway credential sources (#1740)
Resolve UseServerCredentials from RDP account fields while preserving
explicit gateway credentials.

Qualify bare server usernames with the configured domain for gateway
authentication.

Reject unavailable credential sources instead of silently substituting
credentials.
2026-08-21 16:18:09 -04:00
cervigni d4b728a1d4 fix(pdu): accept a 6-byte Share Control Header (#1719)
MS-RDPBCGR 2.2.8.1.1.1.1 defines the Share Control Header as 6 bytes
(totalLength, pduType, pduSource); shareId belongs to the PDU bodies.
decode gates on FIXED_PART_SIZE (10), so a legal header-only PDU is
rejected before any field is read:
`ShareControlHeader::decode: not enough bytes provided to decode:
received 6 bytes, expected 10`

xrdp sends exactly such a Deactivate All PDU, which drops the session.
FreeRDP 3.30.0 accepts it against the same server (xrdp 0.10.1-4.1,
Ubuntu 26.04); ironrdp-pdu 0.9.0 does not.

[#1130](https://github.com/Devolutions/IronRDP/pull/1130) relaxed
ServerDeactivateAll::decode, but that runs after this gate — a 6-byte
buffer never reaches it. This is the outer half suggested in
[#314](https://github.com/Devolutions/IronRDP/issues/314) and never
submitted.

Change: gate on the real wire size (6) and read shareId only when 4
bytes remain. SHARE_CONTROL_HEADER_SIZE is untouched, so Encode is
unaffected.

Tests: 6-byte header decodes as ServerDeactivateAll with share_id == 0
(fails on master); 10-byte header still yields its real shareId.

Not built locally — CI is the first run of fmt/clippy/tests on this
branch. I did a local patch that worked for my workload, unfortunately
didn't have more cloud resources for running the cargo build for this

Addresses the ShareControlHeader gate reported in
[#314](https://github.com/Devolutions/IronRDP/issues/314).

Co-authored-by: Luca Cervigni <luca.cervigni@switch.ch>
2026-08-21 16:16:44 -04:00
Greg Lamberson 01075338e5 perf(egfx): allocate the ClearCodec decoder lazily on first use (#1738)
## Summary

- #1175 constructs ClearCodecDecoder eagerly in
GraphicsPipelineClient::new,
and its own PR body describes that as a deliberate choice: "Constructed
eagerly in GraphicsPipelineClient::new(), so V-bar (32K full + 16K short
  entries) and glyph (4000 entries) ring buffers are allocated up front
  regardless of whether ClearCodec frames are subsequently received."
  Revisiting that tradeoff for one case it does not fit well: the caches
are not lazy either (VBarCache::new and GlyphCache::new both resize_with
their full capacity), so every EGFX client session pays the full spine,
around 1.37 MiB on 64-bit and about half that on wasm32, whether or not
a single ClearCodec frame ever arrives, including against a server that
  never negotiates the codec at all. ironrdp-web instantiates one
  GraphicsPipelineClient per session, so this is a per-session wasm cost
  for a codec many sessions will never touch.
- Change clearcodec_decoder to Option<ClearCodecDecoder>, None at
  construction, built via get_or_insert_with on first dispatch to
decode_clearcodec. Same shape as the eager-BulkCompressor fix in #1255.
  Nothing observable changes: the cost just moves from construction time
  to first use.
- Does not touch the reset-graphics path, which already never resets
  clearcodec_decoder (dropping it there would drop the glyph cache and
  break a legitimate post-reset GLYPH_HIT unless the server redundantly
re-sent every glyph, per the existing comment on that code). The Option
wrapper does not change that behavior: decode still get_or_insert_with-s
  the same instance across resets once it exists.

## Validation

`cargo xtask check fmt/lints/tests/typos/locks` all pass, including the
existing ClearCodec coverage (dispatch, RGBA output,
glyph-cache-survives-
reset) unchanged.

## Notes

No public API break: clearcodec_decoder is a private field, and
GraphicsPipelineClient::new's signature is unchanged.
2026-08-21 16:14:40 -04:00
Greg Lamberson 6c27158fa8 test(extra): relocate config, rail, and input tests into testsuite-extra (#1756)
ironrdp-client sets `[lib] test = false`, so `config.rs`, `rail.rs`, and
`rdp.rs`'s inline `#[cfg(test)]` tests never run under `cargo test
--workspace`. This moves the nine tests that exercise only public API
into `ironrdp-testsuite-extra`:

- Eight `ConfigBuilder` tests (RemoteApp mode, monitor layout, sound and
audio-capture modes) into the existing `client_config.rs`, alongside a
new `complete_builder()` helper matching the original's.
- One `RailClient` input-sender test into a new `client_input.rs`.

A new `client_rail.rs` adds six more `RailClient` tests (handshake,
queued-execute release, desktop synchronization, client status flags)
that were also inline-only and untested under CI.

Enabling `ironrdp-client`'s `sound` feature on the `testsuite-extra`
dev-dependency lets the relocated audio-mode tests build without the
crate-level `#[cfg(feature = "sound")]` gates, which only made sense
inside `ironrdp-client` itself; the audio dependencies (`cpal`, `alsa`)
were already pulled in by `testsuite-extra`'s existing
`ironrdp-rdpsnd-native` dev-dependency, so this adds no new weight.

The remaining inline tests in `config.rs` (webauthn, the RemoteApp
Execute-queuing test touching the private `rail_initial_execute` field),
`rail.rs` (`queued_executes_do_not_exceed_pending_limit`, which reads
the private `MAX_PENDING_EXECUTES` const), and all of `rdp.rs` except
the one relocated test stay inline: each touches a private field,
private helper function, or private type with no public equivalent.
2026-08-21 16:11:38 -04:00
Greg Lamberson d59babe075 test(core): relocate autodetect's inline tests into testsuite-core (#1754)
ironrdp-server sets `[lib] test = false`, so `autodetect.rs`'s inline
`#[cfg(test)]` module never runs under `cargo test --workspace`. Six of
its ten tests duplicate coverage already present in
`ironrdp-testsuite-core/tests/server/autodetect.rs`, and a seventh
(`sequence_number_wraps`) checks the same wrap-around behavior the
existing `sequence_number_wraps_at_u16_max` already covers externally,
just via a direct write to the private `next_sequence` field instead of
the public API.

This moves the three tests with no external equivalent
(`backwards_clock_yields_a_zero_sample`,
`backwards_clock_keeps_the_probe_pending`,
`an_enormous_gap_clamps_to_u32_max`) into testsuite-core and deletes the
now-fully-redundant inline module. All ten tests' behavior is preserved:
three run under CI for the first time, seven were already covered by the
external suite.
2026-08-22 00:57:56 +09:00
Benoît Cortier 954fa5f46f chore(release): remove mstsgu unreleased entries (#1745)
Release-plz updates crate changelogs together in release PRs.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-08-22 00:45:21 +09:00
Marc-André Moreau 01aa50bedf feat(mstsgu): extract PacketIo from the WebSocket gateway client (#1717)
Move the HTTPS WebSocket transport, auth upgrade loop, and byte
read/write helpers out of lib.rs so handshake/tunnel/channel
sequencing stays separate from I/O.

GwClient write-side shutdown now closes the outbound sender and
inbound receiver, then waits for the worker so a local EOF can
finish even if inbound delivery is blocked. Local shutdown still
does not send HTTP_CLOSE_PACKET; inbound channel-close handling
from master is preserved.

This does not include dual-HTTP, RPCH, proxies, or certificate
policy APIs.
2026-08-21 09:10:24 +00:00
Marc-André Moreau ac7faecb33 feat(agent): forward TCP through an RD Gateway tunnel (#1714)
Forward TCP through an RD Gateway without an RDP session.

MS-TSGU is not RDP-specific. ironrdp-agent gw-forward exposes an SSH
-L-style local port forward or a SOCKS5 CONNECT proxy, opening one
WebSocket gateway tunnel per inbound connection with
GwClient::connect_with_port.

Master GwClient is WebSocket and HTTP Basic only, so this slice does not
add an RPC transport.

Local-to-gateway copies are capped at 8182 bytes so each write fits in
the 8192-byte MS-TSGU data packet. SOCKS5 carries explicit RFC 1928
reply codes, rejects a non-zero reserved byte, and does not send a
CONNECT reply after a method-negotiation failure. --socks5 and --target
are exclusive, and --target is parsed with TargetAddr so IPv6 requires
an explicit port and is passed to the gateway unbracketed.
GwClient::poll_shutdown is a no-op on master, so a local half-close is
not forwarded to the target.
2026-08-21 17:40:07 +09:00
Marc-André Moreau 70a4239777 feat(replay): unwrap RD Gateway RPC-over-HTTP tunnels (#1724)
Direct TCP replay cannot recover RDP from a legacy RD Gateway capture
because the inner stream is split across RPC_IN_DATA and RPC_OUT_DATA
HTTP channels and wrapped in DCE/RPC TsProxy stubs.

After the outer HTTPS sessions are already decrypted from the capture's
embedded key log, pair those channels, unwrap the RPC-over-HTTP tunnel
into a normal RDP stream, and continue the existing replay pipeline.

A single IN or OUT channel is not a complete tunnel. External key-log
files and resumed TLS decrypt remain out of scope.
2026-08-21 17:36:47 +09:00
Marc-André Moreau 438b177645 feat(mstsgu): add DCE/RPC fragment codecs (#1725)
Master ironrdp-mstsgu is WebSocket + HTTP Negotiate/NTLM/Basic and has
no DCE/RPC types. Add the common-header / fragmentation foundation used
by a later RPC-over-HTTP transport: PDU errors, syntax version, fragment
sizes, common header, stream framer, response reassembly, and fault
parse.

This does not add TsProxy NDR, RTS, NTLM packet integrity, or a live
RPCH client.
2026-08-21 17:18:48 +09:00
Marc-André Moreau 493c894a04 feat(replay): decrypt TLS captures from key logs (#1729)
Accept externally supplied NSS-compatible TLS key logs for capture
replay,
including gateway-unwrapped TLS sessions.

Preserve key material in memory only and report missing tunneled secrets
with a direct remedy.
2026-08-20 22:24:39 -04:00
Marynych Oleksandr 8b1f0dab08 fix(server): release the static channels when a connection ends (#1721)
`run_connection` leaves the connection's static channels attached to the
server. `run` clears them right after each session, so servers driven by
it
are unaffected — but the channel set is per-connection state, and
`run_connection` is the public entry point for embedders that run their
own
accept loop. There is no public API to clear it from outside.

Channel backends own real resources, and several are released through
`Drop`:
`RdpsndServer::drop` stops its handler, which is how an audio backend
learns
to stop capturing. Held past the connection, they keep running with no
client
to serve, and their events accumulate in the server event queue until
the
next client attaches new channels.

Measured on hypr-rdp, a Wayland RDP server that accepts through
`run_connection` so it can answer concurrent connections instead of
leaving
them in the backlog. After the client was killed:

| | audio capture | virtual sink | RSS over 50 s |
|---|---|---|---|
| `run()` | stopped | removed | flat |
| `run_connection()` | still running | still the default output | +176
KB/s |

176 KB/s is exactly 44100 Hz x 2ch x 16-bit — the capture thread still
recording into the queue.

The reset moves into `run_connection_with` so it covers every exit path,
including the early returns, and the now-redundant one in `run` is
dropped.
The doc comment above the same function already explains why
per-connection
state has to be handled here rather than by the caller.

Test: `run_connection_releases_the_static_channels` inserts a channel
that
flags its own drop, ends a connection at EOF, and asserts the flag. It
fails
without the change.
2026-08-20 18:53:22 -04:00
Marc-André Moreau e583e3a1bb feat(mstsgu): decode HTTP service, reauth, and channel-close packets (#1723)
PktTy already named ChannelClose, ServiceMessage, and ReauthMessage
without decoding those payloads.

Add encode/decode for HTTP_SERVICE_MESSAGE, HTTP_REAUTH_MESSAGE, and
HTTP_CLOSE_PACKET, plus common MS-TSGU HRESULT display names. The work
loop logs service and reauth packets. A server channel-close is answered
with PKT_TYPE_CLOSE_CHANNEL_RESPONSE, then the work task ends.
Mid-session reauthentication is not performed.
2026-08-20 15:14:52 -04:00
Marc-André Moreau 3464d75610 feat(replay): unwrap RD Gateway WebSocket tunnels (#1716)
Direct TCP replay cannot recover RDP from an RD Gateway capture because
the inner stream is wrapped in WebSocket frames and HTTP_DATA_PACKET
headers.

After the outer HTTPS session is already decrypted from the capture's
embedded key log, unwrap RDG_OUT_DATA tunnels into a normal RDP stream
and continue the existing replay pipeline.

RPC-over-HTTP tunnels, external key-log files, and resumed TLS decrypt
are out of scope.
2026-08-20 13:08:15 -04:00
Marc-André Moreau 5c6a28d2a5 feat(mstsgu): add RDG-UDP PDU codecs (#1718)
Encode and decode MS-TSGU UDP framing (CONNECT_PKT, DATA_PKT, DISC_PKT,
and UDP_CORRELATION_INFO) plus HTTP_CHANNEL_RESPONSE UDP offer metadata.

A live DTLS side channel is not opened; these helpers only cover the
packet layouts in [MS-TSGU] 2.2.5.4 and 2.2.11.
2026-08-20 13:06:46 -04:00
Marc-André Moreau a67dbf47e4 feat(client): try a direct connection before the RD Gateway (#1713)
GatewayUsageMethod::Detect selected the RD Gateway as soon as a hostname
was present, so a reachable desktop still went through MS-TSGU.

Keep Detect on gateway transport when a hostname is set, but mark it
prefer_direct so the client tries a direct RDP connection first and
falls back to the gateway only after that attempt fails. UseAlways and
explicit CLI or ActiveX gateway selection still skip the direct attempt.
Cancellation still aborts both legs.

Side effects: TransportKind::Gateway and GatewayConfig gain a
prefer_direct field. Detect rustdoc in ironrdp-cfg now describes the
two-step fallback. connect_preferring_direct is a hidden test hook for
that orchestration.
2026-08-20 12:27:19 -04:00
Marc-André Moreau 476b897129 feat(mstsgu): add Negotiate and NTLM HTTP gateway auth (#1715)
Corporate RD Gateways typically challenge with Negotiate or NTLM rather
than Basic, so the WebSocket-only client could not complete the upgrade.

The first upgrade request omits Authorization. On 401, WWW-Authenticate
is parsed as an HTTP challenge list and Negotiate is preferred (Kerberos
then NTLM inside SPNEGO via sspi network_client), then NTLM, then HTTP
Basic. SSPI and KDC resolution run on spawn_blocking. A 101 may complete
SSPI from a final GSS token when present. connect and connect_with_port
signatures are unchanged.

sspi 0.21 is an implementation-only dependency. HTTP auth tests live in
tests/http_auth.rs so [lib] test = false can stay. xtask runs that
target with native-tls. RPCH, UDP, reauth, Detect, extended-auth packet
exchange, and TLS channel bindings remain out of scope.
2026-08-19 22:55:40 -04:00
Greg Lamberson 185f312019 fix(server): weigh RemoteFX ICAP entropy coders instead of taking the last (#1686)
The client's advertised TS_RFX_ICAP array was folded with a plain
assignment in the capability exchange loop, so whichever entry happened
to be parsed last silently decided the entropy coder. Add
pick_remotefx_entropy_coder and
RdpServerBuilder::with_remotefx_entropy_coder so the caller can state a
preferred coder, with a documented fallback instead of an accidental
one.

Per MS-RDPRFX 2.2.1.1.1.1, the TS_RFX_ICAP array is the set of codecs
the client supports, not a ranked preference, so the server is entitled
to pick any entry. With no preference configured, the new fallback is
whichever coder the client offers first, which is deterministic and
matches the array's natural order, instead of whichever happened to be
parsed last. mstsc sends RLGR1 then RLGR3, so today's last-wins behavior
always lands on RLGR3, and RLGR1 never runs against a real client.

Builds on #1684 and #1685, which give the quant table (#1557) the same
server-side shape. Default behavior changes for clients that offer both
coders: the server now uses the first-offered coder instead of the
last-offered one, unless with_remotefx_entropy_coder states otherwise.

Closes #1562.
2026-08-19 20:57:58 -04:00
Greg Lamberson 36a848e085 fix(connector)!: count the auto-detect header, and only answer connect-time (#1559)
## Summary

- The Network Characteristics Byte Count store was incremented by the
payload length alone, so every counted Bandwidth Measure message was
reported 8 bytes short.
- [MS-RDPBCGR] 3.2.5.14 says to increment it "by the value specified in
the **payloadLength** field plus the size of the header fields (8
bytes)", on each Bandwidth Measure Payload and on the 0x002B Stop.
2.2.14.1.3 pins that 8 by requiring `headerLength` to be 0x08.
- The Start and Stop arms now check the request type rather than
matching every variant.

## Those two increments are the whole of the connect-time byte count

Worth stating, because 3.2.5.14 also contains a rule that counts every
byte received while a window is open, and it's easy to assume it applies
here.

It doesn't. That rule belongs to the 0x0014 and 0x0114 Starts, which are
the reliable and lossy UDP variants. Connect-time is 0x1014, and its
step list says only to clear the stores and start the timer. So on this
path the Payload and Stop increments are the entire count, and no
framing-layer accumulation is needed.

## Why the request-type check is required, not tidying

2.2.14.1.4 sets `headerLength` to 0x08 for the 0x002B Stop and 0x06
otherwise. A fixed 8-byte addend is therefore only correct once the type
is known, which makes the check part of the byte-count fix rather than
separate from it.

It has two further effects that are worth having. A continuous-detection
Start no longer opens a connect-time window, and a continuous Stop is no
longer answered with a connect-time result on the main channel when
3.2.5.14 routes those to a multitransport channel under a different
procedure. That procedure also requires a sequence-number correlation on
the 0x0629 Stop which this phase does not track, so ignoring is the
conservative response.

This overlaps the automated reviewer's fifth finding on #1530, which
suggested exactly this narrowing. I'd offered there to fold it into that
PR or take it separately; the conditional header size settled it, since
the byte count is wrong without it.

## This is deliberately not FreeRDP's arithmetic

FreeRDP counts the whole PDU length at the framing layer,
`bandwidthMeasureByteCount += length` in `libfreerdp/core/rdp.c` after
`rdp_read_header`, for any window including connect-time, and then adds
`payloadLength` again in `libfreerdp/core/autodetect.c` for the Payload
and the Stop. On the connect-time path that counts the payload twice and
adds framing bytes the spec doesn't ask for.

I went with the spec rather than the reference here. The reported figure
is an informational QoS hint and the server proceeds on receipt either
way, so there's no interop cost to being correct. The divergence is
called out in a comment at the helper so nobody later "fixes" it toward
FreeRDP.

## Depends on #1530

Stacked. #1530 introduces the bandwidth window state
(`connect_time_bw_started_at`, `connect_time_bw_bytes`) that this counts
into; on master there's nothing to accumulate. The branch carries
#1530's commits, so it builds and tests on its own, and the merge order
is #1530 then this.

Because it carries them, the diff shown here is cumulative. This pull
request's own change is 3 files, +180/-21:
`crates/ironrdp-connector/src/connection.rs`,
`crates/ironrdp-connector/src/lib.rs` and one connector test. The size
label is computed on the cumulative diff, so it counts #1530's four
commits too.

Raised by the automated reviewer on #1530, where the prescribed fix is
the arithmetic used here.

## The reported byte count is measurement-gated

Worth stating for consumers, because it is a deliberate deviation.
3.2.5.14 states the Bandwidth Measure Payload increment unconditionally.
Here the Payload bytes are accumulated only while a window is open,
which means a driver that reports no arrival times never counts them and
its Results carry the Stop's own payload alone against the untimed
floor.

A full count paired with a `timeDelta` the client never measured yields
a bandwidth figure that grows with whatever the server chose to send, so
this under-reports rather than over-reports. The practical consequence
is that a server acting on 3.3.5.14 will pick conservative
bandwidth-dependent settings for such a client. Of the drivers in tree
only the FFI connector is in that position.

## Breaking changes

Two, both in `ironrdp-connector`, and `cargo semver-checks -p
ironrdp-connector --baseline-rev master` reports exactly these two and
nothing else:

- `Sequence::step` takes a third parameter, `received_at:
Option<MonotonicInstant>`. This breaks every external implementor and
every caller of the trait. `step_no_input` keeps its signature and
passes `None`.
- `ClientConnector` gains two private fields,
`connect_time_bw_started_at` and `connect_time_bw_bytes`, so the struct
is no longer constructible by literal downstream.

The clock stays in the driver because a sequence must not read one,
which is what keeps the sans-I/O invariant intact. A defaulted trait
method would avoid the signature break but would let an implementor
override only the old entry point and silently never receive an arrival
time, so the required parameter is the safer of the two.

## Validation

- `cargo xtask check fmt/lints/tests/typos/locks` all pass on the pinned
toolchain, plus `cargo xtask wasm check`, with `fuzz/` built before the
lock check.
- Four existing expectations move by exactly 8 per counted message: 3584
to 3608 (two Payloads and a Stop), 512 to 520 (one Stop), and two at
1536 to 1552 (a Payload and a Stop each), the second of which is the
window-reset test #1530 added after this branch was first filed. A
fifth, 4096 to 4104, went with the redundant test #1530 dropped in
review.
- Two tests added for the guards: continuous Start, Payload and Stop
produce no reply and leave the phase running; and a connect-time Stop
arriving after a continuous Start reports the untimed floor against its
own payload alone, since the continuous Start opened no window.
- Eleven connect-time auto-detect tests pass.
2026-08-19 20:57:27 -04:00
Marc-André Moreau f43966cade fix(mstsgu): forward the target host and port to the gateway (#1710)
The channel-create packet (HTTP_CHANNEL_PACKET) hardcoded port 3389, so
non-3389 RDP targets and Hyper-V VMConnect (port 2179) could not be
tunneled through an RD Gateway.

GwClient::connect still presents port 3389 so existing GwConnectTarget
struct literals keep compiling. GwClient::connect_with_port carries
Config::destination.port() through HTTP_CHANNEL_PACKET. The
vmconnect-over-gateway rejections are removed, and connect_gateway now
runs the VMConnect PCB / connect_front handshake on the tunneled stream
when a VM ID is set.
2026-08-19 20:54:14 -04:00
clintcan 04320a0ce1 test(core): add a rdpeusb (URBDRC) decode fuzz target (#1690)
## Summary

`ironrdp-rdpeusb` has no fuzz coverage, even though it decodes
attacker-controlled **client→server** PDUs off two DVC channels. The
device
channel in particular carries URB completions, IO-control completions
and
interface-info results whose **length-prefixed payloads must be
bounds-checked
before they're read** — historically a good place for unchecked-read
panics.
(A downstream server built on `ironrdp-server`,
[macrdp](https://github.com/clintcan/macrdp),
hit exactly that class of panic in these decoders in the past, which is
what
motivated adding coverage here.)

This adds a fuzz target for the two top-level client PDU families a
server
decodes off the wire.

## What's added

- **Oracle** `oracles::rdpeusb_decode` — decodes the two client→server
entry
  points via `ironrdp_core::decode`:
  - `UrbdrcClientControlPdu` (main-channel family)
- `UrbdrcClientDevicePdu<Raw>` (per-device family — recursively
exercises the
    URB / IO-control / interface-info result payloads)
- **Fuzz target** `fuzz/fuzz_targets/rdpeusb_decode.rs` (auto-discovered
by
`cargo xtask fuzz list`, so it joins the CI matrix with no further
wiring).
- **Regression check** `check_rdpeusb_decode` in `fuzz_regression.rs`,
plus the
`rdpeusb_decode/` corpus folder, so any crash found becomes a permanent
  replay test.

## Verification

- `cargo build -p ironrdp-fuzzing` — the oracle compiles against the
real API.
- `cargo test -p ironrdp-testsuite-core check_rdpeusb_decode` — passes.
- `cargo fmt --all -- --check` (stable + nightly) clean; `cargo clippy
-p ironrdp-fuzzing` clean.
- `cargo xtask fuzz list` lists `rdpeusb_decode`.

Purely additive (a new oracle, target, regression check + the
`ironrdp-rdpeusb`
dev-dependency of `ironrdp-fuzzing`); no existing code changes.
Complements the
in-flight rdpeusb server work by giving the crate's decode surface
ongoing
fuzzing.

Co-authored-by: Clint Christopher Canada <clint.canada@clubitech.com>
2026-08-19 19:34:23 -04:00
Greg Lamberson 393869b30b feat(server)!: expose per-connection keyboard metadata via ConnectionHandler (#1691)
## Summary

AcceptorResult already carried keyboard_layout (the client's GCC Client
Core Data keyboardLayout, MS-RDPBCGR 2.2.1.3.2), but ironrdp-server's
client_accepted never read it, and the only extension point that could
plausibly expose it, ConnectionHandler::on_accept/on_disconnected, only
fires from RdpServer::run's own accept loop. An embedder with its own
accept loop calling run_connection or run_connection_with directly never
sees these hooks at all.

Added keyboard_type and ime_file_name to Acceptor and AcceptorResult,
captured from the same Client Core Data alongside keyboard_layout.

Added a new ConnectionInfo struct and a default-no-op
ConnectionHandler::on_connection_info(&ConnectionInfo) method, fired
from client_accepted itself, right after credential and auto-reconnect
validation succeed. This is reachable from every code path that
completes connection setup, not only run's accept loop, so it is usable
by embedders that never call run.

Kept the hook synchronous. It only hands the embedder a small Clone-able
struct; an embedder that needs to do blocking work in response can spawn
its own task, the same way the existing on_accept/on_disconnected hooks
already work.

Open question: AcceptorResult is a public struct without non_exhaustive,
so the two new fields are a real breaking change for any consumer
destructuring it exhaustively, same class as the keyboardType change in
#1689. AcceptorResult's attributes are unchanged here since marking it
non_exhaustive is a broader decision than this PR's two fields.

## Validation

cargo xtask check fmt/lints/tests/typos/locks all pass.

## Review round and rebase, 2026-08-19

#1689 (KeyboardType) merged. This branch was still carrying a stale
pre-merge copy of that commit, so the diff was cumulative against
master. Rebased onto current master, which dropped the redundant
duplicate commit (its content was already upstream) and left this PR's
own single commit.

Four review findings from the bot review, all addressed:

- `on_connection_info` fired on every Deactivation-Reactivation resize,
not just the initial connection, since `accept_finalize` loops back into
`client_accepted` with `result.reactivation` set. Gated the call on
`!result.reactivation`, matching the existing gate on the static-channel
start block just below it.
- `get_result()` took `ime_file_name` via `mem::take`, emptying it out
of the acceptor before `new_deactivation_reactivation` copied the same
acceptor's field into the next result, so every reactivation after the
first reported an empty IME name. Changed to a clone, matching how the
Copy-type sibling fields on the same lines already survive.
- No regression test covered the permissive zero/unrecognized-value
keyboardType decode in the Input capability set. Added
`keyboard_type_zero_decodes_to_none` and
`keyboard_type_unrecognized_value_round_trips` (0x51).
- A fourth finding asked for the same coverage on Client Core Data's own
keyboardType field; that test already exists on master, added to #1689
in response to its own review. The rebase above inherits it directly, so
no new code was needed there.
2026-08-19 19:33:33 -04:00
Greg Lamberson 6a499faece feat(connector)!: pass frame arrival time into Sequence::step (#1530)
## Summary

- Connect-time bandwidth measurement needs to know when bytes arrived,
and nothing in the sans-I/O layer could tell it. #1465, now merged,
answers the server's Bandwidth Measure Stop with a nominal interval for
exactly that reason: the connector has no way to observe the real one.
- Introduce `MonotonicInstant`, a millisecond counter with an arbitrary
epoch, and make `Option<MonotonicInstant>` a required parameter of
`Sequence::step`. The I/O drivers already know when a read completed, so
`Framed` records the arrival time of each read and hands it to the state
machine. A driver with no clock passes `None`.
- With arrival times available, measure for real: a Bandwidth Measure
Start opens a window, Payload messages accumulate their byte counts, and
Stop reports the elapsed time between its own arrival and the Start's.

#1465 has merged, so this applies directly to master and carries no
merge-order dependency. That PR was the FreeRDP unblock on its own; this
is the design change behind it, split out at @CBenoit's suggestion in
review.

## Why the clock lives in the driver

Two reasons, both of which rule out having the sequence read a clock
itself.

`std::time::Instant::now` panics on `wasm32-unknown-unknown`, and
`ironrdp-connector` compiles for it. `ironrdp-web` reaches
`ironrdp-async` through `ironrdp-futures`, so the clock read is `cfg`'d
there too: the wasm arm returns `None` rather than panicking on the
first socket read.

More fundamentally, a sequence that timestamps its own entry measures
how fast it drained an already-filled buffer, not how long the bytes
took to arrive. `Framed` stamps the actual socket read, so a PDU served
entirely from `buf` correctly reports the read that filled it.

## Why the parameter is an Option

Three situations look alike at the Stop and are not alike, and
collapsing them produces a worse figure than the nominal one #1465
sends.

A Stop with no preceding Start has no window to time. A window whose
Start, Payload and Stop arrived in one socket read carries the same
instant on all three, so the elapsed time rounds down to zero; TCP
coalescing makes this the common case on a fast link, because the
connect-time payload is small. And a driver with no clock reports
nothing at any point, which is not a measurement of zero but the absence
of one.

Only the middle case is a measurement. Making the parameter
`Option<MonotonicInstant>` is what keeps it distinguishable: a window
opens only when the Start carried a reading, so a driver with no clock
opens none, accumulates nothing, and answers the Stop with its own
payload alone. A window that was timed reports every byte per
[MS-RDPBCGR] 3.2.5.14, including when the elapsed time floors to 1 ms,
because the bytes really did arrive inside that millisecond.

Both untimed cases report a 1 ms floor rather than 0, since a server
computing `byteCount * 8 / timeDelta` divides by it.

There is no `MonotonicInstant::ZERO`. An earlier revision used it as
both the clock's origin and the "did not measure" sentinel, which is
precisely what made the wasm32 and FFI drivers indistinguishable from a
fast link: they would have paired a full byte count with an interval the
client never measured, and the reported bandwidth would have grown with
however much payload the server chose to send.

## Breaking change

`Sequence::step` takes an `Option<MonotonicInstant>`. Implementors must
add the parameter; callers driving a sequence by hand must supply an
arrival time or switch to `step_no_input`, which passes `None` for them.
All 8 in-tree implementors and the call sites across `ironrdp-acceptor`,
`ironrdp-async`, `ironrdp-blocking`, `ironrdp-client`, `ironrdp-web` and
`ffi` are updated here. `Framed::last_read_at` returns
`Option<MonotonicInstant>`.

## MonotonicInstant now lives in ironrdp-core

Also folded in here: ironrdp-rdpeudp independently defined its own
MonotonicInstant, identical in spirit to this PR's but not in API (it
carries as_millis and saturating_add, this one didn't), so a reading
from one driver could never be handed to the other. Issue #140 asked for
these to converge on one type in ironrdp-core, which both crates already
depend on.

Moved the fuller rdpeudp version into ironrdp-core and re-exported it
from both existing paths. Not filed separately: there was nothing to
migrate out of ironrdp-connector until this PR introduced its copy, so
this is the first point where the duplication exists to fix. No call
site outside the two definitions changes, both
ironrdp_connector::MonotonicInstant and
ironrdp_rdpeudp::MonotonicInstant keep working unchanged, and it's
non-breaking on its own (the connector's version gains
as_millis/saturating_add/Add<Duration>, which it didn't have before).

## Stacked on this

#1559 is stacked on this pull request and carries its three commits, so
the merge order is this one then #1559. Landing this shrinks #1559's
diff to its own change, 2 files and +149/-15 in `connection.rs` plus one
connector test.

#1559 counts the 8-byte auto-detect header into the byte count
introduced here, and narrows the Start and Stop arms to the connect-time
request type. Both come from the automated reviewer's findings on this
pull request.

## Why this is one PR

The automation flags this as size/XL and asks for it to be split. The
three commits here do not separate into reviewable pull requests.

The first changes the `Sequence::step` signature, and every implementor
and caller moves with it: connector, acceptor, async, blocking, client,
web, the FFI and the tests. That is 19 of the 23 files and +474/-116 on
its own, and a pull request holding the trait change without them does
not build.

The second exists because of the review on the first. It distinguishes a
window that was never timed from one measured as zero, which is the fix
for the finding that a wasm or FFI client would otherwise report a
fabricated bandwidth. Splitting it out means filing the first commit
with a defect already raised against it.

The third is the tests for both.

Stacked pull requests are the remedy the note suggests, and it adds that
they require every branch to live in this repository. This branch is on
a fork, so that path is closed.

## Validation

- `cargo xtask check fmt/typos/lints/tests/locks` all pass on the pinned
toolchain, `fuzz/` built before the lock check.
- `cargo xtask wasm check` passes. Worth stating separately: this is the
gate that catches the `Instant::now` hazard above, since the workspace
default target never compiles that crate for wasm.
- Six new tests in
`crates/ironrdp-testsuite-core/tests/connector/autodetect.rs`: the
interval and byte count match what the driver observed across a
Start/Payload/Stop window; several Payload messages accumulate across a
timed window; a window delivered in one read floors the interval with
every byte still counted; a driver reporting no arrival times answers
with the Stop payload alone; a Stop with no preceding Start is answered
with the floor; and a second Start clears both stores and restarts the
timer, which 3.2.5.14 requires and which nothing else covered.
- Four more in a new
`crates/ironrdp-testsuite-core/tests/async_framed.rs` covering
`Framed::last_read_at` itself, since the tests above feed
`Sequence::step` hand-picked instants and would stay green if the driver
stopped stamping reads. They pin that an unread `Framed` reports no
arrival, that each socket read advances the stamp, that PDUs sharing a
read share its stamp rather than being stamped when the caller drains
them, and that a `Framed` rebuilt around leftover bytes reports no
arrival for them, which is the case `ironrdp-tokio`'s split and unsplit
helpers produce. Each was checked by planting the corresponding
regression and confirming the test fails.
- Those live in `ironrdp-testsuite-core` rather than inline because
`ironrdp-async` sets `[lib] test = false`, so an inline `#[cfg(test)]`
module would compile and never run. This adds `ironrdp-async` as a
dev-dependency of `ironrdp-testsuite-core`.
2026-08-19 19:22:10 -04:00
Marc-André Moreau 8bd50100f5 fix(mstsgu): report EOF and stop polling a completed work task (#1709)
GwClient polled its background work JoinHandle on every read and write,
which tokio panics on once the task completes, and it never reported
end-of-stream when the gateway stream closed. A caller that holds a read
across the connection lifetime (for example a bidirectional relay) hit
`JoinHandle polled after completion` or hung forever instead of seeing
EOF.

Track work completion with a flag so the handle is polled at most once,
and surface UnexpectedEof once the task has ended and no data remains.
2026-08-19 17:25:01 -04:00
Greg Lamberson c0267494ab fix(rdpeudp)!: treat a full send buffer as backpressure, not a fatal error (#1705)
## Summary
- RdpeudpConnection::send's SendBufferFull is documented as transient,
  but the async driver treated it as fatal, tearing down an otherwise
  healthy connection under sustained write load
- send() took the payload by value with no way to hand it back on
  error, so the rejected bytes were also gone by the time the error
  propagated
- send()'s signature now returns the rejected data alongside the
  error on every rejection, via a new SendError type; breaking change
  to this crate's public API, but it has no external consumers yet
- the driver holds a backpressured write in a new pending_write field
  instead of dropping it, and retries once poll_transmit has moved
  entries out of the send buffer (an incoming ACK or a retransmit
  both qualify)
- the write-data branch of the driver's select loop stops pulling new
  data out of the shared write buffer while a write is already
  pending, so a retry never gets interleaved out of order

## Validation
`cargo xtask check fmt/lints/tests/typos/locks` all pass. Four new
driver-level tests build a real, in-memory-established connection and
mutation-verify the fix: filling the send buffer to its bound no
longer errors, the rejected payload comes back intact, a retry
delivers once drain_transmits frees room, and a retry into an
already-closed connection does not turn a clean shutdown into an
error.

## Notes
Surfaced by Copilot's second review pass on #1687, posted 11 minutes
before that PR merged; not addressed there. Second of three follow-up
PRs (see #1704 for the first).
2026-08-19 15:14:06 -04:00
Greg Lamberson 0047a28740 fix(rdpeudp)!: thread server_cert_verifier through MultitransportBootstrap::connect (#1706)
## Summary
- connect_udp already accepted a server_cert_verifier to opt into real
  TLS certificate validation, added in #1687's own first review round
- MultitransportBootstrap builds its UdpTransportConfig internally
  and never set that field, so a caller going through the high-level
  bootstrap API had no way to reach the verification connect_udp
  itself already supported
- connect() now takes server_cert_verifier as a fourth parameter and
  forwards it the same way connection_config already is
- breaking change to this crate's public API (adds a required
  parameter); the crate has no external consumers yet

## Validation
`cargo xtask check fmt/lints/tests/typos/locks` all pass. Added a
full-stack test proving the verifier is actually consulted through
the bootstrap path, reusing the AlwaysRejectVerifier double from the
sibling connect_udp test; mutation-verified by temporarily reverting
the fix and confirming the new test fails.

## Notes
Surfaced by Copilot's second review pass on #1687, posted 11 minutes
before that PR merged; not addressed there. Third of three follow-up
PRs (see #1704 and #1705 for the other two).
2026-08-19 09:22:57 -04:00
Marc-André Moreau 69e323ae47 fix(graphics): retain Progressive difference tiles (#1698)
Retain quantized DWT coefficients per Progressive tile so difference
updates compose with their matching surface reference while progressive
codec-context state remains isolated.

Reject difference tiles that lack a retained reference instead of
decoding them against zeros.

Keep retained surface references across codec grid replacement and
ResetGraphics; only deleting the surface releases them.
2026-08-19 08:26:35 -04:00
Greg Lamberson f24685cde6 fix(rdpeudp): detect driver exit during the async handshake wait (#1704)
## Summary
- connect_udp and accept_udp_inner both waited on connected_notify
  without racing it against the driver task's own completion
- a driver that exits early with a real error (socket failure, fatal
  protocol error) went unnoticed until the configured handshake
  timeout elapsed, or until the caller's outer accept_timeout
  canceled the whole accept sequence for accept_udp_inner, which had
  no timeout of its own on this wait at all
- either way the caller got a generic HandshakeTimeout instead of the
  driver's actual error
- both call sites now race connected_notify against the driver's
  JoinHandle directly, via a shared driver_exit_during_handshake
  helper that turns a join result into the right UdpTransportError
- added AbortOnDrop::handle_mut to borrow the wrapped JoinHandle for
  a select! branch without taking ownership of it

## Validation
`cargo xtask check fmt/lints/tests/typos/locks` all pass. Four new
tests cover the shared helper's three outcomes (real driver error,
clean exit treated as failure, panic) and the select! race itself
(a driver that dies immediately is detected well inside a 5-second
bound instead of falling through to a 60-second stand-in timeout).

## Notes
Surfaced by Copilot's second review pass on #1687, posted 11 minutes
before that PR merged; not addressed there.
2026-08-19 17:57:31 +09:00
Greg Lamberson 2191cf47a1 feat(fuzz): add fuzz targets for the RDP-UDP transport and RDPEMT tunnel (#1707) 2026-08-19 17:53:15 +09:00
uchouT b5c1d4da32 feat(rdpeusb): add the usb translation module (#1683)
Adds a new sans-I/O `usb` module to ironrdp-rdpeusb translating protocol-independent ironrdp-usb requests into complete RDPEUSB TS_URB packets and back, plus a small, explicitly-justified bundled refactor (BcdVersion reuse, CompletionData enum).
2026-08-19 17:42:58 +09:00
Micah Roberts 75ea3b96f0 fix(session): handle MCS Disconnect Provider Ultimatum (#1692)
Some servers (xrdp) end a session by sending a Disconnect Provider
Ultimatum on its own, not wrapped in a Send Data Indication. We only
decoded Send Data Indications, so a clean session end came out as a
protocol error.

Check for it when the Send Data Indication decode fails and return a
Disconnect instead.
2026-08-18 19:06:38 -04:00
Greg Lamberson c74e7c5c94 fix(pdu)!: accept the full documented range of Client Core Data keyboardType values (#1689)
## Summary

KeyboardType (TS_UD_CS_CORE's keyboardType field, MS-RDPBCGR 2.2.1.3.2)
was a closed enum covering discriminants 1 through 7, transcribed from
the field's other documentation in 2.2.7.1.6 (TS_INPUT_CAPABILITYSET),
which omits value 8 (Korean keyboard). The table this type actually
decodes against, 2.2.1.3.2, documents 1 through 8. Any client outside
the narrower range, including every genuine Korean keyboard, had its
whole Client Core Data parse hard rejected before the connection
started.

Converted KeyboardType to a repr(transparent) struct KeyboardType(pub
u32) with named constants for the eight documented values, mirroring
RdpVersion one field above it in the same struct, and made decode
infallible at all three sites that previously disagreed with each other:
gcc::core_data::client hard rejected, rdp::capability_sets::input
silently dropped to None, and ironrdp-activex's COM setter returned
E_INVALIDARG.

FreeRDP hit the identical gap in its own documentation-only enum until a
two-line fix (FreeRDP#11035). Neither FreeRDP nor xrdp gate connection
admission on this field at all; both decode it as a raw integer.
Windows' own GetKeyboardType additionally documents 0x51 for generic HID
keyboards, which a narrower fix adding only Korean would not survive.

Marked as breaking since KeyboardType's public shape changes for any
downstream consumer of ironrdp-pdu outside this workspace. Note that
cargo-semver-checks in this repo's PR automation only runs against the
facade ironrdp crate, which will not see a break confined to
ironrdp-pdu's own API, so the automated breaking-change label may not
apply here even though this is a real one.

## Validation

cargo xtask check fmt/lints/tests/typos/locks all pass. Extended
ironrdp-activex's existing inline COM boundary test to cover value 8
round tripping and a negative value still being rejected.
2026-08-18 19:05:37 -04:00
Greg Lamberson 9aa8a4b063 feat(rdpeudp): add the async driver for the RDP-UDP transport (#1687)
Fifth of six. **Stacked on the connection state machine PR**, and needs
the
RDPEMT PR too.

Wires the sans-I/O connection and the RDPEMT tunnel to a real socket. A
single
task owns the `UdpSocket` and the `RdpeudpConnection` and runs a select
loop over
three sources: datagrams arriving, plaintext the TLS layer wants to
send, and
timer expiry. It is the only place in the stack that reads a clock.

`RdpeudpStream` gives tokio-rustls something to wrap, bridging the
driver to TLS
through a pair of buffers so the TLS layer never learns it is running
over UDP.
`connect_udp` and `accept_udp` run the whole sequence: RDP-UDP
handshake, TLS,
RDPEMT tunnel, then a data pump. `UdpTransport` implements `FramedRead`
and
`FramedWrite`, so the session layer reaches it through the same traits
as the TCP
path.

## Three things this layer has to get right

**A spawned task that is dropped keeps running.** All three handles
(driver,
read pump, write pump) live in a guard that aborts on drop and can be
taken
back when the task is meant to be awaited. That matters because the TLS
upgrade and the tunnel handshake both sit between spawning the driver
and
returning the transport, and both propagate with `?`. Making the guard
structural means each early return cleans up without every path having
to
remember. `shutdown()` follows the same three-task shape in reverse: the
read
pump gets EOF once the shared I/O bridge is marked closed, the write
pump
exits on its own once the send channel is dropped, and the driver is
aborted
last since it may still be sitting in its select loop.

**The read buffer is bounded.** Ceasing to read from the socket is the
backpressure the protocol expects rather than a drop policy: unread
datagrams
stay in the socket buffer, acknowledgements stop, and the receive window
closes
on the sender, which is what [MS-RDPEUDP2] 3.1.1.2.2 has it for. The
half that is
easy to leave out is resuming, so `poll_read` wakes the driver once it
has taken
bytes out.

**An empty tunnel PDU is not end of stream.** `Framed` reads a
zero-length result
as EOF, and [MS-RDPEMT] 2.2.2.3 puts no minimum on `HigherLayerData`.
[MS-RDPBCGR] 1.3.9 sends the four Continuous Auto-Detection messages
"encapsulated in the RDP_TUNNEL_SUBHEADER structure ... over the
sideband
channels that are in active use", and those carriers have nothing behind
the
subheaders.

## On the cookie hash

The SHA-256 the version 3 SYN carries is derived here from the tunnel
config,
which already holds the security cookie. That keeps `ironrdp-rdpeudp`
free of a
cryptographic dependency and means a caller cannot supply a hash over a
different
cookie than the tunnel will present.

## Test plan

`cargo xtask check fmt/lints/tests/typos/locks` plus `cargo xtask wasm
check`

Unit tests for the stream adapter, the framing adapter, task lifetime,
backpressure, and clean-vs-truncated tunnel PDU framing, plus nine
full-stack
loopback tests in `ironrdp-testsuite-extra` that run a client and server
through handshake, TLS, tunnel and bidirectional data over localhost,
including IPv4 and IPv6, an oversized-payload rejection, a
caller-supplied
certificate verifier, and a failed-reconnect state check.

One caveat on those loopback tests, since it caught me out: localhost
carries an
oversized datagram perfectly well, so they cannot detect an MTU
violation. The
datagram sizes are asserted in the connection tests instead.
2026-08-18 21:25:57 +00:00
Marc-André Moreau 39cba1e160 feat(replay): route captured EGFX output (#1697)
Attach a passive EGFX client to recorded graphics DVCs so replay can
composite completed output into payload-free frame exports.

Preserve captured DVC IDs and names while suppressing replay-side
capability advertisements and frame acknowledgements.
2026-08-18 10:57:01 -04:00
Marc-André Moreau 96e388eef2 fix(egfx): compose scaled output surfaces (#1699)
Implement client-side composition for MapSurfaceToScaledOutput.

Track scaled mappings in the EGFX compositor, materialize scaled dirty
output at EndFrame, and preserve bounded output clipping and
frame-atomic updates.

Add client and compositor coverage for dispatch, nearest-neighbor
pixels, dirty bounds, persistent output, and oversized wire-scale
factors.
2026-08-18 10:34:05 -04:00
Marc-André Moreau 7824bc7503 fix(graphics): decode Progressive SRL refinements (#1696)
Preserve SRL and raw-bit state across Progressive DWT bands.

Reject malformed SRL refinement streams without decoding invented zero
data or partially updating tiles.
2026-08-18 10:33:10 -04:00
Greg Lamberson 925e7c0f7c feat(server): make the RemoteFX quantization table configurable (#1685)
Add Quant::try_new(), a validating constructor that rejects any subband
value outside the 6..=15 range, and
RdpServerBuilder::with_remotefx_quant(quant: Quant), wiring it through
RdpServerOptions to the same capability-negotiation call site #1684
touched.

Per [MS-RDPRFX] 2.2.2.1.5, each of the 10 TS_RFX_CODEC_QUANT values is a
4-bit field, and the legal range is 6 to 15. #1557 reports the quant
table is hardcoded to Quant::default(); this gives callers a validated
way to set it instead.

Builds on #1684, which added the storage this PR wires up. Default
behavior is unchanged: with_remotefx_quant is opt-in, and a server that
doesn't call it still gets Quant::default(), the same values Windows RDP
servers send.

Closes #1557.
2026-08-18 10:25:42 -04:00
Greg Lamberson 1bb08bfd8c refactor(server): thread quantization values through the RemoteFX encoder (#1684)
RfxEncoder hardcoded Quant::default() at the point of use instead of
accepting it as encoder state. Add a quant field to RfxEncoder and a
remotefx_quant field to UpdateEncoderCodecs, with a setter that mirrors
the existing set_remotefx pattern.

Per [MS-RDPRFX] 2.2.2.1.5, quantization is chosen entirely by the sender
and isn't part of capability negotiation, so making it configurable is
purely a server-side plumbing problem. This is the first step: give the
encoder somewhere to actually hold and use a caller-chosen Quant. #1557
asks for the ability to set it; this PR doesn't add that public entry
point yet, it just makes the encoder capable of taking one.

Server behavior is unchanged. The capability negotiation call site still
passes Quant::default(), so this is pure plumbing with no functional
change.
2026-08-18 09:11:21 -04:00
Marc-André Moreau c1db8608af fix(pdu): parse ClearCodec V-Bar offsets (#1694)
Decode short V-Bar cache-miss offsets from their specified bit
positions.
2026-08-18 08:42:34 -04:00
Benoît Cortier 46e1d24a7c ci(pr-automation): retrigger review on opt-in (#1688)
Treat the oversized-review label as an explicit review request so a
maintainer can retry a failed review without waiting for another CI
completion or classification-state change.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-08-18 17:14:50 +09:00
uchouT cec0c1487f feat: add the ironrdp-usb crate (#1682)
Introduce a protocol-independent, `no_std`, sans-I/O crate holding
USB-standard data structures and semantics that are shared by any USB
redirection transport adapter:

- typed USB values and identifiers;
- descriptor storage, parsing, validation, and traversal for device,
configuration, interface, and endpoint descriptors (`descriptor`);
- standard control requests and setup packets (`control`);
- endpoint identity, addressing, and companion metadata (`endpoint`);
- transfer direction, type, status, and request/result data
(`transfer`).

The crate is dependency-free, borrows its parsing input, and is generic
over caller-owned buffer storage, so it never allocates. It describes
USB operations and data but does not execute them: device I/O, async
runtime integration, request routing, and pending-request management all
stay in the consuming protocol layers.

**Parsing is restricted to byte layouts defined by USB itself**. RDPEUSB
PDUs, usbredir packets, and other transport framing belong to their
respective crates.

Descriptor parsing is a hostile-input surface, so the tests in
`ironrdp-testsuite-core` cover the framing, length, and topology
boundaries rather than the internals: `bLength` framing, minimum and
trailing-byte rules, `wTotalLength` completeness, the configuration
topology rules enforced by `validate`, setup packet size and field
partitioning, and the endpoint address and packet-size encodings.

Signed-off-by: uchouT <i@uchout.moe>
2026-08-18 16:17:27 +09:00
Greg Lamberson 1723385068 feat(rdpeudp)!: add the connection state machine (#1681)
Fourth of six. Filed against master directly; #1626, #1627 and #1679
have
all merged.

Adds the sans-I/O `RdpeudpConnection` and the machinery it drives: send
and
receive windows, loss detection, NewReno congestion control, an RFC 6298
RTT
estimator, the timer table, the reliability controller that matches
retransmissions to the packets they replace, and sequence-number
reconstruction
from 16-bit wire values.

This is the largest PR in the stack. I looked at splitting the state
machine
from the reliability primitives, but `connection.rs` drives all of them
and the
tests span both, so the seam would have been artificial.

## Sans-I/O

No clock, no socket. Time arrives as a `MonotonicInstant` argument and
outgoing
packets leave as `Transmit` values. That keeps it testable without a
network,
and avoids `std::time::Instant`, whose `now` panics on
`wasm32-unknown-unknown`.

**`MonotonicInstant` is defined here, and #1530 adds one to
`ironrdp-connector`
for the same reason.** Two copies of one abstraction is a wart.
`ironrdp-core`
looks like the right home to me, and I raised it on #140; happy to move
it
wherever you prefer, in this PR or a follow-up.

## Behaviour that is required rather than chosen

**Version 3 in the SYN.** That is the version [MS-RDPEUDP] 1.3.2.2 and
the
2.2.2.9 table tie to the MS-RDPEUDP2 data transfer. Version 2 selects
the
MS-RDPEUDP one, which this crate does not implement. Version 3 requires
the
SHA-256 of the `securityCookie` in the client's SYN (2.2.2.9), so
`ConnectionConfig` carries it, `connect` refuses without it, and the
server
performs the check 3.1.5.1.1 asks for.

**The handshake retransmits.** 1.3.1 delivers the SYN, SYN+ACK and ACK
by
persistent retransmits whatever mode the transport runs in; 3.1.5.4.1
gives up
after between three and five unanswered tries. A repeated datagram from
the peer
draws a repeat of ours rather than an error, including a SYN+ACK
arriving after
we have moved on to v2, which is how a client learns its final ACK was
lost.

**The delayed-ACK timer tracks the RTT instead of a fixed duration.**
MS-RDPEUDP2 3.1.5.2 gives half the round trip time as the receiver's
default.
The handshake round trip seeds the existing RFC 6298 estimator (skipped
when
the handshake datagram was retransmitted, per Karn's algorithm), and the
computed timeout is clamped to the 50-200ms band [MS-RDPEUDP] 3.1.6.3
gives a
version-2 connection, since MS-RDPEUDP2 itself states no floor or cap of
its
own.

**`UdpVersion` widens from a closed enum to a newtype carrying the raw
wire
value.** This is a breaking change to the public API #1627 shipped.
MS-RDPEUDP
1.7 and 3.1.5.1.3 require a responder to negotiate down to a version it
supports when the peer advertises one it does not recognize;
hard-failing
decode on an unrecognized value made that MUST clause unsatisfiable.
Every
call site already used the named constants, so this is the only
consequential
part of the change.

**`error.rs` and its `Cargo.toml`/README wiring are back.** #1627
correctly
dropped them at its own narrower, PDU-only scope; this PR's state
machine is
what actually needs them.

**The receive window advances on both events in 3.1.1.2.2**, not only on
AckOfAcks. The first one is what fires on a connection that is losing
nothing;
without it the window fills one window in and stops accepting.

**AckOfAcks carries our own lowest unacknowledged sequence number**
(2.2.1.2.4,
3.1.5.3). It is the only thing that can move a receiver past a packet
the sender
gave up on, since the retransmission carries a fresh `DataSeqNum` and
the
original is never filled.

**Writes are split to the MTU.** MS-RDPEUDP2 does not segment:
3.1.1.2.4.2
forwards each packet's payload straight up and nothing marks a first or
last
fragment. `ChannelSeqNum` looks like it would serve but 3.1.5.5 gives it
a
different job, matching a retransmission to the packet it replaces. So
anything
longer than one packet is split before it becomes packets.

**Dummy packets** are accounted for by the transport and their contents
dropped,
per 3.1.1.1.5.

## Test plan

`cargo xtask check fmt/lints/tests/typos/locks`

179 rdpeudp tests in `ironrdp-testsuite-core` with this PR applied, plus
179
inline unit tests across the crate's components. The connection tests
cover a
clean transfer longer than the window, a loss in the middle of one,
handshake
retransmission to the give-up limit, the version and cookie negotiation
paths,
decoding an unrecognized `uUdpVer`, the ack-delay timeout's RTT-tracking
and
clamping behaviour, and the review round's findings: an out-of-range ACK
no
longer discards outstanding data, the ACK vector respects its 127-entry
wire
limit, `log_window_size` is validated, the ACK builders encode real
timestamps and gaps, the handshake's Karn's-algorithm check is ordered
correctly, the retransmit timer restarts on real progress, `accept`
completes
the negotiate-down behaviour, and `send` enforces a buffer bound.
2026-08-16 21:00:39 -04:00
Marc-André Moreau f21f1979f4 feat(graphics): decode RFX Progressive tiles (#1673)
Keep Progressive tile state scoped to its surface and codec context.

Reject context-less updates that have no state for their surface, and
expose targeted context and surface cleanup for consumers.
2026-08-16 16:39:06 -04:00
Greg Lamberson 224e8db7ce feat(server): measure and report network characteristics (#1470)
## Summary

- The server measures round-trip time and bandwidth from the continuous
  auto-detect exchange and reports both to the client in a Network
Characteristics Result on the MCS message channel ([MS-RDPBCGR]
2.2.14.1.5).
- Nothing is sent until both are known. A result carrying RTT alone
reports part
of the picture as though it were the whole, which is what krdp and grd
avoid by
  returning early when they have no bandwidth figure.
- The result is paced at one per second on its own clock rather than
once per
probe, and is withheld unless a client response has arrived since the
last one.
A client that stops answering stops producing results instead of leaving
the
  last window values advertised indefinitely.
- `baseRTT` is the lowest RTT seen over the session, per 2.2.14.1.5's
"lowest
  detected round-trip time". `averageRTT` is the window average, so the
  difference between them is queueing delay.

## Validation

- `cargo xtask check fmt/lints/tests/typos/locks` and `cargo xtask wasm
check`
  all pass.
- `cargo semver-checks -p ironrdp-server --baseline-rev master`: no
update
  required.
- Tests live in `ironrdp-testsuite-core`. `ironrdp-server` sets
`[lib] test = false`, so an inline module would compile and never run.
Each new
test was checked by planting the corresponding regression and confirming
it
  fails.

## Notes

- Supersedes #1471, which added bandwidth as a follow-up. With the gate
above,
this PR alone could only ever emit the form it now declines to send, so
the two
  are one change.
- #1487 has merged, so the earlier dependency note no longer applies.
2026-08-16 14:50:00 -04:00
Marc-André Moreau 063efcdc30 feat(activex): negotiate monitor topology (#1675)
Negotiate the client monitor layout from UseMultimon and expose the
confirmed remote topology through the ActiveX compatibility interface.

Advertise Monitor Layout PDU support whenever Extended Client Data is
negotiated, and forward layouts from activation, active sessions, and
reactivation so advertised support does not terminate sessions.

Keep fallback reporting truthful when servers do not honor the request,
while preserving single-monitor resize behavior and blocking
multi-monitor resizing.

Do not send Client Monitor Extended Data; per-monitor DPI and
orientation remain unavailable.
2026-08-16 13:42:43 -04:00