VirtualBox

source: vbox/trunk/src/VBox/Additions/common/VBoxService/VBoxServiceControl.cpp@ 52890

Last change on this file since 52890 was 50810, checked in by vboxsync, 11 years ago

VBoxService/GuestCtrl: Do a HGCM reconnect on saved state restore when the guest session changed; don't try too hard though.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 19.3 KB
Line 
1/* $Id: VBoxServiceControl.cpp 50810 2014-03-18 14:53:28Z vboxsync $ */
2/** @file
3 * VBoxServiceControl - Host-driven Guest Control.
4 */
5
6/*
7 * Copyright (C) 2012-2014 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/asm.h>
23#include <iprt/assert.h>
24#include <iprt/env.h>
25#include <iprt/file.h>
26#include <iprt/getopt.h>
27#include <iprt/mem.h>
28#include <iprt/path.h>
29#include <iprt/process.h>
30#include <iprt/semaphore.h>
31#include <iprt/thread.h>
32#include <VBox/VBoxGuestLib.h>
33#include <VBox/HostServices/GuestControlSvc.h>
34#include "VBoxServiceInternal.h"
35#include "VBoxServiceControl.h"
36#include "VBoxServiceUtils.h"
37
38using namespace guestControl;
39
40/*******************************************************************************
41* Global Variables *
42*******************************************************************************/
43/** The control interval (milliseconds). */
44static uint32_t g_uControlIntervalMS = 0;
45/** The semaphore we're blocking our main control thread on. */
46static RTSEMEVENTMULTI g_hControlEvent = NIL_RTSEMEVENTMULTI;
47/** The VM session ID. Changes whenever the VM is restored or reset. */
48static uint64_t g_idControlSession;
49/** The guest control service client ID. */
50static uint32_t g_uControlSvcClientID = 0;
51/** How many started guest processes are kept into memory for supplying
52 * information to the host. Default is 256 processes. If 0 is specified,
53 * the maximum number of processes is unlimited. */
54static uint32_t g_uControlProcsMaxKept = 256;
55/** List of guest control session threads (VBOXSERVICECTRLSESSIONTHREAD).
56 * A guest session thread represents a forked guest session process
57 * of VBoxService. */
58RTLISTANCHOR g_lstControlSessionThreads;
59/** The local session object used for handling all session-related stuff.
60 * When using the legacy guest control protocol (< 2), this session runs
61 * under behalf of the VBoxService main process. On newer protocol versions
62 * each session is a forked version of VBoxService using the appropriate
63 * user credentials for opening a guest session. These forked sessions then
64 * are kept in VBOXSERVICECTRLSESSIONTHREAD structures. */
65VBOXSERVICECTRLSESSION g_Session;
66
67/*******************************************************************************
68* Internal Functions *
69*******************************************************************************/
70static int gstcntlHandleSessionOpen(PVBGLR3GUESTCTRLCMDCTX pHostCtx);
71static int gstcntlHandleSessionClose(PVBGLR3GUESTCTRLCMDCTX pHostCtx);
72static void VBoxServiceControlShutdown(void);
73
74
75/** @copydoc VBOXSERVICE::pfnPreInit */
76static DECLCALLBACK(int) VBoxServiceControlPreInit(void)
77{
78 int rc;
79#ifdef VBOX_WITH_GUEST_PROPS
80 /*
81 * Read the service options from the VM's guest properties.
82 * Note that these options can be overridden by the command line options later.
83 */
84 uint32_t uGuestPropSvcClientID;
85 rc = VbglR3GuestPropConnect(&uGuestPropSvcClientID);
86 if (RT_FAILURE(rc))
87 {
88 if (rc == VERR_HGCM_SERVICE_NOT_FOUND) /* Host service is not available. */
89 {
90 VBoxServiceVerbose(0, "Guest property service is not available, skipping\n");
91 rc = VINF_SUCCESS;
92 }
93 else
94 VBoxServiceError("Failed to connect to the guest property service, rc=%Rrc\n", rc);
95 }
96 else
97 {
98 VbglR3GuestPropDisconnect(uGuestPropSvcClientID);
99 }
100
101 if (rc == VERR_NOT_FOUND) /* If a value is not found, don't be sad! */
102 rc = VINF_SUCCESS;
103#else
104 /* Nothing to do here yet. */
105 rc = VINF_SUCCESS;
106#endif
107
108 if (RT_SUCCESS(rc))
109 {
110 /* Init session object. */
111 rc = GstCntlSessionInit(&g_Session, 0 /* Flags */);
112 }
113
114 return rc;
115}
116
117
118/** @copydoc VBOXSERVICE::pfnOption */
119static DECLCALLBACK(int) VBoxServiceControlOption(const char **ppszShort, int argc, char **argv, int *pi)
120{
121 int rc = -1;
122 if (ppszShort)
123 /* no short options */;
124 else if (!strcmp(argv[*pi], "--control-interval"))
125 rc = VBoxServiceArgUInt32(argc, argv, "", pi,
126 &g_uControlIntervalMS, 1, UINT32_MAX - 1);
127#ifdef DEBUG
128 else if (!strcmp(argv[*pi], "--control-dump-stdout"))
129 {
130 g_Session.uFlags |= VBOXSERVICECTRLSESSION_FLAG_DUMPSTDOUT;
131 rc = 0; /* Flag this command as parsed. */
132 }
133 else if (!strcmp(argv[*pi], "--control-dump-stderr"))
134 {
135 g_Session.uFlags |= VBOXSERVICECTRLSESSION_FLAG_DUMPSTDERR;
136 rc = 0; /* Flag this command as parsed. */
137 }
138#endif
139 return rc;
140}
141
142
143/** @copydoc VBOXSERVICE::pfnInit */
144static DECLCALLBACK(int) VBoxServiceControlInit(void)
145{
146 /*
147 * If not specified, find the right interval default.
148 * Then create the event sem to block on.
149 */
150 if (!g_uControlIntervalMS)
151 g_uControlIntervalMS = 1000;
152
153 int rc = RTSemEventMultiCreate(&g_hControlEvent);
154 AssertRCReturn(rc, rc);
155
156 VbglR3GetSessionId(&g_idControlSession);
157 /* The status code is ignored as this information is not available with VBox < 3.2.10. */
158
159 if (RT_SUCCESS(rc))
160 rc = VbglR3GuestCtrlConnect(&g_uControlSvcClientID);
161 if (RT_SUCCESS(rc))
162 {
163 VBoxServiceVerbose(3, "Guest control service client ID=%RU32\n",
164 g_uControlSvcClientID);
165
166 /* Init session thread list. */
167 RTListInit(&g_lstControlSessionThreads);
168 }
169 else
170 {
171 /* If the service was not found, we disable this service without
172 causing VBoxService to fail. */
173 if (rc == VERR_HGCM_SERVICE_NOT_FOUND) /* Host service is not available. */
174 {
175 VBoxServiceVerbose(0, "Guest control service is not available\n");
176 rc = VERR_SERVICE_DISABLED;
177 }
178 else
179 VBoxServiceError("Failed to connect to the guest control service! Error: %Rrc\n", rc);
180 RTSemEventMultiDestroy(g_hControlEvent);
181 g_hControlEvent = NIL_RTSEMEVENTMULTI;
182 }
183 return rc;
184}
185
186
187/** @copydoc VBOXSERVICE::pfnWorker */
188DECLCALLBACK(int) VBoxServiceControlWorker(bool volatile *pfShutdown)
189{
190 /*
191 * Tell the control thread that it can continue
192 * spawning services.
193 */
194 RTThreadUserSignal(RTThreadSelf());
195 Assert(g_uControlSvcClientID > 0);
196
197 int rc = VINF_SUCCESS;
198
199 /* Allocate a scratch buffer for commands which also send
200 * payload data with them. */
201 uint32_t cbScratchBuf = _64K; /** @todo Make buffer size configurable via guest properties/argv! */
202 AssertReturn(RT_IS_POWER_OF_TWO(cbScratchBuf), VERR_INVALID_PARAMETER);
203 uint8_t *pvScratchBuf = (uint8_t*)RTMemAlloc(cbScratchBuf);
204 AssertPtrReturn(pvScratchBuf, VERR_NO_MEMORY);
205
206 VBGLR3GUESTCTRLCMDCTX ctxHost = { g_uControlSvcClientID };
207 /* Set default protocol version to 1. */
208 ctxHost.uProtocol = 1;
209
210 int cRetrievalFailed = 0; /* Number of failed message retrievals in a row. */
211 for (;;)
212 {
213 VBoxServiceVerbose(3, "Waiting for host msg ...\n");
214 uint32_t uMsg = 0;
215 uint32_t cParms = 0;
216 rc = VbglR3GuestCtrlMsgWaitFor(g_uControlSvcClientID, &uMsg, &cParms);
217 if (rc == VERR_TOO_MUCH_DATA)
218 {
219#ifdef DEBUG
220 VBoxServiceVerbose(4, "Message requires %ld parameters, but only 2 supplied -- retrying request (no error!)...\n",
221 cParms);
222#endif
223 rc = VINF_SUCCESS; /* Try to get "real" message in next block below. */
224 }
225 else if (RT_FAILURE(rc))
226 {
227 /* Note: VERR_GEN_IO_FAILURE seems to be normal if ran into timeout. */
228 VBoxServiceError("Getting host message failed with %Rrc\n", rc);
229
230 /* Check for VM session change. */
231 uint64_t idNewSession = g_idControlSession;
232 int rc2 = VbglR3GetSessionId(&idNewSession);
233 if ( RT_SUCCESS(rc2)
234 && (idNewSession != g_idControlSession))
235 {
236 VBoxServiceVerbose(1, "The VM session ID changed\n");
237 g_idControlSession = idNewSession;
238
239 /* Close all opened guest sessions -- all context IDs, sessions etc.
240 * are now invalid. */
241 rc2 = GstCntlSessionClose(&g_Session);
242 AssertRC(rc2);
243
244 /* Do a reconnect. */
245 VBoxServiceVerbose(1, "Reconnecting to HGCM service ...\n");
246 rc2 = VbglR3GuestCtrlConnect(&g_uControlSvcClientID);
247 if (RT_SUCCESS(rc2))
248 {
249 VBoxServiceVerbose(3, "Guest control service client ID=%RU32\n",
250 g_uControlSvcClientID);
251 cRetrievalFailed = 0;
252 continue; /* Skip waiting. */
253 }
254 else
255 {
256 VBoxServiceError("Unable to re-connect to HGCM service, rc=%Rrc, bailing out\n", rc);
257 break;
258 }
259 }
260
261 if (++cRetrievalFailed > 16) /** @todo Make this configurable? */
262 {
263 VBoxServiceError("Too many failed attempts in a row to get next message, bailing out\n");
264 break;
265 }
266
267 RTThreadSleep(1000); /* Wait a bit before retrying. */
268 }
269
270 if (RT_SUCCESS(rc))
271 {
272 VBoxServiceVerbose(4, "Msg=%RU32 (%RU32 parms) retrieved\n", uMsg, cParms);
273 cRetrievalFailed = 0; /* Reset failed retrieval count. */
274
275 /* Set number of parameters for current host context. */
276 ctxHost.uNumParms = cParms;
277
278 /* Check for VM session change. */
279 uint64_t idNewSession = g_idControlSession;
280 int rc2 = VbglR3GetSessionId(&idNewSession);
281 if ( RT_SUCCESS(rc2)
282 && (idNewSession != g_idControlSession))
283 {
284 VBoxServiceVerbose(1, "The VM session ID changed\n");
285 g_idControlSession = idNewSession;
286
287 /* Close all opened guest sessions -- all context IDs, sessions etc.
288 * are now invalid. */
289 rc2 = GstCntlSessionClose(&g_Session);
290 AssertRC(rc2);
291 }
292
293 switch (uMsg)
294 {
295 case HOST_CANCEL_PENDING_WAITS:
296 VBoxServiceVerbose(1, "We were asked to quit ...\n");
297 break;
298
299 case HOST_SESSION_CREATE:
300 rc = gstcntlHandleSessionOpen(&ctxHost);
301 break;
302
303 case HOST_SESSION_CLOSE:
304 rc = gstcntlHandleSessionClose(&ctxHost);
305 break;
306
307 default:
308 {
309 /*
310 * Protocol v1 did not have support for (dedicated)
311 * guest sessions, so all actions need to be performed
312 * under behalf of VBoxService's main executable.
313 *
314 * The global session object then acts as a host for all
315 * started guest processes which bring all their
316 * credentials with them with the actual guest process
317 * execution call.
318 */
319 if (ctxHost.uProtocol == 1)
320 {
321 rc = GstCntlSessionHandler(&g_Session, uMsg, &ctxHost,
322 pvScratchBuf, cbScratchBuf, pfShutdown);
323 }
324 else
325 {
326 /*
327 * ... on newer protocols handling all other commands is
328 * up to the guest session fork of VBoxService, so just
329 * skip all not wanted messages here.
330 */
331 rc = VbglR3GuestCtrlMsgSkip(g_uControlSvcClientID);
332 VBoxServiceVerbose(3, "Skipping uMsg=%RU32, cParms=%RU32, rc=%Rrc\n",
333 uMsg, cParms, rc);
334 }
335 break;
336 }
337 }
338 }
339
340 /* Do we need to shutdown? */
341 if ( *pfShutdown
342 || (RT_SUCCESS(rc) && uMsg == HOST_CANCEL_PENDING_WAITS))
343 {
344 break;
345 }
346
347 /* Let's sleep for a bit and let others run ... */
348 RTThreadYield();
349 }
350
351 VBoxServiceVerbose(0, "Guest control service stopped\n");
352
353 /* Delete scratch buffer. */
354 if (pvScratchBuf)
355 RTMemFree(pvScratchBuf);
356
357 VBoxServiceVerbose(0, "Guest control worker returned with rc=%Rrc\n", rc);
358 return rc;
359}
360
361
362static int gstcntlHandleSessionOpen(PVBGLR3GUESTCTRLCMDCTX pHostCtx)
363{
364 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
365
366 VBOXSERVICECTRLSESSIONSTARTUPINFO ssInfo = { 0 };
367 int rc = VbglR3GuestCtrlSessionGetOpen(pHostCtx,
368 &ssInfo.uProtocol,
369 ssInfo.szUser, sizeof(ssInfo.szUser),
370 ssInfo.szPassword, sizeof(ssInfo.szPassword),
371 ssInfo.szDomain, sizeof(ssInfo.szDomain),
372 &ssInfo.uFlags, &ssInfo.uSessionID);
373 if (RT_SUCCESS(rc))
374 {
375 /* The session open call has the protocol version the host
376 * wants to use. So update the current protocol version with the one the
377 * host wants to use in subsequent calls. */
378 pHostCtx->uProtocol = ssInfo.uProtocol;
379 VBoxServiceVerbose(3, "Client ID=%RU32 now is using protocol %RU32\n",
380 pHostCtx->uClientID, pHostCtx->uProtocol);
381
382 rc = GstCntlSessionThreadCreate(&g_lstControlSessionThreads,
383 &ssInfo, NULL /* ppSessionThread */);
384 }
385
386 if (RT_FAILURE(rc))
387 {
388 /* Report back on failure. On success this will be done
389 * by the forked session thread. */
390 int rc2 = VbglR3GuestCtrlSessionNotify(pHostCtx,
391 GUEST_SESSION_NOTIFYTYPE_ERROR, rc /* uint32_t vs. int */);
392 if (RT_FAILURE(rc2))
393 VBoxServiceError("Reporting session error status on open failed with rc=%Rrc\n", rc2);
394 }
395
396 VBoxServiceVerbose(3, "Opening a new guest session returned rc=%Rrc\n", rc);
397 return rc;
398}
399
400
401static int gstcntlHandleSessionClose(PVBGLR3GUESTCTRLCMDCTX pHostCtx)
402{
403 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
404
405 uint32_t uSessionID, uFlags;
406 int rc = VbglR3GuestCtrlSessionGetClose(pHostCtx, &uFlags, &uSessionID);
407 if (RT_SUCCESS(rc))
408 {
409 rc = VERR_NOT_FOUND;
410
411 PVBOXSERVICECTRLSESSIONTHREAD pThread;
412 RTListForEach(&g_lstControlSessionThreads, pThread, VBOXSERVICECTRLSESSIONTHREAD, Node)
413 {
414 if (pThread->StartupInfo.uSessionID == uSessionID)
415 {
416 rc = GstCntlSessionThreadDestroy(pThread, uFlags);
417 break;
418 }
419 }
420#if 0
421 if (RT_FAILURE(rc))
422 {
423 /* Report back on failure. On success this will be done
424 * by the forked session thread. */
425 int rc2 = VbglR3GuestCtrlSessionNotify(pHostCtx,
426 GUEST_SESSION_NOTIFYTYPE_ERROR, rc);
427 if (RT_FAILURE(rc2))
428 {
429 VBoxServiceError("Reporting session error status on close failed with rc=%Rrc\n", rc2);
430 if (RT_SUCCESS(rc))
431 rc = rc2;
432 }
433 }
434#endif
435 VBoxServiceVerbose(2, "Closing guest session %RU32 returned rc=%Rrc\n",
436 uSessionID, rc);
437 }
438 else
439 VBoxServiceError("Closing guest session %RU32 failed with rc=%Rrc\n",
440 uSessionID, rc);
441 return rc;
442}
443
444
445/** @copydoc VBOXSERVICE::pfnStop */
446static DECLCALLBACK(void) VBoxServiceControlStop(void)
447{
448 VBoxServiceVerbose(3, "Stopping ...\n");
449
450 /** @todo Later, figure what to do if we're in RTProcWait(). It's a very
451 * annoying call since doesn't support timeouts in the posix world. */
452 if (g_hControlEvent != NIL_RTSEMEVENTMULTI)
453 RTSemEventMultiSignal(g_hControlEvent);
454
455 /*
456 * Ask the host service to cancel all pending requests for the main
457 * control thread so that we can shutdown properly here.
458 */
459 if (g_uControlSvcClientID)
460 {
461 VBoxServiceVerbose(3, "Cancelling pending waits (client ID=%u) ...\n",
462 g_uControlSvcClientID);
463
464 int rc = VbglR3GuestCtrlCancelPendingWaits(g_uControlSvcClientID);
465 if (RT_FAILURE(rc))
466 VBoxServiceError("Cancelling pending waits failed; rc=%Rrc\n", rc);
467 }
468}
469
470
471/**
472 * Destroys all guest process threads which are still active.
473 */
474static void VBoxServiceControlShutdown(void)
475{
476 VBoxServiceVerbose(2, "Shutting down ...\n");
477
478 int rc2 = GstCntlSessionThreadDestroyAll(&g_lstControlSessionThreads,
479 0 /* Flags */);
480 if (RT_FAILURE(rc2))
481 VBoxServiceError("Closing session threads failed with rc=%Rrc\n", rc2);
482
483 rc2 = GstCntlSessionClose(&g_Session);
484 if (RT_FAILURE(rc2))
485 VBoxServiceError("Closing session failed with rc=%Rrc\n", rc2);
486
487 VBoxServiceVerbose(2, "Shutting down complete\n");
488}
489
490
491/** @copydoc VBOXSERVICE::pfnTerm */
492static DECLCALLBACK(void) VBoxServiceControlTerm(void)
493{
494 VBoxServiceVerbose(3, "Terminating ...\n");
495
496 VBoxServiceControlShutdown();
497
498 VBoxServiceVerbose(3, "Disconnecting client ID=%u ...\n",
499 g_uControlSvcClientID);
500 VbglR3GuestCtrlDisconnect(g_uControlSvcClientID);
501 g_uControlSvcClientID = 0;
502
503 if (g_hControlEvent != NIL_RTSEMEVENTMULTI)
504 {
505 RTSemEventMultiDestroy(g_hControlEvent);
506 g_hControlEvent = NIL_RTSEMEVENTMULTI;
507 }
508}
509
510
511/**
512 * The 'vminfo' service description.
513 */
514VBOXSERVICE g_Control =
515{
516 /* pszName. */
517 "control",
518 /* pszDescription. */
519 "Host-driven Guest Control",
520 /* pszUsage. */
521#ifdef DEBUG
522 " [--control-dump-stderr] [--control-dump-stdout]\n"
523#endif
524 " [--control-interval <ms>]"
525 ,
526 /* pszOptions. */
527#ifdef DEBUG
528 " --control-dump-stderr Dumps all guest proccesses stderr data to the\n"
529 " temporary directory.\n"
530 " --control-dump-stdout Dumps all guest proccesses stdout data to the\n"
531 " temporary directory.\n"
532#endif
533 " --control-interval Specifies the interval at which to check for\n"
534 " new control commands. The default is 1000 ms.\n"
535 ,
536 /* methods */
537 VBoxServiceControlPreInit,
538 VBoxServiceControlOption,
539 VBoxServiceControlInit,
540 VBoxServiceControlWorker,
541 VBoxServiceControlStop,
542 VBoxServiceControlTerm
543};
544
Note: See TracBrowser for help on using the repository browser.

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