VirtualBox

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

Last change on this file since 65120 was 65120, checked in by vboxsync, 8 years ago

Main: doxygen fixes

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

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