VirtualBox

source: vbox/trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxTray.cpp@ 81025

Last change on this file since 81025 was 79036, checked in by vboxsync, 5 years ago

Shared Clipboard/URI: Update.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 63.9 KB
Line 
1/* $Id: VBoxTray.cpp 79036 2019-06-07 14:56:19Z vboxsync $ */
2/** @file
3 * VBoxTray - Guest Additions Tray Application
4 */
5
6/*
7 * Copyright (C) 2006-2019 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#include <package-generated.h>
23#include "product-generated.h"
24
25#include "VBoxTray.h"
26#include "VBoxTrayMsg.h"
27#include "VBoxHelpers.h"
28#include "VBoxSeamless.h"
29#include "VBoxClipboard.h"
30#include "VBoxDisplay.h"
31#include "VBoxVRDP.h"
32#include "VBoxHostVersion.h"
33#ifdef VBOX_WITH_DRAG_AND_DROP
34# include "VBoxDnD.h"
35#endif
36#include "VBoxIPC.h"
37#include "VBoxLA.h"
38#include <VBoxHook.h>
39#include "resource.h"
40
41#include <sddl.h>
42
43#include <iprt/asm.h>
44#include <iprt/buildconfig.h>
45#include <iprt/ldr.h>
46#include <iprt/path.h>
47#include <iprt/process.h>
48#include <iprt/system.h>
49#include <iprt/time.h>
50
51#ifdef DEBUG
52# define LOG_ENABLED
53# define LOG_GROUP LOG_GROUP_DEFAULT
54#endif
55#include <VBox/log.h>
56
57/* Default desktop state tracking */
58#include <Wtsapi32.h>
59
60/*
61 * St (session [state] tracking) functionality API
62 *
63 * !!!NOTE: this API is NOT thread-safe!!!
64 * it is supposed to be called & used from within the window message handler thread
65 * of the window passed to vboxStInit */
66static int vboxStInit(HWND hWnd);
67static void vboxStTerm(void);
68/* @returns true on "IsActiveConsole" state change */
69static BOOL vboxStHandleEvent(WPARAM EventID);
70static BOOL vboxStIsActiveConsole();
71static BOOL vboxStCheckTimer(WPARAM wEvent);
72
73/*
74 * Dt (desktop [state] tracking) functionality API
75 *
76 * !!!NOTE: this API is NOT thread-safe!!!
77 * */
78static int vboxDtInit();
79static void vboxDtTerm();
80/* @returns true on "IsInputDesktop" state change */
81static BOOL vboxDtHandleEvent();
82/* @returns true iff the application (VBoxTray) desktop is input */
83static BOOL vboxDtIsInputDesktop();
84static HANDLE vboxDtGetNotifyEvent();
85static BOOL vboxDtCheckTimer(WPARAM wParam);
86
87/* caps API */
88#define VBOXCAPS_ENTRY_IDX_SEAMLESS 0
89#define VBOXCAPS_ENTRY_IDX_GRAPHICS 1
90#define VBOXCAPS_ENTRY_IDX_COUNT 2
91
92typedef enum VBOXCAPS_ENTRY_FUNCSTATE
93{
94 /* the cap is unsupported */
95 VBOXCAPS_ENTRY_FUNCSTATE_UNSUPPORTED = 0,
96 /* the cap is supported */
97 VBOXCAPS_ENTRY_FUNCSTATE_SUPPORTED,
98 /* the cap functionality is started, it can be disabled however if its AcState is not ACQUIRED */
99 VBOXCAPS_ENTRY_FUNCSTATE_STARTED,
100} VBOXCAPS_ENTRY_FUNCSTATE;
101
102
103static void VBoxCapsEntryFuncStateSet(uint32_t iCup, VBOXCAPS_ENTRY_FUNCSTATE enmFuncState);
104static int VBoxCapsInit();
105static int VBoxCapsReleaseAll();
106static void VBoxCapsTerm();
107static BOOL VBoxCapsEntryIsAcquired(uint32_t iCap);
108static BOOL VBoxCapsEntryIsEnabled(uint32_t iCap);
109static BOOL VBoxCapsCheckTimer(WPARAM wParam);
110static int VBoxCapsEntryRelease(uint32_t iCap);
111static int VBoxCapsEntryAcquire(uint32_t iCap);
112static int VBoxCapsAcquireAllSupported();
113
114/* console-related caps API */
115static BOOL VBoxConsoleIsAllowed();
116static void VBoxConsoleEnable(BOOL fEnable);
117static void VBoxConsoleCapSetSupported(uint32_t iCap, BOOL fSupported);
118
119static void VBoxGrapicsSetSupported(BOOL fSupported);
120
121
122/*********************************************************************************************************************************
123* Internal Functions *
124*********************************************************************************************************************************/
125static int vboxTrayCreateTrayIcon(void);
126static LRESULT CALLBACK vboxToolWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
127
128/* Global message handler prototypes. */
129static int vboxTrayGlMsgTaskbarCreated(WPARAM lParam, LPARAM wParam);
130/*static int vboxTrayGlMsgShowBalloonMsg(WPARAM lParam, LPARAM wParam);*/
131
132static int VBoxAcquireGuestCaps(uint32_t fOr, uint32_t fNot, bool fCfg);
133
134
135/*********************************************************************************************************************************
136* Global Variables *
137*********************************************************************************************************************************/
138HANDLE g_hStopSem;
139HANDLE g_hSeamlessWtNotifyEvent = 0;
140HANDLE g_hSeamlessKmNotifyEvent = 0;
141HINSTANCE g_hInstance;
142HWND g_hwndToolWindow;
143NOTIFYICONDATA g_NotifyIconData;
144
145uint32_t g_fGuestDisplaysChanged = 0;
146
147static PRTLOGGER g_pLoggerRelease = NULL;
148static uint32_t g_cHistory = 10; /* Enable log rotation, 10 files. */
149static uint32_t g_uHistoryFileTime = RT_SEC_1DAY; /* Max 1 day per file. */
150static uint64_t g_uHistoryFileSize = 100 * _1M; /* Max 100MB per file. */
151
152#ifdef DEBUG_andy
153static VBOXSERVICEINFO g_aServices[] =
154{
155 { &g_SvcDescClipboard, NIL_RTTHREAD, NULL, false, false, false, false, true }
156};
157#else
158/**
159 * The details of the services that has been compiled in.
160 */
161static VBOXSERVICEINFO g_aServices[] =
162{
163 { &g_SvcDescDisplay, NIL_RTTHREAD, NULL, false, false, false, false, true },
164#ifdef VBOX_WITH_SHARED_CLIPBOARD
165 { &g_SvcDescClipboard, NIL_RTTHREAD, NULL, false, false, false, false, true },
166#endif
167 { &g_SvcDescSeamless, NIL_RTTHREAD, NULL, false, false, false, false, true },
168 { &g_SvcDescVRDP, NIL_RTTHREAD, NULL, false, false, false, false, true },
169 { &g_SvcDescIPC, NIL_RTTHREAD, NULL, false, false, false, false, true },
170 { &g_SvcDescLA, NIL_RTTHREAD, NULL, false, false, false, false, true },
171#ifdef VBOX_WITH_DRAG_AND_DROP
172 { &g_SvcDescDnD, NIL_RTTHREAD, NULL, false, false, false, false, true }
173#endif
174};
175#endif
176
177/* The global message table. */
178static VBOXGLOBALMESSAGE g_vboxGlobalMessageTable[] =
179{
180 /* Windows specific stuff. */
181 {
182 "TaskbarCreated",
183 vboxTrayGlMsgTaskbarCreated
184 },
185
186 /* VBoxTray specific stuff. */
187 /** @todo Add new messages here! */
188
189 {
190 NULL
191 }
192};
193
194/**
195 * Gets called whenever the Windows main taskbar
196 * get (re-)created. Nice to install our tray icon.
197 *
198 * @return IPRT status code.
199 * @param wParam
200 * @param lParam
201 */
202static int vboxTrayGlMsgTaskbarCreated(WPARAM wParam, LPARAM lParam)
203{
204 RT_NOREF(wParam, lParam);
205 return vboxTrayCreateTrayIcon();
206}
207
208static int vboxTrayCreateTrayIcon(void)
209{
210 HICON hIcon = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_VIRTUALBOX));
211 if (hIcon == NULL)
212 {
213 DWORD dwErr = GetLastError();
214 LogFunc(("Could not load tray icon, error %08X\n", dwErr));
215 return RTErrConvertFromWin32(dwErr);
216 }
217
218 /* Prepare the system tray icon. */
219 RT_ZERO(g_NotifyIconData);
220 g_NotifyIconData.cbSize = NOTIFYICONDATA_V1_SIZE; // sizeof(NOTIFYICONDATA);
221 g_NotifyIconData.hWnd = g_hwndToolWindow;
222 g_NotifyIconData.uID = ID_TRAYICON;
223 g_NotifyIconData.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
224 g_NotifyIconData.uCallbackMessage = WM_VBOXTRAY_TRAY_ICON;
225 g_NotifyIconData.hIcon = hIcon;
226
227 sprintf(g_NotifyIconData.szTip, "%s Guest Additions %d.%d.%dr%d",
228 VBOX_PRODUCT, VBOX_VERSION_MAJOR, VBOX_VERSION_MINOR, VBOX_VERSION_BUILD, VBOX_SVN_REV);
229
230 int rc = VINF_SUCCESS;
231 if (!Shell_NotifyIcon(NIM_ADD, &g_NotifyIconData))
232 {
233 DWORD dwErr = GetLastError();
234 LogFunc(("Could not create tray icon, error=%ld\n", dwErr));
235 rc = RTErrConvertFromWin32(dwErr);
236 RT_ZERO(g_NotifyIconData);
237 }
238
239 if (hIcon)
240 DestroyIcon(hIcon);
241 return rc;
242}
243
244static void vboxTrayRemoveTrayIcon(void)
245{
246 if (g_NotifyIconData.cbSize > 0)
247 {
248 /* Remove the system tray icon and refresh system tray. */
249 Shell_NotifyIcon(NIM_DELETE, &g_NotifyIconData);
250 HWND hTrayWnd = FindWindow("Shell_TrayWnd", NULL); /* We assume we only have one tray atm. */
251 if (hTrayWnd)
252 {
253 HWND hTrayNotifyWnd = FindWindowEx(hTrayWnd, 0, "TrayNotifyWnd", NULL);
254 if (hTrayNotifyWnd)
255 SendMessage(hTrayNotifyWnd, WM_PAINT, 0, NULL);
256 }
257 RT_ZERO(g_NotifyIconData);
258 }
259}
260
261/**
262 * The service thread.
263 *
264 * @returns Whatever the worker function returns.
265 * @param ThreadSelf My thread handle.
266 * @param pvUser The service index.
267 */
268static DECLCALLBACK(int) vboxTrayServiceThread(RTTHREAD ThreadSelf, void *pvUser)
269{
270 PVBOXSERVICEINFO pSvc = (PVBOXSERVICEINFO)pvUser;
271 AssertPtr(pSvc);
272
273#ifndef RT_OS_WINDOWS
274 /*
275 * Block all signals for this thread. Only the main thread will handle signals.
276 */
277 sigset_t signalMask;
278 sigfillset(&signalMask);
279 pthread_sigmask(SIG_BLOCK, &signalMask, NULL);
280#endif
281
282 int rc = pSvc->pDesc->pfnWorker(pSvc->pInstance, &pSvc->fShutdown);
283 ASMAtomicXchgBool(&pSvc->fShutdown, true);
284 RTThreadUserSignal(ThreadSelf);
285
286 LogFunc(("Worker for '%s' ended with %Rrc\n", pSvc->pDesc->pszName, rc));
287 return rc;
288}
289
290static int vboxTrayServicesStart(PVBOXSERVICEENV pEnv)
291{
292 AssertPtrReturn(pEnv, VERR_INVALID_POINTER);
293
294 LogRel(("Starting services ...\n"));
295
296 int rc = VINF_SUCCESS;
297
298 for (unsigned i = 0; i < RT_ELEMENTS(g_aServices); i++)
299 {
300 PVBOXSERVICEINFO pSvc = &g_aServices[i];
301 LogRel(("Starting service '%s' ...\n", pSvc->pDesc->pszName));
302
303 pSvc->hThread = NIL_RTTHREAD;
304 pSvc->pInstance = NULL;
305 pSvc->fStarted = false;
306 pSvc->fShutdown = false;
307
308 int rc2 = VINF_SUCCESS;
309
310 if (pSvc->pDesc->pfnInit)
311 rc2 = pSvc->pDesc->pfnInit(pEnv, &pSvc->pInstance);
312
313 if (RT_FAILURE(rc2))
314 {
315 LogRel(("Failed to initialize service '%s', rc=%Rrc\n", pSvc->pDesc->pszName, rc2));
316 if (rc2 == VERR_NOT_SUPPORTED)
317 {
318 LogRel(("Service '%s' is not supported on this system\n", pSvc->pDesc->pszName));
319 rc2 = VINF_SUCCESS;
320 }
321 /* Keep going. */
322 }
323 else
324 {
325 if (pSvc->pDesc->pfnWorker)
326 {
327 rc2 = RTThreadCreate(&pSvc->hThread, vboxTrayServiceThread, pSvc /* pvUser */,
328 0 /* Default stack size */, RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, pSvc->pDesc->pszName);
329 if (RT_SUCCESS(rc2))
330 {
331 pSvc->fStarted = true;
332
333 RTThreadUserWait(pSvc->hThread, 30 * 1000 /* Timeout in ms */);
334 if (pSvc->fShutdown)
335 {
336 LogRel(("Service '%s' failed to start!\n", pSvc->pDesc->pszName));
337 rc = VERR_GENERAL_FAILURE;
338 }
339 else
340 LogRel(("Service '%s' started\n", pSvc->pDesc->pszName));
341 }
342 else
343 {
344 LogRel(("Failed to start thread for service '%s': %Rrc\n", rc2));
345 if (pSvc->pDesc->pfnDestroy)
346 pSvc->pDesc->pfnDestroy(pSvc->pInstance);
347 }
348 }
349 }
350
351 if (RT_SUCCESS(rc))
352 rc = rc2;
353 }
354
355 if (RT_SUCCESS(rc))
356 LogRel(("All services started\n"));
357 else
358 LogRel(("Services started, but some with errors\n"));
359
360 LogFlowFuncLeaveRC(rc);
361 return rc;
362}
363
364static int vboxTrayServicesStop(VBOXSERVICEENV *pEnv)
365{
366 AssertPtrReturn(pEnv, VERR_INVALID_POINTER);
367
368 LogRel2(("Stopping all services ...\n"));
369
370 /*
371 * Signal all the services.
372 */
373 for (unsigned i = 0; i < RT_ELEMENTS(g_aServices); i++)
374 ASMAtomicWriteBool(&g_aServices[i].fShutdown, true);
375
376 /*
377 * Do the pfnStop callback on all running services.
378 */
379 for (unsigned i = 0; i < RT_ELEMENTS(g_aServices); i++)
380 {
381 PVBOXSERVICEINFO pSvc = &g_aServices[i];
382 if ( pSvc->fStarted
383 && pSvc->pDesc->pfnStop)
384 {
385 LogRel2(("Calling stop function for service '%s' ...\n", pSvc->pDesc->pszName));
386 int rc2 = pSvc->pDesc->pfnStop(pSvc->pInstance);
387 if (RT_FAILURE(rc2))
388 LogRel(("Failed to stop service '%s': %Rrc\n", pSvc->pDesc->pszName, rc2));
389 }
390 }
391
392 LogRel2(("All stop functions for services called\n"));
393
394 int rc = VINF_SUCCESS;
395
396 /*
397 * Wait for all the service threads to complete.
398 */
399 for (unsigned i = 0; i < RT_ELEMENTS(g_aServices); i++)
400 {
401 PVBOXSERVICEINFO pSvc = &g_aServices[i];
402 if (!pSvc->fEnabled) /* Only stop services which were started before. */
403 continue;
404
405 if (pSvc->hThread != NIL_RTTHREAD)
406 {
407 LogRel2(("Waiting for service '%s' to stop ...\n", pSvc->pDesc->pszName));
408 int rc2 = VINF_SUCCESS;
409 for (int j = 0; j < 30; j++) /* Wait 30 seconds in total */
410 {
411 rc2 = RTThreadWait(pSvc->hThread, 1000 /* Wait 1 second */, NULL);
412 if (RT_SUCCESS(rc2))
413 break;
414 }
415 if (RT_FAILURE(rc2))
416 {
417 LogRel(("Service '%s' failed to stop (%Rrc)\n", pSvc->pDesc->pszName, rc2));
418 if (RT_SUCCESS(rc))
419 rc = rc2;
420 }
421 }
422
423 if (pSvc->pDesc->pfnDestroy)
424 {
425 LogRel2(("Terminating service '%s' ...\n", pSvc->pDesc->pszName));
426 pSvc->pDesc->pfnDestroy(pSvc->pInstance);
427 }
428 }
429
430 if (RT_SUCCESS(rc))
431 LogRel(("All services stopped\n"));
432
433 LogFlowFuncLeaveRC(rc);
434 return rc;
435}
436
437static int vboxTrayRegisterGlobalMessages(PVBOXGLOBALMESSAGE pTable)
438{
439 int rc = VINF_SUCCESS;
440 if (pTable == NULL) /* No table to register? Skip. */
441 return rc;
442 while ( pTable->pszName
443 && RT_SUCCESS(rc))
444 {
445 /* Register global accessible window messages. */
446 pTable->uMsgID = RegisterWindowMessage(TEXT(pTable->pszName));
447 if (!pTable->uMsgID)
448 {
449 DWORD dwErr = GetLastError();
450 Log(("Registering global message \"%s\" failed, error = %08X\n", dwErr));
451 rc = RTErrConvertFromWin32(dwErr);
452 }
453
454 /* Advance to next table element. */
455 pTable++;
456 }
457 return rc;
458}
459
460static bool vboxTrayHandleGlobalMessages(PVBOXGLOBALMESSAGE pTable, UINT uMsg,
461 WPARAM wParam, LPARAM lParam)
462{
463 if (pTable == NULL)
464 return false;
465 while (pTable && pTable->pszName)
466 {
467 if (pTable->uMsgID == uMsg)
468 {
469 if (pTable->pfnHandler)
470 pTable->pfnHandler(wParam, lParam);
471 return true;
472 }
473
474 /* Advance to next table element. */
475 pTable++;
476 }
477 return false;
478}
479
480/**
481 * Release logger callback.
482 *
483 * @return IPRT status code.
484 * @param pLoggerRelease
485 * @param enmPhase
486 * @param pfnLog
487 */
488static void vboxTrayLogHeaderFooter(PRTLOGGER pLoggerRelease, RTLOGPHASE enmPhase, PFNRTLOGPHASEMSG pfnLog)
489{
490 /* Some introductory information. */
491 static RTTIMESPEC s_TimeSpec;
492 char szTmp[256];
493 if (enmPhase == RTLOGPHASE_BEGIN)
494 RTTimeNow(&s_TimeSpec);
495 RTTimeSpecToString(&s_TimeSpec, szTmp, sizeof(szTmp));
496
497 switch (enmPhase)
498 {
499 case RTLOGPHASE_BEGIN:
500 {
501 pfnLog(pLoggerRelease,
502 "VBoxTray %s r%s %s (%s %s) release log\n"
503 "Log opened %s\n",
504 RTBldCfgVersion(), RTBldCfgRevisionStr(), VBOX_BUILD_TARGET,
505 __DATE__, __TIME__, szTmp);
506
507 int vrc = RTSystemQueryOSInfo(RTSYSOSINFO_PRODUCT, szTmp, sizeof(szTmp));
508 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
509 pfnLog(pLoggerRelease, "OS Product: %s\n", szTmp);
510 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szTmp, sizeof(szTmp));
511 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
512 pfnLog(pLoggerRelease, "OS Release: %s\n", szTmp);
513 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_VERSION, szTmp, sizeof(szTmp));
514 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
515 pfnLog(pLoggerRelease, "OS Version: %s\n", szTmp);
516 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
517 pfnLog(pLoggerRelease, "OS Service Pack: %s\n", szTmp);
518
519 /* the package type is interesting for Linux distributions */
520 char szExecName[RTPATH_MAX];
521 char *pszExecName = RTProcGetExecutablePath(szExecName, sizeof(szExecName));
522 pfnLog(pLoggerRelease,
523 "Executable: %s\n"
524 "Process ID: %u\n"
525 "Package type: %s"
526#ifdef VBOX_OSE
527 " (OSE)"
528#endif
529 "\n",
530 pszExecName ? pszExecName : "unknown",
531 RTProcSelf(),
532 VBOX_PACKAGE_STRING);
533 break;
534 }
535
536 case RTLOGPHASE_PREROTATE:
537 pfnLog(pLoggerRelease, "Log rotated - Log started %s\n", szTmp);
538 break;
539
540 case RTLOGPHASE_POSTROTATE:
541 pfnLog(pLoggerRelease, "Log continuation - Log started %s\n", szTmp);
542 break;
543
544 case RTLOGPHASE_END:
545 pfnLog(pLoggerRelease, "End of log file - Log started %s\n", szTmp);
546 break;
547
548 default:
549 /* nothing */;
550 }
551}
552
553/**
554 * Creates the default release logger outputting to the specified file.
555 * Pass NULL for disabled logging.
556 *
557 * @return IPRT status code.
558 * @param pszLogFile Filename for log output. Optional.
559 */
560static int vboxTrayLogCreate(const char *pszLogFile)
561{
562 /* Create release logger (stdout + file). */
563 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
564 RTUINT fFlags = RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME_PROG;
565#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
566 fFlags |= RTLOGFLAGS_USECRLF;
567#endif
568 RTERRINFOSTATIC ErrInfo;
569 int rc = RTLogCreateEx(&g_pLoggerRelease, fFlags,
570#ifdef DEBUG
571 "all.e.l.f",
572 "VBOXTRAY_LOG",
573#else
574 "all",
575 "VBOXTRAY_RELEASE_LOG",
576#endif
577 RT_ELEMENTS(s_apszGroups), s_apszGroups, UINT32_MAX, RTLOGDEST_STDOUT,
578 vboxTrayLogHeaderFooter, g_cHistory, g_uHistoryFileSize, g_uHistoryFileTime,
579 RTErrInfoInitStatic(&ErrInfo), pszLogFile);
580 if (RT_SUCCESS(rc))
581 {
582#ifdef DEBUG
583 RTLogSetDefaultInstance(g_pLoggerRelease);
584#else
585 /* Register this logger as the release logger. */
586 RTLogRelSetDefaultInstance(g_pLoggerRelease);
587#endif
588 /* Explicitly flush the log in case of VBOXTRAY_RELEASE_LOG=buffered. */
589 RTLogFlush(g_pLoggerRelease);
590 }
591 else
592 VBoxTrayShowError(ErrInfo.szMsg);
593
594 return rc;
595}
596
597static void vboxTrayLogDestroy(void)
598{
599 RTLogDestroy(RTLogRelSetDefaultInstance(NULL));
600}
601
602/**
603 * Displays an error message.
604 *
605 * @returns RTEXITCODE_FAILURE.
606 * @param pszFormat The message text.
607 * @param ... Format arguments.
608 */
609RTEXITCODE VBoxTrayShowError(const char *pszFormat, ...)
610{
611 va_list args;
612 va_start(args, pszFormat);
613 char *psz = NULL;
614 RTStrAPrintfV(&psz, pszFormat, args);
615 va_end(args);
616
617 AssertPtr(psz);
618 LogRel(("Error: %s", psz));
619
620 MessageBox(GetDesktopWindow(), psz, "VBoxTray - Error", MB_OK | MB_ICONERROR);
621
622 RTStrFree(psz);
623
624 return RTEXITCODE_FAILURE;
625}
626
627static void vboxTrayDestroyToolWindow(void)
628{
629 if (g_hwndToolWindow)
630 {
631 Log(("Destroying tool window ...\n"));
632
633 /* Destroy the tool window. */
634 DestroyWindow(g_hwndToolWindow);
635 g_hwndToolWindow = NULL;
636
637 UnregisterClass("VBoxTrayToolWndClass", g_hInstance);
638 }
639}
640
641static int vboxTrayCreateToolWindow(void)
642{
643 DWORD dwErr = ERROR_SUCCESS;
644
645 /* Create a custom window class. */
646 WNDCLASSEX wc = { 0 };
647 wc.cbSize = sizeof(WNDCLASSEX);
648 wc.style = CS_NOCLOSE;
649 wc.lpfnWndProc = (WNDPROC)vboxToolWndProc;
650 wc.hInstance = g_hInstance;
651 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
652 wc.lpszClassName = "VBoxTrayToolWndClass";
653
654 if (!RegisterClassEx(&wc))
655 {
656 dwErr = GetLastError();
657 Log(("Registering invisible tool window failed, error = %08X\n", dwErr));
658 }
659 else
660 {
661 /*
662 * Create our (invisible) tool window.
663 * Note: The window name ("VBoxTrayToolWnd") and class ("VBoxTrayToolWndClass") is
664 * needed for posting globally registered messages to VBoxTray and must not be
665 * changed! Otherwise things get broken!
666 *
667 */
668 g_hwndToolWindow = CreateWindowEx(WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_TOPMOST,
669 "VBoxTrayToolWndClass", "VBoxTrayToolWnd",
670 WS_POPUPWINDOW,
671 -200, -200, 100, 100, NULL, NULL, g_hInstance, NULL);
672 if (!g_hwndToolWindow)
673 {
674 dwErr = GetLastError();
675 Log(("Creating invisible tool window failed, error = %08X\n", dwErr));
676 }
677 else
678 {
679 /* Reload the cursor(s). */
680 hlpReloadCursor();
681
682 Log(("Invisible tool window handle = %p\n", g_hwndToolWindow));
683 }
684 }
685
686 if (dwErr != ERROR_SUCCESS)
687 vboxTrayDestroyToolWindow();
688 return RTErrConvertFromWin32(dwErr);
689}
690
691static int vboxTraySetupSeamless(void)
692{
693 /* We need to setup a security descriptor to allow other processes modify access to the seamless notification event semaphore. */
694 SECURITY_ATTRIBUTES SecAttr;
695 DWORD dwErr = ERROR_SUCCESS;
696 char secDesc[SECURITY_DESCRIPTOR_MIN_LENGTH];
697 BOOL fRC;
698
699 SecAttr.nLength = sizeof(SecAttr);
700 SecAttr.bInheritHandle = FALSE;
701 SecAttr.lpSecurityDescriptor = &secDesc;
702 InitializeSecurityDescriptor(SecAttr.lpSecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
703 fRC = SetSecurityDescriptorDacl(SecAttr.lpSecurityDescriptor, TRUE, 0, FALSE);
704 if (!fRC)
705 {
706 dwErr = GetLastError();
707 Log(("SetSecurityDescriptorDacl failed with last error = %08X\n", dwErr));
708 }
709 else
710 {
711 /* For Vista and up we need to change the integrity of the security descriptor, too. */
712 uint64_t const uNtVersion = RTSystemGetNtVersion();
713 if (uNtVersion >= RTSYSTEM_MAKE_NT_VERSION(6, 0, 0))
714 {
715 BOOL (WINAPI * pfnConvertStringSecurityDescriptorToSecurityDescriptorA)(LPCSTR StringSecurityDescriptor, DWORD StringSDRevision, PSECURITY_DESCRIPTOR *SecurityDescriptor, PULONG SecurityDescriptorSize);
716 *(void **)&pfnConvertStringSecurityDescriptorToSecurityDescriptorA =
717 RTLdrGetSystemSymbol("advapi32.dll", "ConvertStringSecurityDescriptorToSecurityDescriptorA");
718 Log(("pfnConvertStringSecurityDescriptorToSecurityDescriptorA = %x\n", pfnConvertStringSecurityDescriptorToSecurityDescriptorA));
719 if (pfnConvertStringSecurityDescriptorToSecurityDescriptorA)
720 {
721 PSECURITY_DESCRIPTOR pSD;
722 PACL pSacl = NULL;
723 BOOL fSaclPresent = FALSE;
724 BOOL fSaclDefaulted = FALSE;
725
726 fRC = pfnConvertStringSecurityDescriptorToSecurityDescriptorA("S:(ML;;NW;;;LW)", /* this means "low integrity" */
727 SDDL_REVISION_1, &pSD, NULL);
728 if (!fRC)
729 {
730 dwErr = GetLastError();
731 Log(("ConvertStringSecurityDescriptorToSecurityDescriptorA failed with last error = %08X\n", dwErr));
732 }
733 else
734 {
735 fRC = GetSecurityDescriptorSacl(pSD, &fSaclPresent, &pSacl, &fSaclDefaulted);
736 if (!fRC)
737 {
738 dwErr = GetLastError();
739 Log(("GetSecurityDescriptorSacl failed with last error = %08X\n", dwErr));
740 }
741 else
742 {
743 fRC = SetSecurityDescriptorSacl(SecAttr.lpSecurityDescriptor, TRUE, pSacl, FALSE);
744 if (!fRC)
745 {
746 dwErr = GetLastError();
747 Log(("SetSecurityDescriptorSacl failed with last error = %08X\n", dwErr));
748 }
749 }
750 }
751 }
752 }
753
754 if ( dwErr == ERROR_SUCCESS
755 && uNtVersion >= RTSYSTEM_MAKE_NT_VERSION(5, 0, 0)) /* Only for W2K and up ... */
756 {
757 g_hSeamlessWtNotifyEvent = CreateEvent(&SecAttr, FALSE, FALSE, VBOXHOOK_GLOBAL_WT_EVENT_NAME);
758 if (g_hSeamlessWtNotifyEvent == NULL)
759 {
760 dwErr = GetLastError();
761 Log(("CreateEvent for Seamless failed, last error = %08X\n", dwErr));
762 }
763
764 g_hSeamlessKmNotifyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
765 if (g_hSeamlessKmNotifyEvent == NULL)
766 {
767 dwErr = GetLastError();
768 Log(("CreateEvent for Seamless failed, last error = %08X\n", dwErr));
769 }
770 }
771 }
772 return RTErrConvertFromWin32(dwErr);
773}
774
775static void vboxTrayShutdownSeamless(void)
776{
777 if (g_hSeamlessWtNotifyEvent)
778 {
779 CloseHandle(g_hSeamlessWtNotifyEvent);
780 g_hSeamlessWtNotifyEvent = NULL;
781 }
782
783 if (g_hSeamlessKmNotifyEvent)
784 {
785 CloseHandle(g_hSeamlessKmNotifyEvent);
786 g_hSeamlessKmNotifyEvent = NULL;
787 }
788}
789
790static void VBoxTrayCheckDt()
791{
792 BOOL fOldAllowedState = VBoxConsoleIsAllowed();
793 if (vboxDtHandleEvent())
794 {
795 if (!VBoxConsoleIsAllowed() != !fOldAllowedState)
796 VBoxConsoleEnable(!fOldAllowedState);
797 }
798}
799
800static int vboxTrayServiceMain(void)
801{
802 int rc = VINF_SUCCESS;
803 LogFunc(("Entering vboxTrayServiceMain\n"));
804
805 g_hStopSem = CreateEvent(NULL, TRUE, FALSE, NULL);
806 if (g_hStopSem == NULL)
807 {
808 rc = RTErrConvertFromWin32(GetLastError());
809 LogFunc(("CreateEvent for stopping VBoxTray failed, rc=%Rrc\n", rc));
810 }
811 else
812 {
813 /*
814 * Start services listed in the vboxServiceTable.
815 */
816 VBOXSERVICEENV svcEnv;
817 svcEnv.hInstance = g_hInstance;
818
819 /* Initializes disp-if to default (XPDM) mode. */
820 VBoxDispIfInit(&svcEnv.dispIf); /* Cannot fail atm. */
821 #ifdef VBOX_WITH_WDDM
822 /*
823 * For now the display mode will be adjusted to WDDM mode if needed
824 * on display service initialization when it detects the display driver type.
825 */
826 #endif
827
828 /* Finally start all the built-in services! */
829 rc = vboxTrayServicesStart(&svcEnv);
830 if (RT_FAILURE(rc))
831 {
832 /* Terminate service if something went wrong. */
833 vboxTrayServicesStop(&svcEnv);
834 }
835 else
836 {
837 uint64_t const uNtVersion = RTSystemGetNtVersion();
838 rc = vboxTrayCreateTrayIcon();
839 if ( RT_SUCCESS(rc)
840 && uNtVersion >= RTSYSTEM_MAKE_NT_VERSION(5, 0, 0)) /* Only for W2K and up ... */
841 {
842 /* We're ready to create the tooltip balloon.
843 Check in 10 seconds (@todo make seconds configurable) ... */
844 SetTimer(g_hwndToolWindow,
845 TIMERID_VBOXTRAY_CHECK_HOSTVERSION,
846 10 * 1000, /* 10 seconds */
847 NULL /* No timerproc */);
848 }
849
850 if (RT_SUCCESS(rc))
851 {
852 /* Report the host that we're up and running! */
853 hlpReportStatus(VBoxGuestFacilityStatus_Active);
854 }
855
856 if (RT_SUCCESS(rc))
857 {
858 /* Boost thread priority to make sure we wake up early for seamless window notifications
859 * (not sure if it actually makes any difference though). */
860 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
861
862 /*
863 * Main execution loop
864 * Wait for the stop semaphore to be posted or a window event to arrive
865 */
866
867 HANDLE hWaitEvent[4] = {0};
868 DWORD dwEventCount = 0;
869
870 hWaitEvent[dwEventCount++] = g_hStopSem;
871
872 /* Check if seamless mode is not active and add seamless event to the list */
873 if (0 != g_hSeamlessWtNotifyEvent)
874 {
875 hWaitEvent[dwEventCount++] = g_hSeamlessWtNotifyEvent;
876 }
877
878 if (0 != g_hSeamlessKmNotifyEvent)
879 {
880 hWaitEvent[dwEventCount++] = g_hSeamlessKmNotifyEvent;
881 }
882
883 if (0 != vboxDtGetNotifyEvent())
884 {
885 hWaitEvent[dwEventCount++] = vboxDtGetNotifyEvent();
886 }
887
888 LogFlowFunc(("Number of events to wait in main loop: %ld\n", dwEventCount));
889 while (true)
890 {
891 DWORD waitResult = MsgWaitForMultipleObjectsEx(dwEventCount, hWaitEvent, 500, QS_ALLINPUT, 0);
892 waitResult = waitResult - WAIT_OBJECT_0;
893
894 /* Only enable for message debugging, lots of traffic! */
895 //Log(("Wait result = %ld\n", waitResult));
896
897 if (waitResult == 0)
898 {
899 LogFunc(("Event 'Exit' triggered\n"));
900 /* exit */
901 break;
902 }
903 else
904 {
905 BOOL fHandled = FALSE;
906 if (waitResult < RT_ELEMENTS(hWaitEvent))
907 {
908 if (hWaitEvent[waitResult])
909 {
910 if (hWaitEvent[waitResult] == g_hSeamlessWtNotifyEvent)
911 {
912 LogFunc(("Event 'Seamless' triggered\n"));
913
914 /* seamless window notification */
915 VBoxSeamlessCheckWindows(false);
916 fHandled = TRUE;
917 }
918 else if (hWaitEvent[waitResult] == g_hSeamlessKmNotifyEvent)
919 {
920 LogFunc(("Event 'Km Seamless' triggered\n"));
921
922 /* seamless window notification */
923 VBoxSeamlessCheckWindows(true);
924 fHandled = TRUE;
925 }
926 else if (hWaitEvent[waitResult] == vboxDtGetNotifyEvent())
927 {
928 LogFunc(("Event 'Dt' triggered\n"));
929 VBoxTrayCheckDt();
930 fHandled = TRUE;
931 }
932 }
933 }
934
935 if (!fHandled)
936 {
937 /* timeout or a window message, handle it */
938 MSG msg;
939 while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
940 {
941#ifdef DEBUG_andy
942 LogFlowFunc(("PeekMessage %u\n", msg.message));
943#endif
944 if (msg.message == WM_QUIT)
945 {
946 LogFunc(("Terminating ...\n"));
947 SetEvent(g_hStopSem);
948 }
949 TranslateMessage(&msg);
950 DispatchMessage(&msg);
951 }
952 }
953 }
954 }
955 LogFunc(("Returned from main loop, exiting ...\n"));
956 }
957 LogFunc(("Waiting for services to stop ...\n"));
958 vboxTrayServicesStop(&svcEnv);
959 } /* Services started */
960 CloseHandle(g_hStopSem);
961 } /* Stop event created */
962
963 vboxTrayRemoveTrayIcon();
964
965 LogFunc(("Leaving with rc=%Rrc\n", rc));
966 return rc;
967}
968
969/**
970 * Main function
971 */
972int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
973{
974 RT_NOREF(hPrevInstance, lpCmdLine, nCmdShow);
975 int rc = RTR3InitExeNoArguments(0);
976 if (RT_FAILURE(rc))
977 return RTEXITCODE_INIT;
978
979 /* Note: Do not use a global namespace ("Global\\") for mutex name here,
980 * will blow up NT4 compatibility! */
981 HANDLE hMutexAppRunning = CreateMutex(NULL, FALSE, "VBoxTray");
982 if ( hMutexAppRunning != NULL
983 && GetLastError() == ERROR_ALREADY_EXISTS)
984 {
985 /* VBoxTray already running? Bail out. */
986 CloseHandle (hMutexAppRunning);
987 hMutexAppRunning = NULL;
988 return 0;
989 }
990
991 LogRel(("%s r%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr()));
992
993 rc = vboxTrayLogCreate(NULL /* pszLogFile */);
994 if (RT_SUCCESS(rc))
995 {
996 rc = VbglR3Init();
997 if (RT_SUCCESS(rc))
998 {
999 /* Log the major windows NT version: */
1000 uint64_t const uNtVersion = RTSystemGetNtVersion();
1001 LogRel(("Windows version %u.%u build %u (uNtVersion=%#RX64)\n", RTSYSTEM_NT_VERSION_GET_MAJOR(uNtVersion),
1002 RTSYSTEM_NT_VERSION_GET_MINOR(uNtVersion), RTSYSTEM_NT_VERSION_GET_BUILD(uNtVersion), uNtVersion ));
1003
1004 /* Save instance handle. */
1005 g_hInstance = hInstance;
1006
1007 hlpReportStatus(VBoxGuestFacilityStatus_Init);
1008 rc = vboxTrayCreateToolWindow();
1009 if (RT_SUCCESS(rc))
1010 {
1011 VBoxCapsInit();
1012
1013 rc = vboxStInit(g_hwndToolWindow);
1014 if (!RT_SUCCESS(rc))
1015 {
1016 LogFlowFunc(("vboxStInit failed, rc=%Rrc\n", rc));
1017 /* ignore the St Init failure. this can happen for < XP win that do not support WTS API
1018 * in that case the session is treated as active connected to the physical console
1019 * (i.e. fallback to the old behavior that was before introduction of VBoxSt) */
1020 Assert(vboxStIsActiveConsole());
1021 }
1022
1023 rc = vboxDtInit();
1024 if (!RT_SUCCESS(rc))
1025 {
1026 LogFlowFunc(("vboxDtInit failed, rc=%Rrc\n", rc));
1027 /* ignore the Dt Init failure. this can happen for < XP win that do not support WTS API
1028 * in that case the session is treated as active connected to the physical console
1029 * (i.e. fallback to the old behavior that was before introduction of VBoxSt) */
1030 Assert(vboxDtIsInputDesktop());
1031 }
1032
1033 rc = VBoxAcquireGuestCaps(VMMDEV_GUEST_SUPPORTS_SEAMLESS | VMMDEV_GUEST_SUPPORTS_GRAPHICS, 0, true);
1034 if (!RT_SUCCESS(rc))
1035 LogFlowFunc(("VBoxAcquireGuestCaps failed with rc=%Rrc, ignoring ...\n", rc));
1036
1037 rc = vboxTraySetupSeamless(); /** @todo r=andy Do we really want to be this critical for the whole application? */
1038 if (RT_SUCCESS(rc))
1039 {
1040 rc = vboxTrayServiceMain();
1041 if (RT_SUCCESS(rc))
1042 hlpReportStatus(VBoxGuestFacilityStatus_Terminating);
1043 vboxTrayShutdownSeamless();
1044 }
1045
1046 /* it should be safe to call vboxDtTerm even if vboxStInit above failed */
1047 vboxDtTerm();
1048
1049 /* it should be safe to call vboxStTerm even if vboxStInit above failed */
1050 vboxStTerm();
1051
1052 VBoxCapsTerm();
1053
1054 vboxTrayDestroyToolWindow();
1055 }
1056 if (RT_SUCCESS(rc))
1057 hlpReportStatus(VBoxGuestFacilityStatus_Terminated);
1058 else
1059 {
1060 LogRel(("Error while starting, rc=%Rrc\n", rc));
1061 hlpReportStatus(VBoxGuestFacilityStatus_Failed);
1062 }
1063
1064 LogRel(("Ended\n"));
1065 VbglR3Term();
1066 }
1067 else
1068 LogRel(("VbglR3Init failed: %Rrc\n", rc));
1069 }
1070
1071 /* Release instance mutex. */
1072 if (hMutexAppRunning != NULL)
1073 {
1074 CloseHandle(hMutexAppRunning);
1075 hMutexAppRunning = NULL;
1076 }
1077
1078 vboxTrayLogDestroy();
1079
1080 return RT_SUCCESS(rc) ? 0 : 1;
1081}
1082
1083/**
1084 * Window procedure for our main tool window.
1085 */
1086static LRESULT CALLBACK vboxToolWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
1087{
1088 LogFlowFunc(("hWnd=%p, uMsg=%u\n", hWnd, uMsg));
1089
1090 switch (uMsg)
1091 {
1092 case WM_CREATE:
1093 {
1094 LogFunc(("Tool window created\n"));
1095
1096 int rc = vboxTrayRegisterGlobalMessages(&g_vboxGlobalMessageTable[0]);
1097 if (RT_FAILURE(rc))
1098 LogFunc(("Error registering global window messages, rc=%Rrc\n", rc));
1099 return 0;
1100 }
1101
1102 case WM_CLOSE:
1103 return 0;
1104
1105 case WM_DESTROY:
1106 {
1107 LogFunc(("Tool window destroyed\n"));
1108 KillTimer(g_hwndToolWindow, TIMERID_VBOXTRAY_CHECK_HOSTVERSION);
1109 return 0;
1110 }
1111
1112 case WM_TIMER:
1113 {
1114 if (VBoxCapsCheckTimer(wParam))
1115 return 0;
1116 if (vboxDtCheckTimer(wParam))
1117 return 0;
1118 if (vboxStCheckTimer(wParam))
1119 return 0;
1120
1121 switch (wParam)
1122 {
1123 case TIMERID_VBOXTRAY_CHECK_HOSTVERSION:
1124 if (RT_SUCCESS(VBoxCheckHostVersion()))
1125 {
1126 /* After successful run we don't need to check again. */
1127 KillTimer(g_hwndToolWindow, TIMERID_VBOXTRAY_CHECK_HOSTVERSION);
1128 }
1129 return 0;
1130
1131 default:
1132 break;
1133 }
1134
1135 break; /* Make sure other timers get processed the usual way! */
1136 }
1137
1138 case WM_VBOXTRAY_TRAY_ICON:
1139 {
1140 switch (lParam)
1141 {
1142 case WM_LBUTTONDBLCLK:
1143 break;
1144
1145 case WM_RBUTTONDOWN:
1146 break;
1147 }
1148 return 0;
1149 }
1150
1151 case WM_VBOX_SEAMLESS_ENABLE:
1152 {
1153 VBoxCapsEntryFuncStateSet(VBOXCAPS_ENTRY_IDX_SEAMLESS, VBOXCAPS_ENTRY_FUNCSTATE_STARTED);
1154 if (VBoxCapsEntryIsEnabled(VBOXCAPS_ENTRY_IDX_SEAMLESS))
1155 VBoxSeamlessCheckWindows(true);
1156 return 0;
1157 }
1158
1159 case WM_VBOX_SEAMLESS_DISABLE:
1160 {
1161 VBoxCapsEntryFuncStateSet(VBOXCAPS_ENTRY_IDX_SEAMLESS, VBOXCAPS_ENTRY_FUNCSTATE_SUPPORTED);
1162 return 0;
1163 }
1164
1165 case WM_DISPLAYCHANGE:
1166 ASMAtomicUoWriteU32(&g_fGuestDisplaysChanged, 1);
1167 // No break or return is intentional here.
1168 case WM_VBOX_SEAMLESS_UPDATE:
1169 {
1170 if (VBoxCapsEntryIsEnabled(VBOXCAPS_ENTRY_IDX_SEAMLESS))
1171 VBoxSeamlessCheckWindows(true);
1172 return 0;
1173 }
1174
1175 case WM_VBOX_GRAPHICS_SUPPORTED:
1176 {
1177 VBoxGrapicsSetSupported(TRUE);
1178 return 0;
1179 }
1180
1181 case WM_VBOX_GRAPHICS_UNSUPPORTED:
1182 {
1183 VBoxGrapicsSetSupported(FALSE);
1184 return 0;
1185 }
1186
1187 case WM_WTSSESSION_CHANGE:
1188 {
1189 BOOL fOldAllowedState = VBoxConsoleIsAllowed();
1190 if (vboxStHandleEvent(wParam))
1191 {
1192 if (!VBoxConsoleIsAllowed() != !fOldAllowedState)
1193 VBoxConsoleEnable(!fOldAllowedState);
1194 }
1195 return 0;
1196 }
1197
1198 default:
1199 {
1200 /* Handle all globally registered window messages. */
1201 if (vboxTrayHandleGlobalMessages(&g_vboxGlobalMessageTable[0], uMsg,
1202 wParam, lParam))
1203 {
1204 return 0; /* We handled the message. @todo Add return value!*/
1205 }
1206 break; /* We did not handle the message, dispatch to DefWndProc. */
1207 }
1208 }
1209
1210 /* Only if message was *not* handled by our switch above, dispatch to DefWindowProc. */
1211 return DefWindowProc(hWnd, uMsg, wParam, lParam);
1212}
1213
1214/* St (session [state] tracking) functionality API impl */
1215
1216typedef struct VBOXST
1217{
1218 HWND hWTSAPIWnd;
1219 RTLDRMOD hLdrModWTSAPI32;
1220 BOOL fIsConsole;
1221 WTS_CONNECTSTATE_CLASS enmConnectState;
1222 UINT_PTR idDelayedInitTimer;
1223 BOOL (WINAPI * pfnWTSRegisterSessionNotification)(HWND hWnd, DWORD dwFlags);
1224 BOOL (WINAPI * pfnWTSUnRegisterSessionNotification)(HWND hWnd);
1225 BOOL (WINAPI * pfnWTSQuerySessionInformationA)(HANDLE hServer, DWORD SessionId, WTS_INFO_CLASS WTSInfoClass, LPTSTR *ppBuffer, DWORD *pBytesReturned);
1226} VBOXST;
1227
1228static VBOXST gVBoxSt;
1229
1230static int vboxStCheckState()
1231{
1232 int rc = VINF_SUCCESS;
1233 WTS_CONNECTSTATE_CLASS *penmConnectState = NULL;
1234 USHORT *pProtocolType = NULL;
1235 DWORD cbBuf = 0;
1236 if (gVBoxSt.pfnWTSQuerySessionInformationA(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, WTSConnectState,
1237 (LPTSTR *)&penmConnectState, &cbBuf))
1238 {
1239 if (gVBoxSt.pfnWTSQuerySessionInformationA(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, WTSClientProtocolType,
1240 (LPTSTR *)&pProtocolType, &cbBuf))
1241 {
1242 gVBoxSt.fIsConsole = (*pProtocolType == 0);
1243 gVBoxSt.enmConnectState = *penmConnectState;
1244 return VINF_SUCCESS;
1245 }
1246
1247 DWORD dwErr = GetLastError();
1248 LogFlowFunc(("WTSQuerySessionInformationA WTSClientProtocolType failed, error = %08X\n", dwErr));
1249 rc = RTErrConvertFromWin32(dwErr);
1250 }
1251 else
1252 {
1253 DWORD dwErr = GetLastError();
1254 LogFlowFunc(("WTSQuerySessionInformationA WTSConnectState failed, error = %08X\n", dwErr));
1255 rc = RTErrConvertFromWin32(dwErr);
1256 }
1257
1258 /* failure branch, set to "console-active" state */
1259 gVBoxSt.fIsConsole = TRUE;
1260 gVBoxSt.enmConnectState = WTSActive;
1261
1262 return rc;
1263}
1264
1265static int vboxStInit(HWND hWnd)
1266{
1267 RT_ZERO(gVBoxSt);
1268 int rc = RTLdrLoadSystem("WTSAPI32.DLL", false /*fNoUnload*/, &gVBoxSt.hLdrModWTSAPI32);
1269 if (RT_SUCCESS(rc))
1270 {
1271 rc = RTLdrGetSymbol(gVBoxSt.hLdrModWTSAPI32, "WTSRegisterSessionNotification",
1272 (void **)&gVBoxSt.pfnWTSRegisterSessionNotification);
1273 if (RT_SUCCESS(rc))
1274 {
1275 rc = RTLdrGetSymbol(gVBoxSt.hLdrModWTSAPI32, "WTSUnRegisterSessionNotification",
1276 (void **)&gVBoxSt.pfnWTSUnRegisterSessionNotification);
1277 if (RT_SUCCESS(rc))
1278 {
1279 rc = RTLdrGetSymbol(gVBoxSt.hLdrModWTSAPI32, "WTSQuerySessionInformationA",
1280 (void **)&gVBoxSt.pfnWTSQuerySessionInformationA);
1281 if (RT_FAILURE(rc))
1282 LogFlowFunc(("WTSQuerySessionInformationA not found\n"));
1283 }
1284 else
1285 LogFlowFunc(("WTSUnRegisterSessionNotification not found\n"));
1286 }
1287 else
1288 LogFlowFunc(("WTSRegisterSessionNotification not found\n"));
1289 if (RT_SUCCESS(rc))
1290 {
1291 gVBoxSt.hWTSAPIWnd = hWnd;
1292 if (gVBoxSt.pfnWTSRegisterSessionNotification(gVBoxSt.hWTSAPIWnd, NOTIFY_FOR_THIS_SESSION))
1293 vboxStCheckState();
1294 else
1295 {
1296 DWORD dwErr = GetLastError();
1297 LogFlowFunc(("WTSRegisterSessionNotification failed, error = %08X\n", dwErr));
1298 if (dwErr == RPC_S_INVALID_BINDING)
1299 {
1300 gVBoxSt.idDelayedInitTimer = SetTimer(gVBoxSt.hWTSAPIWnd, TIMERID_VBOXTRAY_ST_DELAYED_INIT_TIMER,
1301 2000, (TIMERPROC)NULL);
1302 gVBoxSt.fIsConsole = TRUE;
1303 gVBoxSt.enmConnectState = WTSActive;
1304 rc = VINF_SUCCESS;
1305 }
1306 else
1307 rc = RTErrConvertFromWin32(dwErr);
1308 }
1309
1310 if (RT_SUCCESS(rc))
1311 return VINF_SUCCESS;
1312 }
1313
1314 RTLdrClose(gVBoxSt.hLdrModWTSAPI32);
1315 }
1316 else
1317 LogFlowFunc(("WTSAPI32 load failed, rc = %Rrc\n", rc));
1318
1319 RT_ZERO(gVBoxSt);
1320 gVBoxSt.fIsConsole = TRUE;
1321 gVBoxSt.enmConnectState = WTSActive;
1322 return rc;
1323}
1324
1325static void vboxStTerm(void)
1326{
1327 if (!gVBoxSt.hWTSAPIWnd)
1328 {
1329 LogFlowFunc(("vboxStTerm called for non-initialized St\n"));
1330 return;
1331 }
1332
1333 if (gVBoxSt.idDelayedInitTimer)
1334 {
1335 /* notification is not registered, just kill timer */
1336 KillTimer(gVBoxSt.hWTSAPIWnd, gVBoxSt.idDelayedInitTimer);
1337 gVBoxSt.idDelayedInitTimer = 0;
1338 }
1339 else
1340 {
1341 if (!gVBoxSt.pfnWTSUnRegisterSessionNotification(gVBoxSt.hWTSAPIWnd))
1342 {
1343 LogFlowFunc(("WTSAPI32 load failed, error = %08X\n", GetLastError()));
1344 }
1345 }
1346
1347 RTLdrClose(gVBoxSt.hLdrModWTSAPI32);
1348 RT_ZERO(gVBoxSt);
1349}
1350
1351#define VBOXST_DBG_MAKECASE(_val) case _val: return #_val;
1352
1353static const char* vboxStDbgGetString(DWORD val)
1354{
1355 switch (val)
1356 {
1357 VBOXST_DBG_MAKECASE(WTS_CONSOLE_CONNECT);
1358 VBOXST_DBG_MAKECASE(WTS_CONSOLE_DISCONNECT);
1359 VBOXST_DBG_MAKECASE(WTS_REMOTE_CONNECT);
1360 VBOXST_DBG_MAKECASE(WTS_REMOTE_DISCONNECT);
1361 VBOXST_DBG_MAKECASE(WTS_SESSION_LOGON);
1362 VBOXST_DBG_MAKECASE(WTS_SESSION_LOGOFF);
1363 VBOXST_DBG_MAKECASE(WTS_SESSION_LOCK);
1364 VBOXST_DBG_MAKECASE(WTS_SESSION_UNLOCK);
1365 VBOXST_DBG_MAKECASE(WTS_SESSION_REMOTE_CONTROL);
1366 default:
1367 LogFlowFunc(("invalid WTS state %d\n", val));
1368 return "Unknown";
1369 }
1370}
1371
1372static BOOL vboxStCheckTimer(WPARAM wEvent)
1373{
1374 if (wEvent != gVBoxSt.idDelayedInitTimer)
1375 return FALSE;
1376
1377 if (gVBoxSt.pfnWTSRegisterSessionNotification(gVBoxSt.hWTSAPIWnd, NOTIFY_FOR_THIS_SESSION))
1378 {
1379 KillTimer(gVBoxSt.hWTSAPIWnd, gVBoxSt.idDelayedInitTimer);
1380 gVBoxSt.idDelayedInitTimer = 0;
1381 vboxStCheckState();
1382 }
1383 else
1384 {
1385 LogFlowFunc(("timer WTSRegisterSessionNotification failed, error = %08X\n", GetLastError()));
1386 Assert(gVBoxSt.fIsConsole == TRUE);
1387 Assert(gVBoxSt.enmConnectState == WTSActive);
1388 }
1389
1390 return TRUE;
1391}
1392
1393
1394static BOOL vboxStHandleEvent(WPARAM wEvent)
1395{
1396 RT_NOREF(wEvent);
1397 LogFlowFunc(("WTS Event: %s\n", vboxStDbgGetString(wEvent)));
1398 BOOL fOldIsActiveConsole = vboxStIsActiveConsole();
1399
1400 vboxStCheckState();
1401
1402 return !vboxStIsActiveConsole() != !fOldIsActiveConsole;
1403}
1404
1405static BOOL vboxStIsActiveConsole(void)
1406{
1407 return (gVBoxSt.enmConnectState == WTSActive && gVBoxSt.fIsConsole);
1408}
1409
1410/*
1411 * Dt (desktop [state] tracking) functionality API impl
1412 *
1413 * !!!NOTE: this API is NOT thread-safe!!!
1414 * */
1415
1416typedef struct VBOXDT
1417{
1418 HANDLE hNotifyEvent;
1419 BOOL fIsInputDesktop;
1420 UINT_PTR idTimer;
1421 RTLDRMOD hLdrModHook;
1422 BOOL (* pfnVBoxHookInstallActiveDesktopTracker)(HMODULE hDll);
1423 BOOL (* pfnVBoxHookRemoveActiveDesktopTracker)();
1424 HDESK (WINAPI * pfnGetThreadDesktop)(DWORD dwThreadId);
1425 HDESK (WINAPI * pfnOpenInputDesktop)(DWORD dwFlags, BOOL fInherit, ACCESS_MASK dwDesiredAccess);
1426 BOOL (WINAPI * pfnCloseDesktop)(HDESK hDesktop);
1427} VBOXDT;
1428
1429static VBOXDT gVBoxDt;
1430
1431static BOOL vboxDtCalculateIsInputDesktop()
1432{
1433 BOOL fIsInputDt = FALSE;
1434 HDESK hInput = gVBoxDt.pfnOpenInputDesktop(0, FALSE, DESKTOP_CREATEWINDOW);
1435 if (hInput)
1436 {
1437// DWORD dwThreadId = GetCurrentThreadId();
1438// HDESK hThreadDt = gVBoxDt.pfnGetThreadDesktop(dwThreadId);
1439// if (hThreadDt)
1440// {
1441 fIsInputDt = TRUE;
1442// }
1443// else
1444// {
1445// DWORD dwErr = GetLastError();
1446// LogFlowFunc(("pfnGetThreadDesktop for Seamless failed, last error = %08X\n", dwErr));
1447// }
1448
1449 gVBoxDt.pfnCloseDesktop(hInput);
1450 }
1451 else
1452 {
1453// DWORD dwErr = GetLastError();
1454// LogFlowFunc(("pfnOpenInputDesktop for Seamless failed, last error = %08X\n", dwErr));
1455 }
1456 return fIsInputDt;
1457}
1458
1459static BOOL vboxDtCheckTimer(WPARAM wParam)
1460{
1461 if (wParam != gVBoxDt.idTimer)
1462 return FALSE;
1463
1464 VBoxTrayCheckDt();
1465
1466 return TRUE;
1467}
1468
1469static int vboxDtInit()
1470{
1471 RT_ZERO(gVBoxDt);
1472
1473 int rc;
1474 gVBoxDt.hNotifyEvent = CreateEvent(NULL, FALSE, FALSE, VBOXHOOK_GLOBAL_DT_EVENT_NAME);
1475 if (gVBoxDt.hNotifyEvent != NULL)
1476 {
1477 /* Load the hook dll and resolve the necessary entry points. */
1478 rc = RTLdrLoadAppPriv(VBOXHOOK_DLL_NAME, &gVBoxDt.hLdrModHook);
1479 if (RT_SUCCESS(rc))
1480 {
1481 rc = RTLdrGetSymbol(gVBoxDt.hLdrModHook, "VBoxHookInstallActiveDesktopTracker",
1482 (void **)&gVBoxDt.pfnVBoxHookInstallActiveDesktopTracker);
1483 if (RT_SUCCESS(rc))
1484 {
1485 rc = RTLdrGetSymbol(gVBoxDt.hLdrModHook, "VBoxHookRemoveActiveDesktopTracker",
1486 (void **)&gVBoxDt.pfnVBoxHookRemoveActiveDesktopTracker);
1487 if (RT_FAILURE(rc))
1488 LogFlowFunc(("VBoxHookRemoveActiveDesktopTracker not found\n"));
1489 }
1490 else
1491 LogFlowFunc(("VBoxHookInstallActiveDesktopTracker not found\n"));
1492 if (RT_SUCCESS(rc))
1493 {
1494 /* Try get the system APIs we need. */
1495 *(void **)&gVBoxDt.pfnGetThreadDesktop = RTLdrGetSystemSymbol("user32.dll", "GetThreadDesktop");
1496 if (!gVBoxDt.pfnGetThreadDesktop)
1497 {
1498 LogFlowFunc(("GetThreadDesktop not found\n"));
1499 rc = VERR_NOT_SUPPORTED;
1500 }
1501
1502 *(void **)&gVBoxDt.pfnOpenInputDesktop = RTLdrGetSystemSymbol("user32.dll", "OpenInputDesktop");
1503 if (!gVBoxDt.pfnOpenInputDesktop)
1504 {
1505 LogFlowFunc(("OpenInputDesktop not found\n"));
1506 rc = VERR_NOT_SUPPORTED;
1507 }
1508
1509 *(void **)&gVBoxDt.pfnCloseDesktop = RTLdrGetSystemSymbol("user32.dll", "CloseDesktop");
1510 if (!gVBoxDt.pfnCloseDesktop)
1511 {
1512 LogFlowFunc(("CloseDesktop not found\n"));
1513 rc = VERR_NOT_SUPPORTED;
1514 }
1515
1516 if (RT_SUCCESS(rc))
1517 {
1518 BOOL fRc = FALSE;
1519 /* For Vista and up we need to change the integrity of the security descriptor, too. */
1520 uint64_t const uNtVersion = RTSystemGetNtVersion();
1521 if (uNtVersion >= RTSYSTEM_MAKE_NT_VERSION(6, 0, 0))
1522 {
1523 HMODULE hModHook = (HMODULE)RTLdrGetNativeHandle(gVBoxDt.hLdrModHook);
1524 Assert((uintptr_t)hModHook != ~(uintptr_t)0);
1525 fRc = gVBoxDt.pfnVBoxHookInstallActiveDesktopTracker(hModHook);
1526 if (!fRc)
1527 LogFlowFunc(("pfnVBoxHookInstallActiveDesktopTracker failed, last error = %08X\n", GetLastError()));
1528 }
1529
1530 if (!fRc)
1531 {
1532 gVBoxDt.idTimer = SetTimer(g_hwndToolWindow, TIMERID_VBOXTRAY_DT_TIMER, 500, (TIMERPROC)NULL);
1533 if (!gVBoxDt.idTimer)
1534 {
1535 DWORD dwErr = GetLastError();
1536 LogFlowFunc(("SetTimer error %08X\n", dwErr));
1537 rc = RTErrConvertFromWin32(dwErr);
1538 }
1539 }
1540
1541 if (RT_SUCCESS(rc))
1542 {
1543 gVBoxDt.fIsInputDesktop = vboxDtCalculateIsInputDesktop();
1544 return VINF_SUCCESS;
1545 }
1546 }
1547 }
1548
1549 RTLdrClose(gVBoxDt.hLdrModHook);
1550 }
1551 else
1552 {
1553 DWORD dwErr = GetLastError();
1554 LogFlowFunc(("CreateEvent for Seamless failed, last error = %08X\n", dwErr));
1555 rc = RTErrConvertFromWin32(dwErr);
1556 }
1557
1558 CloseHandle(gVBoxDt.hNotifyEvent);
1559 }
1560 else
1561 {
1562 DWORD dwErr = GetLastError();
1563 LogFlowFunc(("CreateEvent for Seamless failed, last error = %08X\n", dwErr));
1564 rc = RTErrConvertFromWin32(dwErr);
1565 }
1566
1567
1568 RT_ZERO(gVBoxDt);
1569 gVBoxDt.fIsInputDesktop = TRUE;
1570
1571 return rc;
1572}
1573
1574static void vboxDtTerm()
1575{
1576 if (!gVBoxDt.hLdrModHook)
1577 return;
1578
1579 gVBoxDt.pfnVBoxHookRemoveActiveDesktopTracker();
1580
1581 RTLdrClose(gVBoxDt.hLdrModHook);
1582 CloseHandle(gVBoxDt.hNotifyEvent);
1583
1584 RT_ZERO(gVBoxDt);
1585}
1586/* @returns true on "IsInputDesktop" state change */
1587static BOOL vboxDtHandleEvent()
1588{
1589 BOOL fIsInputDesktop = gVBoxDt.fIsInputDesktop;
1590 gVBoxDt.fIsInputDesktop = vboxDtCalculateIsInputDesktop();
1591 return !fIsInputDesktop != !gVBoxDt.fIsInputDesktop;
1592}
1593
1594static HANDLE vboxDtGetNotifyEvent()
1595{
1596 return gVBoxDt.hNotifyEvent;
1597}
1598
1599/* @returns true iff the application (VBoxTray) desktop is input */
1600static BOOL vboxDtIsInputDesktop()
1601{
1602 return gVBoxDt.fIsInputDesktop;
1603}
1604
1605/* we need to perform Acquire/Release using the file handled we use for rewuesting events from VBoxGuest
1606 * otherwise Acquisition mechanism will treat us as different client and will not propagate necessary requests
1607 * */
1608static int VBoxAcquireGuestCaps(uint32_t fOr, uint32_t fNot, bool fCfg)
1609{
1610 Log(("VBoxAcquireGuestCaps or(0x%x), not(0x%x), cfx(%d)\n", fOr, fNot, fCfg));
1611 int rc = VbglR3AcquireGuestCaps(fOr, fNot, fCfg);
1612 if (RT_FAILURE(rc))
1613 LogFlowFunc(("VBOXGUEST_IOCTL_GUEST_CAPS_ACQUIRE failed: %Rrc\n", rc));
1614 return rc;
1615}
1616
1617typedef enum VBOXCAPS_ENTRY_ACSTATE
1618{
1619 /* the given cap is released */
1620 VBOXCAPS_ENTRY_ACSTATE_RELEASED = 0,
1621 /* the given cap acquisition is in progress */
1622 VBOXCAPS_ENTRY_ACSTATE_ACQUIRING,
1623 /* the given cap is acquired */
1624 VBOXCAPS_ENTRY_ACSTATE_ACQUIRED
1625} VBOXCAPS_ENTRY_ACSTATE;
1626
1627
1628struct VBOXCAPS_ENTRY;
1629struct VBOXCAPS;
1630
1631typedef DECLCALLBACKPTR(void, PFNVBOXCAPS_ENTRY_ON_ENABLE)(struct VBOXCAPS *pConsole, struct VBOXCAPS_ENTRY *pCap, BOOL fEnabled);
1632
1633typedef struct VBOXCAPS_ENTRY
1634{
1635 uint32_t fCap;
1636 uint32_t iCap;
1637 VBOXCAPS_ENTRY_FUNCSTATE enmFuncState;
1638 VBOXCAPS_ENTRY_ACSTATE enmAcState;
1639 PFNVBOXCAPS_ENTRY_ON_ENABLE pfnOnEnable;
1640} VBOXCAPS_ENTRY;
1641
1642
1643typedef struct VBOXCAPS
1644{
1645 UINT_PTR idTimer;
1646 VBOXCAPS_ENTRY aCaps[VBOXCAPS_ENTRY_IDX_COUNT];
1647} VBOXCAPS;
1648
1649static VBOXCAPS gVBoxCaps;
1650
1651static DECLCALLBACK(void) vboxCapsOnEnableSeamless(struct VBOXCAPS *pConsole, struct VBOXCAPS_ENTRY *pCap, BOOL fEnabled)
1652{
1653 RT_NOREF(pConsole, pCap);
1654 if (fEnabled)
1655 {
1656 Log(("vboxCapsOnEnableSeamless: ENABLED\n"));
1657 Assert(pCap->enmAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED);
1658 Assert(pCap->enmFuncState == VBOXCAPS_ENTRY_FUNCSTATE_STARTED);
1659 VBoxSeamlessEnable();
1660 }
1661 else
1662 {
1663 Log(("vboxCapsOnEnableSeamless: DISABLED\n"));
1664 Assert(pCap->enmAcState != VBOXCAPS_ENTRY_ACSTATE_ACQUIRED || pCap->enmFuncState != VBOXCAPS_ENTRY_FUNCSTATE_STARTED);
1665 VBoxSeamlessDisable();
1666 }
1667}
1668
1669static void vboxCapsEntryAcStateSet(VBOXCAPS_ENTRY *pCap, VBOXCAPS_ENTRY_ACSTATE enmAcState)
1670{
1671 VBOXCAPS *pConsole = &gVBoxCaps;
1672
1673 Log(("vboxCapsEntryAcStateSet: new state enmAcState(%d); pCap: fCap(%d), iCap(%d), enmFuncState(%d), enmAcState(%d)\n",
1674 enmAcState, pCap->fCap, pCap->iCap, pCap->enmFuncState, pCap->enmAcState));
1675
1676 if (pCap->enmAcState == enmAcState)
1677 return;
1678
1679 VBOXCAPS_ENTRY_ACSTATE enmOldAcState = pCap->enmAcState;
1680 pCap->enmAcState = enmAcState;
1681
1682 if (enmAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED)
1683 {
1684 if (pCap->enmFuncState == VBOXCAPS_ENTRY_FUNCSTATE_STARTED)
1685 {
1686 if (pCap->pfnOnEnable)
1687 pCap->pfnOnEnable(pConsole, pCap, TRUE);
1688 }
1689 }
1690 else if (enmOldAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED && pCap->enmFuncState == VBOXCAPS_ENTRY_FUNCSTATE_STARTED)
1691 {
1692 if (pCap->pfnOnEnable)
1693 pCap->pfnOnEnable(pConsole, pCap, FALSE);
1694 }
1695}
1696
1697static void vboxCapsEntryFuncStateSet(VBOXCAPS_ENTRY *pCap, VBOXCAPS_ENTRY_FUNCSTATE enmFuncState)
1698{
1699 VBOXCAPS *pConsole = &gVBoxCaps;
1700
1701 Log(("vboxCapsEntryFuncStateSet: new state enmAcState(%d); pCap: fCap(%d), iCap(%d), enmFuncState(%d), enmAcState(%d)\n",
1702 enmFuncState, pCap->fCap, pCap->iCap, pCap->enmFuncState, pCap->enmAcState));
1703
1704 if (pCap->enmFuncState == enmFuncState)
1705 return;
1706
1707 VBOXCAPS_ENTRY_FUNCSTATE enmOldFuncState = pCap->enmFuncState;
1708
1709 pCap->enmFuncState = enmFuncState;
1710
1711 if (enmFuncState == VBOXCAPS_ENTRY_FUNCSTATE_STARTED)
1712 {
1713 Assert(enmOldFuncState == VBOXCAPS_ENTRY_FUNCSTATE_SUPPORTED);
1714 if (pCap->enmAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED)
1715 {
1716 if (pCap->pfnOnEnable)
1717 pCap->pfnOnEnable(pConsole, pCap, TRUE);
1718 }
1719 }
1720 else if (pCap->enmAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED && enmOldFuncState == VBOXCAPS_ENTRY_FUNCSTATE_STARTED)
1721 {
1722 if (pCap->pfnOnEnable)
1723 pCap->pfnOnEnable(pConsole, pCap, FALSE);
1724 }
1725}
1726
1727static void VBoxCapsEntryFuncStateSet(uint32_t iCup, VBOXCAPS_ENTRY_FUNCSTATE enmFuncState)
1728{
1729 VBOXCAPS *pConsole = &gVBoxCaps;
1730 VBOXCAPS_ENTRY *pCap = &pConsole->aCaps[iCup];
1731 vboxCapsEntryFuncStateSet(pCap, enmFuncState);
1732}
1733
1734static int VBoxCapsInit()
1735{
1736 VBOXCAPS *pConsole = &gVBoxCaps;
1737 memset(pConsole, 0, sizeof (*pConsole));
1738 pConsole->aCaps[VBOXCAPS_ENTRY_IDX_SEAMLESS].fCap = VMMDEV_GUEST_SUPPORTS_SEAMLESS;
1739 pConsole->aCaps[VBOXCAPS_ENTRY_IDX_SEAMLESS].iCap = VBOXCAPS_ENTRY_IDX_SEAMLESS;
1740 pConsole->aCaps[VBOXCAPS_ENTRY_IDX_SEAMLESS].pfnOnEnable = vboxCapsOnEnableSeamless;
1741 pConsole->aCaps[VBOXCAPS_ENTRY_IDX_GRAPHICS].fCap = VMMDEV_GUEST_SUPPORTS_GRAPHICS;
1742 pConsole->aCaps[VBOXCAPS_ENTRY_IDX_GRAPHICS].iCap = VBOXCAPS_ENTRY_IDX_GRAPHICS;
1743 return VINF_SUCCESS;
1744}
1745
1746static int VBoxCapsReleaseAll()
1747{
1748 VBOXCAPS *pConsole = &gVBoxCaps;
1749 Log(("VBoxCapsReleaseAll\n"));
1750 int rc = VBoxAcquireGuestCaps(0, VMMDEV_GUEST_SUPPORTS_SEAMLESS | VMMDEV_GUEST_SUPPORTS_GRAPHICS, false);
1751 if (!RT_SUCCESS(rc))
1752 {
1753 LogFlowFunc(("vboxCapsEntryReleaseAll VBoxAcquireGuestCaps failed rc %d\n", rc));
1754 return rc;
1755 }
1756
1757 if (pConsole->idTimer)
1758 {
1759 Log(("killing console timer\n"));
1760 KillTimer(g_hwndToolWindow, pConsole->idTimer);
1761 pConsole->idTimer = 0;
1762 }
1763
1764 for (int i = 0; i < RT_ELEMENTS(pConsole->aCaps); ++i)
1765 {
1766 vboxCapsEntryAcStateSet(&pConsole->aCaps[i], VBOXCAPS_ENTRY_ACSTATE_RELEASED);
1767 }
1768
1769 return rc;
1770}
1771
1772static void VBoxCapsTerm()
1773{
1774 VBOXCAPS *pConsole = &gVBoxCaps;
1775 VBoxCapsReleaseAll();
1776 memset(pConsole, 0, sizeof (*pConsole));
1777}
1778
1779static BOOL VBoxCapsEntryIsAcquired(uint32_t iCap)
1780{
1781 VBOXCAPS *pConsole = &gVBoxCaps;
1782 return pConsole->aCaps[iCap].enmAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED;
1783}
1784
1785static BOOL VBoxCapsEntryIsEnabled(uint32_t iCap)
1786{
1787 VBOXCAPS *pConsole = &gVBoxCaps;
1788 return pConsole->aCaps[iCap].enmAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED
1789 && pConsole->aCaps[iCap].enmFuncState == VBOXCAPS_ENTRY_FUNCSTATE_STARTED;
1790}
1791
1792static BOOL VBoxCapsCheckTimer(WPARAM wParam)
1793{
1794 VBOXCAPS *pConsole = &gVBoxCaps;
1795 if (wParam != pConsole->idTimer)
1796 return FALSE;
1797
1798 uint32_t u32AcquiredCaps = 0;
1799 BOOL fNeedNewTimer = FALSE;
1800
1801 for (int i = 0; i < RT_ELEMENTS(pConsole->aCaps); ++i)
1802 {
1803 VBOXCAPS_ENTRY *pCap = &pConsole->aCaps[i];
1804 if (pCap->enmAcState != VBOXCAPS_ENTRY_ACSTATE_ACQUIRING)
1805 continue;
1806
1807 int rc = VBoxAcquireGuestCaps(pCap->fCap, 0, false);
1808 if (RT_SUCCESS(rc))
1809 {
1810 vboxCapsEntryAcStateSet(&pConsole->aCaps[i], VBOXCAPS_ENTRY_ACSTATE_ACQUIRED);
1811 u32AcquiredCaps |= pCap->fCap;
1812 }
1813 else
1814 {
1815 Assert(rc == VERR_RESOURCE_BUSY);
1816 fNeedNewTimer = TRUE;
1817 }
1818 }
1819
1820 if (!fNeedNewTimer)
1821 {
1822 KillTimer(g_hwndToolWindow, pConsole->idTimer);
1823 /* cleanup timer data */
1824 pConsole->idTimer = 0;
1825 }
1826
1827 return TRUE;
1828}
1829
1830static int VBoxCapsEntryRelease(uint32_t iCap)
1831{
1832 VBOXCAPS *pConsole = &gVBoxCaps;
1833 VBOXCAPS_ENTRY *pCap = &pConsole->aCaps[iCap];
1834 if (pCap->enmAcState == VBOXCAPS_ENTRY_ACSTATE_RELEASED)
1835 {
1836 LogFlowFunc(("invalid cap[%d] state[%d] on release\n", iCap, pCap->enmAcState));
1837 return VERR_INVALID_STATE;
1838 }
1839
1840 if (pCap->enmAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED)
1841 {
1842 int rc = VBoxAcquireGuestCaps(0, pCap->fCap, false);
1843 AssertRC(rc);
1844 }
1845
1846 vboxCapsEntryAcStateSet(pCap, VBOXCAPS_ENTRY_ACSTATE_RELEASED);
1847
1848 return VINF_SUCCESS;
1849}
1850
1851static int VBoxCapsEntryAcquire(uint32_t iCap)
1852{
1853 VBOXCAPS *pConsole = &gVBoxCaps;
1854 Assert(VBoxConsoleIsAllowed());
1855 VBOXCAPS_ENTRY *pCap = &pConsole->aCaps[iCap];
1856 Log(("VBoxCapsEntryAcquire %d\n", iCap));
1857 if (pCap->enmAcState != VBOXCAPS_ENTRY_ACSTATE_RELEASED)
1858 {
1859 LogFlowFunc(("invalid cap[%d] state[%d] on acquire\n", iCap, pCap->enmAcState));
1860 return VERR_INVALID_STATE;
1861 }
1862
1863 vboxCapsEntryAcStateSet(pCap, VBOXCAPS_ENTRY_ACSTATE_ACQUIRING);
1864 int rc = VBoxAcquireGuestCaps(pCap->fCap, 0, false);
1865 if (RT_SUCCESS(rc))
1866 {
1867 vboxCapsEntryAcStateSet(pCap, VBOXCAPS_ENTRY_ACSTATE_ACQUIRED);
1868 return VINF_SUCCESS;
1869 }
1870
1871 if (rc != VERR_RESOURCE_BUSY)
1872 {
1873 LogFlowFunc(("vboxCapsEntryReleaseAll VBoxAcquireGuestCaps failed rc %d\n", rc));
1874 return rc;
1875 }
1876
1877 LogFlowFunc(("iCap %d is busy!\n", iCap));
1878
1879 /* the cap was busy, most likely it is still used by other VBoxTray instance running in another session,
1880 * queue the retry timer */
1881 if (!pConsole->idTimer)
1882 {
1883 pConsole->idTimer = SetTimer(g_hwndToolWindow, TIMERID_VBOXTRAY_CAPS_TIMER, 100, (TIMERPROC)NULL);
1884 if (!pConsole->idTimer)
1885 {
1886 DWORD dwErr = GetLastError();
1887 LogFlowFunc(("SetTimer error %08X\n", dwErr));
1888 return RTErrConvertFromWin32(dwErr);
1889 }
1890 }
1891
1892 return rc;
1893}
1894
1895static int VBoxCapsAcquireAllSupported()
1896{
1897 VBOXCAPS *pConsole = &gVBoxCaps;
1898 Log(("VBoxCapsAcquireAllSupported\n"));
1899 for (int i = 0; i < RT_ELEMENTS(pConsole->aCaps); ++i)
1900 {
1901 if (pConsole->aCaps[i].enmFuncState >= VBOXCAPS_ENTRY_FUNCSTATE_SUPPORTED)
1902 {
1903 Log(("VBoxCapsAcquireAllSupported acquiring cap %d, state %d\n", i, pConsole->aCaps[i].enmFuncState));
1904 VBoxCapsEntryAcquire(i);
1905 }
1906 else
1907 {
1908 LogFlowFunc(("VBoxCapsAcquireAllSupported: WARN: cap %d not supported, state %d\n", i, pConsole->aCaps[i].enmFuncState));
1909 }
1910 }
1911 return VINF_SUCCESS;
1912}
1913
1914static BOOL VBoxConsoleIsAllowed()
1915{
1916 return vboxDtIsInputDesktop() && vboxStIsActiveConsole();
1917}
1918
1919static void VBoxConsoleEnable(BOOL fEnable)
1920{
1921 if (fEnable)
1922 VBoxCapsAcquireAllSupported();
1923 else
1924 VBoxCapsReleaseAll();
1925}
1926
1927static void VBoxConsoleCapSetSupported(uint32_t iCap, BOOL fSupported)
1928{
1929 if (fSupported)
1930 {
1931 VBoxCapsEntryFuncStateSet(iCap, VBOXCAPS_ENTRY_FUNCSTATE_SUPPORTED);
1932
1933 if (VBoxConsoleIsAllowed())
1934 VBoxCapsEntryAcquire(iCap);
1935 }
1936 else
1937 {
1938 VBoxCapsEntryFuncStateSet(iCap, VBOXCAPS_ENTRY_FUNCSTATE_UNSUPPORTED);
1939
1940 VBoxCapsEntryRelease(iCap);
1941 }
1942}
1943
1944void VBoxSeamlessSetSupported(BOOL fSupported)
1945{
1946 VBoxConsoleCapSetSupported(VBOXCAPS_ENTRY_IDX_SEAMLESS, fSupported);
1947}
1948
1949static void VBoxGrapicsSetSupported(BOOL fSupported)
1950{
1951 VBoxConsoleCapSetSupported(VBOXCAPS_ENTRY_IDX_GRAPHICS, fSupported);
1952}
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette