VirtualBox

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

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

Burn fix (trailing spaces).

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

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