VirtualBox

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

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

Main/Console: Fixed some IRPT and COM status code style mixup, bugref:9955

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