VirtualBox

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

Last change on this file since 105555 was 105555, checked in by vboxsync, 4 months ago

Main/ConsoleImpl: Set VMCREATE_F_DRIVERLESS when starting VMs configured with VMExecutionEngine_Interpreter or VMExecutionEngine_Recompiler. bugref:10727

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