FreeRDP
Loading...
Searching...
No Matches
wf_client.c
1
22#include <freerdp/config.h>
23
24#include <winpr/windows.h>
25#include <winpr/library.h>
26
27#include <winpr/crt.h>
28#include <winpr/assert.h>
29
30#include <errno.h>
31#include <stdio.h>
32#include <stdlib.h>
33#include <string.h>
34#include <tchar.h>
35#include <winpr/assert.h>
36#include <sys/types.h>
37#include <io.h>
38
39#ifdef WITH_PROGRESS_BAR
40#include <shobjidl.h>
41#endif
42
43#ifdef WITH_WINDOWS_CERT_STORE
44#include <wincrypt.h>
45#endif
46
47#include <freerdp/log.h>
48#include <freerdp/freerdp.h>
49#include <freerdp/constants.h>
50#include <freerdp/settings.h>
51
52#include <freerdp/locale/locale.h>
53#include <freerdp/locale/keyboard.h>
54#include <freerdp/codec/region.h>
55#include <freerdp/client/cmdline.h>
56#include <freerdp/client/channels.h>
57#include <freerdp/channels/channels.h>
58#include <freerdp/utils/signal.h>
59
60#include "wf_gdi.h"
61#include "wf_rail.h"
62#include "wf_channels.h"
63#include "wf_graphics.h"
64
65#include "resource/resource.h"
66
67#define TAG CLIENT_TAG("windows")
68
69#define WM_FREERDP_SHOWWINDOW (WM_USER + 100)
70
71static BOOL wf_has_console(void)
72{
73#ifdef WITH_WIN_CONSOLE
74 int file = _fileno(stdin);
75 int tty = _isatty(file);
76#else
77 int file = -1;
78 int tty = 0;
79#endif
80
81 WLog_INFO(TAG, "Detected stdin=%d -> %s mode", file, tty ? "console" : "gui");
82 return tty;
83}
84
85static BOOL wf_end_paint(rdpContext* context)
86{
87 RECT updateRect = WINPR_C_ARRAY_INIT;
88 REGION16 invalidRegion = WINPR_C_ARRAY_INIT;
89 RECTANGLE_16 invalidRect = WINPR_C_ARRAY_INIT;
90 const RECTANGLE_16* extents = nullptr;
91
92 WINPR_ASSERT(context);
93
94 wfContext* wfc = (wfContext*)context;
95 rdpGdi* gdi = context->gdi;
96 WINPR_ASSERT(gdi);
97
98 HGDI_DC hdc = gdi->primary->hdc;
99 WINPR_ASSERT(hdc);
100 if (!hdc->hwnd)
101 return TRUE;
102
103 HGDI_WND hwnd = hdc->hwnd;
104 WINPR_ASSERT(hwnd->invalid || (hwnd->ninvalid == 0));
105
106 if (hwnd->invalid->null)
107 return TRUE;
108
109 const int ninvalid = hwnd->ninvalid;
110 const HGDI_RGN cinvalid = hwnd->cinvalid;
111
112 if (ninvalid < 1)
113 return TRUE;
114
115 region16_init(&invalidRegion);
116
117 for (int i = 0; i < ninvalid; i++)
118 {
119 invalidRect.left = cinvalid[i].x;
120 invalidRect.top = cinvalid[i].y;
121 invalidRect.right = cinvalid[i].x + cinvalid[i].w;
122 invalidRect.bottom = cinvalid[i].y + cinvalid[i].h;
123 region16_union_rect(&invalidRegion, &invalidRegion, &invalidRect);
124 }
125
126 if (!region16_is_empty(&invalidRegion))
127 {
128 extents = region16_extents(&invalidRegion);
129 updateRect.left = extents->left;
130 updateRect.top = extents->top;
131 updateRect.right = extents->right;
132 updateRect.bottom = extents->bottom;
133
134 wf_scale_rect(wfc, &updateRect);
135
136 InvalidateRect(wfc->hwnd, &updateRect, FALSE);
137
138 if (wfc->rail)
139 wf_rail_invalidate_region(wfc, &invalidRegion);
140 }
141
142 region16_uninit(&invalidRegion);
143
144 if (!wfc->is_shown)
145 {
146 wfc->is_shown = TRUE;
147
148#ifdef WITH_PROGRESS_BAR
149 if (wfc->taskBarList)
150 {
151 wfc->taskBarList->lpVtbl->SetProgressState(wfc->taskBarList, wfc->hwnd,
152 TBPF_NOPROGRESS);
153 }
154#endif
155
156 PostMessage(wfc->hwnd, WM_FREERDP_SHOWWINDOW, 0, 0);
157 WLog_INFO(TAG, "Window is shown!");
158 }
159 return TRUE;
160}
161
162static BOOL wf_begin_paint(rdpContext* context)
163{
164 HGDI_DC hdc;
165
166 if (!context || !context->gdi || !context->gdi->primary || !context->gdi->primary->hdc)
167 return FALSE;
168
169 hdc = context->gdi->primary->hdc;
170
171 if (!hdc || !hdc->hwnd || !hdc->hwnd->invalid)
172 return FALSE;
173
174 hdc->hwnd->invalid->null = TRUE;
175 hdc->hwnd->ninvalid = 0;
176 return TRUE;
177}
178
179static BOOL wf_desktop_resize(rdpContext* context)
180{
181 BOOL same;
182 RECT rect;
183 rdpSettings* settings;
184 wfContext* wfc = (wfContext*)context;
185
186 if (!context || !context->settings)
187 return FALSE;
188
189 settings = context->settings;
190
191 if (wfc->primary)
192 {
193 same = (wfc->primary == wfc->drawing) ? TRUE : FALSE;
194 wf_image_free(wfc->primary);
195 wfc->primary =
196 wf_image_new(wfc, freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth),
197 freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight),
198 context->gdi->dstFormat, nullptr);
199 }
200
201 if (!gdi_resize_ex(context->gdi, freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth),
202 freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight), 0,
203 context->gdi->dstFormat, wfc->primary->pdata, nullptr))
204 return FALSE;
205
206 if (same)
207 wfc->drawing = wfc->primary;
208
209 if (wfc->fullscreen != TRUE)
210 {
211 if (wfc->hwnd && !freerdp_settings_get_bool(settings, FreeRDP_SmartSizing))
212 SetWindowPos(wfc->hwnd, HWND_TOP, -1, -1,
213 freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) + wfc->diff.x,
214 freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight) + wfc->diff.y,
215 SWP_NOMOVE);
216 }
217 else
218 {
219 wf_update_offset(wfc);
220 GetWindowRect(wfc->hwnd, &rect);
221 InvalidateRect(wfc->hwnd, &rect, TRUE);
222 }
223
224 return TRUE;
225}
226
227static BOOL wf_pre_connect(freerdp* instance)
228{
229 WINPR_ASSERT(instance);
230 WINPR_ASSERT(instance->context);
231 WINPR_ASSERT(instance->context->settings);
232
233 rdpContext* context = instance->context;
234 wfContext* wfc = (wfContext*)instance->context;
235 rdpSettings* settings = context->settings;
236 if (!freerdp_settings_set_uint32(settings, FreeRDP_OsMajorType, OSMAJORTYPE_WINDOWS))
237 return FALSE;
238 if (!freerdp_settings_set_uint32(settings, FreeRDP_OsMinorType, OSMINORTYPE_WINDOWS_NT))
239 return FALSE;
240 wfc->fullscreen = freerdp_settings_get_bool(settings, FreeRDP_Fullscreen);
241 wfc->fullscreen_toggle = freerdp_settings_get_bool(settings, FreeRDP_ToggleFullscreen);
242 UINT32 desktopWidth = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth);
243 UINT32 desktopHeight = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight);
244
245 if (wfc->percentscreen > 0)
246 {
247 desktopWidth = (GetSystemMetrics(SM_CXSCREEN) * wfc->percentscreen) / 100;
248 if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopWidth, desktopWidth))
249 return FALSE;
250 desktopHeight = (GetSystemMetrics(SM_CYSCREEN) * wfc->percentscreen) / 100;
251 if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopHeight, desktopHeight))
252 return FALSE;
253 }
254
255 if (wfc->fullscreen)
256 {
257 if (freerdp_settings_get_bool(settings, FreeRDP_UseMultimon))
258 {
259 desktopWidth = GetSystemMetrics(SM_CXVIRTUALSCREEN);
260 desktopHeight = GetSystemMetrics(SM_CYVIRTUALSCREEN);
261 }
262 else
263 {
264 desktopWidth = GetSystemMetrics(SM_CXSCREEN);
265 desktopHeight = GetSystemMetrics(SM_CYSCREEN);
266 }
267 }
268
269 /* FIXME: desktopWidth has a limitation that it should be divisible by 4,
270 * otherwise the screen will crash when connecting to an XP desktop.*/
271 desktopWidth = (desktopWidth + 3) & (~3);
272
273 if (desktopWidth != freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth))
274 {
275 if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopWidth, desktopWidth))
276 return FALSE;
277 }
278
279 if (desktopHeight != freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight))
280 {
281 if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopHeight, desktopHeight))
282 return FALSE;
283 }
284
285 DWORD keyboardLayoutId = freerdp_settings_get_uint32(settings, FreeRDP_KeyboardLayout);
286
287 {
288 CHAR name[KL_NAMELENGTH + 1] = WINPR_C_ARRAY_INIT;
289 if (GetKeyboardLayoutNameA(name))
290 {
291 ULONG rc = 0;
292
293 errno = 0;
294 rc = strtoul(name, nullptr, 16);
295 if (errno == 0)
296 keyboardLayoutId = rc;
297 }
298
299 if (keyboardLayoutId == 0)
300 {
301 const HKL layout = GetKeyboardLayout(0);
302 const uint32_t masked = (uint32_t)(((uintptr_t)layout >> 16) & 0xFFFF);
303 keyboardLayoutId = masked;
304 }
305 }
306
307 if (keyboardLayoutId == 0)
308 freerdp_detect_keyboard_layout_from_system_locale(&keyboardLayoutId);
309 if (keyboardLayoutId == 0)
310 keyboardLayoutId = ENGLISH_UNITED_STATES;
311 if (!freerdp_settings_set_uint32(settings, FreeRDP_KeyboardLayout, keyboardLayoutId))
312 return FALSE;
313 PubSub_SubscribeChannelConnected(instance->context->pubSub, wf_OnChannelConnectedEventHandler);
314 PubSub_SubscribeChannelDisconnected(instance->context->pubSub,
315 wf_OnChannelDisconnectedEventHandler);
316 return TRUE;
317}
318
319static void wf_append_item_to_system_menu(HMENU hMenu, UINT fMask, UINT wID, const wchar_t* text,
320 wfContext* wfc)
321{
322 MENUITEMINFO item_info = WINPR_C_ARRAY_INIT;
323 item_info.fMask = fMask;
324 item_info.cbSize = sizeof(MENUITEMINFO);
325 item_info.wID = wID;
326 item_info.fType = MFT_STRING;
327 item_info.dwTypeData = _wcsdup(text);
328 item_info.cch = (UINT)_wcslen(text);
329 if (wfc)
330 item_info.dwItemData = (ULONG_PTR)wfc;
331 InsertMenuItem(hMenu, wfc->systemMenuInsertPosition++, TRUE, &item_info);
332}
333
334static void wf_add_system_menu(wfContext* wfc)
335{
336 HMENU hMenu;
337
338 if (wfc->fullscreen && !wfc->fullscreen_toggle)
339 {
340 return;
341 }
342
343 if (freerdp_settings_get_bool(wfc->common.context.settings, FreeRDP_DynamicResolutionUpdate))
344 {
345 return;
346 }
347
348 hMenu = GetSystemMenu(wfc->hwnd, FALSE);
349
350 wf_append_item_to_system_menu(hMenu,
351 MIIM_CHECKMARKS | MIIM_FTYPE | MIIM_ID | MIIM_STRING | MIIM_DATA,
352 SYSCOMMAND_ID_SMARTSIZING, L"Smart sizing", wfc);
353
354 if (freerdp_settings_get_bool(wfc->common.context.settings, FreeRDP_SmartSizing))
355 {
356 CheckMenuItem(hMenu, SYSCOMMAND_ID_SMARTSIZING, MF_CHECKED);
357 }
358
359 if (freerdp_settings_get_bool(wfc->common.context.settings, FreeRDP_RemoteAssistanceMode))
360 wf_append_item_to_system_menu(hMenu, MIIM_FTYPE | MIIM_ID | MIIM_STRING,
361 SYSCOMMAND_ID_REQUEST_CONTROL, L"Request control", wfc);
362}
363
364static WCHAR* wf_window_get_title(rdpSettings* settings)
365{
366 BOOL port;
367 WCHAR* windowTitle = nullptr;
368 size_t size;
369 WCHAR prefix[] = L"FreeRDP:";
370
371 if (!settings)
372 return nullptr;
373
374 const char* name = freerdp_settings_get_string(settings, FreeRDP_ServerHostname);
375
376 if (freerdp_settings_get_string(settings, FreeRDP_WindowTitle))
377 return ConvertUtf8ToWCharAlloc(freerdp_settings_get_string(settings, FreeRDP_WindowTitle),
378 nullptr);
379
380 port = (freerdp_settings_get_uint32(settings, FreeRDP_ServerPort) != 3389);
381 size = strlen(name) + 16 + wcslen(prefix);
382 windowTitle = calloc(size, sizeof(WCHAR));
383
384 if (!windowTitle)
385 return nullptr;
386
387 if (!port)
388 _snwprintf_s(windowTitle, size, _TRUNCATE, L"%s %S", prefix, name);
389 else
390 _snwprintf_s(windowTitle, size, _TRUNCATE, L"%s %S:%u", prefix, name,
391 freerdp_settings_get_uint32(settings, FreeRDP_ServerPort));
392
393 return windowTitle;
394}
395
396static BOOL wf_post_connect(freerdp* instance)
397{
398 rdpGdi* gdi;
399 DWORD dwStyle;
400 rdpCache* cache;
401 wfContext* wfc;
402 rdpContext* context;
403 rdpSettings* settings;
404 EmbedWindowEventArgs e;
405 const UINT32 format = PIXEL_FORMAT_BGRX32;
406
407 WINPR_ASSERT(instance);
408
409 context = instance->context;
410 WINPR_ASSERT(context);
411
412 settings = context->settings;
413 WINPR_ASSERT(settings);
414
415 wfc = (wfContext*)instance->context;
416 WINPR_ASSERT(wfc);
417
418 wfc->primary =
419 wf_image_new(wfc, freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth),
420 freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight), format, nullptr);
421
422 if (!wfc->primary)
423 {
424 WLog_ERR(TAG, "Failed to allocate primary surface");
425 return FALSE;
426 }
427
428 if (!gdi_init_ex(instance, format, 0, wfc->primary->pdata, nullptr))
429 return FALSE;
430
431 cache = instance->context->cache;
432 WINPR_ASSERT(cache);
433
434 gdi = instance->context->gdi;
435
436 if (!freerdp_settings_get_bool(settings, FreeRDP_SoftwareGdi))
437 {
438 wf_gdi_register_update_callbacks(context->update);
439 }
440
441 wfc->window_title = wf_window_get_title(settings);
442
443 if (!wfc->window_title)
444 return FALSE;
445
446 if (freerdp_settings_get_bool(settings, FreeRDP_EmbeddedWindow))
447 {
448 if (!freerdp_settings_set_bool(settings, FreeRDP_Decorations, FALSE))
449 return FALSE;
450 }
451
452 if (wfc->fullscreen)
453 dwStyle = WS_POPUP;
454 else if (!freerdp_settings_get_bool(settings, FreeRDP_Decorations))
455 dwStyle = WS_CHILD | WS_BORDER;
456 else
457 dwStyle =
458 WS_CAPTION | WS_OVERLAPPED | WS_SYSMENU | WS_MINIMIZEBOX | WS_SIZEBOX | WS_MAXIMIZEBOX;
459
460 if (!wfc->hwnd)
461 {
462 wfc->hwnd = CreateWindowEx(0, wfc->wndClassName, wfc->window_title, dwStyle, 0, 0, 0, 0,
463 wfc->hWndParent, nullptr, wfc->hInstance, nullptr);
464 if (!wfc->hwnd)
465 {
466 WLog_ERR(TAG, "CreateWindowEx failed with error: %lu", GetLastError());
467 return FALSE;
468 }
469 SetWindowLongPtr(wfc->hwnd, GWLP_USERDATA, (LONG_PTR)wfc);
470 }
471
472 wf_resize_window(wfc);
473 wf_add_system_menu(wfc);
474 BitBlt(wfc->primary->hdc, 0, 0, freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth),
475 freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight), nullptr, 0, 0, BLACKNESS);
476 wfc->drawing = wfc->primary;
477 EventArgsInit(&e, "wfreerdp");
478 e.embed = FALSE;
479 e.handle = (void*)wfc->hwnd;
480 PubSub_OnEmbedWindow(context->pubSub, context, &e);
481#ifdef WITH_PROGRESS_BAR
482 if (wfc->taskBarList)
483 {
484 ShowWindow(wfc->hwnd, SW_SHOWMINIMIZED);
485 wfc->taskBarList->lpVtbl->SetProgressState(wfc->taskBarList, wfc->hwnd, TBPF_INDETERMINATE);
486 }
487#endif
488 UpdateWindow(wfc->hwnd);
489 context->update->BeginPaint = wf_begin_paint;
490 context->update->DesktopResize = wf_desktop_resize;
491 context->update->EndPaint = wf_end_paint;
492 context->update->SetKeyboardIndicators = wf_keyboard_set_indicators;
493 wf_register_pointer(context->graphics);
494
495 wfc->floatbar = wf_floatbar_new(wfc, wfc->hInstance,
496 freerdp_settings_get_uint32(settings, FreeRDP_Floatbar));
497
498 wf_event_focus_in(wfc);
499
500 return TRUE;
501}
502
503static void wf_post_disconnect(freerdp* instance)
504{
505 wfContext* wfc;
506
507 if (!instance || !instance->context)
508 return;
509
510 wfc = (wfContext*)instance->context;
511 free(wfc->window_title);
512}
513
514static CREDUI_INFOW wfUiInfo = { sizeof(CREDUI_INFOW), nullptr, L"Enter your credentials",
515 L"Remote Desktop Security", nullptr };
516
517static BOOL wf_authenticate_ex(freerdp* instance, char** username, char** password, char** domain,
518 rdp_auth_reason reason)
519{
520 wfContext* wfc;
521 BOOL fSave;
522 DWORD status;
523 DWORD dwFlags;
524 WCHAR UserNameW[CREDUI_MAX_USERNAME_LENGTH + 1] = WINPR_C_ARRAY_INIT;
525 WCHAR UserW[CREDUI_MAX_USERNAME_LENGTH + 1] = WINPR_C_ARRAY_INIT;
526 WCHAR DomainW[CREDUI_MAX_DOMAIN_TARGET_LENGTH + 1] = WINPR_C_ARRAY_INIT;
527 WCHAR PasswordW[CREDUI_MAX_PASSWORD_LENGTH + 1] = WINPR_C_ARRAY_INIT;
528
529 WINPR_ASSERT(instance);
530 WINPR_ASSERT(instance->context);
531 WINPR_ASSERT(instance->context->settings);
532
533 wfc = (wfContext*)instance->context;
534 WINPR_ASSERT(wfc);
535
536 WINPR_ASSERT(username);
537 WINPR_ASSERT(domain);
538 WINPR_ASSERT(password);
539
540 const WCHAR auth[] = L"Target credentials requested";
541 const WCHAR authPin[] = L"PIN requested";
542 const WCHAR gwAuth[] = L"Gateway credentials requested";
543 const WCHAR* titleW = auth;
544
545 fSave = FALSE;
546 dwFlags = CREDUI_FLAGS_DO_NOT_PERSIST | CREDUI_FLAGS_EXCLUDE_CERTIFICATES |
547 CREDUI_FLAGS_USERNAME_TARGET_CREDENTIALS;
548 switch (reason)
549 {
550 case AUTH_NLA:
551 break;
552 case AUTH_TLS:
553 case AUTH_RDP:
554 if ((*username) && (*password))
555 return TRUE;
556 break;
557 case AUTH_SMARTCARD_PIN:
558 dwFlags &= ~CREDUI_FLAGS_USERNAME_TARGET_CREDENTIALS;
559 dwFlags |= CREDUI_FLAGS_PASSWORD_ONLY_OK | CREDUI_FLAGS_KEEP_USERNAME;
560 titleW = authPin;
561 if (*password)
562 return TRUE;
563 if (!(*username))
564 *username = _strdup("PIN");
565 break;
566 case GW_AUTH_HTTP:
567 case GW_AUTH_RDG:
568 case GW_AUTH_RPC:
569 titleW = gwAuth;
570 break;
571 default:
572 return FALSE;
573 }
574
575 if (*username)
576 {
577 (void)ConvertUtf8ToWChar(*username, UserNameW, ARRAYSIZE(UserNameW));
578 (void)ConvertUtf8ToWChar(*username, UserW, ARRAYSIZE(UserW));
579 }
580
581 if (*password)
582 (void)ConvertUtf8ToWChar(*password, PasswordW, ARRAYSIZE(PasswordW));
583
584 if (*domain)
585 (void)ConvertUtf8ToWChar(*domain, DomainW, ARRAYSIZE(DomainW));
586
587 if (_wcsnlen(PasswordW, ARRAYSIZE(PasswordW)) == 0)
588 {
589 if (!wfc->isConsole &&
590 freerdp_settings_get_bool(wfc->common.context.settings, FreeRDP_CredentialsFromStdin))
591 WLog_ERR(TAG, "Flag for stdin read present but stdin is redirected; using GUI");
592 if (wfc->isConsole &&
593 freerdp_settings_get_bool(wfc->common.context.settings, FreeRDP_CredentialsFromStdin))
594 status = CredUICmdLinePromptForCredentialsW(titleW, nullptr, 0, UserNameW,
595 ARRAYSIZE(UserNameW), PasswordW,
596 ARRAYSIZE(PasswordW), &fSave, dwFlags);
597 else
598 status = CredUIPromptForCredentialsW(&wfUiInfo, titleW, nullptr, 0, UserNameW,
599 ARRAYSIZE(UserNameW), PasswordW,
600 ARRAYSIZE(PasswordW), &fSave, dwFlags);
601 if (status != NO_ERROR)
602 {
603 WLog_ERR(TAG, "CredUIPromptForCredentials unexpected status: 0x%08lX", status);
604 return FALSE;
605 }
606
607 if ((dwFlags & CREDUI_FLAGS_KEEP_USERNAME) == 0)
608 {
609 status = CredUIParseUserNameW(UserNameW, UserW, ARRAYSIZE(UserW), DomainW,
610 ARRAYSIZE(DomainW));
611 if (status != NO_ERROR)
612 {
613 CHAR User[CREDUI_MAX_USERNAME_LENGTH + 1] = WINPR_C_ARRAY_INIT;
614 CHAR UserName[CREDUI_MAX_USERNAME_LENGTH + 1] = WINPR_C_ARRAY_INIT;
615 CHAR Domain[CREDUI_MAX_DOMAIN_TARGET_LENGTH + 1] = WINPR_C_ARRAY_INIT;
616
617 (void)ConvertWCharNToUtf8(UserNameW, ARRAYSIZE(UserNameW), UserName,
618 ARRAYSIZE(UserName));
619 (void)ConvertWCharNToUtf8(UserW, ARRAYSIZE(UserW), User, ARRAYSIZE(User));
620 (void)ConvertWCharNToUtf8(DomainW, ARRAYSIZE(DomainW), Domain, ARRAYSIZE(Domain));
621 WLog_ERR(TAG, "Failed to parse UserName: %s into User: %s Domain: %s", UserName,
622 User, Domain);
623 return FALSE;
624 }
625 }
626 }
627
628 *username = ConvertWCharNToUtf8Alloc(UserW, ARRAYSIZE(UserW), nullptr);
629 if (!(*username))
630 {
631 WLog_ERR(TAG, "ConvertWCharNToUtf8Alloc failed", status);
632 return FALSE;
633 }
634
635 if (_wcsnlen(DomainW, ARRAYSIZE(DomainW)) > 0)
636 *domain = ConvertWCharNToUtf8Alloc(DomainW, ARRAYSIZE(DomainW), nullptr);
637 else
638 *domain = _strdup("\0");
639
640 if (!(*domain))
641 {
642 free(*username);
643 WLog_ERR(TAG, "strdup failed", status);
644 return FALSE;
645 }
646
647 *password = ConvertWCharNToUtf8Alloc(PasswordW, ARRAYSIZE(PasswordW), nullptr);
648 if (!(*password))
649 {
650 free(*username);
651 free(*domain);
652 return FALSE;
653 }
654
655 return TRUE;
656}
657
658static WCHAR* wf_format_text(const WCHAR* fmt, ...)
659{
660 int rc;
661 size_t size = 0;
662 WCHAR* buffer = nullptr;
663
664 do
665 {
666 WCHAR* tmp = nullptr;
667 va_list ap = WINPR_C_ARRAY_INIT;
668 va_start(ap, fmt);
669 rc = _vsnwprintf(buffer, size, fmt, ap);
670 va_end(ap);
671 if (rc <= 0)
672 goto fail;
673
674 if ((size_t)rc < size)
675 return buffer;
676
677 size = (size_t)rc + 1;
678 tmp = realloc(buffer, size * sizeof(WCHAR));
679 if (!tmp)
680 goto fail;
681
682 buffer = tmp;
683 } while (TRUE);
684
685fail:
686 free(buffer);
687 return nullptr;
688}
689
690#ifdef WITH_WINDOWS_CERT_STORE
691/* https://stackoverflow.com/questions/1231178/load-an-pem-encoded-x-509-certificate-into-windows-cryptoapi/3803333#3803333
692 */
693/* https://github.com/microsoft/Windows-classic-samples/blob/main/Samples/Win7Samples/security/cryptoapi/peertrust/cpp/peertrust.cpp
694 */
695/* https://stackoverflow.com/questions/7340504/whats-the-correct-way-to-verify-an-ssl-certificate-in-win32
696 */
697
698static void wf_report_error(char* wszMessage, DWORD dwErrCode)
699{
700 LPSTR pwszMsgBuf = nullptr;
701
702 if (nullptr != wszMessage && 0 != *wszMessage)
703 {
704 WLog_ERR(TAG, "%s", wszMessage);
705 }
706
707 FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
708 nullptr, // Location of message
709 // definition ignored
710 dwErrCode, // Message identifier for
711 // the requested message
712 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Language identifier for
713 // the requested message
714 (LPSTR)&pwszMsgBuf, // Buffer that receives
715 // the formatted message
716 0, // Size of output buffer
717 // not needed as allocate
718 // buffer flag is set
719 nullptr // Array of insert values
720 );
721
722 if (nullptr != pwszMsgBuf)
723 {
724 WLog_ERR(TAG, "Error: 0x%08x (%d) %s", dwErrCode, dwErrCode, pwszMsgBuf);
725 LocalFree(pwszMsgBuf);
726 }
727 else
728 {
729 WLog_ERR(TAG, "Error: 0x%08x (%d)", dwErrCode, dwErrCode);
730 }
731}
732
733static DWORD wf_is_x509_certificate_trusted(const char* common_name, const char* subject,
734 const char* issuer, const char* fingerprint)
735{
736 HRESULT hr = CRYPT_E_NOT_FOUND;
737
738 DWORD dwChainFlags = CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;
739 PCCERT_CONTEXT pCert = nullptr;
740 HCERTCHAINENGINE hChainEngine = nullptr;
741 PCCERT_CHAIN_CONTEXT pChainContext = nullptr;
742
743 CERT_ENHKEY_USAGE EnhkeyUsage = WINPR_C_ARRAY_INIT;
744 CERT_USAGE_MATCH CertUsage = WINPR_C_ARRAY_INIT;
745 CERT_CHAIN_PARA ChainPara = WINPR_C_ARRAY_INIT;
746 CERT_CHAIN_POLICY_PARA ChainPolicy = WINPR_C_ARRAY_INIT;
747 CERT_CHAIN_POLICY_STATUS PolicyStatus = WINPR_C_ARRAY_INIT;
748 CERT_CHAIN_ENGINE_CONFIG EngineConfig = WINPR_C_ARRAY_INIT;
749
750 DWORD derPubKeyLen = WINPR_ASSERTING_INT_CAST(uint32_t, strlen(fingerprint));
751 char* derPubKey = calloc(derPubKeyLen, sizeof(char));
752 if (nullptr == derPubKey)
753 {
754 WLog_ERR(TAG, "Could not allocate derPubKey");
755 goto CleanUp;
756 }
757
758 /*
759 * Convert from PEM format to DER format - removes header and footer and decodes from base64
760 */
761 if (!CryptStringToBinaryA(fingerprint, 0, CRYPT_STRING_BASE64HEADER, derPubKey, &derPubKeyLen,
762 nullptr, nullptr))
763 {
764 WLog_ERR(TAG, "CryptStringToBinary failed. Err: %d", GetLastError());
765 goto CleanUp;
766 }
767
768 //---------------------------------------------------------
769 // Initialize data structures for chain building.
770
771 EnhkeyUsage.cUsageIdentifier = 0;
772 EnhkeyUsage.rgpszUsageIdentifier = nullptr;
773
774 CertUsage.dwType = USAGE_MATCH_TYPE_AND;
775 CertUsage.Usage = EnhkeyUsage;
776
777 ChainPara.cbSize = sizeof(ChainPara);
778 ChainPara.RequestedUsage = CertUsage;
779
780 ChainPolicy.cbSize = sizeof(ChainPolicy);
781
782 PolicyStatus.cbSize = sizeof(PolicyStatus);
783
784 EngineConfig.cbSize = sizeof(EngineConfig);
785 EngineConfig.dwUrlRetrievalTimeout = 0;
786
787 pCert = CertCreateCertificateContext(X509_ASN_ENCODING, derPubKey, derPubKeyLen);
788 if (nullptr == pCert)
789 {
790 WLog_ERR(TAG, "FAILED: Certificate could not be parsed.");
791 goto CleanUp;
792 }
793
794 dwChainFlags |= CERT_CHAIN_ENABLE_PEER_TRUST;
795
796 // When this flag is set, end entity certificates in the
797 // Trusted People store are trusted without doing any chain building
798 // This optimizes the chain building process.
799
800 //---------------------------------------------------------
801 // Create chain engine.
802
803 if (!CertCreateCertificateChainEngine(&EngineConfig, &hChainEngine))
804 {
805 hr = HRESULT_FROM_WIN32(GetLastError());
806 goto CleanUp;
807 }
808
809 //-------------------------------------------------------------------
810 // Build a chain using CertGetCertificateChain
811
812 if (!CertGetCertificateChain(hChainEngine, // use the default chain engine
813 pCert, // pointer to the end certificate
814 nullptr, // use the default time
815 nullptr, // search no additional stores
816 &ChainPara, // use AND logic and enhanced key usage
817 // as indicated in the ChainPara
818 // data structure
819 dwChainFlags,
820 nullptr, // currently reserved
821 &pChainContext)) // return a pointer to the chain created
822 {
823 hr = HRESULT_FROM_WIN32(GetLastError());
824 goto CleanUp;
825 }
826
827 //---------------------------------------------------------------
828 // Verify that the chain complies with policy
829
830 if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_BASE, // use the base policy
831 pChainContext, // pointer to the chain
832 &ChainPolicy,
833 &PolicyStatus)) // return a pointer to the policy status
834 {
835 hr = HRESULT_FROM_WIN32(GetLastError());
836 goto CleanUp;
837 }
838
839 if (PolicyStatus.dwError != S_OK)
840 {
841 wf_report_error("CertVerifyCertificateChainPolicy: Chain Status", PolicyStatus.dwError);
842 hr = PolicyStatus.dwError;
843 // Instruction: If the PolicyStatus.dwError is CRYPT_E_NO_REVOCATION_CHECK or
844 // CRYPT_E_REVOCATION_OFFLINE, it indicates errors in obtaining
845 // revocation information. These can be ignored since the retrieval of
846 // revocation information depends on network availability
847
848 if (PolicyStatus.dwError == CRYPT_E_NO_REVOCATION_CHECK ||
849 PolicyStatus.dwError == CRYPT_E_REVOCATION_OFFLINE)
850 {
851 hr = S_OK;
852 }
853
854 goto CleanUp;
855 }
856
857 WLog_INFO(TAG, "CertVerifyCertificateChainPolicy succeeded for %s (%s) issued by %s",
858 common_name, subject, issuer);
859
860 hr = S_OK;
861CleanUp:
862
863 if (FAILED(hr))
864 {
865 WLog_INFO(TAG, "CertVerifyCertificateChainPolicy failed for %s (%s) issued by %s",
866 common_name, subject, issuer);
867 wf_report_error(nullptr, hr);
868 }
869
870 free(derPubKey);
871
872 if (nullptr != pChainContext)
873 {
874 CertFreeCertificateChain(pChainContext);
875 }
876
877 if (nullptr != hChainEngine)
878 {
879 CertFreeCertificateChainEngine(hChainEngine);
880 }
881
882 if (nullptr != pCert)
883 {
884 CertFreeCertificateContext(pCert);
885 }
886
887 return (DWORD)hr;
888}
889#endif
890
891static DWORD wf_cli_verify_certificate_ex(freerdp* instance, const char* host, UINT16 port,
892 const char* common_name, const char* subject,
893 const char* issuer, const char* fingerprint, DWORD flags)
894{
895#ifdef WITH_WINDOWS_CERT_STORE
896 if (flags & VERIFY_CERT_FLAG_FP_IS_PEM && !(flags & VERIFY_CERT_FLAG_MISMATCH))
897 {
898 if (wf_is_x509_certificate_trusted(common_name, subject, issuer, fingerprint) == S_OK)
899 {
900 return 2;
901 }
902 }
903#endif
904
905 return client_cli_verify_certificate_ex(instance, host, port, common_name, subject, issuer,
906 fingerprint, flags);
907}
908
909static DWORD wf_verify_certificate_ex(freerdp* instance, const char* host, UINT16 port,
910 const char* common_name, const char* subject,
911 const char* issuer, const char* fingerprint, DWORD flags)
912{
913 WCHAR* buffer;
914 WCHAR* caption;
915 int what = IDCANCEL;
916
917#ifdef WITH_WINDOWS_CERT_STORE
918 if (flags & VERIFY_CERT_FLAG_FP_IS_PEM && !(flags & VERIFY_CERT_FLAG_MISMATCH))
919 {
920 if (wf_is_x509_certificate_trusted(common_name, subject, issuer, fingerprint) == S_OK)
921 {
922 return 2;
923 }
924 }
925#endif
926
927 buffer = wf_format_text(
928 L"Certificate details:\n"
929 L"\tCommonName: %S\n"
930 L"\tSubject: %S\n"
931 L"\tIssuer: %S\n"
932 L"\tThumbprint: %S\n"
933 L"\tHostMismatch: %S\n"
934 L"\n"
935 L"The above X.509 certificate could not be verified, possibly because you do not have "
936 L"the CA certificate in your certificate store, or the certificate has expired. "
937 L"Please look at the OpenSSL documentation on how to add a private CA to the store.\n"
938 L"\n"
939 L"YES\tAccept permanently\n"
940 L"NO\tAccept for this session only\n"
941 L"CANCEL\tAbort connection\n",
942 common_name, subject, issuer, fingerprint,
943 flags & VERIFY_CERT_FLAG_MISMATCH ? "Yes" : "No");
944 caption = wf_format_text(L"Verify certificate for %S:%hu", host, port);
945
946 WINPR_UNUSED(instance);
947
948 if (!buffer || !caption)
949 goto fail;
950
951 what = MessageBoxW(nullptr, buffer, caption, MB_YESNOCANCEL);
952fail:
953 free(buffer);
954 free(caption);
955
956 /* return 1 to accept and store a certificate, 2 to accept
957 * a certificate only for this session, 0 otherwise */
958 switch (what)
959 {
960 case IDYES:
961 return 1;
962 case IDNO:
963 return 2;
964 default:
965 return 0;
966 }
967}
968
969static DWORD wf_verify_changed_certificate_ex(freerdp* instance, const char* host, UINT16 port,
970 const char* common_name, const char* subject,
971 const char* issuer, const char* new_fingerprint,
972 const char* old_subject, const char* old_issuer,
973 const char* old_fingerprint, DWORD flags)
974{
975 WCHAR* buffer;
976 WCHAR* caption;
977 int what = IDCANCEL;
978
979 buffer = wf_format_text(
980 L"New Certificate details:\n"
981 L"\tCommonName: %S\n"
982 L"\tSubject: %S\n"
983 L"\tIssuer: %S\n"
984 L"\tThumbprint: %S\n"
985 L"\tHostMismatch: %S\n"
986 L"\n"
987 L"Old Certificate details:\n"
988 L"\tSubject: %S\n"
989 L"\tIssuer: %S\n"
990 L"\tThumbprint: %S"
991 L"The above X.509 certificate could not be verified, possibly because you do not have "
992 L"the CA certificate in your certificate store, or the certificate has expired. "
993 L"Please look at the OpenSSL documentation on how to add a private CA to the store.\n"
994 L"\n"
995 L"YES\tAccept permanently\n"
996 L"NO\tAccept for this session only\n"
997 L"CANCEL\tAbort connection\n",
998 common_name, subject, issuer, new_fingerprint,
999 flags & VERIFY_CERT_FLAG_MISMATCH ? "Yes" : "No", old_subject, old_issuer, old_fingerprint);
1000 caption = wf_format_text(L"Verify certificate change for %S:%hu", host, port);
1001
1002 WINPR_UNUSED(instance);
1003 if (!buffer || !caption)
1004 goto fail;
1005
1006 what = MessageBoxW(nullptr, buffer, caption, MB_YESNOCANCEL);
1007fail:
1008 free(buffer);
1009 free(caption);
1010
1011 /* return 1 to accept and store a certificate, 2 to accept
1012 * a certificate only for this session, 0 otherwise */
1013 switch (what)
1014 {
1015 case IDYES:
1016 return 1;
1017 case IDNO:
1018 return 2;
1019 default:
1020 return 0;
1021 }
1022}
1023
1024static BOOL wf_present_gateway_message(freerdp* instance, UINT32 type, BOOL isDisplayMandatory,
1025 BOOL isConsentMandatory, size_t length, const WCHAR* message)
1026{
1027 if (!isDisplayMandatory && !isConsentMandatory)
1028 return TRUE;
1029
1030 /* special handling for consent messages (show modal dialog) */
1031 if (type == GATEWAY_MESSAGE_CONSENT && isConsentMandatory)
1032 {
1033 int mbRes;
1034 WCHAR* msg;
1035
1036 msg = wf_format_text(L"%.*s\n\nI understand and agree to the terms of this policy", length,
1037 message);
1038 mbRes = MessageBoxW(nullptr, msg, L"Consent Message", MB_YESNO);
1039 free(msg);
1040
1041 if (mbRes != IDYES)
1042 return FALSE;
1043 }
1044 else
1045 return client_cli_present_gateway_message(instance, type, isDisplayMandatory,
1046 isConsentMandatory, length, message);
1047
1048 return TRUE;
1049}
1050
1051static DWORD WINAPI wf_client_thread(LPVOID lpParam)
1052{
1053 MSG msg = WINPR_C_ARRAY_INIT;
1054 int width = 0;
1055 int height = 0;
1056 BOOL msg_ret = FALSE;
1057 int quit_msg = 0;
1058 DWORD error = 0;
1059
1060 freerdp* instance = (freerdp*)lpParam;
1061 WINPR_ASSERT(instance);
1062
1063 if (!freerdp_connect(instance))
1064 goto end;
1065
1066 rdpContext* context = instance->context;
1067 WINPR_ASSERT(context);
1068
1069 wfContext* wfc = (wfContext*)instance->context;
1070 WINPR_ASSERT(wfc);
1071
1072 rdpChannels* channels = context->channels;
1073 WINPR_ASSERT(channels);
1074
1075 rdpSettings* settings = context->settings;
1076 WINPR_ASSERT(settings);
1077
1078 while (!freerdp_shall_disconnect_context(instance->context))
1079 {
1080 HANDLE handles[MAXIMUM_WAIT_OBJECTS] = WINPR_C_ARRAY_INIT;
1081 DWORD nCount = 0;
1082
1083 if (freerdp_focus_required(instance))
1084 {
1085 wf_event_focus_in(wfc);
1086 wf_event_focus_in(wfc);
1087 }
1088
1089 {
1090 DWORD tmp = freerdp_get_event_handles(context, &handles[nCount], 64 - nCount);
1091
1092 if (tmp == 0)
1093 {
1094 WLog_ERR(TAG, "freerdp_get_event_handles failed");
1095 break;
1096 }
1097
1098 nCount += tmp;
1099 }
1100
1101 DWORD status = MsgWaitForMultipleObjectsEx(nCount, handles, 5 * 1000, QS_ALLINPUT,
1102 MWMO_ALERTABLE | MWMO_INPUTAVAILABLE);
1103 if (status == WAIT_FAILED)
1104 {
1105 WLog_ERR(TAG, "wfreerdp_run: WaitForMultipleObjects failed: 0x%08lX", GetLastError());
1106 break;
1107 }
1108
1109 {
1110 if (!freerdp_check_event_handles(context))
1111 {
1112 if (client_auto_reconnect(instance))
1113 continue;
1114
1115 WLog_ERR(TAG, "Failed to check FreeRDP file descriptor");
1116 break;
1117 }
1118 }
1119
1120 if (freerdp_shall_disconnect_context(instance->context))
1121 break;
1122
1123 quit_msg = FALSE;
1124
1125 while (PeekMessage(&msg, nullptr, 0, 0, PM_NOREMOVE))
1126 {
1127 msg_ret = GetMessage(&msg, nullptr, 0, 0);
1128
1129 if (freerdp_settings_get_bool(settings, FreeRDP_EmbeddedWindow))
1130 {
1131 if ((msg.message == WM_SETFOCUS) && (msg.lParam == 1))
1132 {
1133 PostMessage(wfc->hwnd, WM_SETFOCUS, 0, 0);
1134 }
1135 else if ((msg.message == WM_KILLFOCUS) && (msg.lParam == 1))
1136 {
1137 PostMessage(wfc->hwnd, WM_KILLFOCUS, 0, 0);
1138 }
1139 }
1140
1141 switch (msg.message)
1142 {
1143 case WM_SIZE:
1144 {
1145 width = LOWORD(msg.lParam);
1146 height = HIWORD(msg.lParam);
1147 SetWindowPos(wfc->hwnd, HWND_TOP, 0, 0, width, height, SWP_FRAMECHANGED);
1148 break;
1149 }
1150 case WM_FREERDP_SHOWWINDOW:
1151 {
1152 ShowWindow(wfc->hwnd, SW_NORMAL);
1153 break;
1154 }
1155 default:
1156 break;
1157 }
1158
1159 if ((msg_ret == 0) || (msg_ret == -1))
1160 {
1161 quit_msg = TRUE;
1162 break;
1163 }
1164
1165 TranslateMessage(&msg);
1166 DispatchMessage(&msg);
1167 }
1168
1169 if (quit_msg)
1170 break;
1171 }
1172
1173 /* cleanup */
1174 freerdp_disconnect(instance);
1175
1176end:
1177 error = freerdp_get_last_error(instance->context);
1178 WLog_DBG(TAG, "Main thread exited with %" PRIu32, error);
1179 ExitThread(error);
1180 return error;
1181}
1182
1183static DWORD WINAPI wf_keyboard_thread(LPVOID lpParam)
1184{
1185 MSG msg;
1186 BOOL status;
1187 wfContext* wfc;
1188 HHOOK hook_handle;
1189 wfc = (wfContext*)lpParam;
1190 WINPR_ASSERT(nullptr != wfc);
1191 hook_handle = SetWindowsHookEx(WH_KEYBOARD_LL, wf_ll_kbd_proc, wfc->hInstance, 0);
1192
1193 if (hook_handle)
1194 {
1195 while ((status = GetMessage(&msg, nullptr, 0, 0)) != 0)
1196 {
1197 if (status == -1)
1198 {
1199 WLog_ERR(TAG, "keyboard thread error getting message");
1200 break;
1201 }
1202 else
1203 {
1204 TranslateMessage(&msg);
1205 DispatchMessage(&msg);
1206 }
1207 }
1208
1209 UnhookWindowsHookEx(hook_handle);
1210 }
1211 else
1212 {
1213 WLog_ERR(TAG, "failed to install keyboard hook");
1214 }
1215
1216 WLog_DBG(TAG, "Keyboard thread exited.");
1217 ExitThread(0);
1218 return 0;
1219}
1220
1221int freerdp_client_set_window_size(wfContext* wfc, int width, int height)
1222{
1223 WLog_DBG(TAG, "freerdp_client_set_window_size %d, %d", width, height);
1224
1225 if ((width != wfc->client_width) || (height != wfc->client_height))
1226 {
1227 PostThreadMessage(wfc->mainThreadId, WM_SIZE, SIZE_RESTORED,
1228 ((UINT)height << 16) | (UINT)width);
1229 }
1230
1231 return 0;
1232}
1233
1234void wf_size_scrollbars(wfContext* wfc, UINT32 client_width, UINT32 client_height)
1235{
1236 const rdpSettings* settings;
1237 WINPR_ASSERT(wfc);
1238
1239 settings = wfc->common.context.settings;
1240 WINPR_ASSERT(settings);
1241
1242 if (wfc->disablewindowtracking)
1243 return;
1244
1245 // prevent infinite message loop
1246 wfc->disablewindowtracking = TRUE;
1247
1248 if (freerdp_settings_get_bool(settings, FreeRDP_SmartSizing) ||
1249 freerdp_settings_get_bool(settings, FreeRDP_DynamicResolutionUpdate))
1250 {
1251 wfc->xCurrentScroll = 0;
1252 wfc->yCurrentScroll = 0;
1253
1254 if (wfc->xScrollVisible || wfc->yScrollVisible)
1255 {
1256 if (ShowScrollBar(wfc->hwnd, SB_BOTH, FALSE))
1257 {
1258 wfc->xScrollVisible = FALSE;
1259 wfc->yScrollVisible = FALSE;
1260 }
1261 }
1262 }
1263 else
1264 {
1265 SCROLLINFO si;
1266 BOOL horiz = wfc->xScrollVisible;
1267 BOOL vert = wfc->yScrollVisible;
1268
1269 if (!horiz && client_width < freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth))
1270 {
1271 horiz = TRUE;
1272 }
1273 else if (horiz &&
1274 client_width >=
1276 settings, FreeRDP_DesktopWidth) /* - GetSystemMetrics(SM_CXVSCROLL)*/)
1277 {
1278 horiz = FALSE;
1279 }
1280
1281 if (!vert && client_height < freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight))
1282 {
1283 vert = TRUE;
1284 }
1285 else if (vert &&
1286 client_height >=
1288 settings, FreeRDP_DesktopHeight) /* - GetSystemMetrics(SM_CYHSCROLL)*/)
1289 {
1290 vert = FALSE;
1291 }
1292
1293 if (horiz == vert && (horiz != wfc->xScrollVisible && vert != wfc->yScrollVisible))
1294 {
1295 if (ShowScrollBar(wfc->hwnd, SB_BOTH, horiz))
1296 {
1297 wfc->xScrollVisible = horiz;
1298 wfc->yScrollVisible = vert;
1299 }
1300 }
1301
1302 if (horiz != wfc->xScrollVisible)
1303 {
1304 if (ShowScrollBar(wfc->hwnd, SB_HORZ, horiz))
1305 {
1306 wfc->xScrollVisible = horiz;
1307 }
1308 }
1309
1310 if (vert != wfc->yScrollVisible)
1311 {
1312 if (ShowScrollBar(wfc->hwnd, SB_VERT, vert))
1313 {
1314 wfc->yScrollVisible = vert;
1315 }
1316 }
1317
1318 if (horiz)
1319 {
1320 // The horizontal scrolling range is defined by
1321 // (bitmap_width) - (client_width). The current horizontal
1322 // scroll value remains within the horizontal scrolling range.
1323 wfc->xMaxScroll =
1324 MAX(freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth) - client_width, 0);
1325 wfc->xCurrentScroll = MIN(wfc->xCurrentScroll, wfc->xMaxScroll);
1326 si.cbSize = sizeof(si);
1327 si.fMask = SIF_RANGE | SIF_PAGE | SIF_POS;
1328 si.nMin = wfc->xMinScroll;
1329 si.nMax = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth);
1330 si.nPage = client_width;
1331 si.nPos = wfc->xCurrentScroll;
1332 SetScrollInfo(wfc->hwnd, SB_HORZ, &si, TRUE);
1333 }
1334
1335 if (vert)
1336 {
1337 // The vertical scrolling range is defined by
1338 // (bitmap_height) - (client_height). The current vertical
1339 // scroll value remains within the vertical scrolling range.
1340 wfc->yMaxScroll = MAX(
1341 freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight) - client_height, 0);
1342 wfc->yCurrentScroll = MIN(wfc->yCurrentScroll, wfc->yMaxScroll);
1343 si.cbSize = sizeof(si);
1344 si.fMask = SIF_RANGE | SIF_PAGE | SIF_POS;
1345 si.nMin = wfc->yMinScroll;
1346 si.nMax = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight);
1347 si.nPage = client_height;
1348 si.nPos = wfc->yCurrentScroll;
1349 SetScrollInfo(wfc->hwnd, SB_VERT, &si, TRUE);
1350 }
1351 }
1352
1353 wfc->disablewindowtracking = FALSE;
1354 wf_update_canvas_diff(wfc);
1355}
1356
1357static BOOL wfreerdp_client_global_init(void)
1358{
1359 WSADATA wsaData;
1360
1361 WSAStartup(0x101, &wsaData);
1362 if (freerdp_handle_signals() != 0)
1363 return FALSE;
1364
1365 if (freerdp_register_addin_provider(freerdp_channels_load_static_addin_entry, 0) !=
1366 CHANNEL_RC_OK)
1367 return FALSE;
1368
1369 return TRUE;
1370}
1371
1372static void wfreerdp_client_global_uninit(void)
1373{
1374 WSACleanup();
1375}
1376
1377static BOOL wfreerdp_client_new(freerdp* instance, rdpContext* context)
1378{
1379 wfContext* wfc = (wfContext*)context;
1380 if (!wfc)
1381 return FALSE;
1382
1383 // AttachConsole and stdin do not work well.
1384 // Use GUI input dialogs instead of command line ones.
1385 wfc->isConsole = wf_has_console();
1386
1387 if (!(wfreerdp_client_global_init()))
1388 return FALSE;
1389
1390 WINPR_ASSERT(instance);
1391 instance->PreConnect = wf_pre_connect;
1392 instance->PostConnect = wf_post_connect;
1393 instance->PostDisconnect = wf_post_disconnect;
1394 instance->AuthenticateEx = wf_authenticate_ex;
1395
1396#ifdef WITH_WINDOWS_CERT_STORE
1397 if (!freerdp_settings_set_bool(context->settings, FreeRDP_CertificateCallbackPreferPEM, TRUE))
1398 return FALSE;
1399#endif
1400
1401 if (!wfc->isConsole)
1402 {
1403 instance->VerifyCertificateEx = wf_verify_certificate_ex;
1404 instance->VerifyChangedCertificateEx = wf_verify_changed_certificate_ex;
1405 instance->PresentGatewayMessage = wf_present_gateway_message;
1406 }
1407
1408#ifdef WITH_PROGRESS_BAR
1409 CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
1410 CoCreateInstance(&CLSID_TaskbarList, nullptr, CLSCTX_ALL, &IID_ITaskbarList3,
1411 (void**)&wfc->taskBarList);
1412#endif
1413
1414 return TRUE;
1415}
1416
1417static void wfreerdp_client_free(freerdp* instance, rdpContext* context)
1418{
1419 WINPR_UNUSED(instance);
1420 if (!context)
1421 return;
1422
1423#ifdef WITH_PROGRESS_BAR
1424 CoUninitialize();
1425#endif
1426}
1427
1428static int wfreerdp_client_start(rdpContext* context)
1429{
1430 wfContext* wfc = (wfContext*)context;
1431
1432 WINPR_ASSERT(context);
1433 WINPR_ASSERT(context->settings);
1434
1435 freerdp* instance = context->instance;
1436 WINPR_ASSERT(instance);
1437
1438 rdpSettings* settings = context->settings;
1439 WINPR_ASSERT(settings);
1440
1441 HINSTANCE hInstance = GetModuleHandle(nullptr);
1442 HWND hWndParent = (HWND)freerdp_settings_get_uint64(settings, FreeRDP_ParentWindowId);
1443 if (!freerdp_settings_set_bool(settings, FreeRDP_EmbeddedWindow, (hWndParent) ? TRUE : FALSE))
1444 return -1;
1445
1446 wfc->hWndParent = hWndParent;
1447
1448 if (freerdp_settings_get_bool(settings, FreeRDP_EmbeddedWindow))
1449 {
1450 typedef UINT(WINAPI * GetDpiForWindow_t)(HWND hwnd);
1451 typedef BOOL(WINAPI * SetProcessDPIAware_t)(void);
1452
1453 HMODULE module = GetModuleHandle(_T("User32"));
1454 if (module)
1455 {
1456 GetDpiForWindow_t pGetDpiForWindow =
1457 GetProcAddressAs(module, "GetDpiForWindow", GetDpiForWindow_t);
1458 SetProcessDPIAware_t pSetProcessDPIAware =
1459 GetProcAddressAs(module, "SetProcessDPIAware", SetProcessDPIAware_t);
1460 if (pGetDpiForWindow && pSetProcessDPIAware)
1461 {
1462 const UINT dpiAwareness = pGetDpiForWindow(hWndParent);
1463 if (dpiAwareness != USER_DEFAULT_SCREEN_DPI)
1464 pSetProcessDPIAware();
1465 }
1466 FreeLibrary(module);
1467 }
1468 }
1469
1470 /* initial windows system item position where we will insert new menu item
1471 * after default 5 items (restore, move, size, minimize, maximize)
1472 * gets incremented each time wf_append_item_to_system_menu is called
1473 * or maybe could use GetMenuItemCount() to get initial item count ? */
1474 wfc->systemMenuInsertPosition = 6;
1475
1476 wfc->hInstance = hInstance;
1477 wfc->cursor = LoadCursor(nullptr, IDC_ARROW);
1478 wfc->icon = LoadIcon(GetModuleHandle(nullptr), MAKEINTRESOURCE(IDI_ICON1));
1479 wfc->wndClassName = _tcsdup(_T("FreeRDP"));
1480 wfc->wndClass.cbSize = sizeof(WNDCLASSEX);
1481 wfc->wndClass.style = CS_HREDRAW | CS_VREDRAW;
1482 wfc->wndClass.lpfnWndProc = wf_event_proc;
1483 wfc->wndClass.cbClsExtra = 0;
1484 wfc->wndClass.cbWndExtra = 0;
1485 wfc->wndClass.hCursor = nullptr;
1486 wfc->wndClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
1487 wfc->wndClass.lpszMenuName = nullptr;
1488 wfc->wndClass.lpszClassName = wfc->wndClassName;
1489 wfc->wndClass.hInstance = hInstance;
1490 wfc->wndClass.hIcon = wfc->icon;
1491 wfc->wndClass.hIconSm = wfc->icon;
1492 RegisterClassEx(&(wfc->wndClass));
1493 wfc->keyboardThread =
1494 CreateThread(nullptr, 0, wf_keyboard_thread, (void*)wfc, 0, &wfc->keyboardThreadId);
1495
1496 if (!wfc->keyboardThread)
1497 return -1;
1498
1499 wfc->common.thread =
1500 CreateThread(nullptr, 0, wf_client_thread, (void*)instance, 0, &wfc->mainThreadId);
1501
1502 if (!wfc->common.thread)
1503 return -1;
1504
1505 return 0;
1506}
1507
1508static int wfreerdp_client_stop(rdpContext* context)
1509{
1510 int rc;
1511 wfContext* wfc = (wfContext*)context;
1512
1513 WINPR_ASSERT(wfc);
1514 PostThreadMessage(wfc->mainThreadId, WM_QUIT, 0, 0);
1515 rc = freerdp_client_common_stop(context);
1516 wfc->mainThreadId = 0;
1517
1518 if (wfc->keyboardThread)
1519 {
1520 PostThreadMessage(wfc->keyboardThreadId, WM_QUIT, 0, 0);
1521 (void)WaitForSingleObject(wfc->keyboardThread, INFINITE);
1522 (void)CloseHandle(wfc->keyboardThread);
1523 wfc->keyboardThread = nullptr;
1524 wfc->keyboardThreadId = 0;
1525 }
1526
1527 return 0;
1528}
1529
1530int RdpClientEntry(RDP_CLIENT_ENTRY_POINTS* pEntryPoints)
1531{
1532 pEntryPoints->Version = 1;
1533 pEntryPoints->Size = sizeof(RDP_CLIENT_ENTRY_POINTS_V1);
1534 pEntryPoints->GlobalInit = wfreerdp_client_global_init;
1535 pEntryPoints->GlobalUninit = wfreerdp_client_global_uninit;
1536 pEntryPoints->ContextSize = sizeof(wfContext);
1537 pEntryPoints->ClientNew = wfreerdp_client_new;
1538 pEntryPoints->ClientFree = wfreerdp_client_free;
1539 pEntryPoints->ClientStart = wfreerdp_client_start;
1540 pEntryPoints->ClientStop = wfreerdp_client_stop;
1541 return 0;
1542}
FREERDP_API BOOL freerdp_settings_set_uint32(rdpSettings *settings, FreeRDP_Settings_Keys_UInt32 id, UINT32 val)
Sets a UINT32 settings value.
FREERDP_API BOOL freerdp_settings_set_bool(rdpSettings *settings, FreeRDP_Settings_Keys_Bool id, BOOL val)
Sets a BOOL settings value.
WINPR_ATTR_NODISCARD FREERDP_API const char * freerdp_settings_get_string(const rdpSettings *settings, FreeRDP_Settings_Keys_String id)
Returns a immutable string settings value.
WINPR_ATTR_NODISCARD FREERDP_API UINT64 freerdp_settings_get_uint64(const rdpSettings *settings, FreeRDP_Settings_Keys_UInt64 id)
Returns a UINT64 settings value.
WINPR_ATTR_NODISCARD FREERDP_API UINT32 freerdp_settings_get_uint32(const rdpSettings *settings, FreeRDP_Settings_Keys_UInt32 id)
Returns a UINT32 settings value.
WINPR_ATTR_NODISCARD FREERDP_API BOOL freerdp_settings_get_bool(const rdpSettings *settings, FreeRDP_Settings_Keys_Bool id)
Returns a boolean settings value.