VirtualBox

source: vbox/trunk/src/VBox/Main/src-global/win/VBoxSDS.cpp@ 76067

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

VBoxSDS,VBoxSVC,VBoxProxyStub: Kicked out the failed attempt at centralized client watching. bugref:3300

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 34.5 KB
 
1/* $Id: VBoxSDS.cpp 76067 2018-12-08 00:54:36Z vboxsync $ */
2/** @file
3 * VBoxSDS - COM global service main entry (System Directory Service)
4 */
5
6/*
7 * Copyright (C) 2017-2018 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/** @page pg_VBoxSDS VBoxSDS - Per user CLSID_VirtualBox coordinater
20 *
21 * VBoxSDS is short for VirtualBox System Directory Service (SDS). Its purpose
22 * is to make sure there is only one CLSID_VirtualBox object running for each
23 * user using VirtualBox on a Windows host system.
24 *
25 *
26 * @section sec_vboxsds_backgroud Background
27 *
28 * COM is desktop oriented when it comes to activate-as-activator (AAA) COM
29 * servers. This means that if the users has two logins to the same box (e.g.
30 * physical console, RDP, SSHD) and tries to use an AAA COM server, a new server
31 * will be instantiated for each login. With the introduction of User Account
32 * Control (UAC) in Windows Vista, this was taken a step further and a user
33 * would talk different AAA COM server instances depending on the elevation
34 * level too.
35 *
36 * VBoxSVC is a service affected by this issue. Using VirtualBox across logins
37 * or between user elevation levels was impossible to do simultaneously. This
38 * was confusing and illogical to the user.
39 *
40 *
41 * @section sec_vboxsds_how How it works
42 *
43 * VBoxSDS assists in working around this problem by tracking which VBoxSVC
44 * server is currently providing CLSID_VirtualBox for a user. Each VBoxSVC
45 * instance will register itself with VBoxSDS when the CLSID_VirtualBox object
46 * is requested via their class factory. The first VBoxSVC registering for a
47 * given user will be allowed to instantate CLSID_VirtualBox. We will call this
48 * the chosen one. Subsequent VBoxSVC instance for the given user, regardless
49 * of elevation, session, windows station, or whatever else, will be told to use
50 * the instance from the first VBoxSVC.
51 *
52 * The registration call passes along an IVBoxSVCRegistration interface from
53 * VBoxSVC. VBoxSDS keeps this around for the chosen one only. When other
54 * VBoxSVC instances for the same user tries to register, VBoxSDS will ask the
55 * choosen one for its CLSID_VirtualBox object and return it to the new
56 * registrant.
57 *
58 * The chosen one will deregister with VBoxSDS before it terminates. Should it
59 * terminate abnormally, VBoxSDS will (probably) notice the next time it tries
60 * to request CLSID_VirtualBox from it and replace it as the chosen one with the
61 * new registrant.
62 *
63 *
64 * @section sec_vboxsds_locking Locking
65 *
66 * VBoxSDS stores data in a map indexed by the stringified secure identifier
67 * (SID) for each user. The map is protected by a shared critical section, so
68 * only inserting new users requires exclusive access.
69 *
70 * Each user data entry has it own lock (regular, not shared), so that it won't
71 * be necessary to hold down the map lock while accessing per user data. Thus
72 * preventing a user from blocking all others from using VirtualBox by
73 * suspending or debugging their chosen VBoxSVC process.
74 *
75 */
76
77
78/*********************************************************************************************************************************
79* Header Files *
80*********************************************************************************************************************************/
81#include <iprt/win/windows.h>
82#include <iprt/win/shlobj.h>
83
84#include "VBox/com/defs.h"
85#include "VBox/com/com.h"
86#include "VBox/com/VirtualBox.h"
87
88#include "VirtualBoxSDSImpl.h"
89#include "Logging.h"
90
91#include <VBox/err.h>
92#include <iprt/asm.h>
93#include <iprt/buildconfig.h>
94#include <iprt/dir.h>
95#include <iprt/env.h>
96#include <iprt/getopt.h>
97#include <iprt/initterm.h>
98#include <iprt/path.h>
99#include <iprt/message.h>
100#include <iprt/string.h>
101
102#include <VBox/com/microatl.h>
103
104#define _ATL_FREE_THREADED /** @todo r=bird: WTF? */
105
106/**
107 * Implements Windows Service
108 */
109class ATL_NO_VTABLE CWindowsServiceModule
110{
111protected:
112 // data members
113 WCHAR m_wszServiceName[256];
114 WCHAR m_wszServiceDisplayName[256];
115 WCHAR m_wszServiceDescription[256];
116 SERVICE_STATUS_HANDLE m_hServiceStatus;
117 SERVICE_STATUS m_Status;
118 DWORD m_dwThreadID;
119
120 /** Pointer to the instance, for use by staticServiceMain and staticHandler. */
121 static CWindowsServiceModule *s_pInstance;
122
123public:
124 CWindowsServiceModule() throw()
125 {
126 // set up the initial service status
127 m_hServiceStatus = NULL;
128 m_Status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
129 m_Status.dwCurrentState = SERVICE_STOPPED;
130 m_Status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
131 m_Status.dwWin32ExitCode = 0;
132 m_Status.dwServiceSpecificExitCode = 0;
133 m_Status.dwCheckPoint = 0;
134 m_Status.dwWaitHint = 3000;
135
136 s_pInstance = this;
137 }
138
139 virtual ~CWindowsServiceModule()
140 {
141 s_pInstance = NULL;
142 }
143
144 HRESULT startService(int /*nShowCmd*/) throw()
145 {
146 SERVICE_TABLE_ENTRY aServiceTable[] =
147 {
148 { m_wszServiceName, staticServiceMain },
149 { NULL, NULL }
150 };
151
152 if (::StartServiceCtrlDispatcher(aServiceTable) == 0)
153 {
154 m_Status.dwWin32ExitCode = ::GetLastError();
155 LogRelFunc(("Error: Cannot start service in console mode. Code: %u\n", m_Status.dwWin32ExitCode));
156 }
157
158 return m_Status.dwWin32ExitCode;
159 }
160
161 virtual HRESULT registerService() throw()
162 {
163 HRESULT hrc;
164 if (uninstallService())
165 {
166 hrc = onRegisterService();
167 if (SUCCEEDED(hrc))
168 {
169 if (installService())
170 hrc = S_OK;
171 else
172 hrc = E_FAIL;
173 }
174 }
175 else
176 hrc = E_FAIL;
177 return hrc;
178 }
179
180 virtual HRESULT unregisterService() throw()
181 {
182 HRESULT hrc = E_FAIL;
183 if (uninstallService())
184 hrc = onUnregisterService();
185 return hrc;
186 }
187
188private:
189 void serviceMain(DWORD, LPTSTR *) throw()
190 {
191 LogFunc(("Enter into serviceMain\n"));
192 // Register the control request handler
193 m_Status.dwCurrentState = SERVICE_START_PENDING;
194 m_dwThreadID = ::GetCurrentThreadId();
195 m_hServiceStatus = ::RegisterServiceCtrlHandler(m_wszServiceName, staticHandler);
196 if (m_hServiceStatus == NULL)
197 {
198 LogWarnFunc(("Handler not installed\n"));
199 return;
200 }
201 setServiceStatus(SERVICE_START_PENDING);
202
203 m_Status.dwWin32ExitCode = S_OK;
204 m_Status.dwCheckPoint = 0;
205 m_Status.dwWaitHint = 0;
206
207 // When the Run function returns, the service has stopped.
208 m_Status.dwWin32ExitCode = runService(SW_HIDE);
209
210 setServiceStatus(SERVICE_STOPPED);
211 LogFunc(("Windows Service stopped\n"));
212 }
213
214 /** Service table callback. */
215 static void WINAPI staticServiceMain(DWORD cArgs, LPTSTR *papwszArgs) throw()
216 {
217 AssertPtrReturnVoid(s_pInstance);
218 s_pInstance->serviceMain(cArgs, papwszArgs);
219 }
220
221 HRESULT runService(int nShowCmd = SW_HIDE) throw()
222 {
223 HRESULT hr = preMessageLoop(nShowCmd);
224
225 if (hr == S_OK)
226 runMessageLoop();
227
228 if (SUCCEEDED(hr))
229 hr = postMessageLoop();
230
231 return hr;
232 }
233
234protected:
235 /** Hook that's called before the message loop starts.
236 * Must return S_OK for it to start. */
237 virtual HRESULT preMessageLoop(int /*nShowCmd*/) throw()
238 {
239 LogFunc(("Enter\n"));
240 if (::InterlockedCompareExchange(&m_Status.dwCurrentState, SERVICE_RUNNING, SERVICE_START_PENDING) == SERVICE_START_PENDING)
241 {
242 LogFunc(("VBoxSDS Service started/resumed without delay\n"));
243 ::SetServiceStatus(m_hServiceStatus, &m_Status);
244 }
245 return S_OK;
246 }
247
248 /** Your typical windows message loop. */
249 virtual void runMessageLoop()
250 {
251 MSG msg;
252 while (::GetMessage(&msg, 0, 0, 0) > 0)
253 {
254 ::TranslateMessage(&msg);
255 ::DispatchMessage(&msg);
256 }
257 }
258
259 /** Hook that's called after the message loop ends. */
260 virtual HRESULT postMessageLoop()
261 {
262 return S_OK;
263 }
264
265 /** @name Overridable status change handlers
266 * @{ */
267 virtual void onStop() throw()
268 {
269 setServiceStatus(SERVICE_STOP_PENDING);
270 ::PostThreadMessage(m_dwThreadID, WM_QUIT, 0, 0);
271 LogFunc(("Windows Service stopped\n"));
272 }
273
274 virtual void onPause() throw()
275 {
276 }
277
278 virtual void onContinue() throw()
279 {
280 }
281
282 virtual void onInterrogate() throw()
283 {
284 }
285
286 virtual void onShutdown() throw()
287 {
288 }
289
290 virtual void onUnknownRequest(DWORD dwOpcode) throw()
291 {
292 LogRelFunc(("Bad service request: %u (%#x)\n", dwOpcode, dwOpcode));
293 }
294
295 virtual HRESULT onRegisterService()
296 {
297 return S_OK;
298 }
299
300 virtual HRESULT onUnregisterService()
301 {
302 return S_OK;
303 }
304 /** @} */
305
306private:
307 void handler(DWORD dwOpcode) throw()
308 {
309
310 switch (dwOpcode)
311 {
312 case SERVICE_CONTROL_STOP:
313 onStop();
314 break;
315 case SERVICE_CONTROL_PAUSE:
316 onPause();
317 break;
318 case SERVICE_CONTROL_CONTINUE:
319 onContinue();
320 break;
321 case SERVICE_CONTROL_INTERROGATE:
322 onInterrogate();
323 break;
324 case SERVICE_CONTROL_SHUTDOWN:
325 onShutdown();
326 break;
327 default:
328 onUnknownRequest(dwOpcode);
329 }
330 }
331
332 static void WINAPI staticHandler(DWORD dwOpcode) throw()
333 {
334 AssertPtrReturnVoid(s_pInstance);
335 s_pInstance->handler(dwOpcode);
336 }
337
338protected:
339 void setServiceStatus(DWORD dwState) throw()
340 {
341 uint32_t const uPrevState = ASMAtomicXchgU32((uint32_t volatile *)&m_Status.dwCurrentState, dwState);
342 if (!::SetServiceStatus(m_hServiceStatus, &m_Status))
343 LogRel(("Error: SetServiceStatus(%p, %u) failed: %u (uPrevState=%u)\n",
344 m_hServiceStatus, dwState, GetLastError(), uPrevState));
345 }
346
347
348public:
349 /** @note unused */
350 BOOL IsInstalled() throw()
351 {
352 BOOL fResult = FALSE;
353
354 SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
355 if (hSCM != NULL)
356 {
357 SC_HANDLE hService = ::OpenService(hSCM, m_wszServiceName, SERVICE_QUERY_CONFIG);
358 if (hService != NULL)
359 {
360 fResult = TRUE;
361 ::CloseServiceHandle(hService);
362 }
363 ::CloseServiceHandle(hSCM);
364 }
365
366 return fResult;
367 }
368
369 BOOL installService() throw()
370 {
371 BOOL fResult = FALSE;
372 SC_HANDLE hSCM = ::OpenSCManagerW(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
373 if (hSCM != NULL)
374 {
375 SC_HANDLE hService = ::OpenService(hSCM, m_wszServiceName, SERVICE_QUERY_CONFIG);
376 if (hService != NULL)
377 {
378 fResult = TRUE; /* Already installed. */
379
380 ::CloseServiceHandle(hService);
381 }
382 else
383 {
384 // Get the executable file path and quote it.
385 const int QUOTES_SPACE = 2;
386 WCHAR wszFilePath[MAX_PATH + QUOTES_SPACE];
387 DWORD cwcFilePath = ::GetModuleFileNameW(NULL, wszFilePath + 1, MAX_PATH);
388 if (cwcFilePath != 0 && cwcFilePath < MAX_PATH)
389 {
390 wszFilePath[0] = L'\"';
391 wszFilePath[cwcFilePath + 1] = L'\"';
392 wszFilePath[cwcFilePath + 2] = L'\0';
393
394 SC_HANDLE hService = ::CreateServiceW(hSCM, m_wszServiceName, m_wszServiceDisplayName,
395 SERVICE_CHANGE_CONFIG,
396 SERVICE_WIN32_OWN_PROCESS,
397 SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL,
398 wszFilePath, NULL, NULL, L"RPCSS\0", NULL, NULL);
399 if (hService != NULL)
400 {
401 SERVICE_DESCRIPTIONW sd;
402 sd.lpDescription = m_wszServiceDescription;
403 if (!::ChangeServiceConfig2W(hService, SERVICE_CONFIG_DESCRIPTION, &sd))
404 AssertLogRelMsgFailed(("Error: could not set service description: %u\n", GetLastError()));
405
406 fResult = TRUE;
407
408 ::CloseServiceHandle(hService);
409 }
410 else
411 AssertLogRelMsgFailed(("Error: Could not create service '%ls': %u\n", m_wszServiceName, GetLastError()));
412 }
413 else
414 AssertLogRelMsgFailed(("Error: GetModuleFileNameW returned %u: %u\n", cwcFilePath, GetLastError()));
415 }
416 }
417 else
418 AssertLogRelMsgFailed(("Error: Could not open the service control manager: %u\n", GetLastError()));
419 return fResult;
420 }
421
422 BOOL uninstallService() throw()
423 {
424 BOOL fResult = FALSE;
425 SC_HANDLE hSCM = ::OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
426 if (hSCM != NULL)
427 {
428 SC_HANDLE hService = ::OpenService(hSCM, m_wszServiceName, SERVICE_STOP | DELETE);
429 if (hService == NULL)
430 {
431 DWORD dwErr = GetLastError();
432 hService = ::OpenService(hSCM, m_wszServiceName, SERVICE_QUERY_CONFIG);
433 if (hService == NULL)
434 fResult = TRUE; /* Probably not installed or some access problem. */
435 else
436 {
437 ::CloseServiceHandle(hService);
438 AssertLogRelMsgFailed(("Error: Failed to open '%ls' for stopping and deletion: %u\n", m_wszServiceName, dwErr));
439 }
440 }
441 else
442 {
443 /* Try stop it. */
444 SERVICE_STATUS status;
445 RT_ZERO(status);
446 if (!::ControlService(hService, SERVICE_CONTROL_STOP, &status))
447 {
448 DWORD dwErr = GetLastError();
449 AssertLogRelMsg( dwErr == ERROR_SERVICE_NOT_ACTIVE
450 || ( dwErr == ERROR_SERVICE_CANNOT_ACCEPT_CTRL
451 && status.dwCurrentState == SERVICE_STOP_PENDING)
452 , ("Error: Failed to stop serive '%ls': dwErr=%u dwCurrentState=%u\n",
453 m_wszServiceName, dwErr, status.dwCurrentState));
454 }
455
456 /* Try delete it. */
457 fResult = ::DeleteService(hService);
458 AssertLogRelMsg(fResult, ("Error: Failed to delete serivce '%ls': %u\n", m_wszServiceName, GetLastError()));
459
460 ::CloseServiceHandle(hService);
461 }
462 ::CloseServiceHandle(hSCM);
463 }
464 else
465 AssertLogRelMsgFailed(("Error: Could not open the service control manager: %u\n", GetLastError()));
466 return fResult;
467 }
468};
469
470/*static*/ CWindowsServiceModule *CWindowsServiceModule::s_pInstance = NULL;
471
472
473/**
474 * Implements COM Module that used within Windows Service.
475 *
476 * It is derived from ComModule to intercept Unlock() and derived from
477 * CWindowsServiceModule to implement Windows Service
478 */
479class CComServiceModule : public CWindowsServiceModule, public ATL::CComModule
480{
481private:
482 /** Tracks whether Init() has been called for debug purposes. */
483 bool m_fInitialized;
484 /** Tracks COM init status for no visible purpose other than debugging. */
485 bool m_fComInitialized;
486 /** Part of the shutdown monitoring logic. */
487 bool volatile m_fActivity;
488 /** Auto reset event for communicating with the shutdown thread.
489 * This is created by startMonitor(). */
490 HANDLE m_hEventShutdown;
491 /** The main thread ID.
492 * The monitorShutdown code needs this to post a WM_QUIT message. */
493 DWORD m_dwMainThreadID;
494
495public:
496 /** Time for EXE to be idle before shutting down.
497 * Can be decreased at system shutdown phase. */
498 volatile uint32_t m_cMsShutdownTimeOut;
499
500public:
501 /**
502 * Constructor.
503 *
504 * @param cMsShutdownTimeout Number of milliseconds to idle without clients
505 * before autoamtically shutting down the service.
506 *
507 * The default is 2 seconds, because VBoxSVC (our
508 * only client) already does 5 seconds making the
509 * effective idle time 7 seconds from clients like
510 * VBoxManage's point of view. We consider single
511 * user and development as the dominant usage
512 * patterns here, not configuration activity by
513 * multiple users via VBoxManage.
514 */
515 CComServiceModule(DWORD cMsShutdownTimeout = 2000)
516 : m_fInitialized(false)
517 , m_fComInitialized(false)
518 , m_fActivity(false)
519 , m_cMsShutdownTimeOut(cMsShutdownTimeout)
520 , m_hEventShutdown(INVALID_HANDLE_VALUE)
521 , m_dwMainThreadID(~(DWORD)42)
522 {
523 }
524
525 /**
526 * Initialization function.
527 */
528 HRESULT init(ATL::_ATL_OBJMAP_ENTRY *p, HINSTANCE h, const GUID *pLibID,
529 wchar_t const *p_wszServiceName, wchar_t const *p_wszDisplayName, wchar_t const *p_wszDescription)
530 {
531 HRESULT hrc = ATL::CComModule::Init(p, h, pLibID);
532 if (SUCCEEDED(hrc))
533 {
534
535 // copy service name
536 int rc = ::RTUtf16Copy(m_wszServiceName, sizeof(m_wszServiceName), p_wszServiceName);
537 AssertRCReturn(rc, E_NOT_SUFFICIENT_BUFFER);
538 rc = ::RTUtf16Copy(m_wszServiceDisplayName, sizeof(m_wszServiceDisplayName), p_wszDisplayName);
539 AssertRCReturn(rc, E_NOT_SUFFICIENT_BUFFER);
540 rc = ::RTUtf16Copy(m_wszServiceDescription, sizeof(m_wszServiceDescription), p_wszDescription);
541 AssertRCReturn(rc, E_NOT_SUFFICIENT_BUFFER);
542
543 m_fInitialized = true;
544 }
545
546 return hrc;
547 }
548
549 /**
550 * Overload CAtlModule::Unlock to trigger delayed automatic shutdown action.
551 */
552 virtual LONG Unlock() throw()
553 {
554 LONG cLocks = ATL::CComModule::Unlock();
555 LogFunc(("Unlock() called. Ref=%d\n", cLocks));
556 if (cLocks == 0)
557 {
558 m_fActivity = true;
559 ::SetEvent(m_hEventShutdown); // tell monitor that we transitioned to zero
560 }
561 return cLocks;
562 }
563
564protected:
565
566 bool hasActiveConnection()
567 {
568 return m_fActivity || GetLockCount() > 0;
569 }
570
571 void monitorShutdown() throw()
572 {
573 for (;;)
574 {
575 ::WaitForSingleObject(m_hEventShutdown, INFINITE);
576 DWORD dwWait;
577 do
578 {
579 m_fActivity = false;
580 dwWait = ::WaitForSingleObject(m_hEventShutdown, m_cMsShutdownTimeOut);
581 } while (dwWait == WAIT_OBJECT_0);
582
583 /* timed out */
584 if (!hasActiveConnection()) /* if no activity let's really bail */
585 {
586 /*
587 * Disable log rotation at this point, worst case a log file
588 * becomes slightly bigger than it should. Avoids quirks with
589 * log rotation: there might be another API service process
590 * running at this point which would rotate the logs concurrently,
591 * creating a mess.
592 */
593 PRTLOGGER pReleaseLogger = ::RTLogRelGetDefaultInstance();
594 if (pReleaseLogger)
595 {
596 char szDest[1024];
597 int rc = ::RTLogGetDestinations(pReleaseLogger, szDest, sizeof(szDest));
598 if (RT_SUCCESS(rc))
599 {
600 rc = ::RTStrCat(szDest, sizeof(szDest), " nohistory");
601 if (RT_SUCCESS(rc))
602 {
603 rc = ::RTLogDestinations(pReleaseLogger, szDest);
604 AssertRC(rc);
605 }
606 }
607 }
608 ::CoSuspendClassObjects();
609 if (!hasActiveConnection())
610 break;
611 LogRel(("Still got active connection(s)...\n"));
612 }
613 }
614
615 LogRel(("Shutting down\n"));
616 if (m_hEventShutdown)
617 {
618 ::CloseHandle(m_hEventShutdown);
619 m_hEventShutdown = NULL;
620 }
621 ::PostThreadMessage(m_dwMainThreadID, WM_QUIT, 0, 0);
622 }
623
624 static DECLCALLBACK(int) monitorThreadProc(RTTHREAD hThreadSelf, void *pvUser) throw()
625 {
626 RT_NOREF(hThreadSelf);
627 CComServiceModule *p = static_cast<CComServiceModule *>(pvUser);
628 p->monitorShutdown();
629 return VINF_SUCCESS;
630 }
631
632 void startMonitor()
633 {
634 m_dwMainThreadID = ::GetCurrentThreadId();
635 m_hEventShutdown = ::CreateEvent(NULL, false, false, NULL);
636 AssertLogRelMsg(m_hEventShutdown != NULL, ("GetLastError => %u\n", GetLastError()));
637
638 int vrc = RTThreadCreate(NULL, monitorThreadProc, this, 0 /*cbStack*/, RTTHREADTYPE_DEFAULT, 0 /*fFlags*/, "MonShdwn");
639 if (RT_FAILURE(vrc))
640 {
641 ::CloseHandle(m_hEventShutdown);
642 m_hEventShutdown = NULL;
643 LogRel(("Error: RTThreadCreate failed to create shutdown monitor thread: %Rrc\n", vrc));
644 }
645 }
646
647 virtual HRESULT preMessageLoop(int nShowCmd)
648 {
649 Assert(m_fInitialized);
650 LogFunc(("Enter\n"));
651
652 HRESULT hrc = com::Initialize();
653 if (SUCCEEDED(hrc))
654 {
655 m_fComInitialized = true;
656 hrc = ATL::CComModule::RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE | REGCLS_SUSPENDED);
657 if (SUCCEEDED(hrc))
658 {
659 // Start Shutdown monitor here
660 startMonitor();
661
662 hrc = CWindowsServiceModule::preMessageLoop(nShowCmd);
663 if (FAILED(hrc))
664 LogRelFunc(("Warning: preMessageLoop failed: %Rhrc\n", hrc));
665
666 hrc = CoResumeClassObjects();
667 if (FAILED(hrc))
668 {
669 ATL::CComModule::RevokeClassObjects();
670 LogRelFunc(("Error: CoResumeClassObjects failed: %Rhrc\n", hrc));
671 }
672 }
673 else
674 LogRel(("Error: ATL::CComModule::RegisterClassObjects: %Rhrc\n", hrc));
675 }
676 else
677 LogRel(("Error: com::Initialize failed\n", hrc));
678 return hrc;
679 }
680
681 virtual HRESULT postMessageLoop()
682 {
683 com::Shutdown();
684 m_fComInitialized = false;
685 return S_OK;
686 }
687};
688
689
690/** Special export that make VBoxProxyStub not register this process as one that
691 * VBoxSDS should be watching.
692 */
693extern "C" DECLEXPORT(void) VBOXCALL Is_VirtualBox_service_process_like_VBoxSDS_And_VBoxSDS(void)
694{
695 /* never called, just need to be here */
696}
697
698
699/**
700 * Main function for the VBoxSDS process.
701 *
702 * @param hInstance The process instance.
703 * @param hPrevInstance Previous instance (not used here).
704 * @param nShowCmd The show flags.
705 * @param lpCmdLine The command line (not used here, we get it from the
706 * C runtime library).
707 *
708 * @return Exit code
709 */
710int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
711{
712 RT_NOREF(hPrevInstance, lpCmdLine);
713 int argc = __argc;
714 char **argv = __argv;
715
716 /*
717 * Initialize the VBox runtime without loading the support driver.
718 */
719 RTR3InitExe(argc, &argv, 0);
720
721 static const RTGETOPTDEF s_aOptions[] =
722 {
723 { "--embedding", 'e', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
724 { "-embedding", 'e', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
725 { "/embedding", 'e', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
726 { "--unregservice", 'u', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
727 { "-unregservice", 'u', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
728 { "/unregservice", 'u', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
729 { "--regservice", 'r', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
730 { "-regservice", 'r', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
731 { "/regservice", 'r', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
732 { "--reregservice", 'f', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
733 { "-reregservice", 'f', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
734 { "/reregservice", 'f', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
735 { "--logfile", 'F', RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
736 { "-logfile", 'F', RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
737 { "/logfile", 'F', RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
738 { "--logrotate", 'R', RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
739 { "-logrotate", 'R', RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
740 { "/logrotate", 'R', RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
741 { "--logsize", 'S', RTGETOPT_REQ_UINT64 | RTGETOPT_FLAG_ICASE },
742 { "-logsize", 'S', RTGETOPT_REQ_UINT64 | RTGETOPT_FLAG_ICASE },
743 { "/logsize", 'S', RTGETOPT_REQ_UINT64 | RTGETOPT_FLAG_ICASE },
744 { "--loginterval", 'I', RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
745 { "-loginterval", 'I', RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
746 { "/loginterval", 'I', RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
747 };
748
749 bool fRun = true;
750 bool fRegister = false;
751 bool fUnregister = false;
752 const char *pszLogFile = NULL;
753 uint32_t cHistory = 10; // enable log rotation, 10 files
754 uint32_t uHistoryFileTime = RT_SEC_1DAY; // max 1 day per file
755 uint64_t uHistoryFileSize = 100 * _1M; // max 100MB per file
756
757 RTGETOPTSTATE GetOptState;
758 int vrc = RTGetOptInit(&GetOptState, argc, argv, &s_aOptions[0], RT_ELEMENTS(s_aOptions), 1, 0 /*fFlags*/);
759 AssertRC(vrc);
760
761 RTGETOPTUNION ValueUnion;
762 while ((vrc = RTGetOpt(&GetOptState, &ValueUnion)))
763 {
764 switch (vrc)
765 {
766 case 'e':
767 break;
768
769 case 'u':
770 fUnregister = true;
771 fRun = false;
772 break;
773
774 case 'r':
775 fRegister = true;
776 fRun = false;
777 break;
778
779 case 'f':
780 fUnregister = true;
781 fRegister = true;
782 fRun = false;
783 break;
784
785 case 'F':
786 pszLogFile = ValueUnion.psz;
787 break;
788
789 case 'R':
790 cHistory = ValueUnion.u32;
791 break;
792
793 case 'S':
794 uHistoryFileSize = ValueUnion.u64;
795 break;
796
797 case 'I':
798 uHistoryFileTime = ValueUnion.u32;
799 break;
800
801 case 'h':
802 {
803 static WCHAR const s_wszHelpText[] =
804 L"Options:\n"
805 L"\n"
806 L"/RegService\t" L"register COM out-of-proc service\n"
807 L"/UnregService\t" L"unregister COM out-of-proc service\n"
808 L"/ReregService\t" L"unregister and register COM service\n"
809 L"no options\t" L"run the service";
810 MessageBoxW(NULL, s_wszHelpText, L"VBoxSDS - Usage", MB_OK);
811 return 0;
812 }
813
814 case 'V':
815 {
816 char *pszText = NULL;
817 RTStrAPrintf(&pszText, "%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
818
819 PRTUTF16 pwszText = NULL;
820 RTStrToUtf16(pszText, &pwszText);
821
822 MessageBoxW(NULL, pwszText, L"VBoxSDS - Version", MB_OK);
823
824 RTStrFree(pszText);
825 RTUtf16Free(pwszText);
826 return 0;
827 }
828
829 default:
830 {
831 char szTmp[256];
832 RTGetOptFormatError(szTmp, sizeof(szTmp), vrc, &ValueUnion);
833
834 PRTUTF16 pwszText = NULL;
835 RTStrToUtf16(szTmp, &pwszText);
836
837 MessageBoxW(NULL, pwszText, L"VBoxSDS - Syntax error", MB_OK | MB_ICONERROR);
838
839 RTUtf16Free(pwszText);
840 return RTEXITCODE_SYNTAX;
841 }
842 }
843 }
844
845 /*
846 * Default log location is %ProgramData%\VirtualBox\VBoxSDS.log, falling back
847 * on %_CWD%\VBoxSDS.log (where _CWD typicaly is 'C:\Windows\System32').
848 *
849 * We change the current directory to %ProgramData%\VirtualBox\ if possible.
850 *
851 * We only create the log file when running VBoxSDS normally, but not
852 * when registering/unregistering, at least for now.
853 */
854 if (fRun)
855 {
856 char szLogFile[RTPATH_MAX];
857 if (!pszLogFile || !*pszLogFile)
858 {
859 WCHAR wszAppData[MAX_PATH + 16];
860 if (SHGetSpecialFolderPathW(NULL, wszAppData, CSIDL_COMMON_APPDATA, TRUE /*fCreate*/))
861 {
862 char *pszConv = szLogFile;
863 vrc = RTUtf16ToUtf8Ex(wszAppData, RTSTR_MAX, &pszConv, sizeof(szLogFile) - 12, NULL);
864 }
865 else
866 vrc = RTEnvGetUtf8("ProgramData", szLogFile, sizeof(szLogFile) - sizeof("VBoxSDS.log"), NULL);
867 if (RT_SUCCESS(vrc))
868 {
869 vrc = RTPathAppend(szLogFile, sizeof(szLogFile), "VirtualBox\\");
870 if (RT_SUCCESS(vrc))
871 {
872 /* Make sure it exists. */
873 if (!RTDirExists(szLogFile))
874 vrc = RTDirCreate(szLogFile, 0755, RTDIRCREATE_FLAGS_NOT_CONTENT_INDEXED_DONT_SET);
875 if (RT_SUCCESS(vrc))
876 {
877 /* Change into it. */
878 RTPathSetCurrent(szLogFile);
879 }
880 }
881 }
882 if (RT_FAILURE(vrc)) /* ignore any failure above */
883 szLogFile[0] = '\0';
884 vrc = RTStrCat(szLogFile, sizeof(szLogFile), "VBoxSDS.log");
885 if (RT_FAILURE(vrc))
886 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to construct release log filename: %Rrc", vrc);
887 pszLogFile = szLogFile;
888 }
889
890 RTERRINFOSTATIC ErrInfo;
891 vrc = com::VBoxLogRelCreate("COM Service", pszLogFile,
892 RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME_PROG,
893 VBOXSDS_LOG_DEFAULT, "VBOXSDS_RELEASE_LOG",
894 RTLOGDEST_FILE, UINT32_MAX /* cMaxEntriesPerGroup */,
895 cHistory, uHistoryFileTime, uHistoryFileSize,
896 RTErrInfoInitStatic(&ErrInfo));
897 if (RT_FAILURE(vrc))
898 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to open release log (%s, %Rrc)", ErrInfo.Core.pszMsg, vrc);
899 }
900
901
902 /*
903 * Initialize COM.
904 */
905 HRESULT hrcExit = com::Initialize();
906 if (SUCCEEDED(hrcExit))
907 {
908 HRESULT hrcSec = CoInitializeSecurity(NULL,
909 -1,
910 NULL,
911 NULL,
912 RPC_C_AUTHN_LEVEL_DEFAULT,
913 RPC_C_IMP_LEVEL_IMPERSONATE,//RPC_C_IMP_LEVEL_IMPERSONATE, RPC_C_IMP_LEVEL_DELEGATE
914 NULL,
915 EOAC_NONE, //EOAC_DYNAMIC_CLOAKING,//EOAC_STATIC_CLOAKING, //EOAC_NONE,
916 NULL);
917 LogRelFunc(("VBoxSDS: InitializeSecurity: %x\n", hrcSec));
918
919 /*
920 * Instantiate our COM service class.
921 */
922 CComServiceModule *pServiceModule = new CComServiceModule();
923 if (pServiceModule)
924 {
925 BEGIN_OBJECT_MAP(s_aObjectMap)
926 OBJECT_ENTRY(CLSID_VirtualBoxSDS, VirtualBoxSDS)
927 END_OBJECT_MAP()
928 hrcExit = pServiceModule->init(s_aObjectMap, hInstance, &LIBID_VirtualBox,
929 L"VBoxSDS",
930 L"VirtualBox system service",
931 L"Used as a COM server for VirtualBox API.");
932
933 if (SUCCEEDED(hrcExit))
934 {
935 if (!fRun)
936 {
937 /*
938 * Do registration work and quit.
939 */
940 /// @todo The VBoxProxyStub should do all work for COM registration
941 if (fUnregister)
942 hrcExit = pServiceModule->unregisterService();
943 if (fRegister)
944 hrcExit = pServiceModule->registerService();
945 }
946 else
947 {
948 /*
949 * Run service.
950 */
951 hrcExit = pServiceModule->startService(nShowCmd);
952 LogRelFunc(("VBoxSDS: Calling _ServiceModule.RevokeClassObjects()...\n"));
953 pServiceModule->RevokeClassObjects();
954 }
955
956 LogRelFunc(("VBoxSDS: Calling _ServiceModule.Term()...\n"));
957 pServiceModule->Term();
958 }
959 else
960 LogRelFunc(("VBoxSDS: new CComServiceModule::Init failed: %Rhrc\n", hrcExit));
961
962 LogRelFunc(("VBoxSDS: deleting pServiceModule (%p)\n", pServiceModule));
963 delete pServiceModule;
964 pServiceModule = NULL;
965 }
966 else
967 LogRelFunc(("VBoxSDS: new CComServiceModule() failed\n"));
968
969 LogRelFunc(("VBoxSDS: Calling com::Shutdown\n"));
970 com::Shutdown();
971 }
972 else
973 LogRelFunc(("VBoxSDS: COM initialization failed: %Rrc\n", hrcExit));
974
975 LogRelFunc(("VBoxSDS: COM service process ends: hrcExit=%Rhrc (%#x)\n", hrcExit, hrcExit));
976 return (int)hrcExit;
977}
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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