VirtualBox

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

Last change on this file since 68437 was 68437, checked in by vboxsync, 8 years ago

VBoxTray: Use VbglR3 APIs for everything. Untested.

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

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