diff --git a/AGENTS.md b/AGENTS.md index 5788aeb..e145142 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -57,7 +57,7 @@ RDP sessions stay alive across idle periods and network drops: the bridge enable RDP certificate verification: the bridge no longer ignores the server certificate. `cxrdp_set_certificate_callback` (API 16, `CX_RDP_CAPABILITY_CERTIFICATE_VERIFICATION`) registers `RdpBridgeClient.OnCertificateVerification`, which runs on the native connect thread and blocks while `Services/RdpCertificateTrustService` asks the user, because the answer must exist before the handshake continues; the bridge calls it outside `callback_mutex` on purpose, so never take that lock around a prompt. The native side switches `FreeRDP_IgnoreCertificate`/`AutoAcceptCertificate` to FALSE only when a callback is registered (an older host keeps the accept-all behaviour), normalises the digest to lower-case hex, and caches one decision per fingerprint so a TLS + NLA/CredSSP exchange prompts once. The trust store (`rdp_certificates` collection in `SqliteAppDataStore`) is keyed on the real target `_profileCacheHost/_profileCachePort`, never the loopback endpoint a tunnel or proxy relay substitutes. First-use prompting and changed-certificate blocking mirror SSH (`ConfirmRdpCertificateOnFirstConnection`, `BlockChangedRdpCertificates`, both default true); a changed certificate is rejected without a prompt and the operator removes the entry in Settings → Trusted hosts, and `RdpCertificatePromptService.CancelPending()` closes a pending prompt when the tab is disconnected. -RDP DPI policy (`SessionInfo.RdpDpiPolicy`, edited in `Views/SessionEditDialog.axaml`): `FollowLocal` (default) maps the local render scaling to a quantized RDP scale (100/125/150/175/200) via `Services/RdpDpiScale.cs`; `Fixed100` forces 100%; `KeepRemote` advertises no scale. At connect time `RdpBridgeClient` calls `cxrdp_set_display_scale`, and the bridge adds the `disp` dynamic channel (registered as `DISP_CHANNEL_NAME` "disp" — the long `DISP_DVC_CHANNEL_NAME` fails to resolve the static addin in freerdp-client3.dll) and sets `FreeRDP_DesktopScaleFactor`/`DeviceScaleFactor`. On resize or a monitored DPI change, `RdpViewModel` calls `cxrdp_update_display`; the bridge queues it on the worker thread, which sends `DispClientContext.SendMonitorLayout` with physical dimensions and then resizes GDI directly (the host's deactivate/reactivate does not emit a Desktop Resize Update). Fall back to the full-reconnect resize path when the bridge lacks API 6 / `CX_RDP_CAPABILITY_RUNTIME_RESIZE`. The C API version is 15 and the smoke tool asserts the runtime-resize capability bit. +RDP DPI policy (`SessionInfo.RdpDpiPolicy`, edited in `Views/SessionEditDialog.axaml`): `FollowLocal` (default) maps the local render scaling to a quantized RDP scale (100/125/150/175/200) via `Services/RdpDpiScale.cs`; `Fixed100` forces 100%; `KeepRemote` advertises no scale. At connect time `RdpBridgeClient` calls `cxrdp_set_display_scale`, and the bridge adds the `disp` dynamic channel (registered as `DISP_CHANNEL_NAME` "disp" — the long `DISP_DVC_CHANNEL_NAME` fails to resolve the static addin in freerdp-client3.dll) and sets `FreeRDP_DesktopScaleFactor`/`DeviceScaleFactor`. On resize or a monitored DPI change, `RdpViewModel` calls `cxrdp_update_display`; the bridge queues it on the worker thread, which sends `DispClientContext.SendMonitorLayout` with physical dimensions and then resizes GDI directly (the host's deactivate/reactivate does not emit a Desktop Resize Update). **GDI buffer ownership (2026-11-29 crash fix, seen 11-27 and 11-29):** `push_frame` must publish `gdi->primary->bitmap->data` (validated through `gdi->primary`), NEVER the cached `gdi->primary_buffer` — FreeRDP 3.32.2's `gdi_init_primary` assigns `primary_buffer` before its final allocations and its `fail_hwnd` path frees the bitmap without clearing the cached pointer, so a failed `gdi_resize` leaves it dangling at the freed data while `gdi->width/height` already hold the new size, and the next frame callback hands freed memory to `CopyDirtyRectFromNative` (the reproducible Access Violation during resolution switches). When `gdi_resize` fails destructively (`gdi->primary == nullptr`), `cx_desktop_resize` rebuilds the GDI in place — `unbind_gfx_pipeline` → `gdi_init` at the settings size → `bind_gfx_pipeline`, because `gfx->custom` still points at the broken struct — and only aborts the session via `freerdp_abort_connect` when the rebuild itself fails; `cx_begin_paint` keeps a null-guarded chain for the same broken state. Fall back to the full-reconnect resize path when the bridge lacks API 6 / `CX_RDP_CAPABILITY_RUNTIME_RESIZE`. The C API version is 15 and the smoke tool asserts the runtime-resize capability bit. RDP scale wire format (`Services/RdpDpiScale.cs`, `native/CxRdpBridge/cxrdp_bridge.cpp`): `ResolveScalePercent` may return any of 100/125/150/175/200 for `DesktopScaleFactor`, but `DeviceScaleFactor` is only allowed to be 100, 140 or 180 — any other value makes Windows drop BOTH scale factors silently, which looked like "the DPI setting does nothing" on multi-monitor layouts. Both sides therefore funnel it through `RdpDpiScale.DeviceScaleFactorFromDesktopScale` / `resolve_device_scale_factor`; keep the two in sync. Desktop sizes must be even numbers (`& ~1`) because MS-RDPEDISP rejects an odd width, and `PhysicalWidth`/`PhysicalHeight` are derived from the scale by `compute_physical_mm` so the remote sees a plausible monitor. `cx_post_connect` remembers whether the `disp` capabilities already arrived (`disp_caps_received`) and, when they did, queues the initial monitor layout instead of waiting for the first resize; after `freerdp_connect` the worker resets all of it so ARC reconnects re-send a layout. `RdpViewModel` keeps `_runtimeDisplayScalePercent` next to the runtime width/height: a resize is only sent when the size moved by 2 px or the scale actually changed, and `RequestViewportResize` debounces 250 ms (`_resizeDebounceCts`) because MS-RDPEDISP throttles back-to-back `SendMonitorLayout` PDUs during a window drag. `Views/RdpView.axaml.cs` disables the local Windows IME with `ImmAssociateContext(hwnd, IntPtr.Zero)` while the RDP view holds focus and restores the saved context on `LostFocus`, so a local input method cannot swallow remote keystrokes. diff --git a/Controls/DataGridSourceAdapter.cs b/Controls/DataGridSourceAdapter.cs index 0f7728a..c69d4af 100644 --- a/Controls/DataGridSourceAdapter.cs +++ b/Controls/DataGridSourceAdapter.cs @@ -1,4 +1,5 @@ using System.Collections; +using System.Collections.Concurrent; using System.Collections.Immutable; using System.Reflection; using System.Runtime.CompilerServices; @@ -14,6 +15,10 @@ namespace CxShell.Controls; /// public sealed class DataGridSourceAdapter : IDisposable { + private static readonly string[] NestedKeyPropertyNames = ["Session", "Entry", "Recording"]; + private static readonly string[] DirectKeyPropertyNames = ["Id", "Key", "FullPath", "Path", "Name"]; + private static readonly ConcurrentDictionary KeyPlans = new(); + private static readonly ConcurrentDictionary IdProperties = new(); private static readonly IComparer ObjectComparer = Comparer.Create(CompareValues); private readonly IReadOnlyList _items; private readonly Dictionary _itemsByKey = new(); @@ -257,28 +262,77 @@ private static bool SupportsScalar(Type type) _ => null }; - private static string GetStableKeyText(T item) + /// + /// Property lookups that produce a row key, resolved once per item type. Row keys are + /// rebuilt on every selection query, so scanning the type with reflection per item made + /// selection cost grow with the number of properties instead of the number of rows. + /// + private sealed class KeyPlan + { + public required string TypeName { get; init; } + public required (string Name, PropertyInfo Property)[] Nested { get; init; } + public required (string Name, PropertyInfo Property)[] Direct { get; init; } + } + + private static KeyPlan BuildKeyPlan(Type type) + { + var properties = new Dictionary(StringComparer.Ordinal); + foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) + { + if (property.GetMethod == null || property.GetIndexParameters().Length != 0) + continue; + + properties.TryAdd(property.Name, property); + } + + return new KeyPlan + { + TypeName = type.FullName ?? string.Empty, + Nested = Collect(NestedKeyPropertyNames), + Direct = Collect(DirectKeyPropertyNames) + }; + + (string, PropertyInfo)[] Collect(string[] names) + { + var found = new List<(string, PropertyInfo)>(names.Length); + foreach (var name in names) + { + if (properties.TryGetValue(name, out var property)) + found.Add((name, property)); + } + + return found.ToArray(); + } + } + + private string GetStableKeyText(T item) { if (item == null) return "null"; - var type = item.GetType(); - foreach (var nestedPropertyName in new[] { "Session", "Entry", "Recording" }) + var plan = KeyPlans.GetOrAdd(item.GetType(), static type => BuildKeyPlan(type)); + var hash = RuntimeHelpers.GetHashCode(item); + + foreach (var (name, property) in plan.Nested) { - var nested = type.GetProperty(nestedPropertyName, BindingFlags.Public | BindingFlags.Instance)?.GetValue(item); - var nestedId = nested?.GetType().GetProperty("Id", BindingFlags.Public | BindingFlags.Instance)?.GetValue(nested); - if (nestedId != null) - return $"{type.FullName}:{nestedPropertyName}:{nestedId}:{RuntimeHelpers.GetHashCode(item)}"; + var nested = property.GetValue(item); + if (nested == null) + continue; + + var idProperty = IdProperties.GetOrAdd( + nested.GetType(), + static nestedType => nestedType.GetProperty("Id", BindingFlags.Public | BindingFlags.Instance)); + if (idProperty?.GetValue(nested) is { } nestedId) + return $"{plan.TypeName}:{name}:{nestedId}:{hash}"; } - foreach (var propertyName in new[] { "Id", "Key", "FullPath", "Path", "Name" }) + foreach (var (name, property) in plan.Direct) { - var property = type.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance); - var value = property?.GetValue(item); + var value = property.GetValue(item); if (value != null && !string.IsNullOrWhiteSpace(value.ToString())) - return $"{type.FullName}:{propertyName}:{value}:{RuntimeHelpers.GetHashCode(item)}"; + return $"{plan.TypeName}:{name}:{value}:{hash}"; } - return $"{type.FullName}:{RuntimeHelpers.GetHashCode(item)}"; + return $"{plan.TypeName}:{hash}"; } } diff --git a/CxShell.Tests/DataGridSourceAdapterTests.cs b/CxShell.Tests/DataGridSourceAdapterTests.cs index 9d491ea..183062f 100644 --- a/CxShell.Tests/DataGridSourceAdapterTests.cs +++ b/CxShell.Tests/DataGridSourceAdapterTests.cs @@ -47,6 +47,79 @@ [new DataGridSelectionInterval(1, 3, scope)], Assert.Equal(items.Skip(1).Take(2), selected); } + [Fact] + public void GetSelectedItems_ResolvesKeyFromNestedProperty() + { + var sharedId = Guid.NewGuid(); + var items = new[] + { + new NestedKeyItem(new NestedKeyId { Id = sharedId }), + new NestedKeyItem(new NestedKeyId { Id = sharedId }) + }; + using var adapter = new DataGridSourceAdapter(items, snapshot: true); + + var selected = SelectExplicitly(adapter, items[0]); + + Assert.Equal(new[] { items[0] }, selected); + } + + [Fact] + public void GetSelectedItems_ResolvesKeyFromDirectProperty() + { + var items = new[] + { + new DirectKeyItem { Name = "first" }, + new DirectKeyItem { Name = "first" } + }; + using var adapter = new DataGridSourceAdapter(items, snapshot: true); + + var selected = SelectExplicitly(adapter, items[1]); + + Assert.Equal(new[] { items[1] }, selected); + } + + [Fact] + public void GetSelectedItems_FallsBackToInstanceIdentityWithoutKeyProperties() + { + var items = new[] { new BareItem(), new BareItem() }; + using var adapter = new DataGridSourceAdapter(items, snapshot: true); + + var selected = SelectExplicitly(adapter, items[0]); + + Assert.Equal(new[] { items[0] }, selected); + } + + private static IReadOnlyList SelectExplicitly(DataGridSourceAdapter adapter, T item) + { + var grid = new DataGrid { SelectionMode = DataGridSelectionMode.Extended }; + grid.Selection = new DataGridSelectionState( + ImmutableArray.Create(adapter.GetKey(item)), + null, + ImmutableArray.Empty, + ImmutableArray.Empty); + return adapter.GetSelectedItems(grid); + } + + private sealed class NestedKeyItem(NestedKeyId session) + { + public NestedKeyId Session { get; } = session; + public string Name { get; } = "shared-name"; + } + + private sealed class NestedKeyId + { + public Guid Id { get; init; } + } + + private sealed class DirectKeyItem + { + public string Name { get; init; } = string.Empty; + } + + private sealed class BareItem + { + } + private static SessionRecordingItemViewModel[] CreateItems(int count) { return Enumerable.Range(0, count) diff --git a/Services/SshConnectionService.cs b/Services/SshConnectionService.cs index 774a30f..0b0f29f 100644 --- a/Services/SshConnectionService.cs +++ b/Services/SshConnectionService.cs @@ -2,7 +2,6 @@ using System.Buffers; using System.Collections.Generic; using System.IO; -using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -1242,40 +1241,15 @@ public void ResizeTerminal(TerminalPtySize size) if (_shellStream == null) return; - // SSH.NET keeps the session channel private; send the PTY window-change - // request through that channel so remote readline/bash wrap at our width. - var channelField = typeof(ShellStream).GetField( - "_channel", - BindingFlags.Instance | BindingFlags.NonPublic); - var channel = channelField?.GetValue(_shellStream); - if (channel == null || channelField == null) - return; - - var method = channelField.FieldType.GetMethod( - "SendWindowChangeRequest", - BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, - binder: null, - types: new[] { typeof(uint), typeof(uint), typeof(uint), typeof(uint) }, - modifiers: null) - ?? channel.GetType().GetMethod( - "SendWindowChangeRequest", - BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, - binder: null, - types: new[] { typeof(uint), typeof(uint), typeof(uint), typeof(uint) }, - modifiers: null); - if (method == null) - { - ErrorOccurred?.Invoke("SSH terminal resize failed: SendWindowChangeRequest was not found."); - return; - } - - method.Invoke(channel, new object[] - { + // ShellStream.ChangeWindowSize sends the PTY window-change request on the + // session channel, so remote readline/bash wrap at our width. Reaching into + // the private channel field by reflection used to break whenever SSH.NET + // reshaped its internals, and reflection is not available under NativeAOT. + _shellStream.ChangeWindowSize( (uint)Math.Max(1, size.Columns), (uint)Math.Max(1, size.Rows), (uint)Math.Max(0, size.PixelWidth), - (uint)Math.Max(0, size.PixelHeight) - }); + (uint)Math.Max(0, size.PixelHeight)); } catch (Exception ex) { diff --git a/native/CxRdpBridge/cxrdp_bridge.cpp b/native/CxRdpBridge/cxrdp_bridge.cpp index 6f7b3df..87d9db0 100644 --- a/native/CxRdpBridge/cxrdp_bridge.cpp +++ b/native/CxRdpBridge/cxrdp_bridge.cpp @@ -86,6 +86,12 @@ struct RemoteClipboardFileEntry uint64_t expected_size = 0; uint64_t received_bytes = 0; bool size_known = false; + // MS-RDPECLIP 3.1.5.4.5 treats knowledge of the file size as a + // prerequisite for FILECONTENTS_RANGE, and rdpclip tracks the file + // stream per streamId: always open each file with a FILECONTENTS_SIZE + // request before reading ranges, mirroring mstsc and FreeRDP's FUSE + // clients (client/common/client_cliprdr_file.c). + bool size_requested = false; }; constexpr uint32_t CX_CLIPRDR_FORMAT_PNG = 0xC001u; @@ -213,6 +219,15 @@ struct CxRdpSession size_t remote_file_download_index = 0; uint32_t remote_file_stream_id = 1; bool remote_file_requesting_size = false; + // Server clipboard capabilities (generalFlags) and the lock we hold on + // the SERVER's clipboard data while downloading remote files. rdpclip + // fails FILECONTENTS requests that do not reference a clipDataId when + // both sides negotiated CB_CAN_LOCK_CLIPDATA, so mirror mstsc: lock the + // remote file list before pulling it and reference the id everywhere. + uint32_t server_clipboard_flags = 0; + uint32_t remote_clip_data_id = 0; + bool remote_clip_data_locked = false; + uint32_t next_remote_clip_data_id = 1; int last_upload_progress_pct = -1; int last_download_progress_pct = -1; @@ -849,6 +864,63 @@ bool parse_file_group_descriptor_w( return !outFiles.empty(); } +// Lock the SERVER's clipboard data before pulling file descriptors/contents +// from it. rdpclip answers clipDataId-less FILECONTENTS requests with +// CB_RESPONSE_FAIL once both sides negotiated CB_CAN_LOCK_CLIPDATA, so the +// download must reference a lock, exactly like mstsc and FreeRDP's FUSE +// clients do (client/common/client_cliprdr_file.c: clip_data_entry_new). +void lock_remote_clip_data(CliprdrClientContext* cliprdr, CxRdpSession* session) +{ + if (!cliprdr || !cliprdr->ClientLockClipboardData || !session) + return; + + uint32_t id = 0; + { + std::lock_guard lock(session->clipboard_mutex); + if (session->remote_clip_data_locked) + return; + if ((session->server_clipboard_flags & CB_CAN_LOCK_CLIPDATA) == 0) + return; + id = session->next_remote_clip_data_id++; + if (id == 0) + id = session->next_remote_clip_data_id++; + session->remote_clip_data_id = id; + session->remote_clip_data_locked = true; + } + + CLIPRDR_LOCK_CLIPBOARD_DATA lockData{}; + lockData.common.msgType = CB_LOCK_CLIPDATA; + lockData.clipDataId = id; + const UINT rc = cliprdr->ClientLockClipboardData(cliprdr, &lockData); + if (rc != CHANNEL_RC_OK) + { + std::lock_guard lock(session->clipboard_mutex); + session->remote_clip_data_locked = false; + session->remote_clip_data_id = 0; + } +} + +void unlock_remote_clip_data(CliprdrClientContext* cliprdr, CxRdpSession* session) +{ + if (!cliprdr || !cliprdr->ClientUnlockClipboardData || !session) + return; + + uint32_t id = 0; + { + std::lock_guard lock(session->clipboard_mutex); + if (!session->remote_clip_data_locked) + return; + id = session->remote_clip_data_id; + session->remote_clip_data_locked = false; + session->remote_clip_data_id = 0; + } + + CLIPRDR_UNLOCK_CLIPBOARD_DATA unlockData{}; + unlockData.common.msgType = CB_UNLOCK_CLIPDATA; + unlockData.clipDataId = id; + cliprdr->ClientUnlockClipboardData(cliprdr, &unlockData); +} + UINT request_next_remote_file_chunk(CliprdrClientContext* cliprdr, CxRdpSession* session) { if (!cliprdr || !session || !cliprdr->ClientFileContentsRequest) @@ -856,6 +928,7 @@ UINT request_next_remote_file_chunk(CliprdrClientContext* cliprdr, CxRdpSession* CLIPRDR_FILE_CONTENTS_REQUEST req{}; bool hasWork = false; + bool shouldUnlock = false; std::vector completedPaths; { @@ -886,10 +959,15 @@ UINT request_next_remote_file_chunk(CliprdrClientContext* cliprdr, CxRdpSession* req.common.msgType = CB_FILECONTENTS_REQUEST; req.streamId = ++session->remote_file_stream_id; req.listIndex = entry.remote_index; - if (!entry.size_known) + if (!entry.size_requested) { + // Always open the remote file stream with a FILECONTENTS_SIZE + // request first: MS-RDPECLIP 3.1.5.4.5 calls the size a + // prerequisite for the contents, and rdpclip associates the + // server-side file handle with the streamId it first sees. req.dwFlags = FILECONTENTS_SIZE; req.cbRequested = 8; + entry.size_requested = true; session->remote_file_requesting_size = true; } else @@ -901,6 +979,11 @@ UINT request_next_remote_file_chunk(CliprdrClientContext* cliprdr, CxRdpSession* req.cbRequested = static_cast(remaining < CX_CLIPRDR_FILE_CHUNK_SIZE ? remaining : CX_CLIPRDR_FILE_CHUNK_SIZE); session->remote_file_requesting_size = false; } + if (session->remote_clip_data_locked) + { + req.haveClipDataId = TRUE; + req.clipDataId = session->remote_clip_data_id; + } hasWork = true; break; } @@ -910,12 +993,16 @@ UINT request_next_remote_file_chunk(CliprdrClientContext* cliprdr, CxRdpSession* completedPaths = session->remote_clipboard_top_level_paths; session->remote_clipboard_top_level_paths.clear(); session->remote_clipboard_files.clear(); + shouldUnlock = session->remote_clip_data_locked; } } if (hasWork) return cliprdr->ClientFileContentsRequest(cliprdr, &req); + if (shouldUnlock) + unlock_remote_clip_data(cliprdr, session); + if (!completedPaths.empty()) { notify_status(session, "RDP clipboard remote files downloaded."); @@ -2062,9 +2149,11 @@ UINT cx_cliprdr_server_capabilities(CliprdrClientContext* cliprdr, const CLIPRDR { std::ostringstream message; message << "RDP clipboard server capabilities received."; + uint32_t serverFlags = 0; if (capabilities && capabilities->cCapabilitiesSets > 0 && capabilities->capabilitySets) { const auto* general = reinterpret_cast(capabilities->capabilitySets); + serverFlags = general->generalFlags; message << " flags=0x" << std::hex << general->generalFlags; } notify_status(session, message.str().c_str()); @@ -2072,6 +2161,7 @@ UINT cx_cliprdr_server_capabilities(CliprdrClientContext* cliprdr, const CLIPRDR { std::lock_guard lock(session->clipboard_mutex); session->client_capabilities_sent = false; + session->server_clipboard_flags = serverFlags; } } @@ -2170,9 +2260,22 @@ UINT cx_cliprdr_server_format_list(CliprdrClientContext* cliprdr, const CLIPRDR_ { if (session && formatList->numFormats == 0) notify_clipboard_text(session, ""); + if (session) + unlock_remote_clip_data(cliprdr, session); return CHANNEL_RC_OK; } + // Lock the server's file list before pulling descriptors so the later + // FILECONTENTS requests can reference the clipDataId (rdpclip requires + // it once CB_CAN_LOCK_CLIPDATA was negotiated by both sides). + if (session) + { + if (requestedFiles) + lock_remote_clip_data(cliprdr, session); + else + unlock_remote_clip_data(cliprdr, session); + } + return send_client_format_data_request(cliprdr, selectedFormat); } @@ -2688,9 +2791,16 @@ UINT cx_cliprdr_server_file_contents_response( if ((fileContentsResponse->common.msgFlags & CB_RESPONSE_FAIL) != 0) { - std::lock_guard lock(session->clipboard_mutex); - session->remote_clipboard_files.clear(); - session->remote_clipboard_top_level_paths.clear(); + bool wasLocked = false; + { + std::lock_guard lock(session->clipboard_mutex); + session->remote_clipboard_files.clear(); + session->remote_clipboard_top_level_paths.clear(); + wasLocked = session->remote_clip_data_locked; + } + notify_status(session, "RDP clipboard remote file contents request failed."); + if (wasLocked) + unlock_remote_clip_data(cliprdr, session); return CHANNEL_RC_OK; } @@ -2775,6 +2885,8 @@ void initialize_cliprdr(CxRdpSession* session, CliprdrClientContext* cliprdr) session->remote_clipboard_top_level_paths.clear(); session->remote_file_download_index = 0; session->remote_file_requesting_size = false; + session->remote_clip_data_locked = false; + session->remote_clip_data_id = 0; } cliprdr->custom = session; @@ -2817,6 +2929,8 @@ void uninitialize_cliprdr(CxRdpSession* session, CliprdrClientContext* cliprdr) session->remote_clipboard_top_level_paths.clear(); session->remote_file_download_index = 0; session->remote_file_requesting_size = false; + session->remote_clip_data_locked = false; + session->remote_clip_data_id = 0; } } @@ -3233,8 +3347,13 @@ BOOL cx_begin_paint(rdpContext* context) if (!context || !context->gdi) return FALSE; + // A failed gdi_resize leaves gdi->primary null; FreeRDP only logs a + // warning for a FALSE BeginPaint, so guard the whole chain instead of + // crashing the decode loop. auto* gdi = context->gdi; - gdi->primary->hdc->hwnd->invalid->null = TRUE; + auto* primary = gdi->primary; + if (primary && primary->hdc && primary->hdc->hwnd && primary->hdc->hwnd->invalid) + primary->hdc->hwnd->invalid->null = TRUE; return TRUE; } @@ -3249,16 +3368,27 @@ bool push_frame(rdpContext* context) if (!session) return false; + // Publish through the bitmap that OWNS the buffer, never the cached + // gdi->primary_buffer. FreeRDP's gdi_init_primary assigns + // primary_buffer before its final allocations, and its failure path + // frees the bitmap without clearing the cached pointer, so after a + // failed gdi_resize the cached value dangles while gdi->primary is + // null. The bitmap data can only be freed together with gdi->primary + // (gdi_resize nulls it first, gdi_free drops the whole struct), so + // validating through the bitmap turns every such state into a skipped + // frame instead of an access violation in the host copy loop. auto* gdi = context->gdi; - if (!gdi->primary_buffer || gdi->width <= 0 || gdi->height <= 0) + auto* primary = gdi->primary; + if (!primary || !primary->bitmap) + return false; + + const auto* source = static_cast(primary->bitmap->data); + if (!source || gdi->width <= 0 || gdi->height <= 0) return false; const int width = static_cast(gdi->width); const int height = static_cast(gdi->height); const int stride = width * 4; - const auto* source = static_cast(gdi->primary_buffer); - if (!source) - return false; std::lock_guard lock(session->callback_mutex); if (session->frame_callback) @@ -3400,7 +3530,34 @@ BOOL cx_desktop_resize(rdpContext* context) return FALSE; if (!gdi_resize(context->gdi, width, height)) - return FALSE; + { + auto* session = get_session(context); + // Destructive failure: gdi_resize freed the old surface but + // gdi_init_primary failed, leaving gdi->primary null, + // gdi->primary_buffer dangling at the freed bitmap data and + // gdi->width/height already at the new size - the next + // push_frame would hand freed memory to the host (the access + // violation in CopyDirtyRectFromNative seen during resolution + // switches). Rebuild the GDI surface in place: the settings + // already carry the new size, and the EGFX pipeline must be + // re-bound because gfx->custom still references the broken + // struct. The abandoned struct leaks its DC - acceptable on this + // rare path compared with a dead or crashing session. + if (context->gdi->primary != nullptr || !context->instance) + return FALSE; + + unbind_gfx_pipeline(session, context); + if (session) + notify_status(session, "RDP display surface lost; rebuilding GDI surface."); + if (!gdi_init(context->instance, PIXEL_FORMAT_BGRA32)) + { + if (session) + notify_status(session, "RDP display surface rebuild failed; closing the session."); + freerdp_abort_connect(context->instance); + return FALSE; + } + bind_gfx_pipeline(session, context); + } if (auto* session = get_session(context)) {