VBoxServiceControl.cpp revision a3030ba6e494ae7402749b6c34e29e15a4829a66
/* $Id$ */
/** @file
* VBoxServiceControl - Host-driven Guest Control.
*/
/*
* Copyright (C) 2012 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#include <iprt/semaphore.h>
#include <VBox/VBoxGuestLib.h>
#include "VBoxServiceInternal.h"
#include "VBoxServiceUtils.h"
using namespace guestControl;
/*******************************************************************************
* Global Variables *
*******************************************************************************/
/** The control interval (milliseconds). */
static uint32_t g_uControlIntervalMS = 0;
/** The semaphore we're blocking our main control thread on. */
/** The guest control service client ID. */
static uint32_t g_uControlSvcClientID = 0;
/** How many started guest processes are kept into memory for supplying
* information to the host. Default is 256 processes. If 0 is specified,
* the maximum number of processes is unlimited. */
#ifdef DEBUG
static bool g_fControlDumpStdErr = false;
static bool g_fControlDumpStdOut = false;
#endif
/** List of active guest control threads (VBOXSERVICECTRLTHREAD). */
/** List of inactive guest control threads (VBOXSERVICECTRLTHREAD). */
/** Critical section protecting g_GuestControlExecThreads. */
static RTCRITSECT g_csControlThreads;
/** List of guest control files (VBOXSERVICECTRLFILE).
**@todo Use a map (later). */
static RTLISTANCHOR g_lstControlFiles;
/** The internal file count for building our internal file handles.
* Should be enough for now. */
static uint32_t g_uControlFileCount = 0;
/*******************************************************************************
* Internal Functions *
*******************************************************************************/
/** @todo Shorten "VBoxServiceControl" to "gstsvcCntl". */
static int VBoxServiceControlReapThreads(void);
static int VBoxServiceControlStartAllowed(bool *pbAllowed);
static int VBoxServiceControlHandleCmdSetInput(uint32_t u32ClientId, uint32_t uNumParms, void *pvScratchBuf, size_t cbScratchBuf);
static int VBoxServiceControlHandleFileWrite(uint32_t idClient, uint32_t cParms, void *pvScratchBuf, size_t cbScratchBuf);
#ifdef DEBUG
{
if (!cbBuf)
return VINF_SUCCESS;
char szFile[RTPATH_MAX];
if (RT_SUCCESS(rc))
if (RT_SUCCESS(rc))
{
if (RT_SUCCESS(rc))
{
}
}
return rc;
}
#endif
/** @copydoc VBOXSERVICE::pfnPreInit */
static DECLCALLBACK(int) VBoxServiceControlPreInit(void)
{
#ifdef VBOX_WITH_GUEST_PROPS
/*
* Read the service options from the VM's guest properties.
* Note that these options can be overridden by the command line options later.
*/
if (RT_FAILURE(rc))
{
{
VBoxServiceVerbose(0, "Guest property service is not available, skipping\n");
rc = VINF_SUCCESS;
}
else
}
else
{
rc = VBoxServiceReadPropUInt32(uGuestPropSvcClientID, "/VirtualBox/GuestAdd/VBoxService/--control-procs-max-kept",
}
rc = VINF_SUCCESS;
return rc;
#else
/* Nothing to do here yet. */
return VINF_SUCCESS;
#endif
}
/** @copydoc VBOXSERVICE::pfnOption */
static DECLCALLBACK(int) VBoxServiceControlOption(const char **ppszShort, int argc, char **argv, int *pi)
{
int rc = -1;
if (ppszShort)
/* no short options */;
#ifdef DEBUG
{
g_fControlDumpStdErr = true;
rc = 0; /* Flag this command as parsed. */
}
{
g_fControlDumpStdOut = true;
rc = 0; /* Flag this command as parsed. */
}
#endif
return rc;
}
/** @copydoc VBOXSERVICE::pfnInit */
static DECLCALLBACK(int) VBoxServiceControlInit(void)
{
/*
* If not specified, find the right interval default.
* Then create the event sem to block on.
*/
if (!g_uControlIntervalMS)
g_uControlIntervalMS = 1000;
if (RT_SUCCESS(rc))
{
/* Init lists. */
/* Init critical section for protecting the thread lists. */
}
else
{
/* If the service was not found, we disable this service without
causing VBoxService to fail. */
{
VBoxServiceVerbose(0, "Guest control service is not available\n");
}
else
}
return rc;
}
/** @copydoc VBOXSERVICE::pfnWorker */
{
/*
* Tell the control thread that it can continue
* spawning services.
*/
Assert(g_uControlSvcClientID > 0);
int rc = VINF_SUCCESS;
/* Allocate a scratch buffer for commands which also send
* payload data with them. */
/*
* Execution loop.
*
* @todo
*/
for (;;)
{
if (rc == VERR_TOO_MUCH_DATA)
{
VBoxServiceVerbose(4, "Message requires %ld parameters, but only 2 supplied -- retrying request (no error!)...\n", cParms);
}
else if (RT_FAILURE(rc))
VBoxServiceVerbose(3, "Getting host message failed with %Rrc\n", rc); /* VERR_GEN_IO_FAILURE seems to be normal if ran into timeout. */
if (RT_SUCCESS(rc))
{
switch (uMsg)
{
break;
case HOST_EXEC_CMD:
break;
case HOST_EXEC_SET_INPUT:
break;
case HOST_EXEC_GET_OUTPUT:
break;
case HOST_FILE_OPEN:
break;
case HOST_FILE_CLOSE:
break;
case HOST_FILE_READ:
break;
case HOST_FILE_WRITE:
break;
case HOST_FILE_SEEK:
break;
case HOST_FILE_TELL:
break;
default:
/* Don't terminate here; just wait for the next message. */
break;
}
}
/* Do we need to shutdown? */
if ( *pfShutdown
{
rc = VINF_SUCCESS;
break;
}
/* Let's sleep for a bit and let others run ... */
}
/* Delete scratch buffer. */
if (pvScratchBuf)
return rc;
}
/**
* Handles starting processes on the guest.
*
* @returns IPRT status code.
* @param uClientID The HGCM client session ID.
* @param cParms The number of parameters the host is offering.
*/
{
uint32_t uContextID = 0;
int rc;
bool fStartAllowed = false; /* Flag indicating whether starting a process is allowed or not. */
if (cParms == 11)
{
/* Initialize maximum environment block size -- needed as input
* parameter to retrieve the stuff from the host. On output this then
* will contain the actual block size. */
/* Command */
/* Flags */
/* Arguments */
/* Environment */
/* Credentials */
/* Timelimit */
&proc.uTimeLimitMS);
if (RT_SUCCESS(rc))
{
VBoxServiceVerbose(3, "Request to start process szCmd=%s, uFlags=0x%x, szArgs=%s, szEnv=%s, szUser=%s, szPassword=%s, uTimeout=%u\n",
#ifdef DEBUG
#else
"XXX", /* Never show passwords in release mode. */
#endif
if (RT_FAILURE(rc))
/* Keep going. */
if (RT_SUCCESS(rc))
{
if (fStartAllowed)
{
}
else
}
}
}
else
/* In case of an error we need to notify the host to not wait forever for our response. */
if (RT_FAILURE(rc))
{
/*
* Note: The context ID can be 0 because we mabye weren't able to fetch the command
* from the host. The host in case has to deal with that!
*/
int rc2 = VbglR3GuestCtrlExecReportStatus(uClientID, uContextID /* Might be 0 */, 0 /* PID, invalid */,
if (RT_FAILURE(rc2))
{
if (RT_SUCCESS(rc))
}
}
return rc;
}
/**
*
* @return IPRT status code.
* @param uPID PID of process to retrieve the output from.
* @param uHandleId Stream ID (stdout = 0, stderr = 2) to get the output from.
* @param uTimeout Timeout (in ms) to wait for output becoming available.
* @param pvBuf Pointer to a pre-allocated buffer to store the output.
* @param cbBuf Size (in bytes) of the pre-allocated buffer.
* @param pcbRead Pointer to number of bytes read. Optional.
*/
{
/* pcbRead is optional. */
int rc = VINF_SUCCESS;
switch (uHandleId)
{
case OUTPUT_HANDLE_ID_STDERR:
break;
case OUTPUT_HANDLE_ID_STDOUT:
break;
default:
break;
}
if (RT_SUCCESS(rc))
{
if (RT_SUCCESS(rc))
if (RT_SUCCESS(rc))
{
if (pcbRead)
}
}
return rc;
}
/**
* Sets the specified guest thread to a certain list.
*
* @return IPRT status code.
* @param enmList List to move thread to.
* @param pThread Thread to set inactive.
*/
{
if (RT_SUCCESS(rc))
{
switch (enmList)
{
break;
break;
default:
break;
}
if (!pAnchor)
if (RT_SUCCESS(rc))
{
{
/* If thread was assigned to a list before,
* remove the thread from the old list first. */
}
/* Add thread to desired list. */
}
if (RT_SUCCESS(rc))
}
return VINF_SUCCESS;
}
/**
* Injects input to a specified running process.
*
* @return IPRT status code.
* @param uPID PID of process to set the input for.
* @param fPendingClose Flag indicating whether this is the last input block sent to the process.
* @param pvBuf Pointer to a buffer containing the actual input data.
* @param cbBuf Size (in bytes) of the input buffer data.
* @param pcbWritten Pointer to number of bytes written to the process. Optional.
*/
bool fPendingClose,
{
/* pvBuf is optional. */
/* cbBuf is optional. */
/* pcbWritten is optional. */
if (RT_SUCCESS(rc))
{
if (RT_SUCCESS(rc))
{
if (pcbWritten)
}
}
return rc;
}
/**
* Handles input for a started process by copying the received data into its
* stdin pipe.
*
* @returns IPRT status code.
* @param idClient The HGCM client session ID.
* @param cParms The number of parameters the host is
* offering.
* @param pvScratchBuf The scratch buffer.
* @param cbScratchBuf The scratch buffer size for retrieving the input data.
*/
{
/*
* Ask the host for the input data.
*/
if (RT_FAILURE(rc))
{
VBoxServiceError("[PID %u]: Failed to retrieve exec input command! Error: %Rrc\n",
}
else if (cbSize > cbScratchBuf)
{
VBoxServiceError("[PID %u]: Too much input received! cbSize=%u, cbScratchBuf=%u\n",
}
else
{
/*
* Is this the last input block we need to deliver? Then let the pipe know ...
*/
bool fPendingClose = false;
if (uFlags & INPUT_FLAG_EOF)
{
fPendingClose = true;
}
VBoxServiceVerbose(4, "[PID %u]: Written input, CID=%u, rc=%Rrc, uFlags=0x%x, fPendingClose=%d, cbSize=%u, cbWritten=%u\n",
if (RT_SUCCESS(rc))
{
uFlags = 0; /* No flags at the moment. */
}
else
{
if (rc == VERR_BAD_PIPE)
else if (rc == VERR_BUFFER_OVERFLOW)
}
}
/*
* If there was an error and we did not set the host status
* yet, then do it now.
*/
if ( RT_FAILURE(rc)
&& uStatus == INPUT_STS_UNDEFINED)
{
}
/* Note: Since the context ID is unique the request *has* to be completed here,
* regardless whether we got data or not! Otherwise the progress object
* on the host never will get completed! */
if (RT_FAILURE(rc))
VBoxServiceError("[PID %u]: Failed to report input status! Error: %Rrc\n",
return rc;
}
{
/** @todo Use a map later! */
{
return pFileCur;
}
return NULL;
}
{
char szFile[RTPATH_MAX];
char szOpenMode[64];
char szDisposition[64];
/* File to open. */
/* Open mode. */
szOpenMode, sizeof(szOpenMode),
/* Disposition. */
szDisposition, sizeof(szDisposition),
/* Creation mode. */
/* Offset. */
&uOffset);
if (RT_SUCCESS(rc))
{
if (!pFile)
return VERR_NO_MEMORY;
if (RT_SUCCESS(rc))
{
if ( RT_SUCCESS(rc)
&& uOffset)
{
/* Seeking is optional. */
if (RT_FAILURE(rc2))
}
else
}
if (RT_SUCCESS(rc))
{
}
if (RT_FAILURE(rc))
/* Report back in any case. */
if (RT_FAILURE(rc2))
VBoxServiceError("[File %s]: Failed to report open status, rc=%Rrc\n",
if (RT_SUCCESS(rc))
}
return rc;
}
{
/* File handle to close. */
&uHandle);
if (RT_SUCCESS(rc))
{
if (pFile)
{
}
else
rc = VERR_NOT_FOUND;
/* Report back in any case. */
if (RT_FAILURE(rc2))
if (RT_SUCCESS(rc))
}
return rc;
}
{
if (RT_SUCCESS(rc))
{
}
return rc;
}
{
&cbToWrite);
if (RT_SUCCESS(rc))
{
}
return rc;
}
{
if (RT_SUCCESS(rc))
{
}
return rc;
}
{
&uHandle);
if (RT_SUCCESS(rc))
{
}
return rc;
}
/**
* Handles the guest control output command.
*
* @return IPRT status code.
* @param idClient The HGCM client session ID.
* @param cParms The number of parameters the host is offering.
*/
{
if (RT_SUCCESS(rc))
{
if (pBuf)
{
#ifdef DEBUG
if ( g_fControlDumpStdErr
&& uHandleID == OUTPUT_HANDLE_ID_STDERR)
{
char szPID[RTPATH_MAX];
if (RT_SUCCESS(rc))
}
else if ( g_fControlDumpStdOut
&& ( uHandleID == OUTPUT_HANDLE_ID_STDOUT
{
char szPID[RTPATH_MAX];
if (RT_SUCCESS(rc))
}
#endif
* data which the host needs to work with -- so just pass through all data unfiltered! */
/* Note: Since the context ID is unique the request *has* to be completed here,
* regardless whether we got data or not! Otherwise the progress object
* on the host never will get completed! */
if (RT_SUCCESS(rc))
rc = VINF_SUCCESS;
}
else
rc = VERR_NO_MEMORY;
}
if (RT_FAILURE(rc))
VBoxServiceError("[PID %u]: Error handling output command! Error: %Rrc\n",
return rc;
}
/** @copydoc VBOXSERVICE::pfnStop */
static DECLCALLBACK(void) VBoxServiceControlStop(void)
{
/** @todo Later, figure what to do if we're in RTProcWait(). It's a very
* annoying call since doesn't support timeouts in the posix world. */
if (g_hControlEvent != NIL_RTSEMEVENTMULTI)
/*
* Ask the host service to cancel all pending requests so that we can
* shutdown properly here.
*/
{
if (RT_FAILURE(rc))
}
}
/**
* Reaps all inactive guest process threads.
*
* @return IPRT status code.
*/
static int VBoxServiceControlReapThreads(void)
{
if (RT_SUCCESS(rc))
{
while (pThread)
{
NULL /* rc */);
if (RT_SUCCESS(rc2))
{
if (RT_FAILURE(rc2))
{
}
}
else
/* Keep going. */
if (fLast)
break;
}
if (RT_SUCCESS(rc))
}
return rc;
}
/**
* Destroys all guest process threads which are still active.
*/
static void VBoxServiceControlShutdown(void)
{
/* Signal all threads in the active list that we want to shutdown. */
/* Wait for all active threads to shutdown and destroy the active thread list. */
while (pThread)
{
30 * 1000 /* Wait 30 seconds max. */,
NULL /* rc */);
if (RT_FAILURE(rc2))
if (fLast)
break;
}
int rc2 = VBoxServiceControlReapThreads();
if (RT_FAILURE(rc2))
("Guest process active thread list still contains entries when it should not\n"));
("Guest process inactive thread list still contains entries when it should not\n"));
/* Destroy critical section. */
/* Close all left guest files. */
while (pFile)
{
if (RT_FAILURE(rc2))
{
VBoxServiceError("Unable to close file \"%s\"; rc=%Rrc\n",
/* Keep going. */
}
if (fLast)
break;
}
("Guest file list still contains entries when it should not\n"));
}
/** @copydoc VBOXSERVICE::pfnTerm */
static DECLCALLBACK(void) VBoxServiceControlTerm(void)
{
if (g_hControlEvent != NIL_RTSEMEVENTMULTI)
{
}
}
/**
* Determines whether starting a new guest process according to the
* maximum number of concurrent guest processes defined is allowed or not.
*
* @return IPRT status code.
* @param pbAllowed True if starting (another) guest process
* is allowed, false if not.
*/
static int VBoxServiceControlStartAllowed(bool *pbAllowed)
{
if (RT_SUCCESS(rc))
{
/*
* Check if we're respecting our memory policy by checking
* how many guest processes are started and served already.
*/
bool fLimitReached = false;
if (g_uControlProcsMaxKept) /* If we allow unlimited processes (=0), take a shortcut. */
{
uint32_t uProcsRunning = 0;
if (iProcsLeft < 0)
{
fLimitReached = true;
}
}
*pbAllowed = !fLimitReached;
if (RT_SUCCESS(rc))
}
return rc;
}
/**
* Finds a (formerly) started process given by its PID and locks it. Must be unlocked
* by the caller with VBoxServiceControlThreadUnlock().
*
* @return PVBOXSERVICECTRLTHREAD Process structure if found, otherwise NULL.
* @param uPID PID to search for.
*/
{
if (RT_SUCCESS(rc))
{
{
{
if (RT_SUCCESS(rc))
break;
}
}
if (RT_SUCCESS(rc))
}
return pThread;
}
/**
* Unlocks a previously locked guest process thread.
*
* @param pThread Thread to unlock.
*/
{
}
/**
* Assigns a valid PID to a guest control thread and also checks if there already was
* another (stale) guest process which was using that PID before and destroys it.
*
* @return IPRT status code.
* @param pThread Thread to assign PID to.
* @param uPID PID to assign to the specified guest control execution thread.
*/
{
if (RT_SUCCESS(rc))
{
/* Search old threads using the desired PID and shut them down completely -- it's
* not used anymore. */
bool fTryAgain = false;
do
{
{
{
uPID += 391939;
fTryAgain = true;
break;
}
}
} while (fTryAgain);
/* Assign PID to current thread. */
}
return rc;
}
/**
* The 'vminfo' service description.
*/
{
/* pszName. */
"control",
/* pszDescription. */
"Host-driven Guest Control",
/* pszUsage. */
#ifdef DEBUG
" [--control-dump-stderr] [--control-dump-stdout]\n"
#endif
" [--control-interval <ms>] [--control-procs-max-kept <x>]\n"
" [--control-procs-mem-std[in|out|err] <KB>]"
,
/* pszOptions. */
#ifdef DEBUG
" --control-dump-stderr Dumps all guest proccesses stderr data to the\n"
" temporary directory.\n"
" --control-dump-stdout Dumps all guest proccesses stdout data to the\n"
" temporary directory.\n"
#endif
" --control-interval Specifies the interval at which to check for\n"
" new control commands. The default is 1000 ms.\n"
" --control-procs-max-kept\n"
" Specifies how many started guest processes are\n"
" kept into memory to work with. Default is 256.\n"
,
/* methods */
};