VirtualBox

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

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

Audio/Main: More code needed for attaching / detaching host backends at runtime.

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