VirtualBox

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

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

backed out r108916

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

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