VirtualBox

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

Last change on this file since 101039 was 101039, checked in by vboxsync, 15 months ago

Initial commit (based draft v2 / on patch v5) for implementing platform architecture support for x86 and ARM: Doxygen / Javadoc fixes. bugref:10384

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

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