FreeRDP
Loading...
Searching...
No Matches
x11_shadow.c
1
20
21#include <errno.h>
22#include <stdio.h>
23#include <stdlib.h>
24#include <string.h>
25#include <unistd.h>
26
27#include <sys/ipc.h>
28#include <sys/shm.h>
29#include <sys/select.h>
30#include <sys/signal.h>
31
32#include <X11/Xlib.h>
33#include <X11/Xutil.h>
34#include <X11/XKBlib.h>
35
36#include <winpr/endian.h>
37#include <winpr/crt.h>
38#include <winpr/assert.h>
39#include <winpr/cast.h>
40#include <winpr/path.h>
41#include <winpr/synch.h>
42#include <winpr/image.h>
43#include <winpr/sysinfo.h>
44
45#include <freerdp/log.h>
46#include <freerdp/codec/color.h>
47#include <freerdp/codec/region.h>
48
49#include "x11_shadow.h"
50
51#define TAG SERVER_TAG("shadow.x11")
52
53// #define USE_SHADOW_BLEND_CURSOR
54WINPR_ATTR_NODISCARD
55static UINT32 x11_shadow_enum_monitors(MONITOR_DEF* monitors, UINT32 maxMonitors);
56
57#ifdef WITH_PAM
58
59#include <security/pam_appl.h>
60
61typedef struct
62{
63 const char* user;
64 const char* domain;
65 const char* password;
66} SHADOW_PAM_AUTH_DATA;
67
68typedef struct
69{
70 char* service_name;
71 pam_handle_t* handle;
72 struct pam_conv pamc;
73 SHADOW_PAM_AUTH_DATA appdata;
74} SHADOW_PAM_AUTH_INFO;
75
76WINPR_ATTR_NODISCARD
77static int x11_shadow_pam_conv(int num_msg, const struct pam_message** msg,
78 struct pam_response** resp, void* appdata_ptr)
79{
80 int pam_status = PAM_CONV_ERR;
81 SHADOW_PAM_AUTH_DATA* appdata = nullptr;
82 struct pam_response* response = nullptr;
83 WINPR_ASSERT(num_msg >= 0);
84 appdata = (SHADOW_PAM_AUTH_DATA*)appdata_ptr;
85 WINPR_ASSERT(appdata);
86
87 if (!(response = (struct pam_response*)calloc((size_t)num_msg, sizeof(struct pam_response))))
88 return PAM_BUF_ERR;
89
90 for (int index = 0; index < num_msg; index++)
91 {
92 switch (msg[index]->msg_style)
93 {
94 case PAM_PROMPT_ECHO_ON:
95 response[index].resp = _strdup(appdata->user);
96
97 if (!response[index].resp)
98 goto out_fail;
99
100 response[index].resp_retcode = PAM_SUCCESS;
101 break;
102
103 case PAM_PROMPT_ECHO_OFF:
104 response[index].resp = _strdup(appdata->password);
105
106 if (!response[index].resp)
107 goto out_fail;
108
109 response[index].resp_retcode = PAM_SUCCESS;
110 break;
111
112 default:
113 pam_status = PAM_CONV_ERR;
114 goto out_fail;
115 }
116 }
117
118 *resp = response;
119 return PAM_SUCCESS;
120out_fail:
121
122 for (int index = 0; index < num_msg; ++index)
123 {
124 if (response[index].resp)
125 {
126 memset(response[index].resp, 0, strlen(response[index].resp));
127 free(response[index].resp);
128 }
129 }
130
131 memset(response, 0, sizeof(struct pam_response) * (size_t)num_msg);
132 free(response);
133 *resp = nullptr;
134 return pam_status;
135}
136
137WINPR_ATTR_NODISCARD
138static BOOL x11_shadow_pam_get_service_name(SHADOW_PAM_AUTH_INFO* info)
139{
140 const char* base = "/etc/pam.d";
141 const char* hints[] = { "lightdm", "gdm", "xdm", "login", "sshd" };
142
143 for (size_t x = 0; x < ARRAYSIZE(hints); x++)
144 {
145 char path[MAX_PATH] = WINPR_C_ARRAY_INIT;
146 const char* hint = hints[x];
147
148 (void)_snprintf(path, sizeof(path), "%s/%s", base, hint);
149 if (winpr_PathFileExists(path))
150 {
151
152 info->service_name = _strdup(hint);
153 return info->service_name != nullptr;
154 }
155 }
156 WLog_WARN(TAG, "Could not determine PAM service name");
157 return FALSE;
158}
159
160WINPR_ATTR_NODISCARD
161static int x11_shadow_pam_authenticate(rdpShadowSubsystem* subsystem, rdpShadowClient* client,
162 const char* user, const char* domain, const char* password)
163{
164 int rc = -1;
165 int pam_status = 0;
166 SHADOW_PAM_AUTH_INFO info = WINPR_C_ARRAY_INIT;
167 WINPR_UNUSED(subsystem);
168 WINPR_UNUSED(client);
169
170 if (!x11_shadow_pam_get_service_name(&info))
171 return -1;
172
173 info.appdata.user = user;
174 info.appdata.domain = domain;
175 info.appdata.password = password;
176 info.pamc.conv = &x11_shadow_pam_conv;
177 info.pamc.appdata_ptr = &info.appdata;
178 pam_status = pam_start(info.service_name, nullptr, &info.pamc, &info.handle);
179
180 if (pam_status != PAM_SUCCESS)
181 {
182 WLog_ERR(TAG, "pam_start failure: %s", pam_strerror(info.handle, pam_status));
183 goto fail;
184 }
185
186 pam_status = pam_authenticate(info.handle, 0);
187
188 if (pam_status != PAM_SUCCESS)
189 {
190 WLog_ERR(TAG, "pam_authenticate failure: %s", pam_strerror(info.handle, pam_status));
191 goto fail;
192 }
193
194 pam_status = pam_acct_mgmt(info.handle, 0);
195
196 if (pam_status != PAM_SUCCESS)
197 {
198 WLog_ERR(TAG, "pam_acct_mgmt failure: %s", pam_strerror(info.handle, pam_status));
199 goto fail;
200 }
201
202 rc = 1;
203fail:
204 if (info.handle)
205 {
206 const int res = pam_end(info.handle, pam_status);
207 if (res != PAM_SUCCESS)
208 WLog_WARN(TAG, "pam_end failure: %s", pam_strerror(info.handle, pam_status));
209 }
210 free(info.service_name);
211 return rc;
212}
213
214#endif
215
216#if defined(WITH_XTEST)
217WINPR_ATTR_NODISCARD
218static BOOL isKeyPressed(Display* display, KeyCode code)
219{
220 char keys[32] = WINPR_C_ARRAY_INIT;
221 if (XQueryKeymap(display, keys) != 1)
222 return FALSE;
223
224 return (keys[code >> 3] >> (code & 7)) & 1;
225}
226
227static BOOL pressKey(Display* display, KeySym sym)
228{
229 WINPR_ASSERT(display);
230
231 KeyCode key = XKeysymToKeycode(display, sym);
232 if (key == AnyKey)
233 {
234 WLog_WARN(TAG, "No KeyCode mapped for KeySym=%lu", sym);
235 return FALSE;
236 }
237
238 Sleep(5);
239 const int rc1 = XTestFakeKeyEvent(display, key, True, CurrentTime);
240 Sleep(5);
241 const int rc2 = XTestFakeKeyEvent(display, key, False, CurrentTime);
242
243 if ((rc1 == 0) || (rc2 == 0))
244 {
245 WLog_WARN(TAG, "Failed to synghesize KeyCode=%u event", key);
246 return FALSE;
247 }
248 return TRUE;
249}
250
251WINPR_ATTR_MALLOC(XFree, 1)
252static char* nameForIndicator(Display* display, unsigned int pos)
253{
254 WINPR_ASSERT(display);
255
256 XkbDescPtr xkb = XkbAllocKeyboard();
257 if (!xkb)
258 {
259 WLog_WARN(TAG, "Failed to allocate XkbDescPtr");
260 return nullptr;
261 }
262
263 if (XkbGetNames(display, XkbIndicatorNamesMask, xkb) != Success)
264 {
265 WLog_WARN(TAG, "Failed to get XkbGetNames");
266 XkbFreeKeyboard(xkb, 0, True);
267 return nullptr;
268 }
269
270 char* name = nullptr;
271 if (pos >= XkbNumIndicators)
272 WLog_WARN(TAG, "invalid indicator bit position %u", pos);
273 else
274 {
275 Atom atom = xkb->names->indicators[pos];
276 if (atom != None)
277 name = XGetAtomName(display, atom);
278 else
279 WLog_WARN(TAG, "Failed to map indicator position %u to atom", pos);
280 }
281 XkbFreeKeyboard(xkb, 0, True);
282 return name;
283}
284
285WINPR_ATTR_NODISCARD
286static unsigned int utf16_to_utf32(WCHAR lehigh, WCHAR lelow)
287{
288 const WCHAR high = winpr_Data_Get_UINT16(&lehigh);
289 const WCHAR low = winpr_Data_Get_UINT16(&lelow);
290 unsigned int u32 = high;
291 if ((high >= 0xD800u) && (high <= 0xDBFFu) && (low >= 0xDC00u) && (low <= 0xDFFFu))
292 u32 = ((high - 0xD800u) << 10u) + (low - 0xDC00u) + 0x10000u;
293 return u32;
294}
295#endif
296
297WINPR_ATTR_NODISCARD
298static BOOL x11_shadow_input_synchronize_event(WINPR_ATTR_UNUSED rdpShadowSubsystem* subsystem,
299 WINPR_ATTR_UNUSED rdpShadowClient* client,
300 WINPR_ATTR_UNUSED UINT32 flags)
301{
302#ifdef WITH_XTEST
303 x11ShadowSubsystem* x11 = (x11ShadowSubsystem*)subsystem;
304
305 if (!client || !subsystem)
306 return FALSE;
307
308 XLockDisplay(x11->display);
309 XTestGrabControl(x11->display, True);
310
311 /* Ensure every key is released */
312 for (KeyCode x = 0; x < 255; x++)
313 {
314 if (!isKeyPressed(x11->display, x))
315 continue;
316 Sleep(5);
317 XTestFakeKeyEvent(x11->display, x, False, CurrentTime);
318 }
319
320 /* Set all modifiers to off */
321 unsigned int state = WINPR_C_ARRAY_INIT;
322 const Status rc = XkbGetIndicatorState(x11->display, XkbUseCoreKbd, &state);
323 if (rc != Success)
324 {
325 WLog_WARN(TAG, "XkbGetIndicatorState failed, not syncing modifiers");
326 }
327 else
328 {
329 /* Reset all indicators currently set */
330 for (unsigned x = 0; x < XkbNumIndicators; x++)
331 {
332 unsigned bit = 1 << x;
333 if ((state & bit) == 0)
334 continue;
335 char* name = nameForIndicator(x11->display, x);
336 if (!name)
337 continue;
338
339 if (_stricmp(name, "Scroll Lock") == 0)
340 {
341 pressKey(x11->display, XK_Scroll_Lock);
342 }
343 else if (_stricmp(name, "Num Lock") == 0)
344 {
345 pressKey(x11->display, XK_Num_Lock);
346 }
347 else if (_stricmp(name, "Caps Lock") == 0)
348 {
349 pressKey(x11->display, XK_Caps_Lock);
350 }
351 else if (_stricmp(name, "Kana Lock") == 0)
352 {
353 pressKey(x11->display, XK_Kana_Lock);
354 }
355 XFree(name);
356 }
357
358 unsigned state2 = 0;
359 const Status rc2 = XkbGetIndicatorState(x11->display, XkbUseCoreKbd, &state2);
360 if (rc2 != Success)
361 {
362 WLog_WARN(TAG, "XkbGetIndicatorState failed, can not check modifiers were cleared");
363 }
364 else if (state2 != 0)
365 {
366 WLog_WARN(TAG, "XkbGetIndicatorState clear check returned 0x%08u, should be 0x00000000",
367 state2);
368 }
369
370 /* Set requested modifiers on */
371 if ((flags & KBD_SYNC_SCROLL_LOCK) != 0)
372 {
373 pressKey(x11->display, XK_Scroll_Lock);
374 }
375 if ((flags & KBD_SYNC_NUM_LOCK) != 0)
376 {
377 pressKey(x11->display, XK_Num_Lock);
378 }
379 if ((flags & KBD_SYNC_CAPS_LOCK) != 0)
380 {
381 pressKey(x11->display, XK_Caps_Lock);
382 }
383 if ((flags & KBD_SYNC_KANA_LOCK) != 0)
384 {
385 pressKey(x11->display, XK_Kana_Lock);
386 }
387
388 unsigned state3 = 0;
389 const Status rc3 = XkbGetIndicatorState(x11->display, XkbUseCoreKbd, &state2);
390 if (rc3 != Success)
391 {
392 WLog_WARN(TAG, "XkbGetIndicatorState failed, can not check modifiers were applied");
393 }
394 else if (state3 != 0)
395 {
396 WLog_DBG(TAG, "XkbGetIndicatorState apply check returned 0x%08u", state3);
397 }
398 }
399
400 XTestGrabControl(x11->display, False);
401 XFlush(x11->display);
402 XUnlockDisplay(x11->display);
403#else
404 WLog_WARN(TAG, "SynchronizeEvent not supported by backend, ignoring");
405#endif
406 return TRUE;
407}
408
409WINPR_ATTR_NODISCARD
410static BOOL x11_shadow_input_keyboard_event(rdpShadowSubsystem* subsystem, rdpShadowClient* client,
411 UINT16 flags, UINT8 code)
412{
413#ifdef WITH_XTEST
414 x11ShadowSubsystem* x11 = (x11ShadowSubsystem*)subsystem;
415 BOOL extended = FALSE;
416
417 if (!client || !subsystem)
418 return FALSE;
419
420 if (flags & KBD_FLAGS_EXTENDED)
421 extended = TRUE;
422
423 DWORD scancode = code;
424 if (extended)
425 scancode |= KBDEXT;
426
427 DWORD vkcode = GetVirtualKeyCodeFromVirtualScanCode(scancode, WINPR_KBD_TYPE_IBM_ENHANCED);
428
429 if (extended)
430 vkcode |= KBDEXT;
431
432 const DWORD keycode = GetKeycodeFromVirtualKeyCode(vkcode, WINPR_KEYCODE_TYPE_XKB);
433
434 if (keycode != 0)
435 {
436 XLockDisplay(x11->display);
437 XTestGrabControl(x11->display, True);
438
439 Sleep(5);
440
441 const Bool down = ((flags & KBD_FLAGS_RELEASE) == 0);
442 XTestFakeKeyEvent(x11->display, keycode, down, CurrentTime);
443
444 XTestGrabControl(x11->display, False);
445 XFlush(x11->display);
446 XUnlockDisplay(x11->display);
447 }
448#else
449 WLog_WARN(TAG, "KeyboardEvent not supported by backend, ignoring");
450#endif
451 return TRUE;
452}
453
454WINPR_ATTR_NODISCARD
455static BOOL x11_shadow_input_unicode_keyboard_event(WINPR_ATTR_UNUSED rdpShadowSubsystem* subsystem,
456 WINPR_ATTR_UNUSED rdpShadowClient* client,
457 WINPR_ATTR_UNUSED UINT16 flags,
458 WINPR_ATTR_UNUSED UINT16 lecode)
459{
460#ifdef WITH_XTEST
461 x11ShadowSubsystem* x11 = (x11ShadowSubsystem*)subsystem;
462 BOOL down = FALSE;
463
464 if (!client || !subsystem)
465 return FALSE;
466
467 if ((flags & KBD_FLAGS_RELEASE) == 0)
468 down = TRUE;
469
470 // Ensure native endianness
471 const WCHAR becode = winpr_Data_Get_UINT16(&lecode);
472 const WCHAR surrogate = x11->surrogate;
473 if ((becode >= 0xD800) && (becode <= 0xDBFF))
474 {
475 if (!down)
476 {
477 if (surrogate != becode)
478 WLog_WARN(TAG,
479 "Invalid high surrogate: mismatch between key down and key up, ignoring");
480 return TRUE;
481 }
482 x11->surrogate = lecode;
483 return TRUE;
484 }
485 else if (!down)
486 x11->surrogate = 0;
487
488 BOOL isSurrogate = FALSE;
489 if (surrogate != 0)
490 {
491 if ((becode >= 0xDC00) && (becode <= 0xDFFF))
492 isSurrogate = TRUE;
493 else
494 WLog_WARN(TAG, "Received invalid surrogate sequence, discarding.");
495 }
496
497 XLockDisplay(x11->display);
498 /* Unicode keysym encoding: 0x01000000 | code point. */
499 KeySym unicode_keysym = NoSymbol;
500 KeyCode keycode = AnyKey;
501
502 if (!isSurrogate && ((becode < 0x20) || (becode == 0x7f)))
503 {
504 switch (becode)
505 {
506 case 0x7f:
507 unicode_keysym = XK_Delete;
508 break;
509 case 0x08:
510 unicode_keysym = XK_BackSpace;
511 break;
512 case 0x09:
513 unicode_keysym = XK_Tab;
514 break;
515 case 0x0a:
516 unicode_keysym = XK_Linefeed;
517 break;
518 case 0x0d:
519 unicode_keysym = XK_Return;
520 break;
521 case 0x18:
522 unicode_keysym = XK_Cancel;
523 break;
524 case 0x1e:
525 unicode_keysym = XK_Escape;
526 break;
527
528 default:
529 WLog_WARN(TAG, "ASCII control 0x%02x unmapped, ignoring", becode);
530 break;
531 /*
532 0x00 NUL Null character
533 0x01 SOH Start of Heading
534 0x02 STX Start of Text
535 0x03 ETX End of Text
536 0x04 EOT End of Transmission
537 0x05 ENQ Enquiry
538 0x06 ACK Acknowledge
539 0x07 BEL Bell, Alert
540 0x09 HT Horizontal Tab
541 0x0B VT Vertical Tabulation
542 0x0C FF Form Feed
543 0x0E SO Shift Out
544 0x0F SI Shift In
545 0x10 DLE Data Link Escape
546 0x11 DC1 Device Control One (XON)
547 0x12 DC2 Device Control Two
548 0x13 DC3 Device Control Three (XOFF)
549 0x14 DC4 Device Control Four
550 0x15 NAK Negative Acknowledge
551 0x16 SYN Synchronous Idle
552 0x17 ETB End of Transmission Block
553 0x19 EM End of medium
554 0x1A SUB Substitute
555 0x1C FS File Separator
556 0x1D GS Group Separator
557 0x1E RS Record Separator
558 0x1F US Unit Separator
559 */
560 }
561 if (unicode_keysym != NoSymbol)
562 {
563 keycode = XKeysymToKeycode(x11->display, unicode_keysym);
564 if (keycode == AnyKey)
565 {
566 keycode = 255;
567 XChangeKeyboardMapping(x11->display, keycode, 1, &unicode_keysym, 1);
568 XSync(x11->display, False);
569 }
570 }
571 }
572 else
573 {
574 if (isSurrogate)
575 unicode_keysym = utf16_to_utf32(surrogate, lecode) | 0x01000000u;
576 else
577 {
578 char buffer[32] = WINPR_C_ARRAY_INIT;
579 (void)ConvertWCharNToUtf8(&lecode, 1, buffer, sizeof(buffer));
580 unicode_keysym = XStringToKeysym(buffer);
581 }
582
583 if (unicode_keysym != NoSymbol)
584 keycode = XKeysymToKeycode(x11->display, unicode_keysym);
585
586 if (keycode == AnyKey)
587 {
588 /* Map this keycode to the Unicode keysym. */
589 keycode = 255;
590 XChangeKeyboardMapping(x11->display, keycode, 1, &unicode_keysym, 1);
591 XSync(x11->display, False);
592 }
593 }
594
595 if (keycode != AnyKey)
596 {
597 XTestGrabControl(x11->display, True);
598 Sleep(5);
599 XTestFakeKeyEvent(x11->display, keycode, down, CurrentTime);
600 XTestGrabControl(x11->display, False);
601 XSync(x11->display, False);
602 XFlush(x11->display);
603 }
604 XUnlockDisplay(x11->display);
605#else
606 WLog_WARN(TAG, "UnicodeKeyboardEvent not supported by backend, ignoring");
607#endif
608 return TRUE;
609}
610
611WINPR_ATTR_NODISCARD
612static BOOL x11_shadow_input_mouse_event(rdpShadowSubsystem* subsystem, rdpShadowClient* client,
613 UINT16 flags, UINT16 x, UINT16 y)
614{
615#ifdef WITH_XTEST
616 x11ShadowSubsystem* x11 = (x11ShadowSubsystem*)subsystem;
617 unsigned int button = 0;
618 BOOL down = FALSE;
619
620 if (!subsystem || !client)
621 return FALSE;
622
623 rdpShadowServer* server = subsystem->server;
624
625 if (!server)
626 return FALSE;
627
628 rdpShadowSurface* surface = server->surface;
629
630 if (!surface)
631 return FALSE;
632
633 EnterCriticalSection(&surface->lock);
634 x11->lastMouseClient = client;
635 x += surface->x;
636 y += surface->y;
637 XLockDisplay(x11->display);
638 XTestGrabControl(x11->display, True);
639
640 if (flags & PTR_FLAGS_WHEEL)
641 {
642 BOOL negative = FALSE;
643
644 if (flags & PTR_FLAGS_WHEEL_NEGATIVE)
645 negative = TRUE;
646
647 button = (negative) ? 5 : 4;
648 XTestFakeButtonEvent(x11->display, button, True, (unsigned long)CurrentTime);
649 XTestFakeButtonEvent(x11->display, button, False, (unsigned long)CurrentTime);
650 }
651 else if (flags & PTR_FLAGS_HWHEEL)
652 {
653 BOOL negative = FALSE;
654
655 if (flags & PTR_FLAGS_WHEEL_NEGATIVE)
656 negative = TRUE;
657
658 button = (negative) ? 7 : 6;
659 XTestFakeButtonEvent(x11->display, button, True, (unsigned long)CurrentTime);
660 XTestFakeButtonEvent(x11->display, button, False, (unsigned long)CurrentTime);
661 }
662 else
663 {
664 if (flags & PTR_FLAGS_MOVE)
665 XTestFakeMotionEvent(x11->display, 0, x, y, CurrentTime);
666
667 if (flags & PTR_FLAGS_BUTTON1)
668 button = 1;
669 else if (flags & PTR_FLAGS_BUTTON2)
670 button = 3;
671 else if (flags & PTR_FLAGS_BUTTON3)
672 button = 2;
673
674 if (flags & PTR_FLAGS_DOWN)
675 down = TRUE;
676
677 if (button)
678 XTestFakeButtonEvent(x11->display, button, down, CurrentTime);
679 }
680
681 XTestGrabControl(x11->display, False);
682 XFlush(x11->display);
683 XUnlockDisplay(x11->display);
684 LeaveCriticalSection(&surface->lock);
685#else
686 WLog_WARN(TAG, "MouseEvent not supported by backend, ignoring");
687#endif
688 return TRUE;
689}
690
691WINPR_ATTR_NODISCARD
692static BOOL x11_shadow_input_rel_mouse_event(rdpShadowSubsystem* subsystem, rdpShadowClient* client,
693 UINT16 flags, INT16 xDelta, INT16 yDelta)
694{
695#ifdef WITH_XTEST
696 x11ShadowSubsystem* x11 = (x11ShadowSubsystem*)subsystem;
697 WINPR_ASSERT(x11);
698
699 unsigned int button = 0;
700 BOOL down = FALSE;
701
702 if (!subsystem || !client)
703 return FALSE;
704
705 rdpShadowServer* server = subsystem->server;
706
707 if (!server)
708 return FALSE;
709
710 rdpShadowSurface* surface = server->surface;
711
712 if (!surface)
713 return FALSE;
714
715 EnterCriticalSection(&surface->lock);
716 x11->lastMouseClient = client;
717
718 XLockDisplay(x11->display);
719 XTestGrabControl(x11->display, True);
720
721 if (flags & PTR_FLAGS_MOVE)
722 XTestFakeRelativeMotionEvent(x11->display, xDelta, yDelta, 0);
723
724 if (flags & PTR_FLAGS_BUTTON1)
725 button = 1;
726 else if (flags & PTR_FLAGS_BUTTON2)
727 button = 3;
728 else if (flags & PTR_FLAGS_BUTTON3)
729 button = 2;
730 else if (flags & PTR_XFLAGS_BUTTON1)
731 button = 4;
732 else if (flags & PTR_XFLAGS_BUTTON2)
733 button = 5;
734
735 if (flags & PTR_FLAGS_DOWN)
736 down = TRUE;
737
738 if (button)
739 XTestFakeButtonEvent(x11->display, button, down, CurrentTime);
740
741 XTestGrabControl(x11->display, False);
742 XFlush(x11->display);
743 XUnlockDisplay(x11->display);
744 LeaveCriticalSection(&surface->lock);
745#else
746 WLog_WARN(TAG, "RelMouseEvent not supported by backend, ignoring");
747#endif
748 return TRUE;
749}
750
751WINPR_ATTR_NODISCARD
752static BOOL x11_shadow_input_extended_mouse_event(rdpShadowSubsystem* subsystem,
753 rdpShadowClient* client, UINT16 flags, UINT16 x,
754 UINT16 y)
755{
756#ifdef WITH_XTEST
757 x11ShadowSubsystem* x11 = (x11ShadowSubsystem*)subsystem;
758 UINT button = 0;
759 BOOL down = FALSE;
760
761 if (!subsystem || !client)
762 return FALSE;
763
764 rdpShadowServer* server = subsystem->server;
765
766 if (!server)
767 return FALSE;
768
769 rdpShadowSurface* surface = server->surface;
770
771 if (!surface)
772 return FALSE;
773
774 EnterCriticalSection(&surface->lock);
775 x11->lastMouseClient = client;
776 x += surface->x;
777 y += surface->y;
778 XLockDisplay(x11->display);
779 XTestGrabControl(x11->display, True);
780 XTestFakeMotionEvent(x11->display, 0, x, y, CurrentTime);
781
782 if (flags & PTR_XFLAGS_BUTTON1)
783 button = 8;
784 else if (flags & PTR_XFLAGS_BUTTON2)
785 button = 9;
786
787 if (flags & PTR_XFLAGS_DOWN)
788 down = TRUE;
789
790 if (button)
791 XTestFakeButtonEvent(x11->display, button, down, CurrentTime);
792
793 XTestGrabControl(x11->display, False);
794 XFlush(x11->display);
795 XUnlockDisplay(x11->display);
796 LeaveCriticalSection(&surface->lock);
797#else
798 WLog_WARN(TAG, "ExtendedMouseEvent not supported by backend, ignoring");
799#endif
800 return TRUE;
801}
802
803static void x11_shadow_message_free(UINT32 id, SHADOW_MSG_OUT* msg)
804{
805 switch (id)
806 {
807 case SHADOW_MSG_OUT_POINTER_POSITION_UPDATE_ID:
808 free(msg);
809 break;
810
811 case SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE_ID:
812 free(((SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE*)msg)->xorMaskData);
813 free(((SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE*)msg)->andMaskData);
814 free(msg);
815 break;
816
817 default:
818 WLog_ERR(TAG, "Unknown message id: %" PRIu32 "", id);
819 free(msg);
820 break;
821 }
822}
823
824WINPR_ATTR_NODISCARD
825static int x11_shadow_pointer_position_update(x11ShadowSubsystem* subsystem)
826{
827 UINT32 msgId = SHADOW_MSG_OUT_POINTER_POSITION_UPDATE_ID;
828 rdpShadowServer* server = nullptr;
829 SHADOW_MSG_OUT_POINTER_POSITION_UPDATE templateMsg = WINPR_C_ARRAY_INIT;
830 int count = 0;
831
832 if (!subsystem || !subsystem->common.server || !subsystem->common.server->clients)
833 return -1;
834
835 templateMsg.xPos = subsystem->common.pointerX;
836 templateMsg.yPos = subsystem->common.pointerY;
837 templateMsg.common.Free = x11_shadow_message_free;
838 server = subsystem->common.server;
839 ArrayList_Lock(server->clients);
840
841 for (size_t index = 0; index < ArrayList_Count(server->clients); index++)
842 {
844 rdpShadowClient* client = (rdpShadowClient*)ArrayList_GetItem(server->clients, index);
845
846 /* Skip the client which send us the latest mouse event */
847 if (client == subsystem->lastMouseClient)
848 continue;
849
850 msg = malloc(sizeof(templateMsg));
851
852 if (!msg)
853 {
854 count = -1;
855 break;
856 }
857
858 memcpy(msg, &templateMsg, sizeof(templateMsg));
859
860 if (shadow_client_post_msg(client, nullptr, msgId, (SHADOW_MSG_OUT*)msg, nullptr))
861 count++;
862 }
863
864 ArrayList_Unlock(server->clients);
865 return count;
866}
867
868WINPR_ATTR_NODISCARD
869static int x11_shadow_pointer_alpha_update(x11ShadowSubsystem* subsystem)
870{
871 UINT32 msgId = SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE_ID;
874
875 if (!msg)
876 return -1;
877
878 msg->xHot = subsystem->cursorHotX;
879 msg->yHot = subsystem->cursorHotY;
880 msg->width = subsystem->cursorWidth;
881 msg->height = subsystem->cursorHeight;
882
883 if (shadow_subsystem_pointer_convert_alpha_pointer_data_to_format(
884 subsystem->cursorPixels, subsystem->format, TRUE, msg->width, msg->height, msg) < 0)
885 {
886 free(msg);
887 return -1;
888 }
889
890 msg->common.Free = x11_shadow_message_free;
891 const int count = shadow_client_boardcast_msg(subsystem->common.server, nullptr, msgId,
892 (SHADOW_MSG_OUT*)msg, nullptr);
893 if (count < 0)
894 return -1;
895 return 1;
896}
897
898WINPR_ATTR_NODISCARD
899static int x11_shadow_query_cursor(x11ShadowSubsystem* subsystem, BOOL getImage)
900{
901 int x = 0;
902 int y = 0;
903 int n = 0;
904 rdpShadowServer* server = subsystem->common.server;
905 rdpShadowSurface* surface = server->surface;
906
907 if (getImage)
908 {
909#ifdef WITH_XFIXES
910 UINT32* pDstPixel = nullptr;
911 XFixesCursorImage* ci = nullptr;
912 XLockDisplay(subsystem->display);
913 ci = XFixesGetCursorImage(subsystem->display);
914 XUnlockDisplay(subsystem->display);
915
916 if (!ci)
917 return -1;
918
919 x = ci->x;
920 y = ci->y;
921
922 if (ci->width > subsystem->cursorMaxWidth)
923 return -1;
924
925 if (ci->height > subsystem->cursorMaxHeight)
926 return -1;
927
928 subsystem->cursorHotX = ci->xhot;
929 subsystem->cursorHotY = ci->yhot;
930 subsystem->cursorWidth = ci->width;
931 subsystem->cursorHeight = ci->height;
932 subsystem->cursorId = ci->cursor_serial;
933 n = ci->width * ci->height;
934 pDstPixel = WINPR_PACKED_ALIGN_CAST(UINT32*, subsystem->cursorPixels);
935
936 for (int k = 0; k < n; k++)
937 {
938 /* XFixesCursorImage.pixels is in *unsigned long*, which may be 8 bytes */
939 *pDstPixel++ = (UINT32)ci->pixels[k];
940 }
941
942 XFree(ci);
943 const int rc = x11_shadow_pointer_alpha_update(subsystem);
944 if (rc < 0)
945 return rc;
946#endif
947 }
948 else
949 {
950 UINT32 mask = 0;
951 int win_x = 0;
952 int win_y = 0;
953 int root_x = 0;
954 int root_y = 0;
955 Window root = 0;
956 Window child = 0;
957 XLockDisplay(subsystem->display);
958
959 if (!XQueryPointer(subsystem->display, subsystem->root_window, &root, &child, &root_x,
960 &root_y, &win_x, &win_y, &mask))
961 {
962 XUnlockDisplay(subsystem->display);
963 return -1;
964 }
965
966 XUnlockDisplay(subsystem->display);
967 x = root_x;
968 y = root_y;
969 }
970
971 /* Convert to offset based on current surface */
972 if (surface)
973 {
974 EnterCriticalSection(&surface->lock);
975 x -= surface->x;
976 y -= surface->y;
977 LeaveCriticalSection(&surface->lock);
978 }
979
980 if ((x != (INT64)subsystem->common.pointerX) || (y != (INT64)subsystem->common.pointerY))
981 {
982 subsystem->common.pointerX = (UINT32)MAX(0, x);
983 subsystem->common.pointerY = (UINT32)MAX(0, y);
984 return x11_shadow_pointer_position_update(subsystem);
985 }
986
987 return 1;
988}
989
990WINPR_ATTR_NODISCARD
991static int x11_shadow_handle_xevent(x11ShadowSubsystem* subsystem, XEvent* xevent)
992{
993 if (xevent->type == MotionNotify)
994 {
995 }
996
997#ifdef WITH_XFIXES
998 else if (xevent->type == subsystem->xfixes_cursor_notify_event)
999 {
1000 return x11_shadow_query_cursor(subsystem, TRUE);
1001 }
1002
1003#endif
1004 else
1005 {
1006 }
1007
1008 return 1;
1009}
1010
1011#if defined(USE_SHADOW_BLEND_CURSOR)
1012WINPR_ATTR_NODISCARD
1013static int x11_shadow_blend_cursor(x11ShadowSubsystem* subsystem)
1014{
1015 if (!subsystem)
1016 return -1;
1017
1018 rdpShadowSurface* surface = subsystem->common.server->surface;
1019 UINT32 nXSrc = 0;
1020 UINT32 nYSrc = 0;
1021 UINT32 nWidth = subsystem->cursorWidth;
1022 UINT32 nHeight = subsystem->cursorHeight;
1023 INT64 nXDst = subsystem->common.pointerX - subsystem->cursorHotX;
1024 INT64 nYDst = subsystem->common.pointerY - subsystem->cursorHotY;
1025
1026 if (nXDst >= surface->width)
1027 return 1;
1028
1029 if (nXDst < 0)
1030 {
1031 nXDst *= -1;
1032
1033 if (nXDst >= nWidth)
1034 return 1;
1035
1036 nXSrc = (UINT32)nXDst;
1037 nWidth -= nXDst;
1038 nXDst = 0;
1039 }
1040
1041 if (nYDst >= surface->height)
1042 return 1;
1043
1044 if (nYDst < 0)
1045 {
1046 nYDst *= -1;
1047
1048 if (nYDst >= nHeight)
1049 return 1;
1050
1051 nYSrc = (UINT32)nYDst;
1052 nHeight -= nYDst;
1053 nYDst = 0;
1054 }
1055
1056 if ((nXDst + nWidth) > surface->width)
1057 nWidth = (nXDst > surface->width) ? 0 : (UINT32)(surface->width - nXDst);
1058
1059 if ((nYDst + nHeight) > surface->height)
1060 nHeight = (nYDst > surface->height) ? 0 : (UINT32)(surface->height - nYDst);
1061
1062 const BYTE* pSrcData = subsystem->cursorPixels;
1063 const UINT32 nSrcStep = subsystem->cursorWidth * 4;
1064 BYTE* pDstData = surface->data;
1065 const UINT32 nDstStep = surface->scanline;
1066
1067 for (size_t y = 0; y < nHeight; y++)
1068 {
1069 const BYTE* pSrcPixel = &pSrcData[((nYSrc + y) * nSrcStep) + (4ULL * nXSrc)];
1070 BYTE* pDstPixel = &pDstData[((WINPR_ASSERTING_INT_CAST(uint32_t, nYDst) + y) * nDstStep) +
1071 (4ULL * WINPR_ASSERTING_INT_CAST(uint32_t, nXDst))];
1072
1073 for (size_t x = 0; x < nWidth; x++)
1074 {
1075 const BYTE B = *pSrcPixel++;
1076 const BYTE G = *pSrcPixel++;
1077 const BYTE R = *pSrcPixel++;
1078 const BYTE A = *pSrcPixel++;
1079
1080 if (A == 0xFF)
1081 {
1082 pDstPixel[0] = B;
1083 pDstPixel[1] = G;
1084 pDstPixel[2] = R;
1085 }
1086 else
1087 {
1088 pDstPixel[0] = B + (pDstPixel[0] * (0xFF - A) + (0xFF / 2)) / 0xFF;
1089 pDstPixel[1] = G + (pDstPixel[1] * (0xFF - A) + (0xFF / 2)) / 0xFF;
1090 pDstPixel[2] = R + (pDstPixel[2] * (0xFF - A) + (0xFF / 2)) / 0xFF;
1091 }
1092
1093 pDstPixel[3] = 0xFF;
1094 pDstPixel += 4;
1095 }
1096 }
1097
1098 return 1;
1099}
1100#endif
1101
1102WINPR_ATTR_NODISCARD
1103static BOOL x11_shadow_check_resize(x11ShadowSubsystem* subsystem)
1104{
1105 XWindowAttributes attr;
1106 XLockDisplay(subsystem->display);
1107 XGetWindowAttributes(subsystem->display, subsystem->root_window, &attr);
1108 XUnlockDisplay(subsystem->display);
1109
1110 if (attr.width != (INT64)subsystem->width || attr.height != (INT64)subsystem->height)
1111 {
1112 MONITOR_DEF* virtualScreen = &(subsystem->common.virtualScreen);
1113
1114 /* Screen size changed. Refresh monitor definitions and trigger screen resize */
1115 subsystem->common.numMonitors = x11_shadow_enum_monitors(subsystem->common.monitors, 16);
1116 if (!shadow_screen_resize(subsystem->common.server->screen))
1117 return FALSE;
1118
1119 WINPR_ASSERT(attr.width > 0);
1120 WINPR_ASSERT(attr.height > 0);
1121
1122 subsystem->width = (UINT32)attr.width;
1123 subsystem->height = (UINT32)attr.height;
1124
1125 virtualScreen->left = 0;
1126 virtualScreen->top = 0;
1127 virtualScreen->right = attr.width - 1;
1128 virtualScreen->bottom = attr.height - 1;
1129 virtualScreen->flags = 1;
1130 return TRUE;
1131 }
1132
1133 return FALSE;
1134}
1135
1136WINPR_ATTR_NODISCARD
1137static int x11_shadow_error_handler_for_capture(Display* display, XErrorEvent* event)
1138{
1139 char msg[256];
1140 XGetErrorText(display, event->error_code, (char*)&msg, sizeof(msg));
1141 WLog_ERR(TAG, "X11 error: %s Error code: %x, request code: %x, minor code: %x", msg,
1142 event->error_code, event->request_code, event->minor_code);
1143
1144 /* Ignore BAD MATCH error during image capture. Abort in other case */
1145 if (event->error_code != BadMatch)
1146 {
1147 abort();
1148 }
1149
1150 return 0;
1151}
1152
1153WINPR_ATTR_NODISCARD
1154static int x11_shadow_screen_grab_disp_locked(x11ShadowSubsystem* subsystem, XImage** ppimage,
1155 RECTANGLE_16* invalidRect)
1156{
1157 WINPR_ASSERT(subsystem);
1158 WINPR_ASSERT(ppimage);
1159 WINPR_ASSERT(invalidRect);
1160
1161 rdpShadowServer* server = subsystem->common.server;
1162 WINPR_ASSERT(server);
1163
1164 rdpShadowSurface* surface = server->surface;
1165 WINPR_ASSERT(surface);
1166
1167 int status = -1;
1168
1169#if defined(WITH_XDAMAGE)
1170 if (subsystem->use_xshm)
1171 {
1172 XImage* image = subsystem->fb_image;
1173 *ppimage = image;
1174
1175 XCopyArea(subsystem->display, subsystem->root_window, subsystem->fb_pixmap,
1176 subsystem->xshm_gc, 0, 0, subsystem->width, subsystem->height, 0, 0);
1177
1178 EnterCriticalSection(&surface->lock);
1179 status = shadow_capture_compare_with_format(
1180 surface->data, surface->format, surface->scanline, surface->width, surface->height,
1181 (BYTE*)&(image->data[surface->width * 4ull]), subsystem->format,
1182 WINPR_ASSERTING_INT_CAST(UINT32, image->bytes_per_line), invalidRect);
1183 LeaveCriticalSection(&surface->lock);
1184 }
1185 else
1186#endif
1187 {
1188 EnterCriticalSection(&surface->lock);
1189 XImage* image = XGetImage(subsystem->display, subsystem->root_window, surface->x,
1190 surface->y, surface->width, surface->height, AllPlanes, ZPixmap);
1191
1192 if (image)
1193 {
1194 status = shadow_capture_compare_with_format(
1195 surface->data, surface->format, surface->scanline, surface->width, surface->height,
1196 (BYTE*)image->data, subsystem->format,
1197 WINPR_ASSERTING_INT_CAST(UINT32, image->bytes_per_line), invalidRect);
1198 }
1199 *ppimage = image;
1200 LeaveCriticalSection(&surface->lock);
1201 }
1202
1203 return status;
1204}
1205
1206WINPR_ATTR_NODISCARD
1207static BOOL x11_shadow_surface_update_invalid(rdpShadowSurface* surface,
1208 const RECTANGLE_16* invalidRect,
1209 const RECTANGLE_16* surfaceRect)
1210{
1211 WINPR_ASSERT(surface);
1212 WINPR_ASSERT(invalidRect);
1213 WINPR_ASSERT(surfaceRect);
1214
1215 EnterCriticalSection(&surface->lock);
1216 const BOOL rc1 =
1217 region16_union_rect(&(surface->invalidRegion), &(surface->invalidRegion), invalidRect);
1218 const BOOL rc2 =
1219 region16_intersect_rect(&(surface->invalidRegion), &(surface->invalidRegion), surfaceRect);
1220 const BOOL empty = region16_is_empty(&(surface->invalidRegion));
1221 LeaveCriticalSection(&surface->lock);
1222 return !rc1 || !rc2 || empty;
1223}
1224
1225WINPR_ATTR_NODISCARD
1226static BOOL x11_shadow_surface_update_contents(rdpShadowSurface* surface, UINT32 format,
1227 const XImage* image)
1228{
1229 WINPR_ASSERT(surface);
1230 WINPR_ASSERT(image);
1231
1232 EnterCriticalSection(&surface->lock);
1233 const RECTANGLE_16* extents = region16_extents(&(surface->invalidRegion));
1234 const UINT16 x = extents->left;
1235 const UINT16 y = extents->top;
1236 const UINT16 width = extents->right - extents->left;
1237 const UINT16 height = extents->bottom - extents->top;
1238 WINPR_ASSERT(image);
1239 WINPR_ASSERT(image->bytes_per_line >= 0);
1240 WINPR_ASSERT(width >= 0);
1241 WINPR_ASSERT(height >= 0);
1242 const BOOL success = freerdp_image_copy_no_overlap(
1243 surface->data, surface->format, surface->scanline, WINPR_ASSERTING_INT_CAST(uint32_t, x),
1244 WINPR_ASSERTING_INT_CAST(uint32_t, y), WINPR_ASSERTING_INT_CAST(uint32_t, width),
1245 WINPR_ASSERTING_INT_CAST(uint32_t, height), (BYTE*)image->data, format,
1246 WINPR_ASSERTING_INT_CAST(uint32_t, image->bytes_per_line),
1247 WINPR_ASSERTING_INT_CAST(UINT32, x), WINPR_ASSERTING_INT_CAST(UINT32, y), nullptr,
1248 FREERDP_FLIP_NONE);
1249 LeaveCriticalSection(&surface->lock);
1250 return success;
1251}
1252
1253WINPR_ATTR_NODISCARD
1254static int x11_shadow_screen_grab(x11ShadowSubsystem* subsystem)
1255{
1256 int rc = 0;
1257
1258 WINPR_ASSERT(subsystem);
1259
1260 RECTANGLE_16 surfaceRect = WINPR_C_ARRAY_INIT;
1261 rdpShadowServer* server = subsystem->common.server;
1262 WINPR_ASSERT(server);
1263
1264 rdpShadowSurface* surface = server->surface;
1265 WINPR_ASSERT(surface);
1266
1267 size_t count = ArrayList_Count(server->clients);
1268
1269 if (count < 1)
1270 return 1;
1271
1272 {
1273 EnterCriticalSection(&surface->lock);
1274 surfaceRect.right = WINPR_ASSERTING_INT_CAST(UINT16, surface->width);
1275 surfaceRect.bottom = WINPR_ASSERTING_INT_CAST(UINT16, surface->height);
1276 LeaveCriticalSection(&surface->lock);
1277 }
1278
1279 XImage* image = nullptr;
1280 RECTANGLE_16 invalidRect = WINPR_C_ARRAY_INIT;
1281 int status = -1;
1282 {
1283 XLockDisplay(subsystem->display);
1284 /*
1285 * Ignore BadMatch error during image capture. The screen size may be
1286 * changed outside. We will resize to correct resolution at next frame
1287 */
1288 XSetErrorHandler(x11_shadow_error_handler_for_capture);
1289
1290 status = x11_shadow_screen_grab_disp_locked(subsystem, &image, &invalidRect);
1291 if (status < 0)
1292 goto fail_capture;
1293
1294 /* Restore the default error handler */
1295 XSetErrorHandler(nullptr);
1296 XSync(subsystem->display, False);
1297 XUnlockDisplay(subsystem->display);
1298 }
1299
1300 if (status)
1301 {
1302 const BOOL empty = x11_shadow_surface_update_invalid(surface, &invalidRect, &surfaceRect);
1303
1304 if (!empty)
1305 {
1306 const BOOL success =
1307 x11_shadow_surface_update_contents(surface, subsystem->format, image);
1308 if (!success)
1309 goto fail_capture;
1310
1311#if defined(USE_SHADOW_BLEND_CURSOR)
1312 if (x11_shadow_blend_cursor(subsystem) < 0)
1313 goto fail_capture;
1314#endif
1315 count = ArrayList_Count(server->clients);
1316 shadow_subsystem_frame_update(&subsystem->common);
1317
1318 if (count == 1)
1319 {
1320 rdpShadowClient* client = nullptr;
1321 client = (rdpShadowClient*)ArrayList_GetItem(server->clients, 0);
1322
1323 if (client)
1324 subsystem->common.captureFrameRate =
1325 shadow_encoder_preferred_fps(client->encoder);
1326 }
1327
1328 {
1329 EnterCriticalSection(&surface->lock);
1330 region16_clear(&(surface->invalidRegion));
1331 LeaveCriticalSection(&surface->lock);
1332 }
1333 }
1334 }
1335
1336 rc = 1;
1337fail_capture:
1338 if (!subsystem->use_xshm && image)
1339 XDestroyImage(image);
1340
1341 return rc;
1342}
1343
1344WINPR_ATTR_NODISCARD
1345static int x11_shadow_subsystem_process_message(x11ShadowSubsystem* subsystem, wMessage* message)
1346{
1347 switch (message->id)
1348 {
1349 case SHADOW_MSG_IN_REFRESH_REQUEST_ID:
1350 shadow_subsystem_frame_update((rdpShadowSubsystem*)subsystem);
1351 break;
1352
1353 default:
1354 WLog_ERR(TAG, "Unknown message id: %" PRIu32 "", message->id);
1355 break;
1356 }
1357
1358 if (message->Free)
1359 message->Free(message);
1360
1361 return 1;
1362}
1363
1364WINPR_ATTR_NODISCARD
1365static DWORD WINAPI x11_shadow_subsystem_thread(LPVOID arg)
1366{
1367 x11ShadowSubsystem* subsystem = (x11ShadowSubsystem*)arg;
1368 XEvent xevent;
1369 DWORD status = 0;
1370 DWORD nCount = 0;
1371 DWORD dwInterval = 0;
1372 UINT64 frameTime = 0;
1373 HANDLE events[32];
1374 wMessage message;
1375 wMessagePipe* MsgPipe = nullptr;
1376 MsgPipe = subsystem->common.MsgPipe;
1377 nCount = 0;
1378 events[nCount++] = subsystem->common.event;
1379 events[nCount++] = MessageQueue_Event(MsgPipe->In);
1380 subsystem->common.captureFrameRate = 16;
1381 dwInterval = 1000 / subsystem->common.captureFrameRate;
1382 frameTime = GetTickCount64() + dwInterval;
1383
1384 while (1)
1385 {
1386 const UINT64 cTime = GetTickCount64();
1387 const DWORD dwTimeout =
1388 (DWORD)((cTime > frameTime) ? 0 : MIN(UINT32_MAX, frameTime - cTime));
1389 status = WaitForMultipleObjects(nCount, events, FALSE, dwTimeout);
1390
1391 if (WaitForSingleObject(MessageQueue_Event(MsgPipe->In), 0) == WAIT_OBJECT_0)
1392 {
1393 if (MessageQueue_Peek(MsgPipe->In, &message, TRUE))
1394 {
1395 if (message.id == WMQ_QUIT)
1396 break;
1397
1398 const int rc = x11_shadow_subsystem_process_message(subsystem, &message);
1399 if (rc < 0)
1400 break;
1401 }
1402 }
1403
1404 if (WaitForSingleObject(subsystem->common.event, 0) == WAIT_OBJECT_0)
1405 {
1406 int rc = 0;
1407 XLockDisplay(subsystem->display);
1408
1409 if (XEventsQueued(subsystem->display, QueuedAlready))
1410 {
1411 XNextEvent(subsystem->display, &xevent);
1412 rc = x11_shadow_handle_xevent(subsystem, &xevent);
1413 }
1414
1415 XUnlockDisplay(subsystem->display);
1416 if (rc < 0)
1417 break;
1418 }
1419
1420 if ((status == WAIT_TIMEOUT) || (GetTickCount64() > frameTime))
1421 {
1422 const int rc1 = x11_shadow_check_resize(subsystem);
1423 if (rc1 < 0)
1424 break;
1425 const int rc2 = x11_shadow_screen_grab(subsystem);
1426 if (rc2 < 0)
1427 break;
1428 const int rc3 = x11_shadow_query_cursor(subsystem, FALSE);
1429 if (rc3 < 0)
1430 break;
1431 dwInterval = 1000 / subsystem->common.captureFrameRate;
1432 frameTime += dwInterval;
1433 }
1434 }
1435
1436 ExitThread(0);
1437 return 0;
1438}
1439
1440WINPR_ATTR_NODISCARD
1441static int x11_shadow_subsystem_base_init(x11ShadowSubsystem* subsystem)
1442{
1443 if (subsystem->display)
1444 return 1; /* initialize once */
1445
1446 // NOLINTNEXTLINE(concurrency-mt-unsafe)
1447 if (!getenv("DISPLAY"))
1448 {
1449 // NOLINTNEXTLINE(concurrency-mt-unsafe)
1450 setenv("DISPLAY", ":0", 1);
1451 }
1452
1453 if (!XInitThreads())
1454 return -1;
1455
1456 subsystem->display = XOpenDisplay(nullptr);
1457
1458 if (!subsystem->display)
1459 {
1460 WLog_ERR(TAG, "failed to open display: %s", XDisplayName(nullptr));
1461 return -1;
1462 }
1463
1464 subsystem->xfds = ConnectionNumber(subsystem->display);
1465 subsystem->number = DefaultScreen(subsystem->display);
1466 subsystem->screen = ScreenOfDisplay(subsystem->display, subsystem->number);
1467 subsystem->depth = WINPR_ASSERTING_INT_CAST(UINT32, DefaultDepthOfScreen(subsystem->screen));
1468 subsystem->width = WINPR_ASSERTING_INT_CAST(UINT32, WidthOfScreen(subsystem->screen));
1469 subsystem->height = WINPR_ASSERTING_INT_CAST(UINT32, HeightOfScreen(subsystem->screen));
1470 subsystem->root_window = RootWindow(subsystem->display, subsystem->number);
1471 return 1;
1472}
1473
1474WINPR_ATTR_NODISCARD
1475static int x11_shadow_xfixes_init(x11ShadowSubsystem* subsystem)
1476{
1477#ifdef WITH_XFIXES
1478 int xfixes_event = 0;
1479 int xfixes_error = 0;
1480 int major = 0;
1481 int minor = 0;
1482
1483 if (!XFixesQueryExtension(subsystem->display, &xfixes_event, &xfixes_error))
1484 return -1;
1485
1486 if (!XFixesQueryVersion(subsystem->display, &major, &minor))
1487 return -1;
1488
1489 subsystem->xfixes_cursor_notify_event = xfixes_event + XFixesCursorNotify;
1490 XFixesSelectCursorInput(subsystem->display, subsystem->root_window,
1491 XFixesDisplayCursorNotifyMask);
1492 return 1;
1493#else
1494 return -1;
1495#endif
1496}
1497
1498WINPR_ATTR_NODISCARD
1499static int x11_shadow_xinerama_init(x11ShadowSubsystem* subsystem)
1500{
1501#ifdef WITH_XINERAMA
1502 int xinerama_event = 0;
1503 int xinerama_error = 0;
1504
1505 const int rc = x11_shadow_subsystem_base_init(subsystem);
1506 if (rc < 0)
1507 return rc;
1508
1509 if (!XineramaQueryExtension(subsystem->display, &xinerama_event, &xinerama_error))
1510 return -1;
1511
1512#if defined(WITH_XDAMAGE)
1513 int major = 0;
1514 int minor = 0;
1515 if (!XDamageQueryVersion(subsystem->display, &major, &minor))
1516 return -1;
1517#endif
1518
1519 if (!XineramaIsActive(subsystem->display))
1520 return -1;
1521
1522 return 1;
1523#else
1524 return -1;
1525#endif
1526}
1527
1528WINPR_ATTR_NODISCARD
1529static int x11_shadow_xdamage_init(x11ShadowSubsystem* subsystem)
1530{
1531#ifdef WITH_XDAMAGE
1532 int major = 0;
1533 int minor = 0;
1534 int damage_event = 0;
1535 int damage_error = 0;
1536
1537 if (!subsystem->use_xfixes)
1538 return -1;
1539
1540 if (!XDamageQueryExtension(subsystem->display, &damage_event, &damage_error))
1541 return -1;
1542
1543 if (!XDamageQueryVersion(subsystem->display, &major, &minor))
1544 return -1;
1545
1546 if (major < 1)
1547 return -1;
1548
1549 subsystem->xdamage_notify_event = damage_event + XDamageNotify;
1550 subsystem->xdamage =
1551 XDamageCreate(subsystem->display, subsystem->root_window, XDamageReportDeltaRectangles);
1552
1553 if (!subsystem->xdamage)
1554 return -1;
1555
1556#ifdef WITH_XFIXES
1557 subsystem->xdamage_region = XFixesCreateRegion(subsystem->display, nullptr, 0);
1558
1559 if (!subsystem->xdamage_region)
1560 return -1;
1561
1562#endif
1563 return 1;
1564#else
1565 return -1;
1566#endif
1567}
1568
1569WINPR_ATTR_NODISCARD
1570static int x11_shadow_xshm_init(x11ShadowSubsystem* subsystem)
1571{
1572 Bool pixmaps = 0;
1573 int major = 0;
1574 int minor = 0;
1575 XGCValues values;
1576
1577 if (!XShmQueryExtension(subsystem->display))
1578 return -1;
1579
1580 if (!XShmQueryVersion(subsystem->display, &major, &minor, &pixmaps))
1581 return -1;
1582
1583 if (!pixmaps)
1584 return -1;
1585
1586 subsystem->fb_shm_info.shmid = -1;
1587 subsystem->fb_shm_info.shmaddr = (char*)-1;
1588 subsystem->fb_shm_info.readOnly = False;
1589 subsystem->fb_image =
1590 XShmCreateImage(subsystem->display, subsystem->visual, subsystem->depth, ZPixmap, nullptr,
1591 &(subsystem->fb_shm_info), subsystem->width, subsystem->height);
1592
1593 if (!subsystem->fb_image)
1594 {
1595 WLog_ERR(TAG, "XShmCreateImage failed");
1596 return -1;
1597 }
1598
1599 subsystem->fb_shm_info.shmid =
1600 shmget(IPC_PRIVATE,
1601 1ull * WINPR_ASSERTING_INT_CAST(uint32_t, subsystem->fb_image->bytes_per_line) *
1602 WINPR_ASSERTING_INT_CAST(uint32_t, subsystem->fb_image->height),
1603 IPC_CREAT | 0600);
1604
1605 if (subsystem->fb_shm_info.shmid == -1)
1606 {
1607 WLog_ERR(TAG, "shmget failed");
1608 return -1;
1609 }
1610
1611 subsystem->fb_shm_info.shmaddr = shmat(subsystem->fb_shm_info.shmid, nullptr, 0);
1612 subsystem->fb_image->data = subsystem->fb_shm_info.shmaddr;
1613
1614 if (subsystem->fb_shm_info.shmaddr == ((char*)-1))
1615 {
1616 WLog_ERR(TAG, "shmat failed");
1617 return -1;
1618 }
1619
1620 if (!XShmAttach(subsystem->display, &(subsystem->fb_shm_info)))
1621 return -1;
1622
1623 XSync(subsystem->display, False);
1624 shmctl(subsystem->fb_shm_info.shmid, IPC_RMID, nullptr);
1625 subsystem->fb_pixmap = XShmCreatePixmap(
1626 subsystem->display, subsystem->root_window, subsystem->fb_image->data,
1627 &(subsystem->fb_shm_info), WINPR_ASSERTING_INT_CAST(uint32_t, subsystem->fb_image->width),
1628 WINPR_ASSERTING_INT_CAST(uint32_t, subsystem->fb_image->height),
1629 WINPR_ASSERTING_INT_CAST(uint32_t, subsystem->fb_image->depth));
1630 XSync(subsystem->display, False);
1631
1632 if (!subsystem->fb_pixmap)
1633 return -1;
1634
1635 values.subwindow_mode = IncludeInferiors;
1636 values.graphics_exposures = False;
1637#if defined(WITH_XDAMAGE)
1638 subsystem->xshm_gc = XCreateGC(subsystem->display, subsystem->root_window,
1639 GCSubwindowMode | GCGraphicsExposures, &values);
1640 XSetFunction(subsystem->display, subsystem->xshm_gc, GXcopy);
1641#endif
1642 XSync(subsystem->display, False);
1643 return 1;
1644}
1645
1646UINT32 x11_shadow_enum_monitors(MONITOR_DEF* monitors, UINT32 maxMonitors)
1647{
1648 Display* display = nullptr;
1649 int displayWidth = 0;
1650 int displayHeight = 0;
1651 int numMonitors = 0;
1652
1653 // NOLINTNEXTLINE(concurrency-mt-unsafe)
1654 if (!getenv("DISPLAY"))
1655 {
1656 // NOLINTNEXTLINE(concurrency-mt-unsafe)
1657 setenv("DISPLAY", ":0", 1);
1658 }
1659
1660 display = XOpenDisplay(nullptr);
1661
1662 if (!display)
1663 {
1664 WLog_ERR(TAG, "failed to open display: %s", XDisplayName(nullptr));
1665 return 0;
1666 }
1667
1668 displayWidth = WidthOfScreen(DefaultScreenOfDisplay(display));
1669 displayHeight = HeightOfScreen(DefaultScreenOfDisplay(display));
1670#ifdef WITH_XINERAMA
1671 {
1672#if defined(WITH_XDAMAGE)
1673 int major = 0;
1674 int minor = 0;
1675#endif
1676 int xinerama_event = 0;
1677 int xinerama_error = 0;
1678 XineramaScreenInfo* screens = nullptr;
1679
1680 const Bool xinerama = XineramaQueryExtension(display, &xinerama_event, &xinerama_error);
1681 const Bool damage =
1682#if defined(WITH_XDAMAGE)
1683 XDamageQueryVersion(display, &major, &minor);
1684#else
1685 False;
1686#endif
1687
1688 if (xinerama && damage && XineramaIsActive(display))
1689 {
1690 screens = XineramaQueryScreens(display, &numMonitors);
1691
1692 if (numMonitors > (INT64)maxMonitors)
1693 numMonitors = (int)maxMonitors;
1694
1695 if (screens && (numMonitors > 0))
1696 {
1697 for (int index = 0; index < numMonitors; index++)
1698 {
1699 MONITOR_DEF* monitor = &monitors[index];
1700 const XineramaScreenInfo* screen = &screens[index];
1701
1702 monitor->left = screen->x_org;
1703 monitor->top = screen->y_org;
1704 monitor->right = monitor->left + screen->width - 1;
1705 monitor->bottom = monitor->top + screen->height - 1;
1706 monitor->flags = (index == 0) ? 1 : 0;
1707 }
1708 }
1709
1710 XFree(screens);
1711 }
1712 }
1713#endif
1714 XCloseDisplay(display);
1715
1716 if (numMonitors < 1)
1717 {
1718 MONITOR_DEF* monitor = &monitors[0];
1719 numMonitors = 1;
1720
1721 monitor->left = 0;
1722 monitor->top = 0;
1723 monitor->right = displayWidth - 1;
1724 monitor->bottom = displayHeight - 1;
1725 monitor->flags = 1;
1726 }
1727
1728 errno = 0;
1729 return WINPR_ASSERTING_INT_CAST(uint32_t, numMonitors);
1730}
1731
1732WINPR_ATTR_NODISCARD
1733static int x11_shadow_subsystem_init(rdpShadowSubsystem* sub)
1734{
1735 int pf_count = 0;
1736 int vi_count = 0;
1737 int nextensions = 0;
1738 XVisualInfo xtemplate = WINPR_C_ARRAY_INIT;
1739 XPixmapFormatValues* pf = nullptr;
1740
1741 x11ShadowSubsystem* subsystem = (x11ShadowSubsystem*)sub;
1742
1743 if (!subsystem)
1744 return -1;
1745
1746 subsystem->common.numMonitors = x11_shadow_enum_monitors(subsystem->common.monitors, 16);
1747 const int rc = x11_shadow_subsystem_base_init(subsystem);
1748 if (rc < 0)
1749 return rc;
1750
1751 subsystem->format = (ImageByteOrder(subsystem->display) == LSBFirst) ? PIXEL_FORMAT_BGRA32
1752 : PIXEL_FORMAT_ARGB32;
1753
1754 if ((subsystem->depth != 24) && (subsystem->depth != 32))
1755 {
1756 WLog_ERR(TAG, "unsupported X11 server color depth: %" PRIu32, subsystem->depth);
1757 return -1;
1758 }
1759
1760 {
1761 char** extensions = XListExtensions(subsystem->display, &nextensions);
1762
1763 if (!extensions || (nextensions < 0))
1764 return -1;
1765
1766 for (int i = 0; i < nextensions; i++)
1767 {
1768 if (strcmp(extensions[i], "Composite") == 0)
1769 subsystem->composite = TRUE;
1770 }
1771
1772 XFreeExtensionList(extensions);
1773 }
1774
1775 if (subsystem->composite)
1776 subsystem->use_xdamage = FALSE;
1777
1778 {
1779 XPixmapFormatValues* pfs = XListPixmapFormats(subsystem->display, &pf_count);
1780
1781 if (!pfs)
1782 {
1783 WLog_ERR(TAG, "XListPixmapFormats failed");
1784 return -1;
1785 }
1786
1787 for (int i = 0; i < pf_count; i++)
1788 {
1789 pf = pfs + i;
1790
1791 if (pf->depth == (INT64)subsystem->depth)
1792 {
1793 subsystem->bpp = WINPR_ASSERTING_INT_CAST(uint32_t, pf->bits_per_pixel);
1794 subsystem->scanline_pad = WINPR_ASSERTING_INT_CAST(uint32_t, pf->scanline_pad);
1795 break;
1796 }
1797 }
1798
1799 XFree(pfs);
1800 }
1801
1802 xtemplate.class = TrueColor;
1803 xtemplate.screen = subsystem->number;
1804
1805 {
1806 XVisualInfo* vis = XGetVisualInfo(subsystem->display, VisualClassMask | VisualScreenMask,
1807 &xtemplate, &vi_count);
1808
1809 if (!vis)
1810 {
1811 WLog_ERR(TAG, "XGetVisualInfo failed");
1812 return -1;
1813 }
1814
1815 for (int i = 0; i < vi_count; i++)
1816 {
1817 XVisualInfo* vi = vis + i;
1818
1819 if (vi->depth == (INT64)subsystem->depth)
1820 {
1821 subsystem->visual = vi->visual;
1822 break;
1823 }
1824 }
1825
1826 XFree(vis);
1827 }
1828
1829 XSelectInput(subsystem->display, subsystem->root_window, SubstructureNotifyMask);
1830 subsystem->cursorMaxWidth = 256;
1831 subsystem->cursorMaxHeight = 256;
1832 subsystem->cursorPixels =
1833 winpr_aligned_calloc(4ULL * subsystem->cursorMaxWidth, subsystem->cursorMaxHeight, 16);
1834
1835 if (!subsystem->cursorPixels)
1836 return -1;
1837
1838 const int rc1 = x11_shadow_query_cursor(subsystem, TRUE);
1839 if (rc1 < 0)
1840 return rc1;
1841
1842 if (subsystem->use_xfixes)
1843 {
1844 if (x11_shadow_xfixes_init(subsystem) < 0)
1845 subsystem->use_xfixes = FALSE;
1846 }
1847
1848 if (subsystem->use_xinerama)
1849 {
1850 if (x11_shadow_xinerama_init(subsystem) < 0)
1851 subsystem->use_xinerama = FALSE;
1852 }
1853
1854 if (subsystem->use_xshm)
1855 {
1856 if (x11_shadow_xshm_init(subsystem) < 0)
1857 subsystem->use_xshm = FALSE;
1858 }
1859
1860 if (subsystem->use_xdamage)
1861 {
1862 if (x11_shadow_xdamage_init(subsystem) < 0)
1863 subsystem->use_xdamage = FALSE;
1864 }
1865
1866 if (!(subsystem->common.event =
1867 CreateFileDescriptorEvent(nullptr, FALSE, FALSE, subsystem->xfds, WINPR_FD_READ)))
1868 return -1;
1869
1870 {
1871 MONITOR_DEF* virtualScreen = &(subsystem->common.virtualScreen);
1872 virtualScreen->left = 0;
1873 virtualScreen->top = 0;
1874 WINPR_ASSERT(subsystem->width <= INT32_MAX);
1875 WINPR_ASSERT(subsystem->height <= INT32_MAX);
1876 virtualScreen->right = (INT32)subsystem->width - 1;
1877 virtualScreen->bottom = (INT32)subsystem->height - 1;
1878 virtualScreen->flags = 1;
1879 WLog_INFO(TAG,
1880 "X11 Extensions: XFixes: %" PRId32 " Xinerama: %" PRId32 " XDamage: %" PRId32
1881 " XShm: %" PRId32 "",
1882 subsystem->use_xfixes, subsystem->use_xinerama, subsystem->use_xdamage,
1883 subsystem->use_xshm);
1884 }
1885
1886 return 1;
1887}
1888
1889static int x11_shadow_subsystem_uninit(rdpShadowSubsystem* sub)
1890{
1891 x11ShadowSubsystem* subsystem = (x11ShadowSubsystem*)sub;
1892
1893 if (!subsystem)
1894 return -1;
1895
1896 if (subsystem->display)
1897 {
1898 XCloseDisplay(subsystem->display);
1899 subsystem->display = nullptr;
1900 }
1901
1902 if (subsystem->common.event)
1903 {
1904 (void)CloseHandle(subsystem->common.event);
1905 subsystem->common.event = nullptr;
1906 }
1907
1908 if (subsystem->cursorPixels)
1909 {
1910 winpr_aligned_free(subsystem->cursorPixels);
1911 subsystem->cursorPixels = nullptr;
1912 }
1913
1914 return 1;
1915}
1916
1917WINPR_ATTR_NODISCARD
1918static int x11_shadow_subsystem_start(rdpShadowSubsystem* sub)
1919{
1920 x11ShadowSubsystem* subsystem = (x11ShadowSubsystem*)sub;
1921
1922 if (!subsystem)
1923 return -1;
1924
1925 if (!(subsystem->thread =
1926 CreateThread(nullptr, 0, x11_shadow_subsystem_thread, (void*)subsystem, 0, nullptr)))
1927 {
1928 WLog_ERR(TAG, "Failed to create thread");
1929 return -1;
1930 }
1931
1932 return 1;
1933}
1934
1935WINPR_ATTR_NODISCARD
1936static int x11_shadow_subsystem_stop(rdpShadowSubsystem* sub)
1937{
1938 x11ShadowSubsystem* subsystem = (x11ShadowSubsystem*)sub;
1939
1940 if (!subsystem)
1941 return -1;
1942
1943 if (subsystem->thread)
1944 {
1945 if (MessageQueue_PostQuit(subsystem->common.MsgPipe->In, 0))
1946 (void)WaitForSingleObject(subsystem->thread, INFINITE);
1947
1948 (void)CloseHandle(subsystem->thread);
1949 subsystem->thread = nullptr;
1950 }
1951
1952 return 1;
1953}
1954
1955WINPR_ATTR_NODISCARD
1956static rdpShadowSubsystem* x11_shadow_subsystem_new(void)
1957{
1958 x11ShadowSubsystem* subsystem = (x11ShadowSubsystem*)calloc(1, sizeof(x11ShadowSubsystem));
1959
1960 if (!subsystem)
1961 return nullptr;
1962
1963#ifdef WITH_PAM
1964 subsystem->common.Authenticate = x11_shadow_pam_authenticate;
1965#endif
1966 subsystem->common.SynchronizeEvent = x11_shadow_input_synchronize_event;
1967 subsystem->common.KeyboardEvent = x11_shadow_input_keyboard_event;
1968 subsystem->common.UnicodeKeyboardEvent = x11_shadow_input_unicode_keyboard_event;
1969 subsystem->common.MouseEvent = x11_shadow_input_mouse_event;
1970 subsystem->common.RelMouseEvent = x11_shadow_input_rel_mouse_event;
1971 subsystem->common.ExtendedMouseEvent = x11_shadow_input_extended_mouse_event;
1972 subsystem->composite = FALSE;
1973 subsystem->use_xshm = FALSE; /* temporarily disabled */
1974 subsystem->use_xfixes = TRUE;
1975 subsystem->use_xdamage = FALSE;
1976 subsystem->use_xinerama = TRUE;
1977 return &subsystem->common;
1978}
1979
1980static void x11_shadow_subsystem_free(rdpShadowSubsystem* subsystem)
1981{
1982 if (!subsystem)
1983 return;
1984
1985 x11_shadow_subsystem_uninit(subsystem);
1986 free(subsystem);
1987}
1988
1989FREERDP_ENTRY_POINT(FREERDP_API WINPR_ATTR_NODISCARD const char* ShadowSubsystemName(void))
1990{
1991 return "X11";
1992}
1993
1994FREERDP_ENTRY_POINT(FREERDP_API WINPR_ATTR_NODISCARD int ShadowSubsystemEntry(
1995 RDP_SHADOW_ENTRY_POINTS* pEntryPoints))
1996{
1997 if (!pEntryPoints)
1998 return -1;
1999
2000 pEntryPoints->New = x11_shadow_subsystem_new;
2001 pEntryPoints->Free = x11_shadow_subsystem_free;
2002 pEntryPoints->Init = x11_shadow_subsystem_init;
2003 pEntryPoints->Uninit = x11_shadow_subsystem_uninit;
2004 pEntryPoints->Start = x11_shadow_subsystem_start;
2005 pEntryPoints->Stop = x11_shadow_subsystem_stop;
2006 pEntryPoints->EnumMonitors = x11_shadow_enum_monitors;
2007 return 1;
2008}