VirtualBox

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

Last change on this file since 103244 was 102455, checked in by vboxsync, 6 months ago

Main: Removed some more BUGBUG entries and documented empty / non-implemented code areas where needed. bugref:10384

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

© 2023 Oracle
ContactPrivacy policyTerms of Use