VirtualBox

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

最後變更 在這個檔案從95969是 95645,由 vboxsync 提交於 3 年 前

Recording/Main: Simplified and got rid of some destruction races by not dynamically (re-)allocating the recording context. Added docs, a bit of renaming. bugref:9286

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 398.4 KB
 
1/* $Id: ConsoleImpl.cpp 95645 2022-07-14 10:33:14Z 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.alldomusa.eu.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 bool const fIsEnabled = mRecording.mCtx.IsStarted();
5890
5891 if (RT_BOOL(fEnable) != fIsEnabled)
5892 {
5893 LogRel(("Recording: %s\n", fEnable ? "Enabling" : "Disabling"));
5894
5895 SafeVMPtrQuiet ptrVM(this);
5896 if (ptrVM.isOk())
5897 {
5898 if (fEnable)
5899 {
5900 vrc = i_recordingCreate();
5901 if (RT_SUCCESS(vrc))
5902 {
5903# ifdef VBOX_WITH_AUDIO_RECORDING
5904 /* Attach the video recording audio driver if required. */
5905 if ( mRecording.mCtx.IsFeatureEnabled(RecordingFeature_Audio)
5906 && mRecording.mAudioRec)
5907 {
5908 vrc = mRecording.mAudioRec->applyConfiguration(mRecording.mCtx.GetConfig());
5909 if (RT_SUCCESS(vrc))
5910 vrc = mRecording.mAudioRec->doAttachDriverViaEmt(ptrVM.rawUVM(), ptrVM.vtable(), pAutoLock);
5911 }
5912# endif
5913 if ( RT_SUCCESS(vrc)
5914 && mRecording.mCtx.IsReady()) /* Any video recording (audio and/or video) feature enabled? */
5915 {
5916 vrc = pDisplay->i_recordingInvalidate();
5917 if (RT_SUCCESS(vrc))
5918 vrc = i_recordingStart(pAutoLock);
5919 }
5920 }
5921
5922 if (RT_FAILURE(vrc))
5923 LogRel(("Recording: Failed to enable with %Rrc\n", vrc));
5924 }
5925 else
5926 {
5927 i_recordingStop(pAutoLock);
5928# ifdef VBOX_WITH_AUDIO_RECORDING
5929 if (mRecording.mAudioRec)
5930 mRecording.mAudioRec->doDetachDriverViaEmt(ptrVM.rawUVM(), ptrVM.vtable(), pAutoLock);
5931# endif
5932 i_recordingDestroy();
5933 }
5934 }
5935 else
5936 vrc = VERR_VM_INVALID_VM_STATE;
5937
5938 if (RT_FAILURE(vrc))
5939 LogRel(("Recording: %s failed with %Rrc\n", fEnable ? "Enabling" : "Disabling", vrc));
5940 }
5941 else /* Should not happen. */
5942 vrc = VERR_NO_CHANGE;
5943 }
5944
5945 return vrc;
5946}
5947#endif /* VBOX_WITH_RECORDING */
5948
5949/**
5950 * Called by IInternalSessionControl::OnRecordingChange().
5951 */
5952HRESULT Console::i_onRecordingChange(BOOL fEnabled)
5953{
5954 AutoCaller autoCaller(this);
5955 AssertComRCReturnRC(autoCaller.rc());
5956
5957 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5958
5959 HRESULT rc = S_OK;
5960#ifdef VBOX_WITH_RECORDING
5961 /* Don't trigger recording changes if the VM isn't running. */
5962 SafeVMPtrQuiet ptrVM(this);
5963 if (ptrVM.isOk())
5964 {
5965 LogFlowThisFunc(("fEnabled=%RTbool\n", RT_BOOL(fEnabled)));
5966
5967 int vrc = i_recordingEnable(fEnabled, &alock);
5968 if (RT_SUCCESS(vrc))
5969 {
5970 alock.release();
5971 ::FireRecordingChangedEvent(mEventSource);
5972 }
5973
5974 ptrVM.release();
5975 }
5976#else
5977 RT_NOREF(fEnabled);
5978#endif /* VBOX_WITH_RECORDING */
5979 return rc;
5980}
5981
5982/**
5983 * Called by IInternalSessionControl::OnUSBControllerChange().
5984 */
5985HRESULT Console::i_onUSBControllerChange()
5986{
5987 LogFlowThisFunc(("\n"));
5988
5989 AutoCaller autoCaller(this);
5990 AssertComRCReturnRC(autoCaller.rc());
5991
5992 ::FireUSBControllerChangedEvent(mEventSource);
5993
5994 return S_OK;
5995}
5996
5997/**
5998 * Called by IInternalSessionControl::OnSharedFolderChange().
5999 *
6000 * @note Locks this object for writing.
6001 */
6002HRESULT Console::i_onSharedFolderChange(BOOL aGlobal)
6003{
6004 LogFlowThisFunc(("aGlobal=%RTbool\n", aGlobal));
6005
6006 AutoCaller autoCaller(this);
6007 AssertComRCReturnRC(autoCaller.rc());
6008
6009 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6010
6011 HRESULT rc = i_fetchSharedFolders(aGlobal);
6012
6013 /* notify console callbacks on success */
6014 if (SUCCEEDED(rc))
6015 {
6016 alock.release();
6017 ::FireSharedFolderChangedEvent(mEventSource, aGlobal ? Scope_Global : Scope_Machine);
6018 }
6019
6020 return rc;
6021}
6022
6023/**
6024 * Called by IInternalSessionControl::OnUSBDeviceAttach() or locally by
6025 * processRemoteUSBDevices() after IInternalMachineControl::RunUSBDeviceFilters()
6026 * returns TRUE for a given remote USB device.
6027 *
6028 * @return S_OK if the device was attached to the VM.
6029 * @return failure if not attached.
6030 *
6031 * @param aDevice The device in question.
6032 * @param aError Error information.
6033 * @param aMaskedIfs The interfaces to hide from the guest.
6034 * @param aCaptureFilename File name where to store the USB traffic.
6035 *
6036 * @note Locks this object for writing.
6037 */
6038HRESULT Console::i_onUSBDeviceAttach(IUSBDevice *aDevice, IVirtualBoxErrorInfo *aError, ULONG aMaskedIfs,
6039 const Utf8Str &aCaptureFilename)
6040{
6041#ifdef VBOX_WITH_USB
6042 LogFlowThisFunc(("aDevice=%p aError=%p\n", aDevice, aError));
6043
6044 AutoCaller autoCaller(this);
6045 ComAssertComRCRetRC(autoCaller.rc());
6046
6047 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6048
6049 /* Get the VM pointer (we don't need error info, since it's a callback). */
6050 SafeVMPtrQuiet ptrVM(this);
6051 if (!ptrVM.isOk())
6052 {
6053 /* The VM may be no more operational when this message arrives
6054 * (e.g. it may be Saving or Stopping or just PoweredOff) --
6055 * autoVMCaller.rc() will return a failure in this case. */
6056 LogFlowThisFunc(("Attach request ignored (mMachineState=%d).\n", mMachineState));
6057 return ptrVM.rc();
6058 }
6059
6060 if (aError != NULL)
6061 {
6062 /* notify callbacks about the error */
6063 alock.release();
6064 i_onUSBDeviceStateChange(aDevice, true /* aAttached */, aError);
6065 return S_OK;
6066 }
6067
6068 /* Don't proceed unless there's at least one USB hub. */
6069 if (!ptrVM.vtable()->pfnPDMR3UsbHasHub(ptrVM.rawUVM()))
6070 {
6071 LogFlowThisFunc(("Attach request ignored (no USB controller).\n"));
6072 return E_FAIL;
6073 }
6074
6075 alock.release();
6076 HRESULT rc = i_attachUSBDevice(aDevice, aMaskedIfs, aCaptureFilename);
6077 if (FAILED(rc))
6078 {
6079 /* take the current error info */
6080 com::ErrorInfoKeeper eik;
6081 /* the error must be a VirtualBoxErrorInfo instance */
6082 ComPtr<IVirtualBoxErrorInfo> pError = eik.takeError();
6083 Assert(!pError.isNull());
6084 if (!pError.isNull())
6085 {
6086 /* notify callbacks about the error */
6087 i_onUSBDeviceStateChange(aDevice, true /* aAttached */, pError);
6088 }
6089 }
6090
6091 return rc;
6092
6093#else /* !VBOX_WITH_USB */
6094 RT_NOREF(aDevice, aError, aMaskedIfs, aCaptureFilename);
6095 return E_FAIL;
6096#endif /* !VBOX_WITH_USB */
6097}
6098
6099/**
6100 * Called by IInternalSessionControl::OnUSBDeviceDetach() and locally by
6101 * processRemoteUSBDevices().
6102 *
6103 * @note Locks this object for writing.
6104 */
6105HRESULT Console::i_onUSBDeviceDetach(IN_BSTR aId,
6106 IVirtualBoxErrorInfo *aError)
6107{
6108#ifdef VBOX_WITH_USB
6109 Guid Uuid(aId);
6110 LogFlowThisFunc(("aId={%RTuuid} aError=%p\n", Uuid.raw(), aError));
6111
6112 AutoCaller autoCaller(this);
6113 AssertComRCReturnRC(autoCaller.rc());
6114
6115 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6116
6117 /* Find the device. */
6118 ComObjPtr<OUSBDevice> pUSBDevice;
6119 USBDeviceList::iterator it = mUSBDevices.begin();
6120 while (it != mUSBDevices.end())
6121 {
6122 LogFlowThisFunc(("it={%RTuuid}\n", (*it)->i_id().raw()));
6123 if ((*it)->i_id() == Uuid)
6124 {
6125 pUSBDevice = *it;
6126 break;
6127 }
6128 ++it;
6129 }
6130
6131
6132 if (pUSBDevice.isNull())
6133 {
6134 LogFlowThisFunc(("USB device not found.\n"));
6135
6136 /* The VM may be no more operational when this message arrives
6137 * (e.g. it may be Saving or Stopping or just PoweredOff). Use
6138 * AutoVMCaller to detect it -- AutoVMCaller::rc() will return a
6139 * failure in this case. */
6140
6141 AutoVMCallerQuiet autoVMCaller(this);
6142 if (FAILED(autoVMCaller.rc()))
6143 {
6144 LogFlowThisFunc(("Detach request ignored (mMachineState=%d).\n",
6145 mMachineState));
6146 return autoVMCaller.rc();
6147 }
6148
6149 /* the device must be in the list otherwise */
6150 AssertFailedReturn(E_FAIL);
6151 }
6152
6153 if (aError != NULL)
6154 {
6155 /* notify callback about an error */
6156 alock.release();
6157 i_onUSBDeviceStateChange(pUSBDevice, false /* aAttached */, aError);
6158 return S_OK;
6159 }
6160
6161 /* Remove the device from the collection, it is re-added below for failures */
6162 mUSBDevices.erase(it);
6163
6164 alock.release();
6165 HRESULT rc = i_detachUSBDevice(pUSBDevice);
6166 if (FAILED(rc))
6167 {
6168 /* Re-add the device to the collection */
6169 alock.acquire();
6170 mUSBDevices.push_back(pUSBDevice);
6171 alock.release();
6172 /* take the current error info */
6173 com::ErrorInfoKeeper eik;
6174 /* the error must be a VirtualBoxErrorInfo instance */
6175 ComPtr<IVirtualBoxErrorInfo> pError = eik.takeError();
6176 Assert(!pError.isNull());
6177 if (!pError.isNull())
6178 {
6179 /* notify callbacks about the error */
6180 i_onUSBDeviceStateChange(pUSBDevice, false /* aAttached */, pError);
6181 }
6182 }
6183
6184 return rc;
6185
6186#else /* !VBOX_WITH_USB */
6187 RT_NOREF(aId, aError);
6188 return E_FAIL;
6189#endif /* !VBOX_WITH_USB */
6190}
6191
6192/**
6193 * Called by IInternalSessionControl::OnBandwidthGroupChange().
6194 *
6195 * @note Locks this object for writing.
6196 */
6197HRESULT Console::i_onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
6198{
6199 LogFlowThisFunc(("\n"));
6200
6201 AutoCaller autoCaller(this);
6202 AssertComRCReturnRC(autoCaller.rc());
6203
6204 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6205
6206 HRESULT rc = S_OK;
6207
6208 /* don't trigger bandwidth group changes if the VM isn't running */
6209 SafeVMPtrQuiet ptrVM(this);
6210 if (ptrVM.isOk())
6211 {
6212 if ( mMachineState == MachineState_Running
6213 || mMachineState == MachineState_Teleporting
6214 || mMachineState == MachineState_LiveSnapshotting
6215 )
6216 {
6217 /* No need to call in the EMT thread. */
6218 Bstr bstrName;
6219 rc = aBandwidthGroup->COMGETTER(Name)(bstrName.asOutParam());
6220 if (SUCCEEDED(rc))
6221 {
6222 Utf8Str const strName(bstrName);
6223 LONG64 cMax;
6224 rc = aBandwidthGroup->COMGETTER(MaxBytesPerSec)(&cMax);
6225 if (SUCCEEDED(rc))
6226 {
6227 BandwidthGroupType_T enmType;
6228 rc = aBandwidthGroup->COMGETTER(Type)(&enmType);
6229 if (SUCCEEDED(rc))
6230 {
6231 int vrc = VINF_SUCCESS;
6232 if (enmType == BandwidthGroupType_Disk)
6233 vrc = ptrVM.vtable()->pfnPDMR3AsyncCompletionBwMgrSetMaxForFile(ptrVM.rawUVM(), strName.c_str(),
6234 (uint32_t)cMax);
6235#ifdef VBOX_WITH_NETSHAPER
6236 else if (enmType == BandwidthGroupType_Network)
6237 vrc = ptrVM.vtable()->pfnPDMR3NsBwGroupSetLimit(ptrVM.rawUVM(), strName.c_str(), cMax);
6238 else
6239 rc = E_NOTIMPL;
6240#endif
6241 AssertRC(vrc);
6242 }
6243 }
6244 }
6245 }
6246 else
6247 rc = i_setInvalidMachineStateError();
6248 ptrVM.release();
6249 }
6250
6251 /* notify console callbacks on success */
6252 if (SUCCEEDED(rc))
6253 {
6254 alock.release();
6255 ::FireBandwidthGroupChangedEvent(mEventSource, aBandwidthGroup);
6256 }
6257
6258 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
6259 return rc;
6260}
6261
6262/**
6263 * Called by IInternalSessionControl::OnStorageDeviceChange().
6264 *
6265 * @note Locks this object for writing.
6266 */
6267HRESULT Console::i_onStorageDeviceChange(IMediumAttachment *aMediumAttachment, BOOL aRemove, BOOL aSilent)
6268{
6269 LogFlowThisFunc(("\n"));
6270
6271 AutoCaller autoCaller(this);
6272 AssertComRCReturnRC(autoCaller.rc());
6273
6274 HRESULT rc = S_OK;
6275
6276 /* don't trigger medium changes if the VM isn't running */
6277 SafeVMPtrQuiet ptrVM(this);
6278 if (ptrVM.isOk())
6279 {
6280 if (aRemove)
6281 rc = i_doStorageDeviceDetach(aMediumAttachment, ptrVM.rawUVM(), ptrVM.vtable(), RT_BOOL(aSilent));
6282 else
6283 rc = i_doStorageDeviceAttach(aMediumAttachment, ptrVM.rawUVM(), ptrVM.vtable(), RT_BOOL(aSilent));
6284 ptrVM.release();
6285 }
6286
6287 /* notify console callbacks on success */
6288 if (SUCCEEDED(rc))
6289 ::FireStorageDeviceChangedEvent(mEventSource, aMediumAttachment, aRemove, aSilent);
6290
6291 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
6292 return rc;
6293}
6294
6295HRESULT Console::i_onExtraDataChange(const Bstr &aMachineId, const Bstr &aKey, const Bstr &aVal)
6296{
6297 LogFlowThisFunc(("\n"));
6298
6299 AutoCaller autoCaller(this);
6300 if (FAILED(autoCaller.rc()))
6301 return autoCaller.rc();
6302
6303 if (aMachineId != i_getId())
6304 return S_OK;
6305
6306 /* don't do anything if the VM isn't running */
6307 if (aKey == "VBoxInternal2/TurnResetIntoPowerOff")
6308 {
6309 SafeVMPtrQuiet ptrVM(this);
6310 if (ptrVM.isOk())
6311 {
6312 mfTurnResetIntoPowerOff = aVal == "1";
6313 int vrc = ptrVM.vtable()->pfnVMR3SetPowerOffInsteadOfReset(ptrVM.rawUVM(), mfTurnResetIntoPowerOff);
6314 AssertRC(vrc);
6315
6316 ptrVM.release();
6317 }
6318 }
6319
6320 /* notify console callbacks on success */
6321 ::FireExtraDataChangedEvent(mEventSource, aMachineId.raw(), aKey.raw(), aVal.raw());
6322
6323 LogFlowThisFunc(("Leaving S_OK\n"));
6324 return S_OK;
6325}
6326
6327/**
6328 * @note Temporarily locks this object for writing.
6329 */
6330HRESULT Console::i_getGuestProperty(const Utf8Str &aName, Utf8Str *aValue, LONG64 *aTimestamp, Utf8Str *aFlags)
6331{
6332#ifndef VBOX_WITH_GUEST_PROPS
6333 ReturnComNotImplemented();
6334#else /* VBOX_WITH_GUEST_PROPS */
6335 if (!RT_VALID_PTR(aValue))
6336 return E_POINTER;
6337 if (aTimestamp != NULL && !RT_VALID_PTR(aTimestamp))
6338 return E_POINTER;
6339 if (aFlags != NULL && !RT_VALID_PTR(aFlags))
6340 return E_POINTER;
6341
6342 AutoCaller autoCaller(this);
6343 AssertComRCReturnRC(autoCaller.rc());
6344
6345 /* protect mpUVM (if not NULL) */
6346 SafeVMPtrQuiet ptrVM(this);
6347 if (FAILED(ptrVM.rc()))
6348 return ptrVM.rc();
6349
6350 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
6351 * ptrVM, so there is no need to hold a lock of this */
6352
6353 HRESULT rc = E_UNEXPECTED;
6354 try
6355 {
6356 VBOXHGCMSVCPARM parm[4];
6357 char szBuffer[GUEST_PROP_MAX_VALUE_LEN + GUEST_PROP_MAX_FLAGS_LEN];
6358
6359 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
6360 parm[0].u.pointer.addr = (void *)aName.c_str();
6361 parm[0].u.pointer.size = (uint32_t)aName.length() + 1; /* The + 1 is the null terminator */
6362
6363 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
6364 parm[1].u.pointer.addr = szBuffer;
6365 parm[1].u.pointer.size = sizeof(szBuffer);
6366
6367 parm[2].type = VBOX_HGCM_SVC_PARM_64BIT;
6368 parm[2].u.uint64 = 0;
6369
6370 parm[3].type = VBOX_HGCM_SVC_PARM_32BIT;
6371 parm[3].u.uint32 = 0;
6372
6373 int vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GUEST_PROP_FN_HOST_GET_PROP,
6374 4, &parm[0]);
6375 /* The returned string should never be able to be greater than our buffer */
6376 AssertLogRel(vrc != VERR_BUFFER_OVERFLOW);
6377 AssertLogRel(RT_FAILURE(vrc) || parm[2].type == VBOX_HGCM_SVC_PARM_64BIT);
6378 if (RT_SUCCESS(vrc))
6379 {
6380 *aValue = szBuffer;
6381
6382 if (aTimestamp)
6383 *aTimestamp = parm[2].u.uint64;
6384
6385 if (aFlags)
6386 *aFlags = &szBuffer[strlen(szBuffer) + 1];
6387
6388 rc = S_OK;
6389 }
6390 else if (vrc == VERR_NOT_FOUND)
6391 {
6392 *aValue = "";
6393 rc = S_OK;
6394 }
6395 else
6396 rc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("The VBoxGuestPropSvc service call failed with the error %Rrc"), vrc);
6397 }
6398 catch(std::bad_alloc & /*e*/)
6399 {
6400 rc = E_OUTOFMEMORY;
6401 }
6402
6403 return rc;
6404#endif /* VBOX_WITH_GUEST_PROPS */
6405}
6406
6407/**
6408 * @note Temporarily locks this object for writing.
6409 */
6410HRESULT Console::i_setGuestProperty(const Utf8Str &aName, const Utf8Str &aValue, const Utf8Str &aFlags)
6411{
6412#ifndef VBOX_WITH_GUEST_PROPS
6413 ReturnComNotImplemented();
6414#else /* VBOX_WITH_GUEST_PROPS */
6415
6416 AutoCaller autoCaller(this);
6417 AssertComRCReturnRC(autoCaller.rc());
6418
6419 /* protect mpUVM (if not NULL) */
6420 SafeVMPtrQuiet ptrVM(this);
6421 if (FAILED(ptrVM.rc()))
6422 return ptrVM.rc();
6423
6424 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
6425 * ptrVM, so there is no need to hold a lock of this */
6426
6427 VBOXHGCMSVCPARM parm[3];
6428
6429 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
6430 parm[0].u.pointer.addr = (void*)aName.c_str();
6431 parm[0].u.pointer.size = (uint32_t)aName.length() + 1; /* The + 1 is the null terminator */
6432
6433 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
6434 parm[1].u.pointer.addr = (void *)aValue.c_str();
6435 parm[1].u.pointer.size = (uint32_t)aValue.length() + 1; /* The + 1 is the null terminator */
6436
6437 int vrc;
6438 if (aFlags.isEmpty())
6439 {
6440 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GUEST_PROP_FN_HOST_SET_PROP_VALUE, 2, &parm[0]);
6441 }
6442 else
6443 {
6444 parm[2].type = VBOX_HGCM_SVC_PARM_PTR;
6445 parm[2].u.pointer.addr = (void*)aFlags.c_str();
6446 parm[2].u.pointer.size = (uint32_t)aFlags.length() + 1; /* The + 1 is the null terminator */
6447
6448 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GUEST_PROP_FN_HOST_SET_PROP, 3, &parm[0]);
6449 }
6450
6451 HRESULT hrc = S_OK;
6452 if (RT_FAILURE(vrc))
6453 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("The VBoxGuestPropSvc service call failed with the error %Rrc"), vrc);
6454 return hrc;
6455#endif /* VBOX_WITH_GUEST_PROPS */
6456}
6457
6458HRESULT Console::i_deleteGuestProperty(const Utf8Str &aName)
6459{
6460#ifndef VBOX_WITH_GUEST_PROPS
6461 ReturnComNotImplemented();
6462#else /* VBOX_WITH_GUEST_PROPS */
6463
6464 AutoCaller autoCaller(this);
6465 AssertComRCReturnRC(autoCaller.rc());
6466
6467 /* protect mpUVM (if not NULL) */
6468 SafeVMPtrQuiet ptrVM(this);
6469 if (FAILED(ptrVM.rc()))
6470 return ptrVM.rc();
6471
6472 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
6473 * ptrVM, so there is no need to hold a lock of this */
6474
6475 VBOXHGCMSVCPARM parm[1];
6476 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
6477 parm[0].u.pointer.addr = (void*)aName.c_str();
6478 parm[0].u.pointer.size = (uint32_t)aName.length() + 1; /* The + 1 is the null terminator */
6479
6480 int vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GUEST_PROP_FN_HOST_DEL_PROP, 1, &parm[0]);
6481
6482 HRESULT hrc = S_OK;
6483 if (RT_FAILURE(vrc))
6484 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("The VBoxGuestPropSvc service call failed with the error %Rrc"), vrc);
6485 return hrc;
6486#endif /* VBOX_WITH_GUEST_PROPS */
6487}
6488
6489/**
6490 * @note Temporarily locks this object for writing.
6491 */
6492HRESULT Console::i_enumerateGuestProperties(const Utf8Str &aPatterns,
6493 std::vector<Utf8Str> &aNames,
6494 std::vector<Utf8Str> &aValues,
6495 std::vector<LONG64> &aTimestamps,
6496 std::vector<Utf8Str> &aFlags)
6497{
6498#ifndef VBOX_WITH_GUEST_PROPS
6499 ReturnComNotImplemented();
6500#else /* VBOX_WITH_GUEST_PROPS */
6501
6502 AutoCaller autoCaller(this);
6503 AssertComRCReturnRC(autoCaller.rc());
6504
6505 /* protect mpUVM (if not NULL) */
6506 AutoVMCallerWeak autoVMCaller(this);
6507 if (FAILED(autoVMCaller.rc()))
6508 return autoVMCaller.rc();
6509
6510 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
6511 * autoVMCaller, so there is no need to hold a lock of this */
6512
6513 return i_doEnumerateGuestProperties(aPatterns, aNames, aValues, aTimestamps, aFlags);
6514#endif /* VBOX_WITH_GUEST_PROPS */
6515}
6516
6517
6518/*
6519 * Internal: helper function for connecting progress reporting
6520 */
6521static DECLCALLBACK(int) onlineMergeMediumProgress(void *pvUser, unsigned uPercentage)
6522{
6523 HRESULT rc = S_OK;
6524 IProgress *pProgress = static_cast<IProgress *>(pvUser);
6525 if (pProgress)
6526 {
6527 ComPtr<IInternalProgressControl> pProgressControl(pProgress);
6528 AssertReturn(!!pProgressControl, VERR_INVALID_PARAMETER);
6529 rc = pProgressControl->SetCurrentOperationProgress(uPercentage);
6530 }
6531 return SUCCEEDED(rc) ? VINF_SUCCESS : VERR_GENERAL_FAILURE;
6532}
6533
6534/**
6535 * @note Temporarily locks this object for writing. bird: And/or reading?
6536 */
6537HRESULT Console::i_onlineMergeMedium(IMediumAttachment *aMediumAttachment,
6538 ULONG aSourceIdx, ULONG aTargetIdx,
6539 IProgress *aProgress)
6540{
6541 AutoCaller autoCaller(this);
6542 AssertComRCReturnRC(autoCaller.rc());
6543
6544 HRESULT rc = S_OK;
6545 int vrc = VINF_SUCCESS;
6546
6547 /* Get the VM - must be done before the read-locking. */
6548 SafeVMPtr ptrVM(this);
6549 if (!ptrVM.isOk())
6550 return ptrVM.rc();
6551
6552 /* We will need to release the lock before doing the actual merge */
6553 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6554
6555 /* paranoia - we don't want merges to happen while teleporting etc. */
6556 switch (mMachineState)
6557 {
6558 case MachineState_DeletingSnapshotOnline:
6559 case MachineState_DeletingSnapshotPaused:
6560 break;
6561
6562 default:
6563 return i_setInvalidMachineStateError();
6564 }
6565
6566 /** @todo AssertComRC -> AssertComRCReturn! Could potentially end up
6567 * using uninitialized variables here. */
6568 BOOL fBuiltinIOCache;
6569 rc = mMachine->COMGETTER(IOCacheEnabled)(&fBuiltinIOCache);
6570 AssertComRC(rc);
6571 SafeIfaceArray<IStorageController> ctrls;
6572 rc = mMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));
6573 AssertComRC(rc);
6574 LONG lDev;
6575 rc = aMediumAttachment->COMGETTER(Device)(&lDev);
6576 AssertComRC(rc);
6577 LONG lPort;
6578 rc = aMediumAttachment->COMGETTER(Port)(&lPort);
6579 AssertComRC(rc);
6580 IMedium *pMedium;
6581 rc = aMediumAttachment->COMGETTER(Medium)(&pMedium);
6582 AssertComRC(rc);
6583 Bstr mediumLocation;
6584 if (pMedium)
6585 {
6586 rc = pMedium->COMGETTER(Location)(mediumLocation.asOutParam());
6587 AssertComRC(rc);
6588 }
6589
6590 Bstr attCtrlName;
6591 rc = aMediumAttachment->COMGETTER(Controller)(attCtrlName.asOutParam());
6592 AssertComRC(rc);
6593 ComPtr<IStorageController> pStorageController;
6594 for (size_t i = 0; i < ctrls.size(); ++i)
6595 {
6596 Bstr ctrlName;
6597 rc = ctrls[i]->COMGETTER(Name)(ctrlName.asOutParam());
6598 AssertComRC(rc);
6599 if (attCtrlName == ctrlName)
6600 {
6601 pStorageController = ctrls[i];
6602 break;
6603 }
6604 }
6605 if (pStorageController.isNull())
6606 return setError(E_FAIL,
6607 tr("Could not find storage controller '%ls'"),
6608 attCtrlName.raw());
6609
6610 StorageControllerType_T enmCtrlType;
6611 rc = pStorageController->COMGETTER(ControllerType)(&enmCtrlType);
6612 AssertComRC(rc);
6613 const char *pcszDevice = i_storageControllerTypeToStr(enmCtrlType);
6614
6615 StorageBus_T enmBus;
6616 rc = pStorageController->COMGETTER(Bus)(&enmBus);
6617 AssertComRC(rc);
6618 ULONG uInstance;
6619 rc = pStorageController->COMGETTER(Instance)(&uInstance);
6620 AssertComRC(rc);
6621 BOOL fUseHostIOCache;
6622 rc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
6623 AssertComRC(rc);
6624
6625 unsigned uLUN;
6626 rc = Console::i_storageBusPortDeviceToLun(enmBus, lPort, lDev, uLUN);
6627 AssertComRCReturnRC(rc);
6628
6629 Assert(mMachineState == MachineState_DeletingSnapshotOnline);
6630
6631 /* Pause the VM, as it might have pending IO on this drive */
6632 bool fResume = false;
6633 rc = i_suspendBeforeConfigChange(ptrVM.rawUVM(), ptrVM.vtable(), &alock, &fResume);
6634 if (FAILED(rc))
6635 return rc;
6636
6637 bool fInsertDiskIntegrityDrv = false;
6638 Bstr strDiskIntegrityFlag;
6639 rc = mMachine->GetExtraData(Bstr("VBoxInternal2/EnableDiskIntegrityDriver").raw(),
6640 strDiskIntegrityFlag.asOutParam());
6641 if ( rc == S_OK
6642 && strDiskIntegrityFlag == "1")
6643 fInsertDiskIntegrityDrv = true;
6644
6645 alock.release();
6646 vrc = ptrVM.vtable()->pfnVMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY,
6647 (PFNRT)i_reconfigureMediumAttachment, 15,
6648 this, ptrVM.rawUVM(), ptrVM.vtable(), pcszDevice, uInstance, enmBus,
6649 fUseHostIOCache, fBuiltinIOCache, fInsertDiskIntegrityDrv, true /* fSetupMerge */,
6650 aSourceIdx, aTargetIdx, aMediumAttachment, mMachineState, &rc);
6651 /* error handling is after resuming the VM */
6652
6653 if (fResume)
6654 i_resumeAfterConfigChange(ptrVM.rawUVM(), ptrVM.vtable());
6655
6656 if (RT_FAILURE(vrc))
6657 return setErrorBoth(E_FAIL, vrc, "%Rrc", vrc);
6658 if (FAILED(rc))
6659 return rc;
6660
6661 PPDMIBASE pIBase = NULL;
6662 PPDMIMEDIA pIMedium = NULL;
6663 vrc = ptrVM.vtable()->pfnPDMR3QueryDriverOnLun(ptrVM.rawUVM(), pcszDevice, uInstance, uLUN, "VD", &pIBase);
6664 if (RT_SUCCESS(vrc))
6665 {
6666 if (pIBase)
6667 {
6668 pIMedium = (PPDMIMEDIA)pIBase->pfnQueryInterface(pIBase, PDMIMEDIA_IID);
6669 if (!pIMedium)
6670 return setError(E_FAIL, tr("could not query medium interface of controller"));
6671 }
6672 else
6673 return setError(E_FAIL, tr("could not query base interface of controller"));
6674 }
6675
6676 /* Finally trigger the merge. */
6677 vrc = pIMedium->pfnMerge(pIMedium, onlineMergeMediumProgress, aProgress);
6678 if (RT_FAILURE(vrc))
6679 return setErrorBoth(E_FAIL, vrc, tr("Failed to perform an online medium merge (%Rrc)"), vrc);
6680
6681 alock.acquire();
6682 /* Pause the VM, as it might have pending IO on this drive */
6683 rc = i_suspendBeforeConfigChange(ptrVM.rawUVM(), ptrVM.vtable(), &alock, &fResume);
6684 if (FAILED(rc))
6685 return rc;
6686 alock.release();
6687
6688 /* Update medium chain and state now, so that the VM can continue. */
6689 rc = mControl->FinishOnlineMergeMedium();
6690
6691 vrc = ptrVM.vtable()->pfnVMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY,
6692 (PFNRT)i_reconfigureMediumAttachment, 15,
6693 this, ptrVM.rawUVM(), ptrVM.vtable(), pcszDevice, uInstance, enmBus,
6694 fUseHostIOCache, fBuiltinIOCache, fInsertDiskIntegrityDrv, false /* fSetupMerge */,
6695 0 /* uMergeSource */, 0 /* uMergeTarget */, aMediumAttachment, mMachineState, &rc);
6696 /* error handling is after resuming the VM */
6697
6698 if (fResume)
6699 i_resumeAfterConfigChange(ptrVM.rawUVM(), ptrVM.vtable());
6700
6701 if (RT_FAILURE(vrc))
6702 return setErrorBoth(E_FAIL, vrc, "%Rrc", vrc);
6703 if (FAILED(rc))
6704 return rc;
6705
6706 return rc;
6707}
6708
6709HRESULT Console::i_reconfigureMediumAttachments(const std::vector<ComPtr<IMediumAttachment> > &aAttachments)
6710{
6711 HRESULT rc = S_OK;
6712
6713 AutoCaller autoCaller(this);
6714 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6715
6716 /* get the VM handle. */
6717 SafeVMPtr ptrVM(this);
6718 if (!ptrVM.isOk())
6719 return ptrVM.rc();
6720
6721 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6722
6723 for (size_t i = 0; i < aAttachments.size(); ++i)
6724 {
6725 ComPtr<IStorageController> pStorageController;
6726 Bstr controllerName;
6727 ULONG lInstance;
6728 StorageControllerType_T enmController;
6729 StorageBus_T enmBus;
6730 BOOL fUseHostIOCache;
6731
6732 /*
6733 * We could pass the objects, but then EMT would have to do lots of
6734 * IPC (to VBoxSVC) which takes a significant amount of time.
6735 * Better query needed values here and pass them.
6736 */
6737 rc = aAttachments[i]->COMGETTER(Controller)(controllerName.asOutParam());
6738 if (FAILED(rc))
6739 throw rc;
6740
6741 rc = mMachine->GetStorageControllerByName(controllerName.raw(), pStorageController.asOutParam());
6742 if (FAILED(rc))
6743 throw rc;
6744
6745 rc = pStorageController->COMGETTER(ControllerType)(&enmController);
6746 if (FAILED(rc))
6747 throw rc;
6748 rc = pStorageController->COMGETTER(Instance)(&lInstance);
6749 if (FAILED(rc))
6750 throw rc;
6751 rc = pStorageController->COMGETTER(Bus)(&enmBus);
6752 if (FAILED(rc))
6753 throw rc;
6754 rc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
6755 if (FAILED(rc))
6756 throw rc;
6757
6758 const char *pcszDevice = i_storageControllerTypeToStr(enmController);
6759
6760 BOOL fBuiltinIOCache;
6761 rc = mMachine->COMGETTER(IOCacheEnabled)(&fBuiltinIOCache);
6762 if (FAILED(rc))
6763 throw rc;
6764
6765 bool fInsertDiskIntegrityDrv = false;
6766 Bstr strDiskIntegrityFlag;
6767 rc = mMachine->GetExtraData(Bstr("VBoxInternal2/EnableDiskIntegrityDriver").raw(),
6768 strDiskIntegrityFlag.asOutParam());
6769 if ( rc == S_OK
6770 && strDiskIntegrityFlag == "1")
6771 fInsertDiskIntegrityDrv = true;
6772
6773 alock.release();
6774
6775 IMediumAttachment *pAttachment = aAttachments[i];
6776 int vrc = ptrVM.vtable()->pfnVMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY,
6777 (PFNRT)i_reconfigureMediumAttachment, 15,
6778 this, ptrVM.rawUVM(), ptrVM.vtable(), pcszDevice, lInstance, enmBus,
6779 fUseHostIOCache, fBuiltinIOCache, fInsertDiskIntegrityDrv,
6780 false /* fSetupMerge */, 0 /* uMergeSource */, 0 /* uMergeTarget */,
6781 pAttachment, mMachineState, &rc);
6782 if (RT_FAILURE(vrc))
6783 throw setErrorBoth(E_FAIL, vrc, "%Rrc", vrc);
6784 if (FAILED(rc))
6785 throw rc;
6786
6787 alock.acquire();
6788 }
6789
6790 return rc;
6791}
6792
6793HRESULT Console::i_onVMProcessPriorityChange(VMProcPriority_T priority)
6794{
6795 HRESULT rc = S_OK;
6796
6797 AutoCaller autoCaller(this);
6798 if (FAILED(autoCaller.rc()))
6799 return autoCaller.rc();
6800
6801 RTPROCPRIORITY enmProcPriority = RTPROCPRIORITY_DEFAULT;
6802 switch (priority)
6803 {
6804 case VMProcPriority_Default:
6805 enmProcPriority = RTPROCPRIORITY_DEFAULT;
6806 break;
6807 case VMProcPriority_Flat:
6808 enmProcPriority = RTPROCPRIORITY_FLAT;
6809 break;
6810 case VMProcPriority_Low:
6811 enmProcPriority = RTPROCPRIORITY_LOW;
6812 break;
6813 case VMProcPriority_Normal:
6814 enmProcPriority = RTPROCPRIORITY_NORMAL;
6815 break;
6816 case VMProcPriority_High:
6817 enmProcPriority = RTPROCPRIORITY_HIGH;
6818 break;
6819 default:
6820 return setError(E_INVALIDARG, tr("Unsupported priority type (%d)"), priority);
6821 }
6822 int vrc = RTProcSetPriority(enmProcPriority);
6823 if (RT_FAILURE(vrc))
6824 rc = setErrorBoth(VBOX_E_VM_ERROR, vrc,
6825 tr("Could not set the priority of the process (%Rrc). Try to set it when VM is not started."), vrc);
6826
6827 return rc;
6828}
6829
6830/**
6831 * Load an HGCM service.
6832 *
6833 * Main purpose of this method is to allow extension packs to load HGCM
6834 * service modules, which they can't, because the HGCM functionality lives
6835 * in module VBoxC (and ConsoleImpl.cpp is part of it and thus can call it).
6836 * Extension modules must not link directly against VBoxC, (XP)COM is
6837 * handling this.
6838 */
6839int Console::i_hgcmLoadService(const char *pszServiceLibrary, const char *pszServiceName)
6840{
6841 /* Everyone seems to delegate all HGCM calls to VMMDev, so stick to this
6842 * convention. Adds one level of indirection for no obvious reason. */
6843 AssertPtrReturn(m_pVMMDev, VERR_INVALID_STATE);
6844 return m_pVMMDev->hgcmLoadService(pszServiceLibrary, pszServiceName);
6845}
6846
6847/**
6848 * Merely passes the call to Guest::enableVMMStatistics().
6849 */
6850void Console::i_enableVMMStatistics(BOOL aEnable)
6851{
6852 if (mGuest)
6853 mGuest->i_enableVMMStatistics(aEnable);
6854}
6855
6856/**
6857 * Worker for Console::Pause and internal entry point for pausing a VM for
6858 * a specific reason.
6859 */
6860HRESULT Console::i_pause(Reason_T aReason)
6861{
6862 LogFlowThisFuncEnter();
6863
6864 AutoCaller autoCaller(this);
6865 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6866
6867 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6868
6869 switch (mMachineState)
6870 {
6871 case MachineState_Running:
6872 case MachineState_Teleporting:
6873 case MachineState_LiveSnapshotting:
6874 break;
6875
6876 case MachineState_Paused:
6877 case MachineState_TeleportingPausedVM:
6878 case MachineState_OnlineSnapshotting:
6879 /* Remove any keys which are supposed to be removed on a suspend. */
6880 if ( aReason == Reason_HostSuspend
6881 || aReason == Reason_HostBatteryLow)
6882 {
6883 i_removeSecretKeysOnSuspend();
6884 return S_OK;
6885 }
6886 return setError(VBOX_E_INVALID_VM_STATE, tr("Already paused"));
6887
6888 default:
6889 return i_setInvalidMachineStateError();
6890 }
6891
6892 /* get the VM handle. */
6893 SafeVMPtr ptrVM(this);
6894 HRESULT hrc = ptrVM.rc();
6895 if (SUCCEEDED(hrc))
6896 {
6897 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
6898 alock.release();
6899
6900 LogFlowThisFunc(("Sending PAUSE request...\n"));
6901 if (aReason != Reason_Unspecified)
6902 LogRel(("Pausing VM execution, reason '%s'\n", ::stringifyReason(aReason)));
6903
6904 /** @todo r=klaus make use of aReason */
6905 VMSUSPENDREASON enmReason = VMSUSPENDREASON_USER;
6906 if (aReason == Reason_HostSuspend)
6907 enmReason = VMSUSPENDREASON_HOST_SUSPEND;
6908 else if (aReason == Reason_HostBatteryLow)
6909 enmReason = VMSUSPENDREASON_HOST_BATTERY_LOW;
6910
6911 int vrc = ptrVM.vtable()->pfnVMR3Suspend(ptrVM.rawUVM(), enmReason);
6912
6913 if (RT_FAILURE(vrc))
6914 hrc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not suspend the machine execution (%Rrc)"), vrc);
6915 else if ( aReason == Reason_HostSuspend
6916 || aReason == Reason_HostBatteryLow)
6917 {
6918 alock.acquire();
6919 i_removeSecretKeysOnSuspend();
6920 }
6921 }
6922
6923 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
6924 LogFlowThisFuncLeave();
6925 return hrc;
6926}
6927
6928/**
6929 * Worker for Console::Resume and internal entry point for resuming a VM for
6930 * a specific reason.
6931 */
6932HRESULT Console::i_resume(Reason_T aReason, AutoWriteLock &alock)
6933{
6934 LogFlowThisFuncEnter();
6935
6936 AutoCaller autoCaller(this);
6937 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6938
6939 /* get the VM handle. */
6940 SafeVMPtr ptrVM(this);
6941 if (!ptrVM.isOk())
6942 return ptrVM.rc();
6943
6944 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
6945 alock.release();
6946
6947 LogFlowThisFunc(("Sending RESUME request...\n"));
6948 if (aReason != Reason_Unspecified)
6949 LogRel(("Resuming VM execution, reason '%s'\n", ::stringifyReason(aReason)));
6950
6951 int vrc;
6952 VMSTATE const enmVMState = mpVMM->pfnVMR3GetStateU(ptrVM.rawUVM());
6953 if (enmVMState == VMSTATE_CREATED)
6954 {
6955#ifdef VBOX_WITH_EXTPACK
6956 vrc = mptrExtPackManager->i_callAllVmPowerOnHooks(this, ptrVM.vtable()->pfnVMR3GetVM(ptrVM.rawUVM()), ptrVM.vtable());
6957#else
6958 vrc = VINF_SUCCESS;
6959#endif
6960 if (RT_SUCCESS(vrc))
6961 vrc = ptrVM.vtable()->pfnVMR3PowerOn(ptrVM.rawUVM()); /* (PowerUpPaused) */
6962 }
6963 else
6964 {
6965 VMRESUMEREASON enmReason;
6966 if (aReason == Reason_HostResume)
6967 {
6968 /*
6969 * Host resume may be called multiple times successively. We don't want to VMR3Resume->vmR3Resume->vmR3TrySetState()
6970 * to assert on us, hence check for the VM state here and bail if it's not in the 'suspended' state.
6971 * See @bugref{3495}.
6972 *
6973 * Also, don't resume the VM through a host-resume unless it was suspended due to a host-suspend.
6974 */
6975 if (enmVMState != VMSTATE_SUSPENDED)
6976 {
6977 LogRel(("Ignoring VM resume request, VM is currently not suspended (%d)\n", enmVMState));
6978 return S_OK;
6979 }
6980 VMSUSPENDREASON const enmSuspendReason = ptrVM.vtable()->pfnVMR3GetSuspendReason(ptrVM.rawUVM());
6981 if (enmSuspendReason != VMSUSPENDREASON_HOST_SUSPEND)
6982 {
6983 LogRel(("Ignoring VM resume request, VM was not suspended due to host-suspend (%d)\n", enmSuspendReason));
6984 return S_OK;
6985 }
6986
6987 enmReason = VMRESUMEREASON_HOST_RESUME;
6988 }
6989 else
6990 {
6991 /*
6992 * Any other reason to resume the VM throws an error when the VM was suspended due to a host suspend.
6993 * See @bugref{7836}.
6994 */
6995 if ( enmVMState == VMSTATE_SUSPENDED
6996 && ptrVM.vtable()->pfnVMR3GetSuspendReason(ptrVM.rawUVM()) == VMSUSPENDREASON_HOST_SUSPEND)
6997 return setError(VBOX_E_INVALID_VM_STATE, tr("VM is paused due to host power management"));
6998
6999 enmReason = aReason == Reason_Snapshot ? VMRESUMEREASON_STATE_SAVED : VMRESUMEREASON_USER;
7000 }
7001
7002 // for snapshots: no state change callback, VBoxSVC does everything
7003 if (aReason == Reason_Snapshot)
7004 mVMStateChangeCallbackDisabled = true;
7005
7006 vrc = ptrVM.vtable()->pfnVMR3Resume(ptrVM.rawUVM(), enmReason);
7007
7008 if (aReason == Reason_Snapshot)
7009 mVMStateChangeCallbackDisabled = false;
7010 }
7011
7012 HRESULT hrc = RT_SUCCESS(vrc) ? S_OK
7013 : setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not resume the machine execution (%Rrc)"), vrc);
7014
7015 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
7016 LogFlowThisFuncLeave();
7017 return hrc;
7018}
7019
7020/**
7021 * Internal entry point for saving state of a VM for a specific reason. This
7022 * method is completely synchronous.
7023 *
7024 * The machine state is already set appropriately. It is only changed when
7025 * saving state actually paused the VM (happens with live snapshots and
7026 * teleportation), and in this case reflects the now paused variant.
7027 *
7028 * @note Locks this object for writing.
7029 */
7030HRESULT Console::i_saveState(Reason_T aReason, const ComPtr<IProgress> &aProgress, const ComPtr<ISnapshot> &aSnapshot,
7031 const Utf8Str &aStateFilePath, bool aPauseVM, bool &aLeftPaused)
7032{
7033 LogFlowThisFuncEnter();
7034 aLeftPaused = false;
7035
7036 AssertReturn(!aProgress.isNull(), E_INVALIDARG);
7037 AssertReturn(!aStateFilePath.isEmpty(), E_INVALIDARG);
7038 Assert(aSnapshot.isNull() || aReason == Reason_Snapshot);
7039
7040 AutoCaller autoCaller(this);
7041 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7042
7043 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7044
7045 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
7046 if ( mMachineState != MachineState_Saving
7047 && mMachineState != MachineState_LiveSnapshotting
7048 && mMachineState != MachineState_OnlineSnapshotting
7049 && mMachineState != MachineState_Teleporting
7050 && mMachineState != MachineState_TeleportingPausedVM)
7051 return setError(VBOX_E_INVALID_VM_STATE,
7052 tr("Cannot save the execution state as the machine is not running or paused (machine state: %s)"),
7053 Global::stringifyMachineState(mMachineState));
7054 bool fContinueAfterwards = mMachineState != MachineState_Saving;
7055
7056 Bstr strDisableSaveState;
7057 mMachine->GetExtraData(Bstr("VBoxInternal2/DisableSaveState").raw(), strDisableSaveState.asOutParam());
7058 if (strDisableSaveState == "1")
7059 return setError(VBOX_E_VM_ERROR,
7060 tr("Saving the execution state is disabled for this VM"));
7061
7062 if (aReason != Reason_Unspecified)
7063 LogRel(("Saving state of VM, reason '%s'\n", ::stringifyReason(aReason)));
7064
7065 /* ensure the directory for the saved state file exists */
7066 {
7067 Utf8Str dir = aStateFilePath;
7068 dir.stripFilename();
7069 if (!RTDirExists(dir.c_str()))
7070 {
7071 int vrc = RTDirCreateFullPath(dir.c_str(), 0700);
7072 if (RT_FAILURE(vrc))
7073 return setErrorBoth(VBOX_E_FILE_ERROR, vrc, tr("Could not create a directory '%s' to save the state to (%Rrc)"),
7074 dir.c_str(), vrc);
7075 }
7076 }
7077
7078 /* Get the VM handle early, we need it in several places. */
7079 SafeVMPtr ptrVM(this);
7080 HRESULT hrc = ptrVM.rc();
7081 if (SUCCEEDED(hrc))
7082 {
7083 bool fPaused = false;
7084 if (aPauseVM)
7085 {
7086 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
7087 alock.release();
7088 VMSUSPENDREASON enmReason = VMSUSPENDREASON_USER;
7089 if (aReason == Reason_HostSuspend)
7090 enmReason = VMSUSPENDREASON_HOST_SUSPEND;
7091 else if (aReason == Reason_HostBatteryLow)
7092 enmReason = VMSUSPENDREASON_HOST_BATTERY_LOW;
7093 int vrc = ptrVM.vtable()->pfnVMR3Suspend(ptrVM.rawUVM(), enmReason);
7094 alock.acquire();
7095
7096 if (RT_SUCCESS(vrc))
7097 fPaused = true;
7098 else
7099 hrc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not suspend the machine execution (%Rrc)"), vrc);
7100 }
7101
7102 Bstr bstrStateKeyId;
7103 Bstr bstrStateKeyStore;
7104#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
7105 if (SUCCEEDED(hrc))
7106 {
7107 hrc = mMachine->COMGETTER(StateKeyId)(bstrStateKeyId.asOutParam());
7108 if (SUCCEEDED(hrc))
7109 {
7110 hrc = mMachine->COMGETTER(StateKeyStore)(bstrStateKeyStore.asOutParam());
7111 if (FAILED(hrc))
7112 hrc = setError(hrc, tr("Could not get key store for state file(%Rhrc (0x%08X))"), hrc, hrc);
7113 }
7114 else
7115 hrc = setError(hrc, tr("Could not get key id for state file(%Rhrc (0x%08X))"), hrc, hrc);
7116 }
7117#endif
7118
7119 if (SUCCEEDED(hrc))
7120 {
7121 LogFlowFunc(("Saving the state to '%s'...\n", aStateFilePath.c_str()));
7122
7123 mpVmm2UserMethods->pISnapshot = aSnapshot;
7124 mptrCancelableProgress = aProgress;
7125
7126 SsmStream ssmStream(this, ptrVM.vtable(), m_pKeyStore, bstrStateKeyId, bstrStateKeyStore);
7127 int vrc = ssmStream.create(aStateFilePath.c_str());
7128 if (RT_SUCCESS(vrc))
7129 {
7130 PCSSMSTRMOPS pStreamOps = NULL;
7131 void *pvStreamOpsUser = NULL;
7132 vrc = ssmStream.querySsmStrmOps(&pStreamOps, &pvStreamOpsUser);
7133 if (RT_SUCCESS(vrc))
7134 {
7135 alock.release();
7136
7137 vrc = ptrVM.vtable()->pfnVMR3Save(ptrVM.rawUVM(),
7138 NULL /*pszFilename*/,
7139 pStreamOps,
7140 pvStreamOpsUser,
7141 fContinueAfterwards,
7142 Console::i_stateProgressCallback,
7143 static_cast<IProgress *>(aProgress),
7144 &aLeftPaused);
7145
7146 alock.acquire();
7147 }
7148
7149 ssmStream.close();
7150 if (RT_FAILURE(vrc))
7151 {
7152 int vrc2 = RTFileDelete(aStateFilePath.c_str());
7153 AssertRC(vrc2);
7154 }
7155 }
7156
7157 mpVmm2UserMethods->pISnapshot = NULL;
7158 mptrCancelableProgress.setNull();
7159 if (RT_SUCCESS(vrc))
7160 {
7161 Assert(fContinueAfterwards || !aLeftPaused);
7162
7163 if (!fContinueAfterwards)
7164 {
7165 /*
7166 * The machine has been successfully saved, so power it down
7167 * (vmstateChangeCallback() will set state to Saved on success).
7168 * Note: we release the VM caller, otherwise it will deadlock.
7169 */
7170 ptrVM.release();
7171 alock.release();
7172 autoCaller.release();
7173
7174 HRESULT rc = i_powerDown();
7175 AssertComRC(rc);
7176
7177 autoCaller.add();
7178 alock.acquire();
7179 }
7180 else if (fPaused)
7181 aLeftPaused = true;
7182 }
7183 else
7184 {
7185 if (fPaused)
7186 {
7187 alock.release();
7188 ptrVM.vtable()->pfnVMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_STATE_RESTORED);
7189 alock.acquire();
7190 }
7191 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to save the machine state to '%s' (%Rrc)"),
7192 aStateFilePath.c_str(), vrc);
7193 }
7194 }
7195 }
7196
7197 LogFlowFuncLeave();
7198 return S_OK;
7199}
7200
7201/**
7202 * Internal entry point for cancelling a VM save state.
7203 *
7204 * @note Locks this object for writing.
7205 */
7206HRESULT Console::i_cancelSaveState()
7207{
7208 LogFlowThisFuncEnter();
7209
7210 AutoCaller autoCaller(this);
7211 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7212
7213 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7214
7215 /* Get the VM handle. */
7216 SafeVMPtr ptrVM(this);
7217 HRESULT hrc = ptrVM.rc();
7218 if (SUCCEEDED(hrc))
7219 ptrVM.vtable()->pfnSSMR3Cancel(ptrVM.rawUVM());
7220
7221 LogFlowFuncLeave();
7222 return hrc;
7223}
7224
7225#ifdef VBOX_WITH_AUDIO_RECORDING
7226/**
7227 * Sends audio (frame) data to the recording routines.
7228 *
7229 * @returns HRESULT
7230 * @param pvData Audio data to send.
7231 * @param cbData Size (in bytes) of audio data to send.
7232 * @param uTimestampMs Timestamp (in ms) of audio data.
7233 */
7234HRESULT Console::i_recordingSendAudio(const void *pvData, size_t cbData, uint64_t uTimestampMs)
7235{
7236 if ( mRecording.mCtx.IsStarted()
7237 && mRecording.mCtx.IsFeatureEnabled(RecordingFeature_Audio))
7238 return mRecording.mCtx.SendAudioFrame(pvData, cbData, uTimestampMs);
7239
7240 return S_OK;
7241}
7242#endif /* VBOX_WITH_AUDIO_RECORDING */
7243
7244#ifdef VBOX_WITH_RECORDING
7245
7246int Console::i_recordingGetSettings(settings::RecordingSettings &recording)
7247{
7248 Assert(mMachine.isNotNull());
7249
7250 recording.applyDefaults();
7251
7252 ComPtr<IRecordingSettings> pRecordSettings;
7253 HRESULT hrc = mMachine->COMGETTER(RecordingSettings)(pRecordSettings.asOutParam());
7254 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7255
7256 BOOL fTemp;
7257 hrc = pRecordSettings->COMGETTER(Enabled)(&fTemp);
7258 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7259 recording.common.fEnabled = RT_BOOL(fTemp);
7260
7261 SafeIfaceArray<IRecordingScreenSettings> paRecScreens;
7262 hrc = pRecordSettings->COMGETTER(Screens)(ComSafeArrayAsOutParam(paRecScreens));
7263 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7264
7265 for (unsigned long i = 0; i < (unsigned long)paRecScreens.size(); ++i)
7266 {
7267 settings::RecordingScreenSettings recScreenSettings;
7268 ComPtr<IRecordingScreenSettings> pRecScreenSettings = paRecScreens[i];
7269
7270 hrc = pRecScreenSettings->COMGETTER(Enabled)(&fTemp);
7271 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7272 recScreenSettings.fEnabled = RT_BOOL(fTemp);
7273 hrc = pRecScreenSettings->COMGETTER(MaxTime)((ULONG *)&recScreenSettings.ulMaxTimeS);
7274 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7275 hrc = pRecScreenSettings->COMGETTER(MaxFileSize)((ULONG *)&recScreenSettings.File.ulMaxSizeMB);
7276 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7277 Bstr bstrTemp;
7278 hrc = pRecScreenSettings->COMGETTER(Filename)(bstrTemp.asOutParam());
7279 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7280 recScreenSettings.File.strName = bstrTemp;
7281 hrc = pRecScreenSettings->COMGETTER(Options)(bstrTemp.asOutParam());
7282 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7283 recScreenSettings.strOptions = bstrTemp;
7284 hrc = pRecScreenSettings->COMGETTER(VideoWidth)((ULONG *)&recScreenSettings.Video.ulWidth);
7285 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7286 hrc = pRecScreenSettings->COMGETTER(VideoHeight)((ULONG *)&recScreenSettings.Video.ulHeight);
7287 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7288 hrc = pRecScreenSettings->COMGETTER(VideoRate)((ULONG *)&recScreenSettings.Video.ulRate);
7289 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7290 hrc = pRecScreenSettings->COMGETTER(VideoFPS)((ULONG *)&recScreenSettings.Video.ulFPS);
7291 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7292
7293 recording.mapScreens[i] = recScreenSettings;
7294 }
7295
7296 Assert(recording.mapScreens.size() == paRecScreens.size());
7297
7298 return VINF_SUCCESS;
7299}
7300
7301/**
7302 * Creates the recording context.
7303 *
7304 * @returns IPRT status code.
7305 */
7306int Console::i_recordingCreate(void)
7307{
7308 settings::RecordingSettings recordingSettings;
7309 int vrc = i_recordingGetSettings(recordingSettings);
7310 if (RT_SUCCESS(vrc))
7311 vrc = mRecording.mCtx.Create(this, recordingSettings);
7312
7313 LogFlowFuncLeaveRC(vrc);
7314 return vrc;
7315}
7316
7317/**
7318 * Destroys the recording context.
7319 */
7320void Console::i_recordingDestroy(void)
7321{
7322 mRecording.mCtx.Destroy();
7323}
7324
7325/**
7326 * Starts recording. Does nothing if recording is already active.
7327 *
7328 * @returns IPRT status code.
7329 */
7330int Console::i_recordingStart(util::AutoWriteLock *pAutoLock /* = NULL */)
7331{
7332 RT_NOREF(pAutoLock);
7333
7334 if (mRecording.mCtx.IsStarted())
7335 return VINF_SUCCESS;
7336
7337 LogRel(("Recording: Starting ...\n"));
7338
7339 int vrc = mRecording.mCtx.Start();
7340 if (RT_SUCCESS(vrc))
7341 {
7342 for (unsigned uScreen = 0; uScreen < mRecording.mCtx.GetStreamCount(); uScreen++)
7343 mDisplay->i_recordingScreenChanged(uScreen);
7344 }
7345
7346 LogFlowFuncLeaveRC(vrc);
7347 return vrc;
7348}
7349
7350/**
7351 * Stops recording. Does nothing if recording is not active.
7352 */
7353int Console::i_recordingStop(util::AutoWriteLock *pAutoLock /* = NULL */)
7354{
7355 if (!mRecording.mCtx.IsStarted())
7356 return VINF_SUCCESS;
7357
7358 LogRel(("Recording: Stopping ...\n"));
7359
7360 int vrc = mRecording.mCtx.Stop();
7361 if (RT_SUCCESS(vrc))
7362 {
7363 const size_t cStreams = mRecording.mCtx.GetStreamCount();
7364 for (unsigned uScreen = 0; uScreen < cStreams; ++uScreen)
7365 mDisplay->i_recordingScreenChanged(uScreen);
7366
7367 if (pAutoLock)
7368 pAutoLock->release();
7369
7370 ComPtr<IRecordingSettings> pRecordSettings;
7371 HRESULT hrc = mMachine->COMGETTER(RecordingSettings)(pRecordSettings.asOutParam());
7372 ComAssertComRC(hrc);
7373 hrc = pRecordSettings->COMSETTER(Enabled)(FALSE);
7374 ComAssertComRC(hrc);
7375
7376 if (pAutoLock)
7377 pAutoLock->acquire();
7378 }
7379
7380 LogFlowFuncLeaveRC(vrc);
7381 return vrc;
7382}
7383
7384#endif /* VBOX_WITH_RECORDING */
7385
7386/**
7387 * Gets called by Session::UpdateMachineState()
7388 * (IInternalSessionControl::updateMachineState()).
7389 *
7390 * Must be called only in certain cases (see the implementation).
7391 *
7392 * @note Locks this object for writing.
7393 */
7394HRESULT Console::i_updateMachineState(MachineState_T aMachineState)
7395{
7396 AutoCaller autoCaller(this);
7397 AssertComRCReturnRC(autoCaller.rc());
7398
7399 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7400
7401 AssertReturn( mMachineState == MachineState_Saving
7402 || mMachineState == MachineState_OnlineSnapshotting
7403 || mMachineState == MachineState_LiveSnapshotting
7404 || mMachineState == MachineState_DeletingSnapshotOnline
7405 || mMachineState == MachineState_DeletingSnapshotPaused
7406 || aMachineState == MachineState_Saving
7407 || aMachineState == MachineState_OnlineSnapshotting
7408 || aMachineState == MachineState_LiveSnapshotting
7409 || aMachineState == MachineState_DeletingSnapshotOnline
7410 || aMachineState == MachineState_DeletingSnapshotPaused
7411 , E_FAIL);
7412
7413 return i_setMachineStateLocally(aMachineState);
7414}
7415
7416/**
7417 * Gets called by Session::COMGETTER(NominalState)()
7418 * (IInternalSessionControl::getNominalState()).
7419 *
7420 * @note Locks this object for reading.
7421 */
7422HRESULT Console::i_getNominalState(MachineState_T &aNominalState)
7423{
7424 LogFlowThisFuncEnter();
7425
7426 AutoCaller autoCaller(this);
7427 AssertComRCReturnRC(autoCaller.rc());
7428
7429 /* Get the VM handle. */
7430 SafeVMPtr ptrVM(this);
7431 if (!ptrVM.isOk())
7432 return ptrVM.rc();
7433
7434 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7435
7436 MachineState_T enmMachineState = MachineState_Null;
7437 VMSTATE enmVMState = ptrVM.vtable()->pfnVMR3GetStateU(ptrVM.rawUVM());
7438 switch (enmVMState)
7439 {
7440 case VMSTATE_CREATING:
7441 case VMSTATE_CREATED:
7442 case VMSTATE_POWERING_ON:
7443 enmMachineState = MachineState_Starting;
7444 break;
7445 case VMSTATE_LOADING:
7446 enmMachineState = MachineState_Restoring;
7447 break;
7448 case VMSTATE_RESUMING:
7449 case VMSTATE_SUSPENDING:
7450 case VMSTATE_SUSPENDING_LS:
7451 case VMSTATE_SUSPENDING_EXT_LS:
7452 case VMSTATE_SUSPENDED:
7453 case VMSTATE_SUSPENDED_LS:
7454 case VMSTATE_SUSPENDED_EXT_LS:
7455 enmMachineState = MachineState_Paused;
7456 break;
7457 case VMSTATE_RUNNING:
7458 case VMSTATE_RUNNING_LS:
7459 case VMSTATE_RESETTING:
7460 case VMSTATE_RESETTING_LS:
7461 case VMSTATE_SOFT_RESETTING:
7462 case VMSTATE_SOFT_RESETTING_LS:
7463 case VMSTATE_DEBUGGING:
7464 case VMSTATE_DEBUGGING_LS:
7465 enmMachineState = MachineState_Running;
7466 break;
7467 case VMSTATE_SAVING:
7468 enmMachineState = MachineState_Saving;
7469 break;
7470 case VMSTATE_POWERING_OFF:
7471 case VMSTATE_POWERING_OFF_LS:
7472 case VMSTATE_DESTROYING:
7473 enmMachineState = MachineState_Stopping;
7474 break;
7475 case VMSTATE_OFF:
7476 case VMSTATE_OFF_LS:
7477 case VMSTATE_FATAL_ERROR:
7478 case VMSTATE_FATAL_ERROR_LS:
7479 case VMSTATE_LOAD_FAILURE:
7480 case VMSTATE_TERMINATED:
7481 enmMachineState = MachineState_PoweredOff;
7482 break;
7483 case VMSTATE_GURU_MEDITATION:
7484 case VMSTATE_GURU_MEDITATION_LS:
7485 enmMachineState = MachineState_Stuck;
7486 break;
7487 default:
7488 AssertMsgFailed(("%s\n", ptrVM.vtable()->pfnVMR3GetStateName(enmVMState)));
7489 enmMachineState = MachineState_PoweredOff;
7490 }
7491 aNominalState = enmMachineState;
7492
7493 LogFlowFuncLeave();
7494 return S_OK;
7495}
7496
7497void Console::i_onMousePointerShapeChange(bool fVisible, bool fAlpha,
7498 uint32_t xHot, uint32_t yHot,
7499 uint32_t width, uint32_t height,
7500 const uint8_t *pu8Shape,
7501 uint32_t cbShape)
7502{
7503#if 0
7504 LogFlowThisFuncEnter();
7505 LogFlowThisFunc(("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, height=%d, shape=%p\n",
7506 fVisible, fAlpha, xHot, yHot, width, height, pShape));
7507#endif
7508
7509 AutoCaller autoCaller(this);
7510 AssertComRCReturnVoid(autoCaller.rc());
7511
7512 if (!mMouse.isNull())
7513 mMouse->updateMousePointerShape(fVisible, fAlpha, xHot, yHot, width, height, pu8Shape, cbShape);
7514
7515 com::SafeArray<BYTE> shape(cbShape);
7516 if (pu8Shape)
7517 memcpy(shape.raw(), pu8Shape, cbShape);
7518 ::FireMousePointerShapeChangedEvent(mEventSource, fVisible, fAlpha, xHot, yHot, width, height, ComSafeArrayAsInParam(shape));
7519
7520#if 0
7521 LogFlowThisFuncLeave();
7522#endif
7523}
7524
7525void Console::i_onMouseCapabilityChange(BOOL supportsAbsolute, BOOL supportsRelative,
7526 BOOL supportsTouchScreen, BOOL supportsTouchPad, BOOL needsHostCursor)
7527{
7528 LogFlowThisFunc(("supportsAbsolute=%d supportsRelative=%d supportsTouchScreen=%d supportsTouchPad=%d needsHostCursor=%d\n",
7529 supportsAbsolute, supportsRelative, supportsTouchScreen, supportsTouchPad, needsHostCursor));
7530
7531 AutoCaller autoCaller(this);
7532 AssertComRCReturnVoid(autoCaller.rc());
7533
7534 ::FireMouseCapabilityChangedEvent(mEventSource, supportsAbsolute, supportsRelative, supportsTouchScreen, supportsTouchPad, needsHostCursor);
7535}
7536
7537void Console::i_onStateChange(MachineState_T machineState)
7538{
7539 AutoCaller autoCaller(this);
7540 AssertComRCReturnVoid(autoCaller.rc());
7541 ::FireStateChangedEvent(mEventSource, machineState);
7542}
7543
7544void Console::i_onAdditionsStateChange()
7545{
7546 AutoCaller autoCaller(this);
7547 AssertComRCReturnVoid(autoCaller.rc());
7548
7549 ::FireAdditionsStateChangedEvent(mEventSource);
7550}
7551
7552/**
7553 * @remarks This notification only is for reporting an incompatible
7554 * Guest Additions interface, *not* the Guest Additions version!
7555 *
7556 * The user will be notified inside the guest if new Guest
7557 * Additions are available (via VBoxTray/VBoxClient).
7558 */
7559void Console::i_onAdditionsOutdated()
7560{
7561 AutoCaller autoCaller(this);
7562 AssertComRCReturnVoid(autoCaller.rc());
7563
7564 /** @todo implement this */
7565}
7566
7567void Console::i_onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
7568{
7569 AutoCaller autoCaller(this);
7570 AssertComRCReturnVoid(autoCaller.rc());
7571
7572 ::FireKeyboardLedsChangedEvent(mEventSource, fNumLock, fCapsLock, fScrollLock);
7573}
7574
7575void Console::i_onUSBDeviceStateChange(IUSBDevice *aDevice, bool aAttached,
7576 IVirtualBoxErrorInfo *aError)
7577{
7578 AutoCaller autoCaller(this);
7579 AssertComRCReturnVoid(autoCaller.rc());
7580
7581 ::FireUSBDeviceStateChangedEvent(mEventSource, aDevice, aAttached, aError);
7582}
7583
7584void Console::i_onRuntimeError(BOOL aFatal, IN_BSTR aErrorID, IN_BSTR aMessage)
7585{
7586 AutoCaller autoCaller(this);
7587 AssertComRCReturnVoid(autoCaller.rc());
7588
7589 ::FireRuntimeErrorEvent(mEventSource, aFatal, aErrorID, aMessage);
7590}
7591
7592HRESULT Console::i_onShowWindow(BOOL aCheck, BOOL *aCanShow, LONG64 *aWinId)
7593{
7594 AssertReturn(aCanShow, E_POINTER);
7595 AssertReturn(aWinId, E_POINTER);
7596
7597 *aCanShow = FALSE;
7598 *aWinId = 0;
7599
7600 AutoCaller autoCaller(this);
7601 AssertComRCReturnRC(autoCaller.rc());
7602
7603 ComPtr<IEvent> ptrEvent;
7604 if (aCheck)
7605 {
7606 *aCanShow = TRUE;
7607 HRESULT hrc = ::CreateCanShowWindowEvent(ptrEvent.asOutParam(), mEventSource);
7608 if (SUCCEEDED(hrc))
7609 {
7610 VBoxEventDesc EvtDesc(ptrEvent, mEventSource);
7611 BOOL fDelivered = EvtDesc.fire(5000); /* Wait up to 5 secs for delivery */
7612 //Assert(fDelivered);
7613 if (fDelivered)
7614 {
7615 // bit clumsy
7616 ComPtr<ICanShowWindowEvent> ptrCanShowEvent = ptrEvent;
7617 if (ptrCanShowEvent)
7618 {
7619 BOOL fVetoed = FALSE;
7620 BOOL fApproved = FALSE;
7621 ptrCanShowEvent->IsVetoed(&fVetoed);
7622 ptrCanShowEvent->IsApproved(&fApproved);
7623 *aCanShow = fApproved || !fVetoed;
7624 }
7625 else
7626 AssertFailed();
7627 }
7628 }
7629 }
7630 else
7631 {
7632 HRESULT hrc = ::CreateShowWindowEvent(ptrEvent.asOutParam(), mEventSource, 0);
7633 if (SUCCEEDED(hrc))
7634 {
7635 VBoxEventDesc EvtDesc(ptrEvent, mEventSource);
7636 BOOL fDelivered = EvtDesc.fire(5000); /* Wait up to 5 secs for delivery */
7637 //Assert(fDelivered);
7638 if (fDelivered)
7639 {
7640 ComPtr<IShowWindowEvent> ptrShowEvent = ptrEvent;
7641 if (ptrShowEvent)
7642 {
7643 LONG64 idWindow = 0;
7644 ptrShowEvent->COMGETTER(WinId)(&idWindow);
7645 if (idWindow != 0 && *aWinId == 0)
7646 *aWinId = idWindow;
7647 }
7648 else
7649 AssertFailed();
7650 }
7651 }
7652 }
7653
7654 return S_OK;
7655}
7656
7657// private methods
7658////////////////////////////////////////////////////////////////////////////////
7659
7660/**
7661 * Loads the VMM if needed.
7662 *
7663 * @returns COM status.
7664 * @remarks Caller must write lock the console object.
7665 */
7666HRESULT Console::i_loadVMM(void) RT_NOEXCEPT
7667{
7668 if ( mhModVMM == NIL_RTLDRMOD
7669 || mpVMM == NULL)
7670 {
7671 Assert(!mpVMM);
7672
7673 HRESULT hrc;
7674 RTERRINFOSTATIC ErrInfo;
7675 RTLDRMOD hModVMM = NIL_RTLDRMOD;
7676 int vrc = SUPR3HardenedLdrLoadAppPriv("VBoxVMM", &hModVMM, RTLDRLOAD_FLAGS_LOCAL, RTErrInfoInitStatic(&ErrInfo));
7677 if (RT_SUCCESS(vrc))
7678 {
7679 PFNVMMGETVTABLE pfnGetVTable = NULL;
7680 vrc = RTLdrGetSymbol(hModVMM, VMMR3VTABLE_GETTER_NAME, (void **)&pfnGetVTable);
7681 if (pfnGetVTable)
7682 {
7683 PCVMMR3VTABLE pVMM = pfnGetVTable();
7684 if (pVMM)
7685 {
7686 if (VMMR3VTABLE_IS_COMPATIBLE(pVMM->uMagicVersion))
7687 {
7688 if (pVMM->uMagicVersion == pVMM->uMagicVersionEnd)
7689 {
7690 mhModVMM = hModVMM;
7691 mpVMM = pVMM;
7692 LogFunc(("mhLdrVMM=%p phVMM=%p uMagicVersion=%#RX64\n", hModVMM, pVMM, pVMM->uMagicVersion));
7693 return S_OK;
7694 }
7695
7696 hrc = setErrorVrc(vrc, "Bogus VMM vtable: uMagicVersion=%#RX64 uMagicVersionEnd=%#RX64",
7697 pVMM->uMagicVersion, pVMM->uMagicVersionEnd);
7698 }
7699 else
7700 hrc = setErrorVrc(vrc, "Incompatible of bogus VMM version magic: %#RX64", pVMM->uMagicVersion);
7701 }
7702 else
7703 hrc = setErrorVrc(vrc, "pfnGetVTable return NULL!");
7704 }
7705 else
7706 hrc = setErrorVrc(vrc, "Failed to locate symbol '%s' in VBoxVMM: %Rrc", VMMR3VTABLE_GETTER_NAME, vrc);
7707 RTLdrClose(hModVMM);
7708 }
7709 else
7710 hrc = setErrorVrc(vrc, "Failed to load VBoxVMM: %#RTeic", &ErrInfo.Core);
7711 return hrc;
7712 }
7713
7714 return S_OK;
7715}
7716
7717/**
7718 * Increases the usage counter of the mpUVM pointer.
7719 *
7720 * Guarantees that VMR3Destroy() will not be called on it at least until
7721 * releaseVMCaller() is called.
7722 *
7723 * If this method returns a failure, the caller is not allowed to use mpUVM and
7724 * may return the failed result code to the upper level. This method sets the
7725 * extended error info on failure if \a aQuiet is false.
7726 *
7727 * Setting \a aQuiet to true is useful for methods that don't want to return
7728 * the failed result code to the caller when this method fails (e.g. need to
7729 * silently check for the mpUVM availability).
7730 *
7731 * When mpUVM is NULL but \a aAllowNullVM is true, a corresponding error will be
7732 * returned instead of asserting. Having it false is intended as a sanity check
7733 * for methods that have checked mMachineState and expect mpUVM *NOT* to be
7734 * NULL.
7735 *
7736 * @param aQuiet true to suppress setting error info
7737 * @param aAllowNullVM true to accept mpUVM being NULL and return a failure
7738 * (otherwise this method will assert if mpUVM is NULL)
7739 *
7740 * @note Locks this object for writing.
7741 */
7742HRESULT Console::i_addVMCaller(bool aQuiet /* = false */,
7743 bool aAllowNullVM /* = false */)
7744{
7745 RT_NOREF(aAllowNullVM);
7746 AutoCaller autoCaller(this);
7747 /** @todo Fix race during console/VM reference destruction, refer @bugref{6318}
7748 * comment 25. */
7749 if (FAILED(autoCaller.rc()))
7750 return autoCaller.rc();
7751
7752 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7753
7754 if (mVMDestroying)
7755 {
7756 /* powerDown() is waiting for all callers to finish */
7757 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED, tr("The virtual machine is being powered down"));
7758 }
7759
7760 if (mpUVM == NULL)
7761 {
7762 Assert(aAllowNullVM == true);
7763
7764 /* The machine is not powered up */
7765 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED, tr("The virtual machine is not powered up"));
7766 }
7767
7768 ++mVMCallers;
7769
7770 return S_OK;
7771}
7772
7773/**
7774 * Decreases the usage counter of the mpUVM pointer.
7775 *
7776 * Must always complete the addVMCaller() call after the mpUVM pointer is no
7777 * more necessary.
7778 *
7779 * @note Locks this object for writing.
7780 */
7781void Console::i_releaseVMCaller()
7782{
7783 AutoCaller autoCaller(this);
7784 AssertComRCReturnVoid(autoCaller.rc());
7785
7786 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7787
7788 AssertReturnVoid(mpUVM != NULL);
7789
7790 Assert(mVMCallers > 0);
7791 --mVMCallers;
7792
7793 if (mVMCallers == 0 && mVMDestroying)
7794 {
7795 /* inform powerDown() there are no more callers */
7796 RTSemEventSignal(mVMZeroCallersSem);
7797 }
7798}
7799
7800
7801/**
7802 * Helper for SafeVMPtrBase.
7803 */
7804HRESULT Console::i_safeVMPtrRetainer(PUVM *a_ppUVM, PCVMMR3VTABLE *a_ppVMM, bool a_Quiet) RT_NOEXCEPT
7805{
7806 *a_ppUVM = NULL;
7807 *a_ppVMM = NULL;
7808
7809 AutoCaller autoCaller(this);
7810 AssertComRCReturnRC(autoCaller.rc());
7811 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7812
7813 /*
7814 * Repeat the checks done by addVMCaller.
7815 */
7816 if (mVMDestroying) /* powerDown() is waiting for all callers to finish */
7817 return a_Quiet
7818 ? E_ACCESSDENIED
7819 : setError(E_ACCESSDENIED, tr("The virtual machine is being powered down"));
7820 PUVM const pUVM = mpUVM;
7821 if (!pUVM)
7822 return a_Quiet
7823 ? E_ACCESSDENIED
7824 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
7825 PCVMMR3VTABLE const pVMM = mpVMM;
7826 if (!pVMM)
7827 return a_Quiet
7828 ? E_ACCESSDENIED
7829 : setError(E_ACCESSDENIED, tr("No VMM loaded!"));
7830
7831 /*
7832 * Retain a reference to the user mode VM handle and get the global handle.
7833 */
7834 uint32_t cRefs = pVMM->pfnVMR3RetainUVM(pUVM);
7835 if (cRefs == UINT32_MAX)
7836 return a_Quiet
7837 ? E_ACCESSDENIED
7838 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
7839
7840 /* done */
7841 *a_ppUVM = pUVM;
7842 *a_ppVMM = pVMM;
7843 return S_OK;
7844}
7845
7846void Console::i_safeVMPtrReleaser(PUVM *a_ppUVM)
7847{
7848 PUVM const pUVM = *a_ppUVM;
7849 *a_ppUVM = NULL;
7850 if (pUVM)
7851 {
7852 PCVMMR3VTABLE const pVMM = mpVMM;
7853 if (pVMM)
7854 pVMM->pfnVMR3ReleaseUVM(pUVM);
7855 }
7856}
7857
7858
7859#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
7860/*static*/
7861DECLCALLBACK(int) Console::i_logEncryptedOpen(PCRTLOGOUTPUTIF pIf, void *pvUser, const char *pszFilename, uint32_t fFlags)
7862{
7863 RT_NOREF(pIf);
7864 Console *pConsole = static_cast<Console *>(pvUser);
7865 RTVFSFILE hVfsFile = NIL_RTVFSFILE;
7866
7867 int vrc = RTVfsFileOpenNormal(pszFilename, fFlags, &hVfsFile);
7868 if (RT_SUCCESS(vrc))
7869 {
7870 PCVBOXCRYPTOIF pCryptoIf = NULL;
7871 vrc = pConsole->i_retainCryptoIf(&pCryptoIf);
7872 if (RT_SUCCESS(vrc))
7873 {
7874 SecretKey *pKey = NULL;
7875
7876 vrc = pConsole->m_pKeyStore->retainSecretKey(pConsole->m_strLogKeyId, &pKey);
7877 if (RT_SUCCESS(vrc))
7878 {
7879 const char *pszPassword = (const char *)pKey->getKeyBuffer();
7880
7881 vrc = pCryptoIf->pfnCryptoFileFromVfsFile(hVfsFile, pConsole->m_strLogKeyStore.c_str(), pszPassword,
7882 &pConsole->m_hVfsFileLog);
7883 pKey->release();
7884 }
7885
7886 /* On success we keep the reference to keep the cryptographic module loaded. */
7887 if (RT_FAILURE(vrc))
7888 pConsole->i_releaseCryptoIf(pCryptoIf);
7889 }
7890
7891 /* Always do this because the encrypted log has retained a reference to the underlying file. */
7892 RTVfsFileRelease(hVfsFile);
7893 if (RT_FAILURE(vrc))
7894 RTFileDelete(pszFilename);
7895 }
7896
7897 return vrc;
7898}
7899
7900
7901/*static*/
7902DECLCALLBACK(int) Console::i_logEncryptedClose(PCRTLOGOUTPUTIF pIf, void *pvUser)
7903{
7904 RT_NOREF(pIf);
7905 Console *pConsole = static_cast<Console *>(pvUser);
7906
7907 RTVfsFileRelease(pConsole->m_hVfsFileLog);
7908 pConsole->m_hVfsFileLog = NIL_RTVFSFILE;
7909 return VINF_SUCCESS;
7910}
7911
7912
7913/*static*/
7914DECLCALLBACK(int) Console::i_logEncryptedDelete(PCRTLOGOUTPUTIF pIf, void *pvUser, const char *pszFilename)
7915{
7916 RT_NOREF(pIf, pvUser);
7917 return RTFileDelete(pszFilename);
7918}
7919
7920
7921/*static*/
7922DECLCALLBACK(int) Console::i_logEncryptedRename(PCRTLOGOUTPUTIF pIf, void *pvUser, const char *pszFilenameOld,
7923 const char *pszFilenameNew, uint32_t fFlags)
7924{
7925 RT_NOREF(pIf, pvUser);
7926 return RTFileRename(pszFilenameOld, pszFilenameNew, fFlags);
7927}
7928
7929
7930/*static*/
7931DECLCALLBACK(int) Console::i_logEncryptedQuerySize(PCRTLOGOUTPUTIF pIf, void *pvUser, uint64_t *pcbSize)
7932{
7933 RT_NOREF(pIf);
7934 Console *pConsole = static_cast<Console *>(pvUser);
7935
7936 return RTVfsFileQuerySize(pConsole->m_hVfsFileLog, pcbSize);
7937}
7938
7939
7940/*static*/
7941DECLCALLBACK(int) Console::i_logEncryptedWrite(PCRTLOGOUTPUTIF pIf, void *pvUser, const void *pvBuf,
7942 size_t cbWrite, size_t *pcbWritten)
7943{
7944 RT_NOREF(pIf);
7945 Console *pConsole = static_cast<Console *>(pvUser);
7946
7947 return RTVfsFileWrite(pConsole->m_hVfsFileLog, pvBuf, cbWrite, pcbWritten);
7948}
7949
7950
7951/*static*/
7952DECLCALLBACK(int) Console::i_logEncryptedFlush(PCRTLOGOUTPUTIF pIf, void *pvUser)
7953{
7954 RT_NOREF(pIf);
7955 Console *pConsole = static_cast<Console *>(pvUser);
7956
7957 return RTVfsFileFlush(pConsole->m_hVfsFileLog);
7958}
7959#endif
7960
7961
7962/**
7963 * Initialize the release logging facility. In case something
7964 * goes wrong, there will be no release logging. Maybe in the future
7965 * we can add some logic to use different file names in this case.
7966 * Note that the logic must be in sync with Machine::DeleteSettings().
7967 */
7968HRESULT Console::i_consoleInitReleaseLog(const ComPtr<IMachine> aMachine)
7969{
7970 Bstr bstrLogFolder;
7971 HRESULT hrc = aMachine->COMGETTER(LogFolder)(bstrLogFolder.asOutParam());
7972 if (FAILED(hrc))
7973 return hrc;
7974 Utf8Str strLogDir = bstrLogFolder;
7975
7976 /* make sure the Logs folder exists */
7977 Assert(strLogDir.length());
7978 if (!RTDirExists(strLogDir.c_str()))
7979 RTDirCreateFullPath(strLogDir.c_str(), 0700);
7980
7981 Utf8StrFmt logFile("%s%cVBox.log", strLogDir.c_str(), RTPATH_DELIMITER);
7982 Utf8StrFmt pngFile("%s%cVBox.png", strLogDir.c_str(), RTPATH_DELIMITER);
7983
7984 /*
7985 * Age the old log files.
7986 * Rename .(n-1) to .(n), .(n-2) to .(n-1), ..., and the last log file to .1
7987 * Overwrite target files in case they exist.
7988 */
7989 ComPtr<IVirtualBox> pVirtualBox;
7990 aMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
7991 ComPtr<ISystemProperties> pSystemProperties;
7992 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
7993 ULONG cHistoryFiles = 3;
7994 pSystemProperties->COMGETTER(LogHistoryCount)(&cHistoryFiles);
7995 if (cHistoryFiles)
7996 {
7997 for (int i = cHistoryFiles - 1; i >= 0; i--)
7998 {
7999 Utf8Str *files[] = { &logFile, &pngFile };
8000 Utf8Str oldName, newName;
8001
8002 for (unsigned int j = 0; j < RT_ELEMENTS(files); ++j)
8003 {
8004 if (i > 0)
8005 oldName.printf("%s.%d", files[j]->c_str(), i);
8006 else
8007 oldName = *files[j];
8008 newName.printf("%s.%d", files[j]->c_str(), i + 1);
8009
8010 /* If the old file doesn't exist, delete the new file (if it
8011 * exists) to provide correct rotation even if the sequence is
8012 * broken */
8013 if (RTFileRename(oldName.c_str(), newName.c_str(), RTFILEMOVE_FLAGS_REPLACE) == VERR_FILE_NOT_FOUND)
8014 RTFileDelete(newName.c_str());
8015 }
8016 }
8017 }
8018
8019 Bstr bstrLogKeyId;
8020 Bstr bstrLogKeyStore;
8021 PCRTLOGOUTPUTIF pLogOutputIf = NULL;
8022 void *pvLogOutputUser = NULL;
8023 int vrc = VINF_SUCCESS;
8024#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
8025 hrc = aMachine->COMGETTER(LogKeyId)(bstrLogKeyId.asOutParam());
8026 if (SUCCEEDED(hrc))
8027 {
8028 hrc = aMachine->COMGETTER(LogKeyStore)(bstrLogKeyStore.asOutParam());
8029 if ( SUCCEEDED(hrc)
8030 && bstrLogKeyId.isNotEmpty()
8031 && bstrLogKeyStore.isNotEmpty())
8032 {
8033 m_LogOutputIf.pfnOpen = Console::i_logEncryptedOpen;
8034 m_LogOutputIf.pfnClose = Console::i_logEncryptedClose;
8035 m_LogOutputIf.pfnDelete = Console::i_logEncryptedDelete;
8036 m_LogOutputIf.pfnRename = Console::i_logEncryptedRename;
8037 m_LogOutputIf.pfnQuerySize = Console::i_logEncryptedQuerySize;
8038 m_LogOutputIf.pfnWrite = Console::i_logEncryptedWrite;
8039 m_LogOutputIf.pfnFlush = Console::i_logEncryptedFlush;
8040
8041 m_strLogKeyId = Utf8Str(bstrLogKeyId);
8042 m_strLogKeyStore = Utf8Str(bstrLogKeyStore);
8043
8044 pLogOutputIf = &m_LogOutputIf;
8045 pvLogOutputUser = this;
8046 m_fEncryptedLog = true;
8047 }
8048 }
8049
8050 if (RT_FAILURE(vrc))
8051 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to set encryption for release log (%Rrc)"), vrc);
8052 else
8053#endif
8054 {
8055 RTERRINFOSTATIC ErrInfo;
8056 vrc = com::VBoxLogRelCreateEx("VM", logFile.c_str(),
8057 RTLOGFLAGS_PREFIX_TIME_PROG | RTLOGFLAGS_RESTRICT_GROUPS,
8058 "all all.restrict -default.restrict",
8059 "VBOX_RELEASE_LOG", RTLOGDEST_FILE,
8060 32768 /* cMaxEntriesPerGroup */,
8061 0 /* cHistory */, 0 /* uHistoryFileTime */,
8062 0 /* uHistoryFileSize */,
8063 pLogOutputIf, pvLogOutputUser,
8064 RTErrInfoInitStatic(&ErrInfo));
8065 if (RT_FAILURE(vrc))
8066 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to open release log (%s, %Rrc)"), ErrInfo.Core.pszMsg, vrc);
8067 }
8068
8069 /* If we've made any directory changes, flush the directory to increase
8070 the likelihood that the log file will be usable after a system panic.
8071
8072 Tip: Try 'export VBOX_RELEASE_LOG_FLAGS=flush' if the last bits of the log
8073 is missing. Just don't have too high hopes for this to help. */
8074 if (SUCCEEDED(hrc) || cHistoryFiles)
8075 RTDirFlush(strLogDir.c_str());
8076
8077 return hrc;
8078}
8079
8080/**
8081 * Common worker for PowerUp and PowerUpPaused.
8082 *
8083 * @returns COM status code.
8084 *
8085 * @param aProgress Where to return the progress object.
8086 * @param aPaused true if PowerUpPaused called.
8087 */
8088HRESULT Console::i_powerUp(IProgress **aProgress, bool aPaused)
8089{
8090 LogFlowThisFuncEnter();
8091
8092 CheckComArgOutPointerValid(aProgress);
8093
8094 AutoCaller autoCaller(this);
8095 HRESULT rc = autoCaller.rc();
8096 if (FAILED(rc)) return rc;
8097
8098 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8099 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
8100
8101 if (Global::IsOnlineOrTransient(mMachineState))
8102 return setError(VBOX_E_INVALID_VM_STATE, tr("The virtual machine is already running or busy (machine state: %s)"),
8103 Global::stringifyMachineState(mMachineState));
8104
8105
8106 /* Set up release logging as early as possible after the check if
8107 * there is already a running VM which we shouldn't disturb. */
8108 rc = i_consoleInitReleaseLog(mMachine);
8109 if (FAILED(rc))
8110 return rc;
8111
8112#ifdef VBOX_OPENSSL_FIPS
8113 LogRel(("crypto: FIPS mode %s\n", FIPS_mode() ? "enabled" : "FAILED"));
8114#endif
8115
8116 /* test and clear the TeleporterEnabled property */
8117 BOOL fTeleporterEnabled;
8118 rc = mMachine->COMGETTER(TeleporterEnabled)(&fTeleporterEnabled);
8119 if (FAILED(rc))
8120 return rc;
8121
8122#if 0 /** @todo we should save it afterwards, but that isn't necessarily a good idea. Find a better place for this (VBoxSVC). */
8123 if (fTeleporterEnabled)
8124 {
8125 rc = mMachine->COMSETTER(TeleporterEnabled)(FALSE);
8126 if (FAILED(rc))
8127 return rc;
8128 }
8129#endif
8130
8131 PCVMMR3VTABLE const pVMM = mpVMM;
8132 AssertPtrReturn(pVMM, E_UNEXPECTED);
8133
8134 ComObjPtr<Progress> pPowerupProgress;
8135 bool fBeganPoweringUp = false;
8136
8137 LONG cOperations = 1;
8138 LONG ulTotalOperationsWeight = 1;
8139 VMPowerUpTask *task = NULL;
8140
8141 try
8142 {
8143 /* Create a progress object to track progress of this operation. Must
8144 * be done as early as possible (together with BeginPowerUp()) as this
8145 * is vital for communicating as much as possible early powerup
8146 * failure information to the API caller */
8147 pPowerupProgress.createObject();
8148 Bstr progressDesc;
8149 if (mMachineState == MachineState_Saved || mMachineState == MachineState_AbortedSaved)
8150 progressDesc = tr("Restoring virtual machine");
8151 else if (fTeleporterEnabled)
8152 progressDesc = tr("Teleporting virtual machine");
8153 else
8154 progressDesc = tr("Starting virtual machine");
8155
8156 /*
8157 * Saved VMs will have to prove that their saved states seem kosher.
8158 */
8159 Utf8Str strSavedStateFile;
8160 Bstr bstrStateKeyId;
8161 Bstr bstrStateKeyStore;
8162
8163 if (mMachineState == MachineState_Saved || mMachineState == MachineState_AbortedSaved)
8164 {
8165 Bstr bstrSavedStateFile;
8166 rc = mMachine->COMGETTER(StateFilePath)(bstrSavedStateFile.asOutParam());
8167 if (FAILED(rc))
8168 throw rc;
8169 strSavedStateFile = bstrSavedStateFile;
8170
8171#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
8172 rc = mMachine->COMGETTER(StateKeyId)(bstrStateKeyId.asOutParam());
8173 if (FAILED(rc))
8174 throw rc;
8175 rc = mMachine->COMGETTER(StateKeyStore)(bstrStateKeyStore.asOutParam());
8176 if (FAILED(rc))
8177 throw rc;
8178#endif
8179
8180 ComAssertRet(bstrSavedStateFile.isNotEmpty(), E_FAIL);
8181 SsmStream ssmStream(this, pVMM, m_pKeyStore, bstrStateKeyId, bstrStateKeyStore);
8182 int vrc = ssmStream.open(strSavedStateFile.c_str());
8183 if (RT_SUCCESS(vrc))
8184 {
8185 PCSSMSTRMOPS pStreamOps;
8186 void *pvStreamOpsUser;
8187
8188 vrc = ssmStream.querySsmStrmOps(&pStreamOps, &pvStreamOpsUser);
8189 if (RT_SUCCESS(vrc))
8190 vrc = pVMM->pfnSSMR3ValidateFile(NULL /*pszFilename*/, pStreamOps, pvStreamOpsUser,
8191 false /* fChecksumIt */);
8192 }
8193
8194 if (RT_FAILURE(vrc))
8195 {
8196 Utf8Str errMsg;
8197 switch (vrc)
8198 {
8199 case VERR_FILE_NOT_FOUND:
8200 errMsg.printf(tr("VM failed to start because the saved state file '%s' does not exist."),
8201 strSavedStateFile.c_str());
8202 break;
8203 default:
8204 errMsg.printf(tr("VM failed to start because the saved state file '%s' is invalid (%Rrc). "
8205 "Delete the saved state prior to starting the VM."), strSavedStateFile.c_str(), vrc);
8206 break;
8207 }
8208 throw setErrorBoth(VBOX_E_FILE_ERROR, vrc, errMsg.c_str());
8209 }
8210
8211 }
8212
8213 /* Read console data, including console shared folders, stored in the
8214 * saved state file (if not yet done).
8215 */
8216 rc = i_loadDataFromSavedState();
8217 if (FAILED(rc))
8218 throw rc;
8219
8220 /* Check all types of shared folders and compose a single list */
8221 SharedFolderDataMap sharedFolders;
8222 {
8223 /* first, insert global folders */
8224 for (SharedFolderDataMap::const_iterator it = m_mapGlobalSharedFolders.begin();
8225 it != m_mapGlobalSharedFolders.end();
8226 ++it)
8227 {
8228 const SharedFolderData &d = it->second;
8229 sharedFolders[it->first] = d;
8230 }
8231
8232 /* second, insert machine folders */
8233 for (SharedFolderDataMap::const_iterator it = m_mapMachineSharedFolders.begin();
8234 it != m_mapMachineSharedFolders.end();
8235 ++it)
8236 {
8237 const SharedFolderData &d = it->second;
8238 sharedFolders[it->first] = d;
8239 }
8240
8241 /* third, insert console folders */
8242 for (SharedFolderMap::const_iterator it = m_mapSharedFolders.begin();
8243 it != m_mapSharedFolders.end();
8244 ++it)
8245 {
8246 SharedFolder *pSF = it->second;
8247 AutoCaller sfCaller(pSF);
8248 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
8249 sharedFolders[it->first] = SharedFolderData(pSF->i_getHostPath(),
8250 pSF->i_isWritable(),
8251 pSF->i_isAutoMounted(),
8252 pSF->i_getAutoMountPoint());
8253 }
8254 }
8255
8256
8257 /* Setup task object and thread to carry out the operation
8258 * asynchronously */
8259 try { task = new VMPowerUpTask(this, pPowerupProgress); }
8260 catch (std::bad_alloc &) { throw rc = E_OUTOFMEMORY; }
8261 if (!task->isOk())
8262 throw task->rc();
8263
8264 task->mpfnConfigConstructor = i_configConstructor;
8265 task->mSharedFolders = sharedFolders;
8266 task->mStartPaused = aPaused;
8267 if (mMachineState == MachineState_Saved || mMachineState == MachineState_AbortedSaved)
8268 try { task->mSavedStateFile = strSavedStateFile; }
8269 catch (std::bad_alloc &) { throw rc = E_OUTOFMEMORY; }
8270 task->mTeleporterEnabled = fTeleporterEnabled;
8271
8272 /* Reset differencing hard disks for which autoReset is true,
8273 * but only if the machine has no snapshots OR the current snapshot
8274 * is an OFFLINE snapshot; otherwise we would reset the current
8275 * differencing image of an ONLINE snapshot which contains the disk
8276 * state of the machine while it was previously running, but without
8277 * the corresponding machine state, which is equivalent to powering
8278 * off a running machine and not good idea
8279 */
8280 ComPtr<ISnapshot> pCurrentSnapshot;
8281 rc = mMachine->COMGETTER(CurrentSnapshot)(pCurrentSnapshot.asOutParam());
8282 if (FAILED(rc))
8283 throw rc;
8284
8285 BOOL fCurrentSnapshotIsOnline = false;
8286 if (pCurrentSnapshot)
8287 {
8288 rc = pCurrentSnapshot->COMGETTER(Online)(&fCurrentSnapshotIsOnline);
8289 if (FAILED(rc))
8290 throw rc;
8291 }
8292
8293 if (strSavedStateFile.isEmpty() && !fCurrentSnapshotIsOnline)
8294 {
8295 LogFlowThisFunc(("Looking for immutable images to reset\n"));
8296
8297 com::SafeIfaceArray<IMediumAttachment> atts;
8298 rc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
8299 if (FAILED(rc))
8300 throw rc;
8301
8302 for (size_t i = 0;
8303 i < atts.size();
8304 ++i)
8305 {
8306 DeviceType_T devType;
8307 rc = atts[i]->COMGETTER(Type)(&devType);
8308 /** @todo later applies to floppies as well */
8309 if (devType == DeviceType_HardDisk)
8310 {
8311 ComPtr<IMedium> pMedium;
8312 rc = atts[i]->COMGETTER(Medium)(pMedium.asOutParam());
8313 if (FAILED(rc))
8314 throw rc;
8315
8316 /* needs autoreset? */
8317 BOOL autoReset = FALSE;
8318 rc = pMedium->COMGETTER(AutoReset)(&autoReset);
8319 if (FAILED(rc))
8320 throw rc;
8321
8322 if (autoReset)
8323 {
8324 ComPtr<IProgress> pResetProgress;
8325 rc = pMedium->Reset(pResetProgress.asOutParam());
8326 if (FAILED(rc))
8327 throw rc;
8328
8329 /* save for later use on the powerup thread */
8330 task->hardDiskProgresses.push_back(pResetProgress);
8331 }
8332 }
8333 }
8334 }
8335 else
8336 LogFlowThisFunc(("Machine has a current snapshot which is online, skipping immutable images reset\n"));
8337
8338 /* setup task object and thread to carry out the operation
8339 * asynchronously */
8340
8341#ifdef VBOX_WITH_EXTPACK
8342 mptrExtPackManager->i_dumpAllToReleaseLog();
8343#endif
8344
8345#ifdef RT_OS_SOLARIS
8346 /* setup host core dumper for the VM */
8347 Bstr value;
8348 HRESULT hrc = mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpEnabled").raw(), value.asOutParam());
8349 if (SUCCEEDED(hrc) && value == "1")
8350 {
8351 Bstr coreDumpDir, coreDumpReplaceSys, coreDumpLive;
8352 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpDir").raw(), coreDumpDir.asOutParam());
8353 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpReplaceSystemDump").raw(), coreDumpReplaceSys.asOutParam());
8354 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpLive").raw(), coreDumpLive.asOutParam());
8355
8356 uint32_t fCoreFlags = 0;
8357 if ( coreDumpReplaceSys.isEmpty() == false
8358 && Utf8Str(coreDumpReplaceSys).toUInt32() == 1)
8359 fCoreFlags |= RTCOREDUMPER_FLAGS_REPLACE_SYSTEM_DUMP;
8360
8361 if ( coreDumpLive.isEmpty() == false
8362 && Utf8Str(coreDumpLive).toUInt32() == 1)
8363 fCoreFlags |= RTCOREDUMPER_FLAGS_LIVE_CORE;
8364
8365 Utf8Str strDumpDir(coreDumpDir);
8366 const char *pszDumpDir = strDumpDir.c_str();
8367 if ( pszDumpDir
8368 && *pszDumpDir == '\0')
8369 pszDumpDir = NULL;
8370
8371 int vrc;
8372 if ( pszDumpDir
8373 && !RTDirExists(pszDumpDir))
8374 {
8375 /*
8376 * Try create the directory.
8377 */
8378 vrc = RTDirCreateFullPath(pszDumpDir, 0700);
8379 if (RT_FAILURE(vrc))
8380 throw setErrorBoth(E_FAIL, vrc, tr("Failed to setup CoreDumper. Couldn't create dump directory '%s' (%Rrc)"),
8381 pszDumpDir, vrc);
8382 }
8383
8384 vrc = RTCoreDumperSetup(pszDumpDir, fCoreFlags);
8385 if (RT_FAILURE(vrc))
8386 throw setErrorBoth(E_FAIL, vrc, tr("Failed to setup CoreDumper (%Rrc)"), vrc);
8387 LogRel(("CoreDumper setup successful. pszDumpDir=%s fFlags=%#x\n", pszDumpDir ? pszDumpDir : ".", fCoreFlags));
8388 }
8389#endif
8390
8391
8392 // If there is immutable drive the process that.
8393 VMPowerUpTask::ProgressList progresses(task->hardDiskProgresses);
8394 if (aProgress && !progresses.empty())
8395 {
8396 for (VMPowerUpTask::ProgressList::const_iterator it = progresses.begin(); it != progresses.end(); ++it)
8397 {
8398 ++cOperations;
8399 ulTotalOperationsWeight += 1;
8400 }
8401 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
8402 progressDesc.raw(),
8403 TRUE, // Cancelable
8404 cOperations,
8405 ulTotalOperationsWeight,
8406 tr("Starting Hard Disk operations"),
8407 1);
8408 AssertComRCReturnRC(rc);
8409 }
8410 else if ( mMachineState == MachineState_Saved
8411 || mMachineState == MachineState_AbortedSaved
8412 || !fTeleporterEnabled)
8413 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
8414 progressDesc.raw(),
8415 FALSE /* aCancelable */);
8416 else if (fTeleporterEnabled)
8417 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
8418 progressDesc.raw(),
8419 TRUE /* aCancelable */,
8420 3 /* cOperations */,
8421 10 /* ulTotalOperationsWeight */,
8422 tr("Teleporting virtual machine"),
8423 1 /* ulFirstOperationWeight */);
8424
8425 if (FAILED(rc))
8426 throw rc;
8427
8428 /* Tell VBoxSVC and Machine about the progress object so they can
8429 combine/proxy it to any openRemoteSession caller. */
8430 LogFlowThisFunc(("Calling BeginPowerUp...\n"));
8431 rc = mControl->BeginPowerUp(pPowerupProgress);
8432 if (FAILED(rc))
8433 {
8434 LogFlowThisFunc(("BeginPowerUp failed\n"));
8435 throw rc;
8436 }
8437 fBeganPoweringUp = true;
8438
8439 LogFlowThisFunc(("Checking if canceled...\n"));
8440 BOOL fCanceled;
8441 rc = pPowerupProgress->COMGETTER(Canceled)(&fCanceled);
8442 if (FAILED(rc))
8443 throw rc;
8444
8445 if (fCanceled)
8446 {
8447 LogFlowThisFunc(("Canceled in BeginPowerUp\n"));
8448 throw setError(E_FAIL, tr("Powerup was canceled"));
8449 }
8450 LogFlowThisFunc(("Not canceled yet.\n"));
8451
8452 /** @todo this code prevents starting a VM with unavailable bridged
8453 * networking interface. The only benefit is a slightly better error
8454 * message, which should be moved to the driver code. This is the
8455 * only reason why I left the code in for now. The driver allows
8456 * unavailable bridged networking interfaces in certain circumstances,
8457 * and this is sabotaged by this check. The VM will initially have no
8458 * network connectivity, but the user can fix this at runtime. */
8459#if 0
8460 /* the network cards will undergo a quick consistency check */
8461 for (ULONG slot = 0;
8462 slot < maxNetworkAdapters;
8463 ++slot)
8464 {
8465 ComPtr<INetworkAdapter> pNetworkAdapter;
8466 mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
8467 BOOL enabled = FALSE;
8468 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
8469 if (!enabled)
8470 continue;
8471
8472 NetworkAttachmentType_T netattach;
8473 pNetworkAdapter->COMGETTER(AttachmentType)(&netattach);
8474 switch (netattach)
8475 {
8476 case NetworkAttachmentType_Bridged:
8477 {
8478 /* a valid host interface must have been set */
8479 Bstr hostif;
8480 pNetworkAdapter->COMGETTER(HostInterface)(hostif.asOutParam());
8481 if (hostif.isEmpty())
8482 {
8483 throw setError(VBOX_E_HOST_ERROR,
8484 tr("VM cannot start because host interface networking requires a host interface name to be set"));
8485 }
8486 ComPtr<IVirtualBox> pVirtualBox;
8487 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
8488 ComPtr<IHost> pHost;
8489 pVirtualBox->COMGETTER(Host)(pHost.asOutParam());
8490 ComPtr<IHostNetworkInterface> pHostInterface;
8491 if (!SUCCEEDED(pHost->FindHostNetworkInterfaceByName(hostif.raw(), pHostInterface.asOutParam())))
8492 throw setError(VBOX_E_HOST_ERROR,
8493 tr("VM cannot start because the host interface '%ls' does not exist"), hostif.raw());
8494 break;
8495 }
8496 default:
8497 break;
8498 }
8499 }
8500#endif // 0
8501
8502
8503 /* setup task object and thread to carry out the operation
8504 * asynchronously */
8505 if (aProgress)
8506 {
8507 rc = pPowerupProgress.queryInterfaceTo(aProgress);
8508 AssertComRCReturnRC(rc);
8509 }
8510
8511#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
8512 task->mKeyStore = Utf8Str(bstrStateKeyStore);
8513 task->mKeyId = Utf8Str(bstrStateKeyId);
8514 task->m_pKeyStore = m_pKeyStore;
8515#endif
8516
8517 rc = task->createThread();
8518 task = NULL;
8519 if (FAILED(rc))
8520 throw rc;
8521
8522 /* finally, set the state: no right to fail in this method afterwards
8523 * since we've already started the thread and it is now responsible for
8524 * any error reporting and appropriate state change! */
8525 if (mMachineState == MachineState_Saved || mMachineState == MachineState_AbortedSaved)
8526 i_setMachineState(MachineState_Restoring);
8527 else if (fTeleporterEnabled)
8528 i_setMachineState(MachineState_TeleportingIn);
8529 else
8530 i_setMachineState(MachineState_Starting);
8531 }
8532 catch (HRESULT aRC)
8533 {
8534 rc = aRC;
8535 }
8536
8537 if (FAILED(rc) && fBeganPoweringUp)
8538 {
8539
8540 /* The progress object will fetch the current error info */
8541 if (!pPowerupProgress.isNull())
8542 pPowerupProgress->i_notifyComplete(rc);
8543
8544 /* Save the error info across the IPC below. Can't be done before the
8545 * progress notification above, as saving the error info deletes it
8546 * from the current context, and thus the progress object wouldn't be
8547 * updated correctly. */
8548 ErrorInfoKeeper eik;
8549
8550 /* signal end of operation */
8551 mControl->EndPowerUp(rc);
8552 }
8553
8554 if (task)
8555 {
8556 ErrorInfoKeeper eik;
8557 delete task;
8558 }
8559
8560 LogFlowThisFunc(("mMachineState=%d, rc=%Rhrc\n", mMachineState, rc));
8561 LogFlowThisFuncLeave();
8562 return rc;
8563}
8564
8565/**
8566 * Internal power off worker routine.
8567 *
8568 * This method may be called only at certain places with the following meaning
8569 * as shown below:
8570 *
8571 * - if the machine state is either Running or Paused, a normal
8572 * Console-initiated powerdown takes place (e.g. PowerDown());
8573 * - if the machine state is Saving, saveStateThread() has successfully done its
8574 * job;
8575 * - if the machine state is Starting or Restoring, powerUpThread() has failed
8576 * to start/load the VM;
8577 * - if the machine state is Stopping, the VM has powered itself off (i.e. not
8578 * as a result of the powerDown() call).
8579 *
8580 * Calling it in situations other than the above will cause unexpected behavior.
8581 *
8582 * Note that this method should be the only one that destroys mpUVM and sets it
8583 * to NULL.
8584 *
8585 * @param aProgress Progress object to run (may be NULL).
8586 *
8587 * @note Locks this object for writing.
8588 *
8589 * @note Never call this method from a thread that called addVMCaller() or
8590 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
8591 * release(). Otherwise it will deadlock.
8592 */
8593HRESULT Console::i_powerDown(IProgress *aProgress /*= NULL*/)
8594{
8595 LogFlowThisFuncEnter();
8596
8597 AutoCaller autoCaller(this);
8598 AssertComRCReturnRC(autoCaller.rc());
8599
8600 ComPtr<IInternalProgressControl> pProgressControl(aProgress);
8601
8602 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8603
8604 /* Total # of steps for the progress object. Must correspond to the
8605 * number of "advance percent count" comments in this method! */
8606 enum { StepCount = 7 };
8607 /* current step */
8608 ULONG step = 0;
8609
8610 HRESULT rc = S_OK;
8611 int vrc = VINF_SUCCESS;
8612
8613 /* sanity */
8614 Assert(mVMDestroying == false);
8615
8616 PCVMMR3VTABLE const pVMM = mpVMM;
8617 AssertPtrReturn(pVMM, E_UNEXPECTED);
8618 PUVM pUVM = mpUVM;
8619 AssertPtrReturn(pUVM, E_UNEXPECTED);
8620
8621 uint32_t cRefs = pVMM->pfnVMR3RetainUVM(pUVM);
8622 Assert(cRefs != UINT32_MAX); NOREF(cRefs);
8623
8624 AssertMsg( mMachineState == MachineState_Running
8625 || mMachineState == MachineState_Paused
8626 || mMachineState == MachineState_Stuck
8627 || mMachineState == MachineState_Starting
8628 || mMachineState == MachineState_Stopping
8629 || mMachineState == MachineState_Saving
8630 || mMachineState == MachineState_Restoring
8631 || mMachineState == MachineState_TeleportingPausedVM
8632 || mMachineState == MachineState_TeleportingIn
8633 , ("Invalid machine state: %s\n", ::stringifyMachineState(mMachineState)));
8634
8635 LogRel(("Console::powerDown(): A request to power off the VM has been issued (mMachineState=%s, InUninit=%d)\n",
8636 ::stringifyMachineState(mMachineState), getObjectState().getState() == ObjectState::InUninit));
8637
8638 /* Check if we need to power off the VM. In case of mVMPoweredOff=true, the
8639 * VM has already powered itself off in vmstateChangeCallback() and is just
8640 * notifying Console about that. In case of Starting or Restoring,
8641 * powerUpThread() is calling us on failure, so the VM is already off at
8642 * that point. */
8643 if ( !mVMPoweredOff
8644 && ( mMachineState == MachineState_Starting
8645 || mMachineState == MachineState_Restoring
8646 || mMachineState == MachineState_TeleportingIn)
8647 )
8648 mVMPoweredOff = true;
8649
8650 /*
8651 * Go to Stopping state if not already there.
8652 *
8653 * Note that we don't go from Saving/Restoring to Stopping because
8654 * vmstateChangeCallback() needs it to set the state to Saved on
8655 * VMSTATE_TERMINATED. In terms of protecting from inappropriate operations
8656 * while leaving the lock below, Saving or Restoring should be fine too.
8657 * Ditto for TeleportingPausedVM -> Teleported.
8658 */
8659 if ( mMachineState != MachineState_Saving
8660 && mMachineState != MachineState_Restoring
8661 && mMachineState != MachineState_Stopping
8662 && mMachineState != MachineState_TeleportingIn
8663 && mMachineState != MachineState_TeleportingPausedVM
8664 )
8665 i_setMachineState(MachineState_Stopping);
8666
8667 /* ----------------------------------------------------------------------
8668 * DONE with necessary state changes, perform the power down actions (it's
8669 * safe to release the object lock now if needed)
8670 * ---------------------------------------------------------------------- */
8671
8672 if (mDisplay)
8673 {
8674 alock.release();
8675
8676 mDisplay->i_notifyPowerDown();
8677
8678 alock.acquire();
8679 }
8680
8681 /* Stop the VRDP server to prevent new clients connection while VM is being
8682 * powered off. */
8683 if (mConsoleVRDPServer)
8684 {
8685 LogFlowThisFunc(("Stopping VRDP server...\n"));
8686
8687 /* Leave the lock since EMT could call us back as addVMCaller() */
8688 alock.release();
8689
8690 mConsoleVRDPServer->Stop();
8691
8692 alock.acquire();
8693 }
8694
8695 /* advance percent count */
8696 if (pProgressControl)
8697 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8698
8699
8700 /* ----------------------------------------------------------------------
8701 * Now, wait for all mpUVM callers to finish their work if there are still
8702 * some on other threads. NO methods that need mpUVM (or initiate other calls
8703 * that need it) may be called after this point
8704 * ---------------------------------------------------------------------- */
8705
8706 /* go to the destroying state to prevent from adding new callers */
8707 mVMDestroying = true;
8708
8709 if (mVMCallers > 0)
8710 {
8711 /* lazy creation */
8712 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
8713 RTSemEventCreate(&mVMZeroCallersSem);
8714
8715 LogFlowThisFunc(("Waiting for mpUVM callers (%d) to drop to zero...\n", mVMCallers));
8716
8717 alock.release();
8718
8719 RTSemEventWait(mVMZeroCallersSem, RT_INDEFINITE_WAIT);
8720
8721 alock.acquire();
8722 }
8723
8724 /* advance percent count */
8725 if (pProgressControl)
8726 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8727
8728 vrc = VINF_SUCCESS;
8729
8730 /*
8731 * Power off the VM if not already done that.
8732 * Leave the lock since EMT will call vmstateChangeCallback.
8733 *
8734 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
8735 * VM-(guest-)initiated power off happened in parallel a ms before this
8736 * call. So far, we let this error pop up on the user's side.
8737 */
8738 if (!mVMPoweredOff)
8739 {
8740 LogFlowThisFunc(("Powering off the VM...\n"));
8741 alock.release();
8742 vrc = pVMM->pfnVMR3PowerOff(pUVM);
8743#ifdef VBOX_WITH_EXTPACK
8744 mptrExtPackManager->i_callAllVmPowerOffHooks(this, pVMM->pfnVMR3GetVM(pUVM), pVMM);
8745#endif
8746 alock.acquire();
8747 }
8748
8749 /* advance percent count */
8750 if (pProgressControl)
8751 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8752
8753#ifdef VBOX_WITH_HGCM
8754 /* Shutdown HGCM services before destroying the VM. */
8755 if (m_pVMMDev)
8756 {
8757 LogFlowThisFunc(("Shutdown HGCM...\n"));
8758
8759 /* Leave the lock since EMT might wait for it and will call us back as addVMCaller() */
8760 alock.release();
8761
8762# ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
8763 /** @todo Deregister area callbacks? */
8764# endif
8765# ifdef VBOX_WITH_DRAG_AND_DROP
8766 if (m_hHgcmSvcExtDragAndDrop)
8767 {
8768 HGCMHostUnregisterServiceExtension(m_hHgcmSvcExtDragAndDrop);
8769 m_hHgcmSvcExtDragAndDrop = NULL;
8770 }
8771# endif
8772
8773 m_pVMMDev->hgcmShutdown();
8774
8775 alock.acquire();
8776 }
8777
8778 /* advance percent count */
8779 if (pProgressControl)
8780 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8781
8782#endif /* VBOX_WITH_HGCM */
8783
8784 LogFlowThisFunc(("Ready for VM destruction.\n"));
8785
8786 /* If we are called from Console::uninit(), then try to destroy the VM even
8787 * on failure (this will most likely fail too, but what to do?..) */
8788 if (RT_SUCCESS(vrc) || getObjectState().getState() == ObjectState::InUninit)
8789 {
8790 /* If the machine has a USB controller, release all USB devices
8791 * (symmetric to the code in captureUSBDevices()) */
8792 if (mfVMHasUsbController)
8793 {
8794 alock.release();
8795 i_detachAllUSBDevices(false /* aDone */);
8796 alock.acquire();
8797 }
8798
8799 /* Now we've got to destroy the VM as well. (mpUVM is not valid beyond
8800 * this point). We release the lock before calling VMR3Destroy() because
8801 * it will result into calling destructors of drivers associated with
8802 * Console children which may in turn try to lock Console (e.g. by
8803 * instantiating SafeVMPtr to access mpUVM). It's safe here because
8804 * mVMDestroying is set which should prevent any activity. */
8805
8806 /* Set mpUVM to NULL early just in case if some old code is not using
8807 * addVMCaller()/releaseVMCaller(). (We have our own ref on pUVM.) */
8808 pVMM->pfnVMR3ReleaseUVM(mpUVM);
8809 mpUVM = NULL;
8810
8811 LogFlowThisFunc(("Destroying the VM...\n"));
8812
8813 alock.release();
8814
8815 vrc = pVMM->pfnVMR3Destroy(pUVM);
8816
8817 /* take the lock again */
8818 alock.acquire();
8819
8820 /* advance percent count */
8821 if (pProgressControl)
8822 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8823
8824 if (RT_SUCCESS(vrc))
8825 {
8826 LogFlowThisFunc(("Machine has been destroyed (mMachineState=%d)\n",
8827 mMachineState));
8828 /* Note: the Console-level machine state change happens on the
8829 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
8830 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
8831 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
8832 * occurred yet. This is okay, because mMachineState is already
8833 * Stopping in this case, so any other attempt to call PowerDown()
8834 * will be rejected. */
8835 }
8836 else
8837 {
8838 /* bad bad bad, but what to do? (Give Console our UVM ref.) */
8839 mpUVM = pUVM;
8840 pUVM = NULL;
8841 rc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not destroy the machine. (Error: %Rrc)"), vrc);
8842 }
8843
8844 /* Complete the detaching of the USB devices. */
8845 if (mfVMHasUsbController)
8846 {
8847 alock.release();
8848 i_detachAllUSBDevices(true /* aDone */);
8849 alock.acquire();
8850 }
8851
8852 /* advance percent count */
8853 if (pProgressControl)
8854 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8855 }
8856 else
8857 rc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not power off the machine. (Error: %Rrc)"), vrc);
8858
8859 /*
8860 * Finished with the destruction.
8861 *
8862 * Note that if something impossible happened and we've failed to destroy
8863 * the VM, mVMDestroying will remain true and mMachineState will be
8864 * something like Stopping, so most Console methods will return an error
8865 * to the caller.
8866 */
8867 if (pUVM != NULL)
8868 pVMM->pfnVMR3ReleaseUVM(pUVM);
8869 else
8870 mVMDestroying = false;
8871
8872 LogFlowThisFuncLeave();
8873 return rc;
8874}
8875
8876/**
8877 * @note Locks this object for writing.
8878 */
8879HRESULT Console::i_setMachineState(MachineState_T aMachineState, bool aUpdateServer /* = true */)
8880{
8881 AutoCaller autoCaller(this);
8882 AssertComRCReturnRC(autoCaller.rc());
8883
8884 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8885
8886 HRESULT rc = S_OK;
8887
8888 if (mMachineState != aMachineState)
8889 {
8890 LogThisFunc(("machineState=%s -> %s aUpdateServer=%RTbool\n",
8891 ::stringifyMachineState(mMachineState), ::stringifyMachineState(aMachineState), aUpdateServer));
8892 LogRel(("Console: Machine state changed to '%s'\n", ::stringifyMachineState(aMachineState)));
8893 mMachineState = aMachineState;
8894
8895 /// @todo (dmik)
8896 // possibly, we need to redo onStateChange() using the dedicated
8897 // Event thread, like it is done in VirtualBox. This will make it
8898 // much safer (no deadlocks possible if someone tries to use the
8899 // console from the callback), however, listeners will lose the
8900 // ability to synchronously react to state changes (is it really
8901 // necessary??)
8902 LogFlowThisFunc(("Doing onStateChange()...\n"));
8903 i_onStateChange(aMachineState);
8904 LogFlowThisFunc(("Done onStateChange()\n"));
8905
8906 if (aUpdateServer)
8907 {
8908 /* Server notification MUST be done from under the lock; otherwise
8909 * the machine state here and on the server might go out of sync
8910 * which can lead to various unexpected results (like the machine
8911 * state being >= MachineState_Running on the server, while the
8912 * session state is already SessionState_Unlocked at the same time
8913 * there).
8914 *
8915 * Cross-lock conditions should be carefully watched out: calling
8916 * UpdateState we will require Machine and SessionMachine locks
8917 * (remember that here we're holding the Console lock here, and also
8918 * all locks that have been acquire by the thread before calling
8919 * this method).
8920 */
8921 LogFlowThisFunc(("Doing mControl->UpdateState()...\n"));
8922 rc = mControl->UpdateState(aMachineState);
8923 LogFlowThisFunc(("mControl->UpdateState()=%Rhrc\n", rc));
8924 }
8925 }
8926
8927 return rc;
8928}
8929
8930/**
8931 * Searches for a shared folder with the given logical name
8932 * in the collection of shared folders.
8933 *
8934 * @param strName logical name of the shared folder
8935 * @param aSharedFolder where to return the found object
8936 * @param aSetError whether to set the error info if the folder is
8937 * not found
8938 * @return
8939 * S_OK when found or E_INVALIDARG when not found
8940 *
8941 * @note The caller must lock this object for writing.
8942 */
8943HRESULT Console::i_findSharedFolder(const Utf8Str &strName, ComObjPtr<SharedFolder> &aSharedFolder, bool aSetError /* = false */)
8944{
8945 /* sanity check */
8946 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8947
8948 SharedFolderMap::const_iterator it = m_mapSharedFolders.find(strName);
8949 if (it != m_mapSharedFolders.end())
8950 {
8951 aSharedFolder = it->second;
8952 return S_OK;
8953 }
8954
8955 if (aSetError)
8956 setError(VBOX_E_FILE_ERROR, tr("Could not find a shared folder named '%s'."), strName.c_str());
8957 return VBOX_E_FILE_ERROR;
8958}
8959
8960/**
8961 * Fetches the list of global or machine shared folders from the server.
8962 *
8963 * @param aGlobal true to fetch global folders.
8964 *
8965 * @note The caller must lock this object for writing.
8966 */
8967HRESULT Console::i_fetchSharedFolders(BOOL aGlobal)
8968{
8969 /* sanity check */
8970 AssertReturn( getObjectState().getState() == ObjectState::InInit
8971 || isWriteLockOnCurrentThread(), E_FAIL);
8972
8973 LogFlowThisFunc(("Entering\n"));
8974
8975 /* Check if we're online and keep it that way. */
8976 SafeVMPtrQuiet ptrVM(this);
8977 AutoVMCallerQuietWeak autoVMCaller(this);
8978 bool const online = ptrVM.isOk()
8979 && m_pVMMDev
8980 && m_pVMMDev->isShFlActive();
8981
8982 HRESULT rc = S_OK;
8983
8984 try
8985 {
8986 if (aGlobal)
8987 {
8988 /// @todo grab & process global folders when they are done
8989 }
8990 else
8991 {
8992 SharedFolderDataMap oldFolders;
8993 if (online)
8994 oldFolders = m_mapMachineSharedFolders;
8995
8996 m_mapMachineSharedFolders.clear();
8997
8998 SafeIfaceArray<ISharedFolder> folders;
8999 rc = mMachine->COMGETTER(SharedFolders)(ComSafeArrayAsOutParam(folders));
9000 if (FAILED(rc)) throw rc;
9001
9002 for (size_t i = 0; i < folders.size(); ++i)
9003 {
9004 ComPtr<ISharedFolder> pSharedFolder = folders[i];
9005
9006 Bstr bstr;
9007 rc = pSharedFolder->COMGETTER(Name)(bstr.asOutParam());
9008 if (FAILED(rc)) throw rc;
9009 Utf8Str strName(bstr);
9010
9011 rc = pSharedFolder->COMGETTER(HostPath)(bstr.asOutParam());
9012 if (FAILED(rc)) throw rc;
9013 Utf8Str strHostPath(bstr);
9014
9015 BOOL writable;
9016 rc = pSharedFolder->COMGETTER(Writable)(&writable);
9017 if (FAILED(rc)) throw rc;
9018
9019 BOOL autoMount;
9020 rc = pSharedFolder->COMGETTER(AutoMount)(&autoMount);
9021 if (FAILED(rc)) throw rc;
9022
9023 rc = pSharedFolder->COMGETTER(AutoMountPoint)(bstr.asOutParam());
9024 if (FAILED(rc)) throw rc;
9025 Utf8Str strAutoMountPoint(bstr);
9026
9027 m_mapMachineSharedFolders.insert(std::make_pair(strName,
9028 SharedFolderData(strHostPath, !!writable,
9029 !!autoMount, strAutoMountPoint)));
9030
9031 /* send changes to HGCM if the VM is running */
9032 if (online)
9033 {
9034 SharedFolderDataMap::iterator it = oldFolders.find(strName);
9035 if ( it == oldFolders.end()
9036 || it->second.m_strHostPath != strHostPath)
9037 {
9038 /* a new machine folder is added or
9039 * the existing machine folder is changed */
9040 if (m_mapSharedFolders.find(strName) != m_mapSharedFolders.end())
9041 ; /* the console folder exists, nothing to do */
9042 else
9043 {
9044 /* remove the old machine folder (when changed)
9045 * or the global folder if any (when new) */
9046 if ( it != oldFolders.end()
9047 || m_mapGlobalSharedFolders.find(strName) != m_mapGlobalSharedFolders.end()
9048 )
9049 {
9050 rc = i_removeSharedFolder(strName);
9051 if (FAILED(rc)) throw rc;
9052 }
9053
9054 /* create the new machine folder */
9055 rc = i_createSharedFolder(strName,
9056 SharedFolderData(strHostPath, !!writable, !!autoMount, strAutoMountPoint));
9057 if (FAILED(rc)) throw rc;
9058 }
9059 }
9060 /* forget the processed (or identical) folder */
9061 if (it != oldFolders.end())
9062 oldFolders.erase(it);
9063 }
9064 }
9065
9066 /* process outdated (removed) folders */
9067 if (online)
9068 {
9069 for (SharedFolderDataMap::const_iterator it = oldFolders.begin();
9070 it != oldFolders.end(); ++it)
9071 {
9072 if (m_mapSharedFolders.find(it->first) != m_mapSharedFolders.end())
9073 ; /* the console folder exists, nothing to do */
9074 else
9075 {
9076 /* remove the outdated machine folder */
9077 rc = i_removeSharedFolder(it->first);
9078 if (FAILED(rc)) throw rc;
9079
9080 /* create the global folder if there is any */
9081 SharedFolderDataMap::const_iterator git =
9082 m_mapGlobalSharedFolders.find(it->first);
9083 if (git != m_mapGlobalSharedFolders.end())
9084 {
9085 rc = i_createSharedFolder(git->first, git->second);
9086 if (FAILED(rc)) throw rc;
9087 }
9088 }
9089 }
9090 }
9091 }
9092 }
9093 catch (HRESULT rc2)
9094 {
9095 rc = rc2;
9096 if (online)
9097 i_atVMRuntimeErrorCallbackF(0, "BrokenSharedFolder", N_("Broken shared folder!"));
9098 }
9099
9100 LogFlowThisFunc(("Leaving\n"));
9101
9102 return rc;
9103}
9104
9105/**
9106 * Searches for a shared folder with the given name in the list of machine
9107 * shared folders and then in the list of the global shared folders.
9108 *
9109 * @param strName Name of the folder to search for.
9110 * @param aIt Where to store the pointer to the found folder.
9111 * @return @c true if the folder was found and @c false otherwise.
9112 *
9113 * @note The caller must lock this object for reading.
9114 */
9115bool Console::i_findOtherSharedFolder(const Utf8Str &strName,
9116 SharedFolderDataMap::const_iterator &aIt)
9117{
9118 /* sanity check */
9119 AssertReturn(isWriteLockOnCurrentThread(), false);
9120
9121 /* first, search machine folders */
9122 aIt = m_mapMachineSharedFolders.find(strName);
9123 if (aIt != m_mapMachineSharedFolders.end())
9124 return true;
9125
9126 /* second, search machine folders */
9127 aIt = m_mapGlobalSharedFolders.find(strName);
9128 if (aIt != m_mapGlobalSharedFolders.end())
9129 return true;
9130
9131 return false;
9132}
9133
9134/**
9135 * Calls the HGCM service to add a shared folder definition.
9136 *
9137 * @param strName Shared folder name.
9138 * @param aData Shared folder data.
9139 *
9140 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
9141 * @note Doesn't lock anything.
9142 */
9143HRESULT Console::i_createSharedFolder(const Utf8Str &strName, const SharedFolderData &aData)
9144{
9145 Log(("Adding shared folder '%s' -> '%s'\n", strName.c_str(), aData.m_strHostPath.c_str()));
9146
9147 /*
9148 * Sanity checks
9149 */
9150 ComAssertRet(strName.isNotEmpty(), E_FAIL);
9151 ComAssertRet(aData.m_strHostPath.isNotEmpty(), E_FAIL);
9152
9153 AssertReturn(mpUVM, E_FAIL);
9154 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
9155
9156 /*
9157 * Find out whether we should allow symbolic link creation.
9158 */
9159 Bstr bstrValue;
9160 HRESULT hrc = mMachine->GetExtraData(BstrFmt("VBoxInternal2/SharedFoldersEnableSymlinksCreate/%s", strName.c_str()).raw(),
9161 bstrValue.asOutParam());
9162 bool fSymlinksCreate = hrc == S_OK && bstrValue == "1";
9163
9164 /*
9165 * Check whether the path is valid and exists.
9166 */
9167 char szAbsHostPath[RTPATH_MAX];
9168 int vrc = RTPathAbs(aData.m_strHostPath.c_str(), szAbsHostPath, sizeof(szAbsHostPath));
9169 if (RT_FAILURE(vrc))
9170 return setErrorBoth(E_INVALIDARG, vrc, tr("Invalid shared folder path: '%s' (%Rrc)"), aData.m_strHostPath.c_str(), vrc);
9171
9172 /* Check whether the path is full (absolute). ASSUMING a RTPATH_MAX of ~4K
9173 this also checks that the length is within bounds of a SHFLSTRING. */
9174 if (RTPathCompare(aData.m_strHostPath.c_str(), szAbsHostPath) != 0)
9175 return setError(E_INVALIDARG, tr("Shared folder path '%s' is not absolute"), aData.m_strHostPath.c_str());
9176
9177 bool const fMissing = !RTPathExists(szAbsHostPath);
9178
9179 /*
9180 * Check the other two string lengths before converting them all to SHFLSTRINGS.
9181 */
9182 if (strName.length() >= _2K)
9183 return setError(E_INVALIDARG, tr("Shared folder name is too long: %zu bytes", "", strName.length()), strName.length());
9184 if (aData.m_strAutoMountPoint.length() >= RTPATH_MAX)
9185 return setError(E_INVALIDARG, tr("Shared folder mount point too long: %zu bytes", "",
9186 (int)aData.m_strAutoMountPoint.length()),
9187 aData.m_strAutoMountPoint.length());
9188
9189 PSHFLSTRING pHostPath = ShflStringDupUtf8AsUtf16(aData.m_strHostPath.c_str());
9190 PSHFLSTRING pName = ShflStringDupUtf8AsUtf16(strName.c_str());
9191 PSHFLSTRING pAutoMountPoint = ShflStringDupUtf8AsUtf16(aData.m_strAutoMountPoint.c_str());
9192 if (pHostPath && pName && pAutoMountPoint)
9193 {
9194 /*
9195 * Make a SHFL_FN_ADD_MAPPING call to tell the service about folder.
9196 */
9197 VBOXHGCMSVCPARM aParams[SHFL_CPARMS_ADD_MAPPING];
9198 SHFLSTRING_TO_HGMC_PARAM(&aParams[0], pHostPath);
9199 SHFLSTRING_TO_HGMC_PARAM(&aParams[1], pName);
9200 HGCMSvcSetU32(&aParams[2],
9201 (aData.m_fWritable ? SHFL_ADD_MAPPING_F_WRITABLE : 0)
9202 | (aData.m_fAutoMount ? SHFL_ADD_MAPPING_F_AUTOMOUNT : 0)
9203 | (fSymlinksCreate ? SHFL_ADD_MAPPING_F_CREATE_SYMLINKS : 0)
9204 | (fMissing ? SHFL_ADD_MAPPING_F_MISSING : 0));
9205 SHFLSTRING_TO_HGMC_PARAM(&aParams[3], pAutoMountPoint);
9206 AssertCompile(SHFL_CPARMS_ADD_MAPPING == 4);
9207
9208 vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders", SHFL_FN_ADD_MAPPING, SHFL_CPARMS_ADD_MAPPING, aParams);
9209 if (RT_FAILURE(vrc))
9210 hrc = setErrorBoth(E_FAIL, vrc, tr("Could not create a shared folder '%s' mapped to '%s' (%Rrc)"),
9211 strName.c_str(), aData.m_strHostPath.c_str(), vrc);
9212
9213 else if (fMissing)
9214 hrc = setError(E_INVALIDARG, tr("Shared folder path '%s' does not exist on the host"), aData.m_strHostPath.c_str());
9215 else
9216 hrc = S_OK;
9217 }
9218 else
9219 hrc = E_OUTOFMEMORY;
9220 RTMemFree(pAutoMountPoint);
9221 RTMemFree(pName);
9222 RTMemFree(pHostPath);
9223 return hrc;
9224}
9225
9226/**
9227 * Calls the HGCM service to remove the shared folder definition.
9228 *
9229 * @param strName Shared folder name.
9230 *
9231 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
9232 * @note Doesn't lock anything.
9233 */
9234HRESULT Console::i_removeSharedFolder(const Utf8Str &strName)
9235{
9236 ComAssertRet(strName.isNotEmpty(), E_FAIL);
9237
9238 /* sanity checks */
9239 AssertReturn(mpUVM, E_FAIL);
9240 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
9241
9242 VBOXHGCMSVCPARM parms;
9243 SHFLSTRING *pMapName;
9244 size_t cbString;
9245
9246 Log(("Removing shared folder '%s'\n", strName.c_str()));
9247
9248 Bstr bstrName(strName);
9249 cbString = (bstrName.length() + 1) * sizeof(RTUTF16);
9250 if (cbString >= UINT16_MAX)
9251 return setError(E_INVALIDARG, tr("The name is too long"));
9252 pMapName = (SHFLSTRING *) RTMemAllocZ(SHFLSTRING_HEADER_SIZE + cbString);
9253 Assert(pMapName);
9254 memcpy(pMapName->String.ucs2, bstrName.raw(), cbString);
9255
9256 pMapName->u16Size = (uint16_t)cbString;
9257 pMapName->u16Length = (uint16_t)(cbString - sizeof(RTUTF16));
9258
9259 parms.type = VBOX_HGCM_SVC_PARM_PTR;
9260 parms.u.pointer.addr = pMapName;
9261 parms.u.pointer.size = ShflStringSizeOfBuffer(pMapName);
9262
9263 int vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders", SHFL_FN_REMOVE_MAPPING, 1, &parms);
9264 RTMemFree(pMapName);
9265 if (RT_FAILURE(vrc))
9266 return setErrorBoth(E_FAIL, vrc, tr("Could not remove the shared folder '%s' (%Rrc)"), strName.c_str(), vrc);
9267
9268 return S_OK;
9269}
9270
9271/**
9272 * Retains a reference to the default cryptographic interface.
9273 *
9274 * @returns VBox status code.
9275 * @retval VERR_NOT_SUPPORTED if the VM is not configured for encryption.
9276 * @param ppCryptoIf Where to store the pointer to the cryptographic interface on success.
9277 *
9278 * @note Locks this object for writing.
9279 */
9280int Console::i_retainCryptoIf(PCVBOXCRYPTOIF *ppCryptoIf)
9281{
9282 AssertReturn(ppCryptoIf != NULL, VERR_INVALID_PARAMETER);
9283
9284 int vrc = VINF_SUCCESS;
9285 if (mhLdrModCrypto == NIL_RTLDRMOD)
9286 {
9287#ifdef VBOX_WITH_EXTPACK
9288 /*
9289 * Check that a crypto extension pack name is set and resolve it into a
9290 * library path.
9291 */
9292 HRESULT hrc = S_OK;
9293 Bstr bstrExtPack;
9294
9295 ComPtr<IVirtualBox> pVirtualBox;
9296 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
9297 ComPtr<ISystemProperties> pSystemProperties;
9298 if (pVirtualBox)
9299 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
9300 if (pSystemProperties)
9301 pSystemProperties->COMGETTER(DefaultCryptoExtPack)(bstrExtPack.asOutParam());
9302 if (FAILED(hrc))
9303 return hrc;
9304
9305 Utf8Str strExtPack(bstrExtPack);
9306 if (strExtPack.isEmpty())
9307 {
9308 setError(VBOX_E_OBJECT_NOT_FOUND,
9309 tr("Ńo extension pack providing a cryptographic support module could be found"));
9310 return VERR_NOT_FOUND;
9311 }
9312
9313 Utf8Str strCryptoLibrary;
9314 vrc = mptrExtPackManager->i_getCryptoLibraryPathForExtPack(&strExtPack, &strCryptoLibrary);
9315 if (RT_SUCCESS(vrc))
9316 {
9317 RTERRINFOSTATIC ErrInfo;
9318 vrc = SUPR3HardenedLdrLoadPlugIn(strCryptoLibrary.c_str(), &mhLdrModCrypto, RTErrInfoInitStatic(&ErrInfo));
9319 if (RT_SUCCESS(vrc))
9320 {
9321 /* Resolve the entry point and query the pointer to the cryptographic interface. */
9322 PFNVBOXCRYPTOENTRY pfnCryptoEntry = NULL;
9323 vrc = RTLdrGetSymbol(mhLdrModCrypto, VBOX_CRYPTO_MOD_ENTRY_POINT, (void **)&pfnCryptoEntry);
9324 if (RT_SUCCESS(vrc))
9325 {
9326 vrc = pfnCryptoEntry(&mpCryptoIf);
9327 if (RT_FAILURE(vrc))
9328 setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
9329 tr("Failed to query the interface callback table from the cryptographic support module '%s' from extension pack '%s'"),
9330 strCryptoLibrary.c_str(), strExtPack.c_str());
9331 }
9332 else
9333 setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
9334 tr("Failed to resolve the entry point for the cryptographic support module '%s' from extension pack '%s'"),
9335 strCryptoLibrary.c_str(), strExtPack.c_str());
9336
9337 if (RT_FAILURE(vrc))
9338 {
9339 RTLdrClose(mhLdrModCrypto);
9340 mhLdrModCrypto = NIL_RTLDRMOD;
9341 }
9342 }
9343 else
9344 setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
9345 tr("Couldn't load the cryptographic support module '%s' from extension pack '%s' (error: '%s')"),
9346 strCryptoLibrary.c_str(), strExtPack.c_str(), ErrInfo.Core.pszMsg);
9347 }
9348 else
9349 setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
9350 tr("Couldn't resolve the library path of the crpytographic support module for extension pack '%s'"),
9351 strExtPack.c_str());
9352#else
9353 setError(VBOX_E_NOT_SUPPORTED,
9354 tr("The cryptographic support module is not supported in this build because extension packs are not supported"));
9355 vrc = VERR_NOT_SUPPORTED;
9356#endif
9357 }
9358
9359 if (RT_SUCCESS(vrc))
9360 {
9361 ASMAtomicIncU32(&mcRefsCrypto);
9362 *ppCryptoIf = mpCryptoIf;
9363 }
9364
9365 return vrc;
9366}
9367
9368/**
9369 * Releases the reference of the given cryptographic interface.
9370 *
9371 * @returns VBox status code.
9372 * @param pCryptoIf Pointer to the cryptographic interface to release.
9373 *
9374 * @note Locks this object for writing.
9375 */
9376int Console::i_releaseCryptoIf(PCVBOXCRYPTOIF pCryptoIf)
9377{
9378 AssertReturn(pCryptoIf == mpCryptoIf, VERR_INVALID_PARAMETER);
9379
9380 ASMAtomicDecU32(&mcRefsCrypto);
9381 return VINF_SUCCESS;
9382}
9383
9384/**
9385 * Tries to unload any loaded cryptographic support module if it is not in use currently.
9386 *
9387 * @returns COM status code.
9388 *
9389 * @note Locks this object for writing.
9390 */
9391HRESULT Console::i_unloadCryptoIfModule(void)
9392{
9393 AutoCaller autoCaller(this);
9394 AssertComRCReturnRC(autoCaller.rc());
9395
9396 AutoWriteLock wlock(this COMMA_LOCKVAL_SRC_POS);
9397
9398 if (mcRefsCrypto)
9399 return setError(E_ACCESSDENIED,
9400 tr("The cryptographic support module is in use and can't be unloaded"));
9401
9402 if (mhLdrModCrypto != NIL_RTLDRMOD)
9403 {
9404 int vrc = RTLdrClose(mhLdrModCrypto);
9405 AssertRC(vrc);
9406 mhLdrModCrypto = NIL_RTLDRMOD;
9407 }
9408
9409 return S_OK;
9410}
9411
9412/** @callback_method_impl{FNVMATSTATE}
9413 *
9414 * @note Locks the Console object for writing.
9415 * @remarks The @a pUVM parameter can be NULL in one case where powerUpThread()
9416 * calls after the VM was destroyed.
9417 */
9418/*static*/ DECLCALLBACK(void)
9419Console::i_vmstateChangeCallback(PUVM pUVM, PCVMMR3VTABLE pVMM, VMSTATE enmState, VMSTATE enmOldState, void *pvUser)
9420{
9421 LogFlowFunc(("Changing state from %s to %s (pUVM=%p)\n",
9422 pVMM->pfnVMR3GetStateName(enmOldState), pVMM->pfnVMR3GetStateName(enmState), pUVM));
9423 RT_NOREF(pVMM);
9424
9425 Console *that = static_cast<Console *>(pvUser);
9426 AssertReturnVoid(that);
9427
9428 AutoCaller autoCaller(that);
9429
9430 /* Note that we must let this method proceed even if Console::uninit() has
9431 * been already called. In such case this VMSTATE change is a result of:
9432 * 1) powerDown() called from uninit() itself, or
9433 * 2) VM-(guest-)initiated power off. */
9434 AssertReturnVoid( autoCaller.isOk()
9435 || that->getObjectState().getState() == ObjectState::InUninit);
9436
9437 switch (enmState)
9438 {
9439 /*
9440 * The VM has terminated
9441 */
9442 case VMSTATE_OFF:
9443 {
9444#ifdef VBOX_WITH_GUEST_PROPS
9445 if (that->mfTurnResetIntoPowerOff)
9446 {
9447 Bstr strPowerOffReason;
9448
9449 if (that->mfPowerOffCausedByReset)
9450 strPowerOffReason = Bstr("Reset");
9451 else
9452 strPowerOffReason = Bstr("PowerOff");
9453
9454 that->mMachine->DeleteGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw());
9455 that->mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw(),
9456 strPowerOffReason.raw(), Bstr("RDONLYGUEST").raw());
9457 that->mMachine->SaveSettings();
9458 }
9459#endif
9460
9461 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9462
9463 if (that->mVMStateChangeCallbackDisabled)
9464 return;
9465
9466 /* Do we still think that it is running? It may happen if this is a
9467 * VM-(guest-)initiated shutdown/poweroff.
9468 */
9469 if ( that->mMachineState != MachineState_Stopping
9470 && that->mMachineState != MachineState_Saving
9471 && that->mMachineState != MachineState_Restoring
9472 && that->mMachineState != MachineState_TeleportingIn
9473 && that->mMachineState != MachineState_TeleportingPausedVM
9474 && !that->mVMIsAlreadyPoweringOff
9475 )
9476 {
9477 LogFlowFunc(("VM has powered itself off but Console still thinks it is running. Notifying.\n"));
9478
9479 /*
9480 * Prevent powerDown() from calling VMR3PowerOff() again if this was called from
9481 * the power off state change.
9482 * When called from the Reset state make sure to call VMR3PowerOff() first.
9483 */
9484 Assert(that->mVMPoweredOff == false);
9485 that->mVMPoweredOff = true;
9486
9487 /*
9488 * request a progress object from the server
9489 * (this will set the machine state to Stopping on the server
9490 * to block others from accessing this machine)
9491 */
9492 ComPtr<IProgress> pProgress;
9493 HRESULT rc = that->mControl->BeginPoweringDown(pProgress.asOutParam());
9494 AssertComRC(rc);
9495
9496 /* sync the state with the server */
9497 that->i_setMachineStateLocally(MachineState_Stopping);
9498
9499 /*
9500 * Setup task object and thread to carry out the operation
9501 * asynchronously (if we call powerDown() right here but there
9502 * is one or more mpUVM callers (added with addVMCaller()) we'll
9503 * deadlock).
9504 */
9505 VMPowerDownTask *pTask = NULL;
9506 try
9507 {
9508 pTask = new VMPowerDownTask(that, pProgress);
9509 }
9510 catch (std::bad_alloc &)
9511 {
9512 LogRelFunc(("E_OUTOFMEMORY creating VMPowerDownTask"));
9513 rc = E_OUTOFMEMORY;
9514 break;
9515 }
9516
9517 /*
9518 * If creating a task failed, this can currently mean one of
9519 * two: either Console::uninit() has been called just a ms
9520 * before (so a powerDown() call is already on the way), or
9521 * powerDown() itself is being already executed. Just do
9522 * nothing.
9523 */
9524 if (pTask->isOk())
9525 {
9526 rc = pTask->createThread();
9527 pTask = NULL;
9528 if (FAILED(rc))
9529 LogRelFunc(("Problem with creating thread for VMPowerDownTask.\n"));
9530 }
9531 else
9532 {
9533 LogFlowFunc(("Console is already being uninitialized. (%Rhrc)\n", pTask->rc()));
9534 delete pTask;
9535 pTask = NULL;
9536 rc = E_FAIL;
9537 }
9538 }
9539 break;
9540 }
9541
9542 /* The VM has been completely destroyed.
9543 *
9544 * Note: This state change can happen at two points:
9545 * 1) At the end of VMR3Destroy() if it was not called from EMT.
9546 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
9547 * called by EMT.
9548 */
9549 case VMSTATE_TERMINATED:
9550 {
9551 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9552
9553 if (that->mVMStateChangeCallbackDisabled)
9554 break;
9555
9556#ifdef VBOX_WITH_CLOUD_NET
9557 /*
9558 * We stop cloud gateway here because we may have failed to connect to it,
9559 * configure it, or establish a tunnel. We definitely do not want an orphaned
9560 * instance running in the cloud.
9561 */
9562 if (!that->mGateway.mGatewayInstanceId.isEmpty())
9563 {
9564 ComPtr<IVirtualBox> pVirtualBox;
9565 HRESULT rc = that->mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
9566 AssertComRC(rc);
9567 if (SUCCEEDED(rc) && !pVirtualBox.isNull())
9568 stopCloudGateway(pVirtualBox, that->mGateway);
9569 }
9570#endif /* VBOX_WITH_CLOUD_NET */
9571 /* Terminate host interface networking. If pUVM is NULL, we've been
9572 * manually called from powerUpThread() either before calling
9573 * VMR3Create() or after VMR3Create() failed, so no need to touch
9574 * networking.
9575 */
9576 if (pUVM)
9577 that->i_powerDownHostInterfaces();
9578
9579 /* From now on the machine is officially powered down or remains in
9580 * the Saved state.
9581 */
9582 switch (that->mMachineState)
9583 {
9584 default:
9585 AssertFailed();
9586 RT_FALL_THRU();
9587 case MachineState_Stopping:
9588 /* successfully powered down */
9589 that->i_setMachineState(MachineState_PoweredOff);
9590 break;
9591 case MachineState_Saving:
9592 /* successfully saved */
9593 that->i_setMachineState(MachineState_Saved);
9594 break;
9595 case MachineState_Starting:
9596 /* failed to start, but be patient: set back to PoweredOff
9597 * (for similarity with the below) */
9598 that->i_setMachineState(MachineState_PoweredOff);
9599 break;
9600 case MachineState_Restoring:
9601 /* failed to load the saved state file, but be patient: set
9602 * to AbortedSaved (to preserve the saved state file) */
9603 that->i_setMachineState(MachineState_AbortedSaved);
9604 break;
9605 case MachineState_TeleportingIn:
9606 /* Teleportation failed or was canceled. Back to powered off. */
9607 that->i_setMachineState(MachineState_PoweredOff);
9608 break;
9609 case MachineState_TeleportingPausedVM:
9610 /* Successfully teleported the VM. */
9611 that->i_setMachineState(MachineState_Teleported);
9612 break;
9613 }
9614 break;
9615 }
9616
9617 case VMSTATE_RESETTING:
9618 /** @todo shouldn't VMSTATE_RESETTING_LS be here? */
9619 {
9620#ifdef VBOX_WITH_GUEST_PROPS
9621 /* Do not take any read/write locks here! */
9622 that->i_guestPropertiesHandleVMReset();
9623#endif
9624 break;
9625 }
9626
9627 case VMSTATE_SOFT_RESETTING:
9628 case VMSTATE_SOFT_RESETTING_LS:
9629 /* Shouldn't do anything here! */
9630 break;
9631
9632 case VMSTATE_SUSPENDED:
9633 {
9634 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9635
9636 if (that->mVMStateChangeCallbackDisabled)
9637 break;
9638
9639 switch (that->mMachineState)
9640 {
9641 case MachineState_Teleporting:
9642 that->i_setMachineState(MachineState_TeleportingPausedVM);
9643 break;
9644
9645 case MachineState_LiveSnapshotting:
9646 that->i_setMachineState(MachineState_OnlineSnapshotting);
9647 break;
9648
9649 case MachineState_TeleportingPausedVM:
9650 case MachineState_Saving:
9651 case MachineState_Restoring:
9652 case MachineState_Stopping:
9653 case MachineState_TeleportingIn:
9654 case MachineState_OnlineSnapshotting:
9655 /* The worker thread handles the transition. */
9656 break;
9657
9658 case MachineState_Running:
9659 that->i_setMachineState(MachineState_Paused);
9660 break;
9661
9662 case MachineState_Paused:
9663 /* Nothing to do. */
9664 break;
9665
9666 default:
9667 AssertMsgFailed(("%s\n", ::stringifyMachineState(that->mMachineState)));
9668 }
9669 break;
9670 }
9671
9672 case VMSTATE_SUSPENDED_LS:
9673 case VMSTATE_SUSPENDED_EXT_LS:
9674 {
9675 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9676 if (that->mVMStateChangeCallbackDisabled)
9677 break;
9678 switch (that->mMachineState)
9679 {
9680 case MachineState_Teleporting:
9681 that->i_setMachineState(MachineState_TeleportingPausedVM);
9682 break;
9683
9684 case MachineState_LiveSnapshotting:
9685 that->i_setMachineState(MachineState_OnlineSnapshotting);
9686 break;
9687
9688 case MachineState_TeleportingPausedVM:
9689 case MachineState_Saving:
9690 /* ignore */
9691 break;
9692
9693 default:
9694 AssertMsgFailed(("%s/%s -> %s\n", ::stringifyMachineState(that->mMachineState),
9695 pVMM->pfnVMR3GetStateName(enmOldState), pVMM->pfnVMR3GetStateName(enmState) ));
9696 that->i_setMachineState(MachineState_Paused);
9697 break;
9698 }
9699 break;
9700 }
9701
9702 case VMSTATE_RUNNING:
9703 {
9704 if ( enmOldState == VMSTATE_POWERING_ON
9705 || enmOldState == VMSTATE_RESUMING)
9706 {
9707 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9708
9709 if (that->mVMStateChangeCallbackDisabled)
9710 break;
9711
9712 Assert( ( ( that->mMachineState == MachineState_Starting
9713 || that->mMachineState == MachineState_Paused)
9714 && enmOldState == VMSTATE_POWERING_ON)
9715 || ( ( that->mMachineState == MachineState_Restoring
9716 || that->mMachineState == MachineState_TeleportingIn
9717 || that->mMachineState == MachineState_Paused
9718 || that->mMachineState == MachineState_Saving
9719 )
9720 && enmOldState == VMSTATE_RESUMING));
9721
9722 that->i_setMachineState(MachineState_Running);
9723 }
9724
9725 break;
9726 }
9727
9728 case VMSTATE_RUNNING_LS:
9729 AssertMsg( that->mMachineState == MachineState_LiveSnapshotting
9730 || that->mMachineState == MachineState_Teleporting,
9731 ("%s/%s -> %s\n", ::stringifyMachineState(that->mMachineState),
9732 pVMM->pfnVMR3GetStateName(enmOldState), pVMM->pfnVMR3GetStateName(enmState) ));
9733 break;
9734
9735 case VMSTATE_FATAL_ERROR:
9736 {
9737 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9738
9739 if (that->mVMStateChangeCallbackDisabled)
9740 break;
9741
9742 /* Fatal errors are only for running VMs. */
9743 Assert(Global::IsOnline(that->mMachineState));
9744
9745 /* Note! 'Pause' is used here in want of something better. There
9746 * are currently only two places where fatal errors might be
9747 * raised, so it is not worth adding a new externally
9748 * visible state for this yet. */
9749 that->i_setMachineState(MachineState_Paused);
9750 break;
9751 }
9752
9753 case VMSTATE_GURU_MEDITATION:
9754 {
9755 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9756
9757 if (that->mVMStateChangeCallbackDisabled)
9758 break;
9759
9760 /* Guru are only for running VMs */
9761 Assert(Global::IsOnline(that->mMachineState));
9762
9763 that->i_setMachineState(MachineState_Stuck);
9764 break;
9765 }
9766
9767 case VMSTATE_CREATED:
9768 {
9769 /*
9770 * We have to set the secret key helper interface for the VD drivers to
9771 * get notified about missing keys.
9772 */
9773 that->i_initSecretKeyIfOnAllAttachments();
9774 break;
9775 }
9776
9777 default: /* shut up gcc */
9778 break;
9779 }
9780}
9781
9782/**
9783 * Changes the clipboard mode.
9784 *
9785 * @returns VBox status code.
9786 * @param aClipboardMode new clipboard mode.
9787 */
9788int Console::i_changeClipboardMode(ClipboardMode_T aClipboardMode)
9789{
9790#ifdef VBOX_WITH_SHARED_CLIPBOARD
9791 VMMDev *pVMMDev = m_pVMMDev;
9792 AssertPtrReturn(pVMMDev, VERR_INVALID_POINTER);
9793
9794 VBOXHGCMSVCPARM parm;
9795 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
9796
9797 switch (aClipboardMode)
9798 {
9799 default:
9800 case ClipboardMode_Disabled:
9801 LogRel(("Shared Clipboard: Mode: Off\n"));
9802 parm.u.uint32 = VBOX_SHCL_MODE_OFF;
9803 break;
9804 case ClipboardMode_GuestToHost:
9805 LogRel(("Shared Clipboard: Mode: Guest to Host\n"));
9806 parm.u.uint32 = VBOX_SHCL_MODE_GUEST_TO_HOST;
9807 break;
9808 case ClipboardMode_HostToGuest:
9809 LogRel(("Shared Clipboard: Mode: Host to Guest\n"));
9810 parm.u.uint32 = VBOX_SHCL_MODE_HOST_TO_GUEST;
9811 break;
9812 case ClipboardMode_Bidirectional:
9813 LogRel(("Shared Clipboard: Mode: Bidirectional\n"));
9814 parm.u.uint32 = VBOX_SHCL_MODE_BIDIRECTIONAL;
9815 break;
9816 }
9817
9818 int vrc = pVMMDev->hgcmHostCall("VBoxSharedClipboard", VBOX_SHCL_HOST_FN_SET_MODE, 1, &parm);
9819 if (RT_FAILURE(vrc))
9820 LogRel(("Shared Clipboard: Error changing mode: %Rrc\n", vrc));
9821
9822 return vrc;
9823#else
9824 RT_NOREF(aClipboardMode);
9825 return VERR_NOT_IMPLEMENTED;
9826#endif
9827}
9828
9829/**
9830 * Changes the clipboard file transfer mode.
9831 *
9832 * @returns VBox status code.
9833 * @param aEnabled Whether clipboard file transfers are enabled or not.
9834 */
9835int Console::i_changeClipboardFileTransferMode(bool aEnabled)
9836{
9837#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
9838 VMMDev *pVMMDev = m_pVMMDev;
9839 AssertPtrReturn(pVMMDev, VERR_INVALID_POINTER);
9840
9841 VBOXHGCMSVCPARM parm;
9842 RT_ZERO(parm);
9843
9844 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
9845 parm.u.uint32 = aEnabled ? VBOX_SHCL_TRANSFER_MODE_ENABLED : VBOX_SHCL_TRANSFER_MODE_DISABLED;
9846
9847 int vrc = pVMMDev->hgcmHostCall("VBoxSharedClipboard", VBOX_SHCL_HOST_FN_SET_TRANSFER_MODE, 1 /* cParms */, &parm);
9848 if (RT_FAILURE(vrc))
9849 LogRel(("Shared Clipboard: Error changing file transfer mode: %Rrc\n", vrc));
9850
9851 return vrc;
9852#else
9853 RT_NOREF(aEnabled);
9854 return VERR_NOT_IMPLEMENTED;
9855#endif
9856}
9857
9858/**
9859 * Changes the drag and drop mode.
9860 *
9861 * @param aDnDMode new drag and drop mode.
9862 */
9863int Console::i_changeDnDMode(DnDMode_T aDnDMode)
9864{
9865 VMMDev *pVMMDev = m_pVMMDev;
9866 AssertPtrReturn(pVMMDev, VERR_INVALID_POINTER);
9867
9868 VBOXHGCMSVCPARM parm;
9869 RT_ZERO(parm);
9870 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
9871
9872 switch (aDnDMode)
9873 {
9874 default:
9875 case DnDMode_Disabled:
9876 LogRel(("Drag and drop mode: Off\n"));
9877 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_OFF;
9878 break;
9879 case DnDMode_GuestToHost:
9880 LogRel(("Drag and drop mode: Guest to Host\n"));
9881 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_GUEST_TO_HOST;
9882 break;
9883 case DnDMode_HostToGuest:
9884 LogRel(("Drag and drop mode: Host to Guest\n"));
9885 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_HOST_TO_GUEST;
9886 break;
9887 case DnDMode_Bidirectional:
9888 LogRel(("Drag and drop mode: Bidirectional\n"));
9889 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_BIDIRECTIONAL;
9890 break;
9891 }
9892
9893 int rc = pVMMDev->hgcmHostCall("VBoxDragAndDropSvc", DragAndDropSvc::HOST_DND_FN_SET_MODE, 1 /* cParms */, &parm);
9894 if (RT_FAILURE(rc))
9895 LogRel(("Error changing drag and drop mode: %Rrc\n", rc));
9896
9897 return rc;
9898}
9899
9900#ifdef VBOX_WITH_USB
9901/**
9902 * @interface_method_impl{REMOTEUSBIF,pfnQueryRemoteUsbBackend}
9903 */
9904/*static*/ DECLCALLBACK(PREMOTEUSBCALLBACK)
9905Console::i_usbQueryRemoteUsbBackend(void *pvUser, PCRTUUID pUuid, uint32_t idClient)
9906{
9907 Console *pConsole = (Console *)pvUser;
9908
9909 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
9910
9911 Guid const uuid(*pUuid);
9912 return (PREMOTEUSBCALLBACK)pConsole->i_consoleVRDPServer()->USBBackendRequestPointer(idClient, &uuid);
9913}
9914
9915
9916/**
9917 * Sends a request to VMM to attach the given host device.
9918 * After this method succeeds, the attached device will appear in the
9919 * mUSBDevices collection.
9920 *
9921 * @param aHostDevice device to attach
9922 *
9923 * @note Synchronously calls EMT.
9924 */
9925HRESULT Console::i_attachUSBDevice(IUSBDevice *aHostDevice, ULONG aMaskedIfs, const Utf8Str &aCaptureFilename)
9926{
9927 AssertReturn(aHostDevice, E_FAIL);
9928 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
9929
9930 HRESULT hrc;
9931
9932 /*
9933 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
9934 * method in EMT (using usbAttachCallback()).
9935 */
9936 Bstr bstrAddress;
9937 hrc = aHostDevice->COMGETTER(Address)(bstrAddress.asOutParam());
9938 ComAssertComRCRetRC(hrc);
9939 Utf8Str const Address(bstrAddress);
9940
9941 Bstr id;
9942 hrc = aHostDevice->COMGETTER(Id)(id.asOutParam());
9943 ComAssertComRCRetRC(hrc);
9944 Guid const uuid(id);
9945
9946 BOOL fRemote = FALSE;
9947 hrc = aHostDevice->COMGETTER(Remote)(&fRemote);
9948 ComAssertComRCRetRC(hrc);
9949
9950 Bstr bstrBackend;
9951 hrc = aHostDevice->COMGETTER(Backend)(bstrBackend.asOutParam());
9952 ComAssertComRCRetRC(hrc);
9953 Utf8Str const strBackend(bstrBackend);
9954
9955 /* Get the VM handle. */
9956 SafeVMPtr ptrVM(this);
9957 if (!ptrVM.isOk())
9958 return ptrVM.rc();
9959
9960 LogFlowThisFunc(("Proxying USB device '%s' {%RTuuid}...\n", Address.c_str(), uuid.raw()));
9961
9962 PCFGMNODE pRemoteCfg = NULL;
9963 if (fRemote)
9964 {
9965 RemoteUSBDevice *pRemoteUSBDevice = static_cast<RemoteUSBDevice *>(aHostDevice);
9966
9967 pRemoteCfg = mpVMM->pfnCFGMR3CreateTree(ptrVM.rawUVM());
9968 if (pRemoteCfg)
9969 {
9970 int vrc = mpVMM->pfnCFGMR3InsertInteger(pRemoteCfg, "ClientId", pRemoteUSBDevice->clientId());
9971 if (RT_FAILURE(vrc))
9972 {
9973 mpVMM->pfnCFGMR3DestroyTree(pRemoteCfg);
9974 return setErrorBoth(E_FAIL, vrc, tr("Failed to create configuration for USB device."));
9975 }
9976 }
9977 else
9978 return setErrorBoth(E_OUTOFMEMORY, VERR_NO_MEMORY, tr("Failed to allocate config tree for USB device."));
9979 }
9980
9981 USBConnectionSpeed_T enmSpeed;
9982 hrc = aHostDevice->COMGETTER(Speed)(&enmSpeed);
9983 AssertComRCReturnRC(hrc);
9984
9985 int vrc = ptrVM.vtable()->pfnVMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
9986 (PFNRT)i_usbAttachCallback, 11,
9987 this, ptrVM.rawUVM(), ptrVM.vtable(), aHostDevice, uuid.raw(),
9988 strBackend.c_str(), Address.c_str(), pRemoteCfg, enmSpeed, aMaskedIfs,
9989 aCaptureFilename.isEmpty() ? NULL : aCaptureFilename.c_str());
9990 if (RT_SUCCESS(vrc))
9991 {
9992 /* Create a OUSBDevice and add it to the device list */
9993 ComObjPtr<OUSBDevice> pUSBDevice;
9994 pUSBDevice.createObject();
9995 hrc = pUSBDevice->init(aHostDevice);
9996 AssertComRC(hrc);
9997
9998 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9999 mUSBDevices.push_back(pUSBDevice);
10000 LogFlowFunc(("Attached device {%RTuuid}\n", pUSBDevice->i_id().raw()));
10001
10002 /* notify callbacks */
10003 alock.release();
10004 i_onUSBDeviceStateChange(pUSBDevice, true /* aAttached */, NULL);
10005 }
10006 else
10007 {
10008 Log1WarningThisFunc(("Failed to create proxy device for '%s' {%RTuuid} (%Rrc)\n", Address.c_str(), uuid.raw(), vrc));
10009 switch (vrc)
10010 {
10011 case VERR_VUSB_NO_PORTS:
10012 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to attach the USB device. (No available ports on the USB controller)."));
10013 break;
10014 case VERR_VUSB_USBFS_PERMISSION:
10015 hrc = setErrorBoth(E_FAIL, vrc, tr("Not permitted to open the USB device, check usbfs options"));
10016 break;
10017 default:
10018 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to create a proxy device for the USB device. (Error: %Rrc)"), vrc);
10019 break;
10020 }
10021 }
10022
10023 return hrc;
10024}
10025
10026/**
10027 * USB device attach callback used by AttachUSBDevice().
10028 * Note that AttachUSBDevice() doesn't return until this callback is executed,
10029 * so we don't use AutoCaller and don't care about reference counters of
10030 * interface pointers passed in.
10031 *
10032 * @thread EMT
10033 * @note Locks the console object for writing.
10034 */
10035//static
10036DECLCALLBACK(int)
10037Console::i_usbAttachCallback(Console *that, PUVM pUVM, PCVMMR3VTABLE pVMM, IUSBDevice *aHostDevice, PCRTUUID aUuid,
10038 const char *pszBackend, const char *aAddress, PCFGMNODE pRemoteCfg, USBConnectionSpeed_T aEnmSpeed,
10039 ULONG aMaskedIfs, const char *pszCaptureFilename)
10040{
10041 RT_NOREF(aHostDevice);
10042 LogFlowFuncEnter();
10043 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
10044
10045 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
10046 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
10047
10048 VUSBSPEED enmSpeed = VUSB_SPEED_UNKNOWN;
10049 switch (aEnmSpeed)
10050 {
10051 case USBConnectionSpeed_Low: enmSpeed = VUSB_SPEED_LOW; break;
10052 case USBConnectionSpeed_Full: enmSpeed = VUSB_SPEED_FULL; break;
10053 case USBConnectionSpeed_High: enmSpeed = VUSB_SPEED_HIGH; break;
10054 case USBConnectionSpeed_Super: enmSpeed = VUSB_SPEED_SUPER; break;
10055 case USBConnectionSpeed_SuperPlus: enmSpeed = VUSB_SPEED_SUPERPLUS; break;
10056 default: AssertFailed(); break;
10057 }
10058
10059 int vrc = pVMM->pfnPDMR3UsbCreateProxyDevice(pUVM, aUuid, pszBackend, aAddress, pRemoteCfg,
10060 enmSpeed, aMaskedIfs, pszCaptureFilename);
10061 LogFlowFunc(("vrc=%Rrc\n", vrc));
10062 LogFlowFuncLeave();
10063 return vrc;
10064}
10065
10066/**
10067 * Sends a request to VMM to detach the given host device. After this method
10068 * succeeds, the detached device will disappear from the mUSBDevices
10069 * collection.
10070 *
10071 * @param aHostDevice device to attach
10072 *
10073 * @note Synchronously calls EMT.
10074 */
10075HRESULT Console::i_detachUSBDevice(const ComObjPtr<OUSBDevice> &aHostDevice)
10076{
10077 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
10078
10079 /* Get the VM handle. */
10080 SafeVMPtr ptrVM(this);
10081 if (!ptrVM.isOk())
10082 return ptrVM.rc();
10083
10084 /* if the device is attached, then there must at least one USB hub. */
10085 AssertReturn(ptrVM.vtable()->pfnPDMR3UsbHasHub(ptrVM.rawUVM()), E_FAIL);
10086
10087 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10088 LogFlowThisFunc(("Detaching USB proxy device {%RTuuid}...\n", aHostDevice->i_id().raw()));
10089
10090 /*
10091 * If this was a remote device, release the backend pointer.
10092 * The pointer was requested in usbAttachCallback.
10093 */
10094 BOOL fRemote = FALSE;
10095
10096 HRESULT hrc2 = aHostDevice->COMGETTER(Remote)(&fRemote);
10097 if (FAILED(hrc2))
10098 i_setErrorStatic(hrc2, "GetRemote() failed");
10099
10100 PCRTUUID pUuid = aHostDevice->i_id().raw();
10101 if (fRemote)
10102 {
10103 Guid guid(*pUuid);
10104 i_consoleVRDPServer()->USBBackendReleasePointer(&guid);
10105 }
10106
10107 alock.release();
10108 int vrc = ptrVM.vtable()->pfnVMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
10109 (PFNRT)i_usbDetachCallback, 4,
10110 this, ptrVM.rawUVM(), ptrVM.vtable(), pUuid);
10111 if (RT_SUCCESS(vrc))
10112 {
10113 LogFlowFunc(("Detached device {%RTuuid}\n", pUuid));
10114
10115 /* notify callbacks */
10116 i_onUSBDeviceStateChange(aHostDevice, false /* aAttached */, NULL);
10117 }
10118
10119 ComAssertRCRet(vrc, E_FAIL);
10120
10121 return S_OK;
10122}
10123
10124/**
10125 * USB device detach callback used by DetachUSBDevice().
10126 *
10127 * Note that DetachUSBDevice() doesn't return until this callback is executed,
10128 * so we don't use AutoCaller and don't care about reference counters of
10129 * interface pointers passed in.
10130 *
10131 * @thread EMT
10132 */
10133//static
10134DECLCALLBACK(int)
10135Console::i_usbDetachCallback(Console *that, PUVM pUVM, PCVMMR3VTABLE pVMM, PCRTUUID aUuid)
10136{
10137 LogFlowFuncEnter();
10138 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
10139
10140 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
10141 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
10142
10143 int vrc = pVMM->pfnPDMR3UsbDetachDevice(pUVM, aUuid);
10144
10145 LogFlowFunc(("vrc=%Rrc\n", vrc));
10146 LogFlowFuncLeave();
10147 return vrc;
10148}
10149#endif /* VBOX_WITH_USB */
10150
10151/* Note: FreeBSD needs this whether netflt is used or not. */
10152#if ((defined(RT_OS_LINUX) && !defined(VBOX_WITH_NETFLT)) || defined(RT_OS_FREEBSD))
10153
10154/**
10155 * Helper function to handle host interface device creation and attachment.
10156 *
10157 * @param networkAdapter the network adapter which attachment should be reset
10158 * @return COM status code
10159 *
10160 * @note The caller must lock this object for writing.
10161 *
10162 * @todo Move this back into the driver!
10163 */
10164HRESULT Console::i_attachToTapInterface(INetworkAdapter *networkAdapter)
10165{
10166 LogFlowThisFunc(("\n"));
10167 /* sanity check */
10168 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
10169
10170# ifdef VBOX_STRICT
10171 /* paranoia */
10172 NetworkAttachmentType_T attachment;
10173 networkAdapter->COMGETTER(AttachmentType)(&attachment);
10174 Assert(attachment == NetworkAttachmentType_Bridged);
10175# endif /* VBOX_STRICT */
10176
10177 HRESULT rc = S_OK;
10178
10179 ULONG slot = 0;
10180 rc = networkAdapter->COMGETTER(Slot)(&slot);
10181 AssertComRC(rc);
10182
10183# ifdef RT_OS_LINUX
10184 /*
10185 * Allocate a host interface device
10186 */
10187 int vrc = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
10188 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
10189 if (RT_SUCCESS(vrc))
10190 {
10191 /*
10192 * Set/obtain the tap interface.
10193 */
10194 struct ifreq IfReq;
10195 RT_ZERO(IfReq);
10196 /* The name of the TAP interface we are using */
10197 Bstr tapDeviceName;
10198 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
10199 if (FAILED(rc))
10200 tapDeviceName.setNull(); /* Is this necessary? */
10201 if (tapDeviceName.isEmpty())
10202 {
10203 LogRel(("No TAP device name was supplied.\n"));
10204 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
10205 }
10206
10207 if (SUCCEEDED(rc))
10208 {
10209 /* If we are using a static TAP device then try to open it. */
10210 Utf8Str str(tapDeviceName);
10211 RTStrCopy(IfReq.ifr_name, sizeof(IfReq.ifr_name), str.c_str()); /** @todo bitch about names which are too long... */
10212 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
10213 vrc = ioctl(RTFileToNative(maTapFD[slot]), TUNSETIFF, &IfReq);
10214 if (vrc != 0)
10215 {
10216 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
10217 rc = setErrorBoth(E_FAIL, vrc, tr("Failed to open the host network interface %ls"), tapDeviceName.raw());
10218 }
10219 }
10220 if (SUCCEEDED(rc))
10221 {
10222 /*
10223 * Make it pollable.
10224 */
10225 if (fcntl(RTFileToNative(maTapFD[slot]), F_SETFL, O_NONBLOCK) != -1)
10226 {
10227 Log(("i_attachToTapInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
10228 /*
10229 * Here is the right place to communicate the TAP file descriptor and
10230 * the host interface name to the server if/when it becomes really
10231 * necessary.
10232 */
10233 maTAPDeviceName[slot] = tapDeviceName;
10234 vrc = VINF_SUCCESS;
10235 }
10236 else
10237 {
10238 int iErr = errno;
10239
10240 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
10241 vrc = VERR_HOSTIF_BLOCKING;
10242 rc = setErrorBoth(E_FAIL, vrc, tr("could not set up the host networking device for non blocking access: %s"),
10243 strerror(errno));
10244 }
10245 }
10246 }
10247 else
10248 {
10249 LogRel(("Configuration error: Failed to open /dev/net/tun rc=%Rrc\n", vrc));
10250 switch (vrc)
10251 {
10252 case VERR_ACCESS_DENIED:
10253 /* will be handled by our caller */
10254 rc = E_ACCESSDENIED;
10255 break;
10256 default:
10257 rc = setErrorBoth(E_FAIL, vrc, tr("Could not set up the host networking device: %Rrc"), vrc);
10258 break;
10259 }
10260 }
10261
10262# elif defined(RT_OS_FREEBSD)
10263 /*
10264 * Set/obtain the tap interface.
10265 */
10266 /* The name of the TAP interface we are using */
10267 Bstr tapDeviceName;
10268 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
10269 if (FAILED(rc))
10270 tapDeviceName.setNull(); /* Is this necessary? */
10271 if (tapDeviceName.isEmpty())
10272 {
10273 LogRel(("No TAP device name was supplied.\n"));
10274 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
10275 }
10276 char szTapdev[1024] = "/dev/";
10277 /* If we are using a static TAP device then try to open it. */
10278 Utf8Str str(tapDeviceName);
10279 if (str.length() + strlen(szTapdev) <= sizeof(szTapdev))
10280 strcat(szTapdev, str.c_str());
10281 else
10282 memcpy(szTapdev + strlen(szTapdev), str.c_str(),
10283 sizeof(szTapdev) - strlen(szTapdev) - 1); /** @todo bitch about names which are too long... */
10284 int vrc = RTFileOpen(&maTapFD[slot], szTapdev,
10285 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT | RTFILE_O_NON_BLOCK);
10286
10287 if (RT_SUCCESS(vrc))
10288 maTAPDeviceName[slot] = tapDeviceName;
10289 else
10290 {
10291 switch (vrc)
10292 {
10293 case VERR_ACCESS_DENIED:
10294 /* will be handled by our caller */
10295 rc = E_ACCESSDENIED;
10296 break;
10297 default:
10298 rc = setErrorBoth(E_FAIL, vrc, tr("Failed to open the host network interface %ls"), tapDeviceName.raw());
10299 break;
10300 }
10301 }
10302# else
10303# error "huh?"
10304# endif
10305 /* in case of failure, cleanup. */
10306 if (RT_FAILURE(vrc) && SUCCEEDED(rc))
10307 {
10308 LogRel(("General failure attaching to host interface\n"));
10309 rc = setErrorBoth(E_FAIL, vrc, tr("General failure attaching to host interface"));
10310 }
10311 LogFlowThisFunc(("rc=%Rhrc\n", rc));
10312 return rc;
10313}
10314
10315
10316/**
10317 * Helper function to handle detachment from a host interface
10318 *
10319 * @param networkAdapter the network adapter which attachment should be reset
10320 * @return COM status code
10321 *
10322 * @note The caller must lock this object for writing.
10323 *
10324 * @todo Move this back into the driver!
10325 */
10326HRESULT Console::i_detachFromTapInterface(INetworkAdapter *networkAdapter)
10327{
10328 /* sanity check */
10329 LogFlowThisFunc(("\n"));
10330 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
10331
10332 HRESULT rc = S_OK;
10333# ifdef VBOX_STRICT
10334 /* paranoia */
10335 NetworkAttachmentType_T attachment;
10336 networkAdapter->COMGETTER(AttachmentType)(&attachment);
10337 Assert(attachment == NetworkAttachmentType_Bridged);
10338# endif /* VBOX_STRICT */
10339
10340 ULONG slot = 0;
10341 rc = networkAdapter->COMGETTER(Slot)(&slot);
10342 AssertComRC(rc);
10343
10344 /* is there an open TAP device? */
10345 if (maTapFD[slot] != NIL_RTFILE)
10346 {
10347 /*
10348 * Close the file handle.
10349 */
10350 Bstr tapDeviceName, tapTerminateApplication;
10351 bool isStatic = true;
10352 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
10353 if (FAILED(rc) || tapDeviceName.isEmpty())
10354 {
10355 /* If the name is empty, this is a dynamic TAP device, so close it now,
10356 so that the termination script can remove the interface. Otherwise we still
10357 need the FD to pass to the termination script. */
10358 isStatic = false;
10359 int rcVBox = RTFileClose(maTapFD[slot]);
10360 AssertRC(rcVBox);
10361 maTapFD[slot] = NIL_RTFILE;
10362 }
10363 if (isStatic)
10364 {
10365 /* If we are using a static TAP device, we close it now, after having called the
10366 termination script. */
10367 int rcVBox = RTFileClose(maTapFD[slot]);
10368 AssertRC(rcVBox);
10369 }
10370 /* the TAP device name and handle are no longer valid */
10371 maTapFD[slot] = NIL_RTFILE;
10372 maTAPDeviceName[slot] = "";
10373 }
10374 LogFlowThisFunc(("returning %d\n", rc));
10375 return rc;
10376}
10377
10378#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
10379
10380/**
10381 * Called at power down to terminate host interface networking.
10382 *
10383 * @note The caller must lock this object for writing.
10384 */
10385HRESULT Console::i_powerDownHostInterfaces()
10386{
10387 LogFlowThisFunc(("\n"));
10388
10389 /* sanity check */
10390 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
10391
10392 /*
10393 * host interface termination handling
10394 */
10395 HRESULT rc = S_OK;
10396 ComPtr<IVirtualBox> pVirtualBox;
10397 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
10398 ComPtr<ISystemProperties> pSystemProperties;
10399 if (pVirtualBox)
10400 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
10401 ChipsetType_T chipsetType = ChipsetType_PIIX3;
10402 mMachine->COMGETTER(ChipsetType)(&chipsetType);
10403 ULONG maxNetworkAdapters = 0;
10404 if (pSystemProperties)
10405 pSystemProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters);
10406
10407 for (ULONG slot = 0; slot < maxNetworkAdapters; slot++)
10408 {
10409 ComPtr<INetworkAdapter> pNetworkAdapter;
10410 rc = mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
10411 if (FAILED(rc)) break;
10412
10413 BOOL enabled = FALSE;
10414 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
10415 if (!enabled)
10416 continue;
10417
10418 NetworkAttachmentType_T attachment;
10419 pNetworkAdapter->COMGETTER(AttachmentType)(&attachment);
10420 if (attachment == NetworkAttachmentType_Bridged)
10421 {
10422#if ((defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)) && !defined(VBOX_WITH_NETFLT))
10423 HRESULT rc2 = i_detachFromTapInterface(pNetworkAdapter);
10424 if (FAILED(rc2) && SUCCEEDED(rc))
10425 rc = rc2;
10426#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
10427 }
10428 }
10429
10430 return rc;
10431}
10432
10433
10434/**
10435 * Process callback handler for VMR3LoadFromFile, VMR3LoadFromStream, VMR3Save
10436 * and VMR3Teleport.
10437 *
10438 * @param pUVM The user mode VM handle.
10439 * @param uPercent Completion percentage (0-100).
10440 * @param pvUser Pointer to an IProgress instance.
10441 * @return VINF_SUCCESS.
10442 */
10443/*static*/
10444DECLCALLBACK(int) Console::i_stateProgressCallback(PUVM pUVM, unsigned uPercent, void *pvUser)
10445{
10446 IProgress *pProgress = static_cast<IProgress *>(pvUser);
10447
10448 /* update the progress object */
10449 if (pProgress)
10450 {
10451 ComPtr<IInternalProgressControl> pProgressControl(pProgress);
10452 AssertReturn(!!pProgressControl, VERR_INVALID_PARAMETER);
10453 pProgressControl->SetCurrentOperationProgress(uPercent);
10454 }
10455
10456 NOREF(pUVM);
10457 return VINF_SUCCESS;
10458}
10459
10460/**
10461 * @copydoc FNVMATERROR
10462 *
10463 * @remarks Might be some tiny serialization concerns with access to the string
10464 * object here...
10465 */
10466/*static*/ DECLCALLBACK(void)
10467Console::i_genericVMSetErrorCallback(PUVM pUVM, void *pvUser, int rc, RT_SRC_POS_DECL, const char *pszFormat, va_list args)
10468{
10469 RT_SRC_POS_NOREF();
10470 Utf8Str *pErrorText = (Utf8Str *)pvUser;
10471 AssertPtr(pErrorText);
10472
10473 /* We ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users. */
10474 va_list va2;
10475 va_copy(va2, args);
10476
10477 /* Append to any the existing error message. */
10478 try
10479 {
10480 if (pErrorText->length())
10481 pErrorText->appendPrintf(".\n%N (%Rrc)", pszFormat, &va2, rc, rc);
10482 else
10483 pErrorText->printf("%N (%Rrc)", pszFormat, &va2, rc, rc);
10484 }
10485 catch (std::bad_alloc &)
10486 {
10487 }
10488
10489 va_end(va2);
10490
10491 NOREF(pUVM);
10492}
10493
10494/**
10495 * VM runtime error callback function (FNVMATRUNTIMEERROR).
10496 *
10497 * See VMSetRuntimeError for the detailed description of parameters.
10498 *
10499 * @param pUVM The user mode VM handle. Ignored, so passing NULL
10500 * is fine.
10501 * @param pvUser The user argument, pointer to the Console instance.
10502 * @param fFlags The action flags. See VMSETRTERR_FLAGS_*.
10503 * @param pszErrorId Error ID string.
10504 * @param pszFormat Error message format string.
10505 * @param va Error message arguments.
10506 * @thread EMT.
10507 */
10508/* static */ DECLCALLBACK(void)
10509Console::i_atVMRuntimeErrorCallback(PUVM pUVM, void *pvUser, uint32_t fFlags,
10510 const char *pszErrorId, const char *pszFormat, va_list va)
10511{
10512 bool const fFatal = !!(fFlags & VMSETRTERR_FLAGS_FATAL);
10513 LogFlowFuncEnter();
10514
10515 Console *that = static_cast<Console *>(pvUser);
10516 AssertReturnVoid(that);
10517
10518 Utf8Str message(pszFormat, va);
10519
10520 LogRel(("Console: VM runtime error: fatal=%RTbool, errorID=%s message=\"%s\"\n", fFatal, pszErrorId, message.c_str()));
10521 try
10522 {
10523 that->i_onRuntimeError(BOOL(fFatal), Bstr(pszErrorId).raw(), Bstr(message).raw());
10524 }
10525 catch (std::bad_alloc &)
10526 {
10527 }
10528 LogFlowFuncLeave(); NOREF(pUVM);
10529}
10530
10531/**
10532 * Captures USB devices that match filters of the VM.
10533 * Called at VM startup.
10534 *
10535 * @param pUVM The VM handle.
10536 */
10537HRESULT Console::i_captureUSBDevices(PUVM pUVM)
10538{
10539 RT_NOREF(pUVM);
10540 LogFlowThisFunc(("\n"));
10541
10542 /* sanity check */
10543 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
10544 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10545
10546 /* If the machine has a USB controller, ask the USB proxy service to
10547 * capture devices */
10548 if (mfVMHasUsbController)
10549 {
10550 /* release the lock before calling Host in VBoxSVC since Host may call
10551 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
10552 * produce an inter-process dead-lock otherwise. */
10553 alock.release();
10554
10555 HRESULT hrc = mControl->AutoCaptureUSBDevices();
10556 ComAssertComRCRetRC(hrc);
10557 }
10558
10559 return S_OK;
10560}
10561
10562
10563/**
10564 * Detach all USB device which are attached to the VM for the
10565 * purpose of clean up and such like.
10566 */
10567void Console::i_detachAllUSBDevices(bool aDone)
10568{
10569 LogFlowThisFunc(("aDone=%RTbool\n", aDone));
10570
10571 /* sanity check */
10572 AssertReturnVoid(!isWriteLockOnCurrentThread());
10573 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10574
10575 mUSBDevices.clear();
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 mControl->DetachAllUSBDevices(aDone);
10583}
10584
10585/**
10586 * @note Locks this object for writing.
10587 */
10588void Console::i_processRemoteUSBDevices(uint32_t u32ClientId, VRDEUSBDEVICEDESC *pDevList, uint32_t cbDevList, bool fDescExt)
10589{
10590 LogFlowThisFuncEnter();
10591 LogFlowThisFunc(("u32ClientId = %d, pDevList=%p, cbDevList = %d, fDescExt = %d\n",
10592 u32ClientId, pDevList, cbDevList, fDescExt));
10593
10594 AutoCaller autoCaller(this);
10595 if (!autoCaller.isOk())
10596 {
10597 /* Console has been already uninitialized, deny request */
10598 AssertMsgFailed(("Console is already uninitialized\n"));
10599 LogFlowThisFunc(("Console is already uninitialized\n"));
10600 LogFlowThisFuncLeave();
10601 return;
10602 }
10603
10604 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10605
10606 /*
10607 * Mark all existing remote USB devices as dirty.
10608 */
10609 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
10610 it != mRemoteUSBDevices.end();
10611 ++it)
10612 {
10613 (*it)->dirty(true);
10614 }
10615
10616 /*
10617 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
10618 */
10619 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
10620 VRDEUSBDEVICEDESC *e = pDevList;
10621
10622 /* The cbDevList condition must be checked first, because the function can
10623 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
10624 */
10625 while (cbDevList >= 2 && e->oNext)
10626 {
10627 /* Sanitize incoming strings in case they aren't valid UTF-8. */
10628 if (e->oManufacturer)
10629 RTStrPurgeEncoding((char *)e + e->oManufacturer);
10630 if (e->oProduct)
10631 RTStrPurgeEncoding((char *)e + e->oProduct);
10632 if (e->oSerialNumber)
10633 RTStrPurgeEncoding((char *)e + e->oSerialNumber);
10634
10635 LogFlowThisFunc(("vendor %04x, product %04x, name = %s\n",
10636 e->idVendor, e->idProduct, e->oProduct ? (char *)e + e->oProduct : ""));
10637
10638 bool fNewDevice = true;
10639
10640 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
10641 it != mRemoteUSBDevices.end();
10642 ++it)
10643 {
10644 if ( (*it)->devId() == e->id
10645 && (*it)->clientId() == u32ClientId)
10646 {
10647 /* The device is already in the list. */
10648 (*it)->dirty(false);
10649 fNewDevice = false;
10650 break;
10651 }
10652 }
10653
10654 if (fNewDevice)
10655 {
10656 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
10657 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""));
10658
10659 /* Create the device object and add the new device to list. */
10660 ComObjPtr<RemoteUSBDevice> pUSBDevice;
10661 pUSBDevice.createObject();
10662 pUSBDevice->init(u32ClientId, e, fDescExt);
10663
10664 mRemoteUSBDevices.push_back(pUSBDevice);
10665
10666 /* Check if the device is ok for current USB filters. */
10667 BOOL fMatched = FALSE;
10668 ULONG fMaskedIfs = 0;
10669 HRESULT hrc = mControl->RunUSBDeviceFilters(pUSBDevice, &fMatched, &fMaskedIfs);
10670
10671 AssertComRC(hrc);
10672
10673 LogFlowThisFunc(("USB filters return %d %#x\n", fMatched, fMaskedIfs));
10674
10675 if (fMatched)
10676 {
10677 alock.release();
10678 hrc = i_onUSBDeviceAttach(pUSBDevice, NULL, fMaskedIfs, Utf8Str());
10679 alock.acquire();
10680
10681 /// @todo (r=dmik) warning reporting subsystem
10682
10683 if (hrc == S_OK)
10684 {
10685 LogFlowThisFunc(("Device attached\n"));
10686 pUSBDevice->captured(true);
10687 }
10688 }
10689 }
10690
10691 if (cbDevList < e->oNext)
10692 {
10693 Log1WarningThisFunc(("cbDevList %d > oNext %d\n", cbDevList, e->oNext));
10694 break;
10695 }
10696
10697 cbDevList -= e->oNext;
10698
10699 e = (VRDEUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
10700 }
10701
10702 /*
10703 * Remove dirty devices, that is those which are not reported by the server anymore.
10704 */
10705 for (;;)
10706 {
10707 ComObjPtr<RemoteUSBDevice> pUSBDevice;
10708
10709 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
10710 while (it != mRemoteUSBDevices.end())
10711 {
10712 if ((*it)->dirty())
10713 {
10714 pUSBDevice = *it;
10715 break;
10716 }
10717
10718 ++it;
10719 }
10720
10721 if (!pUSBDevice)
10722 {
10723 break;
10724 }
10725
10726 USHORT vendorId = 0;
10727 pUSBDevice->COMGETTER(VendorId)(&vendorId);
10728
10729 USHORT productId = 0;
10730 pUSBDevice->COMGETTER(ProductId)(&productId);
10731
10732 Bstr product;
10733 pUSBDevice->COMGETTER(Product)(product.asOutParam());
10734
10735 LogRel(("Remote USB: ---- Vendor %04x. Product %04x. Name = [%ls].\n", vendorId, productId, product.raw()));
10736
10737 /* Detach the device from VM. */
10738 if (pUSBDevice->captured())
10739 {
10740 Bstr uuid;
10741 pUSBDevice->COMGETTER(Id)(uuid.asOutParam());
10742 alock.release();
10743 i_onUSBDeviceDetach(uuid.raw(), NULL);
10744 alock.acquire();
10745 }
10746
10747 /* And remove it from the list. */
10748 mRemoteUSBDevices.erase(it);
10749 }
10750
10751 LogFlowThisFuncLeave();
10752}
10753
10754
10755/**
10756 * Worker called by VMPowerUpTask::handler to start the VM (also from saved
10757 * state) and track progress.
10758 *
10759 * @param pTask The power up task.
10760 *
10761 * @note Locks the Console object for writing.
10762 */
10763/*static*/
10764void Console::i_powerUpThreadTask(VMPowerUpTask *pTask)
10765{
10766 LogFlowFuncEnter();
10767
10768 AssertReturnVoid(pTask);
10769 AssertReturnVoid(!pTask->mConsole.isNull());
10770 AssertReturnVoid(!pTask->mProgress.isNull());
10771
10772 VirtualBoxBase::initializeComForThread();
10773
10774 HRESULT rc = S_OK;
10775 int vrc = VINF_SUCCESS;
10776
10777 /* Set up a build identifier so that it can be seen from core dumps what
10778 * exact build was used to produce the core. */
10779 static char s_szBuildID[48];
10780 RTStrPrintf(s_szBuildID, sizeof(s_szBuildID), "%s%s%s%s VirtualBox %s r%u %s%s%s%s",
10781 "BU", "IL", "DI", "D", RTBldCfgVersion(), RTBldCfgRevision(), "BU", "IL", "DI", "D");
10782
10783 ComObjPtr<Console> pConsole = pTask->mConsole;
10784
10785 /* Note: no need to use AutoCaller because VMPowerUpTask does that */
10786
10787 /* The lock is also used as a signal from the task initiator (which
10788 * releases it only after RTThreadCreate()) that we can start the job */
10789 AutoWriteLock alock(pConsole COMMA_LOCKVAL_SRC_POS);
10790
10791 /* sanity */
10792 Assert(pConsole->mpUVM == NULL);
10793
10794 try
10795 {
10796 // Create the VMM device object, which starts the HGCM thread; do this only
10797 // once for the console, for the pathological case that the same console
10798 // object is used to power up a VM twice.
10799 if (!pConsole->m_pVMMDev)
10800 {
10801 pConsole->m_pVMMDev = new VMMDev(pConsole);
10802 AssertReturnVoid(pConsole->m_pVMMDev);
10803 }
10804
10805 /* wait for auto reset ops to complete so that we can successfully lock
10806 * the attached hard disks by calling LockMedia() below */
10807 for (VMPowerUpTask::ProgressList::const_iterator
10808 it = pTask->hardDiskProgresses.begin();
10809 it != pTask->hardDiskProgresses.end(); ++it)
10810 {
10811 HRESULT rc2 = (*it)->WaitForCompletion(-1);
10812 AssertComRC(rc2);
10813
10814 rc = pTask->mProgress->SetNextOperation(BstrFmt(tr("Disk Image Reset Operation - Immutable Image")).raw(), 1);
10815 AssertComRCReturnVoid(rc);
10816 }
10817
10818 /*
10819 * Lock attached media. This method will also check their accessibility.
10820 * If we're a teleporter, we'll have to postpone this action so we can
10821 * migrate between local processes.
10822 *
10823 * Note! The media will be unlocked automatically by
10824 * SessionMachine::i_setMachineState() when the VM is powered down.
10825 */
10826 if (!pTask->mTeleporterEnabled)
10827 {
10828 rc = pConsole->mControl->LockMedia();
10829 if (FAILED(rc)) throw rc;
10830 }
10831
10832 /* Create the VRDP server. In case of headless operation, this will
10833 * also create the framebuffer, required at VM creation.
10834 */
10835 ConsoleVRDPServer *server = pConsole->i_consoleVRDPServer();
10836 Assert(server);
10837
10838 /* Does VRDP server call Console from the other thread?
10839 * Not sure (and can change), so release the lock just in case.
10840 */
10841 alock.release();
10842 vrc = server->Launch();
10843 alock.acquire();
10844
10845 if (vrc != VINF_SUCCESS)
10846 {
10847 Utf8Str errMsg = pConsole->VRDPServerErrorToMsg(vrc);
10848 if ( RT_FAILURE(vrc)
10849 && vrc != VERR_NET_ADDRESS_IN_USE) /* not fatal */
10850 throw i_setErrorStaticBoth(E_FAIL, vrc, errMsg.c_str());
10851 }
10852
10853 ComPtr<IMachine> pMachine = pConsole->i_machine();
10854 ULONG cCpus = 1;
10855 pMachine->COMGETTER(CPUCount)(&cCpus);
10856
10857 VMProcPriority_T enmVMPriority = VMProcPriority_Default;
10858 pMachine->COMGETTER(VMProcessPriority)(&enmVMPriority);
10859
10860 /*
10861 * Create the VM
10862 *
10863 * Note! Release the lock since EMT will call Console. It's safe because
10864 * mMachineState is either Starting or Restoring state here.
10865 */
10866 alock.release();
10867
10868 if (enmVMPriority != VMProcPriority_Default)
10869 pConsole->i_onVMProcessPriorityChange(enmVMPriority);
10870
10871 PCVMMR3VTABLE pVMM = pConsole->mpVMM;
10872 PVM pVM = NULL;
10873 vrc = pVMM->pfnVMR3Create(cCpus,
10874 pConsole->mpVmm2UserMethods,
10875 Console::i_genericVMSetErrorCallback,
10876 &pTask->mErrorMsg,
10877 pTask->mpfnConfigConstructor,
10878 static_cast<Console *>(pConsole),
10879 &pVM, NULL);
10880 alock.acquire();
10881 if (RT_SUCCESS(vrc))
10882 {
10883 do /* break "loop" */
10884 {
10885 /*
10886 * Register our load/save state file handlers
10887 */
10888 vrc = pVMM->pfnSSMR3RegisterExternal(pConsole->mpUVM, sSSMConsoleUnit, 0 /*iInstance*/,
10889 CONSOLE_SAVED_STATE_VERSION, 0 /* cbGuess */,
10890 NULL, NULL, NULL,
10891 NULL, i_saveStateFileExec, NULL,
10892 NULL, i_loadStateFileExec, NULL,
10893 static_cast<Console *>(pConsole));
10894 AssertRCBreak(vrc);
10895
10896 vrc = static_cast<Console *>(pConsole)->i_getDisplay()->i_registerSSM(pConsole->mpUVM);
10897 AssertRC(vrc);
10898 if (RT_FAILURE(vrc))
10899 break;
10900
10901 /*
10902 * Synchronize debugger settings
10903 */
10904 MachineDebugger *machineDebugger = pConsole->i_getMachineDebugger();
10905 if (machineDebugger)
10906 machineDebugger->i_flushQueuedSettings();
10907
10908 /*
10909 * Shared Folders
10910 */
10911 if (pConsole->m_pVMMDev->isShFlActive())
10912 {
10913 /* Does the code below call Console from the other thread?
10914 * Not sure, so release the lock just in case. */
10915 alock.release();
10916
10917 for (SharedFolderDataMap::const_iterator it = pTask->mSharedFolders.begin();
10918 it != pTask->mSharedFolders.end();
10919 ++it)
10920 {
10921 const SharedFolderData &d = it->second;
10922 rc = pConsole->i_createSharedFolder(it->first, d);
10923 if (FAILED(rc))
10924 {
10925 ErrorInfoKeeper eik;
10926 pConsole->i_atVMRuntimeErrorCallbackF(0, "BrokenSharedFolder",
10927 N_("The shared folder '%s' could not be set up: %ls.\n"
10928 "The shared folder setup will not be complete. It is recommended to power down the virtual "
10929 "machine and fix the shared folder settings while the machine is not running"),
10930 it->first.c_str(), eik.getText().raw());
10931 }
10932 }
10933 if (FAILED(rc))
10934 rc = S_OK; // do not fail with broken shared folders
10935
10936 /* acquire the lock again */
10937 alock.acquire();
10938 }
10939
10940#ifdef VBOX_WITH_AUDIO_VRDE
10941 /*
10942 * Attach the VRDE audio driver.
10943 */
10944 if (pConsole->i_getVRDEServer())
10945 {
10946 BOOL fVRDEEnabled = FALSE;
10947 rc = pConsole->i_getVRDEServer()->COMGETTER(Enabled)(&fVRDEEnabled);
10948 AssertComRCBreak(rc, RT_NOTHING);
10949
10950 if ( fVRDEEnabled
10951 && pConsole->mAudioVRDE)
10952 pConsole->mAudioVRDE->doAttachDriverViaEmt(pConsole->mpUVM, pVMM, &alock);
10953 }
10954#endif
10955
10956 /*
10957 * Enable client connections to the VRDP server.
10958 */
10959 pConsole->i_consoleVRDPServer()->EnableConnections();
10960
10961#ifdef VBOX_WITH_RECORDING
10962 /*
10963 * Enable recording if configured.
10964 */
10965 BOOL fRecordingEnabled = FALSE;
10966 {
10967 ComPtr<IRecordingSettings> ptrRecordingSettings;
10968 rc = pConsole->mMachine->COMGETTER(RecordingSettings)(ptrRecordingSettings.asOutParam());
10969 AssertComRCBreak(rc, RT_NOTHING);
10970
10971 rc = ptrRecordingSettings->COMGETTER(Enabled)(&fRecordingEnabled);
10972 AssertComRCBreak(rc, RT_NOTHING);
10973 }
10974 if (fRecordingEnabled)
10975 {
10976 vrc = pConsole->i_recordingEnable(fRecordingEnabled, &alock);
10977 if (RT_SUCCESS(vrc))
10978 ::FireRecordingChangedEvent(pConsole->mEventSource);
10979 else
10980 {
10981 LogRel(("Recording: Failed with %Rrc on VM power up\n", vrc));
10982 vrc = VINF_SUCCESS; /* do not fail with broken recording */
10983 }
10984 }
10985#endif
10986
10987 /* release the lock before a lengthy operation */
10988 alock.release();
10989
10990 /*
10991 * Capture USB devices.
10992 */
10993 rc = pConsole->i_captureUSBDevices(pConsole->mpUVM);
10994 if (FAILED(rc))
10995 {
10996 alock.acquire();
10997 break;
10998 }
10999
11000 /*
11001 * Load saved state?
11002 */
11003 if (pTask->mSavedStateFile.length())
11004 {
11005 LogFlowFunc(("Restoring saved state from '%s'...\n", pTask->mSavedStateFile.c_str()));
11006
11007#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
11008 SsmStream ssmStream(pConsole, pVMM, pTask->m_pKeyStore, pTask->mKeyId, pTask->mKeyStore);
11009
11010 vrc = ssmStream.open(pTask->mSavedStateFile.c_str());
11011 if (RT_SUCCESS(vrc))
11012 {
11013 PCSSMSTRMOPS pStreamOps;
11014 void *pvStreamOpsUser;
11015
11016 vrc = ssmStream.querySsmStrmOps(&pStreamOps, &pvStreamOpsUser);
11017 if (RT_SUCCESS(vrc))
11018 vrc = pVMM->pfnVMR3LoadFromStream(pConsole->mpUVM,
11019 pStreamOps, pvStreamOpsUser,
11020 Console::i_stateProgressCallback,
11021 static_cast<IProgress *>(pTask->mProgress));
11022 }
11023#else
11024 vrc = pVMM->pfnVMR3LoadFromFile(pConsole->mpUVM,
11025 pTask->mSavedStateFile.c_str(),
11026 Console::i_stateProgressCallback,
11027 static_cast<IProgress *>(pTask->mProgress));
11028#endif
11029 if (RT_SUCCESS(vrc))
11030 {
11031 if (pTask->mStartPaused)
11032 /* done */
11033 pConsole->i_setMachineState(MachineState_Paused);
11034 else
11035 {
11036 /* Start/Resume the VM execution */
11037#ifdef VBOX_WITH_EXTPACK
11038 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM, pVMM);
11039#endif
11040 if (RT_SUCCESS(vrc))
11041 vrc = pVMM->pfnVMR3Resume(pConsole->mpUVM, VMRESUMEREASON_STATE_RESTORED);
11042 AssertLogRelRC(vrc);
11043 }
11044 }
11045
11046 /* Power off in case we failed loading or resuming the VM */
11047 if (RT_FAILURE(vrc))
11048 {
11049 int vrc2 = pVMM->pfnVMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
11050#ifdef VBOX_WITH_EXTPACK
11051 pConsole->mptrExtPackManager->i_callAllVmPowerOffHooks(pConsole, pVM, pVMM);
11052#endif
11053 }
11054 }
11055 else if (pTask->mTeleporterEnabled)
11056 {
11057 /* -> ConsoleImplTeleporter.cpp */
11058 bool fPowerOffOnFailure;
11059 rc = pConsole->i_teleporterTrg(pConsole->mpUVM, pConsole->mpVMM, pMachine, &pTask->mErrorMsg,
11060 pTask->mStartPaused, pTask->mProgress, &fPowerOffOnFailure);
11061 if (FAILED(rc) && fPowerOffOnFailure)
11062 {
11063 ErrorInfoKeeper eik;
11064 int vrc2 = pVMM->pfnVMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
11065#ifdef VBOX_WITH_EXTPACK
11066 pConsole->mptrExtPackManager->i_callAllVmPowerOffHooks(pConsole, pVM, pVMM);
11067#endif
11068 }
11069 }
11070 else if (pTask->mStartPaused)
11071 /* done */
11072 pConsole->i_setMachineState(MachineState_Paused);
11073 else
11074 {
11075 /* Power on the VM (i.e. start executing) */
11076#ifdef VBOX_WITH_EXTPACK
11077 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM, pVMM);
11078#endif
11079 if (RT_SUCCESS(vrc))
11080 vrc = pVMM->pfnVMR3PowerOn(pConsole->mpUVM);
11081 AssertLogRelRC(vrc);
11082 }
11083
11084 /* acquire the lock again */
11085 alock.acquire();
11086 }
11087 while (0);
11088
11089 /* On failure, destroy the VM */
11090 if (FAILED(rc) || RT_FAILURE(vrc))
11091 {
11092 /* preserve existing error info */
11093 ErrorInfoKeeper eik;
11094
11095 /* powerDown() will call VMR3Destroy() and do all necessary
11096 * cleanup (VRDP, USB devices) */
11097 alock.release();
11098 HRESULT rc2 = pConsole->i_powerDown();
11099 alock.acquire();
11100 AssertComRC(rc2);
11101 }
11102 else
11103 {
11104 /*
11105 * Deregister the VMSetError callback. This is necessary as the
11106 * pfnVMAtError() function passed to VMR3Create() is supposed to
11107 * be sticky but our error callback isn't.
11108 */
11109 alock.release();
11110 pVMM->pfnVMR3AtErrorDeregister(pConsole->mpUVM, Console::i_genericVMSetErrorCallback, &pTask->mErrorMsg);
11111 /** @todo register another VMSetError callback? */
11112 alock.acquire();
11113 }
11114 }
11115 else
11116 {
11117 /*
11118 * If VMR3Create() failed it has released the VM memory.
11119 */
11120 if (pConsole->m_pVMMDev)
11121 {
11122 alock.release(); /* just to be on the safe side... */
11123 pConsole->m_pVMMDev->hgcmShutdown(true /*fUvmIsInvalid*/);
11124 alock.acquire();
11125 }
11126 pVMM->pfnVMR3ReleaseUVM(pConsole->mpUVM);
11127 pConsole->mpUVM = NULL;
11128 }
11129
11130 if (SUCCEEDED(rc) && RT_FAILURE(vrc))
11131 {
11132 /* If VMR3Create() or one of the other calls in this function fail,
11133 * an appropriate error message has been set in pTask->mErrorMsg.
11134 * However since that happens via a callback, the rc status code in
11135 * this function is not updated.
11136 */
11137 if (!pTask->mErrorMsg.length())
11138 {
11139 /* If the error message is not set but we've got a failure,
11140 * convert the VBox status code into a meaningful error message.
11141 * This becomes unused once all the sources of errors set the
11142 * appropriate error message themselves.
11143 */
11144 AssertMsgFailed(("Missing error message during powerup for status code %Rrc\n", vrc));
11145 pTask->mErrorMsg = Utf8StrFmt(tr("Failed to start VM execution (%Rrc)"), vrc);
11146 }
11147
11148 /* Set the error message as the COM error.
11149 * Progress::notifyComplete() will pick it up later. */
11150 throw i_setErrorStaticBoth(E_FAIL, vrc, pTask->mErrorMsg.c_str());
11151 }
11152 }
11153 catch (HRESULT aRC) { rc = aRC; }
11154
11155 if ( pConsole->mMachineState == MachineState_Starting
11156 || pConsole->mMachineState == MachineState_Restoring
11157 || pConsole->mMachineState == MachineState_TeleportingIn
11158 )
11159 {
11160 /* We are still in the Starting/Restoring state. This means one of:
11161 *
11162 * 1) we failed before VMR3Create() was called;
11163 * 2) VMR3Create() failed.
11164 *
11165 * In both cases, there is no need to call powerDown(), but we still
11166 * need to go back to the PoweredOff/Saved state. Reuse
11167 * vmstateChangeCallback() for that purpose.
11168 */
11169
11170 /* preserve existing error info */
11171 ErrorInfoKeeper eik;
11172
11173 Assert(pConsole->mpUVM == NULL);
11174 i_vmstateChangeCallback(NULL, pConsole->mpVMM, VMSTATE_TERMINATED, VMSTATE_CREATING, pConsole);
11175 }
11176
11177 /*
11178 * Evaluate the final result. Note that the appropriate mMachineState value
11179 * is already set by vmstateChangeCallback() in all cases.
11180 */
11181
11182 /* release the lock, don't need it any more */
11183 alock.release();
11184
11185 if (SUCCEEDED(rc))
11186 {
11187 /* Notify the progress object of the success */
11188 pTask->mProgress->i_notifyComplete(S_OK);
11189 }
11190 else
11191 {
11192 /* The progress object will fetch the current error info */
11193 pTask->mProgress->i_notifyComplete(rc);
11194 LogRel(("Power up failed (vrc=%Rrc, rc=%Rhrc (%#08X))\n", vrc, rc, rc));
11195 }
11196
11197 /* Notify VBoxSVC and any waiting openRemoteSession progress object. */
11198 pConsole->mControl->EndPowerUp(rc);
11199
11200#if defined(RT_OS_WINDOWS)
11201 /* uninitialize COM */
11202 CoUninitialize();
11203#endif
11204
11205 LogFlowFuncLeave();
11206}
11207
11208
11209/**
11210 * Reconfigures a medium attachment (part of taking or deleting an online snapshot).
11211 *
11212 * @param pThis Reference to the console object.
11213 * @param pUVM The VM handle.
11214 * @param pVMM The VMM vtable.
11215 * @param pcszDevice The name of the controller type.
11216 * @param uInstance The instance of the controller.
11217 * @param enmBus The storage bus type of the controller.
11218 * @param fUseHostIOCache Use the host I/O cache (disable async I/O).
11219 * @param fBuiltinIOCache Use the builtin I/O cache.
11220 * @param fInsertDiskIntegrityDrv Flag whether to insert the disk integrity driver into the chain
11221 * for additionalk debugging aids.
11222 * @param fSetupMerge Whether to set up a medium merge
11223 * @param uMergeSource Merge source image index
11224 * @param uMergeTarget Merge target image index
11225 * @param aMediumAtt The medium attachment.
11226 * @param aMachineState The current machine state.
11227 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
11228 * @return VBox status code.
11229 */
11230/* static */
11231DECLCALLBACK(int) Console::i_reconfigureMediumAttachment(Console *pThis,
11232 PUVM pUVM,
11233 PCVMMR3VTABLE pVMM,
11234 const char *pcszDevice,
11235 unsigned uInstance,
11236 StorageBus_T enmBus,
11237 bool fUseHostIOCache,
11238 bool fBuiltinIOCache,
11239 bool fInsertDiskIntegrityDrv,
11240 bool fSetupMerge,
11241 unsigned uMergeSource,
11242 unsigned uMergeTarget,
11243 IMediumAttachment *aMediumAtt,
11244 MachineState_T aMachineState,
11245 HRESULT *phrc)
11246{
11247 LogFlowFunc(("pUVM=%p aMediumAtt=%p phrc=%p\n", pUVM, aMediumAtt, phrc));
11248
11249 HRESULT hrc;
11250 Bstr bstr;
11251 *phrc = S_OK;
11252#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%Rhrc (%#x)\n", hrc, hrc)); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
11253
11254 /* Ignore attachments other than hard disks, since at the moment they are
11255 * not subject to snapshotting in general. */
11256 DeviceType_T lType;
11257 hrc = aMediumAtt->COMGETTER(Type)(&lType); H();
11258 if (lType != DeviceType_HardDisk)
11259 return VINF_SUCCESS;
11260
11261 /* Update the device instance configuration. */
11262 int rc = pThis->i_configMediumAttachment(pcszDevice,
11263 uInstance,
11264 enmBus,
11265 fUseHostIOCache,
11266 fBuiltinIOCache,
11267 fInsertDiskIntegrityDrv,
11268 fSetupMerge,
11269 uMergeSource,
11270 uMergeTarget,
11271 aMediumAtt,
11272 aMachineState,
11273 phrc,
11274 true /* fAttachDetach */,
11275 false /* fForceUnmount */,
11276 false /* fHotplug */,
11277 pUVM,
11278 pVMM,
11279 NULL /* paLedDevType */,
11280 NULL /* ppLunL0)*/);
11281 if (RT_FAILURE(rc))
11282 {
11283 AssertMsgFailed(("rc=%Rrc\n", rc));
11284 return rc;
11285 }
11286
11287#undef H
11288
11289 LogFlowFunc(("Returns success\n"));
11290 return VINF_SUCCESS;
11291}
11292
11293/**
11294 * Thread for powering down the Console.
11295 *
11296 * @param pTask The power down task.
11297 *
11298 * @note Locks the Console object for writing.
11299 */
11300/*static*/
11301void Console::i_powerDownThreadTask(VMPowerDownTask *pTask)
11302{
11303 int rc = VINF_SUCCESS; /* only used in assertion */
11304 LogFlowFuncEnter();
11305 try
11306 {
11307 if (pTask->isOk() == false)
11308 rc = VERR_GENERAL_FAILURE;
11309
11310 const ComObjPtr<Console> &that = pTask->mConsole;
11311
11312 /* Note: no need to use AutoCaller to protect Console because VMTask does
11313 * that */
11314
11315 /* wait until the method tat started us returns */
11316 AutoWriteLock thatLock(that COMMA_LOCKVAL_SRC_POS);
11317
11318 /* release VM caller to avoid the powerDown() deadlock */
11319 pTask->releaseVMCaller();
11320
11321 thatLock.release();
11322
11323 that->i_powerDown(pTask->mServerProgress);
11324
11325 /* complete the operation */
11326 that->mControl->EndPoweringDown(S_OK, Bstr().raw());
11327
11328 }
11329 catch (const std::exception &e)
11330 {
11331 AssertMsgFailed(("Exception %s was caught, rc=%Rrc\n", e.what(), rc));
11332 NOREF(e); NOREF(rc);
11333 }
11334
11335 LogFlowFuncLeave();
11336}
11337
11338/**
11339 * @interface_method_impl{VMM2USERMETHODS,pfnSaveState}
11340 */
11341/*static*/ DECLCALLBACK(int)
11342Console::i_vmm2User_SaveState(PCVMM2USERMETHODS pThis, PUVM pUVM)
11343{
11344 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
11345 NOREF(pUVM);
11346
11347 /*
11348 * For now, just call SaveState. We should probably try notify the GUI so
11349 * it can pop up a progress object and stuff. The progress object created
11350 * by the call isn't returned to anyone and thus gets updated without
11351 * anyone noticing it.
11352 */
11353 ComPtr<IProgress> pProgress;
11354 HRESULT hrc = pConsole->mMachine->SaveState(pProgress.asOutParam());
11355 return SUCCEEDED(hrc) ? VINF_SUCCESS : Global::vboxStatusCodeFromCOM(hrc);
11356}
11357
11358/**
11359 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtInit}
11360 */
11361/*static*/ DECLCALLBACK(void)
11362Console::i_vmm2User_NotifyEmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
11363{
11364 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
11365 VirtualBoxBase::initializeComForThread();
11366}
11367
11368/**
11369 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtTerm}
11370 */
11371/*static*/ DECLCALLBACK(void)
11372Console::i_vmm2User_NotifyEmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
11373{
11374 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
11375 VirtualBoxBase::uninitializeComForThread();
11376}
11377
11378/**
11379 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtInit}
11380 */
11381/*static*/ DECLCALLBACK(void)
11382Console::i_vmm2User_NotifyPdmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM)
11383{
11384 NOREF(pThis); NOREF(pUVM);
11385 VirtualBoxBase::initializeComForThread();
11386}
11387
11388/**
11389 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtTerm}
11390 */
11391/*static*/ DECLCALLBACK(void)
11392Console::i_vmm2User_NotifyPdmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM)
11393{
11394 NOREF(pThis); NOREF(pUVM);
11395 VirtualBoxBase::uninitializeComForThread();
11396}
11397
11398/**
11399 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyResetTurnedIntoPowerOff}
11400 */
11401/*static*/ DECLCALLBACK(void)
11402Console::i_vmm2User_NotifyResetTurnedIntoPowerOff(PCVMM2USERMETHODS pThis, PUVM pUVM)
11403{
11404 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
11405 NOREF(pUVM);
11406
11407 pConsole->mfPowerOffCausedByReset = true;
11408}
11409
11410/**
11411 * Internal function to get LED set off of Console instance
11412 *
11413 * @returns pointer to PDMLED object
11414 *
11415 * @param iLedSet Index of LED set to fetch
11416 */
11417PPDMLED *
11418Console::i_getLedSet(uint32_t iLedSet)
11419{
11420 AssertReturn(iLedSet < RT_ELEMENTS(maLedSets), NULL);
11421 return maLedSets[iLedSet].papLeds;
11422}
11423
11424/**
11425 * @interface_method_impl{VMM2USERMETHODS,pfnQueryGenericObject}
11426 */
11427/*static*/ DECLCALLBACK(void *)
11428Console::i_vmm2User_QueryGenericObject(PCVMM2USERMETHODS pThis, PUVM pUVM, PCRTUUID pUuid)
11429{
11430 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
11431 NOREF(pUVM);
11432
11433 /* To simplify comparison we copy the UUID into a com::Guid object. */
11434 com::Guid const UuidCopy(*pUuid);
11435
11436 if (UuidCopy == COM_IIDOF(IConsole))
11437 {
11438 IConsole *pIConsole = static_cast<IConsole *>(pConsole);
11439 return pIConsole;
11440 }
11441
11442 if (UuidCopy == COM_IIDOF(IMachine))
11443 {
11444 IMachine *pIMachine = pConsole->mMachine;
11445 return pIMachine;
11446 }
11447
11448 if (UuidCopy == COM_IIDOF(IKeyboard))
11449 {
11450 IKeyboard *pIKeyboard = pConsole->mKeyboard;
11451 return pIKeyboard;
11452 }
11453
11454 if (UuidCopy == COM_IIDOF(IMouse))
11455 {
11456 IMouse *pIMouse = pConsole->mMouse;
11457 return pIMouse;
11458 }
11459
11460 if (UuidCopy == COM_IIDOF(IDisplay))
11461 {
11462 IDisplay *pIDisplay = pConsole->mDisplay;
11463 return pIDisplay;
11464 }
11465
11466 if (UuidCopy == COM_IIDOF(INvramStore))
11467 {
11468 NvramStore *pNvramStore = static_cast<NvramStore *>(pConsole->mptrNvramStore);
11469 return pNvramStore;
11470 }
11471
11472 if (UuidCopy == VMMDEV_OID)
11473 return pConsole->m_pVMMDev;
11474
11475 if (UuidCopy == USBCARDREADER_OID)
11476 return pConsole->mUsbCardReader;
11477
11478 if (UuidCopy == COM_IIDOF(ISnapshot))
11479 return ((MYVMM2USERMETHODS *)pThis)->pISnapshot;
11480
11481 if (UuidCopy == REMOTEUSBIF_OID)
11482 return &pConsole->mRemoteUsbIf;
11483
11484 if (UuidCopy == EMULATEDUSBIF_OID)
11485 return pConsole->mEmulatedUSB->i_getEmulatedUsbIf();
11486
11487 return NULL;
11488}
11489
11490
11491/**
11492 * @interface_method_impl{PDMISECKEY,pfnKeyRetain}
11493 */
11494/*static*/ DECLCALLBACK(int)
11495Console::i_pdmIfSecKey_KeyRetain(PPDMISECKEY pInterface, const char *pszId, const uint8_t **ppbKey, size_t *pcbKey)
11496{
11497 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
11498
11499 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
11500 SecretKey *pKey = NULL;
11501
11502 int rc = pConsole->m_pKeyStore->retainSecretKey(Utf8Str(pszId), &pKey);
11503 if (RT_SUCCESS(rc))
11504 {
11505 *ppbKey = (const uint8_t *)pKey->getKeyBuffer();
11506 *pcbKey = pKey->getKeySize();
11507 }
11508
11509 return rc;
11510}
11511
11512/**
11513 * @interface_method_impl{PDMISECKEY,pfnKeyRelease}
11514 */
11515/*static*/ DECLCALLBACK(int)
11516Console::i_pdmIfSecKey_KeyRelease(PPDMISECKEY pInterface, const char *pszId)
11517{
11518 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
11519
11520 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
11521 return pConsole->m_pKeyStore->releaseSecretKey(Utf8Str(pszId));
11522}
11523
11524/**
11525 * @interface_method_impl{PDMISECKEY,pfnPasswordRetain}
11526 */
11527/*static*/ DECLCALLBACK(int)
11528Console::i_pdmIfSecKey_PasswordRetain(PPDMISECKEY pInterface, const char *pszId, const char **ppszPassword)
11529{
11530 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
11531
11532 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
11533 SecretKey *pKey = NULL;
11534
11535 int rc = pConsole->m_pKeyStore->retainSecretKey(Utf8Str(pszId), &pKey);
11536 if (RT_SUCCESS(rc))
11537 *ppszPassword = (const char *)pKey->getKeyBuffer();
11538
11539 return rc;
11540}
11541
11542/**
11543 * @interface_method_impl{PDMISECKEY,pfnPasswordRelease}
11544 */
11545/*static*/ DECLCALLBACK(int)
11546Console::i_pdmIfSecKey_PasswordRelease(PPDMISECKEY pInterface, const char *pszId)
11547{
11548 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
11549
11550 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
11551 return pConsole->m_pKeyStore->releaseSecretKey(Utf8Str(pszId));
11552}
11553
11554/**
11555 * @interface_method_impl{PDMISECKEYHLP,pfnKeyMissingNotify}
11556 */
11557/*static*/ DECLCALLBACK(int)
11558Console::i_pdmIfSecKeyHlp_KeyMissingNotify(PPDMISECKEYHLP pInterface)
11559{
11560 Console *pConsole = ((MYPDMISECKEYHLP *)pInterface)->pConsole;
11561
11562 /* Set guest property only, the VM is paused in the media driver calling us. */
11563 pConsole->mMachine->DeleteGuestProperty(Bstr("/VirtualBox/HostInfo/DekMissing").raw());
11564 pConsole->mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/DekMissing").raw(),
11565 Bstr("1").raw(), Bstr("RDONLYGUEST").raw());
11566 pConsole->mMachine->SaveSettings();
11567
11568 return VINF_SUCCESS;
11569}
11570
11571
11572
11573/**
11574 * The Main status driver instance data.
11575 */
11576typedef struct DRVMAINSTATUS
11577{
11578 /** The LED connectors. */
11579 PDMILEDCONNECTORS ILedConnectors;
11580 /** Pointer to the LED ports interface above us. */
11581 PPDMILEDPORTS pLedPorts;
11582 /** Pointer to the array of LED pointers. */
11583 PPDMLED *papLeds;
11584 /** The unit number corresponding to the first entry in the LED array. */
11585 uint32_t iFirstLUN;
11586 /** The unit number corresponding to the last entry in the LED array.
11587 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
11588 uint32_t iLastLUN;
11589 /** Pointer to the driver instance. */
11590 PPDMDRVINS pDrvIns;
11591 /** The Media Notify interface. */
11592 PDMIMEDIANOTIFY IMediaNotify;
11593 /** Set if there potentially are medium attachments. */
11594 bool fHasMediumAttachments;
11595 /** Device name+instance for mapping */
11596 char *pszDeviceInstance;
11597 /** Pointer to the Console object, for driver triggered activities. */
11598 Console *pConsole;
11599} DRVMAINSTATUS, *PDRVMAINSTATUS;
11600
11601
11602/**
11603 * Notification about a unit which have been changed.
11604 *
11605 * The driver must discard any pointers to data owned by
11606 * the unit and requery it.
11607 *
11608 * @param pInterface Pointer to the interface structure containing the called function pointer.
11609 * @param iLUN The unit number.
11610 */
11611DECLCALLBACK(void) Console::i_drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
11612{
11613 PDRVMAINSTATUS pThis = RT_FROM_MEMBER(pInterface, DRVMAINSTATUS, ILedConnectors);
11614 if (iLUN >= pThis->iFirstLUN && iLUN <= pThis->iLastLUN)
11615 {
11616 PPDMLED pLed;
11617 int rc = pThis->pLedPorts->pfnQueryStatusLed(pThis->pLedPorts, iLUN, &pLed);
11618 /*
11619 * pLed now points directly to the per-unit struct PDMLED field
11620 * inside the target device struct owned by the hardware driver.
11621 */
11622 if (RT_FAILURE(rc))
11623 pLed = NULL;
11624 ASMAtomicWritePtr(&pThis->papLeds[iLUN - pThis->iFirstLUN], pLed);
11625 /*
11626 * papLeds[] points to the struct PDMLED of each of this driver's
11627 * units. The entries are initialized here, called out of a loop
11628 * in Console::i_drvStatus_Construct(), which previously called
11629 * Console::i_attachStatusDriver() to allocate the array itself.
11630 *
11631 * The arrays (and thus individual LEDs) are eventually read out
11632 * by Console::getDeviceActivity(), which is itself called from
11633 * src/VBox/Frontends/VirtualBox/src/runtime/UIIndicatorsPool.cpp
11634 */
11635 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
11636 }
11637}
11638
11639
11640/**
11641 * Notification about a medium eject.
11642 *
11643 * @returns VBox status code.
11644 * @param pInterface Pointer to the interface structure containing the called function pointer.
11645 * @param uLUN The unit number.
11646 */
11647DECLCALLBACK(int) Console::i_drvStatus_MediumEjected(PPDMIMEDIANOTIFY pInterface, unsigned uLUN)
11648{
11649 PDRVMAINSTATUS pThis = RT_FROM_MEMBER(pInterface, DRVMAINSTATUS, IMediaNotify);
11650 LogFunc(("uLUN=%d\n", uLUN));
11651 if (pThis->fHasMediumAttachments)
11652 {
11653 Console * const pConsole = pThis->pConsole;
11654 AutoWriteLock alock(pConsole COMMA_LOCKVAL_SRC_POS);
11655
11656 ComPtr<IMediumAttachment> pMediumAtt;
11657 Utf8Str devicePath = Utf8StrFmt("%s/LUN#%u", pThis->pszDeviceInstance, uLUN);
11658 Console::MediumAttachmentMap::const_iterator end = pConsole->mapMediumAttachments.end();
11659 Console::MediumAttachmentMap::const_iterator it = pConsole->mapMediumAttachments.find(devicePath);
11660 if (it != end)
11661 pMediumAtt = it->second;
11662 Assert(!pMediumAtt.isNull());
11663 if (!pMediumAtt.isNull())
11664 {
11665 IMedium *pMedium = NULL;
11666 HRESULT rc = pMediumAtt->COMGETTER(Medium)(&pMedium);
11667 AssertComRC(rc);
11668 if (SUCCEEDED(rc) && pMedium)
11669 {
11670 BOOL fHostDrive = FALSE;
11671 rc = pMedium->COMGETTER(HostDrive)(&fHostDrive);
11672 AssertComRC(rc);
11673 if (!fHostDrive)
11674 {
11675 alock.release();
11676
11677 ComPtr<IMediumAttachment> pNewMediumAtt;
11678 rc = pThis->pConsole->mControl->EjectMedium(pMediumAtt, pNewMediumAtt.asOutParam());
11679 if (SUCCEEDED(rc))
11680 {
11681 pThis->pConsole->mMachine->SaveSettings();
11682 ::FireMediumChangedEvent(pThis->pConsole->mEventSource, pNewMediumAtt);
11683 }
11684
11685 alock.acquire();
11686 if (pNewMediumAtt != pMediumAtt)
11687 {
11688 pConsole->mapMediumAttachments.erase(devicePath);
11689 pConsole->mapMediumAttachments.insert(std::make_pair(devicePath, pNewMediumAtt));
11690 }
11691 }
11692 }
11693 }
11694 }
11695 return VINF_SUCCESS;
11696}
11697
11698
11699/**
11700 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
11701 */
11702DECLCALLBACK(void *) Console::i_drvStatus_QueryInterface(PPDMIBASE pInterface, const char *pszIID)
11703{
11704 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
11705 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
11706 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
11707 PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDCONNECTORS, &pThis->ILedConnectors);
11708 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIANOTIFY, &pThis->IMediaNotify);
11709 return NULL;
11710}
11711
11712
11713/**
11714 * Destruct a status driver instance.
11715 *
11716 * @returns VBox status code.
11717 * @param pDrvIns The driver instance data.
11718 */
11719DECLCALLBACK(void) Console::i_drvStatus_Destruct(PPDMDRVINS pDrvIns)
11720{
11721 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
11722 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
11723 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
11724
11725 if (pThis->papLeds)
11726 {
11727 unsigned iLed = pThis->iLastLUN - pThis->iFirstLUN + 1;
11728 while (iLed-- > 0)
11729 ASMAtomicWriteNullPtr(&pThis->papLeds[iLed]);
11730 }
11731}
11732
11733
11734/**
11735 * Construct a status driver instance.
11736 *
11737 * @copydoc FNPDMDRVCONSTRUCT
11738 */
11739DECLCALLBACK(int) Console::i_drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
11740{
11741 RT_NOREF(fFlags);
11742 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
11743 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
11744 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
11745
11746 /*
11747 * Initialize data.
11748 */
11749 com::Guid ConsoleUuid(COM_IIDOF(IConsole));
11750 IConsole *pIConsole = (IConsole *)PDMDrvHlpQueryGenericUserObject(pDrvIns, ConsoleUuid.raw());
11751 AssertLogRelReturn(pIConsole, VERR_INTERNAL_ERROR_3);
11752 Console *pConsole = static_cast<Console *>(pIConsole);
11753 AssertLogRelReturn(pConsole, VERR_INTERNAL_ERROR_3);
11754
11755 pDrvIns->IBase.pfnQueryInterface = Console::i_drvStatus_QueryInterface;
11756 pThis->ILedConnectors.pfnUnitChanged = Console::i_drvStatus_UnitChanged;
11757 pThis->IMediaNotify.pfnEjected = Console::i_drvStatus_MediumEjected;
11758 pThis->pDrvIns = pDrvIns;
11759 pThis->pConsole = pConsole;
11760 pThis->fHasMediumAttachments = false;
11761 pThis->papLeds = NULL;
11762 pThis->pszDeviceInstance = NULL;
11763
11764 /*
11765 * Validate configuration.
11766 */
11767 PDMDRV_VALIDATE_CONFIG_RETURN(pDrvIns,
11768 "DeviceInstance|"
11769 "iLedSet|"
11770 "HasMediumAttachments|"
11771 "First|"
11772 "Last",
11773 "");
11774 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
11775 ("Configuration error: Not possible to attach anything to this driver!\n"),
11776 VERR_PDM_DRVINS_NO_ATTACH);
11777
11778 /*
11779 * Read config.
11780 */
11781 PCPDMDRVHLPR3 const pHlp = pDrvIns->pHlpR3;
11782
11783 uint32_t iLedSet;
11784 int rc = pHlp->pfnCFGMQueryU32(pCfg, "iLedSet", &iLedSet);
11785 AssertLogRelMsgRCReturn(rc, ("Configuration error: Failed to query the \"iLedSet\" value! rc=%Rrc\n", rc), rc);
11786 pThis->papLeds = pConsole->i_getLedSet(iLedSet);
11787
11788 rc = pHlp->pfnCFGMQueryBoolDef(pCfg, "HasMediumAttachments", &pThis->fHasMediumAttachments, false);
11789 AssertLogRelMsgRCReturn(rc, ("Configuration error: Failed to query the \"HasMediumAttachments\" value! rc=%Rrc\n", rc), rc);
11790
11791 if (pThis->fHasMediumAttachments)
11792 {
11793 rc = pHlp->pfnCFGMQueryStringAlloc(pCfg, "DeviceInstance", &pThis->pszDeviceInstance);
11794 AssertLogRelMsgRCReturn(rc, ("Configuration error: Failed to query the \"DeviceInstance\" value! rc=%Rrc\n", rc), rc);
11795 }
11796
11797 rc = pHlp->pfnCFGMQueryU32Def(pCfg, "First", &pThis->iFirstLUN, 0);
11798 AssertLogRelMsgRCReturn(rc, ("Configuration error: Failed to query the \"First\" value! rc=%Rrc\n", rc), rc);
11799
11800 rc = pHlp->pfnCFGMQueryU32Def(pCfg, "Last", &pThis->iLastLUN, 0);
11801 AssertLogRelMsgRCReturn(rc, ("Configuration error: Failed to query the \"Last\" value! rc=%Rrc\n", rc), rc);
11802
11803 AssertLogRelMsgReturn(pThis->iFirstLUN <= pThis->iLastLUN,
11804 ("Configuration error: Invalid unit range %u-%u\n", pThis->iFirstLUN, pThis->iLastLUN),
11805 VERR_INVALID_PARAMETER);
11806
11807 /*
11808 * Get the ILedPorts interface of the above driver/device and
11809 * query the LEDs we want.
11810 */
11811 pThis->pLedPorts = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMILEDPORTS);
11812 AssertMsgReturn(pThis->pLedPorts, ("Configuration error: No led ports interface above!\n"),
11813 VERR_PDM_MISSING_INTERFACE_ABOVE);
11814
11815 for (unsigned i = pThis->iFirstLUN; i <= pThis->iLastLUN; ++i)
11816 Console::i_drvStatus_UnitChanged(&pThis->ILedConnectors, i);
11817
11818 return VINF_SUCCESS;
11819}
11820
11821
11822/**
11823 * Console status driver (LED) registration record.
11824 */
11825const PDMDRVREG Console::DrvStatusReg =
11826{
11827 /* u32Version */
11828 PDM_DRVREG_VERSION,
11829 /* szName */
11830 "MainStatus",
11831 /* szRCMod */
11832 "",
11833 /* szR0Mod */
11834 "",
11835 /* pszDescription */
11836 "Main status driver (Main as in the API).",
11837 /* fFlags */
11838 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
11839 /* fClass. */
11840 PDM_DRVREG_CLASS_STATUS,
11841 /* cMaxInstances */
11842 ~0U,
11843 /* cbInstance */
11844 sizeof(DRVMAINSTATUS),
11845 /* pfnConstruct */
11846 Console::i_drvStatus_Construct,
11847 /* pfnDestruct */
11848 Console::i_drvStatus_Destruct,
11849 /* pfnRelocate */
11850 NULL,
11851 /* pfnIOCtl */
11852 NULL,
11853 /* pfnPowerOn */
11854 NULL,
11855 /* pfnReset */
11856 NULL,
11857 /* pfnSuspend */
11858 NULL,
11859 /* pfnResume */
11860 NULL,
11861 /* pfnAttach */
11862 NULL,
11863 /* pfnDetach */
11864 NULL,
11865 /* pfnPowerOff */
11866 NULL,
11867 /* pfnSoftReset */
11868 NULL,
11869 /* u32EndVersion */
11870 PDM_DRVREG_VERSION
11871};
11872
11873
11874
11875/* vi: set tabstop=4 shiftwidth=4 expandtab: */
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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