VirtualBox

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

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

Recording/Main: Renaming (IPRT status code -> VBox status code). bugref:10275

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

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