VirtualBox

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

Last change on this file since 105455 was 105455, checked in by vboxsync, 9 months ago

Main: Special API tweak for ARM host disabling x86-on-arm by default (set global VBoxInternal2/EnableX86OnArm extradata to 1 to enable).

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

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