VirtualBox

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

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

Additions/VBoxTray: Added long overdue command line handling to VBoxTray to specify verbosity and log file handling, to make it easier for normal users to enable debugging (also as a runtime setting). When verbosity is increased, this also will enable VBoxTray's popup menu (via right click in system tray). bugref:10267

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 71.5 KB
 
1/* $Id: VBoxTray.cpp 95827 2022-07-26 09:55:21Z 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 sprintf(g_NotifyIconData.szTip, "%s Guest Additions %d.%d.%dr%d",
228 VBOX_PRODUCT, VBOX_VERSION_MAJOR, VBOX_VERSION_MINOR, VBOX_VERSION_BUILD, VBOX_SVN_REV);
229
230 int rc = VINF_SUCCESS;
231 if (!Shell_NotifyIcon(NIM_ADD, &g_NotifyIconData))
232 {
233 DWORD dwErr = GetLastError();
234 LogFunc(("Could not create tray icon, error=%ld\n", dwErr));
235 rc = RTErrConvertFromWin32(dwErr);
236 RT_ZERO(g_NotifyIconData);
237 }
238
239 if (hIcon)
240 DestroyIcon(hIcon);
241 return rc;
242}
243
244static void vboxTrayRemoveTrayIcon(void)
245{
246 if (g_NotifyIconData.cbSize > 0)
247 {
248 /* Remove the system tray icon and refresh system tray. */
249 Shell_NotifyIcon(NIM_DELETE, &g_NotifyIconData);
250 HWND hTrayWnd = FindWindow("Shell_TrayWnd", NULL); /* We assume we only have one tray atm. */
251 if (hTrayWnd)
252 {
253 HWND hTrayNotifyWnd = FindWindowEx(hTrayWnd, 0, "TrayNotifyWnd", NULL);
254 if (hTrayNotifyWnd)
255 SendMessage(hTrayNotifyWnd, WM_PAINT, 0, NULL);
256 }
257 RT_ZERO(g_NotifyIconData);
258 }
259}
260
261/**
262 * The service thread.
263 *
264 * @returns Whatever the worker function returns.
265 * @param ThreadSelf My thread handle.
266 * @param pvUser The service index.
267 */
268static DECLCALLBACK(int) vboxTrayServiceThread(RTTHREAD ThreadSelf, void *pvUser)
269{
270 PVBOXSERVICEINFO pSvc = (PVBOXSERVICEINFO)pvUser;
271 AssertPtr(pSvc);
272
273#ifndef RT_OS_WINDOWS
274 /*
275 * Block all signals for this thread. Only the main thread will handle signals.
276 */
277 sigset_t signalMask;
278 sigfillset(&signalMask);
279 pthread_sigmask(SIG_BLOCK, &signalMask, NULL);
280#endif
281
282 int rc = pSvc->pDesc->pfnWorker(pSvc->pInstance, &pSvc->fShutdown);
283 ASMAtomicXchgBool(&pSvc->fShutdown, true);
284 RTThreadUserSignal(ThreadSelf);
285
286 LogFunc(("Worker for '%s' ended with %Rrc\n", pSvc->pDesc->pszName, rc));
287 return rc;
288}
289
290static int vboxTrayServicesStart(PVBOXSERVICEENV pEnv)
291{
292 AssertPtrReturn(pEnv, VERR_INVALID_POINTER);
293
294 LogRel(("Starting services ...\n"));
295
296 int rc = VINF_SUCCESS;
297
298 for (unsigned i = 0; i < RT_ELEMENTS(g_aServices); i++)
299 {
300 PVBOXSERVICEINFO pSvc = &g_aServices[i];
301 LogRel(("Starting service '%s' ...\n", pSvc->pDesc->pszName));
302
303 pSvc->hThread = NIL_RTTHREAD;
304 pSvc->pInstance = NULL;
305 pSvc->fStarted = false;
306 pSvc->fShutdown = false;
307
308 int rc2 = VINF_SUCCESS;
309
310 if (pSvc->pDesc->pfnInit)
311 rc2 = pSvc->pDesc->pfnInit(pEnv, &pSvc->pInstance);
312
313 if (RT_FAILURE(rc2))
314 {
315 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 */
1001int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
1002{
1003 RT_NOREF(hPrevInstance, lpCmdLine, nCmdShow);
1004
1005 int rc = RTR3InitExe(__argc, &__argv, RTR3INIT_FLAGS_STANDALONE_APP);
1006 if (RT_FAILURE(rc))
1007 return RTMsgInitFailure(rc);
1008
1009 LPWSTR pwszCmdLine = GetCommandLineW();
1010 if (!pwszCmdLine)
1011 return RTMsgErrorExit(RTEXITCODE_FAILURE, "GetCommandLineW failed");
1012
1013 char *pszCmdLine;
1014 rc = RTUtf16ToUtf8(pwszCmdLine, &pszCmdLine); /* leaked */
1015 if (RT_FAILURE(rc))
1016 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to convert the command line: %Rrc", rc);
1017
1018 char szLogFile[RTPATH_MAX] = {0};
1019
1020 int cArgs;
1021 char **papszArgs;
1022 rc = RTGetOptArgvFromString(&papszArgs, &cArgs, pszCmdLine, RTGETOPTARGV_CNV_QUOTE_MS_CRT, NULL);
1023 if (RT_SUCCESS(rc))
1024 {
1025 /*
1026 * Parse the top level arguments until we find a command.
1027 */
1028 static const RTGETOPTDEF s_aOptions[] =
1029 {
1030 { "--help", 'h', RTGETOPT_REQ_NOTHING },
1031 { "-help", 'h', RTGETOPT_REQ_NOTHING },
1032 { "/help", 'h', RTGETOPT_REQ_NOTHING },
1033 { "/?", 'h', RTGETOPT_REQ_NOTHING },
1034 { "--logfile", 'l', RTGETOPT_REQ_STRING },
1035 { "-l", 'l', RTGETOPT_REQ_STRING },
1036 { "/l", 'l', RTGETOPT_REQ_STRING },
1037 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
1038 { "-v", 'v', RTGETOPT_REQ_NOTHING },
1039 { "/v", 'v', RTGETOPT_REQ_NOTHING },
1040 { "--version", 'V', RTGETOPT_REQ_NOTHING },
1041 { "-version", 'V', RTGETOPT_REQ_NOTHING },
1042 { "/version", 'V', RTGETOPT_REQ_NOTHING },
1043 { "/V", 'V', RTGETOPT_REQ_NOTHING }
1044 };
1045
1046 RTGETOPTSTATE GetState;
1047 rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, 0 /*fFlags*/);
1048 if (RT_FAILURE(rc))
1049 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTGetOptInit failed: %Rrc\n", rc);
1050
1051 int ch;
1052 RTGETOPTUNION ValueUnion;
1053 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
1054 {
1055 switch (ch)
1056 {
1057 case 'h':
1058 hlpShowMessageBox(VBOX_VBOXTRAY_TITLE, MB_ICONINFORMATION, "-- %s v%u.%u.%ur%u --\n"
1059 "\n"
1060 "Command Line Parameters:\n\n"
1061 "-l, --logfile <file>\n"
1062 " Enables logging to a file\n"
1063 "-v, --verbose\n"
1064 " Increases verbosity\n"
1065 "-V, --version\n"
1066 " Displays version number and exit\n"
1067 "-?, -h, --help\n"
1068 " Displays this help text and exit\n"
1069 "\n"
1070 "Examples:\n"
1071 " %s -vvv\n",
1072 VBOX_VBOXTRAY_TITLE, VBOX_VERSION_MAJOR, VBOX_VERSION_MINOR, VBOX_VERSION_BUILD, VBOX_SVN_REV,
1073 papszArgs[0], papszArgs[0]);
1074 return RTEXITCODE_SUCCESS;
1075
1076 case 'l':
1077 if (*ValueUnion.psz == '\0')
1078 szLogFile[0] = '\0';
1079 else
1080 {
1081 rc = RTPathAbs(ValueUnion.psz, szLogFile, sizeof(szLogFile));
1082 if (RT_FAILURE(rc))
1083 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Log file path is too long (%Rrc)", rc);
1084 }
1085 break;
1086
1087 case 'v':
1088 g_cVerbosity++;
1089 break;
1090
1091 case 'V':
1092 hlpShowMessageBox(VBOX_VBOXTRAY_TITLE, MB_ICONINFORMATION,
1093 "Version: %u.%u.%ur%u",
1094 VBOX_VERSION_MAJOR, VBOX_VERSION_MINOR, VBOX_VERSION_BUILD, VBOX_SVN_REV);
1095 return RTEXITCODE_SUCCESS;
1096
1097 default:
1098 rc = RTGetOptPrintError(ch, &ValueUnion);
1099 break;
1100 }
1101 }
1102
1103 RTGetOptArgvFree(papszArgs);
1104 }
1105 else
1106 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTGetOptArgvFromString failed: %Rrc", rc);
1107
1108 /* Note: Do not use a global namespace ("Global\\") for mutex name here,
1109 * will blow up NT4 compatibility! */
1110 HANDLE hMutexAppRunning = CreateMutex(NULL, FALSE, VBOX_VBOXTRAY_TITLE);
1111 if ( hMutexAppRunning != NULL
1112 && GetLastError() == ERROR_ALREADY_EXISTS)
1113 {
1114 /* VBoxTray already running? Bail out. */
1115 CloseHandle (hMutexAppRunning);
1116 hMutexAppRunning = NULL;
1117 return RTEXITCODE_SUCCESS;
1118 }
1119
1120 rc = vboxTrayLogCreate(szLogFile[0] ? szLogFile : NULL);
1121 if (RT_SUCCESS(rc))
1122 {
1123 LogRel(("Verbosity level: %d\n", g_cVerbosity));
1124
1125 rc = VbglR3Init();
1126 if (RT_SUCCESS(rc))
1127 {
1128 /* Log the major windows NT version: */
1129 uint64_t const uNtVersion = RTSystemGetNtVersion();
1130 LogRel(("Windows version %u.%u build %u (uNtVersion=%#RX64)\n", RTSYSTEM_NT_VERSION_GET_MAJOR(uNtVersion),
1131 RTSYSTEM_NT_VERSION_GET_MINOR(uNtVersion), RTSYSTEM_NT_VERSION_GET_BUILD(uNtVersion), uNtVersion ));
1132
1133 /* Save instance handle. */
1134 g_hInstance = hInstance;
1135
1136 hlpReportStatus(VBoxGuestFacilityStatus_Init);
1137 rc = vboxTrayCreateToolWindow();
1138 if (RT_SUCCESS(rc))
1139 {
1140 VBoxCapsInit();
1141
1142 rc = vboxStInit(g_hwndToolWindow);
1143 if (!RT_SUCCESS(rc))
1144 {
1145 LogFlowFunc(("vboxStInit failed, rc=%Rrc\n", rc));
1146 /* ignore the St Init failure. this can happen for < XP win that do not support WTS API
1147 * in that case the session is treated as active connected to the physical console
1148 * (i.e. fallback to the old behavior that was before introduction of VBoxSt) */
1149 Assert(vboxStIsActiveConsole());
1150 }
1151
1152 rc = vboxDtInit();
1153 if (!RT_SUCCESS(rc))
1154 {
1155 LogFlowFunc(("vboxDtInit failed, rc=%Rrc\n", rc));
1156 /* ignore the Dt Init failure. this can happen for < XP win that do not support WTS API
1157 * in that case the session is treated as active connected to the physical console
1158 * (i.e. fallback to the old behavior that was before introduction of VBoxSt) */
1159 Assert(vboxDtIsInputDesktop());
1160 }
1161
1162 rc = VBoxAcquireGuestCaps(VMMDEV_GUEST_SUPPORTS_SEAMLESS | VMMDEV_GUEST_SUPPORTS_GRAPHICS, 0, true);
1163 if (!RT_SUCCESS(rc))
1164 LogFlowFunc(("VBoxAcquireGuestCaps failed with rc=%Rrc, ignoring ...\n", rc));
1165
1166 rc = vboxTraySetupSeamless(); /** @todo r=andy Do we really want to be this critical for the whole application? */
1167 if (RT_SUCCESS(rc))
1168 {
1169 rc = vboxTrayServiceMain();
1170 if (RT_SUCCESS(rc))
1171 hlpReportStatus(VBoxGuestFacilityStatus_Terminating);
1172 vboxTrayShutdownSeamless();
1173 }
1174
1175 /* it should be safe to call vboxDtTerm even if vboxStInit above failed */
1176 vboxDtTerm();
1177
1178 /* it should be safe to call vboxStTerm even if vboxStInit above failed */
1179 vboxStTerm();
1180
1181 VBoxCapsTerm();
1182
1183 vboxTrayDestroyToolWindow();
1184 }
1185 if (RT_SUCCESS(rc))
1186 hlpReportStatus(VBoxGuestFacilityStatus_Terminated);
1187 else
1188 {
1189 LogRel(("Error while starting, rc=%Rrc\n", rc));
1190 hlpReportStatus(VBoxGuestFacilityStatus_Failed);
1191 }
1192
1193 LogRel(("Ended\n"));
1194 VbglR3Term();
1195 }
1196 else
1197 LogRel(("VbglR3Init failed: %Rrc\n", rc));
1198 }
1199
1200 /* Release instance mutex. */
1201 if (hMutexAppRunning != NULL)
1202 {
1203 CloseHandle(hMutexAppRunning);
1204 hMutexAppRunning = NULL;
1205 }
1206
1207 vboxTrayLogDestroy();
1208
1209 return RT_SUCCESS(rc) ? 0 : 1;
1210}
1211
1212/**
1213 * Window procedure for our main tool window.
1214 */
1215static LRESULT CALLBACK vboxToolWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
1216{
1217 LogFlowFunc(("hWnd=%p, uMsg=%u\n", hWnd, uMsg));
1218
1219 switch (uMsg)
1220 {
1221 case WM_CREATE:
1222 {
1223 LogFunc(("Tool window created\n"));
1224
1225 int rc = vboxTrayRegisterGlobalMessages(&g_vboxGlobalMessageTable[0]);
1226 if (RT_FAILURE(rc))
1227 LogFunc(("Error registering global window messages, rc=%Rrc\n", rc));
1228 return 0;
1229 }
1230
1231 case WM_CLOSE:
1232 return 0;
1233
1234 case WM_DESTROY:
1235 {
1236 LogFunc(("Tool window destroyed\n"));
1237 KillTimer(g_hwndToolWindow, TIMERID_VBOXTRAY_CHECK_HOSTVERSION);
1238 return 0;
1239 }
1240
1241 case WM_TIMER:
1242 {
1243 if (VBoxCapsCheckTimer(wParam))
1244 return 0;
1245 if (vboxDtCheckTimer(wParam))
1246 return 0;
1247 if (vboxStCheckTimer(wParam))
1248 return 0;
1249
1250 switch (wParam)
1251 {
1252 case TIMERID_VBOXTRAY_CHECK_HOSTVERSION:
1253 if (RT_SUCCESS(VBoxCheckHostVersion()))
1254 {
1255 /* After successful run we don't need to check again. */
1256 KillTimer(g_hwndToolWindow, TIMERID_VBOXTRAY_CHECK_HOSTVERSION);
1257 }
1258 return 0;
1259
1260 default:
1261 break;
1262 }
1263
1264 break; /* Make sure other timers get processed the usual way! */
1265 }
1266
1267 case WM_VBOXTRAY_TRAY_ICON:
1268 {
1269 switch (LOWORD(lParam))
1270 {
1271 case WM_LBUTTONDBLCLK:
1272 break;
1273 case WM_RBUTTONDOWN:
1274 {
1275 if (!g_cVerbosity) /* Don't show menu when running in non-verbose mode. */
1276 break;
1277
1278 POINT lpCursor;
1279 if (GetCursorPos(&lpCursor))
1280 {
1281 HMENU hContextMenu = CreatePopupMenu();
1282 if (hContextMenu)
1283 {
1284 UINT_PTR uMenuItem = 9999;
1285 UINT fMenuItem = MF_BYPOSITION | MF_STRING;
1286 if (InsertMenuW(hContextMenu, UINT_MAX, fMenuItem, uMenuItem, L"Exit"))
1287 {
1288 SetForegroundWindow(hWnd);
1289
1290 const bool fBlockWhileTracking = true;
1291
1292 UINT fTrack = TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_BOTTOMALIGN;
1293
1294 if (fBlockWhileTracking)
1295 fTrack |= TPM_RETURNCMD | TPM_NONOTIFY;
1296
1297 uMsg = TrackPopupMenu(hContextMenu, fTrack, lpCursor.x, lpCursor.y, 0, hWnd, NULL);
1298 if ( uMsg
1299 && fBlockWhileTracking)
1300 {
1301 if (uMsg == uMenuItem)
1302 PostMessage(g_hwndToolWindow, WM_QUIT, 0, 0);
1303 }
1304 else if (!uMsg)
1305 LogFlowFunc(("Tracking popup menu failed with %ld\n", GetLastError()));
1306 }
1307
1308 DestroyMenu(hContextMenu);
1309 }
1310 }
1311 break;
1312 }
1313 }
1314 return 0;
1315 }
1316
1317 case WM_VBOX_SEAMLESS_ENABLE:
1318 {
1319 VBoxCapsEntryFuncStateSet(VBOXCAPS_ENTRY_IDX_SEAMLESS, VBOXCAPS_ENTRY_FUNCSTATE_STARTED);
1320 if (VBoxCapsEntryIsEnabled(VBOXCAPS_ENTRY_IDX_SEAMLESS))
1321 VBoxSeamlessCheckWindows(true);
1322 return 0;
1323 }
1324
1325 case WM_VBOX_SEAMLESS_DISABLE:
1326 {
1327 VBoxCapsEntryFuncStateSet(VBOXCAPS_ENTRY_IDX_SEAMLESS, VBOXCAPS_ENTRY_FUNCSTATE_SUPPORTED);
1328 return 0;
1329 }
1330
1331 case WM_DISPLAYCHANGE:
1332 ASMAtomicUoWriteU32(&g_fGuestDisplaysChanged, 1);
1333 // No break or return is intentional here.
1334 case WM_VBOX_SEAMLESS_UPDATE:
1335 {
1336 if (VBoxCapsEntryIsEnabled(VBOXCAPS_ENTRY_IDX_SEAMLESS))
1337 VBoxSeamlessCheckWindows(true);
1338 return 0;
1339 }
1340
1341 case WM_VBOX_GRAPHICS_SUPPORTED:
1342 {
1343 VBoxGrapicsSetSupported(TRUE);
1344 return 0;
1345 }
1346
1347 case WM_VBOX_GRAPHICS_UNSUPPORTED:
1348 {
1349 VBoxGrapicsSetSupported(FALSE);
1350 return 0;
1351 }
1352
1353 case WM_WTSSESSION_CHANGE:
1354 {
1355 BOOL fOldAllowedState = VBoxConsoleIsAllowed();
1356 if (vboxStHandleEvent(wParam))
1357 {
1358 if (!VBoxConsoleIsAllowed() != !fOldAllowedState)
1359 VBoxConsoleEnable(!fOldAllowedState);
1360 }
1361 return 0;
1362 }
1363
1364 default:
1365 {
1366 /* Handle all globally registered window messages. */
1367 if (vboxTrayHandleGlobalMessages(&g_vboxGlobalMessageTable[0], uMsg,
1368 wParam, lParam))
1369 {
1370 return 0; /* We handled the message. @todo Add return value!*/
1371 }
1372 break; /* We did not handle the message, dispatch to DefWndProc. */
1373 }
1374 }
1375
1376 /* Only if message was *not* handled by our switch above, dispatch to DefWindowProc. */
1377 return DefWindowProc(hWnd, uMsg, wParam, lParam);
1378}
1379
1380/* St (session [state] tracking) functionality API impl */
1381
1382typedef struct VBOXST
1383{
1384 HWND hWTSAPIWnd;
1385 RTLDRMOD hLdrModWTSAPI32;
1386 BOOL fIsConsole;
1387 WTS_CONNECTSTATE_CLASS enmConnectState;
1388 UINT_PTR idDelayedInitTimer;
1389 BOOL (WINAPI * pfnWTSRegisterSessionNotification)(HWND hWnd, DWORD dwFlags);
1390 BOOL (WINAPI * pfnWTSUnRegisterSessionNotification)(HWND hWnd);
1391 BOOL (WINAPI * pfnWTSQuerySessionInformationA)(HANDLE hServer, DWORD SessionId, WTS_INFO_CLASS WTSInfoClass, LPTSTR *ppBuffer, DWORD *pBytesReturned);
1392} VBOXST;
1393
1394static VBOXST gVBoxSt;
1395
1396static int vboxStCheckState()
1397{
1398 int rc = VINF_SUCCESS;
1399 WTS_CONNECTSTATE_CLASS *penmConnectState = NULL;
1400 USHORT *pProtocolType = NULL;
1401 DWORD cbBuf = 0;
1402 if (gVBoxSt.pfnWTSQuerySessionInformationA(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, WTSConnectState,
1403 (LPTSTR *)&penmConnectState, &cbBuf))
1404 {
1405 if (gVBoxSt.pfnWTSQuerySessionInformationA(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, WTSClientProtocolType,
1406 (LPTSTR *)&pProtocolType, &cbBuf))
1407 {
1408 gVBoxSt.fIsConsole = (*pProtocolType == 0);
1409 gVBoxSt.enmConnectState = *penmConnectState;
1410 return VINF_SUCCESS;
1411 }
1412
1413 DWORD dwErr = GetLastError();
1414 LogFlowFunc(("WTSQuerySessionInformationA WTSClientProtocolType failed, error = %08X\n", dwErr));
1415 rc = RTErrConvertFromWin32(dwErr);
1416 }
1417 else
1418 {
1419 DWORD dwErr = GetLastError();
1420 LogFlowFunc(("WTSQuerySessionInformationA WTSConnectState failed, error = %08X\n", dwErr));
1421 rc = RTErrConvertFromWin32(dwErr);
1422 }
1423
1424 /* failure branch, set to "console-active" state */
1425 gVBoxSt.fIsConsole = TRUE;
1426 gVBoxSt.enmConnectState = WTSActive;
1427
1428 return rc;
1429}
1430
1431static int vboxStInit(HWND hWnd)
1432{
1433 RT_ZERO(gVBoxSt);
1434 int rc = RTLdrLoadSystem("WTSAPI32.DLL", false /*fNoUnload*/, &gVBoxSt.hLdrModWTSAPI32);
1435 if (RT_SUCCESS(rc))
1436 {
1437 rc = RTLdrGetSymbol(gVBoxSt.hLdrModWTSAPI32, "WTSRegisterSessionNotification",
1438 (void **)&gVBoxSt.pfnWTSRegisterSessionNotification);
1439 if (RT_SUCCESS(rc))
1440 {
1441 rc = RTLdrGetSymbol(gVBoxSt.hLdrModWTSAPI32, "WTSUnRegisterSessionNotification",
1442 (void **)&gVBoxSt.pfnWTSUnRegisterSessionNotification);
1443 if (RT_SUCCESS(rc))
1444 {
1445 rc = RTLdrGetSymbol(gVBoxSt.hLdrModWTSAPI32, "WTSQuerySessionInformationA",
1446 (void **)&gVBoxSt.pfnWTSQuerySessionInformationA);
1447 if (RT_FAILURE(rc))
1448 LogFlowFunc(("WTSQuerySessionInformationA not found\n"));
1449 }
1450 else
1451 LogFlowFunc(("WTSUnRegisterSessionNotification not found\n"));
1452 }
1453 else
1454 LogFlowFunc(("WTSRegisterSessionNotification not found\n"));
1455 if (RT_SUCCESS(rc))
1456 {
1457 gVBoxSt.hWTSAPIWnd = hWnd;
1458 if (gVBoxSt.pfnWTSRegisterSessionNotification(gVBoxSt.hWTSAPIWnd, NOTIFY_FOR_THIS_SESSION))
1459 vboxStCheckState();
1460 else
1461 {
1462 DWORD dwErr = GetLastError();
1463 LogFlowFunc(("WTSRegisterSessionNotification failed, error = %08X\n", dwErr));
1464 if (dwErr == RPC_S_INVALID_BINDING)
1465 {
1466 gVBoxSt.idDelayedInitTimer = SetTimer(gVBoxSt.hWTSAPIWnd, TIMERID_VBOXTRAY_ST_DELAYED_INIT_TIMER,
1467 2000, (TIMERPROC)NULL);
1468 gVBoxSt.fIsConsole = TRUE;
1469 gVBoxSt.enmConnectState = WTSActive;
1470 rc = VINF_SUCCESS;
1471 }
1472 else
1473 rc = RTErrConvertFromWin32(dwErr);
1474 }
1475
1476 if (RT_SUCCESS(rc))
1477 return VINF_SUCCESS;
1478 }
1479
1480 RTLdrClose(gVBoxSt.hLdrModWTSAPI32);
1481 }
1482 else
1483 LogFlowFunc(("WTSAPI32 load failed, rc = %Rrc\n", rc));
1484
1485 RT_ZERO(gVBoxSt);
1486 gVBoxSt.fIsConsole = TRUE;
1487 gVBoxSt.enmConnectState = WTSActive;
1488 return rc;
1489}
1490
1491static void vboxStTerm(void)
1492{
1493 if (!gVBoxSt.hWTSAPIWnd)
1494 {
1495 LogFlowFunc(("vboxStTerm called for non-initialized St\n"));
1496 return;
1497 }
1498
1499 if (gVBoxSt.idDelayedInitTimer)
1500 {
1501 /* notification is not registered, just kill timer */
1502 KillTimer(gVBoxSt.hWTSAPIWnd, gVBoxSt.idDelayedInitTimer);
1503 gVBoxSt.idDelayedInitTimer = 0;
1504 }
1505 else
1506 {
1507 if (!gVBoxSt.pfnWTSUnRegisterSessionNotification(gVBoxSt.hWTSAPIWnd))
1508 {
1509 LogFlowFunc(("WTSAPI32 load failed, error = %08X\n", GetLastError()));
1510 }
1511 }
1512
1513 RTLdrClose(gVBoxSt.hLdrModWTSAPI32);
1514 RT_ZERO(gVBoxSt);
1515}
1516
1517#define VBOXST_DBG_MAKECASE(_val) case _val: return #_val;
1518
1519static const char* vboxStDbgGetString(DWORD val)
1520{
1521 switch (val)
1522 {
1523 VBOXST_DBG_MAKECASE(WTS_CONSOLE_CONNECT);
1524 VBOXST_DBG_MAKECASE(WTS_CONSOLE_DISCONNECT);
1525 VBOXST_DBG_MAKECASE(WTS_REMOTE_CONNECT);
1526 VBOXST_DBG_MAKECASE(WTS_REMOTE_DISCONNECT);
1527 VBOXST_DBG_MAKECASE(WTS_SESSION_LOGON);
1528 VBOXST_DBG_MAKECASE(WTS_SESSION_LOGOFF);
1529 VBOXST_DBG_MAKECASE(WTS_SESSION_LOCK);
1530 VBOXST_DBG_MAKECASE(WTS_SESSION_UNLOCK);
1531 VBOXST_DBG_MAKECASE(WTS_SESSION_REMOTE_CONTROL);
1532 default:
1533 LogFlowFunc(("invalid WTS state %d\n", val));
1534 return "Unknown";
1535 }
1536}
1537
1538static BOOL vboxStCheckTimer(WPARAM wEvent)
1539{
1540 if (wEvent != gVBoxSt.idDelayedInitTimer)
1541 return FALSE;
1542
1543 if (gVBoxSt.pfnWTSRegisterSessionNotification(gVBoxSt.hWTSAPIWnd, NOTIFY_FOR_THIS_SESSION))
1544 {
1545 KillTimer(gVBoxSt.hWTSAPIWnd, gVBoxSt.idDelayedInitTimer);
1546 gVBoxSt.idDelayedInitTimer = 0;
1547 vboxStCheckState();
1548 }
1549 else
1550 {
1551 LogFlowFunc(("timer WTSRegisterSessionNotification failed, error = %08X\n", GetLastError()));
1552 Assert(gVBoxSt.fIsConsole == TRUE);
1553 Assert(gVBoxSt.enmConnectState == WTSActive);
1554 }
1555
1556 return TRUE;
1557}
1558
1559
1560static BOOL vboxStHandleEvent(WPARAM wEvent)
1561{
1562 RT_NOREF(wEvent);
1563 LogFlowFunc(("WTS Event: %s\n", vboxStDbgGetString(wEvent)));
1564 BOOL fOldIsActiveConsole = vboxStIsActiveConsole();
1565
1566 vboxStCheckState();
1567
1568 return !vboxStIsActiveConsole() != !fOldIsActiveConsole;
1569}
1570
1571static BOOL vboxStIsActiveConsole(void)
1572{
1573 return (gVBoxSt.enmConnectState == WTSActive && gVBoxSt.fIsConsole);
1574}
1575
1576/*
1577 * Dt (desktop [state] tracking) functionality API impl
1578 *
1579 * !!!NOTE: this API is NOT thread-safe!!!
1580 * */
1581
1582typedef struct VBOXDT
1583{
1584 HANDLE hNotifyEvent;
1585 BOOL fIsInputDesktop;
1586 UINT_PTR idTimer;
1587 RTLDRMOD hLdrModHook;
1588 BOOL (* pfnVBoxHookInstallActiveDesktopTracker)(HMODULE hDll);
1589 BOOL (* pfnVBoxHookRemoveActiveDesktopTracker)();
1590 HDESK (WINAPI * pfnGetThreadDesktop)(DWORD dwThreadId);
1591 HDESK (WINAPI * pfnOpenInputDesktop)(DWORD dwFlags, BOOL fInherit, ACCESS_MASK dwDesiredAccess);
1592 BOOL (WINAPI * pfnCloseDesktop)(HDESK hDesktop);
1593} VBOXDT;
1594
1595static VBOXDT gVBoxDt;
1596
1597static BOOL vboxDtCalculateIsInputDesktop()
1598{
1599 BOOL fIsInputDt = FALSE;
1600 HDESK hInput = gVBoxDt.pfnOpenInputDesktop(0, FALSE, DESKTOP_CREATEWINDOW);
1601 if (hInput)
1602 {
1603// DWORD dwThreadId = GetCurrentThreadId();
1604// HDESK hThreadDt = gVBoxDt.pfnGetThreadDesktop(dwThreadId);
1605// if (hThreadDt)
1606// {
1607 fIsInputDt = TRUE;
1608// }
1609// else
1610// {
1611// DWORD dwErr = GetLastError();
1612// LogFlowFunc(("pfnGetThreadDesktop for Seamless failed, last error = %08X\n", dwErr));
1613// }
1614
1615 gVBoxDt.pfnCloseDesktop(hInput);
1616 }
1617 else
1618 {
1619// DWORD dwErr = GetLastError();
1620// LogFlowFunc(("pfnOpenInputDesktop for Seamless failed, last error = %08X\n", dwErr));
1621 }
1622 return fIsInputDt;
1623}
1624
1625static BOOL vboxDtCheckTimer(WPARAM wParam)
1626{
1627 if (wParam != gVBoxDt.idTimer)
1628 return FALSE;
1629
1630 VBoxTrayCheckDt();
1631
1632 return TRUE;
1633}
1634
1635static int vboxDtInit()
1636{
1637 RT_ZERO(gVBoxDt);
1638
1639 int rc;
1640 gVBoxDt.hNotifyEvent = CreateEvent(NULL, FALSE, FALSE, VBOXHOOK_GLOBAL_DT_EVENT_NAME);
1641 if (gVBoxDt.hNotifyEvent != NULL)
1642 {
1643 /* Load the hook dll and resolve the necessary entry points. */
1644 rc = RTLdrLoadAppPriv(VBOXHOOK_DLL_NAME, &gVBoxDt.hLdrModHook);
1645 if (RT_SUCCESS(rc))
1646 {
1647 rc = RTLdrGetSymbol(gVBoxDt.hLdrModHook, "VBoxHookInstallActiveDesktopTracker",
1648 (void **)&gVBoxDt.pfnVBoxHookInstallActiveDesktopTracker);
1649 if (RT_SUCCESS(rc))
1650 {
1651 rc = RTLdrGetSymbol(gVBoxDt.hLdrModHook, "VBoxHookRemoveActiveDesktopTracker",
1652 (void **)&gVBoxDt.pfnVBoxHookRemoveActiveDesktopTracker);
1653 if (RT_FAILURE(rc))
1654 LogFlowFunc(("VBoxHookRemoveActiveDesktopTracker not found\n"));
1655 }
1656 else
1657 LogFlowFunc(("VBoxHookInstallActiveDesktopTracker not found\n"));
1658 if (RT_SUCCESS(rc))
1659 {
1660 /* Try get the system APIs we need. */
1661 *(void **)&gVBoxDt.pfnGetThreadDesktop = RTLdrGetSystemSymbol("user32.dll", "GetThreadDesktop");
1662 if (!gVBoxDt.pfnGetThreadDesktop)
1663 {
1664 LogFlowFunc(("GetThreadDesktop not found\n"));
1665 rc = VERR_NOT_SUPPORTED;
1666 }
1667
1668 *(void **)&gVBoxDt.pfnOpenInputDesktop = RTLdrGetSystemSymbol("user32.dll", "OpenInputDesktop");
1669 if (!gVBoxDt.pfnOpenInputDesktop)
1670 {
1671 LogFlowFunc(("OpenInputDesktop not found\n"));
1672 rc = VERR_NOT_SUPPORTED;
1673 }
1674
1675 *(void **)&gVBoxDt.pfnCloseDesktop = RTLdrGetSystemSymbol("user32.dll", "CloseDesktop");
1676 if (!gVBoxDt.pfnCloseDesktop)
1677 {
1678 LogFlowFunc(("CloseDesktop not found\n"));
1679 rc = VERR_NOT_SUPPORTED;
1680 }
1681
1682 if (RT_SUCCESS(rc))
1683 {
1684 BOOL fRc = FALSE;
1685 /* For Vista and up we need to change the integrity of the security descriptor, too. */
1686 uint64_t const uNtVersion = RTSystemGetNtVersion();
1687 if (uNtVersion >= RTSYSTEM_MAKE_NT_VERSION(6, 0, 0))
1688 {
1689 HMODULE hModHook = (HMODULE)RTLdrGetNativeHandle(gVBoxDt.hLdrModHook);
1690 Assert((uintptr_t)hModHook != ~(uintptr_t)0);
1691 fRc = gVBoxDt.pfnVBoxHookInstallActiveDesktopTracker(hModHook);
1692 if (!fRc)
1693 LogFlowFunc(("pfnVBoxHookInstallActiveDesktopTracker failed, last error = %08X\n", GetLastError()));
1694 }
1695
1696 if (!fRc)
1697 {
1698 gVBoxDt.idTimer = SetTimer(g_hwndToolWindow, TIMERID_VBOXTRAY_DT_TIMER, 500, (TIMERPROC)NULL);
1699 if (!gVBoxDt.idTimer)
1700 {
1701 DWORD dwErr = GetLastError();
1702 LogFlowFunc(("SetTimer error %08X\n", dwErr));
1703 rc = RTErrConvertFromWin32(dwErr);
1704 }
1705 }
1706
1707 if (RT_SUCCESS(rc))
1708 {
1709 gVBoxDt.fIsInputDesktop = vboxDtCalculateIsInputDesktop();
1710 return VINF_SUCCESS;
1711 }
1712 }
1713 }
1714
1715 RTLdrClose(gVBoxDt.hLdrModHook);
1716 }
1717 else
1718 {
1719 DWORD dwErr = GetLastError();
1720 LogFlowFunc(("CreateEvent for Seamless failed, last error = %08X\n", dwErr));
1721 rc = RTErrConvertFromWin32(dwErr);
1722 }
1723
1724 CloseHandle(gVBoxDt.hNotifyEvent);
1725 }
1726 else
1727 {
1728 DWORD dwErr = GetLastError();
1729 LogFlowFunc(("CreateEvent for Seamless failed, last error = %08X\n", dwErr));
1730 rc = RTErrConvertFromWin32(dwErr);
1731 }
1732
1733
1734 RT_ZERO(gVBoxDt);
1735 gVBoxDt.fIsInputDesktop = TRUE;
1736
1737 return rc;
1738}
1739
1740static void vboxDtTerm()
1741{
1742 if (!gVBoxDt.hLdrModHook)
1743 return;
1744
1745 gVBoxDt.pfnVBoxHookRemoveActiveDesktopTracker();
1746
1747 RTLdrClose(gVBoxDt.hLdrModHook);
1748 CloseHandle(gVBoxDt.hNotifyEvent);
1749
1750 RT_ZERO(gVBoxDt);
1751}
1752/* @returns true on "IsInputDesktop" state change */
1753static BOOL vboxDtHandleEvent()
1754{
1755 BOOL fIsInputDesktop = gVBoxDt.fIsInputDesktop;
1756 gVBoxDt.fIsInputDesktop = vboxDtCalculateIsInputDesktop();
1757 return !fIsInputDesktop != !gVBoxDt.fIsInputDesktop;
1758}
1759
1760static HANDLE vboxDtGetNotifyEvent()
1761{
1762 return gVBoxDt.hNotifyEvent;
1763}
1764
1765/* @returns true iff the application (VBoxTray) desktop is input */
1766static BOOL vboxDtIsInputDesktop()
1767{
1768 return gVBoxDt.fIsInputDesktop;
1769}
1770
1771/* we need to perform Acquire/Release using the file handled we use for rewuesting events from VBoxGuest
1772 * otherwise Acquisition mechanism will treat us as different client and will not propagate necessary requests
1773 * */
1774static int VBoxAcquireGuestCaps(uint32_t fOr, uint32_t fNot, bool fCfg)
1775{
1776 Log(("VBoxAcquireGuestCaps or(0x%x), not(0x%x), cfx(%d)\n", fOr, fNot, fCfg));
1777 int rc = VbglR3AcquireGuestCaps(fOr, fNot, fCfg);
1778 if (RT_FAILURE(rc))
1779 LogFlowFunc(("VBOXGUEST_IOCTL_GUEST_CAPS_ACQUIRE failed: %Rrc\n", rc));
1780 return rc;
1781}
1782
1783typedef enum VBOXCAPS_ENTRY_ACSTATE
1784{
1785 /* the given cap is released */
1786 VBOXCAPS_ENTRY_ACSTATE_RELEASED = 0,
1787 /* the given cap acquisition is in progress */
1788 VBOXCAPS_ENTRY_ACSTATE_ACQUIRING,
1789 /* the given cap is acquired */
1790 VBOXCAPS_ENTRY_ACSTATE_ACQUIRED
1791} VBOXCAPS_ENTRY_ACSTATE;
1792
1793
1794struct VBOXCAPS_ENTRY;
1795struct VBOXCAPS;
1796
1797typedef DECLCALLBACKPTR(void, PFNVBOXCAPS_ENTRY_ON_ENABLE,(struct VBOXCAPS *pConsole, struct VBOXCAPS_ENTRY *pCap, BOOL fEnabled));
1798
1799typedef struct VBOXCAPS_ENTRY
1800{
1801 uint32_t fCap;
1802 uint32_t iCap;
1803 VBOXCAPS_ENTRY_FUNCSTATE enmFuncState;
1804 VBOXCAPS_ENTRY_ACSTATE enmAcState;
1805 PFNVBOXCAPS_ENTRY_ON_ENABLE pfnOnEnable;
1806} VBOXCAPS_ENTRY;
1807
1808
1809typedef struct VBOXCAPS
1810{
1811 UINT_PTR idTimer;
1812 VBOXCAPS_ENTRY aCaps[VBOXCAPS_ENTRY_IDX_COUNT];
1813} VBOXCAPS;
1814
1815static VBOXCAPS gVBoxCaps;
1816
1817static DECLCALLBACK(void) vboxCapsOnEnableSeamless(struct VBOXCAPS *pConsole, struct VBOXCAPS_ENTRY *pCap, BOOL fEnabled)
1818{
1819 RT_NOREF(pConsole, pCap);
1820 if (fEnabled)
1821 {
1822 Log(("vboxCapsOnEnableSeamless: ENABLED\n"));
1823 Assert(pCap->enmAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED);
1824 Assert(pCap->enmFuncState == VBOXCAPS_ENTRY_FUNCSTATE_STARTED);
1825 VBoxSeamlessEnable();
1826 }
1827 else
1828 {
1829 Log(("vboxCapsOnEnableSeamless: DISABLED\n"));
1830 Assert(pCap->enmAcState != VBOXCAPS_ENTRY_ACSTATE_ACQUIRED || pCap->enmFuncState != VBOXCAPS_ENTRY_FUNCSTATE_STARTED);
1831 VBoxSeamlessDisable();
1832 }
1833}
1834
1835static void vboxCapsEntryAcStateSet(VBOXCAPS_ENTRY *pCap, VBOXCAPS_ENTRY_ACSTATE enmAcState)
1836{
1837 VBOXCAPS *pConsole = &gVBoxCaps;
1838
1839 Log(("vboxCapsEntryAcStateSet: new state enmAcState(%d); pCap: fCap(%d), iCap(%d), enmFuncState(%d), enmAcState(%d)\n",
1840 enmAcState, pCap->fCap, pCap->iCap, pCap->enmFuncState, pCap->enmAcState));
1841
1842 if (pCap->enmAcState == enmAcState)
1843 return;
1844
1845 VBOXCAPS_ENTRY_ACSTATE enmOldAcState = pCap->enmAcState;
1846 pCap->enmAcState = enmAcState;
1847
1848 if (enmAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED)
1849 {
1850 if (pCap->enmFuncState == VBOXCAPS_ENTRY_FUNCSTATE_STARTED)
1851 {
1852 if (pCap->pfnOnEnable)
1853 pCap->pfnOnEnable(pConsole, pCap, TRUE);
1854 }
1855 }
1856 else if (enmOldAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED && pCap->enmFuncState == VBOXCAPS_ENTRY_FUNCSTATE_STARTED)
1857 {
1858 if (pCap->pfnOnEnable)
1859 pCap->pfnOnEnable(pConsole, pCap, FALSE);
1860 }
1861}
1862
1863static void vboxCapsEntryFuncStateSet(VBOXCAPS_ENTRY *pCap, VBOXCAPS_ENTRY_FUNCSTATE enmFuncState)
1864{
1865 VBOXCAPS *pConsole = &gVBoxCaps;
1866
1867 Log(("vboxCapsEntryFuncStateSet: new state enmAcState(%d); pCap: fCap(%d), iCap(%d), enmFuncState(%d), enmAcState(%d)\n",
1868 enmFuncState, pCap->fCap, pCap->iCap, pCap->enmFuncState, pCap->enmAcState));
1869
1870 if (pCap->enmFuncState == enmFuncState)
1871 return;
1872
1873 VBOXCAPS_ENTRY_FUNCSTATE enmOldFuncState = pCap->enmFuncState;
1874
1875 pCap->enmFuncState = enmFuncState;
1876
1877 if (enmFuncState == VBOXCAPS_ENTRY_FUNCSTATE_STARTED)
1878 {
1879 Assert(enmOldFuncState == VBOXCAPS_ENTRY_FUNCSTATE_SUPPORTED);
1880 if (pCap->enmAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED)
1881 {
1882 if (pCap->pfnOnEnable)
1883 pCap->pfnOnEnable(pConsole, pCap, TRUE);
1884 }
1885 }
1886 else if (pCap->enmAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED && enmOldFuncState == VBOXCAPS_ENTRY_FUNCSTATE_STARTED)
1887 {
1888 if (pCap->pfnOnEnable)
1889 pCap->pfnOnEnable(pConsole, pCap, FALSE);
1890 }
1891}
1892
1893static void VBoxCapsEntryFuncStateSet(uint32_t iCup, VBOXCAPS_ENTRY_FUNCSTATE enmFuncState)
1894{
1895 VBOXCAPS *pConsole = &gVBoxCaps;
1896 VBOXCAPS_ENTRY *pCap = &pConsole->aCaps[iCup];
1897 vboxCapsEntryFuncStateSet(pCap, enmFuncState);
1898}
1899
1900static int VBoxCapsInit()
1901{
1902 VBOXCAPS *pConsole = &gVBoxCaps;
1903 memset(pConsole, 0, sizeof (*pConsole));
1904 pConsole->aCaps[VBOXCAPS_ENTRY_IDX_SEAMLESS].fCap = VMMDEV_GUEST_SUPPORTS_SEAMLESS;
1905 pConsole->aCaps[VBOXCAPS_ENTRY_IDX_SEAMLESS].iCap = VBOXCAPS_ENTRY_IDX_SEAMLESS;
1906 pConsole->aCaps[VBOXCAPS_ENTRY_IDX_SEAMLESS].pfnOnEnable = vboxCapsOnEnableSeamless;
1907 pConsole->aCaps[VBOXCAPS_ENTRY_IDX_GRAPHICS].fCap = VMMDEV_GUEST_SUPPORTS_GRAPHICS;
1908 pConsole->aCaps[VBOXCAPS_ENTRY_IDX_GRAPHICS].iCap = VBOXCAPS_ENTRY_IDX_GRAPHICS;
1909 return VINF_SUCCESS;
1910}
1911
1912static int VBoxCapsReleaseAll()
1913{
1914 VBOXCAPS *pConsole = &gVBoxCaps;
1915 Log(("VBoxCapsReleaseAll\n"));
1916 int rc = VBoxAcquireGuestCaps(0, VMMDEV_GUEST_SUPPORTS_SEAMLESS | VMMDEV_GUEST_SUPPORTS_GRAPHICS, false);
1917 if (!RT_SUCCESS(rc))
1918 {
1919 LogFlowFunc(("vboxCapsEntryReleaseAll VBoxAcquireGuestCaps failed rc %d\n", rc));
1920 return rc;
1921 }
1922
1923 if (pConsole->idTimer)
1924 {
1925 Log(("killing console timer\n"));
1926 KillTimer(g_hwndToolWindow, pConsole->idTimer);
1927 pConsole->idTimer = 0;
1928 }
1929
1930 for (int i = 0; i < RT_ELEMENTS(pConsole->aCaps); ++i)
1931 {
1932 vboxCapsEntryAcStateSet(&pConsole->aCaps[i], VBOXCAPS_ENTRY_ACSTATE_RELEASED);
1933 }
1934
1935 return rc;
1936}
1937
1938static void VBoxCapsTerm()
1939{
1940 VBOXCAPS *pConsole = &gVBoxCaps;
1941 VBoxCapsReleaseAll();
1942 memset(pConsole, 0, sizeof (*pConsole));
1943}
1944
1945static BOOL VBoxCapsEntryIsAcquired(uint32_t iCap)
1946{
1947 VBOXCAPS *pConsole = &gVBoxCaps;
1948 return pConsole->aCaps[iCap].enmAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED;
1949}
1950
1951static BOOL VBoxCapsEntryIsEnabled(uint32_t iCap)
1952{
1953 VBOXCAPS *pConsole = &gVBoxCaps;
1954 return pConsole->aCaps[iCap].enmAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED
1955 && pConsole->aCaps[iCap].enmFuncState == VBOXCAPS_ENTRY_FUNCSTATE_STARTED;
1956}
1957
1958static BOOL VBoxCapsCheckTimer(WPARAM wParam)
1959{
1960 VBOXCAPS *pConsole = &gVBoxCaps;
1961 if (wParam != pConsole->idTimer)
1962 return FALSE;
1963
1964 uint32_t u32AcquiredCaps = 0;
1965 BOOL fNeedNewTimer = FALSE;
1966
1967 for (int i = 0; i < RT_ELEMENTS(pConsole->aCaps); ++i)
1968 {
1969 VBOXCAPS_ENTRY *pCap = &pConsole->aCaps[i];
1970 if (pCap->enmAcState != VBOXCAPS_ENTRY_ACSTATE_ACQUIRING)
1971 continue;
1972
1973 int rc = VBoxAcquireGuestCaps(pCap->fCap, 0, false);
1974 if (RT_SUCCESS(rc))
1975 {
1976 vboxCapsEntryAcStateSet(&pConsole->aCaps[i], VBOXCAPS_ENTRY_ACSTATE_ACQUIRED);
1977 u32AcquiredCaps |= pCap->fCap;
1978 }
1979 else
1980 {
1981 Assert(rc == VERR_RESOURCE_BUSY);
1982 fNeedNewTimer = TRUE;
1983 }
1984 }
1985
1986 if (!fNeedNewTimer)
1987 {
1988 KillTimer(g_hwndToolWindow, pConsole->idTimer);
1989 /* cleanup timer data */
1990 pConsole->idTimer = 0;
1991 }
1992
1993 return TRUE;
1994}
1995
1996static int VBoxCapsEntryRelease(uint32_t iCap)
1997{
1998 VBOXCAPS *pConsole = &gVBoxCaps;
1999 VBOXCAPS_ENTRY *pCap = &pConsole->aCaps[iCap];
2000 if (pCap->enmAcState == VBOXCAPS_ENTRY_ACSTATE_RELEASED)
2001 {
2002 LogFlowFunc(("invalid cap[%d] state[%d] on release\n", iCap, pCap->enmAcState));
2003 return VERR_INVALID_STATE;
2004 }
2005
2006 if (pCap->enmAcState == VBOXCAPS_ENTRY_ACSTATE_ACQUIRED)
2007 {
2008 int rc = VBoxAcquireGuestCaps(0, pCap->fCap, false);
2009 AssertRC(rc);
2010 }
2011
2012 vboxCapsEntryAcStateSet(pCap, VBOXCAPS_ENTRY_ACSTATE_RELEASED);
2013
2014 return VINF_SUCCESS;
2015}
2016
2017static int VBoxCapsEntryAcquire(uint32_t iCap)
2018{
2019 VBOXCAPS *pConsole = &gVBoxCaps;
2020 Assert(VBoxConsoleIsAllowed());
2021 VBOXCAPS_ENTRY *pCap = &pConsole->aCaps[iCap];
2022 Log(("VBoxCapsEntryAcquire %d\n", iCap));
2023 if (pCap->enmAcState != VBOXCAPS_ENTRY_ACSTATE_RELEASED)
2024 {
2025 LogFlowFunc(("invalid cap[%d] state[%d] on acquire\n", iCap, pCap->enmAcState));
2026 return VERR_INVALID_STATE;
2027 }
2028
2029 vboxCapsEntryAcStateSet(pCap, VBOXCAPS_ENTRY_ACSTATE_ACQUIRING);
2030 int rc = VBoxAcquireGuestCaps(pCap->fCap, 0, false);
2031 if (RT_SUCCESS(rc))
2032 {
2033 vboxCapsEntryAcStateSet(pCap, VBOXCAPS_ENTRY_ACSTATE_ACQUIRED);
2034 return VINF_SUCCESS;
2035 }
2036
2037 if (rc != VERR_RESOURCE_BUSY)
2038 {
2039 LogFlowFunc(("vboxCapsEntryReleaseAll VBoxAcquireGuestCaps failed rc %d\n", rc));
2040 return rc;
2041 }
2042
2043 LogFlowFunc(("iCap %d is busy!\n", iCap));
2044
2045 /* the cap was busy, most likely it is still used by other VBoxTray instance running in another session,
2046 * queue the retry timer */
2047 if (!pConsole->idTimer)
2048 {
2049 pConsole->idTimer = SetTimer(g_hwndToolWindow, TIMERID_VBOXTRAY_CAPS_TIMER, 100, (TIMERPROC)NULL);
2050 if (!pConsole->idTimer)
2051 {
2052 DWORD dwErr = GetLastError();
2053 LogFlowFunc(("SetTimer error %08X\n", dwErr));
2054 return RTErrConvertFromWin32(dwErr);
2055 }
2056 }
2057
2058 return rc;
2059}
2060
2061static int VBoxCapsAcquireAllSupported()
2062{
2063 VBOXCAPS *pConsole = &gVBoxCaps;
2064 Log(("VBoxCapsAcquireAllSupported\n"));
2065 for (int i = 0; i < RT_ELEMENTS(pConsole->aCaps); ++i)
2066 {
2067 if (pConsole->aCaps[i].enmFuncState >= VBOXCAPS_ENTRY_FUNCSTATE_SUPPORTED)
2068 {
2069 Log(("VBoxCapsAcquireAllSupported acquiring cap %d, state %d\n", i, pConsole->aCaps[i].enmFuncState));
2070 VBoxCapsEntryAcquire(i);
2071 }
2072 else
2073 {
2074 LogFlowFunc(("VBoxCapsAcquireAllSupported: WARN: cap %d not supported, state %d\n", i, pConsole->aCaps[i].enmFuncState));
2075 }
2076 }
2077 return VINF_SUCCESS;
2078}
2079
2080static BOOL VBoxConsoleIsAllowed()
2081{
2082 return vboxDtIsInputDesktop() && vboxStIsActiveConsole();
2083}
2084
2085static void VBoxConsoleEnable(BOOL fEnable)
2086{
2087 if (fEnable)
2088 VBoxCapsAcquireAllSupported();
2089 else
2090 VBoxCapsReleaseAll();
2091}
2092
2093static void VBoxConsoleCapSetSupported(uint32_t iCap, BOOL fSupported)
2094{
2095 if (fSupported)
2096 {
2097 VBoxCapsEntryFuncStateSet(iCap, VBOXCAPS_ENTRY_FUNCSTATE_SUPPORTED);
2098
2099 if (VBoxConsoleIsAllowed())
2100 VBoxCapsEntryAcquire(iCap);
2101 }
2102 else
2103 {
2104 VBoxCapsEntryFuncStateSet(iCap, VBOXCAPS_ENTRY_FUNCSTATE_UNSUPPORTED);
2105
2106 VBoxCapsEntryRelease(iCap);
2107 }
2108}
2109
2110void VBoxSeamlessSetSupported(BOOL fSupported)
2111{
2112 VBoxConsoleCapSetSupported(VBOXCAPS_ENTRY_IDX_SEAMLESS, fSupported);
2113}
2114
2115static void VBoxGrapicsSetSupported(BOOL fSupported)
2116{
2117 VBoxConsoleCapSetSupported(VBOXCAPS_ENTRY_IDX_GRAPHICS, fSupported);
2118}
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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