VirtualBox

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

Last change on this file since 94304 was 94246, checked in by vboxsync, 3 years ago

Main/Console: Attach and detach storage stuff on EMT(0) to avoid upsetting PDM queue destruction code. bugref:10200 bugref:10093

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