VBoxHeadless.cpp revision 614920b3c08750ed28ebbaefeb7dd9a6f6c779a7
/* $Id$ */
/** @file
* VBoxHeadless - The VirtualBox Headless frontend for running VMs on servers.
*/
/*
* Copyright (C) 2006-2011 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.
*/
using namespace com;
#define LOG_GROUP LOG_GROUP_GUI
#include <iprt/buildconfig.h>
#include <iprt/initterm.h>
#include <VBox/VBoxVideo.h>
#ifdef VBOX_FFMPEG
#include <cstdlib>
#include <cerrno>
#include "VBoxHeadless.h"
#endif
//#define VBOX_WITH_SAVESTATE_ON_SIGNAL
#include <signal.h>
#endif
#include "Framebuffer.h"
#ifdef VBOX_WITH_VNC
# include "FramebufferVNC.h"
#endif
#include "NullFramebuffer.h"
////////////////////////////////////////////////////////////////////////////////
do { \
RTPrintf("%s\n", m); \
} while (0)
////////////////////////////////////////////////////////////////////////////////
/* global weak references (for event handlers) */
/* flag whether frontend should terminate */
static volatile bool g_fTerminateFE = false;
#ifdef VBOX_WITH_VNC
static VNCFB *g_pFramebufferVNC;
#endif
////////////////////////////////////////////////////////////////////////////////
/**
* Handler for VirtualBoxClient events.
*/
{
public:
{
}
virtual ~VirtualBoxClientEventListener()
{
}
{
return S_OK;
}
void uninit()
{
}
{
switch (aType)
{
{
if (!fAvailable)
{
LogRel(("VBoxHeadless: VBoxSVC became unavailable, exiting.\n"));
RTPrintf("VBoxSVC became unavailable, exiting.\n");
/* Terminate the VM as cleanly as possible given that VBoxSVC
* is no longer present. */
g_fTerminateFE = true;
}
break;
}
default:
AssertFailed();
}
return S_OK;
}
private:
};
/**
* Handler for global events.
*/
class VirtualBoxEventListener
{
public:
{
mfNoLoggedInUsers = true;
}
virtual ~VirtualBoxEventListener()
{
}
{
return S_OK;
}
void uninit()
{
}
{
switch (aType)
{
{
{
/* Check if this is our machine and the "disconnect on logout feature" is enabled. */
if (gConsole)
{
{
{
value1.asOutParam());
{
}
}
}
}
{
bool fDropConnection = false;
if (!mfNoLoggedInUsers) /* Only if the property really changes. */
{
if ( utf8Value == "true"
/* Guest property got deleted due to reset,
* so it has no value anymore. */
{
mfNoLoggedInUsers = true;
fDropConnection = true;
}
}
else if (utf8Value == "false")
mfNoLoggedInUsers = false;
/* Guest property got deleted due to reset,
* take the shortcut without touching the mfNoLoggedInUsers
* state. */
fDropConnection = true;
if (fDropConnection)
{
/* If there is a connection, drop it. */
{
{
{
LogRel(("VRDE: the guest user has logged out, disconnecting remote clients.\n"));
}
}
}
}
}
}
break;
}
default:
AssertFailed();
}
return S_OK;
}
private:
bool mfNoLoggedInUsers;
};
/**
* Handler for machine events.
*/
class ConsoleEventListener
{
public:
mLastVRDEPort(-1),
m_fIgnorePowerOffEvents(false)
{
}
virtual ~ConsoleEventListener()
{
}
{
return S_OK;
}
void uninit()
{
}
{
switch (aType)
{
{
BOOL fSupportsAbsolute = false;
/* Emit absolute mouse event to actually enable the host mouse cursor. */
if (fSupportsAbsolute && gConsole)
{
if (mouse)
{
}
}
#ifdef VBOX_WITH_VNC
if (g_pFramebufferVNC)
#endif
break;
}
{
/* Terminate any event wait operation if the machine has been
* PoweredDown/Saved/Aborted. */
{
g_fTerminateFE = true;
}
break;
}
{
if (gConsole)
{
if (info)
{
if (port != mLastVRDEPort)
{
if (port == -1)
RTPrintf("VRDE server is inactive.\n");
else if (port == 0)
RTPrintf("VRDE server failed to start.\n");
else
}
}
}
break;
}
{
break;
}
{
break;
}
default:
AssertFailed();
}
return S_OK;
}
void ignorePowerOffEvents(bool fIgnore)
{
}
private:
long mLastVRDEPort;
bool m_fIgnorePowerOffEvents;
};
{
/** @todo Deal with nested signals, multithreaded signal dispatching (esp. on windows),
* and multiple signals (both SIGINT and SIGTERM in some order).
* Consider processing the signal request asynchronously since there are lots of things
* which aren't safe (like RTPrintf and printf IIRC) in a signal context. */
RTPrintf("Signal received, saving state.\n");
{
return;
}
RTPrintf("0%%");
for (;;)
{
BOOL fCompleted = false;
break;
break;
{
}
/* wait */
}
lrc = ~0;
if (!lrc)
{
RTPrintf(" -- Saved the state successfully.\n");
}
else
}
#endif /* VBOX_WITH_SAVESTATE_ON_SIGNAL */
////////////////////////////////////////////////////////////////////////////////
static void show_usage()
{
RTPrintf("Usage:\n"
" -s, -startvm, --startvm <name|uuid> Start given VM (required argument)\n"
#ifdef VBOX_WITH_VNC
" -n, --vnc Enable the built in VNC server\n"
" -m, --vncport <port> TCP port number to use for the VNC server\n"
" -o, --vncpass <pw> Set the VNC server password\n"
#endif
" -v, -vrde, --vrde on|off|config Enable (default) or disable the VRDE\n"
" server or don't change the setting\n"
" -e, -vrdeproperty, --vrdeproperty <name=[value]> Set a VRDE property:\n"
" the VRDE server can bind to. Use a dash between\n"
" two port numbers to specify a range\n"
" will bind to\n"
#ifdef VBOX_FFMPEG
" -c, -capture, --capture Record the VM screen output to a file\n"
" -w, --width Frame width when recording\n"
" -h, --height Frame height when recording\n"
" -r, --bitrate Recording bit rate when recording\n"
" -f, --filename File name when recording. The codec\n"
" used will be chosen based on the\n"
" file extension\n"
#endif
"\n");
}
#ifdef VBOX_FFMPEG
/**
* Parse the environment for variables which can influence the FFMPEG settings.
* purely for backwards compatibility.
* @param pulFrameWidth may be updated with a desired frame width
* @param pulFrameHeight may be updated with a desired frame height
* @param pulBitRate may be updated with a desired bit rate
* @param ppszFileName may be updated with a desired file name
*/
unsigned long *pulBitRate, const char **ppszFileName)
{
const char *pszEnvTemp;
{
errno = 0;
if (errno != 0)
LogError("VBoxHeadless: ERROR: invalid VBOX_CAPTUREWIDTH environment variable", 0);
else
}
{
errno = 0;
if (errno != 0)
LogError("VBoxHeadless: ERROR: invalid VBOX_CAPTUREHEIGHT environment variable", 0);
else
}
{
errno = 0;
if (errno != 0)
LogError("VBoxHeadless: ERROR: invalid VBOX_CAPTUREBITRATE environment variable", 0);
else
*pulBitRate = ulBitRate;
}
}
#endif /* VBOX_FFMPEG defined */
#ifdef RT_OS_WINDOWS
// Required for ATL
static CComModule _Module;
#endif
/**
* Entry point.
*/
{
const char *vrdeAddress = NULL;
const char *vrdeEnabled = NULL;
unsigned cVRDEProperties = 0;
const char *aVRDEProperties[16];
#ifdef VBOX_WITH_VNC
bool fVNCEnable = false;
unsigned uVNCPort = 0; /* default port */
#endif
unsigned fRawR0 = ~0U;
unsigned fRawR3 = ~0U;
unsigned fPATM = ~0U;
unsigned fCSAM = ~0U;
#ifdef VBOX_FFMPEG
unsigned fFFMPEG = 0;
unsigned long ulFrameWidth = 800;
unsigned long ulFrameHeight = 600;
unsigned long ulBitRate = 300000;
char pszMPEGFile[RTPATH_MAX];
const char *pszFileNameParam = "VBox-%d.vob";
#endif /* VBOX_FFMPEG */
LogFlow (("VBoxHeadless STARTED.\n"));
"All rights reserved.\n\n");
#ifdef VBOX_FFMPEG
/* Parse the environment */
#endif
enum eHeadlessOptions
{
OPT_RAW_R0 = 0x100,
};
static const RTGETOPTDEF s_aOptions[] =
{
#ifdef VBOX_WITH_VNC
{ "--vnc", 'n', 0 },
#endif /* VBOX_WITH_VNC */
{ "-rawr0", OPT_RAW_R0, 0 },
{ "--rawr0", OPT_RAW_R0, 0 },
{ "-norawr0", OPT_NO_RAW_R0, 0 },
{ "--norawr0", OPT_NO_RAW_R0, 0 },
{ "-rawr3", OPT_RAW_R3, 0 },
{ "--rawr3", OPT_RAW_R3, 0 },
{ "-norawr3", OPT_NO_RAW_R3, 0 },
{ "--norawr3", OPT_NO_RAW_R3, 0 },
{ "-patm", OPT_PATM, 0 },
{ "--patm", OPT_PATM, 0 },
{ "-nopatm", OPT_NO_PATM, 0 },
{ "--nopatm", OPT_NO_PATM, 0 },
{ "-csam", OPT_CSAM, 0 },
{ "--csam", OPT_CSAM, 0 },
{ "-nocsam", OPT_NO_CSAM, 0 },
{ "--nocsam", OPT_NO_CSAM, 0 },
#ifdef VBOX_FFMPEG
{ "-capture", 'c', 0 },
{ "--capture", 'c', 0 },
#endif /* VBOX_FFMPEG defined */
};
const char *pcszNameOrUUID = NULL;
// parse the command line
int ch;
{
switch(ch)
{
case 's':
break;
case 'p':
RTPrintf("Warning: '-p' or '-vrdpport' are deprecated. Use '-e \"TCP/Ports=%s\"'\n", ValueUnion.psz);
break;
case 'a':
RTPrintf("Warning: '-a' or '-vrdpaddress' are deprecated. Use '-e \"TCP/Address=%s\"'\n", ValueUnion.psz);
break;
case 'v':
break;
case 'e':
else
break;
#ifdef VBOX_WITH_VNC
case 'n':
fVNCEnable = true;
break;
case 'm':
break;
case 'o':
break;
#endif /* VBOX_WITH_VNC */
case OPT_RAW_R0:
fRawR0 = true;
break;
case OPT_NO_RAW_R0:
fRawR0 = false;
break;
case OPT_RAW_R3:
fRawR3 = true;
break;
case OPT_NO_RAW_R3:
fRawR3 = false;
break;
case OPT_PATM:
fPATM = true;
break;
case OPT_NO_PATM:
fPATM = false;
break;
case OPT_CSAM:
fCSAM = true;
break;
case OPT_NO_CSAM:
fCSAM = false;
break;
#ifdef VBOX_FFMPEG
case 'c':
fFFMPEG = true;
break;
case 'w':
break;
case 'r':
break;
case 'f':
break;
#endif /* VBOX_FFMPEG defined */
case 'h':
#ifdef VBOX_FFMPEG
{
break;
}
#endif
show_usage();
return 0;
case OPT_COMMENT:
/* nothing to do */
break;
case 'V':
return 0;
default:
show_usage();
return ch;
}
}
#ifdef VBOX_FFMPEG
{
LogError("VBoxHeadless: ERROR: please specify an even frame width between 512 and 2048", 0);
return 1;
}
{
LogError("VBoxHeadless: ERROR: please specify an even frame height between 384 and 1536", 0);
return 1;
}
{
LogError("VBoxHeadless: ERROR: please specify an even bitrate between 300000 and 1000000", 0);
return 1;
}
/* Make sure we only have %d or %u (or none) in the file name specified */
{
return 1;
}
/* And no more than one % in the name */
{
return 1;
}
#endif /* defined VBOX_FFMPEG */
if (!pcszNameOrUUID)
{
show_usage();
return 1;
}
{
RTPrintf("VBoxHeadless: ERROR: failed to initialize COM!\n");
return 1;
}
bool fSessionOpened = false;
do
{
{
RTPrintf("VBoxHeadless: ERROR: failed to create the VirtualBoxClient object!\n");
{
RTPrintf("Most likely, the VirtualBox COM server is not running or failed to start.\n");
}
else
break;
}
{
break;
}
{
break;
}
{
break;
}
break;
Log(("VBoxHeadless: Opening a session with machine (id={%s})...\n",
// open a session
fSessionOpened = true;
/* get the console */
/* get the mutable machine */
#ifdef VBOX_FFMPEG
IFramebuffer *pFramebuffer = 0;
if (fFFMPEG)
{
int rrc = VINF_SUCCESS;
Log2(("VBoxHeadless: loading VBoxFFmpegFB shared library\n"));
rrc = SUPR3HardenedLdrLoadAppPriv("VBoxFFmpegFB", &hLdrFFmpegFB, RTLDRLOAD_FLAGS_LOCAL, &ErrInfo.Core);
if (RT_SUCCESS(rrc))
{
Log2(("VBoxHeadless: looking up symbol VBoxRegisterFFmpegFB\n"));
reinterpret_cast<void **>(&pfnRegisterFFmpegFB));
if (RT_FAILURE(rrc))
}
else
LogError("Failed to load the video capture extension\n", rrc); /** @todo stupid function, no formatting options. */
if (RT_SUCCESS(rrc))
{
Log2(("VBoxHeadless: calling pfnRegisterFFmpegFB\n"));
LogError("Failed to initialise video capturing - make sure that the file format\n"
"you wish to use is supported on your system\n", rcc);
}
{
Log2(("VBoxHeadless: Registering framebuffer\n"));
pFramebuffer->AddRef();
}
}
{
break;
}
#endif /* defined(VBOX_FFMPEG) */
#ifdef VBOX_WITH_VNC
if (fVNCEnable)
{
{
delete g_pFramebufferVNC;
break;
}
Log2(("VBoxHeadless: Registering VNC framebuffer\n"));
}
break;
#endif
unsigned uScreenId;
{
# ifdef VBOX_FFMPEG
{
/* Already registered. */
continue;
}
# endif
# ifdef VBOX_WITH_VNC
if (fVNCEnable && uScreenId == 0)
{
/* Already registered. */
continue;
}
# endif
if (!pVRDPFramebuffer)
{
break;
}
}
{
break;
}
// fill in remaining slots with null framebuffers
{
fb.asOutParam(),
{
}
}
/* get the machine debugger (isn't necessarily available) */
if (machineDebugger)
{
Log(("Machine debugger available!\n"));
}
if (fRawR0 != ~0U)
{
if (!machineDebugger)
{
break;
}
}
if (fRawR3 != ~0U)
{
if (!machineDebugger)
{
break;
}
}
if (fPATM != ~0U)
{
if (!machineDebugger)
{
break;
}
}
if (fCSAM != ~0U)
{
if (!machineDebugger)
{
break;
}
}
/* initialize global references */
/* VirtualBoxClient events registration. */
{
}
/* Console events registration. */
{
}
/* default is to enable the remote desktop server (backward compatibility) */
BOOL fVRDEEnable = true;
if (vrdeEnabled != NULL)
{
/* -vrdeServer on|off|config */
fVRDEEnable = false;
{
if (!fVRDEEnabled)
fVRDEEnable = false;
}
{
RTPrintf("-vrdeServer requires an argument (on|off|config)\n");
break;
}
}
if (fVRDEEnable)
{
Log(("VBoxHeadless: Enabling VRDE server...\n"));
/* set VRDE port if requested by the user */
{
}
/* set VRDE address if requested by the user */
if (vrdeAddress != NULL)
{
}
/* Set VRDE properties. */
if (cVRDEProperties > 0)
{
for (unsigned i = 0; i < cVRDEProperties; i++)
{
/* Parse 'name=value' */
if (pszProperty)
{
if (pDelimiter)
{
*pDelimiter = '\0';
}
else
{
rc = E_INVALIDARG;
break;
}
}
else
{
rc = E_OUTOFMEMORY;
break;
}
}
break;
}
/* enable VRDE server (only if currently disabled) */
if (!fVRDEEnabled)
{
}
}
else
{
/* disable VRDE server (only if currently enabled */
if (fVRDEEnabled)
{
}
}
/* Disable the host clipboard before powering up */
Log(("VBoxHeadless: Powering up the machine...\n"));
/*
* Wait for the result because there can be errors.
*
* It's vital to process events while waiting (teleportation deadlocks),
* so we'll poll for the completion instead of waiting on it.
*/
for (;;)
{
break;
/* Process pending events, then wait for new ones. Note, this
* processes NULL events signalling event loop termination. */
gEventQ->processEventQueue(0);
if (!g_fTerminateFE)
}
{
/* Figure out if the operation completed with a failed status
* and print the error message. Terminate immediately, and let
* the cleanup code take care of potentially pending events. */
rc = progressRc;
{
if (info.isBasicAvailable())
{
}
else
{
RTPrintf("Error: failed to start machine. No error message available!\n");
}
break;
}
}
/* VirtualBox events registration. */
{
}
#endif
Log(("VBoxHeadless: Waiting for PowerDown...\n"));
while ( !g_fTerminateFE
/* nothing */ ;
Log(("VBoxHeadless: event loop has terminated...\n"));
#ifdef VBOX_FFMPEG
if (pFramebuffer)
{
pFramebuffer->Release();
Log(("Released framebuffer\n"));
pFramebuffer = NULL;
}
#endif /* defined(VBOX_FFMPEG) */
/* we don't have to disable VRDE here because we don't save the settings of the VM */
}
while (0);
/*
* Get the machine state.
*/
/*
* Turn off the VM if it's running
*/
if ( gConsole
&& ( machineState == MachineState_Running
/** @todo power off paused VMs too? */
)
)
do
{
{
RTPrintf("VBoxHeadless: ERROR: Failed to power down VM!");
else
break;
}
} while (0);
/* VirtualBox callback unregistration. */
if (vboxListener)
{
}
/* Console callback unregistration. */
if (consoleListener)
{
}
/* VirtualBoxClient callback unregistration. */
if (vboxClientListener)
{
}
/* No more access to the 'console' object, which will be uninitialized by the next session->Close call. */
if (fSessionOpened)
{
/*
* Close the session. This will also uninitialize the console and
* unregister the callback we've registered before.
*/
Log(("VBoxHeadless: Closing the session...\n"));
session->UnlockMachine();
}
/* Must be before com::Shutdown */
LogFlow(("VBoxHeadless FINISHED.\n"));
}
#ifndef VBOX_WITH_HARDENING
/**
* Main entry point.
*/
{
// initialize VBox Runtime
int rc = RTR3InitAndSUPLib();
if (RT_FAILURE(rc))
{
RTPrintf("VBoxHeadless: Runtime Error:\n"
switch (rc)
{
RTPrintf("Cannot access the kernel driver. Make sure the kernel module has been \n"
"loaded successfully. Aborting ...\n");
break;
default:
break;
}
return 1;
}
}
#endif /* !VBOX_WITH_HARDENING */
#ifdef VBOX_WITH_XPCOM
#endif