VirtualBox

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

Last change on this file since 96172 was 96172, checked in by vboxsync, 2 years ago

Recording/Main: Changed IRecordingScreenSettings::features attribute to get/set a safe array of RecordingFeature entries instead of an anonymous ULONG. Makes it much easier to use. bugref:10275

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 401.7 KB
Line 
1/* $Id: ConsoleImpl.cpp 96172 2022-08-12 13:27:46Z 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 for (size_t f = 0; f < vecFeatures.size(); ++f)
7296 {
7297 if (vecFeatures[f] == RecordingFeature_Audio)
7298 recScreenSettings.featureMap[RecordingFeature_Audio] = true;
7299 else if (vecFeatures[f] == RecordingFeature_Video)
7300 recScreenSettings.featureMap[RecordingFeature_Video] = true;
7301 }
7302 hrc = pRecScreenSettings->COMGETTER(MaxTime)((ULONG *)&recScreenSettings.ulMaxTimeS);
7303 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7304 hrc = pRecScreenSettings->COMGETTER(MaxFileSize)((ULONG *)&recScreenSettings.File.ulMaxSizeMB);
7305 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7306 Bstr bstrTemp;
7307 hrc = pRecScreenSettings->COMGETTER(Filename)(bstrTemp.asOutParam());
7308 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7309 recScreenSettings.File.strName = bstrTemp;
7310 hrc = pRecScreenSettings->COMGETTER(Options)(bstrTemp.asOutParam());
7311 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7312 recScreenSettings.strOptions = bstrTemp;
7313 hrc = pRecScreenSettings->COMGETTER(AudioCodec)(&recScreenSettings.Audio.enmCodec);
7314 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7315 hrc = pRecScreenSettings->COMGETTER(AudioDeadline)(&recScreenSettings.Audio.enmDeadline);
7316 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7317 hrc = pRecScreenSettings->COMGETTER(AudioRateControlMode)(&recScreenSettings.Audio.enmRateCtlMode);
7318 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7319 hrc = pRecScreenSettings->COMGETTER(AudioHz)((ULONG *)&recScreenSettings.Audio.uHz);
7320 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7321 hrc = pRecScreenSettings->COMGETTER(AudioBits)((ULONG *)&recScreenSettings.Audio.cBits);
7322 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7323 hrc = pRecScreenSettings->COMGETTER(AudioChannels)((ULONG *)&recScreenSettings.Audio.cChannels);
7324 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7325 hrc = pRecScreenSettings->COMGETTER(VideoCodec)(&recScreenSettings.Video.enmCodec);
7326 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7327 hrc = pRecScreenSettings->COMGETTER(VideoWidth)((ULONG *)&recScreenSettings.Video.ulWidth);
7328 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7329 hrc = pRecScreenSettings->COMGETTER(VideoHeight)((ULONG *)&recScreenSettings.Video.ulHeight);
7330 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7331 hrc = pRecScreenSettings->COMGETTER(VideoDeadline)(&recScreenSettings.Video.enmDeadline);
7332 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7333 hrc = pRecScreenSettings->COMGETTER(VideoRateControlMode)(&recScreenSettings.Video.enmRateCtlMode);
7334 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7335 hrc = pRecScreenSettings->COMGETTER(VideoScalingMode)(&recScreenSettings.Video.enmScalingMode);
7336 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7337 hrc = pRecScreenSettings->COMGETTER(VideoRate)((ULONG *)&recScreenSettings.Video.ulRate);
7338 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7339 hrc = pRecScreenSettings->COMGETTER(VideoFPS)((ULONG *)&recScreenSettings.Video.ulFPS);
7340 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7341
7342 recording.mapScreens[i] = recScreenSettings;
7343 }
7344
7345 Assert(recording.mapScreens.size() == paRecScreens.size());
7346
7347 return VINF_SUCCESS;
7348}
7349
7350/**
7351 * Creates the recording context.
7352 *
7353 * @returns IPRT status code.
7354 */
7355int Console::i_recordingCreate(void)
7356{
7357 settings::RecordingSettings recordingSettings;
7358 int vrc = i_recordingGetSettings(recordingSettings);
7359 if (RT_SUCCESS(vrc))
7360 vrc = mRecording.mCtx.Create(this, recordingSettings);
7361
7362 LogFlowFuncLeaveRC(vrc);
7363 return vrc;
7364}
7365
7366/**
7367 * Destroys the recording context.
7368 */
7369void Console::i_recordingDestroy(void)
7370{
7371 mRecording.mCtx.Destroy();
7372}
7373
7374/**
7375 * Starts recording. Does nothing if recording is already active.
7376 *
7377 * @returns IPRT status code.
7378 */
7379int Console::i_recordingStart(util::AutoWriteLock *pAutoLock /* = NULL */)
7380{
7381 RT_NOREF(pAutoLock);
7382
7383 if (mRecording.mCtx.IsStarted())
7384 return VINF_SUCCESS;
7385
7386 LogRel(("Recording: Starting ...\n"));
7387
7388 int vrc = mRecording.mCtx.Start();
7389 if (RT_SUCCESS(vrc))
7390 {
7391 for (unsigned uScreen = 0; uScreen < mRecording.mCtx.GetStreamCount(); uScreen++)
7392 mDisplay->i_recordingScreenChanged(uScreen);
7393 }
7394
7395 LogFlowFuncLeaveRC(vrc);
7396 return vrc;
7397}
7398
7399/**
7400 * Stops recording. Does nothing if recording is not active.
7401 */
7402int Console::i_recordingStop(util::AutoWriteLock *pAutoLock /* = NULL */)
7403{
7404 if (!mRecording.mCtx.IsStarted())
7405 return VINF_SUCCESS;
7406
7407 LogRel(("Recording: Stopping ...\n"));
7408
7409 int vrc = mRecording.mCtx.Stop();
7410 if (RT_SUCCESS(vrc))
7411 {
7412 const size_t cStreams = mRecording.mCtx.GetStreamCount();
7413 for (unsigned uScreen = 0; uScreen < cStreams; ++uScreen)
7414 mDisplay->i_recordingScreenChanged(uScreen);
7415
7416 if (pAutoLock)
7417 pAutoLock->release();
7418
7419 ComPtr<IRecordingSettings> pRecordSettings;
7420 HRESULT hrc = mMachine->COMGETTER(RecordingSettings)(pRecordSettings.asOutParam());
7421 ComAssertComRC(hrc);
7422 hrc = pRecordSettings->COMSETTER(Enabled)(FALSE);
7423 ComAssertComRC(hrc);
7424
7425 if (pAutoLock)
7426 pAutoLock->acquire();
7427 }
7428
7429 LogFlowFuncLeaveRC(vrc);
7430 return vrc;
7431}
7432
7433#endif /* VBOX_WITH_RECORDING */
7434
7435/**
7436 * Gets called by Session::UpdateMachineState()
7437 * (IInternalSessionControl::updateMachineState()).
7438 *
7439 * Must be called only in certain cases (see the implementation).
7440 *
7441 * @note Locks this object for writing.
7442 */
7443HRESULT Console::i_updateMachineState(MachineState_T aMachineState)
7444{
7445 AutoCaller autoCaller(this);
7446 AssertComRCReturnRC(autoCaller.rc());
7447
7448 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7449
7450 AssertReturn( mMachineState == MachineState_Saving
7451 || mMachineState == MachineState_OnlineSnapshotting
7452 || mMachineState == MachineState_LiveSnapshotting
7453 || mMachineState == MachineState_DeletingSnapshotOnline
7454 || mMachineState == MachineState_DeletingSnapshotPaused
7455 || aMachineState == MachineState_Saving
7456 || aMachineState == MachineState_OnlineSnapshotting
7457 || aMachineState == MachineState_LiveSnapshotting
7458 || aMachineState == MachineState_DeletingSnapshotOnline
7459 || aMachineState == MachineState_DeletingSnapshotPaused
7460 , E_FAIL);
7461
7462 return i_setMachineStateLocally(aMachineState);
7463}
7464
7465/**
7466 * Gets called by Session::COMGETTER(NominalState)()
7467 * (IInternalSessionControl::getNominalState()).
7468 *
7469 * @note Locks this object for reading.
7470 */
7471HRESULT Console::i_getNominalState(MachineState_T &aNominalState)
7472{
7473 LogFlowThisFuncEnter();
7474
7475 AutoCaller autoCaller(this);
7476 AssertComRCReturnRC(autoCaller.rc());
7477
7478 /* Get the VM handle. */
7479 SafeVMPtr ptrVM(this);
7480 if (!ptrVM.isOk())
7481 return ptrVM.rc();
7482
7483 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7484
7485 MachineState_T enmMachineState = MachineState_Null;
7486 VMSTATE enmVMState = ptrVM.vtable()->pfnVMR3GetStateU(ptrVM.rawUVM());
7487 switch (enmVMState)
7488 {
7489 case VMSTATE_CREATING:
7490 case VMSTATE_CREATED:
7491 case VMSTATE_POWERING_ON:
7492 enmMachineState = MachineState_Starting;
7493 break;
7494 case VMSTATE_LOADING:
7495 enmMachineState = MachineState_Restoring;
7496 break;
7497 case VMSTATE_RESUMING:
7498 case VMSTATE_SUSPENDING:
7499 case VMSTATE_SUSPENDING_LS:
7500 case VMSTATE_SUSPENDING_EXT_LS:
7501 case VMSTATE_SUSPENDED:
7502 case VMSTATE_SUSPENDED_LS:
7503 case VMSTATE_SUSPENDED_EXT_LS:
7504 enmMachineState = MachineState_Paused;
7505 break;
7506 case VMSTATE_RUNNING:
7507 case VMSTATE_RUNNING_LS:
7508 case VMSTATE_RESETTING:
7509 case VMSTATE_RESETTING_LS:
7510 case VMSTATE_SOFT_RESETTING:
7511 case VMSTATE_SOFT_RESETTING_LS:
7512 case VMSTATE_DEBUGGING:
7513 case VMSTATE_DEBUGGING_LS:
7514 enmMachineState = MachineState_Running;
7515 break;
7516 case VMSTATE_SAVING:
7517 enmMachineState = MachineState_Saving;
7518 break;
7519 case VMSTATE_POWERING_OFF:
7520 case VMSTATE_POWERING_OFF_LS:
7521 case VMSTATE_DESTROYING:
7522 enmMachineState = MachineState_Stopping;
7523 break;
7524 case VMSTATE_OFF:
7525 case VMSTATE_OFF_LS:
7526 case VMSTATE_FATAL_ERROR:
7527 case VMSTATE_FATAL_ERROR_LS:
7528 case VMSTATE_LOAD_FAILURE:
7529 case VMSTATE_TERMINATED:
7530 enmMachineState = MachineState_PoweredOff;
7531 break;
7532 case VMSTATE_GURU_MEDITATION:
7533 case VMSTATE_GURU_MEDITATION_LS:
7534 enmMachineState = MachineState_Stuck;
7535 break;
7536 default:
7537 AssertMsgFailed(("%s\n", ptrVM.vtable()->pfnVMR3GetStateName(enmVMState)));
7538 enmMachineState = MachineState_PoweredOff;
7539 }
7540 aNominalState = enmMachineState;
7541
7542 LogFlowFuncLeave();
7543 return S_OK;
7544}
7545
7546void Console::i_onMousePointerShapeChange(bool fVisible, bool fAlpha,
7547 uint32_t xHot, uint32_t yHot,
7548 uint32_t width, uint32_t height,
7549 const uint8_t *pu8Shape,
7550 uint32_t cbShape)
7551{
7552#if 0
7553 LogFlowThisFuncEnter();
7554 LogFlowThisFunc(("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, height=%d, shape=%p\n",
7555 fVisible, fAlpha, xHot, yHot, width, height, pShape));
7556#endif
7557
7558 AutoCaller autoCaller(this);
7559 AssertComRCReturnVoid(autoCaller.rc());
7560
7561 if (!mMouse.isNull())
7562 mMouse->updateMousePointerShape(fVisible, fAlpha, xHot, yHot, width, height, pu8Shape, cbShape);
7563
7564 com::SafeArray<BYTE> shape(cbShape);
7565 if (pu8Shape)
7566 memcpy(shape.raw(), pu8Shape, cbShape);
7567 ::FireMousePointerShapeChangedEvent(mEventSource, fVisible, fAlpha, xHot, yHot, width, height, ComSafeArrayAsInParam(shape));
7568
7569#if 0
7570 LogFlowThisFuncLeave();
7571#endif
7572}
7573
7574void Console::i_onMouseCapabilityChange(BOOL supportsAbsolute, BOOL supportsRelative,
7575 BOOL supportsTouchScreen, BOOL supportsTouchPad, BOOL needsHostCursor)
7576{
7577 LogFlowThisFunc(("supportsAbsolute=%d supportsRelative=%d supportsTouchScreen=%d supportsTouchPad=%d needsHostCursor=%d\n",
7578 supportsAbsolute, supportsRelative, supportsTouchScreen, supportsTouchPad, needsHostCursor));
7579
7580 AutoCaller autoCaller(this);
7581 AssertComRCReturnVoid(autoCaller.rc());
7582
7583 ::FireMouseCapabilityChangedEvent(mEventSource, supportsAbsolute, supportsRelative, supportsTouchScreen, supportsTouchPad, needsHostCursor);
7584}
7585
7586void Console::i_onStateChange(MachineState_T machineState)
7587{
7588 AutoCaller autoCaller(this);
7589 AssertComRCReturnVoid(autoCaller.rc());
7590 ::FireStateChangedEvent(mEventSource, machineState);
7591}
7592
7593void Console::i_onAdditionsStateChange()
7594{
7595 AutoCaller autoCaller(this);
7596 AssertComRCReturnVoid(autoCaller.rc());
7597
7598 ::FireAdditionsStateChangedEvent(mEventSource);
7599}
7600
7601/**
7602 * @remarks This notification only is for reporting an incompatible
7603 * Guest Additions interface, *not* the Guest Additions version!
7604 *
7605 * The user will be notified inside the guest if new Guest
7606 * Additions are available (via VBoxTray/VBoxClient).
7607 */
7608void Console::i_onAdditionsOutdated()
7609{
7610 AutoCaller autoCaller(this);
7611 AssertComRCReturnVoid(autoCaller.rc());
7612
7613 /** @todo implement this */
7614}
7615
7616void Console::i_onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
7617{
7618 AutoCaller autoCaller(this);
7619 AssertComRCReturnVoid(autoCaller.rc());
7620
7621 ::FireKeyboardLedsChangedEvent(mEventSource, fNumLock, fCapsLock, fScrollLock);
7622}
7623
7624void Console::i_onUSBDeviceStateChange(IUSBDevice *aDevice, bool aAttached,
7625 IVirtualBoxErrorInfo *aError)
7626{
7627 AutoCaller autoCaller(this);
7628 AssertComRCReturnVoid(autoCaller.rc());
7629
7630 ::FireUSBDeviceStateChangedEvent(mEventSource, aDevice, aAttached, aError);
7631}
7632
7633void Console::i_onRuntimeError(BOOL aFatal, IN_BSTR aErrorID, IN_BSTR aMessage)
7634{
7635 AutoCaller autoCaller(this);
7636 AssertComRCReturnVoid(autoCaller.rc());
7637
7638 ::FireRuntimeErrorEvent(mEventSource, aFatal, aErrorID, aMessage);
7639}
7640
7641HRESULT Console::i_onShowWindow(BOOL aCheck, BOOL *aCanShow, LONG64 *aWinId)
7642{
7643 AssertReturn(aCanShow, E_POINTER);
7644 AssertReturn(aWinId, E_POINTER);
7645
7646 *aCanShow = FALSE;
7647 *aWinId = 0;
7648
7649 AutoCaller autoCaller(this);
7650 AssertComRCReturnRC(autoCaller.rc());
7651
7652 ComPtr<IEvent> ptrEvent;
7653 if (aCheck)
7654 {
7655 *aCanShow = TRUE;
7656 HRESULT hrc = ::CreateCanShowWindowEvent(ptrEvent.asOutParam(), mEventSource);
7657 if (SUCCEEDED(hrc))
7658 {
7659 VBoxEventDesc EvtDesc(ptrEvent, mEventSource);
7660 BOOL fDelivered = EvtDesc.fire(5000); /* Wait up to 5 secs for delivery */
7661 //Assert(fDelivered);
7662 if (fDelivered)
7663 {
7664 // bit clumsy
7665 ComPtr<ICanShowWindowEvent> ptrCanShowEvent = ptrEvent;
7666 if (ptrCanShowEvent)
7667 {
7668 BOOL fVetoed = FALSE;
7669 BOOL fApproved = FALSE;
7670 ptrCanShowEvent->IsVetoed(&fVetoed);
7671 ptrCanShowEvent->IsApproved(&fApproved);
7672 *aCanShow = fApproved || !fVetoed;
7673 }
7674 else
7675 AssertFailed();
7676 }
7677 }
7678 }
7679 else
7680 {
7681 HRESULT hrc = ::CreateShowWindowEvent(ptrEvent.asOutParam(), mEventSource, 0);
7682 if (SUCCEEDED(hrc))
7683 {
7684 VBoxEventDesc EvtDesc(ptrEvent, mEventSource);
7685 BOOL fDelivered = EvtDesc.fire(5000); /* Wait up to 5 secs for delivery */
7686 //Assert(fDelivered);
7687 if (fDelivered)
7688 {
7689 ComPtr<IShowWindowEvent> ptrShowEvent = ptrEvent;
7690 if (ptrShowEvent)
7691 {
7692 LONG64 idWindow = 0;
7693 ptrShowEvent->COMGETTER(WinId)(&idWindow);
7694 if (idWindow != 0 && *aWinId == 0)
7695 *aWinId = idWindow;
7696 }
7697 else
7698 AssertFailed();
7699 }
7700 }
7701 }
7702
7703 return S_OK;
7704}
7705
7706// private methods
7707////////////////////////////////////////////////////////////////////////////////
7708
7709/**
7710 * Loads the VMM if needed.
7711 *
7712 * @returns COM status.
7713 * @remarks Caller must write lock the console object.
7714 */
7715HRESULT Console::i_loadVMM(void) RT_NOEXCEPT
7716{
7717 if ( mhModVMM == NIL_RTLDRMOD
7718 || mpVMM == NULL)
7719 {
7720 Assert(!mpVMM);
7721
7722 HRESULT hrc;
7723 RTERRINFOSTATIC ErrInfo;
7724 RTLDRMOD hModVMM = NIL_RTLDRMOD;
7725 int vrc = SUPR3HardenedLdrLoadAppPriv("VBoxVMM", &hModVMM, RTLDRLOAD_FLAGS_LOCAL, RTErrInfoInitStatic(&ErrInfo));
7726 if (RT_SUCCESS(vrc))
7727 {
7728 PFNVMMGETVTABLE pfnGetVTable = NULL;
7729 vrc = RTLdrGetSymbol(hModVMM, VMMR3VTABLE_GETTER_NAME, (void **)&pfnGetVTable);
7730 if (pfnGetVTable)
7731 {
7732 PCVMMR3VTABLE pVMM = pfnGetVTable();
7733 if (pVMM)
7734 {
7735 if (VMMR3VTABLE_IS_COMPATIBLE(pVMM->uMagicVersion))
7736 {
7737 if (pVMM->uMagicVersion == pVMM->uMagicVersionEnd)
7738 {
7739 mhModVMM = hModVMM;
7740 mpVMM = pVMM;
7741 LogFunc(("mhLdrVMM=%p phVMM=%p uMagicVersion=%#RX64\n", hModVMM, pVMM, pVMM->uMagicVersion));
7742 return S_OK;
7743 }
7744
7745 hrc = setErrorVrc(vrc, "Bogus VMM vtable: uMagicVersion=%#RX64 uMagicVersionEnd=%#RX64",
7746 pVMM->uMagicVersion, pVMM->uMagicVersionEnd);
7747 }
7748 else
7749 hrc = setErrorVrc(vrc, "Incompatible of bogus VMM version magic: %#RX64", pVMM->uMagicVersion);
7750 }
7751 else
7752 hrc = setErrorVrc(vrc, "pfnGetVTable return NULL!");
7753 }
7754 else
7755 hrc = setErrorVrc(vrc, "Failed to locate symbol '%s' in VBoxVMM: %Rrc", VMMR3VTABLE_GETTER_NAME, vrc);
7756 RTLdrClose(hModVMM);
7757 }
7758 else
7759 hrc = setErrorVrc(vrc, "Failed to load VBoxVMM: %#RTeic", &ErrInfo.Core);
7760 return hrc;
7761 }
7762
7763 return S_OK;
7764}
7765
7766/**
7767 * Increases the usage counter of the mpUVM pointer.
7768 *
7769 * Guarantees that VMR3Destroy() will not be called on it at least until
7770 * releaseVMCaller() is called.
7771 *
7772 * If this method returns a failure, the caller is not allowed to use mpUVM and
7773 * may return the failed result code to the upper level. This method sets the
7774 * extended error info on failure if \a aQuiet is false.
7775 *
7776 * Setting \a aQuiet to true is useful for methods that don't want to return
7777 * the failed result code to the caller when this method fails (e.g. need to
7778 * silently check for the mpUVM availability).
7779 *
7780 * When mpUVM is NULL but \a aAllowNullVM is true, a corresponding error will be
7781 * returned instead of asserting. Having it false is intended as a sanity check
7782 * for methods that have checked mMachineState and expect mpUVM *NOT* to be
7783 * NULL.
7784 *
7785 * @param aQuiet true to suppress setting error info
7786 * @param aAllowNullVM true to accept mpUVM being NULL and return a failure
7787 * (otherwise this method will assert if mpUVM is NULL)
7788 *
7789 * @note Locks this object for writing.
7790 */
7791HRESULT Console::i_addVMCaller(bool aQuiet /* = false */,
7792 bool aAllowNullVM /* = false */)
7793{
7794 RT_NOREF(aAllowNullVM);
7795 AutoCaller autoCaller(this);
7796 /** @todo Fix race during console/VM reference destruction, refer @bugref{6318}
7797 * comment 25. */
7798 if (FAILED(autoCaller.rc()))
7799 return autoCaller.rc();
7800
7801 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7802
7803 if (mVMDestroying)
7804 {
7805 /* powerDown() is waiting for all callers to finish */
7806 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED, tr("The virtual machine is being powered down"));
7807 }
7808
7809 if (mpUVM == NULL)
7810 {
7811 Assert(aAllowNullVM == true);
7812
7813 /* The machine is not powered up */
7814 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED, tr("The virtual machine is not powered up"));
7815 }
7816
7817 ++mVMCallers;
7818
7819 return S_OK;
7820}
7821
7822/**
7823 * Decreases the usage counter of the mpUVM pointer.
7824 *
7825 * Must always complete the addVMCaller() call after the mpUVM pointer is no
7826 * more necessary.
7827 *
7828 * @note Locks this object for writing.
7829 */
7830void Console::i_releaseVMCaller()
7831{
7832 AutoCaller autoCaller(this);
7833 AssertComRCReturnVoid(autoCaller.rc());
7834
7835 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7836
7837 AssertReturnVoid(mpUVM != NULL);
7838
7839 Assert(mVMCallers > 0);
7840 --mVMCallers;
7841
7842 if (mVMCallers == 0 && mVMDestroying)
7843 {
7844 /* inform powerDown() there are no more callers */
7845 RTSemEventSignal(mVMZeroCallersSem);
7846 }
7847}
7848
7849
7850/**
7851 * Helper for SafeVMPtrBase.
7852 */
7853HRESULT Console::i_safeVMPtrRetainer(PUVM *a_ppUVM, PCVMMR3VTABLE *a_ppVMM, bool a_Quiet) RT_NOEXCEPT
7854{
7855 *a_ppUVM = NULL;
7856 *a_ppVMM = NULL;
7857
7858 AutoCaller autoCaller(this);
7859 AssertComRCReturnRC(autoCaller.rc());
7860 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7861
7862 /*
7863 * Repeat the checks done by addVMCaller.
7864 */
7865 if (mVMDestroying) /* powerDown() is waiting for all callers to finish */
7866 return a_Quiet
7867 ? E_ACCESSDENIED
7868 : setError(E_ACCESSDENIED, tr("The virtual machine is being powered down"));
7869 PUVM const pUVM = mpUVM;
7870 if (!pUVM)
7871 return a_Quiet
7872 ? E_ACCESSDENIED
7873 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
7874 PCVMMR3VTABLE const pVMM = mpVMM;
7875 if (!pVMM)
7876 return a_Quiet
7877 ? E_ACCESSDENIED
7878 : setError(E_ACCESSDENIED, tr("No VMM loaded!"));
7879
7880 /*
7881 * Retain a reference to the user mode VM handle and get the global handle.
7882 */
7883 uint32_t cRefs = pVMM->pfnVMR3RetainUVM(pUVM);
7884 if (cRefs == UINT32_MAX)
7885 return a_Quiet
7886 ? E_ACCESSDENIED
7887 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
7888
7889 /* done */
7890 *a_ppUVM = pUVM;
7891 *a_ppVMM = pVMM;
7892 return S_OK;
7893}
7894
7895void Console::i_safeVMPtrReleaser(PUVM *a_ppUVM)
7896{
7897 PUVM const pUVM = *a_ppUVM;
7898 *a_ppUVM = NULL;
7899 if (pUVM)
7900 {
7901 PCVMMR3VTABLE const pVMM = mpVMM;
7902 if (pVMM)
7903 pVMM->pfnVMR3ReleaseUVM(pUVM);
7904 }
7905}
7906
7907
7908#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
7909/*static*/
7910DECLCALLBACK(int) Console::i_logEncryptedOpen(PCRTLOGOUTPUTIF pIf, void *pvUser, const char *pszFilename, uint32_t fFlags)
7911{
7912 RT_NOREF(pIf);
7913 Console *pConsole = static_cast<Console *>(pvUser);
7914 RTVFSFILE hVfsFile = NIL_RTVFSFILE;
7915
7916 int vrc = RTVfsFileOpenNormal(pszFilename, fFlags, &hVfsFile);
7917 if (RT_SUCCESS(vrc))
7918 {
7919 PCVBOXCRYPTOIF pCryptoIf = NULL;
7920 vrc = pConsole->i_retainCryptoIf(&pCryptoIf);
7921 if (RT_SUCCESS(vrc))
7922 {
7923 SecretKey *pKey = NULL;
7924
7925 vrc = pConsole->m_pKeyStore->retainSecretKey(pConsole->m_strLogKeyId, &pKey);
7926 if (RT_SUCCESS(vrc))
7927 {
7928 const char *pszPassword = (const char *)pKey->getKeyBuffer();
7929
7930 vrc = pCryptoIf->pfnCryptoFileFromVfsFile(hVfsFile, pConsole->m_strLogKeyStore.c_str(), pszPassword,
7931 &pConsole->m_hVfsFileLog);
7932 pKey->release();
7933 }
7934
7935 /* On success we keep the reference to keep the cryptographic module loaded. */
7936 if (RT_FAILURE(vrc))
7937 pConsole->i_releaseCryptoIf(pCryptoIf);
7938 }
7939
7940 /* Always do this because the encrypted log has retained a reference to the underlying file. */
7941 RTVfsFileRelease(hVfsFile);
7942 if (RT_FAILURE(vrc))
7943 RTFileDelete(pszFilename);
7944 }
7945
7946 return vrc;
7947}
7948
7949
7950/*static*/
7951DECLCALLBACK(int) Console::i_logEncryptedClose(PCRTLOGOUTPUTIF pIf, void *pvUser)
7952{
7953 RT_NOREF(pIf);
7954 Console *pConsole = static_cast<Console *>(pvUser);
7955
7956 RTVfsFileRelease(pConsole->m_hVfsFileLog);
7957 pConsole->m_hVfsFileLog = NIL_RTVFSFILE;
7958 return VINF_SUCCESS;
7959}
7960
7961
7962/*static*/
7963DECLCALLBACK(int) Console::i_logEncryptedDelete(PCRTLOGOUTPUTIF pIf, void *pvUser, const char *pszFilename)
7964{
7965 RT_NOREF(pIf, pvUser);
7966 return RTFileDelete(pszFilename);
7967}
7968
7969
7970/*static*/
7971DECLCALLBACK(int) Console::i_logEncryptedRename(PCRTLOGOUTPUTIF pIf, void *pvUser, const char *pszFilenameOld,
7972 const char *pszFilenameNew, uint32_t fFlags)
7973{
7974 RT_NOREF(pIf, pvUser);
7975 return RTFileRename(pszFilenameOld, pszFilenameNew, fFlags);
7976}
7977
7978
7979/*static*/
7980DECLCALLBACK(int) Console::i_logEncryptedQuerySize(PCRTLOGOUTPUTIF pIf, void *pvUser, uint64_t *pcbSize)
7981{
7982 RT_NOREF(pIf);
7983 Console *pConsole = static_cast<Console *>(pvUser);
7984
7985 return RTVfsFileQuerySize(pConsole->m_hVfsFileLog, pcbSize);
7986}
7987
7988
7989/*static*/
7990DECLCALLBACK(int) Console::i_logEncryptedWrite(PCRTLOGOUTPUTIF pIf, void *pvUser, const void *pvBuf,
7991 size_t cbWrite, size_t *pcbWritten)
7992{
7993 RT_NOREF(pIf);
7994 Console *pConsole = static_cast<Console *>(pvUser);
7995
7996 return RTVfsFileWrite(pConsole->m_hVfsFileLog, pvBuf, cbWrite, pcbWritten);
7997}
7998
7999
8000/*static*/
8001DECLCALLBACK(int) Console::i_logEncryptedFlush(PCRTLOGOUTPUTIF pIf, void *pvUser)
8002{
8003 RT_NOREF(pIf);
8004 Console *pConsole = static_cast<Console *>(pvUser);
8005
8006 return RTVfsFileFlush(pConsole->m_hVfsFileLog);
8007}
8008#endif
8009
8010
8011/**
8012 * Initialize the release logging facility. In case something
8013 * goes wrong, there will be no release logging. Maybe in the future
8014 * we can add some logic to use different file names in this case.
8015 * Note that the logic must be in sync with Machine::DeleteSettings().
8016 */
8017HRESULT Console::i_consoleInitReleaseLog(const ComPtr<IMachine> aMachine)
8018{
8019 Bstr bstrLogFolder;
8020 HRESULT hrc = aMachine->COMGETTER(LogFolder)(bstrLogFolder.asOutParam());
8021 if (FAILED(hrc))
8022 return hrc;
8023 Utf8Str strLogDir = bstrLogFolder;
8024
8025 /* make sure the Logs folder exists */
8026 Assert(strLogDir.length());
8027 if (!RTDirExists(strLogDir.c_str()))
8028 RTDirCreateFullPath(strLogDir.c_str(), 0700);
8029
8030 Utf8StrFmt logFile("%s%cVBox.log", strLogDir.c_str(), RTPATH_DELIMITER);
8031 Utf8StrFmt pngFile("%s%cVBox.png", strLogDir.c_str(), RTPATH_DELIMITER);
8032
8033 /*
8034 * Age the old log files.
8035 * Rename .(n-1) to .(n), .(n-2) to .(n-1), ..., and the last log file to .1
8036 * Overwrite target files in case they exist.
8037 */
8038 ComPtr<IVirtualBox> pVirtualBox;
8039 aMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
8040 ComPtr<ISystemProperties> pSystemProperties;
8041 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
8042 ULONG cHistoryFiles = 3;
8043 pSystemProperties->COMGETTER(LogHistoryCount)(&cHistoryFiles);
8044 if (cHistoryFiles)
8045 {
8046 for (int i = cHistoryFiles - 1; i >= 0; i--)
8047 {
8048 Utf8Str *files[] = { &logFile, &pngFile };
8049 Utf8Str oldName, newName;
8050
8051 for (unsigned int j = 0; j < RT_ELEMENTS(files); ++j)
8052 {
8053 if (i > 0)
8054 oldName.printf("%s.%d", files[j]->c_str(), i);
8055 else
8056 oldName = *files[j];
8057 newName.printf("%s.%d", files[j]->c_str(), i + 1);
8058
8059 /* If the old file doesn't exist, delete the new file (if it
8060 * exists) to provide correct rotation even if the sequence is
8061 * broken */
8062 if (RTFileRename(oldName.c_str(), newName.c_str(), RTFILEMOVE_FLAGS_REPLACE) == VERR_FILE_NOT_FOUND)
8063 RTFileDelete(newName.c_str());
8064 }
8065 }
8066 }
8067
8068 Bstr bstrLogKeyId;
8069 Bstr bstrLogKeyStore;
8070 PCRTLOGOUTPUTIF pLogOutputIf = NULL;
8071 void *pvLogOutputUser = NULL;
8072 int vrc = VINF_SUCCESS;
8073#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
8074 hrc = aMachine->COMGETTER(LogKeyId)(bstrLogKeyId.asOutParam());
8075 if (SUCCEEDED(hrc))
8076 {
8077 hrc = aMachine->COMGETTER(LogKeyStore)(bstrLogKeyStore.asOutParam());
8078 if ( SUCCEEDED(hrc)
8079 && bstrLogKeyId.isNotEmpty()
8080 && bstrLogKeyStore.isNotEmpty())
8081 {
8082 m_LogOutputIf.pfnOpen = Console::i_logEncryptedOpen;
8083 m_LogOutputIf.pfnClose = Console::i_logEncryptedClose;
8084 m_LogOutputIf.pfnDelete = Console::i_logEncryptedDelete;
8085 m_LogOutputIf.pfnRename = Console::i_logEncryptedRename;
8086 m_LogOutputIf.pfnQuerySize = Console::i_logEncryptedQuerySize;
8087 m_LogOutputIf.pfnWrite = Console::i_logEncryptedWrite;
8088 m_LogOutputIf.pfnFlush = Console::i_logEncryptedFlush;
8089
8090 m_strLogKeyId = Utf8Str(bstrLogKeyId);
8091 m_strLogKeyStore = Utf8Str(bstrLogKeyStore);
8092
8093 pLogOutputIf = &m_LogOutputIf;
8094 pvLogOutputUser = this;
8095 m_fEncryptedLog = true;
8096 }
8097 }
8098
8099 if (RT_FAILURE(vrc))
8100 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to set encryption for release log (%Rrc)"), vrc);
8101 else
8102#endif
8103 {
8104 RTERRINFOSTATIC ErrInfo;
8105 vrc = com::VBoxLogRelCreateEx("VM", logFile.c_str(),
8106 RTLOGFLAGS_PREFIX_TIME_PROG | RTLOGFLAGS_RESTRICT_GROUPS,
8107 "all all.restrict -default.restrict",
8108 "VBOX_RELEASE_LOG", RTLOGDEST_FILE,
8109 32768 /* cMaxEntriesPerGroup */,
8110 0 /* cHistory */, 0 /* uHistoryFileTime */,
8111 0 /* uHistoryFileSize */,
8112 pLogOutputIf, pvLogOutputUser,
8113 RTErrInfoInitStatic(&ErrInfo));
8114 if (RT_FAILURE(vrc))
8115 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to open release log (%s, %Rrc)"), ErrInfo.Core.pszMsg, vrc);
8116 }
8117
8118 /* If we've made any directory changes, flush the directory to increase
8119 the likelihood that the log file will be usable after a system panic.
8120
8121 Tip: Try 'export VBOX_RELEASE_LOG_FLAGS=flush' if the last bits of the log
8122 is missing. Just don't have too high hopes for this to help. */
8123 if (SUCCEEDED(hrc) || cHistoryFiles)
8124 RTDirFlush(strLogDir.c_str());
8125
8126 return hrc;
8127}
8128
8129/**
8130 * Common worker for PowerUp and PowerUpPaused.
8131 *
8132 * @returns COM status code.
8133 *
8134 * @param aProgress Where to return the progress object.
8135 * @param aPaused true if PowerUpPaused called.
8136 */
8137HRESULT Console::i_powerUp(IProgress **aProgress, bool aPaused)
8138{
8139 LogFlowThisFuncEnter();
8140
8141 CheckComArgOutPointerValid(aProgress);
8142
8143 AutoCaller autoCaller(this);
8144 HRESULT rc = autoCaller.rc();
8145 if (FAILED(rc)) return rc;
8146
8147 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8148 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
8149
8150 if (Global::IsOnlineOrTransient(mMachineState))
8151 return setError(VBOX_E_INVALID_VM_STATE, tr("The virtual machine is already running or busy (machine state: %s)"),
8152 Global::stringifyMachineState(mMachineState));
8153
8154
8155 /* Set up release logging as early as possible after the check if
8156 * there is already a running VM which we shouldn't disturb. */
8157 rc = i_consoleInitReleaseLog(mMachine);
8158 if (FAILED(rc))
8159 return rc;
8160
8161#ifdef VBOX_OPENSSL_FIPS
8162 LogRel(("crypto: FIPS mode %s\n", FIPS_mode() ? "enabled" : "FAILED"));
8163#endif
8164
8165 /* test and clear the TeleporterEnabled property */
8166 BOOL fTeleporterEnabled;
8167 rc = mMachine->COMGETTER(TeleporterEnabled)(&fTeleporterEnabled);
8168 if (FAILED(rc))
8169 return rc;
8170
8171#if 0 /** @todo we should save it afterwards, but that isn't necessarily a good idea. Find a better place for this (VBoxSVC). */
8172 if (fTeleporterEnabled)
8173 {
8174 rc = mMachine->COMSETTER(TeleporterEnabled)(FALSE);
8175 if (FAILED(rc))
8176 return rc;
8177 }
8178#endif
8179
8180 PCVMMR3VTABLE const pVMM = mpVMM;
8181 AssertPtrReturn(pVMM, E_UNEXPECTED);
8182
8183 ComObjPtr<Progress> pPowerupProgress;
8184 bool fBeganPoweringUp = false;
8185
8186 LONG cOperations = 1;
8187 LONG ulTotalOperationsWeight = 1;
8188 VMPowerUpTask *task = NULL;
8189
8190 try
8191 {
8192 /* Create a progress object to track progress of this operation. Must
8193 * be done as early as possible (together with BeginPowerUp()) as this
8194 * is vital for communicating as much as possible early powerup
8195 * failure information to the API caller */
8196 pPowerupProgress.createObject();
8197 Bstr progressDesc;
8198 if (mMachineState == MachineState_Saved || mMachineState == MachineState_AbortedSaved)
8199 progressDesc = tr("Restoring virtual machine");
8200 else if (fTeleporterEnabled)
8201 progressDesc = tr("Teleporting virtual machine");
8202 else
8203 progressDesc = tr("Starting virtual machine");
8204
8205 /*
8206 * Saved VMs will have to prove that their saved states seem kosher.
8207 */
8208 Utf8Str strSavedStateFile;
8209 Bstr bstrStateKeyId;
8210 Bstr bstrStateKeyStore;
8211
8212 if (mMachineState == MachineState_Saved || mMachineState == MachineState_AbortedSaved)
8213 {
8214 Bstr bstrSavedStateFile;
8215 rc = mMachine->COMGETTER(StateFilePath)(bstrSavedStateFile.asOutParam());
8216 if (FAILED(rc))
8217 throw rc;
8218 strSavedStateFile = bstrSavedStateFile;
8219
8220#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
8221 rc = mMachine->COMGETTER(StateKeyId)(bstrStateKeyId.asOutParam());
8222 if (FAILED(rc))
8223 throw rc;
8224 rc = mMachine->COMGETTER(StateKeyStore)(bstrStateKeyStore.asOutParam());
8225 if (FAILED(rc))
8226 throw rc;
8227#endif
8228
8229 ComAssertRet(bstrSavedStateFile.isNotEmpty(), E_FAIL);
8230 SsmStream ssmStream(this, pVMM, m_pKeyStore, bstrStateKeyId, bstrStateKeyStore);
8231 int vrc = ssmStream.open(strSavedStateFile.c_str());
8232 if (RT_SUCCESS(vrc))
8233 {
8234 PCSSMSTRMOPS pStreamOps;
8235 void *pvStreamOpsUser;
8236
8237 vrc = ssmStream.querySsmStrmOps(&pStreamOps, &pvStreamOpsUser);
8238 if (RT_SUCCESS(vrc))
8239 vrc = pVMM->pfnSSMR3ValidateFile(NULL /*pszFilename*/, pStreamOps, pvStreamOpsUser,
8240 false /* fChecksumIt */);
8241 }
8242
8243 if (RT_FAILURE(vrc))
8244 {
8245 Utf8Str errMsg;
8246 switch (vrc)
8247 {
8248 case VERR_FILE_NOT_FOUND:
8249 errMsg.printf(tr("VM failed to start because the saved state file '%s' does not exist."),
8250 strSavedStateFile.c_str());
8251 break;
8252 default:
8253 errMsg.printf(tr("VM failed to start because the saved state file '%s' is invalid (%Rrc). "
8254 "Delete the saved state prior to starting the VM."), strSavedStateFile.c_str(), vrc);
8255 break;
8256 }
8257 throw setErrorBoth(VBOX_E_FILE_ERROR, vrc, errMsg.c_str());
8258 }
8259
8260 }
8261
8262 /* Read console data, including console shared folders, stored in the
8263 * saved state file (if not yet done).
8264 */
8265 rc = i_loadDataFromSavedState();
8266 if (FAILED(rc))
8267 throw rc;
8268
8269 /* Check all types of shared folders and compose a single list */
8270 SharedFolderDataMap sharedFolders;
8271 {
8272 /* first, insert global folders */
8273 for (SharedFolderDataMap::const_iterator it = m_mapGlobalSharedFolders.begin();
8274 it != m_mapGlobalSharedFolders.end();
8275 ++it)
8276 {
8277 const SharedFolderData &d = it->second;
8278 sharedFolders[it->first] = d;
8279 }
8280
8281 /* second, insert machine folders */
8282 for (SharedFolderDataMap::const_iterator it = m_mapMachineSharedFolders.begin();
8283 it != m_mapMachineSharedFolders.end();
8284 ++it)
8285 {
8286 const SharedFolderData &d = it->second;
8287 sharedFolders[it->first] = d;
8288 }
8289
8290 /* third, insert console folders */
8291 for (SharedFolderMap::const_iterator it = m_mapSharedFolders.begin();
8292 it != m_mapSharedFolders.end();
8293 ++it)
8294 {
8295 SharedFolder *pSF = it->second;
8296 AutoCaller sfCaller(pSF);
8297 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
8298 sharedFolders[it->first] = SharedFolderData(pSF->i_getHostPath(),
8299 pSF->i_isWritable(),
8300 pSF->i_isAutoMounted(),
8301 pSF->i_getAutoMountPoint());
8302 }
8303 }
8304
8305
8306 /* Setup task object and thread to carry out the operation
8307 * asynchronously */
8308 try { task = new VMPowerUpTask(this, pPowerupProgress); }
8309 catch (std::bad_alloc &) { throw rc = E_OUTOFMEMORY; }
8310 if (!task->isOk())
8311 throw task->rc();
8312
8313 task->mpfnConfigConstructor = i_configConstructor;
8314 task->mSharedFolders = sharedFolders;
8315 task->mStartPaused = aPaused;
8316 if (mMachineState == MachineState_Saved || mMachineState == MachineState_AbortedSaved)
8317 try { task->mSavedStateFile = strSavedStateFile; }
8318 catch (std::bad_alloc &) { throw rc = E_OUTOFMEMORY; }
8319 task->mTeleporterEnabled = fTeleporterEnabled;
8320
8321 /* Reset differencing hard disks for which autoReset is true,
8322 * but only if the machine has no snapshots OR the current snapshot
8323 * is an OFFLINE snapshot; otherwise we would reset the current
8324 * differencing image of an ONLINE snapshot which contains the disk
8325 * state of the machine while it was previously running, but without
8326 * the corresponding machine state, which is equivalent to powering
8327 * off a running machine and not good idea
8328 */
8329 ComPtr<ISnapshot> pCurrentSnapshot;
8330 rc = mMachine->COMGETTER(CurrentSnapshot)(pCurrentSnapshot.asOutParam());
8331 if (FAILED(rc))
8332 throw rc;
8333
8334 BOOL fCurrentSnapshotIsOnline = false;
8335 if (pCurrentSnapshot)
8336 {
8337 rc = pCurrentSnapshot->COMGETTER(Online)(&fCurrentSnapshotIsOnline);
8338 if (FAILED(rc))
8339 throw rc;
8340 }
8341
8342 if (strSavedStateFile.isEmpty() && !fCurrentSnapshotIsOnline)
8343 {
8344 LogFlowThisFunc(("Looking for immutable images to reset\n"));
8345
8346 com::SafeIfaceArray<IMediumAttachment> atts;
8347 rc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
8348 if (FAILED(rc))
8349 throw rc;
8350
8351 for (size_t i = 0;
8352 i < atts.size();
8353 ++i)
8354 {
8355 DeviceType_T devType;
8356 rc = atts[i]->COMGETTER(Type)(&devType);
8357 /** @todo later applies to floppies as well */
8358 if (devType == DeviceType_HardDisk)
8359 {
8360 ComPtr<IMedium> pMedium;
8361 rc = atts[i]->COMGETTER(Medium)(pMedium.asOutParam());
8362 if (FAILED(rc))
8363 throw rc;
8364
8365 /* needs autoreset? */
8366 BOOL autoReset = FALSE;
8367 rc = pMedium->COMGETTER(AutoReset)(&autoReset);
8368 if (FAILED(rc))
8369 throw rc;
8370
8371 if (autoReset)
8372 {
8373 ComPtr<IProgress> pResetProgress;
8374 rc = pMedium->Reset(pResetProgress.asOutParam());
8375 if (FAILED(rc))
8376 throw rc;
8377
8378 /* save for later use on the powerup thread */
8379 task->hardDiskProgresses.push_back(pResetProgress);
8380 }
8381 }
8382 }
8383 }
8384 else
8385 LogFlowThisFunc(("Machine has a current snapshot which is online, skipping immutable images reset\n"));
8386
8387 /* setup task object and thread to carry out the operation
8388 * asynchronously */
8389
8390#ifdef VBOX_WITH_EXTPACK
8391 mptrExtPackManager->i_dumpAllToReleaseLog();
8392#endif
8393
8394#ifdef RT_OS_SOLARIS
8395 /* setup host core dumper for the VM */
8396 Bstr value;
8397 HRESULT hrc = mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpEnabled").raw(), value.asOutParam());
8398 if (SUCCEEDED(hrc) && value == "1")
8399 {
8400 Bstr coreDumpDir, coreDumpReplaceSys, coreDumpLive;
8401 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpDir").raw(), coreDumpDir.asOutParam());
8402 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpReplaceSystemDump").raw(), coreDumpReplaceSys.asOutParam());
8403 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpLive").raw(), coreDumpLive.asOutParam());
8404
8405 uint32_t fCoreFlags = 0;
8406 if ( coreDumpReplaceSys.isEmpty() == false
8407 && Utf8Str(coreDumpReplaceSys).toUInt32() == 1)
8408 fCoreFlags |= RTCOREDUMPER_FLAGS_REPLACE_SYSTEM_DUMP;
8409
8410 if ( coreDumpLive.isEmpty() == false
8411 && Utf8Str(coreDumpLive).toUInt32() == 1)
8412 fCoreFlags |= RTCOREDUMPER_FLAGS_LIVE_CORE;
8413
8414 Utf8Str strDumpDir(coreDumpDir);
8415 const char *pszDumpDir = strDumpDir.c_str();
8416 if ( pszDumpDir
8417 && *pszDumpDir == '\0')
8418 pszDumpDir = NULL;
8419
8420 int vrc;
8421 if ( pszDumpDir
8422 && !RTDirExists(pszDumpDir))
8423 {
8424 /*
8425 * Try create the directory.
8426 */
8427 vrc = RTDirCreateFullPath(pszDumpDir, 0700);
8428 if (RT_FAILURE(vrc))
8429 throw setErrorBoth(E_FAIL, vrc, tr("Failed to setup CoreDumper. Couldn't create dump directory '%s' (%Rrc)"),
8430 pszDumpDir, vrc);
8431 }
8432
8433 vrc = RTCoreDumperSetup(pszDumpDir, fCoreFlags);
8434 if (RT_FAILURE(vrc))
8435 throw setErrorBoth(E_FAIL, vrc, tr("Failed to setup CoreDumper (%Rrc)"), vrc);
8436 LogRel(("CoreDumper setup successful. pszDumpDir=%s fFlags=%#x\n", pszDumpDir ? pszDumpDir : ".", fCoreFlags));
8437 }
8438#endif
8439
8440
8441 // If there is immutable drive the process that.
8442 VMPowerUpTask::ProgressList progresses(task->hardDiskProgresses);
8443 if (aProgress && !progresses.empty())
8444 {
8445 for (VMPowerUpTask::ProgressList::const_iterator it = progresses.begin(); it != progresses.end(); ++it)
8446 {
8447 ++cOperations;
8448 ulTotalOperationsWeight += 1;
8449 }
8450 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
8451 progressDesc.raw(),
8452 TRUE, // Cancelable
8453 cOperations,
8454 ulTotalOperationsWeight,
8455 tr("Starting Hard Disk operations"),
8456 1);
8457 AssertComRCReturnRC(rc);
8458 }
8459 else if ( mMachineState == MachineState_Saved
8460 || mMachineState == MachineState_AbortedSaved
8461 || !fTeleporterEnabled)
8462 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
8463 progressDesc.raw(),
8464 FALSE /* aCancelable */);
8465 else if (fTeleporterEnabled)
8466 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
8467 progressDesc.raw(),
8468 TRUE /* aCancelable */,
8469 3 /* cOperations */,
8470 10 /* ulTotalOperationsWeight */,
8471 tr("Teleporting virtual machine"),
8472 1 /* ulFirstOperationWeight */);
8473
8474 if (FAILED(rc))
8475 throw rc;
8476
8477 /* Tell VBoxSVC and Machine about the progress object so they can
8478 combine/proxy it to any openRemoteSession caller. */
8479 LogFlowThisFunc(("Calling BeginPowerUp...\n"));
8480 rc = mControl->BeginPowerUp(pPowerupProgress);
8481 if (FAILED(rc))
8482 {
8483 LogFlowThisFunc(("BeginPowerUp failed\n"));
8484 throw rc;
8485 }
8486 fBeganPoweringUp = true;
8487
8488 LogFlowThisFunc(("Checking if canceled...\n"));
8489 BOOL fCanceled;
8490 rc = pPowerupProgress->COMGETTER(Canceled)(&fCanceled);
8491 if (FAILED(rc))
8492 throw rc;
8493
8494 if (fCanceled)
8495 {
8496 LogFlowThisFunc(("Canceled in BeginPowerUp\n"));
8497 throw setError(E_FAIL, tr("Powerup was canceled"));
8498 }
8499 LogFlowThisFunc(("Not canceled yet.\n"));
8500
8501 /** @todo this code prevents starting a VM with unavailable bridged
8502 * networking interface. The only benefit is a slightly better error
8503 * message, which should be moved to the driver code. This is the
8504 * only reason why I left the code in for now. The driver allows
8505 * unavailable bridged networking interfaces in certain circumstances,
8506 * and this is sabotaged by this check. The VM will initially have no
8507 * network connectivity, but the user can fix this at runtime. */
8508#if 0
8509 /* the network cards will undergo a quick consistency check */
8510 for (ULONG slot = 0;
8511 slot < maxNetworkAdapters;
8512 ++slot)
8513 {
8514 ComPtr<INetworkAdapter> pNetworkAdapter;
8515 mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
8516 BOOL enabled = FALSE;
8517 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
8518 if (!enabled)
8519 continue;
8520
8521 NetworkAttachmentType_T netattach;
8522 pNetworkAdapter->COMGETTER(AttachmentType)(&netattach);
8523 switch (netattach)
8524 {
8525 case NetworkAttachmentType_Bridged:
8526 {
8527 /* a valid host interface must have been set */
8528 Bstr hostif;
8529 pNetworkAdapter->COMGETTER(HostInterface)(hostif.asOutParam());
8530 if (hostif.isEmpty())
8531 {
8532 throw setError(VBOX_E_HOST_ERROR,
8533 tr("VM cannot start because host interface networking requires a host interface name to be set"));
8534 }
8535 ComPtr<IVirtualBox> pVirtualBox;
8536 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
8537 ComPtr<IHost> pHost;
8538 pVirtualBox->COMGETTER(Host)(pHost.asOutParam());
8539 ComPtr<IHostNetworkInterface> pHostInterface;
8540 if (!SUCCEEDED(pHost->FindHostNetworkInterfaceByName(hostif.raw(), pHostInterface.asOutParam())))
8541 throw setError(VBOX_E_HOST_ERROR,
8542 tr("VM cannot start because the host interface '%ls' does not exist"), hostif.raw());
8543 break;
8544 }
8545 default:
8546 break;
8547 }
8548 }
8549#endif // 0
8550
8551
8552 /* setup task object and thread to carry out the operation
8553 * asynchronously */
8554 if (aProgress)
8555 {
8556 rc = pPowerupProgress.queryInterfaceTo(aProgress);
8557 AssertComRCReturnRC(rc);
8558 }
8559
8560#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
8561 task->mKeyStore = Utf8Str(bstrStateKeyStore);
8562 task->mKeyId = Utf8Str(bstrStateKeyId);
8563 task->m_pKeyStore = m_pKeyStore;
8564#endif
8565
8566 rc = task->createThread();
8567 task = NULL;
8568 if (FAILED(rc))
8569 throw rc;
8570
8571 /* finally, set the state: no right to fail in this method afterwards
8572 * since we've already started the thread and it is now responsible for
8573 * any error reporting and appropriate state change! */
8574 if (mMachineState == MachineState_Saved || mMachineState == MachineState_AbortedSaved)
8575 i_setMachineState(MachineState_Restoring);
8576 else if (fTeleporterEnabled)
8577 i_setMachineState(MachineState_TeleportingIn);
8578 else
8579 i_setMachineState(MachineState_Starting);
8580 }
8581 catch (HRESULT aRC)
8582 {
8583 rc = aRC;
8584 }
8585
8586 if (FAILED(rc) && fBeganPoweringUp)
8587 {
8588
8589 /* The progress object will fetch the current error info */
8590 if (!pPowerupProgress.isNull())
8591 pPowerupProgress->i_notifyComplete(rc);
8592
8593 /* Save the error info across the IPC below. Can't be done before the
8594 * progress notification above, as saving the error info deletes it
8595 * from the current context, and thus the progress object wouldn't be
8596 * updated correctly. */
8597 ErrorInfoKeeper eik;
8598
8599 /* signal end of operation */
8600 mControl->EndPowerUp(rc);
8601 }
8602
8603 if (task)
8604 {
8605 ErrorInfoKeeper eik;
8606 delete task;
8607 }
8608
8609 LogFlowThisFunc(("mMachineState=%d, rc=%Rhrc\n", mMachineState, rc));
8610 LogFlowThisFuncLeave();
8611 return rc;
8612}
8613
8614/**
8615 * Internal power off worker routine.
8616 *
8617 * This method may be called only at certain places with the following meaning
8618 * as shown below:
8619 *
8620 * - if the machine state is either Running or Paused, a normal
8621 * Console-initiated powerdown takes place (e.g. PowerDown());
8622 * - if the machine state is Saving, saveStateThread() has successfully done its
8623 * job;
8624 * - if the machine state is Starting or Restoring, powerUpThread() has failed
8625 * to start/load the VM;
8626 * - if the machine state is Stopping, the VM has powered itself off (i.e. not
8627 * as a result of the powerDown() call).
8628 *
8629 * Calling it in situations other than the above will cause unexpected behavior.
8630 *
8631 * Note that this method should be the only one that destroys mpUVM and sets it
8632 * to NULL.
8633 *
8634 * @param aProgress Progress object to run (may be NULL).
8635 *
8636 * @note Locks this object for writing.
8637 *
8638 * @note Never call this method from a thread that called addVMCaller() or
8639 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
8640 * release(). Otherwise it will deadlock.
8641 */
8642HRESULT Console::i_powerDown(IProgress *aProgress /*= NULL*/)
8643{
8644 LogFlowThisFuncEnter();
8645
8646 AutoCaller autoCaller(this);
8647 AssertComRCReturnRC(autoCaller.rc());
8648
8649 ComPtr<IInternalProgressControl> pProgressControl(aProgress);
8650
8651 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8652
8653 /* Total # of steps for the progress object. Must correspond to the
8654 * number of "advance percent count" comments in this method! */
8655 enum { StepCount = 7 };
8656 /* current step */
8657 ULONG step = 0;
8658
8659 HRESULT rc = S_OK;
8660 int vrc = VINF_SUCCESS;
8661
8662 /* sanity */
8663 Assert(mVMDestroying == false);
8664
8665 PCVMMR3VTABLE const pVMM = mpVMM;
8666 AssertPtrReturn(pVMM, E_UNEXPECTED);
8667 PUVM pUVM = mpUVM;
8668 AssertPtrReturn(pUVM, E_UNEXPECTED);
8669
8670 uint32_t cRefs = pVMM->pfnVMR3RetainUVM(pUVM);
8671 Assert(cRefs != UINT32_MAX); NOREF(cRefs);
8672
8673 AssertMsg( mMachineState == MachineState_Running
8674 || mMachineState == MachineState_Paused
8675 || mMachineState == MachineState_Stuck
8676 || mMachineState == MachineState_Starting
8677 || mMachineState == MachineState_Stopping
8678 || mMachineState == MachineState_Saving
8679 || mMachineState == MachineState_Restoring
8680 || mMachineState == MachineState_TeleportingPausedVM
8681 || mMachineState == MachineState_TeleportingIn
8682 , ("Invalid machine state: %s\n", ::stringifyMachineState(mMachineState)));
8683
8684 LogRel(("Console::powerDown(): A request to power off the VM has been issued (mMachineState=%s, InUninit=%d)\n",
8685 ::stringifyMachineState(mMachineState), getObjectState().getState() == ObjectState::InUninit));
8686
8687 /* Check if we need to power off the VM. In case of mVMPoweredOff=true, the
8688 * VM has already powered itself off in vmstateChangeCallback() and is just
8689 * notifying Console about that. In case of Starting or Restoring,
8690 * powerUpThread() is calling us on failure, so the VM is already off at
8691 * that point. */
8692 if ( !mVMPoweredOff
8693 && ( mMachineState == MachineState_Starting
8694 || mMachineState == MachineState_Restoring
8695 || mMachineState == MachineState_TeleportingIn)
8696 )
8697 mVMPoweredOff = true;
8698
8699 /*
8700 * Go to Stopping state if not already there.
8701 *
8702 * Note that we don't go from Saving/Restoring to Stopping because
8703 * vmstateChangeCallback() needs it to set the state to Saved on
8704 * VMSTATE_TERMINATED. In terms of protecting from inappropriate operations
8705 * while leaving the lock below, Saving or Restoring should be fine too.
8706 * Ditto for TeleportingPausedVM -> Teleported.
8707 */
8708 if ( mMachineState != MachineState_Saving
8709 && mMachineState != MachineState_Restoring
8710 && mMachineState != MachineState_Stopping
8711 && mMachineState != MachineState_TeleportingIn
8712 && mMachineState != MachineState_TeleportingPausedVM
8713 )
8714 i_setMachineState(MachineState_Stopping);
8715
8716 /* ----------------------------------------------------------------------
8717 * DONE with necessary state changes, perform the power down actions (it's
8718 * safe to release the object lock now if needed)
8719 * ---------------------------------------------------------------------- */
8720
8721 if (mDisplay)
8722 {
8723 alock.release();
8724
8725 mDisplay->i_notifyPowerDown();
8726
8727 alock.acquire();
8728 }
8729
8730 /* Stop the VRDP server to prevent new clients connection while VM is being
8731 * powered off. */
8732 if (mConsoleVRDPServer)
8733 {
8734 LogFlowThisFunc(("Stopping VRDP server...\n"));
8735
8736 /* Leave the lock since EMT could call us back as addVMCaller() */
8737 alock.release();
8738
8739 mConsoleVRDPServer->Stop();
8740
8741 alock.acquire();
8742 }
8743
8744 /* advance percent count */
8745 if (pProgressControl)
8746 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8747
8748
8749 /* ----------------------------------------------------------------------
8750 * Now, wait for all mpUVM callers to finish their work if there are still
8751 * some on other threads. NO methods that need mpUVM (or initiate other calls
8752 * that need it) may be called after this point
8753 * ---------------------------------------------------------------------- */
8754
8755 /* go to the destroying state to prevent from adding new callers */
8756 mVMDestroying = true;
8757
8758 if (mVMCallers > 0)
8759 {
8760 /* lazy creation */
8761 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
8762 RTSemEventCreate(&mVMZeroCallersSem);
8763
8764 LogFlowThisFunc(("Waiting for mpUVM callers (%d) to drop to zero...\n", mVMCallers));
8765
8766 alock.release();
8767
8768 RTSemEventWait(mVMZeroCallersSem, RT_INDEFINITE_WAIT);
8769
8770 alock.acquire();
8771 }
8772
8773 /* advance percent count */
8774 if (pProgressControl)
8775 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8776
8777 vrc = VINF_SUCCESS;
8778
8779 /*
8780 * Power off the VM if not already done that.
8781 * Leave the lock since EMT will call vmstateChangeCallback.
8782 *
8783 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
8784 * VM-(guest-)initiated power off happened in parallel a ms before this
8785 * call. So far, we let this error pop up on the user's side.
8786 */
8787 if (!mVMPoweredOff)
8788 {
8789 LogFlowThisFunc(("Powering off the VM...\n"));
8790 alock.release();
8791 vrc = pVMM->pfnVMR3PowerOff(pUVM);
8792#ifdef VBOX_WITH_EXTPACK
8793 mptrExtPackManager->i_callAllVmPowerOffHooks(this, pVMM->pfnVMR3GetVM(pUVM), pVMM);
8794#endif
8795 alock.acquire();
8796 }
8797
8798 /* advance percent count */
8799 if (pProgressControl)
8800 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8801
8802#ifdef VBOX_WITH_HGCM
8803 /* Shutdown HGCM services before destroying the VM. */
8804 if (m_pVMMDev)
8805 {
8806 LogFlowThisFunc(("Shutdown HGCM...\n"));
8807
8808 /* Leave the lock since EMT might wait for it and will call us back as addVMCaller() */
8809 alock.release();
8810
8811# ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
8812 /** @todo Deregister area callbacks? */
8813# endif
8814# ifdef VBOX_WITH_DRAG_AND_DROP
8815 if (m_hHgcmSvcExtDragAndDrop)
8816 {
8817 HGCMHostUnregisterServiceExtension(m_hHgcmSvcExtDragAndDrop);
8818 m_hHgcmSvcExtDragAndDrop = NULL;
8819 }
8820# endif
8821
8822 m_pVMMDev->hgcmShutdown();
8823
8824 alock.acquire();
8825 }
8826
8827 /* advance percent count */
8828 if (pProgressControl)
8829 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8830
8831#endif /* VBOX_WITH_HGCM */
8832
8833 LogFlowThisFunc(("Ready for VM destruction.\n"));
8834
8835 /* If we are called from Console::uninit(), then try to destroy the VM even
8836 * on failure (this will most likely fail too, but what to do?..) */
8837 if (RT_SUCCESS(vrc) || getObjectState().getState() == ObjectState::InUninit)
8838 {
8839 /* If the machine has a USB controller, release all USB devices
8840 * (symmetric to the code in captureUSBDevices()) */
8841 if (mfVMHasUsbController)
8842 {
8843 alock.release();
8844 i_detachAllUSBDevices(false /* aDone */);
8845 alock.acquire();
8846 }
8847
8848 /* Now we've got to destroy the VM as well. (mpUVM is not valid beyond
8849 * this point). We release the lock before calling VMR3Destroy() because
8850 * it will result into calling destructors of drivers associated with
8851 * Console children which may in turn try to lock Console (e.g. by
8852 * instantiating SafeVMPtr to access mpUVM). It's safe here because
8853 * mVMDestroying is set which should prevent any activity. */
8854
8855 /* Set mpUVM to NULL early just in case if some old code is not using
8856 * addVMCaller()/releaseVMCaller(). (We have our own ref on pUVM.) */
8857 pVMM->pfnVMR3ReleaseUVM(mpUVM);
8858 mpUVM = NULL;
8859
8860 LogFlowThisFunc(("Destroying the VM...\n"));
8861
8862 alock.release();
8863
8864 vrc = pVMM->pfnVMR3Destroy(pUVM);
8865
8866 /* take the lock again */
8867 alock.acquire();
8868
8869 /* advance percent count */
8870 if (pProgressControl)
8871 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8872
8873 if (RT_SUCCESS(vrc))
8874 {
8875 LogFlowThisFunc(("Machine has been destroyed (mMachineState=%d)\n",
8876 mMachineState));
8877 /* Note: the Console-level machine state change happens on the
8878 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
8879 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
8880 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
8881 * occurred yet. This is okay, because mMachineState is already
8882 * Stopping in this case, so any other attempt to call PowerDown()
8883 * will be rejected. */
8884 }
8885 else
8886 {
8887 /* bad bad bad, but what to do? (Give Console our UVM ref.) */
8888 mpUVM = pUVM;
8889 pUVM = NULL;
8890 rc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not destroy the machine. (Error: %Rrc)"), vrc);
8891 }
8892
8893 /* Complete the detaching of the USB devices. */
8894 if (mfVMHasUsbController)
8895 {
8896 alock.release();
8897 i_detachAllUSBDevices(true /* aDone */);
8898 alock.acquire();
8899 }
8900
8901 /* advance percent count */
8902 if (pProgressControl)
8903 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8904 }
8905 else
8906 rc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not power off the machine. (Error: %Rrc)"), vrc);
8907
8908 /*
8909 * Finished with the destruction.
8910 *
8911 * Note that if something impossible happened and we've failed to destroy
8912 * the VM, mVMDestroying will remain true and mMachineState will be
8913 * something like Stopping, so most Console methods will return an error
8914 * to the caller.
8915 */
8916 if (pUVM != NULL)
8917 pVMM->pfnVMR3ReleaseUVM(pUVM);
8918 else
8919 mVMDestroying = false;
8920
8921 LogFlowThisFuncLeave();
8922 return rc;
8923}
8924
8925/**
8926 * @note Locks this object for writing.
8927 */
8928HRESULT Console::i_setMachineState(MachineState_T aMachineState, bool aUpdateServer /* = true */)
8929{
8930 AutoCaller autoCaller(this);
8931 AssertComRCReturnRC(autoCaller.rc());
8932
8933 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8934
8935 HRESULT rc = S_OK;
8936
8937 if (mMachineState != aMachineState)
8938 {
8939 LogThisFunc(("machineState=%s -> %s aUpdateServer=%RTbool\n",
8940 ::stringifyMachineState(mMachineState), ::stringifyMachineState(aMachineState), aUpdateServer));
8941 LogRel(("Console: Machine state changed to '%s'\n", ::stringifyMachineState(aMachineState)));
8942 mMachineState = aMachineState;
8943
8944 /// @todo (dmik)
8945 // possibly, we need to redo onStateChange() using the dedicated
8946 // Event thread, like it is done in VirtualBox. This will make it
8947 // much safer (no deadlocks possible if someone tries to use the
8948 // console from the callback), however, listeners will lose the
8949 // ability to synchronously react to state changes (is it really
8950 // necessary??)
8951 LogFlowThisFunc(("Doing onStateChange()...\n"));
8952 i_onStateChange(aMachineState);
8953 LogFlowThisFunc(("Done onStateChange()\n"));
8954
8955 if (aUpdateServer)
8956 {
8957 /* Server notification MUST be done from under the lock; otherwise
8958 * the machine state here and on the server might go out of sync
8959 * which can lead to various unexpected results (like the machine
8960 * state being >= MachineState_Running on the server, while the
8961 * session state is already SessionState_Unlocked at the same time
8962 * there).
8963 *
8964 * Cross-lock conditions should be carefully watched out: calling
8965 * UpdateState we will require Machine and SessionMachine locks
8966 * (remember that here we're holding the Console lock here, and also
8967 * all locks that have been acquire by the thread before calling
8968 * this method).
8969 */
8970 LogFlowThisFunc(("Doing mControl->UpdateState()...\n"));
8971 rc = mControl->UpdateState(aMachineState);
8972 LogFlowThisFunc(("mControl->UpdateState()=%Rhrc\n", rc));
8973 }
8974 }
8975
8976 return rc;
8977}
8978
8979/**
8980 * Searches for a shared folder with the given logical name
8981 * in the collection of shared folders.
8982 *
8983 * @param strName logical name of the shared folder
8984 * @param aSharedFolder where to return the found object
8985 * @param aSetError whether to set the error info if the folder is
8986 * not found
8987 * @return
8988 * S_OK when found or E_INVALIDARG when not found
8989 *
8990 * @note The caller must lock this object for writing.
8991 */
8992HRESULT Console::i_findSharedFolder(const Utf8Str &strName, ComObjPtr<SharedFolder> &aSharedFolder, bool aSetError /* = false */)
8993{
8994 /* sanity check */
8995 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8996
8997 SharedFolderMap::const_iterator it = m_mapSharedFolders.find(strName);
8998 if (it != m_mapSharedFolders.end())
8999 {
9000 aSharedFolder = it->second;
9001 return S_OK;
9002 }
9003
9004 if (aSetError)
9005 setError(VBOX_E_FILE_ERROR, tr("Could not find a shared folder named '%s'."), strName.c_str());
9006 return VBOX_E_FILE_ERROR;
9007}
9008
9009/**
9010 * Fetches the list of global or machine shared folders from the server.
9011 *
9012 * @param aGlobal true to fetch global folders.
9013 *
9014 * @note The caller must lock this object for writing.
9015 */
9016HRESULT Console::i_fetchSharedFolders(BOOL aGlobal)
9017{
9018 /* sanity check */
9019 AssertReturn( getObjectState().getState() == ObjectState::InInit
9020 || isWriteLockOnCurrentThread(), E_FAIL);
9021
9022 LogFlowThisFunc(("Entering\n"));
9023
9024 /* Check if we're online and keep it that way. */
9025 SafeVMPtrQuiet ptrVM(this);
9026 AutoVMCallerQuietWeak autoVMCaller(this);
9027 bool const online = ptrVM.isOk()
9028 && m_pVMMDev
9029 && m_pVMMDev->isShFlActive();
9030
9031 HRESULT rc = S_OK;
9032
9033 try
9034 {
9035 if (aGlobal)
9036 {
9037 /// @todo grab & process global folders when they are done
9038 }
9039 else
9040 {
9041 SharedFolderDataMap oldFolders;
9042 if (online)
9043 oldFolders = m_mapMachineSharedFolders;
9044
9045 m_mapMachineSharedFolders.clear();
9046
9047 SafeIfaceArray<ISharedFolder> folders;
9048 rc = mMachine->COMGETTER(SharedFolders)(ComSafeArrayAsOutParam(folders));
9049 if (FAILED(rc)) throw rc;
9050
9051 for (size_t i = 0; i < folders.size(); ++i)
9052 {
9053 ComPtr<ISharedFolder> pSharedFolder = folders[i];
9054
9055 Bstr bstr;
9056 rc = pSharedFolder->COMGETTER(Name)(bstr.asOutParam());
9057 if (FAILED(rc)) throw rc;
9058 Utf8Str strName(bstr);
9059
9060 rc = pSharedFolder->COMGETTER(HostPath)(bstr.asOutParam());
9061 if (FAILED(rc)) throw rc;
9062 Utf8Str strHostPath(bstr);
9063
9064 BOOL writable;
9065 rc = pSharedFolder->COMGETTER(Writable)(&writable);
9066 if (FAILED(rc)) throw rc;
9067
9068 BOOL autoMount;
9069 rc = pSharedFolder->COMGETTER(AutoMount)(&autoMount);
9070 if (FAILED(rc)) throw rc;
9071
9072 rc = pSharedFolder->COMGETTER(AutoMountPoint)(bstr.asOutParam());
9073 if (FAILED(rc)) throw rc;
9074 Utf8Str strAutoMountPoint(bstr);
9075
9076 m_mapMachineSharedFolders.insert(std::make_pair(strName,
9077 SharedFolderData(strHostPath, !!writable,
9078 !!autoMount, strAutoMountPoint)));
9079
9080 /* send changes to HGCM if the VM is running */
9081 if (online)
9082 {
9083 SharedFolderDataMap::iterator it = oldFolders.find(strName);
9084 if ( it == oldFolders.end()
9085 || it->second.m_strHostPath != strHostPath)
9086 {
9087 /* a new machine folder is added or
9088 * the existing machine folder is changed */
9089 if (m_mapSharedFolders.find(strName) != m_mapSharedFolders.end())
9090 ; /* the console folder exists, nothing to do */
9091 else
9092 {
9093 /* remove the old machine folder (when changed)
9094 * or the global folder if any (when new) */
9095 if ( it != oldFolders.end()
9096 || m_mapGlobalSharedFolders.find(strName) != m_mapGlobalSharedFolders.end()
9097 )
9098 {
9099 rc = i_removeSharedFolder(strName);
9100 if (FAILED(rc)) throw rc;
9101 }
9102
9103 /* create the new machine folder */
9104 rc = i_createSharedFolder(strName,
9105 SharedFolderData(strHostPath, !!writable, !!autoMount, strAutoMountPoint));
9106 if (FAILED(rc)) throw rc;
9107 }
9108 }
9109 /* forget the processed (or identical) folder */
9110 if (it != oldFolders.end())
9111 oldFolders.erase(it);
9112 }
9113 }
9114
9115 /* process outdated (removed) folders */
9116 if (online)
9117 {
9118 for (SharedFolderDataMap::const_iterator it = oldFolders.begin();
9119 it != oldFolders.end(); ++it)
9120 {
9121 if (m_mapSharedFolders.find(it->first) != m_mapSharedFolders.end())
9122 ; /* the console folder exists, nothing to do */
9123 else
9124 {
9125 /* remove the outdated machine folder */
9126 rc = i_removeSharedFolder(it->first);
9127 if (FAILED(rc)) throw rc;
9128
9129 /* create the global folder if there is any */
9130 SharedFolderDataMap::const_iterator git =
9131 m_mapGlobalSharedFolders.find(it->first);
9132 if (git != m_mapGlobalSharedFolders.end())
9133 {
9134 rc = i_createSharedFolder(git->first, git->second);
9135 if (FAILED(rc)) throw rc;
9136 }
9137 }
9138 }
9139 }
9140 }
9141 }
9142 catch (HRESULT rc2)
9143 {
9144 rc = rc2;
9145 if (online)
9146 i_atVMRuntimeErrorCallbackF(0, "BrokenSharedFolder", N_("Broken shared folder!"));
9147 }
9148
9149 LogFlowThisFunc(("Leaving\n"));
9150
9151 return rc;
9152}
9153
9154/**
9155 * Searches for a shared folder with the given name in the list of machine
9156 * shared folders and then in the list of the global shared folders.
9157 *
9158 * @param strName Name of the folder to search for.
9159 * @param aIt Where to store the pointer to the found folder.
9160 * @return @c true if the folder was found and @c false otherwise.
9161 *
9162 * @note The caller must lock this object for reading.
9163 */
9164bool Console::i_findOtherSharedFolder(const Utf8Str &strName,
9165 SharedFolderDataMap::const_iterator &aIt)
9166{
9167 /* sanity check */
9168 AssertReturn(isWriteLockOnCurrentThread(), false);
9169
9170 /* first, search machine folders */
9171 aIt = m_mapMachineSharedFolders.find(strName);
9172 if (aIt != m_mapMachineSharedFolders.end())
9173 return true;
9174
9175 /* second, search machine folders */
9176 aIt = m_mapGlobalSharedFolders.find(strName);
9177 if (aIt != m_mapGlobalSharedFolders.end())
9178 return true;
9179
9180 return false;
9181}
9182
9183/**
9184 * Calls the HGCM service to add a shared folder definition.
9185 *
9186 * @param strName Shared folder name.
9187 * @param aData Shared folder data.
9188 *
9189 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
9190 * @note Doesn't lock anything.
9191 */
9192HRESULT Console::i_createSharedFolder(const Utf8Str &strName, const SharedFolderData &aData)
9193{
9194 Log(("Adding shared folder '%s' -> '%s'\n", strName.c_str(), aData.m_strHostPath.c_str()));
9195
9196 /*
9197 * Sanity checks
9198 */
9199 ComAssertRet(strName.isNotEmpty(), E_FAIL);
9200 ComAssertRet(aData.m_strHostPath.isNotEmpty(), E_FAIL);
9201
9202 AssertReturn(mpUVM, E_FAIL);
9203 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
9204
9205 /*
9206 * Find out whether we should allow symbolic link creation.
9207 */
9208 Bstr bstrValue;
9209 HRESULT hrc = mMachine->GetExtraData(BstrFmt("VBoxInternal2/SharedFoldersEnableSymlinksCreate/%s", strName.c_str()).raw(),
9210 bstrValue.asOutParam());
9211 bool fSymlinksCreate = hrc == S_OK && bstrValue == "1";
9212
9213 /*
9214 * Check whether the path is valid and exists.
9215 */
9216 char szAbsHostPath[RTPATH_MAX];
9217 int vrc = RTPathAbs(aData.m_strHostPath.c_str(), szAbsHostPath, sizeof(szAbsHostPath));
9218 if (RT_FAILURE(vrc))
9219 return setErrorBoth(E_INVALIDARG, vrc, tr("Invalid shared folder path: '%s' (%Rrc)"), aData.m_strHostPath.c_str(), vrc);
9220
9221 /* Check whether the path is full (absolute). ASSUMING a RTPATH_MAX of ~4K
9222 this also checks that the length is within bounds of a SHFLSTRING. */
9223 if (RTPathCompare(aData.m_strHostPath.c_str(), szAbsHostPath) != 0)
9224 return setError(E_INVALIDARG, tr("Shared folder path '%s' is not absolute"), aData.m_strHostPath.c_str());
9225
9226 bool const fMissing = !RTPathExists(szAbsHostPath);
9227
9228 /*
9229 * Check the other two string lengths before converting them all to SHFLSTRINGS.
9230 */
9231 if (strName.length() >= _2K)
9232 return setError(E_INVALIDARG, tr("Shared folder name is too long: %zu bytes", "", strName.length()), strName.length());
9233 if (aData.m_strAutoMountPoint.length() >= RTPATH_MAX)
9234 return setError(E_INVALIDARG, tr("Shared folder mount point too long: %zu bytes", "",
9235 (int)aData.m_strAutoMountPoint.length()),
9236 aData.m_strAutoMountPoint.length());
9237
9238 PSHFLSTRING pHostPath = ShflStringDupUtf8AsUtf16(aData.m_strHostPath.c_str());
9239 PSHFLSTRING pName = ShflStringDupUtf8AsUtf16(strName.c_str());
9240 PSHFLSTRING pAutoMountPoint = ShflStringDupUtf8AsUtf16(aData.m_strAutoMountPoint.c_str());
9241 if (pHostPath && pName && pAutoMountPoint)
9242 {
9243 /*
9244 * Make a SHFL_FN_ADD_MAPPING call to tell the service about folder.
9245 */
9246 VBOXHGCMSVCPARM aParams[SHFL_CPARMS_ADD_MAPPING];
9247 SHFLSTRING_TO_HGMC_PARAM(&aParams[0], pHostPath);
9248 SHFLSTRING_TO_HGMC_PARAM(&aParams[1], pName);
9249 HGCMSvcSetU32(&aParams[2],
9250 (aData.m_fWritable ? SHFL_ADD_MAPPING_F_WRITABLE : 0)
9251 | (aData.m_fAutoMount ? SHFL_ADD_MAPPING_F_AUTOMOUNT : 0)
9252 | (fSymlinksCreate ? SHFL_ADD_MAPPING_F_CREATE_SYMLINKS : 0)
9253 | (fMissing ? SHFL_ADD_MAPPING_F_MISSING : 0));
9254 SHFLSTRING_TO_HGMC_PARAM(&aParams[3], pAutoMountPoint);
9255 AssertCompile(SHFL_CPARMS_ADD_MAPPING == 4);
9256
9257 vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders", SHFL_FN_ADD_MAPPING, SHFL_CPARMS_ADD_MAPPING, aParams);
9258 if (RT_FAILURE(vrc))
9259 hrc = setErrorBoth(E_FAIL, vrc, tr("Could not create a shared folder '%s' mapped to '%s' (%Rrc)"),
9260 strName.c_str(), aData.m_strHostPath.c_str(), vrc);
9261
9262 else if (fMissing)
9263 hrc = setError(E_INVALIDARG, tr("Shared folder path '%s' does not exist on the host"), aData.m_strHostPath.c_str());
9264 else
9265 hrc = S_OK;
9266 }
9267 else
9268 hrc = E_OUTOFMEMORY;
9269 RTMemFree(pAutoMountPoint);
9270 RTMemFree(pName);
9271 RTMemFree(pHostPath);
9272 return hrc;
9273}
9274
9275/**
9276 * Calls the HGCM service to remove the shared folder definition.
9277 *
9278 * @param strName Shared folder name.
9279 *
9280 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
9281 * @note Doesn't lock anything.
9282 */
9283HRESULT Console::i_removeSharedFolder(const Utf8Str &strName)
9284{
9285 ComAssertRet(strName.isNotEmpty(), E_FAIL);
9286
9287 /* sanity checks */
9288 AssertReturn(mpUVM, E_FAIL);
9289 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
9290
9291 VBOXHGCMSVCPARM parms;
9292 SHFLSTRING *pMapName;
9293 size_t cbString;
9294
9295 Log(("Removing shared folder '%s'\n", strName.c_str()));
9296
9297 Bstr bstrName(strName);
9298 cbString = (bstrName.length() + 1) * sizeof(RTUTF16);
9299 if (cbString >= UINT16_MAX)
9300 return setError(E_INVALIDARG, tr("The name is too long"));
9301 pMapName = (SHFLSTRING *) RTMemAllocZ(SHFLSTRING_HEADER_SIZE + cbString);
9302 Assert(pMapName);
9303 memcpy(pMapName->String.ucs2, bstrName.raw(), cbString);
9304
9305 pMapName->u16Size = (uint16_t)cbString;
9306 pMapName->u16Length = (uint16_t)(cbString - sizeof(RTUTF16));
9307
9308 parms.type = VBOX_HGCM_SVC_PARM_PTR;
9309 parms.u.pointer.addr = pMapName;
9310 parms.u.pointer.size = ShflStringSizeOfBuffer(pMapName);
9311
9312 int vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders", SHFL_FN_REMOVE_MAPPING, 1, &parms);
9313 RTMemFree(pMapName);
9314 if (RT_FAILURE(vrc))
9315 return setErrorBoth(E_FAIL, vrc, tr("Could not remove the shared folder '%s' (%Rrc)"), strName.c_str(), vrc);
9316
9317 return S_OK;
9318}
9319
9320/**
9321 * Retains a reference to the default cryptographic interface.
9322 *
9323 * @returns VBox status code.
9324 * @retval VERR_NOT_SUPPORTED if the VM is not configured for encryption.
9325 * @param ppCryptoIf Where to store the pointer to the cryptographic interface on success.
9326 *
9327 * @note Locks this object for writing.
9328 */
9329int Console::i_retainCryptoIf(PCVBOXCRYPTOIF *ppCryptoIf)
9330{
9331 AssertReturn(ppCryptoIf != NULL, VERR_INVALID_PARAMETER);
9332
9333 int vrc = VINF_SUCCESS;
9334 if (mhLdrModCrypto == NIL_RTLDRMOD)
9335 {
9336#ifdef VBOX_WITH_EXTPACK
9337 /*
9338 * Check that a crypto extension pack name is set and resolve it into a
9339 * library path.
9340 */
9341 HRESULT hrc = S_OK;
9342 Bstr bstrExtPack;
9343
9344 ComPtr<IVirtualBox> pVirtualBox;
9345 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
9346 ComPtr<ISystemProperties> pSystemProperties;
9347 if (pVirtualBox)
9348 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
9349 if (pSystemProperties)
9350 pSystemProperties->COMGETTER(DefaultCryptoExtPack)(bstrExtPack.asOutParam());
9351 if (FAILED(hrc))
9352 return hrc;
9353
9354 Utf8Str strExtPack(bstrExtPack);
9355 if (strExtPack.isEmpty())
9356 {
9357 setError(VBOX_E_OBJECT_NOT_FOUND,
9358 tr("Ńo extension pack providing a cryptographic support module could be found"));
9359 return VERR_NOT_FOUND;
9360 }
9361
9362 Utf8Str strCryptoLibrary;
9363 vrc = mptrExtPackManager->i_getCryptoLibraryPathForExtPack(&strExtPack, &strCryptoLibrary);
9364 if (RT_SUCCESS(vrc))
9365 {
9366 RTERRINFOSTATIC ErrInfo;
9367 vrc = SUPR3HardenedLdrLoadPlugIn(strCryptoLibrary.c_str(), &mhLdrModCrypto, RTErrInfoInitStatic(&ErrInfo));
9368 if (RT_SUCCESS(vrc))
9369 {
9370 /* Resolve the entry point and query the pointer to the cryptographic interface. */
9371 PFNVBOXCRYPTOENTRY pfnCryptoEntry = NULL;
9372 vrc = RTLdrGetSymbol(mhLdrModCrypto, VBOX_CRYPTO_MOD_ENTRY_POINT, (void **)&pfnCryptoEntry);
9373 if (RT_SUCCESS(vrc))
9374 {
9375 vrc = pfnCryptoEntry(&mpCryptoIf);
9376 if (RT_FAILURE(vrc))
9377 setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
9378 tr("Failed to query the interface callback table from the cryptographic support module '%s' from extension pack '%s'"),
9379 strCryptoLibrary.c_str(), strExtPack.c_str());
9380 }
9381 else
9382 setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
9383 tr("Failed to resolve the entry point for the cryptographic support module '%s' from extension pack '%s'"),
9384 strCryptoLibrary.c_str(), strExtPack.c_str());
9385
9386 if (RT_FAILURE(vrc))
9387 {
9388 RTLdrClose(mhLdrModCrypto);
9389 mhLdrModCrypto = NIL_RTLDRMOD;
9390 }
9391 }
9392 else
9393 setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
9394 tr("Couldn't load the cryptographic support module '%s' from extension pack '%s' (error: '%s')"),
9395 strCryptoLibrary.c_str(), strExtPack.c_str(), ErrInfo.Core.pszMsg);
9396 }
9397 else
9398 setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
9399 tr("Couldn't resolve the library path of the crpytographic support module for extension pack '%s'"),
9400 strExtPack.c_str());
9401#else
9402 setError(VBOX_E_NOT_SUPPORTED,
9403 tr("The cryptographic support module is not supported in this build because extension packs are not supported"));
9404 vrc = VERR_NOT_SUPPORTED;
9405#endif
9406 }
9407
9408 if (RT_SUCCESS(vrc))
9409 {
9410 ASMAtomicIncU32(&mcRefsCrypto);
9411 *ppCryptoIf = mpCryptoIf;
9412 }
9413
9414 return vrc;
9415}
9416
9417/**
9418 * Releases the reference of the given cryptographic interface.
9419 *
9420 * @returns VBox status code.
9421 * @param pCryptoIf Pointer to the cryptographic interface to release.
9422 *
9423 * @note Locks this object for writing.
9424 */
9425int Console::i_releaseCryptoIf(PCVBOXCRYPTOIF pCryptoIf)
9426{
9427 AssertReturn(pCryptoIf == mpCryptoIf, VERR_INVALID_PARAMETER);
9428
9429 ASMAtomicDecU32(&mcRefsCrypto);
9430 return VINF_SUCCESS;
9431}
9432
9433/**
9434 * Tries to unload any loaded cryptographic support module if it is not in use currently.
9435 *
9436 * @returns COM status code.
9437 *
9438 * @note Locks this object for writing.
9439 */
9440HRESULT Console::i_unloadCryptoIfModule(void)
9441{
9442 AutoCaller autoCaller(this);
9443 AssertComRCReturnRC(autoCaller.rc());
9444
9445 AutoWriteLock wlock(this COMMA_LOCKVAL_SRC_POS);
9446
9447 if (mcRefsCrypto)
9448 return setError(E_ACCESSDENIED,
9449 tr("The cryptographic support module is in use and can't be unloaded"));
9450
9451 if (mhLdrModCrypto != NIL_RTLDRMOD)
9452 {
9453 int vrc = RTLdrClose(mhLdrModCrypto);
9454 AssertRC(vrc);
9455 mhLdrModCrypto = NIL_RTLDRMOD;
9456 }
9457
9458 return S_OK;
9459}
9460
9461/** @callback_method_impl{FNVMATSTATE}
9462 *
9463 * @note Locks the Console object for writing.
9464 * @remarks The @a pUVM parameter can be NULL in one case where powerUpThread()
9465 * calls after the VM was destroyed.
9466 */
9467/*static*/ DECLCALLBACK(void)
9468Console::i_vmstateChangeCallback(PUVM pUVM, PCVMMR3VTABLE pVMM, VMSTATE enmState, VMSTATE enmOldState, void *pvUser)
9469{
9470 LogFlowFunc(("Changing state from %s to %s (pUVM=%p)\n",
9471 pVMM->pfnVMR3GetStateName(enmOldState), pVMM->pfnVMR3GetStateName(enmState), pUVM));
9472 RT_NOREF(pVMM);
9473
9474 Console *that = static_cast<Console *>(pvUser);
9475 AssertReturnVoid(that);
9476
9477 AutoCaller autoCaller(that);
9478
9479 /* Note that we must let this method proceed even if Console::uninit() has
9480 * been already called. In such case this VMSTATE change is a result of:
9481 * 1) powerDown() called from uninit() itself, or
9482 * 2) VM-(guest-)initiated power off. */
9483 AssertReturnVoid( autoCaller.isOk()
9484 || that->getObjectState().getState() == ObjectState::InUninit);
9485
9486 switch (enmState)
9487 {
9488 /*
9489 * The VM has terminated
9490 */
9491 case VMSTATE_OFF:
9492 {
9493#ifdef VBOX_WITH_GUEST_PROPS
9494 if (that->mfTurnResetIntoPowerOff)
9495 {
9496 Bstr strPowerOffReason;
9497
9498 if (that->mfPowerOffCausedByReset)
9499 strPowerOffReason = Bstr("Reset");
9500 else
9501 strPowerOffReason = Bstr("PowerOff");
9502
9503 that->mMachine->DeleteGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw());
9504 that->mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw(),
9505 strPowerOffReason.raw(), Bstr("RDONLYGUEST").raw());
9506 that->mMachine->SaveSettings();
9507 }
9508#endif
9509
9510 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9511
9512 if (that->mVMStateChangeCallbackDisabled)
9513 return;
9514
9515 /* Do we still think that it is running? It may happen if this is a
9516 * VM-(guest-)initiated shutdown/poweroff.
9517 */
9518 if ( that->mMachineState != MachineState_Stopping
9519 && that->mMachineState != MachineState_Saving
9520 && that->mMachineState != MachineState_Restoring
9521 && that->mMachineState != MachineState_TeleportingIn
9522 && that->mMachineState != MachineState_TeleportingPausedVM
9523 && !that->mVMIsAlreadyPoweringOff
9524 )
9525 {
9526 LogFlowFunc(("VM has powered itself off but Console still thinks it is running. Notifying.\n"));
9527
9528 /*
9529 * Prevent powerDown() from calling VMR3PowerOff() again if this was called from
9530 * the power off state change.
9531 * When called from the Reset state make sure to call VMR3PowerOff() first.
9532 */
9533 Assert(that->mVMPoweredOff == false);
9534 that->mVMPoweredOff = true;
9535
9536 /*
9537 * request a progress object from the server
9538 * (this will set the machine state to Stopping on the server
9539 * to block others from accessing this machine)
9540 */
9541 ComPtr<IProgress> pProgress;
9542 HRESULT rc = that->mControl->BeginPoweringDown(pProgress.asOutParam());
9543 AssertComRC(rc);
9544
9545 /* sync the state with the server */
9546 that->i_setMachineStateLocally(MachineState_Stopping);
9547
9548 /*
9549 * Setup task object and thread to carry out the operation
9550 * asynchronously (if we call powerDown() right here but there
9551 * is one or more mpUVM callers (added with addVMCaller()) we'll
9552 * deadlock).
9553 */
9554 VMPowerDownTask *pTask = NULL;
9555 try
9556 {
9557 pTask = new VMPowerDownTask(that, pProgress);
9558 }
9559 catch (std::bad_alloc &)
9560 {
9561 LogRelFunc(("E_OUTOFMEMORY creating VMPowerDownTask"));
9562 rc = E_OUTOFMEMORY;
9563 break;
9564 }
9565
9566 /*
9567 * If creating a task failed, this can currently mean one of
9568 * two: either Console::uninit() has been called just a ms
9569 * before (so a powerDown() call is already on the way), or
9570 * powerDown() itself is being already executed. Just do
9571 * nothing.
9572 */
9573 if (pTask->isOk())
9574 {
9575 rc = pTask->createThread();
9576 pTask = NULL;
9577 if (FAILED(rc))
9578 LogRelFunc(("Problem with creating thread for VMPowerDownTask.\n"));
9579 }
9580 else
9581 {
9582 LogFlowFunc(("Console is already being uninitialized. (%Rhrc)\n", pTask->rc()));
9583 delete pTask;
9584 pTask = NULL;
9585 rc = E_FAIL;
9586 }
9587 }
9588 break;
9589 }
9590
9591 /* The VM has been completely destroyed.
9592 *
9593 * Note: This state change can happen at two points:
9594 * 1) At the end of VMR3Destroy() if it was not called from EMT.
9595 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
9596 * called by EMT.
9597 */
9598 case VMSTATE_TERMINATED:
9599 {
9600 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9601
9602 if (that->mVMStateChangeCallbackDisabled)
9603 break;
9604
9605#ifdef VBOX_WITH_CLOUD_NET
9606 /*
9607 * We stop cloud gateway here because we may have failed to connect to it,
9608 * configure it, or establish a tunnel. We definitely do not want an orphaned
9609 * instance running in the cloud.
9610 */
9611 if (!that->mGateway.mGatewayInstanceId.isEmpty())
9612 {
9613 ComPtr<IVirtualBox> pVirtualBox;
9614 HRESULT rc = that->mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
9615 AssertComRC(rc);
9616 if (SUCCEEDED(rc) && !pVirtualBox.isNull())
9617 stopCloudGateway(pVirtualBox, that->mGateway);
9618 }
9619#endif /* VBOX_WITH_CLOUD_NET */
9620 /* Terminate host interface networking. If pUVM is NULL, we've been
9621 * manually called from powerUpThread() either before calling
9622 * VMR3Create() or after VMR3Create() failed, so no need to touch
9623 * networking.
9624 */
9625 if (pUVM)
9626 that->i_powerDownHostInterfaces();
9627
9628 /* From now on the machine is officially powered down or remains in
9629 * the Saved state.
9630 */
9631 switch (that->mMachineState)
9632 {
9633 default:
9634 AssertFailed();
9635 RT_FALL_THRU();
9636 case MachineState_Stopping:
9637 /* successfully powered down */
9638 that->i_setMachineState(MachineState_PoweredOff);
9639 break;
9640 case MachineState_Saving:
9641 /* successfully saved */
9642 that->i_setMachineState(MachineState_Saved);
9643 break;
9644 case MachineState_Starting:
9645 /* failed to start, but be patient: set back to PoweredOff
9646 * (for similarity with the below) */
9647 that->i_setMachineState(MachineState_PoweredOff);
9648 break;
9649 case MachineState_Restoring:
9650 /* failed to load the saved state file, but be patient: set
9651 * to AbortedSaved (to preserve the saved state file) */
9652 that->i_setMachineState(MachineState_AbortedSaved);
9653 break;
9654 case MachineState_TeleportingIn:
9655 /* Teleportation failed or was canceled. Back to powered off. */
9656 that->i_setMachineState(MachineState_PoweredOff);
9657 break;
9658 case MachineState_TeleportingPausedVM:
9659 /* Successfully teleported the VM. */
9660 that->i_setMachineState(MachineState_Teleported);
9661 break;
9662 }
9663 break;
9664 }
9665
9666 case VMSTATE_RESETTING:
9667 /** @todo shouldn't VMSTATE_RESETTING_LS be here? */
9668 {
9669#ifdef VBOX_WITH_GUEST_PROPS
9670 /* Do not take any read/write locks here! */
9671 that->i_guestPropertiesHandleVMReset();
9672#endif
9673 break;
9674 }
9675
9676 case VMSTATE_SOFT_RESETTING:
9677 case VMSTATE_SOFT_RESETTING_LS:
9678 /* Shouldn't do anything here! */
9679 break;
9680
9681 case VMSTATE_SUSPENDED:
9682 {
9683 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9684
9685 if (that->mVMStateChangeCallbackDisabled)
9686 break;
9687
9688 switch (that->mMachineState)
9689 {
9690 case MachineState_Teleporting:
9691 that->i_setMachineState(MachineState_TeleportingPausedVM);
9692 break;
9693
9694 case MachineState_LiveSnapshotting:
9695 that->i_setMachineState(MachineState_OnlineSnapshotting);
9696 break;
9697
9698 case MachineState_TeleportingPausedVM:
9699 case MachineState_Saving:
9700 case MachineState_Restoring:
9701 case MachineState_Stopping:
9702 case MachineState_TeleportingIn:
9703 case MachineState_OnlineSnapshotting:
9704 /* The worker thread handles the transition. */
9705 break;
9706
9707 case MachineState_Running:
9708 that->i_setMachineState(MachineState_Paused);
9709 break;
9710
9711 case MachineState_Paused:
9712 /* Nothing to do. */
9713 break;
9714
9715 default:
9716 AssertMsgFailed(("%s\n", ::stringifyMachineState(that->mMachineState)));
9717 }
9718 break;
9719 }
9720
9721 case VMSTATE_SUSPENDED_LS:
9722 case VMSTATE_SUSPENDED_EXT_LS:
9723 {
9724 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9725 if (that->mVMStateChangeCallbackDisabled)
9726 break;
9727 switch (that->mMachineState)
9728 {
9729 case MachineState_Teleporting:
9730 that->i_setMachineState(MachineState_TeleportingPausedVM);
9731 break;
9732
9733 case MachineState_LiveSnapshotting:
9734 that->i_setMachineState(MachineState_OnlineSnapshotting);
9735 break;
9736
9737 case MachineState_TeleportingPausedVM:
9738 case MachineState_Saving:
9739 /* ignore */
9740 break;
9741
9742 default:
9743 AssertMsgFailed(("%s/%s -> %s\n", ::stringifyMachineState(that->mMachineState),
9744 pVMM->pfnVMR3GetStateName(enmOldState), pVMM->pfnVMR3GetStateName(enmState) ));
9745 that->i_setMachineState(MachineState_Paused);
9746 break;
9747 }
9748 break;
9749 }
9750
9751 case VMSTATE_RUNNING:
9752 {
9753 if ( enmOldState == VMSTATE_POWERING_ON
9754 || enmOldState == VMSTATE_RESUMING)
9755 {
9756 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9757
9758 if (that->mVMStateChangeCallbackDisabled)
9759 break;
9760
9761 Assert( ( ( that->mMachineState == MachineState_Starting
9762 || that->mMachineState == MachineState_Paused)
9763 && enmOldState == VMSTATE_POWERING_ON)
9764 || ( ( that->mMachineState == MachineState_Restoring
9765 || that->mMachineState == MachineState_TeleportingIn
9766 || that->mMachineState == MachineState_Paused
9767 || that->mMachineState == MachineState_Saving
9768 )
9769 && enmOldState == VMSTATE_RESUMING));
9770
9771 that->i_setMachineState(MachineState_Running);
9772 }
9773
9774 break;
9775 }
9776
9777 case VMSTATE_RUNNING_LS:
9778 AssertMsg( that->mMachineState == MachineState_LiveSnapshotting
9779 || that->mMachineState == MachineState_Teleporting,
9780 ("%s/%s -> %s\n", ::stringifyMachineState(that->mMachineState),
9781 pVMM->pfnVMR3GetStateName(enmOldState), pVMM->pfnVMR3GetStateName(enmState) ));
9782 break;
9783
9784 case VMSTATE_FATAL_ERROR:
9785 {
9786 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9787
9788 if (that->mVMStateChangeCallbackDisabled)
9789 break;
9790
9791 /* Fatal errors are only for running VMs. */
9792 Assert(Global::IsOnline(that->mMachineState));
9793
9794 /* Note! 'Pause' is used here in want of something better. There
9795 * are currently only two places where fatal errors might be
9796 * raised, so it is not worth adding a new externally
9797 * visible state for this yet. */
9798 that->i_setMachineState(MachineState_Paused);
9799 break;
9800 }
9801
9802 case VMSTATE_GURU_MEDITATION:
9803 {
9804 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9805
9806 if (that->mVMStateChangeCallbackDisabled)
9807 break;
9808
9809 /* Guru are only for running VMs */
9810 Assert(Global::IsOnline(that->mMachineState));
9811
9812 that->i_setMachineState(MachineState_Stuck);
9813 break;
9814 }
9815
9816 case VMSTATE_CREATED:
9817 {
9818 /*
9819 * We have to set the secret key helper interface for the VD drivers to
9820 * get notified about missing keys.
9821 */
9822 that->i_initSecretKeyIfOnAllAttachments();
9823 break;
9824 }
9825
9826 default: /* shut up gcc */
9827 break;
9828 }
9829}
9830
9831/**
9832 * Changes the clipboard mode.
9833 *
9834 * @returns VBox status code.
9835 * @param aClipboardMode new clipboard mode.
9836 */
9837int Console::i_changeClipboardMode(ClipboardMode_T aClipboardMode)
9838{
9839#ifdef VBOX_WITH_SHARED_CLIPBOARD
9840 VMMDev *pVMMDev = m_pVMMDev;
9841 AssertPtrReturn(pVMMDev, VERR_INVALID_POINTER);
9842
9843 VBOXHGCMSVCPARM parm;
9844 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
9845
9846 switch (aClipboardMode)
9847 {
9848 default:
9849 case ClipboardMode_Disabled:
9850 LogRel(("Shared Clipboard: Mode: Off\n"));
9851 parm.u.uint32 = VBOX_SHCL_MODE_OFF;
9852 break;
9853 case ClipboardMode_GuestToHost:
9854 LogRel(("Shared Clipboard: Mode: Guest to Host\n"));
9855 parm.u.uint32 = VBOX_SHCL_MODE_GUEST_TO_HOST;
9856 break;
9857 case ClipboardMode_HostToGuest:
9858 LogRel(("Shared Clipboard: Mode: Host to Guest\n"));
9859 parm.u.uint32 = VBOX_SHCL_MODE_HOST_TO_GUEST;
9860 break;
9861 case ClipboardMode_Bidirectional:
9862 LogRel(("Shared Clipboard: Mode: Bidirectional\n"));
9863 parm.u.uint32 = VBOX_SHCL_MODE_BIDIRECTIONAL;
9864 break;
9865 }
9866
9867 int vrc = pVMMDev->hgcmHostCall("VBoxSharedClipboard", VBOX_SHCL_HOST_FN_SET_MODE, 1, &parm);
9868 if (RT_FAILURE(vrc))
9869 LogRel(("Shared Clipboard: Error changing mode: %Rrc\n", vrc));
9870
9871 return vrc;
9872#else
9873 RT_NOREF(aClipboardMode);
9874 return VERR_NOT_IMPLEMENTED;
9875#endif
9876}
9877
9878/**
9879 * Changes the clipboard file transfer mode.
9880 *
9881 * @returns VBox status code.
9882 * @param aEnabled Whether clipboard file transfers are enabled or not.
9883 */
9884int Console::i_changeClipboardFileTransferMode(bool aEnabled)
9885{
9886#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
9887 VMMDev *pVMMDev = m_pVMMDev;
9888 AssertPtrReturn(pVMMDev, VERR_INVALID_POINTER);
9889
9890 VBOXHGCMSVCPARM parm;
9891 RT_ZERO(parm);
9892
9893 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
9894 parm.u.uint32 = aEnabled ? VBOX_SHCL_TRANSFER_MODE_ENABLED : VBOX_SHCL_TRANSFER_MODE_DISABLED;
9895
9896 int vrc = pVMMDev->hgcmHostCall("VBoxSharedClipboard", VBOX_SHCL_HOST_FN_SET_TRANSFER_MODE, 1 /* cParms */, &parm);
9897 if (RT_FAILURE(vrc))
9898 LogRel(("Shared Clipboard: Error changing file transfer mode: %Rrc\n", vrc));
9899
9900 return vrc;
9901#else
9902 RT_NOREF(aEnabled);
9903 return VERR_NOT_IMPLEMENTED;
9904#endif
9905}
9906
9907/**
9908 * Changes the drag and drop mode.
9909 *
9910 * @param aDnDMode new drag and drop mode.
9911 */
9912int Console::i_changeDnDMode(DnDMode_T aDnDMode)
9913{
9914 VMMDev *pVMMDev = m_pVMMDev;
9915 AssertPtrReturn(pVMMDev, VERR_INVALID_POINTER);
9916
9917 VBOXHGCMSVCPARM parm;
9918 RT_ZERO(parm);
9919 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
9920
9921 switch (aDnDMode)
9922 {
9923 default:
9924 case DnDMode_Disabled:
9925 LogRel(("Drag and drop mode: Off\n"));
9926 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_OFF;
9927 break;
9928 case DnDMode_GuestToHost:
9929 LogRel(("Drag and drop mode: Guest to Host\n"));
9930 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_GUEST_TO_HOST;
9931 break;
9932 case DnDMode_HostToGuest:
9933 LogRel(("Drag and drop mode: Host to Guest\n"));
9934 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_HOST_TO_GUEST;
9935 break;
9936 case DnDMode_Bidirectional:
9937 LogRel(("Drag and drop mode: Bidirectional\n"));
9938 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_BIDIRECTIONAL;
9939 break;
9940 }
9941
9942 int rc = pVMMDev->hgcmHostCall("VBoxDragAndDropSvc", DragAndDropSvc::HOST_DND_FN_SET_MODE, 1 /* cParms */, &parm);
9943 if (RT_FAILURE(rc))
9944 LogRel(("Error changing drag and drop mode: %Rrc\n", rc));
9945
9946 return rc;
9947}
9948
9949#ifdef VBOX_WITH_USB
9950/**
9951 * @interface_method_impl{REMOTEUSBIF,pfnQueryRemoteUsbBackend}
9952 */
9953/*static*/ DECLCALLBACK(PREMOTEUSBCALLBACK)
9954Console::i_usbQueryRemoteUsbBackend(void *pvUser, PCRTUUID pUuid, uint32_t idClient)
9955{
9956 Console *pConsole = (Console *)pvUser;
9957
9958 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
9959
9960 Guid const uuid(*pUuid);
9961 return (PREMOTEUSBCALLBACK)pConsole->i_consoleVRDPServer()->USBBackendRequestPointer(idClient, &uuid);
9962}
9963
9964
9965/**
9966 * Sends a request to VMM to attach the given host device.
9967 * After this method succeeds, the attached device will appear in the
9968 * mUSBDevices collection.
9969 *
9970 * @param aHostDevice device to attach
9971 *
9972 * @note Synchronously calls EMT.
9973 */
9974HRESULT Console::i_attachUSBDevice(IUSBDevice *aHostDevice, ULONG aMaskedIfs, const Utf8Str &aCaptureFilename)
9975{
9976 AssertReturn(aHostDevice, E_FAIL);
9977 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
9978
9979 HRESULT hrc;
9980
9981 /*
9982 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
9983 * method in EMT (using usbAttachCallback()).
9984 */
9985 Bstr bstrAddress;
9986 hrc = aHostDevice->COMGETTER(Address)(bstrAddress.asOutParam());
9987 ComAssertComRCRetRC(hrc);
9988 Utf8Str const Address(bstrAddress);
9989
9990 Bstr id;
9991 hrc = aHostDevice->COMGETTER(Id)(id.asOutParam());
9992 ComAssertComRCRetRC(hrc);
9993 Guid const uuid(id);
9994
9995 BOOL fRemote = FALSE;
9996 hrc = aHostDevice->COMGETTER(Remote)(&fRemote);
9997 ComAssertComRCRetRC(hrc);
9998
9999 Bstr bstrBackend;
10000 hrc = aHostDevice->COMGETTER(Backend)(bstrBackend.asOutParam());
10001 ComAssertComRCRetRC(hrc);
10002 Utf8Str const strBackend(bstrBackend);
10003
10004 /* Get the VM handle. */
10005 SafeVMPtr ptrVM(this);
10006 if (!ptrVM.isOk())
10007 return ptrVM.rc();
10008
10009 LogFlowThisFunc(("Proxying USB device '%s' {%RTuuid}...\n", Address.c_str(), uuid.raw()));
10010
10011 PCFGMNODE pRemoteCfg = NULL;
10012 if (fRemote)
10013 {
10014 RemoteUSBDevice *pRemoteUSBDevice = static_cast<RemoteUSBDevice *>(aHostDevice);
10015
10016 pRemoteCfg = mpVMM->pfnCFGMR3CreateTree(ptrVM.rawUVM());
10017 if (pRemoteCfg)
10018 {
10019 int vrc = mpVMM->pfnCFGMR3InsertInteger(pRemoteCfg, "ClientId", pRemoteUSBDevice->clientId());
10020 if (RT_FAILURE(vrc))
10021 {
10022 mpVMM->pfnCFGMR3DestroyTree(pRemoteCfg);
10023 return setErrorBoth(E_FAIL, vrc, tr("Failed to create configuration for USB device."));
10024 }
10025 }
10026 else
10027 return setErrorBoth(E_OUTOFMEMORY, VERR_NO_MEMORY, tr("Failed to allocate config tree for USB device."));
10028 }
10029
10030 USBConnectionSpeed_T enmSpeed;
10031 hrc = aHostDevice->COMGETTER(Speed)(&enmSpeed);
10032 AssertComRCReturnRC(hrc);
10033
10034 int vrc = ptrVM.vtable()->pfnVMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
10035 (PFNRT)i_usbAttachCallback, 11,
10036 this, ptrVM.rawUVM(), ptrVM.vtable(), aHostDevice, uuid.raw(),
10037 strBackend.c_str(), Address.c_str(), pRemoteCfg, enmSpeed, aMaskedIfs,
10038 aCaptureFilename.isEmpty() ? NULL : aCaptureFilename.c_str());
10039 if (RT_SUCCESS(vrc))
10040 {
10041 /* Create a OUSBDevice and add it to the device list */
10042 ComObjPtr<OUSBDevice> pUSBDevice;
10043 pUSBDevice.createObject();
10044 hrc = pUSBDevice->init(aHostDevice);
10045 AssertComRC(hrc);
10046
10047 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10048 mUSBDevices.push_back(pUSBDevice);
10049 LogFlowFunc(("Attached device {%RTuuid}\n", pUSBDevice->i_id().raw()));
10050
10051 /* notify callbacks */
10052 alock.release();
10053 i_onUSBDeviceStateChange(pUSBDevice, true /* aAttached */, NULL);
10054 }
10055 else
10056 {
10057 Log1WarningThisFunc(("Failed to create proxy device for '%s' {%RTuuid} (%Rrc)\n", Address.c_str(), uuid.raw(), vrc));
10058 switch (vrc)
10059 {
10060 case VERR_VUSB_NO_PORTS:
10061 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to attach the USB device. (No available ports on the USB controller)."));
10062 break;
10063 case VERR_VUSB_USBFS_PERMISSION:
10064 hrc = setErrorBoth(E_FAIL, vrc, tr("Not permitted to open the USB device, check usbfs options"));
10065 break;
10066 default:
10067 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to create a proxy device for the USB device. (Error: %Rrc)"), vrc);
10068 break;
10069 }
10070 }
10071
10072 return hrc;
10073}
10074
10075/**
10076 * USB device attach callback used by AttachUSBDevice().
10077 * Note that AttachUSBDevice() doesn't return until this callback is executed,
10078 * so we don't use AutoCaller and don't care about reference counters of
10079 * interface pointers passed in.
10080 *
10081 * @thread EMT
10082 * @note Locks the console object for writing.
10083 */
10084//static
10085DECLCALLBACK(int)
10086Console::i_usbAttachCallback(Console *that, PUVM pUVM, PCVMMR3VTABLE pVMM, IUSBDevice *aHostDevice, PCRTUUID aUuid,
10087 const char *pszBackend, const char *aAddress, PCFGMNODE pRemoteCfg, USBConnectionSpeed_T aEnmSpeed,
10088 ULONG aMaskedIfs, const char *pszCaptureFilename)
10089{
10090 RT_NOREF(aHostDevice);
10091 LogFlowFuncEnter();
10092 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
10093
10094 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
10095 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
10096
10097 VUSBSPEED enmSpeed = VUSB_SPEED_UNKNOWN;
10098 switch (aEnmSpeed)
10099 {
10100 case USBConnectionSpeed_Low: enmSpeed = VUSB_SPEED_LOW; break;
10101 case USBConnectionSpeed_Full: enmSpeed = VUSB_SPEED_FULL; break;
10102 case USBConnectionSpeed_High: enmSpeed = VUSB_SPEED_HIGH; break;
10103 case USBConnectionSpeed_Super: enmSpeed = VUSB_SPEED_SUPER; break;
10104 case USBConnectionSpeed_SuperPlus: enmSpeed = VUSB_SPEED_SUPERPLUS; break;
10105 default: AssertFailed(); break;
10106 }
10107
10108 int vrc = pVMM->pfnPDMR3UsbCreateProxyDevice(pUVM, aUuid, pszBackend, aAddress, pRemoteCfg,
10109 enmSpeed, aMaskedIfs, pszCaptureFilename);
10110 LogFlowFunc(("vrc=%Rrc\n", vrc));
10111 LogFlowFuncLeave();
10112 return vrc;
10113}
10114
10115/**
10116 * Sends a request to VMM to detach the given host device. After this method
10117 * succeeds, the detached device will disappear from the mUSBDevices
10118 * collection.
10119 *
10120 * @param aHostDevice device to attach
10121 *
10122 * @note Synchronously calls EMT.
10123 */
10124HRESULT Console::i_detachUSBDevice(const ComObjPtr<OUSBDevice> &aHostDevice)
10125{
10126 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
10127
10128 /* Get the VM handle. */
10129 SafeVMPtr ptrVM(this);
10130 if (!ptrVM.isOk())
10131 return ptrVM.rc();
10132
10133 /* if the device is attached, then there must at least one USB hub. */
10134 AssertReturn(ptrVM.vtable()->pfnPDMR3UsbHasHub(ptrVM.rawUVM()), E_FAIL);
10135
10136 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10137 LogFlowThisFunc(("Detaching USB proxy device {%RTuuid}...\n", aHostDevice->i_id().raw()));
10138
10139 /*
10140 * If this was a remote device, release the backend pointer.
10141 * The pointer was requested in usbAttachCallback.
10142 */
10143 BOOL fRemote = FALSE;
10144
10145 HRESULT hrc2 = aHostDevice->COMGETTER(Remote)(&fRemote);
10146 if (FAILED(hrc2))
10147 i_setErrorStatic(hrc2, "GetRemote() failed");
10148
10149 PCRTUUID pUuid = aHostDevice->i_id().raw();
10150 if (fRemote)
10151 {
10152 Guid guid(*pUuid);
10153 i_consoleVRDPServer()->USBBackendReleasePointer(&guid);
10154 }
10155
10156 alock.release();
10157 int vrc = ptrVM.vtable()->pfnVMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
10158 (PFNRT)i_usbDetachCallback, 4,
10159 this, ptrVM.rawUVM(), ptrVM.vtable(), pUuid);
10160 if (RT_SUCCESS(vrc))
10161 {
10162 LogFlowFunc(("Detached device {%RTuuid}\n", pUuid));
10163
10164 /* notify callbacks */
10165 i_onUSBDeviceStateChange(aHostDevice, false /* aAttached */, NULL);
10166 }
10167
10168 ComAssertRCRet(vrc, E_FAIL);
10169
10170 return S_OK;
10171}
10172
10173/**
10174 * USB device detach callback used by DetachUSBDevice().
10175 *
10176 * Note that DetachUSBDevice() doesn't return until this callback is executed,
10177 * so we don't use AutoCaller and don't care about reference counters of
10178 * interface pointers passed in.
10179 *
10180 * @thread EMT
10181 */
10182//static
10183DECLCALLBACK(int)
10184Console::i_usbDetachCallback(Console *that, PUVM pUVM, PCVMMR3VTABLE pVMM, PCRTUUID aUuid)
10185{
10186 LogFlowFuncEnter();
10187 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
10188
10189 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
10190 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
10191
10192 int vrc = pVMM->pfnPDMR3UsbDetachDevice(pUVM, aUuid);
10193
10194 LogFlowFunc(("vrc=%Rrc\n", vrc));
10195 LogFlowFuncLeave();
10196 return vrc;
10197}
10198#endif /* VBOX_WITH_USB */
10199
10200/* Note: FreeBSD needs this whether netflt is used or not. */
10201#if ((defined(RT_OS_LINUX) && !defined(VBOX_WITH_NETFLT)) || defined(RT_OS_FREEBSD))
10202
10203/**
10204 * Helper function to handle host interface device creation and attachment.
10205 *
10206 * @param networkAdapter the network adapter which attachment should be reset
10207 * @return COM status code
10208 *
10209 * @note The caller must lock this object for writing.
10210 *
10211 * @todo Move this back into the driver!
10212 */
10213HRESULT Console::i_attachToTapInterface(INetworkAdapter *networkAdapter)
10214{
10215 LogFlowThisFunc(("\n"));
10216 /* sanity check */
10217 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
10218
10219# ifdef VBOX_STRICT
10220 /* paranoia */
10221 NetworkAttachmentType_T attachment;
10222 networkAdapter->COMGETTER(AttachmentType)(&attachment);
10223 Assert(attachment == NetworkAttachmentType_Bridged);
10224# endif /* VBOX_STRICT */
10225
10226 HRESULT rc = S_OK;
10227
10228 ULONG slot = 0;
10229 rc = networkAdapter->COMGETTER(Slot)(&slot);
10230 AssertComRC(rc);
10231
10232# ifdef RT_OS_LINUX
10233 /*
10234 * Allocate a host interface device
10235 */
10236 int vrc = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
10237 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
10238 if (RT_SUCCESS(vrc))
10239 {
10240 /*
10241 * Set/obtain the tap interface.
10242 */
10243 struct ifreq IfReq;
10244 RT_ZERO(IfReq);
10245 /* The name of the TAP interface we are using */
10246 Bstr tapDeviceName;
10247 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
10248 if (FAILED(rc))
10249 tapDeviceName.setNull(); /* Is this necessary? */
10250 if (tapDeviceName.isEmpty())
10251 {
10252 LogRel(("No TAP device name was supplied.\n"));
10253 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
10254 }
10255
10256 if (SUCCEEDED(rc))
10257 {
10258 /* If we are using a static TAP device then try to open it. */
10259 Utf8Str str(tapDeviceName);
10260 RTStrCopy(IfReq.ifr_name, sizeof(IfReq.ifr_name), str.c_str()); /** @todo bitch about names which are too long... */
10261 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
10262 vrc = ioctl(RTFileToNative(maTapFD[slot]), TUNSETIFF, &IfReq);
10263 if (vrc != 0)
10264 {
10265 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
10266 rc = setErrorBoth(E_FAIL, vrc, tr("Failed to open the host network interface %ls"), tapDeviceName.raw());
10267 }
10268 }
10269 if (SUCCEEDED(rc))
10270 {
10271 /*
10272 * Make it pollable.
10273 */
10274 if (fcntl(RTFileToNative(maTapFD[slot]), F_SETFL, O_NONBLOCK) != -1)
10275 {
10276 Log(("i_attachToTapInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
10277 /*
10278 * Here is the right place to communicate the TAP file descriptor and
10279 * the host interface name to the server if/when it becomes really
10280 * necessary.
10281 */
10282 maTAPDeviceName[slot] = tapDeviceName;
10283 vrc = VINF_SUCCESS;
10284 }
10285 else
10286 {
10287 int iErr = errno;
10288
10289 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
10290 vrc = VERR_HOSTIF_BLOCKING;
10291 rc = setErrorBoth(E_FAIL, vrc, tr("could not set up the host networking device for non blocking access: %s"),
10292 strerror(errno));
10293 }
10294 }
10295 }
10296 else
10297 {
10298 LogRel(("Configuration error: Failed to open /dev/net/tun rc=%Rrc\n", vrc));
10299 switch (vrc)
10300 {
10301 case VERR_ACCESS_DENIED:
10302 /* will be handled by our caller */
10303 rc = E_ACCESSDENIED;
10304 break;
10305 default:
10306 rc = setErrorBoth(E_FAIL, vrc, tr("Could not set up the host networking device: %Rrc"), vrc);
10307 break;
10308 }
10309 }
10310
10311# elif defined(RT_OS_FREEBSD)
10312 /*
10313 * Set/obtain the tap interface.
10314 */
10315 /* The name of the TAP interface we are using */
10316 Bstr tapDeviceName;
10317 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
10318 if (FAILED(rc))
10319 tapDeviceName.setNull(); /* Is this necessary? */
10320 if (tapDeviceName.isEmpty())
10321 {
10322 LogRel(("No TAP device name was supplied.\n"));
10323 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
10324 }
10325 char szTapdev[1024] = "/dev/";
10326 /* If we are using a static TAP device then try to open it. */
10327 Utf8Str str(tapDeviceName);
10328 if (str.length() + strlen(szTapdev) <= sizeof(szTapdev))
10329 strcat(szTapdev, str.c_str());
10330 else
10331 memcpy(szTapdev + strlen(szTapdev), str.c_str(),
10332 sizeof(szTapdev) - strlen(szTapdev) - 1); /** @todo bitch about names which are too long... */
10333 int vrc = RTFileOpen(&maTapFD[slot], szTapdev,
10334 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT | RTFILE_O_NON_BLOCK);
10335
10336 if (RT_SUCCESS(vrc))
10337 maTAPDeviceName[slot] = tapDeviceName;
10338 else
10339 {
10340 switch (vrc)
10341 {
10342 case VERR_ACCESS_DENIED:
10343 /* will be handled by our caller */
10344 rc = E_ACCESSDENIED;
10345 break;
10346 default:
10347 rc = setErrorBoth(E_FAIL, vrc, tr("Failed to open the host network interface %ls"), tapDeviceName.raw());
10348 break;
10349 }
10350 }
10351# else
10352# error "huh?"
10353# endif
10354 /* in case of failure, cleanup. */
10355 if (RT_FAILURE(vrc) && SUCCEEDED(rc))
10356 {
10357 LogRel(("General failure attaching to host interface\n"));
10358 rc = setErrorBoth(E_FAIL, vrc, tr("General failure attaching to host interface"));
10359 }
10360 LogFlowThisFunc(("rc=%Rhrc\n", rc));
10361 return rc;
10362}
10363
10364
10365/**
10366 * Helper function to handle detachment from a host interface
10367 *
10368 * @param networkAdapter the network adapter which attachment should be reset
10369 * @return COM status code
10370 *
10371 * @note The caller must lock this object for writing.
10372 *
10373 * @todo Move this back into the driver!
10374 */
10375HRESULT Console::i_detachFromTapInterface(INetworkAdapter *networkAdapter)
10376{
10377 /* sanity check */
10378 LogFlowThisFunc(("\n"));
10379 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
10380
10381 HRESULT rc = S_OK;
10382# ifdef VBOX_STRICT
10383 /* paranoia */
10384 NetworkAttachmentType_T attachment;
10385 networkAdapter->COMGETTER(AttachmentType)(&attachment);
10386 Assert(attachment == NetworkAttachmentType_Bridged);
10387# endif /* VBOX_STRICT */
10388
10389 ULONG slot = 0;
10390 rc = networkAdapter->COMGETTER(Slot)(&slot);
10391 AssertComRC(rc);
10392
10393 /* is there an open TAP device? */
10394 if (maTapFD[slot] != NIL_RTFILE)
10395 {
10396 /*
10397 * Close the file handle.
10398 */
10399 Bstr tapDeviceName, tapTerminateApplication;
10400 bool isStatic = true;
10401 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
10402 if (FAILED(rc) || tapDeviceName.isEmpty())
10403 {
10404 /* If the name is empty, this is a dynamic TAP device, so close it now,
10405 so that the termination script can remove the interface. Otherwise we still
10406 need the FD to pass to the termination script. */
10407 isStatic = false;
10408 int rcVBox = RTFileClose(maTapFD[slot]);
10409 AssertRC(rcVBox);
10410 maTapFD[slot] = NIL_RTFILE;
10411 }
10412 if (isStatic)
10413 {
10414 /* If we are using a static TAP device, we close it now, after having called the
10415 termination script. */
10416 int rcVBox = RTFileClose(maTapFD[slot]);
10417 AssertRC(rcVBox);
10418 }
10419 /* the TAP device name and handle are no longer valid */
10420 maTapFD[slot] = NIL_RTFILE;
10421 maTAPDeviceName[slot] = "";
10422 }
10423 LogFlowThisFunc(("returning %d\n", rc));
10424 return rc;
10425}
10426
10427#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
10428
10429/**
10430 * Called at power down to terminate host interface networking.
10431 *
10432 * @note The caller must lock this object for writing.
10433 */
10434HRESULT Console::i_powerDownHostInterfaces()
10435{
10436 LogFlowThisFunc(("\n"));
10437
10438 /* sanity check */
10439 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
10440
10441 /*
10442 * host interface termination handling
10443 */
10444 HRESULT rc = S_OK;
10445 ComPtr<IVirtualBox> pVirtualBox;
10446 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
10447 ComPtr<ISystemProperties> pSystemProperties;
10448 if (pVirtualBox)
10449 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
10450 ChipsetType_T chipsetType = ChipsetType_PIIX3;
10451 mMachine->COMGETTER(ChipsetType)(&chipsetType);
10452 ULONG maxNetworkAdapters = 0;
10453 if (pSystemProperties)
10454 pSystemProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters);
10455
10456 for (ULONG slot = 0; slot < maxNetworkAdapters; slot++)
10457 {
10458 ComPtr<INetworkAdapter> pNetworkAdapter;
10459 rc = mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
10460 if (FAILED(rc)) break;
10461
10462 BOOL enabled = FALSE;
10463 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
10464 if (!enabled)
10465 continue;
10466
10467 NetworkAttachmentType_T attachment;
10468 pNetworkAdapter->COMGETTER(AttachmentType)(&attachment);
10469 if (attachment == NetworkAttachmentType_Bridged)
10470 {
10471#if ((defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)) && !defined(VBOX_WITH_NETFLT))
10472 HRESULT rc2 = i_detachFromTapInterface(pNetworkAdapter);
10473 if (FAILED(rc2) && SUCCEEDED(rc))
10474 rc = rc2;
10475#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
10476 }
10477 }
10478
10479 return rc;
10480}
10481
10482
10483/**
10484 * Process callback handler for VMR3LoadFromFile, VMR3LoadFromStream, VMR3Save
10485 * and VMR3Teleport.
10486 *
10487 * @param pUVM The user mode VM handle.
10488 * @param uPercent Completion percentage (0-100).
10489 * @param pvUser Pointer to an IProgress instance.
10490 * @return VINF_SUCCESS.
10491 */
10492/*static*/
10493DECLCALLBACK(int) Console::i_stateProgressCallback(PUVM pUVM, unsigned uPercent, void *pvUser)
10494{
10495 IProgress *pProgress = static_cast<IProgress *>(pvUser);
10496
10497 /* update the progress object */
10498 if (pProgress)
10499 {
10500 ComPtr<IInternalProgressControl> pProgressControl(pProgress);
10501 AssertReturn(!!pProgressControl, VERR_INVALID_PARAMETER);
10502 pProgressControl->SetCurrentOperationProgress(uPercent);
10503 }
10504
10505 NOREF(pUVM);
10506 return VINF_SUCCESS;
10507}
10508
10509/**
10510 * @copydoc FNVMATERROR
10511 *
10512 * @remarks Might be some tiny serialization concerns with access to the string
10513 * object here...
10514 */
10515/*static*/ DECLCALLBACK(void)
10516Console::i_genericVMSetErrorCallback(PUVM pUVM, void *pvUser, int rc, RT_SRC_POS_DECL, const char *pszFormat, va_list args)
10517{
10518 RT_SRC_POS_NOREF();
10519 Utf8Str *pErrorText = (Utf8Str *)pvUser;
10520 AssertPtr(pErrorText);
10521
10522 /* We ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users. */
10523 va_list va2;
10524 va_copy(va2, args);
10525
10526 /* Append to any the existing error message. */
10527 try
10528 {
10529 if (pErrorText->length())
10530 pErrorText->appendPrintf(".\n%N (%Rrc)", pszFormat, &va2, rc, rc);
10531 else
10532 pErrorText->printf("%N (%Rrc)", pszFormat, &va2, rc, rc);
10533 }
10534 catch (std::bad_alloc &)
10535 {
10536 }
10537
10538 va_end(va2);
10539
10540 NOREF(pUVM);
10541}
10542
10543/**
10544 * VM runtime error callback function (FNVMATRUNTIMEERROR).
10545 *
10546 * See VMSetRuntimeError for the detailed description of parameters.
10547 *
10548 * @param pUVM The user mode VM handle. Ignored, so passing NULL
10549 * is fine.
10550 * @param pvUser The user argument, pointer to the Console instance.
10551 * @param fFlags The action flags. See VMSETRTERR_FLAGS_*.
10552 * @param pszErrorId Error ID string.
10553 * @param pszFormat Error message format string.
10554 * @param va Error message arguments.
10555 * @thread EMT.
10556 */
10557/* static */ DECLCALLBACK(void)
10558Console::i_atVMRuntimeErrorCallback(PUVM pUVM, void *pvUser, uint32_t fFlags,
10559 const char *pszErrorId, const char *pszFormat, va_list va)
10560{
10561 bool const fFatal = !!(fFlags & VMSETRTERR_FLAGS_FATAL);
10562 LogFlowFuncEnter();
10563
10564 Console *that = static_cast<Console *>(pvUser);
10565 AssertReturnVoid(that);
10566
10567 Utf8Str message(pszFormat, va);
10568
10569 LogRel(("Console: VM runtime error: fatal=%RTbool, errorID=%s message=\"%s\"\n", fFatal, pszErrorId, message.c_str()));
10570 try
10571 {
10572 that->i_onRuntimeError(BOOL(fFatal), Bstr(pszErrorId).raw(), Bstr(message).raw());
10573 }
10574 catch (std::bad_alloc &)
10575 {
10576 }
10577 LogFlowFuncLeave(); NOREF(pUVM);
10578}
10579
10580/**
10581 * Captures USB devices that match filters of the VM.
10582 * Called at VM startup.
10583 *
10584 * @param pUVM The VM handle.
10585 */
10586HRESULT Console::i_captureUSBDevices(PUVM pUVM)
10587{
10588 RT_NOREF(pUVM);
10589 LogFlowThisFunc(("\n"));
10590
10591 /* sanity check */
10592 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
10593 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10594
10595 /* If the machine has a USB controller, ask the USB proxy service to
10596 * capture devices */
10597 if (mfVMHasUsbController)
10598 {
10599 /* release the lock before calling Host in VBoxSVC since Host may call
10600 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
10601 * produce an inter-process dead-lock otherwise. */
10602 alock.release();
10603
10604 HRESULT hrc = mControl->AutoCaptureUSBDevices();
10605 ComAssertComRCRetRC(hrc);
10606 }
10607
10608 return S_OK;
10609}
10610
10611
10612/**
10613 * Detach all USB device which are attached to the VM for the
10614 * purpose of clean up and such like.
10615 */
10616void Console::i_detachAllUSBDevices(bool aDone)
10617{
10618 LogFlowThisFunc(("aDone=%RTbool\n", aDone));
10619
10620 /* sanity check */
10621 AssertReturnVoid(!isWriteLockOnCurrentThread());
10622 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10623
10624 mUSBDevices.clear();
10625
10626 /* release the lock before calling Host in VBoxSVC since Host may call
10627 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
10628 * produce an inter-process dead-lock otherwise. */
10629 alock.release();
10630
10631 mControl->DetachAllUSBDevices(aDone);
10632}
10633
10634/**
10635 * @note Locks this object for writing.
10636 */
10637void Console::i_processRemoteUSBDevices(uint32_t u32ClientId, VRDEUSBDEVICEDESC *pDevList, uint32_t cbDevList, bool fDescExt)
10638{
10639 LogFlowThisFuncEnter();
10640 LogFlowThisFunc(("u32ClientId = %d, pDevList=%p, cbDevList = %d, fDescExt = %d\n",
10641 u32ClientId, pDevList, cbDevList, fDescExt));
10642
10643 AutoCaller autoCaller(this);
10644 if (!autoCaller.isOk())
10645 {
10646 /* Console has been already uninitialized, deny request */
10647 AssertMsgFailed(("Console is already uninitialized\n"));
10648 LogFlowThisFunc(("Console is already uninitialized\n"));
10649 LogFlowThisFuncLeave();
10650 return;
10651 }
10652
10653 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10654
10655 /*
10656 * Mark all existing remote USB devices as dirty.
10657 */
10658 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
10659 it != mRemoteUSBDevices.end();
10660 ++it)
10661 {
10662 (*it)->dirty(true);
10663 }
10664
10665 /*
10666 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
10667 */
10668 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
10669 VRDEUSBDEVICEDESC *e = pDevList;
10670
10671 /* The cbDevList condition must be checked first, because the function can
10672 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
10673 */
10674 while (cbDevList >= 2 && e->oNext)
10675 {
10676 /* Sanitize incoming strings in case they aren't valid UTF-8. */
10677 if (e->oManufacturer)
10678 RTStrPurgeEncoding((char *)e + e->oManufacturer);
10679 if (e->oProduct)
10680 RTStrPurgeEncoding((char *)e + e->oProduct);
10681 if (e->oSerialNumber)
10682 RTStrPurgeEncoding((char *)e + e->oSerialNumber);
10683
10684 LogFlowThisFunc(("vendor %04x, product %04x, name = %s\n",
10685 e->idVendor, e->idProduct, e->oProduct ? (char *)e + e->oProduct : ""));
10686
10687 bool fNewDevice = true;
10688
10689 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
10690 it != mRemoteUSBDevices.end();
10691 ++it)
10692 {
10693 if ( (*it)->devId() == e->id
10694 && (*it)->clientId() == u32ClientId)
10695 {
10696 /* The device is already in the list. */
10697 (*it)->dirty(false);
10698 fNewDevice = false;
10699 break;
10700 }
10701 }
10702
10703 if (fNewDevice)
10704 {
10705 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
10706 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""));
10707
10708 /* Create the device object and add the new device to list. */
10709 ComObjPtr<RemoteUSBDevice> pUSBDevice;
10710 pUSBDevice.createObject();
10711 pUSBDevice->init(u32ClientId, e, fDescExt);
10712
10713 mRemoteUSBDevices.push_back(pUSBDevice);
10714
10715 /* Check if the device is ok for current USB filters. */
10716 BOOL fMatched = FALSE;
10717 ULONG fMaskedIfs = 0;
10718 HRESULT hrc = mControl->RunUSBDeviceFilters(pUSBDevice, &fMatched, &fMaskedIfs);
10719
10720 AssertComRC(hrc);
10721
10722 LogFlowThisFunc(("USB filters return %d %#x\n", fMatched, fMaskedIfs));
10723
10724 if (fMatched)
10725 {
10726 alock.release();
10727 hrc = i_onUSBDeviceAttach(pUSBDevice, NULL, fMaskedIfs, Utf8Str());
10728 alock.acquire();
10729
10730 /// @todo (r=dmik) warning reporting subsystem
10731
10732 if (hrc == S_OK)
10733 {
10734 LogFlowThisFunc(("Device attached\n"));
10735 pUSBDevice->captured(true);
10736 }
10737 }
10738 }
10739
10740 if (cbDevList < e->oNext)
10741 {
10742 Log1WarningThisFunc(("cbDevList %d > oNext %d\n", cbDevList, e->oNext));
10743 break;
10744 }
10745
10746 cbDevList -= e->oNext;
10747
10748 e = (VRDEUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
10749 }
10750
10751 /*
10752 * Remove dirty devices, that is those which are not reported by the server anymore.
10753 */
10754 for (;;)
10755 {
10756 ComObjPtr<RemoteUSBDevice> pUSBDevice;
10757
10758 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
10759 while (it != mRemoteUSBDevices.end())
10760 {
10761 if ((*it)->dirty())
10762 {
10763 pUSBDevice = *it;
10764 break;
10765 }
10766
10767 ++it;
10768 }
10769
10770 if (!pUSBDevice)
10771 {
10772 break;
10773 }
10774
10775 USHORT vendorId = 0;
10776 pUSBDevice->COMGETTER(VendorId)(&vendorId);
10777
10778 USHORT productId = 0;
10779 pUSBDevice->COMGETTER(ProductId)(&productId);
10780
10781 Bstr product;
10782 pUSBDevice->COMGETTER(Product)(product.asOutParam());
10783
10784 LogRel(("Remote USB: ---- Vendor %04x. Product %04x. Name = [%ls].\n", vendorId, productId, product.raw()));
10785
10786 /* Detach the device from VM. */
10787 if (pUSBDevice->captured())
10788 {
10789 Bstr uuid;
10790 pUSBDevice->COMGETTER(Id)(uuid.asOutParam());
10791 alock.release();
10792 i_onUSBDeviceDetach(uuid.raw(), NULL);
10793 alock.acquire();
10794 }
10795
10796 /* And remove it from the list. */
10797 mRemoteUSBDevices.erase(it);
10798 }
10799
10800 LogFlowThisFuncLeave();
10801}
10802
10803
10804/**
10805 * Worker called by VMPowerUpTask::handler to start the VM (also from saved
10806 * state) and track progress.
10807 *
10808 * @param pTask The power up task.
10809 *
10810 * @note Locks the Console object for writing.
10811 */
10812/*static*/
10813void Console::i_powerUpThreadTask(VMPowerUpTask *pTask)
10814{
10815 LogFlowFuncEnter();
10816
10817 AssertReturnVoid(pTask);
10818 AssertReturnVoid(!pTask->mConsole.isNull());
10819 AssertReturnVoid(!pTask->mProgress.isNull());
10820
10821 VirtualBoxBase::initializeComForThread();
10822
10823 HRESULT rc = S_OK;
10824 int vrc = VINF_SUCCESS;
10825
10826 /* Set up a build identifier so that it can be seen from core dumps what
10827 * exact build was used to produce the core. */
10828 static char s_szBuildID[48];
10829 RTStrPrintf(s_szBuildID, sizeof(s_szBuildID), "%s%s%s%s VirtualBox %s r%u %s%s%s%s",
10830 "BU", "IL", "DI", "D", RTBldCfgVersion(), RTBldCfgRevision(), "BU", "IL", "DI", "D");
10831
10832 ComObjPtr<Console> pConsole = pTask->mConsole;
10833
10834 /* Note: no need to use AutoCaller because VMPowerUpTask does that */
10835
10836 /* The lock is also used as a signal from the task initiator (which
10837 * releases it only after RTThreadCreate()) that we can start the job */
10838 AutoWriteLock alock(pConsole COMMA_LOCKVAL_SRC_POS);
10839
10840 /* sanity */
10841 Assert(pConsole->mpUVM == NULL);
10842
10843 try
10844 {
10845 // Create the VMM device object, which starts the HGCM thread; do this only
10846 // once for the console, for the pathological case that the same console
10847 // object is used to power up a VM twice.
10848 if (!pConsole->m_pVMMDev)
10849 {
10850 pConsole->m_pVMMDev = new VMMDev(pConsole);
10851 AssertReturnVoid(pConsole->m_pVMMDev);
10852 }
10853
10854 /* wait for auto reset ops to complete so that we can successfully lock
10855 * the attached hard disks by calling LockMedia() below */
10856 for (VMPowerUpTask::ProgressList::const_iterator
10857 it = pTask->hardDiskProgresses.begin();
10858 it != pTask->hardDiskProgresses.end(); ++it)
10859 {
10860 HRESULT rc2 = (*it)->WaitForCompletion(-1);
10861 AssertComRC(rc2);
10862
10863 rc = pTask->mProgress->SetNextOperation(BstrFmt(tr("Disk Image Reset Operation - Immutable Image")).raw(), 1);
10864 AssertComRCReturnVoid(rc);
10865 }
10866
10867 /*
10868 * Lock attached media. This method will also check their accessibility.
10869 * If we're a teleporter, we'll have to postpone this action so we can
10870 * migrate between local processes.
10871 *
10872 * Note! The media will be unlocked automatically by
10873 * SessionMachine::i_setMachineState() when the VM is powered down.
10874 */
10875 if (!pTask->mTeleporterEnabled)
10876 {
10877 rc = pConsole->mControl->LockMedia();
10878 if (FAILED(rc)) throw rc;
10879 }
10880
10881 /* Create the VRDP server. In case of headless operation, this will
10882 * also create the framebuffer, required at VM creation.
10883 */
10884 ConsoleVRDPServer *server = pConsole->i_consoleVRDPServer();
10885 Assert(server);
10886
10887 /* Does VRDP server call Console from the other thread?
10888 * Not sure (and can change), so release the lock just in case.
10889 */
10890 alock.release();
10891 vrc = server->Launch();
10892 alock.acquire();
10893
10894 if (vrc != VINF_SUCCESS)
10895 {
10896 Utf8Str errMsg = pConsole->VRDPServerErrorToMsg(vrc);
10897 if ( RT_FAILURE(vrc)
10898 && vrc != VERR_NET_ADDRESS_IN_USE) /* not fatal */
10899 throw i_setErrorStaticBoth(E_FAIL, vrc, errMsg.c_str());
10900 }
10901
10902 ComPtr<IMachine> pMachine = pConsole->i_machine();
10903 ULONG cCpus = 1;
10904 pMachine->COMGETTER(CPUCount)(&cCpus);
10905
10906 VMProcPriority_T enmVMPriority = VMProcPriority_Default;
10907 pMachine->COMGETTER(VMProcessPriority)(&enmVMPriority);
10908
10909 /*
10910 * Create the VM
10911 *
10912 * Note! Release the lock since EMT will call Console. It's safe because
10913 * mMachineState is either Starting or Restoring state here.
10914 */
10915 alock.release();
10916
10917 if (enmVMPriority != VMProcPriority_Default)
10918 pConsole->i_onVMProcessPriorityChange(enmVMPriority);
10919
10920 PCVMMR3VTABLE pVMM = pConsole->mpVMM;
10921 PVM pVM = NULL;
10922 vrc = pVMM->pfnVMR3Create(cCpus,
10923 pConsole->mpVmm2UserMethods,
10924 Console::i_genericVMSetErrorCallback,
10925 &pTask->mErrorMsg,
10926 pTask->mpfnConfigConstructor,
10927 static_cast<Console *>(pConsole),
10928 &pVM, NULL);
10929 alock.acquire();
10930 if (RT_SUCCESS(vrc))
10931 {
10932 do /* break "loop" */
10933 {
10934 /*
10935 * Register our load/save state file handlers
10936 */
10937 vrc = pVMM->pfnSSMR3RegisterExternal(pConsole->mpUVM, sSSMConsoleUnit, 0 /*iInstance*/,
10938 CONSOLE_SAVED_STATE_VERSION, 0 /* cbGuess */,
10939 NULL, NULL, NULL,
10940 NULL, i_saveStateFileExec, NULL,
10941 NULL, i_loadStateFileExec, NULL,
10942 static_cast<Console *>(pConsole));
10943 AssertRCBreak(vrc);
10944
10945 vrc = static_cast<Console *>(pConsole)->i_getDisplay()->i_registerSSM(pConsole->mpUVM);
10946 AssertRC(vrc);
10947 if (RT_FAILURE(vrc))
10948 break;
10949
10950 /*
10951 * Synchronize debugger settings
10952 */
10953 MachineDebugger *machineDebugger = pConsole->i_getMachineDebugger();
10954 if (machineDebugger)
10955 machineDebugger->i_flushQueuedSettings();
10956
10957 /*
10958 * Shared Folders
10959 */
10960 if (pConsole->m_pVMMDev->isShFlActive())
10961 {
10962 /* Does the code below call Console from the other thread?
10963 * Not sure, so release the lock just in case. */
10964 alock.release();
10965
10966 for (SharedFolderDataMap::const_iterator it = pTask->mSharedFolders.begin();
10967 it != pTask->mSharedFolders.end();
10968 ++it)
10969 {
10970 const SharedFolderData &d = it->second;
10971 rc = pConsole->i_createSharedFolder(it->first, d);
10972 if (FAILED(rc))
10973 {
10974 ErrorInfoKeeper eik;
10975 pConsole->i_atVMRuntimeErrorCallbackF(0, "BrokenSharedFolder",
10976 N_("The shared folder '%s' could not be set up: %ls.\n"
10977 "The shared folder setup will not be complete. It is recommended to power down the virtual "
10978 "machine and fix the shared folder settings while the machine is not running"),
10979 it->first.c_str(), eik.getText().raw());
10980 }
10981 }
10982 if (FAILED(rc))
10983 rc = S_OK; // do not fail with broken shared folders
10984
10985 /* acquire the lock again */
10986 alock.acquire();
10987 }
10988
10989#ifdef VBOX_WITH_AUDIO_VRDE
10990 /*
10991 * Attach the VRDE audio driver.
10992 */
10993 if (pConsole->i_getVRDEServer())
10994 {
10995 BOOL fVRDEEnabled = FALSE;
10996 rc = pConsole->i_getVRDEServer()->COMGETTER(Enabled)(&fVRDEEnabled);
10997 AssertComRCBreak(rc, RT_NOTHING);
10998
10999 if ( fVRDEEnabled
11000 && pConsole->mAudioVRDE)
11001 pConsole->mAudioVRDE->doAttachDriverViaEmt(pConsole->mpUVM, pVMM, &alock);
11002 }
11003#endif
11004
11005 /*
11006 * Enable client connections to the VRDP server.
11007 */
11008 pConsole->i_consoleVRDPServer()->EnableConnections();
11009
11010#ifdef VBOX_WITH_RECORDING
11011 /*
11012 * Enable recording if configured.
11013 */
11014 BOOL fRecordingEnabled = FALSE;
11015 {
11016 ComPtr<IRecordingSettings> ptrRecordingSettings;
11017 rc = pConsole->mMachine->COMGETTER(RecordingSettings)(ptrRecordingSettings.asOutParam());
11018 AssertComRCBreak(rc, RT_NOTHING);
11019
11020 rc = ptrRecordingSettings->COMGETTER(Enabled)(&fRecordingEnabled);
11021 AssertComRCBreak(rc, RT_NOTHING);
11022 }
11023 if (fRecordingEnabled)
11024 {
11025 vrc = pConsole->i_recordingEnable(fRecordingEnabled, &alock);
11026 if (RT_SUCCESS(vrc))
11027 ::FireRecordingChangedEvent(pConsole->mEventSource);
11028 else
11029 {
11030 LogRel(("Recording: Failed with %Rrc on VM power up\n", vrc));
11031 vrc = VINF_SUCCESS; /* do not fail with broken recording */
11032 }
11033 }
11034#endif
11035
11036 /* release the lock before a lengthy operation */
11037 alock.release();
11038
11039 /*
11040 * Capture USB devices.
11041 */
11042 rc = pConsole->i_captureUSBDevices(pConsole->mpUVM);
11043 if (FAILED(rc))
11044 {
11045 alock.acquire();
11046 break;
11047 }
11048
11049 /*
11050 * Load saved state?
11051 */
11052 if (pTask->mSavedStateFile.length())
11053 {
11054 LogFlowFunc(("Restoring saved state from '%s'...\n", pTask->mSavedStateFile.c_str()));
11055
11056#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
11057 SsmStream ssmStream(pConsole, pVMM, pTask->m_pKeyStore, pTask->mKeyId, pTask->mKeyStore);
11058
11059 vrc = ssmStream.open(pTask->mSavedStateFile.c_str());
11060 if (RT_SUCCESS(vrc))
11061 {
11062 PCSSMSTRMOPS pStreamOps;
11063 void *pvStreamOpsUser;
11064
11065 vrc = ssmStream.querySsmStrmOps(&pStreamOps, &pvStreamOpsUser);
11066 if (RT_SUCCESS(vrc))
11067 vrc = pVMM->pfnVMR3LoadFromStream(pConsole->mpUVM,
11068 pStreamOps, pvStreamOpsUser,
11069 Console::i_stateProgressCallback,
11070 static_cast<IProgress *>(pTask->mProgress));
11071 }
11072#else
11073 vrc = pVMM->pfnVMR3LoadFromFile(pConsole->mpUVM,
11074 pTask->mSavedStateFile.c_str(),
11075 Console::i_stateProgressCallback,
11076 static_cast<IProgress *>(pTask->mProgress));
11077#endif
11078 if (RT_SUCCESS(vrc))
11079 {
11080 if (pTask->mStartPaused)
11081 /* done */
11082 pConsole->i_setMachineState(MachineState_Paused);
11083 else
11084 {
11085 /* Start/Resume the VM execution */
11086#ifdef VBOX_WITH_EXTPACK
11087 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM, pVMM);
11088#endif
11089 if (RT_SUCCESS(vrc))
11090 vrc = pVMM->pfnVMR3Resume(pConsole->mpUVM, VMRESUMEREASON_STATE_RESTORED);
11091 AssertLogRelRC(vrc);
11092 }
11093 }
11094
11095 /* Power off in case we failed loading or resuming the VM */
11096 if (RT_FAILURE(vrc))
11097 {
11098 int vrc2 = pVMM->pfnVMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
11099#ifdef VBOX_WITH_EXTPACK
11100 pConsole->mptrExtPackManager->i_callAllVmPowerOffHooks(pConsole, pVM, pVMM);
11101#endif
11102 }
11103 }
11104 else if (pTask->mTeleporterEnabled)
11105 {
11106 /* -> ConsoleImplTeleporter.cpp */
11107 bool fPowerOffOnFailure;
11108 rc = pConsole->i_teleporterTrg(pConsole->mpUVM, pConsole->mpVMM, pMachine, &pTask->mErrorMsg,
11109 pTask->mStartPaused, pTask->mProgress, &fPowerOffOnFailure);
11110 if (FAILED(rc) && fPowerOffOnFailure)
11111 {
11112 ErrorInfoKeeper eik;
11113 int vrc2 = pVMM->pfnVMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
11114#ifdef VBOX_WITH_EXTPACK
11115 pConsole->mptrExtPackManager->i_callAllVmPowerOffHooks(pConsole, pVM, pVMM);
11116#endif
11117 }
11118 }
11119 else if (pTask->mStartPaused)
11120 /* done */
11121 pConsole->i_setMachineState(MachineState_Paused);
11122 else
11123 {
11124 /* Power on the VM (i.e. start executing) */
11125#ifdef VBOX_WITH_EXTPACK
11126 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM, pVMM);
11127#endif
11128 if (RT_SUCCESS(vrc))
11129 vrc = pVMM->pfnVMR3PowerOn(pConsole->mpUVM);
11130 AssertLogRelRC(vrc);
11131 }
11132
11133 /* acquire the lock again */
11134 alock.acquire();
11135 }
11136 while (0);
11137
11138 /* On failure, destroy the VM */
11139 if (FAILED(rc) || RT_FAILURE(vrc))
11140 {
11141 /* preserve existing error info */
11142 ErrorInfoKeeper eik;
11143
11144 /* powerDown() will call VMR3Destroy() and do all necessary
11145 * cleanup (VRDP, USB devices) */
11146 alock.release();
11147 HRESULT rc2 = pConsole->i_powerDown();
11148 alock.acquire();
11149 AssertComRC(rc2);
11150 }
11151 else
11152 {
11153 /*
11154 * Deregister the VMSetError callback. This is necessary as the
11155 * pfnVMAtError() function passed to VMR3Create() is supposed to
11156 * be sticky but our error callback isn't.
11157 */
11158 alock.release();
11159 pVMM->pfnVMR3AtErrorDeregister(pConsole->mpUVM, Console::i_genericVMSetErrorCallback, &pTask->mErrorMsg);
11160 /** @todo register another VMSetError callback? */
11161 alock.acquire();
11162 }
11163 }
11164 else
11165 {
11166 /*
11167 * If VMR3Create() failed it has released the VM memory.
11168 */
11169 if (pConsole->m_pVMMDev)
11170 {
11171 alock.release(); /* just to be on the safe side... */
11172 pConsole->m_pVMMDev->hgcmShutdown(true /*fUvmIsInvalid*/);
11173 alock.acquire();
11174 }
11175 pVMM->pfnVMR3ReleaseUVM(pConsole->mpUVM);
11176 pConsole->mpUVM = NULL;
11177 }
11178
11179 if (SUCCEEDED(rc) && RT_FAILURE(vrc))
11180 {
11181 /* If VMR3Create() or one of the other calls in this function fail,
11182 * an appropriate error message has been set in pTask->mErrorMsg.
11183 * However since that happens via a callback, the rc status code in
11184 * this function is not updated.
11185 */
11186 if (!pTask->mErrorMsg.length())
11187 {
11188 /* If the error message is not set but we've got a failure,
11189 * convert the VBox status code into a meaningful error message.
11190 * This becomes unused once all the sources of errors set the
11191 * appropriate error message themselves.
11192 */
11193 AssertMsgFailed(("Missing error message during powerup for status code %Rrc\n", vrc));
11194 pTask->mErrorMsg = Utf8StrFmt(tr("Failed to start VM execution (%Rrc)"), vrc);
11195 }
11196
11197 /* Set the error message as the COM error.
11198 * Progress::notifyComplete() will pick it up later. */
11199 throw i_setErrorStaticBoth(E_FAIL, vrc, pTask->mErrorMsg.c_str());
11200 }
11201 }
11202 catch (HRESULT aRC) { rc = aRC; }
11203
11204 if ( pConsole->mMachineState == MachineState_Starting
11205 || pConsole->mMachineState == MachineState_Restoring
11206 || pConsole->mMachineState == MachineState_TeleportingIn
11207 )
11208 {
11209 /* We are still in the Starting/Restoring state. This means one of:
11210 *
11211 * 1) we failed before VMR3Create() was called;
11212 * 2) VMR3Create() failed.
11213 *
11214 * In both cases, there is no need to call powerDown(), but we still
11215 * need to go back to the PoweredOff/Saved state. Reuse
11216 * vmstateChangeCallback() for that purpose.
11217 */
11218
11219 /* preserve existing error info */
11220 ErrorInfoKeeper eik;
11221
11222 Assert(pConsole->mpUVM == NULL);
11223 i_vmstateChangeCallback(NULL, pConsole->mpVMM, VMSTATE_TERMINATED, VMSTATE_CREATING, pConsole);
11224 }
11225
11226 /*
11227 * Evaluate the final result. Note that the appropriate mMachineState value
11228 * is already set by vmstateChangeCallback() in all cases.
11229 */
11230
11231 /* release the lock, don't need it any more */
11232 alock.release();
11233
11234 if (SUCCEEDED(rc))
11235 {
11236 /* Notify the progress object of the success */
11237 pTask->mProgress->i_notifyComplete(S_OK);
11238 }
11239 else
11240 {
11241 /* The progress object will fetch the current error info */
11242 pTask->mProgress->i_notifyComplete(rc);
11243 LogRel(("Power up failed (vrc=%Rrc, rc=%Rhrc (%#08X))\n", vrc, rc, rc));
11244 }
11245
11246 /* Notify VBoxSVC and any waiting openRemoteSession progress object. */
11247 pConsole->mControl->EndPowerUp(rc);
11248
11249#if defined(RT_OS_WINDOWS)
11250 /* uninitialize COM */
11251 CoUninitialize();
11252#endif
11253
11254 LogFlowFuncLeave();
11255}
11256
11257
11258/**
11259 * Reconfigures a medium attachment (part of taking or deleting an online snapshot).
11260 *
11261 * @param pThis Reference to the console object.
11262 * @param pUVM The VM handle.
11263 * @param pVMM The VMM vtable.
11264 * @param pcszDevice The name of the controller type.
11265 * @param uInstance The instance of the controller.
11266 * @param enmBus The storage bus type of the controller.
11267 * @param fUseHostIOCache Use the host I/O cache (disable async I/O).
11268 * @param fBuiltinIOCache Use the builtin I/O cache.
11269 * @param fInsertDiskIntegrityDrv Flag whether to insert the disk integrity driver into the chain
11270 * for additionalk debugging aids.
11271 * @param fSetupMerge Whether to set up a medium merge
11272 * @param uMergeSource Merge source image index
11273 * @param uMergeTarget Merge target image index
11274 * @param aMediumAtt The medium attachment.
11275 * @param aMachineState The current machine state.
11276 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
11277 * @return VBox status code.
11278 */
11279/* static */
11280DECLCALLBACK(int) Console::i_reconfigureMediumAttachment(Console *pThis,
11281 PUVM pUVM,
11282 PCVMMR3VTABLE pVMM,
11283 const char *pcszDevice,
11284 unsigned uInstance,
11285 StorageBus_T enmBus,
11286 bool fUseHostIOCache,
11287 bool fBuiltinIOCache,
11288 bool fInsertDiskIntegrityDrv,
11289 bool fSetupMerge,
11290 unsigned uMergeSource,
11291 unsigned uMergeTarget,
11292 IMediumAttachment *aMediumAtt,
11293 MachineState_T aMachineState,
11294 HRESULT *phrc)
11295{
11296 LogFlowFunc(("pUVM=%p aMediumAtt=%p phrc=%p\n", pUVM, aMediumAtt, phrc));
11297
11298 HRESULT hrc;
11299 Bstr bstr;
11300 *phrc = S_OK;
11301#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%Rhrc (%#x)\n", hrc, hrc)); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
11302
11303 /* Ignore attachments other than hard disks, since at the moment they are
11304 * not subject to snapshotting in general. */
11305 DeviceType_T lType;
11306 hrc = aMediumAtt->COMGETTER(Type)(&lType); H();
11307 if (lType != DeviceType_HardDisk)
11308 return VINF_SUCCESS;
11309
11310 /* Update the device instance configuration. */
11311 int rc = pThis->i_configMediumAttachment(pcszDevice,
11312 uInstance,
11313 enmBus,
11314 fUseHostIOCache,
11315 fBuiltinIOCache,
11316 fInsertDiskIntegrityDrv,
11317 fSetupMerge,
11318 uMergeSource,
11319 uMergeTarget,
11320 aMediumAtt,
11321 aMachineState,
11322 phrc,
11323 true /* fAttachDetach */,
11324 false /* fForceUnmount */,
11325 false /* fHotplug */,
11326 pUVM,
11327 pVMM,
11328 NULL /* paLedDevType */,
11329 NULL /* ppLunL0)*/);
11330 if (RT_FAILURE(rc))
11331 {
11332 AssertMsgFailed(("rc=%Rrc\n", rc));
11333 return rc;
11334 }
11335
11336#undef H
11337
11338 LogFlowFunc(("Returns success\n"));
11339 return VINF_SUCCESS;
11340}
11341
11342/**
11343 * Thread for powering down the Console.
11344 *
11345 * @param pTask The power down task.
11346 *
11347 * @note Locks the Console object for writing.
11348 */
11349/*static*/
11350void Console::i_powerDownThreadTask(VMPowerDownTask *pTask)
11351{
11352 int rc = VINF_SUCCESS; /* only used in assertion */
11353 LogFlowFuncEnter();
11354 try
11355 {
11356 if (pTask->isOk() == false)
11357 rc = VERR_GENERAL_FAILURE;
11358
11359 const ComObjPtr<Console> &that = pTask->mConsole;
11360
11361 /* Note: no need to use AutoCaller to protect Console because VMTask does
11362 * that */
11363
11364 /* wait until the method tat started us returns */
11365 AutoWriteLock thatLock(that COMMA_LOCKVAL_SRC_POS);
11366
11367 /* release VM caller to avoid the powerDown() deadlock */
11368 pTask->releaseVMCaller();
11369
11370 thatLock.release();
11371
11372 that->i_powerDown(pTask->mServerProgress);
11373
11374 /* complete the operation */
11375 that->mControl->EndPoweringDown(S_OK, Bstr().raw());
11376
11377 }
11378 catch (const std::exception &e)
11379 {
11380 AssertMsgFailed(("Exception %s was caught, rc=%Rrc\n", e.what(), rc));
11381 NOREF(e); NOREF(rc);
11382 }
11383
11384 LogFlowFuncLeave();
11385}
11386
11387/**
11388 * @interface_method_impl{VMM2USERMETHODS,pfnSaveState}
11389 */
11390/*static*/ DECLCALLBACK(int)
11391Console::i_vmm2User_SaveState(PCVMM2USERMETHODS pThis, PUVM pUVM)
11392{
11393 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
11394 NOREF(pUVM);
11395
11396 /*
11397 * For now, just call SaveState. We should probably try notify the GUI so
11398 * it can pop up a progress object and stuff. The progress object created
11399 * by the call isn't returned to anyone and thus gets updated without
11400 * anyone noticing it.
11401 */
11402 ComPtr<IProgress> pProgress;
11403 HRESULT hrc = pConsole->mMachine->SaveState(pProgress.asOutParam());
11404 return SUCCEEDED(hrc) ? VINF_SUCCESS : Global::vboxStatusCodeFromCOM(hrc);
11405}
11406
11407/**
11408 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtInit}
11409 */
11410/*static*/ DECLCALLBACK(void)
11411Console::i_vmm2User_NotifyEmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
11412{
11413 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
11414 VirtualBoxBase::initializeComForThread();
11415}
11416
11417/**
11418 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtTerm}
11419 */
11420/*static*/ DECLCALLBACK(void)
11421Console::i_vmm2User_NotifyEmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
11422{
11423 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
11424 VirtualBoxBase::uninitializeComForThread();
11425}
11426
11427/**
11428 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtInit}
11429 */
11430/*static*/ DECLCALLBACK(void)
11431Console::i_vmm2User_NotifyPdmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM)
11432{
11433 NOREF(pThis); NOREF(pUVM);
11434 VirtualBoxBase::initializeComForThread();
11435}
11436
11437/**
11438 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtTerm}
11439 */
11440/*static*/ DECLCALLBACK(void)
11441Console::i_vmm2User_NotifyPdmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM)
11442{
11443 NOREF(pThis); NOREF(pUVM);
11444 VirtualBoxBase::uninitializeComForThread();
11445}
11446
11447/**
11448 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyResetTurnedIntoPowerOff}
11449 */
11450/*static*/ DECLCALLBACK(void)
11451Console::i_vmm2User_NotifyResetTurnedIntoPowerOff(PCVMM2USERMETHODS pThis, PUVM pUVM)
11452{
11453 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
11454 NOREF(pUVM);
11455
11456 pConsole->mfPowerOffCausedByReset = true;
11457}
11458
11459/**
11460 * Internal function to get LED set off of Console instance
11461 *
11462 * @returns pointer to PDMLED object
11463 *
11464 * @param iLedSet Index of LED set to fetch
11465 */
11466PPDMLED *
11467Console::i_getLedSet(uint32_t iLedSet)
11468{
11469 AssertReturn(iLedSet < RT_ELEMENTS(maLedSets), NULL);
11470 return maLedSets[iLedSet].papLeds;
11471}
11472
11473/**
11474 * @interface_method_impl{VMM2USERMETHODS,pfnQueryGenericObject}
11475 */
11476/*static*/ DECLCALLBACK(void *)
11477Console::i_vmm2User_QueryGenericObject(PCVMM2USERMETHODS pThis, PUVM pUVM, PCRTUUID pUuid)
11478{
11479 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
11480 NOREF(pUVM);
11481
11482 /* To simplify comparison we copy the UUID into a com::Guid object. */
11483 com::Guid const UuidCopy(*pUuid);
11484
11485 if (UuidCopy == COM_IIDOF(IConsole))
11486 {
11487 IConsole *pIConsole = static_cast<IConsole *>(pConsole);
11488 return pIConsole;
11489 }
11490
11491 if (UuidCopy == COM_IIDOF(IMachine))
11492 {
11493 IMachine *pIMachine = pConsole->mMachine;
11494 return pIMachine;
11495 }
11496
11497 if (UuidCopy == COM_IIDOF(IKeyboard))
11498 {
11499 IKeyboard *pIKeyboard = pConsole->mKeyboard;
11500 return pIKeyboard;
11501 }
11502
11503 if (UuidCopy == COM_IIDOF(IMouse))
11504 {
11505 IMouse *pIMouse = pConsole->mMouse;
11506 return pIMouse;
11507 }
11508
11509 if (UuidCopy == COM_IIDOF(IDisplay))
11510 {
11511 IDisplay *pIDisplay = pConsole->mDisplay;
11512 return pIDisplay;
11513 }
11514
11515 if (UuidCopy == COM_IIDOF(INvramStore))
11516 {
11517 NvramStore *pNvramStore = static_cast<NvramStore *>(pConsole->mptrNvramStore);
11518 return pNvramStore;
11519 }
11520
11521 if (UuidCopy == VMMDEV_OID)
11522 return pConsole->m_pVMMDev;
11523
11524 if (UuidCopy == USBCARDREADER_OID)
11525 return pConsole->mUsbCardReader;
11526
11527 if (UuidCopy == COM_IIDOF(ISnapshot))
11528 return ((MYVMM2USERMETHODS *)pThis)->pISnapshot;
11529
11530 if (UuidCopy == REMOTEUSBIF_OID)
11531 return &pConsole->mRemoteUsbIf;
11532
11533 if (UuidCopy == EMULATEDUSBIF_OID)
11534 return pConsole->mEmulatedUSB->i_getEmulatedUsbIf();
11535
11536 return NULL;
11537}
11538
11539
11540/**
11541 * @interface_method_impl{PDMISECKEY,pfnKeyRetain}
11542 */
11543/*static*/ DECLCALLBACK(int)
11544Console::i_pdmIfSecKey_KeyRetain(PPDMISECKEY pInterface, const char *pszId, const uint8_t **ppbKey, size_t *pcbKey)
11545{
11546 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
11547
11548 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
11549 SecretKey *pKey = NULL;
11550
11551 int rc = pConsole->m_pKeyStore->retainSecretKey(Utf8Str(pszId), &pKey);
11552 if (RT_SUCCESS(rc))
11553 {
11554 *ppbKey = (const uint8_t *)pKey->getKeyBuffer();
11555 *pcbKey = pKey->getKeySize();
11556 }
11557
11558 return rc;
11559}
11560
11561/**
11562 * @interface_method_impl{PDMISECKEY,pfnKeyRelease}
11563 */
11564/*static*/ DECLCALLBACK(int)
11565Console::i_pdmIfSecKey_KeyRelease(PPDMISECKEY pInterface, const char *pszId)
11566{
11567 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
11568
11569 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
11570 return pConsole->m_pKeyStore->releaseSecretKey(Utf8Str(pszId));
11571}
11572
11573/**
11574 * @interface_method_impl{PDMISECKEY,pfnPasswordRetain}
11575 */
11576/*static*/ DECLCALLBACK(int)
11577Console::i_pdmIfSecKey_PasswordRetain(PPDMISECKEY pInterface, const char *pszId, const char **ppszPassword)
11578{
11579 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
11580
11581 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
11582 SecretKey *pKey = NULL;
11583
11584 int rc = pConsole->m_pKeyStore->retainSecretKey(Utf8Str(pszId), &pKey);
11585 if (RT_SUCCESS(rc))
11586 *ppszPassword = (const char *)pKey->getKeyBuffer();
11587
11588 return rc;
11589}
11590
11591/**
11592 * @interface_method_impl{PDMISECKEY,pfnPasswordRelease}
11593 */
11594/*static*/ DECLCALLBACK(int)
11595Console::i_pdmIfSecKey_PasswordRelease(PPDMISECKEY pInterface, const char *pszId)
11596{
11597 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
11598
11599 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
11600 return pConsole->m_pKeyStore->releaseSecretKey(Utf8Str(pszId));
11601}
11602
11603/**
11604 * @interface_method_impl{PDMISECKEYHLP,pfnKeyMissingNotify}
11605 */
11606/*static*/ DECLCALLBACK(int)
11607Console::i_pdmIfSecKeyHlp_KeyMissingNotify(PPDMISECKEYHLP pInterface)
11608{
11609 Console *pConsole = ((MYPDMISECKEYHLP *)pInterface)->pConsole;
11610
11611 /* Set guest property only, the VM is paused in the media driver calling us. */
11612 pConsole->mMachine->DeleteGuestProperty(Bstr("/VirtualBox/HostInfo/DekMissing").raw());
11613 pConsole->mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/DekMissing").raw(),
11614 Bstr("1").raw(), Bstr("RDONLYGUEST").raw());
11615 pConsole->mMachine->SaveSettings();
11616
11617 return VINF_SUCCESS;
11618}
11619
11620
11621
11622/**
11623 * The Main status driver instance data.
11624 */
11625typedef struct DRVMAINSTATUS
11626{
11627 /** The LED connectors. */
11628 PDMILEDCONNECTORS ILedConnectors;
11629 /** Pointer to the LED ports interface above us. */
11630 PPDMILEDPORTS pLedPorts;
11631 /** Pointer to the array of LED pointers. */
11632 PPDMLED *papLeds;
11633 /** The unit number corresponding to the first entry in the LED array. */
11634 uint32_t iFirstLUN;
11635 /** The unit number corresponding to the last entry in the LED array.
11636 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
11637 uint32_t iLastLUN;
11638 /** Pointer to the driver instance. */
11639 PPDMDRVINS pDrvIns;
11640 /** The Media Notify interface. */
11641 PDMIMEDIANOTIFY IMediaNotify;
11642 /** Set if there potentially are medium attachments. */
11643 bool fHasMediumAttachments;
11644 /** Device name+instance for mapping */
11645 char *pszDeviceInstance;
11646 /** Pointer to the Console object, for driver triggered activities. */
11647 Console *pConsole;
11648} DRVMAINSTATUS, *PDRVMAINSTATUS;
11649
11650
11651/**
11652 * Notification about a unit which have been changed.
11653 *
11654 * The driver must discard any pointers to data owned by
11655 * the unit and requery it.
11656 *
11657 * @param pInterface Pointer to the interface structure containing the called function pointer.
11658 * @param iLUN The unit number.
11659 */
11660DECLCALLBACK(void) Console::i_drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
11661{
11662 PDRVMAINSTATUS pThis = RT_FROM_MEMBER(pInterface, DRVMAINSTATUS, ILedConnectors);
11663 if (iLUN >= pThis->iFirstLUN && iLUN <= pThis->iLastLUN)
11664 {
11665 PPDMLED pLed;
11666 int rc = pThis->pLedPorts->pfnQueryStatusLed(pThis->pLedPorts, iLUN, &pLed);
11667 /*
11668 * pLed now points directly to the per-unit struct PDMLED field
11669 * inside the target device struct owned by the hardware driver.
11670 */
11671 if (RT_FAILURE(rc))
11672 pLed = NULL;
11673 ASMAtomicWritePtr(&pThis->papLeds[iLUN - pThis->iFirstLUN], pLed);
11674 /*
11675 * papLeds[] points to the struct PDMLED of each of this driver's
11676 * units. The entries are initialized here, called out of a loop
11677 * in Console::i_drvStatus_Construct(), which previously called
11678 * Console::i_attachStatusDriver() to allocate the array itself.
11679 *
11680 * The arrays (and thus individual LEDs) are eventually read out
11681 * by Console::getDeviceActivity(), which is itself called from
11682 * src/VBox/Frontends/VirtualBox/src/runtime/UIIndicatorsPool.cpp
11683 */
11684 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
11685 }
11686}
11687
11688
11689/**
11690 * Notification about a medium eject.
11691 *
11692 * @returns VBox status code.
11693 * @param pInterface Pointer to the interface structure containing the called function pointer.
11694 * @param uLUN The unit number.
11695 */
11696DECLCALLBACK(int) Console::i_drvStatus_MediumEjected(PPDMIMEDIANOTIFY pInterface, unsigned uLUN)
11697{
11698 PDRVMAINSTATUS pThis = RT_FROM_MEMBER(pInterface, DRVMAINSTATUS, IMediaNotify);
11699 LogFunc(("uLUN=%d\n", uLUN));
11700 if (pThis->fHasMediumAttachments)
11701 {
11702 Console * const pConsole = pThis->pConsole;
11703 AutoWriteLock alock(pConsole COMMA_LOCKVAL_SRC_POS);
11704
11705 ComPtr<IMediumAttachment> pMediumAtt;
11706 Utf8Str devicePath = Utf8StrFmt("%s/LUN#%u", pThis->pszDeviceInstance, uLUN);
11707 Console::MediumAttachmentMap::const_iterator end = pConsole->mapMediumAttachments.end();
11708 Console::MediumAttachmentMap::const_iterator it = pConsole->mapMediumAttachments.find(devicePath);
11709 if (it != end)
11710 pMediumAtt = it->second;
11711 Assert(!pMediumAtt.isNull());
11712 if (!pMediumAtt.isNull())
11713 {
11714 IMedium *pMedium = NULL;
11715 HRESULT rc = pMediumAtt->COMGETTER(Medium)(&pMedium);
11716 AssertComRC(rc);
11717 if (SUCCEEDED(rc) && pMedium)
11718 {
11719 BOOL fHostDrive = FALSE;
11720 rc = pMedium->COMGETTER(HostDrive)(&fHostDrive);
11721 AssertComRC(rc);
11722 if (!fHostDrive)
11723 {
11724 alock.release();
11725
11726 ComPtr<IMediumAttachment> pNewMediumAtt;
11727 rc = pThis->pConsole->mControl->EjectMedium(pMediumAtt, pNewMediumAtt.asOutParam());
11728 if (SUCCEEDED(rc))
11729 {
11730 pThis->pConsole->mMachine->SaveSettings();
11731 ::FireMediumChangedEvent(pThis->pConsole->mEventSource, pNewMediumAtt);
11732 }
11733
11734 alock.acquire();
11735 if (pNewMediumAtt != pMediumAtt)
11736 {
11737 pConsole->mapMediumAttachments.erase(devicePath);
11738 pConsole->mapMediumAttachments.insert(std::make_pair(devicePath, pNewMediumAtt));
11739 }
11740 }
11741 }
11742 }
11743 }
11744 return VINF_SUCCESS;
11745}
11746
11747
11748/**
11749 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
11750 */
11751DECLCALLBACK(void *) Console::i_drvStatus_QueryInterface(PPDMIBASE pInterface, const char *pszIID)
11752{
11753 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
11754 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
11755 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
11756 PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDCONNECTORS, &pThis->ILedConnectors);
11757 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIANOTIFY, &pThis->IMediaNotify);
11758 return NULL;
11759}
11760
11761
11762/**
11763 * Destruct a status driver instance.
11764 *
11765 * @returns VBox status code.
11766 * @param pDrvIns The driver instance data.
11767 */
11768DECLCALLBACK(void) Console::i_drvStatus_Destruct(PPDMDRVINS pDrvIns)
11769{
11770 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
11771 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
11772 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
11773
11774 if (pThis->papLeds)
11775 {
11776 unsigned iLed = pThis->iLastLUN - pThis->iFirstLUN + 1;
11777 while (iLed-- > 0)
11778 ASMAtomicWriteNullPtr(&pThis->papLeds[iLed]);
11779 }
11780}
11781
11782
11783/**
11784 * Construct a status driver instance.
11785 *
11786 * @copydoc FNPDMDRVCONSTRUCT
11787 */
11788DECLCALLBACK(int) Console::i_drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
11789{
11790 RT_NOREF(fFlags);
11791 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
11792 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
11793 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
11794
11795 /*
11796 * Initialize data.
11797 */
11798 com::Guid ConsoleUuid(COM_IIDOF(IConsole));
11799 IConsole *pIConsole = (IConsole *)PDMDrvHlpQueryGenericUserObject(pDrvIns, ConsoleUuid.raw());
11800 AssertLogRelReturn(pIConsole, VERR_INTERNAL_ERROR_3);
11801 Console *pConsole = static_cast<Console *>(pIConsole);
11802 AssertLogRelReturn(pConsole, VERR_INTERNAL_ERROR_3);
11803
11804 pDrvIns->IBase.pfnQueryInterface = Console::i_drvStatus_QueryInterface;
11805 pThis->ILedConnectors.pfnUnitChanged = Console::i_drvStatus_UnitChanged;
11806 pThis->IMediaNotify.pfnEjected = Console::i_drvStatus_MediumEjected;
11807 pThis->pDrvIns = pDrvIns;
11808 pThis->pConsole = pConsole;
11809 pThis->fHasMediumAttachments = false;
11810 pThis->papLeds = NULL;
11811 pThis->pszDeviceInstance = NULL;
11812
11813 /*
11814 * Validate configuration.
11815 */
11816 PDMDRV_VALIDATE_CONFIG_RETURN(pDrvIns,
11817 "DeviceInstance|"
11818 "iLedSet|"
11819 "HasMediumAttachments|"
11820 "First|"
11821 "Last",
11822 "");
11823 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
11824 ("Configuration error: Not possible to attach anything to this driver!\n"),
11825 VERR_PDM_DRVINS_NO_ATTACH);
11826
11827 /*
11828 * Read config.
11829 */
11830 PCPDMDRVHLPR3 const pHlp = pDrvIns->pHlpR3;
11831
11832 uint32_t iLedSet;
11833 int rc = pHlp->pfnCFGMQueryU32(pCfg, "iLedSet", &iLedSet);
11834 AssertLogRelMsgRCReturn(rc, ("Configuration error: Failed to query the \"iLedSet\" value! rc=%Rrc\n", rc), rc);
11835 pThis->papLeds = pConsole->i_getLedSet(iLedSet);
11836
11837 rc = pHlp->pfnCFGMQueryBoolDef(pCfg, "HasMediumAttachments", &pThis->fHasMediumAttachments, false);
11838 AssertLogRelMsgRCReturn(rc, ("Configuration error: Failed to query the \"HasMediumAttachments\" value! rc=%Rrc\n", rc), rc);
11839
11840 if (pThis->fHasMediumAttachments)
11841 {
11842 rc = pHlp->pfnCFGMQueryStringAlloc(pCfg, "DeviceInstance", &pThis->pszDeviceInstance);
11843 AssertLogRelMsgRCReturn(rc, ("Configuration error: Failed to query the \"DeviceInstance\" value! rc=%Rrc\n", rc), rc);
11844 }
11845
11846 rc = pHlp->pfnCFGMQueryU32Def(pCfg, "First", &pThis->iFirstLUN, 0);
11847 AssertLogRelMsgRCReturn(rc, ("Configuration error: Failed to query the \"First\" value! rc=%Rrc\n", rc), rc);
11848
11849 rc = pHlp->pfnCFGMQueryU32Def(pCfg, "Last", &pThis->iLastLUN, 0);
11850 AssertLogRelMsgRCReturn(rc, ("Configuration error: Failed to query the \"Last\" value! rc=%Rrc\n", rc), rc);
11851
11852 AssertLogRelMsgReturn(pThis->iFirstLUN <= pThis->iLastLUN,
11853 ("Configuration error: Invalid unit range %u-%u\n", pThis->iFirstLUN, pThis->iLastLUN),
11854 VERR_INVALID_PARAMETER);
11855
11856 /*
11857 * Get the ILedPorts interface of the above driver/device and
11858 * query the LEDs we want.
11859 */
11860 pThis->pLedPorts = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMILEDPORTS);
11861 AssertMsgReturn(pThis->pLedPorts, ("Configuration error: No led ports interface above!\n"),
11862 VERR_PDM_MISSING_INTERFACE_ABOVE);
11863
11864 for (unsigned i = pThis->iFirstLUN; i <= pThis->iLastLUN; ++i)
11865 Console::i_drvStatus_UnitChanged(&pThis->ILedConnectors, i);
11866
11867 return VINF_SUCCESS;
11868}
11869
11870
11871/**
11872 * Console status driver (LED) registration record.
11873 */
11874const PDMDRVREG Console::DrvStatusReg =
11875{
11876 /* u32Version */
11877 PDM_DRVREG_VERSION,
11878 /* szName */
11879 "MainStatus",
11880 /* szRCMod */
11881 "",
11882 /* szR0Mod */
11883 "",
11884 /* pszDescription */
11885 "Main status driver (Main as in the API).",
11886 /* fFlags */
11887 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
11888 /* fClass. */
11889 PDM_DRVREG_CLASS_STATUS,
11890 /* cMaxInstances */
11891 ~0U,
11892 /* cbInstance */
11893 sizeof(DRVMAINSTATUS),
11894 /* pfnConstruct */
11895 Console::i_drvStatus_Construct,
11896 /* pfnDestruct */
11897 Console::i_drvStatus_Destruct,
11898 /* pfnRelocate */
11899 NULL,
11900 /* pfnIOCtl */
11901 NULL,
11902 /* pfnPowerOn */
11903 NULL,
11904 /* pfnReset */
11905 NULL,
11906 /* pfnSuspend */
11907 NULL,
11908 /* pfnResume */
11909 NULL,
11910 /* pfnAttach */
11911 NULL,
11912 /* pfnDetach */
11913 NULL,
11914 /* pfnPowerOff */
11915 NULL,
11916 /* pfnSoftReset */
11917 NULL,
11918 /* u32EndVersion */
11919 PDM_DRVREG_VERSION
11920};
11921
11922
11923
11924/* 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