VirtualBox

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

Last change on this file since 43777 was 42476, checked in by vboxsync, 12 years ago

VBoxHeadless: help typo

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