VirtualBox

source: vbox/trunk/src/VBox/Frontends/VBoxHeadless/VBoxHeadless.cpp@ 62521

Last change on this file since 62521 was 60865, checked in by vboxsync, 8 years ago

Never use static instances of CComModule as it messes up the log filename by using VBoxRT.dll before it's initialized.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 46.2 KB
Line 
1/* $Id: VBoxHeadless.cpp 60865 2016-05-06 14:43:04Z vboxsync $ */
2/** @file
3 * VBoxHeadless - The VirtualBox Headless frontend for running VMs on servers.
4 */
5
6/*
7 * Copyright (C) 2006-2016 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#include <VBox/com/com.h>
19#include <VBox/com/string.h>
20#include <VBox/com/array.h>
21#include <VBox/com/Guid.h>
22#include <VBox/com/ErrorInfo.h>
23#include <VBox/com/errorprint.h>
24#include <VBox/com/NativeEventQueue.h>
25
26#include <VBox/com/VirtualBox.h>
27#include <VBox/com/listeners.h>
28
29using namespace com;
30
31#define LOG_GROUP LOG_GROUP_GUI
32
33#include <VBox/log.h>
34#include <VBox/version.h>
35#include <iprt/buildconfig.h>
36#include <iprt/ctype.h>
37#include <iprt/initterm.h>
38#include <iprt/stream.h>
39#include <iprt/ldr.h>
40#include <iprt/getopt.h>
41#include <iprt/env.h>
42#include <VBox/err.h>
43#include <VBox/VBoxVideo.h>
44
45#ifdef VBOX_WITH_VPX
46# include <cstdlib>
47# include <cerrno>
48# include <iprt/process.h>
49#endif
50
51#ifdef RT_OS_DARWIN
52# include <iprt/asm.h>
53# include <dlfcn.h>
54# include <sys/mman.h>
55#endif
56
57//#define VBOX_WITH_SAVESTATE_ON_SIGNAL
58#ifdef VBOX_WITH_SAVESTATE_ON_SIGNAL
59#include <signal.h>
60#endif
61
62////////////////////////////////////////////////////////////////////////////////
63
64#define LogError(m,rc) \
65 do { \
66 Log(("VBoxHeadless: ERROR: " m " [rc=0x%08X]\n", rc)); \
67 RTPrintf("%s\n", m); \
68 } while (0)
69
70////////////////////////////////////////////////////////////////////////////////
71
72/* global weak references (for event handlers) */
73static IConsole *gConsole = NULL;
74static NativeEventQueue *gEventQ = NULL;
75
76/* flag whether frontend should terminate */
77static volatile bool g_fTerminateFE = false;
78
79////////////////////////////////////////////////////////////////////////////////
80
81/**
82 * Handler for VirtualBoxClient events.
83 */
84class VirtualBoxClientEventListener
85{
86public:
87 VirtualBoxClientEventListener()
88 {
89 }
90
91 virtual ~VirtualBoxClientEventListener()
92 {
93 }
94
95 HRESULT init()
96 {
97 return S_OK;
98 }
99
100 void uninit()
101 {
102 }
103
104 STDMETHOD(HandleEvent)(VBoxEventType_T aType, IEvent *aEvent)
105 {
106 switch (aType)
107 {
108 case VBoxEventType_OnVBoxSVCAvailabilityChanged:
109 {
110 ComPtr<IVBoxSVCAvailabilityChangedEvent> pVSACEv = aEvent;
111 Assert(pVSACEv);
112 BOOL fAvailable = FALSE;
113 pVSACEv->COMGETTER(Available)(&fAvailable);
114 if (!fAvailable)
115 {
116 LogRel(("VBoxHeadless: VBoxSVC became unavailable, exiting.\n"));
117 RTPrintf("VBoxSVC became unavailable, exiting.\n");
118 /* Terminate the VM as cleanly as possible given that VBoxSVC
119 * is no longer present. */
120 g_fTerminateFE = true;
121 gEventQ->interruptEventQueueProcessing();
122 }
123 break;
124 }
125 default:
126 AssertFailed();
127 }
128
129 return S_OK;
130 }
131
132private:
133};
134
135/**
136 * Handler for machine events.
137 */
138class ConsoleEventListener
139{
140public:
141 ConsoleEventListener() :
142 mLastVRDEPort(-1),
143 m_fIgnorePowerOffEvents(false),
144 m_fNoLoggedInUsers(true)
145 {
146 }
147
148 virtual ~ConsoleEventListener()
149 {
150 }
151
152 HRESULT init()
153 {
154 return S_OK;
155 }
156
157 void uninit()
158 {
159 }
160
161 STDMETHOD(HandleEvent)(VBoxEventType_T aType, IEvent *aEvent)
162 {
163 switch (aType)
164 {
165 case VBoxEventType_OnMouseCapabilityChanged:
166 {
167
168 ComPtr<IMouseCapabilityChangedEvent> mccev = aEvent;
169 Assert(!mccev.isNull());
170
171 BOOL fSupportsAbsolute = false;
172 mccev->COMGETTER(SupportsAbsolute)(&fSupportsAbsolute);
173
174 /* Emit absolute mouse event to actually enable the host mouse cursor. */
175 if (fSupportsAbsolute && gConsole)
176 {
177 ComPtr<IMouse> mouse;
178 gConsole->COMGETTER(Mouse)(mouse.asOutParam());
179 if (mouse)
180 {
181 mouse->PutMouseEventAbsolute(-1, -1, 0, 0 /* Horizontal wheel */, 0);
182 }
183 }
184 break;
185 }
186 case VBoxEventType_OnStateChanged:
187 {
188 ComPtr<IStateChangedEvent> scev = aEvent;
189 Assert(scev);
190
191 MachineState_T machineState;
192 scev->COMGETTER(State)(&machineState);
193
194 /* Terminate any event wait operation if the machine has been
195 * PoweredDown/Saved/Aborted. */
196 if (machineState < MachineState_Running && !m_fIgnorePowerOffEvents)
197 {
198 g_fTerminateFE = true;
199 gEventQ->interruptEventQueueProcessing();
200 }
201
202 break;
203 }
204 case VBoxEventType_OnVRDEServerInfoChanged:
205 {
206 ComPtr<IVRDEServerInfoChangedEvent> rdicev = aEvent;
207 Assert(rdicev);
208
209 if (gConsole)
210 {
211 ComPtr<IVRDEServerInfo> info;
212 gConsole->COMGETTER(VRDEServerInfo)(info.asOutParam());
213 if (info)
214 {
215 LONG port;
216 info->COMGETTER(Port)(&port);
217 if (port != mLastVRDEPort)
218 {
219 if (port == -1)
220 RTPrintf("VRDE server is inactive.\n");
221 else if (port == 0)
222 RTPrintf("VRDE server failed to start.\n");
223 else
224 RTPrintf("VRDE server is listening on port %d.\n", port);
225
226 mLastVRDEPort = port;
227 }
228 }
229 }
230 break;
231 }
232 case VBoxEventType_OnCanShowWindow:
233 {
234 ComPtr<ICanShowWindowEvent> cswev = aEvent;
235 Assert(cswev);
236 cswev->AddVeto(NULL);
237 break;
238 }
239 case VBoxEventType_OnShowWindow:
240 {
241 ComPtr<IShowWindowEvent> swev = aEvent;
242 Assert(swev);
243 /* Ignore the event, WinId is either still zero or some other listener assigned it. */
244 NOREF(swev); /* swev->COMSETTER(WinId)(0); */
245 break;
246 }
247 case VBoxEventType_OnGuestPropertyChanged:
248 {
249 ComPtr<IGuestPropertyChangedEvent> pChangedEvent = aEvent;
250 Assert(pChangedEvent);
251
252 HRESULT hrc;
253
254 ComPtr <IMachine> pMachine;
255 if (gConsole)
256 {
257 hrc = gConsole->COMGETTER(Machine)(pMachine.asOutParam());
258 if (FAILED(hrc) || !pMachine)
259 hrc = VBOX_E_OBJECT_NOT_FOUND;
260 }
261 else
262 hrc = VBOX_E_INVALID_VM_STATE;
263
264 if (SUCCEEDED(hrc))
265 {
266 Bstr strKey;
267 hrc = pChangedEvent->COMGETTER(Name)(strKey.asOutParam());
268 AssertComRC(hrc);
269
270 Bstr strValue;
271 hrc = pChangedEvent->COMGETTER(Value)(strValue.asOutParam());
272 AssertComRC(hrc);
273
274 Utf8Str utf8Key = strKey;
275 Utf8Str utf8Value = strValue;
276 LogRelFlow(("Guest property \"%s\" has been changed to \"%s\"\n",
277 utf8Key.c_str(), utf8Value.c_str()));
278
279 if (utf8Key.equals("/VirtualBox/GuestInfo/OS/NoLoggedInUsers"))
280 {
281 LogRelFlow(("Guest indicates that there %s logged in users\n",
282 utf8Value.equals("true") ? "are no" : "are"));
283
284 /* Check if this is our machine and the "disconnect on logout feature" is enabled. */
285 BOOL fProcessDisconnectOnGuestLogout = FALSE;
286
287 /* Does the machine handle VRDP disconnects? */
288 Bstr strDiscon;
289 hrc = pMachine->GetExtraData(Bstr("VRDP/DisconnectOnGuestLogout").raw(),
290 strDiscon.asOutParam());
291 if (SUCCEEDED(hrc))
292 {
293 Utf8Str utf8Discon = strDiscon;
294 fProcessDisconnectOnGuestLogout = utf8Discon.equals("1")
295 ? TRUE : FALSE;
296 }
297
298 LogRelFlow(("VRDE: hrc=%Rhrc: Host %s disconnecting clients (current host state known: %s)\n",
299 hrc, fProcessDisconnectOnGuestLogout ? "will handle" : "does not handle",
300 m_fNoLoggedInUsers ? "No users logged in" : "Users logged in"));
301
302 if (fProcessDisconnectOnGuestLogout)
303 {
304 bool fDropConnection = false;
305 if (!m_fNoLoggedInUsers) /* Only if the property really changes. */
306 {
307 if ( utf8Value == "true"
308 /* Guest property got deleted due to reset,
309 * so it has no value anymore. */
310 || utf8Value.isEmpty())
311 {
312 m_fNoLoggedInUsers = true;
313 fDropConnection = true;
314 }
315 }
316 else if (utf8Value == "false")
317 m_fNoLoggedInUsers = false;
318 /* Guest property got deleted due to reset,
319 * take the shortcut without touching the m_fNoLoggedInUsers
320 * state. */
321 else if (utf8Value.isEmpty())
322 fDropConnection = true;
323
324 LogRelFlow(("VRDE: szNoLoggedInUsers=%s, m_fNoLoggedInUsers=%RTbool, fDropConnection=%RTbool\n",
325 utf8Value.c_str(), m_fNoLoggedInUsers, fDropConnection));
326
327 if (fDropConnection)
328 {
329 /* If there is a connection, drop it. */
330 ComPtr<IVRDEServerInfo> info;
331 hrc = gConsole->COMGETTER(VRDEServerInfo)(info.asOutParam());
332 if (SUCCEEDED(hrc) && info)
333 {
334 ULONG cClients = 0;
335 hrc = info->COMGETTER(NumberOfClients)(&cClients);
336
337 LogRelFlow(("VRDE: connected clients=%RU32\n", cClients));
338 if (SUCCEEDED(hrc) && cClients > 0)
339 {
340 ComPtr <IVRDEServer> vrdeServer;
341 hrc = pMachine->COMGETTER(VRDEServer)(vrdeServer.asOutParam());
342 if (SUCCEEDED(hrc) && vrdeServer)
343 {
344 LogRel(("VRDE: the guest user has logged out, disconnecting remote clients.\n"));
345 hrc = vrdeServer->COMSETTER(Enabled)(FALSE);
346 AssertComRC(hrc);
347 HRESULT hrc2 = vrdeServer->COMSETTER(Enabled)(TRUE);
348 if (SUCCEEDED(hrc))
349 hrc = hrc2;
350 }
351 }
352 }
353 }
354 }
355 }
356
357 if (FAILED(hrc))
358 LogRelFlow(("VRDE: returned error=%Rhrc\n", hrc));
359 }
360
361 break;
362 }
363
364 default:
365 AssertFailed();
366 }
367 return S_OK;
368 }
369
370 void ignorePowerOffEvents(bool fIgnore)
371 {
372 m_fIgnorePowerOffEvents = fIgnore;
373 }
374
375private:
376
377 long mLastVRDEPort;
378 bool m_fIgnorePowerOffEvents;
379 bool m_fNoLoggedInUsers;
380};
381
382typedef ListenerImpl<VirtualBoxClientEventListener> VirtualBoxClientEventListenerImpl;
383typedef ListenerImpl<ConsoleEventListener> ConsoleEventListenerImpl;
384
385VBOX_LISTENER_DECLARE(VirtualBoxClientEventListenerImpl)
386VBOX_LISTENER_DECLARE(ConsoleEventListenerImpl)
387
388#ifdef VBOX_WITH_SAVESTATE_ON_SIGNAL
389static void SaveState(int sig)
390{
391 ComPtr <IProgress> progress = NULL;
392
393/** @todo Deal with nested signals, multithreaded signal dispatching (esp. on windows),
394 * and multiple signals (both SIGINT and SIGTERM in some order).
395 * Consider processing the signal request asynchronously since there are lots of things
396 * which aren't safe (like RTPrintf and printf IIRC) in a signal context. */
397
398 RTPrintf("Signal received, saving state.\n");
399
400 HRESULT rc = gConsole->SaveState(progress.asOutParam());
401 if (FAILED(rc))
402 {
403 RTPrintf("Error saving state! rc = 0x%x\n", rc);
404 return;
405 }
406 Assert(progress);
407 LONG cPercent = 0;
408
409 RTPrintf("0%%");
410 RTStrmFlush(g_pStdOut);
411 for (;;)
412 {
413 BOOL fCompleted = false;
414 rc = progress->COMGETTER(Completed)(&fCompleted);
415 if (FAILED(rc) || fCompleted)
416 break;
417 ULONG cPercentNow;
418 rc = progress->COMGETTER(Percent)(&cPercentNow);
419 if (FAILED(rc))
420 break;
421 if ((cPercentNow / 10) != (cPercent / 10))
422 {
423 cPercent = cPercentNow;
424 RTPrintf("...%d%%", cPercentNow);
425 RTStrmFlush(g_pStdOut);
426 }
427
428 /* wait */
429 rc = progress->WaitForCompletion(100);
430 }
431
432 HRESULT lrc;
433 rc = progress->COMGETTER(ResultCode)(&lrc);
434 if (FAILED(rc))
435 lrc = ~0;
436 if (!lrc)
437 {
438 RTPrintf(" -- Saved the state successfully.\n");
439 RTThreadYield();
440 }
441 else
442 RTPrintf("-- Error saving state, lrc=%d (%#x)\n", lrc, lrc);
443
444}
445#endif /* VBOX_WITH_SAVESTATE_ON_SIGNAL */
446
447////////////////////////////////////////////////////////////////////////////////
448
449static void show_usage()
450{
451 RTPrintf("Usage:\n"
452 " -s, -startvm, --startvm <name|uuid> Start given VM (required argument)\n"
453 " -v, -vrde, --vrde on|off|config Enable or disable the VRDE server\n"
454 " or don't change the setting (default)\n"
455 " -e, -vrdeproperty, --vrdeproperty <name=[value]> Set a VRDE property:\n"
456 " \"TCP/Ports\" - comma-separated list of\n"
457 " ports the VRDE server can bind to; dash\n"
458 " between two port numbers specifies range\n"
459 " \"TCP/Address\" - interface IP the VRDE\n"
460 " server will bind to\n"
461 " --settingspw <pw> Specify the settings password\n"
462 " --settingspwfile <file> Specify a file containing the\n"
463 " settings password\n"
464 " -start-paused, --start-paused Start the VM in paused state\n"
465#ifdef VBOX_WITH_VPX
466 " -c, -capture, --capture Record the VM screen output to a file\n"
467 " -w, --width Frame width when recording\n"
468 " -h, --height Frame height when recording\n"
469 " -r, --bitrate Recording bit rate when recording\n"
470 " -f, --filename File name when recording. The codec used\n"
471 " will be chosen based on file extension\n"
472#endif
473 "\n");
474}
475
476#ifdef VBOX_WITH_VPX
477/**
478 * Parse the environment for variables which can influence the VIDEOREC settings.
479 * purely for backwards compatibility.
480 * @param pulFrameWidth may be updated with a desired frame width
481 * @param pulFrameHeight may be updated with a desired frame height
482 * @param pulBitRate may be updated with a desired bit rate
483 * @param ppszFileName may be updated with a desired file name
484 */
485static void parse_environ(unsigned long *pulFrameWidth, unsigned long *pulFrameHeight,
486 unsigned long *pulBitRate, const char **ppszFileName)
487{
488 const char *pszEnvTemp;
489/** @todo r=bird: This isn't up to scratch. The life time of an RTEnvGet
490 * return value is only up to the next RTEnv*, *getenv, *putenv,
491 * setenv call in _any_ process in the system and the it has known and
492 * documented code page issues.
493 *
494 * Use RTEnvGetEx instead! */
495 if ((pszEnvTemp = RTEnvGet("VBOX_CAPTUREWIDTH")) != 0)
496 {
497 errno = 0;
498 unsigned long ulFrameWidth = strtoul(pszEnvTemp, 0, 10);
499 if (errno != 0)
500 LogError("VBoxHeadless: ERROR: invalid VBOX_CAPTUREWIDTH environment variable", 0);
501 else
502 *pulFrameWidth = ulFrameWidth;
503 }
504 if ((pszEnvTemp = RTEnvGet("VBOX_CAPTUREHEIGHT")) != 0)
505 {
506 errno = 0;
507 unsigned long ulFrameHeight = strtoul(pszEnvTemp, 0, 10);
508 if (errno != 0)
509 LogError("VBoxHeadless: ERROR: invalid VBOX_CAPTUREHEIGHT environment variable", 0);
510 else
511 *pulFrameHeight = ulFrameHeight;
512 }
513 if ((pszEnvTemp = RTEnvGet("VBOX_CAPTUREBITRATE")) != 0)
514 {
515 errno = 0;
516 unsigned long ulBitRate = strtoul(pszEnvTemp, 0, 10);
517 if (errno != 0)
518 LogError("VBoxHeadless: ERROR: invalid VBOX_CAPTUREBITRATE environment variable", 0);
519 else
520 *pulBitRate = ulBitRate;
521 }
522 if ((pszEnvTemp = RTEnvGet("VBOX_CAPTUREFILE")) != 0)
523 *ppszFileName = pszEnvTemp;
524}
525#endif /* VBOX_WITH_VPX defined */
526
527static RTEXITCODE readPasswordFile(const char *pszFilename, com::Utf8Str *pPasswd)
528{
529 size_t cbFile;
530 char szPasswd[512];
531 int vrc = VINF_SUCCESS;
532 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
533 bool fStdIn = !strcmp(pszFilename, "stdin");
534 PRTSTREAM pStrm;
535 if (!fStdIn)
536 vrc = RTStrmOpen(pszFilename, "r", &pStrm);
537 else
538 pStrm = g_pStdIn;
539 if (RT_SUCCESS(vrc))
540 {
541 vrc = RTStrmReadEx(pStrm, szPasswd, sizeof(szPasswd)-1, &cbFile);
542 if (RT_SUCCESS(vrc))
543 {
544 if (cbFile >= sizeof(szPasswd)-1)
545 {
546 RTPrintf("Provided password in file '%s' is too long\n", pszFilename);
547 rcExit = RTEXITCODE_FAILURE;
548 }
549 else
550 {
551 unsigned i;
552 for (i = 0; i < cbFile && !RT_C_IS_CNTRL(szPasswd[i]); i++)
553 ;
554 szPasswd[i] = '\0';
555 *pPasswd = szPasswd;
556 }
557 }
558 else
559 {
560 RTPrintf("Cannot read password from file '%s': %Rrc\n", pszFilename, vrc);
561 rcExit = RTEXITCODE_FAILURE;
562 }
563 if (!fStdIn)
564 RTStrmClose(pStrm);
565 }
566 else
567 {
568 RTPrintf("Cannot open password file '%s' (%Rrc)\n", pszFilename, vrc);
569 rcExit = RTEXITCODE_FAILURE;
570 }
571
572 return rcExit;
573}
574
575static RTEXITCODE settingsPasswordFile(ComPtr<IVirtualBox> virtualBox, const char *pszFilename)
576{
577 com::Utf8Str passwd;
578 RTEXITCODE rcExit = readPasswordFile(pszFilename, &passwd);
579 if (rcExit == RTEXITCODE_SUCCESS)
580 {
581 int rc;
582 CHECK_ERROR(virtualBox, SetSettingsSecret(com::Bstr(passwd).raw()));
583 if (FAILED(rc))
584 rcExit = RTEXITCODE_FAILURE;
585 }
586
587 return rcExit;
588}
589
590
591#ifdef RT_OS_DARWIN
592/**
593 * Mac OS X: Really ugly hack to bypass a set-uid check in AppKit.
594 *
595 * This will modify the issetugid() function to always return zero. This must
596 * be done _before_ AppKit is initialized, otherwise it will refuse to play ball
597 * with us as it distrusts set-uid processes since Snow Leopard. We, however,
598 * have carefully dropped all root privileges at this point and there should be
599 * no reason for any security concern here.
600 */
601static void hideSetUidRootFromAppKit()
602{
603 /* Find issetguid() and make it always return 0 by modifying the code: */
604 void *pvAddr = dlsym(RTLD_DEFAULT, "issetugid");
605 int rc = mprotect((void *)((uintptr_t)pvAddr & ~(uintptr_t)0xfff), 0x2000, PROT_WRITE | PROT_READ | PROT_EXEC);
606 if (!rc)
607 ASMAtomicWriteU32((volatile uint32_t *)pvAddr, 0xccc3c031); /* xor eax, eax; ret; int3 */
608}
609#endif /* RT_OS_DARWIN */
610
611/**
612 * Entry point.
613 */
614extern "C" DECLEXPORT(int) TrustedMain(int argc, char **argv, char **envp)
615{
616 const char *vrdePort = NULL;
617 const char *vrdeAddress = NULL;
618 const char *vrdeEnabled = NULL;
619 unsigned cVRDEProperties = 0;
620 const char *aVRDEProperties[16];
621 unsigned fRawR0 = ~0U;
622 unsigned fRawR3 = ~0U;
623 unsigned fPATM = ~0U;
624 unsigned fCSAM = ~0U;
625 unsigned fPaused = 0;
626#ifdef VBOX_WITH_VPX
627 bool fVideoRec = 0;
628 unsigned long ulFrameWidth = 800;
629 unsigned long ulFrameHeight = 600;
630 unsigned long ulBitRate = 300000; /** @todo r=bird: The COM type ULONG isn't unsigned long, it's 32-bit unsigned int. */
631 char szMpegFile[RTPATH_MAX];
632 const char *pszFileNameParam = "VBox-%d.vob";
633#endif /* VBOX_WITH_VPX */
634#ifdef RT_OS_WINDOWS
635 ATL::CComModule _Module; /* Required internally by ATL (constructor records instance in global variable). */
636#endif
637
638 LogFlow(("VBoxHeadless STARTED.\n"));
639 RTPrintf(VBOX_PRODUCT " Headless Interface " VBOX_VERSION_STRING "\n"
640 "(C) 2008-" VBOX_C_YEAR " " VBOX_VENDOR "\n"
641 "All rights reserved.\n\n");
642
643#ifdef VBOX_WITH_VPX
644 /* Parse the environment */
645 parse_environ(&ulFrameWidth, &ulFrameHeight, &ulBitRate, &pszFileNameParam);
646#endif
647
648 enum eHeadlessOptions
649 {
650 OPT_RAW_R0 = 0x100,
651 OPT_NO_RAW_R0,
652 OPT_RAW_R3,
653 OPT_NO_RAW_R3,
654 OPT_PATM,
655 OPT_NO_PATM,
656 OPT_CSAM,
657 OPT_NO_CSAM,
658 OPT_SETTINGSPW,
659 OPT_SETTINGSPW_FILE,
660 OPT_COMMENT,
661 OPT_PAUSED
662 };
663
664 static const RTGETOPTDEF s_aOptions[] =
665 {
666 { "-startvm", 's', RTGETOPT_REQ_STRING },
667 { "--startvm", 's', RTGETOPT_REQ_STRING },
668 { "-vrdpport", 'p', RTGETOPT_REQ_STRING }, /* VRDE: deprecated. */
669 { "--vrdpport", 'p', RTGETOPT_REQ_STRING }, /* VRDE: deprecated. */
670 { "-vrdpaddress", 'a', RTGETOPT_REQ_STRING }, /* VRDE: deprecated. */
671 { "--vrdpaddress", 'a', RTGETOPT_REQ_STRING }, /* VRDE: deprecated. */
672 { "-vrdp", 'v', RTGETOPT_REQ_STRING }, /* VRDE: deprecated. */
673 { "--vrdp", 'v', RTGETOPT_REQ_STRING }, /* VRDE: deprecated. */
674 { "-vrde", 'v', RTGETOPT_REQ_STRING },
675 { "--vrde", 'v', RTGETOPT_REQ_STRING },
676 { "-vrdeproperty", 'e', RTGETOPT_REQ_STRING },
677 { "--vrdeproperty", 'e', RTGETOPT_REQ_STRING },
678 { "-rawr0", OPT_RAW_R0, 0 },
679 { "--rawr0", OPT_RAW_R0, 0 },
680 { "-norawr0", OPT_NO_RAW_R0, 0 },
681 { "--norawr0", OPT_NO_RAW_R0, 0 },
682 { "-rawr3", OPT_RAW_R3, 0 },
683 { "--rawr3", OPT_RAW_R3, 0 },
684 { "-norawr3", OPT_NO_RAW_R3, 0 },
685 { "--norawr3", OPT_NO_RAW_R3, 0 },
686 { "-patm", OPT_PATM, 0 },
687 { "--patm", OPT_PATM, 0 },
688 { "-nopatm", OPT_NO_PATM, 0 },
689 { "--nopatm", OPT_NO_PATM, 0 },
690 { "-csam", OPT_CSAM, 0 },
691 { "--csam", OPT_CSAM, 0 },
692 { "-nocsam", OPT_NO_CSAM, 0 },
693 { "--nocsam", OPT_NO_CSAM, 0 },
694 { "--settingspw", OPT_SETTINGSPW, RTGETOPT_REQ_STRING },
695 { "--settingspwfile", OPT_SETTINGSPW_FILE, RTGETOPT_REQ_STRING },
696#ifdef VBOX_WITH_VPX
697 { "-capture", 'c', 0 },
698 { "--capture", 'c', 0 },
699 { "--width", 'w', RTGETOPT_REQ_UINT32 },
700 { "--height", 'h', RTGETOPT_REQ_UINT32 }, /* great choice of short option! */
701 { "--bitrate", 'r', RTGETOPT_REQ_UINT32 },
702 { "--filename", 'f', RTGETOPT_REQ_STRING },
703#endif /* VBOX_WITH_VPX defined */
704 { "-comment", OPT_COMMENT, RTGETOPT_REQ_STRING },
705 { "--comment", OPT_COMMENT, RTGETOPT_REQ_STRING },
706 { "-start-paused", OPT_PAUSED, 0 },
707 { "--start-paused", OPT_PAUSED, 0 }
708 };
709
710 const char *pcszNameOrUUID = NULL;
711
712#ifdef RT_OS_DARWIN
713 hideSetUidRootFromAppKit();
714#endif
715
716 // parse the command line
717 int ch;
718 const char *pcszSettingsPw = NULL;
719 const char *pcszSettingsPwFile = NULL;
720 RTGETOPTUNION ValueUnion;
721 RTGETOPTSTATE GetState;
722 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, 0 /* fFlags */);
723 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
724 {
725 switch(ch)
726 {
727 case 's':
728 pcszNameOrUUID = ValueUnion.psz;
729 break;
730 case 'p':
731 RTPrintf("Warning: '-p' or '-vrdpport' are deprecated. Use '-e \"TCP/Ports=%s\"'\n", ValueUnion.psz);
732 vrdePort = ValueUnion.psz;
733 break;
734 case 'a':
735 RTPrintf("Warning: '-a' or '-vrdpaddress' are deprecated. Use '-e \"TCP/Address=%s\"'\n", ValueUnion.psz);
736 vrdeAddress = ValueUnion.psz;
737 break;
738 case 'v':
739 vrdeEnabled = ValueUnion.psz;
740 break;
741 case 'e':
742 if (cVRDEProperties < RT_ELEMENTS(aVRDEProperties))
743 aVRDEProperties[cVRDEProperties++] = ValueUnion.psz;
744 else
745 RTPrintf("Warning: too many VRDE properties. Ignored: '%s'\n", ValueUnion.psz);
746 break;
747 case OPT_RAW_R0:
748 fRawR0 = true;
749 break;
750 case OPT_NO_RAW_R0:
751 fRawR0 = false;
752 break;
753 case OPT_RAW_R3:
754 fRawR3 = true;
755 break;
756 case OPT_NO_RAW_R3:
757 fRawR3 = false;
758 break;
759 case OPT_PATM:
760 fPATM = true;
761 break;
762 case OPT_NO_PATM:
763 fPATM = false;
764 break;
765 case OPT_CSAM:
766 fCSAM = true;
767 break;
768 case OPT_NO_CSAM:
769 fCSAM = false;
770 break;
771 case OPT_SETTINGSPW:
772 pcszSettingsPw = ValueUnion.psz;
773 break;
774 case OPT_SETTINGSPW_FILE:
775 pcszSettingsPwFile = ValueUnion.psz;
776 break;
777 case OPT_PAUSED:
778 fPaused = true;
779 break;
780#ifdef VBOX_WITH_VPX
781 case 'c':
782 fVideoRec = true;
783 break;
784 case 'w':
785 ulFrameWidth = ValueUnion.u32;
786 break;
787 case 'r':
788 ulBitRate = ValueUnion.u32;
789 break;
790 case 'f':
791 pszFileNameParam = ValueUnion.psz;
792 break;
793#endif /* VBOX_WITH_VPX defined */
794 case 'h':
795#ifdef VBOX_WITH_VPX
796 if ((GetState.pDef->fFlags & RTGETOPT_REQ_MASK) != RTGETOPT_REQ_NOTHING)
797 {
798 ulFrameHeight = ValueUnion.u32;
799 break;
800 }
801#endif
802 show_usage();
803 return 0;
804 case OPT_COMMENT:
805 /* nothing to do */
806 break;
807 case 'V':
808 RTPrintf("%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
809 return 0;
810 default:
811 ch = RTGetOptPrintError(ch, &ValueUnion);
812 show_usage();
813 return ch;
814 }
815 }
816
817#ifdef VBOX_WITH_VPX
818 if (ulFrameWidth < 512 || ulFrameWidth > 2048 || ulFrameWidth % 2)
819 {
820 LogError("VBoxHeadless: ERROR: please specify an even frame width between 512 and 2048", 0);
821 return 1;
822 }
823 if (ulFrameHeight < 384 || ulFrameHeight > 1536 || ulFrameHeight % 2)
824 {
825 LogError("VBoxHeadless: ERROR: please specify an even frame height between 384 and 1536", 0);
826 return 1;
827 }
828 if (ulBitRate < 300000 || ulBitRate > 1000000)
829 {
830 LogError("VBoxHeadless: ERROR: please specify an even bitrate between 300000 and 1000000", 0);
831 return 1;
832 }
833 /* Make sure we only have %d or %u (or none) in the file name specified */
834 char *pcPercent = (char*)strchr(pszFileNameParam, '%');
835 if (pcPercent != 0 && *(pcPercent + 1) != 'd' && *(pcPercent + 1) != 'u')
836 {
837 LogError("VBoxHeadless: ERROR: Only %%d and %%u are allowed in the capture file name.", -1);
838 return 1;
839 }
840 /* And no more than one % in the name */
841 if (pcPercent != 0 && strchr(pcPercent + 1, '%') != 0)
842 {
843 LogError("VBoxHeadless: ERROR: Only one format modifier is allowed in the capture file name.", -1);
844 return 1;
845 }
846 RTStrPrintf(&szMpegFile[0], RTPATH_MAX, pszFileNameParam, RTProcSelf());
847#endif /* defined VBOX_WITH_VPX */
848
849 if (!pcszNameOrUUID)
850 {
851 show_usage();
852 return 1;
853 }
854
855 HRESULT rc;
856
857 rc = com::Initialize();
858#ifdef VBOX_WITH_XPCOM
859 if (rc == NS_ERROR_FILE_ACCESS_DENIED)
860 {
861 char szHome[RTPATH_MAX] = "";
862 com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome));
863 RTPrintf("Failed to initialize COM because the global settings directory '%s' is not accessible!", szHome);
864 return 1;
865 }
866#endif
867 if (FAILED(rc))
868 {
869 RTPrintf("VBoxHeadless: ERROR: failed to initialize COM!\n");
870 return 1;
871 }
872
873 ComPtr<IVirtualBoxClient> pVirtualBoxClient;
874 ComPtr<IVirtualBox> virtualBox;
875 ComPtr<ISession> session;
876 ComPtr<IMachine> machine;
877 bool fSessionOpened = false;
878 ComPtr<IEventListener> vboxClientListener;
879 ComPtr<IEventListener> vboxListener;
880 ComObjPtr<ConsoleEventListenerImpl> consoleListener;
881
882 do
883 {
884 rc = pVirtualBoxClient.createInprocObject(CLSID_VirtualBoxClient);
885 if (FAILED(rc))
886 {
887 RTPrintf("VBoxHeadless: ERROR: failed to create the VirtualBoxClient object!\n");
888 com::ErrorInfo info;
889 if (!info.isFullAvailable() && !info.isBasicAvailable())
890 {
891 com::GluePrintRCMessage(rc);
892 RTPrintf("Most likely, the VirtualBox COM server is not running or failed to start.\n");
893 }
894 else
895 GluePrintErrorInfo(info);
896 break;
897 }
898
899 rc = pVirtualBoxClient->COMGETTER(VirtualBox)(virtualBox.asOutParam());
900 if (FAILED(rc))
901 {
902 RTPrintf("Failed to get VirtualBox object (rc=%Rhrc)!\n", rc);
903 break;
904 }
905 rc = pVirtualBoxClient->COMGETTER(Session)(session.asOutParam());
906 if (FAILED(rc))
907 {
908 RTPrintf("Failed to get session object (rc=%Rhrc)!\n", rc);
909 break;
910 }
911
912 if (pcszSettingsPw)
913 {
914 CHECK_ERROR(virtualBox, SetSettingsSecret(Bstr(pcszSettingsPw).raw()));
915 if (FAILED(rc))
916 break;
917 }
918 else if (pcszSettingsPwFile)
919 {
920 int rcExit = settingsPasswordFile(virtualBox, pcszSettingsPwFile);
921 if (rcExit != RTEXITCODE_SUCCESS)
922 break;
923 }
924
925 ComPtr<IMachine> m;
926
927 rc = virtualBox->FindMachine(Bstr(pcszNameOrUUID).raw(), m.asOutParam());
928 if (FAILED(rc))
929 {
930 LogError("Invalid machine name or UUID!\n", rc);
931 break;
932 }
933 Bstr id;
934 m->COMGETTER(Id)(id.asOutParam());
935 AssertComRC(rc);
936 if (FAILED(rc))
937 break;
938
939 Log(("VBoxHeadless: Opening a session with machine (id={%s})...\n",
940 Utf8Str(id).c_str()));
941
942 // set session name
943 CHECK_ERROR_BREAK(session, COMSETTER(Name)(Bstr("headless").raw()));
944 // open a session
945 CHECK_ERROR_BREAK(m, LockMachine(session, LockType_VM));
946 fSessionOpened = true;
947
948 /* get the console */
949 ComPtr<IConsole> console;
950 CHECK_ERROR_BREAK(session, COMGETTER(Console)(console.asOutParam()));
951
952 /* get the mutable machine */
953 CHECK_ERROR_BREAK(console, COMGETTER(Machine)(machine.asOutParam()));
954
955 ComPtr<IDisplay> display;
956 CHECK_ERROR_BREAK(console, COMGETTER(Display)(display.asOutParam()));
957
958#ifdef VBOX_WITH_VPX
959 if (fVideoRec)
960 {
961 CHECK_ERROR_BREAK(machine, COMSETTER(VideoCaptureFile)(Bstr(szMpegFile).raw()));
962 CHECK_ERROR_BREAK(machine, COMSETTER(VideoCaptureWidth)(ulFrameWidth));
963 CHECK_ERROR_BREAK(machine, COMSETTER(VideoCaptureHeight)(ulFrameHeight));
964 CHECK_ERROR_BREAK(machine, COMSETTER(VideoCaptureRate)(ulBitRate));
965 CHECK_ERROR_BREAK(machine, COMSETTER(VideoCaptureEnabled)(TRUE));
966 }
967#endif /* defined(VBOX_WITH_VPX) */
968
969 /* get the machine debugger (isn't necessarily available) */
970 ComPtr <IMachineDebugger> machineDebugger;
971 console->COMGETTER(Debugger)(machineDebugger.asOutParam());
972 if (machineDebugger)
973 {
974 Log(("Machine debugger available!\n"));
975 }
976
977 if (fRawR0 != ~0U)
978 {
979 if (!machineDebugger)
980 {
981 RTPrintf("Error: No debugger object; -%srawr0 cannot be executed!\n", fRawR0 ? "" : "no");
982 break;
983 }
984 machineDebugger->COMSETTER(RecompileSupervisor)(!fRawR0);
985 }
986 if (fRawR3 != ~0U)
987 {
988 if (!machineDebugger)
989 {
990 RTPrintf("Error: No debugger object; -%srawr3 cannot be executed!\n", fRawR3 ? "" : "no");
991 break;
992 }
993 machineDebugger->COMSETTER(RecompileUser)(!fRawR3);
994 }
995 if (fPATM != ~0U)
996 {
997 if (!machineDebugger)
998 {
999 RTPrintf("Error: No debugger object; -%spatm cannot be executed!\n", fPATM ? "" : "no");
1000 break;
1001 }
1002 machineDebugger->COMSETTER(PATMEnabled)(fPATM);
1003 }
1004 if (fCSAM != ~0U)
1005 {
1006 if (!machineDebugger)
1007 {
1008 RTPrintf("Error: No debugger object; -%scsam cannot be executed!\n", fCSAM ? "" : "no");
1009 break;
1010 }
1011 machineDebugger->COMSETTER(CSAMEnabled)(fCSAM);
1012 }
1013
1014 /* initialize global references */
1015 gConsole = console;
1016 gEventQ = com::NativeEventQueue::getMainEventQueue();
1017
1018 /* VirtualBoxClient events registration. */
1019 {
1020 ComPtr<IEventSource> pES;
1021 CHECK_ERROR(pVirtualBoxClient, COMGETTER(EventSource)(pES.asOutParam()));
1022 ComObjPtr<VirtualBoxClientEventListenerImpl> listener;
1023 listener.createObject();
1024 listener->init(new VirtualBoxClientEventListener());
1025 vboxClientListener = listener;
1026 com::SafeArray<VBoxEventType_T> eventTypes;
1027 eventTypes.push_back(VBoxEventType_OnVBoxSVCAvailabilityChanged);
1028 CHECK_ERROR(pES, RegisterListener(vboxClientListener, ComSafeArrayAsInParam(eventTypes), true));
1029 }
1030
1031 /* Console events registration. */
1032 {
1033 ComPtr<IEventSource> es;
1034 CHECK_ERROR(console, COMGETTER(EventSource)(es.asOutParam()));
1035 consoleListener.createObject();
1036 consoleListener->init(new ConsoleEventListener());
1037 com::SafeArray<VBoxEventType_T> eventTypes;
1038 eventTypes.push_back(VBoxEventType_OnMouseCapabilityChanged);
1039 eventTypes.push_back(VBoxEventType_OnStateChanged);
1040 eventTypes.push_back(VBoxEventType_OnVRDEServerInfoChanged);
1041 eventTypes.push_back(VBoxEventType_OnCanShowWindow);
1042 eventTypes.push_back(VBoxEventType_OnShowWindow);
1043 eventTypes.push_back(VBoxEventType_OnGuestPropertyChanged);
1044 CHECK_ERROR(es, RegisterListener(consoleListener, ComSafeArrayAsInParam(eventTypes), true));
1045 }
1046
1047 /* Default is to use the VM setting for the VRDE server. */
1048 enum VRDEOption
1049 {
1050 VRDEOption_Config,
1051 VRDEOption_Off,
1052 VRDEOption_On
1053 };
1054 VRDEOption enmVRDEOption = VRDEOption_Config;
1055 BOOL fVRDEEnabled;
1056 ComPtr <IVRDEServer> vrdeServer;
1057 CHECK_ERROR_BREAK(machine, COMGETTER(VRDEServer)(vrdeServer.asOutParam()));
1058 CHECK_ERROR_BREAK(vrdeServer, COMGETTER(Enabled)(&fVRDEEnabled));
1059
1060 if (vrdeEnabled != NULL)
1061 {
1062 /* -vrde on|off|config */
1063 if (!strcmp(vrdeEnabled, "off") || !strcmp(vrdeEnabled, "disable"))
1064 enmVRDEOption = VRDEOption_Off;
1065 else if (!strcmp(vrdeEnabled, "on") || !strcmp(vrdeEnabled, "enable"))
1066 enmVRDEOption = VRDEOption_On;
1067 else if (strcmp(vrdeEnabled, "config"))
1068 {
1069 RTPrintf("-vrde requires an argument (on|off|config)\n");
1070 break;
1071 }
1072 }
1073
1074 Log(("VBoxHeadless: enmVRDE %d, fVRDEEnabled %d\n", enmVRDEOption, fVRDEEnabled));
1075
1076 if (enmVRDEOption != VRDEOption_Off)
1077 {
1078 /* Set other specified options. */
1079
1080 /* set VRDE port if requested by the user */
1081 if (vrdePort != NULL)
1082 {
1083 Bstr bstr = vrdePort;
1084 CHECK_ERROR_BREAK(vrdeServer, SetVRDEProperty(Bstr("TCP/Ports").raw(), bstr.raw()));
1085 }
1086 /* set VRDE address if requested by the user */
1087 if (vrdeAddress != NULL)
1088 {
1089 CHECK_ERROR_BREAK(vrdeServer, SetVRDEProperty(Bstr("TCP/Address").raw(), Bstr(vrdeAddress).raw()));
1090 }
1091
1092 /* Set VRDE properties. */
1093 if (cVRDEProperties > 0)
1094 {
1095 for (unsigned i = 0; i < cVRDEProperties; i++)
1096 {
1097 /* Parse 'name=value' */
1098 char *pszProperty = RTStrDup(aVRDEProperties[i]);
1099 if (pszProperty)
1100 {
1101 char *pDelimiter = strchr(pszProperty, '=');
1102 if (pDelimiter)
1103 {
1104 *pDelimiter = '\0';
1105
1106 Bstr bstrName = pszProperty;
1107 Bstr bstrValue = &pDelimiter[1];
1108 CHECK_ERROR_BREAK(vrdeServer, SetVRDEProperty(bstrName.raw(), bstrValue.raw()));
1109 }
1110 else
1111 {
1112 RTPrintf("Error: Invalid VRDE property '%s'\n", aVRDEProperties[i]);
1113 RTStrFree(pszProperty);
1114 rc = E_INVALIDARG;
1115 break;
1116 }
1117 RTStrFree(pszProperty);
1118 }
1119 else
1120 {
1121 RTPrintf("Error: Failed to allocate memory for VRDE property '%s'\n", aVRDEProperties[i]);
1122 rc = E_OUTOFMEMORY;
1123 break;
1124 }
1125 }
1126 if (FAILED(rc))
1127 break;
1128 }
1129
1130 }
1131
1132 if (enmVRDEOption == VRDEOption_On)
1133 {
1134 /* enable VRDE server (only if currently disabled) */
1135 if (!fVRDEEnabled)
1136 {
1137 CHECK_ERROR_BREAK(vrdeServer, COMSETTER(Enabled)(TRUE));
1138 }
1139 }
1140 else if (enmVRDEOption == VRDEOption_Off)
1141 {
1142 /* disable VRDE server (only if currently enabled */
1143 if (fVRDEEnabled)
1144 {
1145 CHECK_ERROR_BREAK(vrdeServer, COMSETTER(Enabled)(FALSE));
1146 }
1147 }
1148
1149 /* Disable the host clipboard before powering up */
1150 console->COMSETTER(UseHostClipboard)(false);
1151
1152 Log(("VBoxHeadless: Powering up the machine...\n"));
1153
1154 ComPtr <IProgress> progress;
1155 if (!fPaused)
1156 CHECK_ERROR_BREAK(console, PowerUp(progress.asOutParam()));
1157 else
1158 CHECK_ERROR_BREAK(console, PowerUpPaused(progress.asOutParam()));
1159
1160 /*
1161 * Wait for the result because there can be errors.
1162 *
1163 * It's vital to process events while waiting (teleportation deadlocks),
1164 * so we'll poll for the completion instead of waiting on it.
1165 */
1166 for (;;)
1167 {
1168 BOOL fCompleted;
1169 rc = progress->COMGETTER(Completed)(&fCompleted);
1170 if (FAILED(rc) || fCompleted)
1171 break;
1172
1173 /* Process pending events, then wait for new ones. Note, this
1174 * processes NULL events signalling event loop termination. */
1175 gEventQ->processEventQueue(0);
1176 if (!g_fTerminateFE)
1177 gEventQ->processEventQueue(500);
1178 }
1179
1180 if (SUCCEEDED(progress->WaitForCompletion(-1)))
1181 {
1182 /* Figure out if the operation completed with a failed status
1183 * and print the error message. Terminate immediately, and let
1184 * the cleanup code take care of potentially pending events. */
1185 LONG progressRc;
1186 progress->COMGETTER(ResultCode)(&progressRc);
1187 rc = progressRc;
1188 if (FAILED(rc))
1189 {
1190 com::ProgressErrorInfo info(progress);
1191 if (info.isBasicAvailable())
1192 {
1193 RTPrintf("Error: failed to start machine. Error message: %ls\n", info.getText().raw());
1194 }
1195 else
1196 {
1197 RTPrintf("Error: failed to start machine. No error message available!\n");
1198 }
1199 break;
1200 }
1201 }
1202
1203#ifdef VBOX_WITH_SAVESTATE_ON_SIGNAL
1204 signal(SIGINT, SaveState);
1205 signal(SIGTERM, SaveState);
1206#endif
1207
1208 Log(("VBoxHeadless: Waiting for PowerDown...\n"));
1209
1210 while ( !g_fTerminateFE
1211 && RT_SUCCESS(gEventQ->processEventQueue(RT_INDEFINITE_WAIT)))
1212 /* nothing */ ;
1213
1214 Log(("VBoxHeadless: event loop has terminated...\n"));
1215
1216#ifdef VBOX_WITH_VPX
1217 if (fVideoRec)
1218 {
1219 if (!machine.isNull())
1220 machine->COMSETTER(VideoCaptureEnabled)(FALSE);
1221 }
1222#endif /* defined(VBOX_WITH_VPX) */
1223
1224 /* we don't have to disable VRDE here because we don't save the settings of the VM */
1225 }
1226 while (0);
1227
1228 /*
1229 * Get the machine state.
1230 */
1231 MachineState_T machineState = MachineState_Aborted;
1232 if (!machine.isNull())
1233 machine->COMGETTER(State)(&machineState);
1234
1235 /*
1236 * Turn off the VM if it's running
1237 */
1238 if ( gConsole
1239 && ( machineState == MachineState_Running
1240 || machineState == MachineState_Teleporting
1241 || machineState == MachineState_LiveSnapshotting
1242 /** @todo power off paused VMs too? */
1243 )
1244 )
1245 do
1246 {
1247 consoleListener->getWrapped()->ignorePowerOffEvents(true);
1248 ComPtr<IProgress> pProgress;
1249 CHECK_ERROR_BREAK(gConsole, PowerDown(pProgress.asOutParam()));
1250 CHECK_ERROR_BREAK(pProgress, WaitForCompletion(-1));
1251 BOOL completed;
1252 CHECK_ERROR_BREAK(pProgress, COMGETTER(Completed)(&completed));
1253 ASSERT(completed);
1254 LONG hrc;
1255 CHECK_ERROR_BREAK(pProgress, COMGETTER(ResultCode)(&hrc));
1256 if (FAILED(hrc))
1257 {
1258 RTPrintf("VBoxHeadless: ERROR: Failed to power down VM!");
1259 com::ErrorInfo info;
1260 if (!info.isFullAvailable() && !info.isBasicAvailable())
1261 com::GluePrintRCMessage(hrc);
1262 else
1263 GluePrintErrorInfo(info);
1264 break;
1265 }
1266 } while (0);
1267
1268 /* VirtualBox callback unregistration. */
1269 if (vboxListener)
1270 {
1271 ComPtr<IEventSource> es;
1272 CHECK_ERROR(virtualBox, COMGETTER(EventSource)(es.asOutParam()));
1273 if (!es.isNull())
1274 CHECK_ERROR(es, UnregisterListener(vboxListener));
1275 vboxListener.setNull();
1276 }
1277
1278 /* Console callback unregistration. */
1279 if (consoleListener)
1280 {
1281 ComPtr<IEventSource> es;
1282 CHECK_ERROR(gConsole, COMGETTER(EventSource)(es.asOutParam()));
1283 if (!es.isNull())
1284 CHECK_ERROR(es, UnregisterListener(consoleListener));
1285 consoleListener.setNull();
1286 }
1287
1288 /* VirtualBoxClient callback unregistration. */
1289 if (vboxClientListener)
1290 {
1291 ComPtr<IEventSource> pES;
1292 CHECK_ERROR(pVirtualBoxClient, COMGETTER(EventSource)(pES.asOutParam()));
1293 if (!pES.isNull())
1294 CHECK_ERROR(pES, UnregisterListener(vboxClientListener));
1295 vboxClientListener.setNull();
1296 }
1297
1298 /* No more access to the 'console' object, which will be uninitialized by the next session->Close call. */
1299 gConsole = NULL;
1300
1301 if (fSessionOpened)
1302 {
1303 /*
1304 * Close the session. This will also uninitialize the console and
1305 * unregister the callback we've registered before.
1306 */
1307 Log(("VBoxHeadless: Closing the session...\n"));
1308 session->UnlockMachine();
1309 }
1310
1311 /* Must be before com::Shutdown */
1312 session.setNull();
1313 virtualBox.setNull();
1314 pVirtualBoxClient.setNull();
1315 machine.setNull();
1316
1317 com::Shutdown();
1318
1319 LogFlow(("VBoxHeadless FINISHED.\n"));
1320
1321 return FAILED(rc) ? 1 : 0;
1322}
1323
1324
1325#ifndef VBOX_WITH_HARDENING
1326/**
1327 * Main entry point.
1328 */
1329int main(int argc, char **argv, char **envp)
1330{
1331 // initialize VBox Runtime
1332 int rc = RTR3InitExe(argc, &argv, RTR3INIT_FLAGS_SUPLIB);
1333 if (RT_FAILURE(rc))
1334 {
1335 RTPrintf("VBoxHeadless: Runtime Error:\n"
1336 " %Rrc -- %Rrf\n", rc, rc);
1337 switch (rc)
1338 {
1339 case VERR_VM_DRIVER_NOT_INSTALLED:
1340 RTPrintf("Cannot access the kernel driver. Make sure the kernel module has been \n"
1341 "loaded successfully. Aborting ...\n");
1342 break;
1343 default:
1344 break;
1345 }
1346 return 1;
1347 }
1348
1349 return TrustedMain(argc, argv, envp);
1350}
1351#endif /* !VBOX_WITH_HARDENING */
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