VirtualBox

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

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

Main: Restored bwGroups[i]->COMGETTER(Name)(strName.asOutParam()); accidentally removed by r150070; Corrected bogus AssertLogRelMsgRCReturn; various cleanups. bugref:10053

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

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