VirtualBox

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

Last change on this file since 93920 was 93891, checked in by vboxsync, 3 years ago

Main: Guest Properties: improved property name and value validation, bugref:10185.

This commit also prevents guest properties loss if they were set while VM was running.

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