VirtualBox

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

Last change on this file since 102493 was 102455, checked in by vboxsync, 13 months ago

Main: Removed some more BUGBUG entries and documented empty / non-implemented code areas where needed. bugref:10384

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 414.1 KB
Line 
1/* $Id: ConsoleImpl.cpp 102455 2023-12-04 15:53:11Z 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 mRemoteUsbIf.pvUser = this;
492 mRemoteUsbIf.pfnQueryRemoteUsbBackend = Console::i_usbQueryRemoteUsbBackend;
493
494 return BaseFinalConstruct();
495}
496
497void Console::FinalRelease()
498{
499 LogFlowThisFunc(("\n"));
500
501 uninit();
502
503 BaseFinalRelease();
504}
505
506// public initializer/uninitializer for internal purposes only
507/////////////////////////////////////////////////////////////////////////////
508
509/** @todo r=bird: aLockType is always LockType_VM. */
510HRESULT Console::initWithMachine(IMachine *aMachine, IInternalMachineControl *aControl, LockType_T aLockType)
511{
512 AssertReturn(aMachine && aControl, E_INVALIDARG);
513
514 /* Enclose the state transition NotReady->InInit->Ready */
515 AutoInitSpan autoInitSpan(this);
516 AssertReturn(autoInitSpan.isOk(), E_FAIL);
517
518 LogFlowThisFuncEnter();
519 LogFlowThisFunc(("aMachine=%p, aControl=%p\n", aMachine, aControl));
520
521 unconst(mMachine) = aMachine;
522 unconst(mControl) = aControl;
523
524 /* Cache essential properties and objects, and create child objects */
525
526 HRESULT hrc = mMachine->COMGETTER(State)(&mMachineState);
527 AssertComRCReturnRC(hrc);
528
529 hrc = mMachine->COMGETTER(Id)(mstrUuid.asOutParam());
530 AssertComRCReturnRC(hrc);
531
532#ifdef VBOX_WITH_EXTPACK
533 unconst(mptrExtPackManager).createObject();
534 hrc = mptrExtPackManager->initExtPackManager(NULL, VBOXEXTPACKCTX_VM_PROCESS);
535 AssertComRCReturnRC(hrc);
536#endif
537
538 // Event source may be needed by other children
539 unconst(mEventSource).createObject();
540 hrc = mEventSource->init();
541 AssertComRCReturnRC(hrc);
542
543 mcAudioRefs = 0;
544 mcVRDPClients = 0;
545 mu32SingleRDPClientId = 0;
546 mcGuestCredentialsProvided = false;
547
548 ComPtr<IPlatform> pPlatform;
549 hrc = mMachine->COMGETTER(Platform)(pPlatform.asOutParam());
550 AssertComRCReturnRC(hrc);
551
552 PlatformArchitecture_T platformArch;
553 hrc = pPlatform->COMGETTER(Architecture)(&platformArch);
554 AssertComRCReturnRC(hrc);
555
556 /* Now the VM specific parts */
557 /** @todo r=bird: aLockType is always LockType_VM. */
558 if (aLockType == LockType_VM)
559 {
560 const char *pszVMM = NULL; /* Shut up MSVC. */
561
562 switch (platformArch)
563 {
564 case PlatformArchitecture_x86:
565 pszVMM = "VBoxVMM";
566 break;
567#ifdef VBOX_WITH_VIRT_ARMV8
568 case PlatformArchitecture_ARM:
569 pszVMM = "VBoxVMMArm";
570 break;
571#endif
572 default:
573 hrc = VBOX_E_PLATFORM_ARCH_NOT_SUPPORTED;
574 break;
575 }
576
577 if (FAILED(hrc))
578 return hrc;
579
580 /* Load the VMM. We won't continue without it being successfully loaded here. */
581 hrc = i_loadVMM(pszVMM);
582 AssertComRCReturnRC(hrc);
583
584#ifdef VBOX_WITH_VIRT_ARMV8
585 unconst(mptrResourceStore).createObject();
586 hrc = mptrResourceStore->init(this);
587 AssertComRCReturnRC(hrc);
588#endif
589 hrc = mMachine->COMGETTER(VRDEServer)(unconst(mVRDEServer).asOutParam());
590 AssertComRCReturnRC(hrc);
591
592 unconst(mGuest).createObject();
593 hrc = mGuest->init(this);
594 AssertComRCReturnRC(hrc);
595
596 ULONG cCpus = 1;
597 hrc = mMachine->COMGETTER(CPUCount)(&cCpus);
598 mGuest->i_setCpuCount(cCpus);
599
600 unconst(mKeyboard).createObject();
601 hrc = mKeyboard->init(this);
602 AssertComRCReturnRC(hrc);
603
604 unconst(mMouse).createObject();
605 hrc = mMouse->init(this);
606 AssertComRCReturnRC(hrc);
607
608 unconst(mDisplay).createObject();
609 hrc = mDisplay->init(this);
610 AssertComRCReturnRC(hrc);
611
612 unconst(mVRDEServerInfo).createObject();
613 hrc = mVRDEServerInfo->init(this);
614 AssertComRCReturnRC(hrc);
615
616 unconst(mEmulatedUSB).createObject();
617 hrc = mEmulatedUSB->init(this);
618 AssertComRCReturnRC(hrc);
619
620 /* Init the NVRAM store. */
621 ComPtr<INvramStore> pNvramStore;
622 hrc = aMachine->COMGETTER(NonVolatileStore)(pNvramStore.asOutParam());
623 AssertComRCReturnRC(hrc);
624
625 Bstr strNonVolatilePath;
626 pNvramStore->COMGETTER(NonVolatileStorageFile)(strNonVolatilePath.asOutParam());
627
628 unconst(mptrNvramStore).createObject();
629 hrc = mptrNvramStore->init(this, strNonVolatilePath);
630 AssertComRCReturnRC(hrc);
631
632#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
633 Bstr bstrNvramKeyId;
634 Bstr bstrNvramKeyStore;
635 hrc = pNvramStore->COMGETTER(KeyId)(bstrNvramKeyId.asOutParam());
636 AssertComRCReturnRC(hrc);
637 hrc = pNvramStore->COMGETTER(KeyStore)(bstrNvramKeyStore.asOutParam());
638 AssertComRCReturnRC(hrc);
639 const Utf8Str strNvramKeyId(bstrNvramKeyId);
640 const Utf8Str strNvramKeyStore(bstrNvramKeyStore);
641 mptrNvramStore->i_updateEncryptionSettings(strNvramKeyId, strNvramKeyStore);
642#endif
643
644 /* Grab global and machine shared folder lists */
645
646 hrc = i_fetchSharedFolders(true /* aGlobal */);
647 AssertComRCReturnRC(hrc);
648 hrc = i_fetchSharedFolders(false /* aGlobal */);
649 AssertComRCReturnRC(hrc);
650
651 /* Create other child objects */
652
653 unconst(mConsoleVRDPServer) = new ConsoleVRDPServer(this);
654 AssertReturn(mConsoleVRDPServer, E_FAIL);
655
656 /* Figure out size of meAttachmentType vector */
657 ComPtr<IVirtualBox> pVirtualBox;
658 hrc = aMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
659 AssertComRC(hrc);
660
661 ComPtr<ISystemProperties> pSystemProperties;
662 ComPtr<IPlatformProperties> pPlatformProperties;
663 if (pVirtualBox)
664 {
665 hrc = pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
666 AssertComRC(hrc);
667 hrc = pVirtualBox->GetPlatformProperties(platformArch, pPlatformProperties.asOutParam());
668 AssertComRC(hrc);
669 }
670
671 ChipsetType_T chipsetType = ChipsetType_PIIX3;
672 pPlatform->COMGETTER(ChipsetType)(&chipsetType);
673 ULONG maxNetworkAdapters = 0;
674 if (pPlatformProperties)
675 pPlatformProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters);
676 meAttachmentType.resize(maxNetworkAdapters);
677 for (ULONG slot = 0; slot < maxNetworkAdapters; ++slot)
678 meAttachmentType[slot] = NetworkAttachmentType_Null;
679
680#ifdef VBOX_WITH_AUDIO_VRDE
681 unconst(mAudioVRDE) = new AudioVRDE(this);
682 AssertReturn(mAudioVRDE, E_FAIL);
683#endif
684#ifdef VBOX_WITH_AUDIO_RECORDING
685 unconst(mRecording.mAudioRec) = new AudioVideoRec(this);
686 AssertReturn(mRecording.mAudioRec, E_FAIL);
687#endif
688
689#ifdef VBOX_WITH_USB_CARDREADER
690 unconst(mUsbCardReader) = new UsbCardReader(this);
691 AssertReturn(mUsbCardReader, E_FAIL);
692#endif
693
694 m_cDisksPwProvided = 0;
695 m_cDisksEncrypted = 0;
696
697 unconst(m_pKeyStore) = new SecretKeyStore(true /* fKeyBufNonPageable */);
698 AssertReturn(m_pKeyStore, E_FAIL);
699
700 /* VirtualBox events registration. */
701 {
702 ComPtr<IEventSource> pES;
703 hrc = pVirtualBox->COMGETTER(EventSource)(pES.asOutParam());
704 AssertComRC(hrc);
705 ComObjPtr<VmEventListenerImpl> aVmListener;
706 aVmListener.createObject();
707 aVmListener->init(new VmEventListener(), this);
708 mVmListener = aVmListener;
709 com::SafeArray<VBoxEventType_T> eventTypes;
710 eventTypes.push_back(VBoxEventType_OnNATRedirect);
711 eventTypes.push_back(VBoxEventType_OnHostNameResolutionConfigurationChange);
712 eventTypes.push_back(VBoxEventType_OnHostPCIDevicePlug);
713 eventTypes.push_back(VBoxEventType_OnExtraDataChanged);
714 hrc = pES->RegisterListener(aVmListener, ComSafeArrayAsInParam(eventTypes), true);
715 AssertComRC(hrc);
716 }
717 }
718
719 /* Confirm a successful initialization when it's the case */
720 autoInitSpan.setSucceeded();
721
722#ifdef VBOX_WITH_EXTPACK
723 /* Let the extension packs have a go at things (hold no locks). */
724 if (SUCCEEDED(hrc))
725 mptrExtPackManager->i_callAllConsoleReadyHooks(this);
726#endif
727
728 LogFlowThisFuncLeave();
729
730 return S_OK;
731}
732
733/**
734 * Uninitializes the Console object.
735 */
736void Console::uninit()
737{
738 LogFlowThisFuncEnter();
739
740 /* Enclose the state transition Ready->InUninit->NotReady */
741 AutoUninitSpan autoUninitSpan(this);
742 if (autoUninitSpan.uninitDone())
743 {
744 LogFlowThisFunc(("Already uninitialized.\n"));
745 LogFlowThisFuncLeave();
746 return;
747 }
748
749 LogFlowThisFunc(("initFailed()=%d\n", autoUninitSpan.initFailed()));
750 if (mVmListener)
751 {
752 ComPtr<IEventSource> pES;
753 ComPtr<IVirtualBox> pVirtualBox;
754 HRESULT hrc = mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
755 AssertComRC(hrc);
756 if (SUCCEEDED(hrc) && !pVirtualBox.isNull())
757 {
758 hrc = pVirtualBox->COMGETTER(EventSource)(pES.asOutParam());
759 AssertComRC(hrc);
760 if (!pES.isNull())
761 {
762 hrc = pES->UnregisterListener(mVmListener);
763 AssertComRC(hrc);
764 }
765 }
766 mVmListener.setNull();
767 }
768
769 /* power down the VM if necessary */
770 if (mpUVM)
771 {
772 i_powerDown();
773 Assert(mpUVM == NULL);
774 }
775
776 if (mVMZeroCallersSem != NIL_RTSEMEVENT)
777 {
778 RTSemEventDestroy(mVMZeroCallersSem);
779 mVMZeroCallersSem = NIL_RTSEMEVENT;
780 }
781
782 if (mpVmm2UserMethods)
783 {
784 RTMemFree((void *)mpVmm2UserMethods);
785 mpVmm2UserMethods = NULL;
786 }
787
788 if (mpIfSecKey)
789 {
790 RTMemFree((void *)mpIfSecKey);
791 mpIfSecKey = NULL;
792 }
793
794 if (mpIfSecKeyHlp)
795 {
796 RTMemFree((void *)mpIfSecKeyHlp);
797 mpIfSecKeyHlp = NULL;
798 }
799
800#ifdef VBOX_WITH_USB_CARDREADER
801 if (mUsbCardReader)
802 {
803 delete mUsbCardReader;
804 unconst(mUsbCardReader) = NULL;
805 }
806#endif
807
808#ifdef VBOX_WITH_AUDIO_VRDE
809 if (mAudioVRDE)
810 {
811 delete mAudioVRDE;
812 unconst(mAudioVRDE) = NULL;
813 }
814#endif
815
816#ifdef VBOX_WITH_RECORDING
817 i_recordingDestroy();
818# ifdef VBOX_WITH_AUDIO_RECORDING
819 if (mRecording.mAudioRec)
820 {
821 delete mRecording.mAudioRec;
822 unconst(mRecording.mAudioRec) = NULL;
823 }
824# endif
825#endif /* VBOX_WITH_RECORDING */
826
827 // if the VM had a VMMDev with an HGCM thread, then remove that here
828 if (m_pVMMDev)
829 {
830 delete m_pVMMDev;
831 unconst(m_pVMMDev) = NULL;
832 }
833
834 if (mBusMgr)
835 {
836 mBusMgr->Release();
837 mBusMgr = NULL;
838 }
839
840 if (m_pKeyStore)
841 {
842 delete m_pKeyStore;
843 unconst(m_pKeyStore) = NULL;
844 }
845
846 m_mapGlobalSharedFolders.clear();
847 m_mapMachineSharedFolders.clear();
848 m_mapSharedFolders.clear(); // console instances
849
850 mRemoteUSBDevices.clear();
851 mUSBDevices.clear();
852
853 if (mVRDEServerInfo)
854 {
855 mVRDEServerInfo->uninit();
856 unconst(mVRDEServerInfo).setNull();
857 }
858
859 if (mEmulatedUSB)
860 {
861 mEmulatedUSB->uninit();
862 unconst(mEmulatedUSB).setNull();
863 }
864
865 if (mDebugger)
866 {
867 mDebugger->uninit();
868 unconst(mDebugger).setNull();
869 }
870
871 if (mDisplay)
872 {
873 mDisplay->uninit();
874 unconst(mDisplay).setNull();
875 }
876
877 if (mMouse)
878 {
879 mMouse->uninit();
880 unconst(mMouse).setNull();
881 }
882
883 if (mKeyboard)
884 {
885 mKeyboard->uninit();
886 unconst(mKeyboard).setNull();
887 }
888
889 if (mGuest)
890 {
891 mGuest->uninit();
892 unconst(mGuest).setNull();
893 }
894
895 if (mConsoleVRDPServer)
896 {
897 delete mConsoleVRDPServer;
898 unconst(mConsoleVRDPServer) = NULL;
899 }
900
901 if (mptrNvramStore)
902 {
903 mptrNvramStore->uninit();
904 unconst(mptrNvramStore).setNull();
905 }
906
907 unconst(mVRDEServer).setNull();
908
909#ifdef VBOX_WITH_VIRT_ARMV8
910 if (mptrResourceStore)
911 {
912 mptrResourceStore->uninit();
913 unconst(mptrResourceStore).setNull();
914 }
915#endif
916
917 unconst(mControl).setNull();
918 unconst(mMachine).setNull();
919
920 // we don't perform uninit() as it's possible that some pending event refers to this source
921 unconst(mEventSource).setNull();
922
923#ifdef VBOX_WITH_EXTPACK
924 unconst(mptrExtPackManager).setNull();
925#endif
926
927 /* Unload the VMM. */
928 mpVMM = NULL;
929 if (mhModVMM != NIL_RTLDRMOD)
930 {
931 RTLdrClose(mhModVMM);
932 mhModVMM = NIL_RTLDRMOD;
933 }
934
935 /* Release memory held by the LED sets (no need to take lock). */
936 for (size_t idxType = 0; idxType < RT_ELEMENTS(maLedTypes); idxType++)
937 {
938 maLedTypes[idxType].cLeds = 0;
939 maLedTypes[idxType].cAllocated = 0;
940 RTMemFree(maLedTypes[idxType].pappLeds);
941 maLedTypes[idxType].pappLeds = NULL;
942 }
943 for (size_t idxSet = 0; idxSet < mcLedSets; idxSet++)
944 {
945 maLedSets[idxSet].cLeds = 0;
946 RTMemFree((void *)maLedSets[idxSet].papLeds);
947 maLedSets[idxSet].papLeds = NULL;
948 maLedSets[idxSet].paSubTypes = NULL;
949 }
950 mcLedSets = 0;
951
952#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
953 /* Close the release log before unloading the cryptographic module. */
954 if (m_fEncryptedLog)
955 {
956 PRTLOGGER pLogEnc = RTLogRelSetDefaultInstance(NULL);
957 int vrc = RTLogDestroy(pLogEnc);
958 AssertRC(vrc);
959 }
960#endif
961
962 HRESULT hrc = i_unloadCryptoIfModule();
963 AssertComRC(hrc);
964
965 LogFlowThisFuncLeave();
966}
967
968#ifdef VBOX_WITH_GUEST_PROPS
969
970/**
971 * Wrapper for VMMDev::i_guestPropertiesHandleVMReset
972 */
973HRESULT Console::i_pullGuestProperties(ComSafeArrayOut(BSTR, names), ComSafeArrayOut(BSTR, values),
974 ComSafeArrayOut(LONG64, timestamps), ComSafeArrayOut(BSTR, flags))
975{
976 AssertReturn(mControl.isNotNull(), VERR_INVALID_POINTER);
977 return mControl->PullGuestProperties(ComSafeArrayOutArg(names), ComSafeArrayOutArg(values),
978 ComSafeArrayOutArg(timestamps), ComSafeArrayOutArg(flags));
979}
980
981/**
982 * Handles guest properties on a VM reset.
983 *
984 * We must delete properties that are flagged TRANSRESET.
985 *
986 * @todo r=bird: Would be more efficient if we added a request to the HGCM
987 * service to do this instead of detouring thru VBoxSVC.
988 * (IMachine::SetGuestProperty ends up in VBoxSVC, which in turns calls
989 * back into the VM process and the HGCM service.)
990 */
991void Console::i_guestPropertiesHandleVMReset(void)
992{
993 std::vector<Utf8Str> names;
994 std::vector<Utf8Str> values;
995 std::vector<LONG64> timestamps;
996 std::vector<Utf8Str> flags;
997 HRESULT hrc = i_enumerateGuestProperties("*", names, values, timestamps, flags);
998 if (SUCCEEDED(hrc))
999 {
1000 for (size_t i = 0; i < flags.size(); i++)
1001 {
1002 /* Delete all properties which have the flag "TRANSRESET". */
1003 if (flags[i].contains("TRANSRESET", Utf8Str::CaseInsensitive))
1004 {
1005 hrc = mMachine->DeleteGuestProperty(Bstr(names[i]).raw());
1006 if (FAILED(hrc))
1007 LogRel(("RESET: Could not delete transient property \"%s\", hrc=%Rhrc\n",
1008 names[i].c_str(), hrc));
1009 }
1010 }
1011 }
1012 else
1013 LogRel(("RESET: Unable to enumerate guest properties, hrc=%Rhrc\n", hrc));
1014}
1015
1016bool Console::i_guestPropertiesVRDPEnabled(void)
1017{
1018 Bstr value;
1019 HRESULT hrc = mMachine->GetExtraData(Bstr("VBoxInternal2/EnableGuestPropertiesVRDP").raw(),
1020 value.asOutParam());
1021 if ( hrc == S_OK
1022 && value == "1")
1023 return true;
1024 return false;
1025}
1026
1027void Console::i_guestPropertiesVRDPUpdateLogon(uint32_t u32ClientId, const char *pszUser, const char *pszDomain)
1028{
1029 if (!i_guestPropertiesVRDPEnabled())
1030 return;
1031
1032 LogFlowFunc(("\n"));
1033
1034 char szPropNm[256];
1035 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
1036
1037 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Name", u32ClientId);
1038 Bstr clientName;
1039 mVRDEServerInfo->COMGETTER(ClientName)(clientName.asOutParam());
1040
1041 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
1042 clientName.raw(),
1043 bstrReadOnlyGuest.raw());
1044
1045 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/User", u32ClientId);
1046 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
1047 Bstr(pszUser).raw(),
1048 bstrReadOnlyGuest.raw());
1049
1050 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Domain", u32ClientId);
1051 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
1052 Bstr(pszDomain).raw(),
1053 bstrReadOnlyGuest.raw());
1054
1055 char szClientId[64];
1056 RTStrPrintf(szClientId, sizeof(szClientId), "%u", u32ClientId);
1057 mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VRDP/LastConnectedClient").raw(),
1058 Bstr(szClientId).raw(),
1059 bstrReadOnlyGuest.raw());
1060
1061 return;
1062}
1063
1064void Console::i_guestPropertiesVRDPUpdateActiveClient(uint32_t u32ClientId)
1065{
1066 if (!i_guestPropertiesVRDPEnabled())
1067 return;
1068
1069 LogFlowFunc(("%d\n", u32ClientId));
1070
1071 Bstr bstrFlags(L"RDONLYGUEST,TRANSIENT");
1072
1073 char szClientId[64];
1074 RTStrPrintf(szClientId, sizeof(szClientId), "%u", u32ClientId);
1075
1076 mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VRDP/ActiveClient").raw(),
1077 Bstr(szClientId).raw(),
1078 bstrFlags.raw());
1079
1080 return;
1081}
1082
1083void Console::i_guestPropertiesVRDPUpdateNameChange(uint32_t u32ClientId, const char *pszName)
1084{
1085 if (!i_guestPropertiesVRDPEnabled())
1086 return;
1087
1088 LogFlowFunc(("\n"));
1089
1090 char szPropNm[256];
1091 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
1092
1093 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Name", u32ClientId);
1094 Bstr clientName(pszName);
1095
1096 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
1097 clientName.raw(),
1098 bstrReadOnlyGuest.raw());
1099
1100}
1101
1102void Console::i_guestPropertiesVRDPUpdateIPAddrChange(uint32_t u32ClientId, const char *pszIPAddr)
1103{
1104 if (!i_guestPropertiesVRDPEnabled())
1105 return;
1106
1107 LogFlowFunc(("\n"));
1108
1109 char szPropNm[256];
1110 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
1111
1112 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/IPAddr", u32ClientId);
1113 Bstr clientIPAddr(pszIPAddr);
1114
1115 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
1116 clientIPAddr.raw(),
1117 bstrReadOnlyGuest.raw());
1118
1119}
1120
1121void Console::i_guestPropertiesVRDPUpdateLocationChange(uint32_t u32ClientId, const char *pszLocation)
1122{
1123 if (!i_guestPropertiesVRDPEnabled())
1124 return;
1125
1126 LogFlowFunc(("\n"));
1127
1128 char szPropNm[256];
1129 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
1130
1131 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Location", u32ClientId);
1132 Bstr clientLocation(pszLocation);
1133
1134 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
1135 clientLocation.raw(),
1136 bstrReadOnlyGuest.raw());
1137
1138}
1139
1140void Console::i_guestPropertiesVRDPUpdateOtherInfoChange(uint32_t u32ClientId, const char *pszOtherInfo)
1141{
1142 if (!i_guestPropertiesVRDPEnabled())
1143 return;
1144
1145 LogFlowFunc(("\n"));
1146
1147 char szPropNm[256];
1148 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
1149
1150 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/OtherInfo", u32ClientId);
1151 Bstr clientOtherInfo(pszOtherInfo);
1152
1153 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
1154 clientOtherInfo.raw(),
1155 bstrReadOnlyGuest.raw());
1156
1157}
1158
1159void Console::i_guestPropertiesVRDPUpdateClientAttach(uint32_t u32ClientId, bool fAttached)
1160{
1161 if (!i_guestPropertiesVRDPEnabled())
1162 return;
1163
1164 LogFlowFunc(("\n"));
1165
1166 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
1167
1168 char szPropNm[256];
1169 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Attach", u32ClientId);
1170
1171 Bstr bstrValue = fAttached? "1": "0";
1172
1173 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
1174 bstrValue.raw(),
1175 bstrReadOnlyGuest.raw());
1176}
1177
1178void Console::i_guestPropertiesVRDPUpdateDisconnect(uint32_t u32ClientId)
1179{
1180 if (!i_guestPropertiesVRDPEnabled())
1181 return;
1182
1183 LogFlowFunc(("\n"));
1184
1185 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
1186
1187 char szPropNm[256];
1188 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Name", u32ClientId);
1189 mMachine->SetGuestProperty(Bstr(szPropNm).raw(), NULL,
1190 bstrReadOnlyGuest.raw());
1191
1192 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/User", u32ClientId);
1193 mMachine->SetGuestProperty(Bstr(szPropNm).raw(), NULL,
1194 bstrReadOnlyGuest.raw());
1195
1196 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Domain", u32ClientId);
1197 mMachine->SetGuestProperty(Bstr(szPropNm).raw(), NULL,
1198 bstrReadOnlyGuest.raw());
1199
1200 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Attach", u32ClientId);
1201 mMachine->SetGuestProperty(Bstr(szPropNm).raw(), NULL,
1202 bstrReadOnlyGuest.raw());
1203
1204 char szClientId[64];
1205 RTStrPrintf(szClientId, sizeof(szClientId), "%d", u32ClientId);
1206 mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VRDP/LastDisconnectedClient").raw(),
1207 Bstr(szClientId).raw(),
1208 bstrReadOnlyGuest.raw());
1209
1210 return;
1211}
1212
1213#endif /* VBOX_WITH_GUEST_PROPS */
1214
1215#ifdef VBOX_WITH_EXTPACK
1216/**
1217 * Used by VRDEServer and others to talke to the extension pack manager.
1218 *
1219 * @returns The extension pack manager.
1220 */
1221ExtPackManager *Console::i_getExtPackManager()
1222{
1223 return mptrExtPackManager;
1224}
1225#endif
1226
1227
1228int Console::i_VRDPClientLogon(uint32_t u32ClientId, const char *pszUser, const char *pszPassword, const char *pszDomain)
1229{
1230 LogFlowFuncEnter();
1231 LogFlowFunc(("%d, %s, %s, %s\n", u32ClientId, pszUser, pszPassword, pszDomain));
1232
1233 AutoCaller autoCaller(this);
1234 if (!autoCaller.isOk())
1235 {
1236 /* Console has been already uninitialized, deny request */
1237 LogRel(("AUTH: Access denied (Console uninitialized).\n"));
1238 LogFlowFuncLeave();
1239 return VERR_ACCESS_DENIED;
1240 }
1241
1242 Guid uuid = Guid(i_getId());
1243
1244 AuthType_T authType = AuthType_Null;
1245 HRESULT hrc = mVRDEServer->COMGETTER(AuthType)(&authType);
1246 AssertComRCReturn(hrc, VERR_ACCESS_DENIED);
1247
1248 ULONG authTimeout = 0;
1249 hrc = mVRDEServer->COMGETTER(AuthTimeout)(&authTimeout);
1250 AssertComRCReturn(hrc, VERR_ACCESS_DENIED);
1251
1252 AuthResult result = AuthResultAccessDenied;
1253 AuthGuestJudgement guestJudgement = AuthGuestNotAsked;
1254
1255 LogFlowFunc(("Auth type %d\n", authType));
1256
1257 LogRel(("AUTH: User: [%s]. Domain: [%s]. Authentication type: [%s]\n",
1258 pszUser, pszDomain,
1259 authType == AuthType_Null?
1260 "Null":
1261 (authType == AuthType_External?
1262 "External":
1263 (authType == AuthType_Guest?
1264 "Guest":
1265 "INVALID"
1266 )
1267 )
1268 ));
1269
1270 switch (authType)
1271 {
1272 case AuthType_Null:
1273 {
1274 result = AuthResultAccessGranted;
1275 break;
1276 }
1277
1278 case AuthType_External:
1279 {
1280 /* Call the external library. */
1281 result = mConsoleVRDPServer->Authenticate(uuid, guestJudgement, pszUser, pszPassword, pszDomain, u32ClientId);
1282
1283 if (result != AuthResultDelegateToGuest)
1284 {
1285 break;
1286 }
1287
1288 LogRel(("AUTH: Delegated to guest.\n"));
1289
1290 LogFlowFunc(("External auth asked for guest judgement\n"));
1291 }
1292 RT_FALL_THRU();
1293
1294 case AuthType_Guest:
1295 {
1296 guestJudgement = AuthGuestNotReacted;
1297
1298 /** @todo r=dj locking required here for m_pVMMDev? */
1299 PPDMIVMMDEVPORT pDevPort;
1300 if ( m_pVMMDev
1301 && ((pDevPort = m_pVMMDev->getVMMDevPort()))
1302 )
1303 {
1304 /* Issue the request to guest. Assume that the call does not require EMT. It should not. */
1305
1306 /* Ask the guest to judge these credentials. */
1307 uint32_t u32GuestFlags = VMMDEV_SETCREDENTIALS_JUDGE;
1308
1309 int vrc = pDevPort->pfnSetCredentials(pDevPort, pszUser, pszPassword, pszDomain, u32GuestFlags);
1310 if (RT_SUCCESS(vrc))
1311 {
1312 /* Wait for guest. */
1313 vrc = m_pVMMDev->WaitCredentialsJudgement(authTimeout, &u32GuestFlags);
1314 if (RT_SUCCESS(vrc))
1315 {
1316 switch (u32GuestFlags & ( VMMDEV_CREDENTIALS_JUDGE_OK
1317 | VMMDEV_CREDENTIALS_JUDGE_DENY
1318 | VMMDEV_CREDENTIALS_JUDGE_NOJUDGEMENT))
1319 {
1320 case VMMDEV_CREDENTIALS_JUDGE_DENY: guestJudgement = AuthGuestAccessDenied; break;
1321 case VMMDEV_CREDENTIALS_JUDGE_NOJUDGEMENT: guestJudgement = AuthGuestNoJudgement; break;
1322 case VMMDEV_CREDENTIALS_JUDGE_OK: guestJudgement = AuthGuestAccessGranted; break;
1323 default:
1324 LogFlowFunc(("Invalid guest flags %#08x!!!\n", u32GuestFlags));
1325 break;
1326 }
1327 }
1328 else
1329 LogFlowFunc(("Wait for credentials judgement vrc = %Rrc!!!\n", vrc));
1330 LogFlowFunc(("Guest judgement %d\n", guestJudgement));
1331 }
1332 else
1333 LogFlowFunc(("Could not set credentials vrc = %Rrc!!!\n", vrc));
1334 }
1335
1336 if (authType == AuthType_External)
1337 {
1338 LogRel(("AUTH: Guest judgement %d.\n", guestJudgement));
1339 LogFlowFunc(("External auth called again with guest judgement = %d\n", guestJudgement));
1340 result = mConsoleVRDPServer->Authenticate(uuid, guestJudgement, pszUser, pszPassword, pszDomain, u32ClientId);
1341 }
1342 else
1343 {
1344 switch (guestJudgement)
1345 {
1346 case AuthGuestAccessGranted:
1347 result = AuthResultAccessGranted;
1348 break;
1349 default:
1350 result = AuthResultAccessDenied;
1351 break;
1352 }
1353 }
1354 break;
1355 }
1356
1357 default:
1358 AssertFailed();
1359 }
1360
1361 LogFlowFunc(("Result = %d\n", result));
1362 LogFlowFuncLeave();
1363
1364 if (result != AuthResultAccessGranted)
1365 {
1366 /* Reject. */
1367 LogRel(("AUTH: Access denied.\n"));
1368 return VERR_ACCESS_DENIED;
1369 }
1370
1371 LogRel(("AUTH: Access granted.\n"));
1372
1373 /* Multiconnection check must be made after authentication, so bad clients would not interfere with a good one. */
1374 BOOL allowMultiConnection = FALSE;
1375 hrc = mVRDEServer->COMGETTER(AllowMultiConnection)(&allowMultiConnection);
1376 AssertComRCReturn(hrc, VERR_ACCESS_DENIED);
1377
1378 BOOL reuseSingleConnection = FALSE;
1379 hrc = mVRDEServer->COMGETTER(ReuseSingleConnection)(&reuseSingleConnection);
1380 AssertComRCReturn(hrc, VERR_ACCESS_DENIED);
1381
1382 LogFlowFunc(("allowMultiConnection %d, reuseSingleConnection = %d, mcVRDPClients = %d, mu32SingleRDPClientId = %d\n",
1383 allowMultiConnection, reuseSingleConnection, mcVRDPClients, mu32SingleRDPClientId));
1384
1385 if (allowMultiConnection == FALSE)
1386 {
1387 /* Note: the 'mcVRDPClients' variable is incremented in ClientConnect callback, which is called when the client
1388 * is successfully connected, that is after the ClientLogon callback. Therefore the mcVRDPClients
1389 * value is 0 for first client.
1390 */
1391 if (mcVRDPClients != 0)
1392 {
1393 Assert(mcVRDPClients == 1);
1394 /* There is a client already.
1395 * If required drop the existing client connection and let the connecting one in.
1396 */
1397 if (reuseSingleConnection)
1398 {
1399 LogRel(("AUTH: Multiple connections are not enabled. Disconnecting existing client.\n"));
1400 mConsoleVRDPServer->DisconnectClient(mu32SingleRDPClientId, false);
1401 }
1402 else
1403 {
1404 /* Reject. */
1405 LogRel(("AUTH: Multiple connections are not enabled. Access denied.\n"));
1406 return VERR_ACCESS_DENIED;
1407 }
1408 }
1409
1410 /* Save the connected client id. From now on it will be necessary to disconnect this one. */
1411 mu32SingleRDPClientId = u32ClientId;
1412 }
1413
1414#ifdef VBOX_WITH_GUEST_PROPS
1415 i_guestPropertiesVRDPUpdateLogon(u32ClientId, pszUser, pszDomain);
1416#endif /* VBOX_WITH_GUEST_PROPS */
1417
1418 /* Check if the successfully verified credentials are to be sent to the guest. */
1419 BOOL fProvideGuestCredentials = FALSE;
1420
1421 Bstr value;
1422 hrc = mMachine->GetExtraData(Bstr("VRDP/ProvideGuestCredentials").raw(),
1423 value.asOutParam());
1424 if (SUCCEEDED(hrc) && value == "1")
1425 {
1426 /* Provide credentials only if there are no logged in users. */
1427 Utf8Str noLoggedInUsersValue;
1428 LONG64 ul64Timestamp = 0;
1429 Utf8Str flags;
1430
1431 hrc = i_getGuestProperty("/VirtualBox/GuestInfo/OS/NoLoggedInUsers",
1432 &noLoggedInUsersValue, &ul64Timestamp, &flags);
1433
1434 if (SUCCEEDED(hrc) && noLoggedInUsersValue != "false")
1435 {
1436 /* And only if there are no connected clients. */
1437 if (ASMAtomicCmpXchgBool(&mcGuestCredentialsProvided, true, false))
1438 {
1439 fProvideGuestCredentials = TRUE;
1440 }
1441 }
1442 }
1443
1444 /** @todo r=dj locking required here for m_pVMMDev? */
1445 if ( fProvideGuestCredentials
1446 && m_pVMMDev)
1447 {
1448 uint32_t u32GuestFlags = VMMDEV_SETCREDENTIALS_GUESTLOGON;
1449
1450 PPDMIVMMDEVPORT pDevPort = m_pVMMDev->getVMMDevPort();
1451 if (pDevPort)
1452 {
1453 int vrc = pDevPort->pfnSetCredentials(m_pVMMDev->getVMMDevPort(), pszUser, pszPassword, pszDomain, u32GuestFlags);
1454 AssertRC(vrc);
1455 }
1456 }
1457
1458 return VINF_SUCCESS;
1459}
1460
1461void Console::i_VRDPClientStatusChange(uint32_t u32ClientId, const char *pszStatus)
1462{
1463 LogFlowFuncEnter();
1464
1465 AutoCaller autoCaller(this);
1466 AssertComRCReturnVoid(autoCaller.hrc());
1467
1468 LogFlowFunc(("%s\n", pszStatus));
1469
1470#ifdef VBOX_WITH_GUEST_PROPS
1471 /* Parse the status string. */
1472 if (RTStrICmp(pszStatus, "ATTACH") == 0)
1473 {
1474 i_guestPropertiesVRDPUpdateClientAttach(u32ClientId, true);
1475 }
1476 else if (RTStrICmp(pszStatus, "DETACH") == 0)
1477 {
1478 i_guestPropertiesVRDPUpdateClientAttach(u32ClientId, false);
1479 }
1480 else if (RTStrNICmp(pszStatus, "NAME=", strlen("NAME=")) == 0)
1481 {
1482 i_guestPropertiesVRDPUpdateNameChange(u32ClientId, pszStatus + strlen("NAME="));
1483 }
1484 else if (RTStrNICmp(pszStatus, "CIPA=", strlen("CIPA=")) == 0)
1485 {
1486 i_guestPropertiesVRDPUpdateIPAddrChange(u32ClientId, pszStatus + strlen("CIPA="));
1487 }
1488 else if (RTStrNICmp(pszStatus, "CLOCATION=", strlen("CLOCATION=")) == 0)
1489 {
1490 i_guestPropertiesVRDPUpdateLocationChange(u32ClientId, pszStatus + strlen("CLOCATION="));
1491 }
1492 else if (RTStrNICmp(pszStatus, "COINFO=", strlen("COINFO=")) == 0)
1493 {
1494 i_guestPropertiesVRDPUpdateOtherInfoChange(u32ClientId, pszStatus + strlen("COINFO="));
1495 }
1496#endif
1497
1498 LogFlowFuncLeave();
1499}
1500
1501void Console::i_VRDPClientConnect(uint32_t u32ClientId)
1502{
1503 LogFlowFuncEnter();
1504
1505 AutoCaller autoCaller(this);
1506 AssertComRCReturnVoid(autoCaller.hrc());
1507
1508 uint32_t u32Clients = ASMAtomicIncU32(&mcVRDPClients);
1509 VMMDev *pDev;
1510 PPDMIVMMDEVPORT pPort;
1511 if ( (u32Clients == 1)
1512 && ((pDev = i_getVMMDev()))
1513 && ((pPort = pDev->getVMMDevPort()))
1514 )
1515 {
1516 pPort->pfnVRDPChange(pPort,
1517 true,
1518 VRDP_EXPERIENCE_LEVEL_FULL); /** @todo configurable */
1519 }
1520
1521 NOREF(u32ClientId);
1522 mDisplay->i_VRDPConnectionEvent(true);
1523
1524#ifdef VBOX_WITH_GUEST_PROPS
1525 i_guestPropertiesVRDPUpdateActiveClient(u32ClientId);
1526#endif /* VBOX_WITH_GUEST_PROPS */
1527
1528 LogFlowFuncLeave();
1529 return;
1530}
1531
1532void Console::i_VRDPClientDisconnect(uint32_t u32ClientId,
1533 uint32_t fu32Intercepted)
1534{
1535 LogFlowFuncEnter();
1536
1537 AutoCaller autoCaller(this);
1538 AssertComRCReturnVoid(autoCaller.hrc());
1539
1540 AssertReturnVoid(mConsoleVRDPServer);
1541
1542 uint32_t u32Clients = ASMAtomicDecU32(&mcVRDPClients);
1543 VMMDev *pDev;
1544 PPDMIVMMDEVPORT pPort;
1545
1546 if ( (u32Clients == 0)
1547 && ((pDev = i_getVMMDev()))
1548 && ((pPort = pDev->getVMMDevPort()))
1549 )
1550 {
1551 pPort->pfnVRDPChange(pPort,
1552 false,
1553 0);
1554 }
1555
1556 mDisplay->i_VRDPConnectionEvent(false);
1557
1558 if (fu32Intercepted & VRDE_CLIENT_INTERCEPT_USB)
1559 {
1560 mConsoleVRDPServer->USBBackendDelete(u32ClientId);
1561 }
1562
1563 if (fu32Intercepted & VRDE_CLIENT_INTERCEPT_CLIPBOARD)
1564 {
1565 mConsoleVRDPServer->ClipboardDelete(u32ClientId);
1566 }
1567
1568#ifdef VBOX_WITH_AUDIO_VRDE
1569 if (fu32Intercepted & VRDE_CLIENT_INTERCEPT_AUDIO)
1570 {
1571 if (mAudioVRDE)
1572 mAudioVRDE->onVRDEControl(false /* fEnable */, 0 /* uFlags */);
1573 }
1574#endif
1575
1576 AuthType_T authType = AuthType_Null;
1577 HRESULT hrc = mVRDEServer->COMGETTER(AuthType)(&authType);
1578 AssertComRC(hrc);
1579
1580 if (authType == AuthType_External)
1581 mConsoleVRDPServer->AuthDisconnect(i_getId(), u32ClientId);
1582
1583#ifdef VBOX_WITH_GUEST_PROPS
1584 i_guestPropertiesVRDPUpdateDisconnect(u32ClientId);
1585 if (u32Clients == 0)
1586 i_guestPropertiesVRDPUpdateActiveClient(0);
1587#endif /* VBOX_WITH_GUEST_PROPS */
1588
1589 if (u32Clients == 0)
1590 mcGuestCredentialsProvided = false;
1591
1592 LogFlowFuncLeave();
1593 return;
1594}
1595
1596void Console::i_VRDPInterceptAudio(uint32_t u32ClientId)
1597{
1598 RT_NOREF(u32ClientId);
1599 LogFlowFuncEnter();
1600
1601 AutoCaller autoCaller(this);
1602 AssertComRCReturnVoid(autoCaller.hrc());
1603
1604 LogFlowFunc(("u32ClientId=%RU32\n", u32ClientId));
1605
1606#ifdef VBOX_WITH_AUDIO_VRDE
1607 if (mAudioVRDE)
1608 mAudioVRDE->onVRDEControl(true /* fEnable */, 0 /* uFlags */);
1609#endif
1610
1611 LogFlowFuncLeave();
1612 return;
1613}
1614
1615void Console::i_VRDPInterceptUSB(uint32_t u32ClientId, void **ppvIntercept)
1616{
1617 LogFlowFuncEnter();
1618
1619 AutoCaller autoCaller(this);
1620 AssertComRCReturnVoid(autoCaller.hrc());
1621
1622 AssertReturnVoid(mConsoleVRDPServer);
1623
1624 mConsoleVRDPServer->USBBackendCreate(u32ClientId, ppvIntercept);
1625
1626 LogFlowFuncLeave();
1627 return;
1628}
1629
1630void Console::i_VRDPInterceptClipboard(uint32_t u32ClientId)
1631{
1632 LogFlowFuncEnter();
1633
1634 AutoCaller autoCaller(this);
1635 AssertComRCReturnVoid(autoCaller.hrc());
1636
1637 AssertReturnVoid(mConsoleVRDPServer);
1638
1639 mConsoleVRDPServer->ClipboardCreate(u32ClientId);
1640
1641 LogFlowFuncLeave();
1642 return;
1643}
1644
1645
1646//static
1647const char *Console::sSSMConsoleUnit = "ConsoleData";
1648/** The saved state version. */
1649#define CONSOLE_SAVED_STATE_VERSION UINT32_C(0x00010002)
1650/** The saved state version, pre shared folder autoMountPoint. */
1651#define CONSOLE_SAVED_STATE_VERSION_PRE_AUTO_MOUNT_POINT UINT32_C(0x00010001)
1652
1653inline static const char *networkAdapterTypeToName(NetworkAdapterType_T adapterType)
1654{
1655 switch (adapterType)
1656 {
1657 case NetworkAdapterType_Am79C970A:
1658 case NetworkAdapterType_Am79C973:
1659 case NetworkAdapterType_Am79C960:
1660 return "pcnet";
1661#ifdef VBOX_WITH_E1000
1662 case NetworkAdapterType_I82540EM:
1663 case NetworkAdapterType_I82543GC:
1664 case NetworkAdapterType_I82545EM:
1665 return "e1000";
1666#endif
1667#ifdef VBOX_WITH_VIRTIO
1668 case NetworkAdapterType_Virtio:
1669 return "virtio-net";
1670#endif
1671 case NetworkAdapterType_NE1000:
1672 case NetworkAdapterType_NE2000:
1673 case NetworkAdapterType_WD8003:
1674 case NetworkAdapterType_WD8013:
1675 case NetworkAdapterType_ELNK2:
1676 return "dp8390";
1677 case NetworkAdapterType_ELNK1:
1678 return "3c501";
1679 default:
1680 AssertFailed();
1681 return "unknown";
1682 }
1683 /* not reached */
1684}
1685
1686/**
1687 * Loads various console data stored in the saved state file.
1688 *
1689 * This method does validation of the state file and returns an error info
1690 * when appropriate.
1691 *
1692 * The method does nothing if the machine is not in the Saved file or if
1693 * console data from it has already been loaded.
1694 *
1695 * @note The caller must lock this object for writing.
1696 */
1697HRESULT Console::i_loadDataFromSavedState()
1698{
1699 if ( ( mMachineState != MachineState_Saved
1700 && mMachineState != MachineState_AbortedSaved)
1701 || mSavedStateDataLoaded)
1702 return S_OK;
1703
1704 Bstr bstrSavedStateFile;
1705 HRESULT hrc = mMachine->COMGETTER(StateFilePath)(bstrSavedStateFile.asOutParam());
1706 if (SUCCEEDED(hrc))
1707 {
1708 Bstr bstrStateKeyId;
1709 hrc = mMachine->COMGETTER(StateKeyId)(bstrStateKeyId.asOutParam());
1710 if (SUCCEEDED(hrc))
1711 {
1712 Bstr bstrStateKeyStore;
1713 hrc = mMachine->COMGETTER(StateKeyStore)(bstrStateKeyStore.asOutParam());
1714 if (SUCCEEDED(hrc))
1715 {
1716 Utf8Str const strSavedStateFile(bstrSavedStateFile);
1717
1718 PCVMMR3VTABLE pVMM = mpVMM;
1719 AssertPtrReturn(pVMM, E_UNEXPECTED);
1720
1721 PSSMHANDLE pSSM;
1722 SsmStream ssmStream(this, pVMM, m_pKeyStore, bstrStateKeyId, bstrStateKeyStore);
1723
1724 int vrc = ssmStream.open(strSavedStateFile.c_str(), false /*fWrite*/, &pSSM);
1725 if (RT_SUCCESS(vrc))
1726 {
1727 uint32_t uVersion = 0;
1728 vrc = pVMM->pfnSSMR3Seek(pSSM, sSSMConsoleUnit, 0 /* iInstance */, &uVersion);
1729 /** @todo r=bird: This version check is premature, so the logic here is
1730 * buggered as we won't ignore VERR_SSM_UNIT_NOT_FOUND as seems to be
1731 * intended. Sigh. */
1732 if (SSM_VERSION_MAJOR(uVersion) == SSM_VERSION_MAJOR(CONSOLE_SAVED_STATE_VERSION))
1733 {
1734 if (RT_SUCCESS(vrc))
1735 try
1736 {
1737 vrc = i_loadStateFileExecInternal(pSSM, pVMM, uVersion);
1738 }
1739 catch (std::bad_alloc &)
1740 {
1741 vrc = VERR_NO_MEMORY;
1742 }
1743 else if (vrc == VERR_SSM_UNIT_NOT_FOUND)
1744 vrc = VINF_SUCCESS;
1745 }
1746 else
1747 vrc = VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
1748
1749 ssmStream.close();
1750 }
1751
1752 if (RT_FAILURE(vrc))
1753 hrc = setErrorBoth(VBOX_E_FILE_ERROR, vrc,
1754 tr("The saved state file '%s' is invalid (%Rrc). Delete the saved state and try again"),
1755 strSavedStateFile.c_str(), vrc);
1756
1757 mSavedStateDataLoaded = true;
1758 }
1759 }
1760 }
1761
1762 return hrc;
1763}
1764
1765/**
1766 * Callback handler to save various console data to the state file,
1767 * called when the user saves the VM state.
1768 *
1769 * @returns VBox status code.
1770 * @param pSSM SSM handle.
1771 * @param pVMM The VMM ring-3 vtable.
1772 * @param pvUser Pointer to Console
1773 *
1774 * @note Locks the Console object for reading.
1775 */
1776/*static*/ DECLCALLBACK(int)
1777Console::i_saveStateFileExec(PSSMHANDLE pSSM, PCVMMR3VTABLE pVMM, void *pvUser)
1778{
1779 LogFlowFunc(("\n"));
1780
1781 Console *pThat = static_cast<Console *>(pvUser);
1782 AssertReturn(pThat, VERR_INVALID_POINTER);
1783
1784 AutoCaller autoCaller(pThat);
1785 AssertComRCReturn(autoCaller.hrc(), VERR_INVALID_STATE);
1786
1787 AutoReadLock alock(pThat COMMA_LOCKVAL_SRC_POS);
1788
1789 pVMM->pfnSSMR3PutU32(pSSM, (uint32_t)pThat->m_mapSharedFolders.size());
1790
1791 for (SharedFolderMap::const_iterator it = pThat->m_mapSharedFolders.begin();
1792 it != pThat->m_mapSharedFolders.end();
1793 ++it)
1794 {
1795 ConsoleSharedFolder *pSF = (*it).second;
1796 AutoCaller sfCaller(pSF);
1797 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
1798
1799 const Utf8Str &name = pSF->i_getName();
1800 pVMM->pfnSSMR3PutU32(pSSM, (uint32_t)name.length() + 1 /* term. 0 */);
1801 pVMM->pfnSSMR3PutStrZ(pSSM, name.c_str());
1802
1803 const Utf8Str &hostPath = pSF->i_getHostPath();
1804 pVMM->pfnSSMR3PutU32(pSSM, (uint32_t)hostPath.length() + 1 /* term. 0 */);
1805 pVMM->pfnSSMR3PutStrZ(pSSM, hostPath.c_str());
1806
1807 pVMM->pfnSSMR3PutBool(pSSM, !!pSF->i_isWritable());
1808 pVMM->pfnSSMR3PutBool(pSSM, !!pSF->i_isAutoMounted());
1809
1810 const Utf8Str &rStrAutoMountPoint = pSF->i_getAutoMountPoint();
1811 pVMM->pfnSSMR3PutU32(pSSM, (uint32_t)rStrAutoMountPoint.length() + 1 /* term. 0 */);
1812 pVMM->pfnSSMR3PutStrZ(pSSM, rStrAutoMountPoint.c_str());
1813 }
1814
1815 return VINF_SUCCESS;
1816}
1817
1818/**
1819 * Callback handler to load various console data from the state file.
1820 *
1821 * Called when the VM is being restored from the saved state.
1822 *
1823 * @returns VBox status code.
1824 * @param pSSM SSM handle.
1825 * @param pVMM The VMM ring-3 vtable.
1826 * @param pvUser pointer to Console
1827 * @param uVersion Console unit version. Should match sSSMConsoleVer.
1828 * @param uPass The data pass.
1829 */
1830//static
1831DECLCALLBACK(int)
1832Console::i_loadStateFileExec(PSSMHANDLE pSSM, PCVMMR3VTABLE pVMM, void *pvUser, uint32_t uVersion, uint32_t uPass)
1833{
1834 LogFlowFunc(("uVersion=%#x uPass=%#x\n", uVersion, uPass));
1835 Assert(uPass == SSM_PASS_FINAL); RT_NOREF_PV(uPass);
1836
1837 if (SSM_VERSION_MAJOR_CHANGED(uVersion, CONSOLE_SAVED_STATE_VERSION))
1838 return VERR_VERSION_MISMATCH;
1839
1840 Console *pThat = static_cast<Console *>(pvUser);
1841 AssertReturn(pThat, VERR_INVALID_PARAMETER);
1842
1843 /* Currently, nothing to do when we've been called from VMR3Load*. */
1844 return pVMM->pfnSSMR3SkipToEndOfUnit(pSSM);
1845}
1846
1847/**
1848 * Method to load various console data from the state file.
1849 *
1850 * Called from #i_loadDataFromSavedState.
1851 *
1852 * @param pSSM SSM handle.
1853 * @param pVMM The VMM vtable.
1854 * @param u32Version Console unit version.
1855 * Should match sSSMConsoleVer.
1856 *
1857 * @note Locks the Console object for writing.
1858 */
1859int Console::i_loadStateFileExecInternal(PSSMHANDLE pSSM, PCVMMR3VTABLE pVMM, uint32_t u32Version)
1860{
1861 AutoCaller autoCaller(this);
1862 AssertComRCReturn(autoCaller.hrc(), VERR_ACCESS_DENIED);
1863
1864 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1865
1866 AssertReturn(m_mapSharedFolders.empty(), VERR_INTERNAL_ERROR);
1867
1868 uint32_t size = 0;
1869 int vrc = pVMM->pfnSSMR3GetU32(pSSM, &size);
1870 AssertRCReturn(vrc, vrc);
1871
1872 for (uint32_t i = 0; i < size; ++i)
1873 {
1874 Utf8Str strName;
1875 Utf8Str strHostPath;
1876 bool writable = true;
1877 bool autoMount = false;
1878
1879 uint32_t cbStr = 0;
1880 char *buf = NULL;
1881
1882 vrc = pVMM->pfnSSMR3GetU32(pSSM, &cbStr);
1883 AssertRCReturn(vrc, vrc);
1884 buf = new char[cbStr];
1885 vrc = pVMM->pfnSSMR3GetStrZ(pSSM, buf, cbStr);
1886 AssertRC(vrc);
1887 strName = buf;
1888 delete[] buf;
1889
1890 vrc = pVMM->pfnSSMR3GetU32(pSSM, &cbStr);
1891 AssertRCReturn(vrc, vrc);
1892 buf = new char[cbStr];
1893 vrc = pVMM->pfnSSMR3GetStrZ(pSSM, buf, cbStr);
1894 AssertRC(vrc);
1895 strHostPath = buf;
1896 delete[] buf;
1897
1898 if (u32Version >= CONSOLE_SAVED_STATE_VERSION_PRE_AUTO_MOUNT_POINT)
1899 pVMM->pfnSSMR3GetBool(pSSM, &writable);
1900
1901 if ( u32Version >= CONSOLE_SAVED_STATE_VERSION_PRE_AUTO_MOUNT_POINT
1902#ifndef VBOX_OSE /* This broke saved state when introduced in r63916 (4.0). */
1903 && pVMM->pfnSSMR3HandleRevision(pSSM) >= 63916
1904#endif
1905 )
1906 pVMM->pfnSSMR3GetBool(pSSM, &autoMount);
1907
1908 Utf8Str strAutoMountPoint;
1909 if (u32Version >= CONSOLE_SAVED_STATE_VERSION)
1910 {
1911 vrc = pVMM->pfnSSMR3GetU32(pSSM, &cbStr);
1912 AssertRCReturn(vrc, vrc);
1913 vrc = strAutoMountPoint.reserveNoThrow(cbStr);
1914 AssertRCReturn(vrc, vrc);
1915 vrc = pVMM->pfnSSMR3GetStrZ(pSSM, strAutoMountPoint.mutableRaw(), cbStr);
1916 AssertRCReturn(vrc, vrc);
1917 strAutoMountPoint.jolt();
1918 }
1919
1920 ComObjPtr<ConsoleSharedFolder> pSharedFolder;
1921 pSharedFolder.createObject();
1922 HRESULT hrc = pSharedFolder->init(this,
1923 strName,
1924 strHostPath,
1925 writable,
1926 autoMount,
1927 strAutoMountPoint,
1928 false /* fFailOnError */);
1929 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
1930
1931 m_mapSharedFolders.insert(std::make_pair(strName, pSharedFolder));
1932 }
1933
1934 return VINF_SUCCESS;
1935}
1936
1937#ifdef VBOX_WITH_GUEST_PROPS
1938
1939// static
1940DECLCALLBACK(int) Console::i_doGuestPropNotification(void *pvExtension,
1941 uint32_t u32Function,
1942 void *pvParms,
1943 uint32_t cbParms)
1944{
1945 Assert(u32Function == 0); NOREF(u32Function);
1946
1947 /*
1948 * No locking, as this is purely a notification which does not make any
1949 * changes to the object state.
1950 */
1951 PGUESTPROPHOSTCALLBACKDATA pCBData = reinterpret_cast<PGUESTPROPHOSTCALLBACKDATA>(pvParms);
1952 AssertReturn(sizeof(GUESTPROPHOSTCALLBACKDATA) == cbParms, VERR_INVALID_PARAMETER);
1953 AssertReturn(pCBData->u32Magic == GUESTPROPHOSTCALLBACKDATA_MAGIC, VERR_INVALID_PARAMETER);
1954 LogFlow(("Console::doGuestPropNotification: pCBData={.pcszName=%s, .pcszValue=%s, .pcszFlags=%s}\n",
1955 pCBData->pcszName, pCBData->pcszValue, pCBData->pcszFlags));
1956
1957 Bstr name(pCBData->pcszName);
1958 Bstr value(pCBData->pcszValue);
1959 Bstr flags(pCBData->pcszFlags);
1960 BOOL fWasDeleted = !pCBData->pcszValue;
1961 ComObjPtr<Console> pConsole = reinterpret_cast<Console *>(pvExtension);
1962 HRESULT hrc = pConsole->mControl->PushGuestProperty(name.raw(),
1963 value.raw(),
1964 pCBData->u64Timestamp,
1965 flags.raw(),
1966 fWasDeleted);
1967 if (SUCCEEDED(hrc))
1968 {
1969 ::FireGuestPropertyChangedEvent(pConsole->mEventSource, pConsole->i_getId().raw(), name.raw(), value.raw(), flags.raw(),
1970 fWasDeleted);
1971 return VINF_SUCCESS;
1972 }
1973 LogFlow(("Console::doGuestPropNotification: hrc=%Rhrc pCBData={.pcszName=%s, .pcszValue=%s, .pcszFlags=%s}\n",
1974 hrc, pCBData->pcszName, pCBData->pcszValue, pCBData->pcszFlags));
1975 return Global::vboxStatusCodeFromCOM(hrc);
1976}
1977
1978HRESULT Console::i_doEnumerateGuestProperties(const Utf8Str &aPatterns,
1979 std::vector<Utf8Str> &aNames,
1980 std::vector<Utf8Str> &aValues,
1981 std::vector<LONG64> &aTimestamps,
1982 std::vector<Utf8Str> &aFlags)
1983{
1984 AssertReturn(m_pVMMDev, E_FAIL);
1985
1986 VBOXHGCMSVCPARM parm[3];
1987 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
1988 parm[0].u.pointer.addr = (void*)aPatterns.c_str();
1989 parm[0].u.pointer.size = (uint32_t)aPatterns.length() + 1;
1990
1991 /*
1992 * Now things get slightly complicated. Due to a race with the guest adding
1993 * properties, there is no good way to know how much to enlarge a buffer for
1994 * the service to enumerate into. We choose a decent starting size and loop a
1995 * few times, each time retrying with the size suggested by the service plus
1996 * one Kb.
1997 */
1998 size_t cchBuf = 4096;
1999 Utf8Str Utf8Buf;
2000 int vrc = VERR_BUFFER_OVERFLOW;
2001 for (unsigned i = 0; i < 10 && (VERR_BUFFER_OVERFLOW == vrc); ++i)
2002 {
2003 try
2004 {
2005 Utf8Buf.reserve(cchBuf + 1024);
2006 }
2007 catch(...)
2008 {
2009 return E_OUTOFMEMORY;
2010 }
2011
2012 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
2013 parm[1].u.pointer.addr = Utf8Buf.mutableRaw();
2014 parm[1].u.pointer.size = (uint32_t)cchBuf + 1024;
2015
2016 parm[2].type = VBOX_HGCM_SVC_PARM_32BIT;
2017 parm[2].u.uint32 = 0;
2018
2019 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GUEST_PROP_FN_HOST_ENUM_PROPS, 3, &parm[0]);
2020 Utf8Buf.jolt();
2021 if (parm[2].type != VBOX_HGCM_SVC_PARM_32BIT)
2022 return setErrorBoth(E_FAIL, vrc, tr("Internal application error"));
2023 cchBuf = parm[2].u.uint32;
2024 }
2025 if (vrc == VERR_BUFFER_OVERFLOW)
2026 return setError(E_UNEXPECTED, tr("Temporary failure due to guest activity, please retry"));
2027
2028 /*
2029 * Finally we have to unpack the data returned by the service into the safe
2030 * arrays supplied by the caller. We start by counting the number of entries.
2031 */
2032 const char *pszBuf
2033 = reinterpret_cast<const char *>(parm[1].u.pointer.addr);
2034 unsigned cEntries = 0;
2035 /* The list is terminated by a zero-length string at the end of a set
2036 * of four strings. */
2037 for (size_t i = 0; strlen(pszBuf + i) != 0; )
2038 {
2039 /* We are counting sets of four strings. */
2040 for (unsigned j = 0; j < 4; ++j)
2041 i += strlen(pszBuf + i) + 1;
2042 ++cEntries;
2043 }
2044
2045 aNames.resize(cEntries);
2046 aValues.resize(cEntries);
2047 aTimestamps.resize(cEntries);
2048 aFlags.resize(cEntries);
2049
2050 size_t iBuf = 0;
2051 /* Rely on the service to have formated the data correctly. */
2052 for (unsigned i = 0; i < cEntries; ++i)
2053 {
2054 size_t cchName = strlen(pszBuf + iBuf);
2055 aNames[i] = &pszBuf[iBuf];
2056 iBuf += cchName + 1;
2057
2058 size_t cchValue = strlen(pszBuf + iBuf);
2059 aValues[i] = &pszBuf[iBuf];
2060 iBuf += cchValue + 1;
2061
2062 size_t cchTimestamp = strlen(pszBuf + iBuf);
2063 aTimestamps[i] = RTStrToUInt64(&pszBuf[iBuf]);
2064 iBuf += cchTimestamp + 1;
2065
2066 size_t cchFlags = strlen(pszBuf + iBuf);
2067 aFlags[i] = &pszBuf[iBuf];
2068 iBuf += cchFlags + 1;
2069 }
2070
2071 return S_OK;
2072}
2073
2074#endif /* VBOX_WITH_GUEST_PROPS */
2075
2076
2077// IConsole properties
2078/////////////////////////////////////////////////////////////////////////////
2079HRESULT Console::getMachine(ComPtr<IMachine> &aMachine)
2080{
2081 /* mMachine is constant during life time, no need to lock */
2082 mMachine.queryInterfaceTo(aMachine.asOutParam());
2083
2084 /* callers expect to get a valid reference, better fail than crash them */
2085 if (mMachine.isNull())
2086 return E_FAIL;
2087
2088 return S_OK;
2089}
2090
2091HRESULT Console::getState(MachineState_T *aState)
2092{
2093 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2094
2095 /* we return our local state (since it's always the same as on the server) */
2096 *aState = mMachineState;
2097
2098 return S_OK;
2099}
2100
2101HRESULT Console::getGuest(ComPtr<IGuest> &aGuest)
2102{
2103 /* mGuest is constant during life time, no need to lock */
2104 mGuest.queryInterfaceTo(aGuest.asOutParam());
2105
2106 return S_OK;
2107}
2108
2109HRESULT Console::getKeyboard(ComPtr<IKeyboard> &aKeyboard)
2110{
2111 /* mKeyboard is constant during life time, no need to lock */
2112 mKeyboard.queryInterfaceTo(aKeyboard.asOutParam());
2113
2114 return S_OK;
2115}
2116
2117HRESULT Console::getMouse(ComPtr<IMouse> &aMouse)
2118{
2119 /* mMouse is constant during life time, no need to lock */
2120 mMouse.queryInterfaceTo(aMouse.asOutParam());
2121
2122 return S_OK;
2123}
2124
2125HRESULT Console::getDisplay(ComPtr<IDisplay> &aDisplay)
2126{
2127 /* mDisplay is constant during life time, no need to lock */
2128 mDisplay.queryInterfaceTo(aDisplay.asOutParam());
2129
2130 return S_OK;
2131}
2132
2133HRESULT Console::getDebugger(ComPtr<IMachineDebugger> &aDebugger)
2134{
2135 /* we need a write lock because of the lazy mDebugger initialization*/
2136 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2137
2138 /* check if we have to create the debugger object */
2139 if (!mDebugger)
2140 {
2141 unconst(mDebugger).createObject();
2142 mDebugger->init(this);
2143 }
2144
2145 mDebugger.queryInterfaceTo(aDebugger.asOutParam());
2146
2147 return S_OK;
2148}
2149
2150HRESULT Console::getUSBDevices(std::vector<ComPtr<IUSBDevice> > &aUSBDevices)
2151{
2152 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2153
2154 size_t i = 0;
2155 aUSBDevices.resize(mUSBDevices.size());
2156 for (USBDeviceList::const_iterator it = mUSBDevices.begin(); it != mUSBDevices.end(); ++i, ++it)
2157 (*it).queryInterfaceTo(aUSBDevices[i].asOutParam());
2158
2159 return S_OK;
2160}
2161
2162
2163HRESULT Console::getRemoteUSBDevices(std::vector<ComPtr<IHostUSBDevice> > &aRemoteUSBDevices)
2164{
2165 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2166
2167 size_t i = 0;
2168 aRemoteUSBDevices.resize(mRemoteUSBDevices.size());
2169 for (RemoteUSBDeviceList::const_iterator it = mRemoteUSBDevices.begin(); it != mRemoteUSBDevices.end(); ++i, ++it)
2170 (*it).queryInterfaceTo(aRemoteUSBDevices[i].asOutParam());
2171
2172 return S_OK;
2173}
2174
2175HRESULT Console::getVRDEServerInfo(ComPtr<IVRDEServerInfo> &aVRDEServerInfo)
2176{
2177 /* mVRDEServerInfo is constant during life time, no need to lock */
2178 mVRDEServerInfo.queryInterfaceTo(aVRDEServerInfo.asOutParam());
2179
2180 return S_OK;
2181}
2182
2183HRESULT Console::getEmulatedUSB(ComPtr<IEmulatedUSB> &aEmulatedUSB)
2184{
2185 /* mEmulatedUSB is constant during life time, no need to lock */
2186 mEmulatedUSB.queryInterfaceTo(aEmulatedUSB.asOutParam());
2187
2188 return S_OK;
2189}
2190
2191HRESULT Console::getSharedFolders(std::vector<ComPtr<ISharedFolder> > &aSharedFolders)
2192{
2193 /* loadDataFromSavedState() needs a write lock */
2194 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2195
2196 /* Read console data stored in the saved state file (if not yet done) */
2197 HRESULT hrc = i_loadDataFromSavedState();
2198 if (FAILED(hrc))
2199 return hrc;
2200
2201 size_t i = 0;
2202 aSharedFolders.resize(m_mapSharedFolders.size());
2203 for (SharedFolderMap::const_iterator it = m_mapSharedFolders.begin(); it != m_mapSharedFolders.end(); ++i, ++it)
2204 (it)->second.queryInterfaceTo(aSharedFolders[i].asOutParam());
2205
2206 return S_OK;
2207}
2208
2209HRESULT Console::getEventSource(ComPtr<IEventSource> &aEventSource)
2210{
2211 // no need to lock - lifetime constant
2212 mEventSource.queryInterfaceTo(aEventSource.asOutParam());
2213
2214 return S_OK;
2215}
2216
2217HRESULT Console::getAttachedPCIDevices(std::vector<ComPtr<IPCIDeviceAttachment> > &aAttachedPCIDevices)
2218{
2219 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2220
2221 if (mBusMgr)
2222 {
2223 std::vector<BusAssignmentManager::PCIDeviceInfo> devInfos;
2224 mBusMgr->listAttachedPCIDevices(devInfos);
2225 ComObjPtr<PCIDeviceAttachment> dev;
2226 aAttachedPCIDevices.resize(devInfos.size());
2227 for (size_t i = 0; i < devInfos.size(); i++)
2228 {
2229 const BusAssignmentManager::PCIDeviceInfo &devInfo = devInfos[i];
2230 dev.createObject();
2231 dev->init(NULL, devInfo.strDeviceName,
2232 devInfo.hostAddress.valid() ? devInfo.hostAddress.asLong() : -1,
2233 devInfo.guestAddress.asLong(),
2234 devInfo.hostAddress.valid());
2235 dev.queryInterfaceTo(aAttachedPCIDevices[i].asOutParam());
2236 }
2237 }
2238 else
2239 aAttachedPCIDevices.resize(0);
2240
2241 return S_OK;
2242}
2243
2244HRESULT Console::getUseHostClipboard(BOOL *aUseHostClipboard)
2245{
2246 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2247
2248 *aUseHostClipboard = mfUseHostClipboard;
2249
2250 return S_OK;
2251}
2252
2253HRESULT Console::setUseHostClipboard(BOOL aUseHostClipboard)
2254{
2255 if (mfUseHostClipboard != RT_BOOL(aUseHostClipboard))
2256 {
2257 mfUseHostClipboard = RT_BOOL(aUseHostClipboard);
2258 LogRel(("Shared Clipboard: %s using host clipboard\n", mfUseHostClipboard ? "Enabled" : "Disabled"));
2259 }
2260
2261 return S_OK;
2262}
2263
2264// IConsole methods
2265/////////////////////////////////////////////////////////////////////////////
2266
2267HRESULT Console::powerUp(ComPtr<IProgress> &aProgress)
2268{
2269 return i_powerUp(aProgress.asOutParam(), false /* aPaused */);
2270}
2271
2272HRESULT Console::powerUpPaused(ComPtr<IProgress> &aProgress)
2273{
2274 return i_powerUp(aProgress.asOutParam(), true /* aPaused */);
2275}
2276
2277HRESULT Console::powerDown(ComPtr<IProgress> &aProgress)
2278{
2279 LogFlowThisFuncEnter();
2280
2281 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2282
2283 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
2284 switch (mMachineState)
2285 {
2286 case MachineState_Running:
2287 case MachineState_Paused:
2288 case MachineState_Stuck:
2289 break;
2290
2291 /* Try cancel the save state. */
2292 case MachineState_Saving:
2293 if (!mptrCancelableProgress.isNull())
2294 {
2295 HRESULT hrc = mptrCancelableProgress->Cancel();
2296 if (SUCCEEDED(hrc))
2297 break;
2298 }
2299 return setError(VBOX_E_INVALID_VM_STATE, tr("Cannot power down at this point during a save state"));
2300
2301 /* Try cancel the teleportation. */
2302 case MachineState_Teleporting:
2303 case MachineState_TeleportingPausedVM:
2304 if (!mptrCancelableProgress.isNull())
2305 {
2306 HRESULT hrc = mptrCancelableProgress->Cancel();
2307 if (SUCCEEDED(hrc))
2308 break;
2309 }
2310 return setError(VBOX_E_INVALID_VM_STATE, tr("Cannot power down at this point in a teleportation"));
2311
2312 /* Try cancel the online snapshot. */
2313 case MachineState_OnlineSnapshotting:
2314 if (!mptrCancelableProgress.isNull())
2315 {
2316 HRESULT hrc = mptrCancelableProgress->Cancel();
2317 if (SUCCEEDED(hrc))
2318 break;
2319 }
2320 return setError(VBOX_E_INVALID_VM_STATE, tr("Cannot power down at this point in an online snapshot"));
2321
2322 /* Try cancel the live snapshot. */
2323 case MachineState_LiveSnapshotting:
2324 if (!mptrCancelableProgress.isNull())
2325 {
2326 HRESULT hrc = mptrCancelableProgress->Cancel();
2327 if (SUCCEEDED(hrc))
2328 break;
2329 }
2330 return setError(VBOX_E_INVALID_VM_STATE, tr("Cannot power down at this point in a live snapshot"));
2331
2332 /* extra nice error message for a common case */
2333 case MachineState_Saved:
2334 case MachineState_AbortedSaved:
2335 return setError(VBOX_E_INVALID_VM_STATE, tr("Cannot power down a saved virtual machine"));
2336 case MachineState_Stopping:
2337 return setError(VBOX_E_INVALID_VM_STATE, tr("The virtual machine is being powered down"));
2338 default:
2339 return setError(VBOX_E_INVALID_VM_STATE,
2340 tr("Invalid machine state: %s (must be Running, Paused or Stuck)"),
2341 Global::stringifyMachineState(mMachineState));
2342 }
2343 LogFlowThisFunc(("Initiating SHUTDOWN request...\n"));
2344
2345 /* memorize the current machine state */
2346 MachineState_T lastMachineState = mMachineState;
2347
2348#ifdef VBOX_WITH_GUEST_PROPS
2349 if (mfTurnResetIntoPowerOff)
2350 {
2351 alock.release(); /** @todo r=bird: This code introduces a race condition wrt to the state. This must be done elsewhere! */
2352 mMachine->DeleteGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw());
2353 mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw(),
2354 Bstr("PowerOff").raw(), Bstr("RDONLYGUEST").raw());
2355 mMachine->SaveSettings();
2356 alock.acquire();
2357 }
2358#endif
2359
2360 /*
2361 * Request a progress object from the server (this will set the machine state
2362 * to Stopping on the server to block others from accessing this machine).
2363 */
2364 ComPtr<IProgress> ptrProgress;
2365 HRESULT hrc = mControl->BeginPoweringDown(ptrProgress.asOutParam());
2366 if (SUCCEEDED(hrc))
2367 {
2368 /* Sync the state with the server: */
2369 i_setMachineStateLocally(MachineState_Stopping);
2370
2371 /* Create the power down task: */
2372 VMPowerDownTask *pTask = NULL;
2373 try
2374 {
2375 pTask = new VMPowerDownTask(this, ptrProgress);
2376 if (!pTask->isOk())
2377 {
2378 hrc = setError(FAILED(pTask->hrc()) ? pTask->hrc() : E_FAIL, tr("Could not create VMPowerDownTask object\n"));
2379 delete(pTask);
2380 pTask = NULL;
2381 }
2382 }
2383 catch (std::bad_alloc &)
2384 {
2385 hrc = E_OUTOFMEMORY;
2386 }
2387 if (SUCCEEDED(hrc))
2388 {
2389 hrc = pTask->createThread();
2390 if (SUCCEEDED(hrc))
2391 {
2392 ptrProgress.queryInterfaceTo(aProgress.asOutParam());
2393 LogFlowThisFunc(("LEAVE: hrc=%Rhrc\n", hrc));
2394 return hrc;
2395 }
2396 }
2397
2398 /*
2399 * Cancel the requested power down procedure.
2400 * This will reset the machine state to the state it had right
2401 * before calling mControl->BeginPoweringDown().
2402 */
2403 ErrorInfoKeeper eik;
2404 mControl->EndPoweringDown(eik.getResultCode(), eik.getText().raw());
2405 i_setMachineStateLocally(lastMachineState);
2406 }
2407 LogFlowThisFunc(("LEAVE: hrc=%Rhrc\n", hrc));
2408 return hrc;
2409}
2410
2411HRESULT Console::reset()
2412{
2413 LogFlowThisFuncEnter();
2414
2415 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2416
2417 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
2418 if ( mMachineState != MachineState_Running
2419 && mMachineState != MachineState_Teleporting
2420 && mMachineState != MachineState_LiveSnapshotting
2421 /** @todo r=bird: This should be allowed on paused VMs as well. Later. */
2422 )
2423 return i_setInvalidMachineStateError();
2424
2425 /* protect mpUVM */
2426 SafeVMPtr ptrVM(this);
2427 HRESULT hrc = ptrVM.hrc();
2428 if (SUCCEEDED(hrc))
2429 {
2430 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
2431 alock.release();
2432
2433 int vrc = ptrVM.vtable()->pfnVMR3Reset(ptrVM.rawUVM());
2434
2435 hrc = RT_SUCCESS(vrc) ? S_OK : setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not reset the machine (%Rrc)"), vrc);
2436 }
2437
2438 LogFlowThisFunc(("mMachineState=%d, hrc=%Rhrc\n", mMachineState, hrc));
2439 LogFlowThisFuncLeave();
2440 return hrc;
2441}
2442
2443/*static*/ DECLCALLBACK(int) Console::i_unplugCpu(Console *pThis, PUVM pUVM, PCVMMR3VTABLE pVMM, VMCPUID idCpu)
2444{
2445 LogFlowFunc(("pThis=%p pVM=%p idCpu=%u\n", pThis, pUVM, idCpu));
2446
2447 AssertReturn(pThis, VERR_INVALID_PARAMETER);
2448
2449 int vrc = pVMM->pfnPDMR3DeviceDetach(pUVM, "acpi", 0, idCpu, 0);
2450 Log(("UnplugCpu: vrc=%Rrc\n", vrc));
2451
2452 return vrc;
2453}
2454
2455HRESULT Console::i_doCPURemove(ULONG aCpu, PUVM pUVM, PCVMMR3VTABLE pVMM)
2456{
2457 LogFlowThisFuncEnter();
2458
2459 AutoCaller autoCaller(this);
2460 HRESULT hrc = autoCaller.hrc();
2461 if (FAILED(hrc))
2462 return hrc;
2463
2464 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2465
2466 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
2467 AssertReturn(m_pVMMDev, E_FAIL);
2468 PPDMIVMMDEVPORT pVmmDevPort = m_pVMMDev->getVMMDevPort();
2469 AssertReturn(pVmmDevPort, E_FAIL);
2470
2471 if ( mMachineState != MachineState_Running
2472 && mMachineState != MachineState_Teleporting
2473 && mMachineState != MachineState_LiveSnapshotting
2474 )
2475 return i_setInvalidMachineStateError();
2476
2477 /* Check if the CPU is present */
2478 BOOL fCpuAttached;
2479 hrc = mMachine->GetCPUStatus(aCpu, &fCpuAttached);
2480 if (FAILED(hrc))
2481 return hrc;
2482 if (!fCpuAttached)
2483 return setError(E_FAIL, tr("CPU %d is not attached"), aCpu);
2484
2485 /* Leave the lock before any EMT/VMMDev call. */
2486 alock.release();
2487 bool fLocked = true;
2488
2489 /* Check if the CPU is unlocked */
2490 PPDMIBASE pBase;
2491 int vrc = pVMM->pfnPDMR3QueryDeviceLun(pUVM, "acpi", 0, aCpu, &pBase);
2492 if (RT_SUCCESS(vrc))
2493 {
2494 Assert(pBase);
2495 PPDMIACPIPORT pApicPort = PDMIBASE_QUERY_INTERFACE(pBase, PDMIACPIPORT);
2496
2497 /* Notify the guest if possible. */
2498 uint32_t idCpuCore, idCpuPackage;
2499 vrc = pVMM->pfnVMR3GetCpuCoreAndPackageIdFromCpuId(pUVM, aCpu, &idCpuCore, &idCpuPackage); AssertRC(vrc);
2500 if (RT_SUCCESS(vrc))
2501 vrc = pVmmDevPort->pfnCpuHotUnplug(pVmmDevPort, idCpuCore, idCpuPackage);
2502 if (RT_SUCCESS(vrc))
2503 {
2504 unsigned cTries = 100;
2505 do
2506 {
2507 /* It will take some time until the event is processed in the guest. Wait... */
2508 vrc = pApicPort ? pApicPort->pfnGetCpuStatus(pApicPort, aCpu, &fLocked) : VERR_INVALID_POINTER;
2509 if (RT_SUCCESS(vrc) && !fLocked)
2510 break;
2511
2512 /* Sleep a bit */
2513 RTThreadSleep(100);
2514 } while (cTries-- > 0);
2515 }
2516 else if (vrc == VERR_VMMDEV_CPU_HOTPLUG_NOT_MONITORED_BY_GUEST)
2517 {
2518 /* Query one time. It is possible that the user ejected the CPU. */
2519 vrc = pApicPort ? pApicPort->pfnGetCpuStatus(pApicPort, aCpu, &fLocked) : VERR_INVALID_POINTER;
2520 }
2521 }
2522
2523 /* If the CPU was unlocked we can detach it now. */
2524 if (RT_SUCCESS(vrc) && !fLocked)
2525 {
2526 /*
2527 * Call worker on EMT #0, that's faster and safer than doing everything
2528 * using VMR3ReqCall.
2529 */
2530 PVMREQ pReq;
2531 vrc = pVMM->pfnVMR3ReqCallU(pUVM, 0, &pReq, 0 /* no wait! */, VMREQFLAGS_VBOX_STATUS,
2532 (PFNRT)i_unplugCpu, 4,
2533 this, pUVM, pVMM, (VMCPUID)aCpu);
2534
2535 if (vrc == VERR_TIMEOUT)
2536 vrc = pVMM->pfnVMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
2537 AssertRC(vrc);
2538 if (RT_SUCCESS(vrc))
2539 vrc = pReq->iStatus;
2540 pVMM->pfnVMR3ReqFree(pReq);
2541
2542 if (RT_SUCCESS(vrc))
2543 {
2544 /* Detach it from the VM */
2545 vrc = pVMM->pfnVMR3HotUnplugCpu(pUVM, aCpu);
2546 AssertRC(vrc);
2547 }
2548 else
2549 hrc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Hot-Remove failed (vrc=%Rrc)"), vrc);
2550 }
2551 else
2552 hrc = setErrorBoth(VBOX_E_VM_ERROR, VERR_RESOURCE_BUSY,
2553 tr("Hot-Remove was aborted because the CPU may still be used by the guest"), VERR_RESOURCE_BUSY);
2554
2555 LogFlowThisFunc(("mMachineState=%d, hrc=%Rhrc\n", mMachineState, hrc));
2556 LogFlowThisFuncLeave();
2557 return hrc;
2558}
2559
2560/*static*/ DECLCALLBACK(int) Console::i_plugCpu(Console *pThis, PUVM pUVM, PCVMMR3VTABLE pVMM, VMCPUID idCpu)
2561{
2562 LogFlowFunc(("pThis=%p uCpu=%u\n", pThis, idCpu));
2563 RT_NOREF(pThis);
2564
2565 int vrc = pVMM->pfnVMR3HotPlugCpu(pUVM, idCpu);
2566 AssertRC(vrc);
2567
2568 /** @todo r=bird: Error handling here just sucks. */
2569
2570 PCFGMNODE pInst = pVMM->pfnCFGMR3GetChild(pVMM->pfnCFGMR3GetRootU(pUVM), "Devices/acpi/0/");
2571 AssertRelease(pInst);
2572 /* nuke anything which might have been left behind. */
2573 pVMM->pfnCFGMR3RemoveNode(pVMM->pfnCFGMR3GetChildF(pInst, "LUN#%u", idCpu));
2574
2575#define RC_CHECK() do { AssertReleaseRC(vrc); } while (0)
2576
2577 PCFGMNODE pLunL0;
2578 PCFGMNODE pCfg;
2579 vrc = pVMM->pfnCFGMR3InsertNodeF(pInst, &pLunL0, "LUN#%u", idCpu); RC_CHECK();
2580 vrc = pVMM->pfnCFGMR3InsertString(pLunL0, "Driver", "ACPICpu"); RC_CHECK();
2581 vrc = pVMM->pfnCFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
2582
2583 /*
2584 * Attach the driver.
2585 */
2586 PPDMIBASE pBase;
2587 vrc = pVMM->pfnPDMR3DeviceAttach(pUVM, "acpi", 0, idCpu, 0, &pBase); RC_CHECK();
2588
2589 Log(("PlugCpu: vrc=%Rrc\n", vrc));
2590
2591 pVMM->pfnCFGMR3Dump(pInst);
2592
2593#undef RC_CHECK
2594
2595 return VINF_SUCCESS;
2596}
2597
2598HRESULT Console::i_doCPUAdd(ULONG aCpu, PUVM pUVM, PCVMMR3VTABLE pVMM)
2599{
2600 LogFlowThisFuncEnter();
2601
2602 AutoCaller autoCaller(this);
2603 HRESULT hrc = autoCaller.hrc();
2604 if (FAILED(hrc))
2605 return hrc;
2606
2607 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2608
2609 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
2610 if ( mMachineState != MachineState_Running
2611 && mMachineState != MachineState_Teleporting
2612 && mMachineState != MachineState_LiveSnapshotting
2613 /** @todo r=bird: This should be allowed on paused VMs as well. Later. */
2614 )
2615 return i_setInvalidMachineStateError();
2616
2617 AssertReturn(m_pVMMDev, E_FAIL);
2618 PPDMIVMMDEVPORT pDevPort = m_pVMMDev->getVMMDevPort();
2619 AssertReturn(pDevPort, E_FAIL);
2620
2621 /* Check if the CPU is present */
2622 BOOL fCpuAttached;
2623 hrc = mMachine->GetCPUStatus(aCpu, &fCpuAttached);
2624 if (FAILED(hrc))
2625 return hrc;
2626
2627 if (fCpuAttached)
2628 return setError(E_FAIL, tr("CPU %d is already attached"), aCpu);
2629
2630 /*
2631 * Call worker on EMT #0, that's faster and safer than doing everything
2632 * using VMR3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
2633 * here to make requests from under the lock in order to serialize them.
2634 */
2635 PVMREQ pReq;
2636 int vrc = pVMM->pfnVMR3ReqCallU(pUVM, 0, &pReq, 0 /* no wait! */, VMREQFLAGS_VBOX_STATUS,
2637 (PFNRT)i_plugCpu, 4,
2638 this, pUVM, pVMM, aCpu);
2639
2640 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
2641 alock.release();
2642
2643 if (vrc == VERR_TIMEOUT)
2644 vrc = pVMM->pfnVMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
2645 AssertRC(vrc);
2646 if (RT_SUCCESS(vrc))
2647 vrc = pReq->iStatus;
2648 pVMM->pfnVMR3ReqFree(pReq);
2649
2650 if (RT_SUCCESS(vrc))
2651 {
2652 /* Notify the guest if possible. */
2653 uint32_t idCpuCore, idCpuPackage;
2654 vrc = pVMM->pfnVMR3GetCpuCoreAndPackageIdFromCpuId(pUVM, aCpu, &idCpuCore, &idCpuPackage); AssertRC(vrc);
2655 if (RT_SUCCESS(vrc))
2656 vrc = pDevPort->pfnCpuHotPlug(pDevPort, idCpuCore, idCpuPackage);
2657 /** @todo warning if the guest doesn't support it */
2658 }
2659 else
2660 hrc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not add CPU to the machine (%Rrc)"), vrc);
2661
2662 LogFlowThisFunc(("mMachineState=%d, hrc=%Rhrc\n", mMachineState, hrc));
2663 LogFlowThisFuncLeave();
2664 return hrc;
2665}
2666
2667HRESULT Console::pause()
2668{
2669 LogFlowThisFuncEnter();
2670
2671 HRESULT hrc = i_pause(Reason_Unspecified);
2672
2673 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
2674 LogFlowThisFuncLeave();
2675 return hrc;
2676}
2677
2678HRESULT Console::resume()
2679{
2680 LogFlowThisFuncEnter();
2681
2682 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2683
2684 if (mMachineState != MachineState_Paused)
2685 return setError(VBOX_E_INVALID_VM_STATE,
2686 tr("Cannot resume the machine as it is not paused (machine state: %s)"),
2687 Global::stringifyMachineState(mMachineState));
2688
2689 HRESULT hrc = i_resume(Reason_Unspecified, alock);
2690
2691 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
2692 LogFlowThisFuncLeave();
2693 return hrc;
2694}
2695
2696HRESULT Console::powerButton()
2697{
2698 LogFlowThisFuncEnter();
2699
2700 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2701
2702 if ( mMachineState != MachineState_Running
2703 && mMachineState != MachineState_Teleporting
2704 && mMachineState != MachineState_LiveSnapshotting
2705 )
2706 return i_setInvalidMachineStateError();
2707
2708 /* get the VM handle. */
2709 SafeVMPtr ptrVM(this);
2710 HRESULT hrc = ptrVM.hrc();
2711 if (SUCCEEDED(hrc))
2712 {
2713 // no need to release lock, as there are no cross-thread callbacks
2714
2715 /* get the acpi device interface and press the button. */
2716 PPDMIBASE pBase = NULL;
2717 int vrc = ptrVM.vtable()->pfnPDMR3QueryDeviceLun(ptrVM.rawUVM(), "acpi", 0, 0, &pBase);
2718 /** @todo r=aeichner Think about a prettier way to do this without relying on hardocded device/driver names. */
2719 if (vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND) /* Try GPIO device for ARM VMs */
2720 vrc = ptrVM.vtable()->pfnPDMR3QueryDriverOnLun(ptrVM.rawUVM(), "arm-pl061-gpio", 0, 0, "GpioButton", &pBase);
2721 if (RT_SUCCESS(vrc))
2722 {
2723 Assert(pBase);
2724 PPDMIEVENTBUTTONPORT pPort = PDMIBASE_QUERY_INTERFACE(pBase, PDMIEVENTBUTTONPORT);
2725 if (pPort)
2726 vrc = pPort->pfnPowerButtonPress(pPort);
2727 else
2728 vrc = VERR_PDM_MISSING_INTERFACE;
2729 }
2730
2731 hrc = RT_SUCCESS(vrc) ? S_OK : setErrorBoth(VBOX_E_PDM_ERROR, vrc, tr("Controlled power off failed (%Rrc)"), vrc);
2732 }
2733
2734 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
2735 LogFlowThisFuncLeave();
2736 return hrc;
2737}
2738
2739HRESULT Console::getPowerButtonHandled(BOOL *aHandled)
2740{
2741 LogFlowThisFuncEnter();
2742
2743 *aHandled = FALSE;
2744
2745 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2746
2747 if ( mMachineState != MachineState_Running
2748 && mMachineState != MachineState_Teleporting
2749 && mMachineState != MachineState_LiveSnapshotting
2750 )
2751 return i_setInvalidMachineStateError();
2752
2753 /* get the VM handle. */
2754 SafeVMPtr ptrVM(this);
2755 HRESULT hrc = ptrVM.hrc();
2756 if (SUCCEEDED(hrc))
2757 {
2758 // no need to release lock, as there are no cross-thread callbacks
2759
2760 /* get the acpi device interface and check if the button press was handled. */
2761 PPDMIBASE pBase;
2762 int vrc = ptrVM.vtable()->pfnPDMR3QueryDeviceLun(ptrVM.rawUVM(), "acpi", 0, 0, &pBase);
2763 if (RT_SUCCESS(vrc))
2764 {
2765 Assert(pBase);
2766 PPDMIEVENTBUTTONPORT pPort = PDMIBASE_QUERY_INTERFACE(pBase, PDMIEVENTBUTTONPORT);
2767 if (pPort)
2768 {
2769 bool fHandled = false;
2770 vrc = pPort->pfnQueryPowerButtonHandled(pPort, &fHandled);
2771 if (RT_SUCCESS(vrc))
2772 *aHandled = fHandled;
2773 }
2774 else
2775 vrc = VERR_PDM_MISSING_INTERFACE;
2776 }
2777
2778 hrc = RT_SUCCESS(vrc) ? S_OK
2779 : setErrorBoth(VBOX_E_PDM_ERROR, vrc,
2780 tr("Checking if the ACPI Power Button event was handled by the guest OS failed (%Rrc)"), vrc);
2781
2782 }
2783 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
2784 LogFlowThisFuncLeave();
2785 return hrc;
2786}
2787
2788HRESULT Console::getGuestEnteredACPIMode(BOOL *aEntered)
2789{
2790 LogFlowThisFuncEnter();
2791
2792 *aEntered = FALSE;
2793
2794 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2795
2796 if ( mMachineState != MachineState_Running
2797 && mMachineState != MachineState_Teleporting
2798 && mMachineState != MachineState_LiveSnapshotting
2799 )
2800 return setError(VBOX_E_INVALID_VM_STATE,
2801 tr("Invalid machine state %s when checking if the guest entered the ACPI mode"),
2802 Global::stringifyMachineState(mMachineState));
2803
2804 /* get the VM handle. */
2805 SafeVMPtr ptrVM(this);
2806 HRESULT hrc = ptrVM.hrc();
2807 if (SUCCEEDED(hrc))
2808 {
2809 // no need to release lock, as there are no cross-thread callbacks
2810
2811 /* get the acpi device interface and query the information. */
2812 PPDMIBASE pBase;
2813 int vrc = ptrVM.vtable()->pfnPDMR3QueryDeviceLun(ptrVM.rawUVM(), "acpi", 0, 0, &pBase);
2814 if (RT_SUCCESS(vrc))
2815 {
2816 Assert(pBase);
2817 PPDMIACPIPORT pPort = PDMIBASE_QUERY_INTERFACE(pBase, PDMIACPIPORT);
2818 if (pPort)
2819 {
2820 bool fEntered = false;
2821 vrc = pPort->pfnGetGuestEnteredACPIMode(pPort, &fEntered);
2822 if (RT_SUCCESS(vrc))
2823 *aEntered = fEntered;
2824 }
2825 else
2826 vrc = VERR_PDM_MISSING_INTERFACE;
2827 }
2828
2829 if (vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND)
2830 {
2831 /* Might be an ARM VM. */
2832 /** @todo r=aeichner Think about a prettier way to do this without relying on hardocded device/driver names,
2833 * and this shouldn't be here as it is not about ACPI but needs a dedicated interface. */
2834 vrc = ptrVM.vtable()->pfnPDMR3QueryDriverOnLun(ptrVM.rawUVM(), "arm-pl061-gpio", 0, 0, "GpioButton", &pBase);
2835 if (RT_SUCCESS(vrc))
2836 {
2837 Assert(pBase);
2838 PPDMIEVENTBUTTONPORT pPort = PDMIBASE_QUERY_INTERFACE(pBase, PDMIEVENTBUTTONPORT);
2839 if (pPort)
2840 {
2841 bool fEntered = false;
2842 vrc = pPort->pfnQueryGuestCanHandleButtonEvents(pPort, &fEntered);
2843 if (RT_SUCCESS(vrc))
2844 *aEntered = fEntered;
2845 }
2846 else
2847 vrc = VERR_PDM_MISSING_INTERFACE;
2848 }
2849 }
2850 }
2851
2852 LogFlowThisFuncLeave();
2853 return hrc;
2854}
2855
2856HRESULT Console::sleepButton()
2857{
2858 LogFlowThisFuncEnter();
2859
2860 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2861
2862 if ( mMachineState != MachineState_Running
2863 && mMachineState != MachineState_Teleporting
2864 && mMachineState != MachineState_LiveSnapshotting)
2865 return i_setInvalidMachineStateError();
2866
2867 /* get the VM handle. */
2868 SafeVMPtr ptrVM(this);
2869 HRESULT hrc = ptrVM.hrc();
2870 if (SUCCEEDED(hrc))
2871 {
2872 // no need to release lock, as there are no cross-thread callbacks
2873
2874 /* get the acpi device interface and press the sleep button. */
2875 PPDMIBASE pBase = NULL;
2876 int vrc = ptrVM.vtable()->pfnPDMR3QueryDeviceLun(ptrVM.rawUVM(), "acpi", 0, 0, &pBase);
2877 /** @todo r=aeichner Think about a prettier way to do this without relying on hardocded device/driver names. */
2878 if (vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND) /* Try GPIO device for ARM VMs */
2879 vrc = ptrVM.vtable()->pfnPDMR3QueryDriverOnLun(ptrVM.rawUVM(), "arm-pl061-gpio", 0, 0, "GpioButton", &pBase);
2880 if (RT_SUCCESS(vrc))
2881 {
2882 Assert(pBase);
2883 PPDMIEVENTBUTTONPORT pPort = PDMIBASE_QUERY_INTERFACE(pBase, PDMIEVENTBUTTONPORT);
2884 if (pPort)
2885 vrc = pPort->pfnSleepButtonPress(pPort);
2886 else
2887 vrc = VERR_PDM_MISSING_INTERFACE;
2888 }
2889
2890 hrc = RT_SUCCESS(vrc) ? S_OK : setErrorBoth(VBOX_E_PDM_ERROR, vrc, tr("Sending sleep button event failed (%Rrc)"), vrc);
2891 }
2892
2893 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
2894 LogFlowThisFuncLeave();
2895 return hrc;
2896}
2897
2898/**
2899 * Refreshes the maLedTypes and muLedTypeGen members.
2900 */
2901HRESULT Console::i_refreshLedTypeArrays(AutoReadLock *pReadLock)
2902{
2903 pReadLock->release();
2904 AutoWriteLock alock(mLedLock COMMA_LOCKVAL_SRC_POS);
2905
2906 /*
2907 * Check that the refresh was already done by someone else while we
2908 * acquired the write lock.
2909 */
2910 if (muLedTypeGen != muLedGen)
2911 {
2912 /*
2913 * Reset the data.
2914 */
2915 for (size_t idxType = 0; idxType < RT_ELEMENTS(maLedTypes); idxType++)
2916 maLedTypes[idxType].cLeds = 0;
2917
2918 /*
2919 * Rebuild the data.
2920 */
2921 for (uint32_t idxSet = 0; idxSet < mcLedSets; idxSet++)
2922 {
2923 PLEDSET const pLS = &maLedSets[idxSet];
2924 uint32_t const cLeds = pLS->cLeds;
2925 PPDMLED volatile * const papSrcLeds = pLS->papLeds;
2926 DeviceType_T * const paSubTypes = pLS->paSubTypes;
2927 for (uint32_t idxLed = 0; idxLed < cLeds; idxLed++)
2928 {
2929 /** @todo If we make Console::i_drvStatus_UnitChanged() modify the generation
2930 * too, we could skip NULL entries here and make it a bit more compact.
2931 * OTOH, most unused LED entires have a paSubTypes of DeviceType_Null. */
2932 DeviceType_T enmType = paSubTypes ? paSubTypes[idxLed] : (DeviceType_T)(ASMBitFirstSetU32(pLS->fTypes) - 1);
2933 if (enmType > DeviceType_Null && enmType < DeviceType_End)
2934 {
2935 uint32_t const idxLedType = maLedTypes[enmType].cLeds;
2936 if (idxLedType >= maLedTypes[enmType].cAllocated)
2937 {
2938 void *pvNew = RTMemRealloc(maLedTypes[enmType].pappLeds,
2939 sizeof(maLedTypes[0].pappLeds[0]) * (idxLedType + 16));
2940 if (!pvNew)
2941 return E_OUTOFMEMORY;
2942 maLedTypes[enmType].pappLeds = (PPDMLED volatile **)pvNew;
2943 maLedTypes[enmType].cAllocated = idxLedType + 16;
2944 }
2945 maLedTypes[enmType].pappLeds[idxLedType] = &papSrcLeds[idxLed];
2946 maLedTypes[enmType].cLeds = idxLedType + 1;
2947 }
2948 }
2949 }
2950 muLedTypeGen = muLedGen;
2951 }
2952
2953 /*
2954 * We have to release the write lock before re-acquiring the read-lock.
2955 *
2956 * This means there is a theoretical race here, however we ASSUME that
2957 * LED sets are never removed and therefore we will be just fine
2958 * accessing slightly dated per-type data.
2959 */
2960 alock.release();
2961 pReadLock->acquire();
2962 return S_OK;
2963}
2964
2965/** read the value of a LED. */
2966DECLINLINE(uint32_t) readAndClearLed(PPDMLED pLed)
2967{
2968 if (!pLed)
2969 return 0;
2970 uint32_t u32 = pLed->Actual.u32 | pLed->Asserted.u32;
2971 pLed->Asserted.u32 = 0;
2972 return u32;
2973}
2974
2975HRESULT Console::getDeviceActivity(const std::vector<DeviceType_T> &aType, std::vector<DeviceActivity_T> &aActivity)
2976{
2977 /*
2978 * Make a roadmap of which DeviceType_T LED types are wanted.
2979 *
2980 * Note! This approach means we'll return the same values in aActivity for
2981 * duplicate aType entries.
2982 */
2983 uint32_t fRequestedTypes = 0;
2984 AssertCompile(DeviceType_End <= 32);
2985
2986 for (size_t iType = 0; iType < aType.size(); ++iType)
2987 {
2988 DeviceType_T const enmType = aType[iType];
2989 AssertCompile((unsigned)DeviceType_Null == 0 /* first */);
2990 AssertReturn(enmType > DeviceType_Null && enmType < DeviceType_End,
2991 setError(E_INVALIDARG, tr("Invalid DeviceType for getDeviceActivity in entry #%u: %d"), iType, enmType));
2992 fRequestedTypes |= RT_BIT_32((unsigned)enmType);
2993 }
2994
2995 /*
2996 * Resize the result vector before making changes (may throw, paranoia).
2997 */
2998 aActivity.resize(aType.size());
2999
3000 /*
3001 * Accumulate the per-type data for all the requested types.
3002 * We will lazily refresh the per-type data collection here when needed.
3003 */
3004 PDMLEDCORE aLEDs[DeviceType_End] = { {0} };
3005 Assert(aLEDs[1].u32 == 0 && aLEDs[DeviceType_End / 2].u32 == 0 && aLEDs[DeviceType_End - 1].u32 == 0); /* paranoia */
3006 {
3007 AutoReadLock alock(mLedLock COMMA_LOCKVAL_SRC_POS);
3008 if (RT_LIKELY(muLedGen == muLedTypeGen))
3009 { /* likely */ }
3010 else
3011 {
3012 HRESULT hrc = i_refreshLedTypeArrays(&alock);
3013 if (FAILED(hrc))
3014 return hrc;
3015 }
3016
3017 AssertCompile((unsigned)DeviceType_Null == 0 /* we skip this one */);
3018 for (uint32_t idxType = 1; idxType < RT_ELEMENTS(maLedTypes); idxType++)
3019 if (fRequestedTypes & RT_BIT_32(idxType))
3020 {
3021 uint32_t const cLeds = maLedTypes[idxType].cLeds;
3022 PPDMLED volatile ** const pappSrcLeds = maLedTypes[idxType].pappLeds;
3023 for (size_t iLed = 0; iLed < cLeds; iLed++)
3024 aLEDs[idxType].u32 |= readAndClearLed(*pappSrcLeds[iLed]);
3025 }
3026 }
3027
3028 /*
3029 * Compose the result vector:
3030 */
3031 for (size_t iType = 0; iType < aActivity.size(); ++iType)
3032 {
3033 switch (aLEDs[aType[iType]].u32 & (PDMLED_READING | PDMLED_WRITING))
3034 {
3035 case 0:
3036 aActivity[iType] = DeviceActivity_Idle;
3037 break;
3038 case PDMLED_READING:
3039 aActivity[iType] = DeviceActivity_Reading;
3040 break;
3041 case PDMLED_WRITING:
3042 case PDMLED_READING | PDMLED_WRITING:
3043 aActivity[iType] = DeviceActivity_Writing;
3044 break;
3045 }
3046 }
3047
3048 return S_OK;
3049}
3050
3051HRESULT Console::attachUSBDevice(const com::Guid &aId, const com::Utf8Str &aCaptureFilename)
3052{
3053#ifdef VBOX_WITH_USB
3054 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3055
3056 if ( mMachineState != MachineState_Running
3057 && mMachineState != MachineState_Paused)
3058 return setError(VBOX_E_INVALID_VM_STATE,
3059 tr("Cannot attach a USB device to the machine which is not running or paused (machine state: %s)"),
3060 Global::stringifyMachineState(mMachineState));
3061
3062 /* Get the VM handle. */
3063 SafeVMPtr ptrVM(this);
3064 HRESULT hrc = ptrVM.hrc();
3065 if (SUCCEEDED(hrc))
3066 {
3067 /* Don't proceed unless we have a USB controller. */
3068 if (mfVMHasUsbController)
3069 {
3070 /* release the lock because the USB Proxy service may call us back
3071 * (via onUSBDeviceAttach()) */
3072 alock.release();
3073
3074 /* Request the device capture */
3075 hrc = mControl->CaptureUSBDevice(Bstr(aId.toString()).raw(), Bstr(aCaptureFilename).raw());
3076 }
3077 else
3078 hrc = setError(VBOX_E_PDM_ERROR, tr("The virtual machine does not have a USB controller"));
3079 }
3080 return hrc;
3081
3082#else /* !VBOX_WITH_USB */
3083 RT_NOREF(aId, aCaptureFilename);
3084 return setError(VBOX_E_PDM_ERROR, tr("The virtual machine does not have a USB controller"));
3085#endif /* !VBOX_WITH_USB */
3086}
3087
3088HRESULT Console::detachUSBDevice(const com::Guid &aId, ComPtr<IUSBDevice> &aDevice)
3089{
3090 RT_NOREF(aDevice);
3091#ifdef VBOX_WITH_USB
3092 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3093
3094 /* Find it. */
3095 for (USBDeviceList::iterator it = mUSBDevices.begin(); it != mUSBDevices.end(); ++it)
3096 if ((*it)->i_id() == aId)
3097 {
3098 /* Found it! */
3099 ComObjPtr<OUSBDevice> pUSBDevice(*it);
3100
3101 /* Remove the device from the collection, it is re-added below for failures */
3102 mUSBDevices.erase(it);
3103
3104 /*
3105 * Inform the USB device and USB proxy about what's cooking.
3106 */
3107 alock.release();
3108 HRESULT hrc = mControl->DetachUSBDevice(Bstr(aId.toString()).raw(), false /* aDone */);
3109 if (SUCCEEDED(hrc))
3110 {
3111 /* Request the PDM to detach the USB device. */
3112 hrc = i_detachUSBDevice(pUSBDevice);
3113 if (SUCCEEDED(hrc))
3114 {
3115 //return the detached USB device
3116 pUSBDevice.queryInterfaceTo(aDevice.asOutParam());
3117 /* Request the device release. Even if it fails, the device will
3118 * remain as held by proxy, which is OK for us (the VM process). */
3119 return mControl->DetachUSBDevice(Bstr(aId.toString()).raw(), true /* aDone */);
3120 }
3121 }
3122
3123 /* Re-add the device to the collection */
3124 alock.acquire();
3125 mUSBDevices.push_back(pUSBDevice);
3126 return hrc;
3127 }
3128
3129 return setError(E_INVALIDARG, tr("USB device with UUID {%RTuuid} is not attached to this machine"), aId.raw());
3130
3131#else /* !VBOX_WITH_USB */
3132 RT_NOREF(aId, aDevice);
3133 return setError(VBOX_E_PDM_ERROR, tr("The virtual machine does not have a USB controller"));
3134#endif /* !VBOX_WITH_USB */
3135}
3136
3137
3138HRESULT Console::findUSBDeviceByAddress(const com::Utf8Str &aName, ComPtr<IUSBDevice> &aDevice)
3139{
3140#ifdef VBOX_WITH_USB
3141 aDevice = NULL;
3142
3143 SafeIfaceArray<IUSBDevice> devsvec;
3144 HRESULT hrc = COMGETTER(USBDevices)(ComSafeArrayAsOutParam(devsvec));
3145 if (FAILED(hrc))
3146 return hrc;
3147
3148 for (size_t i = 0; i < devsvec.size(); ++i)
3149 {
3150 Bstr bstrAddress;
3151 hrc = devsvec[i]->COMGETTER(Address)(bstrAddress.asOutParam());
3152 if (FAILED(hrc))
3153 return hrc;
3154 if (bstrAddress == aName)
3155 {
3156 ComObjPtr<OUSBDevice> pUSBDevice;
3157 pUSBDevice.createObject();
3158 pUSBDevice->init(devsvec[i]);
3159 return pUSBDevice.queryInterfaceTo(aDevice.asOutParam());
3160 }
3161 }
3162
3163 return setErrorNoLog(VBOX_E_OBJECT_NOT_FOUND, tr("Could not find a USB device with address '%s'"), aName.c_str());
3164
3165#else /* !VBOX_WITH_USB */
3166 RT_NOREF(aName, aDevice);
3167 return E_NOTIMPL;
3168#endif /* !VBOX_WITH_USB */
3169}
3170
3171HRESULT Console::findUSBDeviceById(const com::Guid &aId, ComPtr<IUSBDevice> &aDevice)
3172{
3173#ifdef VBOX_WITH_USB
3174 aDevice = NULL;
3175
3176 SafeIfaceArray<IUSBDevice> devsvec;
3177 HRESULT hrc = COMGETTER(USBDevices)(ComSafeArrayAsOutParam(devsvec));
3178 if (FAILED(hrc))
3179 return hrc;
3180
3181 Utf8Str const strId = aId.toString();
3182 for (size_t i = 0; i < devsvec.size(); ++i)
3183 {
3184 Bstr id;
3185 hrc = devsvec[i]->COMGETTER(Id)(id.asOutParam());
3186 if (FAILED(hrc))
3187 return hrc;
3188 if (id == strId)
3189 {
3190 ComObjPtr<OUSBDevice> pUSBDevice;
3191 pUSBDevice.createObject();
3192 pUSBDevice->init(devsvec[i]);
3193 ComObjPtr<IUSBDevice> iUSBDevice = static_cast <ComObjPtr<IUSBDevice> > (pUSBDevice);
3194 return iUSBDevice.queryInterfaceTo(aDevice.asOutParam());
3195 }
3196 }
3197
3198 return setErrorNoLog(VBOX_E_OBJECT_NOT_FOUND, tr("Could not find a USB device with uuid {%RTuuid}"), aId.raw());
3199
3200#else /* !VBOX_WITH_USB */
3201 RT_NOREF(aId, aDevice);
3202 return E_NOTIMPL;
3203#endif /* !VBOX_WITH_USB */
3204}
3205
3206HRESULT Console::createSharedFolder(const com::Utf8Str &aName, const com::Utf8Str &aHostPath, BOOL aWritable,
3207 BOOL aAutomount, const com::Utf8Str &aAutoMountPoint)
3208{
3209 LogFlowThisFunc(("Entering for '%s' -> '%s'\n", aName.c_str(), aHostPath.c_str()));
3210
3211 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3212
3213 /// @todo see @todo in AttachUSBDevice() about the Paused state
3214 if (mMachineState == MachineState_Saved || mMachineState == MachineState_AbortedSaved)
3215 return setError(VBOX_E_INVALID_VM_STATE,
3216 tr("Cannot create a transient shared folder on a machine in a saved state (machine state: %s)"),
3217 Global::stringifyMachineState(mMachineState));
3218 if ( mMachineState != MachineState_PoweredOff
3219 && mMachineState != MachineState_Teleported
3220 && mMachineState != MachineState_Aborted
3221 && mMachineState != MachineState_Running
3222 && mMachineState != MachineState_Paused
3223 )
3224 return setError(VBOX_E_INVALID_VM_STATE,
3225 tr("Cannot create a transient shared folder on the machine while it is changing the state (machine state: %s)"),
3226 Global::stringifyMachineState(mMachineState));
3227
3228 ComObjPtr<ConsoleSharedFolder> pSharedFolder;
3229 HRESULT hrc = i_findSharedFolder(aName, pSharedFolder, false /* aSetError */);
3230 if (SUCCEEDED(hrc))
3231 return setError(VBOX_E_FILE_ERROR, tr("Shared folder named '%s' already exists"), aName.c_str());
3232
3233 pSharedFolder.createObject();
3234 hrc = pSharedFolder->init(this,
3235 aName,
3236 aHostPath,
3237 !!aWritable,
3238 !!aAutomount,
3239 aAutoMountPoint,
3240 true /* fFailOnError */);
3241 if (FAILED(hrc))
3242 return hrc;
3243
3244 /* If the VM is online and supports shared folders, share this folder
3245 * under the specified name. (Ignore any failure to obtain the VM handle.) */
3246 SafeVMPtrQuiet ptrVM(this);
3247 if ( ptrVM.isOk()
3248 && m_pVMMDev
3249 && m_pVMMDev->isShFlActive()
3250 )
3251 {
3252 /* first, remove the machine or the global folder if there is any */
3253 SharedFolderDataMap::const_iterator it;
3254 if (i_findOtherSharedFolder(aName, it))
3255 {
3256 hrc = i_removeSharedFolder(aName);
3257 if (FAILED(hrc))
3258 return hrc;
3259 }
3260
3261 /* second, create the given folder */
3262 hrc = i_createSharedFolder(aName, SharedFolderData(aHostPath, !!aWritable, !!aAutomount, aAutoMountPoint));
3263 if (FAILED(hrc))
3264 return hrc;
3265 }
3266
3267 m_mapSharedFolders.insert(std::make_pair(aName, pSharedFolder));
3268
3269 /* Notify console callbacks after the folder is added to the list. */
3270 alock.release();
3271 ::FireSharedFolderChangedEvent(mEventSource, Scope_Session);
3272
3273 LogFlowThisFunc(("Leaving for '%s' -> '%s'\n", aName.c_str(), aHostPath.c_str()));
3274
3275 return hrc;
3276}
3277
3278HRESULT Console::removeSharedFolder(const com::Utf8Str &aName)
3279{
3280 LogFlowThisFunc(("Entering for '%s'\n", aName.c_str()));
3281
3282 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3283
3284 /// @todo see @todo in AttachUSBDevice() about the Paused state
3285 if (mMachineState == MachineState_Saved || mMachineState == MachineState_AbortedSaved)
3286 return setError(VBOX_E_INVALID_VM_STATE,
3287 tr("Cannot remove a transient shared folder from a machine in a saved state (machine state: %s)"),
3288 Global::stringifyMachineState(mMachineState));;
3289 if ( mMachineState != MachineState_PoweredOff
3290 && mMachineState != MachineState_Teleported
3291 && mMachineState != MachineState_Aborted
3292 && mMachineState != MachineState_Running
3293 && mMachineState != MachineState_Paused
3294 )
3295 return setError(VBOX_E_INVALID_VM_STATE,
3296 tr("Cannot remove a transient shared folder from the machine while it is changing the state (machine state: %s)"),
3297 Global::stringifyMachineState(mMachineState));
3298
3299 ComObjPtr<ConsoleSharedFolder> pSharedFolder;
3300 HRESULT hrc = i_findSharedFolder(aName, pSharedFolder, true /* aSetError */);
3301 if (FAILED(hrc))
3302 return hrc;
3303
3304 /* protect the VM handle (if not NULL) */
3305 SafeVMPtrQuiet ptrVM(this);
3306 if ( ptrVM.isOk()
3307 && m_pVMMDev
3308 && m_pVMMDev->isShFlActive()
3309 )
3310 {
3311 /* if the VM is online and supports shared folders, UNshare this folder. */
3312
3313 /* first, remove the given folder */
3314 hrc = i_removeSharedFolder(aName);
3315 if (FAILED(hrc))
3316 return hrc;
3317
3318 /* first, remove the machine or the global folder if there is any */
3319 SharedFolderDataMap::const_iterator it;
3320 if (i_findOtherSharedFolder(aName, it))
3321 {
3322 hrc = i_createSharedFolder(aName, it->second);
3323 /* don't check hrc here because we need to remove the console
3324 * folder from the collection even on failure */
3325 }
3326 }
3327
3328 m_mapSharedFolders.erase(aName);
3329
3330 /* Notify console callbacks after the folder is removed from the list. */
3331 alock.release();
3332 ::FireSharedFolderChangedEvent(mEventSource, Scope_Session);
3333
3334 LogFlowThisFunc(("Leaving for '%s'\n", aName.c_str()));
3335
3336 return hrc;
3337}
3338
3339HRESULT Console::addEncryptionPassword(const com::Utf8Str &aId, const com::Utf8Str &aPassword,
3340 BOOL aClearOnSuspend)
3341{
3342 if ( aId.isEmpty()
3343 || aPassword.isEmpty())
3344 return setError(E_FAIL, tr("The ID and password must be both valid"));
3345
3346 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3347
3348 HRESULT hrc = S_OK;
3349 size_t cbKey = aPassword.length() + 1; /* Include terminator */
3350 const uint8_t *pbKey = (const uint8_t *)aPassword.c_str();
3351
3352 int vrc = m_pKeyStore->addSecretKey(aId, pbKey, cbKey);
3353 if ( RT_SUCCESS(vrc)
3354#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
3355 || vrc == VERR_ALREADY_EXISTS /* Allow setting an existing key for encrypted VMs. */
3356#endif
3357 )
3358 {
3359 unsigned cDisksConfigured = 0;
3360
3361#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
3362 if (mptrNvramStore.isNotNull())
3363 mptrNvramStore->i_addPassword(aId, aPassword);
3364
3365 SecretKey *pKey = NULL;
3366 vrc = m_pKeyStore->retainSecretKey(aId, &pKey);
3367 AssertRCReturn(vrc, E_FAIL);
3368 pKey->setRemoveOnSuspend(!!aClearOnSuspend);
3369 pKey->release();
3370#endif
3371
3372 hrc = i_configureEncryptionForDisk(aId, &cDisksConfigured);
3373 if (SUCCEEDED(hrc))
3374 {
3375#ifndef VBOX_WITH_FULL_VM_ENCRYPTION
3376 SecretKey *pKey = NULL;
3377#endif
3378 vrc = m_pKeyStore->retainSecretKey(aId, &pKey);
3379 AssertRCReturn(vrc, E_FAIL);
3380
3381 pKey->setUsers(cDisksConfigured);
3382#ifndef VBOX_WITH_FULL_VM_ENCRYPTION
3383 pKey->setRemoveOnSuspend(!!aClearOnSuspend);
3384 m_pKeyStore->releaseSecretKey(aId);
3385#endif
3386 m_cDisksPwProvided += cDisksConfigured;
3387
3388 if ( m_cDisksPwProvided == m_cDisksEncrypted
3389 && mMachineState == MachineState_Paused)
3390 {
3391 /* get the VM handle. */
3392 SafeVMPtr ptrVM(this);
3393 if (!ptrVM.isOk())
3394 return ptrVM.hrc();
3395
3396 alock.release();
3397 vrc = ptrVM.vtable()->pfnVMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_RECONFIG);
3398
3399 hrc = RT_SUCCESS(vrc) ? S_OK
3400 : setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not resume the machine execution (%Rrc)"), vrc);
3401 }
3402 }
3403 }
3404#ifndef VBOX_WITH_FULL_VM_ENCRYPTION
3405 else if (vrc == VERR_ALREADY_EXISTS)
3406 hrc = setErrorBoth(VBOX_E_OBJECT_IN_USE, vrc, tr("A password with the given ID already exists"));
3407#endif
3408 else if (vrc == VERR_NO_MEMORY)
3409 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to allocate enough secure memory for the key"));
3410 else
3411 hrc = setErrorBoth(E_FAIL, vrc, tr("Unknown error happened while adding a password (%Rrc)"), vrc);
3412
3413 return hrc;
3414}
3415
3416HRESULT Console::addEncryptionPasswords(const std::vector<com::Utf8Str> &aIds, const std::vector<com::Utf8Str> &aPasswords,
3417 BOOL aClearOnSuspend)
3418{
3419 HRESULT hrc = S_OK;
3420
3421 if ( aIds.empty()
3422 || aPasswords.empty())
3423 return setError(E_FAIL, tr("IDs and passwords must not be empty"));
3424
3425 if (aIds.size() != aPasswords.size())
3426 return setError(E_FAIL, tr("The number of entries in the id and password arguments must match"));
3427
3428 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3429
3430#ifndef VBOX_WITH_FULL_VM_ENCRYPTION
3431 /* Check that the IDs do not exist already before changing anything. */
3432 for (unsigned i = 0; i < aIds.size(); i++)
3433 {
3434 SecretKey *pKey = NULL;
3435 int vrc = m_pKeyStore->retainSecretKey(aIds[i], &pKey);
3436 if (vrc != VERR_NOT_FOUND)
3437 {
3438 AssertPtr(pKey);
3439 if (pKey)
3440 pKey->release();
3441 return setError(VBOX_E_OBJECT_IN_USE, tr("A password with the given ID already exists"));
3442 }
3443 }
3444#else
3445 /*
3446 * Passwords for the same ID can be added in different ways because
3447 * of encrypted VMs now. Just add them instead of generating an error.
3448 */
3449 /** @todo Check that passwords with the same ID match. */
3450#endif
3451
3452 for (unsigned i = 0; i < aIds.size(); i++)
3453 {
3454 hrc = addEncryptionPassword(aIds[i], aPasswords[i], aClearOnSuspend);
3455 if (FAILED(hrc))
3456 {
3457 /*
3458 * Try to remove already successfully added passwords from the map to not
3459 * change the state of the Console object.
3460 */
3461 ErrorInfoKeeper eik; /* Keep current error info or it gets deestroyed in the IPC methods below. */
3462 for (unsigned ii = 0; ii < i; ii++)
3463 {
3464 i_clearDiskEncryptionKeysOnAllAttachmentsWithKeyId(aIds[ii]);
3465 removeEncryptionPassword(aIds[ii]);
3466 }
3467
3468 break;
3469 }
3470 }
3471
3472 return hrc;
3473}
3474
3475HRESULT Console::removeEncryptionPassword(const com::Utf8Str &aId)
3476{
3477 if (aId.isEmpty())
3478 return setError(E_FAIL, tr("The ID must be valid"));
3479
3480 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3481
3482 SecretKey *pKey = NULL;
3483 int vrc = m_pKeyStore->retainSecretKey(aId, &pKey);
3484 if (RT_SUCCESS(vrc))
3485 {
3486 m_cDisksPwProvided -= pKey->getUsers();
3487 m_pKeyStore->releaseSecretKey(aId);
3488 vrc = m_pKeyStore->deleteSecretKey(aId);
3489 AssertRCReturn(vrc, E_FAIL);
3490
3491#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
3492 if (mptrNvramStore.isNotNull())
3493 mptrNvramStore->i_removePassword(aId);
3494#endif
3495 }
3496 else if (vrc == VERR_NOT_FOUND)
3497 return setErrorBoth(VBOX_E_OBJECT_NOT_FOUND, vrc, tr("A password with the ID \"%s\" does not exist"), aId.c_str());
3498 else
3499 return setErrorBoth(E_FAIL, vrc, tr("Failed to remove password with ID \"%s\" (%Rrc)"), aId.c_str(), vrc);
3500
3501 return S_OK;
3502}
3503
3504HRESULT Console::clearAllEncryptionPasswords()
3505{
3506 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3507
3508#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
3509 if (mptrNvramStore.isNotNull())
3510 mptrNvramStore->i_removeAllPasswords();
3511#endif
3512
3513 int vrc = m_pKeyStore->deleteAllSecretKeys(false /* fSuspend */, false /* fForce */);
3514 if (vrc == VERR_RESOURCE_IN_USE)
3515 return setErrorBoth(VBOX_E_OBJECT_IN_USE, vrc, tr("A password is still in use by the VM"));
3516 else if (RT_FAILURE(vrc))
3517 return setErrorBoth(E_FAIL, vrc, tr("Deleting all passwords failed (%Rrc)"));
3518
3519 m_cDisksPwProvided = 0;
3520 return S_OK;
3521}
3522
3523// Non-interface public methods
3524/////////////////////////////////////////////////////////////////////////////
3525
3526/*static*/
3527HRESULT Console::i_setErrorStatic(HRESULT aResultCode, const char *pcsz, ...)
3528{
3529 va_list args;
3530 va_start(args, pcsz);
3531 HRESULT hrc = setErrorInternalV(aResultCode,
3532 getStaticClassIID(),
3533 getStaticComponentName(),
3534 pcsz, args,
3535 false /* aWarning */,
3536 true /* aLogIt */);
3537 va_end(args);
3538 return hrc;
3539}
3540
3541/*static*/
3542HRESULT Console::i_setErrorStaticBoth(HRESULT aResultCode, int vrc, const char *pcsz, ...)
3543{
3544 va_list args;
3545 va_start(args, pcsz);
3546 HRESULT hrc = setErrorInternalV(aResultCode,
3547 getStaticClassIID(),
3548 getStaticComponentName(),
3549 pcsz, args,
3550 false /* aWarning */,
3551 true /* aLogIt */,
3552 vrc);
3553 va_end(args);
3554 return hrc;
3555}
3556
3557HRESULT Console::i_setInvalidMachineStateError()
3558{
3559 return setError(VBOX_E_INVALID_VM_STATE,
3560 tr("Invalid machine state: %s"),
3561 Global::stringifyMachineState(mMachineState));
3562}
3563
3564
3565/**
3566 * Converts to PDM device names.
3567 */
3568/* static */ const char *Console::i_storageControllerTypeToStr(StorageControllerType_T enmCtrlType)
3569{
3570 switch (enmCtrlType)
3571 {
3572 case StorageControllerType_LsiLogic:
3573 return "lsilogicscsi";
3574 case StorageControllerType_BusLogic:
3575 return "buslogic";
3576 case StorageControllerType_LsiLogicSas:
3577 return "lsilogicsas";
3578 case StorageControllerType_IntelAhci:
3579 return "ahci";
3580 case StorageControllerType_PIIX3:
3581 case StorageControllerType_PIIX4:
3582 case StorageControllerType_ICH6:
3583 return "piix3ide";
3584 case StorageControllerType_I82078:
3585 return "i82078";
3586 case StorageControllerType_USB:
3587 return "Msd";
3588 case StorageControllerType_NVMe:
3589 return "nvme";
3590 case StorageControllerType_VirtioSCSI:
3591 return "virtio-scsi";
3592 default:
3593 return NULL;
3594 }
3595}
3596
3597HRESULT Console::i_storageBusPortDeviceToLun(StorageBus_T enmBus, LONG port, LONG device, unsigned &uLun)
3598{
3599 switch (enmBus)
3600 {
3601 case StorageBus_IDE:
3602 case StorageBus_Floppy:
3603 {
3604 AssertMsgReturn(port < 2 && port >= 0, ("%d\n", port), E_INVALIDARG);
3605 AssertMsgReturn(device < 2 && device >= 0, ("%d\n", device), E_INVALIDARG);
3606 uLun = 2 * port + device;
3607 return S_OK;
3608 }
3609 case StorageBus_SATA:
3610 case StorageBus_SCSI:
3611 case StorageBus_SAS:
3612 case StorageBus_PCIe:
3613 case StorageBus_VirtioSCSI:
3614 {
3615 uLun = port;
3616 return S_OK;
3617 }
3618 case StorageBus_USB:
3619 {
3620 /*
3621 * It is always the first lun, the port denotes the device instance
3622 * for the Msd device.
3623 */
3624 uLun = 0;
3625 return S_OK;
3626 }
3627 default:
3628 uLun = 0;
3629 AssertMsgFailedReturn(("%d\n", enmBus), E_INVALIDARG);
3630 }
3631}
3632
3633// private methods
3634/////////////////////////////////////////////////////////////////////////////
3635
3636/**
3637 * Suspend the VM before we do any medium or network attachment change.
3638 *
3639 * @param pUVM Safe VM handle.
3640 * @param pVMM Safe VMM vtable.
3641 * @param pAlock The automatic lock instance. This is for when we have
3642 * to leave it in order to avoid deadlocks.
3643 * @param pfResume where to store the information if we need to resume
3644 * afterwards.
3645 */
3646HRESULT Console::i_suspendBeforeConfigChange(PUVM pUVM, PCVMMR3VTABLE pVMM, AutoWriteLock *pAlock, bool *pfResume)
3647{
3648 *pfResume = false;
3649
3650 VMSTATE enmVMState = pVMM->pfnVMR3GetStateU(pUVM);
3651 switch (enmVMState)
3652 {
3653 case VMSTATE_RUNNING:
3654 case VMSTATE_RESETTING:
3655 case VMSTATE_SOFT_RESETTING:
3656 {
3657 LogFlowFunc(("Suspending the VM...\n"));
3658 /* disable the callback to prevent Console-level state change */
3659 mVMStateChangeCallbackDisabled = true;
3660 if (pAlock)
3661 pAlock->release();
3662 int vrc = pVMM->pfnVMR3Suspend(pUVM, VMSUSPENDREASON_RECONFIG);
3663 if (pAlock)
3664 pAlock->acquire();
3665 mVMStateChangeCallbackDisabled = false;
3666 if (RT_FAILURE(vrc))
3667 return setErrorInternalF(VBOX_E_INVALID_VM_STATE,
3668 COM_IIDOF(IConsole),
3669 getStaticComponentName(),
3670 false /*aWarning*/,
3671 true /*aLogIt*/,
3672 vrc,
3673 tr("Could suspend VM for medium change (%Rrc)"), vrc);
3674 *pfResume = true;
3675 break;
3676 }
3677 case VMSTATE_SUSPENDED:
3678 break;
3679 default:
3680 return setErrorInternalF(VBOX_E_INVALID_VM_STATE,
3681 COM_IIDOF(IConsole),
3682 getStaticComponentName(),
3683 false /*aWarning*/,
3684 true /*aLogIt*/,
3685 0 /* aResultDetail */,
3686 tr("Invalid state '%s' for changing medium"),
3687 pVMM->pfnVMR3GetStateName(enmVMState));
3688 }
3689
3690 return S_OK;
3691}
3692
3693/**
3694 * Resume the VM after we did any medium or network attachment change.
3695 * This is the counterpart to Console::suspendBeforeConfigChange().
3696 *
3697 * @param pUVM Safe VM handle.
3698 * @param pVMM Safe VMM vtable.
3699 */
3700void Console::i_resumeAfterConfigChange(PUVM pUVM, PCVMMR3VTABLE pVMM)
3701{
3702 LogFlowFunc(("Resuming the VM...\n"));
3703
3704 /* disable the callback to prevent Console-level state change */
3705 mVMStateChangeCallbackDisabled = true;
3706 int vrc = pVMM->pfnVMR3Resume(pUVM, VMRESUMEREASON_RECONFIG);
3707 mVMStateChangeCallbackDisabled = false;
3708 AssertRC(vrc);
3709 if (RT_FAILURE(vrc))
3710 {
3711 VMSTATE enmVMState = pVMM->pfnVMR3GetStateU(pUVM);
3712 if (enmVMState == VMSTATE_SUSPENDED)
3713 {
3714 /* too bad, we failed. try to sync the console state with the VMM state */
3715 i_vmstateChangeCallback(pUVM, pVMM, VMSTATE_SUSPENDED, enmVMState, this);
3716 }
3717 }
3718}
3719
3720/**
3721 * Process a medium change.
3722 *
3723 * @param aMediumAttachment The medium attachment with the new medium state.
3724 * @param fForce Force medium chance, if it is locked or not.
3725 * @param pUVM Safe VM handle.
3726 * @param pVMM Safe VMM vtable.
3727 *
3728 * @note Locks this object for writing.
3729 */
3730HRESULT Console::i_doMediumChange(IMediumAttachment *aMediumAttachment, bool fForce, PUVM pUVM, PCVMMR3VTABLE pVMM)
3731{
3732 AutoCaller autoCaller(this);
3733 AssertComRCReturnRC(autoCaller.hrc());
3734
3735 /* We will need to release the write lock before calling EMT */
3736 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3737
3738 const char *pszDevice = NULL;
3739
3740 SafeIfaceArray<IStorageController> ctrls;
3741 HRESULT hrc = mMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));
3742 AssertComRC(hrc);
3743
3744 IMedium *pMedium = NULL;
3745 hrc = aMediumAttachment->COMGETTER(Medium)(&pMedium);
3746 AssertComRC(hrc);
3747
3748 Bstr mediumLocation;
3749 if (pMedium)
3750 {
3751 hrc = pMedium->COMGETTER(Location)(mediumLocation.asOutParam());
3752 AssertComRC(hrc);
3753 }
3754
3755 Bstr attCtrlName;
3756 hrc = aMediumAttachment->COMGETTER(Controller)(attCtrlName.asOutParam());
3757 AssertComRC(hrc);
3758 ComPtr<IStorageController> pStorageController;
3759 for (size_t i = 0; i < ctrls.size(); ++i)
3760 {
3761 Bstr ctrlName;
3762 hrc = ctrls[i]->COMGETTER(Name)(ctrlName.asOutParam());
3763 AssertComRC(hrc);
3764 if (attCtrlName == ctrlName)
3765 {
3766 pStorageController = ctrls[i];
3767 break;
3768 }
3769 }
3770 if (pStorageController.isNull())
3771 return setError(E_FAIL, tr("Could not find storage controller '%ls'"), attCtrlName.raw());
3772
3773 StorageControllerType_T enmCtrlType;
3774 hrc = pStorageController->COMGETTER(ControllerType)(&enmCtrlType);
3775 AssertComRC(hrc);
3776 pszDevice = i_storageControllerTypeToStr(enmCtrlType);
3777
3778 StorageBus_T enmBus;
3779 hrc = pStorageController->COMGETTER(Bus)(&enmBus);
3780 AssertComRC(hrc);
3781
3782 ULONG uInstance;
3783 hrc = pStorageController->COMGETTER(Instance)(&uInstance);
3784 AssertComRC(hrc);
3785
3786 BOOL fUseHostIOCache;
3787 hrc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
3788 AssertComRC(hrc);
3789
3790 /*
3791 * Suspend the VM first. The VM must not be running since it might have
3792 * pending I/O to the drive which is being changed.
3793 */
3794 bool fResume = false;
3795 hrc = i_suspendBeforeConfigChange(pUVM, pVMM, &alock, &fResume);
3796 if (FAILED(hrc))
3797 return hrc;
3798
3799 /*
3800 * Call worker on EMT #0, that's faster and safer than doing everything
3801 * using VMR3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
3802 * here to make requests from under the lock in order to serialize them.
3803 */
3804 PVMREQ pReq;
3805 int vrc = pVMM->pfnVMR3ReqCallU(pUVM, 0, &pReq, 0 /* no wait! */, VMREQFLAGS_VBOX_STATUS,
3806 (PFNRT)i_changeRemovableMedium, 9,
3807 this, pUVM, pVMM, pszDevice, uInstance, enmBus, fUseHostIOCache, aMediumAttachment, fForce);
3808
3809 /* release the lock before waiting for a result (EMT might wait for it, @bugref{7648})! */
3810 alock.release();
3811
3812 if (vrc == VERR_TIMEOUT)
3813 vrc = pVMM->pfnVMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
3814 AssertRC(vrc);
3815 if (RT_SUCCESS(vrc))
3816 vrc = pReq->iStatus;
3817 pVMM->pfnVMR3ReqFree(pReq);
3818
3819 if (fResume)
3820 i_resumeAfterConfigChange(pUVM, pVMM);
3821
3822 if (RT_SUCCESS(vrc))
3823 {
3824 LogFlowThisFunc(("Returns S_OK\n"));
3825 return S_OK;
3826 }
3827
3828 if (pMedium)
3829 return setErrorBoth(E_FAIL, vrc, tr("Could not mount the media/drive '%ls' (%Rrc)"), mediumLocation.raw(), vrc);
3830 return setErrorBoth(E_FAIL, vrc, tr("Could not unmount the currently mounted media/drive (%Rrc)"), vrc);
3831}
3832
3833/**
3834 * Performs the medium change in EMT.
3835 *
3836 * @returns VBox status code.
3837 *
3838 * @param pThis Pointer to the Console object.
3839 * @param pUVM The VM handle.
3840 * @param pVMM The VMM vtable.
3841 * @param pcszDevice The PDM device name.
3842 * @param uInstance The PDM device instance.
3843 * @param enmBus The storage bus type of the controller.
3844 * @param fUseHostIOCache Whether to use the host I/O cache (disable async I/O).
3845 * @param aMediumAtt The medium attachment.
3846 * @param fForce Force unmounting.
3847 *
3848 * @thread EMT
3849 * @note The VM must not be running since it might have pending I/O to the drive which is being changed.
3850 */
3851DECLCALLBACK(int) Console::i_changeRemovableMedium(Console *pThis,
3852 PUVM pUVM,
3853 PCVMMR3VTABLE pVMM,
3854 const char *pcszDevice,
3855 unsigned uInstance,
3856 StorageBus_T enmBus,
3857 bool fUseHostIOCache,
3858 IMediumAttachment *aMediumAtt,
3859 bool fForce)
3860{
3861 LogFlowFunc(("pThis=%p uInstance=%u pszDevice=%p:{%s} enmBus=%u, aMediumAtt=%p, fForce=%d\n",
3862 pThis, uInstance, pcszDevice, pcszDevice, enmBus, aMediumAtt, fForce));
3863
3864 AssertReturn(pThis, VERR_INVALID_PARAMETER);
3865
3866 AutoCaller autoCaller(pThis);
3867 AssertComRCReturn(autoCaller.hrc(), VERR_ACCESS_DENIED);
3868
3869 /*
3870 * Check the VM for correct state.
3871 */
3872 VMSTATE enmVMState = pVMM->pfnVMR3GetStateU(pUVM);
3873 AssertReturn(enmVMState == VMSTATE_SUSPENDED, VERR_INVALID_STATE);
3874
3875 int vrc = pThis->i_configMediumAttachment(pcszDevice,
3876 uInstance,
3877 enmBus,
3878 fUseHostIOCache,
3879 false /* fSetupMerge */,
3880 false /* fBuiltinIOCache */,
3881 false /* fInsertDiskIntegrityDrv. */,
3882 0 /* uMergeSource */,
3883 0 /* uMergeTarget */,
3884 aMediumAtt,
3885 pThis->mMachineState,
3886 NULL /* phrc */,
3887 true /* fAttachDetach */,
3888 fForce /* fForceUnmount */,
3889 false /* fHotplug */,
3890 pUVM,
3891 pVMM,
3892 NULL /* paLedDevType */,
3893 NULL /* ppLunL0 */);
3894 LogFlowFunc(("Returning %Rrc\n", vrc));
3895 return vrc;
3896}
3897
3898
3899/**
3900 * Attach a new storage device to the VM.
3901 *
3902 * @param aMediumAttachment The medium attachment which is added.
3903 * @param pUVM Safe VM handle.
3904 * @param pVMM Safe VMM vtable.
3905 * @param fSilent Flag whether to notify the guest about the attached device.
3906 *
3907 * @note Locks this object for writing.
3908 */
3909HRESULT Console::i_doStorageDeviceAttach(IMediumAttachment *aMediumAttachment, PUVM pUVM, PCVMMR3VTABLE pVMM, bool fSilent)
3910{
3911 AutoCaller autoCaller(this);
3912 AssertComRCReturnRC(autoCaller.hrc());
3913
3914 /* We will need to release the write lock before calling EMT */
3915 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3916
3917 const char *pszDevice = NULL;
3918
3919 SafeIfaceArray<IStorageController> ctrls;
3920 HRESULT hrc = mMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));
3921 AssertComRC(hrc);
3922
3923 IMedium *pMedium = NULL;
3924 hrc = aMediumAttachment->COMGETTER(Medium)(&pMedium);
3925 AssertComRC(hrc);
3926
3927 Bstr mediumLocation;
3928 if (pMedium)
3929 {
3930 hrc = pMedium->COMGETTER(Location)(mediumLocation.asOutParam());
3931 AssertComRC(hrc);
3932 }
3933
3934 Bstr attCtrlName;
3935 hrc = aMediumAttachment->COMGETTER(Controller)(attCtrlName.asOutParam());
3936 AssertComRC(hrc);
3937 ComPtr<IStorageController> pStorageController;
3938 for (size_t i = 0; i < ctrls.size(); ++i)
3939 {
3940 Bstr ctrlName;
3941 hrc = ctrls[i]->COMGETTER(Name)(ctrlName.asOutParam());
3942 AssertComRC(hrc);
3943 if (attCtrlName == ctrlName)
3944 {
3945 pStorageController = ctrls[i];
3946 break;
3947 }
3948 }
3949 if (pStorageController.isNull())
3950 return setError(E_FAIL, tr("Could not find storage controller '%ls'"), attCtrlName.raw());
3951
3952 StorageControllerType_T enmCtrlType;
3953 hrc = pStorageController->COMGETTER(ControllerType)(&enmCtrlType);
3954 AssertComRC(hrc);
3955 pszDevice = i_storageControllerTypeToStr(enmCtrlType);
3956
3957 StorageBus_T enmBus;
3958 hrc = pStorageController->COMGETTER(Bus)(&enmBus);
3959 AssertComRC(hrc);
3960
3961 ULONG uInstance;
3962 hrc = pStorageController->COMGETTER(Instance)(&uInstance);
3963 AssertComRC(hrc);
3964
3965 BOOL fUseHostIOCache;
3966 hrc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
3967 AssertComRC(hrc);
3968
3969 /*
3970 * Suspend the VM first. The VM must not be running since it might have
3971 * pending I/O to the drive which is being changed.
3972 */
3973 bool fResume = false;
3974 hrc = i_suspendBeforeConfigChange(pUVM, pVMM, &alock, &fResume);
3975 if (FAILED(hrc))
3976 return hrc;
3977
3978 /*
3979 * Call worker on EMT #0, that's faster and safer than doing everything
3980 * using VMR3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
3981 * here to make requests from under the lock in order to serialize them.
3982 */
3983 PVMREQ pReq;
3984 int vrc = pVMM->pfnVMR3ReqCallU(pUVM, 0, &pReq, 0 /* no wait! */, VMREQFLAGS_VBOX_STATUS,
3985 (PFNRT)i_attachStorageDevice, 9,
3986 this, pUVM, pVMM, pszDevice, uInstance, enmBus, fUseHostIOCache, aMediumAttachment, fSilent);
3987
3988 /* release the lock before waiting for a result (EMT might wait for it, @bugref{7648})! */
3989 alock.release();
3990
3991 if (vrc == VERR_TIMEOUT)
3992 vrc = pVMM->pfnVMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
3993 AssertRC(vrc);
3994 if (RT_SUCCESS(vrc))
3995 vrc = pReq->iStatus;
3996 pVMM->pfnVMR3ReqFree(pReq);
3997
3998 if (fResume)
3999 i_resumeAfterConfigChange(pUVM, pVMM);
4000
4001 if (RT_SUCCESS(vrc))
4002 {
4003 LogFlowThisFunc(("Returns S_OK\n"));
4004 return S_OK;
4005 }
4006
4007 if (!pMedium)
4008 return setErrorBoth(E_FAIL, vrc, tr("Could not mount the media/drive '%ls' (%Rrc)"), mediumLocation.raw(), vrc);
4009 return setErrorBoth(E_FAIL, vrc, tr("Could not unmount the currently mounted media/drive (%Rrc)"), vrc);
4010}
4011
4012
4013/**
4014 * Performs the storage attach operation in EMT.
4015 *
4016 * @returns VBox status code.
4017 *
4018 * @param pThis Pointer to the Console object.
4019 * @param pUVM The VM handle.
4020 * @param pVMM The VMM vtable.
4021 * @param pcszDevice The PDM device name.
4022 * @param uInstance The PDM device instance.
4023 * @param enmBus The storage bus type of the controller.
4024 * @param fUseHostIOCache Whether to use the host I/O cache (disable async I/O).
4025 * @param aMediumAtt The medium attachment.
4026 * @param fSilent Flag whether to inform the guest about the attached device.
4027 *
4028 * @thread EMT
4029 * @note The VM must not be running since it might have pending I/O to the drive which is being changed.
4030 */
4031DECLCALLBACK(int) Console::i_attachStorageDevice(Console *pThis,
4032 PUVM pUVM,
4033 PCVMMR3VTABLE pVMM,
4034 const char *pcszDevice,
4035 unsigned uInstance,
4036 StorageBus_T enmBus,
4037 bool fUseHostIOCache,
4038 IMediumAttachment *aMediumAtt,
4039 bool fSilent)
4040{
4041 LogFlowFunc(("pThis=%p uInstance=%u pszDevice=%p:{%s} enmBus=%u, aMediumAtt=%p\n",
4042 pThis, uInstance, pcszDevice, pcszDevice, enmBus, aMediumAtt));
4043
4044 AssertReturn(pThis, VERR_INVALID_PARAMETER);
4045
4046 AutoCaller autoCaller(pThis);
4047 AssertComRCReturn(autoCaller.hrc(), VERR_ACCESS_DENIED);
4048
4049 /*
4050 * Check the VM for correct state.
4051 */
4052 VMSTATE enmVMState = pVMM->pfnVMR3GetStateU(pUVM);
4053 AssertReturn(enmVMState == VMSTATE_SUSPENDED, VERR_INVALID_STATE);
4054
4055 int vrc = pThis->i_configMediumAttachment(pcszDevice,
4056 uInstance,
4057 enmBus,
4058 fUseHostIOCache,
4059 false /* fSetupMerge */,
4060 false /* fBuiltinIOCache */,
4061 false /* fInsertDiskIntegrityDrv. */,
4062 0 /* uMergeSource */,
4063 0 /* uMergeTarget */,
4064 aMediumAtt,
4065 pThis->mMachineState,
4066 NULL /* phrc */,
4067 true /* fAttachDetach */,
4068 false /* fForceUnmount */,
4069 !fSilent /* fHotplug */,
4070 pUVM,
4071 pVMM,
4072 NULL /* paLedDevType */,
4073 NULL);
4074 LogFlowFunc(("Returning %Rrc\n", vrc));
4075 return vrc;
4076}
4077
4078/**
4079 * Attach a new storage device to the VM.
4080 *
4081 * @param aMediumAttachment The medium attachment which is added.
4082 * @param pUVM Safe VM handle.
4083 * @param pVMM Safe VMM vtable.
4084 * @param fSilent Flag whether to notify the guest about the detached device.
4085 *
4086 * @note Locks this object for writing.
4087 */
4088HRESULT Console::i_doStorageDeviceDetach(IMediumAttachment *aMediumAttachment, PUVM pUVM, PCVMMR3VTABLE pVMM, bool fSilent)
4089{
4090 AutoCaller autoCaller(this);
4091 AssertComRCReturnRC(autoCaller.hrc());
4092
4093 /* We will need to release the write lock before calling EMT */
4094 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4095
4096 const char *pszDevice = NULL;
4097
4098 SafeIfaceArray<IStorageController> ctrls;
4099 HRESULT hrc = mMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));
4100 AssertComRC(hrc);
4101
4102 IMedium *pMedium = NULL;
4103 hrc = aMediumAttachment->COMGETTER(Medium)(&pMedium);
4104 AssertComRC(hrc);
4105
4106 Bstr mediumLocation;
4107 if (pMedium)
4108 {
4109 hrc = pMedium->COMGETTER(Location)(mediumLocation.asOutParam());
4110 AssertComRC(hrc);
4111 }
4112
4113 Bstr attCtrlName;
4114 hrc = aMediumAttachment->COMGETTER(Controller)(attCtrlName.asOutParam());
4115 AssertComRC(hrc);
4116 ComPtr<IStorageController> pStorageController;
4117 for (size_t i = 0; i < ctrls.size(); ++i)
4118 {
4119 Bstr ctrlName;
4120 hrc = ctrls[i]->COMGETTER(Name)(ctrlName.asOutParam());
4121 AssertComRC(hrc);
4122 if (attCtrlName == ctrlName)
4123 {
4124 pStorageController = ctrls[i];
4125 break;
4126 }
4127 }
4128 if (pStorageController.isNull())
4129 return setError(E_FAIL, tr("Could not find storage controller '%ls'"), attCtrlName.raw());
4130
4131 StorageControllerType_T enmCtrlType;
4132 hrc = pStorageController->COMGETTER(ControllerType)(&enmCtrlType);
4133 AssertComRC(hrc);
4134 pszDevice = i_storageControllerTypeToStr(enmCtrlType);
4135
4136 StorageBus_T enmBus = (StorageBus_T)0;
4137 hrc = pStorageController->COMGETTER(Bus)(&enmBus);
4138 AssertComRC(hrc);
4139
4140 ULONG uInstance = 0;
4141 hrc = pStorageController->COMGETTER(Instance)(&uInstance);
4142 AssertComRC(hrc);
4143
4144 /*
4145 * Suspend the VM first. The VM must not be running since it might have
4146 * pending I/O to the drive which is being changed.
4147 */
4148 bool fResume = false;
4149 hrc = i_suspendBeforeConfigChange(pUVM, pVMM, &alock, &fResume);
4150 if (FAILED(hrc))
4151 return hrc;
4152
4153 /*
4154 * Call worker on EMT #0, that's faster and safer than doing everything
4155 * using VMR3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
4156 * here to make requests from under the lock in order to serialize them.
4157 */
4158 PVMREQ pReq;
4159 int vrc = pVMM->pfnVMR3ReqCallU(pUVM, 0, &pReq, 0 /* no wait! */, VMREQFLAGS_VBOX_STATUS,
4160 (PFNRT)i_detachStorageDevice, 8,
4161 this, pUVM, pVMM, pszDevice, uInstance, enmBus, aMediumAttachment, fSilent);
4162
4163 /* release the lock before waiting for a result (EMT might wait for it, @bugref{7648})! */
4164 alock.release();
4165
4166 if (vrc == VERR_TIMEOUT)
4167 vrc = pVMM->pfnVMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
4168 AssertRC(vrc);
4169 if (RT_SUCCESS(vrc))
4170 vrc = pReq->iStatus;
4171 pVMM->pfnVMR3ReqFree(pReq);
4172
4173 if (fResume)
4174 i_resumeAfterConfigChange(pUVM, pVMM);
4175
4176 if (RT_SUCCESS(vrc))
4177 {
4178 LogFlowThisFunc(("Returns S_OK\n"));
4179 return S_OK;
4180 }
4181
4182 if (!pMedium)
4183 return setErrorBoth(E_FAIL, vrc, tr("Could not mount the media/drive '%ls' (%Rrc)"), mediumLocation.raw(), vrc);
4184 return setErrorBoth(E_FAIL, vrc, tr("Could not unmount the currently mounted media/drive (%Rrc)"), vrc);
4185}
4186
4187/**
4188 * Performs the storage detach operation in EMT.
4189 *
4190 * @returns VBox status code.
4191 *
4192 * @param pThis Pointer to the Console object.
4193 * @param pUVM The VM handle.
4194 * @param pVMM The VMM vtable.
4195 * @param pcszDevice The PDM device name.
4196 * @param uInstance The PDM device instance.
4197 * @param enmBus The storage bus type of the controller.
4198 * @param pMediumAtt Pointer to the medium attachment.
4199 * @param fSilent Flag whether to notify the guest about the detached device.
4200 *
4201 * @thread EMT
4202 * @note The VM must not be running since it might have pending I/O to the drive which is being changed.
4203 */
4204DECLCALLBACK(int) Console::i_detachStorageDevice(Console *pThis,
4205 PUVM pUVM,
4206 PCVMMR3VTABLE pVMM,
4207 const char *pcszDevice,
4208 unsigned uInstance,
4209 StorageBus_T enmBus,
4210 IMediumAttachment *pMediumAtt,
4211 bool fSilent)
4212{
4213 LogRelFlowFunc(("pThis=%p uInstance=%u pszDevice=%p:{%s} enmBus=%u, pMediumAtt=%p\n",
4214 pThis, uInstance, pcszDevice, pcszDevice, enmBus, pMediumAtt));
4215
4216 AssertReturn(pThis, VERR_INVALID_PARAMETER);
4217
4218 AutoCaller autoCaller(pThis);
4219 AssertComRCReturn(autoCaller.hrc(), VERR_ACCESS_DENIED);
4220
4221 /*
4222 * Check the VM for correct state.
4223 */
4224 VMSTATE enmVMState = pVMM->pfnVMR3GetStateU(pUVM);
4225 AssertReturn(enmVMState == VMSTATE_SUSPENDED, VERR_INVALID_STATE);
4226
4227 /* Determine the base path for the device instance. */
4228 PCFGMNODE pCtlInst = pVMM->pfnCFGMR3GetChildF(pVMM->pfnCFGMR3GetRootU(pUVM), "Devices/%s/%u/", pcszDevice, uInstance);
4229 AssertReturn(pCtlInst || enmBus == StorageBus_USB, VERR_INTERNAL_ERROR);
4230
4231#define H() AssertMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE)
4232
4233 HRESULT hrc;
4234 int vrc = VINF_SUCCESS;
4235 LONG lDev;
4236 hrc = pMediumAtt->COMGETTER(Device)(&lDev); H();
4237 LONG lPort;
4238 hrc = pMediumAtt->COMGETTER(Port)(&lPort); H();
4239 DeviceType_T lType;
4240 hrc = pMediumAtt->COMGETTER(Type)(&lType); H();
4241 unsigned uLUN;
4242 hrc = Console::i_storageBusPortDeviceToLun(enmBus, lPort, lDev, uLUN); H();
4243
4244#undef H
4245
4246 PCFGMNODE pLunL0 = NULL;
4247 if (enmBus != StorageBus_USB)
4248 {
4249 /* First check if the LUN really exists. */
4250 pLunL0 = pVMM->pfnCFGMR3GetChildF(pCtlInst, "LUN#%u", uLUN);
4251 if (pLunL0)
4252 {
4253 uint32_t fFlags = 0;
4254 if (fSilent)
4255 fFlags |= PDM_TACH_FLAGS_NOT_HOT_PLUG;
4256
4257 vrc = pVMM->pfnPDMR3DeviceDetach(pUVM, pcszDevice, uInstance, uLUN, fFlags);
4258 if (vrc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
4259 vrc = VINF_SUCCESS;
4260 AssertLogRelRCReturn(vrc, vrc);
4261 pVMM->pfnCFGMR3RemoveNode(pLunL0);
4262
4263 Utf8StrFmt devicePath("%s/%u/LUN#%u", pcszDevice, uInstance, uLUN);
4264 pThis->mapMediumAttachments.erase(devicePath);
4265 }
4266 else
4267 AssertLogRelFailedReturn(VERR_INTERNAL_ERROR);
4268
4269 pVMM->pfnCFGMR3Dump(pCtlInst);
4270 }
4271#ifdef VBOX_WITH_USB
4272 else
4273 {
4274 /* Find the correct USB device in the list. */
4275 USBStorageDeviceList::iterator it;
4276 for (it = pThis->mUSBStorageDevices.begin(); it != pThis->mUSBStorageDevices.end(); ++it)
4277 if (it->iPort == lPort)
4278 break;
4279 AssertLogRelReturn(it != pThis->mUSBStorageDevices.end(), VERR_INTERNAL_ERROR);
4280
4281 vrc = pVMM->pfnPDMR3UsbDetachDevice(pUVM, &it->mUuid);
4282 AssertLogRelRCReturn(vrc, vrc);
4283 pThis->mUSBStorageDevices.erase(it);
4284 }
4285#endif
4286
4287 LogFlowFunc(("Returning VINF_SUCCESS\n"));
4288 return VINF_SUCCESS;
4289}
4290
4291/**
4292 * Called by IInternalSessionControl::OnNetworkAdapterChange().
4293 *
4294 * @note Locks this object for writing.
4295 */
4296HRESULT Console::i_onNetworkAdapterChange(INetworkAdapter *aNetworkAdapter, BOOL changeAdapter)
4297{
4298 LogFlowThisFunc(("\n"));
4299
4300 AutoCaller autoCaller(this);
4301 AssertComRCReturnRC(autoCaller.hrc());
4302
4303 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4304
4305 HRESULT hrc = S_OK;
4306
4307 /* don't trigger network changes if the VM isn't running */
4308 SafeVMPtrQuiet ptrVM(this);
4309 if (ptrVM.isOk())
4310 {
4311 /* Get the properties we need from the adapter */
4312 BOOL fCableConnected, fTraceEnabled;
4313 hrc = aNetworkAdapter->COMGETTER(CableConnected)(&fCableConnected);
4314 AssertComRC(hrc);
4315 if (SUCCEEDED(hrc))
4316 {
4317 hrc = aNetworkAdapter->COMGETTER(TraceEnabled)(&fTraceEnabled);
4318 AssertComRC(hrc);
4319 if (SUCCEEDED(hrc))
4320 {
4321 ULONG ulInstance;
4322 hrc = aNetworkAdapter->COMGETTER(Slot)(&ulInstance);
4323 AssertComRC(hrc);
4324 if (SUCCEEDED(hrc))
4325 {
4326 /*
4327 * Find the adapter instance, get the config interface and update
4328 * the link state.
4329 */
4330 NetworkAdapterType_T adapterType;
4331 hrc = aNetworkAdapter->COMGETTER(AdapterType)(&adapterType);
4332 AssertComRC(hrc);
4333 const char *pszAdapterName = networkAdapterTypeToName(adapterType);
4334
4335 // prevent cross-thread deadlocks, don't need the lock any more
4336 alock.release();
4337
4338 PPDMIBASE pBase = NULL;
4339 int vrc = ptrVM.vtable()->pfnPDMR3QueryDeviceLun(ptrVM.rawUVM(), pszAdapterName, ulInstance, 0, &pBase);
4340 if (RT_SUCCESS(vrc))
4341 {
4342 Assert(pBase);
4343 PPDMINETWORKCONFIG pINetCfg;
4344 pINetCfg = PDMIBASE_QUERY_INTERFACE(pBase, PDMINETWORKCONFIG);
4345 if (pINetCfg)
4346 {
4347 Log(("Console::onNetworkAdapterChange: setting link state to %d\n",
4348 fCableConnected));
4349 vrc = pINetCfg->pfnSetLinkState(pINetCfg,
4350 fCableConnected ? PDMNETWORKLINKSTATE_UP
4351 : PDMNETWORKLINKSTATE_DOWN);
4352 ComAssertRC(vrc);
4353 }
4354 if (RT_SUCCESS(vrc) && changeAdapter)
4355 {
4356 VMSTATE enmVMState = mpVMM->pfnVMR3GetStateU(ptrVM.rawUVM());
4357 if ( enmVMState == VMSTATE_RUNNING /** @todo LiveMigration: Forbid or deal
4358 correctly with the _LS variants */
4359 || enmVMState == VMSTATE_SUSPENDED)
4360 {
4361 if (fTraceEnabled && fCableConnected && pINetCfg)
4362 {
4363 vrc = pINetCfg->pfnSetLinkState(pINetCfg, PDMNETWORKLINKSTATE_DOWN);
4364 ComAssertRC(vrc);
4365 }
4366
4367 hrc = i_doNetworkAdapterChange(ptrVM.rawUVM(), ptrVM.vtable(), pszAdapterName,
4368 ulInstance, 0, aNetworkAdapter);
4369
4370 if (fTraceEnabled && fCableConnected && pINetCfg)
4371 {
4372 vrc = pINetCfg->pfnSetLinkState(pINetCfg, PDMNETWORKLINKSTATE_UP);
4373 ComAssertRC(vrc);
4374 }
4375 }
4376 }
4377 }
4378 else if (vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND)
4379 return setErrorBoth(E_FAIL, vrc, tr("The network adapter #%u is not enabled"), ulInstance);
4380 else
4381 ComAssertRC(vrc);
4382
4383 if (RT_FAILURE(vrc))
4384 hrc = E_FAIL;
4385
4386 alock.acquire();
4387 }
4388 }
4389 }
4390 ptrVM.release();
4391 }
4392
4393 // definitely don't need the lock any more
4394 alock.release();
4395
4396 /* notify console callbacks on success */
4397 if (SUCCEEDED(hrc))
4398 ::FireNetworkAdapterChangedEvent(mEventSource, aNetworkAdapter);
4399
4400 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
4401 return hrc;
4402}
4403
4404/**
4405 * Called by IInternalSessionControl::OnNATEngineChange().
4406 *
4407 * @note Locks this object for writing.
4408 */
4409HRESULT Console::i_onNATRedirectRuleChanged(ULONG ulInstance, BOOL aNatRuleRemove, NATProtocol_T aProto, IN_BSTR aHostIP,
4410 LONG aHostPort, IN_BSTR aGuestIP, LONG aGuestPort)
4411{
4412 LogFlowThisFunc(("\n"));
4413
4414 AutoCaller autoCaller(this);
4415 AssertComRCReturnRC(autoCaller.hrc());
4416
4417 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4418
4419 HRESULT hrc = S_OK;
4420
4421 /* don't trigger NAT engine changes if the VM isn't running */
4422 SafeVMPtrQuiet ptrVM(this);
4423 if (ptrVM.isOk())
4424 {
4425 do
4426 {
4427 ComPtr<INetworkAdapter> pNetworkAdapter;
4428 hrc = i_machine()->GetNetworkAdapter(ulInstance, pNetworkAdapter.asOutParam());
4429 if ( FAILED(hrc)
4430 || pNetworkAdapter.isNull())
4431 break;
4432
4433 /*
4434 * Find the adapter instance, get the config interface and update
4435 * the link state.
4436 */
4437 NetworkAdapterType_T adapterType;
4438 hrc = pNetworkAdapter->COMGETTER(AdapterType)(&adapterType);
4439 if (FAILED(hrc))
4440 {
4441 AssertComRC(hrc);
4442 hrc = E_FAIL;
4443 break;
4444 }
4445
4446 const char *pszAdapterName = networkAdapterTypeToName(adapterType);
4447 PPDMIBASE pBase;
4448 int vrc = ptrVM.vtable()->pfnPDMR3QueryLun(ptrVM.rawUVM(), pszAdapterName, ulInstance, 0, &pBase);
4449 if (RT_FAILURE(vrc))
4450 {
4451 /* This may happen if the NAT network adapter is currently not attached.
4452 * This is a valid condition. */
4453 if (vrc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
4454 break;
4455 ComAssertRC(vrc);
4456 hrc = E_FAIL;
4457 break;
4458 }
4459
4460 NetworkAttachmentType_T attachmentType;
4461 hrc = pNetworkAdapter->COMGETTER(AttachmentType)(&attachmentType);
4462 if ( FAILED(hrc)
4463 || attachmentType != NetworkAttachmentType_NAT)
4464 {
4465 hrc = E_FAIL;
4466 break;
4467 }
4468
4469 /* look down for PDMINETWORKNATCONFIG interface */
4470 PPDMINETWORKNATCONFIG pNetNatCfg = NULL;
4471 while (pBase)
4472 {
4473 pNetNatCfg = (PPDMINETWORKNATCONFIG)pBase->pfnQueryInterface(pBase, PDMINETWORKNATCONFIG_IID);
4474 if (pNetNatCfg)
4475 break;
4476 /** @todo r=bird: This stinks! */
4477 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pBase);
4478 pBase = pDrvIns->pDownBase;
4479 }
4480 if (!pNetNatCfg)
4481 break;
4482
4483 bool fUdp = aProto == NATProtocol_UDP;
4484 vrc = pNetNatCfg->pfnRedirectRuleCommand(pNetNatCfg, !!aNatRuleRemove, fUdp,
4485 Utf8Str(aHostIP).c_str(), (uint16_t)aHostPort, Utf8Str(aGuestIP).c_str(),
4486 (uint16_t)aGuestPort);
4487 if (RT_FAILURE(vrc))
4488 hrc = E_FAIL;
4489 } while (0); /* break loop */
4490 ptrVM.release();
4491 }
4492
4493 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
4494 return hrc;
4495}
4496
4497
4498/*
4499 * IHostNameResolutionConfigurationChangeEvent
4500 *
4501 * Currently this event doesn't carry actual resolver configuration,
4502 * so we have to go back to VBoxSVC and ask... This is not ideal.
4503 */
4504HRESULT Console::i_onNATDnsChanged()
4505{
4506 HRESULT hrc;
4507
4508 AutoCaller autoCaller(this);
4509 AssertComRCReturnRC(autoCaller.hrc());
4510
4511 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4512
4513#if 0 /* XXX: We don't yet pass this down to pfnNotifyDnsChanged */
4514 ComPtr<IVirtualBox> pVirtualBox;
4515 hrc = mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
4516 if (FAILED(hrc))
4517 return S_OK;
4518
4519 ComPtr<IHost> pHost;
4520 hrc = pVirtualBox->COMGETTER(Host)(pHost.asOutParam());
4521 if (FAILED(hrc))
4522 return S_OK;
4523
4524 SafeArray<BSTR> aNameServers;
4525 hrc = pHost->COMGETTER(NameServers)(ComSafeArrayAsOutParam(aNameServers));
4526 if (FAILED(hrc))
4527 return S_OK;
4528
4529 const size_t cNameServers = aNameServers.size();
4530 Log(("DNS change - %zu nameservers\n", cNameServers));
4531
4532 for (size_t i = 0; i < cNameServers; ++i)
4533 {
4534 com::Utf8Str strNameServer(aNameServers[i]);
4535 Log(("- nameserver[%zu] = \"%s\"\n", i, strNameServer.c_str()));
4536 }
4537
4538 com::Bstr domain;
4539 pHost->COMGETTER(DomainName)(domain.asOutParam());
4540 Log(("domain name = \"%s\"\n", com::Utf8Str(domain).c_str()));
4541#endif /* 0 */
4542
4543 ComPtr<IPlatform> pPlatform;
4544 hrc = mMachine->COMGETTER(Platform)(pPlatform.asOutParam());
4545 AssertComRCReturn(hrc, hrc);
4546
4547 ChipsetType_T enmChipsetType;
4548 hrc = pPlatform->COMGETTER(ChipsetType)(&enmChipsetType);
4549 AssertComRCReturn(hrc, hrc);
4550
4551 SafeVMPtrQuiet ptrVM(this);
4552 if (ptrVM.isOk())
4553 {
4554 ULONG const ulInstanceMax = PlatformProperties::s_getMaxNetworkAdapters(enmChipsetType);
4555
4556 notifyNatDnsChange(ptrVM.rawUVM(), ptrVM.vtable(), "pcnet", ulInstanceMax);
4557 notifyNatDnsChange(ptrVM.rawUVM(), ptrVM.vtable(), "e1000", ulInstanceMax);
4558 notifyNatDnsChange(ptrVM.rawUVM(), ptrVM.vtable(), "virtio-net", ulInstanceMax);
4559 }
4560
4561 return S_OK;
4562}
4563
4564
4565/*
4566 * This routine walks over all network device instances, checking if
4567 * device instance has DrvNAT attachment and triggering DrvNAT DNS
4568 * change callback.
4569 */
4570void Console::notifyNatDnsChange(PUVM pUVM, PCVMMR3VTABLE pVMM, const char *pszDevice, ULONG ulInstanceMax)
4571{
4572 Log(("notifyNatDnsChange: looking for DrvNAT attachment on %s device instances\n", pszDevice));
4573 for (ULONG ulInstance = 0; ulInstance < ulInstanceMax; ulInstance++)
4574 {
4575 PPDMIBASE pBase;
4576 int vrc = pVMM->pfnPDMR3QueryDriverOnLun(pUVM, pszDevice, ulInstance, 0 /* iLun */, "NAT", &pBase);
4577 if (RT_FAILURE(vrc))
4578 continue;
4579
4580 Log(("Instance %s#%d has DrvNAT attachment; do actual notify\n", pszDevice, ulInstance));
4581 if (pBase)
4582 {
4583 PPDMINETWORKNATCONFIG pNetNatCfg = NULL;
4584 pNetNatCfg = (PPDMINETWORKNATCONFIG)pBase->pfnQueryInterface(pBase, PDMINETWORKNATCONFIG_IID);
4585 if (pNetNatCfg && pNetNatCfg->pfnNotifyDnsChanged)
4586 pNetNatCfg->pfnNotifyDnsChanged(pNetNatCfg);
4587 }
4588 }
4589}
4590
4591
4592VMMDevMouseInterface *Console::i_getVMMDevMouseInterface()
4593{
4594 return m_pVMMDev;
4595}
4596
4597DisplayMouseInterface *Console::i_getDisplayMouseInterface()
4598{
4599 return mDisplay;
4600}
4601
4602/**
4603 * Parses one key value pair.
4604 *
4605 * @returns VBox status code.
4606 * @param psz Configuration string.
4607 * @param ppszEnd Where to store the pointer to the string following the key value pair.
4608 * @param ppszKey Where to store the key on success.
4609 * @param ppszVal Where to store the value on success.
4610 */
4611int Console::i_consoleParseKeyValue(const char *psz, const char **ppszEnd, char **ppszKey, char **ppszVal)
4612{
4613 const char *pszKeyStart = psz;
4614 while ( *psz != '='
4615 && *psz)
4616 psz++;
4617
4618 /* End of string at this point is invalid. */
4619 if (*psz == '\0')
4620 return VERR_INVALID_PARAMETER;
4621
4622 size_t const cchKey = psz - pszKeyStart;
4623
4624 psz++; /* Skip '=' character */
4625 const char *pszValStart = psz;
4626
4627 while ( *psz != ','
4628 && *psz != '\n'
4629 && *psz != '\r'
4630 && *psz)
4631 psz++;
4632 size_t const cchVal = psz - pszValStart;
4633
4634 int vrc = VINF_SUCCESS;
4635 if (cchKey && cchVal)
4636 {
4637 *ppszKey = RTStrDupN(pszKeyStart, cchKey);
4638 if (*ppszKey)
4639 {
4640 *ppszVal = RTStrDupN(pszValStart, cchVal);
4641 if (*ppszVal)
4642 *ppszEnd = psz;
4643 else
4644 {
4645 RTStrFree(*ppszKey);
4646 vrc = VERR_NO_STR_MEMORY;
4647 }
4648 }
4649 else
4650 vrc = VERR_NO_STR_MEMORY;
4651 }
4652 else
4653 vrc = VERR_INVALID_PARAMETER;
4654
4655 return vrc;
4656}
4657
4658/**
4659 * Initializes the secret key interface on all configured attachments.
4660 *
4661 * @returns COM status code.
4662 */
4663HRESULT Console::i_initSecretKeyIfOnAllAttachments(void)
4664{
4665 HRESULT hrc = S_OK;
4666 SafeIfaceArray<IMediumAttachment> sfaAttachments;
4667
4668 AutoCaller autoCaller(this);
4669 AssertComRCReturnRC(autoCaller.hrc());
4670
4671 /* Get the VM - must be done before the read-locking. */
4672 SafeVMPtr ptrVM(this);
4673 if (!ptrVM.isOk())
4674 return ptrVM.hrc();
4675
4676 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4677
4678 hrc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(sfaAttachments));
4679 AssertComRCReturnRC(hrc);
4680
4681#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
4682 m_cDisksPwProvided = 0;
4683#endif
4684
4685 /* Find the correct attachment. */
4686 for (unsigned i = 0; i < sfaAttachments.size(); i++)
4687 {
4688 const ComPtr<IMediumAttachment> &pAtt = sfaAttachments[i];
4689
4690#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
4691 ComPtr<IMedium> pMedium;
4692 ComPtr<IMedium> pBase;
4693
4694 hrc = pAtt->COMGETTER(Medium)(pMedium.asOutParam());
4695 AssertComRC(hrc);
4696
4697 bool fKeepSecIf = false;
4698 /* Skip non hard disk attachments. */
4699 if (pMedium.isNotNull())
4700 {
4701 /* Get the UUID of the base medium and compare. */
4702 hrc = pMedium->COMGETTER(Base)(pBase.asOutParam());
4703 AssertComRC(hrc);
4704
4705 Bstr bstrKeyId;
4706 hrc = pBase->GetProperty(Bstr("CRYPT/KeyId").raw(), bstrKeyId.asOutParam());
4707 if (SUCCEEDED(hrc))
4708 {
4709 Utf8Str strKeyId(bstrKeyId);
4710 SecretKey *pKey = NULL;
4711 int vrc = m_pKeyStore->retainSecretKey(strKeyId, &pKey);
4712 if (RT_SUCCESS(vrc))
4713 {
4714 fKeepSecIf = true;
4715 m_pKeyStore->releaseSecretKey(strKeyId);
4716 }
4717 }
4718 }
4719#endif
4720
4721 /*
4722 * Query storage controller, port and device
4723 * to identify the correct driver.
4724 */
4725 ComPtr<IStorageController> pStorageCtrl;
4726 Bstr storageCtrlName;
4727 LONG lPort, lDev;
4728 ULONG ulStorageCtrlInst;
4729
4730 hrc = pAtt->COMGETTER(Controller)(storageCtrlName.asOutParam());
4731 AssertComRC(hrc);
4732
4733 hrc = pAtt->COMGETTER(Port)(&lPort);
4734 AssertComRC(hrc);
4735
4736 hrc = pAtt->COMGETTER(Device)(&lDev);
4737 AssertComRC(hrc);
4738
4739 hrc = mMachine->GetStorageControllerByName(storageCtrlName.raw(), pStorageCtrl.asOutParam());
4740 AssertComRC(hrc);
4741
4742 hrc = pStorageCtrl->COMGETTER(Instance)(&ulStorageCtrlInst);
4743 AssertComRC(hrc);
4744
4745 StorageControllerType_T enmCtrlType;
4746 hrc = pStorageCtrl->COMGETTER(ControllerType)(&enmCtrlType);
4747 AssertComRC(hrc);
4748 const char *pcszDevice = i_storageControllerTypeToStr(enmCtrlType);
4749
4750 StorageBus_T enmBus;
4751 hrc = pStorageCtrl->COMGETTER(Bus)(&enmBus);
4752 AssertComRC(hrc);
4753
4754 unsigned uLUN;
4755 hrc = Console::i_storageBusPortDeviceToLun(enmBus, lPort, lDev, uLUN);
4756 AssertComRC(hrc);
4757
4758 PPDMIBASE pIBase = NULL;
4759 PPDMIMEDIA pIMedium = NULL;
4760 int vrc = ptrVM.vtable()->pfnPDMR3QueryDriverOnLun(ptrVM.rawUVM(), pcszDevice, ulStorageCtrlInst, uLUN, "VD", &pIBase);
4761 if (RT_SUCCESS(vrc))
4762 {
4763 if (pIBase)
4764 {
4765 pIMedium = (PPDMIMEDIA)pIBase->pfnQueryInterface(pIBase, PDMIMEDIA_IID);
4766 if (pIMedium)
4767 {
4768#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
4769 vrc = pIMedium->pfnSetSecKeyIf(pIMedium, fKeepSecIf ? mpIfSecKey : NULL, mpIfSecKeyHlp);
4770 Assert(RT_SUCCESS(vrc) || vrc == VERR_NOT_SUPPORTED);
4771 if (fKeepSecIf)
4772 m_cDisksPwProvided++;
4773#else
4774 vrc = pIMedium->pfnSetSecKeyIf(pIMedium, NULL, mpIfSecKeyHlp);
4775 Assert(RT_SUCCESS(vrc) || vrc == VERR_NOT_SUPPORTED);
4776#endif
4777 }
4778 }
4779 }
4780 }
4781
4782 return hrc;
4783}
4784
4785/**
4786 * Removes the key interfaces from all disk attachments with the given key ID.
4787 * Useful when changing the key store or dropping it.
4788 *
4789 * @returns COM status code.
4790 * @param strId The ID to look for.
4791 */
4792HRESULT Console::i_clearDiskEncryptionKeysOnAllAttachmentsWithKeyId(const Utf8Str &strId)
4793{
4794 HRESULT hrc = S_OK;
4795 SafeIfaceArray<IMediumAttachment> sfaAttachments;
4796
4797 /* Get the VM - must be done before the read-locking. */
4798 SafeVMPtr ptrVM(this);
4799 if (!ptrVM.isOk())
4800 return ptrVM.hrc();
4801
4802 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4803
4804 hrc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(sfaAttachments));
4805 AssertComRCReturnRC(hrc);
4806
4807 /* Find the correct attachment. */
4808 for (unsigned i = 0; i < sfaAttachments.size(); i++)
4809 {
4810 const ComPtr<IMediumAttachment> &pAtt = sfaAttachments[i];
4811 ComPtr<IMedium> pMedium;
4812 ComPtr<IMedium> pBase;
4813 Bstr bstrKeyId;
4814
4815 hrc = pAtt->COMGETTER(Medium)(pMedium.asOutParam());
4816 if (FAILED(hrc))
4817 break;
4818
4819 /* Skip non hard disk attachments. */
4820 if (pMedium.isNull())
4821 continue;
4822
4823 /* Get the UUID of the base medium and compare. */
4824 hrc = pMedium->COMGETTER(Base)(pBase.asOutParam());
4825 if (FAILED(hrc))
4826 break;
4827
4828 hrc = pBase->GetProperty(Bstr("CRYPT/KeyId").raw(), bstrKeyId.asOutParam());
4829 if (hrc == VBOX_E_OBJECT_NOT_FOUND)
4830 {
4831 hrc = S_OK;
4832 continue;
4833 }
4834 else if (FAILED(hrc))
4835 break;
4836
4837 if (strId.equals(Utf8Str(bstrKeyId)))
4838 {
4839
4840 /*
4841 * Query storage controller, port and device
4842 * to identify the correct driver.
4843 */
4844 ComPtr<IStorageController> pStorageCtrl;
4845 Bstr storageCtrlName;
4846 LONG lPort, lDev;
4847 ULONG ulStorageCtrlInst;
4848
4849 hrc = pAtt->COMGETTER(Controller)(storageCtrlName.asOutParam());
4850 AssertComRC(hrc);
4851
4852 hrc = pAtt->COMGETTER(Port)(&lPort);
4853 AssertComRC(hrc);
4854
4855 hrc = pAtt->COMGETTER(Device)(&lDev);
4856 AssertComRC(hrc);
4857
4858 hrc = mMachine->GetStorageControllerByName(storageCtrlName.raw(), pStorageCtrl.asOutParam());
4859 AssertComRC(hrc);
4860
4861 hrc = pStorageCtrl->COMGETTER(Instance)(&ulStorageCtrlInst);
4862 AssertComRC(hrc);
4863
4864 StorageControllerType_T enmCtrlType;
4865 hrc = pStorageCtrl->COMGETTER(ControllerType)(&enmCtrlType);
4866 AssertComRC(hrc);
4867 const char *pcszDevice = i_storageControllerTypeToStr(enmCtrlType);
4868
4869 StorageBus_T enmBus;
4870 hrc = pStorageCtrl->COMGETTER(Bus)(&enmBus);
4871 AssertComRC(hrc);
4872
4873 unsigned uLUN;
4874 hrc = Console::i_storageBusPortDeviceToLun(enmBus, lPort, lDev, uLUN);
4875 AssertComRC(hrc);
4876
4877 PPDMIBASE pIBase = NULL;
4878 PPDMIMEDIA pIMedium = NULL;
4879 int vrc = ptrVM.vtable()->pfnPDMR3QueryDriverOnLun(ptrVM.rawUVM(), pcszDevice, ulStorageCtrlInst, uLUN, "VD", &pIBase);
4880 if (RT_SUCCESS(vrc))
4881 {
4882 if (pIBase)
4883 {
4884 pIMedium = (PPDMIMEDIA)pIBase->pfnQueryInterface(pIBase, PDMIMEDIA_IID);
4885 if (pIMedium)
4886 {
4887 vrc = pIMedium->pfnSetSecKeyIf(pIMedium, NULL, mpIfSecKeyHlp);
4888 Assert(RT_SUCCESS(vrc) || vrc == VERR_NOT_SUPPORTED);
4889 }
4890 }
4891 }
4892 }
4893 }
4894
4895 return hrc;
4896}
4897
4898/**
4899 * Configures the encryption support for the disk which have encryption conigured
4900 * with the configured key.
4901 *
4902 * @returns COM status code.
4903 * @param strId The ID of the password.
4904 * @param pcDisksConfigured Where to store the number of disks configured for the given ID.
4905 */
4906HRESULT Console::i_configureEncryptionForDisk(const com::Utf8Str &strId, unsigned *pcDisksConfigured)
4907{
4908 unsigned cDisksConfigured = 0;
4909 HRESULT hrc = S_OK;
4910 SafeIfaceArray<IMediumAttachment> sfaAttachments;
4911
4912 AutoCaller autoCaller(this);
4913 AssertComRCReturnRC(autoCaller.hrc());
4914
4915 /* Get the VM - must be done before the read-locking. */
4916 SafeVMPtr ptrVM(this);
4917 if (!ptrVM.isOk())
4918 return ptrVM.hrc();
4919
4920 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4921
4922 hrc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(sfaAttachments));
4923 if (FAILED(hrc))
4924 return hrc;
4925
4926 /* Find the correct attachment. */
4927 for (unsigned i = 0; i < sfaAttachments.size(); i++)
4928 {
4929 const ComPtr<IMediumAttachment> &pAtt = sfaAttachments[i];
4930 ComPtr<IMedium> pMedium;
4931 ComPtr<IMedium> pBase;
4932 Bstr bstrKeyId;
4933
4934 hrc = pAtt->COMGETTER(Medium)(pMedium.asOutParam());
4935 if (FAILED(hrc))
4936 break;
4937
4938 /* Skip non hard disk attachments. */
4939 if (pMedium.isNull())
4940 continue;
4941
4942 /* Get the UUID of the base medium and compare. */
4943 hrc = pMedium->COMGETTER(Base)(pBase.asOutParam());
4944 if (FAILED(hrc))
4945 break;
4946
4947 hrc = pBase->GetProperty(Bstr("CRYPT/KeyId").raw(), bstrKeyId.asOutParam());
4948 if (hrc == VBOX_E_OBJECT_NOT_FOUND)
4949 {
4950 hrc = S_OK;
4951 continue;
4952 }
4953 else if (FAILED(hrc))
4954 break;
4955
4956 if (strId.equals(Utf8Str(bstrKeyId)))
4957 {
4958 /*
4959 * Found the matching medium, query storage controller, port and device
4960 * to identify the correct driver.
4961 */
4962 ComPtr<IStorageController> pStorageCtrl;
4963 Bstr storageCtrlName;
4964 LONG lPort, lDev;
4965 ULONG ulStorageCtrlInst;
4966
4967 hrc = pAtt->COMGETTER(Controller)(storageCtrlName.asOutParam());
4968 if (FAILED(hrc))
4969 break;
4970
4971 hrc = pAtt->COMGETTER(Port)(&lPort);
4972 if (FAILED(hrc))
4973 break;
4974
4975 hrc = pAtt->COMGETTER(Device)(&lDev);
4976 if (FAILED(hrc))
4977 break;
4978
4979 hrc = mMachine->GetStorageControllerByName(storageCtrlName.raw(), pStorageCtrl.asOutParam());
4980 if (FAILED(hrc))
4981 break;
4982
4983 hrc = pStorageCtrl->COMGETTER(Instance)(&ulStorageCtrlInst);
4984 if (FAILED(hrc))
4985 break;
4986
4987 StorageControllerType_T enmCtrlType;
4988 hrc = pStorageCtrl->COMGETTER(ControllerType)(&enmCtrlType);
4989 AssertComRC(hrc);
4990 const char *pcszDevice = i_storageControllerTypeToStr(enmCtrlType);
4991
4992 StorageBus_T enmBus;
4993 hrc = pStorageCtrl->COMGETTER(Bus)(&enmBus);
4994 AssertComRC(hrc);
4995
4996 unsigned uLUN;
4997 hrc = Console::i_storageBusPortDeviceToLun(enmBus, lPort, lDev, uLUN);
4998 AssertComRCReturnRC(hrc);
4999
5000 PPDMIBASE pIBase = NULL;
5001 PPDMIMEDIA pIMedium = NULL;
5002 int vrc = ptrVM.vtable()->pfnPDMR3QueryDriverOnLun(ptrVM.rawUVM(), pcszDevice, ulStorageCtrlInst, uLUN, "VD", &pIBase);
5003 if (RT_SUCCESS(vrc))
5004 {
5005 if (pIBase)
5006 {
5007 pIMedium = (PPDMIMEDIA)pIBase->pfnQueryInterface(pIBase, PDMIMEDIA_IID);
5008 if (!pIMedium)
5009 return setError(E_FAIL, tr("could not query medium interface of controller"));
5010 vrc = pIMedium->pfnSetSecKeyIf(pIMedium, mpIfSecKey, mpIfSecKeyHlp);
5011 if (vrc == VERR_VD_PASSWORD_INCORRECT)
5012 {
5013 hrc = setError(VBOX_E_PASSWORD_INCORRECT,
5014 tr("The provided password for ID \"%s\" is not correct for at least one disk using this ID"),
5015 strId.c_str());
5016 break;
5017 }
5018 else if (RT_FAILURE(vrc))
5019 {
5020 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to set the encryption key (%Rrc)"), vrc);
5021 break;
5022 }
5023
5024 if (RT_SUCCESS(vrc))
5025 cDisksConfigured++;
5026 }
5027 else
5028 return setError(E_FAIL, tr("could not query base interface of controller"));
5029 }
5030 }
5031 }
5032
5033 if ( SUCCEEDED(hrc)
5034 && pcDisksConfigured)
5035 *pcDisksConfigured = cDisksConfigured;
5036 else if (FAILED(hrc))
5037 {
5038 /* Clear disk encryption setup on successfully configured attachments. */
5039 ErrorInfoKeeper eik; /* Keep current error info or it gets deestroyed in the IPC methods below. */
5040 i_clearDiskEncryptionKeysOnAllAttachmentsWithKeyId(strId);
5041 }
5042
5043 return hrc;
5044}
5045
5046/**
5047 * Parses the encryption configuration for one disk.
5048 *
5049 * @returns COM status code.
5050 * @param psz Pointer to the configuration for the encryption of one disk.
5051 * @param ppszEnd Pointer to the string following encrpytion configuration.
5052 */
5053HRESULT Console::i_consoleParseDiskEncryption(const char *psz, const char **ppszEnd)
5054{
5055 char *pszUuid = NULL;
5056 char *pszKeyEnc = NULL;
5057 int vrc = VINF_SUCCESS;
5058 HRESULT hrc = S_OK;
5059
5060 while ( *psz
5061 && RT_SUCCESS(vrc))
5062 {
5063 char *pszKey = NULL;
5064 char *pszVal = NULL;
5065 const char *pszEnd = NULL;
5066
5067 vrc = i_consoleParseKeyValue(psz, &pszEnd, &pszKey, &pszVal);
5068 if (RT_SUCCESS(vrc))
5069 {
5070 if (!RTStrCmp(pszKey, "uuid"))
5071 pszUuid = pszVal;
5072 else if (!RTStrCmp(pszKey, "dek"))
5073 pszKeyEnc = pszVal;
5074 else
5075 vrc = VERR_INVALID_PARAMETER;
5076
5077 RTStrFree(pszKey);
5078
5079 if (*pszEnd == ',')
5080 psz = pszEnd + 1;
5081 else
5082 {
5083 /*
5084 * End of the configuration for the current disk, skip linefeed and
5085 * carriage returns.
5086 */
5087 while ( *pszEnd == '\n'
5088 || *pszEnd == '\r')
5089 pszEnd++;
5090
5091 psz = pszEnd;
5092 break; /* Stop parsing */
5093 }
5094
5095 }
5096 }
5097
5098 if ( RT_SUCCESS(vrc)
5099 && pszUuid
5100 && pszKeyEnc)
5101 {
5102 ssize_t cbKey = 0;
5103
5104 /* Decode the key. */
5105 cbKey = RTBase64DecodedSize(pszKeyEnc, NULL);
5106 if (cbKey != -1)
5107 {
5108 uint8_t *pbKey;
5109 vrc = RTMemSaferAllocZEx((void **)&pbKey, cbKey, RTMEMSAFER_F_REQUIRE_NOT_PAGABLE);
5110 if (RT_SUCCESS(vrc))
5111 {
5112 vrc = RTBase64Decode(pszKeyEnc, pbKey, cbKey, NULL, NULL);
5113 if (RT_SUCCESS(vrc))
5114 {
5115 vrc = m_pKeyStore->addSecretKey(Utf8Str(pszUuid), pbKey, cbKey);
5116 if (RT_SUCCESS(vrc))
5117 {
5118 hrc = i_configureEncryptionForDisk(Utf8Str(pszUuid), NULL);
5119 if (FAILED(hrc))
5120 {
5121 /* Delete the key from the map. */
5122 vrc = m_pKeyStore->deleteSecretKey(Utf8Str(pszUuid));
5123 AssertRC(vrc);
5124 }
5125 }
5126 }
5127 else
5128 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to decode the key (%Rrc)"), vrc);
5129
5130 RTMemSaferFree(pbKey, cbKey);
5131 }
5132 else
5133 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to allocate secure memory for the key (%Rrc)"), vrc);
5134 }
5135 else
5136 hrc = setError(E_FAIL, tr("The base64 encoding of the passed key is incorrect"));
5137 }
5138 else if (RT_SUCCESS(vrc))
5139 hrc = setError(E_FAIL, tr("The encryption configuration is incomplete"));
5140
5141 if (pszUuid)
5142 RTStrFree(pszUuid);
5143 if (pszKeyEnc)
5144 {
5145 RTMemWipeThoroughly(pszKeyEnc, strlen(pszKeyEnc), 10 /* cMinPasses */);
5146 RTStrFree(pszKeyEnc);
5147 }
5148
5149 if (ppszEnd)
5150 *ppszEnd = psz;
5151
5152 return hrc;
5153}
5154
5155HRESULT Console::i_setDiskEncryptionKeys(const Utf8Str &strCfg)
5156{
5157 HRESULT hrc = S_OK;
5158 const char *pszCfg = strCfg.c_str();
5159
5160 while ( *pszCfg
5161 && SUCCEEDED(hrc))
5162 {
5163 const char *pszNext = NULL;
5164 hrc = i_consoleParseDiskEncryption(pszCfg, &pszNext);
5165 pszCfg = pszNext;
5166 }
5167
5168 return hrc;
5169}
5170
5171void Console::i_removeSecretKeysOnSuspend()
5172{
5173 /* Remove keys which are supposed to be removed on a suspend. */
5174 int vrc = m_pKeyStore->deleteAllSecretKeys(true /* fSuspend */, true /* fForce */);
5175 AssertRC(vrc);
5176}
5177
5178/**
5179 * Process a network adaptor change.
5180 *
5181 * @returns COM status code.
5182 *
5183 * @param pUVM The VM handle (caller hold this safely).
5184 * @param pVMM The VMM vtable.
5185 * @param pszDevice The PDM device name.
5186 * @param uInstance The PDM device instance.
5187 * @param uLun The PDM LUN number of the drive.
5188 * @param aNetworkAdapter The network adapter whose attachment needs to be changed
5189 */
5190HRESULT Console::i_doNetworkAdapterChange(PUVM pUVM, PCVMMR3VTABLE pVMM, const char *pszDevice,
5191 unsigned uInstance, unsigned uLun, INetworkAdapter *aNetworkAdapter)
5192{
5193 LogFlowThisFunc(("pszDevice=%p:{%s} uInstance=%u uLun=%u aNetworkAdapter=%p\n",
5194 pszDevice, pszDevice, uInstance, uLun, aNetworkAdapter));
5195
5196 AutoCaller autoCaller(this);
5197 AssertComRCReturnRC(autoCaller.hrc());
5198
5199 /*
5200 * Suspend the VM first.
5201 */
5202 bool fResume = false;
5203 HRESULT hr = i_suspendBeforeConfigChange(pUVM, pVMM, NULL, &fResume);
5204 if (FAILED(hr))
5205 return hr;
5206
5207 /*
5208 * Call worker in EMT, that's faster and safer than doing everything
5209 * using VM3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
5210 * here to make requests from under the lock in order to serialize them.
5211 */
5212 int vrc = pVMM->pfnVMR3ReqCallWaitU(pUVM, 0 /*idDstCpu*/,
5213 (PFNRT)i_changeNetworkAttachment, 7,
5214 this, pUVM, pVMM, pszDevice, uInstance, uLun, aNetworkAdapter);
5215
5216 if (fResume)
5217 i_resumeAfterConfigChange(pUVM, pVMM);
5218
5219 if (RT_SUCCESS(vrc))
5220 return S_OK;
5221
5222 return setErrorBoth(E_FAIL, vrc, tr("Could not change the network adaptor attachement type (%Rrc)"), vrc);
5223}
5224
5225
5226/**
5227 * Performs the Network Adaptor change in EMT.
5228 *
5229 * @returns VBox status code.
5230 *
5231 * @param pThis Pointer to the Console object.
5232 * @param pUVM The VM handle.
5233 * @param pVMM The VMM vtable.
5234 * @param pszDevice The PDM device name.
5235 * @param uInstance The PDM device instance.
5236 * @param uLun The PDM LUN number of the drive.
5237 * @param aNetworkAdapter The network adapter whose attachment needs to be changed
5238 *
5239 * @thread EMT
5240 * @note Locks the Console object for writing.
5241 * @note The VM must not be running.
5242 */
5243DECLCALLBACK(int) Console::i_changeNetworkAttachment(Console *pThis,
5244 PUVM pUVM,
5245 PCVMMR3VTABLE pVMM,
5246 const char *pszDevice,
5247 unsigned uInstance,
5248 unsigned uLun,
5249 INetworkAdapter *aNetworkAdapter)
5250{
5251 LogFlowFunc(("pThis=%p pszDevice=%p:{%s} uInstance=%u uLun=%u aNetworkAdapter=%p\n",
5252 pThis, pszDevice, pszDevice, uInstance, uLun, aNetworkAdapter));
5253
5254 AssertReturn(pThis, VERR_INVALID_PARAMETER);
5255
5256 AutoCaller autoCaller(pThis);
5257 AssertComRCReturn(autoCaller.hrc(), VERR_ACCESS_DENIED);
5258
5259 ComPtr<IPlatform> pPlatform;
5260 HRESULT hrc = pThis->mMachine->COMGETTER(Platform)(pPlatform.asOutParam());
5261 AssertComRC(hrc);
5262
5263 PlatformArchitecture_T platformArch;
5264 hrc = pPlatform->COMGETTER(Architecture)(&platformArch);
5265 AssertComRC(hrc);
5266
5267 ComPtr<IVirtualBox> pVirtualBox;
5268 pThis->mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
5269
5270 ComPtr<IPlatformProperties> pPlatformProperties;
5271 hrc = pVirtualBox->GetPlatformProperties(platformArch, pPlatformProperties.asOutParam());
5272 AssertComRC(hrc);
5273
5274 ChipsetType_T chipsetType = ChipsetType_PIIX3;
5275 pPlatform->COMGETTER(ChipsetType)(&chipsetType);
5276 AssertComRC(hrc);
5277
5278 ULONG maxNetworkAdapters = 0;
5279 hrc = pPlatformProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters);
5280 AssertComRC(hrc);
5281 AssertMsg( ( !strcmp(pszDevice, "pcnet")
5282 || !strcmp(pszDevice, "e1000")
5283 || !strcmp(pszDevice, "virtio-net"))
5284 && uLun == 0
5285 && uInstance < maxNetworkAdapters,
5286 ("pszDevice=%s uLun=%d uInstance=%d\n", pszDevice, uLun, uInstance));
5287 Log(("pszDevice=%s uLun=%d uInstance=%d\n", pszDevice, uLun, uInstance));
5288
5289 /*
5290 * Check the VM for correct state.
5291 */
5292 PCFGMNODE pCfg = NULL; /* /Devices/Dev/.../Config/ */
5293 PCFGMNODE pLunL0 = NULL; /* /Devices/Dev/0/LUN#0/ */
5294 PCFGMNODE pInst = pVMM->pfnCFGMR3GetChildF(pVMM->pfnCFGMR3GetRootU(pUVM), "Devices/%s/%d/", pszDevice, uInstance);
5295 AssertRelease(pInst);
5296
5297 int vrc = pThis->i_configNetwork(pszDevice, uInstance, uLun, aNetworkAdapter, pCfg, pLunL0, pInst,
5298 true /*fAttachDetach*/, false /*fIgnoreConnectFailure*/, pUVM, pVMM);
5299
5300 LogFlowFunc(("Returning %Rrc\n", vrc));
5301 return vrc;
5302}
5303
5304/**
5305 * Returns the device name of a given audio adapter.
5306 *
5307 * @returns Device name, or an empty string if no device is configured.
5308 * @param aAudioAdapter Audio adapter to return device name for.
5309 */
5310Utf8Str Console::i_getAudioAdapterDeviceName(IAudioAdapter *aAudioAdapter)
5311{
5312 Utf8Str strDevice;
5313
5314 AudioControllerType_T audioController;
5315 HRESULT hrc = aAudioAdapter->COMGETTER(AudioController)(&audioController);
5316 AssertComRC(hrc);
5317 if (SUCCEEDED(hrc))
5318 {
5319 switch (audioController)
5320 {
5321 case AudioControllerType_HDA: strDevice = "hda"; break;
5322 case AudioControllerType_AC97: strDevice = "ichac97"; break;
5323 case AudioControllerType_SB16: strDevice = "sb16"; break;
5324 case AudioControllerType_VirtioSound: strDevice = "virtio-sound"; break;
5325 default: break; /* None. */
5326 }
5327 }
5328
5329 return strDevice;
5330}
5331
5332/**
5333 * Called by IInternalSessionControl::OnAudioAdapterChange().
5334 */
5335HRESULT Console::i_onAudioAdapterChange(IAudioAdapter *aAudioAdapter)
5336{
5337 LogFlowThisFunc(("\n"));
5338
5339 AutoCaller autoCaller(this);
5340 AssertComRCReturnRC(autoCaller.hrc());
5341
5342 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5343
5344 HRESULT hrc = S_OK;
5345
5346 /* don't trigger audio changes if the VM isn't running */
5347 SafeVMPtrQuiet ptrVM(this);
5348 if (ptrVM.isOk())
5349 {
5350 BOOL fEnabledIn, fEnabledOut;
5351 hrc = aAudioAdapter->COMGETTER(EnabledIn)(&fEnabledIn);
5352 AssertComRC(hrc);
5353 if (SUCCEEDED(hrc))
5354 {
5355 hrc = aAudioAdapter->COMGETTER(EnabledOut)(&fEnabledOut);
5356 AssertComRC(hrc);
5357 if (SUCCEEDED(hrc))
5358 {
5359 int vrc = VINF_SUCCESS;
5360
5361 for (ULONG ulLUN = 0; ulLUN < 16 /** @todo Use a define */; ulLUN++)
5362 {
5363 PPDMIBASE pBase;
5364 int vrc2 = ptrVM.vtable()->pfnPDMR3QueryDriverOnLun(ptrVM.rawUVM(),
5365 i_getAudioAdapterDeviceName(aAudioAdapter).c_str(),
5366 0 /* iInstance */, ulLUN, "AUDIO", &pBase);
5367 if (RT_FAILURE(vrc2))
5368 continue;
5369
5370 if (pBase)
5371 {
5372 PPDMIAUDIOCONNECTOR pAudioCon = (PPDMIAUDIOCONNECTOR)pBase->pfnQueryInterface(pBase,
5373 PDMIAUDIOCONNECTOR_IID);
5374 if ( pAudioCon
5375 && pAudioCon->pfnEnable)
5376 {
5377 int vrcIn = pAudioCon->pfnEnable(pAudioCon, PDMAUDIODIR_IN, RT_BOOL(fEnabledIn));
5378 if (RT_FAILURE(vrcIn))
5379 LogRel(("Audio: Failed to %s input of LUN#%RU32, vrcIn=%Rrc\n",
5380 fEnabledIn ? "enable" : "disable", ulLUN, vrcIn));
5381
5382 if (RT_SUCCESS(vrc))
5383 vrc = vrcIn;
5384
5385 int vrcOut = pAudioCon->pfnEnable(pAudioCon, PDMAUDIODIR_OUT, RT_BOOL(fEnabledOut));
5386 if (RT_FAILURE(vrcOut))
5387 LogRel(("Audio: Failed to %s output of LUN#%RU32, vrcOut=%Rrc\n",
5388 fEnabledIn ? "enable" : "disable", ulLUN, vrcOut));
5389
5390 if (RT_SUCCESS(vrc))
5391 vrc = vrcOut;
5392 }
5393 }
5394 }
5395
5396 if (RT_SUCCESS(vrc))
5397 LogRel(("Audio: Status has changed (input is %s, output is %s)\n",
5398 fEnabledIn ? "enabled" : "disabled", fEnabledOut ? "enabled" : "disabled"));
5399 }
5400 }
5401
5402 ptrVM.release();
5403 }
5404
5405 alock.release();
5406
5407 /* notify console callbacks on success */
5408 if (SUCCEEDED(hrc))
5409 ::FireAudioAdapterChangedEvent(mEventSource, aAudioAdapter);
5410
5411 LogFlowThisFunc(("Leaving S_OKn"));
5412 return S_OK;
5413}
5414
5415/**
5416 * Called by IInternalSessionControl::OnHostAudioDeviceChange().
5417 */
5418HRESULT Console::i_onHostAudioDeviceChange(IHostAudioDevice *aDevice, BOOL aNew, AudioDeviceState_T aState,
5419 IVirtualBoxErrorInfo *aErrInfo)
5420{
5421 LogFlowThisFunc(("\n"));
5422
5423 AutoCaller autoCaller(this);
5424 AssertComRCReturnRC(autoCaller.hrc());
5425
5426 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5427
5428 HRESULT hrc = S_OK;
5429
5430 /** @todo Implement logic here. */
5431
5432 alock.release();
5433
5434 /* notify console callbacks on success */
5435 if (SUCCEEDED(hrc))
5436 ::FireHostAudioDeviceChangedEvent(mEventSource, aDevice, aNew, aState, aErrInfo);
5437
5438 LogFlowThisFunc(("Leaving S_OK\n"));
5439 return S_OK;
5440}
5441
5442/**
5443 * Performs the Serial Port attachment change in EMT.
5444 *
5445 * @returns VBox status code.
5446 *
5447 * @param pThis Pointer to the Console object.
5448 * @param pUVM The VM handle.
5449 * @param pVMM The VMM vtable.
5450 * @param pSerialPort The serial port whose attachment needs to be changed
5451 *
5452 * @thread EMT
5453 * @note Locks the Console object for writing.
5454 * @note The VM must not be running.
5455 */
5456DECLCALLBACK(int) Console::i_changeSerialPortAttachment(Console *pThis, PUVM pUVM, PCVMMR3VTABLE pVMM, ISerialPort *pSerialPort)
5457{
5458 LogFlowFunc(("pThis=%p pUVM=%p pSerialPort=%p\n", pThis, pUVM, pSerialPort));
5459
5460 AssertReturn(pThis, VERR_INVALID_PARAMETER);
5461
5462 AutoCaller autoCaller(pThis);
5463 AssertComRCReturn(autoCaller.hrc(), VERR_ACCESS_DENIED);
5464
5465 AutoWriteLock alock(pThis COMMA_LOCKVAL_SRC_POS);
5466
5467 /*
5468 * Check the VM for correct state.
5469 */
5470 VMSTATE enmVMState = pVMM->pfnVMR3GetStateU(pUVM);
5471 AssertReturn(enmVMState == VMSTATE_SUSPENDED, VERR_INVALID_STATE);
5472
5473 HRESULT hrc = S_OK;
5474 int vrc = VINF_SUCCESS;
5475 ULONG ulSlot;
5476 hrc = pSerialPort->COMGETTER(Slot)(&ulSlot);
5477 if (SUCCEEDED(hrc))
5478 {
5479 /* Check whether the port mode changed and act accordingly. */
5480 Assert(ulSlot < 4);
5481
5482 PortMode_T eHostMode;
5483 hrc = pSerialPort->COMGETTER(HostMode)(&eHostMode);
5484 if (SUCCEEDED(hrc))
5485 {
5486 PCFGMNODE pInst = pVMM->pfnCFGMR3GetChildF(pVMM->pfnCFGMR3GetRootU(pUVM), "Devices/serial/%d/", ulSlot);
5487 AssertRelease(pInst);
5488
5489 /* Remove old driver. */
5490 if (pThis->m_aeSerialPortMode[ulSlot] != PortMode_Disconnected)
5491 {
5492 vrc = pVMM->pfnPDMR3DeviceDetach(pUVM, "serial", ulSlot, 0, 0);
5493 PCFGMNODE pLunL0 = pVMM->pfnCFGMR3GetChildF(pInst, "LUN#0");
5494 pVMM->pfnCFGMR3RemoveNode(pLunL0);
5495 }
5496
5497 if (RT_SUCCESS(vrc))
5498 {
5499 BOOL fServer;
5500 Bstr bstrPath;
5501 hrc = pSerialPort->COMGETTER(Server)(&fServer);
5502 if (SUCCEEDED(hrc))
5503 hrc = pSerialPort->COMGETTER(Path)(bstrPath.asOutParam());
5504
5505 /* Configure new driver. */
5506 if ( SUCCEEDED(hrc)
5507 && eHostMode != PortMode_Disconnected)
5508 {
5509 vrc = pThis->i_configSerialPort(pInst, eHostMode, Utf8Str(bstrPath).c_str(), RT_BOOL(fServer));
5510 if (RT_SUCCESS(vrc))
5511 {
5512 /*
5513 * Attach the driver.
5514 */
5515 PPDMIBASE pBase;
5516 vrc = pVMM->pfnPDMR3DeviceAttach(pUVM, "serial", ulSlot, 0, 0, &pBase);
5517
5518 pVMM->pfnCFGMR3Dump(pInst);
5519 }
5520 }
5521 }
5522 }
5523 }
5524
5525 if (RT_SUCCESS(vrc) && FAILED(hrc))
5526 vrc = VERR_INTERNAL_ERROR;
5527
5528 LogFlowFunc(("Returning %Rrc\n", vrc));
5529 return vrc;
5530}
5531
5532
5533/**
5534 * Called by IInternalSessionControl::OnSerialPortChange().
5535 */
5536HRESULT Console::i_onSerialPortChange(ISerialPort *aSerialPort)
5537{
5538 LogFlowThisFunc(("\n"));
5539
5540 AutoCaller autoCaller(this);
5541 AssertComRCReturnRC(autoCaller.hrc());
5542
5543 HRESULT hrc = S_OK;
5544
5545 /* don't trigger audio changes if the VM isn't running */
5546 SafeVMPtrQuiet ptrVM(this);
5547 if (ptrVM.isOk())
5548 {
5549 ULONG ulSlot;
5550 BOOL fEnabled = FALSE;
5551 hrc = aSerialPort->COMGETTER(Slot)(&ulSlot);
5552 if (SUCCEEDED(hrc))
5553 hrc = aSerialPort->COMGETTER(Enabled)(&fEnabled);
5554 if (SUCCEEDED(hrc) && fEnabled)
5555 {
5556 /* Check whether the port mode changed and act accordingly. */
5557 Assert(ulSlot < 4);
5558
5559 PortMode_T eHostMode;
5560 hrc = aSerialPort->COMGETTER(HostMode)(&eHostMode);
5561 if (SUCCEEDED(hrc) && m_aeSerialPortMode[ulSlot] != eHostMode)
5562 {
5563 /*
5564 * Suspend the VM first.
5565 */
5566 bool fResume = false;
5567 hrc = i_suspendBeforeConfigChange(ptrVM.rawUVM(), ptrVM.vtable(), NULL, &fResume);
5568