VirtualBox

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

Last change on this file since 50926 was 50406, checked in by vboxsync, 11 years ago

Some RTEnvGet cleanup, adding todos for the rest.

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