VirtualBox

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

Last change on this file since 91692 was 91690, checked in by vboxsync, 3 years ago

VBoxHeadless: bugref:9790 - Don't use logging on the Windows message
loop thread after we've got WM_QUIT.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 66.6 KB
Line 
1/* $Id: VBoxHeadless.cpp 91690 2021-10-12 13:08:19Z vboxsync $ */
2/** @file
3 * VBoxHeadless - The VirtualBox Headless frontend for running VMs on servers.
4 */
5
6/*
7 * Copyright (C) 2006-2020 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/message.h>
39#include <iprt/semaphore.h>
40#include <iprt/path.h>
41#include <iprt/stream.h>
42#include <iprt/ldr.h>
43#include <iprt/getopt.h>
44#include <iprt/env.h>
45#include <VBox/err.h>
46#include <VBoxVideo.h>
47
48#ifdef VBOX_WITH_RECORDING
49# include <cstdlib>
50# include <cerrno>
51# include <iprt/process.h>
52#endif
53
54#ifdef RT_OS_DARWIN
55# include <iprt/asm.h>
56# include <dlfcn.h>
57# include <sys/mman.h>
58#endif
59
60#if !defined(RT_OS_WINDOWS)
61#include <signal.h>
62static void HandleSignal(int sig);
63#endif
64
65#include "PasswordInput.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 NativeEventQueue *gEventQ = NULL;
80
81/* keep this handy for messages */
82static com::Utf8Str g_strVMName;
83static com::Utf8Str g_strVMUUID;
84
85/* flag whether frontend should terminate */
86static volatile bool g_fTerminateFE = false;
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 machine events.
146 */
147class ConsoleEventListener
148{
149public:
150 ConsoleEventListener() :
151 mLastVRDEPort(-1),
152 m_fIgnorePowerOffEvents(false),
153 m_fNoLoggedInUsers(true)
154 {
155 }
156
157 virtual ~ConsoleEventListener()
158 {
159 }
160
161 HRESULT init()
162 {
163 return S_OK;
164 }
165
166 void uninit()
167 {
168 }
169
170 STDMETHOD(HandleEvent)(VBoxEventType_T aType, IEvent *aEvent)
171 {
172 switch (aType)
173 {
174 case VBoxEventType_OnMouseCapabilityChanged:
175 {
176
177 ComPtr<IMouseCapabilityChangedEvent> mccev = aEvent;
178 Assert(!mccev.isNull());
179
180 BOOL fSupportsAbsolute = false;
181 mccev->COMGETTER(SupportsAbsolute)(&fSupportsAbsolute);
182
183 /* Emit absolute mouse event to actually enable the host mouse cursor. */
184 if (fSupportsAbsolute && gConsole)
185 {
186 ComPtr<IMouse> mouse;
187 gConsole->COMGETTER(Mouse)(mouse.asOutParam());
188 if (mouse)
189 {
190 mouse->PutMouseEventAbsolute(-1, -1, 0, 0 /* Horizontal wheel */, 0);
191 }
192 }
193 break;
194 }
195 case VBoxEventType_OnStateChanged:
196 {
197 ComPtr<IStateChangedEvent> scev = aEvent;
198 Assert(scev);
199
200 MachineState_T machineState;
201 scev->COMGETTER(State)(&machineState);
202
203 /* Terminate any event wait operation if the machine has been
204 * PoweredDown/Saved/Aborted. */
205 if (machineState < MachineState_Running && !m_fIgnorePowerOffEvents)
206 {
207 g_fTerminateFE = true;
208 gEventQ->interruptEventQueueProcessing();
209 }
210
211 break;
212 }
213 case VBoxEventType_OnVRDEServerInfoChanged:
214 {
215 ComPtr<IVRDEServerInfoChangedEvent> rdicev = aEvent;
216 Assert(rdicev);
217
218 if (gConsole)
219 {
220 ComPtr<IVRDEServerInfo> info;
221 gConsole->COMGETTER(VRDEServerInfo)(info.asOutParam());
222 if (info)
223 {
224 LONG port;
225 info->COMGETTER(Port)(&port);
226 if (port != mLastVRDEPort)
227 {
228 if (port == -1)
229 RTPrintf("VRDE server is inactive.\n");
230 else if (port == 0)
231 RTPrintf("VRDE server failed to start.\n");
232 else
233 RTPrintf("VRDE server is listening on port %d.\n", port);
234
235 mLastVRDEPort = port;
236 }
237 }
238 }
239 break;
240 }
241 case VBoxEventType_OnCanShowWindow:
242 {
243 ComPtr<ICanShowWindowEvent> cswev = aEvent;
244 Assert(cswev);
245 cswev->AddVeto(NULL);
246 break;
247 }
248 case VBoxEventType_OnShowWindow:
249 {
250 ComPtr<IShowWindowEvent> swev = aEvent;
251 Assert(swev);
252 /* Ignore the event, WinId is either still zero or some other listener assigned it. */
253 NOREF(swev); /* swev->COMSETTER(WinId)(0); */
254 break;
255 }
256 case VBoxEventType_OnGuestPropertyChanged:
257 {
258 ComPtr<IGuestPropertyChangedEvent> pChangedEvent = aEvent;
259 Assert(pChangedEvent);
260
261 HRESULT hrc;
262
263 ComPtr <IMachine> pMachine;
264 if (gConsole)
265 {
266 hrc = gConsole->COMGETTER(Machine)(pMachine.asOutParam());
267 if (FAILED(hrc) || !pMachine)
268 hrc = VBOX_E_OBJECT_NOT_FOUND;
269 }
270 else
271 hrc = VBOX_E_INVALID_VM_STATE;
272
273 if (SUCCEEDED(hrc))
274 {
275 Bstr strKey;
276 hrc = pChangedEvent->COMGETTER(Name)(strKey.asOutParam());
277 AssertComRC(hrc);
278
279 Bstr strValue;
280 hrc = pChangedEvent->COMGETTER(Value)(strValue.asOutParam());
281 AssertComRC(hrc);
282
283 Utf8Str utf8Key = strKey;
284 Utf8Str utf8Value = strValue;
285 LogRelFlow(("Guest property \"%s\" has been changed to \"%s\"\n",
286 utf8Key.c_str(), utf8Value.c_str()));
287
288 if (utf8Key.equals("/VirtualBox/GuestInfo/OS/NoLoggedInUsers"))
289 {
290 LogRelFlow(("Guest indicates that there %s logged in users\n",
291 utf8Value.equals("true") ? "are no" : "are"));
292
293 /* Check if this is our machine and the "disconnect on logout feature" is enabled. */
294 BOOL fProcessDisconnectOnGuestLogout = FALSE;
295
296 /* Does the machine handle VRDP disconnects? */
297 Bstr strDiscon;
298 hrc = pMachine->GetExtraData(Bstr("VRDP/DisconnectOnGuestLogout").raw(),
299 strDiscon.asOutParam());
300 if (SUCCEEDED(hrc))
301 {
302 Utf8Str utf8Discon = strDiscon;
303 fProcessDisconnectOnGuestLogout = utf8Discon.equals("1")
304 ? TRUE : FALSE;
305 }
306
307 LogRelFlow(("VRDE: hrc=%Rhrc: Host %s disconnecting clients (current host state known: %s)\n",
308 hrc, fProcessDisconnectOnGuestLogout ? "will handle" : "does not handle",
309 m_fNoLoggedInUsers ? "No users logged in" : "Users logged in"));
310
311 if (fProcessDisconnectOnGuestLogout)
312 {
313 bool fDropConnection = false;
314 if (!m_fNoLoggedInUsers) /* Only if the property really changes. */
315 {
316 if ( utf8Value == "true"
317 /* Guest property got deleted due to reset,
318 * so it has no value anymore. */
319 || utf8Value.isEmpty())
320 {
321 m_fNoLoggedInUsers = true;
322 fDropConnection = true;
323 }
324 }
325 else if (utf8Value == "false")
326 m_fNoLoggedInUsers = false;
327 /* Guest property got deleted due to reset,
328 * take the shortcut without touching the m_fNoLoggedInUsers
329 * state. */
330 else if (utf8Value.isEmpty())
331 fDropConnection = true;
332
333 LogRelFlow(("VRDE: szNoLoggedInUsers=%s, m_fNoLoggedInUsers=%RTbool, fDropConnection=%RTbool\n",
334 utf8Value.c_str(), m_fNoLoggedInUsers, fDropConnection));
335
336 if (fDropConnection)
337 {
338 /* If there is a connection, drop it. */
339 ComPtr<IVRDEServerInfo> info;
340 hrc = gConsole->COMGETTER(VRDEServerInfo)(info.asOutParam());
341 if (SUCCEEDED(hrc) && info)
342 {
343 ULONG cClients = 0;
344 hrc = info->COMGETTER(NumberOfClients)(&cClients);
345
346 LogRelFlow(("VRDE: connected clients=%RU32\n", cClients));
347 if (SUCCEEDED(hrc) && cClients > 0)
348 {
349 ComPtr <IVRDEServer> vrdeServer;
350 hrc = pMachine->COMGETTER(VRDEServer)(vrdeServer.asOutParam());
351 if (SUCCEEDED(hrc) && vrdeServer)
352 {
353 LogRel(("VRDE: the guest user has logged out, disconnecting remote clients.\n"));
354 hrc = vrdeServer->COMSETTER(Enabled)(FALSE);
355 AssertComRC(hrc);
356 HRESULT hrc2 = vrdeServer->COMSETTER(Enabled)(TRUE);
357 if (SUCCEEDED(hrc))
358 hrc = hrc2;
359 }
360 }
361 }
362 }
363 }
364 }
365
366 if (FAILED(hrc))
367 LogRelFlow(("VRDE: returned error=%Rhrc\n", hrc));
368 }
369
370 break;
371 }
372
373 default:
374 AssertFailed();
375 }
376 return S_OK;
377 }
378
379 void ignorePowerOffEvents(bool fIgnore)
380 {
381 m_fIgnorePowerOffEvents = fIgnore;
382 }
383
384private:
385
386 long mLastVRDEPort;
387 bool m_fIgnorePowerOffEvents;
388 bool m_fNoLoggedInUsers;
389};
390
391typedef ListenerImpl<VirtualBoxClientEventListener> VirtualBoxClientEventListenerImpl;
392typedef ListenerImpl<ConsoleEventListener> ConsoleEventListenerImpl;
393
394VBOX_LISTENER_DECLARE(VirtualBoxClientEventListenerImpl)
395VBOX_LISTENER_DECLARE(ConsoleEventListenerImpl)
396
397#if !defined(RT_OS_WINDOWS)
398static void
399HandleSignal(int sig)
400{
401 RT_NOREF(sig);
402 LogRel(("VBoxHeadless: received singal %d\n", sig));
403 g_fTerminateFE = true;
404}
405#endif /* !RT_OS_WINDOWS */
406
407////////////////////////////////////////////////////////////////////////////////
408
409static void show_usage()
410{
411 RTPrintf("Usage:\n"
412 " -s, -startvm, --startvm <name|uuid> Start given VM (required argument)\n"
413 " -v, -vrde, --vrde on|off|config Enable or disable the VRDE server\n"
414 " or don't change the setting (default)\n"
415 " -e, -vrdeproperty, --vrdeproperty <name=[value]> Set a VRDE property:\n"
416 " \"TCP/Ports\" - comma-separated list of\n"
417 " ports the VRDE server can bind to; dash\n"
418 " between two port numbers specifies range\n"
419 " \"TCP/Address\" - interface IP the VRDE\n"
420 " server will bind to\n"
421 " --settingspw <pw> Specify the settings password\n"
422 " --settingspwfile <file> Specify a file containing the\n"
423 " settings password\n"
424 " -start-paused, --start-paused Start the VM in paused state\n"
425#ifdef VBOX_WITH_RECORDING
426 " -c, -record, --record Record the VM screen output to a file\n"
427 " -w, --videowidth Video frame width when recording\n"
428 " -h, --videoheight Video frame height when recording\n"
429 " -r, --videobitrate Recording bit rate when recording\n"
430 " -f, --filename File name when recording. The codec used\n"
431 " will be chosen based on file extension\n"
432#endif
433 "\n");
434}
435
436#ifdef VBOX_WITH_RECORDING
437/**
438 * Parse the environment for variables which can influence the VIDEOREC settings.
439 * purely for backwards compatibility.
440 * @param pulFrameWidth may be updated with a desired frame width
441 * @param pulFrameHeight may be updated with a desired frame height
442 * @param pulBitRate may be updated with a desired bit rate
443 * @param ppszFilename may be updated with a desired file name
444 */
445static void parse_environ(uint32_t *pulFrameWidth, uint32_t *pulFrameHeight,
446 uint32_t *pulBitRate, const char **ppszFilename)
447{
448 const char *pszEnvTemp;
449/** @todo r=bird: This isn't up to scratch. The life time of an RTEnvGet
450 * return value is only up to the next RTEnv*, *getenv, *putenv,
451 * setenv call in _any_ process in the system and the it has known and
452 * documented code page issues.
453 *
454 * Use RTEnvGetEx instead! */
455 if ((pszEnvTemp = RTEnvGet("VBOX_RECORDWIDTH")) != 0)
456 {
457 errno = 0;
458 unsigned long ulFrameWidth = strtoul(pszEnvTemp, 0, 10);
459 if (errno != 0)
460 LogError("VBoxHeadless: ERROR: invalid VBOX_RECORDWIDTH environment variable", 0);
461 else
462 *pulFrameWidth = ulFrameWidth;
463 }
464 if ((pszEnvTemp = RTEnvGet("VBOX_RECORDHEIGHT")) != 0)
465 {
466 errno = 0;
467 unsigned long ulFrameHeight = strtoul(pszEnvTemp, 0, 10);
468 if (errno != 0)
469 LogError("VBoxHeadless: ERROR: invalid VBOX_RECORDHEIGHT environment variable", 0);
470 else
471 *pulFrameHeight = ulFrameHeight;
472 }
473 if ((pszEnvTemp = RTEnvGet("VBOX_RECORDBITRATE")) != 0)
474 {
475 errno = 0;
476 unsigned long ulBitRate = strtoul(pszEnvTemp, 0, 10);
477 if (errno != 0)
478 LogError("VBoxHeadless: ERROR: invalid VBOX_RECORDBITRATE environment variable", 0);
479 else
480 *pulBitRate = ulBitRate;
481 }
482 if ((pszEnvTemp = RTEnvGet("VBOX_RECORDFILE")) != 0)
483 *ppszFilename = pszEnvTemp;
484}
485#endif /* VBOX_WITH_RECORDING defined */
486
487#ifdef RT_OS_DARWIN
488
489# include <unistd.h>
490# include <stdio.h>
491# include <dlfcn.h>
492# include <iprt/formats/mach-o.h>
493
494/**
495 * Override this one to try hide the fact that we're setuid to root
496 * orginially.
497 */
498int issetugid_for_AppKit(void)
499{
500 Dl_info Info = {0};
501 char szMsg[512];
502 size_t cchMsg;
503 const void * uCaller = __builtin_return_address(0);
504 if (dladdr(uCaller, &Info))
505 cchMsg = snprintf(szMsg, sizeof(szMsg), "DEBUG: issetugid_for_AppKit was called by %p %s::%s+%p\n",
506 uCaller, Info.dli_fname, Info.dli_sname, (void *)((uintptr_t)uCaller - (uintptr_t)Info.dli_saddr));
507 else
508 cchMsg = snprintf(szMsg, sizeof(szMsg), "DEBUG: issetugid_for_AppKit was called by %p\n", uCaller);
509 write(2, szMsg, cchMsg);
510 return 0;
511}
512
513static bool patchExtSym(mach_header_64_t *pHdr, const char *pszSymbol, uintptr_t uNewValue)
514{
515 /*
516 * First do some basic header checks and the scan the load
517 * commands for the symbol table info.
518 */
519 AssertLogRelMsgReturn(pHdr->magic == (ARCH_BITS == 64 ? MH_MAGIC_64 : MH_MAGIC),
520 ("%p: magic=%#x\n", pHdr, pHdr->magic), false);
521 uint32_t const cCmds = pHdr->ncmds;
522 uint32_t const cbCmds = pHdr->sizeofcmds;
523 AssertLogRelMsgReturn(cCmds < 16384 && cbCmds < _2M, ("%p: ncmds=%u sizeofcmds=%u\n", pHdr, cCmds, cbCmds), false);
524
525 /*
526 * First command pass: Locate the symbol table and dynamic symbol table info
527 * commands, also calc the slide (load addr - link addr).
528 */
529 dysymtab_command_t const *pDySymTab = NULL;
530 symtab_command_t const *pSymTab = NULL;
531 segment_command_64_t const *pFirstSeg = NULL;
532 uintptr_t offSlide = 0;
533 uint32_t offCmd = 0;
534 for (uint32_t iCmd = 0; iCmd < cCmds; iCmd++)
535 {
536 AssertLogRelMsgReturn(offCmd + sizeof(load_command_t) <= cbCmds,
537 ("%p: iCmd=%u offCmd=%#x cbCmds=%#x\n", pHdr, iCmd, offCmd, cbCmds), false);
538 load_command_t const * const pCmd = (load_command_t const *)((uintptr_t)(pHdr + 1) + offCmd);
539 uint32_t const cbCurCmd = pCmd->cmdsize;
540 AssertLogRelMsgReturn(offCmd + cbCurCmd <= cbCmds && cbCurCmd <= cbCmds,
541 ("%p: iCmd=%u offCmd=%#x cbCurCmd=%#x cbCmds=%#x\n", pHdr, iCmd, offCmd, cbCurCmd, cbCmds), false);
542 offCmd += cbCurCmd;
543
544 if (pCmd->cmd == LC_SYMTAB)
545 {
546 AssertLogRelMsgReturn(!pSymTab, ("%p: pSymTab=%p pCmd=%p\n", pHdr, pSymTab, pCmd), false);
547 pSymTab = (symtab_command_t const *)pCmd;
548 AssertLogRelMsgReturn(cbCurCmd == sizeof(*pSymTab), ("%p: pSymTab=%p cbCurCmd=%#x\n", pHdr, pCmd, cbCurCmd), false);
549
550 }
551 else if (pCmd->cmd == LC_DYSYMTAB)
552 {
553 AssertLogRelMsgReturn(!pDySymTab, ("%p: pDySymTab=%p pCmd=%p\n", pHdr, pDySymTab, pCmd), false);
554 pDySymTab = (dysymtab_command_t const *)pCmd;
555 AssertLogRelMsgReturn(cbCurCmd == sizeof(*pDySymTab), ("%p: pDySymTab=%p cbCurCmd=%#x\n", pHdr, pCmd, cbCurCmd),
556 false);
557 }
558 else if (pCmd->cmd == LC_SEGMENT_64 && !pFirstSeg) /* ASSUMES the first seg is the one with the header and stuff. */
559 {
560 /* Note! the fileoff and vmaddr seems to be modified. */
561 pFirstSeg = (segment_command_64_t const *)pCmd;
562 AssertLogRelMsgReturn(cbCurCmd >= sizeof(*pFirstSeg), ("%p: iCmd=%u cbCurCmd=%#x\n", pHdr, iCmd, cbCurCmd), false);
563 AssertLogRelMsgReturn(/*pFirstSeg->fileoff == 0 && */ pFirstSeg->vmsize >= sizeof(*pHdr) + cbCmds,
564 ("%p: iCmd=%u fileoff=%llx vmsize=%#llx cbCmds=%#x name=%.16s\n",
565 pHdr, iCmd, pFirstSeg->fileoff, pFirstSeg->vmsize, cbCmds, pFirstSeg->segname), false);
566 offSlide = (uintptr_t)pHdr - pFirstSeg->vmaddr;
567 }
568 }
569 AssertLogRelMsgReturn(pSymTab, ("%p: no LC_SYMTAB\n", pHdr), false);
570 AssertLogRelMsgReturn(pDySymTab, ("%p: no LC_DYSYMTAB\n", pHdr), false);
571 AssertLogRelMsgReturn(pFirstSeg, ("%p: no LC_SEGMENT_64\n", pHdr), false);
572
573 /*
574 * Second command pass: Locate the memory locations of the symbol table, string
575 * table and the indirect symbol table by checking LC_SEGMENT_xx.
576 */
577 macho_nlist_64_t const *paSymbols = NULL;
578 uint32_t const offSymbols = pSymTab->symoff;
579 uint32_t const cSymbols = pSymTab->nsyms;
580 AssertLogRelMsgReturn(cSymbols > 0 && offSymbols >= sizeof(pHdr) + cbCmds,
581 ("%p: cSymbols=%#x offSymbols=%#x\n", pHdr, cSymbols, offSymbols), false);
582
583 const char *pchStrTab = NULL;
584 uint32_t const offStrTab = pSymTab->stroff;
585 uint32_t const cbStrTab = pSymTab->strsize;
586 AssertLogRelMsgReturn(cbStrTab > 0 && offStrTab >= sizeof(pHdr) + cbCmds,
587 ("%p: cbStrTab=%#x offStrTab=%#x\n", pHdr, cbStrTab, offStrTab), false);
588
589 uint32_t const *paidxIndirSymbols = NULL;
590 uint32_t const offIndirSymbols = pDySymTab->indirectsymboff;
591 uint32_t const cIndirSymbols = pDySymTab->nindirectsymb;
592 AssertLogRelMsgReturn(cIndirSymbols > 0 && offIndirSymbols >= sizeof(pHdr) + cbCmds,
593 ("%p: cIndirSymbols=%#x offIndirSymbols=%#x\n", pHdr, cIndirSymbols, offIndirSymbols), false);
594
595 offCmd = 0;
596 for (uint32_t iCmd = 0; iCmd < cCmds; iCmd++)
597 {
598 load_command_t const * const pCmd = (load_command_t const *)((uintptr_t)(pHdr + 1) + offCmd);
599 uint32_t const cbCurCmd = pCmd->cmdsize;
600 AssertLogRelMsgReturn(offCmd + cbCurCmd <= cbCmds && cbCurCmd <= cbCmds,
601 ("%p: iCmd=%u offCmd=%#x cbCurCmd=%#x cbCmds=%#x\n", pHdr, iCmd, offCmd, cbCurCmd, cbCmds), false);
602 offCmd += cbCurCmd;
603
604 if (pCmd->cmd == LC_SEGMENT_64)
605 {
606 segment_command_64_t const *pSeg = (segment_command_64_t const *)pCmd;
607 AssertLogRelMsgReturn(cbCurCmd >= sizeof(*pSeg), ("%p: iCmd=%u cbCurCmd=%#x\n", pHdr, iCmd, cbCurCmd), false);
608 uintptr_t const uPtrSeg = pSeg->vmaddr + offSlide;
609 uint64_t const cbSeg = pSeg->vmsize;
610 uint64_t const offFile = pSeg->fileoff;
611
612 uint64_t offSeg = offSymbols - offFile;
613 if (offSeg < cbSeg)
614 {
615 AssertLogRelMsgReturn(!paSymbols, ("%p: paSymbols=%p uPtrSeg=%p off=%#llx\n", pHdr, paSymbols, uPtrSeg, offSeg),
616 false);
617 AssertLogRelMsgReturn(offSeg + cSymbols * sizeof(paSymbols[0]) <= cbSeg,
618 ("%p: offSeg=%#llx cSymbols=%#x cbSeg=%llx\n", pHdr, offSeg, cSymbols, cbSeg), false);
619 paSymbols = (macho_nlist_64_t const *)(uPtrSeg + offSeg);
620 }
621
622 offSeg = offStrTab - offFile;
623 if (offSeg < cbSeg)
624 {
625 AssertLogRelMsgReturn(!pchStrTab, ("%p: paSymbols=%p uPtrSeg=%p\n", pHdr, pchStrTab, uPtrSeg), false);
626 AssertLogRelMsgReturn(offSeg + cbStrTab <= cbSeg,
627 ("%p: offSeg=%#llx cbStrTab=%#x cbSeg=%llx\n", pHdr, offSeg, cbStrTab, cbSeg), false);
628 pchStrTab = (const char *)(uPtrSeg + offSeg);
629 }
630
631 offSeg = offIndirSymbols - offFile;
632 if (offSeg < cbSeg)
633 {
634 AssertLogRelMsgReturn(!paidxIndirSymbols,
635 ("%p: paidxIndirSymbols=%p uPtrSeg=%p\n", pHdr, paidxIndirSymbols, uPtrSeg), false);
636 AssertLogRelMsgReturn(offSeg + cIndirSymbols * sizeof(paidxIndirSymbols[0]) <= cbSeg,
637 ("%p: offSeg=%#llx cIndirSymbols=%#x cbSeg=%llx\n", pHdr, offSeg, cIndirSymbols, cbSeg),
638 false);
639 paidxIndirSymbols = (uint32_t const *)(uPtrSeg + offSeg);
640 }
641 }
642 }
643
644 AssertLogRelMsgReturn(paSymbols, ("%p: offSymbols=%#x\n", pHdr, offSymbols), false);
645 AssertLogRelMsgReturn(pchStrTab, ("%p: offStrTab=%#x\n", pHdr, offStrTab), false);
646 AssertLogRelMsgReturn(paidxIndirSymbols, ("%p: offIndirSymbols=%#x\n", pHdr, offIndirSymbols), false);
647
648 /*
649 * Third command pass: Process sections of types S_NON_LAZY_SYMBOL_POINTERS
650 * and S_LAZY_SYMBOL_POINTERS
651 */
652 bool fFound = false;
653 offCmd = 0;
654 for (uint32_t iCmd = 0; iCmd < cCmds; iCmd++)
655 {
656 load_command_t const * const pCmd = (load_command_t const *)((uintptr_t)(pHdr + 1) + offCmd);
657 uint32_t const cbCurCmd = pCmd->cmdsize;
658 AssertLogRelMsgReturn(offCmd + cbCurCmd <= cbCmds && cbCurCmd <= cbCmds,
659 ("%p: iCmd=%u offCmd=%#x cbCurCmd=%#x cbCmds=%#x\n", pHdr, iCmd, offCmd, cbCurCmd, cbCmds), false);
660 offCmd += cbCurCmd;
661 if (pCmd->cmd == LC_SEGMENT_64)
662 {
663 segment_command_64_t const *pSeg = (segment_command_64_t const *)pCmd;
664 AssertLogRelMsgReturn(cbCurCmd >= sizeof(*pSeg), ("%p: iCmd=%u cbCurCmd=%#x\n", pHdr, iCmd, cbCurCmd), false);
665 uint64_t const uSegAddr = pSeg->vmaddr;
666 uint64_t const cbSeg = pSeg->vmsize;
667
668 uint32_t const cSections = pSeg->nsects;
669 section_64_t const * const paSections = (section_64_t const *)(pSeg + 1);
670 AssertLogRelMsgReturn(cSections < _256K && sizeof(*pSeg) + cSections * sizeof(paSections[0]) <= cbCurCmd,
671 ("%p: iCmd=%u cSections=%#x cbCurCmd=%#x\n", pHdr, iCmd, cSections, cbCurCmd), false);
672 for (uint32_t iSection = 0; iSection < cSections; iSection++)
673 {
674 if ( paSections[iSection].flags == S_NON_LAZY_SYMBOL_POINTERS
675 || paSections[iSection].flags == S_LAZY_SYMBOL_POINTERS)
676 {
677 uint32_t const idxIndirBase = paSections[iSection].reserved1;
678 uint32_t const cEntries = paSections[iSection].size / sizeof(uintptr_t);
679 AssertLogRelMsgReturn(idxIndirBase <= cIndirSymbols && idxIndirBase + cEntries <= cIndirSymbols,
680 ("%p: idxIndirBase=%#x cEntries=%#x cIndirSymbols=%#x\n",
681 pHdr, idxIndirBase, cEntries, cIndirSymbols), false);
682 uint64_t const uSecAddr = paSections[iSection].addr;
683 uint64_t const offInSeg = uSecAddr - uSegAddr;
684 AssertLogRelMsgReturn(offInSeg < cbSeg && offInSeg + cEntries * sizeof(uintptr_t) <= cbSeg,
685 ("%p: offInSeg=%#llx cEntries=%#x cbSeg=%#llx\n", pHdr, offInSeg, cEntries, cbSeg),
686 false);
687 uintptr_t *pauPtrs = (uintptr_t *)(uSecAddr + offSlide);
688 for (uint32_t iEntry = 0; iEntry < cEntries; iEntry++)
689 {
690 uint32_t const idxSym = paidxIndirSymbols[idxIndirBase + iEntry];
691 if (idxSym < cSymbols)
692 {
693 macho_nlist_64_t const * const pSym = &paSymbols[idxSym];
694 const char * const pszName = pSym->n_un.n_strx < cbStrTab
695 ? &pchStrTab[pSym->n_un.n_strx] : "!invalid symtab offset!";
696 if (strcmp(pszName, pszSymbol) == 0)
697 {
698 pauPtrs[iEntry] = uNewValue;
699 fFound = true;
700 break;
701 }
702 }
703 else
704 AssertMsg(idxSym == INDIRECT_SYMBOL_LOCAL || idxSym == INDIRECT_SYMBOL_ABS, ("%#x\n", idxSym));
705 }
706 }
707 }
708 }
709 }
710 AssertLogRel(fFound);
711 return fFound;
712}
713
714/**
715 * Mac OS X: Really ugly hack to bypass a set-uid check in AppKit.
716 *
717 * This will modify the issetugid() function to always return zero. This must
718 * be done _before_ AppKit is initialized, otherwise it will refuse to play ball
719 * with us as it distrusts set-uid processes since Snow Leopard. We, however,
720 * have carefully dropped all root privileges at this point and there should be
721 * no reason for any security concern here.
722 */
723static void hideSetUidRootFromAppKit()
724{
725 void *pvAddr;
726 /* Find issetguid() and make it always return 0 by modifying the code: */
727# if 0
728 pvAddr = dlsym(RTLD_DEFAULT, "issetugid");
729 int rc = mprotect((void *)((uintptr_t)pvAddr & ~(uintptr_t)0xfff), 0x2000, PROT_WRITE | PROT_READ | PROT_EXEC);
730 if (!rc)
731 ASMAtomicWriteU32((volatile uint32_t *)pvAddr, 0xccc3c031); /* xor eax, eax; ret; int3 */
732 else
733# endif
734 {
735 /* Failing that, find AppKit and patch its import table: */
736 void *pvAppKit = dlopen("/System/Library/Frameworks/AppKit.framework/AppKit", RTLD_NOLOAD);
737 pvAddr = dlsym(pvAppKit, "NSApplicationMain");
738 Dl_info Info = {0};
739 if ( dladdr(pvAddr, &Info)
740 && Info.dli_fbase != NULL)
741 {
742 if (!patchExtSym((mach_header_64_t *)Info.dli_fbase, "_issetugid", (uintptr_t)&issetugid_for_AppKit))
743 write(2, RT_STR_TUPLE("WARNING: Failed to patch issetugid in AppKit! (patchExtSym)\n"));
744# ifdef DEBUG
745 else
746 write(2, RT_STR_TUPLE("INFO: Successfully patched _issetugid import for AppKit!\n"));
747# endif
748 }
749 else
750 write(2, RT_STR_TUPLE("WARNING: Failed to patch issetugid in AppKit! (dladdr)\n"));
751 }
752
753}
754
755#endif /* RT_OS_DARWIN */
756
757
758#ifdef RT_OS_WINDOWS
759
760#define MAIN_WND_CLASS L"VirtualBox Headless Interface"
761
762HINSTANCE g_hInstance = NULL;
763HWND g_hWindow = NULL;
764RTSEMEVENT g_hCanQuit;
765
766static DECLCALLBACK(int) windowsMessageMonitor(RTTHREAD ThreadSelf, void *pvUser);
767static int createWindow();
768static LRESULT CALLBACK WinMainWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
769static void destroyWindow();
770
771
772static DECLCALLBACK(int)
773windowsMessageMonitor(RTTHREAD ThreadSelf, void *pvUser)
774{
775 RT_NOREF(ThreadSelf, pvUser);
776 int rc;
777
778 rc = createWindow();
779 if (RT_FAILURE(rc))
780 return rc;
781
782 RTSemEventCreate(&g_hCanQuit);
783
784 MSG msg;
785 BOOL b;
786 while ((b = ::GetMessage(&msg, 0, 0, 0)) > 0)
787 {
788 ::TranslateMessage(&msg);
789 ::DispatchMessage(&msg);
790 }
791
792 if (b < 0)
793 LogRel(("VBoxHeadless: GetMessage failed\n"));
794
795 destroyWindow();
796 return VINF_SUCCESS;
797}
798
799
800static int
801createWindow()
802{
803 /* program instance handle */
804 g_hInstance = (HINSTANCE)::GetModuleHandle(NULL);
805 if (g_hInstance == NULL)
806 {
807 LogRel(("VBoxHeadless: failed to obtain module handle\n"));
808 return VERR_GENERAL_FAILURE;
809 }
810
811 /* window class */
812 WNDCLASS wc;
813 RT_ZERO(wc);
814
815 wc.style = CS_NOCLOSE;
816 wc.lpfnWndProc = WinMainWndProc;
817 wc.hInstance = g_hInstance;
818 wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1);
819 wc.lpszClassName = MAIN_WND_CLASS;
820
821 ATOM atomWindowClass = ::RegisterClass(&wc);
822 if (atomWindowClass == 0)
823 {
824 LogRel(("VBoxHeadless: failed to register window class\n"));
825 return VERR_GENERAL_FAILURE;
826 }
827
828 /* secret window, secret garden */
829 g_hWindow = ::CreateWindowEx(0, MAIN_WND_CLASS, MAIN_WND_CLASS, 0,
830 0, 0, 1, 1, NULL, NULL, g_hInstance, NULL);
831 if (g_hWindow == NULL)
832 {
833 LogRel(("VBoxHeadless: failed to create window\n"));
834 return VERR_GENERAL_FAILURE;
835 }
836
837 return VINF_SUCCESS;
838}
839
840
841static void
842destroyWindow()
843{
844 if (g_hWindow == NULL)
845 return;
846
847 ::DestroyWindow(g_hWindow);
848 g_hWindow = NULL;
849
850 if (g_hInstance == NULL)
851 return;
852
853 ::UnregisterClass(MAIN_WND_CLASS, g_hInstance);
854 g_hInstance = NULL;
855}
856
857
858static LRESULT CALLBACK
859WinMainWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
860{
861 int rc;
862
863 LRESULT lResult = 0;
864 switch (msg)
865 {
866 case WM_QUERYENDSESSION:
867 LogRel(("VBoxHeadless: WM_QUERYENDSESSION:%s%s%s%s (0x%08lx)\n",
868 lParam == 0 ? " shutdown" : "",
869 lParam & ENDSESSION_CRITICAL ? " critical" : "",
870 lParam & ENDSESSION_LOGOFF ? " logoff" : "",
871 lParam & ENDSESSION_CLOSEAPP ? " close" : "",
872 (unsigned long)lParam));
873
874 /* do not block windows session termination */
875 lResult = TRUE;
876 break;
877
878 case WM_ENDSESSION:
879 lResult = 0;
880 LogRel(("WM_ENDSESSION:%s%s%s%s%s (%s/0x%08lx)\n",
881 lParam == 0 ? " shutdown" : "",
882 lParam & ENDSESSION_CRITICAL ? " critical" : "",
883 lParam & ENDSESSION_LOGOFF ? " logoff" : "",
884 lParam & ENDSESSION_CLOSEAPP ? " close" : "",
885 wParam == FALSE ? " cancelled" : "",
886 wParam ? "TRUE" : "FALSE",
887 (unsigned long)lParam));
888 if (wParam == FALSE)
889 break;
890
891 /* tell the user what we are doing */
892 ::ShutdownBlockReasonCreate(hwnd,
893 com::BstrFmt("%s saving state",
894 g_strVMName.c_str()).raw());
895
896 /* tell the VM to save state/power off */
897 g_fTerminateFE = true;
898 gEventQ->interruptEventQueueProcessing();
899
900 if (g_hCanQuit != NIL_RTSEMEVENT)
901 {
902 LogRel(("VBoxHeadless: WM_ENDSESSION: waiting for VM termination...\n"));
903
904 rc = RTSemEventWait(g_hCanQuit, RT_INDEFINITE_WAIT);
905 if (RT_SUCCESS(rc))
906 LogRel(("VBoxHeadless: WM_ENDSESSION: done\n"));
907 else
908 LogRel(("VBoxHeadless: WM_ENDSESSION: failed to wait for VM termination: %Rrc\n", rc));
909 }
910 else
911 {
912 LogRel(("VBoxHeadless: WM_ENDSESSION: cannot wait for VM termination\n"));
913 }
914 break;
915
916 default:
917 lResult = ::DefWindowProc(hwnd, msg, wParam, lParam);
918 break;
919 }
920 return lResult;
921}
922
923
924static const char * const ctrl_event_names[] = {
925 "CTRL_C_EVENT",
926 "CTRL_BREAK_EVENT",
927 "CTRL_CLOSE_EVENT",
928 /* reserved, not used */
929 "<console control event 3>",
930 "<console control event 4>",
931 /* not sent to processes that load gdi32.dll or user32.dll */
932 "CTRL_LOGOFF_EVENT",
933 "CTRL_SHUTDOWN_EVENT",
934};
935
936
937BOOL WINAPI
938ConsoleCtrlHandler(DWORD dwCtrlType) RT_NOTHROW_DEF
939{
940 const char *signame;
941 char namebuf[48];
942 int rc;
943
944 if (dwCtrlType < RT_ELEMENTS(ctrl_event_names))
945 signame = ctrl_event_names[dwCtrlType];
946 else
947 {
948 /* should not happen, but be prepared */
949 RTStrPrintf(namebuf, sizeof(namebuf),
950 "<console control event %lu>", (unsigned long)dwCtrlType);
951 signame = namebuf;
952 }
953 LogRel(("VBoxHeadless: got %s\n", signame));
954 RTMsgInfo("Got %s\n", signame);
955 RTMsgInfo("");
956
957 /* tell the VM to save state/power off */
958 g_fTerminateFE = true;
959 gEventQ->interruptEventQueueProcessing();
960
961 /*
962 * We don't need to wait for Ctrl-C / Ctrl-Break, but we must wait
963 * for Close, or we will be killed before the VM is saved.
964 */
965 if (g_hCanQuit != NIL_RTSEMEVENT)
966 {
967 LogRel(("VBoxHeadless: waiting for VM termination...\n"));
968
969 rc = RTSemEventWait(g_hCanQuit, RT_INDEFINITE_WAIT);
970 if (RT_FAILURE(rc))
971 LogRel(("VBoxHeadless: Failed to wait for VM termination: %Rrc\n", rc));
972 }
973
974 /* tell the system we handled it */
975 LogRel(("VBoxHeadless: ConsoleCtrlHandler: return\n"));
976 return TRUE;
977}
978#endif /* RT_OS_WINDOWS */
979
980
981/*
982 * Simplified version of showProgress() borrowed from VBoxManage.
983 * Note that machine power up/down operations are not cancelable, so
984 * we don't bother checking for signals.
985 */
986HRESULT
987showProgress(const ComPtr<IProgress> &progress)
988{
989 BOOL fCompleted = FALSE;
990 ULONG ulLastPercent = 0;
991 ULONG ulCurrentPercent = 0;
992 HRESULT hrc;
993
994 com::Bstr bstrDescription;
995 hrc = progress->COMGETTER(Description(bstrDescription.asOutParam()));
996 if (FAILED(hrc))
997 {
998 RTStrmPrintf(g_pStdErr, "Failed to get progress description: %Rhrc\n", hrc);
999 return hrc;
1000 }
1001
1002 RTStrmPrintf(g_pStdErr, "%ls: ", bstrDescription.raw());
1003 RTStrmFlush(g_pStdErr);
1004
1005 hrc = progress->COMGETTER(Completed(&fCompleted));
1006 while (SUCCEEDED(hrc))
1007 {
1008 progress->COMGETTER(Percent(&ulCurrentPercent));
1009
1010 /* did we cross a 10% mark? */
1011 if (ulCurrentPercent / 10 > ulLastPercent / 10)
1012 {
1013 /* make sure to also print out missed steps */
1014 for (ULONG curVal = (ulLastPercent / 10) * 10 + 10; curVal <= (ulCurrentPercent / 10) * 10; curVal += 10)
1015 {
1016 if (curVal < 100)
1017 {
1018 RTStrmPrintf(g_pStdErr, "%u%%...", curVal);
1019 RTStrmFlush(g_pStdErr);
1020 }
1021 }
1022 ulLastPercent = (ulCurrentPercent / 10) * 10;
1023 }
1024
1025 if (fCompleted)
1026 break;
1027
1028 gEventQ->processEventQueue(500);
1029 hrc = progress->COMGETTER(Completed(&fCompleted));
1030 }
1031
1032 /* complete the line. */
1033 LONG iRc = E_FAIL;
1034 hrc = progress->COMGETTER(ResultCode)(&iRc);
1035 if (SUCCEEDED(hrc))
1036 {
1037 if (SUCCEEDED(iRc))
1038 RTStrmPrintf(g_pStdErr, "100%%\n");
1039#if 0
1040 else if (g_fCanceled)
1041 RTStrmPrintf(g_pStdErr, "CANCELED\n");
1042#endif
1043 else
1044 {
1045 RTStrmPrintf(g_pStdErr, "\n");
1046 RTStrmPrintf(g_pStdErr, "Operation failed: %Rhrc\n", iRc);
1047 }
1048 hrc = iRc;
1049 }
1050 else
1051 {
1052 RTStrmPrintf(g_pStdErr, "\n");
1053 RTStrmPrintf(g_pStdErr, "Failed to obtain operation result: %Rhrc\n", hrc);
1054 }
1055 RTStrmFlush(g_pStdErr);
1056 return hrc;
1057}
1058
1059
1060/**
1061 * Entry point.
1062 */
1063extern "C" DECLEXPORT(int) TrustedMain(int argc, char **argv, char **envp)
1064{
1065 RT_NOREF(envp);
1066 const char *vrdePort = NULL;
1067 const char *vrdeAddress = NULL;
1068 const char *vrdeEnabled = NULL;
1069 unsigned cVRDEProperties = 0;
1070 const char *aVRDEProperties[16];
1071 unsigned fRawR0 = ~0U;
1072 unsigned fRawR3 = ~0U;
1073 unsigned fPATM = ~0U;
1074 unsigned fCSAM = ~0U;
1075 unsigned fPaused = 0;
1076#ifdef VBOX_WITH_RECORDING
1077 bool fRecordEnabled = false;
1078 uint32_t ulRecordVideoWidth = 800;
1079 uint32_t ulRecordVideoHeight = 600;
1080 uint32_t ulRecordVideoRate = 300000;
1081 char szRecordFilename[RTPATH_MAX];
1082 const char *pszRecordFilenameTemplate = "VBox-%d.webm"; /* .webm container by default. */
1083#endif /* VBOX_WITH_RECORDING */
1084#ifdef RT_OS_WINDOWS
1085 ATL::CComModule _Module; /* Required internally by ATL (constructor records instance in global variable). */
1086#endif
1087
1088 LogFlow(("VBoxHeadless STARTED.\n"));
1089 RTPrintf(VBOX_PRODUCT " Headless Interface " VBOX_VERSION_STRING "\n"
1090 "(C) 2008-" VBOX_C_YEAR " " VBOX_VENDOR "\n"
1091 "All rights reserved.\n\n");
1092
1093#ifdef VBOX_WITH_RECORDING
1094 /* Parse the environment */
1095 parse_environ(&ulRecordVideoWidth, &ulRecordVideoHeight, &ulRecordVideoRate, &pszRecordFilenameTemplate);
1096#endif
1097
1098 enum eHeadlessOptions
1099 {
1100 OPT_RAW_R0 = 0x100,
1101 OPT_NO_RAW_R0,
1102 OPT_RAW_R3,
1103 OPT_NO_RAW_R3,
1104 OPT_PATM,
1105 OPT_NO_PATM,
1106 OPT_CSAM,
1107 OPT_NO_CSAM,
1108 OPT_SETTINGSPW,
1109 OPT_SETTINGSPW_FILE,
1110 OPT_COMMENT,
1111 OPT_PAUSED
1112 };
1113
1114 static const RTGETOPTDEF s_aOptions[] =
1115 {
1116 { "-startvm", 's', RTGETOPT_REQ_STRING },
1117 { "--startvm", 's', RTGETOPT_REQ_STRING },
1118 { "-vrdpport", 'p', RTGETOPT_REQ_STRING }, /* VRDE: deprecated. */
1119 { "--vrdpport", 'p', RTGETOPT_REQ_STRING }, /* VRDE: deprecated. */
1120 { "-vrdpaddress", 'a', RTGETOPT_REQ_STRING }, /* VRDE: deprecated. */
1121 { "--vrdpaddress", 'a', RTGETOPT_REQ_STRING }, /* VRDE: deprecated. */
1122 { "-vrdp", 'v', RTGETOPT_REQ_STRING }, /* VRDE: deprecated. */
1123 { "--vrdp", 'v', RTGETOPT_REQ_STRING }, /* VRDE: deprecated. */
1124 { "-vrde", 'v', RTGETOPT_REQ_STRING },
1125 { "--vrde", 'v', RTGETOPT_REQ_STRING },
1126 { "-vrdeproperty", 'e', RTGETOPT_REQ_STRING },
1127 { "--vrdeproperty", 'e', RTGETOPT_REQ_STRING },
1128 { "-rawr0", OPT_RAW_R0, 0 },
1129 { "--rawr0", OPT_RAW_R0, 0 },
1130 { "-norawr0", OPT_NO_RAW_R0, 0 },
1131 { "--norawr0", OPT_NO_RAW_R0, 0 },
1132 { "-rawr3", OPT_RAW_R3, 0 },
1133 { "--rawr3", OPT_RAW_R3, 0 },
1134 { "-norawr3", OPT_NO_RAW_R3, 0 },
1135 { "--norawr3", OPT_NO_RAW_R3, 0 },
1136 { "-patm", OPT_PATM, 0 },
1137 { "--patm", OPT_PATM, 0 },
1138 { "-nopatm", OPT_NO_PATM, 0 },
1139 { "--nopatm", OPT_NO_PATM, 0 },
1140 { "-csam", OPT_CSAM, 0 },
1141 { "--csam", OPT_CSAM, 0 },
1142 { "-nocsam", OPT_NO_CSAM, 0 },
1143 { "--nocsam", OPT_NO_CSAM, 0 },
1144 { "--settingspw", OPT_SETTINGSPW, RTGETOPT_REQ_STRING },
1145 { "--settingspwfile", OPT_SETTINGSPW_FILE, RTGETOPT_REQ_STRING },
1146#ifdef VBOX_WITH_RECORDING
1147 { "-record", 'c', 0 },
1148 { "--record", 'c', 0 },
1149 { "--videowidth", 'w', RTGETOPT_REQ_UINT32 },
1150 { "--videoheight", 'h', RTGETOPT_REQ_UINT32 }, /* great choice of short option! */
1151 { "--videorate", 'r', RTGETOPT_REQ_UINT32 },
1152 { "--filename", 'f', RTGETOPT_REQ_STRING },
1153#endif /* VBOX_WITH_RECORDING defined */
1154 { "-comment", OPT_COMMENT, RTGETOPT_REQ_STRING },
1155 { "--comment", OPT_COMMENT, RTGETOPT_REQ_STRING },
1156 { "-start-paused", OPT_PAUSED, 0 },
1157 { "--start-paused", OPT_PAUSED, 0 }
1158 };
1159
1160 const char *pcszNameOrUUID = NULL;
1161
1162#ifdef RT_OS_DARWIN
1163 hideSetUidRootFromAppKit();
1164#endif
1165
1166 // parse the command line
1167 int ch;
1168 const char *pcszSettingsPw = NULL;
1169 const char *pcszSettingsPwFile = NULL;
1170 RTGETOPTUNION ValueUnion;
1171 RTGETOPTSTATE GetState;
1172 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, 0 /* fFlags */);
1173 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1174 {
1175 switch(ch)
1176 {
1177 case 's':
1178 pcszNameOrUUID = ValueUnion.psz;
1179 break;
1180 case 'p':
1181 RTPrintf("Warning: '-p' or '-vrdpport' are deprecated. Use '-e \"TCP/Ports=%s\"'\n", ValueUnion.psz);
1182 vrdePort = ValueUnion.psz;
1183 break;
1184 case 'a':
1185 RTPrintf("Warning: '-a' or '-vrdpaddress' are deprecated. Use '-e \"TCP/Address=%s\"'\n", ValueUnion.psz);
1186 vrdeAddress = ValueUnion.psz;
1187 break;
1188 case 'v':
1189 vrdeEnabled = ValueUnion.psz;
1190 break;
1191 case 'e':
1192 if (cVRDEProperties < RT_ELEMENTS(aVRDEProperties))
1193 aVRDEProperties[cVRDEProperties++] = ValueUnion.psz;
1194 else
1195 RTPrintf("Warning: too many VRDE properties. Ignored: '%s'\n", ValueUnion.psz);
1196 break;
1197 case OPT_RAW_R0:
1198 fRawR0 = true;
1199 break;
1200 case OPT_NO_RAW_R0:
1201 fRawR0 = false;
1202 break;
1203 case OPT_RAW_R3:
1204 fRawR3 = true;
1205 break;
1206 case OPT_NO_RAW_R3:
1207 fRawR3 = false;
1208 break;
1209 case OPT_PATM:
1210 fPATM = true;
1211 break;
1212 case OPT_NO_PATM:
1213 fPATM = false;
1214 break;
1215 case OPT_CSAM:
1216 fCSAM = true;
1217 break;
1218 case OPT_NO_CSAM:
1219 fCSAM = false;
1220 break;
1221 case OPT_SETTINGSPW:
1222 pcszSettingsPw = ValueUnion.psz;
1223 break;
1224 case OPT_SETTINGSPW_FILE:
1225 pcszSettingsPwFile = ValueUnion.psz;
1226 break;
1227 case OPT_PAUSED:
1228 fPaused = true;
1229 break;
1230#ifdef VBOX_WITH_RECORDING
1231 case 'c':
1232 fRecordEnabled = true;
1233 break;
1234 case 'w':
1235 ulRecordVideoWidth = ValueUnion.u32;
1236 break;
1237 case 'r':
1238 ulRecordVideoRate = ValueUnion.u32;
1239 break;
1240 case 'f':
1241 pszRecordFilenameTemplate = ValueUnion.psz;
1242 break;
1243#endif /* VBOX_WITH_RECORDING defined */
1244 case 'h':
1245#ifdef VBOX_WITH_RECORDING
1246 if ((GetState.pDef->fFlags & RTGETOPT_REQ_MASK) != RTGETOPT_REQ_NOTHING)
1247 {
1248 ulRecordVideoHeight = ValueUnion.u32;
1249 break;
1250 }
1251#endif
1252 show_usage();
1253 return 0;
1254 case OPT_COMMENT:
1255 /* nothing to do */
1256 break;
1257 case 'V':
1258 RTPrintf("%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
1259 return 0;
1260 default:
1261 ch = RTGetOptPrintError(ch, &ValueUnion);
1262 show_usage();
1263 return ch;
1264 }
1265 }
1266
1267#ifdef VBOX_WITH_RECORDING
1268 if (ulRecordVideoWidth < 512 || ulRecordVideoWidth > 2048 || ulRecordVideoWidth % 2)
1269 {
1270 LogError("VBoxHeadless: ERROR: please specify an even video frame width between 512 and 2048", 0);
1271 return 1;
1272 }
1273 if (ulRecordVideoHeight < 384 || ulRecordVideoHeight > 1536 || ulRecordVideoHeight % 2)
1274 {
1275 LogError("VBoxHeadless: ERROR: please specify an even video frame height between 384 and 1536", 0);
1276 return 1;
1277 }
1278 if (ulRecordVideoRate < 300000 || ulRecordVideoRate > 1000000)
1279 {
1280 LogError("VBoxHeadless: ERROR: please specify an even video bitrate between 300000 and 1000000", 0);
1281 return 1;
1282 }
1283 /* Make sure we only have %d or %u (or none) in the file name specified */
1284 char *pcPercent = (char*)strchr(pszRecordFilenameTemplate, '%');
1285 if (pcPercent != 0 && *(pcPercent + 1) != 'd' && *(pcPercent + 1) != 'u')
1286 {
1287 LogError("VBoxHeadless: ERROR: Only %%d and %%u are allowed in the recording file name.", -1);
1288 return 1;
1289 }
1290 /* And no more than one % in the name */
1291 if (pcPercent != 0 && strchr(pcPercent + 1, '%') != 0)
1292 {
1293 LogError("VBoxHeadless: ERROR: Only one format modifier is allowed in the recording file name.", -1);
1294 return 1;
1295 }
1296 RTStrPrintf(&szRecordFilename[0], RTPATH_MAX, pszRecordFilenameTemplate, RTProcSelf());
1297#endif /* defined VBOX_WITH_RECORDING */
1298
1299 if (!pcszNameOrUUID)
1300 {
1301 show_usage();
1302 return 1;
1303 }
1304
1305 HRESULT rc;
1306 int irc;
1307
1308 rc = com::Initialize();
1309#ifdef VBOX_WITH_XPCOM
1310 if (rc == NS_ERROR_FILE_ACCESS_DENIED)
1311 {
1312 char szHome[RTPATH_MAX] = "";
1313 com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome));
1314 RTPrintf("Failed to initialize COM because the global settings directory '%s' is not accessible!", szHome);
1315 return 1;
1316 }
1317#endif
1318 if (FAILED(rc))
1319 {
1320 RTPrintf("VBoxHeadless: ERROR: failed to initialize COM!\n");
1321 return 1;
1322 }
1323
1324 ComPtr<IVirtualBoxClient> pVirtualBoxClient;
1325 ComPtr<IVirtualBox> virtualBox;
1326 ComPtr<ISession> session;
1327 ComPtr<IMachine> machine;
1328 bool fSessionOpened = false;
1329 ComPtr<IEventListener> vboxClientListener;
1330 ComPtr<IEventListener> vboxListener;
1331 ComObjPtr<ConsoleEventListenerImpl> consoleListener;
1332
1333 do
1334 {
1335 rc = pVirtualBoxClient.createInprocObject(CLSID_VirtualBoxClient);
1336 if (FAILED(rc))
1337 {
1338 RTPrintf("VBoxHeadless: ERROR: failed to create the VirtualBoxClient object!\n");
1339 com::ErrorInfo info;
1340 if (!info.isFullAvailable() && !info.isBasicAvailable())
1341 {
1342 com::GluePrintRCMessage(rc);
1343 RTPrintf("Most likely, the VirtualBox COM server is not running or failed to start.\n");
1344 }
1345 else
1346 GluePrintErrorInfo(info);
1347 break;
1348 }
1349
1350 rc = pVirtualBoxClient->COMGETTER(VirtualBox)(virtualBox.asOutParam());
1351 if (FAILED(rc))
1352 {
1353 RTPrintf("Failed to get VirtualBox object (rc=%Rhrc)!\n", rc);
1354 break;
1355 }
1356 rc = pVirtualBoxClient->COMGETTER(Session)(session.asOutParam());
1357 if (FAILED(rc))
1358 {
1359 RTPrintf("Failed to get session object (rc=%Rhrc)!\n", rc);
1360 break;
1361 }
1362
1363 if (pcszSettingsPw)
1364 {
1365 CHECK_ERROR(virtualBox, SetSettingsSecret(Bstr(pcszSettingsPw).raw()));
1366 if (FAILED(rc))
1367 break;
1368 }
1369 else if (pcszSettingsPwFile)
1370 {
1371 int rcExit = settingsPasswordFile(virtualBox, pcszSettingsPwFile);
1372 if (rcExit != RTEXITCODE_SUCCESS)
1373 break;
1374 }
1375
1376 ComPtr<IMachine> m;
1377
1378 rc = virtualBox->FindMachine(Bstr(pcszNameOrUUID).raw(), m.asOutParam());
1379 if (FAILED(rc))
1380 {
1381 LogError("Invalid machine name or UUID!\n", rc);
1382 break;
1383 }
1384
1385 Bstr bstrVMId;
1386 rc = m->COMGETTER(Id)(bstrVMId.asOutParam());
1387 AssertComRC(rc);
1388 if (FAILED(rc))
1389 break;
1390 g_strVMUUID = bstrVMId;
1391
1392 Bstr bstrVMName;
1393 rc = m->COMGETTER(Name)(bstrVMName.asOutParam());
1394 AssertComRC(rc);
1395 if (FAILED(rc))
1396 break;
1397 g_strVMName = bstrVMName;
1398
1399 Log(("VBoxHeadless: Opening a session with machine (id={%s})...\n",
1400 g_strVMUUID.c_str()));
1401
1402 // set session name
1403 CHECK_ERROR_BREAK(session, COMSETTER(Name)(Bstr("headless").raw()));
1404 // open a session
1405 CHECK_ERROR_BREAK(m, LockMachine(session, LockType_VM));
1406 fSessionOpened = true;
1407
1408 /* get the console */
1409 ComPtr<IConsole> console;
1410 CHECK_ERROR_BREAK(session, COMGETTER(Console)(console.asOutParam()));
1411
1412 /* get the mutable machine */
1413 CHECK_ERROR_BREAK(console, COMGETTER(Machine)(machine.asOutParam()));
1414
1415 ComPtr<IDisplay> display;
1416 CHECK_ERROR_BREAK(console, COMGETTER(Display)(display.asOutParam()));
1417
1418#ifdef VBOX_WITH_RECORDING
1419 if (fRecordEnabled)
1420 {
1421 ComPtr<IRecordingSettings> recordingSettings;
1422 CHECK_ERROR_BREAK(machine, COMGETTER(RecordingSettings)(recordingSettings.asOutParam()));
1423 CHECK_ERROR_BREAK(recordingSettings, COMSETTER(Enabled)(TRUE));
1424
1425 SafeIfaceArray <IRecordingScreenSettings> saRecordScreenScreens;
1426 CHECK_ERROR_BREAK(recordingSettings, COMGETTER(Screens)(ComSafeArrayAsOutParam(saRecordScreenScreens)));
1427
1428 /* Note: For now all screens have the same configuration. */
1429 for (size_t i = 0; i < saRecordScreenScreens.size(); ++i)
1430 {
1431 CHECK_ERROR_BREAK(saRecordScreenScreens[i], COMSETTER(Enabled)(TRUE));
1432 CHECK_ERROR_BREAK(saRecordScreenScreens[i], COMSETTER(Filename)(Bstr(szRecordFilename).raw()));
1433 CHECK_ERROR_BREAK(saRecordScreenScreens[i], COMSETTER(VideoWidth)(ulRecordVideoWidth));
1434 CHECK_ERROR_BREAK(saRecordScreenScreens[i], COMSETTER(VideoHeight)(ulRecordVideoHeight));
1435 CHECK_ERROR_BREAK(saRecordScreenScreens[i], COMSETTER(VideoRate)(ulRecordVideoRate));
1436 }
1437 }
1438#endif /* defined(VBOX_WITH_RECORDING) */
1439
1440 /* get the machine debugger (isn't necessarily available) */
1441 ComPtr <IMachineDebugger> machineDebugger;
1442 console->COMGETTER(Debugger)(machineDebugger.asOutParam());
1443 if (machineDebugger)
1444 {
1445 Log(("Machine debugger available!\n"));
1446 }
1447
1448 if (fRawR0 != ~0U)
1449 {
1450 if (!machineDebugger)
1451 {
1452 RTPrintf("Error: No debugger object; -%srawr0 cannot be executed!\n", fRawR0 ? "" : "no");
1453 break;
1454 }
1455 machineDebugger->COMSETTER(RecompileSupervisor)(!fRawR0);
1456 }
1457 if (fRawR3 != ~0U)
1458 {
1459 if (!machineDebugger)
1460 {
1461 RTPrintf("Error: No debugger object; -%srawr3 cannot be executed!\n", fRawR3 ? "" : "no");
1462 break;
1463 }
1464 machineDebugger->COMSETTER(RecompileUser)(!fRawR3);
1465 }
1466 if (fPATM != ~0U)
1467 {
1468 if (!machineDebugger)
1469 {
1470 RTPrintf("Error: No debugger object; -%spatm cannot be executed!\n", fPATM ? "" : "no");
1471 break;
1472 }
1473 machineDebugger->COMSETTER(PATMEnabled)(fPATM);
1474 }
1475 if (fCSAM != ~0U)
1476 {
1477 if (!machineDebugger)
1478 {
1479 RTPrintf("Error: No debugger object; -%scsam cannot be executed!\n", fCSAM ? "" : "no");
1480 break;
1481 }
1482 machineDebugger->COMSETTER(CSAMEnabled)(fCSAM);
1483 }
1484
1485 /* initialize global references */
1486 gConsole = console;
1487 gEventQ = com::NativeEventQueue::getMainEventQueue();
1488
1489 /* VirtualBoxClient events registration. */
1490 {
1491 ComPtr<IEventSource> pES;
1492 CHECK_ERROR(pVirtualBoxClient, COMGETTER(EventSource)(pES.asOutParam()));
1493 ComObjPtr<VirtualBoxClientEventListenerImpl> listener;
1494 listener.createObject();
1495 listener->init(new VirtualBoxClientEventListener());
1496 vboxClientListener = listener;
1497 com::SafeArray<VBoxEventType_T> eventTypes;
1498 eventTypes.push_back(VBoxEventType_OnVBoxSVCAvailabilityChanged);
1499 CHECK_ERROR(pES, RegisterListener(vboxClientListener, ComSafeArrayAsInParam(eventTypes), true));
1500 }
1501
1502 /* Console events registration. */
1503 {
1504 ComPtr<IEventSource> es;
1505 CHECK_ERROR(console, COMGETTER(EventSource)(es.asOutParam()));
1506 consoleListener.createObject();
1507 consoleListener->init(new ConsoleEventListener());
1508 com::SafeArray<VBoxEventType_T> eventTypes;
1509 eventTypes.push_back(VBoxEventType_OnMouseCapabilityChanged);
1510 eventTypes.push_back(VBoxEventType_OnStateChanged);
1511 eventTypes.push_back(VBoxEventType_OnVRDEServerInfoChanged);
1512 eventTypes.push_back(VBoxEventType_OnCanShowWindow);
1513 eventTypes.push_back(VBoxEventType_OnShowWindow);
1514 eventTypes.push_back(VBoxEventType_OnGuestPropertyChanged);
1515 CHECK_ERROR(es, RegisterListener(consoleListener, ComSafeArrayAsInParam(eventTypes), true));
1516 }
1517
1518 /* Default is to use the VM setting for the VRDE server. */
1519 enum VRDEOption
1520 {
1521 VRDEOption_Config,
1522 VRDEOption_Off,
1523 VRDEOption_On
1524 };
1525 VRDEOption enmVRDEOption = VRDEOption_Config;
1526 BOOL fVRDEEnabled;
1527 ComPtr <IVRDEServer> vrdeServer;
1528 CHECK_ERROR_BREAK(machine, COMGETTER(VRDEServer)(vrdeServer.asOutParam()));
1529 CHECK_ERROR_BREAK(vrdeServer, COMGETTER(Enabled)(&fVRDEEnabled));
1530
1531 if (vrdeEnabled != NULL)
1532 {
1533 /* -vrde on|off|config */
1534 if (!strcmp(vrdeEnabled, "off") || !strcmp(vrdeEnabled, "disable"))
1535 enmVRDEOption = VRDEOption_Off;
1536 else if (!strcmp(vrdeEnabled, "on") || !strcmp(vrdeEnabled, "enable"))
1537 enmVRDEOption = VRDEOption_On;
1538 else if (strcmp(vrdeEnabled, "config"))
1539 {
1540 RTPrintf("-vrde requires an argument (on|off|config)\n");
1541 break;
1542 }
1543 }
1544
1545 Log(("VBoxHeadless: enmVRDE %d, fVRDEEnabled %d\n", enmVRDEOption, fVRDEEnabled));
1546
1547 if (enmVRDEOption != VRDEOption_Off)
1548 {
1549 /* Set other specified options. */
1550
1551 /* set VRDE port if requested by the user */
1552 if (vrdePort != NULL)
1553 {
1554 Bstr bstr = vrdePort;
1555 CHECK_ERROR_BREAK(vrdeServer, SetVRDEProperty(Bstr("TCP/Ports").raw(), bstr.raw()));
1556 }
1557 /* set VRDE address if requested by the user */
1558 if (vrdeAddress != NULL)
1559 {
1560 CHECK_ERROR_BREAK(vrdeServer, SetVRDEProperty(Bstr("TCP/Address").raw(), Bstr(vrdeAddress).raw()));
1561 }
1562
1563 /* Set VRDE properties. */
1564 if (cVRDEProperties > 0)
1565 {
1566 for (unsigned i = 0; i < cVRDEProperties; i++)
1567 {
1568 /* Parse 'name=value' */
1569 char *pszProperty = RTStrDup(aVRDEProperties[i]);
1570 if (pszProperty)
1571 {
1572 char *pDelimiter = strchr(pszProperty, '=');
1573 if (pDelimiter)
1574 {
1575 *pDelimiter = '\0';
1576
1577 Bstr bstrName = pszProperty;
1578 Bstr bstrValue = &pDelimiter[1];
1579 CHECK_ERROR_BREAK(vrdeServer, SetVRDEProperty(bstrName.raw(), bstrValue.raw()));
1580 }
1581 else
1582 {
1583 RTPrintf("Error: Invalid VRDE property '%s'\n", aVRDEProperties[i]);
1584 RTStrFree(pszProperty);
1585 rc = E_INVALIDARG;
1586 break;
1587 }
1588 RTStrFree(pszProperty);
1589 }
1590 else
1591 {
1592 RTPrintf("Error: Failed to allocate memory for VRDE property '%s'\n", aVRDEProperties[i]);
1593 rc = E_OUTOFMEMORY;
1594 break;
1595 }
1596 }
1597 if (FAILED(rc))
1598 break;
1599 }
1600
1601 }
1602
1603 if (enmVRDEOption == VRDEOption_On)
1604 {
1605 /* enable VRDE server (only if currently disabled) */
1606 if (!fVRDEEnabled)
1607 {
1608 CHECK_ERROR_BREAK(vrdeServer, COMSETTER(Enabled)(TRUE));
1609 }
1610 }
1611 else if (enmVRDEOption == VRDEOption_Off)
1612 {
1613 /* disable VRDE server (only if currently enabled */
1614 if (fVRDEEnabled)
1615 {
1616 CHECK_ERROR_BREAK(vrdeServer, COMSETTER(Enabled)(FALSE));
1617 }
1618 }
1619
1620 /* Disable the host clipboard before powering up */
1621 console->COMSETTER(UseHostClipboard)(false);
1622
1623 Log(("VBoxHeadless: Powering up the machine...\n"));
1624
1625
1626 /**
1627 * @todo We should probably install handlers earlier so that
1628 * we can undo any temporary settings we do above in case of
1629 * an early signal and use RAII to ensure proper cleanup.
1630 */
1631#if !defined(RT_OS_WINDOWS)
1632 signal(SIGPIPE, SIG_IGN);
1633 signal(SIGTTOU, SIG_IGN);
1634
1635 struct sigaction sa;
1636 RT_ZERO(sa);
1637 sa.sa_handler = HandleSignal;
1638 sigaction(SIGHUP, &sa, NULL);
1639 sigaction(SIGINT, &sa, NULL);
1640 sigaction(SIGTERM, &sa, NULL);
1641 sigaction(SIGUSR1, &sa, NULL);
1642 sigaction(SIGUSR2, &sa, NULL);
1643#else /* RT_OS_WINDOWS */
1644 /*
1645 * Register windows console signal handler to react to Ctrl-C,
1646 * Ctrl-Break, Close, non-interactive session termination.
1647 */
1648 ::SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
1649#endif
1650
1651
1652 ComPtr <IProgress> progress;
1653 if (!fPaused)
1654 CHECK_ERROR_BREAK(console, PowerUp(progress.asOutParam()));
1655 else
1656 CHECK_ERROR_BREAK(console, PowerUpPaused(progress.asOutParam()));
1657
1658 rc = showProgress(progress);
1659 if (FAILED(rc))
1660 {
1661 com::ProgressErrorInfo info(progress);
1662 if (info.isBasicAvailable())
1663 {
1664 RTPrintf("Error: failed to start machine. Error message: %ls\n", info.getText().raw());
1665 }
1666 else
1667 {
1668 RTPrintf("Error: failed to start machine. No error message available!\n");
1669 }
1670 break;
1671 }
1672
1673#ifdef RT_OS_WINDOWS
1674 /*
1675 * Spawn windows message pump to monitor session events.
1676 */
1677 RTTHREAD hThrMsg;
1678 irc = RTThreadCreate(&hThrMsg,
1679 windowsMessageMonitor, NULL,
1680 0, /* :cbStack */
1681 RTTHREADTYPE_MSG_PUMP, 0,
1682 "MSG");
1683 if (RT_FAILURE(irc)) /* not fatal */
1684 LogRel(("VBoxHeadless: failed to start windows message monitor: %Rrc\n", irc));
1685#endif /* RT_OS_WINDOWS */
1686
1687
1688 /*
1689 * Pump vbox events forever
1690 */
1691 LogRel(("VBoxHeadless: starting event loop\n"));
1692 for (;;)
1693 {
1694 irc = gEventQ->processEventQueue(RT_INDEFINITE_WAIT);
1695
1696 /*
1697 * interruptEventQueueProcessing from another thread is
1698 * reported as VERR_INTERRUPTED, so check the flag first.
1699 */
1700 if (g_fTerminateFE)
1701 {
1702 LogRel(("VBoxHeadless: processEventQueue: %Rrc, termination requested\n", irc));
1703 break;
1704 }
1705
1706 if (RT_FAILURE(irc))
1707 {
1708 LogRel(("VBoxHeadless: processEventQueue: %Rrc\n", irc));
1709 RTMsgError("event loop: %Rrc", irc);
1710 break;
1711 }
1712 }
1713
1714 Log(("VBoxHeadless: event loop has terminated...\n"));
1715
1716#ifdef VBOX_WITH_RECORDING
1717 if (fRecordEnabled)
1718 {
1719 if (!machine.isNull())
1720 {
1721 ComPtr<IRecordingSettings> recordingSettings;
1722 CHECK_ERROR_BREAK(machine, COMGETTER(RecordingSettings)(recordingSettings.asOutParam()));
1723 CHECK_ERROR_BREAK(recordingSettings, COMSETTER(Enabled)(FALSE));
1724 }
1725 }
1726#endif /* VBOX_WITH_RECORDING */
1727
1728 /* we don't have to disable VRDE here because we don't save the settings of the VM */
1729 }
1730 while (0);
1731
1732 /*
1733 * Get the machine state.
1734 */
1735 MachineState_T machineState = MachineState_Aborted;
1736 if (!machine.isNull())
1737 {
1738 rc = machine->COMGETTER(State)(&machineState);
1739 if (SUCCEEDED(rc))
1740 Log(("machine state = %RU32\n", machineState));
1741 else
1742 Log(("IMachine::getState: %Rhrc\n", rc));
1743 }
1744 else
1745 {
1746 Log(("machine == NULL\n"));
1747 }
1748
1749 /*
1750 * Turn off the VM if it's running
1751 */
1752 if ( gConsole
1753 && ( machineState == MachineState_Running
1754 || machineState == MachineState_Teleporting
1755 || machineState == MachineState_LiveSnapshotting
1756 /** @todo power off paused VMs too? */
1757 )
1758 )
1759 do
1760 {
1761 consoleListener->getWrapped()->ignorePowerOffEvents(true);
1762
1763 ComPtr<IProgress> pProgress;
1764 if (!machine.isNull())
1765 CHECK_ERROR_BREAK(machine, SaveState(pProgress.asOutParam()));
1766 else
1767 CHECK_ERROR_BREAK(gConsole, PowerDown(pProgress.asOutParam()));
1768
1769 rc = showProgress(pProgress);
1770 if (FAILED(rc))
1771 {
1772 com::ErrorInfo info;
1773 if (!info.isFullAvailable() && !info.isBasicAvailable())
1774 com::GluePrintRCMessage(rc);
1775 else
1776 com::GluePrintErrorInfo(info);
1777 break;
1778 }
1779 } while (0);
1780
1781 /* VirtualBox callback unregistration. */
1782 if (vboxListener)
1783 {
1784 ComPtr<IEventSource> es;
1785 CHECK_ERROR(virtualBox, COMGETTER(EventSource)(es.asOutParam()));
1786 if (!es.isNull())
1787 CHECK_ERROR(es, UnregisterListener(vboxListener));
1788 vboxListener.setNull();
1789 }
1790
1791 /* Console callback unregistration. */
1792 if (consoleListener)
1793 {
1794 ComPtr<IEventSource> es;
1795 CHECK_ERROR(gConsole, COMGETTER(EventSource)(es.asOutParam()));
1796 if (!es.isNull())
1797 CHECK_ERROR(es, UnregisterListener(consoleListener));
1798 consoleListener.setNull();
1799 }
1800
1801 /* VirtualBoxClient callback unregistration. */
1802 if (vboxClientListener)
1803 {
1804 ComPtr<IEventSource> pES;
1805 CHECK_ERROR(pVirtualBoxClient, COMGETTER(EventSource)(pES.asOutParam()));
1806 if (!pES.isNull())
1807 CHECK_ERROR(pES, UnregisterListener(vboxClientListener));
1808 vboxClientListener.setNull();
1809 }
1810
1811 /* No more access to the 'console' object, which will be uninitialized by the next session->Close call. */
1812 gConsole = NULL;
1813
1814 if (fSessionOpened)
1815 {
1816 /*
1817 * Close the session. This will also uninitialize the console and
1818 * unregister the callback we've registered before.
1819 */
1820 Log(("VBoxHeadless: Closing the session...\n"));
1821 session->UnlockMachine();
1822 }
1823
1824 /* Must be before com::Shutdown */
1825 session.setNull();
1826 virtualBox.setNull();
1827 pVirtualBoxClient.setNull();
1828 machine.setNull();
1829
1830 com::Shutdown();
1831
1832#ifdef RT_OS_WINDOWS
1833 /* tell the session monitor it can ack WM_ENDSESSION */
1834 if (g_hCanQuit != NIL_RTSEMEVENT)
1835 {
1836 RTSemEventSignal(g_hCanQuit);
1837 }
1838
1839 /* tell the session monitor to quit */
1840 if (g_hWindow != NULL)
1841 {
1842 ::PostMessage(g_hWindow, WM_QUIT, 0, 0);
1843 }
1844#endif
1845
1846 LogRel(("VBoxHeadless: exiting\n"));
1847 return FAILED(rc) ? 1 : 0;
1848}
1849
1850
1851#ifndef VBOX_WITH_HARDENING
1852/**
1853 * Main entry point.
1854 */
1855int main(int argc, char **argv, char **envp)
1856{
1857 // initialize VBox Runtime
1858 int rc = RTR3InitExe(argc, &argv, RTR3INIT_FLAGS_SUPLIB);
1859 if (RT_FAILURE(rc))
1860 {
1861 RTPrintf("VBoxHeadless: Runtime Error:\n"
1862 " %Rrc -- %Rrf\n", rc, rc);
1863 switch (rc)
1864 {
1865 case VERR_VM_DRIVER_NOT_INSTALLED:
1866 RTPrintf("Cannot access the kernel driver. Make sure the kernel module has been \n"
1867 "loaded successfully. Aborting ...\n");
1868 break;
1869 default:
1870 break;
1871 }
1872 return 1;
1873 }
1874
1875 return TrustedMain(argc, argv, envp);
1876}
1877#endif /* !VBOX_WITH_HARDENING */
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette