VirtualBox

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

Last change on this file since 74942 was 65381, checked in by vboxsync, 8 years ago

bugref:8282: Additions/linux: submit DRM driver to the Linux kernel: move all graphics device-related header files to a separate sub-directory and add that to the include path where they are needed. The intention is too be able to remove the VBox/ include folder in the DRM driver package.

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