VirtualBox

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

Last change on this file since 98273 was 98266, checked in by vboxsync, 23 months ago

Main/ConsoleImpl.cpp: rc -> hrc/vrc. bugref:10223

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