1 | /* $Id: VBoxAutostart-win.cpp 93115 2022-01-01 11:31:46Z vboxsync $ */
|
---|
2 | /** @file
|
---|
3 | * VirtualBox Autostart Service - Windows Specific Code.
|
---|
4 | */
|
---|
5 |
|
---|
6 | /*
|
---|
7 | * Copyright (C) 2012-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 <iprt/win/windows.h>
|
---|
23 | #include <tchar.h>
|
---|
24 |
|
---|
25 | #define SECURITY_WIN32
|
---|
26 | #include <Security.h>
|
---|
27 |
|
---|
28 | #include <VBox/com/array.h>
|
---|
29 | #include <VBox/com/com.h>
|
---|
30 | #include <VBox/com/ErrorInfo.h>
|
---|
31 | #include <VBox/com/errorprint.h>
|
---|
32 | #include <VBox/com/Guid.h>
|
---|
33 | #include <VBox/com/listeners.h>
|
---|
34 | #include <VBox/com/NativeEventQueue.h>
|
---|
35 | #include <VBox/com/string.h>
|
---|
36 | #include <VBox/com/VirtualBox.h>
|
---|
37 |
|
---|
38 | #include <VBox/log.h>
|
---|
39 | #include <VBox/version.h>
|
---|
40 |
|
---|
41 | #include <iprt/dir.h>
|
---|
42 | #include <iprt/env.h>
|
---|
43 | #include <iprt/errcore.h>
|
---|
44 | #include <iprt/getopt.h>
|
---|
45 | #include <iprt/initterm.h>
|
---|
46 | #include <iprt/mem.h>
|
---|
47 | #include <iprt/message.h>
|
---|
48 | #include <iprt/process.h>
|
---|
49 | #include <iprt/path.h>
|
---|
50 | #include <iprt/semaphore.h>
|
---|
51 | #include <iprt/stream.h>
|
---|
52 | #include <iprt/string.h>
|
---|
53 | #include <iprt/thread.h>
|
---|
54 |
|
---|
55 | #include "VBoxAutostart.h"
|
---|
56 | #include "PasswordInput.h"
|
---|
57 |
|
---|
58 |
|
---|
59 | /*********************************************************************************************************************************
|
---|
60 | * Defined Constants And Macros *
|
---|
61 | *********************************************************************************************************************************/
|
---|
62 | /** The service name. */
|
---|
63 | #define AUTOSTART_SERVICE_NAME "VBoxAutostartSvc"
|
---|
64 | /** The service display name. */
|
---|
65 | #define AUTOSTART_SERVICE_DISPLAY_NAME "VirtualBox Autostart Service"
|
---|
66 |
|
---|
67 | ComPtr<IVirtualBoxClient> g_pVirtualBoxClient = NULL;
|
---|
68 | bool g_fVerbose = false;
|
---|
69 | ComPtr<IVirtualBox> g_pVirtualBox = NULL;
|
---|
70 | ComPtr<ISession> g_pSession = NULL;
|
---|
71 |
|
---|
72 |
|
---|
73 | /*********************************************************************************************************************************
|
---|
74 | * Global Variables *
|
---|
75 | *********************************************************************************************************************************/
|
---|
76 | /** The service control handler handle. */
|
---|
77 | static SERVICE_STATUS_HANDLE g_hSupSvcWinCtrlHandler = NULL;
|
---|
78 | /** The service status. */
|
---|
79 | static uint32_t volatile g_u32SupSvcWinStatus = SERVICE_STOPPED;
|
---|
80 | /** The semaphore the main service thread is waiting on in autostartSvcWinServiceMain. */
|
---|
81 | static RTSEMEVENTMULTI g_hSupSvcWinEvent = NIL_RTSEMEVENTMULTI;
|
---|
82 | /** The service name is used for send to service main. */
|
---|
83 | static com::Bstr g_bstrServiceName;
|
---|
84 |
|
---|
85 | /** Logging parameters. */
|
---|
86 | static uint32_t g_cHistory = 10; /* Enable log rotation, 10 files. */
|
---|
87 | static uint32_t g_uHistoryFileTime = 0; /* No time limit, it's very low volume. */
|
---|
88 | static uint64_t g_uHistoryFileSize = 100 * _1M; /* Max 100MB per file. */
|
---|
89 |
|
---|
90 |
|
---|
91 | /*********************************************************************************************************************************
|
---|
92 | * Internal Functions *
|
---|
93 | *********************************************************************************************************************************/
|
---|
94 | static SC_HANDLE autostartSvcWinOpenSCManager(const char *pszAction, DWORD dwAccess);
|
---|
95 |
|
---|
96 | static int autostartGetProcessDomainUser(com::Utf8Str &aUser)
|
---|
97 | {
|
---|
98 | int rc = VERR_NOT_SUPPORTED;
|
---|
99 |
|
---|
100 | RTUTF16 wszUsername[1024] = { 0 };
|
---|
101 | ULONG cwcUsername = RT_ELEMENTS(wszUsername);
|
---|
102 | char *pszUser = NULL;
|
---|
103 | if (!GetUserNameExW(NameSamCompatible, &wszUsername[0], &cwcUsername))
|
---|
104 | return RTErrConvertFromWin32(GetLastError());
|
---|
105 | rc = RTUtf16ToUtf8(wszUsername, &pszUser);
|
---|
106 | aUser = pszUser;
|
---|
107 | aUser.toLower();
|
---|
108 | RTStrFree(pszUser);
|
---|
109 | return rc;
|
---|
110 | }
|
---|
111 |
|
---|
112 | static int autostartGetLocalDomain(com::Utf8Str &aDomain)
|
---|
113 | {
|
---|
114 | RTUTF16 pwszDomain[MAX_COMPUTERNAME_LENGTH + 1] = { 0 };
|
---|
115 | uint32_t cwcDomainSize = MAX_COMPUTERNAME_LENGTH + 1;
|
---|
116 | if (!GetComputerNameW(pwszDomain, (LPDWORD)&cwcDomainSize))
|
---|
117 | return RTErrConvertFromWin32(GetLastError());
|
---|
118 | char *pszDomain = NULL;
|
---|
119 | int rc = RTUtf16ToUtf8(pwszDomain, &pszDomain);
|
---|
120 | aDomain = pszDomain;
|
---|
121 | aDomain.toLower();
|
---|
122 | RTStrFree(pszDomain);
|
---|
123 | return rc;
|
---|
124 | }
|
---|
125 |
|
---|
126 | static int autostartGetDomainAndUser(const com::Utf8Str &aDomainAndUser, com::Utf8Str &aDomain, com::Utf8Str &aUser)
|
---|
127 | {
|
---|
128 | size_t offDelim = aDomainAndUser.find("\\");
|
---|
129 | if (offDelim != aDomainAndUser.npos)
|
---|
130 | {
|
---|
131 | // if only domain is specified
|
---|
132 | if (aDomainAndUser.length() - offDelim == 1)
|
---|
133 | return VERR_INVALID_PARAMETER;
|
---|
134 |
|
---|
135 | if (offDelim == 1 && aDomainAndUser[0] == '.')
|
---|
136 | {
|
---|
137 | int rc = autostartGetLocalDomain(aDomain);
|
---|
138 | aUser = aDomainAndUser.substr(offDelim + 1);
|
---|
139 | return rc;
|
---|
140 | }
|
---|
141 | aDomain = aDomainAndUser.substr(0, offDelim);
|
---|
142 | aUser = aDomainAndUser.substr(offDelim + 1);
|
---|
143 | aDomain.toLower();
|
---|
144 | aUser.toLower();
|
---|
145 | return VINF_SUCCESS;
|
---|
146 | }
|
---|
147 |
|
---|
148 | offDelim = aDomainAndUser.find("@");
|
---|
149 | if (offDelim != aDomainAndUser.npos)
|
---|
150 | {
|
---|
151 | // if only domain is specified
|
---|
152 | if (offDelim == 0)
|
---|
153 | return VERR_INVALID_PARAMETER;
|
---|
154 |
|
---|
155 | // with '@' but without domain
|
---|
156 | if (aDomainAndUser.length() - offDelim == 1)
|
---|
157 | {
|
---|
158 | int rc = autostartGetLocalDomain(aDomain);
|
---|
159 | aUser = aDomainAndUser.substr(0, offDelim);
|
---|
160 | return rc;
|
---|
161 | }
|
---|
162 | aDomain = aDomainAndUser.substr(offDelim + 1);
|
---|
163 | aUser = aDomainAndUser.substr(0, offDelim);
|
---|
164 | aDomain.toLower();
|
---|
165 | aUser.toLower();
|
---|
166 | return VINF_SUCCESS;
|
---|
167 | }
|
---|
168 |
|
---|
169 | // only user is specified
|
---|
170 | int rc = autostartGetLocalDomain(aDomain);
|
---|
171 | aUser = aDomainAndUser;
|
---|
172 | aDomain.toLower();
|
---|
173 | aUser.toLower();
|
---|
174 | return rc;
|
---|
175 | }
|
---|
176 |
|
---|
177 | /** Common helper for formatting the service name. */
|
---|
178 | static void autostartFormatServiceName(const com::Utf8Str &aDomain, const com::Utf8Str &aUser, com::Utf8Str &aServiceName)
|
---|
179 | {
|
---|
180 | aServiceName.printf("%s%s%s", AUTOSTART_SERVICE_NAME, aDomain.c_str(), aUser.c_str());
|
---|
181 | }
|
---|
182 |
|
---|
183 | /** Used by the delete service operation. */
|
---|
184 | static int autostartGetServiceName(const com::Utf8Str &aDomainAndUser, com::Utf8Str &aServiceName)
|
---|
185 | {
|
---|
186 | com::Utf8Str sDomain;
|
---|
187 | com::Utf8Str sUser;
|
---|
188 | int rc = autostartGetDomainAndUser(aDomainAndUser, sDomain, sUser);
|
---|
189 | if (RT_FAILURE(rc))
|
---|
190 | return rc;
|
---|
191 | autostartFormatServiceName(sDomain, sUser, aServiceName);
|
---|
192 | return VINF_SUCCESS;
|
---|
193 | }
|
---|
194 |
|
---|
195 | /**
|
---|
196 | * Print out progress on the console.
|
---|
197 | *
|
---|
198 | * This runs the main event queue every now and then to prevent piling up
|
---|
199 | * unhandled things (which doesn't cause real problems, just makes things
|
---|
200 | * react a little slower than in the ideal case).
|
---|
201 | */
|
---|
202 | DECLHIDDEN(HRESULT) showProgress(ComPtr<IProgress> progress)
|
---|
203 | {
|
---|
204 | using namespace com;
|
---|
205 |
|
---|
206 | BOOL fCompleted = FALSE;
|
---|
207 | ULONG uCurrentPercent = 0;
|
---|
208 | Bstr bstrOperationDescription;
|
---|
209 |
|
---|
210 | NativeEventQueue::getMainEventQueue()->processEventQueue(0);
|
---|
211 |
|
---|
212 | ULONG cOperations = 1;
|
---|
213 | HRESULT hrc = progress->COMGETTER(OperationCount)(&cOperations);
|
---|
214 | if (FAILED(hrc))
|
---|
215 | return hrc;
|
---|
216 |
|
---|
217 | /* setup signal handling if cancelable */
|
---|
218 | bool fCanceledAlready = false;
|
---|
219 | BOOL fCancelable;
|
---|
220 | hrc = progress->COMGETTER(Cancelable)(&fCancelable);
|
---|
221 | if (FAILED(hrc))
|
---|
222 | fCancelable = FALSE;
|
---|
223 |
|
---|
224 | hrc = progress->COMGETTER(Completed(&fCompleted));
|
---|
225 | while (SUCCEEDED(hrc))
|
---|
226 | {
|
---|
227 | progress->COMGETTER(Percent(&uCurrentPercent));
|
---|
228 |
|
---|
229 | if (fCompleted)
|
---|
230 | break;
|
---|
231 |
|
---|
232 | /* process async cancelation */
|
---|
233 | if (!fCanceledAlready)
|
---|
234 | {
|
---|
235 | hrc = progress->Cancel();
|
---|
236 | if (SUCCEEDED(hrc))
|
---|
237 | fCanceledAlready = true;
|
---|
238 | }
|
---|
239 |
|
---|
240 | /* make sure the loop is not too tight */
|
---|
241 | progress->WaitForCompletion(100);
|
---|
242 |
|
---|
243 | NativeEventQueue::getMainEventQueue()->processEventQueue(0);
|
---|
244 | hrc = progress->COMGETTER(Completed(&fCompleted));
|
---|
245 | }
|
---|
246 |
|
---|
247 | /* complete the line. */
|
---|
248 | LONG iRc = E_FAIL;
|
---|
249 | hrc = progress->COMGETTER(ResultCode)(&iRc);
|
---|
250 | if (SUCCEEDED(hrc))
|
---|
251 | {
|
---|
252 | hrc = iRc;
|
---|
253 | }
|
---|
254 |
|
---|
255 | return hrc;
|
---|
256 | }
|
---|
257 |
|
---|
258 | DECLHIDDEN(void) autostartSvcOsLogStr(const char *pszMsg, AUTOSTARTLOGTYPE enmLogType)
|
---|
259 | {
|
---|
260 | /* write it to the release log too */
|
---|
261 | LogRel(("%s", pszMsg));
|
---|
262 |
|
---|
263 | HANDLE hEventLog = RegisterEventSourceA(NULL /* local computer */, "VBoxAutostartSvc");
|
---|
264 | AssertReturnVoid(hEventLog != NULL);
|
---|
265 | WORD wType = 0;
|
---|
266 | const char *apsz[2];
|
---|
267 | apsz[0] = "VBoxAutostartSvc";
|
---|
268 | apsz[1] = pszMsg;
|
---|
269 |
|
---|
270 | switch (enmLogType)
|
---|
271 | {
|
---|
272 | case AUTOSTARTLOGTYPE_INFO:
|
---|
273 | wType = 0;
|
---|
274 | break;
|
---|
275 | case AUTOSTARTLOGTYPE_ERROR:
|
---|
276 | wType = EVENTLOG_ERROR_TYPE;
|
---|
277 | break;
|
---|
278 | case AUTOSTARTLOGTYPE_WARNING:
|
---|
279 | wType = EVENTLOG_WARNING_TYPE;
|
---|
280 | break;
|
---|
281 | case AUTOSTARTLOGTYPE_VERBOSE:
|
---|
282 | if (!g_fVerbose)
|
---|
283 | return;
|
---|
284 | wType = EVENTLOG_INFORMATION_TYPE;
|
---|
285 | break;
|
---|
286 | default:
|
---|
287 | AssertMsgFailed(("Invalid log type %d\n", enmLogType));
|
---|
288 | }
|
---|
289 |
|
---|
290 | BOOL fRc = ReportEventA(hEventLog, /* hEventLog */
|
---|
291 | wType, /* wType */
|
---|
292 | 0, /* wCategory */
|
---|
293 | 0 /** @todo mc */, /* dwEventID */
|
---|
294 | NULL, /* lpUserSid */
|
---|
295 | RT_ELEMENTS(apsz), /* wNumStrings */
|
---|
296 | 0, /* dwDataSize */
|
---|
297 | apsz, /* lpStrings */
|
---|
298 | NULL); /* lpRawData */
|
---|
299 | AssertMsg(fRc, ("%u\n", GetLastError())); NOREF(fRc);
|
---|
300 | DeregisterEventSource(hEventLog);
|
---|
301 | }
|
---|
302 |
|
---|
303 | /**
|
---|
304 | * Opens the service control manager.
|
---|
305 | *
|
---|
306 | * When this fails, an error message will be displayed.
|
---|
307 | *
|
---|
308 | * @returns Valid handle on success.
|
---|
309 | * NULL on failure, will display an error message.
|
---|
310 | *
|
---|
311 | * @param pszAction The action which is requesting access to SCM.
|
---|
312 | * @param dwAccess The desired access.
|
---|
313 | */
|
---|
314 | static SC_HANDLE autostartSvcWinOpenSCManager(const char *pszAction, DWORD dwAccess)
|
---|
315 | {
|
---|
316 | SC_HANDLE hSCM = OpenSCManager(NULL /* lpMachineName*/, NULL /* lpDatabaseName */, dwAccess);
|
---|
317 | if (hSCM == NULL)
|
---|
318 | {
|
---|
319 | DWORD err = GetLastError();
|
---|
320 | switch (err)
|
---|
321 | {
|
---|
322 | case ERROR_ACCESS_DENIED:
|
---|
323 | autostartSvcDisplayError("%s - OpenSCManager failure: access denied\n", pszAction);
|
---|
324 | break;
|
---|
325 | default:
|
---|
326 | autostartSvcDisplayError("%s - OpenSCManager failure: %d\n", pszAction, err);
|
---|
327 | break;
|
---|
328 | }
|
---|
329 | }
|
---|
330 | return hSCM;
|
---|
331 | }
|
---|
332 |
|
---|
333 |
|
---|
334 | /**
|
---|
335 | * Opens the service.
|
---|
336 | *
|
---|
337 | * Last error is preserved on failure and set to 0 on success.
|
---|
338 | *
|
---|
339 | * @returns Valid service handle on success.
|
---|
340 | * NULL on failure, will display an error message unless it's ignored.
|
---|
341 | *
|
---|
342 | * @param pszAction The action which is requesting access to the service.
|
---|
343 | * @param dwSCMAccess The service control manager access.
|
---|
344 | * @param dwSVCAccess The desired service access.
|
---|
345 | * @param cIgnoredErrors The number of ignored errors.
|
---|
346 | * @param ... Errors codes that should not cause a message to be displayed.
|
---|
347 | */
|
---|
348 | static SC_HANDLE autostartSvcWinOpenService(const PRTUTF16 pwszServiceName, const char *pszAction, DWORD dwSCMAccess, DWORD dwSVCAccess,
|
---|
349 | unsigned cIgnoredErrors, ...)
|
---|
350 | {
|
---|
351 | SC_HANDLE hSCM = autostartSvcWinOpenSCManager(pszAction, dwSCMAccess);
|
---|
352 | if (!hSCM)
|
---|
353 | return NULL;
|
---|
354 |
|
---|
355 | SC_HANDLE hSvc = OpenServiceW(hSCM, pwszServiceName, dwSVCAccess);
|
---|
356 | if (hSvc)
|
---|
357 | {
|
---|
358 | CloseServiceHandle(hSCM);
|
---|
359 | SetLastError(0);
|
---|
360 | }
|
---|
361 | else
|
---|
362 | {
|
---|
363 | DWORD err = GetLastError();
|
---|
364 | bool fIgnored = false;
|
---|
365 | va_list va;
|
---|
366 | va_start(va, cIgnoredErrors);
|
---|
367 | while (!fIgnored && cIgnoredErrors-- > 0)
|
---|
368 | fIgnored = (DWORD)va_arg(va, int) == err;
|
---|
369 | va_end(va);
|
---|
370 | if (!fIgnored)
|
---|
371 | {
|
---|
372 | switch (err)
|
---|
373 | {
|
---|
374 | case ERROR_ACCESS_DENIED:
|
---|
375 | autostartSvcDisplayError("%s - OpenService failure: access denied\n", pszAction);
|
---|
376 | break;
|
---|
377 | case ERROR_SERVICE_DOES_NOT_EXIST:
|
---|
378 | autostartSvcDisplayError("%s - OpenService failure: The service %ls does not exist. Reinstall it.\n",
|
---|
379 | pszAction, pwszServiceName);
|
---|
380 | break;
|
---|
381 | default:
|
---|
382 | autostartSvcDisplayError("%s - OpenService failure: %d\n", pszAction, err);
|
---|
383 | break;
|
---|
384 | }
|
---|
385 | }
|
---|
386 |
|
---|
387 | CloseServiceHandle(hSCM);
|
---|
388 | SetLastError(err);
|
---|
389 | }
|
---|
390 | return hSvc;
|
---|
391 | }
|
---|
392 |
|
---|
393 | static RTEXITCODE autostartSvcWinInterrogate(int argc, char **argv)
|
---|
394 | {
|
---|
395 | RT_NOREF(argc, argv);
|
---|
396 | RTPrintf("VBoxAutostartSvc: The \"interrogate\" action is not implemented.\n");
|
---|
397 | return RTEXITCODE_FAILURE;
|
---|
398 | }
|
---|
399 |
|
---|
400 |
|
---|
401 | static RTEXITCODE autostartSvcWinStop(int argc, char **argv)
|
---|
402 | {
|
---|
403 | RT_NOREF(argc, argv);
|
---|
404 | RTPrintf("VBoxAutostartSvc: The \"stop\" action is not implemented.\n");
|
---|
405 | return RTEXITCODE_FAILURE;
|
---|
406 | }
|
---|
407 |
|
---|
408 |
|
---|
409 | static RTEXITCODE autostartSvcWinContinue(int argc, char **argv)
|
---|
410 | {
|
---|
411 | RT_NOREF(argc, argv);
|
---|
412 | RTPrintf("VBoxAutostartSvc: The \"continue\" action is not implemented.\n");
|
---|
413 | return RTEXITCODE_FAILURE;
|
---|
414 | }
|
---|
415 |
|
---|
416 |
|
---|
417 | static RTEXITCODE autostartSvcWinPause(int argc, char **argv)
|
---|
418 | {
|
---|
419 | RT_NOREF(argc, argv);
|
---|
420 | RTPrintf("VBoxAutostartSvc: The \"pause\" action is not implemented.\n");
|
---|
421 | return RTEXITCODE_FAILURE;
|
---|
422 | }
|
---|
423 |
|
---|
424 |
|
---|
425 | static RTEXITCODE autostartSvcWinStart(int argc, char **argv)
|
---|
426 | {
|
---|
427 | RT_NOREF(argc, argv);
|
---|
428 | RTPrintf("VBoxAutostartSvc: The \"start\" action is not implemented.\n");
|
---|
429 | return RTEXITCODE_SUCCESS;
|
---|
430 | }
|
---|
431 |
|
---|
432 |
|
---|
433 | static RTEXITCODE autostartSvcWinQueryDescription(int argc, char **argv)
|
---|
434 | {
|
---|
435 | RT_NOREF(argc, argv);
|
---|
436 | RTPrintf("VBoxAutostartSvc: The \"qdescription\" action is not implemented.\n");
|
---|
437 | return RTEXITCODE_FAILURE;
|
---|
438 | }
|
---|
439 |
|
---|
440 |
|
---|
441 | static RTEXITCODE autostartSvcWinQueryConfig(int argc, char **argv)
|
---|
442 | {
|
---|
443 | RT_NOREF(argc, argv);
|
---|
444 | RTPrintf("VBoxAutostartSvc: The \"qconfig\" action is not implemented.\n");
|
---|
445 | return RTEXITCODE_FAILURE;
|
---|
446 | }
|
---|
447 |
|
---|
448 |
|
---|
449 | static RTEXITCODE autostartSvcWinDisable(int argc, char **argv)
|
---|
450 | {
|
---|
451 | RT_NOREF(argc, argv);
|
---|
452 | RTPrintf("VBoxAutostartSvc: The \"disable\" action is not implemented.\n");
|
---|
453 | return RTEXITCODE_FAILURE;
|
---|
454 | }
|
---|
455 |
|
---|
456 | static RTEXITCODE autostartSvcWinEnable(int argc, char **argv)
|
---|
457 | {
|
---|
458 | RT_NOREF(argc, argv);
|
---|
459 | RTPrintf("VBoxAutostartSvc: The \"enable\" action is not implemented.\n");
|
---|
460 | return RTEXITCODE_FAILURE;
|
---|
461 | }
|
---|
462 |
|
---|
463 |
|
---|
464 | /**
|
---|
465 | * Handle the 'delete' action.
|
---|
466 | *
|
---|
467 | * @returns RTEXITCODE_SUCCESS or RTEXITCODE_FAILURE.
|
---|
468 | * @param argc The action argument count.
|
---|
469 | * @param argv The action argument vector.
|
---|
470 | */
|
---|
471 | static int autostartSvcWinDelete(int argc, char **argv)
|
---|
472 | {
|
---|
473 | /*
|
---|
474 | * Parse the arguments.
|
---|
475 | */
|
---|
476 | bool fVerbose = false;
|
---|
477 | const char *pszUser = NULL;
|
---|
478 | static const RTGETOPTDEF s_aOptions[] =
|
---|
479 | {
|
---|
480 | { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
|
---|
481 | { "--user", 'u', RTGETOPT_REQ_STRING },
|
---|
482 | };
|
---|
483 | int ch;
|
---|
484 | RTGETOPTUNION Value;
|
---|
485 | RTGETOPTSTATE GetState;
|
---|
486 | RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
|
---|
487 | while ((ch = RTGetOpt(&GetState, &Value)))
|
---|
488 | {
|
---|
489 | switch (ch)
|
---|
490 | {
|
---|
491 | case 'v':
|
---|
492 | fVerbose = true;
|
---|
493 | break;
|
---|
494 | case 'u':
|
---|
495 | pszUser = Value.psz;
|
---|
496 | break;
|
---|
497 | default:
|
---|
498 | return autostartSvcDisplayGetOptError("delete", ch, &Value);
|
---|
499 | }
|
---|
500 | }
|
---|
501 |
|
---|
502 | if (!pszUser)
|
---|
503 | return autostartSvcDisplayError("delete - DeleteService failed, user name required.\n");
|
---|
504 |
|
---|
505 | com::Utf8Str sServiceName;
|
---|
506 | int vrc = autostartGetServiceName(pszUser, sServiceName);
|
---|
507 | if (RT_FAILURE(vrc))
|
---|
508 | return autostartSvcDisplayError("delete - DeleteService failed, service name for user %s can not be constructed.\n",
|
---|
509 | pszUser);
|
---|
510 | /*
|
---|
511 | * Create the service.
|
---|
512 | */
|
---|
513 | RTEXITCODE rc = RTEXITCODE_FAILURE;
|
---|
514 | SC_HANDLE hSvc = autostartSvcWinOpenService(com::Bstr(sServiceName).raw(), "delete", SERVICE_CHANGE_CONFIG, DELETE,
|
---|
515 | 1, ERROR_SERVICE_DOES_NOT_EXIST);
|
---|
516 | if (hSvc)
|
---|
517 | {
|
---|
518 | if (DeleteService(hSvc))
|
---|
519 | {
|
---|
520 | RTPrintf("Successfully deleted the %s service.\n", sServiceName.c_str());
|
---|
521 | rc = RTEXITCODE_SUCCESS;
|
---|
522 | }
|
---|
523 | else
|
---|
524 | autostartSvcDisplayError("delete - DeleteService failed, err=%d.\n", GetLastError());
|
---|
525 | CloseServiceHandle(hSvc);
|
---|
526 | }
|
---|
527 | else if (GetLastError() == ERROR_SERVICE_DOES_NOT_EXIST)
|
---|
528 | {
|
---|
529 |
|
---|
530 | if (fVerbose)
|
---|
531 | RTPrintf("The service %s was not installed, nothing to be done.", sServiceName.c_str());
|
---|
532 | else
|
---|
533 | RTPrintf("Successfully deleted the %s service.\n", sServiceName.c_str());
|
---|
534 | rc = RTEXITCODE_SUCCESS;
|
---|
535 | }
|
---|
536 | return rc;
|
---|
537 | }
|
---|
538 |
|
---|
539 |
|
---|
540 | /**
|
---|
541 | * Handle the 'create' action.
|
---|
542 | *
|
---|
543 | * @returns 0 or 1.
|
---|
544 | * @param argc The action argument count.
|
---|
545 | * @param argv The action argument vector.
|
---|
546 | */
|
---|
547 | static RTEXITCODE autostartSvcWinCreate(int argc, char **argv)
|
---|
548 | {
|
---|
549 | /*
|
---|
550 | * Parse the arguments.
|
---|
551 | */
|
---|
552 | bool fVerbose = false;
|
---|
553 | const char *pszUser = NULL;
|
---|
554 | com::Utf8Str strPwd;
|
---|
555 | const char *pszPwdFile = NULL;
|
---|
556 | static const RTGETOPTDEF s_aOptions[] =
|
---|
557 | {
|
---|
558 | { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
|
---|
559 | { "--user", 'u', RTGETOPT_REQ_STRING },
|
---|
560 | { "--password-file", 'p', RTGETOPT_REQ_STRING }
|
---|
561 | };
|
---|
562 | int ch;
|
---|
563 | RTGETOPTUNION Value;
|
---|
564 | RTGETOPTSTATE GetState;
|
---|
565 | RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
|
---|
566 | while ((ch = RTGetOpt(&GetState, &Value)))
|
---|
567 | {
|
---|
568 | switch (ch)
|
---|
569 | {
|
---|
570 | case 'v':
|
---|
571 | fVerbose = true;
|
---|
572 | break;
|
---|
573 | case 'u':
|
---|
574 | pszUser = Value.psz;
|
---|
575 | break;
|
---|
576 | case 'p':
|
---|
577 | pszPwdFile = Value.psz;
|
---|
578 | break;
|
---|
579 | default:
|
---|
580 | return autostartSvcDisplayGetOptError("create", ch, &Value);
|
---|
581 | }
|
---|
582 | }
|
---|
583 |
|
---|
584 | if (!pszUser)
|
---|
585 | return autostartSvcDisplayError("Username is missing");
|
---|
586 |
|
---|
587 | if (pszPwdFile)
|
---|
588 | {
|
---|
589 | /* Get password from file. */
|
---|
590 | RTEXITCODE rcExit = readPasswordFile(pszPwdFile, &strPwd);
|
---|
591 | if (rcExit == RTEXITCODE_FAILURE)
|
---|
592 | return rcExit;
|
---|
593 | }
|
---|
594 | else
|
---|
595 | {
|
---|
596 | /* Get password from console. */
|
---|
597 | RTEXITCODE rcExit = readPasswordFromConsole(&strPwd, "Enter password:");
|
---|
598 | if (rcExit == RTEXITCODE_FAILURE)
|
---|
599 | return rcExit;
|
---|
600 | }
|
---|
601 |
|
---|
602 | if (strPwd.isEmpty())
|
---|
603 | return autostartSvcDisplayError("Password is missing");
|
---|
604 |
|
---|
605 | com::Utf8Str sDomain;
|
---|
606 | com::Utf8Str sUserTmp;
|
---|
607 | int vrc = autostartGetDomainAndUser(pszUser, sDomain, sUserTmp);
|
---|
608 | if (RT_FAILURE(vrc))
|
---|
609 | return autostartSvcDisplayError("create - CreateService failed, failed to get domain and user from string %s (%d).\n",
|
---|
610 | pszUser, vrc);
|
---|
611 | com::Utf8StrFmt sUserFullName("%s\\%s", sDomain.c_str(), sUserTmp.c_str());
|
---|
612 | com::Utf8StrFmt sDisplayName("%s %s@%s", AUTOSTART_SERVICE_DISPLAY_NAME, sUserTmp.c_str(), sDomain.c_str());
|
---|
613 | com::Utf8Str sServiceName;
|
---|
614 | autostartFormatServiceName(sDomain, sUserTmp, sServiceName);
|
---|
615 |
|
---|
616 | /*
|
---|
617 | * Create the service.
|
---|
618 | */
|
---|
619 | RTEXITCODE rc = RTEXITCODE_FAILURE;
|
---|
620 | SC_HANDLE hSCM = autostartSvcWinOpenSCManager("create", SC_MANAGER_CREATE_SERVICE); /*SC_MANAGER_ALL_ACCESS*/
|
---|
621 | if (hSCM)
|
---|
622 | {
|
---|
623 | char szExecPath[RTPATH_MAX];
|
---|
624 | if (RTProcGetExecutablePath(szExecPath, sizeof(szExecPath)))
|
---|
625 | {
|
---|
626 | if (fVerbose)
|
---|
627 | RTPrintf("Creating the %s service, binary \"%s\"...\n",
|
---|
628 | sServiceName.c_str(), szExecPath); /* yea, the binary name isn't UTF-8, but wtf. */
|
---|
629 |
|
---|
630 | /*
|
---|
631 | * Add service name as command line parameter for the service
|
---|
632 | */
|
---|
633 | com::Utf8StrFmt sCmdLine("\"%s\" --service=%s", szExecPath, sServiceName.c_str());
|
---|
634 | com::Bstr bstrServiceName(sServiceName);
|
---|
635 | com::Bstr bstrDisplayName(sDisplayName);
|
---|
636 | com::Bstr bstrCmdLine(sCmdLine);
|
---|
637 | com::Bstr bstrUserFullName(sUserFullName);
|
---|
638 | com::Bstr bstrPwd(strPwd);
|
---|
639 | com::Bstr bstrDependencies("Winmgmt\0RpcSs\0\0");
|
---|
640 |
|
---|
641 | SC_HANDLE hSvc = CreateServiceW(hSCM, /* hSCManager */
|
---|
642 | bstrServiceName.raw(), /* lpServiceName */
|
---|
643 | bstrDisplayName.raw(), /* lpDisplayName */
|
---|
644 | SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG, /* dwDesiredAccess */
|
---|
645 | SERVICE_WIN32_OWN_PROCESS, /* dwServiceType ( | SERVICE_INTERACTIVE_PROCESS? ) */
|
---|
646 | SERVICE_AUTO_START, /* dwStartType */
|
---|
647 | SERVICE_ERROR_NORMAL, /* dwErrorControl */
|
---|
648 | bstrCmdLine.raw(), /* lpBinaryPathName */
|
---|
649 | NULL, /* lpLoadOrderGroup */
|
---|
650 | NULL, /* lpdwTagId */
|
---|
651 | bstrDependencies.raw(), /* lpDependencies */
|
---|
652 | bstrUserFullName.raw(), /* lpServiceStartName (NULL => LocalSystem) */
|
---|
653 | bstrPwd.raw()); /* lpPassword */
|
---|
654 | if (hSvc)
|
---|
655 | {
|
---|
656 | RTPrintf("Successfully created the %s service.\n", sServiceName.c_str());
|
---|
657 | /** @todo Set the service description or it'll look weird in the vista service manager.
|
---|
658 | * Anything else that should be configured? Start access or something? */
|
---|
659 | rc = RTEXITCODE_SUCCESS;
|
---|
660 | CloseServiceHandle(hSvc);
|
---|
661 | }
|
---|
662 | else
|
---|
663 | {
|
---|
664 | DWORD err = GetLastError();
|
---|
665 | switch (err)
|
---|
666 | {
|
---|
667 | case ERROR_SERVICE_EXISTS:
|
---|
668 | autostartSvcDisplayError("create - The service already exists.\n");
|
---|
669 | break;
|
---|
670 | default:
|
---|
671 | autostartSvcDisplayError("create - CreateService failed, err=%d.\n", GetLastError());
|
---|
672 | break;
|
---|
673 | }
|
---|
674 | }
|
---|
675 | CloseServiceHandle(hSvc);
|
---|
676 | }
|
---|
677 | else
|
---|
678 | autostartSvcDisplayError("create - Failed to obtain the executable path: %d\n", GetLastError());
|
---|
679 | }
|
---|
680 | return rc;
|
---|
681 | }
|
---|
682 |
|
---|
683 |
|
---|
684 | /**
|
---|
685 | * Sets the service status, just a SetServiceStatus Wrapper.
|
---|
686 | *
|
---|
687 | * @returns See SetServiceStatus.
|
---|
688 | * @param dwStatus The current status.
|
---|
689 | * @param iWaitHint The wait hint, if < 0 then supply a default.
|
---|
690 | * @param dwExitCode The service exit code.
|
---|
691 | */
|
---|
692 | static bool autostartSvcWinSetServiceStatus(DWORD dwStatus, int iWaitHint, DWORD dwExitCode)
|
---|
693 | {
|
---|
694 | SERVICE_STATUS SvcStatus;
|
---|
695 | SvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
|
---|
696 | SvcStatus.dwWin32ExitCode = dwExitCode;
|
---|
697 | SvcStatus.dwServiceSpecificExitCode = 0;
|
---|
698 | SvcStatus.dwWaitHint = iWaitHint >= 0 ? iWaitHint : 3000;
|
---|
699 | SvcStatus.dwCurrentState = dwStatus;
|
---|
700 | LogFlow(("autostartSvcWinSetServiceStatus: %d -> %d\n", g_u32SupSvcWinStatus, dwStatus));
|
---|
701 | g_u32SupSvcWinStatus = dwStatus;
|
---|
702 | switch (dwStatus)
|
---|
703 | {
|
---|
704 | case SERVICE_START_PENDING:
|
---|
705 | SvcStatus.dwControlsAccepted = 0;
|
---|
706 | break;
|
---|
707 | default:
|
---|
708 | SvcStatus.dwControlsAccepted
|
---|
709 | = SERVICE_ACCEPT_STOP
|
---|
710 | | SERVICE_ACCEPT_SHUTDOWN;
|
---|
711 | break;
|
---|
712 | }
|
---|
713 |
|
---|
714 | static DWORD dwCheckPoint = 0;
|
---|
715 | switch (dwStatus)
|
---|
716 | {
|
---|
717 | case SERVICE_RUNNING:
|
---|
718 | case SERVICE_STOPPED:
|
---|
719 | SvcStatus.dwCheckPoint = 0;
|
---|
720 | default:
|
---|
721 | SvcStatus.dwCheckPoint = ++dwCheckPoint;
|
---|
722 | break;
|
---|
723 | }
|
---|
724 | return SetServiceStatus(g_hSupSvcWinCtrlHandler, &SvcStatus) != FALSE;
|
---|
725 | }
|
---|
726 |
|
---|
727 |
|
---|
728 | /**
|
---|
729 | * Service control handler (extended).
|
---|
730 | *
|
---|
731 | * @returns Windows status (see HandlerEx).
|
---|
732 | * @retval NO_ERROR if handled.
|
---|
733 | * @retval ERROR_CALL_NOT_IMPLEMENTED if not handled.
|
---|
734 | *
|
---|
735 | * @param dwControl The control code.
|
---|
736 | * @param dwEventType Event type. (specific to the control?)
|
---|
737 | * @param pvEventData Event data, specific to the event.
|
---|
738 | * @param pvContext The context pointer registered with the handler.
|
---|
739 | * Currently not used.
|
---|
740 | */
|
---|
741 | static DWORD WINAPI
|
---|
742 | autostartSvcWinServiceCtrlHandlerEx(DWORD dwControl, DWORD dwEventType, LPVOID pvEventData, LPVOID pvContext) RT_NOTHROW_DEF
|
---|
743 | {
|
---|
744 | RT_NOREF(dwEventType);
|
---|
745 | RT_NOREF(pvEventData);
|
---|
746 | RT_NOREF(pvContext);
|
---|
747 |
|
---|
748 | LogFlow(("autostartSvcWinServiceCtrlHandlerEx: dwControl=%#x dwEventType=%#x pvEventData=%p\n",
|
---|
749 | dwControl, dwEventType, pvEventData));
|
---|
750 |
|
---|
751 | switch (dwControl)
|
---|
752 | {
|
---|
753 | /*
|
---|
754 | * Interrogate the service about it's current status.
|
---|
755 | * MSDN says that this should just return NO_ERROR and does
|
---|
756 | * not need to set the status again.
|
---|
757 | */
|
---|
758 | case SERVICE_CONTROL_INTERROGATE:
|
---|
759 | return NO_ERROR;
|
---|
760 |
|
---|
761 | /*
|
---|
762 | * Request to stop the service.
|
---|
763 | */
|
---|
764 | case SERVICE_CONTROL_SHUTDOWN:
|
---|
765 | case SERVICE_CONTROL_STOP:
|
---|
766 | {
|
---|
767 | if (dwControl == SERVICE_CONTROL_SHUTDOWN)
|
---|
768 | LogRel(("SERVICE_CONTROL_SHUTDOWN\n"));
|
---|
769 | else
|
---|
770 | LogRel(("SERVICE_CONTROL_STOP\n"));
|
---|
771 |
|
---|
772 | /*
|
---|
773 | * Check if the real services can be stopped and then tell them to stop.
|
---|
774 | */
|
---|
775 | autostartSvcWinSetServiceStatus(SERVICE_STOP_PENDING, 3000, NO_ERROR);
|
---|
776 |
|
---|
777 | /*
|
---|
778 | * Notify the main thread that we're done, it will wait for the
|
---|
779 | * VMs to stop, and set the windows service status to SERVICE_STOPPED
|
---|
780 | * and return.
|
---|
781 | */
|
---|
782 | int rc = RTSemEventMultiSignal(g_hSupSvcWinEvent);
|
---|
783 | if (RT_FAILURE(rc))
|
---|
784 | autostartSvcLogError("SERVICE_CONTROL_STOP: RTSemEventMultiSignal failed, %Rrc\n", rc);
|
---|
785 |
|
---|
786 | return NO_ERROR;
|
---|
787 | }
|
---|
788 |
|
---|
789 | default:
|
---|
790 | /*
|
---|
791 | * We only expect to receive controls we explicitly listed
|
---|
792 | * in SERVICE_STATUS::dwControlsAccepted. Logged in hex
|
---|
793 | * b/c WinSvc.h defines them in hex
|
---|
794 | */
|
---|
795 | LogRel(("Unexpected service control message 0x%RX64\n",
|
---|
796 | (uint64_t)dwControl));
|
---|
797 | return ERROR_CALL_NOT_IMPLEMENTED;
|
---|
798 | }
|
---|
799 |
|
---|
800 | /* not reached */
|
---|
801 | }
|
---|
802 |
|
---|
803 | static RTEXITCODE autostartStartVMs()
|
---|
804 | {
|
---|
805 | int rc = autostartSetup();
|
---|
806 | if (RT_FAILURE(rc))
|
---|
807 | return RTEXITCODE_FAILURE;
|
---|
808 |
|
---|
809 | const char *pszConfigFile = RTEnvGet("VBOXAUTOSTART_CONFIG");
|
---|
810 | if (!pszConfigFile)
|
---|
811 | return autostartSvcLogError("Starting VMs failed. VBOXAUTOSTART_CONFIG environment variable is not defined.\n");
|
---|
812 | bool fAllow = false;
|
---|
813 |
|
---|
814 | PCFGAST pCfgAst = NULL;
|
---|
815 | rc = autostartParseConfig(pszConfigFile, &pCfgAst);
|
---|
816 | if (RT_FAILURE(rc))
|
---|
817 | return autostartSvcLogError("Starting VMs failed. Failed to parse the config file. Check the access permissions and file structure.\n");
|
---|
818 |
|
---|
819 | PCFGAST pCfgAstPolicy = autostartConfigAstGetByName(pCfgAst, "default_policy");
|
---|
820 | /* Check default policy. */
|
---|
821 | if (pCfgAstPolicy)
|
---|
822 | {
|
---|
823 | if ( pCfgAstPolicy->enmType == CFGASTNODETYPE_KEYVALUE
|
---|
824 | && ( !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "allow")
|
---|
825 | || !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "deny")))
|
---|
826 | {
|
---|
827 | if (!RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "allow"))
|
---|
828 | fAllow = true;
|
---|
829 | }
|
---|
830 | else
|
---|
831 | {
|
---|
832 | autostartConfigAstDestroy(pCfgAst);
|
---|
833 | return autostartSvcLogError("'default_policy' must be either 'allow' or 'deny'.\n");
|
---|
834 | }
|
---|
835 | }
|
---|
836 |
|
---|
837 | com::Utf8Str sUser;
|
---|
838 | rc = autostartGetProcessDomainUser(sUser);
|
---|
839 | if (RT_FAILURE(rc))
|
---|
840 | {
|
---|
841 | autostartConfigAstDestroy(pCfgAst);
|
---|
842 | return autostartSvcLogError("Failed to query username of the process (%Rrc).\n", rc);
|
---|
843 | }
|
---|
844 |
|
---|
845 | PCFGAST pCfgAstUser = NULL;
|
---|
846 | for (unsigned i = 0; i < pCfgAst->u.Compound.cAstNodes; i++)
|
---|
847 | {
|
---|
848 | PCFGAST pNode = pCfgAst->u.Compound.apAstNodes[i];
|
---|
849 | com::Utf8Str sDomain;
|
---|
850 | com::Utf8Str sUserTmp;
|
---|
851 | rc = autostartGetDomainAndUser(pNode->pszKey, sDomain, sUserTmp);
|
---|
852 | if (RT_FAILURE(rc))
|
---|
853 | continue;
|
---|
854 | com::Utf8StrFmt sDomainUser("%s\\%s", sDomain.c_str(), sUserTmp.c_str());
|
---|
855 | if (sDomainUser == sUser)
|
---|
856 | {
|
---|
857 | pCfgAstUser = pNode;
|
---|
858 | break;
|
---|
859 | }
|
---|
860 | }
|
---|
861 |
|
---|
862 | if ( pCfgAstUser
|
---|
863 | && pCfgAstUser->enmType == CFGASTNODETYPE_COMPOUND)
|
---|
864 | {
|
---|
865 | pCfgAstPolicy = autostartConfigAstGetByName(pCfgAstUser, "allow");
|
---|
866 | if (pCfgAstPolicy)
|
---|
867 | {
|
---|
868 | if ( pCfgAstPolicy->enmType == CFGASTNODETYPE_KEYVALUE
|
---|
869 | && ( !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "true")
|
---|
870 | || !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "false")))
|
---|
871 | fAllow = RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "true") == 0;
|
---|
872 | else
|
---|
873 | {
|
---|
874 | autostartConfigAstDestroy(pCfgAst);
|
---|
875 | return autostartSvcLogError("'allow' must be either 'true' or 'false'.\n");
|
---|
876 | }
|
---|
877 | }
|
---|
878 | }
|
---|
879 | else if (pCfgAstUser)
|
---|
880 | {
|
---|
881 | autostartConfigAstDestroy(pCfgAst);
|
---|
882 | return autostartSvcLogError("Invalid config, user is not a compound node.\n");
|
---|
883 | }
|
---|
884 |
|
---|
885 | if (!fAllow)
|
---|
886 | {
|
---|
887 | autostartConfigAstDestroy(pCfgAst);
|
---|
888 | return autostartSvcLogError("User is not allowed to autostart VMs.\n");
|
---|
889 | }
|
---|
890 |
|
---|
891 | RTEXITCODE rcExit = autostartStartMain(pCfgAstUser);
|
---|
892 | autostartConfigAstDestroy(pCfgAst);
|
---|
893 | if (rcExit != RTEXITCODE_SUCCESS)
|
---|
894 | autostartSvcLogError("Starting VMs failed\n");
|
---|
895 |
|
---|
896 | return rcExit;
|
---|
897 | }
|
---|
898 |
|
---|
899 | /**
|
---|
900 | * Windows Service Main.
|
---|
901 | *
|
---|
902 | * This is invoked when the service is started and should not return until
|
---|
903 | * the service has been stopped.
|
---|
904 | *
|
---|
905 | * @param cArgs Argument count.
|
---|
906 | * @param papwszArgs Argument vector.
|
---|
907 | */
|
---|
908 | static VOID WINAPI autostartSvcWinServiceMain(DWORD cArgs, LPWSTR *papwszArgs)
|
---|
909 | {
|
---|
910 | RT_NOREF(cArgs, papwszArgs);
|
---|
911 | LogFlowFuncEnter();
|
---|
912 |
|
---|
913 | /* Give this thread a name in the logs. */
|
---|
914 | RTThreadAdopt(RTTHREADTYPE_DEFAULT, 0, "service", NULL);
|
---|
915 |
|
---|
916 | #if 0
|
---|
917 | for (size_t i = 0; i < cArgs; ++i)
|
---|
918 | LogRel(("arg[%zu] = %ls\n", i, papwszArgs[i]));
|
---|
919 | #endif
|
---|
920 |
|
---|
921 | /*
|
---|
922 | * Register the control handler function for the service and report to SCM.
|
---|
923 | */
|
---|
924 | Assert(g_u32SupSvcWinStatus == SERVICE_STOPPED);
|
---|
925 | g_hSupSvcWinCtrlHandler = RegisterServiceCtrlHandlerExW(g_bstrServiceName.raw(), autostartSvcWinServiceCtrlHandlerEx, NULL);
|
---|
926 | if (g_hSupSvcWinCtrlHandler)
|
---|
927 | {
|
---|
928 | DWORD err = ERROR_GEN_FAILURE;
|
---|
929 | if (autostartSvcWinSetServiceStatus(SERVICE_START_PENDING, 3000, NO_ERROR))
|
---|
930 | {
|
---|
931 | /*
|
---|
932 | * Create the event semaphore we'll be waiting on and
|
---|
933 | * then instantiate the actual services.
|
---|
934 | */
|
---|
935 | int rc = RTSemEventMultiCreate(&g_hSupSvcWinEvent);
|
---|
936 | if (RT_SUCCESS(rc))
|
---|
937 | {
|
---|
938 | /*
|
---|
939 | * Update the status and enter the work loop.
|
---|
940 | */
|
---|
941 | if (autostartSvcWinSetServiceStatus(SERVICE_RUNNING, 0, 0))
|
---|
942 | {
|
---|
943 | LogFlow(("autostartSvcWinServiceMain: calling autostartStartVMs\n"));
|
---|
944 |
|
---|
945 | /* check if we should stopped already, e.g. windows shutdown */
|
---|
946 | rc = RTSemEventMultiWait(g_hSupSvcWinEvent, 1);
|
---|
947 | if (RT_FAILURE(rc))
|
---|
948 | {
|
---|
949 | /* No one signaled us to stop */
|
---|
950 | RTEXITCODE ec = autostartStartVMs();
|
---|
951 | if (ec == RTEXITCODE_SUCCESS)
|
---|
952 | {
|
---|
953 | LogFlow(("autostartSvcWinServiceMain: done starting VMs\n"));
|
---|
954 | err = NO_ERROR;
|
---|
955 | }
|
---|
956 | /* No reason to keep started. Shutdown the service*/
|
---|
957 | }
|
---|
958 | autostartShutdown();
|
---|
959 | }
|
---|
960 | else
|
---|
961 | {
|
---|
962 | err = GetLastError();
|
---|
963 | autostartSvcLogError("SetServiceStatus failed, err=%u", err);
|
---|
964 | }
|
---|
965 |
|
---|
966 | RTSemEventMultiDestroy(g_hSupSvcWinEvent);
|
---|
967 | g_hSupSvcWinEvent = NIL_RTSEMEVENTMULTI;
|
---|
968 | }
|
---|
969 | else
|
---|
970 | autostartSvcLogError("RTSemEventMultiCreate failed, rc=%Rrc", rc);
|
---|
971 | }
|
---|
972 | else
|
---|
973 | {
|
---|
974 | err = GetLastError();
|
---|
975 | autostartSvcLogError("SetServiceStatus failed, err=%u", err);
|
---|
976 | }
|
---|
977 | autostartSvcWinSetServiceStatus(SERVICE_STOPPED, 0, err);
|
---|
978 | }
|
---|
979 | else
|
---|
980 | autostartSvcLogError("RegisterServiceCtrlHandlerEx failed, err=%u", GetLastError());
|
---|
981 |
|
---|
982 | LogFlowFuncLeave();
|
---|
983 | }
|
---|
984 |
|
---|
985 |
|
---|
986 | /**
|
---|
987 | * Handle the 'create' action.
|
---|
988 | *
|
---|
989 | * @returns RTEXITCODE_SUCCESS or RTEXITCODE_FAILURE.
|
---|
990 | * @param argc The action argument count.
|
---|
991 | * @param argv The action argument vector.
|
---|
992 | */
|
---|
993 | static int autostartSvcWinRunIt(int argc, char **argv)
|
---|
994 | {
|
---|
995 | int rc;
|
---|
996 |
|
---|
997 | LogFlowFuncEnter();
|
---|
998 |
|
---|
999 | /*
|
---|
1000 | * Init com here for first main thread initialization.
|
---|
1001 | * Service main function called in another thread
|
---|
1002 | * created by service manager.
|
---|
1003 | */
|
---|
1004 | HRESULT hrc = com::Initialize();
|
---|
1005 | # ifdef VBOX_WITH_XPCOM
|
---|
1006 | if (hrc == NS_ERROR_FILE_ACCESS_DENIED)
|
---|
1007 | {
|
---|
1008 | char szHome[RTPATH_MAX] = "";
|
---|
1009 | com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome));
|
---|
1010 | return RTMsgErrorExit(RTEXITCODE_FAILURE,
|
---|
1011 | "Failed to initialize COM because the global settings directory '%s' is not accessible!", szHome);
|
---|
1012 | }
|
---|
1013 | # endif
|
---|
1014 | if (FAILED(hrc))
|
---|
1015 | return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to initialize COM (%Rhrc)!", hrc);
|
---|
1016 |
|
---|
1017 | /*
|
---|
1018 | * Initialize release logging, do this early. This means command
|
---|
1019 | * line options (like --logfile &c) can't be introduced to affect
|
---|
1020 | * the log file parameters, but the user can't change them easily
|
---|
1021 | * anyway and is better off using environment variables.
|
---|
1022 | */
|
---|
1023 | do
|
---|
1024 | {
|
---|
1025 | char szLogFile[RTPATH_MAX];
|
---|
1026 | rc = com::GetVBoxUserHomeDirectory(szLogFile, sizeof(szLogFile),
|
---|
1027 | /* :fCreateDir */ false);
|
---|
1028 | if (RT_FAILURE(rc))
|
---|
1029 | {
|
---|
1030 | autostartSvcLogError("Failed to get VirtualBox user home directory: %Rrc\n", rc);
|
---|
1031 | break;
|
---|
1032 | }
|
---|
1033 |
|
---|
1034 | if (!RTDirExists(szLogFile)) /* vbox user home dir */
|
---|
1035 | {
|
---|
1036 | autostartSvcLogError("%s doesn't exist\n", szLogFile);
|
---|
1037 | break;
|
---|
1038 | }
|
---|
1039 |
|
---|
1040 | rc = RTPathAppend(szLogFile, sizeof(szLogFile), "VBoxAutostart.log");
|
---|
1041 | if (RT_FAILURE(rc))
|
---|
1042 | {
|
---|
1043 | autostartSvcLogError("Failed to construct release log file name: %Rrc\n", rc);
|
---|
1044 | break;
|
---|
1045 | }
|
---|
1046 |
|
---|
1047 | rc = com::VBoxLogRelCreate("Autostart",
|
---|
1048 | szLogFile,
|
---|
1049 | RTLOGFLAGS_PREFIX_THREAD
|
---|
1050 | | RTLOGFLAGS_PREFIX_TIME_PROG,
|
---|
1051 | "all",
|
---|
1052 | "VBOXAUTOSTART_RELEASE_LOG",
|
---|
1053 | RTLOGDEST_FILE,
|
---|
1054 | UINT32_MAX /* cMaxEntriesPerGroup */,
|
---|
1055 | g_cHistory,
|
---|
1056 | g_uHistoryFileTime,
|
---|
1057 | g_uHistoryFileSize,
|
---|
1058 | NULL);
|
---|
1059 | if (RT_FAILURE(rc))
|
---|
1060 | autostartSvcLogError("Failed to create release log file: %Rrc\n", rc);
|
---|
1061 | } while (0);
|
---|
1062 |
|
---|
1063 | /*
|
---|
1064 | * Parse the arguments.
|
---|
1065 | */
|
---|
1066 | static const RTGETOPTDEF s_aOptions[] =
|
---|
1067 | {
|
---|
1068 | { "--service", 's', RTGETOPT_REQ_STRING },
|
---|
1069 | };
|
---|
1070 |
|
---|
1071 | const char *pszServiceName = NULL;
|
---|
1072 | int ch;
|
---|
1073 | RTGETOPTUNION Value;
|
---|
1074 | RTGETOPTSTATE GetState;
|
---|
1075 | RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
|
---|
1076 | while ((ch = RTGetOpt(&GetState, &Value)))
|
---|
1077 | {
|
---|
1078 | switch (ch)
|
---|
1079 | {
|
---|
1080 | case 's':
|
---|
1081 | pszServiceName = Value.psz;
|
---|
1082 | try
|
---|
1083 | {
|
---|
1084 | g_bstrServiceName = com::Bstr(Value.psz);
|
---|
1085 | }
|
---|
1086 | catch (...)
|
---|
1087 | {
|
---|
1088 | autostartSvcLogError("runit failed, service name is not valid utf-8 string or out of memory");
|
---|
1089 | return RTEXITCODE_FAILURE;
|
---|
1090 | }
|
---|
1091 | break;
|
---|
1092 |
|
---|
1093 | default:
|
---|
1094 | /**
|
---|
1095 | * @todo autostartSvcLogGetOptError is useless as it
|
---|
1096 | * is, should be change after RTGetOptPrintError.
|
---|
1097 | */
|
---|
1098 | return autostartSvcLogError("RTGetOpt: %Rrc\n", ch);
|
---|
1099 | }
|
---|
1100 | }
|
---|
1101 |
|
---|
1102 | if (!pszServiceName)
|
---|
1103 | {
|
---|
1104 | autostartSvcLogError("runit failed, service name is missing");
|
---|
1105 | return RTEXITCODE_FAILURE;
|
---|
1106 | }
|
---|
1107 |
|
---|
1108 | LogRel(("Starting service %ls\n", g_bstrServiceName.raw()));
|
---|
1109 |
|
---|
1110 | /*
|
---|
1111 | * Register the service with the service control manager
|
---|
1112 | * and start dispatching requests from it (all done by the API).
|
---|
1113 | */
|
---|
1114 | SERVICE_TABLE_ENTRYW const s_aServiceStartTable[] =
|
---|
1115 | {
|
---|
1116 | { g_bstrServiceName.raw(), autostartSvcWinServiceMain },
|
---|
1117 | { NULL, NULL}
|
---|
1118 | };
|
---|
1119 | if (StartServiceCtrlDispatcherW(&s_aServiceStartTable[0]))
|
---|
1120 | {
|
---|
1121 | LogFlowFuncLeave();
|
---|
1122 | return RTEXITCODE_SUCCESS; /* told to quit, so quit. */
|
---|
1123 | }
|
---|
1124 |
|
---|
1125 | DWORD err = GetLastError();
|
---|
1126 | switch (err)
|
---|
1127 | {
|
---|
1128 | case ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
|
---|
1129 | autostartSvcWinServiceMain(0, NULL);//autostartSvcDisplayError("Cannot run a service from the command line. Use the 'start' action to start it the right way.\n");
|
---|
1130 | break;
|
---|
1131 | default:
|
---|
1132 | autostartSvcLogError("StartServiceCtrlDispatcher failed, err=%u", err);
|
---|
1133 | break;
|
---|
1134 | }
|
---|
1135 |
|
---|
1136 | com::Shutdown();
|
---|
1137 |
|
---|
1138 | return RTEXITCODE_FAILURE;
|
---|
1139 | }
|
---|
1140 |
|
---|
1141 |
|
---|
1142 | /**
|
---|
1143 | * Show the version info.
|
---|
1144 | *
|
---|
1145 | * @returns RTEXITCODE_SUCCESS.
|
---|
1146 | */
|
---|
1147 | static RTEXITCODE autostartSvcWinShowVersion(int argc, char **argv)
|
---|
1148 | {
|
---|
1149 | /*
|
---|
1150 | * Parse the arguments.
|
---|
1151 | */
|
---|
1152 | bool fBrief = false;
|
---|
1153 | static const RTGETOPTDEF s_aOptions[] =
|
---|
1154 | {
|
---|
1155 | { "--brief", 'b', RTGETOPT_REQ_NOTHING }
|
---|
1156 | };
|
---|
1157 | int ch;
|
---|
1158 | RTGETOPTUNION Value;
|
---|
1159 | RTGETOPTSTATE GetState;
|
---|
1160 | RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
|
---|
1161 | while ((ch = RTGetOpt(&GetState, &Value)))
|
---|
1162 | switch (ch)
|
---|
1163 | {
|
---|
1164 | case 'b': fBrief = true; break;
|
---|
1165 | default: return autostartSvcDisplayGetOptError("version", ch, &Value);
|
---|
1166 | }
|
---|
1167 |
|
---|
1168 | /*
|
---|
1169 | * Do the printing.
|
---|
1170 | */
|
---|
1171 | if (fBrief)
|
---|
1172 | RTPrintf("%s\n", VBOX_VERSION_STRING);
|
---|
1173 | else
|
---|
1174 | RTPrintf("VirtualBox Autostart Service Version %s\n"
|
---|
1175 | "(C) 2012 Oracle Corporation\n"
|
---|
1176 | "All rights reserved.\n",
|
---|
1177 | VBOX_VERSION_STRING);
|
---|
1178 | return RTEXITCODE_SUCCESS;
|
---|
1179 | }
|
---|
1180 |
|
---|
1181 |
|
---|
1182 | /**
|
---|
1183 | * Show the usage help screen.
|
---|
1184 | *
|
---|
1185 | * @returns RTEXITCODE_SUCCESS.
|
---|
1186 | */
|
---|
1187 | static RTEXITCODE autostartSvcWinShowHelp(void)
|
---|
1188 | {
|
---|
1189 | RTPrintf("VirtualBox Autostart Service Version %s\n"
|
---|
1190 | "(C) 2012 Oracle Corporation\n"
|
---|
1191 | "All rights reserved.\n"
|
---|
1192 | "\n",
|
---|
1193 | VBOX_VERSION_STRING);
|
---|
1194 | RTPrintf("Usage:\n"
|
---|
1195 | "\n"
|
---|
1196 | "VBoxAutostartSvc\n"
|
---|
1197 | " Runs the service.\n"
|
---|
1198 | "VBoxAutostartSvc <version|-v|--version> [-brief]\n"
|
---|
1199 | " Displays the version.\n"
|
---|
1200 | "VBoxAutostartSvc <help|-?|-h|--help> [...]\n"
|
---|
1201 | " Displays this help screen.\n"
|
---|
1202 | "\n"
|
---|
1203 | "VBoxAutostartSvc <install|/RegServer|/i>\n"
|
---|
1204 | " Installs the service.\n"
|
---|
1205 | "VBoxAutostartSvc <uninstall|delete|/UnregServer|/u>\n"
|
---|
1206 | " Uninstalls the service.\n"
|
---|
1207 | );
|
---|
1208 | return RTEXITCODE_SUCCESS;
|
---|
1209 | }
|
---|
1210 |
|
---|
1211 |
|
---|
1212 | /**
|
---|
1213 | * VBoxAutostart main(), Windows edition.
|
---|
1214 | *
|
---|
1215 | *
|
---|
1216 | * @returns 0 on success.
|
---|
1217 | *
|
---|
1218 | * @param argc Number of arguments in argv.
|
---|
1219 | * @param argv Argument vector.
|
---|
1220 | */
|
---|
1221 | int main(int argc, char **argv)
|
---|
1222 | {
|
---|
1223 | /*
|
---|
1224 | * Initialize the IPRT first of all.
|
---|
1225 | */
|
---|
1226 | int rc = RTR3InitExe(argc, &argv, 0);
|
---|
1227 | if (RT_FAILURE(rc))
|
---|
1228 | {
|
---|
1229 | autostartSvcLogError("RTR3InitExe failed with rc=%Rrc", rc);
|
---|
1230 | return RTEXITCODE_FAILURE;
|
---|
1231 | }
|
---|
1232 |
|
---|
1233 | /*
|
---|
1234 | * Parse the initial arguments to determine the desired action.
|
---|
1235 | */
|
---|
1236 | enum
|
---|
1237 | {
|
---|
1238 | kAutoSvcAction_RunIt,
|
---|
1239 |
|
---|
1240 | kAutoSvcAction_Create,
|
---|
1241 | kAutoSvcAction_Delete,
|
---|
1242 |
|
---|
1243 | kAutoSvcAction_Enable,
|
---|
1244 | kAutoSvcAction_Disable,
|
---|
1245 | kAutoSvcAction_QueryConfig,
|
---|
1246 | kAutoSvcAction_QueryDescription,
|
---|
1247 |
|
---|
1248 | kAutoSvcAction_Start,
|
---|
1249 | kAutoSvcAction_Pause,
|
---|
1250 | kAutoSvcAction_Continue,
|
---|
1251 | kAutoSvcAction_Stop,
|
---|
1252 | kAutoSvcAction_Interrogate,
|
---|
1253 |
|
---|
1254 | kAutoSvcAction_End
|
---|
1255 | } enmAction = kAutoSvcAction_RunIt;
|
---|
1256 | int iArg = 1;
|
---|
1257 | if (argc > 1)
|
---|
1258 | {
|
---|
1259 | if ( !stricmp(argv[iArg], "/RegServer")
|
---|
1260 | || !stricmp(argv[iArg], "install")
|
---|
1261 | || !stricmp(argv[iArg], "/i"))
|
---|
1262 | enmAction = kAutoSvcAction_Create;
|
---|
1263 | else if ( !stricmp(argv[iArg], "/UnregServer")
|
---|
1264 | || !stricmp(argv[iArg], "/u")
|
---|
1265 | || !stricmp(argv[iArg], "uninstall")
|
---|
1266 | || !stricmp(argv[iArg], "delete"))
|
---|
1267 | enmAction = kAutoSvcAction_Delete;
|
---|
1268 |
|
---|
1269 | else if (!stricmp(argv[iArg], "enable"))
|
---|
1270 | enmAction = kAutoSvcAction_Enable;
|
---|
1271 | else if (!stricmp(argv[iArg], "disable"))
|
---|
1272 | enmAction = kAutoSvcAction_Disable;
|
---|
1273 | else if (!stricmp(argv[iArg], "qconfig"))
|
---|
1274 | enmAction = kAutoSvcAction_QueryConfig;
|
---|
1275 | else if (!stricmp(argv[iArg], "qdescription"))
|
---|
1276 | enmAction = kAutoSvcAction_QueryDescription;
|
---|
1277 |
|
---|
1278 | else if ( !stricmp(argv[iArg], "start")
|
---|
1279 | || !stricmp(argv[iArg], "/t"))
|
---|
1280 | enmAction = kAutoSvcAction_Start;
|
---|
1281 | else if (!stricmp(argv[iArg], "pause"))
|
---|
1282 | enmAction = kAutoSvcAction_Start;
|
---|
1283 | else if (!stricmp(argv[iArg], "continue"))
|
---|
1284 | enmAction = kAutoSvcAction_Continue;
|
---|
1285 | else if (!stricmp(argv[iArg], "stop"))
|
---|
1286 | enmAction = kAutoSvcAction_Stop;
|
---|
1287 | else if (!stricmp(argv[iArg], "interrogate"))
|
---|
1288 | enmAction = kAutoSvcAction_Interrogate;
|
---|
1289 | else if ( !stricmp(argv[iArg], "help")
|
---|
1290 | || !stricmp(argv[iArg], "?")
|
---|
1291 | || !stricmp(argv[iArg], "/?")
|
---|
1292 | || !stricmp(argv[iArg], "-?")
|
---|
1293 | || !stricmp(argv[iArg], "/h")
|
---|
1294 | || !stricmp(argv[iArg], "-h")
|
---|
1295 | || !stricmp(argv[iArg], "/help")
|
---|
1296 | || !stricmp(argv[iArg], "-help")
|
---|
1297 | || !stricmp(argv[iArg], "--help"))
|
---|
1298 | return autostartSvcWinShowHelp();
|
---|
1299 | else if ( !stricmp(argv[iArg], "version")
|
---|
1300 | || !stricmp(argv[iArg], "/v")
|
---|
1301 | || !stricmp(argv[iArg], "-v")
|
---|
1302 | || !stricmp(argv[iArg], "/version")
|
---|
1303 | || !stricmp(argv[iArg], "-version")
|
---|
1304 | || !stricmp(argv[iArg], "--version"))
|
---|
1305 | return autostartSvcWinShowVersion(argc - iArg - 1, argv + iArg + 1);
|
---|
1306 | else
|
---|
1307 | iArg--;
|
---|
1308 | iArg++;
|
---|
1309 | }
|
---|
1310 |
|
---|
1311 | /*
|
---|
1312 | * Dispatch it.
|
---|
1313 | */
|
---|
1314 | switch (enmAction)
|
---|
1315 | {
|
---|
1316 | case kAutoSvcAction_RunIt:
|
---|
1317 | return autostartSvcWinRunIt(argc - iArg, argv + iArg);
|
---|
1318 |
|
---|
1319 | case kAutoSvcAction_Create:
|
---|
1320 | return autostartSvcWinCreate(argc - iArg, argv + iArg);
|
---|
1321 | case kAutoSvcAction_Delete:
|
---|
1322 | return autostartSvcWinDelete(argc - iArg, argv + iArg);
|
---|
1323 |
|
---|
1324 | case kAutoSvcAction_Enable:
|
---|
1325 | return autostartSvcWinEnable(argc - iArg, argv + iArg);
|
---|
1326 | case kAutoSvcAction_Disable:
|
---|
1327 | return autostartSvcWinDisable(argc - iArg, argv + iArg);
|
---|
1328 | case kAutoSvcAction_QueryConfig:
|
---|
1329 | return autostartSvcWinQueryConfig(argc - iArg, argv + iArg);
|
---|
1330 | case kAutoSvcAction_QueryDescription:
|
---|
1331 | return autostartSvcWinQueryDescription(argc - iArg, argv + iArg);
|
---|
1332 |
|
---|
1333 | case kAutoSvcAction_Start:
|
---|
1334 | return autostartSvcWinStart(argc - iArg, argv + iArg);
|
---|
1335 | case kAutoSvcAction_Pause:
|
---|
1336 | return autostartSvcWinPause(argc - iArg, argv + iArg);
|
---|
1337 | case kAutoSvcAction_Continue:
|
---|
1338 | return autostartSvcWinContinue(argc - iArg, argv + iArg);
|
---|
1339 | case kAutoSvcAction_Stop:
|
---|
1340 | return autostartSvcWinStop(argc - iArg, argv + iArg);
|
---|
1341 | case kAutoSvcAction_Interrogate:
|
---|
1342 | return autostartSvcWinInterrogate(argc - iArg, argv + iArg);
|
---|
1343 |
|
---|
1344 | default:
|
---|
1345 | AssertMsgFailed(("enmAction=%d\n", enmAction));
|
---|
1346 | return RTEXITCODE_FAILURE;
|
---|
1347 | }
|
---|
1348 | }
|
---|
1349 |
|
---|