VirtualBox

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

Last change on this file since 95877 was 95877, checked in by vboxsync, 2 years ago

VBoxTray/VBoxTray.cpp: Resolved @todo in r152588. Now also using WinMain only as a stub, so that the code requires less IPRT_NO_CRT defines. bugref:10261

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

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