VirtualBox

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

Last change on this file since 95423 was 95423, checked in by vboxsync, 3 years ago

Audio/Main: Bigger revamp of the audio interface(s) to later also support host audio device enumeration and selection for individual VMs. The audio settings now live in a dedicated (per-VM) IAudioSettings interface (audio adapter + audio host device stuff), to further tidy up the IMachine interface. Also added stubs for IAudioDevice + IHostAudioDevice, plus enmuerations, left for further implementation. Added a new IHostAudioDeviceChangedEvent that can also be used later by API clients. bugref:10050

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

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