VirtualBox

source: vbox/trunk/src/VBox/Additions/common/VBoxService/VBoxService-win.cpp

Last change on this file was 99828, checked in by vboxsync, 12 months ago

*: A bunch of adjustments that allows using /permissive- with Visual C++ (qt 6.x necessity).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 24.0 KB
Line 
1/* $Id: VBoxService-win.cpp 99828 2023-05-17 13:48:57Z vboxsync $ */
2/** @file
3 * VBoxService - Guest Additions Service Skeleton, Windows Specific Parts.
4 */
5
6/*
7 * Copyright (C) 2009-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28
29/*********************************************************************************************************************************
30* Header Files *
31*********************************************************************************************************************************/
32#include <iprt/assert.h>
33#include <iprt/err.h>
34#include <iprt/ldr.h>
35#include <iprt/system.h> /* For querying OS version. */
36
37#define WIN32_NO_STATUS
38#include <iprt/win/ws2tcpip.h>
39#include <iprt/win/winsock2.h>
40#undef WIN32_NO_STATUS
41#include <iprt/nt/nt-and-windows.h>
42#include <iprt/win/iphlpapi.h>
43#include <aclapi.h>
44#include <tlhelp32.h>
45#define _NTDEF_
46#include <Ntsecapi.h>
47
48#include "VBoxServiceInternal.h"
49
50
51/*********************************************************************************************************************************
52* Internal Functions *
53*********************************************************************************************************************************/
54static void WINAPI vgsvcWinMain(DWORD argc, LPTSTR *argv);
55
56
57/*********************************************************************************************************************************
58* Global Variables *
59*********************************************************************************************************************************/
60static DWORD g_dwWinServiceLastStatus = 0;
61SERVICE_STATUS_HANDLE g_hWinServiceStatus = NULL;
62/** The semaphore for the dummy Windows service. */
63static RTSEMEVENT g_WindowsEvent = NIL_RTSEMEVENT;
64
65static SERVICE_TABLE_ENTRYA const g_aServiceTable[] =
66{
67 { (PSTR)VBOXSERVICE_NAME, vgsvcWinMain },
68 { NULL, NULL}
69};
70
71/** @name APIs from ADVAPI32.DLL.
72 * @{ */
73decltype(RegisterServiceCtrlHandlerExA) *g_pfnRegisterServiceCtrlHandlerExA; /**< W2K+ */
74decltype(ChangeServiceConfig2A) *g_pfnChangeServiceConfig2A; /**< W2K+ */
75decltype(GetNamedSecurityInfoA) *g_pfnGetNamedSecurityInfoA; /**< NT4+ */
76decltype(SetEntriesInAclA) *g_pfnSetEntriesInAclA; /**< NT4+ */
77decltype(SetNamedSecurityInfoA) *g_pfnSetNamedSecurityInfoA; /**< NT4+ */
78decltype(LsaNtStatusToWinError) *g_pfnLsaNtStatusToWinError; /**< NT3.51+ */
79/** @} */
80
81/** @name API from KERNEL32.DLL
82 * @{ */
83decltype(CreateToolhelp32Snapshot) *g_pfnCreateToolhelp32Snapshot; /**< W2K+, but Geoff says NT4. Hmm. */
84decltype(Process32First) *g_pfnProcess32First; /**< W2K+, but Geoff says NT4. Hmm. */
85decltype(Process32Next) *g_pfnProcess32Next; /**< W2K+, but Geoff says NT4. Hmm. */
86decltype(Module32First) *g_pfnModule32First; /**< W2K+, but Geoff says NT4. Hmm. */
87decltype(Module32Next) *g_pfnModule32Next; /**< W2K+, but Geoff says NT4. Hmm. */
88decltype(GetSystemTimeAdjustment) *g_pfnGetSystemTimeAdjustment; /**< NT 3.50+ */
89decltype(SetSystemTimeAdjustment) *g_pfnSetSystemTimeAdjustment; /**< NT 3.50+ */
90/** @} */
91
92/** @name API from NTDLL.DLL
93 * @{ */
94decltype(ZwQuerySystemInformation) *g_pfnZwQuerySystemInformation; /**< NT4 (where as NtQuerySystemInformation is W2K). */
95/** @} */
96
97/** @name API from IPHLPAPI.DLL
98 * @{ */
99decltype(GetAdaptersInfo) *g_pfnGetAdaptersInfo;
100/** @} */
101
102/** @name APIs from WS2_32.DLL
103 * @note WSAIoctl is not present in wsock32.dll, so no point in trying the
104 * fallback here.
105 * @{ */
106decltype(WSAStartup) *g_pfnWSAStartup;
107decltype(WSACleanup) *g_pfnWSACleanup;
108decltype(WSASocketA) *g_pfnWSASocketA;
109decltype(WSAIoctl) *g_pfnWSAIoctl;
110decltype(WSAGetLastError) *g_pfnWSAGetLastError;
111decltype(closesocket) *g_pfnclosesocket;
112decltype(inet_ntoa) *g_pfninet_ntoa;
113
114/** @} */
115
116/**
117 * Resolve APIs not present on older windows versions.
118 */
119void VGSvcWinResolveApis(void)
120{
121 RTLDRMOD hLdrMod;
122#define RESOLVE_SYMBOL(a_fn) do { RT_CONCAT(g_pfn, a_fn) = (decltype(a_fn) *)RTLdrGetFunction(hLdrMod, #a_fn); } while (0)
123
124 /* From ADVAPI32.DLL: */
125 int rc = RTLdrLoadSystem("advapi32.dll", true /*fNoUnload*/, &hLdrMod);
126 AssertRC(rc);
127 if (RT_SUCCESS(rc))
128 {
129 RESOLVE_SYMBOL(RegisterServiceCtrlHandlerExA);
130 RESOLVE_SYMBOL(ChangeServiceConfig2A);
131 RESOLVE_SYMBOL(GetNamedSecurityInfoA);
132 RESOLVE_SYMBOL(SetEntriesInAclA);
133 RESOLVE_SYMBOL(SetNamedSecurityInfoA);
134 RESOLVE_SYMBOL(LsaNtStatusToWinError);
135 RTLdrClose(hLdrMod);
136 }
137
138 /* From KERNEL32.DLL: */
139 rc = RTLdrLoadSystem("kernel32.dll", true /*fNoUnload*/, &hLdrMod);
140 AssertRC(rc);
141 if (RT_SUCCESS(rc))
142 {
143 RESOLVE_SYMBOL(CreateToolhelp32Snapshot);
144 RESOLVE_SYMBOL(Process32First);
145 RESOLVE_SYMBOL(Process32Next);
146 RESOLVE_SYMBOL(Module32First);
147 RESOLVE_SYMBOL(Module32Next);
148 RESOLVE_SYMBOL(GetSystemTimeAdjustment);
149 RESOLVE_SYMBOL(SetSystemTimeAdjustment);
150 RTLdrClose(hLdrMod);
151 }
152
153 /* From NTDLL.DLL: */
154 rc = RTLdrLoadSystem("ntdll.dll", true /*fNoUnload*/, &hLdrMod);
155 AssertRC(rc);
156 if (RT_SUCCESS(rc))
157 {
158 RESOLVE_SYMBOL(ZwQuerySystemInformation);
159 RTLdrClose(hLdrMod);
160 }
161
162 /* From IPHLPAPI.DLL: */
163 rc = RTLdrLoadSystem("iphlpapi.dll", true /*fNoUnload*/, &hLdrMod);
164 if (RT_SUCCESS(rc))
165 {
166 RESOLVE_SYMBOL(GetAdaptersInfo);
167 RTLdrClose(hLdrMod);
168 }
169
170 /* From WS2_32.DLL: */
171 rc = RTLdrLoadSystem("ws2_32.dll", true /*fNoUnload*/, &hLdrMod);
172 if (RT_SUCCESS(rc))
173 {
174 RESOLVE_SYMBOL(WSAStartup);
175 RESOLVE_SYMBOL(WSACleanup);
176 RESOLVE_SYMBOL(WSASocketA);
177 RESOLVE_SYMBOL(WSAIoctl);
178 RESOLVE_SYMBOL(WSAGetLastError);
179 RESOLVE_SYMBOL(closesocket);
180 RESOLVE_SYMBOL(inet_ntoa);
181 RTLdrClose(hLdrMod);
182 }
183}
184
185
186/**
187 * @todo Add full unicode support.
188 * @todo Add event log capabilities / check return values.
189 */
190static int vgsvcWinAddAceToObjectsSecurityDescriptor(LPCSTR pszObjName, SE_OBJECT_TYPE enmObjectType, const char *pszTrustee,
191 TRUSTEE_FORM enmTrusteeForm, DWORD dwAccessRights, ACCESS_MODE fAccessMode,
192 DWORD dwInheritance)
193{
194 int rc;
195 if ( g_pfnGetNamedSecurityInfoA
196 && g_pfnSetEntriesInAclA
197 && g_pfnSetNamedSecurityInfoA)
198 {
199 /* Get a pointer to the existing DACL. */
200 PSECURITY_DESCRIPTOR pSD = NULL;
201 PACL pOldDACL = NULL;
202 DWORD rcWin = g_pfnGetNamedSecurityInfoA(pszObjName, enmObjectType, DACL_SECURITY_INFORMATION,
203 NULL, NULL, &pOldDACL, NULL, &pSD);
204 if (rcWin == ERROR_SUCCESS)
205 {
206 /* Initialize an EXPLICIT_ACCESS structure for the new ACE. */
207 EXPLICIT_ACCESSA ExplicitAccess;
208 RT_ZERO(ExplicitAccess);
209 ExplicitAccess.grfAccessPermissions = dwAccessRights;
210 ExplicitAccess.grfAccessMode = fAccessMode;
211 ExplicitAccess.grfInheritance = dwInheritance;
212 ExplicitAccess.Trustee.TrusteeForm = enmTrusteeForm;
213 ExplicitAccess.Trustee.ptstrName = (char *)pszTrustee;
214
215 /* Create a new ACL that merges the new ACE into the existing DACL. */
216 PACL pNewDACL = NULL;
217 rcWin = g_pfnSetEntriesInAclA(1, &ExplicitAccess, pOldDACL, &pNewDACL);
218 if (rcWin == ERROR_SUCCESS)
219 {
220 /* Attach the new ACL as the object's DACL. */
221 rcWin = g_pfnSetNamedSecurityInfoA((PSTR)pszObjName, enmObjectType, DACL_SECURITY_INFORMATION,
222 NULL, NULL, pNewDACL, NULL);
223 if (rcWin == ERROR_SUCCESS)
224 rc = VINF_SUCCESS;
225 else
226 {
227 VGSvcError("AddAceToObjectsSecurityDescriptor: SetNamedSecurityInfo: Error %u\n", rcWin);
228 rc = RTErrConvertFromWin32(rcWin);
229 }
230 if (pNewDACL)
231 LocalFree(pNewDACL);
232 }
233 else
234 {
235 VGSvcError("AddAceToObjectsSecurityDescriptor: SetEntriesInAcl: Error %u\n", rcWin);
236 rc = RTErrConvertFromWin32(rcWin);
237 }
238 if (pSD)
239 LocalFree(pSD);
240 }
241 else
242 {
243 if (rcWin == ERROR_FILE_NOT_FOUND)
244 VGSvcError("AddAceToObjectsSecurityDescriptor: Object not found/installed: %s\n", pszObjName);
245 else
246 VGSvcError("AddAceToObjectsSecurityDescriptor: GetNamedSecurityInfo: Error %u\n", rcWin);
247 rc = RTErrConvertFromWin32(rcWin);
248 }
249 }
250 else
251 rc = VINF_SUCCESS; /* fake it */
252 return rc;
253}
254
255
256/** Reports our current status to the SCM. */
257static BOOL vgsvcWinSetStatus(DWORD dwStatus, DWORD dwCheckPoint)
258{
259 if (g_hWinServiceStatus == NULL) /* Program could be in testing mode, so no service environment available. */
260 return FALSE;
261
262 VGSvcVerbose(2, "Setting service status to: %ld\n", dwStatus);
263 g_dwWinServiceLastStatus = dwStatus;
264
265 SERVICE_STATUS ss;
266 RT_ZERO(ss);
267
268 ss.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
269 ss.dwCurrentState = dwStatus;
270 /* Don't accept controls when in start pending state. */
271 if (ss.dwCurrentState != SERVICE_START_PENDING)
272 {
273 ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
274
275 /* Don't use SERVICE_ACCEPT_SESSIONCHANGE on Windows 2000 or earlier. This makes SCM angry. */
276 char szOSVersion[32];
277 int rc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szOSVersion, sizeof(szOSVersion));
278 if (RT_SUCCESS(rc))
279 {
280 if (RTStrVersionCompare(szOSVersion, "5.1") >= 0)
281 ss.dwControlsAccepted |= SERVICE_ACCEPT_SESSIONCHANGE;
282 }
283 else
284 VGSvcError("Error determining OS version, rc=%Rrc\n", rc);
285 }
286
287 ss.dwWin32ExitCode = NO_ERROR;
288 ss.dwServiceSpecificExitCode = 0; /* Not used */
289 ss.dwCheckPoint = dwCheckPoint;
290 ss.dwWaitHint = 3000;
291
292 BOOL fStatusSet = SetServiceStatus(g_hWinServiceStatus, &ss);
293 if (!fStatusSet)
294 VGSvcError("Error reporting service status=%ld (controls=%x, checkpoint=%ld) to SCM: %ld\n",
295 dwStatus, ss.dwControlsAccepted, dwCheckPoint, GetLastError());
296 return fStatusSet;
297}
298
299
300/**
301 * Reports SERVICE_STOP_PENDING to SCM.
302 *
303 * @param uCheckPoint Some number.
304 */
305void VGSvcWinSetStopPendingStatus(uint32_t uCheckPoint)
306{
307 vgsvcWinSetStatus(SERVICE_STOP_PENDING, uCheckPoint);
308}
309
310
311static RTEXITCODE vgsvcWinSetDesc(SC_HANDLE hService)
312{
313 /* On W2K+ there's ChangeServiceConfig2() which lets us set some fields
314 like a longer service description. */
315 if (g_pfnChangeServiceConfig2A)
316 {
317 /** @todo On Vista+ SERVICE_DESCRIPTION also supports localized strings! */
318 SERVICE_DESCRIPTION desc;
319 desc.lpDescription = (LPSTR)VBOXSERVICE_DESCRIPTION;
320 if (!g_pfnChangeServiceConfig2A(hService, SERVICE_CONFIG_DESCRIPTION, &desc))
321 {
322 VGSvcError("Cannot set the service description! Error: %ld\n", GetLastError());
323 return RTEXITCODE_FAILURE;
324 }
325 }
326 return RTEXITCODE_SUCCESS;
327}
328
329
330/**
331 * Installs the service.
332 */
333RTEXITCODE VGSvcWinInstall(void)
334{
335 VGSvcVerbose(1, "Installing service ...\n");
336
337 TCHAR imagePath[MAX_PATH] = { 0 };
338 GetModuleFileName(NULL, imagePath, sizeof(imagePath));
339
340 SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
341 if (hSCManager == NULL)
342 {
343 VGSvcError("Could not open SCM! Error: %ld\n", GetLastError());
344 return RTEXITCODE_FAILURE;
345 }
346
347 RTEXITCODE rc = RTEXITCODE_SUCCESS;
348 SC_HANDLE hService = CreateService(hSCManager,
349 VBOXSERVICE_NAME, VBOXSERVICE_FRIENDLY_NAME,
350 SERVICE_ALL_ACCESS,
351 SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS,
352 SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL,
353 imagePath, NULL, NULL, NULL, NULL, NULL);
354 if (hService != NULL)
355 VGSvcVerbose(0, "Service successfully installed!\n");
356 else
357 {
358 DWORD dwErr = GetLastError();
359 switch (dwErr)
360 {
361 case ERROR_SERVICE_EXISTS:
362 VGSvcVerbose(1, "Service already exists, just updating the service config.\n");
363 hService = OpenService(hSCManager, VBOXSERVICE_NAME, SERVICE_ALL_ACCESS);
364 if (hService)
365 {
366 if (ChangeServiceConfig(hService,
367 SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS,
368 SERVICE_DEMAND_START,
369 SERVICE_ERROR_NORMAL,
370 imagePath,
371 NULL,
372 NULL,
373 NULL,
374 NULL,
375 NULL,
376 VBOXSERVICE_FRIENDLY_NAME))
377 VGSvcVerbose(1, "The service config has been successfully updated.\n");
378 else
379 rc = VGSvcError("Could not change service config! Error: %ld\n", GetLastError());
380 }
381 else
382 rc = VGSvcError("Could not open service! Error: %ld\n", GetLastError());
383 break;
384
385 default:
386 rc = VGSvcError("Could not create service! Error: %ld\n", dwErr);
387 break;
388 }
389 }
390
391 if (rc == RTEXITCODE_SUCCESS)
392 rc = vgsvcWinSetDesc(hService);
393
394 CloseServiceHandle(hService);
395 CloseServiceHandle(hSCManager);
396 return rc;
397}
398
399/**
400 * Uninstalls the service.
401 */
402RTEXITCODE VGSvcWinUninstall(void)
403{
404 VGSvcVerbose(1, "Uninstalling service ...\n");
405
406 SC_HANDLE hSCManager = OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);
407 if (hSCManager == NULL)
408 {
409 VGSvcError("Could not open SCM! Error: %d\n", GetLastError());
410 return RTEXITCODE_FAILURE;
411 }
412
413 RTEXITCODE rcExit;
414 SC_HANDLE hService = OpenService(hSCManager, VBOXSERVICE_NAME, SERVICE_ALL_ACCESS );
415 if (hService != NULL)
416 {
417 if (DeleteService(hService))
418 {
419 /*
420 * ???
421 */
422 HKEY hKey = NULL;
423 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,
424 "SYSTEM\\CurrentControlSet\\Services\\EventLog\\System",
425 0,
426 KEY_ALL_ACCESS,
427 &hKey)
428 == ERROR_SUCCESS)
429 {
430 RegDeleteKey(hKey, VBOXSERVICE_NAME);
431 RegCloseKey(hKey);
432 }
433
434 VGSvcVerbose(0, "Service successfully uninstalled!\n");
435 rcExit = RTEXITCODE_SUCCESS;
436 }
437 else
438 rcExit = VGSvcError("Could not remove service! Error: %d\n", GetLastError());
439 CloseServiceHandle(hService);
440 }
441 else
442 rcExit = VGSvcError("Could not open service! Error: %d\n", GetLastError());
443 CloseServiceHandle(hSCManager);
444
445 return rcExit;
446}
447
448
449static int vgsvcWinStart(void)
450{
451 int rc = VINF_SUCCESS;
452
453 /*
454 * Create a well-known SID for the "Builtin Users" group and modify the ACE
455 * for the shared folders miniport redirector DN (whatever DN means).
456 */
457 PSID pBuiltinUsersSID = NULL;
458 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_LOCAL_SID_AUTHORITY;
459 if (AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_LOCAL_RID, 0, 0, 0, 0, 0, 0, 0, &pBuiltinUsersSID))
460 {
461 rc = vgsvcWinAddAceToObjectsSecurityDescriptor("\\\\.\\VBoxMiniRdrDN", SE_FILE_OBJECT,
462 (LPTSTR)pBuiltinUsersSID, TRUSTEE_IS_SID,
463 FILE_GENERIC_READ | FILE_GENERIC_WRITE, SET_ACCESS, NO_INHERITANCE);
464 /* If we don't find our "VBoxMiniRdrDN" (for Shared Folders) object above,
465 don't report an error; it just might be not installed. Otherwise this
466 would cause the SCM to hang on starting up the service. */
467 if (rc == VERR_FILE_NOT_FOUND || rc == VERR_PATH_NOT_FOUND)
468 rc = VINF_SUCCESS;
469
470 FreeSid(pBuiltinUsersSID);
471 }
472 else
473 rc = RTErrConvertFromWin32(GetLastError());
474 if (RT_SUCCESS(rc))
475 {
476 /*
477 * Start the service.
478 */
479 vgsvcWinSetStatus(SERVICE_START_PENDING, 0);
480
481 rc = VGSvcStartServices();
482 if (RT_SUCCESS(rc))
483 {
484 vgsvcWinSetStatus(SERVICE_RUNNING, 0);
485 VGSvcMainWait();
486 }
487 else
488 {
489 vgsvcWinSetStatus(SERVICE_STOPPED, 0);
490#if 0 /** @todo r=bird: Enable this if SERVICE_CONTROL_STOP isn't triggered automatically */
491 VGSvcStopServices();
492#endif
493 }
494 }
495 else
496 vgsvcWinSetStatus(SERVICE_STOPPED, 0);
497
498 if (RT_FAILURE(rc))
499 VGSvcError("Service failed to start with rc=%Rrc!\n", rc);
500
501 return rc;
502}
503
504
505/**
506 * Call StartServiceCtrlDispatcher.
507 *
508 * The main() thread invokes this when not started in foreground mode. It
509 * won't return till the service is being shutdown (unless start up fails).
510 *
511 * @returns RTEXITCODE_SUCCESS on normal return after service shutdown.
512 * Something else on failure, error will have been reported.
513 */
514RTEXITCODE VGSvcWinEnterCtrlDispatcher(void)
515{
516 if (!StartServiceCtrlDispatcher(&g_aServiceTable[0]))
517 return VGSvcError("StartServiceCtrlDispatcher: %u. Please start %s with option -f (foreground)!\n",
518 GetLastError(), g_pszProgName);
519 return RTEXITCODE_SUCCESS;
520}
521
522
523/**
524 * Event code to description.
525 *
526 * @returns String.
527 * @param dwEvent The event code.
528 */
529static const char *vgsvcWTSStateToString(DWORD dwEvent)
530{
531 switch (dwEvent)
532 {
533 case WTS_CONSOLE_CONNECT: return "A session was connected to the console terminal";
534 case WTS_CONSOLE_DISCONNECT: return "A session was disconnected from the console terminal";
535 case WTS_REMOTE_CONNECT: return "A session connected to the remote terminal";
536 case WTS_REMOTE_DISCONNECT: return "A session was disconnected from the remote terminal";
537 case WTS_SESSION_LOGON: return "A user has logged on to a session";
538 case WTS_SESSION_LOGOFF: return "A user has logged off the session";
539 case WTS_SESSION_LOCK: return "A session has been locked";
540 case WTS_SESSION_UNLOCK: return "A session has been unlocked";
541 case WTS_SESSION_REMOTE_CONTROL: return "A session has changed its remote controlled status";
542#ifdef WTS_SESSION_CREATE
543 case WTS_SESSION_CREATE: return "A session has been created";
544#endif
545#ifdef WTS_SESSION_TERMINATE
546 case WTS_SESSION_TERMINATE: return "The session has been terminated";
547#endif
548 default: return "Uknonwn state";
549 }
550}
551
552
553/**
554 * Common control handler.
555 *
556 * @returns Return code for NT5+.
557 * @param dwControl The control code.
558 */
559static DWORD vgsvcWinCtrlHandlerCommon(DWORD dwControl)
560{
561 DWORD rcRet = NO_ERROR;
562 switch (dwControl)
563 {
564 case SERVICE_CONTROL_INTERROGATE:
565 vgsvcWinSetStatus(g_dwWinServiceLastStatus, 0);
566 break;
567
568 case SERVICE_CONTROL_STOP:
569 case SERVICE_CONTROL_SHUTDOWN:
570 {
571 vgsvcWinSetStatus(SERVICE_STOP_PENDING, 0);
572
573 int rc2 = VGSvcStopServices();
574 if (RT_FAILURE(rc2))
575 rcRet = ERROR_GEN_FAILURE;
576 else
577 {
578 rc2 = VGSvcReportStatus(VBoxGuestFacilityStatus_Terminated);
579 AssertRC(rc2);
580 }
581
582 vgsvcWinSetStatus(SERVICE_STOPPED, 0);
583 break;
584 }
585
586 default:
587 VGSvcVerbose(1, "Control handler: Function not implemented: %#x\n", dwControl);
588 rcRet = ERROR_CALL_NOT_IMPLEMENTED;
589 break;
590 }
591
592 return rcRet;
593}
594
595
596/**
597 * Callback registered by RegisterServiceCtrlHandler on NT4 and earlier.
598 */
599static VOID WINAPI vgsvcWinCtrlHandlerNt4(DWORD dwControl) RT_NOTHROW_DEF
600{
601 VGSvcVerbose(2, "Control handler (NT4): dwControl=%#x\n", dwControl);
602 vgsvcWinCtrlHandlerCommon(dwControl);
603}
604
605
606/**
607 * Callback registered by RegisterServiceCtrlHandler on NT5 and later.
608 */
609static DWORD WINAPI
610vgsvcWinCtrlHandlerNt5Plus(DWORD dwControl, DWORD dwEventType, LPVOID lpEventData, LPVOID lpContext) RT_NOTHROW_DEF
611{
612 VGSvcVerbose(2, "Control handler: dwControl=%#x, dwEventType=%#x\n", dwControl, dwEventType);
613 RT_NOREF1(lpContext);
614
615 switch (dwControl)
616 {
617 default:
618 return vgsvcWinCtrlHandlerCommon(dwControl);
619
620 case SERVICE_CONTROL_SESSIONCHANGE: /* Only Windows 2000 and up. */
621 {
622 AssertPtr(lpEventData);
623 PWTSSESSION_NOTIFICATION pNotify = (PWTSSESSION_NOTIFICATION)lpEventData;
624 Assert(pNotify->cbSize == sizeof(WTSSESSION_NOTIFICATION));
625
626 VGSvcVerbose(1, "Control handler: %s (Session=%ld, Event=%#x)\n",
627 vgsvcWTSStateToString(dwEventType), pNotify->dwSessionId, dwEventType);
628
629 /* Handle all events, regardless of dwEventType. */
630 int rc2 = VGSvcVMInfoSignal();
631 AssertRC(rc2);
632
633 return NO_ERROR;
634 }
635 }
636}
637
638
639static void WINAPI vgsvcWinMain(DWORD argc, LPTSTR *argv)
640{
641 RT_NOREF2(argc, argv);
642 VGSvcVerbose(2, "Registering service control handler ...\n");
643 if (g_pfnRegisterServiceCtrlHandlerExA)
644 g_hWinServiceStatus = g_pfnRegisterServiceCtrlHandlerExA(VBOXSERVICE_NAME, vgsvcWinCtrlHandlerNt5Plus, NULL);
645 else
646 g_hWinServiceStatus = RegisterServiceCtrlHandlerA(VBOXSERVICE_NAME, vgsvcWinCtrlHandlerNt4);
647 if (g_hWinServiceStatus != NULL)
648 {
649 VGSvcVerbose(2, "Service control handler registered.\n");
650 vgsvcWinStart();
651 }
652 else
653 {
654 DWORD dwErr = GetLastError();
655 switch (dwErr)
656 {
657 case ERROR_INVALID_NAME:
658 VGSvcError("Invalid service name!\n");
659 break;
660 case ERROR_SERVICE_DOES_NOT_EXIST:
661 VGSvcError("Service does not exist!\n");
662 break;
663 default:
664 VGSvcError("Could not register service control handle! Error: %ld\n", dwErr);
665 break;
666 }
667 }
668}
669
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use