VirtualBox

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

Last change on this file since 69496 was 69496, checked in by vboxsync, 7 years ago

*: scm --update-copyright-year

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