FreeRDP
Loading...
Searching...
No Matches
win_shadow.c
1
18
19#include <windows.h>
20#include <winuser.h>
21
22#include <winpr/crt.h>
23#include <winpr/synch.h>
24#include <winpr/sysinfo.h>
25
26#include <freerdp/log.h>
27#include <freerdp/codec/color.h>
28#include <freerdp/codec/region.h>
29#include <freerdp/server/server-common.h>
30
31#include "win_shadow.h"
32#include "win_sas.h"
33#include "win_audio.h"
34
35#if defined(CHANNEL_CLIPRDR_SERVER)
36#include "win_shadow_cliprdr.h"
37#endif
38
39#define TAG SERVER_TAG("shadow.win")
40
41/* https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-mouse_event
42 * does not mention this flag is only supported if building for _WIN32_WINNT >= 0x0600
43 */
44#ifndef MOUSEEVENTF_HWHEEL
45#define MOUSEEVENTF_HWHEEL 0x1000
46#endif
47
48/* The desktop this thread opened to follow the input desktop, if any */
49static WINPR_TLS HDESK win_shadow_thread_desktop = nullptr;
50
51/* Moves the calling thread to the input desktop when that changed: SendInput
52 * and DXGI desktop duplication only work there. The input desktop is the
53 * user's (Default) or, as SYSTEM on the console session (the service mode),
54 * the secure one (Winlogon: the logon and lock screens, UAC prompts). A user
55 * process cannot open the secure desktop and stays where it is. Returns TRUE
56 * when the thread moved. */
57WINPR_ATTR_NODISCARD
58static BOOL win_shadow_follow_input_desktop(void)
59{
60 WCHAR inputName[64] = WINPR_C_ARRAY_INIT;
61 WCHAR threadName[64] = WINPR_C_ARRAY_INIT;
62 HDESK input = OpenInputDesktop(0, FALSE, GENERIC_ALL);
63
64 if (!input)
65 return FALSE;
66
67 if (!GetUserObjectInformationW(input, UOI_NAME, inputName, sizeof(inputName), nullptr))
68 WLog_WARN(TAG, "GetUserObjectInformationW(input desktop, UOI_NAME) failed: 0x%08lX",
69 GetLastError());
70 if (!GetUserObjectInformationW(GetThreadDesktop(GetCurrentThreadId()), UOI_NAME, threadName,
71 sizeof(threadName), nullptr))
72 WLog_WARN(TAG, "GetUserObjectInformationW(thread desktop, UOI_NAME) failed: 0x%08lX",
73 GetLastError());
74
75 if (_wcsicmp(inputName, threadName) == 0)
76 {
77 (void)CloseDesktop(input);
78 return FALSE;
79 }
80
81 if (!SetThreadDesktop(input))
82 {
83 WLog_WARN(TAG, "SetThreadDesktop(%ls) failed: 0x%08lX", inputName, GetLastError());
84 (void)CloseDesktop(input);
85 return FALSE;
86 }
87
88 /* the desktop GetThreadDesktop() gave first is not ours to close */
89 if (win_shadow_thread_desktop)
90 (void)CloseDesktop(win_shadow_thread_desktop);
91 win_shadow_thread_desktop = input;
92 WLog_INFO(TAG, "thread %lu follows the input desktop from %ls to %ls", GetCurrentThreadId(),
93 threadName, inputName);
94 return TRUE;
95}
96
97/* SendInput, without ending the session when Windows refuses the event: it
98 * does while the input desktop switches (the secure desktop comes or goes)
99 * and for a window above our integrity level, and FreeRDP drops the client
100 * when an input handler fails. The failure log names only the input kind:
101 * the key codes themselves must never reach the log. */
102static void win_shadow_send_input(const char* what, INPUT* event)
103{
104 WINPR_ASSERT(what);
105 WINPR_ASSERT(event);
106
107 if (SendInput(1, event, sizeof(INPUT)) == 0)
108 WLog_WARN(TAG, "%s: SendInput refused the event (0x%08lX), it is dropped", what,
109 GetLastError());
110}
111
112/* UIPI: a process below High integrity (a scheduled task defaults to Medium)
113 * may not send input to windows of a higher integrity level (an elevated
114 * foreground application), and SendInput does not report the refusal: it
115 * returns success and does not set the last error. The screen capture is
116 * unaffected, so such a shadow serves a perfectly fine picture while every
117 * keystroke and mouse click into an elevated window is silently dropped.
118 * Say so at startup: this turns a "keyboard and mouse dead while picture is
119 * fine" report into a log line readable in seconds.
120 * https://learn.microsoft.com/en-us/windows/win32/secauthz/how-uipi-works */
121static void win_shadow_check_input_integrity(void)
122{
123 HANDLE token = nullptr;
124 DWORD length = 0;
125
126 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token))
127 {
128 WLog_WARN(TAG, "OpenProcessToken failed: cannot read the process integrity level (0x%08lX)",
129 GetLastError());
130 return;
131 }
132
133 /* the integrity level RID is the last sub-authority of the mandatory
134 * label SID (S-1-16-<rid>) */
135 if (!GetTokenInformation(token, TokenIntegrityLevel, nullptr, 0, &length) &&
136 (GetLastError() == ERROR_INSUFFICIENT_BUFFER))
137 {
138 PTOKEN_MANDATORY_LABEL label = (PTOKEN_MANDATORY_LABEL)malloc(length);
139
140 if (!label)
141 WLog_WARN(TAG, "out of memory: cannot read the process integrity level");
142 else
143 {
144 if (GetTokenInformation(token, TokenIntegrityLevel, label, length, &length) &&
145 label->Label.Sid)
146 {
147 const PSID sid = label->Label.Sid;
148 const DWORD rid = *GetSidSubAuthority(sid, *GetSidSubAuthorityCount(sid) - 1);
149
150 if (rid < SECURITY_MANDATORY_HIGH_RID)
151 WLog_WARN(TAG,
152 "process is NOT elevated (integrity level 0x%04lX, Medium or lower): "
153 "injected input to elevated windows will be silently dropped by UIPI "
154 "- run the shadow elevated (e.g. scheduled task RunLevel Highest) or "
155 "expect \"keyboard and mouse dead while picture is fine\" reports",
156 rid);
157 else
158 WLog_DBG(TAG,
159 "process integrity level 0x%04lX: injected input reaches elevated "
160 "windows",
161 rid);
162 }
163 else
164 WLog_WARN(
165 TAG,
166 "GetTokenInformation(TokenIntegrityLevel) failed: cannot read the process "
167 "integrity level (0x%08lX)",
168 GetLastError());
169
170 free(label);
171 }
172 }
173
174 (void)CloseHandle(token);
175}
176
177/* Ctrl+Alt+Del: asks freerdp-shadow-service for the secure attention
178 * sequence (win_sas.h) */
179static void win_shadow_send_sas(void)
180{
181 HANDLE event = OpenEventW(EVENT_MODIFY_STATE, FALSE, WIN_SHADOW_SAS_EVENT);
182
183 if (!event)
184 {
185 WLog_WARN(TAG, "Ctrl+Alt+Del: no freerdp-shadow-service to send it (0x%08lX)",
186 GetLastError());
187 return;
188 }
189
190 if (SetEvent(event))
191 WLog_INFO(TAG,
192 "Ctrl+Alt+Del: asked freerdp-shadow-service for the secure attention sequence");
193 else
194 WLog_WARN(TAG, "Ctrl+Alt+Del: SetEvent failed (0x%08lX)", GetLastError());
195 (void)CloseHandle(event);
196}
197
198static BOOL win_shadow_input_synchronize_event(rdpShadowSubsystem* subsystem,
199 rdpShadowClient* client, UINT32 flags)
200{
201 WLog_WARN(TAG, "TODO: Implement!");
202 return TRUE;
203}
204
205static BOOL win_shadow_input_keyboard_event(rdpShadowSubsystem* subsystem, rdpShadowClient* client,
206 UINT16 flags, UINT8 code)
207{
208 winShadowSubsystem* win = (winShadowSubsystem*)subsystem;
209 const BOOL down = (flags & KBD_FLAGS_RELEASE) == 0;
210
211 WINPR_ASSERT(win);
212 (void)win_shadow_follow_input_desktop();
213
214 /* scan codes: Ctrl 0x1D, Alt 0x38 (the right ones extended), Delete
215 * 0x53 (the keypad's not extended); Windows takes either Delete */
216 if (code == 0x1D)
217 win->ctrlDown = down;
218 else if (code == 0x38)
219 win->altDown = down;
220 else if ((code == 0x53) && win->ctrlDown && win->altDown)
221 {
222 if (down)
223 win_shadow_send_sas();
224 return TRUE; /* never typed into the desktop */
225 }
226 INPUT event = WINPR_C_ARRAY_INIT;
227 event.type = INPUT_KEYBOARD;
228 KEYBDINPUT* ki =
229#if defined(NONAMELESSUNION)
230 &event.u.ki;
231#else
232 &event.ki;
233#endif
234
235 ki->wVk = 0;
236 ki->wScan = code;
237 ki->dwFlags = KEYEVENTF_SCANCODE;
238 ki->dwExtraInfo = 0;
239 ki->time = 0;
240
241 if (flags & KBD_FLAGS_RELEASE)
242 ki->dwFlags |= KEYEVENTF_KEYUP;
243
244 if (flags & KBD_FLAGS_EXTENDED)
245 ki->dwFlags |= KEYEVENTF_EXTENDEDKEY;
246
247 win_shadow_send_input("keyboard", &event);
248 return TRUE;
249}
250
251static BOOL win_shadow_input_unicode_keyboard_event(rdpShadowSubsystem* subsystem,
252 rdpShadowClient* client, UINT16 flags,
253 UINT16 code)
254{
255 (void)win_shadow_follow_input_desktop();
256 INPUT event = WINPR_C_ARRAY_INIT;
257 event.type = INPUT_KEYBOARD;
258 KEYBDINPUT* ki =
259#if defined(NONAMELESSUNION)
260 &event.u.ki;
261#else
262 &event.ki;
263#endif
264 ki->wVk = 0;
265 ki->wScan = code;
266 ki->dwFlags = KEYEVENTF_UNICODE;
267 ki->dwExtraInfo = 0;
268 ki->time = 0;
269
270 if (flags & KBD_FLAGS_RELEASE)
271 ki->dwFlags |= KEYEVENTF_KEYUP;
272
273 win_shadow_send_input("unicode keyboard", &event);
274 return TRUE;
275}
276
277static BOOL win_shadow_input_mouse_event(rdpShadowSubsystem* subsystem, rdpShadowClient* client,
278 UINT16 flags, UINT16 x, UINT16 y)
279{
280 (void)win_shadow_follow_input_desktop();
281 INPUT event = WINPR_C_ARRAY_INIT;
282 float width;
283 float height;
284 MOUSEINPUT* mi =
285#if defined(NONAMELESSUNION)
286 &event.u.mi;
287#else
288 &event.mi;
289#endif
290
291 event.type = INPUT_MOUSE;
292
293 if (flags & (PTR_FLAGS_WHEEL | PTR_FLAGS_HWHEEL))
294 {
295 if (flags & PTR_FLAGS_WHEEL)
296 mi->dwFlags = MOUSEEVENTF_WHEEL;
297 else
298 mi->dwFlags = MOUSEEVENTF_HWHEEL;
299 mi->mouseData = flags & WheelRotationMask;
300
301 if (flags & PTR_FLAGS_WHEEL_NEGATIVE)
302 mi->mouseData *= -1;
303
304 win_shadow_send_input("mouse", &event);
305 }
306 else
307 {
308 /* Normalize against the captured framebuffer, not GetSystemMetrics:
309 * this process is not marked DPI aware, so the metrics are
310 * virtualized (scaled down) on a desktop with display scaling while
311 * the client coordinates are physical pixels of the primary screen
312 * the subsystem geometry describes. */
313 width = (float)((winShadowSubsystem*)subsystem)->width;
314 height = (float)((winShadowSubsystem*)subsystem)->height;
315 mi->dx = (LONG)((float)x * (65535.0f / width));
316 mi->dy = (LONG)((float)y * (65535.0f / height));
317 mi->dwFlags = MOUSEEVENTF_ABSOLUTE;
318
319 if (flags & PTR_FLAGS_MOVE)
320 {
321 mi->dwFlags |= MOUSEEVENTF_MOVE;
322 win_shadow_send_input("mouse", &event);
323 }
324
325 mi->dwFlags = MOUSEEVENTF_ABSOLUTE;
326
327 if (flags & PTR_FLAGS_BUTTON1)
328 {
329 if (flags & PTR_FLAGS_DOWN)
330 mi->dwFlags |= MOUSEEVENTF_LEFTDOWN;
331 else
332 mi->dwFlags |= MOUSEEVENTF_LEFTUP;
333
334 win_shadow_send_input("mouse", &event);
335 }
336 else if (flags & PTR_FLAGS_BUTTON2)
337 {
338 if (flags & PTR_FLAGS_DOWN)
339 mi->dwFlags |= MOUSEEVENTF_RIGHTDOWN;
340 else
341 mi->dwFlags |= MOUSEEVENTF_RIGHTUP;
342
343 win_shadow_send_input("mouse", &event);
344 }
345 else if (flags & PTR_FLAGS_BUTTON3)
346 {
347 if (flags & PTR_FLAGS_DOWN)
348 mi->dwFlags |= MOUSEEVENTF_MIDDLEDOWN;
349 else
350 mi->dwFlags |= MOUSEEVENTF_MIDDLEUP;
351
352 win_shadow_send_input("mouse", &event);
353 }
354 }
355
356 return TRUE;
357}
358
359static BOOL win_shadow_input_extended_mouse_event(rdpShadowSubsystem* subsystem,
360 rdpShadowClient* client, UINT16 flags, UINT16 x,
361 UINT16 y)
362{
363 (void)win_shadow_follow_input_desktop();
364 INPUT event = WINPR_C_ARRAY_INIT;
365 float width;
366 float height;
367 MOUSEINPUT* mi =
368#if defined(NONAMELESSUNION)
369 &event.u.mi;
370#else
371 &event.mi;
372#endif
373
374 if ((flags & PTR_XFLAGS_BUTTON1) || (flags & PTR_XFLAGS_BUTTON2))
375 {
376 event.type = INPUT_MOUSE;
377
378 if (flags & PTR_FLAGS_MOVE)
379 {
380 /* same as above: the physical framebuffer, not virtualized
381 * GetSystemMetrics values, is the coordinate domain */
382 width = (float)((winShadowSubsystem*)subsystem)->width;
383 height = (float)((winShadowSubsystem*)subsystem)->height;
384 mi->dx = (LONG)((float)x * (65535.0f / width));
385 mi->dy = (LONG)((float)y * (65535.0f / height));
386 mi->dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;
387 win_shadow_send_input("extended mouse", &event);
388 }
389
390 mi->dx = mi->dy = mi->dwFlags = 0;
391
392 if (flags & PTR_XFLAGS_DOWN)
393 mi->dwFlags |= MOUSEEVENTF_XDOWN;
394 else
395 mi->dwFlags |= MOUSEEVENTF_XUP;
396
397 if (flags & PTR_XFLAGS_BUTTON1)
398 mi->mouseData = XBUTTON1;
399 else if (flags & PTR_XFLAGS_BUTTON2)
400 mi->mouseData = XBUTTON2;
401
402 win_shadow_send_input("extended mouse", &event);
403 }
404
405 return TRUE;
406}
407
408static int win_shadow_invalidate_region(winShadowSubsystem* subsystem, int x, int y, int width,
409 int height)
410{
411 rdpShadowServer* server = subsystem->base.server;
412 rdpShadowSurface* surface = server->surface;
413 RECTANGLE_16 invalidRect = { .left = x, .top = y, .right = x + width, .bottom = y + height };
414 EnterCriticalSection(&(surface->lock));
415 region16_union_rect(&(surface->invalidRegion), &(surface->invalidRegion), &invalidRect);
416 LeaveCriticalSection(&(surface->lock));
417 return 1;
418}
419
420static int win_shadow_surface_copy(winShadowSubsystem* subsystem)
421{
422 int x, y;
423 int width;
424 int height;
425 int status = 1;
426 int nDstStep = 0;
427 DWORD DstFormat;
428 BYTE* pDstData = nullptr;
429 rdpShadowServer* server;
430 rdpShadowSurface* surface;
431 RECTANGLE_16 surfaceRect;
432 RECTANGLE_16 invalidRect;
433 const RECTANGLE_16* extents;
434 server = subsystem->base.server;
435 surface = server->surface;
436
437 if (ArrayList_Count(server->clients) < 1)
438 return 1;
439
440 surfaceRect.left = surface->x;
441 surfaceRect.top = surface->y;
442 surfaceRect.right = surface->x + surface->width;
443 surfaceRect.bottom = surface->y + surface->height;
444 region16_intersect_rect(&(surface->invalidRegion), &(surface->invalidRegion), &surfaceRect);
445
446 if (region16_is_empty(&(surface->invalidRegion)))
447 return 1;
448
449 extents = region16_extents(&(surface->invalidRegion));
450 CopyMemory(&invalidRect, extents, sizeof(RECTANGLE_16));
451 shadow_capture_align_clip_rect(&invalidRect, &surfaceRect);
452 x = invalidRect.left;
453 y = invalidRect.top;
454 width = invalidRect.right - invalidRect.left;
455 height = invalidRect.bottom - invalidRect.top;
456
457 /* The alignment to 16 pixels may reach past the captured screen when its
458 * size is not a multiple of 16 (1600x900): copy what was captured only */
459 if (x + width > subsystem->width)
460 width = subsystem->width - x;
461 if (y + height > subsystem->height)
462 height = subsystem->height - y;
463 if ((width <= 0) || (height <= 0))
464 {
465 region16_clear(&(surface->invalidRegion));
466 return 1;
467 }
468
469 if (0)
470 {
471 x = 0;
472 y = 0;
473 width = surface->width;
474 height = surface->height;
475 }
476
477 WLog_INFO(TAG, "SurfaceCopy x: %d y: %d width: %d height: %d right: %d bottom: %d", x, y, width,
478 height, x + width, y + height);
479#if defined(WITH_WDS_API)
480 {
481 rdpGdi* gdi;
482 shwContext* shw;
483 rdpContext* context;
484
485 WINPR_ASSERT(subsystem);
486 shw = subsystem->shw;
487 WINPR_ASSERT(shw);
488
489 context = &shw->common.context;
490 WINPR_ASSERT(context);
491
492 gdi = context->gdi;
493 WINPR_ASSERT(gdi);
494
495 /* The inner framebuffer is owned by the WDS attendee client. It can be
496 * absent before its first frame, or smaller than the surface while a
497 * desktop resize is in flight: copying past its bounds crashes the
498 * server inside freerdp_image_copy_no_overlap's memcpy. Clamp the copy
499 * to what is actually there and skip the frame when nothing overlaps. */
500 if (!gdi || !gdi->primary_buffer || (gdi->width <= 0) || (gdi->height <= 0))
501 {
502 region16_clear(&(surface->invalidRegion));
503 return 0;
504 }
505 if (x + width > gdi->width)
506 width = gdi->width - x;
507 if (y + height > gdi->height)
508 height = gdi->height - y;
509 if ((width <= 0) || (height <= 0))
510 {
511 region16_clear(&(surface->invalidRegion));
512 return 1;
513 }
514
515 pDstData = gdi->primary_buffer;
516 nDstStep = gdi->width * 4;
517 DstFormat = gdi->dstFormat;
518 }
519#elif defined(WITH_DXGI_1_2)
520 DstFormat = PIXEL_FORMAT_BGRX32;
521 status = win_shadow_dxgi_fetch_frame_data(subsystem, &pDstData, &nDstStep, x, y, width, height);
522#endif
523
524 if (status <= 0)
525 return status;
526
527#if defined(WITH_WDS_API)
528 /* WDS: the GDI primary buffer spans the whole desktop */
529 const int srcX = x;
530 const int srcY = y;
531#elif defined(WITH_DXGI_1_2)
532 /* DXGI: fetch_frame_data() copies the region to the staging texture
533 * origin, so the source offset is always the origin */
534 const int srcX = 0;
535 const int srcY = 0;
536#else
537 /* no capture backend compiled in: keep the previous behavior */
538 const int srcX = x;
539 const int srcY = y;
540#endif
541 if (!freerdp_image_copy_no_overlap(surface->data, surface->format, surface->scanline, x, y,
542 width, height, pDstData, DstFormat, nDstStep, srcX, srcY,
543 nullptr, FREERDP_FLIP_NONE))
544 return ERROR_INTERNAL_ERROR;
545
546 /* shadow_subsystem_frame_update() publishes the frame to all subscriber
547 * clients and waits until every one of them consumed it. That wait must
548 * not happen while the server clients list is locked: the listener
549 * thread needs this lock in shadow_client_accepted() (ArrayList_Append)
550 * and shadow_server_check_peer_restrictions() (ArrayList Count), so
551 * holding it across an unresponsive subscriber would stop accepting new
552 * connections entirely. The frame publication iterates the update
553 * event's own subscriber list, not the server clients list, so the lock
554 * is not needed here at all. */
555 shadow_subsystem_frame_update(&subsystem->base);
556 region16_clear(&(surface->invalidRegion));
557 return 1;
558}
559
560#if defined(WITH_WDS_API)
561
562static DWORD WINAPI win_shadow_subsystem_thread(LPVOID arg)
563{
564 winShadowSubsystem* subsystem = (winShadowSubsystem*)arg;
565 DWORD status;
566 DWORD nCount;
567 HANDLE events[32];
568 HANDLE StopEvent;
569 StopEvent = subsystem->base.server->StopEvent;
570 nCount = 0;
571 events[nCount++] = StopEvent;
572 events[nCount++] = subsystem->RdpUpdateEnterEvent;
573
574 while (1)
575 {
576 status = WaitForMultipleObjects(nCount, events, FALSE, INFINITE);
577
578 if (WaitForSingleObject(StopEvent, 0) == WAIT_OBJECT_0)
579 {
580 break;
581 }
582
583 if (WaitForSingleObject(subsystem->RdpUpdateEnterEvent, 0) == WAIT_OBJECT_0)
584 {
585 /* the shared desktop can be resized between two updates: keep the
586 * shadow screen in step before the copy, as the DXGI variant does */
587 (void)win_shadow_check_resize(subsystem);
588 win_shadow_surface_copy(subsystem);
589 (void)ResetEvent(subsystem->RdpUpdateEnterEvent);
590 (void)SetEvent(subsystem->RdpUpdateLeaveEvent);
591 }
592 }
593
594 ExitThread(0);
595 return 0;
596}
597
598#elif defined(WITH_DXGI_1_2)
599
600static DWORD WINAPI win_shadow_subsystem_thread(LPVOID arg)
601{
602 winShadowSubsystem* subsystem = (winShadowSubsystem*)arg;
603 DWORD status;
604 DWORD nCount;
605 UINT64 cTime;
606 DWORD dwTimeout;
607 DWORD dwInterval;
608 UINT64 frameTime;
609 HANDLE events[32];
610 HANDLE StopEvent;
611 StopEvent = subsystem->base.server->StopEvent;
612 wMessagePipe* MsgPipe = subsystem->base.MsgPipe;
613 WINPR_ASSERT(MsgPipe);
614 nCount = 0;
615 events[nCount++] = StopEvent;
616 events[nCount++] = MessageQueue_Event(MsgPipe->In);
617 subsystem->base.captureFrameRate = 120;
618 dwInterval = 1000 / subsystem->base.captureFrameRate;
619 frameTime = GetTickCount64() + dwInterval;
620 BOOL refresh = FALSE;
621
622 while (1)
623 {
624 dwTimeout = INFINITE;
625 cTime = GetTickCount64();
626 dwTimeout = (DWORD)((cTime > frameTime) ? 0 : frameTime - cTime);
627 status = WaitForMultipleObjects(nCount, events, FALSE, dwTimeout);
628
629 if (WaitForSingleObject(StopEvent, 0) == WAIT_OBJECT_0)
630 {
631 break;
632 }
633
634 /* a client asks for the whole screen (its graphics channel is
635 * ready, or it asked to refresh), as the X11 subsystem answers */
636 wMessage message = WINPR_C_ARRAY_INIT;
637 BOOL quit = FALSE;
638 while (!quit && MessageQueue_Peek(MsgPipe->In, &message, TRUE))
639 {
640 quit = (message.id == WMQ_QUIT);
641 if (message.id == SHADOW_MSG_IN_REFRESH_REQUEST_ID)
642 refresh = TRUE;
643 if (message.Free)
644 message.Free(&message);
645 }
646 if (quit)
647 break;
648
649 if ((status == WAIT_TIMEOUT) || (GetTickCount64() > frameTime))
650 {
651 int dxgi_status = win_shadow_check_resize(subsystem);
652
653 /* apply a pending desktop display mode change before the
654 * restart/acquire below; on fatal resize error (<0) skip this
655 * round, the next tick retries */
656 if (dxgi_status >= 0)
657 {
658 /* a desktop switch (logon, lock screen, UAC), a refresh request,
659 * or no duplication yet: duplicate the output again on the input
660 * desktop, and send all of it. DXGI reports changes only: on a
661 * desktop that does not change, a new client would otherwise wait
662 * for its first picture until something moves; a new duplication
663 * starts with the whole desktop image. A missing duplication is
664 * retried from dxgiRetryTime on, not on every pass: every
665 * WIN_SHADOW_DXGI_DENIED_RETRY_MS while a desktop this process
666 * may not capture is active, every WIN_SHADOW_DXGI_INIT_RETRY_MS
667 * after a failure which does not recover by itself (no D3D11
668 * device, no duplicatable output) */
669 const BOOL followed = win_shadow_follow_input_desktop();
670 const BOOL retry = !subsystem->dxgiOutputDuplication &&
671 (GetTickCount64() >= subsystem->dxgiRetryTime);
672 /* a desktop resize leaves the duplication behind on the old
673 * geometry: win_shadow_check_resize has just resized the shadow
674 * screen, so the next frame would be copied from objects of the
675 * previous size. Duplicate the output again on the new one and
676 * send all of it, as for a desktop switch. */
677 const BOOL resized = (dxgi_status > 0);
678 if (followed || refresh || retry || resized)
679 {
680 refresh = FALSE;
681 if (win_shadow_dxgi_restart_duplication(subsystem) > 0)
682 (void)win_shadow_invalidate_region(subsystem, 0, 0, subsystem->width,
683 subsystem->height);
684 }
685
686 /* the resize status only gates this block; without a duplication
687 * (capture paused, or a failed restart) there is no frame */
688 dxgi_status = subsystem->dxgiOutputDuplication
689 ? win_shadow_dxgi_get_next_frame(subsystem)
690 : 0;
691
692 /* a frame without dirty rectangles of its own (the first of a
693 * new duplication) still holds the whole desktop image: copy
694 * what is marked invalid already */
695 if (dxgi_status > 0)
696 {
697 const int changed = win_shadow_dxgi_get_invalid_region(subsystem);
698 rdpShadowSurface* surface = subsystem->base.server->surface;
699 WINPR_ASSERT(surface);
700 EnterCriticalSection(&(surface->lock));
701 const BOOL pending = !region16_is_empty(&(surface->invalidRegion));
702 LeaveCriticalSection(&(surface->lock));
703 dxgi_status = ((changed > 0) || ((changed == 0) && pending)) ? 1 : changed;
704 }
705 }
706
707 if (dxgi_status > 0)
708 win_shadow_surface_copy(subsystem);
709
710 /* Follow the encoder capture rate suggestion, like the X11 and Mac
711 * subsystems do: shadow_encoder_create_frame_id() lowers the
712 * preferred fps while frames are still in flight (not yet
713 * acknowledged by the client). This subsystem hardcoded the
714 * capture rate and never read the suggestion, so a slow client
715 * could not throttle the capture and in-flight frames (latency)
716 * accumulated without bound. Use the lowest suggestion of all
717 * connected clients. */
718 UINT32 captureFrameRate = UINT32_MAX;
719 ArrayList_Lock(subsystem->base.server->clients);
720 const UINT32 clientCount = ArrayList_Count(subsystem->base.server->clients);
721 for (UINT32 index = 0; index < clientCount; index++)
722 {
723 const rdpShadowClient* client =
724 (rdpShadowClient*)ArrayList_GetItem(subsystem->base.server->clients, index);
725
726 if (client && client->encoder)
727 {
728 const UINT32 suggestion = shadow_encoder_preferred_fps(client->encoder);
729 if (suggestion < captureFrameRate)
730 captureFrameRate = suggestion;
731 }
732 }
733 ArrayList_Unlock(subsystem->base.server->clients);
734
735 if ((captureFrameRate == UINT32_MAX) || (captureFrameRate < 1))
736 captureFrameRate = subsystem->base.captureFrameRate;
737 subsystem->base.captureFrameRate = captureFrameRate;
738
739 dwInterval = 1000 / subsystem->base.captureFrameRate;
740 frameTime += dwInterval;
741 }
742 }
743
744 ExitThread(0);
745 return 0;
746}
747
748#endif
749
750static UINT32 win_shadow_enum_monitors(MONITOR_DEF* monitors, UINT32 maxMonitors)
751{
752 HDC hdc;
753 int index;
754 int desktopWidth;
755 int desktopHeight;
756 DWORD iDevNum = 0;
757 int numMonitors = 0;
758 MONITOR_DEF* monitor;
759 DISPLAY_DEVICE displayDevice = WINPR_C_ARRAY_INIT;
760
761 displayDevice.cb = sizeof(DISPLAY_DEVICE);
762
763 /* Skip adapters which are not attached to the desktop: on machines with
764 * a BMC/management GPU (e.g. ASPEED) listed as device 0 while the real GPU
765 * is attached later in the list, CreateDC for the unattached device fails
766 * and the monitor rectangle stays zeroed, which results in a 1x1 surface. */
767 {
768 DWORD devNum = 0;
769 BOOL attached = FALSE;
770 DISPLAY_DEVICE probe = WINPR_C_ARRAY_INIT;
771 probe.cb = sizeof(DISPLAY_DEVICE);
772 while (EnumDisplayDevices(nullptr, devNum, &probe, 0))
773 {
774 if (probe.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP)
775 {
776 attached = TRUE;
777 break;
778 }
779 devNum++;
780 probe.cb = sizeof(DISPLAY_DEVICE);
781 }
782 if (attached && (devNum != 0))
783 {
784 displayDevice.cb = sizeof(DISPLAY_DEVICE);
785 if (EnumDisplayDevices(nullptr, devNum, &displayDevice, 0))
786 iDevNum = devNum;
787 }
788 }
789
790 if (EnumDisplayDevices(nullptr, iDevNum, &displayDevice, 0))
791 {
792 hdc = CreateDC(displayDevice.DeviceName, nullptr, nullptr, nullptr);
793 desktopWidth = GetDeviceCaps(hdc, HORZRES);
794 desktopHeight = GetDeviceCaps(hdc, VERTRES);
795 index = 0;
796 numMonitors = 1;
797 monitor = &monitors[index];
798 monitor->left = 0;
799 monitor->top = 0;
800 /* right and bottom are inclusive, as the shadow server reads them */
801 monitor->right = desktopWidth - 1;
802 monitor->bottom = desktopHeight - 1;
803 monitor->flags = 1;
804 DeleteDC(hdc);
805 }
806
807 /* Fallback to the primary screen metrics if enumeration did not
808 * yield a usable rectangle, otherwise shadow_screen_new computes a
809 * 1x1 surface and clients are resized to 1x1. */
810 if ((numMonitors == 0) || (monitors[0].right <= 0) || (monitors[0].bottom <= 0))
811 {
812 monitor = &monitors[0];
813 monitor->left = 0;
814 monitor->top = 0;
815 monitor->right = GetSystemMetrics(SM_CXSCREEN) - 1;
816 monitor->bottom = GetSystemMetrics(SM_CYSCREEN) - 1;
817 monitor->flags = 1;
818 numMonitors = 1;
819 }
820
821 return numMonitors;
822}
823
824/* Win counterpart of x11_shadow_check_resize: track desktop display mode
825 * changes while the server is running. Returns 1 when the geometry
826 * changed, 0 when it did not and <0 on fatal error. */
827int win_shadow_check_resize(winShadowSubsystem* subsystem)
828{
829 WINPR_ASSERT(subsystem);
830
831 DEVMODEW dm = WINPR_C_ARRAY_INIT;
832 dm.dmSize = (WORD)sizeof(dm);
833
834 if (!EnumDisplaySettingsW(nullptr, ENUM_CURRENT_SETTINGS, &dm))
835 return 0;
836
837 /* compare unsigned: an int cast would wrap resolutions above INT_MAX */
838 if (((UINT32)dm.dmPelsWidth == (UINT32)subsystem->width) &&
839 ((UINT32)dm.dmPelsHeight == (UINT32)subsystem->height))
840 return 0;
841
842 MONITOR_DEF* virtualScreen = &(subsystem->base.virtualScreen);
843
844 /* refresh the monitor definition; a false alarm from a non-primary
845 * device bails out below to avoid per-tick flapping */
846 subsystem->base.numMonitors = win_shadow_enum_monitors(subsystem->base.monitors, 16);
847
848 if (subsystem->base.numMonitors < 1)
849 return 0;
850
851 {
852 const MONITOR_DEF* primary = &subsystem->base.monitors[0];
853 const int newWidth = primary->right - primary->left + 1;
854 const int newHeight = primary->bottom - primary->top + 1;
855
856 if ((newWidth == subsystem->width) && (newHeight == subsystem->height))
857 return 0;
858
859 /* The screen does not exist yet while the subsystem is initialized;
860 * in that case updating the geometry below is all that is needed. */
861 if (subsystem->base.server && subsystem->base.server->screen &&
862 !shadow_screen_resize(subsystem->base.server->screen))
863 return -1;
864
865 subsystem->width = newWidth;
866 subsystem->height = newHeight;
867 }
868
869 virtualScreen->left = 0;
870 virtualScreen->top = 0;
871 virtualScreen->right = subsystem->width - 1;
872 virtualScreen->bottom = subsystem->height - 1;
873 virtualScreen->flags = 1;
874
875 WLog_INFO(TAG, "desktop resized to %dx%d", subsystem->width, subsystem->height);
876 return 1;
877}
878
879static BOOL win_shadow_client_connect(rdpShadowSubsystem* subsystem, rdpShadowClient* client)
880{
881 WINPR_ASSERT(subsystem);
882 WINPR_ASSERT(client);
883
884#if defined(CHANNEL_CLIPRDR_SERVER)
885 /* cliprdr is a static channel: the join decision is final by the time
886 * ClientConnect runs (shadow_client_channels_post_connect precedes it). */
887 if (WTSVirtualChannelManagerIsChannelJoined(client->vcm, CLIPRDR_SVC_CHANNEL_NAME))
888 {
889 if (win_shadow_cliprdr_init(client) < 0)
890 return FALSE;
891 }
892#endif
893 return TRUE;
894}
895
896static void win_shadow_client_disconnect(rdpShadowSubsystem* subsystem, rdpShadowClient* client)
897{
898 WINPR_ASSERT(subsystem);
899 WINPR_ASSERT(client);
900
901#if defined(CHANNEL_CLIPRDR_SERVER)
902 win_shadow_cliprdr_uninit(client);
903#endif
904}
905
906static int win_shadow_subsystem_init(rdpShadowSubsystem* arg)
907{
908 winShadowSubsystem* subsystem = (winShadowSubsystem*)arg;
909 int status;
910 MONITOR_DEF* virtualScreen;
911
912 /* This binary carries no dpiAware manifest, so on a desktop with
913 * display scaling the process is virtualized: geometry APIs
914 * (GetSystemMetrics, display modes, the WDS capture coordinate space)
915 * report scaled-down values while the client and injected input speak
916 * physical pixels. Claim per-monitor awareness so all of them agree,
917 * falling back to system-wide awareness on older Windows. */
918#if defined(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2)
919 if (!SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) &&
920 !SetProcessDPIAware())
921 WLog_WARN(TAG, "DPI awareness setup failed: 0x%08lX", GetLastError());
922#else
923 if (!SetProcessDPIAware())
924 WLog_WARN(TAG, "DPI awareness setup failed: 0x%08lX", GetLastError());
925#endif
926
927 win_shadow_check_input_integrity();
928 subsystem->base.numMonitors = win_shadow_enum_monitors(subsystem->base.monitors, 16);
929 if (subsystem->base.numMonitors > 0)
930 {
931 const MONITOR_DEF* primary = &subsystem->base.monitors[0];
932 subsystem->width = primary->right - primary->left + 1;
933 subsystem->height = primary->bottom - primary->top + 1;
934 }
935
936 if ((subsystem->width <= 0) || (subsystem->height <= 0))
937 {
938 subsystem->width = GetSystemMetrics(SM_CXSCREEN);
939 subsystem->height = GetSystemMetrics(SM_CYSCREEN);
940 }
941#if defined(WITH_WDS_API)
942 /* The Windows Desktop Sharing API is the low performance capture path:
943 * its throughput degrades with multiple clients and high frame rates.
944 * Which capture backend a binary carries is decided at build time (the
945 * alternative, DXGI desktop duplication, is WITH_SHADOW_WIN_DXGI=ON),
946 * so a binary holding only the slow path would degrade silently: say
947 * what was built in. */
948 WLog_WARN(TAG,
949 "capture uses the Windows Desktop Sharing API: the low performance capture path, "
950 "throughput drops with multiple clients or high frame rates - build with "
951 "WITH_SHADOW_WIN_DXGI=ON for DXGI desktop duplication");
952 status = win_shadow_wds_init(subsystem);
953#elif defined(WITH_DXGI_1_2)
954 status = win_shadow_dxgi_init(subsystem);
955 if (status < 0)
956 WLog_WARN(TAG, "DXGI init failed, the capture thread retries at a low rate");
957#endif
958 virtualScreen = &(subsystem->base.virtualScreen);
959 virtualScreen->left = 0;
960 virtualScreen->top = 0;
961 virtualScreen->right = subsystem->width - 1;
962 virtualScreen->bottom = subsystem->height - 1;
963 virtualScreen->flags = 1;
964 WLog_INFO(TAG, "width: %d height: %d", subsystem->width, subsystem->height);
965
966 if (!win_shadow_audio_init(subsystem))
967 WLog_WARN(TAG, "audio: no formats to offer: no sound");
968 return 1;
969}
970
971static int win_shadow_subsystem_uninit(rdpShadowSubsystem* arg)
972{
973 winShadowSubsystem* subsystem = (winShadowSubsystem*)arg;
974
975 if (!subsystem)
976 return -1;
977
978 win_shadow_audio_uninit(subsystem);
979#if defined(WITH_WDS_API)
980 win_shadow_wds_uninit(subsystem);
981#elif defined(WITH_DXGI_1_2)
982 win_shadow_dxgi_uninit(subsystem);
983#endif
984 return 1;
985}
986
987static int win_shadow_subsystem_start(rdpShadowSubsystem* arg)
988{
989 winShadowSubsystem* subsystem = (winShadowSubsystem*)arg;
990 HANDLE thread;
991
992 if (!subsystem)
993 return -1;
994
995 if (!(thread =
996 CreateThread(nullptr, 0, win_shadow_subsystem_thread, (void*)subsystem, 0, nullptr)))
997 {
998 WLog_ERR(TAG, "Failed to create thread");
999 return -1;
1000 }
1001
1002 /* the picture works without the sound */
1003 if (!win_shadow_audio_start(subsystem))
1004 WLog_WARN(TAG, "audio: no capture thread: no sound");
1005 return 1;
1006}
1007
1008static int win_shadow_subsystem_stop(rdpShadowSubsystem* arg)
1009{
1010 winShadowSubsystem* subsystem = (winShadowSubsystem*)arg;
1011
1012 if (!subsystem)
1013 return -1;
1014
1015 win_shadow_audio_stop(subsystem);
1016 return 1;
1017}
1018
1019static void win_shadow_subsystem_free(rdpShadowSubsystem* arg)
1020{
1021 winShadowSubsystem* subsystem = (winShadowSubsystem*)arg;
1022
1023 if (!subsystem)
1024 return;
1025
1026 win_shadow_subsystem_uninit(arg);
1027 free(subsystem);
1028}
1029
1030static rdpShadowSubsystem* win_shadow_subsystem_new(void)
1031{
1032 winShadowSubsystem* subsystem;
1033 subsystem = (winShadowSubsystem*)calloc(1, sizeof(winShadowSubsystem));
1034
1035 if (!subsystem)
1036 return nullptr;
1037
1038 subsystem->base.SynchronizeEvent = win_shadow_input_synchronize_event;
1039 subsystem->base.KeyboardEvent = win_shadow_input_keyboard_event;
1040 subsystem->base.UnicodeKeyboardEvent = win_shadow_input_unicode_keyboard_event;
1041 subsystem->base.MouseEvent = win_shadow_input_mouse_event;
1042 subsystem->base.ExtendedMouseEvent = win_shadow_input_extended_mouse_event;
1043 subsystem->base.ClientConnect = win_shadow_client_connect;
1044 subsystem->base.ClientDisconnect = win_shadow_client_disconnect;
1045 return &subsystem->base;
1046}
1047
1048FREERDP_API const char* ShadowSubsystemName(void)
1049{
1050 return "Win";
1051}
1052
1053FREERDP_API int ShadowSubsystemEntry(RDP_SHADOW_ENTRY_POINTS* pEntryPoints)
1054{
1055 char name[] = "windows shadow subsystem";
1056 char* arg[] = { name };
1057
1058 freerdp_server_warn_unmaintained(ARRAYSIZE(arg), arg);
1059 pEntryPoints->New = win_shadow_subsystem_new;
1060 pEntryPoints->Free = win_shadow_subsystem_free;
1061 pEntryPoints->Init = win_shadow_subsystem_init;
1062 pEntryPoints->Uninit = win_shadow_subsystem_uninit;
1063 pEntryPoints->Start = win_shadow_subsystem_start;
1064 pEntryPoints->Stop = win_shadow_subsystem_stop;
1065 pEntryPoints->EnumMonitors = win_shadow_enum_monitors;
1066 return 1;
1067}