VirtualBox

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

最後變更 在這個檔案從95864是 95864,由 vboxsync 提交於 3 年 前

VBoxTray: There is no need for the /l, /v, /version or /V options as there is no legacy to think of here. The /? and /help options makes sense, given that we're on windows. Also, no need to specify '-l' as a long option when 'l' is the short option (probably some copy & paste issue, so fix original). Ditto for '-v'.

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

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