VirtualBox

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

Last change on this file since 72088 was 72014, checked in by vboxsync, 7 years ago

VideoRec/Main: Simplified recoding state checking by only using the IMachine::VideoCaptureEnabled getter. A bit of renaming.

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