VirtualBox

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

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

USB: When capturing devices, provide the speed rather than USB port version, since the speed provides a superset of the information (bugref:7280).

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

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