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