VirtualBox

source: vbox/trunk/src/VBox/Main/src-client/ConsoleImpl.cpp@ 107491

Last change on this file since 107491 was 107465, checked in by vboxsync, 13 days ago

Main/src-client/ConsoleImpl.cpp: Missing error check, bugref:3409

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 420.1 KB
Line 
1/* $Id: ConsoleImpl.cpp 107465 2025-01-07 12:32:38Z vboxsync $ */
2/** @file
3 * VBox Console COM Class implementation
4 */
5
6/*
7 * Copyright (C) 2005-2024 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28#define LOG_GROUP LOG_GROUP_MAIN_CONSOLE
29#include "LoggingNew.h"
30
31/** @todo Move the TAP mess back into the driver! */
32#if defined(RT_OS_WINDOWS)
33#elif defined(RT_OS_LINUX)
34# include <errno.h>
35# include <sys/ioctl.h>
36# include <sys/poll.h>
37# include <sys/fcntl.h>
38# include <sys/types.h>
39# include <sys/wait.h>
40# include <net/if.h>
41# include <linux/if_tun.h>
42# include <stdio.h>
43# include <stdlib.h>
44# include <string.h>
45#elif defined(RT_OS_FREEBSD)
46# include <errno.h>
47# include <sys/ioctl.h>
48# include <sys/poll.h>
49# include <sys/fcntl.h>
50# include <sys/types.h>
51# include <sys/wait.h>
52# include <stdio.h>
53# include <stdlib.h>
54# include <string.h>
55#elif defined(RT_OS_SOLARIS)
56# include <iprt/coredumper.h>
57#endif
58
59#include "ConsoleImpl.h"
60
61#include "Global.h"
62#include "VirtualBoxErrorInfoImpl.h"
63#include "GuestImpl.h"
64#include "KeyboardImpl.h"
65#include "MouseImpl.h"
66#include "DisplayImpl.h"
67#include "MachineDebuggerImpl.h"
68#include "USBDeviceImpl.h"
69#include "RemoteUSBDeviceImpl.h"
70#include "ConsoleSharedFolderImpl.h"
71#ifdef VBOX_WITH_AUDIO_VRDE
72# include "DrvAudioVRDE.h"
73#endif
74#ifdef VBOX_WITH_AUDIO_RECORDING
75# include "DrvAudioRec.h"
76#endif
77#ifdef VBOX_WITH_USB_CARDREADER
78# include "UsbCardReader.h"
79#endif
80#include "PlatformPropertiesImpl.h"
81#include "ProgressImpl.h"
82#include "ConsoleVRDPServer.h"
83#include "VMMDev.h"
84#ifdef VBOX_WITH_EXTPACK
85# include "ExtPackManagerImpl.h"
86#endif
87#include "BusAssignmentManager.h"
88#include "PCIDeviceAttachmentImpl.h"
89#include "EmulatedUSBImpl.h"
90#include "NvramStoreImpl.h"
91#ifdef VBOX_WITH_VIRT_ARMV8
92# include "ResourceStoreImpl.h"
93#endif
94#ifdef VBOX_WITH_SHARED_CLIPBOARD
95# include "GuestShClPrivate.h"
96#endif
97#include "StringifyEnums.h"
98
99#include "VBoxEvents.h"
100#include "AutoCaller.h"
101#include "ThreadTask.h"
102
103#ifdef VBOX_WITH_RECORDING
104# include "Recording.h"
105#endif
106
107#include "CryptoUtils.h"
108
109#include <VBox/com/array.h>
110#include "VBox/com/ErrorInfo.h"
111#include <VBox/com/listeners.h>
112
113#include <iprt/asm.h>
114#include <iprt/buildconfig.h>
115#include <iprt/cpp/utils.h>
116#include <iprt/dir.h>
117#include <iprt/file.h>
118#include <iprt/ldr.h>
119#include <iprt/path.h>
120#include <iprt/process.h>
121#include <iprt/string.h>
122#include <iprt/system.h>
123#include <iprt/base64.h>
124#include <iprt/memsafer.h>
125
126#include <VBox/vmm/vmmr3vtable.h>
127#include <VBox/vmm/vmapi.h>
128#include <VBox/vmm/vmm.h>
129#include <VBox/vmm/pdmapi.h>
130#include <VBox/vmm/pdmaudioifs.h>
131#include <VBox/vmm/pdmasynccompletion.h>
132#include <VBox/vmm/pdmnetifs.h>
133#include <VBox/vmm/pdmstorageifs.h>
134#ifdef VBOX_WITH_USB
135# include <VBox/vmm/pdmusb.h>
136#endif
137#ifdef VBOX_WITH_NETSHAPER
138# include <VBox/vmm/pdmnetshaper.h>
139#endif /* VBOX_WITH_NETSHAPER */
140#include <VBox/vmm/mm.h>
141#include <VBox/vmm/ssm.h>
142#include <VBox/err.h>
143#include <VBox/param.h>
144#include <VBox/vusb.h>
145
146#include <VBox/VMMDev.h>
147
148#ifdef VBOX_WITH_SHARED_CLIPBOARD
149# include <VBox/HostServices/VBoxClipboardSvc.h>
150#endif
151#include <VBox/HostServices/DragAndDropSvc.h>
152#ifdef VBOX_WITH_GUEST_PROPS
153# include <VBox/HostServices/GuestPropertySvc.h>
154# include <VBox/com/array.h>
155#endif
156
157#ifdef VBOX_OPENSSL_FIPS
158# include <openssl/crypto.h>
159#endif
160
161#include <set>
162#include <algorithm>
163#include <memory> // for auto_ptr
164#include <vector>
165#include <exception>// std::exception
166
167// VMTask and friends
168////////////////////////////////////////////////////////////////////////////////
169
170/**
171 * Task structure for asynchronous VM operations.
172 *
173 * Once created, the task structure adds itself as a Console caller. This means:
174 *
175 * 1. The user must check for #hrc() before using the created structure
176 * (e.g. passing it as a thread function argument). If #hrc() returns a
177 * failure, the Console object may not be used by the task.
178 * 2. On successful initialization, the structure keeps the Console caller
179 * until destruction (to ensure Console remains in the Ready state and won't
180 * be accidentally uninitialized). Forgetting to delete the created task
181 * will lead to Console::uninit() stuck waiting for releasing all added
182 * callers.
183 *
184 * If \a aUsesVMPtr parameter is true, the task structure will also add itself
185 * as a Console::mpUVM caller with the same meaning as above. See
186 * Console::addVMCaller() for more info.
187 */
188class VMTask: public ThreadTask
189{
190public:
191 VMTask(Console *aConsole,
192 Progress *aProgress,
193 const ComPtr<IProgress> &aServerProgress,
194 bool aUsesVMPtr)
195 : ThreadTask("GenericVMTask"),
196 mConsole(aConsole),
197 mConsoleCaller(aConsole),
198 mProgress(aProgress),
199 mServerProgress(aServerProgress),
200 mRC(E_FAIL),
201 mpSafeVMPtr(NULL)
202 {
203 AssertReturnVoid(aConsole);
204 mRC = mConsoleCaller.hrc();
205 if (FAILED(mRC))
206 return;
207 if (aUsesVMPtr)
208 {
209 mpSafeVMPtr = new Console::SafeVMPtr(aConsole);
210 if (!mpSafeVMPtr->isOk())
211 mRC = mpSafeVMPtr->hrc();
212 }
213 }
214
215 virtual ~VMTask()
216 {
217 releaseVMCaller();
218 }
219
220 HRESULT hrc() const { return mRC; }
221 bool isOk() const { return SUCCEEDED(hrc()); }
222
223 /** Releases the VM caller before destruction. Not normally necessary. */
224 void releaseVMCaller()
225 {
226 if (mpSafeVMPtr)
227 {
228 delete mpSafeVMPtr;
229 mpSafeVMPtr = NULL;
230 }
231 }
232
233 const ComObjPtr<Console> mConsole;
234 AutoCaller mConsoleCaller;
235 const ComObjPtr<Progress> mProgress;
236 Utf8Str mErrorMsg;
237 const ComPtr<IProgress> mServerProgress;
238
239private:
240 HRESULT mRC;
241 Console::SafeVMPtr *mpSafeVMPtr;
242};
243
244
245class VMPowerUpTask : public VMTask
246{
247public:
248 VMPowerUpTask(Console *aConsole,
249 Progress *aProgress)
250 : VMTask(aConsole, aProgress, NULL /* aServerProgress */, false /* aUsesVMPtr */)
251 , mpfnConfigConstructor(NULL)
252 , mStartPaused(false)
253 , mTeleporterEnabled(FALSE)
254 , m_pKeyStore(NULL)
255 {
256 m_strTaskName = "VMPwrUp";
257 }
258
259 PFNCFGMCONSTRUCTOR mpfnConfigConstructor;
260 Utf8Str mSavedStateFile;
261 Utf8Str mKeyStore;
262 Utf8Str mKeyId;
263 Console::SharedFolderDataMap mSharedFolders;
264 bool mStartPaused;
265 BOOL mTeleporterEnabled;
266 SecretKeyStore *m_pKeyStore;
267
268 /* array of progress objects for hard disk reset operations */
269 typedef std::list<ComPtr<IProgress> > ProgressList;
270 ProgressList hardDiskProgresses;
271
272 void handler()
273 {
274 Console::i_powerUpThreadTask(this);
275 }
276
277};
278
279class VMPowerDownTask : public VMTask
280{
281public:
282 VMPowerDownTask(Console *aConsole,
283 const ComPtr<IProgress> &aServerProgress)
284 : VMTask(aConsole, NULL /* aProgress */, aServerProgress,
285 true /* aUsesVMPtr */)
286 {
287 m_strTaskName = "VMPwrDwn";
288 }
289
290 void handler()
291 {
292 Console::i_powerDownThreadTask(this);
293 }
294};
295
296// Handler for global events
297////////////////////////////////////////////////////////////////////////////////
298inline static const char *networkAdapterTypeToName(NetworkAdapterType_T adapterType);
299
300class VmEventListener
301{
302public:
303 VmEventListener()
304 {}
305
306
307 HRESULT init(Console *aConsole)
308 {
309 mConsole = aConsole;
310 return S_OK;
311 }
312
313 void uninit()
314 {
315 }
316
317 virtual ~VmEventListener()
318 {
319 }
320
321 STDMETHOD(HandleEvent)(VBoxEventType_T aType, IEvent *aEvent)
322 {
323 switch(aType)
324 {
325 case VBoxEventType_OnNATRedirect:
326 {
327 ComPtr<IMachine> pMachine = mConsole->i_machine();
328 ComPtr<INATRedirectEvent> pNREv = aEvent;
329 Assert(pNREv);
330
331 Bstr id;
332 HRESULT hrc = pNREv->COMGETTER(MachineId)(id.asOutParam());
333 AssertComRC(hrc);
334 if (id != mConsole->i_getId())
335 break;
336
337 /* now we can operate with redirects */
338 NATProtocol_T proto = (NATProtocol_T)0;
339 pNREv->COMGETTER(Proto)(&proto);
340 BOOL fRemove;
341 pNREv->COMGETTER(Remove)(&fRemove);
342 Bstr hostIp;
343 pNREv->COMGETTER(HostIP)(hostIp.asOutParam());
344 LONG hostPort = 0;
345 pNREv->COMGETTER(HostPort)(&hostPort);
346 Bstr guestIp;
347 pNREv->COMGETTER(GuestIP)(guestIp.asOutParam());
348 LONG guestPort = 0;
349 pNREv->COMGETTER(GuestPort)(&guestPort);
350 ULONG ulSlot;
351 hrc = pNREv->COMGETTER(Slot)(&ulSlot);
352 AssertComRCBreak(hrc, RT_NOTHING);
353 mConsole->i_onNATRedirectRuleChanged(ulSlot, fRemove, proto, hostIp.raw(), hostPort, guestIp.raw(), guestPort);
354 break;
355 }
356
357 case VBoxEventType_OnHostNameResolutionConfigurationChange:
358 {
359 mConsole->i_onNATDnsChanged();
360 break;
361 }
362
363 case VBoxEventType_OnHostPCIDevicePlug:
364 {
365 // handle if needed
366 break;
367 }
368
369 case VBoxEventType_OnExtraDataChanged:
370 {
371 ComPtr<IExtraDataChangedEvent> pEDCEv = aEvent;
372 Bstr strMachineId;
373 HRESULT hrc = pEDCEv->COMGETTER(MachineId)(strMachineId.asOutParam());
374 if (FAILED(hrc)) break;
375
376 Bstr strKey;
377 hrc = pEDCEv->COMGETTER(Key)(strKey.asOutParam());
378 if (FAILED(hrc)) break;
379
380 Bstr strVal;
381 hrc = pEDCEv->COMGETTER(Value)(strVal.asOutParam());
382 if (FAILED(hrc)) break;
383
384 mConsole->i_onExtraDataChange(strMachineId.raw(), strKey.raw(), strVal.raw());
385 break;
386 }
387
388 default:
389 AssertFailed();
390 }
391
392 return S_OK;
393 }
394private:
395 ComObjPtr<Console> mConsole;
396};
397
398typedef ListenerImpl<VmEventListener, Console*> VmEventListenerImpl;
399
400
401VBOX_LISTENER_DECLARE(VmEventListenerImpl)
402
403
404// constructor / destructor
405/////////////////////////////////////////////////////////////////////////////
406
407Console::Console()
408 : mSavedStateDataLoaded(false)
409 , mConsoleVRDPServer(NULL)
410 , mfVRDEChangeInProcess(false)
411 , mfVRDEChangePending(false)
412 , mhModVMM(NIL_RTLDRMOD)
413 , mpVMM(NULL)
414 , mpUVM(NULL)
415 , mVMCallers(0)
416 , mVMZeroCallersSem(NIL_RTSEMEVENT)
417 , mVMDestroying(false)
418 , mVMPoweredOff(false)
419 , mVMIsAlreadyPoweringOff(false)
420 , mfSnapshotFolderSizeWarningShown(false)
421 , mfSnapshotFolderExt4WarningShown(false)
422 , mfSnapshotFolderDiskTypeShown(false)
423 , mfVMHasUsbController(false)
424 , mfTurnResetIntoPowerOff(false)
425 , mfPowerOffCausedByReset(false)
426 , mpVmm2UserMethods(NULL)
427 , m_pVMMDev(NULL)
428 , mAudioVRDE(NULL)
429#ifdef VBOX_WITH_USB_CARDREADER
430 , mUsbCardReader(NULL)
431#endif
432 , mBusMgr(NULL)
433 , mLedLock(LOCKCLASS_LISTOFOTHEROBJECTS /* must be higher than LOCKCLASS_OTHEROBJECT */, "LedLock")
434 , muLedGen(0)
435 , muLedTypeGen(0)
436 , mcLedSets(0)
437 , m_pKeyStore(NULL)
438 , mpIfSecKey(NULL)
439 , mpIfSecKeyHlp(NULL)
440 , mVMStateChangeCallbackDisabled(false)
441 , mfUseHostClipboard(true)
442 , mMachineState(MachineState_PoweredOff)
443 , mhLdrModCrypto(NIL_RTLDRMOD)
444 , mcRefsCrypto(0)
445 , mpCryptoIf(NULL)
446{
447 RT_ZERO(maLedSets);
448 RT_ZERO(maLedTypes);
449}
450
451Console::~Console()
452{}
453
454HRESULT Console::FinalConstruct()
455{
456 LogFlowThisFunc(("\n"));
457
458 MYVMM2USERMETHODS *pVmm2UserMethods = (MYVMM2USERMETHODS *)RTMemAllocZ(sizeof(*mpVmm2UserMethods) + sizeof(Console *));
459 if (!pVmm2UserMethods)
460 return E_OUTOFMEMORY;
461 pVmm2UserMethods->u32Magic = VMM2USERMETHODS_MAGIC;
462 pVmm2UserMethods->u32Version = VMM2USERMETHODS_VERSION;
463 pVmm2UserMethods->pfnSaveState = Console::i_vmm2User_SaveState;
464 pVmm2UserMethods->pfnNotifyEmtInit = Console::i_vmm2User_NotifyEmtInit;
465 pVmm2UserMethods->pfnNotifyEmtTerm = Console::i_vmm2User_NotifyEmtTerm;
466 pVmm2UserMethods->pfnNotifyPdmtInit = Console::i_vmm2User_NotifyPdmtInit;
467 pVmm2UserMethods->pfnNotifyPdmtTerm = Console::i_vmm2User_NotifyPdmtTerm;
468 pVmm2UserMethods->pfnNotifyResetTurnedIntoPowerOff = Console::i_vmm2User_NotifyResetTurnedIntoPowerOff;
469 pVmm2UserMethods->pfnQueryGenericObject = Console::i_vmm2User_QueryGenericObject;
470 pVmm2UserMethods->u32EndMagic = VMM2USERMETHODS_MAGIC;
471 pVmm2UserMethods->pConsole = this;
472 mpVmm2UserMethods = pVmm2UserMethods;
473
474 MYPDMISECKEY *pIfSecKey = (MYPDMISECKEY *)RTMemAllocZ(sizeof(*mpIfSecKey) + sizeof(Console *));
475 if (!pIfSecKey)
476 return E_OUTOFMEMORY;
477 pIfSecKey->pfnKeyRetain = Console::i_pdmIfSecKey_KeyRetain;
478 pIfSecKey->pfnKeyRelease = Console::i_pdmIfSecKey_KeyRelease;
479 pIfSecKey->pfnPasswordRetain = Console::i_pdmIfSecKey_PasswordRetain;
480 pIfSecKey->pfnPasswordRelease = Console::i_pdmIfSecKey_PasswordRelease;
481 pIfSecKey->pConsole = this;
482 mpIfSecKey = pIfSecKey;
483
484 MYPDMISECKEYHLP *pIfSecKeyHlp = (MYPDMISECKEYHLP *)RTMemAllocZ(sizeof(*mpIfSecKeyHlp) + sizeof(Console *));
485 if (!pIfSecKeyHlp)
486 return E_OUTOFMEMORY;
487 pIfSecKeyHlp->pfnKeyMissingNotify = Console::i_pdmIfSecKeyHlp_KeyMissingNotify;
488 pIfSecKeyHlp->pConsole = this;
489 mpIfSecKeyHlp = pIfSecKeyHlp;
490
491#ifdef VBOX_WITH_USB
492 mRemoteUsbIf.pvUser = this;
493 mRemoteUsbIf.pfnQueryRemoteUsbBackend = Console::i_usbQueryRemoteUsbBackend;
494#endif
495
496 return BaseFinalConstruct();
497}
498
499void Console::FinalRelease()
500{
501 LogFlowThisFunc(("\n"));
502
503 uninit();
504
505 BaseFinalRelease();
506}
507
508// public initializer/uninitializer for internal purposes only
509/////////////////////////////////////////////////////////////////////////////
510
511/** @todo r=bird: aLockType is always LockType_VM. */
512HRESULT Console::initWithMachine(IMachine *aMachine, IInternalMachineControl *aControl, LockType_T aLockType)
513{
514 AssertReturn(aMachine && aControl, E_INVALIDARG);
515
516 /* Enclose the state transition NotReady->InInit->Ready */
517 AutoInitSpan autoInitSpan(this);
518 AssertReturn(autoInitSpan.isOk(), E_FAIL);
519
520 LogFlowThisFuncEnter();
521 LogFlowThisFunc(("aMachine=%p, aControl=%p\n", aMachine, aControl));
522
523 unconst(mMachine) = aMachine;
524 unconst(mControl) = aControl;
525
526 /* Cache essential properties and objects, and create child objects */
527
528 HRESULT hrc = mMachine->COMGETTER(State)(&mMachineState);
529 AssertComRCReturnRC(hrc);
530
531 hrc = mMachine->COMGETTER(Id)(mstrUuid.asOutParam());
532 AssertComRCReturnRC(hrc);
533
534#ifdef VBOX_WITH_EXTPACK
535 unconst(mptrExtPackManager).createObject();
536 hrc = mptrExtPackManager->initExtPackManager(NULL, VBOXEXTPACKCTX_VM_PROCESS);
537 AssertComRCReturnRC(hrc);
538#endif
539
540 // Event source may be needed by other children
541 unconst(mEventSource).createObject();
542 hrc = mEventSource->init();
543 AssertComRCReturnRC(hrc);
544
545 mcAudioRefs = 0;
546 mcVRDPClients = 0;
547 mu32SingleRDPClientId = 0;
548 mcGuestCredentialsProvided = false;
549
550 ComPtr<IPlatform> pPlatform;
551 hrc = mMachine->COMGETTER(Platform)(pPlatform.asOutParam());
552 AssertComRCReturnRC(hrc);
553
554 PlatformArchitecture_T platformArch;
555 hrc = pPlatform->COMGETTER(Architecture)(&platformArch);
556 AssertComRCReturnRC(hrc);
557
558 /* Now the VM specific parts */
559 /** @todo r=bird: aLockType is always LockType_VM. */
560 if (aLockType == LockType_VM)
561 {
562 const char *pszVMM = NULL; /* Shut up MSVC. */
563
564 switch (platformArch)
565 {
566 case PlatformArchitecture_x86:
567#if !defined(RT_ARCH_AMD64) && !defined(VBOX_WITH_X86_ON_ARM_ENABLED)
568 {
569 ComPtr<IVirtualBox> pVirtualBox;
570 hrc = mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
571 if (SUCCEEDED(hrc))
572 {
573 Bstr bstrEnableX86OnArm;
574 hrc = pVirtualBox->GetExtraData(Bstr("VBoxInternal2/EnableX86OnArm").raw(), bstrEnableX86OnArm.asOutParam());
575 if (FAILED(hrc) || !bstrEnableX86OnArm.equals("1"))
576 {
577 hrc = setError(VBOX_E_PLATFORM_ARCH_NOT_SUPPORTED,
578 tr("Cannot run the machine because its platform architecture %s is not supported on %s"),
579 Global::stringifyPlatformArchitecture(platformArch),
580 Global::stringifyPlatformArchitecture(PlatformArchitecture_ARM));
581 break;
582 }
583 }
584 }
585#endif
586 pszVMM = "VBoxVMM";
587 break;
588#ifdef VBOX_WITH_VIRT_ARMV8
589 case PlatformArchitecture_ARM:
590 pszVMM = "VBoxVMMArm";
591 break;
592#endif
593 default:
594 hrc = VBOX_E_PLATFORM_ARCH_NOT_SUPPORTED;
595 break;
596 }
597
598 if (FAILED(hrc))
599 return hrc;
600
601 /* Load the VMM. We won't continue without it being successfully loaded here. */
602 hrc = i_loadVMM(pszVMM);
603 AssertComRCReturnRC(hrc);
604
605#ifdef VBOX_WITH_VIRT_ARMV8
606 unconst(mptrResourceStore).createObject();
607 hrc = mptrResourceStore->init(this);
608 AssertComRCReturnRC(hrc);
609#endif
610 hrc = mMachine->COMGETTER(VRDEServer)(unconst(mVRDEServer).asOutParam());
611 AssertComRCReturnRC(hrc);
612
613 unconst(mGuest).createObject();
614 hrc = mGuest->init(this);
615 AssertComRCReturnRC(hrc);
616
617 ULONG cCpus = 1;
618 hrc = mMachine->COMGETTER(CPUCount)(&cCpus);
619 AssertComRCReturnRC(hrc);
620 mGuest->i_setCpuCount(cCpus);
621
622 unconst(mKeyboard).createObject();
623 hrc = mKeyboard->init(this);
624 AssertComRCReturnRC(hrc);
625
626 unconst(mMouse).createObject();
627 hrc = mMouse->init(this);
628 AssertComRCReturnRC(hrc);
629
630 unconst(mDisplay).createObject();
631 hrc = mDisplay->init(this);
632 AssertComRCReturnRC(hrc);
633
634 unconst(mVRDEServerInfo).createObject();
635 hrc = mVRDEServerInfo->init(this);
636 AssertComRCReturnRC(hrc);
637
638 unconst(mEmulatedUSB).createObject();
639 hrc = mEmulatedUSB->init(this);
640 AssertComRCReturnRC(hrc);
641
642 /* Init the NVRAM store. */
643 ComPtr<INvramStore> pNvramStore;
644 hrc = aMachine->COMGETTER(NonVolatileStore)(pNvramStore.asOutParam());
645 AssertComRCReturnRC(hrc);
646
647 Bstr strNonVolatilePath;
648 pNvramStore->COMGETTER(NonVolatileStorageFile)(strNonVolatilePath.asOutParam());
649
650 unconst(mptrNvramStore).createObject();
651 hrc = mptrNvramStore->init(this, strNonVolatilePath);
652 AssertComRCReturnRC(hrc);
653
654#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
655 Bstr bstrNvramKeyId;
656 Bstr bstrNvramKeyStore;
657 hrc = pNvramStore->COMGETTER(KeyId)(bstrNvramKeyId.asOutParam());
658 AssertComRCReturnRC(hrc);
659 hrc = pNvramStore->COMGETTER(KeyStore)(bstrNvramKeyStore.asOutParam());
660 AssertComRCReturnRC(hrc);
661 const Utf8Str strNvramKeyId(bstrNvramKeyId);
662 const Utf8Str strNvramKeyStore(bstrNvramKeyStore);
663 mptrNvramStore->i_updateEncryptionSettings(strNvramKeyId, strNvramKeyStore);
664#endif
665
666 /* Grab global and machine shared folder lists */
667
668 hrc = i_fetchSharedFolders(true /* aGlobal */);
669 AssertComRCReturnRC(hrc);
670 hrc = i_fetchSharedFolders(false /* aGlobal */);
671 AssertComRCReturnRC(hrc);
672
673 /* Create other child objects */
674
675 unconst(mConsoleVRDPServer) = new ConsoleVRDPServer(this);
676 AssertReturn(mConsoleVRDPServer, E_FAIL);
677
678 /* Figure out size of meAttachmentType vector */
679 ComPtr<IVirtualBox> pVirtualBox;
680 hrc = aMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
681 AssertComRC(hrc);
682
683 ComPtr<ISystemProperties> pSystemProperties;
684 ComPtr<IPlatformProperties> pPlatformProperties;
685 if (pVirtualBox)
686 {
687 hrc = pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
688 AssertComRC(hrc);
689 hrc = pVirtualBox->GetPlatformProperties(platformArch, pPlatformProperties.asOutParam());
690 AssertComRC(hrc);
691 }
692
693 ChipsetType_T chipsetType = ChipsetType_PIIX3;
694 pPlatform->COMGETTER(ChipsetType)(&chipsetType);
695 ULONG maxNetworkAdapters = 0;
696 if (pPlatformProperties)
697 pPlatformProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters);
698 meAttachmentType.resize(maxNetworkAdapters);
699 for (ULONG slot = 0; slot < maxNetworkAdapters; ++slot)
700 meAttachmentType[slot] = NetworkAttachmentType_Null;
701
702#ifdef VBOX_WITH_AUDIO_VRDE
703 unconst(mAudioVRDE) = new AudioVRDE(this);
704 AssertReturn(mAudioVRDE, E_FAIL);
705#endif
706#ifdef VBOX_WITH_AUDIO_RECORDING
707 unconst(mRecording.mAudioRec) = new AudioVideoRec(this);
708 AssertReturn(mRecording.mAudioRec, E_FAIL);
709#endif
710
711#ifdef VBOX_WITH_USB_CARDREADER
712 unconst(mUsbCardReader) = new UsbCardReader(this);
713 AssertReturn(mUsbCardReader, E_FAIL);
714#endif
715
716 m_cDisksPwProvided = 0;
717 m_cDisksEncrypted = 0;
718
719 unconst(m_pKeyStore) = new SecretKeyStore(true /* fKeyBufNonPageable */);
720 AssertReturn(m_pKeyStore, E_FAIL);
721
722 /* VirtualBox events registration. */
723 {
724 ComPtr<IEventSource> pES;
725 hrc = pVirtualBox->COMGETTER(EventSource)(pES.asOutParam());
726 AssertComRC(hrc);
727 ComObjPtr<VmEventListenerImpl> aVmListener;
728 aVmListener.createObject();
729 aVmListener->init(new VmEventListener(), this);
730 mVmListener = aVmListener;
731 com::SafeArray<VBoxEventType_T> eventTypes;
732 eventTypes.push_back(VBoxEventType_OnNATRedirect);
733 eventTypes.push_back(VBoxEventType_OnHostNameResolutionConfigurationChange);
734 eventTypes.push_back(VBoxEventType_OnHostPCIDevicePlug);
735 eventTypes.push_back(VBoxEventType_OnExtraDataChanged);
736 hrc = pES->RegisterListener(aVmListener, ComSafeArrayAsInParam(eventTypes), true);
737 AssertComRC(hrc);
738 }
739 }
740
741 /* Confirm a successful initialization when it's the case */
742 autoInitSpan.setSucceeded();
743
744#ifdef VBOX_WITH_EXTPACK
745 /* Let the extension packs have a go at things (hold no locks). */
746 if (SUCCEEDED(hrc))
747 mptrExtPackManager->i_callAllConsoleReadyHooks(this);
748#endif
749
750 LogFlowThisFuncLeave();
751
752 return S_OK;
753}
754
755/**
756 * Uninitializes the Console object.
757 */
758void Console::uninit()
759{
760 LogFlowThisFuncEnter();
761
762 /* Enclose the state transition Ready->InUninit->NotReady */
763 AutoUninitSpan autoUninitSpan(this);
764 if (autoUninitSpan.uninitDone())
765 {
766 LogFlowThisFunc(("Already uninitialized.\n"));
767 LogFlowThisFuncLeave();
768 return;
769 }
770
771 LogFlowThisFunc(("initFailed()=%d\n", autoUninitSpan.initFailed()));
772 if (mVmListener)
773 {
774 ComPtr<IEventSource> pES;
775 ComPtr<IVirtualBox> pVirtualBox;
776 HRESULT hrc = mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
777 AssertComRC(hrc);
778 if (SUCCEEDED(hrc) && !pVirtualBox.isNull())
779 {
780 hrc = pVirtualBox->COMGETTER(EventSource)(pES.asOutParam());
781 AssertComRC(hrc);
782 if (!pES.isNull())
783 {
784 hrc = pES->UnregisterListener(mVmListener);
785 AssertComRC(hrc);
786 }
787 }
788 mVmListener.setNull();
789 }
790
791 /* power down the VM if necessary */
792 if (mpUVM)
793 {
794 i_powerDown();
795 Assert(mpUVM == NULL);
796 }
797
798 if (mVMZeroCallersSem != NIL_RTSEMEVENT)
799 {
800 RTSemEventDestroy(mVMZeroCallersSem);
801 mVMZeroCallersSem = NIL_RTSEMEVENT;
802 }
803
804 if (mpVmm2UserMethods)
805 {
806 RTMemFree((void *)mpVmm2UserMethods);
807 mpVmm2UserMethods = NULL;
808 }
809
810 if (mpIfSecKey)
811 {
812 RTMemFree((void *)mpIfSecKey);
813 mpIfSecKey = NULL;
814 }
815
816 if (mpIfSecKeyHlp)
817 {
818 RTMemFree((void *)mpIfSecKeyHlp);
819 mpIfSecKeyHlp = NULL;
820 }
821
822#ifdef VBOX_WITH_USB_CARDREADER
823 if (mUsbCardReader)
824 {
825 delete mUsbCardReader;
826 unconst(mUsbCardReader) = NULL;
827 }
828#endif
829
830#ifdef VBOX_WITH_AUDIO_VRDE
831 if (mAudioVRDE)
832 {
833 delete mAudioVRDE;
834 unconst(mAudioVRDE) = NULL;
835 }
836#endif
837
838#ifdef VBOX_WITH_RECORDING
839 i_recordingDestroy();
840# ifdef VBOX_WITH_AUDIO_RECORDING
841 if (mRecording.mAudioRec)
842 {
843 delete mRecording.mAudioRec;
844 unconst(mRecording.mAudioRec) = NULL;
845 }
846# endif
847#endif /* VBOX_WITH_RECORDING */
848
849 // if the VM had a VMMDev with an HGCM thread, then remove that here
850 if (m_pVMMDev)
851 {
852 delete m_pVMMDev;
853 unconst(m_pVMMDev) = NULL;
854 }
855
856 if (mBusMgr)
857 {
858 mBusMgr->Release();
859 mBusMgr = NULL;
860 }
861
862 if (m_pKeyStore)
863 {
864 delete m_pKeyStore;
865 unconst(m_pKeyStore) = NULL;
866 }
867
868 m_mapGlobalSharedFolders.clear();
869 m_mapMachineSharedFolders.clear();
870 m_mapSharedFolders.clear(); // console instances
871
872 mRemoteUSBDevices.clear();
873 mUSBDevices.clear();
874
875 if (mVRDEServerInfo)
876 {
877 mVRDEServerInfo->uninit();
878 unconst(mVRDEServerInfo).setNull();
879 }
880
881 if (mEmulatedUSB)
882 {
883 mEmulatedUSB->uninit();
884 unconst(mEmulatedUSB).setNull();
885 }
886
887 if (mDebugger)
888 {
889 mDebugger->uninit();
890 unconst(mDebugger).setNull();
891 }
892
893 if (mDisplay)
894 {
895 mDisplay->uninit();
896 unconst(mDisplay).setNull();
897 }
898
899 if (mMouse)
900 {
901 mMouse->uninit();
902 unconst(mMouse).setNull();
903 }
904
905 if (mKeyboard)
906 {
907 mKeyboard->uninit();
908 unconst(mKeyboard).setNull();
909 }
910
911 if (mGuest)
912 {
913 mGuest->uninit();
914 unconst(mGuest).setNull();
915 }
916
917 if (mConsoleVRDPServer)
918 {
919 delete mConsoleVRDPServer;
920 unconst(mConsoleVRDPServer) = NULL;
921 }
922
923 if (mptrNvramStore)
924 {
925 mptrNvramStore->uninit();
926 unconst(mptrNvramStore).setNull();
927 }
928
929 unconst(mVRDEServer).setNull();
930
931#ifdef VBOX_WITH_VIRT_ARMV8
932 if (mptrResourceStore)
933 {
934 mptrResourceStore->uninit();
935 unconst(mptrResourceStore).setNull();
936 }
937#endif
938
939 unconst(mControl).setNull();
940 unconst(mMachine).setNull();
941
942 // we don't perform uninit() as it's possible that some pending event refers to this source
943 unconst(mEventSource).setNull();
944
945#ifdef VBOX_WITH_EXTPACK
946 unconst(mptrExtPackManager).setNull();
947#endif
948
949 /* Unload the VMM. */
950 mpVMM = NULL;
951 if (mhModVMM != NIL_RTLDRMOD)
952 {
953 RTLdrClose(mhModVMM);
954 mhModVMM = NIL_RTLDRMOD;
955 }
956
957 /* Release memory held by the LED sets (no need to take lock). */
958 for (size_t idxType = 0; idxType < RT_ELEMENTS(maLedTypes); idxType++)
959 {
960 maLedTypes[idxType].cLeds = 0;
961 maLedTypes[idxType].cAllocated = 0;
962 RTMemFree(maLedTypes[idxType].pappLeds);
963 maLedTypes[idxType].pappLeds = NULL;
964 }
965 for (size_t idxSet = 0; idxSet < mcLedSets; idxSet++)
966 {
967 maLedSets[idxSet].cLeds = 0;
968 RTMemFree((void *)maLedSets[idxSet].papLeds);
969 maLedSets[idxSet].papLeds = NULL;
970 maLedSets[idxSet].paSubTypes = NULL;
971 }
972 mcLedSets = 0;
973
974#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
975 /* Close the release log before unloading the cryptographic module. */
976 if (m_fEncryptedLog)
977 {
978 PRTLOGGER pLogEnc = RTLogRelSetDefaultInstance(NULL);
979 int vrc = RTLogDestroy(pLogEnc);
980 AssertRC(vrc);
981 }
982#endif
983
984 HRESULT hrc = i_unloadCryptoIfModule();
985 AssertComRC(hrc);
986
987 LogFlowThisFuncLeave();
988}
989
990#ifdef VBOX_WITH_GUEST_PROPS
991
992/**
993 * Wrapper for VMMDev::i_guestPropertiesHandleVMReset
994 */
995HRESULT Console::i_pullGuestProperties(ComSafeArrayOut(BSTR, names), ComSafeArrayOut(BSTR, values),
996 ComSafeArrayOut(LONG64, timestamps), ComSafeArrayOut(BSTR, flags))
997{
998 AssertReturn(mControl.isNotNull(), E_POINTER);
999 return mControl->PullGuestProperties(ComSafeArrayOutArg(names), ComSafeArrayOutArg(values),
1000 ComSafeArrayOutArg(timestamps), ComSafeArrayOutArg(flags));
1001}
1002
1003/**
1004 * Handles guest properties on a VM reset.
1005 *
1006 * We must delete properties that are flagged TRANSRESET.
1007 *
1008 * @todo r=bird: Would be more efficient if we added a request to the HGCM
1009 * service to do this instead of detouring thru VBoxSVC.
1010 * (IMachine::SetGuestProperty ends up in VBoxSVC, which in turns calls
1011 * back into the VM process and the HGCM service.)
1012 */
1013void Console::i_guestPropertiesHandleVMReset(void)
1014{
1015 std::vector<Utf8Str> names;
1016 std::vector<Utf8Str> values;
1017 std::vector<LONG64> timestamps;
1018 std::vector<Utf8Str> flags;
1019 HRESULT hrc = i_enumerateGuestProperties("*", names, values, timestamps, flags);
1020 if (SUCCEEDED(hrc))
1021 {
1022 for (size_t i = 0; i < flags.size(); i++)
1023 {
1024 /* Delete all properties which have the flag "TRANSRESET". */
1025 if (flags[i].contains("TRANSRESET", Utf8Str::CaseInsensitive))
1026 {
1027 hrc = mMachine->DeleteGuestProperty(Bstr(names[i]).raw());
1028 if (FAILED(hrc))
1029 LogRel(("RESET: Could not delete transient property \"%s\", hrc=%Rhrc\n",
1030 names[i].c_str(), hrc));
1031 }
1032 }
1033 }
1034 else
1035 LogRel(("RESET: Unable to enumerate guest properties, hrc=%Rhrc\n", hrc));
1036}
1037
1038bool Console::i_guestPropertiesVRDPEnabled(void)
1039{
1040 Bstr value;
1041 HRESULT hrc = mMachine->GetExtraData(Bstr("VBoxInternal2/EnableGuestPropertiesVRDP").raw(),
1042 value.asOutParam());
1043 if ( hrc == S_OK
1044 && value == "1")
1045 return true;
1046 return false;
1047}
1048
1049void Console::i_guestPropertiesVRDPUpdateLogon(uint32_t u32ClientId, const char *pszUser, const char *pszDomain)
1050{
1051 if (!i_guestPropertiesVRDPEnabled())
1052 return;
1053
1054 LogFlowFunc(("\n"));
1055
1056 char szPropNm[256];
1057 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
1058
1059 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Name", u32ClientId);
1060 Bstr clientName;
1061 mVRDEServerInfo->COMGETTER(ClientName)(clientName.asOutParam());
1062
1063 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
1064 clientName.raw(),
1065 bstrReadOnlyGuest.raw());
1066
1067 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/User", u32ClientId);
1068 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
1069 Bstr(pszUser).raw(),
1070 bstrReadOnlyGuest.raw());
1071
1072 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Domain", u32ClientId);
1073 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
1074 Bstr(pszDomain).raw(),
1075 bstrReadOnlyGuest.raw());
1076
1077 char szClientId[64];
1078 RTStrPrintf(szClientId, sizeof(szClientId), "%u", u32ClientId);
1079 mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VRDP/LastConnectedClient").raw(),
1080 Bstr(szClientId).raw(),
1081 bstrReadOnlyGuest.raw());
1082
1083 return;
1084}
1085
1086void Console::i_guestPropertiesVRDPUpdateActiveClient(uint32_t u32ClientId)
1087{
1088 if (!i_guestPropertiesVRDPEnabled())
1089 return;
1090
1091 LogFlowFunc(("%d\n", u32ClientId));
1092
1093 Bstr bstrFlags(L"RDONLYGUEST,TRANSIENT");
1094
1095 char szClientId[64];
1096 RTStrPrintf(szClientId, sizeof(szClientId), "%u", u32ClientId);
1097
1098 mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VRDP/ActiveClient").raw(),
1099 Bstr(szClientId).raw(),
1100 bstrFlags.raw());
1101
1102 return;
1103}
1104
1105void Console::i_guestPropertiesVRDPUpdateNameChange(uint32_t u32ClientId, const char *pszName)
1106{
1107 if (!i_guestPropertiesVRDPEnabled())
1108 return;
1109
1110 LogFlowFunc(("\n"));
1111
1112 char szPropNm[256];
1113 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
1114
1115 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Name", u32ClientId);
1116 Bstr clientName(pszName);
1117
1118 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
1119 clientName.raw(),
1120 bstrReadOnlyGuest.raw());
1121
1122}
1123
1124void Console::i_guestPropertiesVRDPUpdateIPAddrChange(uint32_t u32ClientId, const char *pszIPAddr)
1125{
1126 if (!i_guestPropertiesVRDPEnabled())
1127 return;
1128
1129 LogFlowFunc(("\n"));
1130
1131 char szPropNm[256];
1132 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
1133
1134 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/IPAddr", u32ClientId);
1135 Bstr clientIPAddr(pszIPAddr);
1136
1137 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
1138 clientIPAddr.raw(),
1139 bstrReadOnlyGuest.raw());
1140
1141}
1142
1143void Console::i_guestPropertiesVRDPUpdateLocationChange(uint32_t u32ClientId, const char *pszLocation)
1144{
1145 if (!i_guestPropertiesVRDPEnabled())
1146 return;
1147
1148 LogFlowFunc(("\n"));
1149
1150 char szPropNm[256];
1151 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
1152
1153 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Location", u32ClientId);
1154 Bstr clientLocation(pszLocation);
1155
1156 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
1157 clientLocation.raw(),
1158 bstrReadOnlyGuest.raw());
1159
1160}
1161
1162void Console::i_guestPropertiesVRDPUpdateOtherInfoChange(uint32_t u32ClientId, const char *pszOtherInfo)
1163{
1164 if (!i_guestPropertiesVRDPEnabled())
1165 return;
1166
1167 LogFlowFunc(("\n"));
1168
1169 char szPropNm[256];
1170 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
1171
1172 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/OtherInfo", u32ClientId);
1173 Bstr clientOtherInfo(pszOtherInfo);
1174
1175 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
1176 clientOtherInfo.raw(),
1177 bstrReadOnlyGuest.raw());
1178
1179}
1180
1181void Console::i_guestPropertiesVRDPUpdateClientAttach(uint32_t u32ClientId, bool fAttached)
1182{
1183 if (!i_guestPropertiesVRDPEnabled())
1184 return;
1185
1186 LogFlowFunc(("\n"));
1187
1188 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
1189
1190 char szPropNm[256];
1191 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Attach", u32ClientId);
1192
1193 Bstr bstrValue = fAttached? "1": "0";
1194
1195 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
1196 bstrValue.raw(),
1197 bstrReadOnlyGuest.raw());
1198}
1199
1200void Console::i_guestPropertiesVRDPUpdateDisconnect(uint32_t u32ClientId)
1201{
1202 if (!i_guestPropertiesVRDPEnabled())
1203 return;
1204
1205 LogFlowFunc(("\n"));
1206
1207 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
1208
1209 char szPropNm[256];
1210 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Name", u32ClientId);
1211 mMachine->SetGuestProperty(Bstr(szPropNm).raw(), NULL,
1212 bstrReadOnlyGuest.raw());
1213
1214 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/User", u32ClientId);
1215 mMachine->SetGuestProperty(Bstr(szPropNm).raw(), NULL,
1216 bstrReadOnlyGuest.raw());
1217
1218 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Domain", u32ClientId);
1219 mMachine->SetGuestProperty(Bstr(szPropNm).raw(), NULL,
1220 bstrReadOnlyGuest.raw());
1221
1222 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Attach", u32ClientId);
1223 mMachine->SetGuestProperty(Bstr(szPropNm).raw(), NULL,
1224 bstrReadOnlyGuest.raw());
1225
1226 char szClientId[64];
1227 RTStrPrintf(szClientId, sizeof(szClientId), "%d", u32ClientId);
1228 mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VRDP/LastDisconnectedClient").raw(),
1229 Bstr(szClientId).raw(),
1230 bstrReadOnlyGuest.raw());
1231
1232 return;
1233}
1234
1235#endif /* VBOX_WITH_GUEST_PROPS */
1236
1237#ifdef VBOX_WITH_EXTPACK
1238/**
1239 * Used by VRDEServer and others to talke to the extension pack manager.
1240 *
1241 * @returns The extension pack manager.
1242 */
1243ExtPackManager *Console::i_getExtPackManager()
1244{
1245 return mptrExtPackManager;
1246}
1247#endif
1248
1249
1250int Console::i_VRDPClientLogon(uint32_t u32ClientId, const char *pszUser, const char *pszPassword, const char *pszDomain)
1251{
1252 LogFlowFuncEnter();
1253 LogFlowFunc(("%d, %s, %s, %s\n", u32ClientId, pszUser, pszPassword, pszDomain));
1254
1255 AutoCaller autoCaller(this);
1256 if (!autoCaller.isOk())
1257 {
1258 /* Console has been already uninitialized, deny request */
1259 LogRel(("AUTH: Access denied (Console uninitialized).\n"));
1260 LogFlowFuncLeave();
1261 return VERR_ACCESS_DENIED;
1262 }
1263
1264 Guid uuid = Guid(i_getId());
1265
1266 AuthType_T authType = AuthType_Null;
1267 HRESULT hrc = mVRDEServer->COMGETTER(AuthType)(&authType);
1268 AssertComRCReturn(hrc, VERR_ACCESS_DENIED);
1269
1270 ULONG authTimeout = 0;
1271 hrc = mVRDEServer->COMGETTER(AuthTimeout)(&authTimeout);
1272 AssertComRCReturn(hrc, VERR_ACCESS_DENIED);
1273
1274 AuthResult result = AuthResultAccessDenied;
1275 AuthGuestJudgement guestJudgement = AuthGuestNotAsked;
1276
1277 LogFlowFunc(("Auth type %d\n", authType));
1278
1279 LogRel(("AUTH: User: [%s]. Domain: [%s]. Authentication type: [%s]\n",
1280 pszUser, pszDomain,
1281 authType == AuthType_Null?
1282 "Null":
1283 (authType == AuthType_External?
1284 "External":
1285 (authType == AuthType_Guest?
1286 "Guest":
1287 "INVALID"
1288 )
1289 )
1290 ));
1291
1292 switch (authType)
1293 {
1294 case AuthType_Null:
1295 {
1296 result = AuthResultAccessGranted;
1297 break;
1298 }
1299
1300 case AuthType_External:
1301 {
1302 /* Call the external library. */
1303 result = mConsoleVRDPServer->Authenticate(uuid, guestJudgement, pszUser, pszPassword, pszDomain, u32ClientId);
1304
1305 if (result != AuthResultDelegateToGuest)
1306 {
1307 break;
1308 }
1309
1310 LogRel(("AUTH: Delegated to guest.\n"));
1311
1312 LogFlowFunc(("External auth asked for guest judgement\n"));
1313 }
1314 RT_FALL_THRU();
1315
1316 case AuthType_Guest:
1317 {
1318 guestJudgement = AuthGuestNotReacted;
1319
1320 /** @todo r=dj locking required here for m_pVMMDev? */
1321 PPDMIVMMDEVPORT pDevPort;
1322 if ( m_pVMMDev
1323 && ((pDevPort = m_pVMMDev->getVMMDevPort()))
1324 )
1325 {
1326 /* Issue the request to guest. Assume that the call does not require EMT. It should not. */
1327
1328 /* Ask the guest to judge these credentials. */
1329 uint32_t u32GuestFlags = VMMDEV_SETCREDENTIALS_JUDGE;
1330
1331 int vrc = pDevPort->pfnSetCredentials(pDevPort, pszUser, pszPassword, pszDomain, u32GuestFlags);
1332 if (RT_SUCCESS(vrc))
1333 {
1334 /* Wait for guest. */
1335 vrc = m_pVMMDev->WaitCredentialsJudgement(authTimeout, &u32GuestFlags);
1336 if (RT_SUCCESS(vrc))
1337 {
1338 switch (u32GuestFlags & ( VMMDEV_CREDENTIALS_JUDGE_OK
1339 | VMMDEV_CREDENTIALS_JUDGE_DENY
1340 | VMMDEV_CREDENTIALS_JUDGE_NOJUDGEMENT))
1341 {
1342 case VMMDEV_CREDENTIALS_JUDGE_DENY: guestJudgement = AuthGuestAccessDenied; break;
1343 case VMMDEV_CREDENTIALS_JUDGE_NOJUDGEMENT: guestJudgement = AuthGuestNoJudgement; break;
1344 case VMMDEV_CREDENTIALS_JUDGE_OK: guestJudgement = AuthGuestAccessGranted; break;
1345 default:
1346 LogFlowFunc(("Invalid guest flags %#08x!!!\n", u32GuestFlags));
1347 break;
1348 }
1349 }
1350 else
1351 LogFlowFunc(("Wait for credentials judgement vrc = %Rrc!!!\n", vrc));
1352 LogFlowFunc(("Guest judgement %d\n", guestJudgement));
1353 }
1354 else
1355 LogFlowFunc(("Could not set credentials vrc = %Rrc!!!\n", vrc));
1356 }
1357
1358 if (authType == AuthType_External)
1359 {
1360 LogRel(("AUTH: Guest judgement %d.\n", guestJudgement));
1361 LogFlowFunc(("External auth called again with guest judgement = %d\n", guestJudgement));
1362 result = mConsoleVRDPServer->Authenticate(uuid, guestJudgement, pszUser, pszPassword, pszDomain, u32ClientId);
1363 }
1364 else
1365 {
1366 switch (guestJudgement)
1367 {
1368 case AuthGuestAccessGranted:
1369 result = AuthResultAccessGranted;
1370 break;
1371 default:
1372 result = AuthResultAccessDenied;
1373 break;
1374 }
1375 }
1376 break;
1377 }
1378
1379 default:
1380 AssertFailed();
1381 }
1382
1383 LogFlowFunc(("Result = %d\n", result));
1384 LogFlowFuncLeave();
1385
1386 if (result != AuthResultAccessGranted)
1387 {
1388 /* Reject. */
1389 LogRel(("AUTH: Access denied.\n"));
1390 return VERR_ACCESS_DENIED;
1391 }
1392
1393 LogRel(("AUTH: Access granted.\n"));
1394
1395 /* Multiconnection check must be made after authentication, so bad clients would not interfere with a good one. */
1396 BOOL allowMultiConnection = FALSE;
1397 hrc = mVRDEServer->COMGETTER(AllowMultiConnection)(&allowMultiConnection);
1398 AssertComRCReturn(hrc, VERR_ACCESS_DENIED);
1399
1400 BOOL reuseSingleConnection = FALSE;
1401 hrc = mVRDEServer->COMGETTER(ReuseSingleConnection)(&reuseSingleConnection);
1402 AssertComRCReturn(hrc, VERR_ACCESS_DENIED);
1403
1404 LogFlowFunc(("allowMultiConnection %d, reuseSingleConnection = %d, mcVRDPClients = %d, mu32SingleRDPClientId = %d\n",
1405 allowMultiConnection, reuseSingleConnection, mcVRDPClients, mu32SingleRDPClientId));
1406
1407 if (allowMultiConnection == FALSE)
1408 {
1409 /* Note: the 'mcVRDPClients' variable is incremented in ClientConnect callback, which is called when the client
1410 * is successfully connected, that is after the ClientLogon callback. Therefore the mcVRDPClients
1411 * value is 0 for first client.
1412 */
1413 if (mcVRDPClients != 0)
1414 {
1415 Assert(mcVRDPClients == 1);
1416 /* There is a client already.
1417 * If required drop the existing client connection and let the connecting one in.
1418 */
1419 if (reuseSingleConnection)
1420 {
1421 LogRel(("AUTH: Multiple connections are not enabled. Disconnecting existing client.\n"));
1422 mConsoleVRDPServer->DisconnectClient(mu32SingleRDPClientId, false);
1423 }
1424 else
1425 {
1426 /* Reject. */
1427 LogRel(("AUTH: Multiple connections are not enabled. Access denied.\n"));
1428 return VERR_ACCESS_DENIED;
1429 }
1430 }
1431
1432 /* Save the connected client id. From now on it will be necessary to disconnect this one. */
1433 mu32SingleRDPClientId = u32ClientId;
1434 }
1435
1436#ifdef VBOX_WITH_GUEST_PROPS
1437 i_guestPropertiesVRDPUpdateLogon(u32ClientId, pszUser, pszDomain);
1438#endif /* VBOX_WITH_GUEST_PROPS */
1439
1440 /* Check if the successfully verified credentials are to be sent to the guest. */
1441 BOOL fProvideGuestCredentials = FALSE;
1442
1443 Bstr value;
1444 hrc = mMachine->GetExtraData(Bstr("VRDP/ProvideGuestCredentials").raw(),
1445 value.asOutParam());
1446 if (SUCCEEDED(hrc) && value == "1")
1447 {
1448 /* Provide credentials only if there are no logged in users. */
1449 Utf8Str noLoggedInUsersValue;
1450 LONG64 ul64Timestamp = 0;
1451 Utf8Str flags;
1452
1453 hrc = i_getGuestProperty("/VirtualBox/GuestInfo/OS/NoLoggedInUsers",
1454 &noLoggedInUsersValue, &ul64Timestamp, &flags);
1455
1456 if (SUCCEEDED(hrc) && noLoggedInUsersValue != "false")
1457 {
1458 /* And only if there are no connected clients. */
1459 if (ASMAtomicCmpXchgBool(&mcGuestCredentialsProvided, true, false))
1460 {
1461 fProvideGuestCredentials = TRUE;
1462 }
1463 }
1464 }
1465
1466 /** @todo r=dj locking required here for m_pVMMDev? */
1467 if ( fProvideGuestCredentials
1468 && m_pVMMDev)
1469 {
1470 uint32_t u32GuestFlags = VMMDEV_SETCREDENTIALS_GUESTLOGON;
1471
1472 PPDMIVMMDEVPORT pDevPort = m_pVMMDev->getVMMDevPort();
1473 if (pDevPort)
1474 {
1475 int vrc = pDevPort->pfnSetCredentials(m_pVMMDev->getVMMDevPort(), pszUser, pszPassword, pszDomain, u32GuestFlags);
1476 AssertRC(vrc);
1477 }
1478 }
1479
1480 return VINF_SUCCESS;
1481}
1482
1483void Console::i_VRDPClientStatusChange(uint32_t u32ClientId, const char *pszStatus)
1484{
1485 LogFlowFuncEnter();
1486
1487 AutoCaller autoCaller(this);
1488 AssertComRCReturnVoid(autoCaller.hrc());
1489
1490 LogFlowFunc(("%s\n", pszStatus));
1491
1492#ifdef VBOX_WITH_GUEST_PROPS
1493 /* Parse the status string. */
1494 if (RTStrICmp(pszStatus, "ATTACH") == 0)
1495 {
1496 i_guestPropertiesVRDPUpdateClientAttach(u32ClientId, true);
1497 }
1498 else if (RTStrICmp(pszStatus, "DETACH") == 0)
1499 {
1500 i_guestPropertiesVRDPUpdateClientAttach(u32ClientId, false);
1501 }
1502 else if (RTStrNICmp(pszStatus, "NAME=", strlen("NAME=")) == 0)
1503 {
1504 i_guestPropertiesVRDPUpdateNameChange(u32ClientId, pszStatus + strlen("NAME="));
1505 }
1506 else if (RTStrNICmp(pszStatus, "CIPA=", strlen("CIPA=")) == 0)
1507 {
1508 i_guestPropertiesVRDPUpdateIPAddrChange(u32ClientId, pszStatus + strlen("CIPA="));
1509 }
1510 else if (RTStrNICmp(pszStatus, "CLOCATION=", strlen("CLOCATION=")) == 0)
1511 {
1512 i_guestPropertiesVRDPUpdateLocationChange(u32ClientId, pszStatus + strlen("CLOCATION="));
1513 }
1514 else if (RTStrNICmp(pszStatus, "COINFO=", strlen("COINFO=")) == 0)
1515 {
1516 i_guestPropertiesVRDPUpdateOtherInfoChange(u32ClientId, pszStatus + strlen("COINFO="));
1517 }
1518#endif
1519
1520 LogFlowFuncLeave();
1521}
1522
1523void Console::i_VRDPClientConnect(uint32_t u32ClientId)
1524{
1525 LogFlowFuncEnter();
1526
1527 AutoCaller autoCaller(this);
1528 AssertComRCReturnVoid(autoCaller.hrc());
1529
1530 uint32_t u32Clients = ASMAtomicIncU32(&mcVRDPClients);
1531 VMMDev *pDev;
1532 PPDMIVMMDEVPORT pPort;
1533 if ( (u32Clients == 1)
1534 && ((pDev = i_getVMMDev()))
1535 && ((pPort = pDev->getVMMDevPort()))
1536 )
1537 {
1538 pPort->pfnVRDPChange(pPort,
1539 true,
1540 VRDP_EXPERIENCE_LEVEL_FULL); /** @todo configurable */
1541 }
1542
1543 NOREF(u32ClientId);
1544 mDisplay->i_VRDPConnectionEvent(true);
1545
1546#ifdef VBOX_WITH_GUEST_PROPS
1547 i_guestPropertiesVRDPUpdateActiveClient(u32ClientId);
1548#endif /* VBOX_WITH_GUEST_PROPS */
1549
1550 LogFlowFuncLeave();
1551 return;
1552}
1553
1554void Console::i_VRDPClientDisconnect(uint32_t u32ClientId,
1555 uint32_t fu32Intercepted)
1556{
1557 LogFlowFuncEnter();
1558
1559 AutoCaller autoCaller(this);
1560 AssertComRCReturnVoid(autoCaller.hrc());
1561
1562 AssertReturnVoid(mConsoleVRDPServer);
1563
1564 uint32_t u32Clients = ASMAtomicDecU32(&mcVRDPClients);
1565 VMMDev *pDev;
1566 PPDMIVMMDEVPORT pPort;
1567
1568 if ( (u32Clients == 0)
1569 && ((pDev = i_getVMMDev()))
1570 && ((pPort = pDev->getVMMDevPort()))
1571 )
1572 {
1573 pPort->pfnVRDPChange(pPort,
1574 false,
1575 0);
1576 }
1577
1578 mDisplay->i_VRDPConnectionEvent(false);
1579
1580 if (fu32Intercepted & VRDE_CLIENT_INTERCEPT_USB)
1581 {
1582 mConsoleVRDPServer->USBBackendDelete(u32ClientId);
1583 }
1584
1585 if (fu32Intercepted & VRDE_CLIENT_INTERCEPT_CLIPBOARD)
1586 {
1587 mConsoleVRDPServer->ClipboardDelete(u32ClientId);
1588 }
1589
1590#ifdef VBOX_WITH_AUDIO_VRDE
1591 if (fu32Intercepted & VRDE_CLIENT_INTERCEPT_AUDIO)
1592 {
1593 if (mAudioVRDE)
1594 mAudioVRDE->onVRDEControl(false /* fEnable */, 0 /* uFlags */);
1595 }
1596#endif
1597
1598 AuthType_T authType = AuthType_Null;
1599 HRESULT hrc = mVRDEServer->COMGETTER(AuthType)(&authType);
1600 AssertComRC(hrc);
1601
1602 if (authType == AuthType_External)
1603 mConsoleVRDPServer->AuthDisconnect(i_getId(), u32ClientId);
1604
1605#ifdef VBOX_WITH_GUEST_PROPS
1606 i_guestPropertiesVRDPUpdateDisconnect(u32ClientId);
1607 if (u32Clients == 0)
1608 i_guestPropertiesVRDPUpdateActiveClient(0);
1609#endif /* VBOX_WITH_GUEST_PROPS */
1610
1611 if (u32Clients == 0)
1612 mcGuestCredentialsProvided = false;
1613
1614 LogFlowFuncLeave();
1615 return;
1616}
1617
1618void Console::i_VRDPInterceptAudio(uint32_t u32ClientId)
1619{
1620 RT_NOREF(u32ClientId);
1621 LogFlowFuncEnter();
1622
1623 AutoCaller autoCaller(this);
1624 AssertComRCReturnVoid(autoCaller.hrc());
1625
1626 LogFlowFunc(("u32ClientId=%RU32\n", u32ClientId));
1627
1628#ifdef VBOX_WITH_AUDIO_VRDE
1629 if (mAudioVRDE)
1630 mAudioVRDE->onVRDEControl(true /* fEnable */, 0 /* uFlags */);
1631#endif
1632
1633 LogFlowFuncLeave();
1634 return;
1635}
1636
1637void Console::i_VRDPInterceptUSB(uint32_t u32ClientId, void **ppvIntercept)
1638{
1639 LogFlowFuncEnter();
1640
1641 AutoCaller autoCaller(this);
1642 AssertComRCReturnVoid(autoCaller.hrc());
1643
1644 AssertReturnVoid(mConsoleVRDPServer);
1645
1646 mConsoleVRDPServer->USBBackendCreate(u32ClientId, ppvIntercept);
1647
1648 LogFlowFuncLeave();
1649 return;
1650}
1651
1652void Console::i_VRDPInterceptClipboard(uint32_t u32ClientId)
1653{
1654 LogFlowFuncEnter();
1655
1656 AutoCaller autoCaller(this);
1657 AssertComRCReturnVoid(autoCaller.hrc());
1658
1659 AssertReturnVoid(mConsoleVRDPServer);
1660
1661 mConsoleVRDPServer->ClipboardCreate(u32ClientId);
1662
1663 LogFlowFuncLeave();
1664 return;
1665}
1666
1667
1668//static
1669const char *Console::sSSMConsoleUnit = "ConsoleData";
1670/** The saved state version. */
1671#define CONSOLE_SAVED_STATE_VERSION UINT32_C(0x00010002)
1672/** The saved state version, pre shared folder autoMountPoint. */
1673#define CONSOLE_SAVED_STATE_VERSION_PRE_AUTO_MOUNT_POINT UINT32_C(0x00010001)
1674
1675inline static const char *networkAdapterTypeToName(NetworkAdapterType_T adapterType)
1676{
1677 switch (adapterType)
1678 {
1679 case NetworkAdapterType_Am79C970A:
1680 case NetworkAdapterType_Am79C973:
1681 case NetworkAdapterType_Am79C960:
1682 return "pcnet";
1683#ifdef VBOX_WITH_E1000
1684 case NetworkAdapterType_I82540EM:
1685 case NetworkAdapterType_I82543GC:
1686 case NetworkAdapterType_I82545EM:
1687 return "e1000";
1688#endif
1689#ifdef VBOX_WITH_VIRTIO
1690 case NetworkAdapterType_Virtio:
1691 return "virtio-net";
1692#endif
1693 case NetworkAdapterType_NE1000:
1694 case NetworkAdapterType_NE2000:
1695 case NetworkAdapterType_WD8003:
1696 case NetworkAdapterType_WD8013:
1697 case NetworkAdapterType_ELNK2:
1698 return "dp8390";
1699 case NetworkAdapterType_ELNK1:
1700 return "3c501";
1701 case NetworkAdapterType_UsbNet:
1702 return "UsbNet";
1703 default:
1704 AssertFailed();
1705 return "unknown";
1706 }
1707 /* not reached */
1708}
1709
1710/**
1711 * Loads various console data stored in the saved state file.
1712 *
1713 * This method does validation of the state file and returns an error info
1714 * when appropriate.
1715 *
1716 * The method does nothing if the machine is not in the Saved file or if
1717 * console data from it has already been loaded.
1718 *
1719 * @note The caller must lock this object for writing.
1720 */
1721HRESULT Console::i_loadDataFromSavedState()
1722{
1723 if ( ( mMachineState != MachineState_Saved
1724 && mMachineState != MachineState_AbortedSaved)
1725 || mSavedStateDataLoaded)
1726 return S_OK;
1727
1728 Bstr bstrSavedStateFile;
1729 HRESULT hrc = mMachine->COMGETTER(StateFilePath)(bstrSavedStateFile.asOutParam());
1730 if (SUCCEEDED(hrc))
1731 {
1732 Bstr bstrStateKeyId;
1733 hrc = mMachine->COMGETTER(StateKeyId)(bstrStateKeyId.asOutParam());
1734 if (SUCCEEDED(hrc))
1735 {
1736 Bstr bstrStateKeyStore;
1737 hrc = mMachine->COMGETTER(StateKeyStore)(bstrStateKeyStore.asOutParam());
1738 if (SUCCEEDED(hrc))
1739 {
1740 Utf8Str const strSavedStateFile(bstrSavedStateFile);
1741
1742 PCVMMR3VTABLE pVMM = mpVMM;
1743 AssertPtrReturn(pVMM, E_UNEXPECTED);
1744
1745 PSSMHANDLE pSSM;
1746 SsmStream ssmStream(this, pVMM, m_pKeyStore, bstrStateKeyId, bstrStateKeyStore);
1747
1748 int vrc = ssmStream.open(strSavedStateFile.c_str(), false /*fWrite*/, &pSSM);
1749 if (RT_SUCCESS(vrc))
1750 {
1751 uint32_t uVersion = 0;
1752 vrc = pVMM->pfnSSMR3Seek(pSSM, sSSMConsoleUnit, 0 /* iInstance */, &uVersion);
1753 /** @todo r=bird: This version check is premature, so the logic here is
1754 * buggered as we won't ignore VERR_SSM_UNIT_NOT_FOUND as seems to be
1755 * intended. Sigh. */
1756 if (SSM_VERSION_MAJOR(uVersion) == SSM_VERSION_MAJOR(CONSOLE_SAVED_STATE_VERSION))
1757 {
1758 if (RT_SUCCESS(vrc))
1759 try
1760 {
1761 vrc = i_loadStateFileExecInternal(pSSM, pVMM, uVersion);
1762 }
1763 catch (std::bad_alloc &)
1764 {
1765 vrc = VERR_NO_MEMORY;
1766 }
1767 else if (vrc == VERR_SSM_UNIT_NOT_FOUND)
1768 vrc = VINF_SUCCESS;
1769 }
1770 else
1771 vrc = VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
1772
1773 ssmStream.close();
1774 }
1775
1776 if (RT_FAILURE(vrc))
1777 hrc = setErrorBoth(VBOX_E_FILE_ERROR, vrc,
1778 tr("The saved state file '%s' is invalid (%Rrc). Delete the saved state and try again"),
1779 strSavedStateFile.c_str(), vrc);
1780
1781 mSavedStateDataLoaded = true;
1782 }
1783 }
1784 }
1785
1786 return hrc;
1787}
1788
1789/**
1790 * Callback handler to save various console data to the state file,
1791 * called when the user saves the VM state.
1792 *
1793 * @returns VBox status code.
1794 * @param pSSM SSM handle.
1795 * @param pVMM The VMM ring-3 vtable.
1796 * @param pvUser Pointer to Console
1797 *
1798 * @note Locks the Console object for reading.
1799 */
1800/*static*/ DECLCALLBACK(int)
1801Console::i_saveStateFileExec(PSSMHANDLE pSSM, PCVMMR3VTABLE pVMM, void *pvUser)
1802{
1803 LogFlowFunc(("\n"));
1804
1805 Console *pThat = static_cast<Console *>(pvUser);
1806 AssertReturn(pThat, VERR_INVALID_POINTER);
1807
1808 AutoCaller autoCaller(pThat);
1809 AssertComRCReturn(autoCaller.hrc(), VERR_INVALID_STATE);
1810
1811 AutoReadLock alock(pThat COMMA_LOCKVAL_SRC_POS);
1812
1813 pVMM->pfnSSMR3PutU32(pSSM, (uint32_t)pThat->m_mapSharedFolders.size());
1814
1815 for (SharedFolderMap::const_iterator it = pThat->m_mapSharedFolders.begin();
1816 it != pThat->m_mapSharedFolders.end();
1817 ++it)
1818 {
1819 ConsoleSharedFolder *pSF = (*it).second;
1820 AutoCaller sfCaller(pSF);
1821 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
1822
1823 const Utf8Str &name = pSF->i_getName();
1824 pVMM->pfnSSMR3PutU32(pSSM, (uint32_t)name.length() + 1 /* term. 0 */);
1825 pVMM->pfnSSMR3PutStrZ(pSSM, name.c_str());
1826
1827 const Utf8Str &hostPath = pSF->i_getHostPath();
1828 pVMM->pfnSSMR3PutU32(pSSM, (uint32_t)hostPath.length() + 1 /* term. 0 */);
1829 pVMM->pfnSSMR3PutStrZ(pSSM, hostPath.c_str());
1830
1831 pVMM->pfnSSMR3PutBool(pSSM, !!pSF->i_isWritable());
1832 pVMM->pfnSSMR3PutBool(pSSM, !!pSF->i_isAutoMounted());
1833
1834 const Utf8Str &rStrAutoMountPoint = pSF->i_getAutoMountPoint();
1835 pVMM->pfnSSMR3PutU32(pSSM, (uint32_t)rStrAutoMountPoint.length() + 1 /* term. 0 */);
1836 pVMM->pfnSSMR3PutStrZ(pSSM, rStrAutoMountPoint.c_str());
1837 }
1838
1839 return VINF_SUCCESS;
1840}
1841
1842/**
1843 * Callback handler to load various console data from the state file.
1844 *
1845 * Called when the VM is being restored from the saved state.
1846 *
1847 * @returns VBox status code.
1848 * @param pSSM SSM handle.
1849 * @param pVMM The VMM ring-3 vtable.
1850 * @param pvUser pointer to Console
1851 * @param uVersion Console unit version. Should match sSSMConsoleVer.
1852 * @param uPass The data pass.
1853 */
1854//static
1855DECLCALLBACK(int)
1856Console::i_loadStateFileExec(PSSMHANDLE pSSM, PCVMMR3VTABLE pVMM, void *pvUser, uint32_t uVersion, uint32_t uPass)
1857{
1858 LogFlowFunc(("uVersion=%#x uPass=%#x\n", uVersion, uPass));
1859 Assert(uPass == SSM_PASS_FINAL); RT_NOREF_PV(uPass);
1860
1861 if (SSM_VERSION_MAJOR_CHANGED(uVersion, CONSOLE_SAVED_STATE_VERSION))
1862 return VERR_VERSION_MISMATCH;
1863
1864 Console *pThat = static_cast<Console *>(pvUser);
1865 AssertReturn(pThat, VERR_INVALID_PARAMETER);
1866
1867 /* Currently, nothing to do when we've been called from VMR3Load*. */
1868 return pVMM->pfnSSMR3SkipToEndOfUnit(pSSM);
1869}
1870
1871/**
1872 * Method to load various console data from the state file.
1873 *
1874 * Called from #i_loadDataFromSavedState.
1875 *
1876 * @param pSSM SSM handle.
1877 * @param pVMM The VMM vtable.
1878 * @param u32Version Console unit version.
1879 * Should match sSSMConsoleVer.
1880 *
1881 * @note Locks the Console object for writing.
1882 */
1883int Console::i_loadStateFileExecInternal(PSSMHANDLE pSSM, PCVMMR3VTABLE pVMM, uint32_t u32Version)
1884{
1885 AutoCaller autoCaller(this);
1886 AssertComRCReturn(autoCaller.hrc(), VERR_ACCESS_DENIED);
1887
1888 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1889
1890 AssertReturn(m_mapSharedFolders.empty(), VERR_INTERNAL_ERROR);
1891
1892 uint32_t size = 0;
1893 int vrc = pVMM->pfnSSMR3GetU32(pSSM, &size);
1894 AssertRCReturn(vrc, vrc);
1895
1896 for (uint32_t i = 0; i < size; ++i)
1897 {
1898 Utf8Str strName;
1899 Utf8Str strHostPath;
1900 bool writable = true;
1901 bool autoMount = false;
1902
1903 uint32_t cbStr = 0;
1904 char *buf = NULL;
1905
1906 vrc = pVMM->pfnSSMR3GetU32(pSSM, &cbStr);
1907 AssertRCReturn(vrc, vrc);
1908 buf = new char[cbStr];
1909 vrc = pVMM->pfnSSMR3GetStrZ(pSSM, buf, cbStr);
1910 AssertRC(vrc);
1911 strName = buf;
1912 delete[] buf;
1913
1914 vrc = pVMM->pfnSSMR3GetU32(pSSM, &cbStr);
1915 AssertRCReturn(vrc, vrc);
1916 buf = new char[cbStr];
1917 vrc = pVMM->pfnSSMR3GetStrZ(pSSM, buf, cbStr);
1918 AssertRC(vrc);
1919 strHostPath = buf;
1920 delete[] buf;
1921
1922 if (u32Version >= CONSOLE_SAVED_STATE_VERSION_PRE_AUTO_MOUNT_POINT)
1923 pVMM->pfnSSMR3GetBool(pSSM, &writable);
1924
1925 if ( u32Version >= CONSOLE_SAVED_STATE_VERSION_PRE_AUTO_MOUNT_POINT
1926#ifndef VBOX_OSE /* This broke saved state when introduced in r63916 (4.0). */
1927 && pVMM->pfnSSMR3HandleRevision(pSSM) >= 63916
1928#endif
1929 )
1930 pVMM->pfnSSMR3GetBool(pSSM, &autoMount);
1931
1932 Utf8Str strAutoMountPoint;
1933 if (u32Version >= CONSOLE_SAVED_STATE_VERSION)
1934 {
1935 vrc = pVMM->pfnSSMR3GetU32(pSSM, &cbStr);
1936 AssertRCReturn(vrc, vrc);
1937 vrc = strAutoMountPoint.reserveNoThrow(cbStr);
1938 AssertRCReturn(vrc, vrc);
1939 vrc = pVMM->pfnSSMR3GetStrZ(pSSM, strAutoMountPoint.mutableRaw(), cbStr);
1940 AssertRCReturn(vrc, vrc);
1941 strAutoMountPoint.jolt();
1942 }
1943
1944 ComObjPtr<ConsoleSharedFolder> pSharedFolder;
1945 pSharedFolder.createObject();
1946 HRESULT hrc = pSharedFolder->init(this,
1947 strName,
1948 strHostPath,
1949 writable,
1950 autoMount,
1951 strAutoMountPoint,
1952 false /* fFailOnError */);
1953 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
1954
1955 m_mapSharedFolders.insert(std::make_pair(strName, pSharedFolder));
1956 }
1957
1958 return VINF_SUCCESS;
1959}
1960
1961#ifdef VBOX_WITH_GUEST_PROPS
1962
1963// static
1964DECLCALLBACK(int) Console::i_doGuestPropNotification(void *pvExtension,
1965 uint32_t u32Function,
1966 void *pvParms,
1967 uint32_t cbParms)
1968{
1969 Assert(u32Function == 0); NOREF(u32Function);
1970
1971 /*
1972 * No locking, as this is purely a notification which does not make any
1973 * changes to the object state.
1974 */
1975 PGUESTPROPHOSTCALLBACKDATA pCBData = reinterpret_cast<PGUESTPROPHOSTCALLBACKDATA>(pvParms);
1976 AssertReturn(sizeof(GUESTPROPHOSTCALLBACKDATA) == cbParms, VERR_INVALID_PARAMETER);
1977 AssertReturn(pCBData->u32Magic == GUESTPROPHOSTCALLBACKDATA_MAGIC, VERR_INVALID_PARAMETER);
1978 LogFlow(("Console::doGuestPropNotification: pCBData={.pcszName=%s, .pcszValue=%s, .pcszFlags=%s}\n",
1979 pCBData->pcszName, pCBData->pcszValue, pCBData->pcszFlags));
1980
1981 Bstr name(pCBData->pcszName);
1982 Bstr value(pCBData->pcszValue);
1983 Bstr flags(pCBData->pcszFlags);
1984 BOOL fWasDeleted = !pCBData->pcszValue;
1985 ComObjPtr<Console> pConsole = reinterpret_cast<Console *>(pvExtension);
1986 HRESULT hrc = pConsole->mControl->PushGuestProperty(name.raw(),
1987 value.raw(),
1988 pCBData->u64Timestamp,
1989 flags.raw(),
1990 fWasDeleted);
1991 if (SUCCEEDED(hrc))
1992 {
1993 ::FireGuestPropertyChangedEvent(pConsole->mEventSource, pConsole->i_getId().raw(), name.raw(), value.raw(), flags.raw(),
1994 fWasDeleted);
1995 return VINF_SUCCESS;
1996 }
1997 LogFlow(("Console::doGuestPropNotification: hrc=%Rhrc pCBData={.pcszName=%s, .pcszValue=%s, .pcszFlags=%s}\n",
1998 hrc, pCBData->pcszName, pCBData->pcszValue, pCBData->pcszFlags));
1999 return Global::vboxStatusCodeFromCOM(hrc);
2000}
2001
2002HRESULT Console::i_doEnumerateGuestProperties(const Utf8Str &aPatterns,
2003 std::vector<Utf8Str> &aNames,
2004 std::vector<Utf8Str> &aValues,
2005 std::vector<LONG64> &aTimestamps,
2006 std::vector<Utf8Str> &aFlags)
2007{
2008 AssertReturn(m_pVMMDev, E_FAIL);
2009
2010 VBOXHGCMSVCPARM parm[3];
2011 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
2012 parm[0].u.pointer.addr = (void*)aPatterns.c_str();
2013 parm[0].u.pointer.size = (uint32_t)aPatterns.length() + 1;
2014
2015 /*
2016 * Now things get slightly complicated. Due to a race with the guest adding
2017 * properties, there is no good way to know how much to enlarge a buffer for
2018 * the service to enumerate into. We choose a decent starting size and loop a
2019 * few times, each time retrying with the size suggested by the service plus
2020 * one Kb.
2021 */
2022 size_t cchBuf = 4096;
2023 Utf8Str Utf8Buf;
2024 int vrc = VERR_BUFFER_OVERFLOW;
2025 for (unsigned i = 0; i < 10 && (VERR_BUFFER_OVERFLOW == vrc); ++i)
2026 {
2027 try
2028 {
2029 Utf8Buf.reserve(cchBuf + 1024);
2030 }
2031 catch(...)
2032 {
2033 return E_OUTOFMEMORY;
2034 }
2035
2036 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
2037 parm[1].u.pointer.addr = Utf8Buf.mutableRaw();
2038 parm[1].u.pointer.size = (uint32_t)cchBuf + 1024;
2039
2040 parm[2].type = VBOX_HGCM_SVC_PARM_32BIT;
2041 parm[2].u.uint32 = 0;
2042
2043 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GUEST_PROP_FN_HOST_ENUM_PROPS, 3, &parm[0]);
2044 Utf8Buf.jolt();
2045 if (parm[2].type != VBOX_HGCM_SVC_PARM_32BIT)
2046 return setErrorBoth(E_FAIL, vrc, tr("Internal application error"));
2047 cchBuf = parm[2].u.uint32;
2048 }
2049 if (vrc == VERR_BUFFER_OVERFLOW)
2050 return setError(E_UNEXPECTED, tr("Temporary failure due to guest activity, please retry"));
2051
2052 /*
2053 * Finally we have to unpack the data returned by the service into the safe
2054 * arrays supplied by the caller. We start by counting the number of entries.
2055 */
2056 const char *pszBuf
2057 = reinterpret_cast<const char *>(parm[1].u.pointer.addr);
2058 unsigned cEntries = 0;
2059 /* The list is terminated by a zero-length string at the end of a set
2060 * of four strings. */
2061 for (size_t i = 0; strlen(pszBuf + i) != 0; )
2062 {
2063 /* We are counting sets of four strings. */
2064 for (unsigned j = 0; j < 4; ++j)
2065 i += strlen(pszBuf + i) + 1;
2066 ++cEntries;
2067 }
2068
2069 aNames.resize(cEntries);
2070 aValues.resize(cEntries);
2071 aTimestamps.resize(cEntries);
2072 aFlags.resize(cEntries);
2073
2074 size_t iBuf = 0;
2075 /* Rely on the service to have formated the data correctly. */
2076 for (unsigned i = 0; i < cEntries; ++i)
2077 {
2078 size_t cchName = strlen(pszBuf + iBuf);
2079 aNames[i] = &pszBuf[iBuf];
2080 iBuf += cchName + 1;
2081
2082 size_t cchValue = strlen(pszBuf + iBuf);
2083 aValues[i] = &pszBuf[iBuf];
2084 iBuf += cchValue + 1;
2085
2086 size_t cchTimestamp = strlen(pszBuf + iBuf);
2087 aTimestamps[i] = RTStrToUInt64(&pszBuf[iBuf]);
2088 iBuf += cchTimestamp + 1;
2089
2090 size_t cchFlags = strlen(pszBuf + iBuf);
2091 aFlags[i] = &pszBuf[iBuf];
2092 iBuf += cchFlags + 1;
2093 }
2094
2095 return S_OK;
2096}
2097
2098#endif /* VBOX_WITH_GUEST_PROPS */
2099
2100
2101// IConsole properties
2102/////////////////////////////////////////////////////////////////////////////
2103HRESULT Console::getMachine(ComPtr<IMachine> &aMachine)
2104{
2105 /* mMachine is constant during life time, no need to lock */
2106 mMachine.queryInterfaceTo(aMachine.asOutParam());
2107
2108 /* callers expect to get a valid reference, better fail than crash them */
2109 if (mMachine.isNull())
2110 return E_FAIL;
2111
2112 return S_OK;
2113}
2114
2115HRESULT Console::getState(MachineState_T *aState)
2116{
2117 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2118
2119 /* we return our local state (since it's always the same as on the server) */
2120 *aState = mMachineState;
2121
2122 return S_OK;
2123}
2124
2125HRESULT Console::getGuest(ComPtr<IGuest> &aGuest)
2126{
2127 /* mGuest is constant during life time, no need to lock */
2128 mGuest.queryInterfaceTo(aGuest.asOutParam());
2129
2130 return S_OK;
2131}
2132
2133HRESULT Console::getKeyboard(ComPtr<IKeyboard> &aKeyboard)
2134{
2135 /* mKeyboard is constant during life time, no need to lock */
2136 mKeyboard.queryInterfaceTo(aKeyboard.asOutParam());
2137
2138 return S_OK;
2139}
2140
2141HRESULT Console::getMouse(ComPtr<IMouse> &aMouse)
2142{
2143 /* mMouse is constant during life time, no need to lock */
2144 mMouse.queryInterfaceTo(aMouse.asOutParam());
2145
2146 return S_OK;
2147}
2148
2149HRESULT Console::getDisplay(ComPtr<IDisplay> &aDisplay)
2150{
2151 /* mDisplay is constant during life time, no need to lock */
2152 mDisplay.queryInterfaceTo(aDisplay.asOutParam());
2153
2154 return S_OK;
2155}
2156
2157HRESULT Console::getDebugger(ComPtr<IMachineDebugger> &aDebugger)
2158{
2159 /* we need a write lock because of the lazy mDebugger initialization*/
2160 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2161
2162 /* check if we have to create the debugger object */
2163 if (!mDebugger)
2164 {
2165 unconst(mDebugger).createObject();
2166 mDebugger->init(this);
2167 }
2168
2169 mDebugger.queryInterfaceTo(aDebugger.asOutParam());
2170
2171 return S_OK;
2172}
2173
2174HRESULT Console::getUSBDevices(std::vector<ComPtr<IUSBDevice> > &aUSBDevices)
2175{
2176 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2177
2178 size_t i = 0;
2179 aUSBDevices.resize(mUSBDevices.size());
2180 for (USBDeviceList::const_iterator it = mUSBDevices.begin(); it != mUSBDevices.end(); ++i, ++it)
2181 (*it).queryInterfaceTo(aUSBDevices[i].asOutParam());
2182
2183 return S_OK;
2184}
2185
2186
2187HRESULT Console::getRemoteUSBDevices(std::vector<ComPtr<IHostUSBDevice> > &aRemoteUSBDevices)
2188{
2189 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2190
2191 size_t i = 0;
2192 aRemoteUSBDevices.resize(mRemoteUSBDevices.size());
2193 for (RemoteUSBDeviceList::const_iterator it = mRemoteUSBDevices.begin(); it != mRemoteUSBDevices.end(); ++i, ++it)
2194 (*it).queryInterfaceTo(aRemoteUSBDevices[i].asOutParam());
2195
2196 return S_OK;
2197}
2198
2199HRESULT Console::getVRDEServerInfo(ComPtr<IVRDEServerInfo> &aVRDEServerInfo)
2200{
2201 /* mVRDEServerInfo is constant during life time, no need to lock */
2202 mVRDEServerInfo.queryInterfaceTo(aVRDEServerInfo.asOutParam());
2203
2204 return S_OK;
2205}
2206
2207HRESULT Console::getEmulatedUSB(ComPtr<IEmulatedUSB> &aEmulatedUSB)
2208{
2209 /* mEmulatedUSB is constant during life time, no need to lock */
2210 mEmulatedUSB.queryInterfaceTo(aEmulatedUSB.asOutParam());
2211
2212 return S_OK;
2213}
2214
2215HRESULT Console::getSharedFolders(std::vector<ComPtr<ISharedFolder> > &aSharedFolders)
2216{
2217 /* loadDataFromSavedState() needs a write lock */
2218 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2219
2220 /* Read console data stored in the saved state file (if not yet done) */
2221 HRESULT hrc = i_loadDataFromSavedState();
2222 if (FAILED(hrc))
2223 return hrc;
2224
2225 size_t i = 0;
2226 aSharedFolders.resize(m_mapSharedFolders.size());
2227 for (SharedFolderMap::const_iterator it = m_mapSharedFolders.begin(); it != m_mapSharedFolders.end(); ++i, ++it)
2228 (it)->second.queryInterfaceTo(aSharedFolders[i].asOutParam());
2229
2230 return S_OK;
2231}
2232
2233HRESULT Console::getEventSource(ComPtr<IEventSource> &aEventSource)
2234{
2235 // no need to lock - lifetime constant
2236 mEventSource.queryInterfaceTo(aEventSource.asOutParam());
2237
2238 return S_OK;
2239}
2240
2241HRESULT Console::getAttachedPCIDevices(std::vector<ComPtr<IPCIDeviceAttachment> > &aAttachedPCIDevices)
2242{
2243 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2244
2245 if (mBusMgr)
2246 {
2247 std::vector<BusAssignmentManager::PCIDeviceInfo> devInfos;
2248 mBusMgr->listAttachedPCIDevices(devInfos);
2249 ComObjPtr<PCIDeviceAttachment> dev;
2250 aAttachedPCIDevices.resize(devInfos.size());
2251 for (size_t i = 0; i < devInfos.size(); i++)
2252 {
2253 const BusAssignmentManager::PCIDeviceInfo &devInfo = devInfos[i];
2254 dev.createObject();
2255 dev->init(NULL, devInfo.strDeviceName,
2256 devInfo.hostAddress.valid() ? devInfo.hostAddress.asLong() : -1,
2257 devInfo.guestAddress.asLong(),
2258 devInfo.hostAddress.valid());
2259 dev.queryInterfaceTo(aAttachedPCIDevices[i].asOutParam());
2260 }
2261 }
2262 else
2263 aAttachedPCIDevices.resize(0);
2264
2265 return S_OK;
2266}
2267
2268HRESULT Console::getUseHostClipboard(BOOL *aUseHostClipboard)
2269{
2270 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2271
2272 *aUseHostClipboard = mfUseHostClipboard;
2273
2274 return S_OK;
2275}
2276
2277HRESULT Console::setUseHostClipboard(BOOL aUseHostClipboard)
2278{
2279 if (mfUseHostClipboard != RT_BOOL(aUseHostClipboard))
2280 {
2281 mfUseHostClipboard = RT_BOOL(aUseHostClipboard);
2282 LogRel(("Shared Clipboard: %s using host clipboard\n", mfUseHostClipboard ? "Enabled" : "Disabled"));
2283 }
2284
2285 return S_OK;
2286}
2287
2288// IConsole methods
2289/////////////////////////////////////////////////////////////////////////////
2290
2291HRESULT Console::powerUp(ComPtr<IProgress> &aProgress)
2292{
2293 return i_powerUp(aProgress.asOutParam(), false /* aPaused */);
2294}
2295
2296HRESULT Console::powerUpPaused(ComPtr<IProgress> &aProgress)
2297{
2298 return i_powerUp(aProgress.asOutParam(), true /* aPaused */);
2299}
2300
2301HRESULT Console::powerDown(ComPtr<IProgress> &aProgress)
2302{
2303 LogFlowThisFuncEnter();
2304
2305 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2306
2307 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
2308 switch (mMachineState)
2309 {
2310 case MachineState_Running:
2311 case MachineState_Paused:
2312 case MachineState_Stuck:
2313 break;
2314
2315 /* Try cancel the save state. */
2316 case MachineState_Saving:
2317 if (!mptrCancelableProgress.isNull())
2318 {
2319 HRESULT hrc = mptrCancelableProgress->Cancel();
2320 if (SUCCEEDED(hrc))
2321 break;
2322 }
2323 return setError(VBOX_E_INVALID_VM_STATE, tr("Cannot power down at this point during a save state"));
2324
2325 /* Try cancel the teleportation. */
2326 case MachineState_Teleporting:
2327 case MachineState_TeleportingPausedVM:
2328 if (!mptrCancelableProgress.isNull())
2329 {
2330 HRESULT hrc = mptrCancelableProgress->Cancel();
2331 if (SUCCEEDED(hrc))
2332 break;
2333 }
2334 return setError(VBOX_E_INVALID_VM_STATE, tr("Cannot power down at this point in a teleportation"));
2335
2336 /* Try cancel the online snapshot. */
2337 case MachineState_OnlineSnapshotting:
2338 if (!mptrCancelableProgress.isNull())
2339 {
2340 HRESULT hrc = mptrCancelableProgress->Cancel();
2341 if (SUCCEEDED(hrc))
2342 break;
2343 }
2344 return setError(VBOX_E_INVALID_VM_STATE, tr("Cannot power down at this point in an online snapshot"));
2345
2346 /* Try cancel the live snapshot. */
2347 case MachineState_LiveSnapshotting:
2348 if (!mptrCancelableProgress.isNull())
2349 {
2350 HRESULT hrc = mptrCancelableProgress->Cancel();
2351 if (SUCCEEDED(hrc))
2352 break;
2353 }
2354 return setError(VBOX_E_INVALID_VM_STATE, tr("Cannot power down at this point in a live snapshot"));
2355
2356 /* extra nice error message for a common case */
2357 case MachineState_Saved:
2358 case MachineState_AbortedSaved:
2359 return setError(VBOX_E_INVALID_VM_STATE, tr("Cannot power down a saved virtual machine"));
2360 case MachineState_Stopping:
2361 return setError(VBOX_E_INVALID_VM_STATE, tr("The virtual machine is being powered down"));
2362 default:
2363 return setError(VBOX_E_INVALID_VM_STATE,
2364 tr("Invalid machine state: %s (must be Running, Paused or Stuck)"),
2365 Global::stringifyMachineState(mMachineState));
2366 }
2367 LogFlowThisFunc(("Initiating SHUTDOWN request...\n"));
2368
2369 /* memorize the current machine state */
2370 MachineState_T lastMachineState = mMachineState;
2371
2372#ifdef VBOX_WITH_GUEST_PROPS
2373 if (mfTurnResetIntoPowerOff)
2374 {
2375 alock.release(); /** @todo r=bird: This code introduces a race condition wrt to the state. This must be done elsewhere! */
2376 mMachine->DeleteGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw());
2377 mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw(),
2378 Bstr("PowerOff").raw(), Bstr("RDONLYGUEST").raw());
2379 mMachine->SaveSettings();
2380 alock.acquire();
2381 }
2382#endif
2383
2384 /*
2385 * Request a progress object from the server (this will set the machine state
2386 * to Stopping on the server to block others from accessing this machine).
2387 */
2388 ComPtr<IProgress> ptrProgress;
2389 HRESULT hrc = mControl->BeginPoweringDown(ptrProgress.asOutParam());
2390 if (SUCCEEDED(hrc))
2391 {
2392 /* Sync the state with the server: */
2393 i_setMachineStateLocally(MachineState_Stopping);
2394
2395 /* Create the power down task: */
2396 VMPowerDownTask *pTask = NULL;
2397 try
2398 {
2399 pTask = new VMPowerDownTask(this, ptrProgress);
2400 if (!pTask->isOk())
2401 {
2402 hrc = setError(FAILED(pTask->hrc()) ? pTask->hrc() : E_FAIL, tr("Could not create VMPowerDownTask object\n"));
2403 delete(pTask);
2404 pTask = NULL;
2405 }
2406 }
2407 catch (std::bad_alloc &)
2408 {
2409 hrc = E_OUTOFMEMORY;
2410 }
2411 if (SUCCEEDED(hrc))
2412 {
2413 hrc = pTask->createThread();
2414 if (SUCCEEDED(hrc))
2415 {
2416 ptrProgress.queryInterfaceTo(aProgress.asOutParam());
2417 LogFlowThisFunc(("LEAVE: hrc=%Rhrc\n", hrc));
2418 return hrc;
2419 }
2420 }
2421
2422 /*
2423 * Cancel the requested power down procedure.
2424 * This will reset the machine state to the state it had right
2425 * before calling mControl->BeginPoweringDown().
2426 */
2427 ErrorInfoKeeper eik;
2428 mControl->EndPoweringDown(eik.getResultCode(), eik.getText().raw());
2429 i_setMachineStateLocally(lastMachineState);
2430 }
2431 LogFlowThisFunc(("LEAVE: hrc=%Rhrc\n", hrc));
2432 return hrc;
2433}
2434
2435HRESULT Console::reset()
2436{
2437 LogFlowThisFuncEnter();
2438
2439 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2440
2441 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
2442 if ( mMachineState != MachineState_Running
2443 && mMachineState != MachineState_Teleporting
2444 && mMachineState != MachineState_LiveSnapshotting
2445 /** @todo r=bird: This should be allowed on paused VMs as well. Later. */
2446 )
2447 return i_setInvalidMachineStateError();
2448
2449 /* protect mpUVM */
2450 SafeVMPtr ptrVM(this);
2451 HRESULT hrc = ptrVM.hrc();
2452 if (SUCCEEDED(hrc))
2453 {
2454 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
2455 alock.release();
2456
2457 int vrc = ptrVM.vtable()->pfnVMR3Reset(ptrVM.rawUVM());
2458
2459 hrc = RT_SUCCESS(vrc) ? S_OK : setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not reset the machine (%Rrc)"), vrc);
2460 }
2461
2462 LogFlowThisFunc(("mMachineState=%d, hrc=%Rhrc\n", mMachineState, hrc));
2463 LogFlowThisFuncLeave();
2464 return hrc;
2465}
2466
2467/*static*/ DECLCALLBACK(int) Console::i_unplugCpu(Console *pThis, PUVM pUVM, PCVMMR3VTABLE pVMM, VMCPUID idCpu)
2468{
2469 LogFlowFunc(("pThis=%p pVM=%p idCpu=%u\n", pThis, pUVM, idCpu));
2470
2471 AssertReturn(pThis, VERR_INVALID_PARAMETER);
2472
2473 int vrc = pVMM->pfnPDMR3DeviceDetach(pUVM, "acpi", 0, idCpu, 0);
2474 Log(("UnplugCpu: vrc=%Rrc\n", vrc));
2475
2476 return vrc;
2477}
2478
2479HRESULT Console::i_doCPURemove(ULONG aCpu, PUVM pUVM, PCVMMR3VTABLE pVMM)
2480{
2481 LogFlowThisFuncEnter();
2482
2483 AutoCaller autoCaller(this);
2484 HRESULT hrc = autoCaller.hrc();
2485 if (FAILED(hrc))
2486 return hrc;
2487
2488 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2489
2490 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
2491 AssertReturn(m_pVMMDev, E_FAIL);
2492 PPDMIVMMDEVPORT pVmmDevPort = m_pVMMDev->getVMMDevPort();
2493 AssertReturn(pVmmDevPort, E_FAIL);
2494
2495 if ( mMachineState != MachineState_Running
2496 && mMachineState != MachineState_Teleporting
2497 && mMachineState != MachineState_LiveSnapshotting
2498 )
2499 return i_setInvalidMachineStateError();
2500
2501 /* Check if the CPU is present */
2502 BOOL fCpuAttached;
2503 hrc = mMachine->GetCPUStatus(aCpu, &fCpuAttached);
2504 if (FAILED(hrc))
2505 return hrc;
2506 if (!fCpuAttached)
2507 return setError(E_FAIL, tr("CPU %d is not attached"), aCpu);
2508
2509 /* Leave the lock before any EMT/VMMDev call. */
2510 alock.release();
2511 bool fLocked = true;
2512
2513 /* Check if the CPU is unlocked */
2514 PPDMIBASE pBase;
2515 int vrc = pVMM->pfnPDMR3QueryDeviceLun(pUVM, "acpi", 0, aCpu, &pBase);
2516 if (RT_SUCCESS(vrc))
2517 {
2518 Assert(pBase);
2519 PPDMIACPIPORT pApicPort = PDMIBASE_QUERY_INTERFACE(pBase, PDMIACPIPORT);
2520
2521 /* Notify the guest if possible. */
2522 uint32_t idCpuCore, idCpuPackage;
2523 vrc = pVMM->pfnVMR3GetCpuCoreAndPackageIdFromCpuId(pUVM, aCpu, &idCpuCore, &idCpuPackage); AssertRC(vrc);
2524 if (RT_SUCCESS(vrc))
2525 vrc = pVmmDevPort->pfnCpuHotUnplug(pVmmDevPort, idCpuCore, idCpuPackage);
2526 if (RT_SUCCESS(vrc))
2527 {
2528 unsigned cTries = 100;
2529 do
2530 {
2531 /* It will take some time until the event is processed in the guest. Wait... */
2532 vrc = pApicPort ? pApicPort->pfnGetCpuStatus(pApicPort, aCpu, &fLocked) : VERR_INVALID_POINTER;
2533 if (RT_SUCCESS(vrc) && !fLocked)
2534 break;
2535
2536 /* Sleep a bit */
2537 RTThreadSleep(100);
2538 } while (cTries-- > 0);
2539 }
2540 else if (vrc == VERR_VMMDEV_CPU_HOTPLUG_NOT_MONITORED_BY_GUEST)
2541 {
2542 /* Query one time. It is possible that the user ejected the CPU. */
2543 vrc = pApicPort ? pApicPort->pfnGetCpuStatus(pApicPort, aCpu, &fLocked) : VERR_INVALID_POINTER;
2544 }
2545 }
2546
2547 /* If the CPU was unlocked we can detach it now. */
2548 if (RT_SUCCESS(vrc) && !fLocked)
2549 {
2550 /*
2551 * Call worker on EMT #0, that's faster and safer than doing everything
2552 * using VMR3ReqCall.
2553 */
2554 PVMREQ pReq;
2555 vrc = pVMM->pfnVMR3ReqCallU(pUVM, 0, &pReq, 0 /* no wait! */, VMREQFLAGS_VBOX_STATUS, (PFNRT)i_unplugCpu, 4,
2556 this, pUVM, pVMM, (VMCPUID)aCpu);
2557
2558 if (vrc == VERR_TIMEOUT)
2559 vrc = pVMM->pfnVMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
2560 AssertRC(vrc);
2561 if (RT_SUCCESS(vrc))
2562 vrc = pReq->iStatus;
2563 pVMM->pfnVMR3ReqFree(pReq);
2564
2565 if (RT_SUCCESS(vrc))
2566 {
2567 /* Detach it from the VM */
2568 vrc = pVMM->pfnVMR3HotUnplugCpu(pUVM, aCpu);
2569 AssertRC(vrc);
2570 }
2571 else
2572 hrc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Hot-Remove failed (vrc=%Rrc)"), vrc);
2573 }
2574 else
2575 hrc = setErrorBoth(VBOX_E_VM_ERROR, VERR_RESOURCE_BUSY,
2576 tr("Hot-Remove was aborted because the CPU may still be used by the guest"), VERR_RESOURCE_BUSY);
2577
2578 LogFlowThisFunc(("mMachineState=%d, hrc=%Rhrc\n", mMachineState, hrc));
2579 LogFlowThisFuncLeave();
2580 return hrc;
2581}
2582
2583/*static*/ DECLCALLBACK(int) Console::i_plugCpu(Console *pThis, PUVM pUVM, PCVMMR3VTABLE pVMM, VMCPUID idCpu)
2584{
2585 LogFlowFunc(("pThis=%p uCpu=%u\n", pThis, idCpu));
2586 RT_NOREF(pThis);
2587
2588 int vrc = pVMM->pfnVMR3HotPlugCpu(pUVM, idCpu);
2589 AssertRC(vrc);
2590
2591 /** @todo r=bird: Error handling here just sucks. */
2592
2593 PCFGMNODE pInst = pVMM->pfnCFGMR3GetChild(pVMM->pfnCFGMR3GetRootU(pUVM), "Devices/acpi/0/");
2594 AssertRelease(pInst);
2595 /* nuke anything which might have been left behind. */
2596 pVMM->pfnCFGMR3RemoveNode(pVMM->pfnCFGMR3GetChildF(pInst, "LUN#%u", idCpu));
2597
2598#define RC_CHECK() do { AssertReleaseRC(vrc); } while (0)
2599
2600 PCFGMNODE pLunL0;
2601 PCFGMNODE pCfg;
2602 vrc = pVMM->pfnCFGMR3InsertNodeF(pInst, &pLunL0, "LUN#%u", idCpu); RC_CHECK();
2603 vrc = pVMM->pfnCFGMR3InsertString(pLunL0, "Driver", "ACPICpu"); RC_CHECK();
2604 vrc = pVMM->pfnCFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
2605
2606 /*
2607 * Attach the driver.
2608 */
2609 PPDMIBASE pBase;
2610 vrc = pVMM->pfnPDMR3DeviceAttach(pUVM, "acpi", 0, idCpu, 0, &pBase); RC_CHECK();
2611
2612 Log(("PlugCpu: vrc=%Rrc\n", vrc));
2613
2614 pVMM->pfnCFGMR3Dump(pInst);
2615
2616#undef RC_CHECK
2617
2618 return VINF_SUCCESS;
2619}
2620
2621HRESULT Console::i_doCPUAdd(ULONG aCpu, PUVM pUVM, PCVMMR3VTABLE pVMM)
2622{
2623 LogFlowThisFuncEnter();
2624
2625 AutoCaller autoCaller(this);
2626 HRESULT hrc = autoCaller.hrc();
2627 if (FAILED(hrc))
2628 return hrc;
2629
2630 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2631
2632 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
2633 if ( mMachineState != MachineState_Running
2634 && mMachineState != MachineState_Teleporting
2635 && mMachineState != MachineState_LiveSnapshotting
2636 /** @todo r=bird: This should be allowed on paused VMs as well. Later. */
2637 )
2638 return i_setInvalidMachineStateError();
2639
2640 AssertReturn(m_pVMMDev, E_FAIL);
2641 PPDMIVMMDEVPORT pDevPort = m_pVMMDev->getVMMDevPort();
2642 AssertReturn(pDevPort, E_FAIL);
2643
2644 /* Check if the CPU is present */
2645 BOOL fCpuAttached;
2646 hrc = mMachine->GetCPUStatus(aCpu, &fCpuAttached);
2647 if (FAILED(hrc))
2648 return hrc;
2649
2650 if (fCpuAttached)
2651 return setError(E_FAIL, tr("CPU %d is already attached"), aCpu);
2652
2653 /*
2654 * Call worker on EMT #0, that's faster and safer than doing everything
2655 * using VMR3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
2656 * here to make requests from under the lock in order to serialize them.
2657 */
2658 PVMREQ pReq;
2659 int vrc = pVMM->pfnVMR3ReqCallU(pUVM, 0, &pReq, 0 /* no wait! */, VMREQFLAGS_VBOX_STATUS, (PFNRT)i_plugCpu, 4,
2660 this, pUVM, pVMM, aCpu);
2661
2662 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
2663 alock.release();
2664
2665 if (vrc == VERR_TIMEOUT)
2666 vrc = pVMM->pfnVMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
2667 AssertRC(vrc);
2668 if (RT_SUCCESS(vrc))
2669 vrc = pReq->iStatus;
2670 pVMM->pfnVMR3ReqFree(pReq);
2671
2672 if (RT_SUCCESS(vrc))
2673 {
2674 /* Notify the guest if possible. */
2675 uint32_t idCpuCore, idCpuPackage;
2676 vrc = pVMM->pfnVMR3GetCpuCoreAndPackageIdFromCpuId(pUVM, aCpu, &idCpuCore, &idCpuPackage); AssertRC(vrc);
2677 if (RT_SUCCESS(vrc))
2678 vrc = pDevPort->pfnCpuHotPlug(pDevPort, idCpuCore, idCpuPackage);
2679 /** @todo warning if the guest doesn't support it */
2680 }
2681 else
2682 hrc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not add CPU to the machine (%Rrc)"), vrc);
2683
2684 LogFlowThisFunc(("mMachineState=%d, hrc=%Rhrc\n", mMachineState, hrc));
2685 LogFlowThisFuncLeave();
2686 return hrc;
2687}
2688
2689HRESULT Console::pause()
2690{
2691 LogFlowThisFuncEnter();
2692
2693 HRESULT hrc = i_pause(Reason_Unspecified);
2694
2695 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
2696 LogFlowThisFuncLeave();
2697 return hrc;
2698}
2699
2700HRESULT Console::resume()
2701{
2702 LogFlowThisFuncEnter();
2703
2704 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2705
2706 if (mMachineState != MachineState_Paused)
2707 return setError(VBOX_E_INVALID_VM_STATE,
2708 tr("Cannot resume the machine as it is not paused (machine state: %s)"),
2709 Global::stringifyMachineState(mMachineState));
2710
2711 HRESULT hrc = i_resume(Reason_Unspecified, alock);
2712
2713 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
2714 LogFlowThisFuncLeave();
2715 return hrc;
2716}
2717
2718HRESULT Console::powerButton()
2719{
2720 LogFlowThisFuncEnter();
2721
2722 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2723
2724 if ( mMachineState != MachineState_Running
2725 && mMachineState != MachineState_Teleporting
2726 && mMachineState != MachineState_LiveSnapshotting
2727 )
2728 return i_setInvalidMachineStateError();
2729
2730 /* get the VM handle. */
2731 SafeVMPtr ptrVM(this);
2732 HRESULT hrc = ptrVM.hrc();
2733 if (SUCCEEDED(hrc))
2734 {
2735 // no need to release lock, as there are no cross-thread callbacks
2736
2737 /* get the acpi device interface and press the button. */
2738 PPDMIBASE pBase = NULL;
2739 int vrc = ptrVM.vtable()->pfnPDMR3QueryDeviceLun(ptrVM.rawUVM(), "acpi", 0, 0, &pBase);
2740 /** @todo r=aeichner Think about a prettier way to do this without relying on hardocded device/driver names. */
2741 if (vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND) /* Try GPIO device for ARM VMs */
2742 vrc = ptrVM.vtable()->pfnPDMR3QueryDriverOnLun(ptrVM.rawUVM(), "arm-pl061-gpio", 0, 0, "GpioButton", &pBase);
2743 if (RT_SUCCESS(vrc))
2744 {
2745 Assert(pBase);
2746 PPDMIEVENTBUTTONPORT pPort = PDMIBASE_QUERY_INTERFACE(pBase, PDMIEVENTBUTTONPORT);
2747 if (pPort)
2748 vrc = pPort->pfnPowerButtonPress(pPort);
2749 else
2750 vrc = VERR_PDM_MISSING_INTERFACE;
2751 }
2752
2753 hrc = RT_SUCCESS(vrc) ? S_OK : setErrorBoth(VBOX_E_PDM_ERROR, vrc, tr("Controlled power off failed (%Rrc)"), vrc);
2754 }
2755
2756 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
2757 LogFlowThisFuncLeave();
2758 return hrc;
2759}
2760
2761HRESULT Console::getPowerButtonHandled(BOOL *aHandled)
2762{
2763 LogFlowThisFuncEnter();
2764
2765 *aHandled = FALSE;
2766
2767 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2768
2769 if ( mMachineState != MachineState_Running
2770 && mMachineState != MachineState_Teleporting
2771 && mMachineState != MachineState_LiveSnapshotting
2772 )
2773 return i_setInvalidMachineStateError();
2774
2775 /* get the VM handle. */
2776 SafeVMPtr ptrVM(this);
2777 HRESULT hrc = ptrVM.hrc();
2778 if (SUCCEEDED(hrc))
2779 {
2780 // no need to release lock, as there are no cross-thread callbacks
2781
2782 /* get the acpi device interface and check if the button press was handled. */
2783 PPDMIBASE pBase;
2784 int vrc = ptrVM.vtable()->pfnPDMR3QueryDeviceLun(ptrVM.rawUVM(), "acpi", 0, 0, &pBase);
2785 if (RT_SUCCESS(vrc))
2786 {
2787 Assert(pBase);
2788 PPDMIEVENTBUTTONPORT pPort = PDMIBASE_QUERY_INTERFACE(pBase, PDMIEVENTBUTTONPORT);
2789 if (pPort)
2790 {
2791 bool fHandled = false;
2792 vrc = pPort->pfnQueryPowerButtonHandled(pPort, &fHandled);
2793 if (RT_SUCCESS(vrc))
2794 *aHandled = fHandled;
2795 }
2796 else
2797 vrc = VERR_PDM_MISSING_INTERFACE;
2798 }
2799
2800 hrc = RT_SUCCESS(vrc) ? S_OK
2801 : setErrorBoth(VBOX_E_PDM_ERROR, vrc,
2802 tr("Checking if the ACPI Power Button event was handled by the guest OS failed (%Rrc)"), vrc);
2803
2804 }
2805 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
2806 LogFlowThisFuncLeave();
2807 return hrc;
2808}
2809
2810HRESULT Console::getGuestEnteredACPIMode(BOOL *aEntered)
2811{
2812 LogFlowThisFuncEnter();
2813
2814 *aEntered = FALSE;
2815
2816 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2817
2818 if ( mMachineState != MachineState_Running
2819 && mMachineState != MachineState_Teleporting
2820 && mMachineState != MachineState_LiveSnapshotting
2821 )
2822 return setError(VBOX_E_INVALID_VM_STATE,
2823 tr("Invalid machine state %s when checking if the guest entered the ACPI mode"),
2824 Global::stringifyMachineState(mMachineState));
2825
2826 /* get the VM handle. */
2827 SafeVMPtr ptrVM(this);
2828 HRESULT hrc = ptrVM.hrc();
2829 if (SUCCEEDED(hrc))
2830 {
2831 // no need to release lock, as there are no cross-thread callbacks
2832
2833 /* get the acpi device interface and query the information. */
2834 PPDMIBASE pBase;
2835 int vrc = ptrVM.vtable()->pfnPDMR3QueryDeviceLun(ptrVM.rawUVM(), "acpi", 0, 0, &pBase);
2836 if (RT_SUCCESS(vrc))
2837 {
2838 Assert(pBase);
2839 PPDMIACPIPORT pPort = PDMIBASE_QUERY_INTERFACE(pBase, PDMIACPIPORT);
2840 if (pPort)
2841 {
2842 bool fEntered = false;
2843 vrc = pPort->pfnGetGuestEnteredACPIMode(pPort, &fEntered);
2844 if (RT_SUCCESS(vrc))
2845 *aEntered = fEntered;
2846 }
2847 else
2848 vrc = VERR_PDM_MISSING_INTERFACE;
2849 }
2850
2851 if (vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND)
2852 {
2853 /* Might be an ARM VM. */
2854 /** @todo r=aeichner Think about a prettier way to do this without relying on hardocded device/driver names,
2855 * and this shouldn't be here as it is not about ACPI but needs a dedicated interface. */
2856 vrc = ptrVM.vtable()->pfnPDMR3QueryDriverOnLun(ptrVM.rawUVM(), "arm-pl061-gpio", 0, 0, "GpioButton", &pBase);
2857 if (RT_SUCCESS(vrc))
2858 {
2859 Assert(pBase);
2860 PPDMIEVENTBUTTONPORT pPort = PDMIBASE_QUERY_INTERFACE(pBase, PDMIEVENTBUTTONPORT);
2861 if (pPort)
2862 {
2863 bool fEntered = false;
2864 vrc = pPort->pfnQueryGuestCanHandleButtonEvents(pPort, &fEntered);
2865 if (RT_SUCCESS(vrc))
2866 *aEntered = fEntered;
2867 }
2868 else
2869 vrc = VERR_PDM_MISSING_INTERFACE;
2870 }
2871 }
2872 }
2873
2874 LogFlowThisFuncLeave();
2875 return hrc;
2876}
2877
2878HRESULT Console::sleepButton()
2879{
2880 LogFlowThisFuncEnter();
2881
2882 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2883
2884 if ( mMachineState != MachineState_Running
2885 && mMachineState != MachineState_Teleporting
2886 && mMachineState != MachineState_LiveSnapshotting)
2887 return i_setInvalidMachineStateError();
2888
2889 /* get the VM handle. */
2890 SafeVMPtr ptrVM(this);
2891 HRESULT hrc = ptrVM.hrc();
2892 if (SUCCEEDED(hrc))
2893 {
2894 // no need to release lock, as there are no cross-thread callbacks
2895
2896 /* get the acpi device interface and press the sleep button. */
2897 PPDMIBASE pBase = NULL;
2898 int vrc = ptrVM.vtable()->pfnPDMR3QueryDeviceLun(ptrVM.rawUVM(), "acpi", 0, 0, &pBase);
2899 /** @todo r=aeichner Think about a prettier way to do this without relying on hardocded device/driver names. */
2900 if (vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND) /* Try GPIO device for ARM VMs */
2901 vrc = ptrVM.vtable()->pfnPDMR3QueryDriverOnLun(ptrVM.rawUVM(), "arm-pl061-gpio", 0, 0, "GpioButton", &pBase);
2902 if (RT_SUCCESS(vrc))
2903 {
2904 Assert(pBase);
2905 PPDMIEVENTBUTTONPORT pPort = PDMIBASE_QUERY_INTERFACE(pBase, PDMIEVENTBUTTONPORT);
2906 if (pPort)
2907 vrc = pPort->pfnSleepButtonPress(pPort);
2908 else
2909 vrc = VERR_PDM_MISSING_INTERFACE;
2910 }
2911
2912 hrc = RT_SUCCESS(vrc) ? S_OK : setErrorBoth(VBOX_E_PDM_ERROR, vrc, tr("Sending sleep button event failed (%Rrc)"), vrc);
2913 }
2914
2915 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
2916 LogFlowThisFuncLeave();
2917 return hrc;
2918}
2919
2920/**
2921 * Refreshes the maLedTypes and muLedTypeGen members.
2922 */
2923HRESULT Console::i_refreshLedTypeArrays(AutoReadLock *pReadLock)
2924{
2925 pReadLock->release();
2926 AutoWriteLock alock(mLedLock COMMA_LOCKVAL_SRC_POS);
2927
2928 /*
2929 * Check that the refresh was already done by someone else while we
2930 * acquired the write lock.
2931 */
2932 if (muLedTypeGen != muLedGen)
2933 {
2934 /*
2935 * Reset the data.
2936 */
2937 for (size_t idxType = 0; idxType < RT_ELEMENTS(maLedTypes); idxType++)
2938 maLedTypes[idxType].cLeds = 0;
2939
2940 /*
2941 * Rebuild the data.
2942 */
2943 for (uint32_t idxSet = 0; idxSet < mcLedSets; idxSet++)
2944 {
2945 PLEDSET const pLS = &maLedSets[idxSet];
2946 uint32_t const cLeds = pLS->cLeds;
2947 PPDMLED volatile * const papSrcLeds = pLS->papLeds;
2948 DeviceType_T * const paSubTypes = pLS->paSubTypes;
2949 for (uint32_t idxLed = 0; idxLed < cLeds; idxLed++)
2950 {
2951 /** @todo If we make Console::i_drvStatus_UnitChanged() modify the generation
2952 * too, we could skip NULL entries here and make it a bit more compact.
2953 * OTOH, most unused LED entires have a paSubTypes of DeviceType_Null. */
2954 DeviceType_T enmType = paSubTypes ? paSubTypes[idxLed] : (DeviceType_T)(ASMBitFirstSetU32(pLS->fTypes) - 1);
2955 if (enmType > DeviceType_Null && enmType < DeviceType_End)
2956 {
2957 uint32_t const idxLedType = maLedTypes[enmType].cLeds;
2958 if (idxLedType >= maLedTypes[enmType].cAllocated)
2959 {
2960 void *pvNew = RTMemRealloc(maLedTypes[enmType].pappLeds,
2961 sizeof(maLedTypes[0].pappLeds[0]) * (idxLedType + 16));
2962 if (!pvNew)
2963 return E_OUTOFMEMORY;
2964 maLedTypes[enmType].pappLeds = (PPDMLED volatile **)pvNew;
2965 maLedTypes[enmType].cAllocated = idxLedType + 16;
2966 }
2967 maLedTypes[enmType].pappLeds[idxLedType] = &papSrcLeds[idxLed];
2968 maLedTypes[enmType].cLeds = idxLedType + 1;
2969 }
2970 }
2971 }
2972 muLedTypeGen = muLedGen;
2973 }
2974
2975 /*
2976 * We have to release the write lock before re-acquiring the read-lock.
2977 *
2978 * This means there is a theoretical race here, however we ASSUME that
2979 * LED sets are never removed and therefore we will be just fine
2980 * accessing slightly dated per-type data.
2981 */
2982 alock.release();
2983 pReadLock->acquire();
2984 return S_OK;
2985}
2986
2987/** read the value of a LED. */
2988DECLINLINE(uint32_t) readAndClearLed(PPDMLED pLed)
2989{
2990 if (!pLed)
2991 return 0;
2992 uint32_t u32 = pLed->Actual.u32 | pLed->Asserted.u32;
2993 pLed->Asserted.u32 = 0;
2994 return u32;
2995}
2996
2997HRESULT Console::getDeviceActivity(const std::vector<DeviceType_T> &aType, std::vector<DeviceActivity_T> &aActivity)
2998{
2999 /*
3000 * Make a roadmap of which DeviceType_T LED types are wanted.
3001 *
3002 * Note! This approach means we'll return the same values in aActivity for
3003 * duplicate aType entries.
3004 */
3005 uint32_t fRequestedTypes = 0;
3006 AssertCompile(DeviceType_End <= 32);
3007
3008 for (size_t iType = 0; iType < aType.size(); ++iType)
3009 {
3010 DeviceType_T const enmType = aType[iType];
3011 AssertCompile((unsigned)DeviceType_Null == 0 /* first */);
3012 AssertReturn(enmType > DeviceType_Null && enmType < DeviceType_End,
3013 setError(E_INVALIDARG, tr("Invalid DeviceType for getDeviceActivity in entry #%u: %d"), iType, enmType));
3014 fRequestedTypes |= RT_BIT_32((unsigned)enmType);
3015 }
3016
3017 /*
3018 * Resize the result vector before making changes (may throw, paranoia).
3019 */
3020 aActivity.resize(aType.size());
3021
3022 /*
3023 * Accumulate the per-type data for all the requested types.
3024 * We will lazily refresh the per-type data collection here when needed.
3025 */
3026 PDMLEDCORE aLEDs[DeviceType_End] = { {0} };
3027 Assert(aLEDs[1].u32 == 0 && aLEDs[DeviceType_End / 2].u32 == 0 && aLEDs[DeviceType_End - 1].u32 == 0); /* paranoia */
3028 {
3029 AutoReadLock alock(mLedLock COMMA_LOCKVAL_SRC_POS);
3030 if (RT_LIKELY(muLedGen == muLedTypeGen))
3031 { /* likely */ }
3032 else
3033 {
3034 HRESULT hrc = i_refreshLedTypeArrays(&alock);
3035 if (FAILED(hrc))
3036 return hrc;
3037 }
3038
3039 AssertCompile((unsigned)DeviceType_Null == 0 /* we skip this one */);
3040 for (uint32_t idxType = 1; idxType < RT_ELEMENTS(maLedTypes); idxType++)
3041 if (fRequestedTypes & RT_BIT_32(idxType))
3042 {
3043 uint32_t const cLeds = maLedTypes[idxType].cLeds;
3044 PPDMLED volatile ** const pappSrcLeds = maLedTypes[idxType].pappLeds;
3045 for (size_t iLed = 0; iLed < cLeds; iLed++)
3046 aLEDs[idxType].u32 |= readAndClearLed(*pappSrcLeds[iLed]);
3047 }
3048 }
3049
3050 /*
3051 * Compose the result vector:
3052 */
3053 for (size_t iType = 0; iType < aActivity.size(); ++iType)
3054 {
3055 switch (aLEDs[aType[iType]].u32 & (PDMLED_READING | PDMLED_WRITING))
3056 {
3057 case 0:
3058 aActivity[iType] = DeviceActivity_Idle;
3059 break;
3060 case PDMLED_READING:
3061 aActivity[iType] = DeviceActivity_Reading;
3062 break;
3063 case PDMLED_WRITING:
3064 case PDMLED_READING | PDMLED_WRITING:
3065 aActivity[iType] = DeviceActivity_Writing;
3066 break;
3067 }
3068 }
3069
3070 return S_OK;
3071}
3072
3073HRESULT Console::attachUSBDevice(const com::Guid &aId, const com::Utf8Str &aCaptureFilename)
3074{
3075#ifdef VBOX_WITH_USB
3076 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3077
3078 if ( mMachineState != MachineState_Running
3079 && mMachineState != MachineState_Paused)
3080 return setError(VBOX_E_INVALID_VM_STATE,
3081 tr("Cannot attach a USB device to the machine which is not running or paused (machine state: %s)"),
3082 Global::stringifyMachineState(mMachineState));
3083
3084 /* Get the VM handle. */
3085 SafeVMPtr ptrVM(this);
3086 HRESULT hrc = ptrVM.hrc();
3087 if (SUCCEEDED(hrc))
3088 {
3089 /* Don't proceed unless we have a USB controller. */
3090 if (mfVMHasUsbController)
3091 {
3092 /* release the lock because the USB Proxy service may call us back
3093 * (via onUSBDeviceAttach()) */
3094 alock.release();
3095
3096 /* Request the device capture */
3097 hrc = mControl->CaptureUSBDevice(Bstr(aId.toString()).raw(), Bstr(aCaptureFilename).raw());
3098 }
3099 else
3100 hrc = setError(VBOX_E_PDM_ERROR, tr("The virtual machine does not have a USB controller"));
3101 }
3102 return hrc;
3103
3104#else /* !VBOX_WITH_USB */
3105 RT_NOREF(aId, aCaptureFilename);
3106 return setError(VBOX_E_PDM_ERROR, tr("The virtual machine does not have a USB controller"));
3107#endif /* !VBOX_WITH_USB */
3108}
3109
3110HRESULT Console::detachUSBDevice(const com::Guid &aId, ComPtr<IUSBDevice> &aDevice)
3111{
3112 RT_NOREF(aDevice);
3113#ifdef VBOX_WITH_USB
3114 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3115
3116 /* Find it. */
3117 for (USBDeviceList::iterator it = mUSBDevices.begin(); it != mUSBDevices.end(); ++it)
3118 if ((*it)->i_id() == aId)
3119 {
3120 /* Found it! */
3121 ComObjPtr<OUSBDevice> pUSBDevice(*it);
3122
3123 /* Remove the device from the collection, it is re-added below for failures */
3124 mUSBDevices.erase(it);
3125
3126 /*
3127 * Inform the USB device and USB proxy about what's cooking.
3128 */
3129 alock.release();
3130 HRESULT hrc = mControl->DetachUSBDevice(Bstr(aId.toString()).raw(), false /* aDone */);
3131 if (SUCCEEDED(hrc))
3132 {
3133 /* Request the PDM to detach the USB device. */
3134 hrc = i_detachUSBDevice(pUSBDevice);
3135 if (SUCCEEDED(hrc))
3136 {
3137 //return the detached USB device
3138 pUSBDevice.queryInterfaceTo(aDevice.asOutParam());
3139 /* Request the device release. Even if it fails, the device will
3140 * remain as held by proxy, which is OK for us (the VM process). */
3141 return mControl->DetachUSBDevice(Bstr(aId.toString()).raw(), true /* aDone */);
3142 }
3143 }
3144
3145 /* Re-add the device to the collection */
3146 alock.acquire();
3147 mUSBDevices.push_back(pUSBDevice);
3148 return hrc;
3149 }
3150
3151 return setError(E_INVALIDARG, tr("USB device with UUID {%RTuuid} is not attached to this machine"), aId.raw());
3152
3153#else /* !VBOX_WITH_USB */
3154 RT_NOREF(aId, aDevice);
3155 return setError(VBOX_E_PDM_ERROR, tr("The virtual machine does not have a USB controller"));
3156#endif /* !VBOX_WITH_USB */
3157}
3158
3159
3160HRESULT Console::findUSBDeviceByAddress(const com::Utf8Str &aName, ComPtr<IUSBDevice> &aDevice)
3161{
3162#ifdef VBOX_WITH_USB
3163 aDevice = NULL;
3164
3165 SafeIfaceArray<IUSBDevice> devsvec;
3166 HRESULT hrc = COMGETTER(USBDevices)(ComSafeArrayAsOutParam(devsvec));
3167 if (FAILED(hrc))
3168 return hrc;
3169
3170 for (size_t i = 0; i < devsvec.size(); ++i)
3171 {
3172 Bstr bstrAddress;
3173 hrc = devsvec[i]->COMGETTER(Address)(bstrAddress.asOutParam());
3174 if (FAILED(hrc))
3175 return hrc;
3176 if (bstrAddress == aName)
3177 {
3178 ComObjPtr<OUSBDevice> pUSBDevice;
3179 pUSBDevice.createObject();
3180 pUSBDevice->init(devsvec[i]);
3181 return pUSBDevice.queryInterfaceTo(aDevice.asOutParam());
3182 }
3183 }
3184
3185 return setErrorNoLog(VBOX_E_OBJECT_NOT_FOUND, tr("Could not find a USB device with address '%s'"), aName.c_str());
3186
3187#else /* !VBOX_WITH_USB */
3188 RT_NOREF(aName, aDevice);
3189 return E_NOTIMPL;
3190#endif /* !VBOX_WITH_USB */
3191}
3192
3193HRESULT Console::findUSBDeviceById(const com::Guid &aId, ComPtr<IUSBDevice> &aDevice)
3194{
3195#ifdef VBOX_WITH_USB
3196 aDevice = NULL;
3197
3198 SafeIfaceArray<IUSBDevice> devsvec;
3199 HRESULT hrc = COMGETTER(USBDevices)(ComSafeArrayAsOutParam(devsvec));
3200 if (FAILED(hrc))
3201 return hrc;
3202
3203 Utf8Str const strId = aId.toString();
3204 for (size_t i = 0; i < devsvec.size(); ++i)
3205 {
3206 Bstr id;
3207 hrc = devsvec[i]->COMGETTER(Id)(id.asOutParam());
3208 if (FAILED(hrc))
3209 return hrc;
3210 if (id == strId)
3211 {
3212 ComObjPtr<OUSBDevice> pUSBDevice;
3213 pUSBDevice.createObject();
3214 pUSBDevice->init(devsvec[i]);
3215 ComObjPtr<IUSBDevice> iUSBDevice = static_cast <ComObjPtr<IUSBDevice> > (pUSBDevice);
3216 return iUSBDevice.queryInterfaceTo(aDevice.asOutParam());
3217 }
3218 }
3219
3220 return setErrorNoLog(VBOX_E_OBJECT_NOT_FOUND, tr("Could not find a USB device with uuid {%RTuuid}"), aId.raw());
3221
3222#else /* !VBOX_WITH_USB */
3223 RT_NOREF(aId, aDevice);
3224 return E_NOTIMPL;
3225#endif /* !VBOX_WITH_USB */
3226}
3227
3228HRESULT Console::createSharedFolder(const com::Utf8Str &aName, const com::Utf8Str &aHostPath, BOOL aWritable,
3229 BOOL aAutomount, const com::Utf8Str &aAutoMountPoint)
3230{
3231 LogFlowThisFunc(("Entering for '%s' -> '%s'\n", aName.c_str(), aHostPath.c_str()));
3232
3233 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3234
3235 /// @todo see @todo in AttachUSBDevice() about the Paused state
3236 if (mMachineState == MachineState_Saved || mMachineState == MachineState_AbortedSaved)
3237 return setError(VBOX_E_INVALID_VM_STATE,
3238 tr("Cannot create a transient shared folder on a machine in a saved state (machine state: %s)"),
3239 Global::stringifyMachineState(mMachineState));
3240 if ( mMachineState != MachineState_PoweredOff
3241 && mMachineState != MachineState_Teleported
3242 && mMachineState != MachineState_Aborted
3243 && mMachineState != MachineState_Running
3244 && mMachineState != MachineState_Paused
3245 )
3246 return setError(VBOX_E_INVALID_VM_STATE,
3247 tr("Cannot create a transient shared folder on the machine while it is changing the state (machine state: %s)"),
3248 Global::stringifyMachineState(mMachineState));
3249
3250 ComObjPtr<ConsoleSharedFolder> pSharedFolder;
3251 HRESULT hrc = i_findSharedFolder(aName, pSharedFolder, false /* aSetError */);
3252 if (SUCCEEDED(hrc))
3253 return setError(VBOX_E_FILE_ERROR, tr("Shared folder named '%s' already exists"), aName.c_str());
3254
3255 pSharedFolder.createObject();
3256 hrc = pSharedFolder->init(this,
3257 aName,
3258 aHostPath,
3259 !!aWritable,
3260 !!aAutomount,
3261 aAutoMountPoint,
3262 true /* fFailOnError */);
3263 if (FAILED(hrc))
3264 return hrc;
3265
3266 /* If the VM is online and supports shared folders, share this folder
3267 * under the specified name. (Ignore any failure to obtain the VM handle.) */
3268 SafeVMPtrQuiet ptrVM(this);
3269 if ( ptrVM.isOk()
3270 && m_pVMMDev
3271 && m_pVMMDev->isShFlActive()
3272 )
3273 {
3274 /* first, remove the machine or the global folder if there is any */
3275 SharedFolderDataMap::const_iterator it;
3276 if (i_findOtherSharedFolder(aName, it))
3277 {
3278 hrc = i_removeSharedFolder(aName);
3279 if (FAILED(hrc))
3280 return hrc;
3281 }
3282
3283 /* second, create the given folder */
3284 hrc = i_createSharedFolder(aName, SharedFolderData(aHostPath, !!aWritable, !!aAutomount, aAutoMountPoint));
3285 if (FAILED(hrc))
3286 return hrc;
3287 }
3288
3289 m_mapSharedFolders.insert(std::make_pair(aName, pSharedFolder));
3290
3291 /* Notify console callbacks after the folder is added to the list. */
3292 alock.release();
3293 ::FireSharedFolderChangedEvent(mEventSource, Scope_Session);
3294
3295 LogFlowThisFunc(("Leaving for '%s' -> '%s'\n", aName.c_str(), aHostPath.c_str()));
3296
3297 return hrc;
3298}
3299
3300HRESULT Console::removeSharedFolder(const com::Utf8Str &aName)
3301{
3302 LogFlowThisFunc(("Entering for '%s'\n", aName.c_str()));
3303
3304 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3305
3306 /// @todo see @todo in AttachUSBDevice() about the Paused state
3307 if (mMachineState == MachineState_Saved || mMachineState == MachineState_AbortedSaved)
3308 return setError(VBOX_E_INVALID_VM_STATE,
3309 tr("Cannot remove a transient shared folder from a machine in a saved state (machine state: %s)"),
3310 Global::stringifyMachineState(mMachineState));;
3311 if ( mMachineState != MachineState_PoweredOff
3312 && mMachineState != MachineState_Teleported
3313 && mMachineState != MachineState_Aborted
3314 && mMachineState != MachineState_Running
3315 && mMachineState != MachineState_Paused
3316 )
3317 return setError(VBOX_E_INVALID_VM_STATE,
3318 tr("Cannot remove a transient shared folder from the machine while it is changing the state (machine state: %s)"),
3319 Global::stringifyMachineState(mMachineState));
3320
3321 ComObjPtr<ConsoleSharedFolder> pSharedFolder;
3322 HRESULT hrc = i_findSharedFolder(aName, pSharedFolder, true /* aSetError */);
3323 if (FAILED(hrc))
3324 return hrc;
3325
3326 /* protect the VM handle (if not NULL) */
3327 SafeVMPtrQuiet ptrVM(this);
3328 if ( ptrVM.isOk()
3329 && m_pVMMDev
3330 && m_pVMMDev->isShFlActive()
3331 )
3332 {
3333 /* if the VM is online and supports shared folders, UNshare this folder. */
3334
3335 /* first, remove the given folder */
3336 hrc = i_removeSharedFolder(aName);
3337 if (FAILED(hrc))
3338 return hrc;
3339
3340 /* first, remove the machine or the global folder if there is any */
3341 SharedFolderDataMap::const_iterator it;
3342 if (i_findOtherSharedFolder(aName, it))
3343 {
3344 hrc = i_createSharedFolder(aName, it->second);
3345 /* don't check hrc here because we need to remove the console
3346 * folder from the collection even on failure */
3347 }
3348 }
3349
3350 m_mapSharedFolders.erase(aName);
3351
3352 /* Notify console callbacks after the folder is removed from the list. */
3353 alock.release();
3354 ::FireSharedFolderChangedEvent(mEventSource, Scope_Session);
3355
3356 LogFlowThisFunc(("Leaving for '%s'\n", aName.c_str()));
3357
3358 return hrc;
3359}
3360
3361HRESULT Console::addEncryptionPassword(const com::Utf8Str &aId, const com::Utf8Str &aPassword,
3362 BOOL aClearOnSuspend)
3363{
3364 if ( aId.isEmpty()
3365 || aPassword.isEmpty())
3366 return setError(E_FAIL, tr("The ID and password must be both valid"));
3367
3368 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3369
3370 HRESULT hrc = S_OK;
3371 size_t cbKey = aPassword.length() + 1; /* Include terminator */
3372 const uint8_t *pbKey = (const uint8_t *)aPassword.c_str();
3373
3374 int vrc = m_pKeyStore->addSecretKey(aId, pbKey, cbKey);
3375 if ( RT_SUCCESS(vrc)
3376#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
3377 || vrc == VERR_ALREADY_EXISTS /* Allow setting an existing key for encrypted VMs. */
3378#endif
3379 )
3380 {
3381 unsigned cDisksConfigured = 0;
3382
3383#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
3384 if (mptrNvramStore.isNotNull())
3385 mptrNvramStore->i_addPassword(aId, aPassword);
3386
3387 SecretKey *pKey = NULL;
3388 vrc = m_pKeyStore->retainSecretKey(aId, &pKey);
3389 AssertRCReturn(vrc, E_FAIL);
3390 pKey->setRemoveOnSuspend(!!aClearOnSuspend);
3391 pKey->release();
3392#endif
3393
3394 hrc = i_configureEncryptionForDisk(aId, &cDisksConfigured);
3395 if (SUCCEEDED(hrc))
3396 {
3397#ifndef VBOX_WITH_FULL_VM_ENCRYPTION
3398 SecretKey *pKey = NULL;
3399#endif
3400 vrc = m_pKeyStore->retainSecretKey(aId, &pKey);
3401 AssertRCReturn(vrc, E_FAIL);
3402
3403 pKey->setUsers(cDisksConfigured);
3404#ifndef VBOX_WITH_FULL_VM_ENCRYPTION
3405 pKey->setRemoveOnSuspend(!!aClearOnSuspend);
3406 m_pKeyStore->releaseSecretKey(aId);
3407#endif
3408 m_cDisksPwProvided += cDisksConfigured;
3409
3410 if ( m_cDisksPwProvided == m_cDisksEncrypted
3411 && mMachineState == MachineState_Paused)
3412 {
3413 /* get the VM handle. */
3414 SafeVMPtr ptrVM(this);
3415 if (!ptrVM.isOk())
3416 return ptrVM.hrc();
3417
3418 alock.release();
3419 vrc = ptrVM.vtable()->pfnVMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_RECONFIG);
3420
3421 hrc = RT_SUCCESS(vrc) ? S_OK
3422 : setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not resume the machine execution (%Rrc)"), vrc);
3423 }
3424 }
3425 }
3426#ifndef VBOX_WITH_FULL_VM_ENCRYPTION
3427 else if (vrc == VERR_ALREADY_EXISTS)
3428 hrc = setErrorBoth(VBOX_E_OBJECT_IN_USE, vrc, tr("A password with the given ID already exists"));
3429#endif
3430 else if (vrc == VERR_NO_MEMORY)
3431 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to allocate enough secure memory for the key"));
3432 else
3433 hrc = setErrorBoth(E_FAIL, vrc, tr("Unknown error happened while adding a password (%Rrc)"), vrc);
3434
3435 return hrc;
3436}
3437
3438HRESULT Console::addEncryptionPasswords(const std::vector<com::Utf8Str> &aIds, const std::vector<com::Utf8Str> &aPasswords,
3439 BOOL aClearOnSuspend)
3440{
3441 HRESULT hrc = S_OK;
3442
3443 if ( aIds.empty()
3444 || aPasswords.empty())
3445 return setError(E_FAIL, tr("IDs and passwords must not be empty"));
3446
3447 if (aIds.size() != aPasswords.size())
3448 return setError(E_FAIL, tr("The number of entries in the id and password arguments must match"));
3449
3450 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3451
3452#ifndef VBOX_WITH_FULL_VM_ENCRYPTION
3453 /* Check that the IDs do not exist already before changing anything. */
3454 for (unsigned i = 0; i < aIds.size(); i++)
3455 {
3456 SecretKey *pKey = NULL;
3457 int vrc = m_pKeyStore->retainSecretKey(aIds[i], &pKey);
3458 if (vrc != VERR_NOT_FOUND)
3459 {
3460 AssertPtr(pKey);
3461 if (pKey)
3462 pKey->release();
3463 return setError(VBOX_E_OBJECT_IN_USE, tr("A password with the given ID already exists"));
3464 }
3465 }
3466#else
3467 /*
3468 * Passwords for the same ID can be added in different ways because
3469 * of encrypted VMs now. Just add them instead of generating an error.
3470 */
3471 /** @todo Check that passwords with the same ID match. */
3472#endif
3473
3474 for (unsigned i = 0; i < aIds.size(); i++)
3475 {
3476 hrc = addEncryptionPassword(aIds[i], aPasswords[i], aClearOnSuspend);
3477 if (FAILED(hrc))
3478 {
3479 /*
3480 * Try to remove already successfully added passwords from the map to not
3481 * change the state of the Console object.
3482 */
3483 ErrorInfoKeeper eik; /* Keep current error info or it gets deestroyed in the IPC methods below. */
3484 for (unsigned ii = 0; ii < i; ii++)
3485 {
3486 i_clearDiskEncryptionKeysOnAllAttachmentsWithKeyId(aIds[ii]);
3487 removeEncryptionPassword(aIds[ii]);
3488 }
3489
3490 break;
3491 }
3492 }
3493
3494 return hrc;
3495}
3496
3497HRESULT Console::removeEncryptionPassword(const com::Utf8Str &aId)
3498{
3499 if (aId.isEmpty())
3500 return setError(E_FAIL, tr("The ID must be valid"));
3501
3502 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3503
3504 SecretKey *pKey = NULL;
3505 int vrc = m_pKeyStore->retainSecretKey(aId, &pKey);
3506 if (RT_SUCCESS(vrc))
3507 {
3508 m_cDisksPwProvided -= pKey->getUsers();
3509 m_pKeyStore->releaseSecretKey(aId);
3510 vrc = m_pKeyStore->deleteSecretKey(aId);
3511 AssertRCReturn(vrc, E_FAIL);
3512
3513#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
3514 if (mptrNvramStore.isNotNull())
3515 mptrNvramStore->i_removePassword(aId);
3516#endif
3517 }
3518 else if (vrc == VERR_NOT_FOUND)
3519 return setErrorBoth(VBOX_E_OBJECT_NOT_FOUND, vrc, tr("A password with the ID \"%s\" does not exist"), aId.c_str());
3520 else
3521 return setErrorBoth(E_FAIL, vrc, tr("Failed to remove password with ID \"%s\" (%Rrc)"), aId.c_str(), vrc);
3522
3523 return S_OK;
3524}
3525
3526HRESULT Console::clearAllEncryptionPasswords()
3527{
3528 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3529
3530#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
3531 if (mptrNvramStore.isNotNull())
3532 mptrNvramStore->i_removeAllPasswords();
3533#endif
3534
3535 int vrc = m_pKeyStore->deleteAllSecretKeys(false /* fSuspend */, false /* fForce */);
3536 if (vrc == VERR_RESOURCE_IN_USE)
3537 return setErrorBoth(VBOX_E_OBJECT_IN_USE, vrc, tr("A password is still in use by the VM"));
3538 else if (RT_FAILURE(vrc))
3539 return setErrorBoth(E_FAIL, vrc, tr("Deleting all passwords failed (%Rrc)"));
3540
3541 m_cDisksPwProvided = 0;
3542 return S_OK;
3543}
3544
3545// Non-interface public methods
3546/////////////////////////////////////////////////////////////////////////////
3547
3548/*static*/
3549HRESULT Console::i_setErrorStatic(HRESULT aResultCode, const char *pcsz, ...)
3550{
3551 va_list args;
3552 va_start(args, pcsz);
3553 HRESULT hrc = setErrorInternalV(aResultCode,
3554 getStaticClassIID(),
3555 getStaticComponentName(),
3556 pcsz, args,
3557 false /* aWarning */,
3558 true /* aLogIt */);
3559 va_end(args);
3560 return hrc;
3561}
3562
3563/*static*/
3564HRESULT Console::i_setErrorStaticBoth(HRESULT aResultCode, int vrc, const char *pcsz, ...)
3565{
3566 va_list args;
3567 va_start(args, pcsz);
3568 HRESULT hrc = setErrorInternalV(aResultCode,
3569 getStaticClassIID(),
3570 getStaticComponentName(),
3571 pcsz, args,
3572 false /* aWarning */,
3573 true /* aLogIt */,
3574 vrc);
3575 va_end(args);
3576 return hrc;
3577}
3578
3579HRESULT Console::i_setInvalidMachineStateError()
3580{
3581 return setError(VBOX_E_INVALID_VM_STATE,
3582 tr("Invalid machine state: %s"),
3583 Global::stringifyMachineState(mMachineState));
3584}
3585
3586
3587/**
3588 * Converts to PDM device names.
3589 */
3590/* static */ const char *Console::i_storageControllerTypeToStr(StorageControllerType_T enmCtrlType)
3591{
3592 switch (enmCtrlType)
3593 {
3594 case StorageControllerType_LsiLogic:
3595 return "lsilogicscsi";
3596 case StorageControllerType_BusLogic:
3597 return "buslogic";
3598 case StorageControllerType_LsiLogicSas:
3599 return "lsilogicsas";
3600 case StorageControllerType_IntelAhci:
3601 return "ahci";
3602 case StorageControllerType_PIIX3:
3603 case StorageControllerType_PIIX4:
3604 case StorageControllerType_ICH6:
3605 return "piix3ide";
3606 case StorageControllerType_I82078:
3607 return "i82078";
3608 case StorageControllerType_USB:
3609 return "Msd";
3610 case StorageControllerType_NVMe:
3611 return "nvme";
3612 case StorageControllerType_VirtioSCSI:
3613 return "virtio-scsi";
3614 default:
3615 return NULL;
3616 }
3617}
3618
3619HRESULT Console::i_storageBusPortDeviceToLun(StorageBus_T enmBus, LONG port, LONG device, unsigned &uLun)
3620{
3621 switch (enmBus)
3622 {
3623 case StorageBus_IDE:
3624 case StorageBus_Floppy:
3625 {
3626 AssertMsgReturn(port < 2 && port >= 0, ("%d\n", port), E_INVALIDARG);
3627 AssertMsgReturn(device < 2 && device >= 0, ("%d\n", device), E_INVALIDARG);
3628 uLun = 2 * port + device;
3629 return S_OK;
3630 }
3631 case StorageBus_SATA:
3632 case StorageBus_SCSI:
3633 case StorageBus_SAS:
3634 case StorageBus_PCIe:
3635 case StorageBus_VirtioSCSI:
3636 {
3637 uLun = port;
3638 return S_OK;
3639 }
3640 case StorageBus_USB:
3641 {
3642 /*
3643 * It is always the first lun, the port denotes the device instance
3644 * for the Msd device.
3645 */
3646 uLun = 0;
3647 return S_OK;
3648 }
3649 default:
3650 uLun = 0;
3651 AssertMsgFailedReturn(("%d\n", enmBus), E_INVALIDARG);
3652 }
3653}
3654
3655// private methods
3656/////////////////////////////////////////////////////////////////////////////
3657
3658/**
3659 * Suspend the VM before we do any medium or network attachment change.
3660 *
3661 * @param pUVM Safe VM handle.
3662 * @param pVMM Safe VMM vtable.
3663 * @param pAlock The automatic lock instance. This is for when we have
3664 * to leave it in order to avoid deadlocks.
3665 * @param pfResume where to store the information if we need to resume
3666 * afterwards.
3667 */
3668HRESULT Console::i_suspendBeforeConfigChange(PUVM pUVM, PCVMMR3VTABLE pVMM, AutoWriteLock *pAlock, bool *pfResume)
3669{
3670 *pfResume = false;
3671
3672 VMSTATE enmVMState = pVMM->pfnVMR3GetStateU(pUVM);
3673 switch (enmVMState)
3674 {
3675 case VMSTATE_RUNNING:
3676 case VMSTATE_RESETTING:
3677 case VMSTATE_SOFT_RESETTING:
3678 {
3679 LogFlowFunc(("Suspending the VM...\n"));
3680 /* disable the callback to prevent Console-level state change */
3681 mVMStateChangeCallbackDisabled = true;
3682 if (pAlock)
3683 pAlock->release();
3684 int vrc = pVMM->pfnVMR3Suspend(pUVM, VMSUSPENDREASON_RECONFIG);
3685 if (pAlock)
3686 pAlock->acquire();
3687 mVMStateChangeCallbackDisabled = false;
3688 if (RT_FAILURE(vrc))
3689 return setErrorInternalF(VBOX_E_INVALID_VM_STATE,
3690 COM_IIDOF(IConsole),
3691 getStaticComponentName(),
3692 false /*aWarning*/,
3693 true /*aLogIt*/,
3694 vrc,
3695 tr("Could suspend VM for medium change (%Rrc)"), vrc);
3696 *pfResume = true;
3697 break;
3698 }
3699 case VMSTATE_SUSPENDED:
3700 break;
3701 default:
3702 return setErrorInternalF(VBOX_E_INVALID_VM_STATE,
3703 COM_IIDOF(IConsole),
3704 getStaticComponentName(),
3705 false /*aWarning*/,
3706 true /*aLogIt*/,
3707 0 /* aResultDetail */,
3708 tr("Invalid state '%s' for changing medium"),
3709 pVMM->pfnVMR3GetStateName(enmVMState));
3710 }
3711
3712 return S_OK;
3713}
3714
3715/**
3716 * Resume the VM after we did any medium or network attachment change.
3717 * This is the counterpart to Console::suspendBeforeConfigChange().
3718 *
3719 * @param pUVM Safe VM handle.
3720 * @param pVMM Safe VMM vtable.
3721 */
3722void Console::i_resumeAfterConfigChange(PUVM pUVM, PCVMMR3VTABLE pVMM)
3723{
3724 LogFlowFunc(("Resuming the VM...\n"));
3725
3726 /* disable the callback to prevent Console-level state change */
3727 mVMStateChangeCallbackDisabled = true;
3728 int vrc = pVMM->pfnVMR3Resume(pUVM, VMRESUMEREASON_RECONFIG);
3729 mVMStateChangeCallbackDisabled = false;
3730 AssertRC(vrc);
3731 if (RT_FAILURE(vrc))
3732 {
3733 VMSTATE enmVMState = pVMM->pfnVMR3GetStateU(pUVM);
3734 if (enmVMState == VMSTATE_SUSPENDED)
3735 {
3736 /* too bad, we failed. try to sync the console state with the VMM state */
3737 i_vmstateChangeCallback(pUVM, pVMM, VMSTATE_SUSPENDED, enmVMState, this);
3738 }
3739 }
3740}
3741
3742/**
3743 * Process a medium change.
3744 *
3745 * @param aMediumAttachment The medium attachment with the new medium state.
3746 * @param fForce Force medium chance, if it is locked or not.
3747 * @param pUVM Safe VM handle.
3748 * @param pVMM Safe VMM vtable.
3749 *
3750 * @note Locks this object for writing.
3751 */
3752HRESULT Console::i_doMediumChange(IMediumAttachment *aMediumAttachment, bool fForce, PUVM pUVM, PCVMMR3VTABLE pVMM)
3753{
3754 AutoCaller autoCaller(this);
3755 AssertComRCReturnRC(autoCaller.hrc());
3756
3757 /* We will need to release the write lock before calling EMT */
3758 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3759
3760 const char *pszDevice = NULL;
3761
3762 SafeIfaceArray<IStorageController> ctrls;
3763 HRESULT hrc = mMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));
3764 AssertComRC(hrc);
3765
3766 IMedium *pMedium = NULL;
3767 hrc = aMediumAttachment->COMGETTER(Medium)(&pMedium);
3768 AssertComRC(hrc);
3769
3770 Bstr mediumLocation;
3771 if (pMedium)
3772 {
3773 hrc = pMedium->COMGETTER(Location)(mediumLocation.asOutParam());
3774 AssertComRC(hrc);
3775 }
3776
3777 Bstr attCtrlName;
3778 hrc = aMediumAttachment->COMGETTER(Controller)(attCtrlName.asOutParam());
3779 AssertComRC(hrc);
3780 ComPtr<IStorageController> pStorageController;
3781 for (size_t i = 0; i < ctrls.size(); ++i)
3782 {
3783 Bstr ctrlName;
3784 hrc = ctrls[i]->COMGETTER(Name)(ctrlName.asOutParam());
3785 AssertComRC(hrc);
3786 if (attCtrlName == ctrlName)
3787 {
3788 pStorageController = ctrls[i];
3789 break;
3790 }
3791 }
3792 if (pStorageController.isNull())
3793 return setError(E_FAIL, tr("Could not find storage controller '%ls'"), attCtrlName.raw());
3794
3795 StorageControllerType_T enmCtrlType;
3796 hrc = pStorageController->COMGETTER(ControllerType)(&enmCtrlType);
3797 AssertComRC(hrc);
3798 pszDevice = i_storageControllerTypeToStr(enmCtrlType);
3799
3800 StorageBus_T enmBus;
3801 hrc = pStorageController->COMGETTER(Bus)(&enmBus);
3802 AssertComRC(hrc);
3803
3804 ULONG uInstance;
3805 hrc = pStorageController->COMGETTER(Instance)(&uInstance);
3806 AssertComRC(hrc);
3807
3808 BOOL fUseHostIOCache;
3809 hrc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
3810 AssertComRC(hrc);
3811
3812 /*
3813 * Suspend the VM first. The VM must not be running since it might have
3814 * pending I/O to the drive which is being changed.
3815 */
3816 bool fResume = false;
3817 hrc = i_suspendBeforeConfigChange(pUVM, pVMM, &alock, &fResume);
3818 if (FAILED(hrc))
3819 return hrc;
3820
3821 /*
3822 * Call worker on EMT #0, that's faster and safer than doing everything
3823 * using VMR3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
3824 * here to make requests from under the lock in order to serialize them.
3825 */
3826 PVMREQ pReq;
3827 int vrc = pVMM->pfnVMR3ReqCallU(pUVM, 0, &pReq, 0 /* no wait! */, VMREQFLAGS_VBOX_STATUS, (PFNRT)i_changeRemovableMedium, 9,
3828 this, pUVM, pVMM, pszDevice, uInstance, enmBus, fUseHostIOCache, aMediumAttachment, fForce);
3829
3830 /* release the lock before waiting for a result (EMT might wait for it, @bugref{7648})! */
3831 alock.release();
3832
3833 if (vrc == VERR_TIMEOUT)
3834 vrc = pVMM->pfnVMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
3835 AssertRC(vrc);
3836 if (RT_SUCCESS(vrc))
3837 vrc = pReq->iStatus;
3838 pVMM->pfnVMR3ReqFree(pReq);
3839
3840 if (fResume)
3841 i_resumeAfterConfigChange(pUVM, pVMM);
3842
3843 if (RT_SUCCESS(vrc))
3844 {
3845 LogFlowThisFunc(("Returns S_OK\n"));
3846 return S_OK;
3847 }
3848
3849 if (pMedium)
3850 return setErrorBoth(E_FAIL, vrc, tr("Could not mount the media/drive '%ls' (%Rrc)"), mediumLocation.raw(), vrc);
3851 return setErrorBoth(E_FAIL, vrc, tr("Could not unmount the currently mounted media/drive (%Rrc)"), vrc);
3852}
3853
3854/**
3855 * Performs the medium change in EMT.
3856 *
3857 * @returns VBox status code.
3858 *
3859 * @param pThis Pointer to the Console object.
3860 * @param pUVM The VM handle.
3861 * @param pVMM The VMM vtable.
3862 * @param pcszDevice The PDM device name.
3863 * @param uInstance The PDM device instance.
3864 * @param enmBus The storage bus type of the controller.
3865 * @param fUseHostIOCache Whether to use the host I/O cache (disable async I/O).
3866 * @param aMediumAtt The medium attachment.
3867 * @param fForce Force unmounting.
3868 *
3869 * @thread EMT
3870 * @note The VM must not be running since it might have pending I/O to the drive which is being changed.
3871 */
3872DECLCALLBACK(int) Console::i_changeRemovableMedium(Console *pThis,
3873 PUVM pUVM,
3874 PCVMMR3VTABLE pVMM,
3875 const char *pcszDevice,
3876 unsigned uInstance,
3877 StorageBus_T enmBus,
3878 bool fUseHostIOCache,
3879 IMediumAttachment *aMediumAtt,
3880 bool fForce)
3881{
3882 LogFlowFunc(("pThis=%p uInstance=%u pszDevice=%p:{%s} enmBus=%u, aMediumAtt=%p, fForce=%d\n",
3883 pThis, uInstance, pcszDevice, pcszDevice, enmBus, aMediumAtt, fForce));
3884
3885 AssertReturn(pThis, VERR_INVALID_PARAMETER);
3886
3887 AutoCaller autoCaller(pThis);
3888 AssertComRCReturn(autoCaller.hrc(), VERR_ACCESS_DENIED);
3889
3890 /*
3891 * Check the VM for correct state.
3892 */
3893 VMSTATE enmVMState = pVMM->pfnVMR3GetStateU(pUVM);
3894 AssertReturn(enmVMState == VMSTATE_SUSPENDED, VERR_INVALID_STATE);
3895
3896 int vrc = pThis->i_configMediumAttachment(pcszDevice,
3897 uInstance,
3898 enmBus,
3899 fUseHostIOCache,
3900 false /* fSetupMerge */,
3901 false /* fBuiltinIOCache */,
3902 false /* fInsertDiskIntegrityDrv. */,
3903 0 /* uMergeSource */,
3904 0 /* uMergeTarget */,
3905 aMediumAtt,
3906 pThis->mMachineState,
3907 NULL /* phrc */,
3908 true /* fAttachDetach */,
3909 fForce /* fForceUnmount */,
3910 false /* fHotplug */,
3911 pUVM,
3912 pVMM,
3913 NULL /* paLedDevType */,
3914 NULL /* ppLunL0 */);
3915 LogFlowFunc(("Returning %Rrc\n", vrc));
3916 return vrc;
3917}
3918
3919
3920/**
3921 * Attach a new storage device to the VM.
3922 *
3923 * @param aMediumAttachment The medium attachment which is added.
3924 * @param pUVM Safe VM handle.
3925 * @param pVMM Safe VMM vtable.
3926 * @param fSilent Flag whether to notify the guest about the attached device.
3927 *
3928 * @note Locks this object for writing.
3929 */
3930HRESULT Console::i_doStorageDeviceAttach(IMediumAttachment *aMediumAttachment, PUVM pUVM, PCVMMR3VTABLE pVMM, bool fSilent)
3931{
3932 AutoCaller autoCaller(this);
3933 AssertComRCReturnRC(autoCaller.hrc());
3934
3935 /* We will need to release the write lock before calling EMT */
3936 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3937
3938 const char *pszDevice = NULL;
3939
3940 SafeIfaceArray<IStorageController> ctrls;
3941 HRESULT hrc = mMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));
3942 AssertComRC(hrc);
3943
3944 IMedium *pMedium = NULL;
3945 hrc = aMediumAttachment->COMGETTER(Medium)(&pMedium);
3946 AssertComRC(hrc);
3947
3948 Bstr mediumLocation;
3949 if (pMedium)
3950 {
3951 hrc = pMedium->COMGETTER(Location)(mediumLocation.asOutParam());
3952 AssertComRC(hrc);
3953 }
3954
3955 Bstr attCtrlName;
3956 hrc = aMediumAttachment->COMGETTER(Controller)(attCtrlName.asOutParam());
3957 AssertComRC(hrc);
3958 ComPtr<IStorageController> pStorageController;
3959 for (size_t i = 0; i < ctrls.size(); ++i)
3960 {
3961 Bstr ctrlName;
3962 hrc = ctrls[i]->COMGETTER(Name)(ctrlName.asOutParam());
3963 AssertComRC(hrc);
3964 if (attCtrlName == ctrlName)
3965 {
3966 pStorageController = ctrls[i];
3967 break;
3968 }
3969 }
3970 if (pStorageController.isNull())
3971 return setError(E_FAIL, tr("Could not find storage controller '%ls'"), attCtrlName.raw());
3972
3973 StorageControllerType_T enmCtrlType;
3974 hrc = pStorageController->COMGETTER(ControllerType)(&enmCtrlType);
3975 AssertComRC(hrc);
3976 pszDevice = i_storageControllerTypeToStr(enmCtrlType);
3977
3978 StorageBus_T enmBus;
3979 hrc = pStorageController->COMGETTER(Bus)(&enmBus);
3980 AssertComRC(hrc);
3981
3982 ULONG uInstance;
3983 hrc = pStorageController->COMGETTER(Instance)(&uInstance);
3984 AssertComRC(hrc);
3985
3986 BOOL fUseHostIOCache;
3987 hrc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
3988 AssertComRC(hrc);
3989
3990 /*
3991 * Suspend the VM first. The VM must not be running since it might have
3992 * pending I/O to the drive which is being changed.
3993 */
3994 bool fResume = false;
3995 hrc = i_suspendBeforeConfigChange(pUVM, pVMM, &alock, &fResume);
3996 if (FAILED(hrc))
3997 return hrc;
3998
3999 /*
4000 * Call worker on EMT #0, that's faster and safer than doing everything
4001 * using VMR3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
4002 * here to make requests from under the lock in order to serialize them.
4003 */
4004 PVMREQ pReq;
4005 int vrc = pVMM->pfnVMR3ReqCallU(pUVM, 0, &pReq, 0 /* no wait! */, VMREQFLAGS_VBOX_STATUS, (PFNRT)i_attachStorageDevice, 9,
4006 this, pUVM, pVMM, pszDevice, uInstance, enmBus, fUseHostIOCache, aMediumAttachment, fSilent);
4007
4008 /* release the lock before waiting for a result (EMT might wait for it, @bugref{7648})! */
4009 alock.release();
4010
4011 if (vrc == VERR_TIMEOUT)
4012 vrc = pVMM->pfnVMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
4013 AssertRC(vrc);
4014 if (RT_SUCCESS(vrc))
4015 vrc = pReq->iStatus;
4016 pVMM->pfnVMR3ReqFree(pReq);
4017
4018 if (fResume)
4019 i_resumeAfterConfigChange(pUVM, pVMM);
4020
4021 if (RT_SUCCESS(vrc))
4022 {
4023 LogFlowThisFunc(("Returns S_OK\n"));
4024 return S_OK;
4025 }
4026
4027 if (!pMedium)
4028 return setErrorBoth(E_FAIL, vrc, tr("Could not mount the media/drive '%ls' (%Rrc)"), mediumLocation.raw(), vrc);
4029 return setErrorBoth(E_FAIL, vrc, tr("Could not unmount the currently mounted media/drive (%Rrc)"), vrc);
4030}
4031
4032
4033/**
4034 * Performs the storage attach operation in EMT.
4035 *
4036 * @returns VBox status code.
4037 *
4038 * @param pThis Pointer to the Console object.
4039 * @param pUVM The VM handle.
4040 * @param pVMM The VMM vtable.
4041 * @param pcszDevice The PDM device name.
4042 * @param uInstance The PDM device instance.
4043 * @param enmBus The storage bus type of the controller.
4044 * @param fUseHostIOCache Whether to use the host I/O cache (disable async I/O).
4045 * @param aMediumAtt The medium attachment.
4046 * @param fSilent Flag whether to inform the guest about the attached device.
4047 *
4048 * @thread EMT
4049 * @note The VM must not be running since it might have pending I/O to the drive which is being changed.
4050 */
4051DECLCALLBACK(int) Console::i_attachStorageDevice(Console *pThis,
4052 PUVM pUVM,
4053 PCVMMR3VTABLE pVMM,
4054 const char *pcszDevice,
4055 unsigned uInstance,
4056 StorageBus_T enmBus,
4057 bool fUseHostIOCache,
4058 IMediumAttachment *aMediumAtt,
4059 bool fSilent)
4060{
4061 LogFlowFunc(("pThis=%p uInstance=%u pszDevice=%p:{%s} enmBus=%u, aMediumAtt=%p\n",
4062 pThis, uInstance, pcszDevice, pcszDevice, enmBus, aMediumAtt));
4063
4064 AssertReturn(pThis, VERR_INVALID_PARAMETER);
4065
4066 AutoCaller autoCaller(pThis);
4067 AssertComRCReturn(autoCaller.hrc(), VERR_ACCESS_DENIED);
4068
4069 /*
4070 * Check the VM for correct state.
4071 */
4072 VMSTATE enmVMState = pVMM->pfnVMR3GetStateU(pUVM);
4073 AssertReturn(enmVMState == VMSTATE_SUSPENDED, VERR_INVALID_STATE);
4074
4075 int vrc = pThis->i_configMediumAttachment(pcszDevice,
4076 uInstance,
4077 enmBus,
4078 fUseHostIOCache,
4079 false /* fSetupMerge */,
4080 false /* fBuiltinIOCache */,
4081 false /* fInsertDiskIntegrityDrv. */,
4082 0 /* uMergeSource */,
4083 0 /* uMergeTarget */,
4084 aMediumAtt,
4085 pThis->mMachineState,
4086 NULL /* phrc */,
4087 true /* fAttachDetach */,
4088 false /* fForceUnmount */,
4089 !fSilent /* fHotplug */,
4090 pUVM,
4091 pVMM,
4092 NULL /* paLedDevType */,
4093 NULL);
4094 LogFlowFunc(("Returning %Rrc\n", vrc));
4095 return vrc;
4096}
4097
4098/**
4099 * Attach a new storage device to the VM.
4100 *
4101 * @param aMediumAttachment The medium attachment which is added.
4102 * @param pUVM Safe VM handle.
4103 * @param pVMM Safe VMM vtable.
4104 * @param fSilent Flag whether to notify the guest about the detached device.
4105 *
4106 * @note Locks this object for writing.
4107 */
4108HRESULT Console::i_doStorageDeviceDetach(IMediumAttachment *aMediumAttachment, PUVM pUVM, PCVMMR3VTABLE pVMM, bool fSilent)
4109{
4110 AutoCaller autoCaller(this);
4111 AssertComRCReturnRC(autoCaller.hrc());
4112
4113 /* We will need to release the write lock before calling EMT */
4114 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4115
4116 const char *pszDevice = NULL;
4117
4118 SafeIfaceArray<IStorageController> ctrls;
4119 HRESULT hrc = mMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));
4120 AssertComRC(hrc);
4121
4122 IMedium *pMedium = NULL;
4123 hrc = aMediumAttachment->COMGETTER(Medium)(&pMedium);
4124 AssertComRC(hrc);
4125
4126 Bstr mediumLocation;
4127 if (pMedium)
4128 {
4129 hrc = pMedium->COMGETTER(Location)(mediumLocation.asOutParam());
4130 AssertComRC(hrc);
4131 }
4132
4133 Bstr attCtrlName;
4134 hrc = aMediumAttachment->COMGETTER(Controller)(attCtrlName.asOutParam());
4135 AssertComRC(hrc);
4136 ComPtr<IStorageController> pStorageController;
4137 for (size_t i = 0; i < ctrls.size(); ++i)
4138 {
4139 Bstr ctrlName;
4140 hrc = ctrls[i]->COMGETTER(Name)(ctrlName.asOutParam());
4141 AssertComRC(hrc);
4142 if (attCtrlName == ctrlName)
4143 {
4144 pStorageController = ctrls[i];
4145 break;
4146 }
4147 }
4148 if (pStorageController.isNull())
4149 return setError(E_FAIL, tr("Could not find storage controller '%ls'"), attCtrlName.raw());
4150
4151 StorageControllerType_T enmCtrlType;
4152 hrc = pStorageController->COMGETTER(ControllerType)(&enmCtrlType);
4153 AssertComRC(hrc);
4154 pszDevice = i_storageControllerTypeToStr(enmCtrlType);
4155
4156 StorageBus_T enmBus = (StorageBus_T)0;
4157 hrc = pStorageController->COMGETTER(Bus)(&enmBus);
4158 AssertComRC(hrc);
4159
4160 ULONG uInstance = 0;
4161 hrc = pStorageController->COMGETTER(Instance)(&uInstance);
4162 AssertComRC(hrc);
4163
4164 /*
4165 * Suspend the VM first. The VM must not be running since it might have
4166 * pending I/O to the drive which is being changed.
4167 */
4168 bool fResume = false;
4169 hrc = i_suspendBeforeConfigChange(pUVM, pVMM, &alock, &fResume);
4170 if (FAILED(hrc))
4171 return hrc;
4172
4173 /*
4174 * Call worker on EMT #0, that's faster and safer than doing everything
4175 * using VMR3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
4176 * here to make requests from under the lock in order to serialize them.
4177 */
4178 PVMREQ pReq;
4179 int vrc = pVMM->pfnVMR3ReqCallU(pUVM, 0, &pReq, 0 /* no wait! */, VMREQFLAGS_VBOX_STATUS, (PFNRT)i_detachStorageDevice, 8,
4180 this, pUVM, pVMM, pszDevice, uInstance, enmBus, aMediumAttachment, fSilent);
4181
4182 /* release the lock before waiting for a result (EMT might wait for it, @bugref{7648})! */
4183 alock.release();
4184
4185 if (vrc == VERR_TIMEOUT)
4186 vrc = pVMM->pfnVMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
4187 AssertRC(vrc);
4188 if (RT_SUCCESS(vrc))
4189 vrc = pReq->iStatus;
4190 pVMM->pfnVMR3ReqFree(pReq);
4191
4192 if (fResume)
4193 i_resumeAfterConfigChange(pUVM, pVMM);
4194
4195 if (RT_SUCCESS(vrc))
4196 {
4197 LogFlowThisFunc(("Returns S_OK\n"));
4198 return S_OK;
4199 }
4200
4201 if (!pMedium)
4202 return setErrorBoth(E_FAIL, vrc, tr("Could not mount the media/drive '%ls' (%Rrc)"), mediumLocation.raw(), vrc);
4203 return setErrorBoth(E_FAIL, vrc, tr("Could not unmount the currently mounted media/drive (%Rrc)"), vrc);
4204}
4205
4206/**
4207 * Performs the storage detach operation in EMT.
4208 *
4209 * @returns VBox status code.
4210 *
4211 * @param pThis Pointer to the Console object.
4212 * @param pUVM The VM handle.
4213 * @param pVMM The VMM vtable.
4214 * @param pcszDevice The PDM device name.
4215 * @param uInstance The PDM device instance.
4216 * @param enmBus The storage bus type of the controller.
4217 * @param pMediumAtt Pointer to the medium attachment.
4218 * @param fSilent Flag whether to notify the guest about the detached device.
4219 *
4220 * @thread EMT
4221 * @note The VM must not be running since it might have pending I/O to the drive which is being changed.
4222 */
4223DECLCALLBACK(int) Console::i_detachStorageDevice(Console *pThis,
4224 PUVM pUVM,
4225 PCVMMR3VTABLE pVMM,
4226 const char *pcszDevice,
4227 unsigned uInstance,
4228 StorageBus_T enmBus,
4229 IMediumAttachment *pMediumAtt,
4230 bool fSilent)
4231{
4232 LogRelFlowFunc(("pThis=%p uInstance=%u pszDevice=%p:{%s} enmBus=%u, pMediumAtt=%p\n",
4233 pThis, uInstance, pcszDevice, pcszDevice, enmBus, pMediumAtt));
4234
4235 AssertReturn(pThis, VERR_INVALID_PARAMETER);
4236
4237 AutoCaller autoCaller(pThis);
4238 AssertComRCReturn(autoCaller.hrc(), VERR_ACCESS_DENIED);
4239
4240 /*
4241 * Check the VM for correct state.
4242 */
4243 VMSTATE enmVMState = pVMM->pfnVMR3GetStateU(pUVM);
4244 AssertReturn(enmVMState == VMSTATE_SUSPENDED, VERR_INVALID_STATE);
4245
4246 /* Determine the base path for the device instance. */
4247 PCFGMNODE pCtlInst = pVMM->pfnCFGMR3GetChildF(pVMM->pfnCFGMR3GetRootU(pUVM), "Devices/%s/%u/", pcszDevice, uInstance);
4248 AssertReturn(pCtlInst || enmBus == StorageBus_USB, VERR_INTERNAL_ERROR);
4249
4250#define H() AssertMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE)
4251
4252 HRESULT hrc;
4253 int vrc = VINF_SUCCESS;
4254 LONG lDev;
4255 hrc = pMediumAtt->COMGETTER(Device)(&lDev); H();
4256 LONG lPort;
4257 hrc = pMediumAtt->COMGETTER(Port)(&lPort); H();
4258 DeviceType_T lType;
4259 hrc = pMediumAtt->COMGETTER(Type)(&lType); H();
4260 unsigned uLUN;
4261 hrc = Console::i_storageBusPortDeviceToLun(enmBus, lPort, lDev, uLUN); H();
4262
4263#undef H
4264
4265 PCFGMNODE pLunL0 = NULL;
4266 if (enmBus != StorageBus_USB)
4267 {
4268 /* First check if the LUN really exists. */
4269 pLunL0 = pVMM->pfnCFGMR3GetChildF(pCtlInst, "LUN#%u", uLUN);
4270 if (pLunL0)
4271 {
4272 uint32_t fFlags = 0;
4273 if (fSilent)
4274 fFlags |= PDM_TACH_FLAGS_NOT_HOT_PLUG;
4275
4276 vrc = pVMM->pfnPDMR3DeviceDetach(pUVM, pcszDevice, uInstance, uLUN, fFlags);
4277 if (vrc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
4278 vrc = VINF_SUCCESS;
4279 AssertLogRelRCReturn(vrc, vrc);
4280 pVMM->pfnCFGMR3RemoveNode(pLunL0);
4281
4282 Utf8StrFmt devicePath("%s/%u/LUN#%u", pcszDevice, uInstance, uLUN);
4283 pThis->mapMediumAttachments.erase(devicePath);
4284 }
4285 else
4286 AssertLogRelFailedReturn(VERR_INTERNAL_ERROR);
4287
4288 pVMM->pfnCFGMR3Dump(pCtlInst);
4289 }
4290#ifdef VBOX_WITH_USB
4291 else
4292 {
4293 /* Find the correct USB device in the list. */
4294 USBStorageDeviceList::iterator it;
4295 for (it = pThis->mUSBStorageDevices.begin(); it != pThis->mUSBStorageDevices.end(); ++it)
4296 if (it->iPort == lPort)
4297 break;
4298 AssertLogRelReturn(it != pThis->mUSBStorageDevices.end(), VERR_INTERNAL_ERROR);
4299
4300 vrc = pVMM->pfnPDMR3UsbDetachDevice(pUVM, &it->mUuid);
4301 AssertLogRelRCReturn(vrc, vrc);
4302 pThis->mUSBStorageDevices.erase(it);
4303 }
4304#endif
4305
4306 LogFlowFunc(("Returning VINF_SUCCESS\n"));
4307 return VINF_SUCCESS;
4308}
4309
4310/**
4311 * Called by IInternalSessionControl::OnNetworkAdapterChange().
4312 *
4313 * @note Locks this object for writing.
4314 */
4315HRESULT Console::i_onNetworkAdapterChange(INetworkAdapter *aNetworkAdapter, BOOL changeAdapter)
4316{
4317 LogFlowThisFunc(("\n"));
4318
4319 AutoCaller autoCaller(this);
4320 AssertComRCReturnRC(autoCaller.hrc());
4321
4322 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4323
4324 HRESULT hrc = S_OK;
4325
4326 /* don't trigger network changes if the VM isn't running */
4327 SafeVMPtrQuiet ptrVM(this);
4328 if (ptrVM.isOk())
4329 {
4330 /* Get the properties we need from the adapter */
4331 BOOL fCableConnected, fTraceEnabled;
4332 hrc = aNetworkAdapter->COMGETTER(CableConnected)(&fCableConnected);
4333 AssertComRC(hrc);
4334 if (SUCCEEDED(hrc))
4335 {
4336 hrc = aNetworkAdapter->COMGETTER(TraceEnabled)(&fTraceEnabled);
4337 AssertComRC(hrc);
4338 if (SUCCEEDED(hrc))
4339 {
4340 ULONG ulInstance;
4341 hrc = aNetworkAdapter->COMGETTER(Slot)(&ulInstance);
4342 AssertComRC(hrc);
4343 if (SUCCEEDED(hrc))
4344 {
4345 /*
4346 * Find the adapter instance, get the config interface and update
4347 * the link state.
4348 */
4349 NetworkAdapterType_T adapterType;
4350 hrc = aNetworkAdapter->COMGETTER(AdapterType)(&adapterType);
4351 AssertComRC(hrc);
4352 const char *pszAdapterName = networkAdapterTypeToName(adapterType);
4353
4354 // prevent cross-thread deadlocks, don't need the lock any more
4355 alock.release();
4356
4357 PPDMIBASE pBase = NULL;
4358 int vrc = VINF_SUCCESS;
4359 if (adapterType == NetworkAdapterType_UsbNet)
4360 vrc = ptrVM.vtable()->pfnPDMR3UsbQueryDeviceLun(ptrVM.rawUVM(), pszAdapterName, ulInstance, 0, &pBase);
4361 else
4362 vrc = ptrVM.vtable()->pfnPDMR3QueryDeviceLun(ptrVM.rawUVM(), pszAdapterName, ulInstance, 0, &pBase);
4363 if (RT_SUCCESS(vrc))
4364 {
4365 Assert(pBase);
4366 PPDMINETWORKCONFIG pINetCfg;
4367 pINetCfg = PDMIBASE_QUERY_INTERFACE(pBase, PDMINETWORKCONFIG);
4368 if (pINetCfg)
4369 {
4370 Log(("Console::onNetworkAdapterChange: setting link state to %d\n",
4371 fCableConnected));
4372 vrc = pINetCfg->pfnSetLinkState(pINetCfg,
4373 fCableConnected ? PDMNETWORKLINKSTATE_UP
4374 : PDMNETWORKLINKSTATE_DOWN);
4375 ComAssertRC(vrc);
4376 }
4377 if (RT_SUCCESS(vrc) && changeAdapter)
4378 {
4379 VMSTATE enmVMState = mpVMM->pfnVMR3GetStateU(ptrVM.rawUVM());
4380 if ( enmVMState == VMSTATE_RUNNING /** @todo LiveMigration: Forbid or deal
4381 correctly with the _LS variants */
4382 || enmVMState == VMSTATE_SUSPENDED)
4383 {
4384 if (fTraceEnabled && fCableConnected && pINetCfg)
4385 {
4386 vrc = pINetCfg->pfnSetLinkState(pINetCfg, PDMNETWORKLINKSTATE_DOWN);
4387 ComAssertRC(vrc);
4388 }
4389
4390 hrc = i_doNetworkAdapterChange(ptrVM.rawUVM(), ptrVM.vtable(), pszAdapterName,
4391 ulInstance, 0, aNetworkAdapter);
4392
4393 if (fTraceEnabled && fCableConnected && pINetCfg)
4394 {
4395 vrc = pINetCfg->pfnSetLinkState(pINetCfg, PDMNETWORKLINKSTATE_UP);
4396 ComAssertRC(vrc);
4397 }
4398 }
4399 }
4400 }
4401 else if (vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND)
4402 return setErrorBoth(E_FAIL, vrc, tr("The network adapter #%u is not enabled"), ulInstance);
4403 else
4404 ComAssertRC(vrc);
4405
4406 if (RT_FAILURE(vrc))
4407 hrc = E_FAIL;
4408
4409 alock.acquire();
4410 }
4411 }
4412 }
4413 ptrVM.release();
4414 }
4415
4416 // definitely don't need the lock any more
4417 alock.release();
4418
4419 /* notify console callbacks on success */
4420 if (SUCCEEDED(hrc))
4421 ::FireNetworkAdapterChangedEvent(mEventSource, aNetworkAdapter);
4422
4423 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
4424 return hrc;
4425}
4426
4427/**
4428 * Called by IInternalSessionControl::OnNATEngineChange().
4429 *
4430 * @note Locks this object for writing.
4431 */
4432HRESULT Console::i_onNATRedirectRuleChanged(ULONG ulInstance, BOOL aNatRuleRemove, NATProtocol_T aProto, IN_BSTR aHostIP,
4433 LONG aHostPort, IN_BSTR aGuestIP, LONG aGuestPort)
4434{
4435 LogFlowThisFunc(("\n"));
4436
4437 AutoCaller autoCaller(this);
4438 AssertComRCReturnRC(autoCaller.hrc());
4439
4440 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4441
4442 HRESULT hrc = S_OK;
4443
4444 /* don't trigger NAT engine changes if the VM isn't running */
4445 SafeVMPtrQuiet ptrVM(this);
4446 if (ptrVM.isOk())
4447 {
4448 do
4449 {
4450 ComPtr<INetworkAdapter> pNetworkAdapter;
4451 hrc = i_machine()->GetNetworkAdapter(ulInstance, pNetworkAdapter.asOutParam());
4452 if ( FAILED(hrc)
4453 || pNetworkAdapter.isNull())
4454 break;
4455
4456 /*
4457 * Find the adapter instance, get the config interface and update
4458 * the link state.
4459 */
4460 NetworkAdapterType_T adapterType;
4461 hrc = pNetworkAdapter->COMGETTER(AdapterType)(&adapterType);
4462 if (FAILED(hrc))
4463 {
4464 AssertComRC(hrc);
4465 hrc = E_FAIL;
4466 break;
4467 }
4468
4469 const char *pszAdapterName = networkAdapterTypeToName(adapterType);
4470 PPDMIBASE pBase;
4471 int vrc;
4472 if (adapterType == NetworkAdapterType_UsbNet)
4473 vrc = ptrVM.vtable()->pfnPDMR3UsbQueryLun(ptrVM.rawUVM(), pszAdapterName, ulInstance, 0, &pBase);
4474 else
4475 vrc = ptrVM.vtable()->pfnPDMR3QueryLun(ptrVM.rawUVM(), pszAdapterName, ulInstance, 0, &pBase);
4476 if (RT_FAILURE(vrc))
4477 {
4478 /* This may happen if the NAT network adapter is currently not attached.
4479 * This is a valid condition. */
4480 if (vrc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
4481 break;
4482 ComAssertRC(vrc);
4483 hrc = E_FAIL;
4484 break;
4485 }
4486
4487 NetworkAttachmentType_T attachmentType;
4488 hrc = pNetworkAdapter->COMGETTER(AttachmentType)(&attachmentType);
4489 if ( FAILED(hrc)
4490 || attachmentType != NetworkAttachmentType_NAT)
4491 {
4492 hrc = E_FAIL;
4493 break;
4494 }
4495
4496 /* look down for PDMINETWORKNATCONFIG interface */
4497 PPDMINETWORKNATCONFIG pNetNatCfg = NULL;
4498 while (pBase)
4499 {
4500 pNetNatCfg = (PPDMINETWORKNATCONFIG)pBase->pfnQueryInterface(pBase, PDMINETWORKNATCONFIG_IID);
4501 if (pNetNatCfg)
4502 break;
4503 /** @todo r=bird: This stinks! */
4504 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pBase);
4505 pBase = pDrvIns->pDownBase;
4506 }
4507 if (!pNetNatCfg)
4508 break;
4509
4510 bool fUdp = aProto == NATProtocol_UDP;
4511 vrc = pNetNatCfg->pfnRedirectRuleCommand(pNetNatCfg, !!aNatRuleRemove, fUdp,
4512 Utf8Str(aHostIP).c_str(), (uint16_t)aHostPort, Utf8Str(aGuestIP).c_str(),
4513 (uint16_t)aGuestPort);
4514 if (RT_FAILURE(vrc))
4515 hrc = E_FAIL;
4516 } while (0); /* break loop */
4517 ptrVM.release();
4518 }
4519
4520 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
4521 return hrc;
4522}
4523
4524
4525/** Helper that converts a BSTR safe array into a C-string array. */
4526static char **bstrSafeArrayToC(SafeArray<BSTR> const &a_rStrings, size_t *pcEntries) RT_NOEXCEPT
4527{
4528 if (pcEntries)
4529 *pcEntries = 0;
4530
4531 /*
4532 * The array is NULL terminated.
4533 */
4534 const size_t cStrings = a_rStrings.size();
4535 char **papszRet = (char **)RTMemAllocZ((cStrings + 1) * sizeof(papszRet[0]));
4536 AssertReturn(papszRet, NULL);
4537
4538 /*
4539 * The individual strings.
4540 */
4541 for (size_t i = 0; i < cStrings; i++)
4542 {
4543 int vrc = RTUtf16ToUtf8Ex((PCRTUTF16)a_rStrings[i], RTSTR_MAX, &papszRet[i], 0, NULL);
4544 AssertRC(vrc);
4545 if (RT_FAILURE(vrc))
4546 {
4547 while (i-- > 0)
4548 {
4549 RTStrFree(papszRet[i]);
4550 papszRet[i] = NULL;
4551 }
4552 return NULL;
4553 }
4554
4555 }
4556 if (pcEntries)
4557 *pcEntries = cStrings;
4558 return papszRet;
4559}
4560
4561
4562/**
4563 * IHostNameResolutionConfigurationChangeEvent
4564 *
4565 * Currently this event doesn't carry actual resolver configuration,
4566 * so we have to go back to VBoxSVC and ask... This is not ideal.
4567 */
4568HRESULT Console::i_onNATDnsChanged()
4569{
4570 AutoCaller autoCaller(this);
4571 AssertComRCReturnRC(autoCaller.hrc());
4572
4573 /* We wrap PDMINETWORKNATDNSCONFIG to simplify freeing memory allocations
4574 in it (exceptions, AssertReturn, regular returns). */
4575 struct DnsConfigCleanupWrapper
4576 {
4577 PDMINETWORKNATDNSCONFIG Core;
4578
4579 DnsConfigCleanupWrapper()
4580 {
4581 Core.szDomainName[0] = '\0';
4582 Core.cNameServers = 0;
4583 Core.papszNameServers = NULL;
4584 Core.cSearchDomains = 0;
4585 Core.papszSearchDomains = NULL;
4586 }
4587
4588 void freeStrArray(char **papsz)
4589 {
4590 if (papsz)
4591 {
4592 for (size_t i = 0; papsz[i] != NULL; i++)
4593 RTStrFree(papsz[i]);
4594 RTMemFree(papsz);
4595 }
4596 }
4597
4598 ~DnsConfigCleanupWrapper()
4599 {
4600 freeStrArray((char **)Core.papszNameServers);
4601 Core.papszNameServers = NULL;
4602 freeStrArray((char **)Core.papszSearchDomains);
4603 Core.papszSearchDomains = NULL;
4604 }
4605 } DnsConfig;
4606
4607
4608 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS); /** @todo r=bird: Why a write lock? */
4609
4610 ComPtr<IVirtualBox> ptrVirtualBox;
4611 HRESULT hrc = mMachine->COMGETTER(Parent)(ptrVirtualBox.asOutParam());
4612 if (FAILED(hrc))
4613 return S_OK;
4614
4615 ComPtr<IHost> ptrHost;
4616 hrc = ptrVirtualBox->COMGETTER(Host)(ptrHost.asOutParam());
4617 if (FAILED(hrc))
4618 return S_OK;
4619
4620 /* Domain name: */
4621 {
4622 com::Bstr bstrDomain;
4623 ptrHost->COMGETTER(DomainName)(bstrDomain.asOutParam());
4624 com::Utf8Str const strDomainName(bstrDomain);
4625 int vrc = RTStrCopy(DnsConfig.Core.szDomainName, sizeof(DnsConfig.Core.szDomainName), strDomainName.c_str());
4626 AssertRC(vrc);
4627 }
4628 Log(("domain name = \"%s\"\n", DnsConfig.Core.szDomainName));
4629
4630 /* Name servers: */
4631 {
4632 SafeArray<BSTR> nameServers;
4633 hrc = ptrHost->COMGETTER(NameServers)(ComSafeArrayAsOutParam(nameServers));
4634 if (FAILED(hrc))
4635 return S_OK;
4636 DnsConfig.Core.papszNameServers = bstrSafeArrayToC(nameServers, &DnsConfig.Core.cNameServers);
4637 if (!DnsConfig.Core.papszNameServers)
4638 return E_OUTOFMEMORY;
4639 }
4640 Log(("DNS change - %zu nameservers\n", DnsConfig.Core.cNameServers));
4641 for (size_t i = 0; i < DnsConfig.Core.cNameServers; i++)
4642 Log(("- papszNameServers[%zu] = \"%s\"\n", i, DnsConfig.Core.papszNameServers[i]));
4643
4644 /* Search domains: */
4645 {
4646 SafeArray<BSTR> searchDomains;
4647 hrc = ptrHost->COMGETTER(SearchStrings)(ComSafeArrayAsOutParam(searchDomains));
4648 if (FAILED(hrc))
4649 return S_OK;
4650 DnsConfig.Core.papszSearchDomains = bstrSafeArrayToC(searchDomains, &DnsConfig.Core.cSearchDomains);
4651 if (!DnsConfig.Core.papszSearchDomains)
4652 return E_OUTOFMEMORY;
4653 }
4654 Log(("Search Domain change - %u domains\n", DnsConfig.Core.cSearchDomains));
4655 for (size_t i = 0; i < DnsConfig.Core.cSearchDomains; i++)
4656 Log(("- papszSearchDomain[%zu] = \"%s\"\n", i, DnsConfig.Core.papszSearchDomains[i]));
4657
4658 /*
4659 * Notify all the NAT drivers.
4660 */
4661 SafeVMPtrQuiet ptrVM(this);
4662 if (ptrVM.isOk())
4663 ptrVM.vtable()->pfnPDMR3DriverEnumInstances(ptrVM.rawUVM(), "NAT", Console::notifyNatDnsChangeCallback, &DnsConfig.Core);
4664
4665 return S_OK;
4666}
4667
4668/**
4669 * @callback_method_impl{FNPDMENUMDRVINS,Helper for Console::i_onNATDnsChanged.}
4670 */
4671/*static*/ DECLCALLBACK(int)
4672Console::notifyNatDnsChangeCallback(PPDMIBASE pIBase, uint32_t uDrvInstance, bool fUsbDev, const char *pszDevice,
4673 uint32_t uDevInstance, unsigned uLun, void *pvUser)
4674{
4675 PPDMINETWORKNATCONFIG const pINetNatCfg = (PPDMINETWORKNATCONFIG)pIBase->pfnQueryInterface(pIBase, PDMINETWORKNATCONFIG_IID);
4676 if (pINetNatCfg && pINetNatCfg->pfnNotifyDnsChanged)
4677 {
4678 LogFunc(("Notifying instance #%u attached to %s%s#%u on lun #%u...\n",
4679 uDrvInstance, fUsbDev ? "usb device " : "", pszDevice, uDevInstance, uLun));
4680 pINetNatCfg->pfnNotifyDnsChanged(pINetNatCfg, (PCPDMINETWORKNATDNSCONFIG)pvUser);
4681 }
4682 else
4683 LogFunc(("Not notifying instance #%u attached to %s%s#%u on lun #%u: pINetNatCfg=%p pfnNotifyDnsChanged=%p\n",
4684 uDrvInstance, fUsbDev ? "usb device " : "", pszDevice, uDevInstance, uLun,
4685 pINetNatCfg, pINetNatCfg ? pINetNatCfg->pfnNotifyDnsChanged : NULL));
4686
4687 RT_NOREF(uDrvInstance, fUsbDev, pszDevice, uDevInstance, uLun);
4688 return VINF_SUCCESS;
4689}
4690
4691VMMDevMouseInterface *Console::i_getVMMDevMouseInterface()
4692{
4693 return m_pVMMDev;
4694}
4695
4696DisplayMouseInterface *Console::i_getDisplayMouseInterface()
4697{
4698 return mDisplay;
4699}
4700
4701/**
4702 * Parses one key value pair.
4703 *
4704 * @returns VBox status code.
4705 * @param psz Configuration string.
4706 * @param ppszEnd Where to store the pointer to the string following the key value pair.
4707 * @param ppszKey Where to store the key on success.
4708 * @param ppszVal Where to store the value on success.
4709 */
4710int Console::i_consoleParseKeyValue(const char *psz, const char **ppszEnd, char **ppszKey, char **ppszVal)
4711{
4712 const char *pszKeyStart = psz;
4713 while ( *psz != '='
4714 && *psz)
4715 psz++;
4716
4717 /* End of string at this point is invalid. */
4718 if (*psz == '\0')
4719 return VERR_INVALID_PARAMETER;
4720
4721 size_t const cchKey = psz - pszKeyStart;
4722
4723 psz++; /* Skip '=' character */
4724 const char *pszValStart = psz;
4725
4726 while ( *psz != ','
4727 && *psz != '\n'
4728 && *psz != '\r'
4729 && *psz)
4730 psz++;
4731 size_t const cchVal = psz - pszValStart;
4732
4733 int vrc = VINF_SUCCESS;
4734 if (cchKey && cchVal)
4735 {
4736 *ppszKey = RTStrDupN(pszKeyStart, cchKey);
4737 if (*ppszKey)
4738 {
4739 *ppszVal = RTStrDupN(pszValStart, cchVal);
4740 if (*ppszVal)
4741 *ppszEnd = psz;
4742 else
4743 {
4744 RTStrFree(*ppszKey);
4745 vrc = VERR_NO_STR_MEMORY;
4746 }
4747 }
4748 else
4749 vrc = VERR_NO_STR_MEMORY;
4750 }
4751 else
4752 vrc = VERR_INVALID_PARAMETER;
4753
4754 return vrc;
4755}
4756
4757/**
4758 * Initializes the secret key interface on all configured attachments.
4759 *
4760 * @returns COM status code.
4761 */
4762HRESULT Console::i_initSecretKeyIfOnAllAttachments(void)
4763{
4764 HRESULT hrc = S_OK;
4765 SafeIfaceArray<IMediumAttachment> sfaAttachments;
4766
4767 AutoCaller autoCaller(this);
4768 AssertComRCReturnRC(autoCaller.hrc());
4769
4770 /* Get the VM - must be done before the read-locking. */
4771 SafeVMPtr ptrVM(this);
4772 if (!ptrVM.isOk())
4773 return ptrVM.hrc();
4774
4775 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4776
4777 hrc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(sfaAttachments));
4778 AssertComRCReturnRC(hrc);
4779
4780#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
4781 m_cDisksPwProvided = 0;
4782#endif
4783
4784 /* Find the correct attachment. */
4785 for (unsigned i = 0; i < sfaAttachments.size(); i++)
4786 {
4787 const ComPtr<IMediumAttachment> &pAtt = sfaAttachments[i];
4788
4789#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
4790 ComPtr<IMedium> pMedium;
4791 ComPtr<IMedium> pBase;
4792
4793 hrc = pAtt->COMGETTER(Medium)(pMedium.asOutParam());
4794 AssertComRC(hrc);
4795
4796 bool fKeepSecIf = false;
4797 /* Skip non hard disk attachments. */
4798 if (pMedium.isNotNull())
4799 {
4800 /* Get the UUID of the base medium and compare. */
4801 hrc = pMedium->COMGETTER(Base)(pBase.asOutParam());
4802 AssertComRC(hrc);
4803
4804 Bstr bstrKeyId;
4805 hrc = pBase->GetProperty(Bstr("CRYPT/KeyId").raw(), bstrKeyId.asOutParam());
4806 if (SUCCEEDED(hrc))
4807 {
4808 Utf8Str strKeyId(bstrKeyId);
4809 SecretKey *pKey = NULL;
4810 int vrc = m_pKeyStore->retainSecretKey(strKeyId, &pKey);
4811 if (RT_SUCCESS(vrc))
4812 {
4813 fKeepSecIf = true;
4814 m_pKeyStore->releaseSecretKey(strKeyId);
4815 }
4816 }
4817 }
4818#endif
4819
4820 /*
4821 * Query storage controller, port and device
4822 * to identify the correct driver.
4823 */
4824 ComPtr<IStorageController> pStorageCtrl;
4825 Bstr storageCtrlName;
4826 LONG lPort, lDev;
4827 ULONG ulStorageCtrlInst;
4828
4829 hrc = pAtt->COMGETTER(Controller)(storageCtrlName.asOutParam());
4830 AssertComRC(hrc);
4831
4832 hrc = pAtt->COMGETTER(Port)(&lPort);
4833 AssertComRC(hrc);
4834
4835 hrc = pAtt->COMGETTER(Device)(&lDev);
4836 AssertComRC(hrc);
4837
4838 hrc = mMachine->GetStorageControllerByName(storageCtrlName.raw(), pStorageCtrl.asOutParam());
4839 AssertComRC(hrc);
4840
4841 hrc = pStorageCtrl->COMGETTER(Instance)(&ulStorageCtrlInst);
4842 AssertComRC(hrc);
4843
4844 StorageControllerType_T enmCtrlType;
4845 hrc = pStorageCtrl->COMGETTER(ControllerType)(&enmCtrlType);
4846 AssertComRC(hrc);
4847 const char *pcszDevice = i_storageControllerTypeToStr(enmCtrlType);
4848
4849 StorageBus_T enmBus;
4850 hrc = pStorageCtrl->COMGETTER(Bus)(&enmBus);
4851 AssertComRC(hrc);
4852
4853 unsigned uLUN;
4854 hrc = Console::i_storageBusPortDeviceToLun(enmBus, lPort, lDev, uLUN);
4855 AssertComRC(hrc);
4856
4857 PPDMIBASE pIBase = NULL;
4858 PPDMIMEDIA pIMedium = NULL;
4859 int vrc = ptrVM.vtable()->pfnPDMR3QueryDriverOnLun(ptrVM.rawUVM(), pcszDevice, ulStorageCtrlInst, uLUN, "VD", &pIBase);
4860 if (RT_SUCCESS(vrc))
4861 {
4862 if (pIBase)
4863 {
4864 pIMedium = (PPDMIMEDIA)pIBase->pfnQueryInterface(pIBase, PDMIMEDIA_IID);
4865 if (pIMedium)
4866 {
4867#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
4868 vrc = pIMedium->pfnSetSecKeyIf(pIMedium, fKeepSecIf ? mpIfSecKey : NULL, mpIfSecKeyHlp);
4869 Assert(RT_SUCCESS(vrc) || vrc == VERR_NOT_SUPPORTED);
4870 if (fKeepSecIf)
4871 m_cDisksPwProvided++;
4872#else
4873 vrc = pIMedium->pfnSetSecKeyIf(pIMedium, NULL, mpIfSecKeyHlp);
4874 Assert(RT_SUCCESS(vrc) || vrc == VERR_NOT_SUPPORTED);
4875#endif
4876 }
4877 }
4878 }
4879 }
4880
4881 return hrc;
4882}
4883
4884/**
4885 * Removes the key interfaces from all disk attachments with the given key ID.
4886 * Useful when changing the key store or dropping it.
4887 *
4888 * @returns COM status code.
4889 * @param strId The ID to look for.
4890 */
4891HRESULT Console::i_clearDiskEncryptionKeysOnAllAttachmentsWithKeyId(const Utf8Str &strId)
4892{
4893 HRESULT hrc = S_OK;
4894 SafeIfaceArray<IMediumAttachment> sfaAttachments;
4895
4896 /* Get the VM - must be done before the read-locking. */
4897 SafeVMPtr ptrVM(this);
4898 if (!ptrVM.isOk())
4899 return ptrVM.hrc();
4900
4901 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4902
4903 hrc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(sfaAttachments));
4904 AssertComRCReturnRC(hrc);
4905
4906 /* Find the correct attachment. */
4907 for (unsigned i = 0; i < sfaAttachments.size(); i++)
4908 {
4909 const ComPtr<IMediumAttachment> &pAtt = sfaAttachments[i];
4910 ComPtr<IMedium> pMedium;
4911 ComPtr<IMedium> pBase;
4912 Bstr bstrKeyId;
4913
4914 hrc = pAtt->COMGETTER(Medium)(pMedium.asOutParam());
4915 if (FAILED(hrc))
4916 break;
4917
4918 /* Skip non hard disk attachments. */
4919 if (pMedium.isNull())
4920 continue;
4921
4922 /* Get the UUID of the base medium and compare. */
4923 hrc = pMedium->COMGETTER(Base)(pBase.asOutParam());
4924 if (FAILED(hrc))
4925 break;
4926
4927 hrc = pBase->GetProperty(Bstr("CRYPT/KeyId").raw(), bstrKeyId.asOutParam());
4928 if (hrc == VBOX_E_OBJECT_NOT_FOUND)
4929 {
4930 hrc = S_OK;
4931 continue;
4932 }
4933 else if (FAILED(hrc))
4934 break;
4935
4936 if (strId.equals(Utf8Str(bstrKeyId)))
4937 {
4938
4939 /*
4940 * Query storage controller, port and device
4941 * to identify the correct driver.
4942 */
4943 ComPtr<IStorageController> pStorageCtrl;
4944 Bstr storageCtrlName;
4945 LONG lPort, lDev;
4946 ULONG ulStorageCtrlInst;
4947
4948 hrc = pAtt->COMGETTER(Controller)(storageCtrlName.asOutParam());
4949 AssertComRC(hrc);
4950
4951 hrc = pAtt->COMGETTER(Port)(&lPort);
4952 AssertComRC(hrc);
4953
4954 hrc = pAtt->COMGETTER(Device)(&lDev);
4955 AssertComRC(hrc);
4956
4957 hrc = mMachine->GetStorageControllerByName(storageCtrlName.raw(), pStorageCtrl.asOutParam());
4958 AssertComRC(hrc);
4959
4960 hrc = pStorageCtrl->COMGETTER(Instance)(&ulStorageCtrlInst);
4961 AssertComRC(hrc);
4962
4963 StorageControllerType_T enmCtrlType;
4964 hrc = pStorageCtrl->COMGETTER(ControllerType)(&enmCtrlType);
4965 AssertComRC(hrc);
4966 const char *pcszDevice = i_storageControllerTypeToStr(enmCtrlType);
4967
4968 StorageBus_T enmBus;
4969 hrc = pStorageCtrl->COMGETTER(Bus)(&enmBus);
4970 AssertComRC(hrc);
4971
4972 unsigned uLUN;
4973 hrc = Console::i_storageBusPortDeviceToLun(enmBus, lPort, lDev, uLUN);
4974 AssertComRC(hrc);
4975
4976 PPDMIBASE pIBase = NULL;
4977 PPDMIMEDIA pIMedium = NULL;
4978 int vrc = ptrVM.vtable()->pfnPDMR3QueryDriverOnLun(ptrVM.rawUVM(), pcszDevice, ulStorageCtrlInst, uLUN, "VD", &pIBase);
4979 if (RT_SUCCESS(vrc))
4980 {
4981 if (pIBase)
4982 {
4983 pIMedium = (PPDMIMEDIA)pIBase->pfnQueryInterface(pIBase, PDMIMEDIA_IID);
4984 if (pIMedium)
4985 {
4986 vrc = pIMedium->pfnSetSecKeyIf(pIMedium, NULL, mpIfSecKeyHlp);
4987 Assert(RT_SUCCESS(vrc) || vrc == VERR_NOT_SUPPORTED);
4988 }
4989 }
4990 }
4991 }
4992 }
4993
4994 return hrc;
4995}
4996
4997/**
4998 * Configures the encryption support for the disk which have encryption conigured
4999 * with the configured key.
5000 *
5001 * @returns COM status code.
5002 * @param strId The ID of the password.
5003 * @param pcDisksConfigured Where to store the number of disks configured for the given ID.
5004 */
5005HRESULT Console::i_configureEncryptionForDisk(const com::Utf8Str &strId, unsigned *pcDisksConfigured)
5006{
5007 unsigned cDisksConfigured = 0;
5008 HRESULT hrc = S_OK;
5009 SafeIfaceArray<IMediumAttachment> sfaAttachments;
5010
5011 AutoCaller autoCaller(this);
5012 AssertComRCReturnRC(autoCaller.hrc());
5013
5014 /* Get the VM - must be done before the read-locking. */
5015 SafeVMPtr ptrVM(this);
5016 if (!ptrVM.isOk())
5017 return ptrVM.hrc();
5018
5019 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5020
5021 hrc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(sfaAttachments));
5022 if (FAILED(hrc))
5023 return hrc;
5024
5025 /* Find the correct attachment. */
5026 for (unsigned i = 0; i < sfaAttachments.size(); i++)
5027 {
5028 const ComPtr<IMediumAttachment> &pAtt = sfaAttachments[i];
5029 ComPtr<IMedium> pMedium;
5030 ComPtr<IMedium> pBase;
5031 Bstr bstrKeyId;
5032
5033 hrc = pAtt->COMGETTER(Medium)(pMedium.asOutParam());
5034 if (FAILED(hrc))
5035 break;
5036
5037 /* Skip non hard disk attachments. */
5038 if (pMedium.isNull())
5039 continue;
5040
5041 /* Get the UUID of the base medium and compare. */
5042 hrc = pMedium->COMGETTER(Base)(pBase.asOutParam());
5043 if (FAILED(hrc))
5044 break;
5045
5046 hrc = pBase->GetProperty(Bstr("CRYPT/KeyId").raw(), bstrKeyId.asOutParam());
5047 if (hrc == VBOX_E_OBJECT_NOT_FOUND)
5048 {
5049 hrc = S_OK;
5050 continue;
5051 }
5052 else if (FAILED(hrc))
5053 break;
5054
5055 if (strId.equals(Utf8Str(bstrKeyId)))
5056 {
5057 /*
5058 * Found the matching medium, query storage controller, port and device
5059 * to identify the correct driver.
5060 */
5061 ComPtr<IStorageController> pStorageCtrl;
5062 Bstr storageCtrlName;
5063 LONG lPort, lDev;
5064 ULONG ulStorageCtrlInst;
5065
5066 hrc = pAtt->COMGETTER(Controller)(storageCtrlName.asOutParam());
5067 if (FAILED(hrc))
5068 break;
5069
5070 hrc = pAtt->COMGETTER(Port)(&lPort);
5071 if (FAILED(hrc))
5072 break;
5073
5074 hrc = pAtt->COMGETTER(Device)(&lDev);
5075 if (FAILED(hrc))
5076 break;
5077
5078 hrc = mMachine->GetStorageControllerByName(storageCtrlName.raw(), pStorageCtrl.asOutParam());
5079 if (FAILED(hrc))
5080 break;
5081
5082 hrc = pStorageCtrl->COMGETTER(Instance)(&ulStorageCtrlInst);
5083 if (FAILED(hrc))
5084 break;
5085
5086 StorageControllerType_T enmCtrlType;
5087 hrc = pStorageCtrl->COMGETTER(ControllerType)(&enmCtrlType);
5088 AssertComRC(hrc);
5089 const char *pcszDevice = i_storageControllerTypeToStr(enmCtrlType);
5090
5091 StorageBus_T enmBus;
5092 hrc = pStorageCtrl->COMGETTER(Bus)(&enmBus);
5093 AssertComRC(hrc);
5094
5095 unsigned uLUN;
5096 hrc = Console::i_storageBusPortDeviceToLun(enmBus, lPort, lDev, uLUN);
5097 AssertComRCReturnRC(hrc);
5098
5099 PPDMIBASE pIBase = NULL;
5100 PPDMIMEDIA pIMedium = NULL;
5101 int vrc = ptrVM.vtable()->pfnPDMR3QueryDriverOnLun(ptrVM.rawUVM(), pcszDevice, ulStorageCtrlInst, uLUN, "VD", &pIBase);
5102 if (RT_SUCCESS(vrc))
5103 {
5104 if (pIBase)
5105 {
5106 pIMedium = (PPDMIMEDIA)pIBase->pfnQueryInterface(pIBase, PDMIMEDIA_IID);
5107 if (!pIMedium)
5108 return setError(E_FAIL, tr("could not query medium interface of controller"));
5109 vrc = pIMedium->pfnSetSecKeyIf(pIMedium, mpIfSecKey, mpIfSecKeyHlp);
5110 if (vrc == VERR_VD_PASSWORD_INCORRECT)
5111 {
5112 hrc = setError(VBOX_E_PASSWORD_INCORRECT,
5113 tr("The provided password for ID \"%s\" is not correct for at least one disk using this ID"),
5114 strId.c_str());
5115 break;
5116 }
5117 else if (RT_FAILURE(vrc))
5118 {
5119 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to set the encryption key (%Rrc)"), vrc);
5120 break;
5121 }
5122
5123 if (RT_SUCCESS(vrc))
5124 cDisksConfigured++;
5125 }
5126 else
5127 return setError(E_FAIL, tr("could not query base interface of controller"));
5128 }
5129 }
5130 }
5131
5132 if ( SUCCEEDED(hrc)
5133 && pcDisksConfigured)
5134 *pcDisksConfigured = cDisksConfigured;
5135 else if (FAILED(hrc))
5136 {
5137 /* Clear disk encryption setup on successfully configured attachments. */
5138 ErrorInfoKeeper eik; /* Keep current error info or it gets deestroyed in the IPC methods below. */
5139 i_clearDiskEncryptionKeysOnAllAttachmentsWithKeyId(strId);
5140 }
5141
5142 return hrc;
5143}
5144
5145/**
5146 * Parses the encryption configuration for one disk.
5147 *
5148 * @returns COM status code.
5149 * @param psz Pointer to the configuration for the encryption of one disk.
5150 * @param ppszEnd Pointer to the string following encrpytion configuration.
5151 */
5152HRESULT Console::i_consoleParseDiskEncryption(const char *psz, const char **ppszEnd)
5153{
5154 char *pszUuid = NULL;
5155 char *pszKeyEnc = NULL;
5156 int vrc = VINF_SUCCESS;
5157 HRESULT hrc = S_OK;
5158
5159 while ( *psz
5160 && RT_SUCCESS(vrc))
5161 {
5162 char *pszKey = NULL;
5163 char *pszVal = NULL;
5164 const char *pszEnd = NULL;
5165
5166 vrc = i_consoleParseKeyValue(psz, &pszEnd, &pszKey, &pszVal);
5167 if (RT_SUCCESS(vrc))
5168 {
5169 if (!RTStrCmp(pszKey, "uuid"))
5170 pszUuid = pszVal;
5171 else if (!RTStrCmp(pszKey, "dek"))
5172 pszKeyEnc = pszVal;
5173 else
5174 vrc = VERR_INVALID_PARAMETER;
5175
5176 RTStrFree(pszKey);
5177
5178 if (*pszEnd == ',')
5179 psz = pszEnd + 1;
5180 else
5181 {
5182 /*
5183 * End of the configuration for the current disk, skip linefeed and
5184 * carriage returns.
5185 */
5186 while ( *pszEnd == '\n'
5187 || *pszEnd == '\r')
5188 pszEnd++;
5189
5190 psz = pszEnd;
5191 break; /* Stop parsing */
5192 }
5193
5194 }
5195 }
5196
5197 if ( RT_SUCCESS(vrc)
5198 && pszUuid
5199 && pszKeyEnc)
5200 {
5201 ssize_t cbKey = 0;
5202
5203 /* Decode the key. */
5204 cbKey = RTBase64DecodedSize(pszKeyEnc, NULL);
5205 if (cbKey != -1)
5206 {
5207 uint8_t *pbKey;
5208 vrc = RTMemSaferAllocZEx((void **)&pbKey, cbKey, RTMEMSAFER_F_REQUIRE_NOT_PAGABLE);
5209 if (RT_SUCCESS(vrc))
5210 {
5211 vrc = RTBase64Decode(pszKeyEnc, pbKey, cbKey, NULL, NULL);
5212 if (RT_SUCCESS(vrc))
5213 {
5214 vrc = m_pKeyStore->addSecretKey(Utf8Str(pszUuid), pbKey, cbKey);
5215 if (RT_SUCCESS(vrc))
5216 {
5217 hrc = i_configureEncryptionForDisk(Utf8Str(pszUuid), NULL);
5218 if (FAILED(hrc))
5219 {
5220 /* Delete the key from the map. */
5221 vrc = m_pKeyStore->deleteSecretKey(Utf8Str(pszUuid));
5222 AssertRC(vrc);
5223 }
5224 }
5225 }
5226 else
5227 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to decode the key (%Rrc)"), vrc);
5228
5229 RTMemSaferFree(pbKey, cbKey);
5230 }
5231 else
5232 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to allocate secure memory for the key (%Rrc)"), vrc);
5233 }
5234 else
5235 hrc = setError(E_FAIL, tr("The base64 encoding of the passed key is incorrect"));
5236 }
5237 else if (RT_SUCCESS(vrc))
5238 hrc = setError(E_FAIL, tr("The encryption configuration is incomplete"));
5239
5240 if (pszUuid)
5241 RTStrFree(pszUuid);
5242 if (pszKeyEnc)
5243 {
5244 RTMemWipeThoroughly(pszKeyEnc, strlen(pszKeyEnc), 10 /* cMinPasses */);
5245 RTStrFree(pszKeyEnc);
5246 }
5247
5248 if (ppszEnd)
5249 *ppszEnd = psz;
5250
5251 return hrc;
5252}
5253
5254HRESULT Console::i_setDiskEncryptionKeys(const Utf8Str &strCfg)
5255{
5256 HRESULT hrc = S_OK;
5257 const char *pszCfg = strCfg.c_str();
5258
5259 while ( *pszCfg
5260 && SUCCEEDED(hrc))
5261 {
5262 const char *pszNext = NULL;
5263 hrc = i_consoleParseDiskEncryption(pszCfg, &pszNext);
5264 pszCfg = pszNext;
5265 }
5266
5267 return hrc;
5268}
5269
5270void Console::i_removeSecretKeysOnSuspend()
5271{
5272 /* Remove keys which are supposed to be removed on a suspend. */
5273 int vrc = m_pKeyStore->deleteAllSecretKeys(true /* fSuspend */, true /* fForce */);
5274 AssertRC(vrc);
5275}
5276
5277/**
5278 * Process a network adaptor change.
5279 *
5280 * @returns COM status code.
5281 *
5282 * @param pUVM The VM handle (caller hold this safely).
5283 * @param pVMM The VMM vtable.
5284 * @param pszDevice The PDM device name.
5285 * @param uInstance The PDM device instance.
5286 * @param uLun The PDM LUN number of the drive.
5287 * @param aNetworkAdapter The network adapter whose attachment needs to be changed
5288 */
5289HRESULT Console::i_doNetworkAdapterChange(PUVM pUVM, PCVMMR3VTABLE pVMM, const char *pszDevice,
5290 unsigned uInstance, unsigned uLun, INetworkAdapter *aNetworkAdapter)
5291{
5292 LogFlowThisFunc(("pszDevice=%p:{%s} uInstance=%u uLun=%u aNetworkAdapter=%p\n",
5293 pszDevice, pszDevice, uInstance, uLun, aNetworkAdapter));
5294
5295 AutoCaller autoCaller(this);
5296 AssertComRCReturnRC(autoCaller.hrc());
5297
5298 /*
5299 * Suspend the VM first.
5300 */
5301 bool fResume = false;
5302 HRESULT hr = i_suspendBeforeConfigChange(pUVM, pVMM, NULL, &fResume);
5303 if (FAILED(hr))
5304 return hr;
5305
5306 /*
5307 * Call worker in EMT, that's faster and safer than doing everything
5308 * using VM3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
5309 * here to make requests from under the lock in order to serialize them.
5310 */
5311 int vrc = pVMM->pfnVMR3ReqCallWaitU(pUVM, 0 /*idDstCpu*/, (PFNRT)i_changeNetworkAttachment, 7,
5312 this, pUVM, pVMM, pszDevice, uInstance, uLun, aNetworkAdapter);
5313
5314 if (fResume)
5315 i_resumeAfterConfigChange(pUVM, pVMM);
5316
5317 if (RT_SUCCESS(vrc))
5318 return S_OK;
5319
5320 return setErrorBoth(E_FAIL, vrc, tr("Could not change the network adaptor attachement type (%Rrc)"), vrc);
5321}
5322
5323
5324/**
5325 * Performs the Network Adaptor change in EMT.
5326 *
5327 * @returns VBox status code.
5328 *
5329 * @param pThis Pointer to the Console object.
5330 * @param pUVM The VM handle.
5331 * @param pVMM The VMM vtable.
5332 * @param pszDevice The PDM device name.
5333 * @param uInstance The PDM device instance.
5334 * @param uLun The PDM LUN number of the drive.
5335 * @param aNetworkAdapter The network adapter whose attachment needs to be changed
5336 *
5337 * @thread EMT
5338 * @note Locks the Console object for writing.
5339 * @note The VM must not be running.
5340 */
5341/*static*/ DECLCALLBACK(int) Console::i_changeNetworkAttachment(Console *pThis,
5342 PUVM pUVM,
5343 PCVMMR3VTABLE pVMM,
5344 const char *pszDevice,
5345 unsigned uInstance,
5346 unsigned uLun,
5347 INetworkAdapter *aNetworkAdapter)
5348{
5349 LogFlowFunc(("pThis=%p pszDevice=%p:{%s} uInstance=%u uLun=%u aNetworkAdapter=%p\n",
5350 pThis, pszDevice, pszDevice, uInstance, uLun, aNetworkAdapter));
5351
5352 AssertReturn(pThis, VERR_INVALID_PARAMETER);
5353
5354 AutoCaller autoCaller(pThis);
5355 AssertComRCReturn(autoCaller.hrc(), VERR_ACCESS_DENIED);
5356
5357#ifdef VBOX_STRICT
5358 ComPtr<IPlatform> pPlatform;
5359 HRESULT hrc = pThis->mMachine->COMGETTER(Platform)(pPlatform.asOutParam());
5360 AssertComRC(hrc);
5361
5362 PlatformArchitecture_T platformArch;
5363 hrc = pPlatform->COMGETTER(Architecture)(&platformArch);
5364 AssertComRC(hrc);
5365
5366 ComPtr<IVirtualBox> pVirtualBox;
5367 pThis->mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
5368
5369 ComPtr<IPlatformProperties> pPlatformProperties;
5370 hrc = pVirtualBox->GetPlatformProperties(platformArch, pPlatformProperties.asOutParam());
5371 AssertComRC(hrc);
5372
5373 ChipsetType_T chipsetType = ChipsetType_PIIX3;
5374 pPlatform->COMGETTER(ChipsetType)(&chipsetType);
5375 AssertComRC(hrc);
5376
5377 ULONG maxNetworkAdapters = 0;
5378 hrc = pPlatformProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters);
5379 AssertComRC(hrc);
5380 AssertMsg(uLun == 0 && uInstance < maxNetworkAdapters,
5381 ("pszDevice=%s uLun=%d uInstance=%d\n", pszDevice, uLun, uInstance));
5382#endif
5383 Log(("pszDevice=%s uLun=%d uInstance=%d\n", pszDevice, uLun, uInstance));
5384
5385 /*
5386 * Check the VM for correct state.
5387 */
5388 PCFGMNODE pCfg = NULL; /* /Devices/Dev/.../Config/ */
5389 PCFGMNODE pLunL0 = NULL; /* /Devices/Dev/0/LUN#0/ */
5390 PCFGMNODE pInst = pVMM->pfnCFGMR3GetChildF(pVMM->pfnCFGMR3GetRootU(pUVM), "Devices/%s/%d/", pszDevice, uInstance);
5391 AssertLogRelMsgReturn(pInst, ("pszDevices=%s uInstance=%u\n", pszDevice, uInstance), VERR_CFGM_CHILD_NOT_FOUND);
5392
5393 int vrc = pThis->i_configNetwork(pszDevice, uInstance, uLun, aNetworkAdapter, pCfg, pLunL0, pInst,
5394 true /*fAttachDetach*/, false /*fIgnoreConnectFailure*/, pUVM, pVMM);
5395
5396 LogFlowFunc(("Returning %Rrc\n", vrc));
5397 return vrc;
5398}
5399
5400/**
5401 * Returns the device name of a given audio adapter.
5402 *
5403 * @returns Device name, or an empty string if no device is configured.
5404 * @param aAudioAdapter Audio adapter to return device name for.
5405 */
5406Utf8Str Console::i_getAudioAdapterDeviceName(IAudioAdapter *aAudioAdapter)
5407{
5408 Utf8Str strDevice;
5409
5410 AudioControllerType_T audioController;
5411 HRESULT hrc = aAudioAdapter->COMGETTER(AudioController)(&audioController);
5412 AssertComRC(hrc);
5413 if (SUCCEEDED(hrc))
5414 {
5415 switch (audioController)
5416 {
5417 case AudioControllerType_HDA: strDevice = "hda"; break;
5418 case AudioControllerType_AC97: strDevice = "ichac97"; break;
5419 case AudioControllerType_SB16: strDevice = "sb16"; break;
5420 case AudioControllerType_VirtioSound: strDevice = "virtio-sound"; break;
5421 default: break; /* None. */
5422 }
5423 }
5424
5425 return strDevice;
5426}
5427
5428/**
5429 * Called by IInternalSessionControl::OnAudioAdapterChange().
5430 */
5431HRESULT Console::i_onAudioAdapterChange(IAudioAdapter *aAudioAdapter)
5432{
5433 LogFlowThisFunc(("\n"));
5434
5435 AutoCaller autoCaller(this);
5436 AssertComRCReturnRC(autoCaller.hrc());
5437
5438 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5439
5440 HRESULT hrc = S_OK;
5441
5442 /* don't trigger audio changes if the VM isn't running */
5443 SafeVMPtrQuiet ptrVM(this);
5444 if (ptrVM.isOk())
5445 {
5446 BOOL fEnabledIn, fEnabledOut;
5447 hrc = aAudioAdapter->COMGETTER(EnabledIn)(&fEnabledIn);
5448 AssertComRC(hrc);
5449 if (SUCCEEDED(hrc))
5450 {
5451 hrc = aAudioAdapter->COMGETTER(EnabledOut)(&fEnabledOut);
5452 AssertComRC(hrc);
5453 if (SUCCEEDED(hrc))
5454 {
5455 int vrc = VINF_SUCCESS;
5456
5457 for (ULONG ulLUN = 0; ulLUN < 16 /** @todo Use a define */; ulLUN++)
5458 {
5459 PPDMIBASE pBase;
5460 int vrc2 = ptrVM.vtable()->pfnPDMR3QueryDriverOnLun(ptrVM.rawUVM(),
5461 i_getAudioAdapterDeviceName(aAudioAdapter).c_str(),
5462 0 /* iInstance */, ulLUN, "AUDIO", &pBase);
5463 if (RT_FAILURE(vrc2))
5464 continue;
5465
5466 if (pBase)
5467 {
5468 PPDMIAUDIOCONNECTOR pAudioCon = (PPDMIAUDIOCONNECTOR)pBase->pfnQueryInterface(pBase,
5469 PDMIAUDIOCONNECTOR_IID);
5470 if ( pAudioCon
5471 && pAudioCon->pfnEnable)
5472 {
5473 int vrcIn = pAudioCon->pfnEnable(pAudioCon, PDMAUDIODIR_IN, RT_BOOL(fEnabledIn));
5474 if (RT_FAILURE(vrcIn))
5475 LogRel(("Audio: Failed to %s input of LUN#%RU32, vrcIn=%Rrc\n",
5476 fEnabledIn ? "enable" : "disable", ulLUN, vrcIn));
5477
5478 if (RT_SUCCESS(vrc))
5479 vrc = vrcIn;
5480
5481 int vrcOut = pAudioCon->pfnEnable(pAudioCon, PDMAUDIODIR_OUT, RT_BOOL(fEnabledOut));
5482 if (RT_FAILURE(vrcOut))
5483 LogRel(("Audio: Failed to %s output of LUN#%RU32, vrcOut=%Rrc\n",
5484 fEnabledIn ? "enable" : "disable", ulLUN, vrcOut));
5485
5486 if (RT_SUCCESS(vrc))
5487 vrc = vrcOut;
5488 }
5489 }
5490 }
5491
5492 if (RT_SUCCESS(vrc))
5493 LogRel(("Audio: Status has changed (input is %s, output is %s)\n",
5494 fEnabledIn ? "enabled" : "disabled", fEnabledOut ? "enabled" : "disabled"));
5495 }
5496 }
5497
5498 ptrVM.release();
5499 }
5500
5501 alock.release();
5502
5503 /* notify console callbacks on success */
5504 if (SUCCEEDED(hrc))
5505 ::FireAudioAdapterChangedEvent(mEventSource, aAudioAdapter);
5506
5507 LogFlowThisFunc(("Leaving S_OKn"));
5508 return S_OK;
5509}
5510
5511/**
5512 * Called by IInternalSessionControl::OnHostAudioDeviceChange().
5513 */
5514HRESULT Console::i_onHostAudioDeviceChange(IHostAudioDevice *aDevice, BOOL aNew, AudioDeviceState_T aState,
5515 IVirtualBoxErrorInfo *aErrInfo)
5516{
5517 LogFlowThisFunc(("\n"));
5518
5519 AutoCaller autoCaller(this);
5520 AssertComRCReturnRC(autoCaller.hrc());
5521
5522 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5523
5524 HRESULT hrc = S_OK;
5525
5526 /** @todo Implement logic here. */
5527
5528 alock.release();
5529
5530 /* notify console callbacks on success */
5531 if (SUCCEEDED(hrc))
5532 ::FireHostAudioDeviceChangedEvent(mEventSource, aDevice, aNew, aState, aErrInfo);
5533
5534 LogFlowThisFunc(("Leaving S_OK\n"));
5535 return S_OK;
5536}
5537
5538/**
5539 * Performs the Serial Port attachment change in EMT.
5540 *
5541 * @returns VBox status code.
5542 *
5543 * @param pThis Pointer to the Console object.
5544 * @param pUVM The VM handle.
5545 * @param pVMM The VMM vtable.
5546 * @param pSerialPort The serial port whose attachment needs to be changed
5547 *
5548 * @thread EMT
5549 * @note Locks the Console object for writing.
5550 * @note The VM must not be running.
5551 */
5552DECLCALLBACK(int) Console::i_changeSerialPortAttachment(Console *pThis, PUVM pUVM, PCVMMR3VTABLE pVMM, ISerialPort *pSerialPort)
5553{
5554 LogFlowFunc(("pThis=%p pUVM=%p pSerialPort=%p\n", pThis, pUVM, pSerialPort));
5555
5556 AssertReturn(pThis, VERR_INVALID_PARAMETER);
5557
5558 AutoCaller autoCaller(pThis);
5559 AssertComRCReturn(autoCaller.hrc(), VERR_ACCESS_DENIED);
5560
5561 AutoWriteLock alock(pThis COMMA_LOCKVAL_SRC_POS);
5562
5563 /*
5564 * Check the VM for correct state.
5565 */
5566 VMSTATE enmVMState = pVMM->pfnVMR3GetStateU(pUVM);
5567 AssertReturn(enmVMState == VMSTATE_SUSPENDED, VERR_INVALID_STATE);
5568
5569 HRESULT hrc = S_OK;
5570 int vrc = VINF_SUCCESS;
5571 ULONG ulSlot;
5572 hrc = pSerialPort->COMGETTER(Slot)(&ulSlot);
5573 if (SUCCEEDED(hrc))
5574 {
5575 /* Check whether the port mode changed and act accordingly. */
5576 Assert(ulSlot < 4);
5577
5578 PortMode_T eHostMode;
5579 hrc = pSerialPort->COMGETTER(HostMode)(&eHostMode);
5580 if (SUCCEEDED(hrc))
5581 {
5582 PCFGMNODE pInst = pVMM->pfnCFGMR3GetChildF(pVMM->pfnCFGMR3GetRootU(pUVM), "Devices/serial/%d/", ulSlot);
5583 AssertRelease(pInst);
5584
5585 /* Remove old driver. */
5586 if (pThis->m_aeSerialPortMode[ulSlot] != PortMode_Disconnected)
5587 {
5588 vrc = pVMM->pfnPDMR3DeviceDetach(pUVM, "serial", ulSlot, 0, 0);
5589 PCFGMNODE pLunL0 = pVMM->pfnCFGMR3GetChildF(pInst, "LUN#0");
5590 pVMM->pfnCFGMR3RemoveNode(pLunL0);
5591 }
5592
5593 if (RT_SUCCESS(vrc))
5594 {
5595 BOOL fServer;
5596 Bstr bstrPath;
5597 hrc = pSerialPort->COMGETTER(Server)(&fServer);
5598 if (SUCCEEDED(hrc))
5599 hrc = pSerialPort->COMGETTER(Path)(bstrPath.asOutParam());
5600
5601 /* Configure new driver. */
5602 if ( SUCCEEDED(hrc)
5603 && eHostMode != PortMode_Disconnected)
5604 {
5605 vrc = pThis->i_configSerialPort(pInst, eHostMode, Utf8Str(bstrPath).c_str(), RT_BOOL(fServer));
5606 if (RT_SUCCESS(vrc))
5607 {
5608 /*
5609 * Attach the driver.
5610 */
5611 PPDMIBASE pBase;
5612 vrc = pVMM->pfnPDMR3DeviceAttach(pUVM, "serial", ulSlot, 0, 0, &pBase);
5613
5614 pVMM->pfnCFGMR3Dump(pInst);
5615 }
5616 }
5617 }
5618 }
5619 }
5620
5621 if (RT_SUCCESS(vrc) && FAILED(hrc))
5622 vrc = VERR_INTERNAL_ERROR;
5623
5624 LogFlowFunc(("Returning %Rrc\n", vrc));
5625 return vrc;
5626}
5627
5628
5629/**
5630 * Called by IInternalSessionControl::OnSerialPortChange().
5631 */
5632HRESULT Console::i_onSerialPortChange(ISerialPort *aSerialPort)
5633{
5634 LogFlowThisFunc(("\n"));
5635
5636 AutoCaller autoCaller(this);
5637 AssertComRCReturnRC(autoCaller.hrc());
5638
5639 HRESULT hrc = S_OK;
5640
5641 /* don't trigger audio changes if the VM isn't running */
5642 SafeVMPtrQuiet ptrVM(this);
5643 if (ptrVM.isOk())
5644 {
5645 ULONG ulSlot;
5646 BOOL fEnabled = FALSE;
5647 hrc = aSerialPort->COMGETTER(Slot)(&ulSlot);
5648 if (SUCCEEDED(hrc))
5649 hrc = aSerialPort->COMGETTER(Enabled)(&fEnabled);
5650 if (SUCCEEDED(hrc) && fEnabled)
5651 {
5652 /* Check whether the port mode changed and act accordingly. */
5653 Assert(ulSlot < 4);
5654
5655 PortMode_T eHostMode;
5656 hrc = aSerialPort->COMGETTER(HostMode)(&eHostMode);
5657 if (SUCCEEDED(hrc) && m_aeSerialPortMode[ulSlot] != eHostMode)
5658 {
5659 /*
5660 * Suspend the VM first.
5661 */
5662 bool fResume = false;
5663 hrc = i_suspendBeforeConfigChange(ptrVM.rawUVM(), ptrVM.vtable(), NULL, &fResume);
5664 if (FAILED(hrc))
5665 return hrc;
5666
5667 /*
5668 * Call worker in EMT, that's faster and safer than doing everything
5669 * using VM3ReqCallWait.
5670 */
5671 int vrc = ptrVM.vtable()->pfnVMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /*idDstCpu*/,
5672 (PFNRT)i_changeSerialPortAttachment, 4,
5673 this, ptrVM.rawUVM(), ptrVM.vtable(), aSerialPort);
5674
5675 if (fResume)
5676 i_resumeAfterConfigChange(ptrVM.rawUVM(), ptrVM.vtable());
5677 if (RT_SUCCESS(vrc))
5678 m_aeSerialPortMode[ulSlot] = eHostMode;
5679 else
5680 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to change the serial port attachment (%Rrc)"), vrc);
5681 }
5682 }
5683 }
5684
5685 if (SUCCEEDED(hrc))
5686 ::FireSerialPortChangedEvent(mEventSource, aSerialPort);
5687
5688 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
5689 return hrc;
5690}
5691
5692/**
5693 * Called by IInternalSessionControl::OnParallelPortChange().
5694 */
5695HRESULT Console::i_onParallelPortChange(IParallelPort *aParallelPort)
5696{
5697 LogFlowThisFunc(("\n"));
5698
5699 AutoCaller autoCaller(this);
5700 AssertComRCReturnRC(autoCaller.hrc());
5701
5702 ::FireParallelPortChangedEvent(mEventSource, aParallelPort);
5703
5704 LogFlowThisFunc(("Leaving S_OK\n"));
5705 return S_OK;
5706}
5707
5708/**
5709 * Called by IInternalSessionControl::OnStorageControllerChange().
5710 */
5711HRESULT Console::i_onStorageControllerChange(const Guid &aMachineId, const Utf8Str &aControllerName)
5712{
5713 LogFlowThisFunc(("\n"));
5714
5715 AutoCaller autoCaller(this);
5716 AssertComRCReturnRC(autoCaller.hrc());
5717
5718 ::FireStorageControllerChangedEvent(mEventSource, aMachineId.toString(), aControllerName);
5719
5720 LogFlowThisFunc(("Leaving S_OK\n"));
5721 return S_OK;
5722}
5723
5724/**
5725 * Called by IInternalSessionControl::OnMediumChange().
5726 */
5727HRESULT Console::i_onMediumChange(IMediumAttachment *aMediumAttachment, BOOL aForce)
5728{
5729 LogFlowThisFunc(("\n"));
5730
5731 AutoCaller autoCaller(this);
5732 AssertComRCReturnRC(autoCaller.hrc());
5733
5734 HRESULT hrc = S_OK;
5735
5736 /* don't trigger medium changes if the VM isn't running */
5737 SafeVMPtrQuiet ptrVM(this);
5738 if (ptrVM.isOk())
5739 {
5740 hrc = i_doMediumChange(aMediumAttachment, !!aForce, ptrVM.rawUVM(), ptrVM.vtable());
5741 ptrVM.release();
5742 }
5743
5744 /* notify console callbacks on success */
5745 if (SUCCEEDED(hrc))
5746 ::FireMediumChangedEvent(mEventSource, aMediumAttachment);
5747
5748 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
5749 return hrc;
5750}
5751
5752/**
5753 * Called by IInternalSessionControl::OnCPUChange().
5754 *
5755 * @note Locks this object for writing.
5756 */
5757HRESULT Console::i_onCPUChange(ULONG aCPU, BOOL aRemove)
5758{
5759 LogFlowThisFunc(("\n"));
5760
5761 AutoCaller autoCaller(this);
5762 AssertComRCReturnRC(autoCaller.hrc());
5763
5764 HRESULT hrc = S_OK;
5765
5766 /* don't trigger CPU changes if the VM isn't running */
5767 SafeVMPtrQuiet ptrVM(this);
5768 if (ptrVM.isOk())
5769 {
5770 if (aRemove)
5771 hrc = i_doCPURemove(aCPU, ptrVM.rawUVM(), ptrVM.vtable());
5772 else
5773 hrc = i_doCPUAdd(aCPU, ptrVM.rawUVM(), ptrVM.vtable());
5774 ptrVM.release();
5775 }
5776
5777 /* notify console callbacks on success */
5778 if (SUCCEEDED(hrc))
5779 ::FireCPUChangedEvent(mEventSource, aCPU, aRemove);
5780
5781 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
5782 return hrc;
5783}
5784
5785/**
5786 * Called by IInternalSessionControl::OnCpuExecutionCapChange().
5787 *
5788 * @note Locks this object for writing.
5789 */
5790HRESULT Console::i_onCPUExecutionCapChange(ULONG aExecutionCap)
5791{
5792 LogFlowThisFunc(("\n"));
5793
5794 AutoCaller autoCaller(this);
5795 AssertComRCReturnRC(autoCaller.hrc());
5796
5797 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5798
5799 HRESULT hrc = S_OK;
5800
5801 /* don't trigger the CPU priority change if the VM isn't running */
5802 SafeVMPtrQuiet ptrVM(this);
5803 if (ptrVM.isOk())
5804 {
5805 if ( mMachineState == MachineState_Running
5806 || mMachineState == MachineState_Teleporting
5807 || mMachineState == MachineState_LiveSnapshotting
5808 )
5809 {
5810 /* No need to call in the EMT thread. */
5811 int vrc = ptrVM.vtable()->pfnVMR3SetCpuExecutionCap(ptrVM.rawUVM(), aExecutionCap);
5812 if (RT_FAILURE(vrc))
5813 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to change the CPU execution limit (%Rrc)"), vrc);
5814 }
5815 else
5816 hrc = i_setInvalidMachineStateError();
5817 ptrVM.release();
5818 }
5819
5820 /* notify console callbacks on success */
5821 if (SUCCEEDED(hrc))
5822 {
5823 alock.release();
5824 ::FireCPUExecutionCapChangedEvent(mEventSource, aExecutionCap);
5825 }
5826
5827 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
5828 return hrc;
5829}
5830
5831/**
5832 * Called by IInternalSessionControl::OnClipboardError().
5833 *
5834 * @note Locks this object for writing.
5835 */
5836HRESULT Console::i_onClipboardError(const Utf8Str &aId, const Utf8Str &aErrMsg, LONG aRc)
5837{
5838 LogFlowThisFunc(("\n"));
5839
5840 AutoCaller autoCaller(this);
5841 AssertComRCReturnRC(autoCaller.hrc());
5842
5843 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5844
5845 HRESULT hrc = S_OK;
5846
5847 /* don't trigger the drag and drop mode change if the VM isn't running */
5848 SafeVMPtrQuiet ptrVM(this);
5849 if (ptrVM.isOk())
5850 {
5851 if ( mMachineState == MachineState_Running
5852 || mMachineState == MachineState_Teleporting
5853 || mMachineState == MachineState_LiveSnapshotting)
5854 {
5855 }
5856 else
5857 hrc = i_setInvalidMachineStateError();
5858 ptrVM.release();
5859 }
5860
5861 /* notify console callbacks on success */
5862 if (SUCCEEDED(hrc))
5863 {
5864 alock.release();
5865 ::FireClipboardErrorEvent(mEventSource, aId, aErrMsg, aRc);
5866 }
5867
5868 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
5869 return hrc;
5870}
5871
5872/**
5873 * Called by IInternalSessionControl::OnClipboardModeChange().
5874 *
5875 * @note Locks this object for writing.
5876 */
5877HRESULT Console::i_onClipboardModeChange(ClipboardMode_T aClipboardMode)
5878{
5879 LogFlowThisFunc(("\n"));
5880
5881 AutoCaller autoCaller(this);
5882 AssertComRCReturnRC(autoCaller.hrc());
5883
5884 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5885
5886 HRESULT hrc = S_OK;
5887
5888 /* don't trigger the clipboard mode change if the VM isn't running */
5889 SafeVMPtrQuiet ptrVM(this);
5890 if (ptrVM.isOk())
5891 {
5892 if ( mMachineState == MachineState_Running
5893 || mMachineState == MachineState_Teleporting
5894 || mMachineState == MachineState_LiveSnapshotting)
5895 {
5896 int vrc = i_changeClipboardMode(aClipboardMode);
5897 if (RT_FAILURE(vrc))
5898 hrc = E_FAIL; /** @todo r=andy Set error info here! */
5899 }
5900 else
5901 hrc = i_setInvalidMachineStateError();
5902 ptrVM.release();
5903 }
5904
5905 /* notify console callbacks on success */
5906 if (SUCCEEDED(hrc))
5907 {
5908 alock.release();
5909 ::FireClipboardModeChangedEvent(mEventSource, aClipboardMode);
5910 }
5911
5912 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
5913 return hrc;
5914}
5915
5916/**
5917 * Called by IInternalSessionControl::OnClipboardFileTransferModeChange().
5918 *
5919 * @note Locks this object for writing.
5920 */
5921HRESULT Console::i_onClipboardFileTransferModeChange(bool aEnabled)
5922{
5923 LogFlowThisFunc(("\n"));
5924
5925 AutoCaller autoCaller(this);
5926 AssertComRCReturnRC(autoCaller.hrc());
5927
5928 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5929
5930 HRESULT hrc = S_OK;
5931
5932 /* don't trigger the change if the VM isn't running */
5933 SafeVMPtrQuiet ptrVM(this);
5934 if (ptrVM.isOk())
5935 {
5936 if ( mMachineState == MachineState_Running
5937 || mMachineState == MachineState_Teleporting
5938 || mMachineState == MachineState_LiveSnapshotting)
5939 {
5940 int vrc = i_changeClipboardFileTransferMode(aEnabled);
5941 if (RT_FAILURE(vrc))
5942 hrc = E_FAIL; /** @todo r=andy Set error info here! */
5943 }
5944 else
5945 hrc = i_setInvalidMachineStateError();
5946 ptrVM.release();
5947 }
5948
5949 /* notify console callbacks on success */
5950 if (SUCCEEDED(hrc))
5951 {
5952 alock.release();
5953 ::FireClipboardFileTransferModeChangedEvent(mEventSource, aEnabled ? TRUE : FALSE);
5954 }
5955
5956 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
5957 return hrc;
5958}
5959
5960/**
5961 * Called by IInternalSessionControl::OnDnDModeChange().
5962 *
5963 * @note Locks this object for writing.
5964 */
5965HRESULT Console::i_onDnDModeChange(DnDMode_T aDnDMode)
5966{
5967 LogFlowThisFunc(("\n"));
5968
5969 AutoCaller autoCaller(this);
5970 AssertComRCReturnRC(autoCaller.hrc());
5971
5972 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5973
5974 HRESULT hrc = S_OK;
5975
5976 /* don't trigger the drag and drop mode change if the VM isn't running */
5977 SafeVMPtrQuiet ptrVM(this);
5978 if (ptrVM.isOk())
5979 {
5980 if ( mMachineState == MachineState_Running
5981 || mMachineState == MachineState_Teleporting
5982 || mMachineState == MachineState_LiveSnapshotting)
5983 i_changeDnDMode(aDnDMode);
5984 else
5985 hrc = i_setInvalidMachineStateError();
5986 ptrVM.release();
5987 }
5988
5989 /* notify console callbacks on success */
5990 if (SUCCEEDED(hrc))
5991 {
5992 alock.release();
5993 ::FireDnDModeChangedEvent(mEventSource, aDnDMode);
5994 }
5995
5996 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
5997 return hrc;
5998}
5999
6000/**
6001 * Check the return code of mConsoleVRDPServer->Launch. LogRel() the error reason and
6002 * return an error message appropriate for setError().
6003 */
6004Utf8Str Console::VRDPServerErrorToMsg(int vrc)
6005{
6006 Utf8Str errMsg;
6007 if (vrc == VERR_NET_ADDRESS_IN_USE)
6008 {
6009 /* Not fatal if we start the VM, fatal if the VM is already running. */
6010 Bstr bstr;
6011 mVRDEServer->GetVRDEProperty(Bstr("TCP/Ports").raw(), bstr.asOutParam());
6012 errMsg = Utf8StrFmt(tr("VirtualBox Remote Desktop Extension server can't bind to the port(s): %s"),
6013 Utf8Str(bstr).c_str());
6014 LogRel(("VRDE: Warning: failed to launch VRDE server (%Rrc): %s\n", vrc, errMsg.c_str()));
6015 }
6016 else if (vrc == VINF_NOT_SUPPORTED)
6017 {
6018 /* This means that the VRDE is not installed.
6019 * Not fatal if we start the VM, fatal if the VM is already running. */
6020 LogRel(("VRDE: VirtualBox Remote Desktop Extension is not available.\n"));
6021 errMsg = Utf8Str(tr("VirtualBox Remote Desktop Extension is not available"));
6022 }
6023 else if (RT_FAILURE(vrc))
6024 {
6025 /* Fail if the server is installed but can't start. Always fatal. */
6026 switch (vrc)
6027 {
6028 case VERR_FILE_NOT_FOUND:
6029 errMsg = Utf8StrFmt(tr("Could not find the VirtualBox Remote Desktop Extension library"));
6030 break;
6031 default:
6032 errMsg = Utf8StrFmt(tr("Failed to launch the Remote Desktop Extension server (%Rrc)"), vrc);
6033 break;
6034 }
6035 LogRel(("VRDE: Failed: (%Rrc): %s\n", vrc, errMsg.c_str()));
6036 }
6037
6038 return errMsg;
6039}
6040
6041/**
6042 * Called by IInternalSessionControl::OnVRDEServerChange().
6043 *
6044 * @note Locks this object for writing.
6045 */
6046HRESULT Console::i_onVRDEServerChange(BOOL aRestart)
6047{
6048 AutoCaller autoCaller(this);
6049 AssertComRCReturnRC(autoCaller.hrc());
6050
6051 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6052
6053 HRESULT hrc = S_OK;
6054
6055 /* don't trigger VRDE server changes if the VM isn't running */
6056 SafeVMPtrQuiet ptrVM(this);
6057 if (ptrVM.isOk())
6058 {
6059 /* Serialize. */
6060 if (mfVRDEChangeInProcess)
6061 mfVRDEChangePending = true;
6062 else
6063 {
6064 do {
6065 mfVRDEChangeInProcess = true;
6066 mfVRDEChangePending = false;
6067
6068 if ( mVRDEServer
6069 && ( mMachineState == MachineState_Running
6070 || mMachineState == MachineState_Teleporting
6071 || mMachineState == MachineState_LiveSnapshotting
6072 || mMachineState == MachineState_Paused
6073 )
6074 )
6075 {
6076 BOOL vrdpEnabled = FALSE;
6077
6078 hrc = mVRDEServer->COMGETTER(Enabled)(&vrdpEnabled);
6079 ComAssertComRCRetRC(hrc);
6080
6081 if (aRestart)
6082 {
6083 /* VRDP server may call this Console object back from other threads (VRDP INPUT or OUTPUT). */
6084 alock.release();
6085
6086 if (vrdpEnabled)
6087 {
6088 // If there was no VRDP server started the 'stop' will do nothing.
6089 // However if a server was started and this notification was called,
6090 // we have to restart the server.
6091 mConsoleVRDPServer->Stop();
6092
6093 int vrc = mConsoleVRDPServer->Launch();
6094 if (vrc != VINF_SUCCESS)
6095 {
6096 Utf8Str errMsg = VRDPServerErrorToMsg(vrc);
6097 hrc = setErrorBoth(E_FAIL, vrc, "%s", errMsg.c_str());
6098 }
6099 else
6100 {
6101#ifdef VBOX_WITH_AUDIO_VRDE
6102 mAudioVRDE->doAttachDriverViaEmt(ptrVM.rawUVM(), ptrVM.vtable(), NULL /*alock is not held*/);
6103#endif
6104 mConsoleVRDPServer->EnableConnections();
6105 }
6106 }
6107 else
6108 {
6109 mConsoleVRDPServer->Stop();
6110#ifdef VBOX_WITH_AUDIO_VRDE
6111 mAudioVRDE->doDetachDriverViaEmt(ptrVM.rawUVM(), ptrVM.vtable(), NULL /*alock is not held*/);
6112#endif
6113 }
6114
6115 alock.acquire();
6116 }
6117 }
6118 else
6119 hrc = i_setInvalidMachineStateError();
6120
6121 mfVRDEChangeInProcess = false;
6122 } while (mfVRDEChangePending && SUCCEEDED(hrc));
6123 }
6124
6125 ptrVM.release();
6126 }
6127
6128 /* notify console callbacks on success */
6129 if (SUCCEEDED(hrc))
6130 {
6131 alock.release();
6132 ::FireVRDEServerChangedEvent(mEventSource);
6133 }
6134
6135 return hrc;
6136}
6137
6138void Console::i_onVRDEServerInfoChange()
6139{
6140 AutoCaller autoCaller(this);
6141 AssertComRCReturnVoid(autoCaller.hrc());
6142
6143 ::FireVRDEServerInfoChangedEvent(mEventSource);
6144}
6145
6146HRESULT Console::i_sendACPIMonitorHotPlugEvent()
6147{
6148 LogFlowThisFuncEnter();
6149
6150 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6151
6152 if ( mMachineState != MachineState_Running
6153 && mMachineState != MachineState_Teleporting
6154 && mMachineState != MachineState_LiveSnapshotting)
6155 return i_setInvalidMachineStateError();
6156
6157 /* get the VM handle. */
6158 SafeVMPtr ptrVM(this);
6159 if (!ptrVM.isOk())
6160 return ptrVM.hrc();
6161
6162 // no need to release lock, as there are no cross-thread callbacks
6163
6164 /* get the acpi device interface and press the sleep button. */
6165 PPDMIBASE pBase;
6166 int vrc = ptrVM.vtable()->pfnPDMR3QueryDeviceLun(ptrVM.rawUVM(), "acpi", 0, 0, &pBase);
6167 if (RT_SUCCESS(vrc))
6168 {
6169 Assert(pBase);
6170 PPDMIACPIPORT pPort = PDMIBASE_QUERY_INTERFACE(pBase, PDMIACPIPORT);
6171 if (pPort)
6172 vrc = pPort->pfnMonitorHotPlugEvent(pPort);
6173 else
6174 vrc = VERR_PDM_MISSING_INTERFACE;
6175 }
6176
6177 HRESULT hrc = RT_SUCCESS(vrc) ? S_OK
6178 : setErrorBoth(VBOX_E_PDM_ERROR, vrc, tr("Sending monitor hot-plug event failed (%Rrc)"), vrc);
6179
6180 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
6181 LogFlowThisFuncLeave();
6182 return hrc;
6183}
6184
6185#ifdef VBOX_WITH_RECORDING
6186/**
6187 * Enables or disables recording of a VM.
6188 *
6189 * @returns VBox status code.
6190 * @retval VINF_NO_CHANGE if the recording state has not been changed.
6191 * @param fEnable Whether to enable or disable the recording.
6192 * @param pAutoLock Pointer to auto write lock to use for attaching/detaching required driver(s) at runtime.
6193 * @param pProgress Progress object to use. Optional and can be NULL.
6194 */
6195int Console::i_recordingEnable(BOOL fEnable, util::AutoWriteLock *pAutoLock, ComPtr<IProgress> &pProgress)
6196{
6197 AssertPtrReturn(pAutoLock, VERR_INVALID_POINTER);
6198
6199 bool const fIsEnabled = mRecording.mCtx.IsStarted();
6200
6201 if (RT_BOOL(fEnable) == fIsEnabled) /* No change? Bail out. */
6202 return VINF_NO_CHANGE;
6203
6204 int vrc = VINF_SUCCESS;
6205
6206 Display *pDisplay = i_getDisplay();
6207 AssertPtrReturn(pDisplay, VERR_INVALID_POINTER);
6208
6209 LogRel(("Recording: %s\n", fEnable ? "Enabling" : "Disabling"));
6210
6211 SafeVMPtrQuiet ptrVM(this);
6212 if (ptrVM.isOk())
6213 {
6214 if (fEnable)
6215 {
6216 vrc = i_recordingCreate(pProgress);
6217 if (RT_SUCCESS(vrc))
6218 {
6219# ifdef VBOX_WITH_AUDIO_RECORDING
6220 /* Attach the video recording audio driver if required. */
6221 if ( mRecording.mCtx.IsFeatureEnabled(RecordingFeature_Audio)
6222 && mRecording.mAudioRec)
6223 {
6224 vrc = mRecording.mAudioRec->applyConfiguration(mRecording.mCtx.GetConfig());
6225 if (RT_SUCCESS(vrc))
6226 vrc = mRecording.mAudioRec->doAttachDriverViaEmt(ptrVM.rawUVM(), ptrVM.vtable(), pAutoLock);
6227
6228 if (RT_FAILURE(vrc))
6229 mRecording.mCtx.SetError(vrc, Utf8StrFmt(tr("Attaching audio recording driver failed (%Rrc)"), vrc));
6230 }
6231# endif
6232 if ( RT_SUCCESS(vrc)
6233 && mRecording.mCtx.IsReady()) /* Any video recording (audio and/or video) feature enabled? */
6234 {
6235 vrc = i_recordingStart(pAutoLock);
6236 }
6237 }
6238
6239 if (RT_FAILURE(vrc))
6240 LogRel(("Recording: Failed to enable with %Rrc\n", vrc));
6241 }
6242 else /* Disable */
6243 {
6244 vrc = i_recordingStop(pAutoLock);
6245 if (RT_SUCCESS(vrc))
6246 {
6247# ifdef VBOX_WITH_AUDIO_RECORDING
6248 if (mRecording.mAudioRec)
6249 {
6250 vrc = mRecording.mAudioRec->doDetachDriverViaEmt(ptrVM.rawUVM(), ptrVM.vtable(), pAutoLock);
6251 if (RT_FAILURE(vrc))
6252 mRecording.mCtx.SetError(vrc, Utf8StrFmt(tr("Detaching audio recording driver failed (%Rrc) -- please consult log file for details"), vrc));
6253 }
6254# endif
6255 i_recordingDestroy();
6256 }
6257 }
6258 }
6259 else
6260 vrc = VERR_VM_INVALID_VM_STATE;
6261
6262 if (RT_FAILURE(vrc))
6263 LogRel(("Recording: %s failed with %Rrc\n", fEnable ? "Enabling" : "Disabling", vrc));
6264
6265 return vrc;
6266}
6267#endif /* VBOX_WITH_RECORDING */
6268
6269/**
6270 * Called by IInternalSessionControl::OnRecordingStateChange().
6271 */
6272HRESULT Console::i_onRecordingStateChange(BOOL aEnable, ComPtr<IProgress> &aProgress)
6273{
6274#ifdef VBOX_WITH_RECORDING
6275 HRESULT hrc = S_OK;
6276
6277 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6278
6279 LogRel2(("Recording: State changed (%s)\n", aEnable ? "enabled" : "disabled"));
6280
6281 /* Don't trigger recording changes if the VM isn't running. */
6282 SafeVMPtrQuiet ptrVM(this);
6283 if (ptrVM.isOk())
6284 {
6285 ComPtr<IVirtualBoxErrorInfo> pErrorInfo;
6286
6287 int vrc = i_recordingEnable(aEnable, &alock, aProgress);
6288 if (RT_FAILURE(vrc))
6289 {
6290 /* If available, get the error information from the progress object and fire it via the event below. */
6291 if (aProgress.isNotNull())
6292 {
6293 hrc = aProgress->COMGETTER(ErrorInfo(pErrorInfo.asOutParam()));
6294 AssertComRCReturn(hrc, hrc);
6295 }
6296 }
6297
6298 alock.release(); /* Release lock before firing event. */
6299
6300 if (vrc != VINF_NO_CHANGE)
6301 ::FireRecordingStateChangedEvent(mEventSource, aEnable, pErrorInfo);
6302
6303 if (RT_FAILURE(vrc))
6304 hrc = VBOX_E_RECORDING_ERROR;
6305
6306 ptrVM.release();
6307 }
6308
6309 return hrc;
6310#else
6311 RT_NOREF(aEnable, aProgress);
6312 ReturnComNotImplemented();
6313#endif /* VBOX_WITH_RECORDING */
6314}
6315
6316/**
6317 * Called by IInternalSessionControl::OnRecordingScreenStateChange().
6318 */
6319HRESULT Console::i_onRecordingScreenStateChange(BOOL aEnable, ULONG aScreen)
6320{
6321 RT_NOREF(aEnable, aScreen);
6322 ReturnComNotImplemented();
6323}
6324
6325/**
6326 * Called by IInternalSessionControl::OnUSBControllerChange().
6327 */
6328HRESULT Console::i_onUSBControllerChange()
6329{
6330 LogFlowThisFunc(("\n"));
6331
6332 AutoCaller autoCaller(this);
6333 AssertComRCReturnRC(autoCaller.hrc());
6334
6335 ::FireUSBControllerChangedEvent(mEventSource);
6336
6337 return S_OK;
6338}
6339
6340/**
6341 * Called by IInternalSessionControl::OnSharedFolderChange().
6342 *
6343 * @note Locks this object for writing.
6344 */
6345HRESULT Console::i_onSharedFolderChange(BOOL aGlobal)
6346{
6347 LogFlowThisFunc(("aGlobal=%RTbool\n", aGlobal));
6348
6349 AutoCaller autoCaller(this);
6350 AssertComRCReturnRC(autoCaller.hrc());
6351
6352 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6353
6354 HRESULT hrc = i_fetchSharedFolders(aGlobal);
6355
6356 /* notify console callbacks on success */
6357 if (SUCCEEDED(hrc))
6358 {
6359 alock.release();
6360 ::FireSharedFolderChangedEvent(mEventSource, aGlobal ? Scope_Global : Scope_Machine);
6361 }
6362
6363 return hrc;
6364}
6365
6366/**
6367 * Called by IInternalSessionControl::OnGuestDebugControlChange().
6368 */
6369HRESULT Console::i_onGuestDebugControlChange(IGuestDebugControl *aGuestDebugControl)
6370{
6371 LogFlowThisFunc(("\n"));
6372
6373 AutoCaller autoCaller(this);
6374 AssertComRCReturnRC(autoCaller.hrc());
6375
6376 HRESULT hrc = S_OK;
6377
6378 /* don't trigger changes if the VM isn't running */
6379 SafeVMPtrQuiet ptrVM(this);
6380 if (ptrVM.isOk())
6381 {
6382 /// @todo
6383 }
6384
6385 if (SUCCEEDED(hrc))
6386 ::FireGuestDebugControlChangedEvent(mEventSource, aGuestDebugControl);
6387
6388 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
6389 return hrc;
6390}
6391
6392
6393/**
6394 * Called by IInternalSessionControl::OnUSBDeviceAttach() or locally by
6395 * processRemoteUSBDevices() after IInternalMachineControl::RunUSBDeviceFilters()
6396 * returns TRUE for a given remote USB device.
6397 *
6398 * @return S_OK if the device was attached to the VM.
6399 * @return failure if not attached.
6400 *
6401 * @param aDevice The device in question.
6402 * @param aError Error information.
6403 * @param aMaskedIfs The interfaces to hide from the guest.
6404 * @param aCaptureFilename File name where to store the USB traffic.
6405 *
6406 * @note Locks this object for writing.
6407 */
6408HRESULT Console::i_onUSBDeviceAttach(IUSBDevice *aDevice, IVirtualBoxErrorInfo *aError, ULONG aMaskedIfs,
6409 const Utf8Str &aCaptureFilename)
6410{
6411#ifdef VBOX_WITH_USB
6412 LogFlowThisFunc(("aDevice=%p aError=%p\n", aDevice, aError));
6413
6414 AutoCaller autoCaller(this);
6415 ComAssertComRCRetRC(autoCaller.hrc());
6416
6417 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6418
6419 /* Get the VM pointer (we don't need error info, since it's a callback). */
6420 SafeVMPtrQuiet ptrVM(this);
6421 if (!ptrVM.isOk())
6422 {
6423 /* The VM may be no more operational when this message arrives
6424 * (e.g. it may be Saving or Stopping or just PoweredOff) --
6425 * autoVMCaller.hrc() will return a failure in this case. */
6426 LogFlowThisFunc(("Attach request ignored (mMachineState=%d).\n", mMachineState));
6427 return ptrVM.hrc();
6428 }
6429
6430 if (aError != NULL)
6431 {
6432 /* notify callbacks about the error */
6433 alock.release();
6434 i_onUSBDeviceStateChange(aDevice, true /* aAttached */, aError);
6435 return S_OK;
6436 }
6437
6438 /* Don't proceed unless there's at least one USB hub. */
6439 if (!ptrVM.vtable()->pfnPDMR3UsbHasHub(ptrVM.rawUVM()))
6440 {
6441 LogFlowThisFunc(("Attach request ignored (no USB controller).\n"));
6442 return E_FAIL;
6443 }
6444
6445 alock.release();
6446 HRESULT hrc = i_attachUSBDevice(aDevice, aMaskedIfs, aCaptureFilename);
6447 if (FAILED(hrc))
6448 {
6449 /* take the current error info */
6450 com::ErrorInfoKeeper eik;
6451 /* the error must be a VirtualBoxErrorInfo instance */
6452 ComPtr<IVirtualBoxErrorInfo> pError = eik.takeError();
6453 Assert(!pError.isNull());
6454 if (!pError.isNull())
6455 {
6456 /* notify callbacks about the error */
6457 i_onUSBDeviceStateChange(aDevice, true /* aAttached */, pError);
6458 }
6459 }
6460
6461 return hrc;
6462
6463#else /* !VBOX_WITH_USB */
6464 RT_NOREF(aDevice, aError, aMaskedIfs, aCaptureFilename);
6465 return E_FAIL;
6466#endif /* !VBOX_WITH_USB */
6467}
6468
6469/**
6470 * Called by IInternalSessionControl::OnUSBDeviceDetach() and locally by
6471 * processRemoteUSBDevices().
6472 *
6473 * @note Locks this object for writing.
6474 */
6475HRESULT Console::i_onUSBDeviceDetach(IN_BSTR aId,
6476 IVirtualBoxErrorInfo *aError)
6477{
6478#ifdef VBOX_WITH_USB
6479 Guid Uuid(aId);
6480 LogFlowThisFunc(("aId={%RTuuid} aError=%p\n", Uuid.raw(), aError));
6481
6482 AutoCaller autoCaller(this);
6483 AssertComRCReturnRC(autoCaller.hrc());
6484
6485 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6486
6487 /* Find the device. */
6488 ComObjPtr<OUSBDevice> pUSBDevice;
6489 USBDeviceList::iterator it = mUSBDevices.begin();
6490 while (it != mUSBDevices.end())
6491 {
6492 LogFlowThisFunc(("it={%RTuuid}\n", (*it)->i_id().raw()));
6493 if ((*it)->i_id() == Uuid)
6494 {
6495 pUSBDevice = *it;
6496 break;
6497 }
6498 ++it;
6499 }
6500
6501
6502 if (pUSBDevice.isNull())
6503 {
6504 LogFlowThisFunc(("USB device not found.\n"));
6505
6506 /* The VM may be no more operational when this message arrives
6507 * (e.g. it may be Saving or Stopping or just PoweredOff). Use
6508 * AutoVMCaller to detect it -- AutoVMCaller::hrc() will return a
6509 * failure in this case. */
6510
6511 AutoVMCallerQuiet autoVMCaller(this);
6512 if (FAILED(autoVMCaller.hrc()))
6513 {
6514 LogFlowThisFunc(("Detach request ignored (mMachineState=%d).\n", mMachineState));
6515 return autoVMCaller.hrc();
6516 }
6517
6518 /* the device must be in the list otherwise */
6519 AssertFailedReturn(E_FAIL);
6520 }
6521
6522 if (aError != NULL)
6523 {
6524 /* notify callback about an error */
6525 alock.release();
6526 i_onUSBDeviceStateChange(pUSBDevice, false /* aAttached */, aError);
6527 return S_OK;
6528 }
6529
6530 /* Remove the device from the collection, it is re-added below for failures */
6531 mUSBDevices.erase(it);
6532
6533 alock.release();
6534 HRESULT hrc = i_detachUSBDevice(pUSBDevice);
6535 if (FAILED(hrc))
6536 {
6537 /* Re-add the device to the collection */
6538 alock.acquire();
6539 mUSBDevices.push_back(pUSBDevice);
6540 alock.release();
6541 /* take the current error info */
6542 com::ErrorInfoKeeper eik;
6543 /* the error must be a VirtualBoxErrorInfo instance */
6544 ComPtr<IVirtualBoxErrorInfo> pError = eik.takeError();
6545 Assert(!pError.isNull());
6546 if (!pError.isNull())
6547 {
6548 /* notify callbacks about the error */
6549 i_onUSBDeviceStateChange(pUSBDevice, false /* aAttached */, pError);
6550 }
6551 }
6552
6553 return hrc;
6554
6555#else /* !VBOX_WITH_USB */
6556 RT_NOREF(aId, aError);
6557 return E_FAIL;
6558#endif /* !VBOX_WITH_USB */
6559}
6560
6561/**
6562 * Called by IInternalSessionControl::OnBandwidthGroupChange().
6563 *
6564 * @note Locks this object for writing.
6565 */
6566HRESULT Console::i_onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
6567{
6568 LogFlowThisFunc(("\n"));
6569
6570 AutoCaller autoCaller(this);
6571 AssertComRCReturnRC(autoCaller.hrc());
6572
6573 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6574
6575 HRESULT hrc = S_OK;
6576
6577 /* don't trigger bandwidth group changes if the VM isn't running */
6578 SafeVMPtrQuiet ptrVM(this);
6579 if (ptrVM.isOk())
6580 {
6581 if ( mMachineState == MachineState_Running
6582 || mMachineState == MachineState_Teleporting
6583 || mMachineState == MachineState_LiveSnapshotting
6584 )
6585 {
6586 /* No need to call in the EMT thread. */
6587 Bstr bstrName;
6588 hrc = aBandwidthGroup->COMGETTER(Name)(bstrName.asOutParam());
6589 if (SUCCEEDED(hrc))
6590 {
6591 Utf8Str const strName(bstrName);
6592 LONG64 cMax;
6593 hrc = aBandwidthGroup->COMGETTER(MaxBytesPerSec)(&cMax);
6594 if (SUCCEEDED(hrc))
6595 {
6596 BandwidthGroupType_T enmType;
6597 hrc = aBandwidthGroup->COMGETTER(Type)(&enmType);
6598 if (SUCCEEDED(hrc))
6599 {
6600 int vrc = VINF_SUCCESS;
6601 if (enmType == BandwidthGroupType_Disk)
6602 vrc = ptrVM.vtable()->pfnPDMR3AsyncCompletionBwMgrSetMaxForFile(ptrVM.rawUVM(), strName.c_str(),
6603 (uint32_t)cMax);
6604#ifdef VBOX_WITH_NETSHAPER
6605 else if (enmType == BandwidthGroupType_Network)
6606 vrc = ptrVM.vtable()->pfnPDMR3NsBwGroupSetLimit(ptrVM.rawUVM(), strName.c_str(), cMax);
6607 else
6608 hrc = E_NOTIMPL;
6609#endif
6610 AssertRC(vrc);
6611 }
6612 }
6613 }
6614 }
6615 else
6616 hrc = i_setInvalidMachineStateError();
6617 ptrVM.release();
6618 }
6619
6620 /* notify console callbacks on success */
6621 if (SUCCEEDED(hrc))
6622 {
6623 alock.release();
6624 ::FireBandwidthGroupChangedEvent(mEventSource, aBandwidthGroup);
6625 }
6626
6627 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
6628 return hrc;
6629}
6630
6631/**
6632 * Called by IInternalSessionControl::OnStorageDeviceChange().
6633 *
6634 * @note Locks this object for writing.
6635 */
6636HRESULT Console::i_onStorageDeviceChange(IMediumAttachment *aMediumAttachment, BOOL aRemove, BOOL aSilent)
6637{
6638 LogFlowThisFunc(("\n"));
6639
6640 AutoCaller autoCaller(this);
6641 AssertComRCReturnRC(autoCaller.hrc());
6642
6643 HRESULT hrc = S_OK;
6644
6645 /* don't trigger medium changes if the VM isn't running */
6646 SafeVMPtrQuiet ptrVM(this);
6647 if (ptrVM.isOk())
6648 {
6649 if (aRemove)
6650 hrc = i_doStorageDeviceDetach(aMediumAttachment, ptrVM.rawUVM(), ptrVM.vtable(), RT_BOOL(aSilent));
6651 else
6652 hrc = i_doStorageDeviceAttach(aMediumAttachment, ptrVM.rawUVM(), ptrVM.vtable(), RT_BOOL(aSilent));
6653 ptrVM.release();
6654 }
6655
6656 /* notify console callbacks on success */
6657 if (SUCCEEDED(hrc))
6658 ::FireStorageDeviceChangedEvent(mEventSource, aMediumAttachment, aRemove, aSilent);
6659
6660 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
6661 return hrc;
6662}
6663
6664HRESULT Console::i_onExtraDataChange(const Bstr &aMachineId, const Bstr &aKey, const Bstr &aVal)
6665{
6666 LogFlowThisFunc(("\n"));
6667
6668 AutoCaller autoCaller(this);
6669 if (FAILED(autoCaller.hrc()))
6670 return autoCaller.hrc();
6671
6672 if (aMachineId != i_getId())
6673 return S_OK;
6674
6675 /* don't do anything if the VM isn't running */
6676 if (aKey == "VBoxInternal2/TurnResetIntoPowerOff")
6677 {
6678 SafeVMPtrQuiet ptrVM(this);
6679 if (ptrVM.isOk())
6680 {
6681 mfTurnResetIntoPowerOff = aVal == "1";
6682 int vrc = ptrVM.vtable()->pfnVMR3SetPowerOffInsteadOfReset(ptrVM.rawUVM(), mfTurnResetIntoPowerOff);
6683 AssertRC(vrc);
6684
6685 ptrVM.release();
6686 }
6687 }
6688
6689 /* notify console callbacks on success */
6690 ::FireExtraDataChangedEvent(mEventSource, aMachineId.raw(), aKey.raw(), aVal.raw());
6691
6692 LogFlowThisFunc(("Leaving S_OK\n"));
6693 return S_OK;
6694}
6695
6696/**
6697 * @note Temporarily locks this object for writing.
6698 */
6699HRESULT Console::i_getGuestProperty(const Utf8Str &aName, Utf8Str *aValue, LONG64 *aTimestamp, Utf8Str *aFlags)
6700{
6701#ifndef VBOX_WITH_GUEST_PROPS
6702 ReturnComNotImplemented();
6703#else /* VBOX_WITH_GUEST_PROPS */
6704 if (!RT_VALID_PTR(aValue))
6705 return E_POINTER;
6706#ifndef VBOX_WITH_PARFAIT /** @todo Fails due to RT_VALID_PTR() being only a != NULL check with parfait. */
6707 if (aTimestamp != NULL && !RT_VALID_PTR(aTimestamp))
6708 return E_POINTER;
6709 if (aFlags != NULL && !RT_VALID_PTR(aFlags))
6710 return E_POINTER;
6711#endif
6712
6713 AutoCaller autoCaller(this);
6714 AssertComRCReturnRC(autoCaller.hrc());
6715
6716 /* protect mpUVM (if not NULL) */
6717 SafeVMPtrQuiet ptrVM(this);
6718 if (FAILED(ptrVM.hrc()))
6719 return ptrVM.hrc();
6720
6721 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
6722 * ptrVM, so there is no need to hold a lock of this */
6723
6724 HRESULT hrc = E_UNEXPECTED;
6725 try
6726 {
6727 VBOXHGCMSVCPARM parm[4];
6728 char szBuffer[GUEST_PROP_MAX_VALUE_LEN + GUEST_PROP_MAX_FLAGS_LEN];
6729
6730 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
6731 parm[0].u.pointer.addr = (void *)aName.c_str();
6732 parm[0].u.pointer.size = (uint32_t)aName.length() + 1; /* The + 1 is the null terminator */
6733
6734 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
6735 parm[1].u.pointer.addr = szBuffer;
6736 parm[1].u.pointer.size = sizeof(szBuffer);
6737
6738 parm[2].type = VBOX_HGCM_SVC_PARM_64BIT;
6739 parm[2].u.uint64 = 0;
6740
6741 parm[3].type = VBOX_HGCM_SVC_PARM_32BIT;
6742 parm[3].u.uint32 = 0;
6743
6744 int vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GUEST_PROP_FN_HOST_GET_PROP,
6745 4, &parm[0]);
6746 /* The returned string should never be able to be greater than our buffer */
6747 AssertLogRel(vrc != VERR_BUFFER_OVERFLOW);
6748 AssertLogRel(RT_FAILURE(vrc) || parm[2].type == VBOX_HGCM_SVC_PARM_64BIT);
6749 if (RT_SUCCESS(vrc))
6750 {
6751 *aValue = szBuffer;
6752
6753 if (aTimestamp)
6754 *aTimestamp = parm[2].u.uint64;
6755
6756 if (aFlags)
6757 *aFlags = &szBuffer[strlen(szBuffer) + 1];
6758
6759 hrc = S_OK;
6760 }
6761 else if (vrc == VERR_NOT_FOUND)
6762 {
6763 *aValue = "";
6764 hrc = S_OK;
6765 }
6766 else
6767 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("The VBoxGuestPropSvc service call failed with the error %Rrc"), vrc);
6768 }
6769 catch(std::bad_alloc & /*e*/)
6770 {
6771 hrc = E_OUTOFMEMORY;
6772 }
6773
6774 return hrc;
6775#endif /* VBOX_WITH_GUEST_PROPS */
6776}
6777
6778/**
6779 * @note Temporarily locks this object for writing.
6780 */
6781HRESULT Console::i_setGuestProperty(const Utf8Str &aName, const Utf8Str &aValue, const Utf8Str &aFlags)
6782{
6783#ifndef VBOX_WITH_GUEST_PROPS
6784 ReturnComNotImplemented();
6785#else /* VBOX_WITH_GUEST_PROPS */
6786
6787 AutoCaller autoCaller(this);
6788 AssertComRCReturnRC(autoCaller.hrc());
6789
6790 /* protect mpUVM (if not NULL) */
6791 SafeVMPtrQuiet ptrVM(this);
6792 if (FAILED(ptrVM.hrc()))
6793 return ptrVM.hrc();
6794
6795 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
6796 * ptrVM, so there is no need to hold a lock of this */
6797
6798 VBOXHGCMSVCPARM parm[3];
6799
6800 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
6801 parm[0].u.pointer.addr = (void*)aName.c_str();
6802 parm[0].u.pointer.size = (uint32_t)aName.length() + 1; /* The + 1 is the null terminator */
6803
6804 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
6805 parm[1].u.pointer.addr = (void *)aValue.c_str();
6806 parm[1].u.pointer.size = (uint32_t)aValue.length() + 1; /* The + 1 is the null terminator */
6807
6808 int vrc;
6809 if (aFlags.isEmpty())
6810 {
6811 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GUEST_PROP_FN_HOST_SET_PROP_VALUE, 2, &parm[0]);
6812 }
6813 else
6814 {
6815 parm[2].type = VBOX_HGCM_SVC_PARM_PTR;
6816 parm[2].u.pointer.addr = (void*)aFlags.c_str();
6817 parm[2].u.pointer.size = (uint32_t)aFlags.length() + 1; /* The + 1 is the null terminator */
6818
6819 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GUEST_PROP_FN_HOST_SET_PROP, 3, &parm[0]);
6820 }
6821
6822 HRESULT hrc = S_OK;
6823 if (RT_FAILURE(vrc))
6824 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("The VBoxGuestPropSvc service call failed with the error %Rrc"), vrc);
6825 return hrc;
6826#endif /* VBOX_WITH_GUEST_PROPS */
6827}
6828
6829HRESULT Console::i_deleteGuestProperty(const Utf8Str &aName)
6830{
6831#ifndef VBOX_WITH_GUEST_PROPS
6832 ReturnComNotImplemented();
6833#else /* VBOX_WITH_GUEST_PROPS */
6834
6835 AutoCaller autoCaller(this);
6836 AssertComRCReturnRC(autoCaller.hrc());
6837
6838 /* protect mpUVM (if not NULL) */
6839 SafeVMPtrQuiet ptrVM(this);
6840 if (FAILED(ptrVM.hrc()))
6841 return ptrVM.hrc();
6842
6843 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
6844 * ptrVM, so there is no need to hold a lock of this */
6845
6846 VBOXHGCMSVCPARM parm[1];
6847 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
6848 parm[0].u.pointer.addr = (void*)aName.c_str();
6849 parm[0].u.pointer.size = (uint32_t)aName.length() + 1; /* The + 1 is the null terminator */
6850
6851 int vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GUEST_PROP_FN_HOST_DEL_PROP, 1, &parm[0]);
6852
6853 HRESULT hrc = S_OK;
6854 if (RT_FAILURE(vrc))
6855 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("The VBoxGuestPropSvc service call failed with the error %Rrc"), vrc);
6856 return hrc;
6857#endif /* VBOX_WITH_GUEST_PROPS */
6858}
6859
6860/**
6861 * @note Temporarily locks this object for writing.
6862 */
6863HRESULT Console::i_enumerateGuestProperties(const Utf8Str &aPatterns,
6864 std::vector<Utf8Str> &aNames,
6865 std::vector<Utf8Str> &aValues,
6866 std::vector<LONG64> &aTimestamps,
6867 std::vector<Utf8Str> &aFlags)
6868{
6869#ifndef VBOX_WITH_GUEST_PROPS
6870 ReturnComNotImplemented();
6871#else /* VBOX_WITH_GUEST_PROPS */
6872
6873 AutoCaller autoCaller(this);
6874 AssertComRCReturnRC(autoCaller.hrc());
6875
6876 /* protect mpUVM (if not NULL) */
6877 AutoVMCallerWeak autoVMCaller(this);
6878 if (FAILED(autoVMCaller.hrc()))
6879 return autoVMCaller.hrc();
6880
6881 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
6882 * autoVMCaller, so there is no need to hold a lock of this */
6883
6884 return i_doEnumerateGuestProperties(aPatterns, aNames, aValues, aTimestamps, aFlags);
6885#endif /* VBOX_WITH_GUEST_PROPS */
6886}
6887
6888
6889/*
6890 * Internal: helper function for connecting progress reporting
6891 */
6892static DECLCALLBACK(int) onlineMergeMediumProgress(void *pvUser, unsigned uPercentage)
6893{
6894 HRESULT hrc = S_OK;
6895 IProgress *pProgress = static_cast<IProgress *>(pvUser);
6896 if (pProgress)
6897 {
6898 ComPtr<IInternalProgressControl> pProgressControl(pProgress);
6899 AssertReturn(!!pProgressControl, VERR_INVALID_PARAMETER);
6900 hrc = pProgressControl->SetCurrentOperationProgress(uPercentage);
6901 }
6902 return SUCCEEDED(hrc) ? VINF_SUCCESS : VERR_GENERAL_FAILURE;
6903}
6904
6905/**
6906 * @note Temporarily locks this object for writing. bird: And/or reading?
6907 */
6908HRESULT Console::i_onlineMergeMedium(IMediumAttachment *aMediumAttachment,
6909 ULONG aSourceIdx, ULONG aTargetIdx,
6910 IProgress *aProgress)
6911{
6912 AutoCaller autoCaller(this);
6913 AssertComRCReturnRC(autoCaller.hrc());
6914
6915 HRESULT hrc = S_OK;
6916 int vrc = VINF_SUCCESS;
6917
6918 /* Get the VM - must be done before the read-locking. */
6919 SafeVMPtr ptrVM(this);
6920 if (!ptrVM.isOk())
6921 return ptrVM.hrc();
6922
6923 /* We will need to release the lock before doing the actual merge */
6924 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6925
6926 /* paranoia - we don't want merges to happen while teleporting etc. */
6927 switch (mMachineState)
6928 {
6929 case MachineState_DeletingSnapshotOnline:
6930 case MachineState_DeletingSnapshotPaused:
6931 break;
6932
6933 default:
6934 return i_setInvalidMachineStateError();
6935 }
6936
6937 /** @todo AssertComRC -> AssertComRCReturn! Could potentially end up
6938 * using uninitialized variables here. */
6939 BOOL fBuiltinIOCache = FALSE;
6940 hrc = mMachine->COMGETTER(IOCacheEnabled)(&fBuiltinIOCache);
6941 AssertComRC(hrc);
6942 SafeIfaceArray<IStorageController> ctrls;
6943 hrc = mMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));
6944 AssertComRC(hrc);
6945 LONG lDev = -1;
6946 hrc = aMediumAttachment->COMGETTER(Device)(&lDev);
6947 AssertComRC(hrc);
6948 LONG lPort = -1;
6949 hrc = aMediumAttachment->COMGETTER(Port)(&lPort);
6950 AssertComRC(hrc);
6951 IMedium *pMedium = NULL;
6952 hrc = aMediumAttachment->COMGETTER(Medium)(&pMedium);
6953 AssertComRC(hrc);
6954 Bstr mediumLocation;
6955 if (pMedium)
6956 {
6957 hrc = pMedium->COMGETTER(Location)(mediumLocation.asOutParam());
6958 AssertComRC(hrc);
6959 }
6960
6961 Bstr attCtrlName;
6962 hrc = aMediumAttachment->COMGETTER(Controller)(attCtrlName.asOutParam());
6963 AssertComRC(hrc);
6964 ComPtr<IStorageController> pStorageController;
6965 for (size_t i = 0; i < ctrls.size(); ++i)
6966 {
6967 Bstr ctrlName;
6968 hrc = ctrls[i]->COMGETTER(Name)(ctrlName.asOutParam());
6969 AssertComRC(hrc);
6970 if (attCtrlName == ctrlName)
6971 {
6972 pStorageController = ctrls[i];
6973 break;
6974 }
6975 }
6976 if (pStorageController.isNull())
6977 return setError(E_FAIL,
6978 tr("Could not find storage controller '%ls'"),
6979 attCtrlName.raw());
6980
6981 StorageControllerType_T enmCtrlType;
6982 hrc = pStorageController->COMGETTER(ControllerType)(&enmCtrlType);
6983 AssertComRC(hrc);
6984 const char *pcszDevice = i_storageControllerTypeToStr(enmCtrlType);
6985
6986 StorageBus_T enmBus;
6987 hrc = pStorageController->COMGETTER(Bus)(&enmBus);
6988 AssertComRC(hrc);
6989
6990 ULONG uInstance = 0;
6991 hrc = pStorageController->COMGETTER(Instance)(&uInstance);
6992 AssertComRC(hrc);
6993
6994 BOOL fUseHostIOCache = TRUE;
6995 hrc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
6996 AssertComRC(hrc);
6997
6998 unsigned uLUN;
6999 hrc = Console::i_storageBusPortDeviceToLun(enmBus, lPort, lDev, uLUN);
7000 AssertComRCReturnRC(hrc);
7001
7002 Assert(mMachineState == MachineState_DeletingSnapshotOnline);
7003
7004 /* Pause the VM, as it might have pending IO on this drive */
7005 bool fResume = false;
7006 hrc = i_suspendBeforeConfigChange(ptrVM.rawUVM(), ptrVM.vtable(), &alock, &fResume);
7007 if (FAILED(hrc))
7008 return hrc;
7009
7010 bool fInsertDiskIntegrityDrv = false;
7011 Bstr strDiskIntegrityFlag;
7012 hrc = mMachine->GetExtraData(Bstr("VBoxInternal2/EnableDiskIntegrityDriver").raw(), strDiskIntegrityFlag.asOutParam());
7013 if ( hrc == S_OK
7014 && strDiskIntegrityFlag == "1")
7015 fInsertDiskIntegrityDrv = true;
7016
7017 alock.release();
7018
7019 Console::ReconfigureMediumAttachmentArgs Args1;
7020 Args1.pcszDevice = pcszDevice;
7021 Args1.uInstance = uInstance;
7022 Args1.enmBus = enmBus;
7023 Args1.fUseHostIOCache = fUseHostIOCache;
7024 Args1.fBuiltinIOCache = fBuiltinIOCache;
7025 Args1.fInsertDiskIntegrityDrv = fInsertDiskIntegrityDrv;
7026 Args1.fSetupMerge = true;
7027 Args1.uMergeSource = aSourceIdx;
7028 Args1.uMergeTarget = aTargetIdx;
7029 Args1.aMediumAtt = aMediumAttachment;
7030 Args1.aMachineState = mMachineState;
7031 vrc = ptrVM.vtable()->pfnVMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY, (PFNRT)i_reconfigureMediumAttachment, 5,
7032 this, ptrVM.rawUVM(), ptrVM.vtable(), &Args1, &hrc);
7033 /* error handling is after resuming the VM */
7034
7035 if (fResume)
7036 i_resumeAfterConfigChange(ptrVM.rawUVM(), ptrVM.vtable());
7037
7038 if (RT_FAILURE(vrc))
7039 return setErrorBoth(E_FAIL, vrc, "%Rrc", vrc);
7040 if (FAILED(hrc))
7041 return hrc;
7042
7043 PPDMIBASE pIBase = NULL;
7044 PPDMIMEDIA pIMedium = NULL;
7045 vrc = ptrVM.vtable()->pfnPDMR3QueryDriverOnLun(ptrVM.rawUVM(), pcszDevice, uInstance, uLUN, "VD", &pIBase);
7046 if (RT_SUCCESS(vrc))
7047 {
7048 if (pIBase)
7049 {
7050 pIMedium = (PPDMIMEDIA)pIBase->pfnQueryInterface(pIBase, PDMIMEDIA_IID);
7051 if (!pIMedium)
7052 return setError(E_FAIL, tr("could not query medium interface of controller"));
7053 }
7054 else
7055 return setError(E_FAIL, tr("could not query base interface of controller"));
7056 }
7057
7058 /* Finally trigger the merge. */
7059 vrc = pIMedium->pfnMerge(pIMedium, onlineMergeMediumProgress, aProgress);
7060 if (RT_FAILURE(vrc))
7061 return setErrorBoth(E_FAIL, vrc, tr("Failed to perform an online medium merge (%Rrc)"), vrc);
7062
7063 alock.acquire();
7064 /* Pause the VM, as it might have pending IO on this drive */
7065 hrc = i_suspendBeforeConfigChange(ptrVM.rawUVM(), ptrVM.vtable(), &alock, &fResume);
7066 if (FAILED(hrc))
7067 return hrc;
7068 alock.release();
7069
7070 /* Update medium chain and state now, so that the VM can continue. */
7071 hrc = mControl->FinishOnlineMergeMedium();
7072
7073 Console::ReconfigureMediumAttachmentArgs Args2;
7074 Args2.pcszDevice = pcszDevice;
7075 Args2.uInstance = uInstance;
7076 Args2.enmBus = enmBus;
7077 Args2.fUseHostIOCache = fUseHostIOCache;
7078 Args2.fBuiltinIOCache = fBuiltinIOCache;
7079 Args2.fInsertDiskIntegrityDrv = fInsertDiskIntegrityDrv;
7080 Args2.fSetupMerge = false;
7081 Args2.uMergeSource = 0;
7082 Args2.uMergeTarget = 0;
7083 Args2.aMediumAtt = aMediumAttachment;
7084 Args2.aMachineState = mMachineState;
7085 vrc = ptrVM.vtable()->pfnVMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY, (PFNRT)i_reconfigureMediumAttachment, 5,
7086 this, ptrVM.rawUVM(), ptrVM.vtable(), &Args2, &hrc);
7087 /* error handling is after resuming the VM */
7088
7089 if (fResume)
7090 i_resumeAfterConfigChange(ptrVM.rawUVM(), ptrVM.vtable());
7091
7092 if (RT_FAILURE(vrc))
7093 return setErrorBoth(E_FAIL, vrc, "%Rrc", vrc);
7094 if (FAILED(hrc))
7095 return hrc;
7096
7097 return hrc;
7098}
7099
7100HRESULT Console::i_reconfigureMediumAttachments(const std::vector<ComPtr<IMediumAttachment> > &aAttachments)
7101{
7102
7103 AutoCaller autoCaller(this);
7104 if (FAILED(autoCaller.hrc()))
7105 return autoCaller.hrc();
7106
7107 /* get the VM handle. */
7108 SafeVMPtr ptrVM(this);
7109 if (!ptrVM.isOk())
7110 return ptrVM.hrc();
7111
7112 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7113
7114 for (size_t i = 0; i < aAttachments.size(); ++i)
7115 {
7116 /*
7117 * We could pass the objects, but then EMT would have to do lots of
7118 * IPC (to VBoxSVC) which takes a significant amount of time.
7119 * Better query needed values here and pass them.
7120 */
7121 Bstr controllerName;
7122 HRESULT hrc = aAttachments[i]->COMGETTER(Controller)(controllerName.asOutParam());
7123 if (FAILED(hrc))
7124 return hrc;
7125
7126 ComPtr<IStorageController> pStorageController;
7127 hrc = mMachine->GetStorageControllerByName(controllerName.raw(), pStorageController.asOutParam());
7128 if (FAILED(hrc))
7129 return hrc;
7130
7131 StorageControllerType_T enmController;
7132 hrc = pStorageController->COMGETTER(ControllerType)(&enmController);
7133 if (FAILED(hrc))
7134 return hrc;
7135 const char * const pcszDevice = i_storageControllerTypeToStr(enmController);
7136
7137 ULONG lInstance;
7138 hrc = pStorageController->COMGETTER(Instance)(&lInstance);
7139 if (FAILED(hrc))
7140 return hrc;
7141
7142 StorageBus_T enmBus;
7143 hrc = pStorageController->COMGETTER(Bus)(&enmBus);
7144 if (FAILED(hrc))
7145 return hrc;
7146
7147 BOOL fUseHostIOCache;
7148 hrc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
7149 if (FAILED(hrc))
7150 return hrc;
7151
7152 BOOL fBuiltinIOCache;
7153 hrc = mMachine->COMGETTER(IOCacheEnabled)(&fBuiltinIOCache);
7154 if (FAILED(hrc))
7155 return hrc;
7156
7157 bool fInsertDiskIntegrityDrv = false;
7158 Bstr strDiskIntegrityFlag;
7159 hrc = mMachine->GetExtraData(Bstr("VBoxInternal2/EnableDiskIntegrityDriver").raw(),
7160 strDiskIntegrityFlag.asOutParam());
7161 if ( hrc == S_OK
7162 && strDiskIntegrityFlag == "1")
7163 fInsertDiskIntegrityDrv = true;
7164
7165 alock.release();
7166
7167 hrc = S_OK;
7168 Console::ReconfigureMediumAttachmentArgs Args;
7169 Args.pcszDevice = pcszDevice;
7170 Args.uInstance = lInstance;
7171 Args.enmBus = enmBus;
7172 Args.fUseHostIOCache = fUseHostIOCache;
7173 Args.fBuiltinIOCache = fBuiltinIOCache;
7174 Args.fInsertDiskIntegrityDrv = fInsertDiskIntegrityDrv;
7175 Args.fSetupMerge = false;
7176 Args.uMergeSource = 0;
7177 Args.uMergeTarget = 0;
7178 Args.aMediumAtt = aAttachments[i];
7179 Args.aMachineState = mMachineState;
7180 int vrc = ptrVM.vtable()->pfnVMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY, (PFNRT)i_reconfigureMediumAttachment, 5,
7181 this, ptrVM.rawUVM(), ptrVM.vtable(), &Args, &hrc);
7182 if (RT_FAILURE(vrc))
7183 throw setErrorBoth(E_FAIL, vrc, "%Rrc", vrc);
7184 if (FAILED(hrc))
7185 throw hrc;
7186
7187 alock.acquire();
7188 }
7189
7190 return S_OK;
7191}
7192
7193HRESULT Console::i_onVMProcessPriorityChange(VMProcPriority_T priority)
7194{
7195 AutoCaller autoCaller(this);
7196 HRESULT hrc = autoCaller.hrc();
7197 if (FAILED(hrc))
7198 return hrc;
7199
7200 RTPROCPRIORITY enmProcPriority = RTPROCPRIORITY_DEFAULT;
7201 switch (priority)
7202 {
7203 case VMProcPriority_Default:
7204 enmProcPriority = RTPROCPRIORITY_DEFAULT;
7205 break;
7206 case VMProcPriority_Flat:
7207 enmProcPriority = RTPROCPRIORITY_FLAT;
7208 break;
7209 case VMProcPriority_Low:
7210 enmProcPriority = RTPROCPRIORITY_LOW;
7211 break;
7212 case VMProcPriority_Normal:
7213 enmProcPriority = RTPROCPRIORITY_NORMAL;
7214 break;
7215 case VMProcPriority_High:
7216 enmProcPriority = RTPROCPRIORITY_HIGH;
7217 break;
7218 default:
7219 return setError(E_INVALIDARG, tr("Unsupported priority type (%d)"), priority);
7220 }
7221 int vrc = RTProcSetPriority(enmProcPriority);
7222 if (RT_FAILURE(vrc))
7223 hrc = setErrorBoth(VBOX_E_VM_ERROR, vrc,
7224 tr("Could not set the priority of the process (%Rrc). Try to set it when VM is not started."), vrc);
7225
7226 return hrc;
7227}
7228
7229/**
7230 * Load an HGCM service.
7231 *
7232 * Main purpose of this method is to allow extension packs to load HGCM
7233 * service modules, which they can't, because the HGCM functionality lives
7234 * in module VBoxC (and ConsoleImpl.cpp is part of it and thus can call it).
7235 * Extension modules must not link directly against VBoxC, (XP)COM is
7236 * handling this.
7237 */
7238int Console::i_hgcmLoadService(const char *pszServiceLibrary, const char *pszServiceName)
7239{
7240 /* Everyone seems to delegate all HGCM calls to VMMDev, so stick to this
7241 * convention. Adds one level of indirection for no obvious reason. */
7242 AssertPtrReturn(m_pVMMDev, VERR_INVALID_STATE);
7243 return m_pVMMDev->hgcmLoadService(pszServiceLibrary, pszServiceName);
7244}
7245
7246/**
7247 * Merely passes the call to Guest::enableVMMStatistics().
7248 */
7249void Console::i_enableVMMStatistics(BOOL aEnable)
7250{
7251 if (mGuest)
7252 mGuest->i_enableVMMStatistics(aEnable);
7253}
7254
7255/**
7256 * Worker for Console::Pause and internal entry point for pausing a VM for
7257 * a specific reason.
7258 */
7259HRESULT Console::i_pause(Reason_T aReason)
7260{
7261 LogFlowThisFuncEnter();
7262
7263 AutoCaller autoCaller(this);
7264 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
7265
7266 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7267
7268 switch (mMachineState)
7269 {
7270 case MachineState_Running:
7271 case MachineState_Teleporting:
7272 case MachineState_LiveSnapshotting:
7273 break;
7274
7275 case MachineState_Paused:
7276 case MachineState_TeleportingPausedVM:
7277 case MachineState_OnlineSnapshotting:
7278 /* Remove any keys which are supposed to be removed on a suspend. */
7279 if ( aReason == Reason_HostSuspend
7280 || aReason == Reason_HostBatteryLow)
7281 {
7282 i_removeSecretKeysOnSuspend();
7283 return S_OK;
7284 }
7285 return setError(VBOX_E_INVALID_VM_STATE, tr("Already paused"));
7286
7287 default:
7288 return i_setInvalidMachineStateError();
7289 }
7290
7291 /* get the VM handle. */
7292 SafeVMPtr ptrVM(this);
7293 HRESULT hrc = ptrVM.hrc();
7294 if (SUCCEEDED(hrc))
7295 {
7296 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
7297 alock.release();
7298
7299 LogFlowThisFunc(("Sending PAUSE request...\n"));
7300 if (aReason != Reason_Unspecified)
7301 LogRel(("Pausing VM execution, reason '%s'\n", ::stringifyReason(aReason)));
7302
7303 /** @todo r=klaus make use of aReason */
7304 VMSUSPENDREASON enmReason = VMSUSPENDREASON_USER;
7305 if (aReason == Reason_HostSuspend)
7306 enmReason = VMSUSPENDREASON_HOST_SUSPEND;
7307 else if (aReason == Reason_HostBatteryLow)
7308 enmReason = VMSUSPENDREASON_HOST_BATTERY_LOW;
7309
7310 int vrc = ptrVM.vtable()->pfnVMR3Suspend(ptrVM.rawUVM(), enmReason);
7311
7312 if (RT_FAILURE(vrc))
7313 hrc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not suspend the machine execution (%Rrc)"), vrc);
7314 else if ( aReason == Reason_HostSuspend
7315 || aReason == Reason_HostBatteryLow)
7316 {
7317 alock.acquire();
7318 i_removeSecretKeysOnSuspend();
7319 }
7320 }
7321
7322 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
7323 LogFlowThisFuncLeave();
7324 return hrc;
7325}
7326
7327/**
7328 * Worker for Console::Resume and internal entry point for resuming a VM for
7329 * a specific reason.
7330 */
7331HRESULT Console::i_resume(Reason_T aReason, AutoWriteLock &alock)
7332{
7333 LogFlowThisFuncEnter();
7334
7335 AutoCaller autoCaller(this);
7336 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
7337
7338 /* get the VM handle. */
7339 SafeVMPtr ptrVM(this);
7340 if (!ptrVM.isOk())
7341 return ptrVM.hrc();
7342
7343 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
7344 alock.release();
7345
7346 LogFlowThisFunc(("Sending RESUME request...\n"));
7347 if (aReason != Reason_Unspecified)
7348 LogRel(("Resuming VM execution, reason '%s'\n", ::stringifyReason(aReason)));
7349
7350 int vrc;
7351 VMSTATE const enmVMState = mpVMM->pfnVMR3GetStateU(ptrVM.rawUVM());
7352 if (enmVMState == VMSTATE_CREATED)
7353 {
7354#ifdef VBOX_WITH_EXTPACK
7355 vrc = mptrExtPackManager->i_callAllVmPowerOnHooks(this, ptrVM.vtable()->pfnVMR3GetVM(ptrVM.rawUVM()), ptrVM.vtable());
7356#else
7357 vrc = VINF_SUCCESS;
7358#endif
7359 if (RT_SUCCESS(vrc))
7360 vrc = ptrVM.vtable()->pfnVMR3PowerOn(ptrVM.rawUVM()); /* (PowerUpPaused) */
7361 }
7362 else
7363 {
7364 VMRESUMEREASON enmReason;
7365 if (aReason == Reason_HostResume)
7366 {
7367 /*
7368 * Host resume may be called multiple times successively. We don't want to VMR3Resume->vmR3Resume->vmR3TrySetState()
7369 * to assert on us, hence check for the VM state here and bail if it's not in the 'suspended' state.
7370 * See @bugref{3495}.
7371 *
7372 * Also, don't resume the VM through a host-resume unless it was suspended due to a host-suspend.
7373 */
7374 if (enmVMState != VMSTATE_SUSPENDED)
7375 {
7376 LogRel(("Ignoring VM resume request, VM is currently not suspended (%d)\n", enmVMState));
7377 return S_OK;
7378 }
7379 VMSUSPENDREASON const enmSuspendReason = ptrVM.vtable()->pfnVMR3GetSuspendReason(ptrVM.rawUVM());
7380 if (enmSuspendReason != VMSUSPENDREASON_HOST_SUSPEND)
7381 {
7382 LogRel(("Ignoring VM resume request, VM was not suspended due to host-suspend (%d)\n", enmSuspendReason));
7383 return S_OK;
7384 }
7385
7386 enmReason = VMRESUMEREASON_HOST_RESUME;
7387 }
7388 else
7389 {
7390 /*
7391 * Any other reason to resume the VM throws an error when the VM was suspended due to a host suspend.
7392 * See @bugref{7836}.
7393 */
7394 if ( enmVMState == VMSTATE_SUSPENDED
7395 && ptrVM.vtable()->pfnVMR3GetSuspendReason(ptrVM.rawUVM()) == VMSUSPENDREASON_HOST_SUSPEND)
7396 return setError(VBOX_E_INVALID_VM_STATE, tr("VM is paused due to host power management"));
7397
7398 enmReason = aReason == Reason_Snapshot ? VMRESUMEREASON_STATE_SAVED : VMRESUMEREASON_USER;
7399 }
7400
7401 // for snapshots: no state change callback, VBoxSVC does everything
7402 if (aReason == Reason_Snapshot)
7403 mVMStateChangeCallbackDisabled = true;
7404
7405 vrc = ptrVM.vtable()->pfnVMR3Resume(ptrVM.rawUVM(), enmReason);
7406
7407 if (aReason == Reason_Snapshot)
7408 mVMStateChangeCallbackDisabled = false;
7409 }
7410
7411 HRESULT hrc = RT_SUCCESS(vrc) ? S_OK
7412 : setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not resume the machine execution (%Rrc)"), vrc);
7413
7414 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
7415 LogFlowThisFuncLeave();
7416 return hrc;
7417}
7418
7419/**
7420 * Internal entry point for saving state of a VM for a specific reason. This
7421 * method is completely synchronous.
7422 *
7423 * The machine state is already set appropriately. It is only changed when
7424 * saving state actually paused the VM (happens with live snapshots and
7425 * teleportation), and in this case reflects the now paused variant.
7426 *
7427 * @note Locks this object for writing.
7428 */
7429HRESULT Console::i_saveState(Reason_T aReason, const ComPtr<IProgress> &aProgress, const ComPtr<ISnapshot> &aSnapshot,
7430 const Utf8Str &aStateFilePath, bool aPauseVM, bool &aLeftPaused)
7431{
7432 LogFlowThisFuncEnter();
7433 aLeftPaused = false;
7434
7435 AssertReturn(!aProgress.isNull(), E_INVALIDARG);
7436 AssertReturn(!aStateFilePath.isEmpty(), E_INVALIDARG);
7437 Assert(aSnapshot.isNull() || aReason == Reason_Snapshot);
7438
7439 AutoCaller autoCaller(this);
7440 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
7441
7442 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7443
7444 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
7445 if ( mMachineState != MachineState_Saving
7446 && mMachineState != MachineState_LiveSnapshotting
7447 && mMachineState != MachineState_OnlineSnapshotting
7448 && mMachineState != MachineState_Teleporting
7449 && mMachineState != MachineState_TeleportingPausedVM)
7450 return setError(VBOX_E_INVALID_VM_STATE,
7451 tr("Cannot save the execution state as the machine is not running or paused (machine state: %s)"),
7452 Global::stringifyMachineState(mMachineState));
7453 bool fContinueAfterwards = mMachineState != MachineState_Saving;
7454
7455 Bstr strDisableSaveState;
7456 mMachine->GetExtraData(Bstr("VBoxInternal2/DisableSaveState").raw(), strDisableSaveState.asOutParam());
7457 if (strDisableSaveState == "1")
7458 return setError(VBOX_E_VM_ERROR,
7459 tr("Saving the execution state is disabled for this VM"));
7460
7461 if (aReason != Reason_Unspecified)
7462 LogRel(("Saving state of VM, reason '%s'\n", ::stringifyReason(aReason)));
7463
7464 /* ensure the directory for the saved state file exists */
7465 {
7466 Utf8Str dir = aStateFilePath;
7467 dir.stripFilename();
7468 if (!RTDirExists(dir.c_str()))
7469 {
7470 int vrc = RTDirCreateFullPath(dir.c_str(), 0700);
7471 if (RT_FAILURE(vrc))
7472 return setErrorBoth(VBOX_E_FILE_ERROR, vrc, tr("Could not create a directory '%s' to save the state to (%Rrc)"),
7473 dir.c_str(), vrc);
7474 }
7475 }
7476
7477 /* Get the VM handle early, we need it in several places. */
7478 SafeVMPtr ptrVM(this);
7479 HRESULT hrc = ptrVM.hrc();
7480 if (SUCCEEDED(hrc))
7481 {
7482 bool fPaused = false;
7483 if (aPauseVM)
7484 {
7485 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
7486 alock.release();
7487 VMSUSPENDREASON enmReason = VMSUSPENDREASON_USER;
7488 if (aReason == Reason_HostSuspend)
7489 enmReason = VMSUSPENDREASON_HOST_SUSPEND;
7490 else if (aReason == Reason_HostBatteryLow)
7491 enmReason = VMSUSPENDREASON_HOST_BATTERY_LOW;
7492 int vrc = ptrVM.vtable()->pfnVMR3Suspend(ptrVM.rawUVM(), enmReason);
7493 alock.acquire();
7494
7495 if (RT_SUCCESS(vrc))
7496 fPaused = true;
7497 else
7498 hrc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not suspend the machine execution (%Rrc)"), vrc);
7499 }
7500
7501 Bstr bstrStateKeyId;
7502 Bstr bstrStateKeyStore;
7503#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
7504 if (SUCCEEDED(hrc))
7505 {
7506 hrc = mMachine->COMGETTER(StateKeyId)(bstrStateKeyId.asOutParam());
7507 if (SUCCEEDED(hrc))
7508 {
7509 hrc = mMachine->COMGETTER(StateKeyStore)(bstrStateKeyStore.asOutParam());
7510 if (FAILED(hrc))
7511 hrc = setError(hrc, tr("Could not get key store for state file(%Rhrc (0x%08X))"), hrc, hrc);
7512 }
7513 else
7514 hrc = setError(hrc, tr("Could not get key id for state file(%Rhrc (0x%08X))"), hrc, hrc);
7515 }
7516#endif
7517
7518 if (SUCCEEDED(hrc))
7519 {
7520 LogFlowFunc(("Saving the state to '%s'...\n", aStateFilePath.c_str()));
7521
7522 mpVmm2UserMethods->pISnapshot = aSnapshot;
7523 mptrCancelableProgress = aProgress;
7524
7525 SsmStream ssmStream(this, ptrVM.vtable(), m_pKeyStore, bstrStateKeyId, bstrStateKeyStore);
7526 int vrc = ssmStream.create(aStateFilePath.c_str());
7527 if (RT_SUCCESS(vrc))
7528 {
7529 PCSSMSTRMOPS pStreamOps = NULL;
7530 void *pvStreamOpsUser = NULL;
7531 vrc = ssmStream.querySsmStrmOps(&pStreamOps, &pvStreamOpsUser);
7532 if (RT_SUCCESS(vrc))
7533 {
7534 alock.release();
7535
7536 vrc = ptrVM.vtable()->pfnVMR3Save(ptrVM.rawUVM(),
7537 NULL /*pszFilename*/,
7538 pStreamOps,
7539 pvStreamOpsUser,
7540 fContinueAfterwards,
7541 Console::i_stateProgressCallback,
7542 static_cast<IProgress *>(aProgress),
7543 &aLeftPaused);
7544
7545 alock.acquire();
7546 }
7547
7548 ssmStream.close();
7549 if (RT_FAILURE(vrc))
7550 {
7551 int vrc2 = RTFileDelete(aStateFilePath.c_str());
7552 AssertRC(vrc2);
7553 }
7554 }
7555
7556 mpVmm2UserMethods->pISnapshot = NULL;
7557 mptrCancelableProgress.setNull();
7558 if (RT_SUCCESS(vrc))
7559 {
7560 Assert(fContinueAfterwards || !aLeftPaused);
7561
7562 if (!fContinueAfterwards)
7563 {
7564 /*
7565 * The machine has been successfully saved, so power it down
7566 * (vmstateChangeCallback() will set state to Saved on success).
7567 * Note: we release the VM caller, otherwise it will deadlock.
7568 */
7569 ptrVM.release();
7570 alock.release();
7571 autoCaller.release();
7572
7573 HRESULT hrc2 = i_powerDown();
7574 AssertComRC(hrc2);
7575
7576 autoCaller.add();
7577 alock.acquire();
7578 }
7579 else if (fPaused)
7580 aLeftPaused = true;
7581 }
7582 else
7583 {
7584 if (fPaused)
7585 {
7586 alock.release();
7587 ptrVM.vtable()->pfnVMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_STATE_RESTORED);
7588 alock.acquire();
7589 }
7590 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to save the machine state to '%s' (%Rrc)"),
7591 aStateFilePath.c_str(), vrc);
7592 }
7593 }
7594 }
7595
7596 LogFlowFuncLeave();
7597 return S_OK;
7598}
7599
7600/**
7601 * Internal entry point for cancelling a VM save state.
7602 *
7603 * @note Locks this object for writing.
7604 */
7605HRESULT Console::i_cancelSaveState()
7606{
7607 LogFlowThisFuncEnter();
7608
7609 AutoCaller autoCaller(this);
7610 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
7611
7612 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7613
7614 /* Get the VM handle. */
7615 SafeVMPtr ptrVM(this);
7616 HRESULT hrc = ptrVM.hrc();
7617 if (SUCCEEDED(hrc))
7618 ptrVM.vtable()->pfnSSMR3Cancel(ptrVM.rawUVM());
7619
7620 LogFlowFuncLeave();
7621 return hrc;
7622}
7623
7624#ifdef VBOX_WITH_AUDIO_RECORDING
7625/**
7626 * Sends audio (frame) data to the recording routines.
7627 *
7628 * @returns HRESULT
7629 * @param pvData Audio data to send.
7630 * @param cbData Size (in bytes) of audio data to send.
7631 * @param uTimestampMs Timestamp (in ms) of audio data.
7632 */
7633HRESULT Console::i_recordingSendAudio(const void *pvData, size_t cbData, uint64_t uTimestampMs)
7634{
7635 if ( mRecording.mCtx.IsStarted()
7636 && mRecording.mCtx.IsFeatureEnabled(RecordingFeature_Audio))
7637 {
7638 int vrc = mRecording.mCtx.SendAudioFrame(pvData, cbData, uTimestampMs);
7639 if (RT_FAILURE(vrc))
7640 return E_FAIL;
7641 }
7642
7643 return S_OK;
7644}
7645#endif /* VBOX_WITH_AUDIO_RECORDING */
7646
7647#ifdef VBOX_WITH_RECORDING
7648
7649int Console::i_recordingGetSettings(settings::Recording &Settings)
7650{
7651 Assert(mMachine.isNotNull());
7652
7653 Settings.applyDefaults();
7654
7655 ComPtr<IRecordingSettings> pRecordSettings;
7656 HRESULT hrc = mMachine->COMGETTER(RecordingSettings)(pRecordSettings.asOutParam());
7657 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7658
7659 BOOL fTemp;
7660 hrc = pRecordSettings->COMGETTER(Enabled)(&fTemp);
7661 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7662 Settings.common.fEnabled = RT_BOOL(fTemp);
7663
7664 SafeIfaceArray<IRecordingScreenSettings> paRecScreens;
7665 hrc = pRecordSettings->COMGETTER(Screens)(ComSafeArrayAsOutParam(paRecScreens));
7666 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7667
7668 for (unsigned long i = 0; i < (unsigned long)paRecScreens.size(); ++i)
7669 {
7670 settings::RecordingScreen recScreenSettings;
7671 ComPtr<IRecordingScreenSettings> pRecScreenSettings = paRecScreens[i];
7672
7673 hrc = pRecScreenSettings->COMGETTER(Enabled)(&fTemp);
7674 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7675 recScreenSettings.fEnabled = RT_BOOL(fTemp);
7676 com::SafeArray<RecordingFeature_T> vecFeatures;
7677 hrc = pRecScreenSettings->COMGETTER(Features)(ComSafeArrayAsOutParam(vecFeatures));
7678 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7679 /* Make sure to clear map first, as we want to (re-)set enabled features. */
7680 recScreenSettings.featureMap.clear();
7681 for (size_t f = 0; f < vecFeatures.size(); ++f)
7682 {
7683 if (vecFeatures[f] == RecordingFeature_Audio)
7684 recScreenSettings.featureMap[RecordingFeature_Audio] = true;
7685 else if (vecFeatures[f] == RecordingFeature_Video)
7686 recScreenSettings.featureMap[RecordingFeature_Video] = true;
7687 }
7688 hrc = pRecScreenSettings->COMGETTER(MaxTime)((ULONG *)&recScreenSettings.ulMaxTimeS);
7689 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7690 hrc = pRecScreenSettings->COMGETTER(MaxFileSize)((ULONG *)&recScreenSettings.File.ulMaxSizeMB);
7691 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7692 Bstr bstrTemp;
7693 hrc = pRecScreenSettings->COMGETTER(Filename)(bstrTemp.asOutParam());
7694 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7695 recScreenSettings.File.strName = bstrTemp;
7696 hrc = pRecScreenSettings->COMGETTER(Options)(bstrTemp.asOutParam());
7697 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7698 recScreenSettings.strOptions = bstrTemp;
7699 hrc = pRecScreenSettings->COMGETTER(AudioCodec)(&recScreenSettings.Audio.enmCodec);
7700 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7701 hrc = pRecScreenSettings->COMGETTER(AudioDeadline)(&recScreenSettings.Audio.enmDeadline);
7702 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7703 hrc = pRecScreenSettings->COMGETTER(AudioRateControlMode)(&recScreenSettings.Audio.enmRateCtlMode);
7704 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7705 hrc = pRecScreenSettings->COMGETTER(AudioHz)((ULONG *)&recScreenSettings.Audio.uHz);
7706 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7707 hrc = pRecScreenSettings->COMGETTER(AudioBits)((ULONG *)&recScreenSettings.Audio.cBits);
7708 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7709 hrc = pRecScreenSettings->COMGETTER(AudioChannels)((ULONG *)&recScreenSettings.Audio.cChannels);
7710 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7711 hrc = pRecScreenSettings->COMGETTER(VideoCodec)(&recScreenSettings.Video.enmCodec);
7712 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7713 hrc = pRecScreenSettings->COMGETTER(VideoWidth)((ULONG *)&recScreenSettings.Video.ulWidth);
7714 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7715 hrc = pRecScreenSettings->COMGETTER(VideoHeight)((ULONG *)&recScreenSettings.Video.ulHeight);
7716 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7717 hrc = pRecScreenSettings->COMGETTER(VideoDeadline)(&recScreenSettings.Video.enmDeadline);
7718 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7719 hrc = pRecScreenSettings->COMGETTER(VideoRateControlMode)(&recScreenSettings.Video.enmRateCtlMode);
7720 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7721 hrc = pRecScreenSettings->COMGETTER(VideoScalingMode)(&recScreenSettings.Video.enmScalingMode);
7722 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7723 hrc = pRecScreenSettings->COMGETTER(VideoRate)((ULONG *)&recScreenSettings.Video.ulRate);
7724 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7725 hrc = pRecScreenSettings->COMGETTER(VideoFPS)((ULONG *)&recScreenSettings.Video.ulFPS);
7726 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7727
7728 Settings.mapScreens[i] = recScreenSettings;
7729 }
7730
7731 Assert(Settings.mapScreens.size() == paRecScreens.size());
7732
7733 return VINF_SUCCESS;
7734}
7735
7736/**
7737 * Creates the recording context.
7738 *
7739 * @returns VBox status code.
7740 */
7741int Console::i_recordingCreate(ComPtr<IProgress> &pProgress)
7742{
7743 settings::Recording Settings;
7744 int vrc = i_recordingGetSettings(Settings);
7745 if (RT_SUCCESS(vrc))
7746 vrc = mRecording.mCtx.Create(this, Settings, pProgress);
7747
7748 if (RT_FAILURE(vrc))
7749 setErrorBoth(VBOX_E_RECORDING_ERROR, vrc, tr("Recording initialization failed (%Rrc) -- please consult log file for details"), vrc);
7750
7751 LogFlowFuncLeaveRC(vrc);
7752 return vrc;
7753}
7754
7755/**
7756 * Destroys the recording context.
7757 */
7758void Console::i_recordingDestroy(void)
7759{
7760 mRecording.mCtx.Destroy();
7761}
7762
7763/**
7764 * Starts recording. Does nothing if recording is already started.
7765 *
7766 * @returns VBox status code.
7767 */
7768int Console::i_recordingStart(util::AutoWriteLock *pAutoLock /* = NULL */)
7769{
7770 RT_NOREF(pAutoLock);
7771
7772 if (mRecording.mCtx.IsStarted())
7773 return VINF_SUCCESS;
7774
7775 int vrc = mRecording.mCtx.Start();
7776 if (RT_SUCCESS(vrc))
7777 vrc = mDisplay->i_recordingStart();
7778
7779 if (RT_FAILURE(vrc))
7780 mRecording.mCtx.SetError(vrc, Utf8StrFmt(tr("Recording start failed (%Rrc)"), vrc).c_str());
7781
7782 LogFlowFuncLeaveRC(vrc);
7783 return vrc;
7784}
7785
7786/**
7787 * Stops recording. Does nothing if recording is not in started state.
7788 *
7789 * Note: This does *not* disable recording for a VM, in other words,
7790 * it does not change the VM's recording (enabled) setting.
7791 */
7792int Console::i_recordingStop(util::AutoWriteLock *)
7793{
7794 if (!mRecording.mCtx.IsStarted())
7795 return VINF_SUCCESS;
7796
7797 int vrc = mRecording.mCtx.Stop();
7798 if (RT_SUCCESS(vrc))
7799 vrc = mDisplay->i_recordingStop();
7800
7801 if (RT_FAILURE(vrc))
7802 setErrorBoth(VBOX_E_RECORDING_ERROR, vrc, tr("Recording stop failed (%Rrc)"), vrc);
7803
7804 LogFlowFuncLeaveRC(vrc);
7805 return vrc;
7806}
7807
7808/**
7809 * Sends a cursor shape change to the recording context.
7810 *
7811 * @returns VBox status code.
7812 * @param fVisible Whether the mouse cursor actually is visible or not.
7813 * @param fAlpha Whether the pixel data contains alpha channel information or not.
7814 * @param xHot X hot position (in pixel) of the new cursor.
7815 * @param yHot Y hot position (in pixel) of the new cursor.
7816 * @param uWidth Width (in pixel) of the new cursor.
7817 * @param uHeight Height (in pixel) of the new cursor.
7818 * @param pu8Shape Pixel data of the new cursor.
7819 * @param cbShape Size of \a pu8Shape (in bytes).
7820 */
7821int Console::i_recordingCursorShapeChange(bool fVisible, bool fAlpha, uint32_t xHot, uint32_t yHot, uint32_t uWidth, uint32_t uHeight, const uint8_t *pu8Shape, uint32_t cbShape)
7822{
7823 if (!mRecording.mCtx.IsStarted())
7824 return VINF_SUCCESS;
7825
7826 return mRecording.mCtx.SendCursorShapeChange(fVisible, fAlpha, xHot, yHot, uWidth, uHeight, pu8Shape, cbShape,
7827 mRecording.mCtx.GetCurrentPTS());
7828}
7829#endif /* VBOX_WITH_RECORDING */
7830
7831/**
7832 * Gets called by Session::UpdateMachineState()
7833 * (IInternalSessionControl::updateMachineState()).
7834 *
7835 * Must be called only in certain cases (see the implementation).
7836 *
7837 * @note Locks this object for writing.
7838 */
7839HRESULT Console::i_updateMachineState(MachineState_T aMachineState)
7840{
7841 AutoCaller autoCaller(this);
7842 AssertComRCReturnRC(autoCaller.hrc());
7843
7844 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7845
7846 AssertReturn( mMachineState == MachineState_Saving
7847 || mMachineState == MachineState_OnlineSnapshotting
7848 || mMachineState == MachineState_LiveSnapshotting
7849 || mMachineState == MachineState_DeletingSnapshotOnline
7850 || mMachineState == MachineState_DeletingSnapshotPaused
7851 || aMachineState == MachineState_Saving
7852 || aMachineState == MachineState_OnlineSnapshotting
7853 || aMachineState == MachineState_LiveSnapshotting
7854 || aMachineState == MachineState_DeletingSnapshotOnline
7855 || aMachineState == MachineState_DeletingSnapshotPaused
7856 , E_FAIL);
7857
7858 return i_setMachineStateLocally(aMachineState);
7859}
7860
7861/**
7862 * Gets called by Session::COMGETTER(NominalState)()
7863 * (IInternalSessionControl::getNominalState()).
7864 *
7865 * @note Locks this object for reading.
7866 */
7867HRESULT Console::i_getNominalState(MachineState_T &aNominalState)
7868{
7869 LogFlowThisFuncEnter();
7870
7871 AutoCaller autoCaller(this);
7872 AssertComRCReturnRC(autoCaller.hrc());
7873
7874 /* Get the VM handle. */
7875 SafeVMPtr ptrVM(this);
7876 if (!ptrVM.isOk())
7877 return ptrVM.hrc();
7878
7879 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7880
7881 MachineState_T enmMachineState = MachineState_Null;
7882 VMSTATE enmVMState = ptrVM.vtable()->pfnVMR3GetStateU(ptrVM.rawUVM());
7883 switch (enmVMState)
7884 {
7885 case VMSTATE_CREATING:
7886 case VMSTATE_CREATED:
7887 case VMSTATE_POWERING_ON:
7888 enmMachineState = MachineState_Starting;
7889 break;
7890 case VMSTATE_LOADING:
7891 enmMachineState = MachineState_Restoring;
7892 break;
7893 case VMSTATE_RESUMING:
7894 case VMSTATE_SUSPENDING:
7895 case VMSTATE_SUSPENDING_LS:
7896 case VMSTATE_SUSPENDING_EXT_LS:
7897 case VMSTATE_SUSPENDED:
7898 case VMSTATE_SUSPENDED_LS:
7899 case VMSTATE_SUSPENDED_EXT_LS:
7900 enmMachineState = MachineState_Paused;
7901 break;
7902 case VMSTATE_RUNNING:
7903 case VMSTATE_RUNNING_LS:
7904 case VMSTATE_RESETTING:
7905 case VMSTATE_RESETTING_LS:
7906 case VMSTATE_SOFT_RESETTING:
7907 case VMSTATE_SOFT_RESETTING_LS:
7908 case VMSTATE_DEBUGGING:
7909 case VMSTATE_DEBUGGING_LS:
7910 enmMachineState = MachineState_Running;
7911 break;
7912 case VMSTATE_SAVING:
7913 enmMachineState = MachineState_Saving;
7914 break;
7915 case VMSTATE_POWERING_OFF:
7916 case VMSTATE_POWERING_OFF_LS:
7917 case VMSTATE_DESTROYING:
7918 enmMachineState = MachineState_Stopping;
7919 break;
7920 case VMSTATE_OFF:
7921 case VMSTATE_OFF_LS:
7922 case VMSTATE_FATAL_ERROR:
7923 case VMSTATE_FATAL_ERROR_LS:
7924 case VMSTATE_LOAD_FAILURE:
7925 case VMSTATE_TERMINATED:
7926 enmMachineState = MachineState_PoweredOff;
7927 break;
7928 case VMSTATE_GURU_MEDITATION:
7929 case VMSTATE_GURU_MEDITATION_LS:
7930 enmMachineState = MachineState_Stuck;
7931 break;
7932 default:
7933 AssertMsgFailed(("%s\n", ptrVM.vtable()->pfnVMR3GetStateName(enmVMState)));
7934 enmMachineState = MachineState_PoweredOff;
7935 }
7936 aNominalState = enmMachineState;
7937
7938 LogFlowFuncLeave();
7939 return S_OK;
7940}
7941
7942void Console::i_onMousePointerShapeChange(bool fVisible, bool fAlpha,
7943 uint32_t xHot, uint32_t yHot,
7944 uint32_t width, uint32_t height,
7945 const uint8_t *pu8Shape,
7946 uint32_t cbShape)
7947{
7948#if 0
7949 LogFlowThisFuncEnter();
7950 LogFlowThisFunc(("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, height=%d, shape=%p\n",
7951 fVisible, fAlpha, xHot, yHot, width, height, pShape));
7952#endif
7953
7954 AutoCaller autoCaller(this);
7955 AssertComRCReturnVoid(autoCaller.hrc());
7956
7957 if (!mMouse.isNull())
7958 mMouse->i_updatePointerShape(fVisible, fAlpha, xHot, yHot, width, height, pu8Shape, cbShape);
7959
7960 com::SafeArray<BYTE> shape(cbShape);
7961 if (pu8Shape)
7962 memcpy(shape.raw(), pu8Shape, cbShape);
7963 ::FireMousePointerShapeChangedEvent(mEventSource, fVisible, fAlpha, xHot, yHot, width, height, ComSafeArrayAsInParam(shape));
7964
7965#ifdef VBOX_WITH_RECORDING
7966 i_recordingCursorShapeChange(fVisible, fAlpha, xHot, yHot, width, height, pu8Shape, cbShape);
7967#endif
7968
7969#if 0
7970 LogFlowThisFuncLeave();
7971#endif
7972}
7973
7974void Console::i_onMouseCapabilityChange(BOOL supportsAbsolute, BOOL supportsRelative,
7975 BOOL supportsTouchScreen, BOOL supportsTouchPad, BOOL needsHostCursor)
7976{
7977 LogFlowThisFunc(("supportsAbsolute=%d supportsRelative=%d supportsTouchScreen=%d supportsTouchPad=%d needsHostCursor=%d\n",
7978 supportsAbsolute, supportsRelative, supportsTouchScreen, supportsTouchPad, needsHostCursor));
7979
7980 AutoCaller autoCaller(this);
7981 AssertComRCReturnVoid(autoCaller.hrc());
7982
7983 ::FireMouseCapabilityChangedEvent(mEventSource, supportsAbsolute, supportsRelative, supportsTouchScreen, supportsTouchPad, needsHostCursor);
7984}
7985
7986void Console::i_onStateChange(MachineState_T machineState)
7987{
7988 AutoCaller autoCaller(this);
7989 AssertComRCReturnVoid(autoCaller.hrc());
7990 ::FireStateChangedEvent(mEventSource, machineState);
7991}
7992
7993void Console::i_onAdditionsStateChange()
7994{
7995 AutoCaller autoCaller(this);
7996 AssertComRCReturnVoid(autoCaller.hrc());
7997
7998 ::FireAdditionsStateChangedEvent(mEventSource);
7999}
8000
8001/**
8002 * @remarks This notification only is for reporting an incompatible
8003 * Guest Additions interface, *not* the Guest Additions version!
8004 *
8005 * The user will be notified inside the guest if new Guest
8006 * Additions are available (via VBoxTray/VBoxClient).
8007 */
8008void Console::i_onAdditionsOutdated()
8009{
8010 AutoCaller autoCaller(this);
8011 AssertComRCReturnVoid(autoCaller.hrc());
8012
8013 /** @todo implement this */
8014}
8015
8016void Console::i_onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
8017{
8018 AutoCaller autoCaller(this);
8019 AssertComRCReturnVoid(autoCaller.hrc());
8020
8021 ::FireKeyboardLedsChangedEvent(mEventSource, fNumLock, fCapsLock, fScrollLock);
8022}
8023
8024void Console::i_onUSBDeviceStateChange(IUSBDevice *aDevice, bool aAttached,
8025 IVirtualBoxErrorInfo *aError)
8026{
8027 AutoCaller autoCaller(this);
8028 AssertComRCReturnVoid(autoCaller.hrc());
8029
8030 ::FireUSBDeviceStateChangedEvent(mEventSource, aDevice, aAttached, aError);
8031}
8032
8033void Console::i_onRuntimeError(BOOL aFatal, IN_BSTR aErrorID, IN_BSTR aMessage)
8034{
8035 AutoCaller autoCaller(this);
8036 AssertComRCReturnVoid(autoCaller.hrc());
8037
8038 ::FireRuntimeErrorEvent(mEventSource, aFatal, aErrorID, aMessage);
8039}
8040
8041HRESULT Console::i_onShowWindow(BOOL aCheck, BOOL *aCanShow, LONG64 *aWinId)
8042{
8043 AssertReturn(aCanShow, E_POINTER);
8044 AssertReturn(aWinId, E_POINTER);
8045
8046 *aCanShow = FALSE;
8047 *aWinId = 0;
8048
8049 AutoCaller autoCaller(this);
8050 AssertComRCReturnRC(autoCaller.hrc());
8051
8052 ComPtr<IEvent> ptrEvent;
8053 if (aCheck)
8054 {
8055 *aCanShow = TRUE;
8056 HRESULT hrc = ::CreateCanShowWindowEvent(ptrEvent.asOutParam(), mEventSource);
8057 if (SUCCEEDED(hrc))
8058 {
8059 VBoxEventDesc EvtDesc(ptrEvent, mEventSource);
8060 BOOL fDelivered = EvtDesc.fire(5000); /* Wait up to 5 secs for delivery */
8061 //Assert(fDelivered);
8062 if (fDelivered)
8063 {
8064 // bit clumsy
8065 ComPtr<ICanShowWindowEvent> ptrCanShowEvent = ptrEvent;
8066 if (ptrCanShowEvent)
8067 {
8068 BOOL fVetoed = FALSE;
8069 BOOL fApproved = FALSE;
8070 ptrCanShowEvent->IsVetoed(&fVetoed);
8071 ptrCanShowEvent->IsApproved(&fApproved);
8072 *aCanShow = fApproved || !fVetoed;
8073 }
8074 else
8075 AssertFailed();
8076 }
8077 }
8078 }
8079 else
8080 {
8081 HRESULT hrc = ::CreateShowWindowEvent(ptrEvent.asOutParam(), mEventSource, 0);
8082 if (SUCCEEDED(hrc))
8083 {
8084 VBoxEventDesc EvtDesc(ptrEvent, mEventSource);
8085 BOOL fDelivered = EvtDesc.fire(5000); /* Wait up to 5 secs for delivery */
8086 //Assert(fDelivered);
8087 if (fDelivered)
8088 {
8089 ComPtr<IShowWindowEvent> ptrShowEvent = ptrEvent;
8090 if (ptrShowEvent)
8091 {
8092 LONG64 idWindow = 0;
8093 ptrShowEvent->COMGETTER(WinId)(&idWindow);
8094 if (idWindow != 0 && *aWinId == 0)
8095 *aWinId = idWindow;
8096 }
8097 else
8098 AssertFailed();
8099 }
8100 }
8101 }
8102
8103 return S_OK;
8104}
8105
8106// private methods
8107////////////////////////////////////////////////////////////////////////////////
8108
8109/**
8110 * Loads the VMM if needed.
8111 *
8112 * @returns COM status.
8113 * @param pszVMMMod The VMM module to load.
8114 * @remarks Caller must write lock the console object.
8115 */
8116HRESULT Console::i_loadVMM(const char *pszVMMMod) RT_NOEXCEPT
8117{
8118 if ( mhModVMM == NIL_RTLDRMOD
8119 || mpVMM == NULL)
8120 {
8121 Assert(!mpVMM);
8122
8123 HRESULT hrc;
8124 RTERRINFOSTATIC ErrInfo;
8125 RTLDRMOD hModVMM = NIL_RTLDRMOD;
8126 int vrc = SUPR3HardenedLdrLoadAppPriv(pszVMMMod, &hModVMM, RTLDRLOAD_FLAGS_LOCAL, RTErrInfoInitStatic(&ErrInfo));
8127 if (RT_SUCCESS(vrc))
8128 {
8129 PFNVMMGETVTABLE pfnGetVTable = NULL;
8130 vrc = RTLdrGetSymbol(hModVMM, VMMR3VTABLE_GETTER_NAME, (void **)&pfnGetVTable);
8131 if (pfnGetVTable)
8132 {
8133 PCVMMR3VTABLE pVMM = pfnGetVTable();
8134 if (pVMM)
8135 {
8136 if (VMMR3VTABLE_IS_COMPATIBLE(pVMM->uMagicVersion))
8137 {
8138 if (pVMM->uMagicVersion == pVMM->uMagicVersionEnd)
8139 {
8140 mhModVMM = hModVMM;
8141 mpVMM = pVMM;
8142 LogFunc(("mhLdrVMM=%p phVMM=%p uMagicVersion=%#RX64\n", hModVMM, pVMM, pVMM->uMagicVersion));
8143 return S_OK;
8144 }
8145
8146 hrc = setErrorVrc(vrc, "Bogus VMM vtable: uMagicVersion=%#RX64 uMagicVersionEnd=%#RX64",
8147 pVMM->uMagicVersion, pVMM->uMagicVersionEnd);
8148 }
8149 else
8150 hrc = setErrorVrc(vrc, "Incompatible of bogus VMM version magic: %#RX64", pVMM->uMagicVersion);
8151 }
8152 else
8153 hrc = setErrorVrc(vrc, "pfnGetVTable return NULL!");
8154 }
8155 else
8156 hrc = setErrorVrc(vrc, "Failed to locate symbol '%s' in VBoxVMM: %Rrc", VMMR3VTABLE_GETTER_NAME, vrc);
8157 RTLdrClose(hModVMM);
8158 }
8159 else
8160 hrc = setErrorVrc(vrc, "Failed to load VBoxVMM: %#RTeic", &ErrInfo.Core);
8161 return hrc;
8162 }
8163
8164 return S_OK;
8165}
8166
8167/**
8168 * Increases the usage counter of the mpUVM pointer.
8169 *
8170 * Guarantees that VMR3Destroy() will not be called on it at least until
8171 * releaseVMCaller() is called.
8172 *
8173 * If this method returns a failure, the caller is not allowed to use mpUVM and
8174 * may return the failed result code to the upper level. This method sets the
8175 * extended error info on failure if \a aQuiet is false.
8176 *
8177 * Setting \a aQuiet to true is useful for methods that don't want to return
8178 * the failed result code to the caller when this method fails (e.g. need to
8179 * silently check for the mpUVM availability).
8180 *
8181 * When mpUVM is NULL but \a aAllowNullVM is true, a corresponding error will be
8182 * returned instead of asserting. Having it false is intended as a sanity check
8183 * for methods that have checked mMachineState and expect mpUVM *NOT* to be
8184 * NULL.
8185 *
8186 * @param aQuiet true to suppress setting error info
8187 * @param aAllowNullVM true to accept mpUVM being NULL and return a failure
8188 * (otherwise this method will assert if mpUVM is NULL)
8189 *
8190 * @note Locks this object for writing.
8191 */
8192HRESULT Console::i_addVMCaller(bool aQuiet /* = false */,
8193 bool aAllowNullVM /* = false */)
8194{
8195 RT_NOREF(aAllowNullVM);
8196 AutoCaller autoCaller(this);
8197 /** @todo Fix race during console/VM reference destruction, refer @bugref{6318}
8198 * comment 25. */
8199 if (FAILED(autoCaller.hrc()))
8200 return autoCaller.hrc();
8201
8202 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8203
8204 if (mVMDestroying)
8205 {
8206 /* powerDown() is waiting for all callers to finish */
8207 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED, tr("The virtual machine is being powered down"));
8208 }
8209
8210 if (mpUVM == NULL)
8211 {
8212 Assert(aAllowNullVM == true);
8213
8214 /* The machine is not powered up */
8215 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED, tr("The virtual machine is not powered up"));
8216 }
8217
8218 ++mVMCallers;
8219
8220 return S_OK;
8221}
8222
8223/**
8224 * Decreases the usage counter of the mpUVM pointer.
8225 *
8226 * Must always complete the addVMCaller() call after the mpUVM pointer is no
8227 * more necessary.
8228 *
8229 * @note Locks this object for writing.
8230 */
8231void Console::i_releaseVMCaller()
8232{
8233 AutoCaller autoCaller(this);
8234 AssertComRCReturnVoid(autoCaller.hrc());
8235
8236 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8237
8238 AssertReturnVoid(mpUVM != NULL);
8239
8240 Assert(mVMCallers > 0);
8241 --mVMCallers;
8242
8243 if (mVMCallers == 0 && mVMDestroying)
8244 {
8245 /* inform powerDown() there are no more callers */
8246 RTSemEventSignal(mVMZeroCallersSem);
8247 }
8248}
8249
8250
8251/**
8252 * Helper for SafeVMPtrBase.
8253 */
8254HRESULT Console::i_safeVMPtrRetainer(PUVM *a_ppUVM, PCVMMR3VTABLE *a_ppVMM, bool a_Quiet) RT_NOEXCEPT
8255{
8256 *a_ppUVM = NULL;
8257 *a_ppVMM = NULL;
8258
8259 AutoCaller autoCaller(this);
8260 AssertComRCReturnRC(autoCaller.hrc());
8261 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8262
8263 /*
8264 * Repeat the checks done by addVMCaller.
8265 */
8266 if (mVMDestroying) /* powerDown() is waiting for all callers to finish */
8267 return a_Quiet
8268 ? E_ACCESSDENIED
8269 : setError(E_ACCESSDENIED, tr("The virtual machine is being powered down"));
8270 PUVM const pUVM = mpUVM;
8271 if (!pUVM)
8272 return a_Quiet
8273 ? E_ACCESSDENIED
8274 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
8275 PCVMMR3VTABLE const pVMM = mpVMM;
8276 if (!pVMM)
8277 return a_Quiet
8278 ? E_ACCESSDENIED
8279 : setError(E_ACCESSDENIED, tr("No VMM loaded!"));
8280
8281 /*
8282 * Retain a reference to the user mode VM handle and get the global handle.
8283 */
8284 uint32_t cRefs = pVMM->pfnVMR3RetainUVM(pUVM);
8285 if (cRefs == UINT32_MAX)
8286 return a_Quiet
8287 ? E_ACCESSDENIED
8288 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
8289
8290 /* done */
8291 *a_ppUVM = pUVM;
8292 *a_ppVMM = pVMM;
8293 return S_OK;
8294}
8295
8296void Console::i_safeVMPtrReleaser(PUVM *a_ppUVM)
8297{
8298 PUVM const pUVM = *a_ppUVM;
8299 *a_ppUVM = NULL;
8300 if (pUVM)
8301 {
8302 PCVMMR3VTABLE const pVMM = mpVMM;
8303 if (pVMM)
8304 pVMM->pfnVMR3ReleaseUVM(pUVM);
8305 }
8306}
8307
8308#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
8309
8310/*static*/ DECLCALLBACK(int)
8311Console::i_logEncryptedDirCtxOpen(PCRTLOGOUTPUTIF pIf, void *pvUser, const char *pszFilename, void **ppvDirCtx)
8312{
8313 RT_NOREF(pIf, pvUser, pszFilename, ppvDirCtx);
8314 *ppvDirCtx = (void *)(intptr_t)22;
8315 return VINF_SUCCESS;
8316}
8317
8318/*static*/ DECLCALLBACK(int)
8319Console::i_logEncryptedDirCtxClose(PCRTLOGOUTPUTIF pIf, void *pvUser, void *pvDirCtx)
8320{
8321 RT_NOREF(pIf, pvUser, pvDirCtx);
8322 Assert((intptr_t)pvDirCtx == 22);
8323 return VINF_SUCCESS;
8324}
8325
8326/*static*/ DECLCALLBACK(int)
8327Console::i_logEncryptedDelete(PCRTLOGOUTPUTIF pIf, void *pvUser, void *pvDirCtx, const char *pszFilename)
8328{
8329 RT_NOREF(pIf, pvDirCtx, pvUser);
8330 return RTFileDelete(pszFilename);
8331}
8332
8333
8334/*static*/ DECLCALLBACK(int)
8335Console::i_logEncryptedRename(PCRTLOGOUTPUTIF pIf, void *pvUser, void *pvDirCtx,
8336 const char *pszFilenameOld, const char *pszFilenameNew, uint32_t fFlags)
8337{
8338 RT_NOREF(pIf, pvDirCtx, pvUser);
8339 return RTFileRename(pszFilenameOld, pszFilenameNew, fFlags);
8340}
8341
8342/*static*/ DECLCALLBACK(int)
8343Console::i_logEncryptedOpen(PCRTLOGOUTPUTIF pIf, void *pvUser, void *pvDirCtx, const char *pszFilename, uint32_t fFlags)
8344{
8345 RT_NOREF(pIf, pvDirCtx);
8346 Console *pConsole = static_cast<Console *>(pvUser);
8347 RTVFSFILE hVfsFile = NIL_RTVFSFILE;
8348
8349 int vrc = RTVfsFileOpenNormal(pszFilename, fFlags, &hVfsFile);
8350 if (RT_SUCCESS(vrc))
8351 {
8352 PCVBOXCRYPTOIF pCryptoIf = NULL;
8353 vrc = pConsole->i_retainCryptoIf(&pCryptoIf);
8354 if (RT_SUCCESS(vrc))
8355 {
8356 SecretKey *pKey = NULL;
8357
8358 vrc = pConsole->m_pKeyStore->retainSecretKey(pConsole->m_strLogKeyId, &pKey);
8359 if (RT_SUCCESS(vrc))
8360 {
8361 const char *pszPassword = (const char *)pKey->getKeyBuffer();
8362
8363 vrc = pCryptoIf->pfnCryptoFileFromVfsFile(hVfsFile, pConsole->m_strLogKeyStore.c_str(), pszPassword,
8364 &pConsole->m_hVfsFileLog);
8365 pKey->release();
8366 }
8367
8368 /* On success we keep the reference to keep the cryptographic module loaded. */
8369 if (RT_FAILURE(vrc))
8370 pConsole->i_releaseCryptoIf(pCryptoIf);
8371 }
8372
8373 /* Always do this because the encrypted log has retained a reference to the underlying file. */
8374 RTVfsFileRelease(hVfsFile);
8375 if (RT_FAILURE(vrc))
8376 RTFileDelete(pszFilename);
8377 }
8378
8379 return vrc;
8380}
8381
8382
8383/*static*/ DECLCALLBACK(int)
8384Console::i_logEncryptedClose(PCRTLOGOUTPUTIF pIf, void *pvUser)
8385{
8386 RT_NOREF(pIf);
8387 Console *pConsole = static_cast<Console *>(pvUser);
8388
8389 RTVfsFileRelease(pConsole->m_hVfsFileLog);
8390 pConsole->m_hVfsFileLog = NIL_RTVFSFILE;
8391 return VINF_SUCCESS;
8392}
8393
8394
8395/*static*/ DECLCALLBACK(int)
8396Console::i_logEncryptedQuerySize(PCRTLOGOUTPUTIF pIf, void *pvUser, uint64_t *pcbSize)
8397{
8398 RT_NOREF(pIf);
8399 Console *pConsole = static_cast<Console *>(pvUser);
8400
8401 return RTVfsFileQuerySize(pConsole->m_hVfsFileLog, pcbSize);
8402}
8403
8404
8405/*static*/ DECLCALLBACK(int)
8406Console::i_logEncryptedWrite(PCRTLOGOUTPUTIF pIf, void *pvUser, const void *pvBuf, size_t cbWrite, size_t *pcbWritten)
8407{
8408 RT_NOREF(pIf);
8409 Console *pConsole = static_cast<Console *>(pvUser);
8410
8411 return RTVfsFileWrite(pConsole->m_hVfsFileLog, pvBuf, cbWrite, pcbWritten);
8412}
8413
8414
8415/*static*/ DECLCALLBACK(int)
8416Console::i_logEncryptedFlush(PCRTLOGOUTPUTIF pIf, void *pvUser)
8417{
8418 RT_NOREF(pIf);
8419 Console *pConsole = static_cast<Console *>(pvUser);
8420
8421 return RTVfsFileFlush(pConsole->m_hVfsFileLog);
8422}
8423
8424
8425/*static*/ RTLOGOUTPUTIF const Console::s_ConsoleEncryptedLogOutputIf =
8426{
8427 Console::i_logEncryptedDirCtxOpen,
8428 Console::i_logEncryptedDirCtxClose,
8429 Console::i_logEncryptedDelete,
8430 Console::i_logEncryptedRename,
8431 Console::i_logEncryptedOpen,
8432 Console::i_logEncryptedClose,
8433 Console::i_logEncryptedQuerySize,
8434 Console::i_logEncryptedWrite,
8435 Console::i_logEncryptedFlush
8436};
8437
8438#endif /* VBOX_WITH_FULL_VM_ENCRYPTION */
8439
8440/**
8441 * Initialize the release logging facility. In case something
8442 * goes wrong, there will be no release logging. Maybe in the future
8443 * we can add some logic to use different file names in this case.
8444 * Note that the logic must be in sync with Machine::DeleteSettings().
8445 */
8446HRESULT Console::i_consoleInitReleaseLog(const ComPtr<IMachine> aMachine)
8447{
8448 Bstr bstrLogFolder;
8449 HRESULT hrc = aMachine->COMGETTER(LogFolder)(bstrLogFolder.asOutParam());
8450 if (FAILED(hrc))
8451 return hrc;
8452 Utf8Str strLogDir = bstrLogFolder;
8453
8454 /* make sure the Logs folder exists */
8455 Assert(strLogDir.length());
8456 if (!RTDirExists(strLogDir.c_str()))
8457 RTDirCreateFullPath(strLogDir.c_str(), 0700);
8458
8459 Utf8StrFmt logFile("%s%cVBox.log", strLogDir.c_str(), RTPATH_DELIMITER);
8460 Utf8StrFmt pngFile("%s%cVBox.png", strLogDir.c_str(), RTPATH_DELIMITER);
8461
8462 /*
8463 * Age the old log files.
8464 * Rename .(n-1) to .(n), .(n-2) to .(n-1), ..., and the last log file to .1
8465 * Overwrite target files in case they exist.
8466 */
8467 ComPtr<IVirtualBox> pVirtualBox;
8468 aMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
8469 ComPtr<ISystemProperties> pSystemProperties;
8470 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
8471 ULONG cHistoryFiles = 3;
8472 pSystemProperties->COMGETTER(LogHistoryCount)(&cHistoryFiles);
8473 if (cHistoryFiles)
8474 {
8475 for (int i = cHistoryFiles - 1; i >= 0; i--)
8476 {
8477 Utf8Str *files[] = { &logFile, &pngFile };
8478 Utf8Str oldName, newName;
8479
8480 for (unsigned int j = 0; j < RT_ELEMENTS(files); ++j)
8481 {
8482 if (i > 0)
8483 oldName.printf("%s.%d", files[j]->c_str(), i);
8484 else
8485 oldName = *files[j];
8486 newName.printf("%s.%d", files[j]->c_str(), i + 1);
8487
8488 /* If the old file doesn't exist, delete the new file (if it
8489 * exists) to provide correct rotation even if the sequence is
8490 * broken */
8491 if (RTFileRename(oldName.c_str(), newName.c_str(), RTFILEMOVE_FLAGS_REPLACE) == VERR_FILE_NOT_FOUND)
8492 RTFileDelete(newName.c_str());
8493 }
8494 }
8495 }
8496
8497 Bstr bstrLogKeyId;
8498 Bstr bstrLogKeyStore;
8499 PCRTLOGOUTPUTIF pLogOutputIf = NULL;
8500 void *pvLogOutputUser = NULL;
8501 int vrc = VINF_SUCCESS;
8502#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
8503 hrc = aMachine->COMGETTER(LogKeyId)(bstrLogKeyId.asOutParam());
8504 if (SUCCEEDED(hrc))
8505 {
8506 hrc = aMachine->COMGETTER(LogKeyStore)(bstrLogKeyStore.asOutParam());
8507 if ( SUCCEEDED(hrc)
8508 && bstrLogKeyId.isNotEmpty()
8509 && bstrLogKeyStore.isNotEmpty())
8510 {
8511 m_strLogKeyId = Utf8Str(bstrLogKeyId);
8512 m_strLogKeyStore = Utf8Str(bstrLogKeyStore);
8513
8514 pLogOutputIf = &s_ConsoleEncryptedLogOutputIf;
8515 pvLogOutputUser = this;
8516 m_fEncryptedLog = true;
8517 }
8518 }
8519
8520 if (RT_FAILURE(vrc))
8521 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to set encryption for release log (%Rrc)"), vrc);
8522 else
8523#endif
8524 {
8525 RTERRINFOSTATIC ErrInfo;
8526 vrc = com::VBoxLogRelCreateEx("VM", logFile.c_str(),
8527 RTLOGFLAGS_PREFIX_TIME_PROG | RTLOGFLAGS_RESTRICT_GROUPS,
8528 "all all.restrict -default.restrict",
8529 "VBOX_RELEASE_LOG", RTLOGDEST_FILE,
8530 32768 /* cMaxEntriesPerGroup */,
8531 0 /* cHistory */, 0 /* uHistoryFileTime */,
8532 0 /* uHistoryFileSize */,
8533 pLogOutputIf, pvLogOutputUser,
8534 RTErrInfoInitStatic(&ErrInfo));
8535 if (RT_FAILURE(vrc))
8536 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to open release log (%s, %Rrc)"), ErrInfo.Core.pszMsg, vrc);
8537 }
8538
8539 /* If we've made any directory changes, flush the directory to increase
8540 the likelihood that the log file will be usable after a system panic.
8541
8542 Tip: Try 'export VBOX_RELEASE_LOG_FLAGS=flush' if the last bits of the log
8543 is missing. Just don't have too high hopes for this to help. */
8544 if (SUCCEEDED(hrc) || cHistoryFiles)
8545 RTDirFlush(strLogDir.c_str());
8546
8547 return hrc;
8548}
8549
8550/**
8551 * Common worker for PowerUp and PowerUpPaused.
8552 *
8553 * @returns COM status code.
8554 *
8555 * @param aProgress Where to return the progress object.
8556 * @param aPaused true if PowerUpPaused called.
8557 */
8558HRESULT Console::i_powerUp(IProgress **aProgress, bool aPaused)
8559{
8560 LogFlowThisFuncEnter();
8561
8562 CheckComArgOutPointerValid(aProgress);
8563
8564 AutoCaller autoCaller(this);
8565 HRESULT hrc = autoCaller.hrc();
8566 if (FAILED(hrc))
8567 return hrc;
8568
8569 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8570 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
8571
8572 if (Global::IsOnlineOrTransient(mMachineState))
8573 return setError(VBOX_E_INVALID_VM_STATE, tr("The virtual machine is already running or busy (machine state: %s)"),
8574 Global::stringifyMachineState(mMachineState));
8575
8576
8577 /* Set up release logging as early as possible after the check if
8578 * there is already a running VM which we shouldn't disturb. */
8579 hrc = i_consoleInitReleaseLog(mMachine);
8580 if (FAILED(hrc))
8581 return hrc;
8582
8583#ifdef VBOX_OPENSSL_FIPS
8584 LogRel(("crypto: FIPS mode %s\n", FIPS_mode() ? "enabled" : "FAILED"));
8585#endif
8586
8587 /* test and clear the TeleporterEnabled property */
8588 BOOL fTeleporterEnabled;
8589 hrc = mMachine->COMGETTER(TeleporterEnabled)(&fTeleporterEnabled);
8590 if (FAILED(hrc))
8591 return hrc;
8592
8593#if 0 /** @todo we should save it afterwards, but that isn't necessarily a good idea. Find a better place for this (VBoxSVC). */
8594 if (fTeleporterEnabled)
8595 {
8596 hrc = mMachine->COMSETTER(TeleporterEnabled)(FALSE);
8597 if (FAILED(hrc))
8598 return hrc;
8599 }
8600#endif
8601
8602 PCVMMR3VTABLE const pVMM = mpVMM;
8603 AssertPtrReturn(pVMM, E_UNEXPECTED);
8604
8605 ComObjPtr<Progress> pPowerupProgress;
8606 bool fBeganPoweringUp = false;
8607
8608 LONG cOperations = 1;
8609 LONG ulTotalOperationsWeight = 1;
8610 VMPowerUpTask *task = NULL;
8611
8612 try
8613 {
8614 /* Create a progress object to track progress of this operation. Must
8615 * be done as early as possible (together with BeginPowerUp()) as this
8616 * is vital for communicating as much as possible early powerup
8617 * failure information to the API caller */
8618 pPowerupProgress.createObject();
8619 Bstr progressDesc;
8620 if (mMachineState == MachineState_Saved || mMachineState == MachineState_AbortedSaved)
8621 progressDesc = tr("Restoring virtual machine");
8622 else if (fTeleporterEnabled)
8623 progressDesc = tr("Teleporting virtual machine");
8624 else
8625 progressDesc = tr("Starting virtual machine");
8626
8627 /*
8628 * Saved VMs will have to prove that their saved states seem kosher.
8629 */
8630 Utf8Str strSavedStateFile;
8631 Bstr bstrStateKeyId;
8632 Bstr bstrStateKeyStore;
8633
8634 if (mMachineState == MachineState_Saved || mMachineState == MachineState_AbortedSaved)
8635 {
8636 Bstr bstrSavedStateFile;
8637 hrc = mMachine->COMGETTER(StateFilePath)(bstrSavedStateFile.asOutParam());
8638 if (FAILED(hrc))
8639 throw hrc;
8640 strSavedStateFile = bstrSavedStateFile;
8641
8642#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
8643 hrc = mMachine->COMGETTER(StateKeyId)(bstrStateKeyId.asOutParam());
8644 if (FAILED(hrc))
8645 throw hrc;
8646 hrc = mMachine->COMGETTER(StateKeyStore)(bstrStateKeyStore.asOutParam());
8647 if (FAILED(hrc))
8648 throw hrc;
8649#endif
8650
8651 ComAssertRet(bstrSavedStateFile.isNotEmpty(), E_FAIL);
8652 SsmStream ssmStream(this, pVMM, m_pKeyStore, bstrStateKeyId, bstrStateKeyStore);
8653 int vrc = ssmStream.open(strSavedStateFile.c_str());
8654 if (RT_SUCCESS(vrc))
8655 {
8656 PCSSMSTRMOPS pStreamOps;
8657 void *pvStreamOpsUser;
8658
8659 vrc = ssmStream.querySsmStrmOps(&pStreamOps, &pvStreamOpsUser);
8660 if (RT_SUCCESS(vrc))
8661 vrc = pVMM->pfnSSMR3ValidateFile(NULL /*pszFilename*/, pStreamOps, pvStreamOpsUser,
8662 false /* fChecksumIt */);
8663 }
8664
8665 if (RT_FAILURE(vrc))
8666 {
8667 Utf8Str errMsg;
8668 switch (vrc)
8669 {
8670 case VERR_FILE_NOT_FOUND:
8671 errMsg.printf(tr("VM failed to start because the saved state file '%s' does not exist."),
8672 strSavedStateFile.c_str());
8673 break;
8674 default:
8675 errMsg.printf(tr("VM failed to start because the saved state file '%s' is invalid (%Rrc). "
8676 "Delete the saved state prior to starting the VM."), strSavedStateFile.c_str(), vrc);
8677 break;
8678 }
8679 throw setErrorBoth(VBOX_E_FILE_ERROR, vrc, errMsg.c_str());
8680 }
8681
8682 }
8683
8684 /* Read console data, including console shared folders, stored in the
8685 * saved state file (if not yet done).
8686 */
8687 hrc = i_loadDataFromSavedState();
8688 if (FAILED(hrc))
8689 throw hrc;
8690
8691 /* Check all types of shared folders and compose a single list */
8692 SharedFolderDataMap sharedFolders;
8693 {
8694 /* first, insert global folders */
8695 for (SharedFolderDataMap::const_iterator it = m_mapGlobalSharedFolders.begin();
8696 it != m_mapGlobalSharedFolders.end();
8697 ++it)
8698 {
8699 const SharedFolderData &d = it->second;
8700 sharedFolders[it->first] = d;
8701 }
8702
8703 /* second, insert machine folders */
8704 for (SharedFolderDataMap::const_iterator it = m_mapMachineSharedFolders.begin();
8705 it != m_mapMachineSharedFolders.end();
8706 ++it)
8707 {
8708 const SharedFolderData &d = it->second;
8709 sharedFolders[it->first] = d;
8710 }
8711
8712 /* third, insert console folders */
8713 for (SharedFolderMap::const_iterator it = m_mapSharedFolders.begin();
8714 it != m_mapSharedFolders.end();
8715 ++it)
8716 {
8717 ConsoleSharedFolder *pSF = it->second;
8718 AutoCaller sfCaller(pSF);
8719 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
8720 sharedFolders[it->first] = SharedFolderData(pSF->i_getHostPath(),
8721 pSF->i_isWritable(),
8722 pSF->i_isAutoMounted(),
8723 pSF->i_getAutoMountPoint());
8724 }
8725 }
8726
8727
8728 /* Setup task object and thread to carry out the operation
8729 * asynchronously */
8730 try { task = new VMPowerUpTask(this, pPowerupProgress); }
8731 catch (std::bad_alloc &) { throw E_OUTOFMEMORY; }
8732 if (!task->isOk())
8733 throw task->hrc();
8734
8735 task->mpfnConfigConstructor = i_configConstructor;
8736 task->mSharedFolders = sharedFolders;
8737 task->mStartPaused = aPaused;
8738 if (mMachineState == MachineState_Saved || mMachineState == MachineState_AbortedSaved)
8739 try { task->mSavedStateFile = strSavedStateFile; }
8740 catch (std::bad_alloc &) { throw E_OUTOFMEMORY; }
8741 task->mTeleporterEnabled = fTeleporterEnabled;
8742
8743 /* Reset differencing hard disks for which autoReset is true,
8744 * but only if the machine has no snapshots OR the current snapshot
8745 * is an OFFLINE snapshot; otherwise we would reset the current
8746 * differencing image of an ONLINE snapshot which contains the disk
8747 * state of the machine while it was previously running, but without
8748 * the corresponding machine state, which is equivalent to powering
8749 * off a running machine and not good idea
8750 */
8751 ComPtr<ISnapshot> pCurrentSnapshot;
8752 hrc = mMachine->COMGETTER(CurrentSnapshot)(pCurrentSnapshot.asOutParam());
8753 if (FAILED(hrc))
8754 throw hrc;
8755
8756 BOOL fCurrentSnapshotIsOnline = false;
8757 if (pCurrentSnapshot)
8758 {
8759 hrc = pCurrentSnapshot->COMGETTER(Online)(&fCurrentSnapshotIsOnline);
8760 if (FAILED(hrc))
8761 throw hrc;
8762 }
8763
8764 if (strSavedStateFile.isEmpty() && !fCurrentSnapshotIsOnline)
8765 {
8766 LogFlowThisFunc(("Looking for immutable images to reset\n"));
8767
8768 com::SafeIfaceArray<IMediumAttachment> atts;
8769 hrc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
8770 if (FAILED(hrc))
8771 throw hrc;
8772
8773 for (size_t i = 0;
8774 i < atts.size();
8775 ++i)
8776 {
8777 DeviceType_T devType;
8778 hrc = atts[i]->COMGETTER(Type)(&devType);
8779 /** @todo later applies to floppies as well */
8780 if (devType == DeviceType_HardDisk)
8781 {
8782 ComPtr<IMedium> pMedium;
8783 hrc = atts[i]->COMGETTER(Medium)(pMedium.asOutParam());
8784 if (FAILED(hrc))
8785 throw hrc;
8786
8787 /* needs autoreset? */
8788 BOOL autoReset = FALSE;
8789 hrc = pMedium->COMGETTER(AutoReset)(&autoReset);
8790 if (FAILED(hrc))
8791 throw hrc;
8792
8793 if (autoReset)
8794 {
8795 ComPtr<IProgress> pResetProgress;
8796 hrc = pMedium->Reset(pResetProgress.asOutParam());
8797 if (FAILED(hrc))
8798 throw hrc;
8799
8800 /* save for later use on the powerup thread */
8801 task->hardDiskProgresses.push_back(pResetProgress);
8802 }
8803 }
8804 }
8805 }
8806 else
8807 LogFlowThisFunc(("Machine has a current snapshot which is online, skipping immutable images reset\n"));
8808
8809 /* setup task object and thread to carry out the operation
8810 * asynchronously */
8811
8812#ifdef VBOX_WITH_EXTPACK
8813 mptrExtPackManager->i_dumpAllToReleaseLog();
8814#endif
8815
8816#ifdef RT_OS_SOLARIS
8817 /* setup host core dumper for the VM */
8818 Bstr value;
8819 hrc = mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpEnabled").raw(), value.asOutParam());
8820 if (SUCCEEDED(hrc) && value == "1")
8821 {
8822 Bstr coreDumpDir, coreDumpReplaceSys, coreDumpLive;
8823 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpDir").raw(), coreDumpDir.asOutParam());
8824 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpReplaceSystemDump").raw(), coreDumpReplaceSys.asOutParam());
8825 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpLive").raw(), coreDumpLive.asOutParam());
8826
8827 uint32_t fCoreFlags = 0;
8828 if ( coreDumpReplaceSys.isEmpty() == false
8829 && Utf8Str(coreDumpReplaceSys).toUInt32() == 1)
8830 fCoreFlags |= RTCOREDUMPER_FLAGS_REPLACE_SYSTEM_DUMP;
8831
8832 if ( coreDumpLive.isEmpty() == false
8833 && Utf8Str(coreDumpLive).toUInt32() == 1)
8834 fCoreFlags |= RTCOREDUMPER_FLAGS_LIVE_CORE;
8835
8836 Utf8Str strDumpDir(coreDumpDir);
8837 const char *pszDumpDir = strDumpDir.c_str();
8838 if ( pszDumpDir
8839 && *pszDumpDir == '\0')
8840 pszDumpDir = NULL;
8841
8842 int vrc;
8843 if ( pszDumpDir
8844 && !RTDirExists(pszDumpDir))
8845 {
8846 /*
8847 * Try create the directory.
8848 */
8849 vrc = RTDirCreateFullPath(pszDumpDir, 0700);
8850 if (RT_FAILURE(vrc))
8851 throw setErrorBoth(E_FAIL, vrc, tr("Failed to setup CoreDumper. Couldn't create dump directory '%s' (%Rrc)"),
8852 pszDumpDir, vrc);
8853 }
8854
8855 vrc = RTCoreDumperSetup(pszDumpDir, fCoreFlags);
8856 if (RT_FAILURE(vrc))
8857 throw setErrorBoth(E_FAIL, vrc, tr("Failed to setup CoreDumper (%Rrc)"), vrc);
8858 LogRel(("CoreDumper setup successful. pszDumpDir=%s fFlags=%#x\n", pszDumpDir ? pszDumpDir : ".", fCoreFlags));
8859 }
8860#endif
8861
8862
8863 // If there is immutable drive the process that.
8864 VMPowerUpTask::ProgressList progresses(task->hardDiskProgresses);
8865 if (aProgress && !progresses.empty())
8866 {
8867 for (VMPowerUpTask::ProgressList::const_iterator it = progresses.begin(); it != progresses.end(); ++it)
8868 {
8869 ++cOperations;
8870 ulTotalOperationsWeight += 1;
8871 }
8872 hrc = pPowerupProgress->init(static_cast<IConsole *>(this),
8873 progressDesc.raw(),
8874 TRUE, // Cancelable
8875 cOperations,
8876 ulTotalOperationsWeight,
8877 tr("Starting Hard Disk operations"),
8878 1);
8879 AssertComRCReturnRC(hrc);
8880 }
8881 else if ( mMachineState == MachineState_Saved
8882 || mMachineState == MachineState_AbortedSaved
8883 || !fTeleporterEnabled)
8884 hrc = pPowerupProgress->init(static_cast<IConsole *>(this),
8885 progressDesc.raw(),
8886 FALSE /* aCancelable */);
8887 else if (fTeleporterEnabled)
8888 hrc = pPowerupProgress->init(static_cast<IConsole *>(this),
8889 progressDesc.raw(),
8890 TRUE /* aCancelable */,
8891 3 /* cOperations */,
8892 10 /* ulTotalOperationsWeight */,
8893 tr("Teleporting virtual machine"),
8894 1 /* ulFirstOperationWeight */);
8895
8896 if (FAILED(hrc))
8897 throw hrc;
8898
8899 /* Tell VBoxSVC and Machine about the progress object so they can
8900 combine/proxy it to any openRemoteSession caller. */
8901 LogFlowThisFunc(("Calling BeginPowerUp...\n"));
8902 hrc = mControl->BeginPowerUp(pPowerupProgress);
8903 if (FAILED(hrc))
8904 {
8905 LogFlowThisFunc(("BeginPowerUp failed\n"));
8906 throw hrc;
8907 }
8908 fBeganPoweringUp = true;
8909
8910 LogFlowThisFunc(("Checking if canceled...\n"));
8911 BOOL fCanceled;
8912 hrc = pPowerupProgress->COMGETTER(Canceled)(&fCanceled);
8913 if (FAILED(hrc))
8914 throw hrc;
8915
8916 if (fCanceled)
8917 {
8918 LogFlowThisFunc(("Canceled in BeginPowerUp\n"));
8919 throw setError(E_FAIL, tr("Powerup was canceled"));
8920 }
8921 LogFlowThisFunc(("Not canceled yet.\n"));
8922
8923 /** @todo this code prevents starting a VM with unavailable bridged
8924 * networking interface. The only benefit is a slightly better error
8925 * message, which should be moved to the driver code. This is the
8926 * only reason why I left the code in for now. The driver allows
8927 * unavailable bridged networking interfaces in certain circumstances,
8928 * and this is sabotaged by this check. The VM will initially have no
8929 * network connectivity, but the user can fix this at runtime. */
8930#if 0
8931 /* the network cards will undergo a quick consistency check */
8932 for (ULONG slot = 0;
8933 slot < maxNetworkAdapters;
8934 ++slot)
8935 {
8936 ComPtr<INetworkAdapter> pNetworkAdapter;
8937 mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
8938 BOOL enabled = FALSE;
8939 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
8940 if (!enabled)
8941 continue;
8942
8943 NetworkAttachmentType_T netattach;
8944 pNetworkAdapter->COMGETTER(AttachmentType)(&netattach);
8945 switch (netattach)
8946 {
8947 case NetworkAttachmentType_Bridged:
8948 {
8949 /* a valid host interface must have been set */
8950 Bstr hostif;
8951 pNetworkAdapter->COMGETTER(HostInterface)(hostif.asOutParam());
8952 if (hostif.isEmpty())
8953 {
8954 throw setError(VBOX_E_HOST_ERROR,
8955 tr("VM cannot start because host interface networking requires a host interface name to be set"));
8956 }
8957 ComPtr<IVirtualBox> pVirtualBox;
8958 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
8959 ComPtr<IHost> pHost;
8960 pVirtualBox->COMGETTER(Host)(pHost.asOutParam());
8961 ComPtr<IHostNetworkInterface> pHostInterface;
8962 if (!SUCCEEDED(pHost->FindHostNetworkInterfaceByName(hostif.raw(), pHostInterface.asOutParam())))
8963 throw setError(VBOX_E_HOST_ERROR,
8964 tr("VM cannot start because the host interface '%ls' does not exist"), hostif.raw());
8965 break;
8966 }
8967 default:
8968 break;
8969 }
8970 }
8971#endif // 0
8972
8973
8974 /* setup task object and thread to carry out the operation
8975 * asynchronously */
8976 if (aProgress)
8977 {
8978 hrc = pPowerupProgress.queryInterfaceTo(aProgress);
8979 AssertComRCReturnRC(hrc);
8980 }
8981
8982#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
8983 task->mKeyStore = Utf8Str(bstrStateKeyStore);
8984 task->mKeyId = Utf8Str(bstrStateKeyId);
8985 task->m_pKeyStore = m_pKeyStore;
8986#endif
8987
8988 hrc = task->createThread();
8989 task = NULL;
8990 if (FAILED(hrc))
8991 throw hrc;
8992
8993 /* finally, set the state: no right to fail in this method afterwards
8994 * since we've already started the thread and it is now responsible for
8995 * any error reporting and appropriate state change! */
8996 if (mMachineState == MachineState_Saved || mMachineState == MachineState_AbortedSaved)
8997 i_setMachineState(MachineState_Restoring);
8998 else if (fTeleporterEnabled)
8999 i_setMachineState(MachineState_TeleportingIn);
9000 else
9001 i_setMachineState(MachineState_Starting);
9002 }
9003 catch (HRESULT aRC)
9004 {
9005 hrc = aRC;
9006 }
9007
9008 if (FAILED(hrc) && fBeganPoweringUp)
9009 {
9010
9011 /* The progress object will fetch the current error info */
9012 if (!pPowerupProgress.isNull())
9013 pPowerupProgress->i_notifyComplete(hrc);
9014
9015 /* Save the error info across the IPC below. Can't be done before the
9016 * progress notification above, as saving the error info deletes it
9017 * from the current context, and thus the progress object wouldn't be
9018 * updated correctly. */
9019 ErrorInfoKeeper eik;
9020
9021 /* signal end of operation */
9022 mControl->EndPowerUp(hrc);
9023 }
9024
9025 if (task)
9026 {
9027 ErrorInfoKeeper eik;
9028 delete task;
9029 }
9030
9031 LogFlowThisFunc(("mMachineState=%d, hrc=%Rhrc\n", mMachineState, hrc));
9032 LogFlowThisFuncLeave();
9033 return hrc;
9034}
9035
9036/**
9037 * Internal power off worker routine.
9038 *
9039 * This method may be called only at certain places with the following meaning
9040 * as shown below:
9041 *
9042 * - if the machine state is either Running or Paused, a normal
9043 * Console-initiated powerdown takes place (e.g. PowerDown());
9044 * - if the machine state is Saving, saveStateThread() has successfully done its
9045 * job;
9046 * - if the machine state is Starting or Restoring, powerUpThread() has failed
9047 * to start/load the VM;
9048 * - if the machine state is Stopping, the VM has powered itself off (i.e. not
9049 * as a result of the powerDown() call).
9050 *
9051 * Calling it in situations other than the above will cause unexpected behavior.
9052 *
9053 * Note that this method should be the only one that destroys mpUVM and sets it
9054 * to NULL.
9055 *
9056 * @param aProgress Progress object to run (may be NULL).
9057 *
9058 * @note Locks this object for writing.
9059 *
9060 * @note Never call this method from a thread that called addVMCaller() or
9061 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
9062 * release(). Otherwise it will deadlock.
9063 */
9064HRESULT Console::i_powerDown(IProgress *aProgress /*= NULL*/)
9065{
9066 LogFlowThisFuncEnter();
9067
9068 AutoCaller autoCaller(this);
9069 AssertComRCReturnRC(autoCaller.hrc());
9070
9071 ComPtr<IInternalProgressControl> pProgressControl(aProgress);
9072
9073 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9074
9075 /* Total # of steps for the progress object. Must correspond to the
9076 * number of "advance percent count" comments in this method! */
9077 enum { StepCount = 7 };
9078 /* current step */
9079 ULONG step = 0;
9080
9081 HRESULT hrc = S_OK;
9082 int vrc = VINF_SUCCESS;
9083
9084 /* sanity */
9085 Assert(mVMDestroying == false);
9086
9087 PCVMMR3VTABLE const pVMM = mpVMM;
9088 AssertPtrReturn(pVMM, E_UNEXPECTED);
9089 PUVM pUVM = mpUVM;
9090 AssertPtrReturn(pUVM, E_UNEXPECTED);
9091
9092 uint32_t cRefs = pVMM->pfnVMR3RetainUVM(pUVM);
9093 Assert(cRefs != UINT32_MAX); NOREF(cRefs);
9094
9095 AssertMsg( mMachineState == MachineState_Running
9096 || mMachineState == MachineState_Paused
9097 || mMachineState == MachineState_Stuck
9098 || mMachineState == MachineState_Starting
9099 || mMachineState == MachineState_Stopping
9100 || mMachineState == MachineState_Saving
9101 || mMachineState == MachineState_Restoring
9102 || mMachineState == MachineState_TeleportingPausedVM
9103 || mMachineState == MachineState_TeleportingIn
9104 , ("Invalid machine state: %s\n", ::stringifyMachineState(mMachineState)));
9105
9106 LogRel(("Console::powerDown(): A request to power off the VM has been issued (mMachineState=%s, InUninit=%d)\n",
9107 ::stringifyMachineState(mMachineState), getObjectState().getState() == ObjectState::InUninit));
9108
9109 /* Check if we need to power off the VM. In case of mVMPoweredOff=true, the
9110 * VM has already powered itself off in vmstateChangeCallback() and is just
9111 * notifying Console about that. In case of Starting or Restoring,
9112 * powerUpThread() is calling us on failure, so the VM is already off at
9113 * that point. */
9114 if ( !mVMPoweredOff
9115 && ( mMachineState == MachineState_Starting
9116 || mMachineState == MachineState_Restoring
9117 || mMachineState == MachineState_TeleportingIn)
9118 )
9119 mVMPoweredOff = true;
9120
9121 /*
9122 * Go to Stopping state if not already there.
9123 *
9124 * Note that we don't go from Saving/Restoring to Stopping because
9125 * vmstateChangeCallback() needs it to set the state to Saved on
9126 * VMSTATE_TERMINATED. In terms of protecting from inappropriate operations
9127 * while leaving the lock below, Saving or Restoring should be fine too.
9128 * Ditto for TeleportingPausedVM -> Teleported.
9129 */
9130 if ( mMachineState != MachineState_Saving
9131 && mMachineState != MachineState_Restoring
9132 && mMachineState != MachineState_Stopping
9133 && mMachineState != MachineState_TeleportingIn
9134 && mMachineState != MachineState_TeleportingPausedVM
9135 )
9136 i_setMachineState(MachineState_Stopping);
9137
9138 /* ----------------------------------------------------------------------
9139 * DONE with necessary state changes, perform the power down actions (it's
9140 * safe to release the object lock now if needed)
9141 * ---------------------------------------------------------------------- */
9142
9143 if (mDisplay)
9144 {
9145 alock.release();
9146
9147 mDisplay->i_notifyPowerDown();
9148
9149 alock.acquire();
9150 }
9151
9152 /* Stop the VRDP server to prevent new clients connection while VM is being
9153 * powered off. */
9154 if (mConsoleVRDPServer)
9155 {
9156 LogFlowThisFunc(("Stopping VRDP server...\n"));
9157
9158 /* Leave the lock since EMT could call us back as addVMCaller() */
9159 alock.release();
9160
9161 mConsoleVRDPServer->Stop();
9162
9163 alock.acquire();
9164 }
9165
9166 /* advance percent count */
9167 if (pProgressControl)
9168 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
9169
9170
9171 /* ----------------------------------------------------------------------
9172 * Now, wait for all mpUVM callers to finish their work if there are still
9173 * some on other threads. NO methods that need mpUVM (or initiate other calls
9174 * that need it) may be called after this point
9175 * ---------------------------------------------------------------------- */
9176
9177 /* go to the destroying state to prevent from adding new callers */
9178 mVMDestroying = true;
9179
9180 if (mVMCallers > 0)
9181 {
9182 /* lazy creation */
9183 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
9184 RTSemEventCreate(&mVMZeroCallersSem);
9185
9186 LogFlowThisFunc(("Waiting for mpUVM callers (%d) to drop to zero...\n", mVMCallers));
9187
9188 alock.release();
9189
9190 RTSemEventWait(mVMZeroCallersSem, RT_INDEFINITE_WAIT);
9191
9192 alock.acquire();
9193 }
9194
9195 /* advance percent count */
9196 if (pProgressControl)
9197 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
9198
9199 vrc = VINF_SUCCESS;
9200
9201 /*
9202 * Power off the VM if not already done that.
9203 * Leave the lock since EMT will call vmstateChangeCallback.
9204 *
9205 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
9206 * VM-(guest-)initiated power off happened in parallel a ms before this
9207 * call. So far, we let this error pop up on the user's side.
9208 */
9209 if (!mVMPoweredOff)
9210 {
9211 LogFlowThisFunc(("Powering off the VM...\n"));
9212 alock.release();
9213 vrc = pVMM->pfnVMR3PowerOff(pUVM);
9214#ifdef VBOX_WITH_EXTPACK
9215 mptrExtPackManager->i_callAllVmPowerOffHooks(this, pVMM->pfnVMR3GetVM(pUVM), pVMM);
9216#endif
9217 alock.acquire();
9218 }
9219
9220 /* advance percent count */
9221 if (pProgressControl)
9222 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
9223
9224#ifdef VBOX_WITH_HGCM
9225 /* Shutdown HGCM services before destroying the VM. */
9226 if (m_pVMMDev)
9227 {
9228 LogFlowThisFunc(("Shutdown HGCM...\n"));
9229
9230 /* Leave the lock since EMT might wait for it and will call us back as addVMCaller() */
9231 alock.release();
9232
9233# ifdef VBOX_WITH_SHARED_CLIPBOARD
9234 if (m_hHgcmSvcExtShCl)
9235 {
9236 HGCMHostUnregisterServiceExtension(m_hHgcmSvcExtShCl);
9237 m_hHgcmSvcExtShCl = NULL;
9238 }
9239 GuestShCl::destroyInstance();
9240#endif
9241
9242# ifdef VBOX_WITH_DRAG_AND_DROP
9243 if (m_hHgcmSvcExtDragAndDrop)
9244 {
9245 HGCMHostUnregisterServiceExtension(m_hHgcmSvcExtDragAndDrop);
9246 m_hHgcmSvcExtDragAndDrop = NULL;
9247 }
9248# endif
9249
9250 m_pVMMDev->hgcmShutdown();
9251
9252 alock.acquire();
9253 }
9254
9255 /* advance percent count */
9256 if (pProgressControl)
9257 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
9258
9259#endif /* VBOX_WITH_HGCM */
9260
9261 LogFlowThisFunc(("Ready for VM destruction.\n"));
9262
9263 /* If we are called from Console::uninit(), then try to destroy the VM even
9264 * on failure (this will most likely fail too, but what to do?..) */
9265 if (RT_SUCCESS(vrc) || getObjectState().getState() == ObjectState::InUninit)
9266 {
9267 /* If the machine has a USB controller, release all USB devices
9268 * (symmetric to the code in captureUSBDevices()) */
9269 if (mfVMHasUsbController)
9270 {
9271 alock.release();
9272 i_detachAllUSBDevices(false /* aDone */);
9273 alock.acquire();
9274 }
9275
9276 /* Now we've got to destroy the VM as well. (mpUVM is not valid beyond
9277 * this point). We release the lock before calling VMR3Destroy() because
9278 * it will result into calling destructors of drivers associated with
9279 * Console children which may in turn try to lock Console (e.g. by
9280 * instantiating SafeVMPtr to access mpUVM). It's safe here because
9281 * mVMDestroying is set which should prevent any activity. */
9282
9283 /* Set mpUVM to NULL early just in case if some old code is not using
9284 * addVMCaller()/releaseVMCaller(). (We have our own ref on pUVM.) */
9285 pVMM->pfnVMR3ReleaseUVM(mpUVM);
9286 mpUVM = NULL;
9287
9288 LogFlowThisFunc(("Destroying the VM...\n"));
9289
9290 alock.release();
9291
9292 vrc = pVMM->pfnVMR3Destroy(pUVM);
9293
9294 /* take the lock again */
9295 alock.acquire();
9296
9297 /* advance percent count */
9298 if (pProgressControl)
9299 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
9300
9301 if (RT_SUCCESS(vrc))
9302 {
9303 LogFlowThisFunc(("Machine has been destroyed (mMachineState=%d)\n",
9304 mMachineState));
9305 /* Note: the Console-level machine state change happens on the
9306 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
9307 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
9308 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
9309 * occurred yet. This is okay, because mMachineState is already
9310 * Stopping in this case, so any other attempt to call PowerDown()
9311 * will be rejected. */
9312 }
9313 else
9314 {
9315 /* bad bad bad, but what to do? (Give Console our UVM ref.) */
9316 mpUVM = pUVM;
9317 pUVM = NULL;
9318 hrc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not destroy the machine. (Error: %Rrc)"), vrc);
9319 }
9320
9321 /* Complete the detaching of the USB devices. */
9322 if (mfVMHasUsbController)
9323 {
9324 alock.release();
9325 i_detachAllUSBDevices(true /* aDone */);
9326 alock.acquire();
9327 }
9328
9329 /* advance percent count */
9330 if (pProgressControl)
9331 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
9332 }
9333 else
9334 hrc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not power off the machine. (Error: %Rrc)"), vrc);
9335
9336 /*
9337 * Finished with the destruction.
9338 *
9339 * Note that if something impossible happened and we've failed to destroy
9340 * the VM, mVMDestroying will remain true and mMachineState will be
9341 * something like Stopping, so most Console methods will return an error
9342 * to the caller.
9343 */
9344 if (pUVM != NULL)
9345 pVMM->pfnVMR3ReleaseUVM(pUVM);
9346 else
9347 mVMDestroying = false;
9348
9349 LogFlowThisFuncLeave();
9350 return hrc;
9351}
9352
9353/**
9354 * @note Locks this object for writing.
9355 */
9356HRESULT Console::i_setMachineState(MachineState_T aMachineState, bool aUpdateServer /* = true */)
9357{
9358 AutoCaller autoCaller(this);
9359 AssertComRCReturnRC(autoCaller.hrc());
9360
9361 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9362
9363 HRESULT hrc = S_OK;
9364
9365 if (mMachineState != aMachineState)
9366 {
9367 LogThisFunc(("machineState=%s -> %s aUpdateServer=%RTbool\n",
9368 ::stringifyMachineState(mMachineState), ::stringifyMachineState(aMachineState), aUpdateServer));
9369 LogRel(("Console: Machine state changed to '%s'\n", ::stringifyMachineState(aMachineState)));
9370 mMachineState = aMachineState;
9371
9372 /// @todo (dmik)
9373 // possibly, we need to redo onStateChange() using the dedicated
9374 // Event thread, like it is done in VirtualBox. This will make it
9375 // much safer (no deadlocks possible if someone tries to use the
9376 // console from the callback), however, listeners will lose the
9377 // ability to synchronously react to state changes (is it really
9378 // necessary??)
9379 LogFlowThisFunc(("Doing onStateChange()...\n"));
9380 i_onStateChange(aMachineState);
9381 LogFlowThisFunc(("Done onStateChange()\n"));
9382
9383 if (aUpdateServer)
9384 {
9385 /* Server notification MUST be done from under the lock; otherwise
9386 * the machine state here and on the server might go out of sync
9387 * which can lead to various unexpected results (like the machine
9388 * state being >= MachineState_Running on the server, while the
9389 * session state is already SessionState_Unlocked at the same time
9390 * there).
9391 *
9392 * Cross-lock conditions should be carefully watched out: calling
9393 * UpdateState we will require Machine and SessionMachine locks
9394 * (remember that here we're holding the Console lock here, and also
9395 * all locks that have been acquire by the thread before calling
9396 * this method).
9397 */
9398 LogFlowThisFunc(("Doing mControl->UpdateState()...\n"));
9399 hrc = mControl->UpdateState(aMachineState);
9400 LogFlowThisFunc(("mControl->UpdateState()=%Rhrc\n", hrc));
9401 }
9402 }
9403
9404 return hrc;
9405}
9406
9407/**
9408 * Searches for a shared folder with the given logical name
9409 * in the collection of shared folders.
9410 *
9411 * @param strName logical name of the shared folder
9412 * @param aSharedFolder where to return the found object
9413 * @param aSetError whether to set the error info if the folder is
9414 * not found
9415 * @return
9416 * S_OK when found or E_INVALIDARG when not found
9417 *
9418 * @note The caller must lock this object for writing.
9419 */
9420HRESULT Console::i_findSharedFolder(const Utf8Str &strName, ComObjPtr<ConsoleSharedFolder> &aSharedFolder, bool aSetError /* = false */)
9421{
9422 /* sanity check */
9423 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9424
9425 SharedFolderMap::const_iterator it = m_mapSharedFolders.find(strName);
9426 if (it != m_mapSharedFolders.end())
9427 {
9428 aSharedFolder = it->second;
9429 return S_OK;
9430 }
9431
9432 if (aSetError)
9433 setError(VBOX_E_FILE_ERROR, tr("Could not find a shared folder named '%s'."), strName.c_str());
9434 return VBOX_E_FILE_ERROR;
9435}
9436
9437/**
9438 * Fetches the list of global or machine shared folders from the server.
9439 *
9440 * @param aGlobal true to fetch global folders.
9441 *
9442 * @note The caller must lock this object for writing.
9443 */
9444HRESULT Console::i_fetchSharedFolders(BOOL aGlobal)
9445{
9446 /* sanity check */
9447 AssertReturn( getObjectState().getState() == ObjectState::InInit
9448 || isWriteLockOnCurrentThread(), E_FAIL);
9449
9450 LogFlowThisFunc(("Entering\n"));
9451
9452 /* Check if we're online and keep it that way. */
9453 SafeVMPtrQuiet ptrVM(this);
9454 AutoVMCallerQuietWeak autoVMCaller(this);
9455 bool const online = ptrVM.isOk()
9456 && m_pVMMDev
9457 && m_pVMMDev->isShFlActive();
9458
9459 HRESULT hrc = S_OK;
9460
9461 try
9462 {
9463 if (aGlobal)
9464 {
9465 /// @todo grab & process global folders when they are done
9466 }
9467 else
9468 {
9469 SharedFolderDataMap oldFolders;
9470 if (online)
9471 oldFolders = m_mapMachineSharedFolders;
9472
9473 m_mapMachineSharedFolders.clear();
9474
9475 SafeIfaceArray<ISharedFolder> folders;
9476 hrc = mMachine->COMGETTER(SharedFolders)(ComSafeArrayAsOutParam(folders));
9477 if (FAILED(hrc)) throw hrc;
9478
9479 for (size_t i = 0; i < folders.size(); ++i)
9480 {
9481 ComPtr<ISharedFolder> pSharedFolder = folders[i];
9482
9483 Bstr bstr;
9484 hrc = pSharedFolder->COMGETTER(Name)(bstr.asOutParam());
9485 if (FAILED(hrc)) throw hrc;
9486 Utf8Str strName(bstr);
9487
9488 hrc = pSharedFolder->COMGETTER(HostPath)(bstr.asOutParam());
9489 if (FAILED(hrc)) throw hrc;
9490 Utf8Str strHostPath(bstr);
9491
9492 BOOL writable;
9493 hrc = pSharedFolder->COMGETTER(Writable)(&writable);
9494 if (FAILED(hrc)) throw hrc;
9495
9496 BOOL autoMount;
9497 hrc = pSharedFolder->COMGETTER(AutoMount)(&autoMount);
9498 if (FAILED(hrc)) throw hrc;
9499
9500 hrc = pSharedFolder->COMGETTER(AutoMountPoint)(bstr.asOutParam());
9501 if (FAILED(hrc)) throw hrc;
9502 Utf8Str strAutoMountPoint(bstr);
9503
9504 m_mapMachineSharedFolders.insert(std::make_pair(strName,
9505 SharedFolderData(strHostPath, !!writable,
9506 !!autoMount, strAutoMountPoint)));
9507
9508 /* send changes to HGCM if the VM is running */
9509 if (online)
9510 {
9511 SharedFolderDataMap::iterator it = oldFolders.find(strName);
9512 if ( it == oldFolders.end()
9513 || it->second.m_strHostPath != strHostPath)
9514 {
9515 /* a new machine folder is added or
9516 * the existing machine folder is changed */
9517 if (m_mapSharedFolders.find(strName) != m_mapSharedFolders.end())
9518 ; /* the console folder exists, nothing to do */
9519 else
9520 {
9521 /* remove the old machine folder (when changed)
9522 * or the global folder if any (when new) */
9523 if ( it != oldFolders.end()
9524 || m_mapGlobalSharedFolders.find(strName) != m_mapGlobalSharedFolders.end()
9525 )
9526 {
9527 hrc = i_removeSharedFolder(strName);
9528 if (FAILED(hrc)) throw hrc;
9529 }
9530
9531 /* create the new machine folder */
9532 hrc = i_createSharedFolder(strName,
9533 SharedFolderData(strHostPath, !!writable, !!autoMount, strAutoMountPoint));
9534 if (FAILED(hrc)) throw hrc;
9535 }
9536 }
9537 /* forget the processed (or identical) folder */
9538 if (it != oldFolders.end())
9539 oldFolders.erase(it);
9540 }
9541 }
9542
9543 /* process outdated (removed) folders */
9544 if (online)
9545 {
9546 for (SharedFolderDataMap::const_iterator it = oldFolders.begin();
9547 it != oldFolders.end(); ++it)
9548 {
9549 if (m_mapSharedFolders.find(it->first) != m_mapSharedFolders.end())
9550 ; /* the console folder exists, nothing to do */
9551 else
9552 {
9553 /* remove the outdated machine folder */
9554 hrc = i_removeSharedFolder(it->first);
9555 if (FAILED(hrc)) throw hrc;
9556
9557 /* create the global folder if there is any */
9558 SharedFolderDataMap::const_iterator git =
9559 m_mapGlobalSharedFolders.find(it->first);
9560 if (git != m_mapGlobalSharedFolders.end())
9561 {
9562 hrc = i_createSharedFolder(git->first, git->second);
9563 if (FAILED(hrc)) throw hrc;
9564 }
9565 }
9566 }
9567 }
9568 }
9569 }
9570 catch (HRESULT hrc2)
9571 {
9572 hrc = hrc2;
9573 if (online)
9574 i_atVMRuntimeErrorCallbackF(0, "BrokenSharedFolder", N_("Broken shared folder!"));
9575 }
9576
9577 LogFlowThisFunc(("Leaving\n"));
9578
9579 return hrc;
9580}
9581
9582/**
9583 * Searches for a shared folder with the given name in the list of machine
9584 * shared folders and then in the list of the global shared folders.
9585 *
9586 * @param strName Name of the folder to search for.
9587 * @param aIt Where to store the pointer to the found folder.
9588 * @return @c true if the folder was found and @c false otherwise.
9589 *
9590 * @note The caller must lock this object for reading.
9591 */
9592bool Console::i_findOtherSharedFolder(const Utf8Str &strName,
9593 SharedFolderDataMap::const_iterator &aIt)
9594{
9595 /* sanity check */
9596 AssertReturn(isWriteLockOnCurrentThread(), false);
9597
9598 /* first, search machine folders */
9599 aIt = m_mapMachineSharedFolders.find(strName);
9600 if (aIt != m_mapMachineSharedFolders.end())
9601 return true;
9602
9603 /* second, search machine folders */
9604 aIt = m_mapGlobalSharedFolders.find(strName);
9605 if (aIt != m_mapGlobalSharedFolders.end())
9606 return true;
9607
9608 return false;
9609}
9610
9611/**
9612 * Calls the HGCM service to add a shared folder definition.
9613 *
9614 * @param strName Shared folder name.
9615 * @param aData Shared folder data.
9616 *
9617 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
9618 * @note Doesn't lock anything.
9619 */
9620HRESULT Console::i_createSharedFolder(const Utf8Str &strName, const SharedFolderData &aData)
9621{
9622 Log(("Adding shared folder '%s' -> '%s'\n", strName.c_str(), aData.m_strHostPath.c_str()));
9623
9624 /*
9625 * Sanity checks
9626 */
9627 ComAssertRet(strName.isNotEmpty(), E_FAIL);
9628 ComAssertRet(aData.m_strHostPath.isNotEmpty(), E_FAIL);
9629
9630 AssertReturn(mpUVM, E_FAIL);
9631 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
9632
9633 /*
9634 * Find out whether we should allow symbolic link creation.
9635 */
9636 Bstr bstrValue;
9637 HRESULT hrc = mMachine->GetExtraData(BstrFmt("VBoxInternal2/SharedFoldersEnableSymlinksCreate/%s", strName.c_str()).raw(),
9638 bstrValue.asOutParam());
9639 bool fSymlinksCreate = hrc == S_OK && bstrValue == "1";
9640
9641 /*
9642 * Check whether the path is valid and exists.
9643 */
9644 char szAbsHostPath[RTPATH_MAX];
9645 int vrc = RTPathAbs(aData.m_strHostPath.c_str(), szAbsHostPath, sizeof(szAbsHostPath));
9646 if (RT_FAILURE(vrc))
9647 return setErrorBoth(E_INVALIDARG, vrc, tr("Invalid shared folder path: '%s' (%Rrc)"), aData.m_strHostPath.c_str(), vrc);
9648
9649 /* Check whether the path is full (absolute). ASSUMING a RTPATH_MAX of ~4K
9650 this also checks that the length is within bounds of a SHFLSTRING. */
9651 if (RTPathCompare(aData.m_strHostPath.c_str(), szAbsHostPath) != 0)
9652 return setError(E_INVALIDARG, tr("Shared folder path '%s' is not absolute"), aData.m_strHostPath.c_str());
9653
9654 bool const fMissing = !RTPathExists(szAbsHostPath);
9655
9656 /*
9657 * Check the other two string lengths before converting them all to SHFLSTRINGS.
9658 */
9659 if (strName.length() >= _2K)
9660 return setError(E_INVALIDARG, tr("Shared folder name is too long: %zu bytes", "", strName.length()), strName.length());
9661 if (aData.m_strAutoMountPoint.length() >= RTPATH_MAX)
9662 return setError(E_INVALIDARG, tr("Shared folder mount point too long: %zu bytes", "",
9663 (int)aData.m_strAutoMountPoint.length()),
9664 aData.m_strAutoMountPoint.length());
9665
9666 PSHFLSTRING pHostPath = ShflStringDupUtf8AsUtf16(aData.m_strHostPath.c_str());
9667 PSHFLSTRING pName = ShflStringDupUtf8AsUtf16(strName.c_str());
9668 PSHFLSTRING pAutoMountPoint = ShflStringDupUtf8AsUtf16(aData.m_strAutoMountPoint.c_str());
9669 if (pHostPath && pName && pAutoMountPoint)
9670 {
9671 /*
9672 * Make a SHFL_FN_ADD_MAPPING call to tell the service about folder.
9673 */
9674 VBOXHGCMSVCPARM aParams[SHFL_CPARMS_ADD_MAPPING];
9675 SHFLSTRING_TO_HGMC_PARAM(&aParams[0], pHostPath);
9676 SHFLSTRING_TO_HGMC_PARAM(&aParams[1], pName);
9677 HGCMSvcSetU32(&aParams[2],
9678 (aData.m_fWritable ? SHFL_ADD_MAPPING_F_WRITABLE : 0)
9679 | (aData.m_fAutoMount ? SHFL_ADD_MAPPING_F_AUTOMOUNT : 0)
9680 | (fSymlinksCreate ? SHFL_ADD_MAPPING_F_CREATE_SYMLINKS : 0)
9681 | (fMissing ? SHFL_ADD_MAPPING_F_MISSING : 0));
9682 SHFLSTRING_TO_HGMC_PARAM(&aParams[3], pAutoMountPoint);
9683 HGCMSvcSetU32(&aParams[4], SymlinkPolicy_None);
9684 AssertCompile(SHFL_CPARMS_ADD_MAPPING == 5);
9685
9686 vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders", SHFL_FN_ADD_MAPPING, SHFL_CPARMS_ADD_MAPPING, aParams);
9687 if (RT_FAILURE(vrc))
9688 hrc = setErrorBoth(E_FAIL, vrc, tr("Could not create a shared folder '%s' mapped to '%s' (%Rrc)"),
9689 strName.c_str(), aData.m_strHostPath.c_str(), vrc);
9690
9691 else if (fMissing)
9692 hrc = setError(E_INVALIDARG, tr("Shared folder path '%s' does not exist on the host"), aData.m_strHostPath.c_str());
9693 else
9694 hrc = S_OK;
9695 }
9696 else
9697 hrc = E_OUTOFMEMORY;
9698 RTMemFree(pAutoMountPoint);
9699 RTMemFree(pName);
9700 RTMemFree(pHostPath);
9701 return hrc;
9702}
9703
9704/**
9705 * Calls the HGCM service to remove the shared folder definition.
9706 *
9707 * @param strName Shared folder name.
9708 *
9709 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
9710 * @note Doesn't lock anything.
9711 */
9712HRESULT Console::i_removeSharedFolder(const Utf8Str &strName)
9713{
9714 ComAssertRet(strName.isNotEmpty(), E_FAIL);
9715
9716 /* sanity checks */
9717 AssertReturn(mpUVM, E_FAIL);
9718 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
9719
9720 VBOXHGCMSVCPARM parms;
9721 SHFLSTRING *pMapName;
9722 size_t cbString;
9723
9724 Log(("Removing shared folder '%s'\n", strName.c_str()));
9725
9726 Bstr bstrName(strName);
9727 cbString = (bstrName.length() + 1) * sizeof(RTUTF16);
9728 if (cbString >= UINT16_MAX)
9729 return setError(E_INVALIDARG, tr("The name is too long"));
9730 pMapName = (SHFLSTRING *) RTMemAllocZ(SHFLSTRING_HEADER_SIZE + cbString);
9731 Assert(pMapName);
9732 memcpy(pMapName->String.ucs2, bstrName.raw(), cbString);
9733
9734 pMapName->u16Size = (uint16_t)cbString;
9735 pMapName->u16Length = (uint16_t)(cbString - sizeof(RTUTF16));
9736
9737 parms.type = VBOX_HGCM_SVC_PARM_PTR;
9738 parms.u.pointer.addr = pMapName;
9739 parms.u.pointer.size = ShflStringSizeOfBuffer(pMapName);
9740
9741 int vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders", SHFL_FN_REMOVE_MAPPING, 1, &parms);
9742 RTMemFree(pMapName);
9743 if (RT_FAILURE(vrc))
9744 return setErrorBoth(E_FAIL, vrc, tr("Could not remove the shared folder '%s' (%Rrc)"), strName.c_str(), vrc);
9745
9746 return S_OK;
9747}
9748
9749/**
9750 * Retains a reference to the default cryptographic interface.
9751 *
9752 * @returns VBox status code.
9753 * @retval VERR_NOT_SUPPORTED if the VM is not configured for encryption.
9754 * @param ppCryptoIf Where to store the pointer to the cryptographic interface on success.
9755 *
9756 * @note Locks this object for writing.
9757 */
9758int Console::i_retainCryptoIf(PCVBOXCRYPTOIF *ppCryptoIf)
9759{
9760 AssertReturn(ppCryptoIf != NULL, VERR_INVALID_PARAMETER);
9761
9762 int vrc = VINF_SUCCESS;
9763 if (mhLdrModCrypto == NIL_RTLDRMOD)
9764 {
9765#ifdef VBOX_WITH_EXTPACK
9766 /*
9767 * Check that a crypto extension pack name is set and resolve it into a
9768 * library path.
9769 */
9770 HRESULT hrc = S_OK;
9771 Bstr bstrExtPack;
9772
9773 ComPtr<IVirtualBox> pVirtualBox;
9774 hrc = mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
9775 ComPtr<ISystemProperties> pSystemProperties;
9776 if (SUCCEEDED(hrc))
9777 hrc = pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
9778 if (SUCCEEDED(hrc))
9779 hrc = pSystemProperties->COMGETTER(DefaultCryptoExtPack)(bstrExtPack.asOutParam());
9780 if (FAILED(hrc))
9781 {
9782 setErrorBoth(hrc, VERR_INVALID_PARAMETER,
9783 tr("Failed to query default extension pack name for the cryptographic module"));
9784 return VERR_INVALID_PARAMETER;
9785 }
9786
9787 Utf8Str strExtPack(bstrExtPack);
9788 if (strExtPack.isEmpty())
9789 {
9790 setError(VBOX_E_OBJECT_NOT_FOUND,
9791 tr("Ńo extension pack providing a cryptographic support module could be found"));
9792 return VERR_NOT_FOUND;
9793 }
9794
9795 Utf8Str strCryptoLibrary;
9796 vrc = mptrExtPackManager->i_getCryptoLibraryPathForExtPack(&strExtPack, &strCryptoLibrary);
9797 if (RT_SUCCESS(vrc))
9798 {
9799 RTERRINFOSTATIC ErrInfo;
9800 vrc = SUPR3HardenedLdrLoadPlugIn(strCryptoLibrary.c_str(), &mhLdrModCrypto, RTErrInfoInitStatic(&ErrInfo));
9801 if (RT_SUCCESS(vrc))
9802 {
9803 /* Resolve the entry point and query the pointer to the cryptographic interface. */
9804 PFNVBOXCRYPTOENTRY pfnCryptoEntry = NULL;
9805 vrc = RTLdrGetSymbol(mhLdrModCrypto, VBOX_CRYPTO_MOD_ENTRY_POINT, (void **)&pfnCryptoEntry);
9806 if (RT_SUCCESS(vrc))
9807 {
9808 vrc = pfnCryptoEntry(&mpCryptoIf);
9809 if (RT_FAILURE(vrc))
9810 setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
9811 tr("Failed to query the interface callback table from the cryptographic support module '%s' from extension pack '%s'"),
9812 strCryptoLibrary.c_str(), strExtPack.c_str());
9813 }
9814 else
9815 setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
9816 tr("Failed to resolve the entry point for the cryptographic support module '%s' from extension pack '%s'"),
9817 strCryptoLibrary.c_str(), strExtPack.c_str());
9818
9819 if (RT_FAILURE(vrc))
9820 {
9821 RTLdrClose(mhLdrModCrypto);
9822 mhLdrModCrypto = NIL_RTLDRMOD;
9823 }
9824 }
9825 else
9826 setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
9827 tr("Couldn't load the cryptographic support module '%s' from extension pack '%s' (error: '%s')"),
9828 strCryptoLibrary.c_str(), strExtPack.c_str(), ErrInfo.Core.pszMsg);
9829 }
9830 else
9831 setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
9832 tr("Couldn't resolve the library path of the crpytographic support module for extension pack '%s'"),
9833 strExtPack.c_str());
9834#else
9835 setError(VBOX_E_NOT_SUPPORTED,
9836 tr("The cryptographic support module is not supported in this build because extension packs are not supported"));
9837 vrc = VERR_NOT_SUPPORTED;
9838#endif
9839 }
9840
9841 if (RT_SUCCESS(vrc))
9842 {
9843 ASMAtomicIncU32(&mcRefsCrypto);
9844 *ppCryptoIf = mpCryptoIf;
9845 }
9846
9847 return vrc;
9848}
9849
9850/**
9851 * Releases the reference of the given cryptographic interface.
9852 *
9853 * @returns VBox status code.
9854 * @param pCryptoIf Pointer to the cryptographic interface to release.
9855 *
9856 * @note Locks this object for writing.
9857 */
9858int Console::i_releaseCryptoIf(PCVBOXCRYPTOIF pCryptoIf)
9859{
9860 AssertReturn(pCryptoIf == mpCryptoIf, VERR_INVALID_PARAMETER);
9861
9862 ASMAtomicDecU32(&mcRefsCrypto);
9863 return VINF_SUCCESS;
9864}
9865
9866/**
9867 * Tries to unload any loaded cryptographic support module if it is not in use currently.
9868 *
9869 * @returns COM status code.
9870 *
9871 * @note Locks this object for writing.
9872 */
9873HRESULT Console::i_unloadCryptoIfModule(void)
9874{
9875 AutoCaller autoCaller(this);
9876 AssertComRCReturnRC(autoCaller.hrc());
9877
9878 AutoWriteLock wlock(this COMMA_LOCKVAL_SRC_POS);
9879
9880 if (mcRefsCrypto)
9881 return setError(E_ACCESSDENIED,
9882 tr("The cryptographic support module is in use and can't be unloaded"));
9883
9884 if (mhLdrModCrypto != NIL_RTLDRMOD)
9885 {
9886 int vrc = RTLdrClose(mhLdrModCrypto);
9887 AssertRC(vrc);
9888 mhLdrModCrypto = NIL_RTLDRMOD;
9889 }
9890
9891 return S_OK;
9892}
9893
9894/** @callback_method_impl{FNVMATSTATE}
9895 *
9896 * @note Locks the Console object for writing.
9897 * @remarks The @a pUVM parameter can be NULL in one case where powerUpThread()
9898 * calls after the VM was destroyed.
9899 */
9900/*static*/ DECLCALLBACK(void)
9901Console::i_vmstateChangeCallback(PUVM pUVM, PCVMMR3VTABLE pVMM, VMSTATE enmState, VMSTATE enmOldState, void *pvUser)
9902{
9903 LogFlowFunc(("Changing state from %s to %s (pUVM=%p)\n",
9904 pVMM->pfnVMR3GetStateName(enmOldState), pVMM->pfnVMR3GetStateName(enmState), pUVM));
9905 RT_NOREF(pVMM);
9906
9907 Console *that = static_cast<Console *>(pvUser);
9908 AssertReturnVoid(that);
9909
9910 AutoCaller autoCaller(that);
9911
9912 /* Note that we must let this method proceed even if Console::uninit() has
9913 * been already called. In such case this VMSTATE change is a result of:
9914 * 1) powerDown() called from uninit() itself, or
9915 * 2) VM-(guest-)initiated power off. */
9916 AssertReturnVoid( autoCaller.isOk()
9917 || that->getObjectState().getState() == ObjectState::InUninit);
9918
9919 switch (enmState)
9920 {
9921 /*
9922 * The VM has terminated
9923 */
9924 case VMSTATE_OFF:
9925 {
9926#ifdef VBOX_WITH_GUEST_PROPS
9927 if (that->mfTurnResetIntoPowerOff)
9928 {
9929 Bstr strPowerOffReason;
9930
9931 if (that->mfPowerOffCausedByReset)
9932 strPowerOffReason = Bstr("Reset");
9933 else
9934 strPowerOffReason = Bstr("PowerOff");
9935
9936 that->mMachine->DeleteGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw());
9937 that->mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw(),
9938 strPowerOffReason.raw(), Bstr("RDONLYGUEST").raw());
9939 that->mMachine->SaveSettings();
9940 }
9941#endif
9942
9943 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9944
9945 if (that->mVMStateChangeCallbackDisabled)
9946 return;
9947
9948 /* Do we still think that it is running? It may happen if this is a
9949 * VM-(guest-)initiated shutdown/poweroff.
9950 */
9951 if ( that->mMachineState != MachineState_Stopping
9952 && that->mMachineState != MachineState_Saving
9953 && that->mMachineState != MachineState_Restoring
9954 && that->mMachineState != MachineState_TeleportingIn
9955 && that->mMachineState != MachineState_TeleportingPausedVM
9956 && !that->mVMIsAlreadyPoweringOff
9957 )
9958 {
9959 LogFlowFunc(("VM has powered itself off but Console still thinks it is running. Notifying.\n"));
9960
9961 /*
9962 * Prevent powerDown() from calling VMR3PowerOff() again if this was called from
9963 * the power off state change.
9964 * When called from the Reset state make sure to call VMR3PowerOff() first.
9965 */
9966 Assert(that->mVMPoweredOff == false);
9967 that->mVMPoweredOff = true;
9968
9969 /*
9970 * request a progress object from the server
9971 * (this will set the machine state to Stopping on the server
9972 * to block others from accessing this machine)
9973 */
9974 ComPtr<IProgress> pProgress;
9975 HRESULT hrc = that->mControl->BeginPoweringDown(pProgress.asOutParam());
9976 AssertComRC(hrc);
9977
9978 /* sync the state with the server */
9979 that->i_setMachineStateLocally(MachineState_Stopping);
9980
9981 /*
9982 * Setup task object and thread to carry out the operation
9983 * asynchronously (if we call powerDown() right here but there
9984 * is one or more mpUVM callers (added with addVMCaller()) we'll
9985 * deadlock).
9986 */
9987 VMPowerDownTask *pTask = NULL;
9988 try
9989 {
9990 pTask = new VMPowerDownTask(that, pProgress);
9991 }
9992 catch (std::bad_alloc &)
9993 {
9994 LogRelFunc(("E_OUTOFMEMORY creating VMPowerDownTask"));
9995 hrc = E_OUTOFMEMORY;
9996 break;
9997 }
9998
9999 /*
10000 * If creating a task failed, this can currently mean one of
10001 * two: either Console::uninit() has been called just a ms
10002 * before (so a powerDown() call is already on the way), or
10003 * powerDown() itself is being already executed. Just do
10004 * nothing.
10005 */
10006 if (pTask->isOk())
10007 {
10008 hrc = pTask->createThread();
10009 pTask = NULL;
10010 if (FAILED(hrc))
10011 LogRelFunc(("Problem with creating thread for VMPowerDownTask.\n"));
10012 }
10013 else
10014 {
10015 LogFlowFunc(("Console is already being uninitialized. (%Rhrc)\n", pTask->hrc()));
10016 delete pTask;
10017 pTask = NULL;
10018 hrc = E_FAIL;
10019 }
10020 }
10021 break;
10022 }
10023
10024 /* The VM has been completely destroyed.
10025 *
10026 * Note: This state change can happen at two points:
10027 * 1) At the end of VMR3Destroy() if it was not called from EMT.
10028 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
10029 * called by EMT.
10030 */
10031 case VMSTATE_TERMINATED:
10032 {
10033 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
10034
10035 if (that->mVMStateChangeCallbackDisabled)
10036 break;
10037
10038#ifdef VBOX_WITH_CLOUD_NET
10039 /*
10040 * We stop cloud gateway here because we may have failed to connect to it,
10041 * configure it, or establish a tunnel. We definitely do not want an orphaned
10042 * instance running in the cloud.
10043 */
10044 if (!that->mGateway.mGatewayInstanceId.isEmpty())
10045 {
10046 ComPtr<IVirtualBox> pVirtualBox;
10047 HRESULT hrc = that->mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
10048 AssertComRC(hrc);
10049 if (SUCCEEDED(hrc) && !pVirtualBox.isNull())
10050 stopCloudGateway(pVirtualBox, that->mGateway);
10051 }
10052#endif /* VBOX_WITH_CLOUD_NET */
10053
10054 /* Terminate host interface networking. If pUVM is NULL, we've been
10055 * manually called from powerUpThread() either before calling
10056 * VMR3Create() or after VMR3Create() failed, so no need to touch
10057 * networking.
10058 */
10059 if (pUVM)
10060 that->i_powerDownHostInterfaces();
10061
10062 /* From now on the machine is officially powered down or remains in
10063 * the Saved state.
10064 */
10065 switch (that->mMachineState)
10066 {
10067 default:
10068 AssertFailed();
10069 RT_FALL_THRU();
10070 case MachineState_Stopping:
10071 /* successfully powered down */
10072 that->i_setMachineState(MachineState_PoweredOff);
10073 break;
10074 case MachineState_Saving:
10075 /* successfully saved */
10076 that->i_setMachineState(MachineState_Saved);
10077 break;
10078 case MachineState_Starting:
10079 /* failed to start, but be patient: set back to PoweredOff
10080 * (for similarity with the below) */
10081 that->i_setMachineState(MachineState_PoweredOff);
10082 break;
10083 case MachineState_Restoring:
10084 /* failed to load the saved state file, but be patient: set
10085 * to AbortedSaved (to preserve the saved state file) */
10086 that->i_setMachineState(MachineState_AbortedSaved);
10087 break;
10088 case MachineState_TeleportingIn:
10089 /* Teleportation failed or was canceled. Back to powered off. */
10090 that->i_setMachineState(MachineState_PoweredOff);
10091 break;
10092 case MachineState_TeleportingPausedVM:
10093 /* Successfully teleported the VM. */
10094 that->i_setMachineState(MachineState_Teleported);
10095 break;
10096 }
10097 break;
10098 }
10099
10100 case VMSTATE_RESETTING:
10101 /** @todo shouldn't VMSTATE_RESETTING_LS be here? */
10102 {
10103#ifdef VBOX_WITH_GUEST_PROPS
10104 /* Do not take any read/write locks here! */
10105 that->i_guestPropertiesHandleVMReset();
10106#endif
10107 break;
10108 }
10109
10110 case VMSTATE_SOFT_RESETTING:
10111 case VMSTATE_SOFT_RESETTING_LS:
10112 /* Shouldn't do anything here! */
10113 break;
10114
10115 case VMSTATE_SUSPENDED:
10116 {
10117 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
10118
10119 if (that->mVMStateChangeCallbackDisabled)
10120 break;
10121
10122 switch (that->mMachineState)
10123 {
10124 case MachineState_Teleporting:
10125 that->i_setMachineState(MachineState_TeleportingPausedVM);
10126 break;
10127
10128 case MachineState_LiveSnapshotting:
10129 that->i_setMachineState(MachineState_OnlineSnapshotting);
10130 break;
10131
10132 case MachineState_TeleportingPausedVM:
10133 case MachineState_Saving:
10134 case MachineState_Restoring:
10135 case MachineState_Stopping:
10136 case MachineState_TeleportingIn:
10137 case MachineState_OnlineSnapshotting:
10138 /* The worker thread handles the transition. */
10139 break;
10140
10141 case MachineState_Running:
10142 that->i_setMachineState(MachineState_Paused);
10143 break;
10144
10145 case MachineState_Paused:
10146 /* Nothing to do. */
10147 break;
10148
10149 default:
10150 AssertMsgFailed(("%s\n", ::stringifyMachineState(that->mMachineState)));
10151 }
10152 break;
10153 }
10154
10155 case VMSTATE_SUSPENDED_LS:
10156 case VMSTATE_SUSPENDED_EXT_LS:
10157 {
10158 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
10159 if (that->mVMStateChangeCallbackDisabled)
10160 break;
10161 switch (that->mMachineState)
10162 {
10163 case MachineState_Teleporting:
10164 that->i_setMachineState(MachineState_TeleportingPausedVM);
10165 break;
10166
10167 case MachineState_LiveSnapshotting:
10168 that->i_setMachineState(MachineState_OnlineSnapshotting);
10169 break;
10170
10171 case MachineState_TeleportingPausedVM:
10172 case MachineState_Saving:
10173 /* ignore */
10174 break;
10175
10176 default:
10177 AssertMsgFailed(("%s/%s -> %s\n", ::stringifyMachineState(that->mMachineState),
10178 pVMM->pfnVMR3GetStateName(enmOldState), pVMM->pfnVMR3GetStateName(enmState) ));
10179 that->i_setMachineState(MachineState_Paused);
10180 break;
10181 }
10182 break;
10183 }
10184
10185 case VMSTATE_RUNNING:
10186 {
10187 if ( enmOldState == VMSTATE_POWERING_ON
10188 || enmOldState == VMSTATE_RESUMING)
10189 {
10190 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
10191
10192 if (that->mVMStateChangeCallbackDisabled)
10193 break;
10194
10195 Assert( ( ( that->mMachineState == MachineState_Starting
10196 || that->mMachineState == MachineState_Paused)
10197 && enmOldState == VMSTATE_POWERING_ON)
10198 || ( ( that->mMachineState == MachineState_Restoring
10199 || that->mMachineState == MachineState_TeleportingIn
10200 || that->mMachineState == MachineState_Paused
10201 || that->mMachineState == MachineState_Saving
10202 )
10203 && enmOldState == VMSTATE_RESUMING));
10204
10205 that->i_setMachineState(MachineState_Running);
10206 }
10207
10208 break;
10209 }
10210
10211 case VMSTATE_RUNNING_LS:
10212 AssertMsg( that->mMachineState == MachineState_LiveSnapshotting
10213 || that->mMachineState == MachineState_Teleporting,
10214 ("%s/%s -> %s\n", ::stringifyMachineState(that->mMachineState),
10215 pVMM->pfnVMR3GetStateName(enmOldState), pVMM->pfnVMR3GetStateName(enmState) ));
10216 break;
10217
10218 case VMSTATE_FATAL_ERROR:
10219 {
10220 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
10221
10222 if (that->mVMStateChangeCallbackDisabled)
10223 break;
10224
10225 /* Fatal errors are only for running VMs. */
10226 Assert(Global::IsOnline(that->mMachineState));
10227
10228 /* Note! 'Pause' is used here in want of something better. There
10229 * are currently only two places where fatal errors might be
10230 * raised, so it is not worth adding a new externally
10231 * visible state for this yet. */
10232 that->i_setMachineState(MachineState_Paused);
10233 break;
10234 }
10235
10236 case VMSTATE_GURU_MEDITATION:
10237 {
10238 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
10239
10240 if (that->mVMStateChangeCallbackDisabled)
10241 break;
10242
10243 /* Guru are only for running VMs */
10244 Assert(Global::IsOnline(that->mMachineState));
10245
10246 that->i_setMachineState(MachineState_Stuck);
10247 break;
10248 }
10249
10250 case VMSTATE_CREATED:
10251 {
10252 /*
10253 * We have to set the secret key helper interface for the VD drivers to
10254 * get notified about missing keys.
10255 */
10256 that->i_initSecretKeyIfOnAllAttachments();
10257 break;
10258 }
10259
10260 default: /* shut up gcc */
10261 break;
10262 }
10263}
10264
10265/**
10266 * Changes the clipboard mode.
10267 *
10268 * @returns VBox status code.
10269 * @param aClipboardMode new clipboard mode.
10270 */
10271int Console::i_changeClipboardMode(ClipboardMode_T aClipboardMode)
10272{
10273#ifdef VBOX_WITH_SHARED_CLIPBOARD
10274 VMMDev *pVMMDev = m_pVMMDev;
10275 AssertPtrReturn(pVMMDev, VERR_INVALID_POINTER);
10276
10277 VBOXHGCMSVCPARM parm;
10278 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
10279
10280 switch (aClipboardMode)
10281 {
10282 default:
10283 case ClipboardMode_Disabled:
10284 LogRel(("Shared Clipboard: Mode: Off\n"));
10285 parm.u.uint32 = VBOX_SHCL_MODE_OFF;
10286 break;
10287 case ClipboardMode_GuestToHost:
10288 LogRel(("Shared Clipboard: Mode: Guest to Host\n"));
10289 parm.u.uint32 = VBOX_SHCL_MODE_GUEST_TO_HOST;
10290 break;
10291 case ClipboardMode_HostToGuest:
10292 LogRel(("Shared Clipboard: Mode: Host to Guest\n"));
10293 parm.u.uint32 = VBOX_SHCL_MODE_HOST_TO_GUEST;
10294 break;
10295 case ClipboardMode_Bidirectional:
10296 LogRel(("Shared Clipboard: Mode: Bidirectional\n"));
10297 parm.u.uint32 = VBOX_SHCL_MODE_BIDIRECTIONAL;
10298 break;
10299 }
10300
10301 int vrc = pVMMDev->hgcmHostCall("VBoxSharedClipboard", VBOX_SHCL_HOST_FN_SET_MODE, 1, &parm);
10302 if (RT_FAILURE(vrc))
10303 LogRel(("Shared Clipboard: Error changing mode: %Rrc\n", vrc));
10304
10305 return vrc;
10306#else
10307 RT_NOREF(aClipboardMode);
10308 return VERR_NOT_IMPLEMENTED;
10309#endif
10310}
10311
10312/**
10313 * Changes the clipboard file transfer mode.
10314 *
10315 * @returns VBox status code.
10316 * @param aEnabled Whether clipboard file transfers are enabled or not.
10317 */
10318int Console::i_changeClipboardFileTransferMode(bool aEnabled)
10319{
10320#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
10321 VMMDev *pVMMDev = m_pVMMDev;
10322 AssertPtrReturn(pVMMDev, VERR_INVALID_POINTER);
10323
10324 VBOXHGCMSVCPARM parm;
10325 RT_ZERO(parm);
10326
10327 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
10328 parm.u.uint32 = aEnabled ? VBOX_SHCL_TRANSFER_MODE_F_ENABLED : VBOX_SHCL_TRANSFER_MODE_F_NONE;
10329
10330 int vrc = pVMMDev->hgcmHostCall("VBoxSharedClipboard", VBOX_SHCL_HOST_FN_SET_TRANSFER_MODE, 1 /* cParms */, &parm);
10331 if (RT_FAILURE(vrc))
10332 LogRel(("Shared Clipboard: Error changing file transfer mode: %Rrc\n", vrc));
10333
10334 return vrc;
10335#else
10336 RT_NOREF(aEnabled);
10337 return VERR_NOT_IMPLEMENTED;
10338#endif
10339}
10340
10341/**
10342 * Changes the drag and drop mode.
10343 *
10344 * @param aDnDMode new drag and drop mode.
10345 */
10346int Console::i_changeDnDMode(DnDMode_T aDnDMode)
10347{
10348 VMMDev *pVMMDev = m_pVMMDev;
10349 AssertPtrReturn(pVMMDev, VERR_INVALID_POINTER);
10350
10351 VBOXHGCMSVCPARM parm;
10352 RT_ZERO(parm);
10353 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
10354
10355 switch (aDnDMode)
10356 {
10357 default:
10358 case DnDMode_Disabled:
10359 LogRel(("Drag and drop mode: Off\n"));
10360 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_OFF;
10361 break;
10362 case DnDMode_GuestToHost:
10363 LogRel(("Drag and drop mode: Guest to Host\n"));
10364 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_GUEST_TO_HOST;
10365 break;
10366 case DnDMode_HostToGuest:
10367 LogRel(("Drag and drop mode: Host to Guest\n"));
10368 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_HOST_TO_GUEST;
10369 break;
10370 case DnDMode_Bidirectional:
10371 LogRel(("Drag and drop mode: Bidirectional\n"));
10372 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_BIDIRECTIONAL;
10373 break;
10374 }
10375
10376 int vrc = pVMMDev->hgcmHostCall("VBoxDragAndDropSvc", DragAndDropSvc::HOST_DND_FN_SET_MODE, 1 /* cParms */, &parm);
10377 if (RT_FAILURE(vrc))
10378 LogRel(("Error changing drag and drop mode: %Rrc\n", vrc));
10379
10380 return vrc;
10381}
10382
10383#ifdef VBOX_WITH_USB
10384/**
10385 * @interface_method_impl{REMOTEUSBIF,pfnQueryRemoteUsbBackend}
10386 */
10387/*static*/ DECLCALLBACK(PREMOTEUSBCALLBACK)
10388Console::i_usbQueryRemoteUsbBackend(void *pvUser, PCRTUUID pUuid, uint32_t idClient)
10389{
10390 Console *pConsole = (Console *)pvUser;
10391
10392 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
10393
10394 Guid const uuid(*pUuid);
10395 return (PREMOTEUSBCALLBACK)pConsole->i_consoleVRDPServer()->USBBackendRequestPointer(idClient, &uuid);
10396}
10397
10398
10399/**
10400 * Sends a request to VMM to attach the given host device.
10401 * After this method succeeds, the attached device will appear in the
10402 * mUSBDevices collection.
10403 *
10404 * @param aHostDevice device to attach
10405 *
10406 * @note Synchronously calls EMT.
10407 */
10408HRESULT Console::i_attachUSBDevice(IUSBDevice *aHostDevice, ULONG aMaskedIfs, const Utf8Str &aCaptureFilename)
10409{
10410 AssertReturn(aHostDevice, E_FAIL);
10411 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
10412
10413 HRESULT hrc;
10414
10415 /*
10416 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
10417 * method in EMT (using usbAttachCallback()).
10418 */
10419 Bstr bstrAddress;
10420 hrc = aHostDevice->COMGETTER(Address)(bstrAddress.asOutParam());
10421 ComAssertComRCRetRC(hrc);
10422 Utf8Str const Address(bstrAddress);
10423
10424 Bstr id;
10425 hrc = aHostDevice->COMGETTER(Id)(id.asOutParam());
10426 ComAssertComRCRetRC(hrc);
10427 Guid const uuid(id);
10428
10429 BOOL fRemote = FALSE;
10430 hrc = aHostDevice->COMGETTER(Remote)(&fRemote);
10431 ComAssertComRCRetRC(hrc);
10432
10433 Bstr bstrBackend;
10434 hrc = aHostDevice->COMGETTER(Backend)(bstrBackend.asOutParam());
10435 ComAssertComRCRetRC(hrc);
10436 Utf8Str const strBackend(bstrBackend);
10437
10438 /* Get the VM handle. */
10439 SafeVMPtr ptrVM(this);
10440 if (!ptrVM.isOk())
10441 return ptrVM.hrc();
10442
10443 LogFlowThisFunc(("Proxying USB device '%s' {%RTuuid}...\n", Address.c_str(), uuid.raw()));
10444
10445 PCFGMNODE pRemoteCfg = NULL;
10446 if (fRemote)
10447 {
10448 RemoteUSBDevice *pRemoteUSBDevice = static_cast<RemoteUSBDevice *>(aHostDevice);
10449
10450 pRemoteCfg = mpVMM->pfnCFGMR3CreateTree(ptrVM.rawUVM());
10451 if (pRemoteCfg)
10452 {
10453 int vrc = mpVMM->pfnCFGMR3InsertInteger(pRemoteCfg, "ClientId", pRemoteUSBDevice->clientId());
10454 if (RT_FAILURE(vrc))
10455 {
10456 mpVMM->pfnCFGMR3DestroyTree(pRemoteCfg);
10457 return setErrorBoth(E_FAIL, vrc, tr("Failed to create configuration for USB device."));
10458 }
10459 }
10460 else
10461 return setErrorBoth(E_OUTOFMEMORY, VERR_NO_MEMORY, tr("Failed to allocate config tree for USB device."));
10462 }
10463
10464 USBConnectionSpeed_T enmSpeed;
10465 hrc = aHostDevice->COMGETTER(Speed)(&enmSpeed);
10466 AssertComRCReturnRC(hrc);
10467
10468 int vrc = ptrVM.vtable()->pfnVMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
10469 (PFNRT)i_usbAttachCallback, 11 | VMREQ_F_EXTRA_ARGS_ALL_PTRS,
10470 this, ptrVM.rawUVM(), ptrVM.vtable(), aHostDevice, uuid.raw(),
10471 strBackend.c_str(), Address.c_str(), pRemoteCfg, /* extra arg (ptrs only): */
10472 &enmSpeed, &aMaskedIfs, aCaptureFilename.isEmpty()
10473 ? (const char *)NULL : aCaptureFilename.c_str());
10474 if (RT_SUCCESS(vrc))
10475 {
10476 /* Create a OUSBDevice and add it to the device list */
10477 ComObjPtr<OUSBDevice> pUSBDevice;
10478 pUSBDevice.createObject();
10479 hrc = pUSBDevice->init(aHostDevice);
10480 AssertComRC(hrc);
10481
10482 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10483 mUSBDevices.push_back(pUSBDevice);
10484 LogFlowFunc(("Attached device {%RTuuid}\n", pUSBDevice->i_id().raw()));
10485
10486 /* notify callbacks */
10487 alock.release();
10488 i_onUSBDeviceStateChange(pUSBDevice, true /* aAttached */, NULL);
10489 }
10490 else
10491 {
10492 Log1WarningThisFunc(("Failed to create proxy device for '%s' {%RTuuid} (%Rrc)\n", Address.c_str(), uuid.raw(), vrc));
10493 switch (vrc)
10494 {
10495 case VERR_VUSB_NO_PORTS:
10496 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to attach the USB device. (No available ports on the USB controller)."));
10497 break;
10498 case VERR_VUSB_USBFS_PERMISSION:
10499 hrc = setErrorBoth(E_FAIL, vrc, tr("Not permitted to open the USB device, check usbfs options"));
10500 break;
10501 default:
10502 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to create a proxy device for the USB device. (Error: %Rrc)"), vrc);
10503 break;
10504 }
10505 }
10506
10507 return hrc;
10508}
10509
10510/**
10511 * USB device attach callback used by AttachUSBDevice().
10512 * Note that AttachUSBDevice() doesn't return until this callback is executed,
10513 * so we don't use AutoCaller and don't care about reference counters of
10514 * interface pointers passed in.
10515 *
10516 * @thread EMT
10517 * @note Locks the console object for writing.
10518 */
10519//static
10520DECLCALLBACK(int)
10521Console::i_usbAttachCallback(Console *that, PUVM pUVM, PCVMMR3VTABLE pVMM, IUSBDevice *aHostDevice, PCRTUUID aUuid,
10522 const char *pszBackend, const char *aAddress, PCFGMNODE pRemoteCfg,
10523 USBConnectionSpeed_T *penmSpeed, ULONG *pfMaskedIfs, const char *pszCaptureFilename)
10524{
10525 RT_NOREF(aHostDevice);
10526 LogFlowFuncEnter();
10527 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
10528
10529 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
10530 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
10531
10532 VUSBSPEED enmSpeed = VUSB_SPEED_UNKNOWN;
10533 switch (*penmSpeed)
10534 {
10535 case USBConnectionSpeed_Low: enmSpeed = VUSB_SPEED_LOW; break;
10536 case USBConnectionSpeed_Full: enmSpeed = VUSB_SPEED_FULL; break;
10537 case USBConnectionSpeed_High: enmSpeed = VUSB_SPEED_HIGH; break;
10538 case USBConnectionSpeed_Super: enmSpeed = VUSB_SPEED_SUPER; break;
10539 case USBConnectionSpeed_SuperPlus: enmSpeed = VUSB_SPEED_SUPERPLUS; break;
10540 default: AssertFailed(); break;
10541 }
10542
10543 int vrc = pVMM->pfnPDMR3UsbCreateProxyDevice(pUVM, aUuid, pszBackend, aAddress, pRemoteCfg,
10544 enmSpeed, *pfMaskedIfs, pszCaptureFilename);
10545 LogFlowFunc(("vrc=%Rrc\n", vrc));
10546 LogFlowFuncLeave();
10547 return vrc;
10548}
10549
10550/**
10551 * Sends a request to VMM to detach the given host device. After this method
10552 * succeeds, the detached device will disappear from the mUSBDevices
10553 * collection.
10554 *
10555 * @param aHostDevice device to attach
10556 *
10557 * @note Synchronously calls EMT.
10558 */
10559HRESULT Console::i_detachUSBDevice(const ComObjPtr<OUSBDevice> &aHostDevice)
10560{
10561 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
10562
10563 /* Get the VM handle. */
10564 SafeVMPtr ptrVM(this);
10565 if (!ptrVM.isOk())
10566 return ptrVM.hrc();
10567
10568 /* if the device is attached, then there must at least one USB hub. */
10569 AssertReturn(ptrVM.vtable()->pfnPDMR3UsbHasHub(ptrVM.rawUVM()), E_FAIL);
10570
10571 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10572 LogFlowThisFunc(("Detaching USB proxy device {%RTuuid}...\n", aHostDevice->i_id().raw()));
10573
10574 /*
10575 * If this was a remote device, release the backend pointer.
10576 * The pointer was requested in usbAttachCallback.
10577 */
10578 BOOL fRemote = FALSE;
10579
10580 HRESULT hrc2 = aHostDevice->COMGETTER(Remote)(&fRemote);
10581 if (FAILED(hrc2))
10582 i_setErrorStatic(hrc2, "GetRemote() failed");
10583
10584 PCRTUUID pUuid = aHostDevice->i_id().raw();
10585 if (fRemote)
10586 {
10587 Guid guid(*pUuid);
10588 i_consoleVRDPServer()->USBBackendReleasePointer(&guid);
10589 }
10590
10591 alock.release();
10592 int vrc = ptrVM.vtable()->pfnVMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
10593 (PFNRT)i_usbDetachCallback, 4, this, ptrVM.rawUVM(), ptrVM.vtable(), pUuid);
10594 if (RT_SUCCESS(vrc))
10595 {
10596 LogFlowFunc(("Detached device {%RTuuid}\n", pUuid));
10597
10598 /* notify callbacks */
10599 i_onUSBDeviceStateChange(aHostDevice, false /* aAttached */, NULL);
10600 }
10601
10602 ComAssertRCRet(vrc, E_FAIL);
10603
10604 return S_OK;
10605}
10606
10607/**
10608 * USB device detach callback used by DetachUSBDevice().
10609 *
10610 * Note that DetachUSBDevice() doesn't return until this callback is executed,
10611 * so we don't use AutoCaller and don't care about reference counters of
10612 * interface pointers passed in.
10613 *
10614 * @thread EMT
10615 */
10616//static
10617DECLCALLBACK(int)
10618Console::i_usbDetachCallback(Console *that, PUVM pUVM, PCVMMR3VTABLE pVMM, PCRTUUID aUuid)
10619{
10620 LogFlowFuncEnter();
10621 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
10622
10623 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
10624 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
10625
10626 int vrc = pVMM->pfnPDMR3UsbDetachDevice(pUVM, aUuid);
10627
10628 LogFlowFunc(("vrc=%Rrc\n", vrc));
10629 LogFlowFuncLeave();
10630 return vrc;
10631}
10632#endif /* VBOX_WITH_USB */
10633
10634/* Note: FreeBSD needs this whether netflt is used or not. */
10635#if ((defined(RT_OS_LINUX) && !defined(VBOX_WITH_NETFLT)) || defined(RT_OS_FREEBSD))
10636
10637/**
10638 * Helper function to handle host interface device creation and attachment.
10639 *
10640 * @param networkAdapter the network adapter which attachment should be reset
10641 * @return COM status code
10642 *
10643 * @note The caller must lock this object for writing.
10644 *
10645 * @todo Move this back into the driver!
10646 */
10647HRESULT Console::i_attachToTapInterface(INetworkAdapter *networkAdapter)
10648{
10649 LogFlowThisFunc(("\n"));
10650 /* sanity check */
10651 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
10652
10653# ifdef VBOX_STRICT
10654 /* paranoia */
10655 NetworkAttachmentType_T attachment;
10656 networkAdapter->COMGETTER(AttachmentType)(&attachment);
10657 Assert(attachment == NetworkAttachmentType_Bridged);
10658# endif /* VBOX_STRICT */
10659
10660 ULONG slot = 0;
10661 HRESULT hrc = networkAdapter->COMGETTER(Slot)(&slot);
10662 AssertComRCReturnRC(hrc);
10663
10664# ifdef RT_OS_LINUX
10665 /*
10666 * Allocate a host interface device
10667 */
10668 int vrc = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
10669 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
10670 if (RT_SUCCESS(vrc))
10671 {
10672 /*
10673 * Set/obtain the tap interface.
10674 */
10675 struct ifreq IfReq;
10676 RT_ZERO(IfReq);
10677 /* The name of the TAP interface we are using */
10678 Bstr tapDeviceName;
10679 hrc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
10680 if (FAILED(hrc))
10681 tapDeviceName.setNull(); /* Is this necessary? */
10682 if (tapDeviceName.isEmpty())
10683 {
10684 LogRel(("No TAP device name was supplied.\n"));
10685 hrc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
10686 }
10687
10688 if (SUCCEEDED(hrc))
10689 {
10690 /* If we are using a static TAP device then try to open it. */
10691 Utf8Str str(tapDeviceName);
10692 RTStrCopy(IfReq.ifr_name, sizeof(IfReq.ifr_name), str.c_str()); /** @todo bitch about names which are too long... */
10693 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
10694 vrc = ioctl(RTFileToNative(maTapFD[slot]), TUNSETIFF, &IfReq);
10695 if (vrc != 0)
10696 {
10697 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
10698 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to open the host network interface %ls"), tapDeviceName.raw());
10699 }
10700 }
10701 if (SUCCEEDED(hrc))
10702 {
10703 /*
10704 * Make it pollable.
10705 */
10706 if (fcntl(RTFileToNative(maTapFD[slot]), F_SETFL, O_NONBLOCK) != -1)
10707 {
10708 Log(("i_attachToTapInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
10709 /*
10710 * Here is the right place to communicate the TAP file descriptor and
10711 * the host interface name to the server if/when it becomes really
10712 * necessary.
10713 */
10714 maTAPDeviceName[slot] = tapDeviceName;
10715 vrc = VINF_SUCCESS;
10716 }
10717 else
10718 {
10719 int iErr = errno;
10720
10721 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
10722 vrc = VERR_HOSTIF_BLOCKING;
10723 hrc = setErrorBoth(E_FAIL, vrc, tr("could not set up the host networking device for non blocking access: %s"),
10724 strerror(errno));
10725 }
10726 }
10727 }
10728 else
10729 {
10730 LogRel(("Configuration error: Failed to open /dev/net/tun vrc=%Rrc\n", vrc));
10731 switch (vrc)
10732 {
10733 case VERR_ACCESS_DENIED:
10734 /* will be handled by our caller */
10735 hrc = E_ACCESSDENIED;
10736 break;
10737 default:
10738 hrc = setErrorBoth(E_FAIL, vrc, tr("Could not set up the host networking device: %Rrc"), vrc);
10739 break;
10740 }
10741 }
10742
10743# elif defined(RT_OS_FREEBSD)
10744 /*
10745 * Set/obtain the tap interface.
10746 */
10747 /* The name of the TAP interface we are using */
10748 Bstr tapDeviceName;
10749 hrc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
10750 if (FAILED(hrc))
10751 tapDeviceName.setNull(); /* Is this necessary? */
10752 if (tapDeviceName.isEmpty())
10753 {
10754 LogRel(("No TAP device name was supplied.\n"));
10755 hrc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
10756 }
10757 char szTapdev[1024] = "/dev/";
10758 /* If we are using a static TAP device then try to open it. */
10759 Utf8Str str(tapDeviceName);
10760 if (str.length() + strlen(szTapdev) <= sizeof(szTapdev))
10761 strcat(szTapdev, str.c_str());
10762 else
10763 memcpy(szTapdev + strlen(szTapdev), str.c_str(),
10764 sizeof(szTapdev) - strlen(szTapdev) - 1); /** @todo bitch about names which are too long... */
10765 int vrc = RTFileOpen(&maTapFD[slot], szTapdev,
10766 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT | RTFILE_O_NON_BLOCK);
10767
10768 if (RT_SUCCESS(vrc))
10769 maTAPDeviceName[slot] = tapDeviceName;
10770 else
10771 {
10772 switch (vrc)
10773 {
10774 case VERR_ACCESS_DENIED:
10775 /* will be handled by our caller */
10776 hrc = E_ACCESSDENIED;
10777 break;
10778 default:
10779 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to open the host network interface %ls"), tapDeviceName.raw());
10780 break;
10781 }
10782 }
10783# else
10784# error "huh?"
10785# endif
10786 /* in case of failure, cleanup. */
10787 if (RT_FAILURE(vrc) && SUCCEEDED(hrc))
10788 {
10789 LogRel(("General failure attaching to host interface\n"));
10790 hrc = setErrorBoth(E_FAIL, vrc, tr("General failure attaching to host interface"));
10791 }
10792 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
10793 return hrc;
10794}
10795
10796
10797/**
10798 * Helper function to handle detachment from a host interface
10799 *
10800 * @param networkAdapter the network adapter which attachment should be reset
10801 * @return COM status code
10802 *
10803 * @note The caller must lock this object for writing.
10804 *
10805 * @todo Move this back into the driver!
10806 */
10807HRESULT Console::i_detachFromTapInterface(INetworkAdapter *networkAdapter)
10808{
10809 /* sanity check */
10810 LogFlowThisFunc(("\n"));
10811 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
10812
10813# ifdef VBOX_STRICT
10814 /* paranoia */
10815 NetworkAttachmentType_T attachment;
10816 networkAdapter->COMGETTER(AttachmentType)(&attachment);
10817 Assert(attachment == NetworkAttachmentType_Bridged);
10818# endif /* VBOX_STRICT */
10819
10820 ULONG slot = 0;
10821 HRESULT hrc = networkAdapter->COMGETTER(Slot)(&slot);
10822 AssertComRCReturnRC(hrc);
10823
10824 /* is there an open TAP device? */
10825 if (maTapFD[slot] != NIL_RTFILE)
10826 {
10827 /*
10828 * Close the file handle.
10829 */
10830 Bstr tapDeviceName, tapTerminateApplication;
10831 bool isStatic = true;
10832 hrc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
10833 if (FAILED(hrc) || tapDeviceName.isEmpty())
10834 {
10835 /* If the name is empty, this is a dynamic TAP device, so close it now,
10836 so that the termination script can remove the interface. Otherwise we still
10837 need the FD to pass to the termination script. */
10838 isStatic = false;
10839 int vrc = RTFileClose(maTapFD[slot]);
10840 AssertRC(vrc);
10841 maTapFD[slot] = NIL_RTFILE;
10842 }
10843 if (isStatic)
10844 {
10845 /* If we are using a static TAP device, we close it now, after having called the
10846 termination script. */
10847 int vrc = RTFileClose(maTapFD[slot]);
10848 AssertRC(vrc);
10849 }
10850 /* the TAP device name and handle are no longer valid */
10851 maTapFD[slot] = NIL_RTFILE;
10852 maTAPDeviceName[slot] = "";
10853 }
10854 LogFlowThisFunc(("returning %Rhrc\n", hrc));
10855 return hrc;
10856}
10857
10858#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
10859
10860/**
10861 * Called at power down to terminate host interface networking.
10862 *
10863 * @note The caller must lock this object for writing.
10864 */
10865HRESULT Console::i_powerDownHostInterfaces()
10866{
10867 LogFlowThisFunc(("\n"));
10868
10869 /* sanity check */
10870 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
10871
10872#if (defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)) && !defined(VBOX_WITH_NETFLT)
10873 /*
10874 * Host TAP interface termination handling.
10875 */
10876 ComPtr<IVirtualBox> pVirtualBox;
10877 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
10878
10879 ComPtr<IPlatform> pPlatform;
10880 HRESULT hrc = mMachine->COMGETTER(Platform)(pPlatform.asOutParam());
10881 AssertComRC(hrc);
10882
10883 PlatformArchitecture_T platformArch;
10884 hrc = pPlatform->COMGETTER(Architecture)(&platformArch);
10885 AssertComRC(hrc);
10886
10887 ComPtr<IPlatformProperties> pPlatformProperties;
10888 hrc = pVirtualBox->GetPlatformProperties(platformArch, pPlatformProperties.asOutParam());
10889 AssertComRC(hrc);
10890
10891 ChipsetType_T chipsetType = ChipsetType_PIIX3;
10892 pPlatform->COMGETTER(ChipsetType)(&chipsetType);
10893 AssertComRC(hrc);
10894
10895 ULONG maxNetworkAdapters = 0;
10896 hrc = pPlatformProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters);
10897 AssertComRC(hrc);
10898
10899 for (ULONG slot = 0; slot < maxNetworkAdapters; slot++)
10900 {
10901 ComPtr<INetworkAdapter> pNetworkAdapter;
10902 hrc = mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
10903 if (FAILED(hrc)) break;
10904
10905 BOOL enabled = FALSE;
10906 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
10907 if (!enabled)
10908 continue;
10909
10910 NetworkAttachmentType_T attachment;
10911 pNetworkAdapter->COMGETTER(AttachmentType)(&attachment);
10912 if (attachment == NetworkAttachmentType_Bridged)
10913 {
10914 HRESULT hrc2 = i_detachFromTapInterface(pNetworkAdapter);
10915 if (FAILED(hrc2) && SUCCEEDED(hrc))
10916 hrc = hrc2;
10917 }
10918 }
10919
10920 return hrc;
10921
10922#else
10923 /* Nothing to do here. */
10924 return S_OK;
10925#endif
10926}
10927
10928
10929/**
10930 * Process callback handler for VMR3LoadFromFile, VMR3LoadFromStream, VMR3Save
10931 * and VMR3Teleport.
10932 *
10933 * @param pUVM The user mode VM handle.
10934 * @param uPercent Completion percentage (0-100).
10935 * @param pvUser Pointer to an IProgress instance.
10936 * @return VINF_SUCCESS.
10937 */
10938/*static*/
10939DECLCALLBACK(int) Console::i_stateProgressCallback(PUVM pUVM, unsigned uPercent, void *pvUser)
10940{
10941 IProgress *pProgress = static_cast<IProgress *>(pvUser);
10942
10943 /* update the progress object */
10944 if (pProgress)
10945 {
10946 ComPtr<IInternalProgressControl> pProgressControl(pProgress);
10947 AssertReturn(!!pProgressControl, VERR_INVALID_PARAMETER);
10948 pProgressControl->SetCurrentOperationProgress(uPercent);
10949 }
10950
10951 NOREF(pUVM);
10952 return VINF_SUCCESS;
10953}
10954
10955/**
10956 * @copydoc FNVMATERROR
10957 *
10958 * @remarks Might be some tiny serialization concerns with access to the string
10959 * object here...
10960 */
10961/*static*/ DECLCALLBACK(void)
10962Console::i_genericVMSetErrorCallback(PUVM pUVM, void *pvUser, int vrc, RT_SRC_POS_DECL, const char *pszFormat, va_list args)
10963{
10964 RT_SRC_POS_NOREF();
10965 Utf8Str *pErrorText = (Utf8Str *)pvUser;
10966 AssertPtr(pErrorText);
10967
10968 /* We ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users. */
10969 va_list va2;
10970 va_copy(va2, args);
10971
10972 /* Append to any the existing error message. */
10973 try
10974 {
10975 if (pErrorText->length())
10976 pErrorText->appendPrintf(".\n%N (%Rrc)", pszFormat, &va2, vrc, vrc);
10977 else
10978 pErrorText->printf("%N (%Rrc)", pszFormat, &va2, vrc, vrc);
10979 }
10980 catch (std::bad_alloc &)
10981 {
10982 }
10983
10984 va_end(va2);
10985
10986 NOREF(pUVM);
10987}
10988
10989/**
10990 * VM runtime error callback function (FNVMATRUNTIMEERROR).
10991 *
10992 * See VMSetRuntimeError for the detailed description of parameters.
10993 *
10994 * @param pUVM The user mode VM handle. Ignored, so passing NULL
10995 * is fine.
10996 * @param pvUser The user argument, pointer to the Console instance.
10997 * @param fFlags The action flags. See VMSETRTERR_FLAGS_*.
10998 * @param pszErrorId Error ID string.
10999 * @param pszFormat Error message format string.
11000 * @param va Error message arguments.
11001 * @thread EMT.
11002 */
11003/* static */ DECLCALLBACK(void)
11004Console::i_atVMRuntimeErrorCallback(PUVM pUVM, void *pvUser, uint32_t fFlags,
11005 const char *pszErrorId, const char *pszFormat, va_list va)
11006{
11007 bool const fFatal = !!(fFlags & VMSETRTERR_FLAGS_FATAL);
11008 LogFlowFuncEnter();
11009
11010 Console *that = static_cast<Console *>(pvUser);
11011 AssertReturnVoid(that);
11012
11013 Utf8Str message(pszFormat, va);
11014
11015 LogRel(("Console: VM runtime error: fatal=%RTbool, errorID=%s message=\"%s\"\n", fFatal, pszErrorId, message.c_str()));
11016 try
11017 {
11018 that->i_onRuntimeError(BOOL(fFatal), Bstr(pszErrorId).raw(), Bstr(message).raw());
11019 }
11020 catch (std::bad_alloc &)
11021 {
11022 }
11023 LogFlowFuncLeave(); NOREF(pUVM);
11024}
11025
11026/**
11027 * Captures USB devices that match filters of the VM.
11028 * Called at VM startup.
11029 *
11030 * @param pUVM The VM handle.
11031 */
11032HRESULT Console::i_captureUSBDevices(PUVM pUVM)
11033{
11034 RT_NOREF(pUVM);
11035 LogFlowThisFunc(("\n"));
11036
11037 /* sanity check */
11038 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
11039 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11040
11041 /* If the machine has a USB controller, ask the USB proxy service to
11042 * capture devices */
11043 if (mfVMHasUsbController)
11044 {
11045 /* release the lock before calling Host in VBoxSVC since Host may call
11046 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
11047 * produce an inter-process dead-lock otherwise. */
11048 alock.release();
11049
11050 HRESULT hrc = mControl->AutoCaptureUSBDevices();
11051 ComAssertComRCRetRC(hrc);
11052 }
11053
11054 return S_OK;
11055}
11056
11057
11058/**
11059 * Detach all USB device which are attached to the VM for the
11060 * purpose of clean up and such like.
11061 */
11062void Console::i_detachAllUSBDevices(bool aDone)
11063{
11064 LogFlowThisFunc(("aDone=%RTbool\n", aDone));
11065
11066 /* sanity check */
11067 AssertReturnVoid(!isWriteLockOnCurrentThread());
11068 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11069
11070 mUSBDevices.clear();
11071
11072 /* release the lock before calling Host in VBoxSVC since Host may call
11073 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
11074 * produce an inter-process dead-lock otherwise. */
11075 alock.release();
11076
11077 mControl->DetachAllUSBDevices(aDone);
11078}
11079
11080/* Make sure that the string is null-terminated and its size is less than cchMax bytes.
11081 * Replace invalid UTF8 bytes with '?'.
11082 */
11083static int validateUtf8String(char *psz, size_t cchMax)
11084{
11085 for (;;)
11086 {
11087 RTUNICP Cp;
11088 int vrc = RTStrGetCpNEx((const char **)&psz, &cchMax, &Cp);
11089 if (RT_SUCCESS(vrc))
11090 {
11091 if (!Cp)
11092 break;
11093 }
11094 else
11095 {
11096 if (!cchMax)
11097 return VERR_END_OF_STRING;
11098
11099 psz[-1] = '?';
11100 }
11101 }
11102 return VINF_SUCCESS;
11103}
11104
11105static int validateRemoteUSBDeviceDesc(VRDEUSBDEVICEDESC const *e, uint32_t cbRemaining, bool fDescExt)
11106{
11107 uint32_t const cbDesc = fDescExt ? sizeof(VRDEUSBDEVICEDESCEXT) : sizeof(VRDEUSBDEVICEDESC);
11108 if (cbDesc > cbRemaining)
11109 return VERR_INVALID_PARAMETER;
11110
11111 if ( e->oNext > cbRemaining /* It is OK for oNext to point to the end of buffer. */
11112 || e->oManufacturer >= cbRemaining
11113 || e->oProduct >= cbRemaining
11114 || e->oSerialNumber >= cbRemaining)
11115 return VERR_INVALID_PARAMETER;
11116
11117 int vrc;
11118 if (e->oManufacturer)
11119 {
11120 vrc = validateUtf8String((char *)e + e->oManufacturer, cbRemaining - e->oManufacturer);
11121 if (RT_FAILURE(vrc))
11122 return VERR_INVALID_PARAMETER;
11123 }
11124 if (e->oProduct)
11125 {
11126 vrc = validateUtf8String((char *)e + e->oProduct, cbRemaining - e->oProduct);
11127 if (RT_FAILURE(vrc))
11128 return VERR_INVALID_PARAMETER;
11129 }
11130 if (e->oSerialNumber)
11131 {
11132 vrc = validateUtf8String((char *)e + e->oSerialNumber, cbRemaining - e->oSerialNumber);
11133 if (RT_FAILURE(vrc))
11134 return VERR_INVALID_PARAMETER;
11135 }
11136
11137 return VINF_SUCCESS;
11138}
11139
11140/**
11141 * @note Locks this object for writing.
11142 */
11143void Console::i_processRemoteUSBDevices(uint32_t u32ClientId, VRDEUSBDEVICEDESC *pDevList, uint32_t cbDevList, bool fDescExt)
11144{
11145 LogFlowThisFuncEnter();
11146 LogFlowThisFunc(("u32ClientId = %d, pDevList=%p, cbDevList = %d, fDescExt = %d\n",
11147 u32ClientId, pDevList, cbDevList, fDescExt));
11148
11149 AutoCaller autoCaller(this);
11150 if (!autoCaller.isOk())
11151 {
11152 /* Console has been already uninitialized, deny request */
11153 AssertMsgFailed(("Console is already uninitialized\n"));
11154 LogFlowThisFunc(("Console is already uninitialized\n"));
11155 LogFlowThisFuncLeave();
11156 return;
11157 }
11158
11159 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
11160
11161 /*
11162 * Mark all existing remote USB devices as dirty.
11163 */
11164 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
11165 it != mRemoteUSBDevices.end();
11166 ++it)
11167 {
11168 (*it)->dirty(true);
11169 }
11170
11171 /*
11172 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
11173 */
11174 VRDEUSBDEVICEDESC *e = pDevList;
11175 uint32_t cbRemaining = cbDevList;
11176
11177 /* The cbRemaining condition must be checked first, because the function can
11178 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
11179 */
11180 while (cbRemaining >= sizeof(e->oNext) && e->oNext)
11181 {
11182 int const vrc = validateRemoteUSBDeviceDesc(e, cbRemaining, fDescExt);
11183 if (RT_FAILURE(vrc))
11184 break; /* Consider the rest of the list invalid too. */
11185
11186 LogFlowThisFunc(("vendor %04x, product %04x, name = %s\n",
11187 e->idVendor, e->idProduct, e->oProduct ? (char *)e + e->oProduct : ""));
11188
11189 bool fNewDevice = true;
11190
11191 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
11192 it != mRemoteUSBDevices.end();
11193 ++it)
11194 {
11195 if ( (*it)->devId() == e->id
11196 && (*it)->clientId() == u32ClientId)
11197 {
11198 /* The device is already in the list. */
11199 (*it)->dirty(false);
11200 fNewDevice = false;
11201 break;
11202 }
11203 }
11204
11205 if (fNewDevice)
11206 {
11207 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
11208 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""));
11209
11210 /* Create the device object and add the new device to list. */
11211 ComObjPtr<RemoteUSBDevice> pUSBDevice;
11212 pUSBDevice.createObject();
11213 pUSBDevice->init(u32ClientId, e, fDescExt);
11214
11215 mRemoteUSBDevices.push_back(pUSBDevice);
11216
11217 /* Check if the device is ok for current USB filters. */
11218 BOOL fMatched = FALSE;
11219 ULONG fMaskedIfs = 0;
11220 HRESULT hrc = mControl->RunUSBDeviceFilters(pUSBDevice, &fMatched, &fMaskedIfs);
11221
11222 AssertComRC(hrc);
11223
11224 LogFlowThisFunc(("USB filters return %d %#x\n", fMatched, fMaskedIfs));
11225
11226 if (fMatched)
11227 {
11228 alock.release();
11229 hrc = i_onUSBDeviceAttach(pUSBDevice, NULL, fMaskedIfs, Utf8Str());
11230 alock.acquire();
11231
11232 /// @todo (r=dmik) warning reporting subsystem
11233
11234 if (hrc == S_OK)
11235 {
11236 LogFlowThisFunc(("Device attached\n"));
11237 pUSBDevice->captured(true);
11238 }
11239 }
11240 }
11241
11242 AssertBreak(cbRemaining >= e->oNext); /* validateRemoteUSBDeviceDesc ensures this. */
11243 cbRemaining -= e->oNext;
11244
11245 e = (VRDEUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
11246 }
11247
11248 /*
11249 * Remove dirty devices, that is those which are not reported by the server anymore.
11250 */
11251 for (;;)
11252 {
11253 ComObjPtr<RemoteUSBDevice> pUSBDevice;
11254
11255 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
11256 while (it != mRemoteUSBDevices.end())
11257 {
11258 if ((*it)->dirty())
11259 {
11260 pUSBDevice = *it;
11261 break;
11262 }
11263
11264 ++it;
11265 }
11266
11267 if (!pUSBDevice)
11268 {
11269 break;
11270 }
11271
11272 USHORT vendorId = 0;
11273 pUSBDevice->COMGETTER(VendorId)(&vendorId);
11274
11275 USHORT productId = 0;
11276 pUSBDevice->COMGETTER(ProductId)(&productId);
11277
11278 Bstr product;
11279 pUSBDevice->COMGETTER(Product)(product.asOutParam());
11280
11281 LogRel(("Remote USB: ---- Vendor %04x. Product %04x. Name = [%ls].\n", vendorId, productId, product.raw()));
11282
11283 /* Detach the device from VM. */
11284 if (pUSBDevice->captured())
11285 {
11286 Bstr uuid;
11287 pUSBDevice->COMGETTER(Id)(uuid.asOutParam());
11288 alock.release();
11289 i_onUSBDeviceDetach(uuid.raw(), NULL);
11290 alock.acquire();
11291 }
11292
11293 /* And remove it from the list. */
11294 mRemoteUSBDevices.erase(it);
11295 }
11296
11297 LogFlowThisFuncLeave();
11298}
11299
11300
11301/**
11302 * Worker called by VMPowerUpTask::handler to start the VM (also from saved
11303 * state) and track progress.
11304 *
11305 * @param pTask The power up task.
11306 *
11307 * @note Locks the Console object for writing.
11308 */
11309/*static*/
11310void Console::i_powerUpThreadTask(VMPowerUpTask *pTask)
11311{
11312 LogFlowFuncEnter();
11313
11314 AssertReturnVoid(pTask);
11315 AssertReturnVoid(!pTask->mConsole.isNull());
11316 AssertReturnVoid(!pTask->mProgress.isNull());
11317
11318 VirtualBoxBase::initializeComForThread();
11319
11320 HRESULT hrc = S_OK;
11321 int vrc = VINF_SUCCESS;
11322
11323 /* Set up a build identifier so that it can be seen from core dumps what
11324 * exact build was used to produce the core. */
11325 static char s_szBuildID[48];
11326 RTStrPrintf(s_szBuildID, sizeof(s_szBuildID), "%s%s%s%s VirtualBox %s r%u %s%s%s%s",
11327 "BU", "IL", "DI", "D", RTBldCfgVersion(), RTBldCfgRevision(), "BU", "IL", "DI", "D");
11328
11329 ComObjPtr<Console> pConsole = pTask->mConsole;
11330
11331 /* Note: no need to use AutoCaller because VMPowerUpTask does that */
11332
11333 /* The lock is also used as a signal from the task initiator (which
11334 * releases it only after RTThreadCreate()) that we can start the job */
11335 AutoWriteLock alock(pConsole COMMA_LOCKVAL_SRC_POS);
11336
11337 /* sanity */
11338 Assert(pConsole->mpUVM == NULL);
11339
11340 try
11341 {
11342 // Create the VMM device object, which starts the HGCM thread; do this only
11343 // once for the console, for the pathological case that the same console
11344 // object is used to power up a VM twice.
11345 if (!pConsole->m_pVMMDev)
11346 {
11347 pConsole->m_pVMMDev = new VMMDev(pConsole);
11348 AssertReturnVoid(pConsole->m_pVMMDev);
11349 }
11350
11351 /* wait for auto reset ops to complete so that we can successfully lock
11352 * the attached hard disks by calling LockMedia() below */
11353 for (VMPowerUpTask::ProgressList::const_iterator
11354 it = pTask->hardDiskProgresses.begin();
11355 it != pTask->hardDiskProgresses.end(); ++it)
11356 {
11357 HRESULT hrc2 = (*it)->WaitForCompletion(-1);
11358 AssertComRC(hrc2);
11359
11360 hrc = pTask->mProgress->SetNextOperation(BstrFmt(tr("Disk Image Reset Operation - Immutable Image")).raw(), 1);
11361 AssertComRCReturnVoid(hrc);
11362 }
11363
11364 /*
11365 * Lock attached media. This method will also check their accessibility.
11366 * If we're a teleporter, we'll have to postpone this action so we can
11367 * migrate between local processes.
11368 *
11369 * Note! The media will be unlocked automatically by
11370 * SessionMachine::i_setMachineState() when the VM is powered down.
11371 */
11372 if (!pTask->mTeleporterEnabled)
11373 {
11374 hrc = pConsole->mControl->LockMedia();
11375 if (FAILED(hrc)) throw hrc;
11376 }
11377
11378 /* Create the VRDP server. In case of headless operation, this will
11379 * also create the framebuffer, required at VM creation.
11380 */
11381 ConsoleVRDPServer *server = pConsole->i_consoleVRDPServer();
11382 Assert(server);
11383
11384 /* Does VRDP server call Console from the other thread?
11385 * Not sure (and can change), so release the lock just in case.
11386 */
11387 alock.release();
11388 vrc = server->Launch();
11389 alock.acquire();
11390
11391 if (vrc != VINF_SUCCESS)
11392 {
11393 Utf8Str errMsg = pConsole->VRDPServerErrorToMsg(vrc);
11394 if ( RT_FAILURE(vrc)
11395 && vrc != VERR_NET_ADDRESS_IN_USE) /* not fatal */
11396 throw i_setErrorStaticBoth(E_FAIL, vrc, errMsg.c_str());
11397 }
11398
11399 ComPtr<IMachine> pMachine = pConsole->i_machine();
11400 ULONG cCpus = 1;
11401 pMachine->COMGETTER(CPUCount)(&cCpus);
11402
11403 VMProcPriority_T enmVMPriority = VMProcPriority_Default;
11404 pMachine->COMGETTER(VMProcessPriority)(&enmVMPriority);
11405
11406 VMExecutionEngine_T enmExecEngine = VMExecutionEngine_NotSet;
11407 pMachine->COMGETTER(VMExecutionEngine)(&enmExecEngine);
11408
11409 /*
11410 * Create the VM
11411 *
11412 * Note! Release the lock since EMT will call Console. It's safe because
11413 * mMachineState is either Starting or Restoring state here.
11414 */
11415 alock.release();
11416
11417 if (enmVMPriority != VMProcPriority_Default)
11418 pConsole->i_onVMProcessPriorityChange(enmVMPriority);
11419
11420 PCVMMR3VTABLE pVMM = pConsole->mpVMM;
11421 PVM pVM = NULL;
11422 vrc = pVMM->pfnVMR3Create(cCpus,
11423 pConsole->mpVmm2UserMethods,
11424 enmExecEngine == VMExecutionEngine_Interpreter
11425 || enmExecEngine == VMExecutionEngine_Recompiler /** @todo NativeApi too? */
11426 ? VMCREATE_F_DRIVERLESS : 0,
11427 Console::i_genericVMSetErrorCallback,
11428 &pTask->mErrorMsg,
11429 pTask->mpfnConfigConstructor,
11430 static_cast<Console *>(pConsole),
11431 &pVM, NULL);
11432 alock.acquire();
11433 if (RT_SUCCESS(vrc))
11434 {
11435 do /* break "loop" */
11436 {
11437 /*
11438 * Register our load/save state file handlers
11439 */
11440 vrc = pVMM->pfnSSMR3RegisterExternal(pConsole->mpUVM, sSSMConsoleUnit, 0 /*iInstance*/,
11441 CONSOLE_SAVED_STATE_VERSION, 0 /* cbGuess */,
11442 NULL, NULL, NULL,
11443 NULL, i_saveStateFileExec, NULL,
11444 NULL, i_loadStateFileExec, NULL,
11445 static_cast<Console *>(pConsole));
11446 AssertRCBreak(vrc);
11447
11448 vrc = static_cast<Console *>(pConsole)->i_getDisplay()->i_registerSSM(pConsole->mpUVM);
11449 AssertRC(vrc);
11450 if (RT_FAILURE(vrc))
11451 break;
11452
11453 /*
11454 * Synchronize debugger settings
11455 */
11456 MachineDebugger *machineDebugger = pConsole->i_getMachineDebugger();
11457 if (machineDebugger)
11458 machineDebugger->i_flushQueuedSettings();
11459
11460 /*
11461 * Set domain name and DNS search list for DrvNAT
11462 */
11463 pConsole->i_onNATDnsChanged();
11464
11465 /*
11466 * Shared Folders
11467 */
11468 if (pConsole->m_pVMMDev->isShFlActive())
11469 {
11470 /* Does the code below call Console from the other thread?
11471 * Not sure, so release the lock just in case. */
11472 alock.release();
11473
11474 for (SharedFolderDataMap::const_iterator it = pTask->mSharedFolders.begin();
11475 it != pTask->mSharedFolders.end();
11476 ++it)
11477 {
11478 const SharedFolderData &d = it->second;
11479 hrc = pConsole->i_createSharedFolder(it->first, d);
11480 if (FAILED(hrc))
11481 {
11482 ErrorInfoKeeper eik;
11483 pConsole->i_atVMRuntimeErrorCallbackF(0, "BrokenSharedFolder",
11484 N_("The shared folder '%s' could not be set up: %ls.\n"
11485 "The shared folder setup will not be complete. It is recommended to power down the virtual "
11486 "machine and fix the shared folder settings while the machine is not running"),
11487 it->first.c_str(), eik.getText().raw());
11488 }
11489 }
11490 if (FAILED(hrc))
11491 hrc = S_OK; // do not fail with broken shared folders
11492
11493 /* acquire the lock again */
11494 alock.acquire();
11495 }
11496
11497#ifdef VBOX_WITH_AUDIO_VRDE
11498 /*
11499 * Attach the VRDE audio driver.
11500 */
11501 if (pConsole->i_getVRDEServer())
11502 {
11503 BOOL fVRDEEnabled = FALSE;
11504 hrc = pConsole->i_getVRDEServer()->COMGETTER(Enabled)(&fVRDEEnabled);
11505 AssertComRCBreak(hrc, RT_NOTHING);
11506
11507 if ( fVRDEEnabled
11508 && pConsole->mAudioVRDE)
11509 pConsole->mAudioVRDE->doAttachDriverViaEmt(pConsole->mpUVM, pVMM, &alock);
11510 }
11511#endif
11512
11513 /*
11514 * Enable client connections to the VRDP server.
11515 */
11516 pConsole->i_consoleVRDPServer()->EnableConnections();
11517
11518 /* Release the lock before a lengthy operation. */
11519 alock.release();
11520
11521#ifdef VBOX_WITH_RECORDING
11522 /*
11523 * Start recording if configured.
11524 */
11525 ComPtr<IRecordingSettings> pRecordingSettings;
11526 hrc = pConsole->mMachine->COMGETTER(RecordingSettings)(pRecordingSettings.asOutParam());
11527 AssertComRCBreak(hrc, RT_NOTHING);
11528
11529 BOOL fRecordingEnabled = FALSE;
11530 hrc = pRecordingSettings->COMGETTER(Enabled)(&fRecordingEnabled);
11531 AssertComRCBreak(hrc, RT_NOTHING);
11532
11533 if (fRecordingEnabled)
11534 {
11535 ComPtr<IProgress> pProgress;
11536 hrc = pRecordingSettings->Start(pProgress.asOutParam());
11537 if (FAILED(hrc))
11538 {
11539 com::ErrorInfoKeeper eik;
11540 ComPtr<IVirtualBoxErrorInfo> pErrorInfo = eik.takeError();
11541 Bstr strMsg;
11542 hrc = pErrorInfo->COMGETTER(Text)(strMsg.asOutParam());
11543 AssertComRCBreak(hrc, RT_NOTHING);
11544 LONG lRc;
11545 hrc = pErrorInfo->COMGETTER(ResultCode)(&lRc);
11546 AssertComRCBreak(hrc, RT_NOTHING);
11547
11548 LogRel(("Recording: Failed to start on VM power up: %ls (%Rrc)\n",
11549 strMsg.raw(), lRc));
11550 }
11551 }
11552#endif
11553 /*
11554 * Capture USB devices.
11555 */
11556 hrc = pConsole->i_captureUSBDevices(pConsole->mpUVM);
11557 if (FAILED(hrc))
11558 {
11559 alock.acquire();
11560 break;
11561 }
11562
11563 /*
11564 * Load saved state?
11565 */
11566 if (pTask->mSavedStateFile.length())
11567 {
11568 LogFlowFunc(("Restoring saved state from '%s'...\n", pTask->mSavedStateFile.c_str()));
11569
11570#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
11571 SsmStream ssmStream(pConsole, pVMM, pTask->m_pKeyStore, pTask->mKeyId, pTask->mKeyStore);
11572
11573 vrc = ssmStream.open(pTask->mSavedStateFile.c_str());
11574 if (RT_SUCCESS(vrc))
11575 {
11576 PCSSMSTRMOPS pStreamOps;
11577 void *pvStreamOpsUser;
11578
11579 vrc = ssmStream.querySsmStrmOps(&pStreamOps, &pvStreamOpsUser);
11580 if (RT_SUCCESS(vrc))
11581 vrc = pVMM->pfnVMR3LoadFromStream(pConsole->mpUVM,
11582 pStreamOps, pvStreamOpsUser,
11583 Console::i_stateProgressCallback,
11584 static_cast<IProgress *>(pTask->mProgress),
11585 false /*fTeleporting*/);
11586 }
11587#else
11588 vrc = pVMM->pfnVMR3LoadFromFile(pConsole->mpUVM,
11589 pTask->mSavedStateFile.c_str(),
11590 Console::i_stateProgressCallback,
11591 static_cast<IProgress *>(pTask->mProgress));
11592#endif
11593 if (RT_SUCCESS(vrc))
11594 {
11595 if (pTask->mStartPaused)
11596 /* done */
11597 pConsole->i_setMachineState(MachineState_Paused);
11598 else
11599 {
11600 /* Start/Resume the VM execution */
11601#ifdef VBOX_WITH_EXTPACK
11602 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM, pVMM);
11603#endif
11604 if (RT_SUCCESS(vrc))
11605 vrc = pVMM->pfnVMR3Resume(pConsole->mpUVM, VMRESUMEREASON_STATE_RESTORED);
11606 AssertLogRelRC(vrc);
11607 }
11608 }
11609
11610 /* Power off in case we failed loading or resuming the VM */
11611 if (RT_FAILURE(vrc))
11612 {
11613 int vrc2 = pVMM->pfnVMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
11614#ifdef VBOX_WITH_EXTPACK
11615 pConsole->mptrExtPackManager->i_callAllVmPowerOffHooks(pConsole, pVM, pVMM);
11616#endif
11617 }
11618 }
11619 else if (pTask->mTeleporterEnabled)
11620 {
11621 /* -> ConsoleImplTeleporter.cpp */
11622 bool fPowerOffOnFailure;
11623 hrc = pConsole->i_teleporterTrg(pConsole->mpUVM, pConsole->mpVMM, pMachine, &pTask->mErrorMsg,
11624 pTask->mStartPaused, pTask->mProgress, &fPowerOffOnFailure);
11625 if (FAILED(hrc) && fPowerOffOnFailure)
11626 {
11627 ErrorInfoKeeper eik;
11628 int vrc2 = pVMM->pfnVMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
11629#ifdef VBOX_WITH_EXTPACK
11630 pConsole->mptrExtPackManager->i_callAllVmPowerOffHooks(pConsole, pVM, pVMM);
11631#endif
11632 }
11633 }
11634 else if (pTask->mStartPaused)
11635 /* done */
11636 pConsole->i_setMachineState(MachineState_Paused);
11637 else
11638 {
11639 /* Power on the VM (i.e. start executing) */
11640#ifdef VBOX_WITH_EXTPACK
11641 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM, pVMM);
11642#endif
11643 if (RT_SUCCESS(vrc))
11644 vrc = pVMM->pfnVMR3PowerOn(pConsole->mpUVM);
11645 AssertLogRelRC(vrc);
11646 }
11647
11648 /* acquire the lock again */
11649 alock.acquire();
11650 }
11651 while (0);
11652
11653 /* On failure, destroy the VM */
11654 if (FAILED(hrc) || RT_FAILURE(vrc))
11655 {
11656 /* preserve existing error info */
11657 ErrorInfoKeeper eik;
11658
11659 /* powerDown() will call VMR3Destroy() and do all necessary
11660 * cleanup (VRDP, USB devices) */
11661 alock.release();
11662 HRESULT hrc2 = pConsole->i_powerDown();
11663 alock.acquire();
11664 AssertComRC(hrc2);
11665 }
11666 else
11667 {
11668 /*
11669 * Deregister the VMSetError callback. This is necessary as the
11670 * pfnVMAtError() function passed to VMR3Create() is supposed to
11671 * be sticky but our error callback isn't.
11672 */
11673 alock.release();
11674 pVMM->pfnVMR3AtErrorDeregister(pConsole->mpUVM, Console::i_genericVMSetErrorCallback, &pTask->mErrorMsg);
11675 /** @todo register another VMSetError callback? */
11676 alock.acquire();
11677 }
11678 }
11679 else
11680 {
11681 /*
11682 * If VMR3Create() failed it has released the VM memory.
11683 */
11684 if (pConsole->m_pVMMDev)
11685 {
11686 alock.release(); /* just to be on the safe side... */
11687 pConsole->m_pVMMDev->hgcmShutdown(true /*fUvmIsInvalid*/);
11688 alock.acquire();
11689 }
11690 pVMM->pfnVMR3ReleaseUVM(pConsole->mpUVM);
11691 pConsole->mpUVM = NULL;
11692 }
11693
11694 if (SUCCEEDED(hrc) && RT_FAILURE(vrc))
11695 {
11696 /* If VMR3Create() or one of the other calls in this function fail,
11697 * an appropriate error message has been set in pTask->mErrorMsg.
11698 * However since that happens via a callback, the hrc status code in
11699 * this function is not updated.
11700 */
11701 if (!pTask->mErrorMsg.length())
11702 {
11703 /* If the error message is not set but we've got a failure,
11704 * convert the VBox status code into a meaningful error message.
11705 * This becomes unused once all the sources of errors set the
11706 * appropriate error message themselves.
11707 */
11708 AssertMsgFailed(("Missing error message during powerup for status code %Rrc\n", vrc));
11709 pTask->mErrorMsg = Utf8StrFmt(tr("Failed to start VM execution (%Rrc)"), vrc);
11710 }
11711
11712 /* Set the error message as the COM error.
11713 * Progress::notifyComplete() will pick it up later. */
11714 throw i_setErrorStaticBoth(E_FAIL, vrc, pTask->mErrorMsg.c_str());
11715 }
11716 }
11717 catch (HRESULT hrcXcpt) { hrc = hrcXcpt; }
11718
11719 if ( pConsole->mMachineState == MachineState_Starting
11720 || pConsole->mMachineState == MachineState_Restoring
11721 || pConsole->mMachineState == MachineState_TeleportingIn
11722 )
11723 {
11724 /* We are still in the Starting/Restoring state. This means one of:
11725 *
11726 * 1) we failed before VMR3Create() was called;
11727 * 2) VMR3Create() failed.
11728 *
11729 * In both cases, there is no need to call powerDown(), but we still
11730 * need to go back to the PoweredOff/Saved state. Reuse
11731 * vmstateChangeCallback() for that purpose.
11732 */
11733
11734 /* preserve existing error info */
11735 ErrorInfoKeeper eik;
11736
11737 Assert(pConsole->mpUVM == NULL);
11738 i_vmstateChangeCallback(NULL, pConsole->mpVMM, VMSTATE_TERMINATED, VMSTATE_CREATING, pConsole);
11739 }
11740
11741 /*
11742 * Evaluate the final result. Note that the appropriate mMachineState value
11743 * is already set by vmstateChangeCallback() in all cases.
11744 */
11745
11746 /* release the lock, don't need it any more */
11747 alock.release();
11748
11749 if (SUCCEEDED(hrc))
11750 {
11751 /* Notify the progress object of the success */
11752 pTask->mProgress->i_notifyComplete(S_OK);
11753 }
11754 else
11755 {
11756 /* The progress object will fetch the current error info */
11757 pTask->mProgress->i_notifyComplete(hrc);
11758 LogRel(("Power up failed (vrc=%Rrc, hrc=%Rhrc (%#08X))\n", vrc, hrc, hrc));
11759 }
11760
11761 /* Notify VBoxSVC and any waiting openRemoteSession progress object. */
11762 pConsole->mControl->EndPowerUp(hrc);
11763
11764#if defined(RT_OS_WINDOWS)
11765 /* uninitialize COM */
11766 CoUninitialize();
11767#endif
11768
11769 LogFlowFuncLeave();
11770}
11771
11772
11773/**
11774 * Reconfigures a medium attachment (part of taking or deleting an online snapshot).
11775 *
11776 * @param pThis Reference to the console object.
11777 * @param pUVM The VM handle.
11778 * @param pVMM The VMM vtable.
11779 * @param pArgs Argument package.
11780 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
11781 * @return VBox status code.
11782 */
11783/* static */
11784DECLCALLBACK(int) Console::i_reconfigureMediumAttachment(Console *pThis,
11785 PUVM pUVM,
11786 PCVMMR3VTABLE pVMM,
11787 Console::ReconfigureMediumAttachmentArgs const *pArgs,
11788 HRESULT *phrc)
11789{
11790 LogFlowFunc(("pUVM=%p aMediumAtt=%p phrc=%p\n", pUVM, pArgs->aMediumAtt, phrc));
11791
11792 HRESULT hrc;
11793 Bstr bstr;
11794 *phrc = S_OK;
11795#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%Rhrc (%#x)\n", hrc, hrc)); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
11796
11797 /* Ignore attachments other than hard disks, since at the moment they are
11798 * not subject to snapshotting in general. */
11799 DeviceType_T lType;
11800 hrc = pArgs->aMediumAtt->COMGETTER(Type)(&lType); H();
11801 if (lType != DeviceType_HardDisk)
11802 return VINF_SUCCESS;
11803
11804 /* Update the device instance configuration. */
11805 int vrc = pThis->i_configMediumAttachment(pArgs->pcszDevice,
11806 pArgs->uInstance,
11807 pArgs->enmBus,
11808 pArgs->fUseHostIOCache,
11809 pArgs->fBuiltinIOCache,
11810 pArgs->fInsertDiskIntegrityDrv,
11811 pArgs->fSetupMerge,
11812 pArgs->uMergeSource,
11813 pArgs->uMergeTarget,
11814 pArgs->aMediumAtt,
11815 pArgs->aMachineState,
11816 phrc,
11817 true /* fAttachDetach */,
11818 false /* fForceUnmount */,
11819 false /* fHotplug */,
11820 pUVM,
11821 pVMM,
11822 NULL /* paLedDevType */,
11823 NULL /* ppLunL0)*/);
11824 if (RT_FAILURE(vrc))
11825 {
11826 AssertMsgFailed(("vrc=%Rrc\n", vrc));
11827 return vrc;
11828 }
11829
11830#undef H
11831
11832 LogFlowFunc(("Returns success\n"));
11833 return VINF_SUCCESS;
11834}
11835
11836/**
11837 * Thread for powering down the Console.
11838 *
11839 * @param pTask The power down task.
11840 *
11841 * @note Locks the Console object for writing.
11842 */
11843/*static*/
11844void Console::i_powerDownThreadTask(VMPowerDownTask *pTask)
11845{
11846 int vrc = VINF_SUCCESS; /* only used in assertion */
11847 LogFlowFuncEnter();
11848 try
11849 {
11850 if (pTask->isOk() == false)
11851 vrc = VERR_GENERAL_FAILURE;
11852
11853 const ComObjPtr<Console> &that = pTask->mConsole;
11854
11855 /* Note: no need to use AutoCaller to protect Console because VMTask does
11856 * that */
11857
11858 /* wait until the method tat started us returns */
11859 AutoWriteLock thatLock(that COMMA_LOCKVAL_SRC_POS);
11860
11861 /* release VM caller to avoid the powerDown() deadlock */
11862 pTask->releaseVMCaller();
11863
11864 thatLock.release();
11865
11866 that->i_powerDown(pTask->mServerProgress);
11867
11868 /* complete the operation */
11869 that->mControl->EndPoweringDown(S_OK, Bstr().raw());
11870
11871 }
11872 catch (const std::exception &e)
11873 {
11874 AssertMsgFailed(("Exception %s was caught, vrc=%Rrc\n", e.what(), vrc));
11875 NOREF(e); NOREF(vrc);
11876 }
11877
11878 LogFlowFuncLeave();
11879}
11880
11881/**
11882 * @interface_method_impl{VMM2USERMETHODS,pfnSaveState}
11883 */
11884/*static*/ DECLCALLBACK(int)
11885Console::i_vmm2User_SaveState(PCVMM2USERMETHODS pThis, PUVM pUVM)
11886{
11887 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
11888 NOREF(pUVM);
11889
11890 /*
11891 * For now, just call SaveState. We should probably try notify the GUI so
11892 * it can pop up a progress object and stuff. The progress object created
11893 * by the call isn't returned to anyone and thus gets updated without
11894 * anyone noticing it.
11895 */
11896 ComPtr<IProgress> pProgress;
11897 HRESULT hrc = pConsole->mMachine->SaveState(pProgress.asOutParam());
11898 return SUCCEEDED(hrc) ? VINF_SUCCESS : Global::vboxStatusCodeFromCOM(hrc);
11899}
11900
11901/**
11902 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtInit}
11903 */
11904/*static*/ DECLCALLBACK(void)
11905Console::i_vmm2User_NotifyEmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
11906{
11907 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
11908 VirtualBoxBase::initializeComForThread();
11909}
11910
11911/**
11912 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtTerm}
11913 */
11914/*static*/ DECLCALLBACK(void)
11915Console::i_vmm2User_NotifyEmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
11916{
11917 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
11918 VirtualBoxBase::uninitializeComForThread();
11919}
11920
11921/**
11922 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtInit}
11923 */
11924/*static*/ DECLCALLBACK(void)
11925Console::i_vmm2User_NotifyPdmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM)
11926{
11927 NOREF(pThis); NOREF(pUVM);
11928 VirtualBoxBase::initializeComForThread();
11929}
11930
11931/**
11932 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtTerm}
11933 */
11934/*static*/ DECLCALLBACK(void)
11935Console::i_vmm2User_NotifyPdmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM)
11936{
11937 NOREF(pThis); NOREF(pUVM);
11938 VirtualBoxBase::uninitializeComForThread();
11939}
11940
11941/**
11942 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyResetTurnedIntoPowerOff}
11943 */
11944/*static*/ DECLCALLBACK(void)
11945Console::i_vmm2User_NotifyResetTurnedIntoPowerOff(PCVMM2USERMETHODS pThis, PUVM pUVM)
11946{
11947 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
11948 NOREF(pUVM);
11949
11950 pConsole->mfPowerOffCausedByReset = true;
11951}
11952
11953/**
11954 * Internal function to get LED set off of Console instance
11955 *
11956 * @returns pointer to PDMLED object
11957 *
11958 * @param iLedSet Index of LED set to fetch
11959 */
11960PPDMLED volatile *
11961Console::i_getLedSet(uint32_t iLedSet)
11962{
11963 AssertReturn(iLedSet < RT_ELEMENTS(maLedSets), NULL);
11964 return maLedSets[iLedSet].papLeds;
11965}
11966
11967/**
11968 * @interface_method_impl{VMM2USERMETHODS,pfnQueryGenericObject}
11969 */
11970/*static*/ DECLCALLBACK(void *)
11971Console::i_vmm2User_QueryGenericObject(PCVMM2USERMETHODS pThis, PUVM pUVM, PCRTUUID pUuid)
11972{
11973 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
11974 NOREF(pUVM);
11975
11976 /* To simplify comparison we copy the UUID into a com::Guid object. */
11977 com::Guid const UuidCopy(*pUuid);
11978
11979 if (UuidCopy == COM_IIDOF(IConsole))
11980 {
11981 IConsole *pIConsole = static_cast<IConsole *>(pConsole);
11982 return pIConsole;
11983 }
11984
11985 if (UuidCopy == COM_IIDOF(IMachine))
11986 {
11987 IMachine *pIMachine = pConsole->mMachine;
11988 return pIMachine;
11989 }
11990
11991 if (UuidCopy == COM_IIDOF(IKeyboard))
11992 {
11993 IKeyboard *pIKeyboard = pConsole->mKeyboard;
11994 return pIKeyboard;
11995 }
11996
11997 if (UuidCopy == COM_IIDOF(IMouse))
11998 {
11999 IMouse *pIMouse = pConsole->mMouse;
12000 return pIMouse;
12001 }
12002
12003 if (UuidCopy == COM_IIDOF(IDisplay))
12004 {
12005 IDisplay *pIDisplay = pConsole->mDisplay;
12006 return pIDisplay;
12007 }
12008
12009 if (UuidCopy == COM_IIDOF(INvramStore))
12010 {
12011 NvramStore *pNvramStore = static_cast<NvramStore *>(pConsole->mptrNvramStore);
12012 return pNvramStore;
12013 }
12014
12015#ifdef VBOX_WITH_VIRT_ARMV8
12016 if (UuidCopy == COM_IIDOF(IResourceStore))
12017 {
12018 ResourceStore *pResourceStore = static_cast<ResourceStore *>(pConsole->mptrResourceStore);
12019 return pResourceStore;
12020 }
12021#endif
12022
12023 if (UuidCopy == VMMDEV_OID)
12024 return pConsole->m_pVMMDev;
12025
12026 if (UuidCopy == USBCARDREADER_OID)
12027 return pConsole->mUsbCardReader;
12028
12029 if (UuidCopy == COM_IIDOF(ISnapshot))
12030 return ((MYVMM2USERMETHODS *)pThis)->pISnapshot;
12031
12032#ifdef VBOX_WITH_USB
12033 if (UuidCopy == REMOTEUSBIF_OID)
12034 return &pConsole->mRemoteUsbIf;
12035#endif
12036
12037 if (UuidCopy == EMULATEDUSBIF_OID)
12038 return pConsole->mEmulatedUSB->i_getEmulatedUsbIf();
12039
12040 return NULL;
12041}
12042
12043
12044/**
12045 * @interface_method_impl{PDMISECKEY,pfnKeyRetain}
12046 */
12047/*static*/ DECLCALLBACK(int)
12048Console::i_pdmIfSecKey_KeyRetain(PPDMISECKEY pInterface, const char *pszId, const uint8_t **ppbKey, size_t *pcbKey)
12049{
12050 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
12051
12052 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
12053 SecretKey *pKey = NULL;
12054
12055 int vrc = pConsole->m_pKeyStore->retainSecretKey(Utf8Str(pszId), &pKey);
12056 if (RT_SUCCESS(vrc))
12057 {
12058 *ppbKey = (const uint8_t *)pKey->getKeyBuffer();
12059 *pcbKey = pKey->getKeySize();
12060 }
12061
12062 return vrc;
12063}
12064
12065/**
12066 * @interface_method_impl{PDMISECKEY,pfnKeyRelease}
12067 */
12068/*static*/ DECLCALLBACK(int)
12069Console::i_pdmIfSecKey_KeyRelease(PPDMISECKEY pInterface, const char *pszId)
12070{
12071 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
12072
12073 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
12074 return pConsole->m_pKeyStore->releaseSecretKey(Utf8Str(pszId));
12075}
12076
12077/**
12078 * @interface_method_impl{PDMISECKEY,pfnPasswordRetain}
12079 */
12080/*static*/ DECLCALLBACK(int)
12081Console::i_pdmIfSecKey_PasswordRetain(PPDMISECKEY pInterface, const char *pszId, const char **ppszPassword)
12082{
12083 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
12084
12085 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
12086 SecretKey *pKey = NULL;
12087
12088 int vrc = pConsole->m_pKeyStore->retainSecretKey(Utf8Str(pszId), &pKey);
12089 if (RT_SUCCESS(vrc))
12090 *ppszPassword = (const char *)pKey->getKeyBuffer();
12091
12092 return vrc;
12093}
12094
12095/**
12096 * @interface_method_impl{PDMISECKEY,pfnPasswordRelease}
12097 */
12098/*static*/ DECLCALLBACK(int)
12099Console::i_pdmIfSecKey_PasswordRelease(PPDMISECKEY pInterface, const char *pszId)
12100{
12101 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
12102
12103 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
12104 return pConsole->m_pKeyStore->releaseSecretKey(Utf8Str(pszId));
12105}
12106
12107/**
12108 * @interface_method_impl{PDMISECKEYHLP,pfnKeyMissingNotify}
12109 */
12110/*static*/ DECLCALLBACK(int)
12111Console::i_pdmIfSecKeyHlp_KeyMissingNotify(PPDMISECKEYHLP pInterface)
12112{
12113 Console *pConsole = ((MYPDMISECKEYHLP *)pInterface)->pConsole;
12114
12115 /* Set guest property only, the VM is paused in the media driver calling us. */
12116 pConsole->mMachine->DeleteGuestProperty(Bstr("/VirtualBox/HostInfo/DekMissing").raw());
12117 pConsole->mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/DekMissing").raw(),
12118 Bstr("1").raw(), Bstr("RDONLYGUEST").raw());
12119 pConsole->mMachine->SaveSettings();
12120
12121 return VINF_SUCCESS;
12122}
12123
12124
12125
12126/**
12127 * The Main status driver instance data.
12128 */
12129typedef struct DRVMAINSTATUS
12130{
12131 /** The LED connectors. */
12132 PDMILEDCONNECTORS ILedConnectors;
12133 /** Pointer to the LED ports interface above us. */
12134 PPDMILEDPORTS pLedPorts;
12135 /** Pointer to the array of LED pointers. */
12136 PPDMLED volatile *papLeds;
12137 /** The unit number corresponding to the first entry in the LED array. */
12138 uint32_t iFirstLUN;
12139 /** The unit number corresponding to the last entry in the LED array.
12140 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
12141 uint32_t iLastLUN;
12142 /** Pointer to the driver instance. */
12143 PPDMDRVINS pDrvIns;
12144 /** The Media Notify interface. */
12145 PDMIMEDIANOTIFY IMediaNotify;
12146 /** Set if there potentially are medium attachments. */
12147 bool fHasMediumAttachments;
12148 /** Device name+instance for mapping */
12149 char *pszDeviceInstance;
12150 /** Pointer to the Console object, for driver triggered activities. */
12151 Console *pConsole;
12152} DRVMAINSTATUS;
12153/** Pointer the instance data for a Main status driver. */
12154typedef DRVMAINSTATUS *PDRVMAINSTATUS;
12155
12156
12157/**
12158 * Notification about a unit which have been changed.
12159 *
12160 * The driver must discard any pointers to data owned by
12161 * the unit and requery it.
12162 *
12163 * @param pInterface Pointer to the interface structure containing the called function pointer.
12164 * @param iLUN The unit number.
12165 */
12166DECLCALLBACK(void) Console::i_drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
12167{
12168 PDRVMAINSTATUS pThis = RT_FROM_MEMBER(pInterface, DRVMAINSTATUS, ILedConnectors);
12169 if (iLUN >= pThis->iFirstLUN && iLUN <= pThis->iLastLUN)
12170 {
12171 /*
12172 * Query the pointer to the PDMLED field inside the target device
12173 * structure (owned by the virtual hardware device).
12174 */
12175 PPDMLED pLed;
12176 int vrc = pThis->pLedPorts->pfnQueryStatusLed(pThis->pLedPorts, iLUN, &pLed);
12177 if (RT_FAILURE(vrc))
12178 pLed = NULL;
12179
12180 /*
12181 * Update the corresponding papLeds[] entry.
12182 *
12183 * papLeds[] points to the struct PDMLED of each of this driver's
12184 * units. The entries are initialized here, called out of a loop
12185 * in Console::i_drvStatus_Construct(), which previously called
12186 * Console::i_attachStatusDriver() to allocate the array itself.
12187 *
12188 * The arrays (and thus individual LEDs) are eventually read out
12189 * by Console::getDeviceActivity(), which is itself called from
12190 * src/VBox/Frontends/VirtualBox/src/runtime/UIIndicatorsPool.cpp
12191 */
12192 /** @todo acquire Console::mLedLock here in exclusive mode? */
12193 ASMAtomicWritePtr(&pThis->papLeds[iLUN - pThis->iFirstLUN], pLed);
12194 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
12195 }
12196}
12197
12198
12199/**
12200 * Notification about a medium eject.
12201 *
12202 * @returns VBox status code.
12203 * @param pInterface Pointer to the interface structure containing the called function pointer.
12204 * @param uLUN The unit number.
12205 */
12206DECLCALLBACK(int) Console::i_drvStatus_MediumEjected(PPDMIMEDIANOTIFY pInterface, unsigned uLUN)
12207{
12208 PDRVMAINSTATUS pThis = RT_FROM_MEMBER(pInterface, DRVMAINSTATUS, IMediaNotify);
12209 LogFunc(("uLUN=%d\n", uLUN));
12210 if (pThis->fHasMediumAttachments)
12211 {
12212 Console * const pConsole = pThis->pConsole;
12213 AutoWriteLock alock(pConsole COMMA_LOCKVAL_SRC_POS);
12214
12215 ComPtr<IMediumAttachment> pMediumAtt;
12216 Utf8Str devicePath = Utf8StrFmt("%s/LUN#%u", pThis->pszDeviceInstance, uLUN);
12217 Console::MediumAttachmentMap::const_iterator end = pConsole->mapMediumAttachments.end();
12218 Console::MediumAttachmentMap::const_iterator it = pConsole->mapMediumAttachments.find(devicePath);
12219 if (it != end)
12220 pMediumAtt = it->second;
12221 Assert(!pMediumAtt.isNull());
12222 if (!pMediumAtt.isNull())
12223 {
12224 IMedium *pMedium = NULL;
12225 HRESULT hrc = pMediumAtt->COMGETTER(Medium)(&pMedium);
12226 AssertComRC(hrc);
12227 if (SUCCEEDED(hrc) && pMedium)
12228 {
12229 BOOL fHostDrive = FALSE;
12230 hrc = pMedium->COMGETTER(HostDrive)(&fHostDrive);
12231 AssertComRC(hrc);
12232 if (!fHostDrive)
12233 {
12234 alock.release();
12235
12236 ComPtr<IMediumAttachment> pNewMediumAtt;
12237 hrc = pThis->pConsole->mControl->EjectMedium(pMediumAtt, pNewMediumAtt.asOutParam());
12238 if (SUCCEEDED(hrc))
12239 {
12240 pThis->pConsole->mMachine->SaveSettings();
12241 ::FireMediumChangedEvent(pThis->pConsole->mEventSource, pNewMediumAtt);
12242 }
12243
12244 alock.acquire();
12245 if (pNewMediumAtt != pMediumAtt)
12246 {
12247 pConsole->mapMediumAttachments.erase(devicePath);
12248 pConsole->mapMediumAttachments.insert(std::make_pair(devicePath, pNewMediumAtt));
12249 }
12250 }
12251 }
12252 }
12253 }
12254 return VINF_SUCCESS;
12255}
12256
12257
12258/**
12259 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
12260 */
12261DECLCALLBACK(void *) Console::i_drvStatus_QueryInterface(PPDMIBASE pInterface, const char *pszIID)
12262{
12263 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
12264 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
12265 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
12266 PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDCONNECTORS, &pThis->ILedConnectors);
12267 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIANOTIFY, &pThis->IMediaNotify);
12268 return NULL;
12269}
12270
12271
12272/**
12273 * Destruct a status driver instance.
12274 *
12275 * @param pDrvIns The driver instance data.
12276 */
12277DECLCALLBACK(void) Console::i_drvStatus_Destruct(PPDMDRVINS pDrvIns)
12278{
12279 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
12280 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
12281 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
12282
12283 if (pThis->papLeds)
12284 {
12285 unsigned iLed = pThis->iLastLUN - pThis->iFirstLUN + 1;
12286 while (iLed-- > 0)
12287 ASMAtomicWriteNullPtr(&pThis->papLeds[iLed]);
12288 }
12289}
12290
12291
12292/**
12293 * Construct a status driver instance.
12294 *
12295 * @copydoc FNPDMDRVCONSTRUCT
12296 */
12297DECLCALLBACK(int) Console::i_drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
12298{
12299 RT_NOREF(fFlags);
12300 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
12301 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
12302 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
12303
12304 /*
12305 * Initialize data.
12306 */
12307 com::Guid ConsoleUuid(COM_IIDOF(IConsole));
12308 IConsole *pIConsole = (IConsole *)PDMDrvHlpQueryGenericUserObject(pDrvIns, ConsoleUuid.raw());
12309 AssertLogRelReturn(pIConsole, VERR_INTERNAL_ERROR_3);
12310 Console *pConsole = static_cast<Console *>(pIConsole);
12311 AssertLogRelReturn(pConsole, VERR_INTERNAL_ERROR_3);
12312
12313 pDrvIns->IBase.pfnQueryInterface = Console::i_drvStatus_QueryInterface;
12314 pThis->ILedConnectors.pfnUnitChanged = Console::i_drvStatus_UnitChanged;
12315 pThis->IMediaNotify.pfnEjected = Console::i_drvStatus_MediumEjected;
12316 pThis->pDrvIns = pDrvIns;
12317 pThis->pConsole = pConsole;
12318 pThis->fHasMediumAttachments = false;
12319 pThis->papLeds = NULL;
12320 pThis->pszDeviceInstance = NULL;
12321
12322 /*
12323 * Validate configuration.
12324 */
12325 PDMDRV_VALIDATE_CONFIG_RETURN(pDrvIns,
12326 "DeviceInstance|"
12327 "iLedSet|"
12328 "HasMediumAttachments|"
12329 "First|"
12330 "Last",
12331 "");
12332 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
12333 ("Configuration error: Not possible to attach anything to this driver!\n"),
12334 VERR_PDM_DRVINS_NO_ATTACH);
12335
12336 /*
12337 * Read config.
12338 */
12339 PCPDMDRVHLPR3 const pHlp = pDrvIns->pHlpR3;
12340
12341 uint32_t iLedSet;
12342 int vrc = pHlp->pfnCFGMQueryU32(pCfg, "iLedSet", &iLedSet);
12343 AssertLogRelMsgRCReturn(vrc, ("Configuration error: Failed to query the \"iLedSet\" value! vrc=%Rrc\n", vrc), vrc);
12344 pThis->papLeds = pConsole->i_getLedSet(iLedSet);
12345
12346 vrc = pHlp->pfnCFGMQueryBoolDef(pCfg, "HasMediumAttachments", &pThis->fHasMediumAttachments, false);
12347 AssertLogRelMsgRCReturn(vrc, ("Configuration error: Failed to query the \"HasMediumAttachments\" value! vrc=%Rrc\n", vrc), vrc);
12348
12349 if (pThis->fHasMediumAttachments)
12350 {
12351 vrc = pHlp->pfnCFGMQueryStringAlloc(pCfg, "DeviceInstance", &pThis->pszDeviceInstance);
12352 AssertLogRelMsgRCReturn(vrc, ("Configuration error: Failed to query the \"DeviceInstance\" value! vrc=%Rrc\n", vrc), vrc);
12353 }
12354
12355 vrc = pHlp->pfnCFGMQueryU32Def(pCfg, "First", &pThis->iFirstLUN, 0);
12356 AssertLogRelMsgRCReturn(vrc, ("Configuration error: Failed to query the \"First\" value! vrc=%Rrc\n", vrc), vrc);
12357
12358 vrc = pHlp->pfnCFGMQueryU32Def(pCfg, "Last", &pThis->iLastLUN, 0);
12359 AssertLogRelMsgRCReturn(vrc, ("Configuration error: Failed to query the \"Last\" value! vrc=%Rrc\n", vrc), vrc);
12360
12361 AssertLogRelMsgReturn(pThis->iFirstLUN <= pThis->iLastLUN,
12362 ("Configuration error: Invalid unit range %u-%u\n", pThis->iFirstLUN, pThis->iLastLUN),
12363 VERR_INVALID_PARAMETER);
12364
12365 /*
12366 * Get the ILedPorts interface of the above driver/device and
12367 * query the LEDs we want.
12368 */
12369 pThis->pLedPorts = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMILEDPORTS);
12370 AssertMsgReturn(pThis->pLedPorts, ("Configuration error: No led ports interface above!\n"),
12371 VERR_PDM_MISSING_INTERFACE_ABOVE);
12372
12373 for (unsigned i = pThis->iFirstLUN; i <= pThis->iLastLUN; ++i)
12374 Console::i_drvStatus_UnitChanged(&pThis->ILedConnectors, i);
12375
12376 return VINF_SUCCESS;
12377}
12378
12379
12380/**
12381 * Console status driver (LED) registration record.
12382 */
12383const PDMDRVREG Console::DrvStatusReg =
12384{
12385 /* u32Version */
12386 PDM_DRVREG_VERSION,
12387 /* szName */
12388 "MainStatus",
12389 /* szRCMod */
12390 "",
12391 /* szR0Mod */
12392 "",
12393 /* pszDescription */
12394 "Main status driver (Main as in the API).",
12395 /* fFlags */
12396 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
12397 /* fClass. */
12398 PDM_DRVREG_CLASS_STATUS,
12399 /* cMaxInstances */
12400 ~0U,
12401 /* cbInstance */
12402 sizeof(DRVMAINSTATUS),
12403 /* pfnConstruct */
12404 Console::i_drvStatus_Construct,
12405 /* pfnDestruct */
12406 Console::i_drvStatus_Destruct,
12407 /* pfnRelocate */
12408 NULL,
12409 /* pfnIOCtl */
12410 NULL,
12411 /* pfnPowerOn */
12412 NULL,
12413 /* pfnReset */
12414 NULL,
12415 /* pfnSuspend */
12416 NULL,
12417 /* pfnResume */
12418 NULL,
12419 /* pfnAttach */
12420 NULL,
12421 /* pfnDetach */
12422 NULL,
12423 /* pfnPowerOff */
12424 NULL,
12425 /* pfnSoftReset */
12426 NULL,
12427 /* u32EndVersion */
12428 PDM_DRVREG_VERSION
12429};
12430
12431
12432
12433/* vi: set tabstop=4 shiftwidth=4 expandtab: */
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