VirtualBox

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

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

VMM,Main,HostServices: Use a function table for accessing the VBoxVMM.dll/so/dylib functionality, and load it dynamically when the Console object is initialized. Also converted a few drivers in Main to use device helpers to get config values and such. bugref:10074

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

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