VirtualBox

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

Last change on this file since 40691 was 40682, checked in by vboxsync, 13 years ago

VBoxService/GuestCtrl: Bugfixes.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 35.9 KB
Line 
1/* $Id: VBoxServiceControl.cpp 40682 2012-03-28 14:36:01Z vboxsync $ */
2/** @file
3 * VBoxServiceControl - Host-driven Guest Control.
4 */
5
6/*
7 * Copyright (C) 2012 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/file.h>
25#include <iprt/getopt.h>
26#include <iprt/mem.h>
27#include <iprt/path.h>
28#include <iprt/semaphore.h>
29#include <iprt/thread.h>
30#include <VBox/VBoxGuestLib.h>
31#include <VBox/HostServices/GuestControlSvc.h>
32#include "VBoxServiceInternal.h"
33#include "VBoxServiceUtils.h"
34
35using namespace guestControl;
36
37/*******************************************************************************
38* Global Variables *
39*******************************************************************************/
40/** The control interval (milliseconds). */
41static uint32_t g_uControlIntervalMS = 0;
42/** The semaphore we're blocking our main control thread on. */
43static RTSEMEVENTMULTI g_hControlEvent = NIL_RTSEMEVENTMULTI;
44/** The guest control service client ID. */
45static uint32_t g_uControlSvcClientID = 0;
46/** How many started guest processes are kept into memory for supplying
47 * information to the host. Default is 25 processes. If 0 is specified,
48 * the maximum number of processes is unlimited. */
49static uint32_t g_uControlProcsMaxKept = 25;
50#ifdef DEBUG
51static bool g_fControlDumpStdErr = false;
52static bool g_fControlDumpStdOut = false;
53#endif
54/** List of active guest control threads (VBOXSERVICECTRLTHREAD). */
55static RTLISTANCHOR g_lstControlThreadsActive;
56/** List of inactive guest control threads (VBOXSERVICECTRLTHREAD). */
57static RTLISTANCHOR g_lstControlThreadsInactive;
58/** Critical section protecting g_GuestControlExecThreads. */
59static RTCRITSECT g_csControlThreads;
60
61
62/*******************************************************************************
63* Internal Functions *
64*******************************************************************************/
65/** @todo Shorten "VBoxServiceControl" to "gstsvcCntl". */
66static int VBoxServiceControlReapThreads(void);
67static int VBoxServiceControlStartAllowed(bool *pbAllowed);
68static int VBoxServiceControlHandleCmdStartProc(uint32_t u32ClientId, uint32_t uNumParms);
69static int VBoxServiceControlHandleCmdSetInput(uint32_t u32ClientId, uint32_t uNumParms, size_t cbMaxBufSize);
70static int VBoxServiceControlHandleCmdGetOutput(uint32_t u32ClientId, uint32_t uNumParms);
71
72
73#ifdef DEBUG
74static int vboxServiceControlDump(const char *pszFileName, void *pvBuf, size_t cbBuf)
75{
76 AssertPtrReturn(pszFileName, VERR_INVALID_POINTER);
77 AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
78
79 if (!cbBuf)
80 return VINF_SUCCESS;
81
82 char szFile[RTPATH_MAX];
83
84 int rc = RTPathTemp(szFile, sizeof(szFile));
85 if (RT_SUCCESS(rc))
86 rc = RTPathAppend(szFile, sizeof(szFile), pszFileName);
87
88 if (RT_SUCCESS(rc))
89 {
90 VBoxServiceVerbose(4, "Dumping %ld bytes to \"%s\"\n", cbBuf, szFile);
91
92 RTFILE fh;
93 rc = RTFileOpen(&fh, szFile, RTFILE_O_OPEN_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_WRITE);
94 if (RT_SUCCESS(rc))
95 {
96 rc = RTFileWrite(fh, pvBuf, cbBuf, NULL /* pcbWritten */);
97 RTFileClose(fh);
98 }
99 }
100
101 return rc;
102}
103#endif
104
105
106/** @copydoc VBOXSERVICE::pfnPreInit */
107static DECLCALLBACK(int) VBoxServiceControlPreInit(void)
108{
109#ifdef VBOX_WITH_GUEST_PROPS
110 /*
111 * Read the service options from the VM's guest properties.
112 * Note that these options can be overridden by the command line options later.
113 */
114 uint32_t uGuestPropSvcClientID;
115 int rc = VbglR3GuestPropConnect(&uGuestPropSvcClientID);
116 if (RT_FAILURE(rc))
117 {
118 if (rc == VERR_HGCM_SERVICE_NOT_FOUND) /* Host service is not available. */
119 {
120 VBoxServiceVerbose(0, "Guest property service is not available, skipping\n");
121 rc = VINF_SUCCESS;
122 }
123 else
124 VBoxServiceError("Failed to connect to the guest property service! Error: %Rrc\n", rc);
125 }
126 else
127 {
128 rc = VBoxServiceReadPropUInt32(uGuestPropSvcClientID, "/VirtualBox/GuestAdd/VBoxService/--control-procs-max-kept",
129 &g_uControlProcsMaxKept, 0, UINT32_MAX - 1);
130
131 VbglR3GuestPropDisconnect(uGuestPropSvcClientID);
132 }
133
134 if (rc == VERR_NOT_FOUND) /* If a value is not found, don't be sad! */
135 rc = VINF_SUCCESS;
136 return rc;
137#else
138 /* Nothing to do here yet. */
139 return VINF_SUCCESS;
140#endif
141}
142
143
144/** @copydoc VBOXSERVICE::pfnOption */
145static DECLCALLBACK(int) VBoxServiceControlOption(const char **ppszShort, int argc, char **argv, int *pi)
146{
147 int rc = -1;
148 if (ppszShort)
149 /* no short options */;
150 else if (!strcmp(argv[*pi], "--control-interval"))
151 rc = VBoxServiceArgUInt32(argc, argv, "", pi,
152 &g_uControlIntervalMS, 1, UINT32_MAX - 1);
153 else if (!strcmp(argv[*pi], "--control-procs-max-kept"))
154 rc = VBoxServiceArgUInt32(argc, argv, "", pi,
155 &g_uControlProcsMaxKept, 0, UINT32_MAX - 1);
156#ifdef DEBUG
157 else if (!strcmp(argv[*pi], "--control-dump-stderr"))
158 {
159 g_fControlDumpStdErr = true;
160 rc = 0; /* Flag this command as parsed. */
161 }
162 else if (!strcmp(argv[*pi], "--control-dump-stdout"))
163 {
164 g_fControlDumpStdOut = true;
165 rc = 0; /* Flag this command as parsed. */
166 }
167#endif
168 return rc;
169}
170
171
172/** @copydoc VBOXSERVICE::pfnInit */
173static DECLCALLBACK(int) VBoxServiceControlInit(void)
174{
175 /*
176 * If not specified, find the right interval default.
177 * Then create the event sem to block on.
178 */
179 if (!g_uControlIntervalMS)
180 g_uControlIntervalMS = 1000;
181
182 int rc = RTSemEventMultiCreate(&g_hControlEvent);
183 AssertRCReturn(rc, rc);
184
185 rc = VbglR3GuestCtrlConnect(&g_uControlSvcClientID);
186 if (RT_SUCCESS(rc))
187 {
188 VBoxServiceVerbose(3, "Service client ID: %#x\n", g_uControlSvcClientID);
189
190 /* Init thread lists. */
191 RTListInit(&g_lstControlThreadsActive);
192 RTListInit(&g_lstControlThreadsInactive);
193
194 /* Init critical section for protecting the thread lists. */
195 rc = RTCritSectInit(&g_csControlThreads);
196 AssertRC(rc);
197 }
198 else
199 {
200 /* If the service was not found, we disable this service without
201 causing VBoxService to fail. */
202 if (rc == VERR_HGCM_SERVICE_NOT_FOUND) /* Host service is not available. */
203 {
204 VBoxServiceVerbose(0, "Guest control service is not available\n");
205 rc = VERR_SERVICE_DISABLED;
206 }
207 else
208 VBoxServiceError("Failed to connect to the guest control service! Error: %Rrc\n", rc);
209 RTSemEventMultiDestroy(g_hControlEvent);
210 g_hControlEvent = NIL_RTSEMEVENTMULTI;
211 }
212 return rc;
213}
214
215
216/** @copydoc VBOXSERVICE::pfnWorker */
217DECLCALLBACK(int) VBoxServiceControlWorker(bool volatile *pfShutdown)
218{
219 /*
220 * Tell the control thread that it can continue
221 * spawning services.
222 */
223 RTThreadUserSignal(RTThreadSelf());
224 Assert(g_uControlSvcClientID > 0);
225
226 int rc = VINF_SUCCESS;
227
228 /*
229 * Execution loop.
230 *
231 * @todo
232 */
233 for (;;)
234 {
235 VBoxServiceVerbose(3, "Waiting for host msg ...\n");
236 uint32_t uMsg = 0;
237 uint32_t cParms = 0;
238 rc = VbglR3GuestCtrlWaitForHostMsg(g_uControlSvcClientID, &uMsg, &cParms);
239 if (rc == VERR_TOO_MUCH_DATA)
240 {
241 VBoxServiceVerbose(4, "Message requires %ld parameters, but only 2 supplied -- retrying request (no error!)...\n", cParms);
242 rc = VINF_SUCCESS; /* Try to get "real" message in next block below. */
243 }
244 else if (RT_FAILURE(rc))
245 VBoxServiceVerbose(3, "Getting host message failed with %Rrc\n", rc); /* VERR_GEN_IO_FAILURE seems to be normal if ran into timeout. */
246 if (RT_SUCCESS(rc))
247 {
248 VBoxServiceVerbose(3, "Msg=%u (%u parms) retrieved\n", uMsg, cParms);
249 switch (uMsg)
250 {
251 case HOST_CANCEL_PENDING_WAITS:
252 VBoxServiceVerbose(3, "Host asked us to quit ...\n");
253 break;
254
255 case HOST_EXEC_CMD:
256 rc = VBoxServiceControlHandleCmdStartProc(g_uControlSvcClientID, cParms);
257 break;
258
259 case HOST_EXEC_SET_INPUT:
260 /** @todo Make buffer size configurable via guest properties/argv! */
261 rc = VBoxServiceControlHandleCmdSetInput(g_uControlSvcClientID, cParms, _1M /* Buffer size */);
262 break;
263
264 case HOST_EXEC_GET_OUTPUT:
265 rc = VBoxServiceControlHandleCmdGetOutput(g_uControlSvcClientID, cParms);
266 break;
267
268 default:
269 VBoxServiceVerbose(3, "Unsupported message from host! Msg=%u\n", uMsg);
270 /* Don't terminate here; just wait for the next message. */
271 break;
272 }
273 }
274
275 /* Do we need to shutdown? */
276 if ( *pfShutdown
277 || uMsg == HOST_CANCEL_PENDING_WAITS)
278 {
279 rc = VINF_SUCCESS;
280 break;
281 }
282
283 /* Let's sleep for a bit and let others run ... */
284 RTThreadYield();
285 }
286
287 return rc;
288}
289
290
291/**
292 * Handles starting processes on the guest.
293 *
294 * @returns IPRT status code.
295 * @param uClientID The HGCM client session ID.
296 * @param cParms The number of parameters the host is offering.
297 */
298static int VBoxServiceControlHandleCmdStartProc(uint32_t uClientID, uint32_t cParms)
299{
300 uint32_t uContextID = 0;
301
302 int rc;
303 bool fStartAllowed = false; /* Flag indicating whether starting a process is allowed or not. */
304 if (cParms == 11)
305 {
306 VBOXSERVICECTRLPROCESS proc;
307 RT_ZERO(proc);
308
309 rc = VbglR3GuestCtrlExecGetHostCmdExec(uClientID,
310 cParms,
311 &uContextID,
312 /* Command */
313 proc.szCmd, sizeof(proc.szCmd),
314 /* Flags */
315 &proc.uFlags,
316 /* Arguments */
317 proc.szArgs, sizeof(proc.szArgs), &proc.uNumArgs,
318 /* Environment */
319 proc.szEnv, &proc.cbEnv, &proc.uNumEnvVars,
320 /* Credentials */
321 proc.szUser, sizeof(proc.szUser),
322 proc.szPassword, sizeof(proc.szPassword),
323 /* Timelimit */
324 &proc.uTimeLimitMS);
325 if (RT_SUCCESS(rc))
326 {
327 VBoxServiceVerbose(3, "Request to start process szCmd=%s, uFlags=0x%x, szArgs=%s, szEnv=%s, szUser=%s, uTimeout=%u\n",
328 proc.szCmd, proc.uFlags,
329 proc.uNumArgs ? proc.szArgs : "<None>",
330 proc.uNumEnvVars ? proc.szEnv : "<None>",
331 proc.szUser, proc.uTimeLimitMS);
332
333 rc = VBoxServiceControlReapThreads();
334 if (RT_FAILURE(rc))
335 VBoxServiceError("Reaping stopped processes failed with rc=%Rrc\n", rc);
336 /* Keep going. */
337
338 rc = VBoxServiceControlStartAllowed(&fStartAllowed);
339 if (RT_SUCCESS(rc))
340 {
341 if (fStartAllowed)
342 {
343 rc = VBoxServiceControlThreadStart(uContextID, &proc);
344 }
345 else
346 rc = VERR_MAX_PROCS_REACHED; /* Maximum number of processes reached. */
347 }
348 }
349 }
350 else
351 rc = VERR_INVALID_PARAMETER; /* Incorrect number of parameters. */
352
353 /* In case of an error we need to notify the host to not wait forever for our response. */
354 if (RT_FAILURE(rc))
355 {
356 VBoxServiceError("Starting process failed with rc=%Rrc\n", rc);
357
358 /*
359 * Note: The context ID can be 0 because we mabye weren't able to fetch the command
360 * from the host. The host in case has to deal with that!
361 */
362 int rc2 = VbglR3GuestCtrlExecReportStatus(uClientID, uContextID /* Might be 0 */, 0 /* PID, invalid */,
363 PROC_STS_ERROR, rc,
364 NULL /* pvData */, 0 /* cbData */);
365 if (RT_FAILURE(rc2))
366 {
367 VBoxServiceError("Error sending start process status to host, rc=%Rrc\n", rc2);
368 if (RT_SUCCESS(rc))
369 rc = rc2;
370 }
371 }
372
373 return rc;
374}
375
376
377/**
378 * Gets output from stdout/stderr of a specified guest process.
379 *
380 * @return IPRT status code.
381 * @param uPID PID of process to retrieve the output from.
382 * @param uHandleId Stream ID (stdout = 0, stderr = 2) to get the output from.
383 * @param uTimeout Timeout (in ms) to wait for output becoming available.
384 * @param pvBuf Pointer to a pre-allocated buffer to store the output.
385 * @param cbBuf Size (in bytes) of the pre-allocated buffer.
386 * @param pcbRead Pointer to number of bytes read. Optional.
387 */
388int VBoxServiceControlExecGetOutput(uint32_t uPID, uint32_t uCID,
389 uint32_t uHandleId, uint32_t uTimeout,
390 void *pvBuf, uint32_t cbBuf, uint32_t *pcbRead)
391{
392 AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
393 AssertReturn(cbBuf, VERR_INVALID_PARAMETER);
394 /* pcbRead is optional. */
395
396 int rc = VINF_SUCCESS;
397 VBOXSERVICECTRLREQUESTTYPE reqType;
398 switch (uHandleId)
399 {
400 case OUTPUT_HANDLE_ID_STDERR:
401 reqType = VBOXSERVICECTRLREQUEST_STDERR_READ;
402 break;
403
404 case OUTPUT_HANDLE_ID_STDOUT:
405 case OUTPUT_HANDLE_ID_STDOUT_DEPRECATED:
406 reqType = VBOXSERVICECTRLREQUEST_STDOUT_READ;
407 break;
408
409 default:
410 rc = VERR_INVALID_PARAMETER;
411 break;
412 }
413
414 PVBOXSERVICECTRLREQUEST pRequest;
415 if (RT_SUCCESS(rc))
416 {
417 rc = VBoxServiceControlThreadRequestAllocEx(&pRequest, reqType,
418 pvBuf, cbBuf, uCID);
419 if (RT_SUCCESS(rc))
420 rc = VBoxServiceControlThreadPerform(uPID, pRequest);
421
422 if (RT_SUCCESS(rc))
423 {
424 if (pcbRead)
425 *pcbRead = pRequest->cbData;
426 }
427
428 VBoxServiceControlThreadRequestFree(pRequest);
429 }
430
431 return rc;
432}
433
434
435/**
436 * Sets the specified guest thread to a certain list.
437 *
438 * @return IPRT status code.
439 * @param enmList List to move thread to.
440 * @param pThread Thread to set inactive.
441 */
442int VBoxServiceControlListSet(VBOXSERVICECTRLTHREADLISTTYPE enmList,
443 PVBOXSERVICECTRLTHREAD pThread)
444{
445 AssertReturn(enmList > VBOXSERVICECTRLTHREADLIST_UNKNOWN, VERR_INVALID_PARAMETER);
446 AssertPtrReturn(pThread, VERR_INVALID_POINTER);
447
448 int rc = RTCritSectEnter(&g_csControlThreads);
449 if (RT_SUCCESS(rc))
450 {
451 VBoxServiceVerbose(3, "Setting thread (PID %u) to list %d\n",
452 pThread->uPID, enmList);
453
454 PRTLISTANCHOR pAnchor = NULL;
455 switch (enmList)
456 {
457 case VBOXSERVICECTRLTHREADLIST_STOPPED:
458 pAnchor = &g_lstControlThreadsInactive;
459 break;
460
461 case VBOXSERVICECTRLTHREADLIST_RUNNING:
462 pAnchor = &g_lstControlThreadsActive;
463 break;
464
465 default:
466 AssertMsgFailed(("Unknown list type: %u", enmList));
467 break;
468 }
469
470 if (!pAnchor)
471 rc = VERR_INVALID_PARAMETER;
472
473 if (RT_SUCCESS(rc))
474 {
475 if (pThread->pAnchor != NULL)
476 {
477 /* If thread was assigned to a list before,
478 * remove the thread from the old list first. */
479 /* rc = */ RTListNodeRemove(&pThread->Node);
480 }
481
482 /* Add thread to desired list. */
483 /* rc = */ RTListAppend(pAnchor, &pThread->Node);
484 pThread->pAnchor = pAnchor;
485 }
486
487 int rc2 = RTCritSectLeave(&g_csControlThreads);
488 if (RT_SUCCESS(rc))
489 rc = rc2;
490 }
491
492 return VINF_SUCCESS;
493}
494
495
496/**
497 * Injects input to a specified running process.
498 *
499 * @return IPRT status code.
500 * @param uPID PID of process to set the input for.
501 * @param fPendingClose Flag indicating whether this is the last input block sent to the process.
502 * @param pvBuf Pointer to a buffer containing the actual input data.
503 * @param cbBuf Size (in bytes) of the input buffer data.
504 * @param pcbWritten Pointer to number of bytes written to the process. Optional.
505 */
506int VBoxServiceControlSetInput(uint32_t uPID, uint32_t uCID,
507 bool fPendingClose,
508 void *pvBuf, uint32_t cbBuf,
509 uint32_t *pcbWritten)
510{
511 /* pvBuf is optional. */
512 /* cbBuf is optional. */
513 /* pcbWritten is optional. */
514
515 PVBOXSERVICECTRLREQUEST pRequest;
516 int rc = VBoxServiceControlThreadRequestAllocEx(&pRequest,
517 fPendingClose
518 ? VBOXSERVICECTRLREQUEST_STDIN_WRITE_EOF
519 : VBOXSERVICECTRLREQUEST_STDIN_WRITE,
520 pvBuf, cbBuf, uCID);
521 if (RT_SUCCESS(rc))
522 {
523 rc = VBoxServiceControlThreadPerform(uPID, pRequest);
524 if (RT_SUCCESS(rc))
525 {
526 if (pcbWritten)
527 *pcbWritten = pRequest->cbData;
528 }
529
530 VBoxServiceControlThreadRequestFree(pRequest);
531 }
532
533 return rc;
534}
535
536
537/**
538 * Handles input for a started process by copying the received data into its
539 * stdin pipe.
540 *
541 * @returns IPRT status code.
542 * @param idClient The HGCM client session ID.
543 * @param cParms The number of parameters the host is
544 * offering.
545 * @param cMaxBufSize The maximum buffer size for retrieving the input data.
546 */
547static int VBoxServiceControlHandleCmdSetInput(uint32_t idClient, uint32_t cParms, size_t cbMaxBufSize)
548{
549 uint32_t uContextID;
550 uint32_t uPID;
551 uint32_t uFlags;
552 uint32_t cbSize;
553
554 AssertReturn(RT_IS_POWER_OF_TWO(cbMaxBufSize), VERR_INVALID_PARAMETER);
555 uint8_t *pabBuffer = (uint8_t*)RTMemAlloc(cbMaxBufSize);
556 AssertPtrReturn(pabBuffer, VERR_NO_MEMORY);
557
558 uint32_t uStatus = INPUT_STS_UNDEFINED; /* Status sent back to the host. */
559 uint32_t cbWritten = 0; /* Number of bytes written to the guest. */
560
561 /*
562 * Ask the host for the input data.
563 */
564 int rc = VbglR3GuestCtrlExecGetHostCmdInput(idClient, cParms,
565 &uContextID, &uPID, &uFlags,
566 pabBuffer, cbMaxBufSize, &cbSize);
567 if (RT_FAILURE(rc))
568 {
569 VBoxServiceError("[PID %u]: Failed to retrieve exec input command! Error: %Rrc\n",
570 uPID, rc);
571 }
572 else if (cbSize > cbMaxBufSize)
573 {
574 VBoxServiceError("[PID %u]: Too much input received! cbSize=%u, cbMaxBufSize=%u\n",
575 uPID, cbSize, cbMaxBufSize);
576 rc = VERR_INVALID_PARAMETER;
577 }
578 else
579 {
580 /*
581 * Is this the last input block we need to deliver? Then let the pipe know ...
582 */
583 bool fPendingClose = false;
584 if (uFlags & INPUT_FLAG_EOF)
585 {
586 fPendingClose = true;
587 VBoxServiceVerbose(4, "[PID %u]: Got last input block of size %u ...\n",
588 uPID, cbSize);
589 }
590
591 rc = VBoxServiceControlSetInput(uPID, uContextID, fPendingClose, pabBuffer,
592 cbSize, &cbWritten);
593 VBoxServiceVerbose(4, "[PID %u]: Written input, CID=%u, rc=%Rrc, uFlags=0x%x, fPendingClose=%d, cbSize=%u, cbWritten=%u\n",
594 uPID, uContextID, rc, uFlags, fPendingClose, cbSize, cbWritten);
595 if (RT_SUCCESS(rc))
596 {
597 uStatus = INPUT_STS_WRITTEN;
598 uFlags = 0; /* No flags at the moment. */
599 }
600 else
601 {
602 if (rc == VERR_BAD_PIPE)
603 uStatus = INPUT_STS_TERMINATED;
604 else if (rc == VERR_BUFFER_OVERFLOW)
605 uStatus = INPUT_STS_OVERFLOW;
606 }
607 }
608 RTMemFree(pabBuffer);
609
610 /*
611 * If there was an error and we did not set the host status
612 * yet, then do it now.
613 */
614 if ( RT_FAILURE(rc)
615 && uStatus == INPUT_STS_UNDEFINED)
616 {
617 uStatus = INPUT_STS_ERROR;
618 uFlags = rc;
619 }
620 Assert(uStatus > INPUT_STS_UNDEFINED);
621
622 VBoxServiceVerbose(3, "[PID %u]: Input processed, CID=%u, uStatus=%u, uFlags=0x%x, cbWritten=%u\n",
623 uPID, uContextID, uStatus, uFlags, cbWritten);
624
625 /* Note: Since the context ID is unique the request *has* to be completed here,
626 * regardless whether we got data or not! Otherwise the progress object
627 * on the host never will get completed! */
628 rc = VbglR3GuestCtrlExecReportStatusIn(idClient, uContextID, uPID,
629 uStatus, uFlags, (uint32_t)cbWritten);
630
631 if (RT_FAILURE(rc))
632 VBoxServiceError("[PID %u]: Failed to report input status! Error: %Rrc\n",
633 uPID, rc);
634 return rc;
635}
636
637
638/**
639 * Handles the guest control output command.
640 *
641 * @return IPRT status code.
642 * @param idClient The HGCM client session ID.
643 * @param cParms The number of parameters the host is offering.
644 */
645static int VBoxServiceControlHandleCmdGetOutput(uint32_t idClient, uint32_t cParms)
646{
647 uint32_t uContextID;
648 uint32_t uPID;
649 uint32_t uHandleID;
650 uint32_t uFlags;
651
652 int rc = VbglR3GuestCtrlExecGetHostCmdOutput(idClient, cParms,
653 &uContextID, &uPID, &uHandleID, &uFlags);
654 if (RT_SUCCESS(rc))
655 {
656 uint8_t *pBuf = (uint8_t*)RTMemAlloc(_64K);
657 if (pBuf)
658 {
659 uint32_t cbRead = 0;
660 rc = VBoxServiceControlExecGetOutput(uPID, uContextID, uHandleID, RT_INDEFINITE_WAIT /* Timeout */,
661 pBuf, _64K /* cbSize */, &cbRead);
662 VBoxServiceVerbose(3, "[PID %u]: Got output, rc=%Rrc, CID=%u, cbRead=%u, uHandle=%u, uFlags=%u\n",
663 uPID, rc, uContextID, cbRead, uHandleID, uFlags);
664
665#ifdef DEBUG
666 if ( g_fControlDumpStdErr
667 && uHandleID == OUTPUT_HANDLE_ID_STDERR)
668 {
669 char szPID[RTPATH_MAX];
670 if (!RTStrPrintf(szPID, sizeof(szPID), "VBoxService_PID%u_StdOut.txt", uPID))
671 rc = VERR_BUFFER_UNDERFLOW;
672 if (RT_SUCCESS(rc))
673 rc = vboxServiceControlDump(szPID, pBuf, cbRead);
674 }
675 else if ( g_fControlDumpStdOut
676 && ( uHandleID == OUTPUT_HANDLE_ID_STDOUT
677 || uHandleID == OUTPUT_HANDLE_ID_STDOUT_DEPRECATED))
678 {
679 char szPID[RTPATH_MAX];
680 if (!RTStrPrintf(szPID, sizeof(szPID), "VBoxService_PID%u_StdOut.txt", uPID))
681 rc = VERR_BUFFER_UNDERFLOW;
682 if (RT_SUCCESS(rc))
683 rc = vboxServiceControlDump(szPID, pBuf, cbRead);
684 AssertRC(rc);
685 }
686#endif
687 /** Note: Don't convert/touch/modify/whatever the output data here! This might be binary
688 * data which the host needs to work with -- so just pass through all data unfiltered! */
689
690 /* Note: Since the context ID is unique the request *has* to be completed here,
691 * regardless whether we got data or not! Otherwise the progress object
692 * on the host never will get completed! */
693 int rc2 = VbglR3GuestCtrlExecSendOut(idClient, uContextID, uPID, uHandleID, uFlags,
694 pBuf, cbRead);
695 if (RT_SUCCESS(rc))
696 rc = rc2;
697 else if (rc == VERR_NOT_FOUND) /* It's not critical if guest process (PID) is not found. */
698 rc = VINF_SUCCESS;
699
700 RTMemFree(pBuf);
701 }
702 else
703 rc = VERR_NO_MEMORY;
704 }
705
706 if (RT_FAILURE(rc))
707 VBoxServiceError("[PID %u]: Error handling output command! Error: %Rrc\n",
708 uPID, rc);
709 return rc;
710}
711
712
713/** @copydoc VBOXSERVICE::pfnStop */
714static DECLCALLBACK(void) VBoxServiceControlStop(void)
715{
716 VBoxServiceVerbose(3, "Stopping ...\n");
717
718 /** @todo Later, figure what to do if we're in RTProcWait(). It's a very
719 * annoying call since doesn't support timeouts in the posix world. */
720 if (g_hControlEvent != NIL_RTSEMEVENTMULTI)
721 RTSemEventMultiSignal(g_hControlEvent);
722
723 /*
724 * Ask the host service to cancel all pending requests so that we can
725 * shutdown properly here.
726 */
727 if (g_uControlSvcClientID)
728 {
729 VBoxServiceVerbose(3, "Cancelling pending waits (client ID=%u) ...\n",
730 g_uControlSvcClientID);
731
732 int rc = VbglR3GuestCtrlCancelPendingWaits(g_uControlSvcClientID);
733 if (RT_FAILURE(rc))
734 VBoxServiceError("Cancelling pending waits failed; rc=%Rrc\n", rc);
735 }
736}
737
738
739/**
740 * Reaps all inactive guest process threads.
741 *
742 * @return IPRT status code.
743 */
744static int VBoxServiceControlReapThreads(void)
745{
746 int rc = RTCritSectEnter(&g_csControlThreads);
747 if (RT_SUCCESS(rc))
748 {
749 PVBOXSERVICECTRLTHREAD pThread =
750 RTListGetFirst(&g_lstControlThreadsInactive, VBOXSERVICECTRLTHREAD, Node);
751 while (pThread)
752 {
753 PVBOXSERVICECTRLTHREAD pNext = RTListNodeGetNext(&pThread->Node, VBOXSERVICECTRLTHREAD, Node);
754 bool fLast = RTListNodeIsLast(&g_lstControlThreadsInactive, &pThread->Node);
755 int rc2 = VBoxServiceControlThreadWait(pThread, 30 * 1000 /* 30 seconds max. */,
756 NULL /* rc */);
757 if (RT_SUCCESS(rc2))
758 {
759 RTListNodeRemove(&pThread->Node);
760
761 rc2 = VBoxServiceControlThreadFree(pThread);
762 if (RT_FAILURE(rc2))
763 {
764 VBoxServiceError("Freeing guest process thread failed with rc=%Rrc\n", rc2);
765 if (RT_SUCCESS(rc)) /* Keep original failure. */
766 rc = rc2;
767 }
768 }
769 else
770 VBoxServiceError("Waiting on guest process thread failed with rc=%Rrc\n", rc2);
771 /* Keep going. */
772
773 if (fLast)
774 break;
775
776 pThread = pNext;
777 }
778
779 int rc2 = RTCritSectLeave(&g_csControlThreads);
780 if (RT_SUCCESS(rc))
781 rc = rc2;
782 }
783
784 VBoxServiceVerbose(4, "Reaping threads returned with rc=%Rrc\n", rc);
785 return rc;
786}
787
788
789/**
790 * Destroys all guest process threads which are still active.
791 */
792static void VBoxServiceControlShutdown(void)
793{
794 VBoxServiceVerbose(2, "Shutting down ...\n");
795
796 /* Signal all threads in the active list that we want to shutdown. */
797 PVBOXSERVICECTRLTHREAD pThread;
798 RTListForEach(&g_lstControlThreadsActive, pThread, VBOXSERVICECTRLTHREAD, Node)
799 VBoxServiceControlThreadStop(pThread);
800
801 /* Wait for all active threads to shutdown and destroy the active thread list. */
802 pThread = RTListGetFirst(&g_lstControlThreadsActive, VBOXSERVICECTRLTHREAD, Node);
803 while (pThread)
804 {
805 PVBOXSERVICECTRLTHREAD pNext = RTListNodeGetNext(&pThread->Node, VBOXSERVICECTRLTHREAD, Node);
806 bool fLast = RTListNodeIsLast(&g_lstControlThreadsActive, &pThread->Node);
807
808 int rc2 = VBoxServiceControlThreadWait(pThread,
809 30 * 1000 /* Wait 30 seconds max. */,
810 NULL /* rc */);
811 if (RT_FAILURE(rc2))
812 VBoxServiceError("Guest process thread failed to stop; rc=%Rrc\n", rc2);
813
814 if (fLast)
815 break;
816
817 pThread = pNext;
818 }
819
820 int rc2 = VBoxServiceControlReapThreads();
821 if (RT_FAILURE(rc2))
822 VBoxServiceError("Reaping inactive threads failed with rc=%Rrc\n", rc2);
823
824 AssertMsg(RTListIsEmpty(&g_lstControlThreadsActive),
825 ("Guest process active thread list still contains entries when it should not\n"));
826 AssertMsg(RTListIsEmpty(&g_lstControlThreadsInactive),
827 ("Guest process inactive thread list still contains entries when it should not\n"));
828
829 /* Destroy critical section. */
830 RTCritSectDelete(&g_csControlThreads);
831
832 VBoxServiceVerbose(2, "Shutting down complete\n");
833}
834
835
836/** @copydoc VBOXSERVICE::pfnTerm */
837static DECLCALLBACK(void) VBoxServiceControlTerm(void)
838{
839 VBoxServiceVerbose(3, "Terminating ...\n");
840
841 VBoxServiceControlShutdown();
842
843 VBoxServiceVerbose(3, "Disconnecting client ID=%u ...\n",
844 g_uControlSvcClientID);
845 VbglR3GuestCtrlDisconnect(g_uControlSvcClientID);
846 g_uControlSvcClientID = 0;
847
848 if (g_hControlEvent != NIL_RTSEMEVENTMULTI)
849 {
850 RTSemEventMultiDestroy(g_hControlEvent);
851 g_hControlEvent = NIL_RTSEMEVENTMULTI;
852 }
853}
854
855
856/**
857 * Determines whether starting a new guest process according to the
858 * maximum number of concurrent guest processes defined is allowed or not.
859 *
860 * @return IPRT status code.
861 * @param pbAllowed True if starting (another) guest process
862 * is allowed, false if not.
863 */
864static int VBoxServiceControlStartAllowed(bool *pbAllowed)
865{
866 AssertPtrReturn(pbAllowed, VERR_INVALID_POINTER);
867
868 int rc = RTCritSectEnter(&g_csControlThreads);
869 if (RT_SUCCESS(rc))
870 {
871 /*
872 * Check if we're respecting our memory policy by checking
873 * how many guest processes are started and served already.
874 */
875 bool fLimitReached = false;
876 if (g_uControlProcsMaxKept) /* If we allow unlimited processes (=0), take a shortcut. */
877 {
878 uint32_t uProcsRunning = 0;
879 PVBOXSERVICECTRLTHREAD pThread;
880 RTListForEach(&g_lstControlThreadsActive, pThread, VBOXSERVICECTRLTHREAD, Node)
881 uProcsRunning++;
882
883 VBoxServiceVerbose(3, "Maximum served guest processes set to %u, running=%u\n",
884 g_uControlProcsMaxKept, uProcsRunning);
885
886 int32_t iProcsLeft = (g_uControlProcsMaxKept - uProcsRunning - 1);
887 if (iProcsLeft < 0)
888 {
889 VBoxServiceVerbose(3, "Maximum running guest processes reached (%u)\n",
890 g_uControlProcsMaxKept);
891 fLimitReached = true;
892 }
893 }
894
895 *pbAllowed = !fLimitReached;
896
897 int rc2 = RTCritSectLeave(&g_csControlThreads);
898 if (RT_SUCCESS(rc))
899 rc = rc2;
900 }
901
902 return rc;
903}
904
905
906/**
907 * Finds a (formerly) started process given by its PID and locks it. Must be unlocked
908 * by the caller with VBoxServiceControlThreadUnlock().
909 *
910 * @return PVBOXSERVICECTRLTHREAD Process structure if found, otherwise NULL.
911 * @param uPID PID to search for.
912 */
913PVBOXSERVICECTRLTHREAD VBoxServiceControlLockThread(uint32_t uPID)
914{
915 PVBOXSERVICECTRLTHREAD pThread = NULL;
916 int rc = RTCritSectEnter(&g_csControlThreads);
917 if (RT_SUCCESS(rc))
918 {
919 PVBOXSERVICECTRLTHREAD pThreadCur;
920 RTListForEach(&g_lstControlThreadsActive, pThreadCur, VBOXSERVICECTRLTHREAD, Node)
921 {
922 if (pThreadCur->uPID == uPID)
923 {
924 rc = RTCritSectEnter(&pThreadCur->CritSect);
925 if (RT_SUCCESS(rc))
926 pThread = pThreadCur;
927 break;
928 }
929 }
930
931 int rc2 = RTCritSectLeave(&g_csControlThreads);
932 if (RT_SUCCESS(rc))
933 rc = rc2;
934 }
935
936 return pThread;
937}
938
939
940/**
941 * Unlocks a previously locked guest process thread.
942 *
943 * @param pThread Thread to unlock.
944 */
945void VBoxServiceControlUnlockThread(const PVBOXSERVICECTRLTHREAD pThread)
946{
947 AssertPtr(pThread);
948
949 int rc = RTCritSectLeave(&pThread->CritSect);
950 AssertRC(rc);
951}
952
953
954/**
955 * Assigns a valid PID to a guest control thread and also checks if there already was
956 * another (stale) guest process which was using that PID before and destroys it.
957 *
958 * @return IPRT status code.
959 * @param pThread Thread to assign PID to.
960 * @param uPID PID to assign to the specified guest control execution thread.
961 */
962int VBoxServiceControlAssignPID(PVBOXSERVICECTRLTHREAD pThread, uint32_t uPID)
963{
964 AssertPtrReturn(pThread, VERR_INVALID_POINTER);
965 AssertReturn(uPID, VERR_INVALID_PARAMETER);
966
967 int rc = RTCritSectEnter(&g_csControlThreads);
968 if (RT_SUCCESS(rc))
969 {
970 /* Search old threads using the desired PID and shut them down completely -- it's
971 * not used anymore. */
972 PVBOXSERVICECTRLTHREAD pThreadCur;
973 bool fTryAgain = false;
974 do
975 {
976 RTListForEach(&g_lstControlThreadsActive, pThreadCur, VBOXSERVICECTRLTHREAD, Node)
977 {
978 if (pThreadCur->uPID == uPID)
979 {
980 Assert(pThreadCur != pThread); /* can't happen */
981 uint32_t uTriedPID = uPID;
982 uPID += 391939;
983 VBoxServiceVerbose(2, "PID %u was used before, trying again with %u ...\n",
984 uTriedPID, uPID);
985 fTryAgain = true;
986 break;
987 }
988 }
989 } while (fTryAgain);
990
991 /* Assign PID to current thread. */
992 pThread->uPID = uPID;
993
994 rc = RTCritSectLeave(&g_csControlThreads);
995 AssertRC(rc);
996 }
997
998 return rc;
999}
1000
1001
1002/**
1003 * The 'vminfo' service description.
1004 */
1005VBOXSERVICE g_Control =
1006{
1007 /* pszName. */
1008 "control",
1009 /* pszDescription. */
1010 "Host-driven Guest Control",
1011 /* pszUsage. */
1012#ifdef DEBUG
1013 " [--control-dump-stderr] [--control-dump-stdout]\n"
1014#endif
1015 " [--control-interval <ms>] [--control-procs-max-kept <x>]\n"
1016 " [--control-procs-mem-std[in|out|err] <KB>]"
1017 ,
1018 /* pszOptions. */
1019#ifdef DEBUG
1020 " --control-dump-stderr Dumps all guest proccesses stderr data to the\n"
1021 " temporary directory.\n"
1022 " --control-dump-stdout Dumps all guest proccesses stdout data to the\n"
1023 " temporary directory.\n"
1024#endif
1025 " --control-interval Specifies the interval at which to check for\n"
1026 " new control commands. The default is 1000 ms.\n"
1027 " --control-procs-max-kept\n"
1028 " Specifies how many started guest processes are\n"
1029 " kept into memory to work with. Default is 25.\n"
1030 ,
1031 /* methods */
1032 VBoxServiceControlPreInit,
1033 VBoxServiceControlOption,
1034 VBoxServiceControlInit,
1035 VBoxServiceControlWorker,
1036 VBoxServiceControlStop,
1037 VBoxServiceControlTerm
1038};
1039
Note: See TracBrowser for help on using the repository browser.

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