VirtualBox

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

Last change on this file since 39631 was 38735, checked in by vboxsync, 13 years ago

%lS -> %ls.

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