VirtualBox

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

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

Main,UsbWebcam: Drop passing pointers through CFGM in favor of using VMM2USERMETHODS::pfnQueryGenericObject, bugref:10053

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

© 2023 Oracle
ContactPrivacy policyTerms of Use