VirtualBox

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

Last change on this file since 101381 was 101199, checked in by vboxsync, 8 months ago

Main + FE/Qt: More Virtio-Sound handling configuration. bugref:10384

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 412.5 KB
Line 
1/* $Id: ConsoleImpl.cpp 101199 2023-09-20 14:14:08Z 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 case AudioControllerType_VirtioSound: strDevice = "virtio-sound"; break;
5297 default: break; /* None. */
5298 }
5299 }
5300
5301 return strDevice;
5302}
5303
5304/**
5305 * Called by IInternalSessionControl::OnAudioAdapterChange().
5306 */
5307HRESULT Console::i_onAudioAdapterChange(IAudioAdapter *aAudioAdapter)
5308{
5309 LogFlowThisFunc(("\n"));
5310
5311 AutoCaller autoCaller(this);
5312 AssertComRCReturnRC(autoCaller.hrc());
5313
5314 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5315
5316 HRESULT hrc = S_OK;
5317
5318 /* don't trigger audio changes if the VM isn't running */
5319 SafeVMPtrQuiet ptrVM(this);
5320 if (ptrVM.isOk())
5321 {
5322 BOOL fEnabledIn, fEnabledOut;
5323 hrc = aAudioAdapter->COMGETTER(EnabledIn)(&fEnabledIn);
5324 AssertComRC(hrc);
5325 if (SUCCEEDED(hrc))
5326 {
5327 hrc = aAudioAdapter->COMGETTER(EnabledOut)(&fEnabledOut);
5328 AssertComRC(hrc);
5329 if (SUCCEEDED(hrc))
5330 {
5331 int vrc = VINF_SUCCESS;
5332
5333 for (ULONG ulLUN = 0; ulLUN < 16 /** @todo Use a define */; ulLUN++)
5334 {
5335 PPDMIBASE pBase;
5336 int vrc2 = ptrVM.vtable()->pfnPDMR3QueryDriverOnLun(ptrVM.rawUVM(),
5337 i_getAudioAdapterDeviceName(aAudioAdapter).c_str(),
5338 0 /* iInstance */, ulLUN, "AUDIO", &pBase);
5339 if (RT_FAILURE(vrc2))
5340 continue;
5341
5342 if (pBase)
5343 {
5344 PPDMIAUDIOCONNECTOR pAudioCon = (PPDMIAUDIOCONNECTOR)pBase->pfnQueryInterface(pBase,
5345 PDMIAUDIOCONNECTOR_IID);
5346 if ( pAudioCon
5347 && pAudioCon->pfnEnable)
5348 {
5349 int vrcIn = pAudioCon->pfnEnable(pAudioCon, PDMAUDIODIR_IN, RT_BOOL(fEnabledIn));
5350 if (RT_FAILURE(vrcIn))
5351 LogRel(("Audio: Failed to %s input of LUN#%RU32, vrcIn=%Rrc\n",
5352 fEnabledIn ? "enable" : "disable", ulLUN, vrcIn));
5353
5354 if (RT_SUCCESS(vrc))
5355 vrc = vrcIn;
5356
5357 int vrcOut = pAudioCon->pfnEnable(pAudioCon, PDMAUDIODIR_OUT, RT_BOOL(fEnabledOut));
5358 if (RT_FAILURE(vrcOut))
5359 LogRel(("Audio: Failed to %s output of LUN#%RU32, vrcOut=%Rrc\n",
5360 fEnabledIn ? "enable" : "disable", ulLUN, vrcOut));
5361
5362 if (RT_SUCCESS(vrc))
5363 vrc = vrcOut;
5364 }
5365 }
5366 }
5367
5368 if (RT_SUCCESS(vrc))
5369 LogRel(("Audio: Status has changed (input is %s, output is %s)\n",
5370 fEnabledIn ? "enabled" : "disabled", fEnabledOut ? "enabled" : "disabled"));
5371 }
5372 }
5373
5374 ptrVM.release();
5375 }
5376
5377 alock.release();
5378
5379 /* notify console callbacks on success */
5380 if (SUCCEEDED(hrc))
5381 ::FireAudioAdapterChangedEvent(mEventSource, aAudioAdapter);
5382
5383 LogFlowThisFunc(("Leaving S_OKn"));
5384 return S_OK;
5385}
5386
5387/**
5388 * Called by IInternalSessionControl::OnHostAudioDeviceChange().
5389 */
5390HRESULT Console::i_onHostAudioDeviceChange(IHostAudioDevice *aDevice, BOOL aNew, AudioDeviceState_T aState,
5391 IVirtualBoxErrorInfo *aErrInfo)
5392{
5393 LogFlowThisFunc(("\n"));
5394
5395 AutoCaller autoCaller(this);
5396 AssertComRCReturnRC(autoCaller.hrc());
5397
5398 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5399
5400 HRESULT hrc = S_OK;
5401
5402 /** @todo Implement logic here. */
5403
5404 alock.release();
5405
5406 /* notify console callbacks on success */
5407 if (SUCCEEDED(hrc))
5408 ::FireHostAudioDeviceChangedEvent(mEventSource, aDevice, aNew, aState, aErrInfo);
5409
5410 LogFlowThisFunc(("Leaving S_OK\n"));
5411 return S_OK;
5412}
5413
5414/**
5415 * Performs the Serial Port attachment change in EMT.
5416 *
5417 * @returns VBox status code.
5418 *
5419 * @param pThis Pointer to the Console object.
5420 * @param pUVM The VM handle.
5421 * @param pVMM The VMM vtable.
5422 * @param pSerialPort The serial port whose attachment needs to be changed
5423 *
5424 * @thread EMT
5425 * @note Locks the Console object for writing.
5426 * @note The VM must not be running.
5427 */
5428DECLCALLBACK(int) Console::i_changeSerialPortAttachment(Console *pThis, PUVM pUVM, PCVMMR3VTABLE pVMM, ISerialPort *pSerialPort)
5429{
5430 LogFlowFunc(("pThis=%p pUVM=%p pSerialPort=%p\n", pThis, pUVM, pSerialPort));
5431
5432 AssertReturn(pThis, VERR_INVALID_PARAMETER);
5433
5434 AutoCaller autoCaller(pThis);
5435 AssertComRCReturn(autoCaller.hrc(), VERR_ACCESS_DENIED);
5436
5437 AutoWriteLock alock(pThis COMMA_LOCKVAL_SRC_POS);
5438
5439 /*
5440 * Check the VM for correct state.
5441 */
5442 VMSTATE enmVMState = pVMM->pfnVMR3GetStateU(pUVM);
5443 AssertReturn(enmVMState == VMSTATE_SUSPENDED, VERR_INVALID_STATE);
5444
5445 HRESULT hrc = S_OK;
5446 int vrc = VINF_SUCCESS;
5447 ULONG ulSlot;
5448 hrc = pSerialPort->COMGETTER(Slot)(&ulSlot);
5449 if (SUCCEEDED(hrc))
5450 {
5451 /* Check whether the port mode changed and act accordingly. */
5452 Assert(ulSlot < 4);
5453
5454 PortMode_T eHostMode;
5455 hrc = pSerialPort->COMGETTER(HostMode)(&eHostMode);
5456 if (SUCCEEDED(hrc))
5457 {
5458 PCFGMNODE pInst = pVMM->pfnCFGMR3GetChildF(pVMM->pfnCFGMR3GetRootU(pUVM), "Devices/serial/%d/", ulSlot);
5459 AssertRelease(pInst);
5460
5461 /* Remove old driver. */
5462 if (pThis->m_aeSerialPortMode[ulSlot] != PortMode_Disconnected)
5463 {
5464 vrc = pVMM->pfnPDMR3DeviceDetach(pUVM, "serial", ulSlot, 0, 0);
5465 PCFGMNODE pLunL0 = pVMM->pfnCFGMR3GetChildF(pInst, "LUN#0");
5466 pVMM->pfnCFGMR3RemoveNode(pLunL0);
5467 }
5468
5469 if (RT_SUCCESS(vrc))
5470 {
5471 BOOL fServer;
5472 Bstr bstrPath;
5473 hrc = pSerialPort->COMGETTER(Server)(&fServer);
5474 if (SUCCEEDED(hrc))
5475 hrc = pSerialPort->COMGETTER(Path)(bstrPath.asOutParam());
5476
5477 /* Configure new driver. */
5478 if ( SUCCEEDED(hrc)
5479 && eHostMode != PortMode_Disconnected)
5480 {
5481 vrc = pThis->i_configSerialPort(pInst, eHostMode, Utf8Str(bstrPath).c_str(), RT_BOOL(fServer));
5482 if (RT_SUCCESS(vrc))
5483 {
5484 /*
5485 * Attach the driver.
5486 */
5487 PPDMIBASE pBase;
5488 vrc = pVMM->pfnPDMR3DeviceAttach(pUVM, "serial", ulSlot, 0, 0, &pBase);
5489
5490 pVMM->pfnCFGMR3Dump(pInst);
5491 }
5492 }
5493 }
5494 }
5495 }
5496
5497 if (RT_SUCCESS(vrc) && FAILED(hrc))
5498 vrc = VERR_INTERNAL_ERROR;
5499
5500 LogFlowFunc(("Returning %Rrc\n", vrc));
5501 return vrc;
5502}
5503
5504
5505/**
5506 * Called by IInternalSessionControl::OnSerialPortChange().
5507 */
5508HRESULT Console::i_onSerialPortChange(ISerialPort *aSerialPort)
5509{
5510 LogFlowThisFunc(("\n"));
5511
5512 AutoCaller autoCaller(this);
5513 AssertComRCReturnRC(autoCaller.hrc());
5514
5515 HRESULT hrc = S_OK;
5516
5517 /* don't trigger audio changes if the VM isn't running */
5518 SafeVMPtrQuiet ptrVM(this);
5519 if (ptrVM.isOk())
5520 {
5521 ULONG ulSlot;
5522 BOOL fEnabled = FALSE;
5523 hrc = aSerialPort->COMGETTER(Slot)(&ulSlot);
5524 if (SUCCEEDED(hrc))
5525 hrc = aSerialPort->COMGETTER(Enabled)(&fEnabled);
5526 if (SUCCEEDED(hrc) && fEnabled)
5527 {
5528 /* Check whether the port mode changed and act accordingly. */
5529 Assert(ulSlot < 4);
5530
5531 PortMode_T eHostMode;
5532 hrc = aSerialPort->COMGETTER(HostMode)(&eHostMode);
5533 if (SUCCEEDED(hrc) && m_aeSerialPortMode[ulSlot] != eHostMode)
5534 {
5535 /*
5536 * Suspend the VM first.
5537 */
5538 bool fResume = false;
5539 hrc = i_suspendBeforeConfigChange(ptrVM.rawUVM(), ptrVM.vtable(), NULL, &fResume);
5540 if (FAILED(hrc))
5541 return hrc;
5542
5543 /*
5544 * Call worker in EMT, that's faster and safer than doing everything
5545 * using VM3ReqCallWait.
5546 */
5547 int vrc = ptrVM.vtable()->pfnVMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /*idDstCpu*/,
5548 (PFNRT)i_changeSerialPortAttachment, 4,
5549 this, ptrVM.rawUVM(), ptrVM.vtable(), aSerialPort);
5550
5551 if (fResume)
5552 i_resumeAfterConfigChange(ptrVM.rawUVM(), ptrVM.vtable());
5553 if (RT_SUCCESS(vrc))
5554 m_aeSerialPortMode[ulSlot] = eHostMode;
5555 else
5556 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to change the serial port attachment (%Rrc)"), vrc);
5557 }
5558 }
5559 }
5560
5561 if (SUCCEEDED(hrc))
5562 ::FireSerialPortChangedEvent(mEventSource, aSerialPort);
5563
5564 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
5565 return hrc;
5566}
5567
5568/**
5569 * Called by IInternalSessionControl::OnParallelPortChange().
5570 */
5571HRESULT Console::i_onParallelPortChange(IParallelPort *aParallelPort)
5572{
5573 LogFlowThisFunc(("\n"));
5574
5575 AutoCaller autoCaller(this);
5576 AssertComRCReturnRC(autoCaller.hrc());
5577
5578 ::FireParallelPortChangedEvent(mEventSource, aParallelPort);
5579
5580 LogFlowThisFunc(("Leaving S_OK\n"));
5581 return S_OK;
5582}
5583
5584/**
5585 * Called by IInternalSessionControl::OnStorageControllerChange().
5586 */
5587HRESULT Console::i_onStorageControllerChange(const Guid &aMachineId, const Utf8Str &aControllerName)
5588{
5589 LogFlowThisFunc(("\n"));
5590
5591 AutoCaller autoCaller(this);
5592 AssertComRCReturnRC(autoCaller.hrc());
5593
5594 ::FireStorageControllerChangedEvent(mEventSource, aMachineId.toString(), aControllerName);
5595
5596 LogFlowThisFunc(("Leaving S_OK\n"));
5597 return S_OK;
5598}
5599
5600/**
5601 * Called by IInternalSessionControl::OnMediumChange().
5602 */
5603HRESULT Console::i_onMediumChange(IMediumAttachment *aMediumAttachment, BOOL aForce)
5604{
5605 LogFlowThisFunc(("\n"));
5606
5607 AutoCaller autoCaller(this);
5608 AssertComRCReturnRC(autoCaller.hrc());
5609
5610 HRESULT hrc = S_OK;
5611
5612 /* don't trigger medium changes if the VM isn't running */
5613 SafeVMPtrQuiet ptrVM(this);
5614 if (ptrVM.isOk())
5615 {
5616 hrc = i_doMediumChange(aMediumAttachment, !!aForce, ptrVM.rawUVM(), ptrVM.vtable());
5617 ptrVM.release();
5618 }
5619
5620 /* notify console callbacks on success */
5621 if (SUCCEEDED(hrc))
5622 ::FireMediumChangedEvent(mEventSource, aMediumAttachment);
5623
5624 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
5625 return hrc;
5626}
5627
5628/**
5629 * Called by IInternalSessionControl::OnCPUChange().
5630 *
5631 * @note Locks this object for writing.
5632 */
5633HRESULT Console::i_onCPUChange(ULONG aCPU, BOOL aRemove)
5634{
5635 LogFlowThisFunc(("\n"));
5636
5637 AutoCaller autoCaller(this);
5638 AssertComRCReturnRC(autoCaller.hrc());
5639
5640 HRESULT hrc = S_OK;
5641
5642 /* don't trigger CPU changes if the VM isn't running */
5643 SafeVMPtrQuiet ptrVM(this);
5644 if (ptrVM.isOk())
5645 {
5646 if (aRemove)
5647 hrc = i_doCPURemove(aCPU, ptrVM.rawUVM(), ptrVM.vtable());
5648 else
5649 hrc = i_doCPUAdd(aCPU, ptrVM.rawUVM(), ptrVM.vtable());
5650 ptrVM.release();
5651 }
5652
5653 /* notify console callbacks on success */
5654 if (SUCCEEDED(hrc))
5655 ::FireCPUChangedEvent(mEventSource, aCPU, aRemove);
5656
5657 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
5658 return hrc;
5659}
5660
5661/**
5662 * Called by IInternalSessionControl::OnCpuExecutionCapChange().
5663 *
5664 * @note Locks this object for writing.
5665 */
5666HRESULT Console::i_onCPUExecutionCapChange(ULONG aExecutionCap)
5667{
5668 LogFlowThisFunc(("\n"));
5669
5670 AutoCaller autoCaller(this);
5671 AssertComRCReturnRC(autoCaller.hrc());
5672
5673 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5674
5675 HRESULT hrc = S_OK;
5676
5677 /* don't trigger the CPU priority change if the VM isn't running */
5678 SafeVMPtrQuiet ptrVM(this);
5679 if (ptrVM.isOk())
5680 {
5681 if ( mMachineState == MachineState_Running
5682 || mMachineState == MachineState_Teleporting
5683 || mMachineState == MachineState_LiveSnapshotting
5684 )
5685 {
5686 /* No need to call in the EMT thread. */
5687 hrc = ptrVM.vtable()->pfnVMR3SetCpuExecutionCap(ptrVM.rawUVM(), aExecutionCap);
5688 }
5689 else
5690 hrc = i_setInvalidMachineStateError();
5691 ptrVM.release();
5692 }
5693
5694 /* notify console callbacks on success */
5695 if (SUCCEEDED(hrc))
5696 {
5697 alock.release();
5698 ::FireCPUExecutionCapChangedEvent(mEventSource, aExecutionCap);
5699 }
5700
5701 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
5702 return hrc;
5703}
5704
5705/**
5706 * Called by IInternalSessionControl::OnClipboardError().
5707 *
5708 * @note Locks this object for writing.
5709 */
5710HRESULT Console::i_onClipboardError(const Utf8Str &aId, const Utf8Str &aErrMsg, LONG aRc)
5711{
5712 LogFlowThisFunc(("\n"));
5713
5714 AutoCaller autoCaller(this);
5715 AssertComRCReturnRC(autoCaller.hrc());
5716
5717 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5718
5719 HRESULT hrc = S_OK;
5720
5721 /* don't trigger the drag and drop mode change if the VM isn't running */
5722 SafeVMPtrQuiet ptrVM(this);
5723 if (ptrVM.isOk())
5724 {
5725 if ( mMachineState == MachineState_Running
5726 || mMachineState == MachineState_Teleporting
5727 || mMachineState == MachineState_LiveSnapshotting)
5728 {
5729 }
5730 else
5731 hrc = i_setInvalidMachineStateError();
5732 ptrVM.release();
5733 }
5734
5735 /* notify console callbacks on success */
5736 if (SUCCEEDED(hrc))
5737 {
5738 alock.release();
5739 ::FireClipboardErrorEvent(mEventSource, aId, aErrMsg, aRc);
5740 }
5741
5742 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
5743 return hrc;
5744}
5745
5746/**
5747 * Called by IInternalSessionControl::OnClipboardModeChange().
5748 *
5749 * @note Locks this object for writing.
5750 */
5751HRESULT Console::i_onClipboardModeChange(ClipboardMode_T aClipboardMode)
5752{
5753 LogFlowThisFunc(("\n"));
5754
5755 AutoCaller autoCaller(this);
5756 AssertComRCReturnRC(autoCaller.hrc());
5757
5758 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5759
5760 HRESULT hrc = S_OK;
5761
5762 /* don't trigger the clipboard mode change if the VM isn't running */
5763 SafeVMPtrQuiet ptrVM(this);
5764 if (ptrVM.isOk())
5765 {
5766 if ( mMachineState == MachineState_Running
5767 || mMachineState == MachineState_Teleporting
5768 || mMachineState == MachineState_LiveSnapshotting)
5769 {
5770 int vrc = i_changeClipboardMode(aClipboardMode);
5771 if (RT_FAILURE(vrc))
5772 hrc = E_FAIL; /** @todo r=andy Set error info here! */
5773 }
5774 else
5775 hrc = i_setInvalidMachineStateError();
5776 ptrVM.release();
5777 }
5778
5779 /* notify console callbacks on success */
5780 if (SUCCEEDED(hrc))
5781 {
5782 alock.release();
5783 ::FireClipboardModeChangedEvent(mEventSource, aClipboardMode);
5784 }
5785
5786 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
5787 return hrc;
5788}
5789
5790/**
5791 * Called by IInternalSessionControl::OnClipboardFileTransferModeChange().
5792 *
5793 * @note Locks this object for writing.
5794 */
5795HRESULT Console::i_onClipboardFileTransferModeChange(bool aEnabled)
5796{
5797 LogFlowThisFunc(("\n"));
5798
5799 AutoCaller autoCaller(this);
5800 AssertComRCReturnRC(autoCaller.hrc());
5801
5802 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5803
5804 HRESULT hrc = S_OK;
5805
5806 /* don't trigger the change if the VM isn't running */
5807 SafeVMPtrQuiet ptrVM(this);
5808 if (ptrVM.isOk())
5809 {
5810 if ( mMachineState == MachineState_Running
5811 || mMachineState == MachineState_Teleporting
5812 || mMachineState == MachineState_LiveSnapshotting)
5813 {
5814 int vrc = i_changeClipboardFileTransferMode(aEnabled);
5815 if (RT_FAILURE(vrc))
5816 hrc = E_FAIL; /** @todo r=andy Set error info here! */
5817 }
5818 else
5819 hrc = i_setInvalidMachineStateError();
5820 ptrVM.release();
5821 }
5822
5823 /* notify console callbacks on success */
5824 if (SUCCEEDED(hrc))
5825 {
5826 alock.release();
5827 ::FireClipboardFileTransferModeChangedEvent(mEventSource, aEnabled ? TRUE : FALSE);
5828 }
5829
5830 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
5831 return hrc;
5832}
5833
5834/**
5835 * Called by IInternalSessionControl::OnDnDModeChange().
5836 *
5837 * @note Locks this object for writing.
5838 */
5839HRESULT Console::i_onDnDModeChange(DnDMode_T aDnDMode)
5840{
5841 LogFlowThisFunc(("\n"));
5842
5843 AutoCaller autoCaller(this);
5844 AssertComRCReturnRC(autoCaller.hrc());
5845
5846 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5847
5848 HRESULT hrc = S_OK;
5849
5850 /* don't trigger the drag and drop mode change if the VM isn't running */
5851 SafeVMPtrQuiet ptrVM(this);
5852 if (ptrVM.isOk())
5853 {
5854 if ( mMachineState == MachineState_Running
5855 || mMachineState == MachineState_Teleporting
5856 || mMachineState == MachineState_LiveSnapshotting)
5857 i_changeDnDMode(aDnDMode);
5858 else
5859 hrc = i_setInvalidMachineStateError();
5860 ptrVM.release();
5861 }
5862
5863 /* notify console callbacks on success */
5864 if (SUCCEEDED(hrc))
5865 {
5866 alock.release();
5867 ::FireDnDModeChangedEvent(mEventSource, aDnDMode);
5868 }
5869
5870 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
5871 return hrc;
5872}
5873
5874/**
5875 * Check the return code of mConsoleVRDPServer->Launch. LogRel() the error reason and
5876 * return an error message appropriate for setError().
5877 */
5878Utf8Str Console::VRDPServerErrorToMsg(int vrc)
5879{
5880 Utf8Str errMsg;
5881 if (vrc == VERR_NET_ADDRESS_IN_USE)
5882 {
5883 /* Not fatal if we start the VM, fatal if the VM is already running. */
5884 Bstr bstr;
5885 mVRDEServer->GetVRDEProperty(Bstr("TCP/Ports").raw(), bstr.asOutParam());
5886 errMsg = Utf8StrFmt(tr("VirtualBox Remote Desktop Extension server can't bind to the port(s): %s"),
5887 Utf8Str(bstr).c_str());
5888 LogRel(("VRDE: Warning: failed to launch VRDE server (%Rrc): %s\n", vrc, errMsg.c_str()));
5889 }
5890 else if (vrc == VINF_NOT_SUPPORTED)
5891 {
5892 /* This means that the VRDE is not installed.
5893 * Not fatal if we start the VM, fatal if the VM is already running. */
5894 LogRel(("VRDE: VirtualBox Remote Desktop Extension is not available.\n"));
5895 errMsg = Utf8Str(tr("VirtualBox Remote Desktop Extension is not available"));
5896 }
5897 else if (RT_FAILURE(vrc))
5898 {
5899 /* Fail if the server is installed but can't start. Always fatal. */
5900 switch (vrc)
5901 {
5902 case VERR_FILE_NOT_FOUND:
5903 errMsg = Utf8StrFmt(tr("Could not find the VirtualBox Remote Desktop Extension library"));
5904 break;
5905 default:
5906 errMsg = Utf8StrFmt(tr("Failed to launch the Remote Desktop Extension server (%Rrc)"), vrc);
5907 break;
5908 }
5909 LogRel(("VRDE: Failed: (%Rrc): %s\n", vrc, errMsg.c_str()));
5910 }
5911
5912 return errMsg;
5913}
5914
5915/**
5916 * Called by IInternalSessionControl::OnVRDEServerChange().
5917 *
5918 * @note Locks this object for writing.
5919 */
5920HRESULT Console::i_onVRDEServerChange(BOOL aRestart)
5921{
5922 AutoCaller autoCaller(this);
5923 AssertComRCReturnRC(autoCaller.hrc());
5924
5925 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5926
5927 HRESULT hrc = S_OK;
5928
5929 /* don't trigger VRDE server changes if the VM isn't running */
5930 SafeVMPtrQuiet ptrVM(this);
5931 if (ptrVM.isOk())
5932 {
5933 /* Serialize. */
5934 if (mfVRDEChangeInProcess)
5935 mfVRDEChangePending = true;
5936 else
5937 {
5938 do {
5939 mfVRDEChangeInProcess = true;
5940 mfVRDEChangePending = false;
5941
5942 if ( mVRDEServer
5943 && ( mMachineState == MachineState_Running
5944 || mMachineState == MachineState_Teleporting
5945 || mMachineState == MachineState_LiveSnapshotting
5946 || mMachineState == MachineState_Paused
5947 )
5948 )
5949 {
5950 BOOL vrdpEnabled = FALSE;
5951
5952 hrc = mVRDEServer->COMGETTER(Enabled)(&vrdpEnabled);
5953 ComAssertComRCRetRC(hrc);
5954
5955 if (aRestart)
5956 {
5957 /* VRDP server may call this Console object back from other threads (VRDP INPUT or OUTPUT). */
5958 alock.release();
5959
5960 if (vrdpEnabled)
5961 {
5962 // If there was no VRDP server started the 'stop' will do nothing.
5963 // However if a server was started and this notification was called,
5964 // we have to restart the server.
5965 mConsoleVRDPServer->Stop();
5966
5967 int vrc = mConsoleVRDPServer->Launch();
5968 if (vrc != VINF_SUCCESS)
5969 {
5970 Utf8Str errMsg = VRDPServerErrorToMsg(vrc);
5971 hrc = setErrorBoth(E_FAIL, vrc, "%s", errMsg.c_str());
5972 }
5973 else
5974 {
5975#ifdef VBOX_WITH_AUDIO_VRDE
5976 mAudioVRDE->doAttachDriverViaEmt(ptrVM.rawUVM(), ptrVM.vtable(), NULL /*alock is not held*/);
5977#endif
5978 mConsoleVRDPServer->EnableConnections();
5979 }
5980 }
5981 else
5982 {
5983 mConsoleVRDPServer->Stop();
5984#ifdef VBOX_WITH_AUDIO_VRDE
5985 mAudioVRDE->doDetachDriverViaEmt(ptrVM.rawUVM(), ptrVM.vtable(), NULL /*alock is not held*/);
5986#endif
5987 }
5988
5989 alock.acquire();
5990 }
5991 }
5992 else
5993 hrc = i_setInvalidMachineStateError();
5994
5995 mfVRDEChangeInProcess = false;
5996 } while (mfVRDEChangePending && SUCCEEDED(hrc));
5997 }
5998
5999 ptrVM.release();
6000 }
6001
6002 /* notify console callbacks on success */
6003 if (SUCCEEDED(hrc))
6004 {
6005 alock.release();
6006 ::FireVRDEServerChangedEvent(mEventSource);
6007 }
6008
6009 return hrc;
6010}
6011
6012void Console::i_onVRDEServerInfoChange()
6013{
6014 AutoCaller autoCaller(this);
6015 AssertComRCReturnVoid(autoCaller.hrc());
6016
6017 ::FireVRDEServerInfoChangedEvent(mEventSource);
6018}
6019
6020HRESULT Console::i_sendACPIMonitorHotPlugEvent()
6021{
6022 LogFlowThisFuncEnter();
6023
6024 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6025
6026 if ( mMachineState != MachineState_Running
6027 && mMachineState != MachineState_Teleporting
6028 && mMachineState != MachineState_LiveSnapshotting)
6029 return i_setInvalidMachineStateError();
6030
6031 /* get the VM handle. */
6032 SafeVMPtr ptrVM(this);
6033 if (!ptrVM.isOk())
6034 return ptrVM.hrc();
6035
6036 // no need to release lock, as there are no cross-thread callbacks
6037
6038 /* get the acpi device interface and press the sleep button. */
6039 PPDMIBASE pBase;
6040 int vrc = ptrVM.vtable()->pfnPDMR3QueryDeviceLun(ptrVM.rawUVM(), "acpi", 0, 0, &pBase);
6041 if (RT_SUCCESS(vrc))
6042 {
6043 Assert(pBase);
6044 PPDMIACPIPORT pPort = PDMIBASE_QUERY_INTERFACE(pBase, PDMIACPIPORT);
6045 if (pPort)
6046 vrc = pPort->pfnMonitorHotPlugEvent(pPort);
6047 else
6048 vrc = VERR_PDM_MISSING_INTERFACE;
6049 }
6050
6051 HRESULT hrc = RT_SUCCESS(vrc) ? S_OK
6052 : setErrorBoth(VBOX_E_PDM_ERROR, vrc, tr("Sending monitor hot-plug event failed (%Rrc)"), vrc);
6053
6054 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
6055 LogFlowThisFuncLeave();
6056 return hrc;
6057}
6058
6059#ifdef VBOX_WITH_RECORDING
6060/**
6061 * Enables or disables recording of a VM.
6062 *
6063 * @returns VBox status code.
6064 * @retval VERR_NO_CHANGE if the recording state has not been changed.
6065 * @param fEnable Whether to enable or disable the recording.
6066 * @param pAutoLock Pointer to auto write lock to use for attaching/detaching required driver(s) at runtime.
6067 */
6068int Console::i_recordingEnable(BOOL fEnable, util::AutoWriteLock *pAutoLock)
6069{
6070 AssertPtrReturn(pAutoLock, VERR_INVALID_POINTER);
6071
6072 int vrc = VINF_SUCCESS;
6073
6074 Display *pDisplay = i_getDisplay();
6075 if (pDisplay)
6076 {
6077 bool const fIsEnabled = mRecording.mCtx.IsStarted();
6078
6079 if (RT_BOOL(fEnable) != fIsEnabled)
6080 {
6081 LogRel(("Recording: %s\n", fEnable ? "Enabling" : "Disabling"));
6082
6083 SafeVMPtrQuiet ptrVM(this);
6084 if (ptrVM.isOk())
6085 {
6086 if (fEnable)
6087 {
6088 vrc = i_recordingCreate();
6089 if (RT_SUCCESS(vrc))
6090 {
6091# ifdef VBOX_WITH_AUDIO_RECORDING
6092 /* Attach the video recording audio driver if required. */
6093 if ( mRecording.mCtx.IsFeatureEnabled(RecordingFeature_Audio)
6094 && mRecording.mAudioRec)
6095 {
6096 vrc = mRecording.mAudioRec->applyConfiguration(mRecording.mCtx.GetConfig());
6097 if (RT_SUCCESS(vrc))
6098 vrc = mRecording.mAudioRec->doAttachDriverViaEmt(ptrVM.rawUVM(), ptrVM.vtable(), pAutoLock);
6099
6100 if (RT_FAILURE(vrc))
6101 setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Attaching to audio recording driver failed (%Rrc) -- please consult log file for details"), vrc);
6102 }
6103# endif
6104 if ( RT_SUCCESS(vrc)
6105 && mRecording.mCtx.IsReady()) /* Any video recording (audio and/or video) feature enabled? */
6106 {
6107 vrc = pDisplay->i_recordingInvalidate();
6108 if (RT_SUCCESS(vrc))
6109 {
6110 vrc = i_recordingStart(pAutoLock);
6111 if (RT_FAILURE(vrc))
6112 setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Recording start failed (%Rrc) -- please consult log file for details"), vrc);
6113 }
6114 }
6115 }
6116 else
6117 setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Recording initialization failed (%Rrc) -- please consult log file for details"), vrc);
6118
6119 if (RT_FAILURE(vrc))
6120 LogRel(("Recording: Failed to enable with %Rrc\n", vrc));
6121 }
6122 else
6123 {
6124 vrc = i_recordingStop(pAutoLock);
6125 if (RT_SUCCESS(vrc))
6126 {
6127# ifdef VBOX_WITH_AUDIO_RECORDING
6128 if (mRecording.mAudioRec)
6129 mRecording.mAudioRec->doDetachDriverViaEmt(ptrVM.rawUVM(), ptrVM.vtable(), pAutoLock);
6130# endif
6131 i_recordingDestroy();
6132 }
6133 else
6134 setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Recording stop failed (%Rrc) -- please consult log file for details"), vrc);
6135 }
6136 }
6137 else
6138 vrc = VERR_VM_INVALID_VM_STATE;
6139
6140 if (RT_FAILURE(vrc))
6141 LogRel(("Recording: %s failed with %Rrc\n", fEnable ? "Enabling" : "Disabling", vrc));
6142 }
6143 else /* Should not happen. */
6144 {
6145 vrc = VERR_NO_CHANGE;
6146 setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Recording already %s"), fIsEnabled ? tr("enabled") : tr("disabled"));
6147 }
6148 }
6149
6150 return vrc;
6151}
6152#endif /* VBOX_WITH_RECORDING */
6153
6154/**
6155 * Called by IInternalSessionControl::OnRecordingChange().
6156 */
6157HRESULT Console::i_onRecordingChange(BOOL fEnabled)
6158{
6159 AutoCaller autoCaller(this);
6160 AssertComRCReturnRC(autoCaller.hrc());
6161
6162 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6163
6164 HRESULT hrc = S_OK;
6165#ifdef VBOX_WITH_RECORDING
6166 /* Don't trigger recording changes if the VM isn't running. */
6167 SafeVMPtrQuiet ptrVM(this);
6168 if (ptrVM.isOk())
6169 {
6170 LogFlowThisFunc(("fEnabled=%RTbool\n", RT_BOOL(fEnabled)));
6171
6172 int vrc = i_recordingEnable(fEnabled, &alock);
6173 if (RT_SUCCESS(vrc))
6174 {
6175 alock.release();
6176 ::FireRecordingChangedEvent(mEventSource);
6177 }
6178 else /* Error set via ErrorInfo within i_recordingEnable() already. */
6179 hrc = VBOX_E_IPRT_ERROR;
6180 ptrVM.release();
6181 }
6182#else
6183 RT_NOREF(fEnabled);
6184#endif /* VBOX_WITH_RECORDING */
6185 return hrc;
6186}
6187
6188/**
6189 * Called by IInternalSessionControl::OnUSBControllerChange().
6190 */
6191HRESULT Console::i_onUSBControllerChange()
6192{
6193 LogFlowThisFunc(("\n"));
6194
6195 AutoCaller autoCaller(this);
6196 AssertComRCReturnRC(autoCaller.hrc());
6197
6198 ::FireUSBControllerChangedEvent(mEventSource);
6199
6200 return S_OK;
6201}
6202
6203/**
6204 * Called by IInternalSessionControl::OnSharedFolderChange().
6205 *
6206 * @note Locks this object for writing.
6207 */
6208HRESULT Console::i_onSharedFolderChange(BOOL aGlobal)
6209{
6210 LogFlowThisFunc(("aGlobal=%RTbool\n", aGlobal));
6211
6212 AutoCaller autoCaller(this);
6213 AssertComRCReturnRC(autoCaller.hrc());
6214
6215 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6216
6217 HRESULT hrc = i_fetchSharedFolders(aGlobal);
6218
6219 /* notify console callbacks on success */
6220 if (SUCCEEDED(hrc))
6221 {
6222 alock.release();
6223 ::FireSharedFolderChangedEvent(mEventSource, aGlobal ? Scope_Global : Scope_Machine);
6224 }
6225
6226 return hrc;
6227}
6228
6229/**
6230 * Called by IInternalSessionControl::OnGuestDebugControlChange().
6231 */
6232HRESULT Console::i_onGuestDebugControlChange(IGuestDebugControl *aGuestDebugControl)
6233{
6234 LogFlowThisFunc(("\n"));
6235
6236 AutoCaller autoCaller(this);
6237 AssertComRCReturnRC(autoCaller.hrc());
6238
6239 HRESULT hrc = S_OK;
6240
6241 /* don't trigger changes if the VM isn't running */
6242 SafeVMPtrQuiet ptrVM(this);
6243 if (ptrVM.isOk())
6244 {
6245 /// @todo
6246 }
6247
6248 if (SUCCEEDED(hrc))
6249 ::FireGuestDebugControlChangedEvent(mEventSource, aGuestDebugControl);
6250
6251 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
6252 return hrc;
6253}
6254
6255
6256/**
6257 * Called by IInternalSessionControl::OnUSBDeviceAttach() or locally by
6258 * processRemoteUSBDevices() after IInternalMachineControl::RunUSBDeviceFilters()
6259 * returns TRUE for a given remote USB device.
6260 *
6261 * @return S_OK if the device was attached to the VM.
6262 * @return failure if not attached.
6263 *
6264 * @param aDevice The device in question.
6265 * @param aError Error information.
6266 * @param aMaskedIfs The interfaces to hide from the guest.
6267 * @param aCaptureFilename File name where to store the USB traffic.
6268 *
6269 * @note Locks this object for writing.
6270 */
6271HRESULT Console::i_onUSBDeviceAttach(IUSBDevice *aDevice, IVirtualBoxErrorInfo *aError, ULONG aMaskedIfs,
6272 const Utf8Str &aCaptureFilename)
6273{
6274#ifdef VBOX_WITH_USB
6275 LogFlowThisFunc(("aDevice=%p aError=%p\n", aDevice, aError));
6276
6277 AutoCaller autoCaller(this);
6278 ComAssertComRCRetRC(autoCaller.hrc());
6279
6280 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6281
6282 /* Get the VM pointer (we don't need error info, since it's a callback). */
6283 SafeVMPtrQuiet ptrVM(this);
6284 if (!ptrVM.isOk())
6285 {
6286 /* The VM may be no more operational when this message arrives
6287 * (e.g. it may be Saving or Stopping or just PoweredOff) --
6288 * autoVMCaller.hrc() will return a failure in this case. */
6289 LogFlowThisFunc(("Attach request ignored (mMachineState=%d).\n", mMachineState));
6290 return ptrVM.hrc();
6291 }
6292
6293 if (aError != NULL)
6294 {
6295 /* notify callbacks about the error */
6296 alock.release();
6297 i_onUSBDeviceStateChange(aDevice, true /* aAttached */, aError);
6298 return S_OK;
6299 }
6300
6301 /* Don't proceed unless there's at least one USB hub. */
6302 if (!ptrVM.vtable()->pfnPDMR3UsbHasHub(ptrVM.rawUVM()))
6303 {
6304 LogFlowThisFunc(("Attach request ignored (no USB controller).\n"));
6305 return E_FAIL;
6306 }
6307
6308 alock.release();
6309 HRESULT hrc = i_attachUSBDevice(aDevice, aMaskedIfs, aCaptureFilename);
6310 if (FAILED(hrc))
6311 {
6312 /* take the current error info */
6313 com::ErrorInfoKeeper eik;
6314 /* the error must be a VirtualBoxErrorInfo instance */
6315 ComPtr<IVirtualBoxErrorInfo> pError = eik.takeError();
6316 Assert(!pError.isNull());
6317 if (!pError.isNull())
6318 {
6319 /* notify callbacks about the error */
6320 i_onUSBDeviceStateChange(aDevice, true /* aAttached */, pError);
6321 }
6322 }
6323
6324 return hrc;
6325
6326#else /* !VBOX_WITH_USB */
6327 RT_NOREF(aDevice, aError, aMaskedIfs, aCaptureFilename);
6328 return E_FAIL;
6329#endif /* !VBOX_WITH_USB */
6330}
6331
6332/**
6333 * Called by IInternalSessionControl::OnUSBDeviceDetach() and locally by
6334 * processRemoteUSBDevices().
6335 *
6336 * @note Locks this object for writing.
6337 */
6338HRESULT Console::i_onUSBDeviceDetach(IN_BSTR aId,
6339 IVirtualBoxErrorInfo *aError)
6340{
6341#ifdef VBOX_WITH_USB
6342 Guid Uuid(aId);
6343 LogFlowThisFunc(("aId={%RTuuid} aError=%p\n", Uuid.raw(), aError));
6344
6345 AutoCaller autoCaller(this);
6346 AssertComRCReturnRC(autoCaller.hrc());
6347
6348 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6349
6350 /* Find the device. */
6351 ComObjPtr<OUSBDevice> pUSBDevice;
6352 USBDeviceList::iterator it = mUSBDevices.begin();
6353 while (it != mUSBDevices.end())
6354 {
6355 LogFlowThisFunc(("it={%RTuuid}\n", (*it)->i_id().raw()));
6356 if ((*it)->i_id() == Uuid)
6357 {
6358 pUSBDevice = *it;
6359 break;
6360 }
6361 ++it;
6362 }
6363
6364
6365 if (pUSBDevice.isNull())
6366 {
6367 LogFlowThisFunc(("USB device not found.\n"));
6368
6369 /* The VM may be no more operational when this message arrives
6370 * (e.g. it may be Saving or Stopping or just PoweredOff). Use
6371 * AutoVMCaller to detect it -- AutoVMCaller::hrc() will return a
6372 * failure in this case. */
6373
6374 AutoVMCallerQuiet autoVMCaller(this);
6375 if (FAILED(autoVMCaller.hrc()))
6376 {
6377 LogFlowThisFunc(("Detach request ignored (mMachineState=%d).\n", mMachineState));
6378 return autoVMCaller.hrc();
6379 }
6380
6381 /* the device must be in the list otherwise */
6382 AssertFailedReturn(E_FAIL);
6383 }
6384
6385 if (aError != NULL)
6386 {
6387 /* notify callback about an error */
6388 alock.release();
6389 i_onUSBDeviceStateChange(pUSBDevice, false /* aAttached */, aError);
6390 return S_OK;
6391 }
6392
6393 /* Remove the device from the collection, it is re-added below for failures */
6394 mUSBDevices.erase(it);
6395
6396 alock.release();
6397 HRESULT hrc = i_detachUSBDevice(pUSBDevice);
6398 if (FAILED(hrc))
6399 {
6400 /* Re-add the device to the collection */
6401 alock.acquire();
6402 mUSBDevices.push_back(pUSBDevice);
6403 alock.release();
6404 /* take the current error info */
6405 com::ErrorInfoKeeper eik;
6406 /* the error must be a VirtualBoxErrorInfo instance */
6407 ComPtr<IVirtualBoxErrorInfo> pError = eik.takeError();
6408 Assert(!pError.isNull());
6409 if (!pError.isNull())
6410 {
6411 /* notify callbacks about the error */
6412 i_onUSBDeviceStateChange(pUSBDevice, false /* aAttached */, pError);
6413 }
6414 }
6415
6416 return hrc;
6417
6418#else /* !VBOX_WITH_USB */
6419 RT_NOREF(aId, aError);
6420 return E_FAIL;
6421#endif /* !VBOX_WITH_USB */
6422}
6423
6424/**
6425 * Called by IInternalSessionControl::OnBandwidthGroupChange().
6426 *
6427 * @note Locks this object for writing.
6428 */
6429HRESULT Console::i_onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
6430{
6431 LogFlowThisFunc(("\n"));
6432
6433 AutoCaller autoCaller(this);
6434 AssertComRCReturnRC(autoCaller.hrc());
6435
6436 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6437
6438 HRESULT hrc = S_OK;
6439
6440 /* don't trigger bandwidth group changes if the VM isn't running */
6441 SafeVMPtrQuiet ptrVM(this);
6442 if (ptrVM.isOk())
6443 {
6444 if ( mMachineState == MachineState_Running
6445 || mMachineState == MachineState_Teleporting
6446 || mMachineState == MachineState_LiveSnapshotting
6447 )
6448 {
6449 /* No need to call in the EMT thread. */
6450 Bstr bstrName;
6451 hrc = aBandwidthGroup->COMGETTER(Name)(bstrName.asOutParam());
6452 if (SUCCEEDED(hrc))
6453 {
6454 Utf8Str const strName(bstrName);
6455 LONG64 cMax;
6456 hrc = aBandwidthGroup->COMGETTER(MaxBytesPerSec)(&cMax);
6457 if (SUCCEEDED(hrc))
6458 {
6459 BandwidthGroupType_T enmType;
6460 hrc = aBandwidthGroup->COMGETTER(Type)(&enmType);
6461 if (SUCCEEDED(hrc))
6462 {
6463 int vrc = VINF_SUCCESS;
6464 if (enmType == BandwidthGroupType_Disk)
6465 vrc = ptrVM.vtable()->pfnPDMR3AsyncCompletionBwMgrSetMaxForFile(ptrVM.rawUVM(), strName.c_str(),
6466 (uint32_t)cMax);
6467#ifdef VBOX_WITH_NETSHAPER
6468 else if (enmType == BandwidthGroupType_Network)
6469 vrc = ptrVM.vtable()->pfnPDMR3NsBwGroupSetLimit(ptrVM.rawUVM(), strName.c_str(), cMax);
6470 else
6471 hrc = E_NOTIMPL;
6472#endif
6473 AssertRC(vrc);
6474 }
6475 }
6476 }
6477 }
6478 else
6479 hrc = i_setInvalidMachineStateError();
6480 ptrVM.release();
6481 }
6482
6483 /* notify console callbacks on success */
6484 if (SUCCEEDED(hrc))
6485 {
6486 alock.release();
6487 ::FireBandwidthGroupChangedEvent(mEventSource, aBandwidthGroup);
6488 }
6489
6490 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
6491 return hrc;
6492}
6493
6494/**
6495 * Called by IInternalSessionControl::OnStorageDeviceChange().
6496 *
6497 * @note Locks this object for writing.
6498 */
6499HRESULT Console::i_onStorageDeviceChange(IMediumAttachment *aMediumAttachment, BOOL aRemove, BOOL aSilent)
6500{
6501 LogFlowThisFunc(("\n"));
6502
6503 AutoCaller autoCaller(this);
6504 AssertComRCReturnRC(autoCaller.hrc());
6505
6506 HRESULT hrc = S_OK;
6507
6508 /* don't trigger medium changes if the VM isn't running */
6509 SafeVMPtrQuiet ptrVM(this);
6510 if (ptrVM.isOk())
6511 {
6512 if (aRemove)
6513 hrc = i_doStorageDeviceDetach(aMediumAttachment, ptrVM.rawUVM(), ptrVM.vtable(), RT_BOOL(aSilent));
6514 else
6515 hrc = i_doStorageDeviceAttach(aMediumAttachment, ptrVM.rawUVM(), ptrVM.vtable(), RT_BOOL(aSilent));
6516 ptrVM.release();
6517 }
6518
6519 /* notify console callbacks on success */
6520 if (SUCCEEDED(hrc))
6521 ::FireStorageDeviceChangedEvent(mEventSource, aMediumAttachment, aRemove, aSilent);
6522
6523 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
6524 return hrc;
6525}
6526
6527HRESULT Console::i_onExtraDataChange(const Bstr &aMachineId, const Bstr &aKey, const Bstr &aVal)
6528{
6529 LogFlowThisFunc(("\n"));
6530
6531 AutoCaller autoCaller(this);
6532 if (FAILED(autoCaller.hrc()))
6533 return autoCaller.hrc();
6534
6535 if (aMachineId != i_getId())
6536 return S_OK;
6537
6538 /* don't do anything if the VM isn't running */
6539 if (aKey == "VBoxInternal2/TurnResetIntoPowerOff")
6540 {
6541 SafeVMPtrQuiet ptrVM(this);
6542 if (ptrVM.isOk())
6543 {
6544 mfTurnResetIntoPowerOff = aVal == "1";
6545 int vrc = ptrVM.vtable()->pfnVMR3SetPowerOffInsteadOfReset(ptrVM.rawUVM(), mfTurnResetIntoPowerOff);
6546 AssertRC(vrc);
6547
6548 ptrVM.release();
6549 }
6550 }
6551
6552 /* notify console callbacks on success */
6553 ::FireExtraDataChangedEvent(mEventSource, aMachineId.raw(), aKey.raw(), aVal.raw());
6554
6555 LogFlowThisFunc(("Leaving S_OK\n"));
6556 return S_OK;
6557}
6558
6559/**
6560 * @note Temporarily locks this object for writing.
6561 */
6562HRESULT Console::i_getGuestProperty(const Utf8Str &aName, Utf8Str *aValue, LONG64 *aTimestamp, Utf8Str *aFlags)
6563{
6564#ifndef VBOX_WITH_GUEST_PROPS
6565 ReturnComNotImplemented();
6566#else /* VBOX_WITH_GUEST_PROPS */
6567 if (!RT_VALID_PTR(aValue))
6568 return E_POINTER;
6569#ifndef VBOX_WITH_PARFAIT /** @todo Fails due to RT_VALID_PTR() being only a != NULL check with parfait. */
6570 if (aTimestamp != NULL && !RT_VALID_PTR(aTimestamp))
6571 return E_POINTER;
6572 if (aFlags != NULL && !RT_VALID_PTR(aFlags))
6573 return E_POINTER;
6574#endif
6575
6576 AutoCaller autoCaller(this);
6577 AssertComRCReturnRC(autoCaller.hrc());
6578
6579 /* protect mpUVM (if not NULL) */
6580 SafeVMPtrQuiet ptrVM(this);
6581 if (FAILED(ptrVM.hrc()))
6582 return ptrVM.hrc();
6583
6584 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
6585 * ptrVM, so there is no need to hold a lock of this */
6586
6587 HRESULT hrc = E_UNEXPECTED;
6588 try
6589 {
6590 VBOXHGCMSVCPARM parm[4];
6591 char szBuffer[GUEST_PROP_MAX_VALUE_LEN + GUEST_PROP_MAX_FLAGS_LEN];
6592
6593 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
6594 parm[0].u.pointer.addr = (void *)aName.c_str();
6595 parm[0].u.pointer.size = (uint32_t)aName.length() + 1; /* The + 1 is the null terminator */
6596
6597 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
6598 parm[1].u.pointer.addr = szBuffer;
6599 parm[1].u.pointer.size = sizeof(szBuffer);
6600
6601 parm[2].type = VBOX_HGCM_SVC_PARM_64BIT;
6602 parm[2].u.uint64 = 0;
6603
6604 parm[3].type = VBOX_HGCM_SVC_PARM_32BIT;
6605 parm[3].u.uint32 = 0;
6606
6607 int vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GUEST_PROP_FN_HOST_GET_PROP,
6608 4, &parm[0]);
6609 /* The returned string should never be able to be greater than our buffer */
6610 AssertLogRel(vrc != VERR_BUFFER_OVERFLOW);
6611 AssertLogRel(RT_FAILURE(vrc) || parm[2].type == VBOX_HGCM_SVC_PARM_64BIT);
6612 if (RT_SUCCESS(vrc))
6613 {
6614 *aValue = szBuffer;
6615
6616 if (aTimestamp)
6617 *aTimestamp = parm[2].u.uint64;
6618
6619 if (aFlags)
6620 *aFlags = &szBuffer[strlen(szBuffer) + 1];
6621
6622 hrc = S_OK;
6623 }
6624 else if (vrc == VERR_NOT_FOUND)
6625 {
6626 *aValue = "";
6627 hrc = S_OK;
6628 }
6629 else
6630 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("The VBoxGuestPropSvc service call failed with the error %Rrc"), vrc);
6631 }
6632 catch(std::bad_alloc & /*e*/)
6633 {
6634 hrc = E_OUTOFMEMORY;
6635 }
6636
6637 return hrc;
6638#endif /* VBOX_WITH_GUEST_PROPS */
6639}
6640
6641/**
6642 * @note Temporarily locks this object for writing.
6643 */
6644HRESULT Console::i_setGuestProperty(const Utf8Str &aName, const Utf8Str &aValue, const Utf8Str &aFlags)
6645{
6646#ifndef VBOX_WITH_GUEST_PROPS
6647 ReturnComNotImplemented();
6648#else /* VBOX_WITH_GUEST_PROPS */
6649
6650 AutoCaller autoCaller(this);
6651 AssertComRCReturnRC(autoCaller.hrc());
6652
6653 /* protect mpUVM (if not NULL) */
6654 SafeVMPtrQuiet ptrVM(this);
6655 if (FAILED(ptrVM.hrc()))
6656 return ptrVM.hrc();
6657
6658 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
6659 * ptrVM, so there is no need to hold a lock of this */
6660
6661 VBOXHGCMSVCPARM parm[3];
6662
6663 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
6664 parm[0].u.pointer.addr = (void*)aName.c_str();
6665 parm[0].u.pointer.size = (uint32_t)aName.length() + 1; /* The + 1 is the null terminator */
6666
6667 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
6668 parm[1].u.pointer.addr = (void *)aValue.c_str();
6669 parm[1].u.pointer.size = (uint32_t)aValue.length() + 1; /* The + 1 is the null terminator */
6670
6671 int vrc;
6672 if (aFlags.isEmpty())
6673 {
6674 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GUEST_PROP_FN_HOST_SET_PROP_VALUE, 2, &parm[0]);
6675 }
6676 else
6677 {
6678 parm[2].type = VBOX_HGCM_SVC_PARM_PTR;
6679 parm[2].u.pointer.addr = (void*)aFlags.c_str();
6680 parm[2].u.pointer.size = (uint32_t)aFlags.length() + 1; /* The + 1 is the null terminator */
6681
6682 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GUEST_PROP_FN_HOST_SET_PROP, 3, &parm[0]);
6683 }
6684
6685 HRESULT hrc = S_OK;
6686 if (RT_FAILURE(vrc))
6687 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("The VBoxGuestPropSvc service call failed with the error %Rrc"), vrc);
6688 return hrc;
6689#endif /* VBOX_WITH_GUEST_PROPS */
6690}
6691
6692HRESULT Console::i_deleteGuestProperty(const Utf8Str &aName)
6693{
6694#ifndef VBOX_WITH_GUEST_PROPS
6695 ReturnComNotImplemented();
6696#else /* VBOX_WITH_GUEST_PROPS */
6697
6698 AutoCaller autoCaller(this);
6699 AssertComRCReturnRC(autoCaller.hrc());
6700
6701 /* protect mpUVM (if not NULL) */
6702 SafeVMPtrQuiet ptrVM(this);
6703 if (FAILED(ptrVM.hrc()))
6704 return ptrVM.hrc();
6705
6706 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
6707 * ptrVM, so there is no need to hold a lock of this */
6708
6709 VBOXHGCMSVCPARM parm[1];
6710 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
6711 parm[0].u.pointer.addr = (void*)aName.c_str();
6712 parm[0].u.pointer.size = (uint32_t)aName.length() + 1; /* The + 1 is the null terminator */
6713
6714 int vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GUEST_PROP_FN_HOST_DEL_PROP, 1, &parm[0]);
6715
6716 HRESULT hrc = S_OK;
6717 if (RT_FAILURE(vrc))
6718 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("The VBoxGuestPropSvc service call failed with the error %Rrc"), vrc);
6719 return hrc;
6720#endif /* VBOX_WITH_GUEST_PROPS */
6721}
6722
6723/**
6724 * @note Temporarily locks this object for writing.
6725 */
6726HRESULT Console::i_enumerateGuestProperties(const Utf8Str &aPatterns,
6727 std::vector<Utf8Str> &aNames,
6728 std::vector<Utf8Str> &aValues,
6729 std::vector<LONG64> &aTimestamps,
6730 std::vector<Utf8Str> &aFlags)
6731{
6732#ifndef VBOX_WITH_GUEST_PROPS
6733 ReturnComNotImplemented();
6734#else /* VBOX_WITH_GUEST_PROPS */
6735
6736 AutoCaller autoCaller(this);
6737 AssertComRCReturnRC(autoCaller.hrc());
6738
6739 /* protect mpUVM (if not NULL) */
6740 AutoVMCallerWeak autoVMCaller(this);
6741 if (FAILED(autoVMCaller.hrc()))
6742 return autoVMCaller.hrc();
6743
6744 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
6745 * autoVMCaller, so there is no need to hold a lock of this */
6746
6747 return i_doEnumerateGuestProperties(aPatterns, aNames, aValues, aTimestamps, aFlags);
6748#endif /* VBOX_WITH_GUEST_PROPS */
6749}
6750
6751
6752/*
6753 * Internal: helper function for connecting progress reporting
6754 */
6755static DECLCALLBACK(int) onlineMergeMediumProgress(void *pvUser, unsigned uPercentage)
6756{
6757 HRESULT hrc = S_OK;
6758 IProgress *pProgress = static_cast<IProgress *>(pvUser);
6759 if (pProgress)
6760 {
6761 ComPtr<IInternalProgressControl> pProgressControl(pProgress);
6762 AssertReturn(!!pProgressControl, VERR_INVALID_PARAMETER);
6763 hrc = pProgressControl->SetCurrentOperationProgress(uPercentage);
6764 }
6765 return SUCCEEDED(hrc) ? VINF_SUCCESS : VERR_GENERAL_FAILURE;
6766}
6767
6768/**
6769 * @note Temporarily locks this object for writing. bird: And/or reading?
6770 */
6771HRESULT Console::i_onlineMergeMedium(IMediumAttachment *aMediumAttachment,
6772 ULONG aSourceIdx, ULONG aTargetIdx,
6773 IProgress *aProgress)
6774{
6775 AutoCaller autoCaller(this);
6776 AssertComRCReturnRC(autoCaller.hrc());
6777
6778 HRESULT hrc = S_OK;
6779 int vrc = VINF_SUCCESS;
6780
6781 /* Get the VM - must be done before the read-locking. */
6782 SafeVMPtr ptrVM(this);
6783 if (!ptrVM.isOk())
6784 return ptrVM.hrc();
6785
6786 /* We will need to release the lock before doing the actual merge */
6787 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6788
6789 /* paranoia - we don't want merges to happen while teleporting etc. */
6790 switch (mMachineState)
6791 {
6792 case MachineState_DeletingSnapshotOnline:
6793 case MachineState_DeletingSnapshotPaused:
6794 break;
6795
6796 default:
6797 return i_setInvalidMachineStateError();
6798 }
6799
6800 /** @todo AssertComRC -> AssertComRCReturn! Could potentially end up
6801 * using uninitialized variables here. */
6802 BOOL fBuiltinIOCache = FALSE;
6803 hrc = mMachine->COMGETTER(IOCacheEnabled)(&fBuiltinIOCache);
6804 AssertComRC(hrc);
6805 SafeIfaceArray<IStorageController> ctrls;
6806 hrc = mMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));
6807 AssertComRC(hrc);
6808 LONG lDev = -1;
6809 hrc = aMediumAttachment->COMGETTER(Device)(&lDev);
6810 AssertComRC(hrc);
6811 LONG lPort = -1;
6812 hrc = aMediumAttachment->COMGETTER(Port)(&lPort);
6813 AssertComRC(hrc);
6814 IMedium *pMedium = NULL;
6815 hrc = aMediumAttachment->COMGETTER(Medium)(&pMedium);
6816 AssertComRC(hrc);
6817 Bstr mediumLocation;
6818 if (pMedium)
6819 {
6820 hrc = pMedium->COMGETTER(Location)(mediumLocation.asOutParam());
6821 AssertComRC(hrc);
6822 }
6823
6824 Bstr attCtrlName;
6825 hrc = aMediumAttachment->COMGETTER(Controller)(attCtrlName.asOutParam());
6826 AssertComRC(hrc);
6827 ComPtr<IStorageController> pStorageController;
6828 for (size_t i = 0; i < ctrls.size(); ++i)
6829 {
6830 Bstr ctrlName;
6831 hrc = ctrls[i]->COMGETTER(Name)(ctrlName.asOutParam());
6832 AssertComRC(hrc);
6833 if (attCtrlName == ctrlName)
6834 {
6835 pStorageController = ctrls[i];
6836 break;
6837 }
6838 }
6839 if (pStorageController.isNull())
6840 return setError(E_FAIL,
6841 tr("Could not find storage controller '%ls'"),
6842 attCtrlName.raw());
6843
6844 StorageControllerType_T enmCtrlType;
6845 hrc = pStorageController->COMGETTER(ControllerType)(&enmCtrlType);
6846 AssertComRC(hrc);
6847 const char *pcszDevice = i_storageControllerTypeToStr(enmCtrlType);
6848
6849 StorageBus_T enmBus;
6850 hrc = pStorageController->COMGETTER(Bus)(&enmBus);
6851 AssertComRC(hrc);
6852
6853 ULONG uInstance = 0;
6854 hrc = pStorageController->COMGETTER(Instance)(&uInstance);
6855 AssertComRC(hrc);
6856
6857 BOOL fUseHostIOCache = TRUE;
6858 hrc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
6859 AssertComRC(hrc);
6860
6861 unsigned uLUN;
6862 hrc = Console::i_storageBusPortDeviceToLun(enmBus, lPort, lDev, uLUN);
6863 AssertComRCReturnRC(hrc);
6864
6865 Assert(mMachineState == MachineState_DeletingSnapshotOnline);
6866
6867 /* Pause the VM, as it might have pending IO on this drive */
6868 bool fResume = false;
6869 hrc = i_suspendBeforeConfigChange(ptrVM.rawUVM(), ptrVM.vtable(), &alock, &fResume);
6870 if (FAILED(hrc))
6871 return hrc;
6872
6873 bool fInsertDiskIntegrityDrv = false;
6874 Bstr strDiskIntegrityFlag;
6875 hrc = mMachine->GetExtraData(Bstr("VBoxInternal2/EnableDiskIntegrityDriver").raw(), strDiskIntegrityFlag.asOutParam());
6876 if ( hrc == S_OK
6877 && strDiskIntegrityFlag == "1")
6878 fInsertDiskIntegrityDrv = true;
6879
6880 alock.release();
6881 vrc = ptrVM.vtable()->pfnVMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY,
6882 (PFNRT)i_reconfigureMediumAttachment, 15,
6883 this, ptrVM.rawUVM(), ptrVM.vtable(), pcszDevice, uInstance, enmBus,
6884 fUseHostIOCache, fBuiltinIOCache, fInsertDiskIntegrityDrv, true /* fSetupMerge */,
6885 aSourceIdx, aTargetIdx, aMediumAttachment, mMachineState, &hrc);
6886 /* error handling is after resuming the VM */
6887
6888 if (fResume)
6889 i_resumeAfterConfigChange(ptrVM.rawUVM(), ptrVM.vtable());
6890
6891 if (RT_FAILURE(vrc))
6892 return setErrorBoth(E_FAIL, vrc, "%Rrc", vrc);
6893 if (FAILED(hrc))
6894 return hrc;
6895
6896 PPDMIBASE pIBase = NULL;
6897 PPDMIMEDIA pIMedium = NULL;
6898 vrc = ptrVM.vtable()->pfnPDMR3QueryDriverOnLun(ptrVM.rawUVM(), pcszDevice, uInstance, uLUN, "VD", &pIBase);
6899 if (RT_SUCCESS(vrc))
6900 {
6901 if (pIBase)
6902 {
6903 pIMedium = (PPDMIMEDIA)pIBase->pfnQueryInterface(pIBase, PDMIMEDIA_IID);
6904 if (!pIMedium)
6905 return setError(E_FAIL, tr("could not query medium interface of controller"));
6906 }
6907 else
6908 return setError(E_FAIL, tr("could not query base interface of controller"));
6909 }
6910
6911 /* Finally trigger the merge. */
6912 vrc = pIMedium->pfnMerge(pIMedium, onlineMergeMediumProgress, aProgress);
6913 if (RT_FAILURE(vrc))
6914 return setErrorBoth(E_FAIL, vrc, tr("Failed to perform an online medium merge (%Rrc)"), vrc);
6915
6916 alock.acquire();
6917 /* Pause the VM, as it might have pending IO on this drive */
6918 hrc = i_suspendBeforeConfigChange(ptrVM.rawUVM(), ptrVM.vtable(), &alock, &fResume);
6919 if (FAILED(hrc))
6920 return hrc;
6921 alock.release();
6922
6923 /* Update medium chain and state now, so that the VM can continue. */
6924 hrc = mControl->FinishOnlineMergeMedium();
6925
6926 vrc = ptrVM.vtable()->pfnVMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY,
6927 (PFNRT)i_reconfigureMediumAttachment, 15,
6928 this, ptrVM.rawUVM(), ptrVM.vtable(), pcszDevice, uInstance, enmBus,
6929 fUseHostIOCache, fBuiltinIOCache, fInsertDiskIntegrityDrv, false /* fSetupMerge */,
6930 0 /* uMergeSource */, 0 /* uMergeTarget */, aMediumAttachment, mMachineState, &hrc);
6931 /* error handling is after resuming the VM */
6932
6933 if (fResume)
6934 i_resumeAfterConfigChange(ptrVM.rawUVM(), ptrVM.vtable());
6935
6936 if (RT_FAILURE(vrc))
6937 return setErrorBoth(E_FAIL, vrc, "%Rrc", vrc);
6938 if (FAILED(hrc))
6939 return hrc;
6940
6941 return hrc;
6942}
6943
6944HRESULT Console::i_reconfigureMediumAttachments(const std::vector<ComPtr<IMediumAttachment> > &aAttachments)
6945{
6946
6947 AutoCaller autoCaller(this);
6948 if (FAILED(autoCaller.hrc()))
6949 return autoCaller.hrc();
6950
6951 /* get the VM handle. */
6952 SafeVMPtr ptrVM(this);
6953 if (!ptrVM.isOk())
6954 return ptrVM.hrc();
6955
6956 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6957
6958 for (size_t i = 0; i < aAttachments.size(); ++i)
6959 {
6960 /*
6961 * We could pass the objects, but then EMT would have to do lots of
6962 * IPC (to VBoxSVC) which takes a significant amount of time.
6963 * Better query needed values here and pass them.
6964 */
6965 Bstr controllerName;
6966 HRESULT hrc = aAttachments[i]->COMGETTER(Controller)(controllerName.asOutParam());
6967 if (FAILED(hrc))
6968 return hrc;
6969
6970 ComPtr<IStorageController> pStorageController;
6971 hrc = mMachine->GetStorageControllerByName(controllerName.raw(), pStorageController.asOutParam());
6972 if (FAILED(hrc))
6973 return hrc;
6974
6975 StorageControllerType_T enmController;
6976 hrc = pStorageController->COMGETTER(ControllerType)(&enmController);
6977 if (FAILED(hrc))
6978 return hrc;
6979 const char * const pcszDevice = i_storageControllerTypeToStr(enmController);
6980
6981 ULONG lInstance;
6982 hrc = pStorageController->COMGETTER(Instance)(&lInstance);
6983 if (FAILED(hrc))
6984 return hrc;
6985
6986 StorageBus_T enmBus;
6987 hrc = pStorageController->COMGETTER(Bus)(&enmBus);
6988 if (FAILED(hrc))
6989 return hrc;
6990
6991 BOOL fUseHostIOCache;
6992 hrc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
6993 if (FAILED(hrc))
6994 return hrc;
6995
6996 BOOL fBuiltinIOCache;
6997 hrc = mMachine->COMGETTER(IOCacheEnabled)(&fBuiltinIOCache);
6998 if (FAILED(hrc))
6999 return hrc;
7000
7001 bool fInsertDiskIntegrityDrv = false;
7002 Bstr strDiskIntegrityFlag;
7003 hrc = mMachine->GetExtraData(Bstr("VBoxInternal2/EnableDiskIntegrityDriver").raw(),
7004 strDiskIntegrityFlag.asOutParam());
7005 if ( hrc == S_OK
7006 && strDiskIntegrityFlag == "1")
7007 fInsertDiskIntegrityDrv = true;
7008
7009 alock.release();
7010
7011 hrc = S_OK;
7012 IMediumAttachment *pAttachment = aAttachments[i];
7013 int vrc = ptrVM.vtable()->pfnVMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY,
7014 (PFNRT)i_reconfigureMediumAttachment, 15,
7015 this, ptrVM.rawUVM(), ptrVM.vtable(), pcszDevice, lInstance, enmBus,
7016 fUseHostIOCache, fBuiltinIOCache, fInsertDiskIntegrityDrv,
7017 false /* fSetupMerge */, 0 /* uMergeSource */, 0 /* uMergeTarget */,
7018 pAttachment, mMachineState, &hrc);
7019 if (RT_FAILURE(vrc))
7020 throw setErrorBoth(E_FAIL, vrc, "%Rrc", vrc);
7021 if (FAILED(hrc))
7022 throw hrc;
7023
7024 alock.acquire();
7025 }
7026
7027 return S_OK;
7028}
7029
7030HRESULT Console::i_onVMProcessPriorityChange(VMProcPriority_T priority)
7031{
7032 AutoCaller autoCaller(this);
7033 HRESULT hrc = autoCaller.hrc();
7034 if (FAILED(hrc))
7035 return hrc;
7036
7037 RTPROCPRIORITY enmProcPriority = RTPROCPRIORITY_DEFAULT;
7038 switch (priority)
7039 {
7040 case VMProcPriority_Default:
7041 enmProcPriority = RTPROCPRIORITY_DEFAULT;
7042 break;
7043 case VMProcPriority_Flat:
7044 enmProcPriority = RTPROCPRIORITY_FLAT;
7045 break;
7046 case VMProcPriority_Low:
7047 enmProcPriority = RTPROCPRIORITY_LOW;
7048 break;
7049 case VMProcPriority_Normal:
7050 enmProcPriority = RTPROCPRIORITY_NORMAL;
7051 break;
7052 case VMProcPriority_High:
7053 enmProcPriority = RTPROCPRIORITY_HIGH;
7054 break;
7055 default:
7056 return setError(E_INVALIDARG, tr("Unsupported priority type (%d)"), priority);
7057 }
7058 int vrc = RTProcSetPriority(enmProcPriority);
7059 if (RT_FAILURE(vrc))
7060 hrc = setErrorBoth(VBOX_E_VM_ERROR, vrc,
7061 tr("Could not set the priority of the process (%Rrc). Try to set it when VM is not started."), vrc);
7062
7063 return hrc;
7064}
7065
7066/**
7067 * Load an HGCM service.
7068 *
7069 * Main purpose of this method is to allow extension packs to load HGCM
7070 * service modules, which they can't, because the HGCM functionality lives
7071 * in module VBoxC (and ConsoleImpl.cpp is part of it and thus can call it).
7072 * Extension modules must not link directly against VBoxC, (XP)COM is
7073 * handling this.
7074 */
7075int Console::i_hgcmLoadService(const char *pszServiceLibrary, const char *pszServiceName)
7076{
7077 /* Everyone seems to delegate all HGCM calls to VMMDev, so stick to this
7078 * convention. Adds one level of indirection for no obvious reason. */
7079 AssertPtrReturn(m_pVMMDev, VERR_INVALID_STATE);
7080 return m_pVMMDev->hgcmLoadService(pszServiceLibrary, pszServiceName);
7081}
7082
7083/**
7084 * Merely passes the call to Guest::enableVMMStatistics().
7085 */
7086void Console::i_enableVMMStatistics(BOOL aEnable)
7087{
7088 if (mGuest)
7089 mGuest->i_enableVMMStatistics(aEnable);
7090}
7091
7092/**
7093 * Worker for Console::Pause and internal entry point for pausing a VM for
7094 * a specific reason.
7095 */
7096HRESULT Console::i_pause(Reason_T aReason)
7097{
7098 LogFlowThisFuncEnter();
7099
7100 AutoCaller autoCaller(this);
7101 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
7102
7103 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7104
7105 switch (mMachineState)
7106 {
7107 case MachineState_Running:
7108 case MachineState_Teleporting:
7109 case MachineState_LiveSnapshotting:
7110 break;
7111
7112 case MachineState_Paused:
7113 case MachineState_TeleportingPausedVM:
7114 case MachineState_OnlineSnapshotting:
7115 /* Remove any keys which are supposed to be removed on a suspend. */
7116 if ( aReason == Reason_HostSuspend
7117 || aReason == Reason_HostBatteryLow)
7118 {
7119 i_removeSecretKeysOnSuspend();
7120 return S_OK;
7121 }
7122 return setError(VBOX_E_INVALID_VM_STATE, tr("Already paused"));
7123
7124 default:
7125 return i_setInvalidMachineStateError();
7126 }
7127
7128 /* get the VM handle. */
7129 SafeVMPtr ptrVM(this);
7130 HRESULT hrc = ptrVM.hrc();
7131 if (SUCCEEDED(hrc))
7132 {
7133 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
7134 alock.release();
7135
7136 LogFlowThisFunc(("Sending PAUSE request...\n"));
7137 if (aReason != Reason_Unspecified)
7138 LogRel(("Pausing VM execution, reason '%s'\n", ::stringifyReason(aReason)));
7139
7140 /** @todo r=klaus make use of aReason */
7141 VMSUSPENDREASON enmReason = VMSUSPENDREASON_USER;
7142 if (aReason == Reason_HostSuspend)
7143 enmReason = VMSUSPENDREASON_HOST_SUSPEND;
7144 else if (aReason == Reason_HostBatteryLow)
7145 enmReason = VMSUSPENDREASON_HOST_BATTERY_LOW;
7146
7147 int vrc = ptrVM.vtable()->pfnVMR3Suspend(ptrVM.rawUVM(), enmReason);
7148
7149 if (RT_FAILURE(vrc))
7150 hrc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not suspend the machine execution (%Rrc)"), vrc);
7151 else if ( aReason == Reason_HostSuspend
7152 || aReason == Reason_HostBatteryLow)
7153 {
7154 alock.acquire();
7155 i_removeSecretKeysOnSuspend();
7156 }
7157 }
7158
7159 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
7160 LogFlowThisFuncLeave();
7161 return hrc;
7162}
7163
7164/**
7165 * Worker for Console::Resume and internal entry point for resuming a VM for
7166 * a specific reason.
7167 */
7168HRESULT Console::i_resume(Reason_T aReason, AutoWriteLock &alock)
7169{
7170 LogFlowThisFuncEnter();
7171
7172 AutoCaller autoCaller(this);
7173 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
7174
7175 /* get the VM handle. */
7176 SafeVMPtr ptrVM(this);
7177 if (!ptrVM.isOk())
7178 return ptrVM.hrc();
7179
7180 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
7181 alock.release();
7182
7183 LogFlowThisFunc(("Sending RESUME request...\n"));
7184 if (aReason != Reason_Unspecified)
7185 LogRel(("Resuming VM execution, reason '%s'\n", ::stringifyReason(aReason)));
7186
7187 int vrc;
7188 VMSTATE const enmVMState = mpVMM->pfnVMR3GetStateU(ptrVM.rawUVM());
7189 if (enmVMState == VMSTATE_CREATED)
7190 {
7191#ifdef VBOX_WITH_EXTPACK
7192 vrc = mptrExtPackManager->i_callAllVmPowerOnHooks(this, ptrVM.vtable()->pfnVMR3GetVM(ptrVM.rawUVM()), ptrVM.vtable());
7193#else
7194 vrc = VINF_SUCCESS;
7195#endif
7196 if (RT_SUCCESS(vrc))
7197 vrc = ptrVM.vtable()->pfnVMR3PowerOn(ptrVM.rawUVM()); /* (PowerUpPaused) */
7198 }
7199 else
7200 {
7201 VMRESUMEREASON enmReason;
7202 if (aReason == Reason_HostResume)
7203 {
7204 /*
7205 * Host resume may be called multiple times successively. We don't want to VMR3Resume->vmR3Resume->vmR3TrySetState()
7206 * to assert on us, hence check for the VM state here and bail if it's not in the 'suspended' state.
7207 * See @bugref{3495}.
7208 *
7209 * Also, don't resume the VM through a host-resume unless it was suspended due to a host-suspend.
7210 */
7211 if (enmVMState != VMSTATE_SUSPENDED)
7212 {
7213 LogRel(("Ignoring VM resume request, VM is currently not suspended (%d)\n", enmVMState));
7214 return S_OK;
7215 }
7216 VMSUSPENDREASON const enmSuspendReason = ptrVM.vtable()->pfnVMR3GetSuspendReason(ptrVM.rawUVM());
7217 if (enmSuspendReason != VMSUSPENDREASON_HOST_SUSPEND)
7218 {
7219 LogRel(("Ignoring VM resume request, VM was not suspended due to host-suspend (%d)\n", enmSuspendReason));
7220 return S_OK;
7221 }
7222
7223 enmReason = VMRESUMEREASON_HOST_RESUME;
7224 }
7225 else
7226 {
7227 /*
7228 * Any other reason to resume the VM throws an error when the VM was suspended due to a host suspend.
7229 * See @bugref{7836}.
7230 */
7231 if ( enmVMState == VMSTATE_SUSPENDED
7232 && ptrVM.vtable()->pfnVMR3GetSuspendReason(ptrVM.rawUVM()) == VMSUSPENDREASON_HOST_SUSPEND)
7233 return setError(VBOX_E_INVALID_VM_STATE, tr("VM is paused due to host power management"));
7234
7235 enmReason = aReason == Reason_Snapshot ? VMRESUMEREASON_STATE_SAVED : VMRESUMEREASON_USER;
7236 }
7237
7238 // for snapshots: no state change callback, VBoxSVC does everything
7239 if (aReason == Reason_Snapshot)
7240 mVMStateChangeCallbackDisabled = true;
7241
7242 vrc = ptrVM.vtable()->pfnVMR3Resume(ptrVM.rawUVM(), enmReason);
7243
7244 if (aReason == Reason_Snapshot)
7245 mVMStateChangeCallbackDisabled = false;
7246 }
7247
7248 HRESULT hrc = RT_SUCCESS(vrc) ? S_OK
7249 : setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not resume the machine execution (%Rrc)"), vrc);
7250
7251 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
7252 LogFlowThisFuncLeave();
7253 return hrc;
7254}
7255
7256/**
7257 * Internal entry point for saving state of a VM for a specific reason. This
7258 * method is completely synchronous.
7259 *
7260 * The machine state is already set appropriately. It is only changed when
7261 * saving state actually paused the VM (happens with live snapshots and
7262 * teleportation), and in this case reflects the now paused variant.
7263 *
7264 * @note Locks this object for writing.
7265 */
7266HRESULT Console::i_saveState(Reason_T aReason, const ComPtr<IProgress> &aProgress, const ComPtr<ISnapshot> &aSnapshot,
7267 const Utf8Str &aStateFilePath, bool aPauseVM, bool &aLeftPaused)
7268{
7269 LogFlowThisFuncEnter();
7270 aLeftPaused = false;
7271
7272 AssertReturn(!aProgress.isNull(), E_INVALIDARG);
7273 AssertReturn(!aStateFilePath.isEmpty(), E_INVALIDARG);
7274 Assert(aSnapshot.isNull() || aReason == Reason_Snapshot);
7275
7276 AutoCaller autoCaller(this);
7277 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
7278
7279 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7280
7281 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
7282 if ( mMachineState != MachineState_Saving
7283 && mMachineState != MachineState_LiveSnapshotting
7284 && mMachineState != MachineState_OnlineSnapshotting
7285 && mMachineState != MachineState_Teleporting
7286 && mMachineState != MachineState_TeleportingPausedVM)
7287 return setError(VBOX_E_INVALID_VM_STATE,
7288 tr("Cannot save the execution state as the machine is not running or paused (machine state: %s)"),
7289 Global::stringifyMachineState(mMachineState));
7290 bool fContinueAfterwards = mMachineState != MachineState_Saving;
7291
7292 Bstr strDisableSaveState;
7293 mMachine->GetExtraData(Bstr("VBoxInternal2/DisableSaveState").raw(), strDisableSaveState.asOutParam());
7294 if (strDisableSaveState == "1")
7295 return setError(VBOX_E_VM_ERROR,
7296 tr("Saving the execution state is disabled for this VM"));
7297
7298 if (aReason != Reason_Unspecified)
7299 LogRel(("Saving state of VM, reason '%s'\n", ::stringifyReason(aReason)));
7300
7301 /* ensure the directory for the saved state file exists */
7302 {
7303 Utf8Str dir = aStateFilePath;
7304 dir.stripFilename();
7305 if (!RTDirExists(dir.c_str()))
7306 {
7307 int vrc = RTDirCreateFullPath(dir.c_str(), 0700);
7308 if (RT_FAILURE(vrc))
7309 return setErrorBoth(VBOX_E_FILE_ERROR, vrc, tr("Could not create a directory '%s' to save the state to (%Rrc)"),
7310 dir.c_str(), vrc);
7311 }
7312 }
7313
7314 /* Get the VM handle early, we need it in several places. */
7315 SafeVMPtr ptrVM(this);
7316 HRESULT hrc = ptrVM.hrc();
7317 if (SUCCEEDED(hrc))
7318 {
7319 bool fPaused = false;
7320 if (aPauseVM)
7321 {
7322 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
7323 alock.release();
7324 VMSUSPENDREASON enmReason = VMSUSPENDREASON_USER;
7325 if (aReason == Reason_HostSuspend)
7326 enmReason = VMSUSPENDREASON_HOST_SUSPEND;
7327 else if (aReason == Reason_HostBatteryLow)
7328 enmReason = VMSUSPENDREASON_HOST_BATTERY_LOW;
7329 int vrc = ptrVM.vtable()->pfnVMR3Suspend(ptrVM.rawUVM(), enmReason);
7330 alock.acquire();
7331
7332 if (RT_SUCCESS(vrc))
7333 fPaused = true;
7334 else
7335 hrc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not suspend the machine execution (%Rrc)"), vrc);
7336 }
7337
7338 Bstr bstrStateKeyId;
7339 Bstr bstrStateKeyStore;
7340#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
7341 if (SUCCEEDED(hrc))
7342 {
7343 hrc = mMachine->COMGETTER(StateKeyId)(bstrStateKeyId.asOutParam());
7344 if (SUCCEEDED(hrc))
7345 {
7346 hrc = mMachine->COMGETTER(StateKeyStore)(bstrStateKeyStore.asOutParam());
7347 if (FAILED(hrc))
7348 hrc = setError(hrc, tr("Could not get key store for state file(%Rhrc (0x%08X))"), hrc, hrc);
7349 }
7350 else
7351 hrc = setError(hrc, tr("Could not get key id for state file(%Rhrc (0x%08X))"), hrc, hrc);
7352 }
7353#endif
7354
7355 if (SUCCEEDED(hrc))
7356 {
7357 LogFlowFunc(("Saving the state to '%s'...\n", aStateFilePath.c_str()));
7358
7359 mpVmm2UserMethods->pISnapshot = aSnapshot;
7360 mptrCancelableProgress = aProgress;
7361
7362 SsmStream ssmStream(this, ptrVM.vtable(), m_pKeyStore, bstrStateKeyId, bstrStateKeyStore);
7363 int vrc = ssmStream.create(aStateFilePath.c_str());
7364 if (RT_SUCCESS(vrc))
7365 {
7366 PCSSMSTRMOPS pStreamOps = NULL;
7367 void *pvStreamOpsUser = NULL;
7368 vrc = ssmStream.querySsmStrmOps(&pStreamOps, &pvStreamOpsUser);
7369 if (RT_SUCCESS(vrc))
7370 {
7371 alock.release();
7372
7373 vrc = ptrVM.vtable()->pfnVMR3Save(ptrVM.rawUVM(),
7374 NULL /*pszFilename*/,
7375 pStreamOps,
7376 pvStreamOpsUser,
7377 fContinueAfterwards,
7378 Console::i_stateProgressCallback,
7379 static_cast<IProgress *>(aProgress),
7380 &aLeftPaused);
7381
7382 alock.acquire();
7383 }
7384
7385 ssmStream.close();
7386 if (RT_FAILURE(vrc))
7387 {
7388 int vrc2 = RTFileDelete(aStateFilePath.c_str());
7389 AssertRC(vrc2);
7390 }
7391 }
7392
7393 mpVmm2UserMethods->pISnapshot = NULL;
7394 mptrCancelableProgress.setNull();
7395 if (RT_SUCCESS(vrc))
7396 {
7397 Assert(fContinueAfterwards || !aLeftPaused);
7398
7399 if (!fContinueAfterwards)
7400 {
7401 /*
7402 * The machine has been successfully saved, so power it down
7403 * (vmstateChangeCallback() will set state to Saved on success).
7404 * Note: we release the VM caller, otherwise it will deadlock.
7405 */
7406 ptrVM.release();
7407 alock.release();
7408 autoCaller.release();
7409
7410 HRESULT hrc2 = i_powerDown();
7411 AssertComRC(hrc2);
7412
7413 autoCaller.add();
7414 alock.acquire();
7415 }
7416 else if (fPaused)
7417 aLeftPaused = true;
7418 }
7419 else
7420 {
7421 if (fPaused)
7422 {
7423 alock.release();
7424 ptrVM.vtable()->pfnVMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_STATE_RESTORED);
7425 alock.acquire();
7426 }
7427 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to save the machine state to '%s' (%Rrc)"),
7428 aStateFilePath.c_str(), vrc);
7429 }
7430 }
7431 }
7432
7433 LogFlowFuncLeave();
7434 return S_OK;
7435}
7436
7437/**
7438 * Internal entry point for cancelling a VM save state.
7439 *
7440 * @note Locks this object for writing.
7441 */
7442HRESULT Console::i_cancelSaveState()
7443{
7444 LogFlowThisFuncEnter();
7445
7446 AutoCaller autoCaller(this);
7447 if (FAILED(autoCaller.hrc())) return autoCaller.hrc();
7448
7449 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7450
7451 /* Get the VM handle. */
7452 SafeVMPtr ptrVM(this);
7453 HRESULT hrc = ptrVM.hrc();
7454 if (SUCCEEDED(hrc))
7455 ptrVM.vtable()->pfnSSMR3Cancel(ptrVM.rawUVM());
7456
7457 LogFlowFuncLeave();
7458 return hrc;
7459}
7460
7461#ifdef VBOX_WITH_AUDIO_RECORDING
7462/**
7463 * Sends audio (frame) data to the recording routines.
7464 *
7465 * @returns HRESULT
7466 * @param pvData Audio data to send.
7467 * @param cbData Size (in bytes) of audio data to send.
7468 * @param uTimestampMs Timestamp (in ms) of audio data.
7469 */
7470HRESULT Console::i_recordingSendAudio(const void *pvData, size_t cbData, uint64_t uTimestampMs)
7471{
7472 if ( mRecording.mCtx.IsStarted()
7473 && mRecording.mCtx.IsFeatureEnabled(RecordingFeature_Audio))
7474 return mRecording.mCtx.SendAudioFrame(pvData, cbData, uTimestampMs);
7475
7476 return S_OK;
7477}
7478#endif /* VBOX_WITH_AUDIO_RECORDING */
7479
7480#ifdef VBOX_WITH_RECORDING
7481
7482int Console::i_recordingGetSettings(settings::RecordingSettings &recording)
7483{
7484 Assert(mMachine.isNotNull());
7485
7486 recording.applyDefaults();
7487
7488 ComPtr<IRecordingSettings> pRecordSettings;
7489 HRESULT hrc = mMachine->COMGETTER(RecordingSettings)(pRecordSettings.asOutParam());
7490 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7491
7492 BOOL fTemp;
7493 hrc = pRecordSettings->COMGETTER(Enabled)(&fTemp);
7494 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7495 recording.common.fEnabled = RT_BOOL(fTemp);
7496
7497 SafeIfaceArray<IRecordingScreenSettings> paRecScreens;
7498 hrc = pRecordSettings->COMGETTER(Screens)(ComSafeArrayAsOutParam(paRecScreens));
7499 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7500
7501 for (unsigned long i = 0; i < (unsigned long)paRecScreens.size(); ++i)
7502 {
7503 settings::RecordingScreenSettings recScreenSettings;
7504 ComPtr<IRecordingScreenSettings> pRecScreenSettings = paRecScreens[i];
7505
7506 hrc = pRecScreenSettings->COMGETTER(Enabled)(&fTemp);
7507 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7508 recScreenSettings.fEnabled = RT_BOOL(fTemp);
7509 com::SafeArray<RecordingFeature_T> vecFeatures;
7510 hrc = pRecScreenSettings->COMGETTER(Features)(ComSafeArrayAsOutParam(vecFeatures));
7511 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7512 /* Make sure to clear map first, as we want to (re-)set enabled features. */
7513 recScreenSettings.featureMap.clear();
7514 for (size_t f = 0; f < vecFeatures.size(); ++f)
7515 {
7516 if (vecFeatures[f] == RecordingFeature_Audio)
7517 recScreenSettings.featureMap[RecordingFeature_Audio] = true;
7518 else if (vecFeatures[f] == RecordingFeature_Video)
7519 recScreenSettings.featureMap[RecordingFeature_Video] = true;
7520 }
7521 hrc = pRecScreenSettings->COMGETTER(MaxTime)((ULONG *)&recScreenSettings.ulMaxTimeS);
7522 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7523 hrc = pRecScreenSettings->COMGETTER(MaxFileSize)((ULONG *)&recScreenSettings.File.ulMaxSizeMB);
7524 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7525 Bstr bstrTemp;
7526 hrc = pRecScreenSettings->COMGETTER(Filename)(bstrTemp.asOutParam());
7527 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7528 recScreenSettings.File.strName = bstrTemp;
7529 hrc = pRecScreenSettings->COMGETTER(Options)(bstrTemp.asOutParam());
7530 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7531 recScreenSettings.strOptions = bstrTemp;
7532 hrc = pRecScreenSettings->COMGETTER(AudioCodec)(&recScreenSettings.Audio.enmCodec);
7533 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7534 hrc = pRecScreenSettings->COMGETTER(AudioDeadline)(&recScreenSettings.Audio.enmDeadline);
7535 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7536 hrc = pRecScreenSettings->COMGETTER(AudioRateControlMode)(&recScreenSettings.Audio.enmRateCtlMode);
7537 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7538 hrc = pRecScreenSettings->COMGETTER(AudioHz)((ULONG *)&recScreenSettings.Audio.uHz);
7539 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7540 hrc = pRecScreenSettings->COMGETTER(AudioBits)((ULONG *)&recScreenSettings.Audio.cBits);
7541 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7542 hrc = pRecScreenSettings->COMGETTER(AudioChannels)((ULONG *)&recScreenSettings.Audio.cChannels);
7543 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7544 hrc = pRecScreenSettings->COMGETTER(VideoCodec)(&recScreenSettings.Video.enmCodec);
7545 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7546 hrc = pRecScreenSettings->COMGETTER(VideoWidth)((ULONG *)&recScreenSettings.Video.ulWidth);
7547 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7548 hrc = pRecScreenSettings->COMGETTER(VideoHeight)((ULONG *)&recScreenSettings.Video.ulHeight);
7549 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7550 hrc = pRecScreenSettings->COMGETTER(VideoDeadline)(&recScreenSettings.Video.enmDeadline);
7551 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7552 hrc = pRecScreenSettings->COMGETTER(VideoRateControlMode)(&recScreenSettings.Video.enmRateCtlMode);
7553 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7554 hrc = pRecScreenSettings->COMGETTER(VideoScalingMode)(&recScreenSettings.Video.enmScalingMode);
7555 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7556 hrc = pRecScreenSettings->COMGETTER(VideoRate)((ULONG *)&recScreenSettings.Video.ulRate);
7557 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7558 hrc = pRecScreenSettings->COMGETTER(VideoFPS)((ULONG *)&recScreenSettings.Video.ulFPS);
7559 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
7560
7561 recording.mapScreens[i] = recScreenSettings;
7562 }
7563
7564 Assert(recording.mapScreens.size() == paRecScreens.size());
7565
7566 return VINF_SUCCESS;
7567}
7568
7569/**
7570 * Creates the recording context.
7571 *
7572 * @returns VBox status code.
7573 */
7574int Console::i_recordingCreate(void)
7575{
7576 settings::RecordingSettings recordingSettings;
7577 int vrc = i_recordingGetSettings(recordingSettings);
7578 if (RT_SUCCESS(vrc))
7579 vrc = mRecording.mCtx.Create(this, recordingSettings);
7580
7581 LogFlowFuncLeaveRC(vrc);
7582 return vrc;
7583}
7584
7585/**
7586 * Destroys the recording context.
7587 */
7588void Console::i_recordingDestroy(void)
7589{
7590 mRecording.mCtx.Destroy();
7591}
7592
7593/**
7594 * Starts recording. Does nothing if recording is already active.
7595 *
7596 * @returns VBox status code.
7597 */
7598int Console::i_recordingStart(util::AutoWriteLock *pAutoLock /* = NULL */)
7599{
7600 RT_NOREF(pAutoLock);
7601
7602 if (mRecording.mCtx.IsStarted())
7603 return VINF_SUCCESS;
7604
7605 LogRel(("Recording: Starting ...\n"));
7606
7607 int vrc = mRecording.mCtx.Start();
7608 if (RT_SUCCESS(vrc))
7609 {
7610 for (unsigned uScreen = 0; uScreen < mRecording.mCtx.GetStreamCount(); uScreen++)
7611 mDisplay->i_recordingScreenChanged(uScreen);
7612 }
7613
7614 LogFlowFuncLeaveRC(vrc);
7615 return vrc;
7616}
7617
7618/**
7619 * Stops recording. Does nothing if recording is not active.
7620 */
7621int Console::i_recordingStop(util::AutoWriteLock *pAutoLock /* = NULL */)
7622{
7623 if (!mRecording.mCtx.IsStarted())
7624 return VINF_SUCCESS;
7625
7626 LogRel(("Recording: Stopping ...\n"));
7627
7628 int vrc = mRecording.mCtx.Stop();
7629 if (RT_SUCCESS(vrc))
7630 {
7631 const size_t cStreams = mRecording.mCtx.GetStreamCount();
7632 for (unsigned uScreen = 0; uScreen < cStreams; ++uScreen)
7633 mDisplay->i_recordingScreenChanged(uScreen);
7634
7635 if (pAutoLock)
7636 pAutoLock->release();
7637
7638 ComPtr<IRecordingSettings> pRecordSettings;
7639 HRESULT hrc = mMachine->COMGETTER(RecordingSettings)(pRecordSettings.asOutParam());
7640 ComAssertComRC(hrc);
7641 hrc = pRecordSettings->COMSETTER(Enabled)(FALSE);
7642 ComAssertComRC(hrc);
7643
7644 if (pAutoLock)
7645 pAutoLock->acquire();
7646 }
7647
7648 LogFlowFuncLeaveRC(vrc);
7649 return vrc;
7650}
7651
7652#endif /* VBOX_WITH_RECORDING */
7653
7654/**
7655 * Gets called by Session::UpdateMachineState()
7656 * (IInternalSessionControl::updateMachineState()).
7657 *
7658 * Must be called only in certain cases (see the implementation).
7659 *
7660 * @note Locks this object for writing.
7661 */
7662HRESULT Console::i_updateMachineState(MachineState_T aMachineState)
7663{
7664 AutoCaller autoCaller(this);
7665 AssertComRCReturnRC(autoCaller.hrc());
7666
7667 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7668
7669 AssertReturn( mMachineState == MachineState_Saving
7670 || mMachineState == MachineState_OnlineSnapshotting
7671 || mMachineState == MachineState_LiveSnapshotting
7672 || mMachineState == MachineState_DeletingSnapshotOnline
7673 || mMachineState == MachineState_DeletingSnapshotPaused
7674 || aMachineState == MachineState_Saving
7675 || aMachineState == MachineState_OnlineSnapshotting
7676 || aMachineState == MachineState_LiveSnapshotting
7677 || aMachineState == MachineState_DeletingSnapshotOnline
7678 || aMachineState == MachineState_DeletingSnapshotPaused
7679 , E_FAIL);
7680
7681 return i_setMachineStateLocally(aMachineState);
7682}
7683
7684/**
7685 * Gets called by Session::COMGETTER(NominalState)()
7686 * (IInternalSessionControl::getNominalState()).
7687 *
7688 * @note Locks this object for reading.
7689 */
7690HRESULT Console::i_getNominalState(MachineState_T &aNominalState)
7691{
7692 LogFlowThisFuncEnter();
7693
7694 AutoCaller autoCaller(this);
7695 AssertComRCReturnRC(autoCaller.hrc());
7696
7697 /* Get the VM handle. */
7698 SafeVMPtr ptrVM(this);
7699 if (!ptrVM.isOk())
7700 return ptrVM.hrc();
7701
7702 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7703
7704 MachineState_T enmMachineState = MachineState_Null;
7705 VMSTATE enmVMState = ptrVM.vtable()->pfnVMR3GetStateU(ptrVM.rawUVM());
7706 switch (enmVMState)
7707 {
7708 case VMSTATE_CREATING:
7709 case VMSTATE_CREATED:
7710 case VMSTATE_POWERING_ON:
7711 enmMachineState = MachineState_Starting;
7712 break;
7713 case VMSTATE_LOADING:
7714 enmMachineState = MachineState_Restoring;
7715 break;
7716 case VMSTATE_RESUMING:
7717 case VMSTATE_SUSPENDING:
7718 case VMSTATE_SUSPENDING_LS:
7719 case VMSTATE_SUSPENDING_EXT_LS:
7720 case VMSTATE_SUSPENDED:
7721 case VMSTATE_SUSPENDED_LS:
7722 case VMSTATE_SUSPENDED_EXT_LS:
7723 enmMachineState = MachineState_Paused;
7724 break;
7725 case VMSTATE_RUNNING:
7726 case VMSTATE_RUNNING_LS:
7727 case VMSTATE_RESETTING:
7728 case VMSTATE_RESETTING_LS:
7729 case VMSTATE_SOFT_RESETTING:
7730 case VMSTATE_SOFT_RESETTING_LS:
7731 case VMSTATE_DEBUGGING:
7732 case VMSTATE_DEBUGGING_LS:
7733 enmMachineState = MachineState_Running;
7734 break;
7735 case VMSTATE_SAVING:
7736 enmMachineState = MachineState_Saving;
7737 break;
7738 case VMSTATE_POWERING_OFF:
7739 case VMSTATE_POWERING_OFF_LS:
7740 case VMSTATE_DESTROYING:
7741 enmMachineState = MachineState_Stopping;
7742 break;
7743 case VMSTATE_OFF:
7744 case VMSTATE_OFF_LS:
7745 case VMSTATE_FATAL_ERROR:
7746 case VMSTATE_FATAL_ERROR_LS:
7747 case VMSTATE_LOAD_FAILURE:
7748 case VMSTATE_TERMINATED:
7749 enmMachineState = MachineState_PoweredOff;
7750 break;
7751 case VMSTATE_GURU_MEDITATION:
7752 case VMSTATE_GURU_MEDITATION_LS:
7753 enmMachineState = MachineState_Stuck;
7754 break;
7755 default:
7756 AssertMsgFailed(("%s\n", ptrVM.vtable()->pfnVMR3GetStateName(enmVMState)));
7757 enmMachineState = MachineState_PoweredOff;
7758 }
7759 aNominalState = enmMachineState;
7760
7761 LogFlowFuncLeave();
7762 return S_OK;
7763}
7764
7765void Console::i_onMousePointerShapeChange(bool fVisible, bool fAlpha,
7766 uint32_t xHot, uint32_t yHot,
7767 uint32_t width, uint32_t height,
7768 const uint8_t *pu8Shape,
7769 uint32_t cbShape)
7770{
7771#if 0
7772 LogFlowThisFuncEnter();
7773 LogFlowThisFunc(("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, height=%d, shape=%p\n",
7774 fVisible, fAlpha, xHot, yHot, width, height, pShape));
7775#endif
7776
7777 AutoCaller autoCaller(this);
7778 AssertComRCReturnVoid(autoCaller.hrc());
7779
7780 if (!mMouse.isNull())
7781 mMouse->updateMousePointerShape(fVisible, fAlpha, xHot, yHot, width, height, pu8Shape, cbShape);
7782
7783 com::SafeArray<BYTE> shape(cbShape);
7784 if (pu8Shape)
7785 memcpy(shape.raw(), pu8Shape, cbShape);
7786 ::FireMousePointerShapeChangedEvent(mEventSource, fVisible, fAlpha, xHot, yHot, width, height, ComSafeArrayAsInParam(shape));
7787
7788#if 0
7789 LogFlowThisFuncLeave();
7790#endif
7791}
7792
7793void Console::i_onMouseCapabilityChange(BOOL supportsAbsolute, BOOL supportsRelative,
7794 BOOL supportsTouchScreen, BOOL supportsTouchPad, BOOL needsHostCursor)
7795{
7796 LogFlowThisFunc(("supportsAbsolute=%d supportsRelative=%d supportsTouchScreen=%d supportsTouchPad=%d needsHostCursor=%d\n",
7797 supportsAbsolute, supportsRelative, supportsTouchScreen, supportsTouchPad, needsHostCursor));
7798
7799 AutoCaller autoCaller(this);
7800 AssertComRCReturnVoid(autoCaller.hrc());
7801
7802 ::FireMouseCapabilityChangedEvent(mEventSource, supportsAbsolute, supportsRelative, supportsTouchScreen, supportsTouchPad, needsHostCursor);
7803}
7804
7805void Console::i_onStateChange(MachineState_T machineState)
7806{
7807 AutoCaller autoCaller(this);
7808 AssertComRCReturnVoid(autoCaller.hrc());
7809 ::FireStateChangedEvent(mEventSource, machineState);
7810}
7811
7812void Console::i_onAdditionsStateChange()
7813{
7814 AutoCaller autoCaller(this);
7815 AssertComRCReturnVoid(autoCaller.hrc());
7816
7817 ::FireAdditionsStateChangedEvent(mEventSource);
7818}
7819
7820/**
7821 * @remarks This notification only is for reporting an incompatible
7822 * Guest Additions interface, *not* the Guest Additions version!
7823 *
7824 * The user will be notified inside the guest if new Guest
7825 * Additions are available (via VBoxTray/VBoxClient).
7826 */
7827void Console::i_onAdditionsOutdated()
7828{
7829 AutoCaller autoCaller(this);
7830 AssertComRCReturnVoid(autoCaller.hrc());
7831
7832 /** @todo implement this */
7833}
7834
7835void Console::i_onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
7836{
7837 AutoCaller autoCaller(this);
7838 AssertComRCReturnVoid(autoCaller.hrc());
7839
7840 ::FireKeyboardLedsChangedEvent(mEventSource, fNumLock, fCapsLock, fScrollLock);
7841}
7842
7843void Console::i_onUSBDeviceStateChange(IUSBDevice *aDevice, bool aAttached,
7844 IVirtualBoxErrorInfo *aError)
7845{
7846 AutoCaller autoCaller(this);
7847 AssertComRCReturnVoid(autoCaller.hrc());
7848
7849 ::FireUSBDeviceStateChangedEvent(mEventSource, aDevice, aAttached, aError);
7850}
7851
7852void Console::i_onRuntimeError(BOOL aFatal, IN_BSTR aErrorID, IN_BSTR aMessage)
7853{
7854 AutoCaller autoCaller(this);
7855 AssertComRCReturnVoid(autoCaller.hrc());
7856
7857 ::FireRuntimeErrorEvent(mEventSource, aFatal, aErrorID, aMessage);
7858}
7859
7860HRESULT Console::i_onShowWindow(BOOL aCheck, BOOL *aCanShow, LONG64 *aWinId)
7861{
7862 AssertReturn(aCanShow, E_POINTER);
7863 AssertReturn(aWinId, E_POINTER);
7864
7865 *aCanShow = FALSE;
7866 *aWinId = 0;
7867
7868 AutoCaller autoCaller(this);
7869 AssertComRCReturnRC(autoCaller.hrc());
7870
7871 ComPtr<IEvent> ptrEvent;
7872 if (aCheck)
7873 {
7874 *aCanShow = TRUE;
7875 HRESULT hrc = ::CreateCanShowWindowEvent(ptrEvent.asOutParam(), mEventSource);
7876 if (SUCCEEDED(hrc))
7877 {
7878 VBoxEventDesc EvtDesc(ptrEvent, mEventSource);
7879 BOOL fDelivered = EvtDesc.fire(5000); /* Wait up to 5 secs for delivery */
7880 //Assert(fDelivered);
7881 if (fDelivered)
7882 {
7883 // bit clumsy
7884 ComPtr<ICanShowWindowEvent> ptrCanShowEvent = ptrEvent;
7885 if (ptrCanShowEvent)
7886 {
7887 BOOL fVetoed = FALSE;
7888 BOOL fApproved = FALSE;
7889 ptrCanShowEvent->IsVetoed(&fVetoed);
7890 ptrCanShowEvent->IsApproved(&fApproved);
7891 *aCanShow = fApproved || !fVetoed;
7892 }
7893 else
7894 AssertFailed();
7895 }
7896 }
7897 }
7898 else
7899 {
7900 HRESULT hrc = ::CreateShowWindowEvent(ptrEvent.asOutParam(), mEventSource, 0);
7901 if (SUCCEEDED(hrc))
7902 {
7903 VBoxEventDesc EvtDesc(ptrEvent, mEventSource);
7904 BOOL fDelivered = EvtDesc.fire(5000); /* Wait up to 5 secs for delivery */
7905 //Assert(fDelivered);
7906 if (fDelivered)
7907 {
7908 ComPtr<IShowWindowEvent> ptrShowEvent = ptrEvent;
7909 if (ptrShowEvent)
7910 {
7911 LONG64 idWindow = 0;
7912 ptrShowEvent->COMGETTER(WinId)(&idWindow);
7913 if (idWindow != 0 && *aWinId == 0)
7914 *aWinId = idWindow;
7915 }
7916 else
7917 AssertFailed();
7918 }
7919 }
7920 }
7921
7922 return S_OK;
7923}
7924
7925// private methods
7926////////////////////////////////////////////////////////////////////////////////
7927
7928/**
7929 * Loads the VMM if needed.
7930 *
7931 * @returns COM status.
7932 * @param pszVMMMod The VMM module to load.
7933 * @remarks Caller must write lock the console object.
7934 */
7935HRESULT Console::i_loadVMM(const char *pszVMMMod) RT_NOEXCEPT
7936{
7937 if ( mhModVMM == NIL_RTLDRMOD
7938 || mpVMM == NULL)
7939 {
7940 Assert(!mpVMM);
7941
7942 HRESULT hrc;
7943 RTERRINFOSTATIC ErrInfo;
7944 RTLDRMOD hModVMM = NIL_RTLDRMOD;
7945 int vrc = SUPR3HardenedLdrLoadAppPriv(pszVMMMod, &hModVMM, RTLDRLOAD_FLAGS_LOCAL, RTErrInfoInitStatic(&ErrInfo));
7946 if (RT_SUCCESS(vrc))
7947 {
7948 PFNVMMGETVTABLE pfnGetVTable = NULL;
7949 vrc = RTLdrGetSymbol(hModVMM, VMMR3VTABLE_GETTER_NAME, (void **)&pfnGetVTable);
7950 if (pfnGetVTable)
7951 {
7952 PCVMMR3VTABLE pVMM = pfnGetVTable();
7953 if (pVMM)
7954 {
7955 if (VMMR3VTABLE_IS_COMPATIBLE(pVMM->uMagicVersion))
7956 {
7957 if (pVMM->uMagicVersion == pVMM->uMagicVersionEnd)
7958 {
7959 mhModVMM = hModVMM;
7960 mpVMM = pVMM;
7961 LogFunc(("mhLdrVMM=%p phVMM=%p uMagicVersion=%#RX64\n", hModVMM, pVMM, pVMM->uMagicVersion));
7962 return S_OK;
7963 }
7964
7965 hrc = setErrorVrc(vrc, "Bogus VMM vtable: uMagicVersion=%#RX64 uMagicVersionEnd=%#RX64",
7966 pVMM->uMagicVersion, pVMM->uMagicVersionEnd);
7967 }
7968 else
7969 hrc = setErrorVrc(vrc, "Incompatible of bogus VMM version magic: %#RX64", pVMM->uMagicVersion);
7970 }
7971 else
7972 hrc = setErrorVrc(vrc, "pfnGetVTable return NULL!");
7973 }
7974 else
7975 hrc = setErrorVrc(vrc, "Failed to locate symbol '%s' in VBoxVMM: %Rrc", VMMR3VTABLE_GETTER_NAME, vrc);
7976 RTLdrClose(hModVMM);
7977 }
7978 else
7979 hrc = setErrorVrc(vrc, "Failed to load VBoxVMM: %#RTeic", &ErrInfo.Core);
7980 return hrc;
7981 }
7982
7983 return S_OK;
7984}
7985
7986/**
7987 * Increases the usage counter of the mpUVM pointer.
7988 *
7989 * Guarantees that VMR3Destroy() will not be called on it at least until
7990 * releaseVMCaller() is called.
7991 *
7992 * If this method returns a failure, the caller is not allowed to use mpUVM and
7993 * may return the failed result code to the upper level. This method sets the
7994 * extended error info on failure if \a aQuiet is false.
7995 *
7996 * Setting \a aQuiet to true is useful for methods that don't want to return
7997 * the failed result code to the caller when this method fails (e.g. need to
7998 * silently check for the mpUVM availability).
7999 *
8000 * When mpUVM is NULL but \a aAllowNullVM is true, a corresponding error will be
8001 * returned instead of asserting. Having it false is intended as a sanity check
8002 * for methods that have checked mMachineState and expect mpUVM *NOT* to be
8003 * NULL.
8004 *
8005 * @param aQuiet true to suppress setting error info
8006 * @param aAllowNullVM true to accept mpUVM being NULL and return a failure
8007 * (otherwise this method will assert if mpUVM is NULL)
8008 *
8009 * @note Locks this object for writing.
8010 */
8011HRESULT Console::i_addVMCaller(bool aQuiet /* = false */,
8012 bool aAllowNullVM /* = false */)
8013{
8014 RT_NOREF(aAllowNullVM);
8015 AutoCaller autoCaller(this);
8016 /** @todo Fix race during console/VM reference destruction, refer @bugref{6318}
8017 * comment 25. */
8018 if (FAILED(autoCaller.hrc()))
8019 return autoCaller.hrc();
8020
8021 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8022
8023 if (mVMDestroying)
8024 {
8025 /* powerDown() is waiting for all callers to finish */
8026 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED, tr("The virtual machine is being powered down"));
8027 }
8028
8029 if (mpUVM == NULL)
8030 {
8031 Assert(aAllowNullVM == true);
8032
8033 /* The machine is not powered up */
8034 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED, tr("The virtual machine is not powered up"));
8035 }
8036
8037 ++mVMCallers;
8038
8039 return S_OK;
8040}
8041
8042/**
8043 * Decreases the usage counter of the mpUVM pointer.
8044 *
8045 * Must always complete the addVMCaller() call after the mpUVM pointer is no
8046 * more necessary.
8047 *
8048 * @note Locks this object for writing.
8049 */
8050void Console::i_releaseVMCaller()
8051{
8052 AutoCaller autoCaller(this);
8053 AssertComRCReturnVoid(autoCaller.hrc());
8054
8055 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8056
8057 AssertReturnVoid(mpUVM != NULL);
8058
8059 Assert(mVMCallers > 0);
8060 --mVMCallers;
8061
8062 if (mVMCallers == 0 && mVMDestroying)
8063 {
8064 /* inform powerDown() there are no more callers */
8065 RTSemEventSignal(mVMZeroCallersSem);
8066 }
8067}
8068
8069
8070/**
8071 * Helper for SafeVMPtrBase.
8072 */
8073HRESULT Console::i_safeVMPtrRetainer(PUVM *a_ppUVM, PCVMMR3VTABLE *a_ppVMM, bool a_Quiet) RT_NOEXCEPT
8074{
8075 *a_ppUVM = NULL;
8076 *a_ppVMM = NULL;
8077
8078 AutoCaller autoCaller(this);
8079 AssertComRCReturnRC(autoCaller.hrc());
8080 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8081
8082 /*
8083 * Repeat the checks done by addVMCaller.
8084 */
8085 if (mVMDestroying) /* powerDown() is waiting for all callers to finish */
8086 return a_Quiet
8087 ? E_ACCESSDENIED
8088 : setError(E_ACCESSDENIED, tr("The virtual machine is being powered down"));
8089 PUVM const pUVM = mpUVM;
8090 if (!pUVM)
8091 return a_Quiet
8092 ? E_ACCESSDENIED
8093 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
8094 PCVMMR3VTABLE const pVMM = mpVMM;
8095 if (!pVMM)
8096 return a_Quiet
8097 ? E_ACCESSDENIED
8098 : setError(E_ACCESSDENIED, tr("No VMM loaded!"));
8099
8100 /*
8101 * Retain a reference to the user mode VM handle and get the global handle.
8102 */
8103 uint32_t cRefs = pVMM->pfnVMR3RetainUVM(pUVM);
8104 if (cRefs == UINT32_MAX)
8105 return a_Quiet
8106 ? E_ACCESSDENIED
8107 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
8108
8109 /* done */
8110 *a_ppUVM = pUVM;
8111 *a_ppVMM = pVMM;
8112 return S_OK;
8113}
8114
8115void Console::i_safeVMPtrReleaser(PUVM *a_ppUVM)
8116{
8117 PUVM const pUVM = *a_ppUVM;
8118 *a_ppUVM = NULL;
8119 if (pUVM)
8120 {
8121 PCVMMR3VTABLE const pVMM = mpVMM;
8122 if (pVMM)
8123 pVMM->pfnVMR3ReleaseUVM(pUVM);
8124 }
8125}
8126
8127
8128#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
8129/*static*/
8130DECLCALLBACK(int) Console::i_logEncryptedOpen(PCRTLOGOUTPUTIF pIf, void *pvUser, const char *pszFilename, uint32_t fFlags)
8131{
8132 RT_NOREF(pIf);
8133 Console *pConsole = static_cast<Console *>(pvUser);
8134 RTVFSFILE hVfsFile = NIL_RTVFSFILE;
8135
8136 int vrc = RTVfsFileOpenNormal(pszFilename, fFlags, &hVfsFile);
8137 if (RT_SUCCESS(vrc))
8138 {
8139 PCVBOXCRYPTOIF pCryptoIf = NULL;
8140 vrc = pConsole->i_retainCryptoIf(&pCryptoIf);
8141 if (RT_SUCCESS(vrc))
8142 {
8143 SecretKey *pKey = NULL;
8144
8145 vrc = pConsole->m_pKeyStore->retainSecretKey(pConsole->m_strLogKeyId, &pKey);
8146 if (RT_SUCCESS(vrc))
8147 {
8148 const char *pszPassword = (const char *)pKey->getKeyBuffer();
8149
8150 vrc = pCryptoIf->pfnCryptoFileFromVfsFile(hVfsFile, pConsole->m_strLogKeyStore.c_str(), pszPassword,
8151 &pConsole->m_hVfsFileLog);
8152 pKey->release();
8153 }
8154
8155 /* On success we keep the reference to keep the cryptographic module loaded. */
8156 if (RT_FAILURE(vrc))
8157 pConsole->i_releaseCryptoIf(pCryptoIf);
8158 }
8159
8160 /* Always do this because the encrypted log has retained a reference to the underlying file. */
8161 RTVfsFileRelease(hVfsFile);
8162 if (RT_FAILURE(vrc))
8163 RTFileDelete(pszFilename);
8164 }
8165
8166 return vrc;
8167}
8168
8169
8170/*static*/
8171DECLCALLBACK(int) Console::i_logEncryptedClose(PCRTLOGOUTPUTIF pIf, void *pvUser)
8172{
8173 RT_NOREF(pIf);
8174 Console *pConsole = static_cast<Console *>(pvUser);
8175
8176 RTVfsFileRelease(pConsole->m_hVfsFileLog);
8177 pConsole->m_hVfsFileLog = NIL_RTVFSFILE;
8178 return VINF_SUCCESS;
8179}
8180
8181
8182/*static*/
8183DECLCALLBACK(int) Console::i_logEncryptedDelete(PCRTLOGOUTPUTIF pIf, void *pvUser, const char *pszFilename)
8184{
8185 RT_NOREF(pIf, pvUser);
8186 return RTFileDelete(pszFilename);
8187}
8188
8189
8190/*static*/
8191DECLCALLBACK(int) Console::i_logEncryptedRename(PCRTLOGOUTPUTIF pIf, void *pvUser, const char *pszFilenameOld,
8192 const char *pszFilenameNew, uint32_t fFlags)
8193{
8194 RT_NOREF(pIf, pvUser);
8195 return RTFileRename(pszFilenameOld, pszFilenameNew, fFlags);
8196}
8197
8198
8199/*static*/
8200DECLCALLBACK(int) Console::i_logEncryptedQuerySize(PCRTLOGOUTPUTIF pIf, void *pvUser, uint64_t *pcbSize)
8201{
8202 RT_NOREF(pIf);
8203 Console *pConsole = static_cast<Console *>(pvUser);
8204
8205 return RTVfsFileQuerySize(pConsole->m_hVfsFileLog, pcbSize);
8206}
8207
8208
8209/*static*/
8210DECLCALLBACK(int) Console::i_logEncryptedWrite(PCRTLOGOUTPUTIF pIf, void *pvUser, const void *pvBuf,
8211 size_t cbWrite, size_t *pcbWritten)
8212{
8213 RT_NOREF(pIf);
8214 Console *pConsole = static_cast<Console *>(pvUser);
8215
8216 return RTVfsFileWrite(pConsole->m_hVfsFileLog, pvBuf, cbWrite, pcbWritten);
8217}
8218
8219
8220/*static*/
8221DECLCALLBACK(int) Console::i_logEncryptedFlush(PCRTLOGOUTPUTIF pIf, void *pvUser)
8222{
8223 RT_NOREF(pIf);
8224 Console *pConsole = static_cast<Console *>(pvUser);
8225
8226 return RTVfsFileFlush(pConsole->m_hVfsFileLog);
8227}
8228#endif
8229
8230
8231/**
8232 * Initialize the release logging facility. In case something
8233 * goes wrong, there will be no release logging. Maybe in the future
8234 * we can add some logic to use different file names in this case.
8235 * Note that the logic must be in sync with Machine::DeleteSettings().
8236 */
8237HRESULT Console::i_consoleInitReleaseLog(const ComPtr<IMachine> aMachine)
8238{
8239 Bstr bstrLogFolder;
8240 HRESULT hrc = aMachine->COMGETTER(LogFolder)(bstrLogFolder.asOutParam());
8241 if (FAILED(hrc))
8242 return hrc;
8243 Utf8Str strLogDir = bstrLogFolder;
8244
8245 /* make sure the Logs folder exists */
8246 Assert(strLogDir.length());
8247 if (!RTDirExists(strLogDir.c_str()))
8248 RTDirCreateFullPath(strLogDir.c_str(), 0700);
8249
8250 Utf8StrFmt logFile("%s%cVBox.log", strLogDir.c_str(), RTPATH_DELIMITER);
8251 Utf8StrFmt pngFile("%s%cVBox.png", strLogDir.c_str(), RTPATH_DELIMITER);
8252
8253 /*
8254 * Age the old log files.
8255 * Rename .(n-1) to .(n), .(n-2) to .(n-1), ..., and the last log file to .1
8256 * Overwrite target files in case they exist.
8257 */
8258 ComPtr<IVirtualBox> pVirtualBox;
8259 aMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
8260 ComPtr<ISystemProperties> pSystemProperties;
8261 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
8262 ULONG cHistoryFiles = 3;
8263 pSystemProperties->COMGETTER(LogHistoryCount)(&cHistoryFiles);
8264 if (cHistoryFiles)
8265 {
8266 for (int i = cHistoryFiles - 1; i >= 0; i--)
8267 {
8268 Utf8Str *files[] = { &logFile, &pngFile };
8269 Utf8Str oldName, newName;
8270
8271 for (unsigned int j = 0; j < RT_ELEMENTS(files); ++j)
8272 {
8273 if (i > 0)
8274 oldName.printf("%s.%d", files[j]->c_str(), i);
8275 else
8276 oldName = *files[j];
8277 newName.printf("%s.%d", files[j]->c_str(), i + 1);
8278
8279 /* If the old file doesn't exist, delete the new file (if it
8280 * exists) to provide correct rotation even if the sequence is
8281 * broken */
8282 if (RTFileRename(oldName.c_str(), newName.c_str(), RTFILEMOVE_FLAGS_REPLACE) == VERR_FILE_NOT_FOUND)
8283 RTFileDelete(newName.c_str());
8284 }
8285 }
8286 }
8287
8288 Bstr bstrLogKeyId;
8289 Bstr bstrLogKeyStore;
8290 PCRTLOGOUTPUTIF pLogOutputIf = NULL;
8291 void *pvLogOutputUser = NULL;
8292 int vrc = VINF_SUCCESS;
8293#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
8294 hrc = aMachine->COMGETTER(LogKeyId)(bstrLogKeyId.asOutParam());
8295 if (SUCCEEDED(hrc))
8296 {
8297 hrc = aMachine->COMGETTER(LogKeyStore)(bstrLogKeyStore.asOutParam());
8298 if ( SUCCEEDED(hrc)
8299 && bstrLogKeyId.isNotEmpty()
8300 && bstrLogKeyStore.isNotEmpty())
8301 {
8302 m_LogOutputIf.pfnOpen = Console::i_logEncryptedOpen;
8303 m_LogOutputIf.pfnClose = Console::i_logEncryptedClose;
8304 m_LogOutputIf.pfnDelete = Console::i_logEncryptedDelete;
8305 m_LogOutputIf.pfnRename = Console::i_logEncryptedRename;
8306 m_LogOutputIf.pfnQuerySize = Console::i_logEncryptedQuerySize;
8307 m_LogOutputIf.pfnWrite = Console::i_logEncryptedWrite;
8308 m_LogOutputIf.pfnFlush = Console::i_logEncryptedFlush;
8309
8310 m_strLogKeyId = Utf8Str(bstrLogKeyId);
8311 m_strLogKeyStore = Utf8Str(bstrLogKeyStore);
8312
8313 pLogOutputIf = &m_LogOutputIf;
8314 pvLogOutputUser = this;
8315 m_fEncryptedLog = true;
8316 }
8317 }
8318
8319 if (RT_FAILURE(vrc))
8320 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to set encryption for release log (%Rrc)"), vrc);
8321 else
8322#endif
8323 {
8324 RTERRINFOSTATIC ErrInfo;
8325 vrc = com::VBoxLogRelCreateEx("VM", logFile.c_str(),
8326 RTLOGFLAGS_PREFIX_TIME_PROG | RTLOGFLAGS_RESTRICT_GROUPS,
8327 "all all.restrict -default.restrict",
8328 "VBOX_RELEASE_LOG", RTLOGDEST_FILE,
8329 32768 /* cMaxEntriesPerGroup */,
8330 0 /* cHistory */, 0 /* uHistoryFileTime */,
8331 0 /* uHistoryFileSize */,
8332 pLogOutputIf, pvLogOutputUser,
8333 RTErrInfoInitStatic(&ErrInfo));
8334 if (RT_FAILURE(vrc))
8335 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to open release log (%s, %Rrc)"), ErrInfo.Core.pszMsg, vrc);
8336 }
8337
8338 /* If we've made any directory changes, flush the directory to increase
8339 the likelihood that the log file will be usable after a system panic.
8340
8341 Tip: Try 'export VBOX_RELEASE_LOG_FLAGS=flush' if the last bits of the log
8342 is missing. Just don't have too high hopes for this to help. */
8343 if (SUCCEEDED(hrc) || cHistoryFiles)
8344 RTDirFlush(strLogDir.c_str());
8345
8346 return hrc;
8347}
8348
8349/**
8350 * Common worker for PowerUp and PowerUpPaused.
8351 *
8352 * @returns COM status code.
8353 *
8354 * @param aProgress Where to return the progress object.
8355 * @param aPaused true if PowerUpPaused called.
8356 */
8357HRESULT Console::i_powerUp(IProgress **aProgress, bool aPaused)
8358{
8359 LogFlowThisFuncEnter();
8360
8361 CheckComArgOutPointerValid(aProgress);
8362
8363 AutoCaller autoCaller(this);
8364 HRESULT hrc = autoCaller.hrc();
8365 if (FAILED(hrc))
8366 return hrc;
8367
8368 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8369 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
8370
8371 if (Global::IsOnlineOrTransient(mMachineState))
8372 return setError(VBOX_E_INVALID_VM_STATE, tr("The virtual machine is already running or busy (machine state: %s)"),
8373 Global::stringifyMachineState(mMachineState));
8374
8375
8376 /* Set up release logging as early as possible after the check if
8377 * there is already a running VM which we shouldn't disturb. */
8378 hrc = i_consoleInitReleaseLog(mMachine);
8379 if (FAILED(hrc))
8380 return hrc;
8381
8382#ifdef VBOX_OPENSSL_FIPS
8383 LogRel(("crypto: FIPS mode %s\n", FIPS_mode() ? "enabled" : "FAILED"));
8384#endif
8385
8386 /* test and clear the TeleporterEnabled property */
8387 BOOL fTeleporterEnabled;
8388 hrc = mMachine->COMGETTER(TeleporterEnabled)(&fTeleporterEnabled);
8389 if (FAILED(hrc))
8390 return hrc;
8391
8392#if 0 /** @todo we should save it afterwards, but that isn't necessarily a good idea. Find a better place for this (VBoxSVC). */
8393 if (fTeleporterEnabled)
8394 {
8395 hrc = mMachine->COMSETTER(TeleporterEnabled)(FALSE);
8396 if (FAILED(hrc))
8397 return hrc;
8398 }
8399#endif
8400
8401 PCVMMR3VTABLE const pVMM = mpVMM;
8402 AssertPtrReturn(pVMM, E_UNEXPECTED);
8403
8404 ComObjPtr<Progress> pPowerupProgress;
8405 bool fBeganPoweringUp = false;
8406
8407 LONG cOperations = 1;
8408 LONG ulTotalOperationsWeight = 1;
8409 VMPowerUpTask *task = NULL;
8410
8411 try
8412 {
8413 /* Create a progress object to track progress of this operation. Must
8414 * be done as early as possible (together with BeginPowerUp()) as this
8415 * is vital for communicating as much as possible early powerup
8416 * failure information to the API caller */
8417 pPowerupProgress.createObject();
8418 Bstr progressDesc;
8419 if (mMachineState == MachineState_Saved || mMachineState == MachineState_AbortedSaved)
8420 progressDesc = tr("Restoring virtual machine");
8421 else if (fTeleporterEnabled)
8422 progressDesc = tr("Teleporting virtual machine");
8423 else
8424 progressDesc = tr("Starting virtual machine");
8425
8426 /*
8427 * Saved VMs will have to prove that their saved states seem kosher.
8428 */
8429 Utf8Str strSavedStateFile;
8430 Bstr bstrStateKeyId;
8431 Bstr bstrStateKeyStore;
8432
8433 if (mMachineState == MachineState_Saved || mMachineState == MachineState_AbortedSaved)
8434 {
8435 Bstr bstrSavedStateFile;
8436 hrc = mMachine->COMGETTER(StateFilePath)(bstrSavedStateFile.asOutParam());
8437 if (FAILED(hrc))
8438 throw hrc;
8439 strSavedStateFile = bstrSavedStateFile;
8440
8441#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
8442 hrc = mMachine->COMGETTER(StateKeyId)(bstrStateKeyId.asOutParam());
8443 if (FAILED(hrc))
8444 throw hrc;
8445 hrc = mMachine->COMGETTER(StateKeyStore)(bstrStateKeyStore.asOutParam());
8446 if (FAILED(hrc))
8447 throw hrc;
8448#endif
8449
8450 ComAssertRet(bstrSavedStateFile.isNotEmpty(), E_FAIL);
8451 SsmStream ssmStream(this, pVMM, m_pKeyStore, bstrStateKeyId, bstrStateKeyStore);
8452 int vrc = ssmStream.open(strSavedStateFile.c_str());
8453 if (RT_SUCCESS(vrc))
8454 {
8455 PCSSMSTRMOPS pStreamOps;
8456 void *pvStreamOpsUser;
8457
8458 vrc = ssmStream.querySsmStrmOps(&pStreamOps, &pvStreamOpsUser);
8459 if (RT_SUCCESS(vrc))
8460 vrc = pVMM->pfnSSMR3ValidateFile(NULL /*pszFilename*/, pStreamOps, pvStreamOpsUser,
8461 false /* fChecksumIt */);
8462 }
8463
8464 if (RT_FAILURE(vrc))
8465 {
8466 Utf8Str errMsg;
8467 switch (vrc)
8468 {
8469 case VERR_FILE_NOT_FOUND:
8470 errMsg.printf(tr("VM failed to start because the saved state file '%s' does not exist."),
8471 strSavedStateFile.c_str());
8472 break;
8473 default:
8474 errMsg.printf(tr("VM failed to start because the saved state file '%s' is invalid (%Rrc). "
8475 "Delete the saved state prior to starting the VM."), strSavedStateFile.c_str(), vrc);
8476 break;
8477 }
8478 throw setErrorBoth(VBOX_E_FILE_ERROR, vrc, errMsg.c_str());
8479 }
8480
8481 }
8482
8483 /* Read console data, including console shared folders, stored in the
8484 * saved state file (if not yet done).
8485 */
8486 hrc = i_loadDataFromSavedState();
8487 if (FAILED(hrc))
8488 throw hrc;
8489
8490 /* Check all types of shared folders and compose a single list */
8491 SharedFolderDataMap sharedFolders;
8492 {
8493 /* first, insert global folders */
8494 for (SharedFolderDataMap::const_iterator it = m_mapGlobalSharedFolders.begin();
8495 it != m_mapGlobalSharedFolders.end();
8496 ++it)
8497 {
8498 const SharedFolderData &d = it->second;
8499 sharedFolders[it->first] = d;
8500 }
8501
8502 /* second, insert machine folders */
8503 for (SharedFolderDataMap::const_iterator it = m_mapMachineSharedFolders.begin();
8504 it != m_mapMachineSharedFolders.end();
8505 ++it)
8506 {
8507 const SharedFolderData &d = it->second;
8508 sharedFolders[it->first] = d;
8509 }
8510
8511 /* third, insert console folders */
8512 for (SharedFolderMap::const_iterator it = m_mapSharedFolders.begin();
8513 it != m_mapSharedFolders.end();
8514 ++it)
8515 {
8516 ConsoleSharedFolder *pSF = it->second;
8517 AutoCaller sfCaller(pSF);
8518 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
8519 sharedFolders[it->first] = SharedFolderData(pSF->i_getHostPath(),
8520 pSF->i_isWritable(),
8521 pSF->i_isAutoMounted(),
8522 pSF->i_getAutoMountPoint());
8523 }
8524 }
8525
8526
8527 /* Setup task object and thread to carry out the operation
8528 * asynchronously */
8529 try { task = new VMPowerUpTask(this, pPowerupProgress); }
8530 catch (std::bad_alloc &) { throw hrc = E_OUTOFMEMORY; }
8531 if (!task->isOk())
8532 throw task->hrc();
8533
8534 task->mpfnConfigConstructor = i_configConstructor;
8535 task->mSharedFolders = sharedFolders;
8536 task->mStartPaused = aPaused;
8537 if (mMachineState == MachineState_Saved || mMachineState == MachineState_AbortedSaved)
8538 try { task->mSavedStateFile = strSavedStateFile; }
8539 catch (std::bad_alloc &) { throw hrc = E_OUTOFMEMORY; }
8540 task->mTeleporterEnabled = fTeleporterEnabled;
8541
8542 /* Reset differencing hard disks for which autoReset is true,
8543 * but only if the machine has no snapshots OR the current snapshot
8544 * is an OFFLINE snapshot; otherwise we would reset the current
8545 * differencing image of an ONLINE snapshot which contains the disk
8546 * state of the machine while it was previously running, but without
8547 * the corresponding machine state, which is equivalent to powering
8548 * off a running machine and not good idea
8549 */
8550 ComPtr<ISnapshot> pCurrentSnapshot;
8551 hrc = mMachine->COMGETTER(CurrentSnapshot)(pCurrentSnapshot.asOutParam());
8552 if (FAILED(hrc))
8553 throw hrc;
8554
8555 BOOL fCurrentSnapshotIsOnline = false;
8556 if (pCurrentSnapshot)
8557 {
8558 hrc = pCurrentSnapshot->COMGETTER(Online)(&fCurrentSnapshotIsOnline);
8559 if (FAILED(hrc))
8560 throw hrc;
8561 }
8562
8563 if (strSavedStateFile.isEmpty() && !fCurrentSnapshotIsOnline)
8564 {
8565 LogFlowThisFunc(("Looking for immutable images to reset\n"));
8566
8567 com::SafeIfaceArray<IMediumAttachment> atts;
8568 hrc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
8569 if (FAILED(hrc))
8570 throw hrc;
8571
8572 for (size_t i = 0;
8573 i < atts.size();
8574 ++i)
8575 {
8576 DeviceType_T devType;
8577 hrc = atts[i]->COMGETTER(Type)(&devType);
8578 /** @todo later applies to floppies as well */
8579 if (devType == DeviceType_HardDisk)
8580 {
8581 ComPtr<IMedium> pMedium;
8582 hrc = atts[i]->COMGETTER(Medium)(pMedium.asOutParam());
8583 if (FAILED(hrc))
8584 throw hrc;
8585
8586 /* needs autoreset? */
8587 BOOL autoReset = FALSE;
8588 hrc = pMedium->COMGETTER(AutoReset)(&autoReset);
8589 if (FAILED(hrc))
8590 throw hrc;
8591
8592 if (autoReset)
8593 {
8594 ComPtr<IProgress> pResetProgress;
8595 hrc = pMedium->Reset(pResetProgress.asOutParam());
8596 if (FAILED(hrc))
8597 throw hrc;
8598
8599 /* save for later use on the powerup thread */
8600 task->hardDiskProgresses.push_back(pResetProgress);
8601 }
8602 }
8603 }
8604 }
8605 else
8606 LogFlowThisFunc(("Machine has a current snapshot which is online, skipping immutable images reset\n"));
8607
8608 /* setup task object and thread to carry out the operation
8609 * asynchronously */
8610
8611#ifdef VBOX_WITH_EXTPACK
8612 mptrExtPackManager->i_dumpAllToReleaseLog();
8613#endif
8614
8615#ifdef RT_OS_SOLARIS
8616 /* setup host core dumper for the VM */
8617 Bstr value;
8618 hrc = mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpEnabled").raw(), value.asOutParam());
8619 if (SUCCEEDED(hrc) && value == "1")
8620 {
8621 Bstr coreDumpDir, coreDumpReplaceSys, coreDumpLive;
8622 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpDir").raw(), coreDumpDir.asOutParam());
8623 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpReplaceSystemDump").raw(), coreDumpReplaceSys.asOutParam());
8624 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpLive").raw(), coreDumpLive.asOutParam());
8625
8626 uint32_t fCoreFlags = 0;
8627 if ( coreDumpReplaceSys.isEmpty() == false
8628 && Utf8Str(coreDumpReplaceSys).toUInt32() == 1)
8629 fCoreFlags |= RTCOREDUMPER_FLAGS_REPLACE_SYSTEM_DUMP;
8630
8631 if ( coreDumpLive.isEmpty() == false
8632 && Utf8Str(coreDumpLive).toUInt32() == 1)
8633 fCoreFlags |= RTCOREDUMPER_FLAGS_LIVE_CORE;
8634
8635 Utf8Str strDumpDir(coreDumpDir);
8636 const char *pszDumpDir = strDumpDir.c_str();
8637 if ( pszDumpDir
8638 && *pszDumpDir == '\0')
8639 pszDumpDir = NULL;
8640
8641 int vrc;
8642 if ( pszDumpDir
8643 && !RTDirExists(pszDumpDir))
8644 {
8645 /*
8646 * Try create the directory.
8647 */
8648 vrc = RTDirCreateFullPath(pszDumpDir, 0700);
8649 if (RT_FAILURE(vrc))
8650 throw setErrorBoth(E_FAIL, vrc, tr("Failed to setup CoreDumper. Couldn't create dump directory '%s' (%Rrc)"),
8651 pszDumpDir, vrc);
8652 }
8653
8654 vrc = RTCoreDumperSetup(pszDumpDir, fCoreFlags);
8655 if (RT_FAILURE(vrc))
8656 throw setErrorBoth(E_FAIL, vrc, tr("Failed to setup CoreDumper (%Rrc)"), vrc);
8657 LogRel(("CoreDumper setup successful. pszDumpDir=%s fFlags=%#x\n", pszDumpDir ? pszDumpDir : ".", fCoreFlags));
8658 }
8659#endif
8660
8661
8662 // If there is immutable drive the process that.
8663 VMPowerUpTask::ProgressList progresses(task->hardDiskProgresses);
8664 if (aProgress && !progresses.empty())
8665 {
8666 for (VMPowerUpTask::ProgressList::const_iterator it = progresses.begin(); it != progresses.end(); ++it)
8667 {
8668 ++cOperations;
8669 ulTotalOperationsWeight += 1;
8670 }
8671 hrc = pPowerupProgress->init(static_cast<IConsole *>(this),
8672 progressDesc.raw(),
8673 TRUE, // Cancelable
8674 cOperations,
8675 ulTotalOperationsWeight,
8676 tr("Starting Hard Disk operations"),
8677 1);
8678 AssertComRCReturnRC(hrc);
8679 }
8680 else if ( mMachineState == MachineState_Saved
8681 || mMachineState == MachineState_AbortedSaved
8682 || !fTeleporterEnabled)
8683 hrc = pPowerupProgress->init(static_cast<IConsole *>(this),
8684 progressDesc.raw(),
8685 FALSE /* aCancelable */);
8686 else if (fTeleporterEnabled)
8687 hrc = pPowerupProgress->init(static_cast<IConsole *>(this),
8688 progressDesc.raw(),
8689 TRUE /* aCancelable */,
8690 3 /* cOperations */,
8691 10 /* ulTotalOperationsWeight */,
8692 tr("Teleporting virtual machine"),
8693 1 /* ulFirstOperationWeight */);
8694
8695 if (FAILED(hrc))
8696 throw hrc;
8697
8698 /* Tell VBoxSVC and Machine about the progress object so they can
8699 combine/proxy it to any openRemoteSession caller. */
8700 LogFlowThisFunc(("Calling BeginPowerUp...\n"));
8701 hrc = mControl->BeginPowerUp(pPowerupProgress);
8702 if (FAILED(hrc))
8703 {
8704 LogFlowThisFunc(("BeginPowerUp failed\n"));
8705 throw hrc;
8706 }
8707 fBeganPoweringUp = true;
8708
8709 LogFlowThisFunc(("Checking if canceled...\n"));
8710 BOOL fCanceled;
8711 hrc = pPowerupProgress->COMGETTER(Canceled)(&fCanceled);
8712 if (FAILED(hrc))
8713 throw hrc;
8714
8715 if (fCanceled)
8716 {
8717 LogFlowThisFunc(("Canceled in BeginPowerUp\n"));
8718 throw setError(E_FAIL, tr("Powerup was canceled"));
8719 }
8720 LogFlowThisFunc(("Not canceled yet.\n"));
8721
8722 /** @todo this code prevents starting a VM with unavailable bridged
8723 * networking interface. The only benefit is a slightly better error
8724 * message, which should be moved to the driver code. This is the
8725 * only reason why I left the code in for now. The driver allows
8726 * unavailable bridged networking interfaces in certain circumstances,
8727 * and this is sabotaged by this check. The VM will initially have no
8728 * network connectivity, but the user can fix this at runtime. */
8729#if 0
8730 /* the network cards will undergo a quick consistency check */
8731 for (ULONG slot = 0;
8732 slot < maxNetworkAdapters;
8733 ++slot)
8734 {
8735 ComPtr<INetworkAdapter> pNetworkAdapter;
8736 mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
8737 BOOL enabled = FALSE;
8738 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
8739 if (!enabled)
8740 continue;
8741
8742 NetworkAttachmentType_T netattach;
8743 pNetworkAdapter->COMGETTER(AttachmentType)(&netattach);
8744 switch (netattach)
8745 {
8746 case NetworkAttachmentType_Bridged:
8747 {
8748 /* a valid host interface must have been set */
8749 Bstr hostif;
8750 pNetworkAdapter->COMGETTER(HostInterface)(hostif.asOutParam());
8751 if (hostif.isEmpty())
8752 {
8753 throw setError(VBOX_E_HOST_ERROR,
8754 tr("VM cannot start because host interface networking requires a host interface name to be set"));
8755 }
8756 ComPtr<IVirtualBox> pVirtualBox;
8757 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
8758 ComPtr<IHost> pHost;
8759 pVirtualBox->COMGETTER(Host)(pHost.asOutParam());
8760 ComPtr<IHostNetworkInterface> pHostInterface;
8761 if (!SUCCEEDED(pHost->FindHostNetworkInterfaceByName(hostif.raw(), pHostInterface.asOutParam())))
8762 throw setError(VBOX_E_HOST_ERROR,
8763 tr("VM cannot start because the host interface '%ls' does not exist"), hostif.raw());
8764 break;
8765 }
8766 default:
8767 break;
8768 }
8769 }
8770#endif // 0
8771
8772
8773 /* setup task object and thread to carry out the operation
8774 * asynchronously */
8775 if (aProgress)
8776 {
8777 hrc = pPowerupProgress.queryInterfaceTo(aProgress);
8778 AssertComRCReturnRC(hrc);
8779 }
8780
8781#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
8782 task->mKeyStore = Utf8Str(bstrStateKeyStore);
8783 task->mKeyId = Utf8Str(bstrStateKeyId);
8784 task->m_pKeyStore = m_pKeyStore;
8785#endif
8786
8787 hrc = task->createThread();
8788 task = NULL;
8789 if (FAILED(hrc))
8790 throw hrc;
8791
8792 /* finally, set the state: no right to fail in this method afterwards
8793 * since we've already started the thread and it is now responsible for
8794 * any error reporting and appropriate state change! */
8795 if (mMachineState == MachineState_Saved || mMachineState == MachineState_AbortedSaved)
8796 i_setMachineState(MachineState_Restoring);
8797 else if (fTeleporterEnabled)
8798 i_setMachineState(MachineState_TeleportingIn);
8799 else
8800 i_setMachineState(MachineState_Starting);
8801 }
8802 catch (HRESULT aRC)
8803 {
8804 hrc = aRC;
8805 }
8806
8807 if (FAILED(hrc) && fBeganPoweringUp)
8808 {
8809
8810 /* The progress object will fetch the current error info */
8811 if (!pPowerupProgress.isNull())
8812 pPowerupProgress->i_notifyComplete(hrc);
8813
8814 /* Save the error info across the IPC below. Can't be done before the
8815 * progress notification above, as saving the error info deletes it
8816 * from the current context, and thus the progress object wouldn't be
8817 * updated correctly. */
8818 ErrorInfoKeeper eik;
8819
8820 /* signal end of operation */
8821 mControl->EndPowerUp(hrc);
8822 }
8823
8824 if (task)
8825 {
8826 ErrorInfoKeeper eik;
8827 delete task;
8828 }
8829
8830 LogFlowThisFunc(("mMachineState=%d, hrc=%Rhrc\n", mMachineState, hrc));
8831 LogFlowThisFuncLeave();
8832 return hrc;
8833}
8834
8835/**
8836 * Internal power off worker routine.
8837 *
8838 * This method may be called only at certain places with the following meaning
8839 * as shown below:
8840 *
8841 * - if the machine state is either Running or Paused, a normal
8842 * Console-initiated powerdown takes place (e.g. PowerDown());
8843 * - if the machine state is Saving, saveStateThread() has successfully done its
8844 * job;
8845 * - if the machine state is Starting or Restoring, powerUpThread() has failed
8846 * to start/load the VM;
8847 * - if the machine state is Stopping, the VM has powered itself off (i.e. not
8848 * as a result of the powerDown() call).
8849 *
8850 * Calling it in situations other than the above will cause unexpected behavior.
8851 *
8852 * Note that this method should be the only one that destroys mpUVM and sets it
8853 * to NULL.
8854 *
8855 * @param aProgress Progress object to run (may be NULL).
8856 *
8857 * @note Locks this object for writing.
8858 *
8859 * @note Never call this method from a thread that called addVMCaller() or
8860 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
8861 * release(). Otherwise it will deadlock.
8862 */
8863HRESULT Console::i_powerDown(IProgress *aProgress /*= NULL*/)
8864{
8865 LogFlowThisFuncEnter();
8866
8867 AutoCaller autoCaller(this);
8868 AssertComRCReturnRC(autoCaller.hrc());
8869
8870 ComPtr<IInternalProgressControl> pProgressControl(aProgress);
8871
8872 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8873
8874 /* Total # of steps for the progress object. Must correspond to the
8875 * number of "advance percent count" comments in this method! */
8876 enum { StepCount = 7 };
8877 /* current step */
8878 ULONG step = 0;
8879
8880 HRESULT hrc = S_OK;
8881 int vrc = VINF_SUCCESS;
8882
8883 /* sanity */
8884 Assert(mVMDestroying == false);
8885
8886 PCVMMR3VTABLE const pVMM = mpVMM;
8887 AssertPtrReturn(pVMM, E_UNEXPECTED);
8888 PUVM pUVM = mpUVM;
8889 AssertPtrReturn(pUVM, E_UNEXPECTED);
8890
8891 uint32_t cRefs = pVMM->pfnVMR3RetainUVM(pUVM);
8892 Assert(cRefs != UINT32_MAX); NOREF(cRefs);
8893
8894 AssertMsg( mMachineState == MachineState_Running
8895 || mMachineState == MachineState_Paused
8896 || mMachineState == MachineState_Stuck
8897 || mMachineState == MachineState_Starting
8898 || mMachineState == MachineState_Stopping
8899 || mMachineState == MachineState_Saving
8900 || mMachineState == MachineState_Restoring
8901 || mMachineState == MachineState_TeleportingPausedVM
8902 || mMachineState == MachineState_TeleportingIn
8903 , ("Invalid machine state: %s\n", ::stringifyMachineState(mMachineState)));
8904
8905 LogRel(("Console::powerDown(): A request to power off the VM has been issued (mMachineState=%s, InUninit=%d)\n",
8906 ::stringifyMachineState(mMachineState), getObjectState().getState() == ObjectState::InUninit));
8907
8908 /* Check if we need to power off the VM. In case of mVMPoweredOff=true, the
8909 * VM has already powered itself off in vmstateChangeCallback() and is just
8910 * notifying Console about that. In case of Starting or Restoring,
8911 * powerUpThread() is calling us on failure, so the VM is already off at
8912 * that point. */
8913 if ( !mVMPoweredOff
8914 && ( mMachineState == MachineState_Starting
8915 || mMachineState == MachineState_Restoring
8916 || mMachineState == MachineState_TeleportingIn)
8917 )
8918 mVMPoweredOff = true;
8919
8920 /*
8921 * Go to Stopping state if not already there.
8922 *
8923 * Note that we don't go from Saving/Restoring to Stopping because
8924 * vmstateChangeCallback() needs it to set the state to Saved on
8925 * VMSTATE_TERMINATED. In terms of protecting from inappropriate operations
8926 * while leaving the lock below, Saving or Restoring should be fine too.
8927 * Ditto for TeleportingPausedVM -> Teleported.
8928 */
8929 if ( mMachineState != MachineState_Saving
8930 && mMachineState != MachineState_Restoring
8931 && mMachineState != MachineState_Stopping
8932 && mMachineState != MachineState_TeleportingIn
8933 && mMachineState != MachineState_TeleportingPausedVM
8934 )
8935 i_setMachineState(MachineState_Stopping);
8936
8937 /* ----------------------------------------------------------------------
8938 * DONE with necessary state changes, perform the power down actions (it's
8939 * safe to release the object lock now if needed)
8940 * ---------------------------------------------------------------------- */
8941
8942 if (mDisplay)
8943 {
8944 alock.release();
8945
8946 mDisplay->i_notifyPowerDown();
8947
8948 alock.acquire();
8949 }
8950
8951 /* Stop the VRDP server to prevent new clients connection while VM is being
8952 * powered off. */
8953 if (mConsoleVRDPServer)
8954 {
8955 LogFlowThisFunc(("Stopping VRDP server...\n"));
8956
8957 /* Leave the lock since EMT could call us back as addVMCaller() */
8958 alock.release();
8959
8960 mConsoleVRDPServer->Stop();
8961
8962 alock.acquire();
8963 }
8964
8965 /* advance percent count */
8966 if (pProgressControl)
8967 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8968
8969
8970 /* ----------------------------------------------------------------------
8971 * Now, wait for all mpUVM callers to finish their work if there are still
8972 * some on other threads. NO methods that need mpUVM (or initiate other calls
8973 * that need it) may be called after this point
8974 * ---------------------------------------------------------------------- */
8975
8976 /* go to the destroying state to prevent from adding new callers */
8977 mVMDestroying = true;
8978
8979 if (mVMCallers > 0)
8980 {
8981 /* lazy creation */
8982 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
8983 RTSemEventCreate(&mVMZeroCallersSem);
8984
8985 LogFlowThisFunc(("Waiting for mpUVM callers (%d) to drop to zero...\n", mVMCallers));
8986
8987 alock.release();
8988
8989 RTSemEventWait(mVMZeroCallersSem, RT_INDEFINITE_WAIT);
8990
8991 alock.acquire();
8992 }
8993
8994 /* advance percent count */
8995 if (pProgressControl)
8996 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8997
8998 vrc = VINF_SUCCESS;
8999
9000 /*
9001 * Power off the VM if not already done that.
9002 * Leave the lock since EMT will call vmstateChangeCallback.
9003 *
9004 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
9005 * VM-(guest-)initiated power off happened in parallel a ms before this
9006 * call. So far, we let this error pop up on the user's side.
9007 */
9008 if (!mVMPoweredOff)
9009 {
9010 LogFlowThisFunc(("Powering off the VM...\n"));
9011 alock.release();
9012 vrc = pVMM->pfnVMR3PowerOff(pUVM);
9013#ifdef VBOX_WITH_EXTPACK
9014 mptrExtPackManager->i_callAllVmPowerOffHooks(this, pVMM->pfnVMR3GetVM(pUVM), pVMM);
9015#endif
9016 alock.acquire();
9017 }
9018
9019 /* advance percent count */
9020 if (pProgressControl)
9021 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
9022
9023#ifdef VBOX_WITH_HGCM
9024 /* Shutdown HGCM services before destroying the VM. */
9025 if (m_pVMMDev)
9026 {
9027 LogFlowThisFunc(("Shutdown HGCM...\n"));
9028
9029 /* Leave the lock since EMT might wait for it and will call us back as addVMCaller() */
9030 alock.release();
9031
9032# ifdef VBOX_WITH_SHARED_CLIPBOARD
9033 if (m_hHgcmSvcExtShCl)
9034 {
9035 HGCMHostUnregisterServiceExtension(m_hHgcmSvcExtShCl);
9036 m_hHgcmSvcExtShCl = NULL;
9037 }
9038 GuestShCl::destroyInstance();
9039#endif
9040
9041# ifdef VBOX_WITH_DRAG_AND_DROP
9042 if (m_hHgcmSvcExtDragAndDrop)
9043 {
9044 HGCMHostUnregisterServiceExtension(m_hHgcmSvcExtDragAndDrop);
9045 m_hHgcmSvcExtDragAndDrop = NULL;
9046 }
9047# endif
9048
9049 m_pVMMDev->hgcmShutdown();
9050
9051 alock.acquire();
9052 }
9053
9054 /* advance percent count */
9055 if (pProgressControl)
9056 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
9057
9058#endif /* VBOX_WITH_HGCM */
9059
9060 LogFlowThisFunc(("Ready for VM destruction.\n"));
9061
9062 /* If we are called from Console::uninit(), then try to destroy the VM even
9063 * on failure (this will most likely fail too, but what to do?..) */
9064 if (RT_SUCCESS(vrc) || getObjectState().getState() == ObjectState::InUninit)
9065 {
9066 /* If the machine has a USB controller, release all USB devices
9067 * (symmetric to the code in captureUSBDevices()) */
9068 if (mfVMHasUsbController)
9069 {
9070 alock.release();
9071 i_detachAllUSBDevices(false /* aDone */);
9072 alock.acquire();
9073 }
9074
9075 /* Now we've got to destroy the VM as well. (mpUVM is not valid beyond
9076 * this point). We release the lock before calling VMR3Destroy() because
9077 * it will result into calling destructors of drivers associated with
9078 * Console children which may in turn try to lock Console (e.g. by
9079 * instantiating SafeVMPtr to access mpUVM). It's safe here because
9080 * mVMDestroying is set which should prevent any activity. */
9081
9082 /* Set mpUVM to NULL early just in case if some old code is not using
9083 * addVMCaller()/releaseVMCaller(). (We have our own ref on pUVM.) */
9084 pVMM->pfnVMR3ReleaseUVM(mpUVM);
9085 mpUVM = NULL;
9086
9087 LogFlowThisFunc(("Destroying the VM...\n"));
9088
9089 alock.release();
9090
9091 vrc = pVMM->pfnVMR3Destroy(pUVM);
9092
9093 /* take the lock again */
9094 alock.acquire();
9095
9096 /* advance percent count */
9097 if (pProgressControl)
9098 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
9099
9100 if (RT_SUCCESS(vrc))
9101 {
9102 LogFlowThisFunc(("Machine has been destroyed (mMachineState=%d)\n",
9103 mMachineState));
9104 /* Note: the Console-level machine state change happens on the
9105 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
9106 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
9107 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
9108 * occurred yet. This is okay, because mMachineState is already
9109 * Stopping in this case, so any other attempt to call PowerDown()
9110 * will be rejected. */
9111 }
9112 else
9113 {
9114 /* bad bad bad, but what to do? (Give Console our UVM ref.) */
9115 mpUVM = pUVM;
9116 pUVM = NULL;
9117 hrc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not destroy the machine. (Error: %Rrc)"), vrc);
9118 }
9119
9120 /* Complete the detaching of the USB devices. */
9121 if (mfVMHasUsbController)
9122 {
9123 alock.release();
9124 i_detachAllUSBDevices(true /* aDone */);
9125 alock.acquire();
9126 }
9127
9128 /* advance percent count */
9129 if (pProgressControl)
9130 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
9131 }
9132 else
9133 hrc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not power off the machine. (Error: %Rrc)"), vrc);
9134
9135 /*
9136 * Finished with the destruction.
9137 *
9138 * Note that if something impossible happened and we've failed to destroy
9139 * the VM, mVMDestroying will remain true and mMachineState will be
9140 * something like Stopping, so most Console methods will return an error
9141 * to the caller.
9142 */
9143 if (pUVM != NULL)
9144 pVMM->pfnVMR3ReleaseUVM(pUVM);
9145 else
9146 mVMDestroying = false;
9147
9148 LogFlowThisFuncLeave();
9149 return hrc;
9150}
9151
9152/**
9153 * @note Locks this object for writing.
9154 */
9155HRESULT Console::i_setMachineState(MachineState_T aMachineState, bool aUpdateServer /* = true */)
9156{
9157 AutoCaller autoCaller(this);
9158 AssertComRCReturnRC(autoCaller.hrc());
9159
9160 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9161
9162 HRESULT hrc = S_OK;
9163
9164 if (mMachineState != aMachineState)
9165 {
9166 LogThisFunc(("machineState=%s -> %s aUpdateServer=%RTbool\n",
9167 ::stringifyMachineState(mMachineState), ::stringifyMachineState(aMachineState), aUpdateServer));
9168 LogRel(("Console: Machine state changed to '%s'\n", ::stringifyMachineState(aMachineState)));
9169 mMachineState = aMachineState;
9170
9171 /// @todo (dmik)
9172 // possibly, we need to redo onStateChange() using the dedicated
9173 // Event thread, like it is done in VirtualBox. This will make it
9174 // much safer (no deadlocks possible if someone tries to use the
9175 // console from the callback), however, listeners will lose the
9176 // ability to synchronously react to state changes (is it really
9177 // necessary??)
9178 LogFlowThisFunc(("Doing onStateChange()...\n"));
9179 i_onStateChange(aMachineState);
9180 LogFlowThisFunc(("Done onStateChange()\n"));
9181
9182 if (aUpdateServer)
9183 {
9184 /* Server notification MUST be done from under the lock; otherwise
9185 * the machine state here and on the server might go out of sync
9186 * which can lead to various unexpected results (like the machine
9187 * state being >= MachineState_Running on the server, while the
9188 * session state is already SessionState_Unlocked at the same time
9189 * there).
9190 *
9191 * Cross-lock conditions should be carefully watched out: calling
9192 * UpdateState we will require Machine and SessionMachine locks
9193 * (remember that here we're holding the Console lock here, and also
9194 * all locks that have been acquire by the thread before calling
9195 * this method).
9196 */
9197 LogFlowThisFunc(("Doing mControl->UpdateState()...\n"));
9198 hrc = mControl->UpdateState(aMachineState);
9199 LogFlowThisFunc(("mControl->UpdateState()=%Rhrc\n", hrc));
9200 }
9201 }
9202
9203 return hrc;
9204}
9205
9206/**
9207 * Searches for a shared folder with the given logical name
9208 * in the collection of shared folders.
9209 *
9210 * @param strName logical name of the shared folder
9211 * @param aSharedFolder where to return the found object
9212 * @param aSetError whether to set the error info if the folder is
9213 * not found
9214 * @return
9215 * S_OK when found or E_INVALIDARG when not found
9216 *
9217 * @note The caller must lock this object for writing.
9218 */
9219HRESULT Console::i_findSharedFolder(const Utf8Str &strName, ComObjPtr<ConsoleSharedFolder> &aSharedFolder, bool aSetError /* = false */)
9220{
9221 /* sanity check */
9222 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9223
9224 SharedFolderMap::const_iterator it = m_mapSharedFolders.find(strName);
9225 if (it != m_mapSharedFolders.end())
9226 {
9227 aSharedFolder = it->second;
9228 return S_OK;
9229 }
9230
9231 if (aSetError)
9232 setError(VBOX_E_FILE_ERROR, tr("Could not find a shared folder named '%s'."), strName.c_str());
9233 return VBOX_E_FILE_ERROR;
9234}
9235
9236/**
9237 * Fetches the list of global or machine shared folders from the server.
9238 *
9239 * @param aGlobal true to fetch global folders.
9240 *
9241 * @note The caller must lock this object for writing.
9242 */
9243HRESULT Console::i_fetchSharedFolders(BOOL aGlobal)
9244{
9245 /* sanity check */
9246 AssertReturn( getObjectState().getState() == ObjectState::InInit
9247 || isWriteLockOnCurrentThread(), E_FAIL);
9248
9249 LogFlowThisFunc(("Entering\n"));
9250
9251 /* Check if we're online and keep it that way. */
9252 SafeVMPtrQuiet ptrVM(this);
9253 AutoVMCallerQuietWeak autoVMCaller(this);
9254 bool const online = ptrVM.isOk()
9255 && m_pVMMDev
9256 && m_pVMMDev->isShFlActive();
9257
9258 HRESULT hrc = S_OK;
9259
9260 try
9261 {
9262 if (aGlobal)
9263 {
9264 /// @todo grab & process global folders when they are done
9265 }
9266 else
9267 {
9268 SharedFolderDataMap oldFolders;
9269 if (online)
9270 oldFolders = m_mapMachineSharedFolders;
9271
9272 m_mapMachineSharedFolders.clear();
9273
9274 SafeIfaceArray<ISharedFolder> folders;
9275 hrc = mMachine->COMGETTER(SharedFolders)(ComSafeArrayAsOutParam(folders));
9276 if (FAILED(hrc)) throw hrc;
9277
9278 for (size_t i = 0; i < folders.size(); ++i)
9279 {
9280 ComPtr<ISharedFolder> pSharedFolder = folders[i];
9281
9282 Bstr bstr;
9283 hrc = pSharedFolder->COMGETTER(Name)(bstr.asOutParam());
9284 if (FAILED(hrc)) throw hrc;
9285 Utf8Str strName(bstr);
9286
9287 hrc = pSharedFolder->COMGETTER(HostPath)(bstr.asOutParam());
9288 if (FAILED(hrc)) throw hrc;
9289 Utf8Str strHostPath(bstr);
9290
9291 BOOL writable;
9292 hrc = pSharedFolder->COMGETTER(Writable)(&writable);
9293 if (FAILED(hrc)) throw hrc;
9294
9295 BOOL autoMount;
9296 hrc = pSharedFolder->COMGETTER(AutoMount)(&autoMount);
9297 if (FAILED(hrc)) throw hrc;
9298
9299 hrc = pSharedFolder->COMGETTER(AutoMountPoint)(bstr.asOutParam());
9300 if (FAILED(hrc)) throw hrc;
9301 Utf8Str strAutoMountPoint(bstr);
9302
9303 m_mapMachineSharedFolders.insert(std::make_pair(strName,
9304 SharedFolderData(strHostPath, !!writable,
9305 !!autoMount, strAutoMountPoint)));
9306
9307 /* send changes to HGCM if the VM is running */
9308 if (online)
9309 {
9310 SharedFolderDataMap::iterator it = oldFolders.find(strName);
9311 if ( it == oldFolders.end()
9312 || it->second.m_strHostPath != strHostPath)
9313 {
9314 /* a new machine folder is added or
9315 * the existing machine folder is changed */
9316 if (m_mapSharedFolders.find(strName) != m_mapSharedFolders.end())
9317 ; /* the console folder exists, nothing to do */
9318 else
9319 {
9320 /* remove the old machine folder (when changed)
9321 * or the global folder if any (when new) */
9322 if ( it != oldFolders.end()
9323 || m_mapGlobalSharedFolders.find(strName) != m_mapGlobalSharedFolders.end()
9324 )
9325 {
9326 hrc = i_removeSharedFolder(strName);
9327 if (FAILED(hrc)) throw hrc;
9328 }
9329
9330 /* create the new machine folder */
9331 hrc = i_createSharedFolder(strName,
9332 SharedFolderData(strHostPath, !!writable, !!autoMount, strAutoMountPoint));
9333 if (FAILED(hrc)) throw hrc;
9334 }
9335 }
9336 /* forget the processed (or identical) folder */
9337 if (it != oldFolders.end())
9338 oldFolders.erase(it);
9339 }
9340 }
9341
9342 /* process outdated (removed) folders */
9343 if (online)
9344 {
9345 for (SharedFolderDataMap::const_iterator it = oldFolders.begin();
9346 it != oldFolders.end(); ++it)
9347 {
9348 if (m_mapSharedFolders.find(it->first) != m_mapSharedFolders.end())
9349 ; /* the console folder exists, nothing to do */
9350 else
9351 {
9352 /* remove the outdated machine folder */
9353 hrc = i_removeSharedFolder(it->first);
9354 if (FAILED(hrc)) throw hrc;
9355
9356 /* create the global folder if there is any */
9357 SharedFolderDataMap::const_iterator git =
9358 m_mapGlobalSharedFolders.find(it->first);
9359 if (git != m_mapGlobalSharedFolders.end())
9360 {
9361 hrc = i_createSharedFolder(git->first, git->second);
9362 if (FAILED(hrc)) throw hrc;
9363 }
9364 }
9365 }
9366 }
9367 }
9368 }
9369 catch (HRESULT hrc2)
9370 {
9371 hrc = hrc2;
9372 if (online)
9373 i_atVMRuntimeErrorCallbackF(0, "BrokenSharedFolder", N_("Broken shared folder!"));
9374 }
9375
9376 LogFlowThisFunc(("Leaving\n"));
9377
9378 return hrc;
9379}
9380
9381/**
9382 * Searches for a shared folder with the given name in the list of machine
9383 * shared folders and then in the list of the global shared folders.
9384 *
9385 * @param strName Name of the folder to search for.
9386 * @param aIt Where to store the pointer to the found folder.
9387 * @return @c true if the folder was found and @c false otherwise.
9388 *
9389 * @note The caller must lock this object for reading.
9390 */
9391bool Console::i_findOtherSharedFolder(const Utf8Str &strName,
9392 SharedFolderDataMap::const_iterator &aIt)
9393{
9394 /* sanity check */
9395 AssertReturn(isWriteLockOnCurrentThread(), false);
9396
9397 /* first, search machine folders */
9398 aIt = m_mapMachineSharedFolders.find(strName);
9399 if (aIt != m_mapMachineSharedFolders.end())
9400 return true;
9401
9402 /* second, search machine folders */
9403 aIt = m_mapGlobalSharedFolders.find(strName);
9404 if (aIt != m_mapGlobalSharedFolders.end())
9405 return true;
9406
9407 return false;
9408}
9409
9410/**
9411 * Calls the HGCM service to add a shared folder definition.
9412 *
9413 * @param strName Shared folder name.
9414 * @param aData Shared folder data.
9415 *
9416 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
9417 * @note Doesn't lock anything.
9418 */
9419HRESULT Console::i_createSharedFolder(const Utf8Str &strName, const SharedFolderData &aData)
9420{
9421 Log(("Adding shared folder '%s' -> '%s'\n", strName.c_str(), aData.m_strHostPath.c_str()));
9422
9423 /*
9424 * Sanity checks
9425 */
9426 ComAssertRet(strName.isNotEmpty(), E_FAIL);
9427 ComAssertRet(aData.m_strHostPath.isNotEmpty(), E_FAIL);
9428
9429 AssertReturn(mpUVM, E_FAIL);
9430 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
9431
9432 /*
9433 * Find out whether we should allow symbolic link creation.
9434 */
9435 Bstr bstrValue;
9436 HRESULT hrc = mMachine->GetExtraData(BstrFmt("VBoxInternal2/SharedFoldersEnableSymlinksCreate/%s", strName.c_str()).raw(),
9437 bstrValue.asOutParam());
9438 bool fSymlinksCreate = hrc == S_OK && bstrValue == "1";
9439
9440 /*
9441 * Check whether the path is valid and exists.
9442 */
9443 char szAbsHostPath[RTPATH_MAX];
9444 int vrc = RTPathAbs(aData.m_strHostPath.c_str(), szAbsHostPath, sizeof(szAbsHostPath));
9445 if (RT_FAILURE(vrc))
9446 return setErrorBoth(E_INVALIDARG, vrc, tr("Invalid shared folder path: '%s' (%Rrc)"), aData.m_strHostPath.c_str(), vrc);
9447
9448 /* Check whether the path is full (absolute). ASSUMING a RTPATH_MAX of ~4K
9449 this also checks that the length is within bounds of a SHFLSTRING. */
9450 if (RTPathCompare(aData.m_strHostPath.c_str(), szAbsHostPath) != 0)
9451 return setError(E_INVALIDARG, tr("Shared folder path '%s' is not absolute"), aData.m_strHostPath.c_str());
9452
9453 bool const fMissing = !RTPathExists(szAbsHostPath);
9454
9455 /*
9456 * Check the other two string lengths before converting them all to SHFLSTRINGS.
9457 */
9458 if (strName.length() >= _2K)
9459 return setError(E_INVALIDARG, tr("Shared folder name is too long: %zu bytes", "", strName.length()), strName.length());
9460 if (aData.m_strAutoMountPoint.length() >= RTPATH_MAX)
9461 return setError(E_INVALIDARG, tr("Shared folder mount point too long: %zu bytes", "",
9462 (int)aData.m_strAutoMountPoint.length()),
9463 aData.m_strAutoMountPoint.length());
9464
9465 PSHFLSTRING pHostPath = ShflStringDupUtf8AsUtf16(aData.m_strHostPath.c_str());
9466 PSHFLSTRING pName = ShflStringDupUtf8AsUtf16(strName.c_str());
9467 PSHFLSTRING pAutoMountPoint = ShflStringDupUtf8AsUtf16(aData.m_strAutoMountPoint.c_str());
9468 if (pHostPath && pName && pAutoMountPoint)
9469 {
9470 /*
9471 * Make a SHFL_FN_ADD_MAPPING call to tell the service about folder.
9472 */
9473 VBOXHGCMSVCPARM aParams[SHFL_CPARMS_ADD_MAPPING];
9474 SHFLSTRING_TO_HGMC_PARAM(&aParams[0], pHostPath);
9475 SHFLSTRING_TO_HGMC_PARAM(&aParams[1], pName);
9476 HGCMSvcSetU32(&aParams[2],
9477 (aData.m_fWritable ? SHFL_ADD_MAPPING_F_WRITABLE : 0)
9478 | (aData.m_fAutoMount ? SHFL_ADD_MAPPING_F_AUTOMOUNT : 0)
9479 | (fSymlinksCreate ? SHFL_ADD_MAPPING_F_CREATE_SYMLINKS : 0)
9480 | (fMissing ? SHFL_ADD_MAPPING_F_MISSING : 0));
9481 SHFLSTRING_TO_HGMC_PARAM(&aParams[3], pAutoMountPoint);
9482 AssertCompile(SHFL_CPARMS_ADD_MAPPING == 4);
9483
9484 vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders", SHFL_FN_ADD_MAPPING, SHFL_CPARMS_ADD_MAPPING, aParams);
9485 if (RT_FAILURE(vrc))
9486 hrc = setErrorBoth(E_FAIL, vrc, tr("Could not create a shared folder '%s' mapped to '%s' (%Rrc)"),
9487 strName.c_str(), aData.m_strHostPath.c_str(), vrc);
9488
9489 else if (fMissing)
9490 hrc = setError(E_INVALIDARG, tr("Shared folder path '%s' does not exist on the host"), aData.m_strHostPath.c_str());
9491 else
9492 hrc = S_OK;
9493 }
9494 else
9495 hrc = E_OUTOFMEMORY;
9496 RTMemFree(pAutoMountPoint);
9497 RTMemFree(pName);
9498 RTMemFree(pHostPath);
9499 return hrc;
9500}
9501
9502/**
9503 * Calls the HGCM service to remove the shared folder definition.
9504 *
9505 * @param strName Shared folder name.
9506 *
9507 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
9508 * @note Doesn't lock anything.
9509 */
9510HRESULT Console::i_removeSharedFolder(const Utf8Str &strName)
9511{
9512 ComAssertRet(strName.isNotEmpty(), E_FAIL);
9513
9514 /* sanity checks */
9515 AssertReturn(mpUVM, E_FAIL);
9516 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
9517
9518 VBOXHGCMSVCPARM parms;
9519 SHFLSTRING *pMapName;
9520 size_t cbString;
9521
9522 Log(("Removing shared folder '%s'\n", strName.c_str()));
9523
9524 Bstr bstrName(strName);
9525 cbString = (bstrName.length() + 1) * sizeof(RTUTF16);
9526 if (cbString >= UINT16_MAX)
9527 return setError(E_INVALIDARG, tr("The name is too long"));
9528 pMapName = (SHFLSTRING *) RTMemAllocZ(SHFLSTRING_HEADER_SIZE + cbString);
9529 Assert(pMapName);
9530 memcpy(pMapName->String.ucs2, bstrName.raw(), cbString);
9531
9532 pMapName->u16Size = (uint16_t)cbString;
9533 pMapName->u16Length = (uint16_t)(cbString - sizeof(RTUTF16));
9534
9535 parms.type = VBOX_HGCM_SVC_PARM_PTR;
9536 parms.u.pointer.addr = pMapName;
9537 parms.u.pointer.size = ShflStringSizeOfBuffer(pMapName);
9538
9539 int vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders", SHFL_FN_REMOVE_MAPPING, 1, &parms);
9540 RTMemFree(pMapName);
9541 if (RT_FAILURE(vrc))
9542 return setErrorBoth(E_FAIL, vrc, tr("Could not remove the shared folder '%s' (%Rrc)"), strName.c_str(), vrc);
9543
9544 return S_OK;
9545}
9546
9547/**
9548 * Retains a reference to the default cryptographic interface.
9549 *
9550 * @returns VBox status code.
9551 * @retval VERR_NOT_SUPPORTED if the VM is not configured for encryption.
9552 * @param ppCryptoIf Where to store the pointer to the cryptographic interface on success.
9553 *
9554 * @note Locks this object for writing.
9555 */
9556int Console::i_retainCryptoIf(PCVBOXCRYPTOIF *ppCryptoIf)
9557{
9558 AssertReturn(ppCryptoIf != NULL, VERR_INVALID_PARAMETER);
9559
9560 int vrc = VINF_SUCCESS;
9561 if (mhLdrModCrypto == NIL_RTLDRMOD)
9562 {
9563#ifdef VBOX_WITH_EXTPACK
9564 /*
9565 * Check that a crypto extension pack name is set and resolve it into a
9566 * library path.
9567 */
9568 HRESULT hrc = S_OK;
9569 Bstr bstrExtPack;
9570
9571 ComPtr<IVirtualBox> pVirtualBox;
9572 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
9573 ComPtr<ISystemProperties> pSystemProperties;
9574 if (pVirtualBox)
9575 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
9576 if (pSystemProperties)
9577 pSystemProperties->COMGETTER(DefaultCryptoExtPack)(bstrExtPack.asOutParam());
9578 if (FAILED(hrc))
9579 return hrc;
9580
9581 Utf8Str strExtPack(bstrExtPack);
9582 if (strExtPack.isEmpty())
9583 {
9584 setError(VBOX_E_OBJECT_NOT_FOUND,
9585 tr("Ńo extension pack providing a cryptographic support module could be found"));
9586 return VERR_NOT_FOUND;
9587 }
9588
9589 Utf8Str strCryptoLibrary;
9590 vrc = mptrExtPackManager->i_getCryptoLibraryPathForExtPack(&strExtPack, &strCryptoLibrary);
9591 if (RT_SUCCESS(vrc))
9592 {
9593 RTERRINFOSTATIC ErrInfo;
9594 vrc = SUPR3HardenedLdrLoadPlugIn(strCryptoLibrary.c_str(), &mhLdrModCrypto, RTErrInfoInitStatic(&ErrInfo));
9595 if (RT_SUCCESS(vrc))
9596 {
9597 /* Resolve the entry point and query the pointer to the cryptographic interface. */
9598 PFNVBOXCRYPTOENTRY pfnCryptoEntry = NULL;
9599 vrc = RTLdrGetSymbol(mhLdrModCrypto, VBOX_CRYPTO_MOD_ENTRY_POINT, (void **)&pfnCryptoEntry);
9600 if (RT_SUCCESS(vrc))
9601 {
9602 vrc = pfnCryptoEntry(&mpCryptoIf);
9603 if (RT_FAILURE(vrc))
9604 setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
9605 tr("Failed to query the interface callback table from the cryptographic support module '%s' from extension pack '%s'"),
9606 strCryptoLibrary.c_str(), strExtPack.c_str());
9607 }
9608 else
9609 setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
9610 tr("Failed to resolve the entry point for the cryptographic support module '%s' from extension pack '%s'"),
9611 strCryptoLibrary.c_str(), strExtPack.c_str());
9612
9613 if (RT_FAILURE(vrc))
9614 {
9615 RTLdrClose(mhLdrModCrypto);
9616 mhLdrModCrypto = NIL_RTLDRMOD;
9617 }
9618 }
9619 else
9620 setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
9621 tr("Couldn't load the cryptographic support module '%s' from extension pack '%s' (error: '%s')"),
9622 strCryptoLibrary.c_str(), strExtPack.c_str(), ErrInfo.Core.pszMsg);
9623 }
9624 else
9625 setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
9626 tr("Couldn't resolve the library path of the crpytographic support module for extension pack '%s'"),
9627 strExtPack.c_str());
9628#else
9629 setError(VBOX_E_NOT_SUPPORTED,
9630 tr("The cryptographic support module is not supported in this build because extension packs are not supported"));
9631 vrc = VERR_NOT_SUPPORTED;
9632#endif
9633 }
9634
9635 if (RT_SUCCESS(vrc))
9636 {
9637 ASMAtomicIncU32(&mcRefsCrypto);
9638 *ppCryptoIf = mpCryptoIf;
9639 }
9640
9641 return vrc;
9642}
9643
9644/**
9645 * Releases the reference of the given cryptographic interface.
9646 *
9647 * @returns VBox status code.
9648 * @param pCryptoIf Pointer to the cryptographic interface to release.
9649 *
9650 * @note Locks this object for writing.
9651 */
9652int Console::i_releaseCryptoIf(PCVBOXCRYPTOIF pCryptoIf)
9653{
9654 AssertReturn(pCryptoIf == mpCryptoIf, VERR_INVALID_PARAMETER);
9655
9656 ASMAtomicDecU32(&mcRefsCrypto);
9657 return VINF_SUCCESS;
9658}
9659
9660/**
9661 * Tries to unload any loaded cryptographic support module if it is not in use currently.
9662 *
9663 * @returns COM status code.
9664 *
9665 * @note Locks this object for writing.
9666 */
9667HRESULT Console::i_unloadCryptoIfModule(void)
9668{
9669 AutoCaller autoCaller(this);
9670 AssertComRCReturnRC(autoCaller.hrc());
9671
9672 AutoWriteLock wlock(this COMMA_LOCKVAL_SRC_POS);
9673
9674 if (mcRefsCrypto)
9675 return setError(E_ACCESSDENIED,
9676 tr("The cryptographic support module is in use and can't be unloaded"));
9677
9678 if (mhLdrModCrypto != NIL_RTLDRMOD)
9679 {
9680 int vrc = RTLdrClose(mhLdrModCrypto);
9681 AssertRC(vrc);
9682 mhLdrModCrypto = NIL_RTLDRMOD;
9683 }
9684
9685 return S_OK;
9686}
9687
9688/** @callback_method_impl{FNVMATSTATE}
9689 *
9690 * @note Locks the Console object for writing.
9691 * @remarks The @a pUVM parameter can be NULL in one case where powerUpThread()
9692 * calls after the VM was destroyed.
9693 */
9694/*static*/ DECLCALLBACK(void)
9695Console::i_vmstateChangeCallback(PUVM pUVM, PCVMMR3VTABLE pVMM, VMSTATE enmState, VMSTATE enmOldState, void *pvUser)
9696{
9697 LogFlowFunc(("Changing state from %s to %s (pUVM=%p)\n",
9698 pVMM->pfnVMR3GetStateName(enmOldState), pVMM->pfnVMR3GetStateName(enmState), pUVM));
9699 RT_NOREF(pVMM);
9700
9701 Console *that = static_cast<Console *>(pvUser);
9702 AssertReturnVoid(that);
9703
9704 AutoCaller autoCaller(that);
9705
9706 /* Note that we must let this method proceed even if Console::uninit() has
9707 * been already called. In such case this VMSTATE change is a result of:
9708 * 1) powerDown() called from uninit() itself, or
9709 * 2) VM-(guest-)initiated power off. */
9710 AssertReturnVoid( autoCaller.isOk()
9711 || that->getObjectState().getState() == ObjectState::InUninit);
9712
9713 switch (enmState)
9714 {
9715 /*
9716 * The VM has terminated
9717 */
9718 case VMSTATE_OFF:
9719 {
9720#ifdef VBOX_WITH_GUEST_PROPS
9721 if (that->mfTurnResetIntoPowerOff)
9722 {
9723 Bstr strPowerOffReason;
9724
9725 if (that->mfPowerOffCausedByReset)
9726 strPowerOffReason = Bstr("Reset");
9727 else
9728 strPowerOffReason = Bstr("PowerOff");
9729
9730 that->mMachine->DeleteGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw());
9731 that->mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw(),
9732 strPowerOffReason.raw(), Bstr("RDONLYGUEST").raw());
9733 that->mMachine->SaveSettings();
9734 }
9735#endif
9736
9737 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9738
9739 if (that->mVMStateChangeCallbackDisabled)
9740 return;
9741
9742 /* Do we still think that it is running? It may happen if this is a
9743 * VM-(guest-)initiated shutdown/poweroff.
9744 */
9745 if ( that->mMachineState != MachineState_Stopping
9746 && that->mMachineState != MachineState_Saving
9747 && that->mMachineState != MachineState_Restoring
9748 && that->mMachineState != MachineState_TeleportingIn
9749 && that->mMachineState != MachineState_TeleportingPausedVM
9750 && !that->mVMIsAlreadyPoweringOff
9751 )
9752 {
9753 LogFlowFunc(("VM has powered itself off but Console still thinks it is running. Notifying.\n"));
9754
9755 /*
9756 * Prevent powerDown() from calling VMR3PowerOff() again if this was called from
9757 * the power off state change.
9758 * When called from the Reset state make sure to call VMR3PowerOff() first.
9759 */
9760 Assert(that->mVMPoweredOff == false);
9761 that->mVMPoweredOff = true;
9762
9763 /*
9764 * request a progress object from the server
9765 * (this will set the machine state to Stopping on the server
9766 * to block others from accessing this machine)
9767 */
9768 ComPtr<IProgress> pProgress;
9769 HRESULT hrc = that->mControl->BeginPoweringDown(pProgress.asOutParam());
9770 AssertComRC(hrc);
9771
9772 /* sync the state with the server */
9773 that->i_setMachineStateLocally(MachineState_Stopping);
9774
9775 /*
9776 * Setup task object and thread to carry out the operation
9777 * asynchronously (if we call powerDown() right here but there
9778 * is one or more mpUVM callers (added with addVMCaller()) we'll
9779 * deadlock).
9780 */
9781 VMPowerDownTask *pTask = NULL;
9782 try
9783 {
9784 pTask = new VMPowerDownTask(that, pProgress);
9785 }
9786 catch (std::bad_alloc &)
9787 {
9788 LogRelFunc(("E_OUTOFMEMORY creating VMPowerDownTask"));
9789 hrc = E_OUTOFMEMORY;
9790 break;
9791 }
9792
9793 /*
9794 * If creating a task failed, this can currently mean one of
9795 * two: either Console::uninit() has been called just a ms
9796 * before (so a powerDown() call is already on the way), or
9797 * powerDown() itself is being already executed. Just do
9798 * nothing.
9799 */
9800 if (pTask->isOk())
9801 {
9802 hrc = pTask->createThread();
9803 pTask = NULL;
9804 if (FAILED(hrc))
9805 LogRelFunc(("Problem with creating thread for VMPowerDownTask.\n"));
9806 }
9807 else
9808 {
9809 LogFlowFunc(("Console is already being uninitialized. (%Rhrc)\n", pTask->hrc()));
9810 delete pTask;
9811 pTask = NULL;
9812 hrc = E_FAIL;
9813 }
9814 }
9815 break;
9816 }
9817
9818 /* The VM has been completely destroyed.
9819 *
9820 * Note: This state change can happen at two points:
9821 * 1) At the end of VMR3Destroy() if it was not called from EMT.
9822 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
9823 * called by EMT.
9824 */
9825 case VMSTATE_TERMINATED:
9826 {
9827 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9828
9829 if (that->mVMStateChangeCallbackDisabled)
9830 break;
9831
9832#ifdef VBOX_WITH_CLOUD_NET
9833 /*
9834 * We stop cloud gateway here because we may have failed to connect to it,
9835 * configure it, or establish a tunnel. We definitely do not want an orphaned
9836 * instance running in the cloud.
9837 */
9838 if (!that->mGateway.mGatewayInstanceId.isEmpty())
9839 {
9840 ComPtr<IVirtualBox> pVirtualBox;
9841 HRESULT hrc = that->mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
9842 AssertComRC(hrc);
9843 if (SUCCEEDED(hrc) && !pVirtualBox.isNull())
9844 stopCloudGateway(pVirtualBox, that->mGateway);
9845 }
9846#endif /* VBOX_WITH_CLOUD_NET */
9847 /* Terminate host interface networking. If pUVM is NULL, we've been
9848 * manually called from powerUpThread() either before calling
9849 * VMR3Create() or after VMR3Create() failed, so no need to touch
9850 * networking.
9851 */
9852 if (pUVM)
9853 that->i_powerDownHostInterfaces();
9854
9855 /* From now on the machine is officially powered down or remains in
9856 * the Saved state.
9857 */
9858 switch (that->mMachineState)
9859 {
9860 default:
9861 AssertFailed();
9862 RT_FALL_THRU();
9863 case MachineState_Stopping:
9864 /* successfully powered down */
9865 that->i_setMachineState(MachineState_PoweredOff);
9866 break;
9867 case MachineState_Saving:
9868 /* successfully saved */
9869 that->i_setMachineState(MachineState_Saved);
9870 break;
9871 case MachineState_Starting:
9872 /* failed to start, but be patient: set back to PoweredOff
9873 * (for similarity with the below) */
9874 that->i_setMachineState(MachineState_PoweredOff);
9875 break;
9876 case MachineState_Restoring:
9877 /* failed to load the saved state file, but be patient: set
9878 * to AbortedSaved (to preserve the saved state file) */
9879 that->i_setMachineState(MachineState_AbortedSaved);
9880 break;
9881 case MachineState_TeleportingIn:
9882 /* Teleportation failed or was canceled. Back to powered off. */
9883 that->i_setMachineState(MachineState_PoweredOff);
9884 break;
9885 case MachineState_TeleportingPausedVM:
9886 /* Successfully teleported the VM. */
9887 that->i_setMachineState(MachineState_Teleported);
9888 break;
9889 }
9890 break;
9891 }
9892
9893 case VMSTATE_RESETTING:
9894 /** @todo shouldn't VMSTATE_RESETTING_LS be here? */
9895 {
9896#ifdef VBOX_WITH_GUEST_PROPS
9897 /* Do not take any read/write locks here! */
9898 that->i_guestPropertiesHandleVMReset();
9899#endif
9900 break;
9901 }
9902
9903 case VMSTATE_SOFT_RESETTING:
9904 case VMSTATE_SOFT_RESETTING_LS:
9905 /* Shouldn't do anything here! */
9906 break;
9907
9908 case VMSTATE_SUSPENDED:
9909 {
9910 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9911
9912 if (that->mVMStateChangeCallbackDisabled)
9913 break;
9914
9915 switch (that->mMachineState)
9916 {
9917 case MachineState_Teleporting:
9918 that->i_setMachineState(MachineState_TeleportingPausedVM);
9919 break;
9920
9921 case MachineState_LiveSnapshotting:
9922 that->i_setMachineState(MachineState_OnlineSnapshotting);
9923 break;
9924
9925 case MachineState_TeleportingPausedVM:
9926 case MachineState_Saving:
9927 case MachineState_Restoring:
9928 case MachineState_Stopping:
9929 case MachineState_TeleportingIn:
9930 case MachineState_OnlineSnapshotting:
9931 /* The worker thread handles the transition. */
9932 break;
9933
9934 case MachineState_Running:
9935 that->i_setMachineState(MachineState_Paused);
9936 break;
9937
9938 case MachineState_Paused:
9939 /* Nothing to do. */
9940 break;
9941
9942 default:
9943 AssertMsgFailed(("%s\n", ::stringifyMachineState(that->mMachineState)));
9944 }
9945 break;
9946 }
9947
9948 case VMSTATE_SUSPENDED_LS:
9949 case VMSTATE_SUSPENDED_EXT_LS:
9950 {
9951 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9952 if (that->mVMStateChangeCallbackDisabled)
9953 break;
9954 switch (that->mMachineState)
9955 {
9956 case MachineState_Teleporting:
9957 that->i_setMachineState(MachineState_TeleportingPausedVM);
9958 break;
9959
9960 case MachineState_LiveSnapshotting:
9961 that->i_setMachineState(MachineState_OnlineSnapshotting);
9962 break;
9963
9964 case MachineState_TeleportingPausedVM:
9965 case MachineState_Saving:
9966 /* ignore */
9967 break;
9968
9969 default:
9970 AssertMsgFailed(("%s/%s -> %s\n", ::stringifyMachineState(that->mMachineState),
9971 pVMM->pfnVMR3GetStateName(enmOldState), pVMM->pfnVMR3GetStateName(enmState) ));
9972 that->i_setMachineState(MachineState_Paused);
9973 break;
9974 }
9975 break;
9976 }
9977
9978 case VMSTATE_RUNNING:
9979 {
9980 if ( enmOldState == VMSTATE_POWERING_ON
9981 || enmOldState == VMSTATE_RESUMING)
9982 {
9983 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9984
9985 if (that->mVMStateChangeCallbackDisabled)
9986 break;
9987
9988 Assert( ( ( that->mMachineState == MachineState_Starting
9989 || that->mMachineState == MachineState_Paused)
9990 && enmOldState == VMSTATE_POWERING_ON)
9991 || ( ( that->mMachineState == MachineState_Restoring
9992 || that->mMachineState == MachineState_TeleportingIn
9993 || that->mMachineState == MachineState_Paused
9994 || that->mMachineState == MachineState_Saving
9995 )
9996 && enmOldState == VMSTATE_RESUMING));
9997
9998 that->i_setMachineState(MachineState_Running);
9999 }
10000
10001 break;
10002 }
10003
10004 case VMSTATE_RUNNING_LS:
10005 AssertMsg( that->mMachineState == MachineState_LiveSnapshotting
10006 || that->mMachineState == MachineState_Teleporting,
10007 ("%s/%s -> %s\n", ::stringifyMachineState(that->mMachineState),
10008 pVMM->pfnVMR3GetStateName(enmOldState), pVMM->pfnVMR3GetStateName(enmState) ));
10009 break;
10010
10011 case VMSTATE_FATAL_ERROR:
10012 {
10013 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
10014
10015 if (that->mVMStateChangeCallbackDisabled)
10016 break;
10017
10018 /* Fatal errors are only for running VMs. */
10019 Assert(Global::IsOnline(that->mMachineState));
10020
10021 /* Note! 'Pause' is used here in want of something better. There
10022 * are currently only two places where fatal errors might be
10023 * raised, so it is not worth adding a new externally
10024 * visible state for this yet. */
10025 that->i_setMachineState(MachineState_Paused);
10026 break;
10027 }
10028
10029 case VMSTATE_GURU_MEDITATION:
10030 {
10031 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
10032
10033 if (that->mVMStateChangeCallbackDisabled)
10034 break;
10035
10036 /* Guru are only for running VMs */
10037 Assert(Global::IsOnline(that->mMachineState));
10038
10039 that->i_setMachineState(MachineState_Stuck);
10040 break;
10041 }
10042
10043 case VMSTATE_CREATED:
10044 {
10045 /*
10046 * We have to set the secret key helper interface for the VD drivers to
10047 * get notified about missing keys.
10048 */
10049 that->i_initSecretKeyIfOnAllAttachments();
10050 break;
10051 }
10052
10053 default: /* shut up gcc */
10054 break;
10055 }
10056}
10057
10058/**
10059 * Changes the clipboard mode.
10060 *
10061 * @returns VBox status code.
10062 * @param aClipboardMode new clipboard mode.
10063 */
10064int Console::i_changeClipboardMode(ClipboardMode_T aClipboardMode)
10065{
10066#ifdef VBOX_WITH_SHARED_CLIPBOARD
10067 VMMDev *pVMMDev = m_pVMMDev;
10068 AssertPtrReturn(pVMMDev, VERR_INVALID_POINTER);
10069
10070 VBOXHGCMSVCPARM parm;
10071 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
10072
10073 switch (aClipboardMode)
10074 {
10075 default:
10076 case ClipboardMode_Disabled:
10077 LogRel(("Shared Clipboard: Mode: Off\n"));
10078 parm.u.uint32 = VBOX_SHCL_MODE_OFF;
10079 break;
10080 case ClipboardMode_GuestToHost:
10081 LogRel(("Shared Clipboard: Mode: Guest to Host\n"));
10082 parm.u.uint32 = VBOX_SHCL_MODE_GUEST_TO_HOST;
10083 break;
10084 case ClipboardMode_HostToGuest:
10085 LogRel(("Shared Clipboard: Mode: Host to Guest\n"));
10086 parm.u.uint32 = VBOX_SHCL_MODE_HOST_TO_GUEST;
10087 break;
10088 case ClipboardMode_Bidirectional:
10089 LogRel(("Shared Clipboard: Mode: Bidirectional\n"));
10090 parm.u.uint32 = VBOX_SHCL_MODE_BIDIRECTIONAL;
10091 break;
10092 }
10093
10094 int vrc = pVMMDev->hgcmHostCall("VBoxSharedClipboard", VBOX_SHCL_HOST_FN_SET_MODE, 1, &parm);
10095 if (RT_FAILURE(vrc))
10096 LogRel(("Shared Clipboard: Error changing mode: %Rrc\n", vrc));
10097
10098 return vrc;
10099#else
10100 RT_NOREF(aClipboardMode);
10101 return VERR_NOT_IMPLEMENTED;
10102#endif
10103}
10104
10105/**
10106 * Changes the clipboard file transfer mode.
10107 *
10108 * @returns VBox status code.
10109 * @param aEnabled Whether clipboard file transfers are enabled or not.
10110 */
10111int Console::i_changeClipboardFileTransferMode(bool aEnabled)
10112{
10113#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
10114 VMMDev *pVMMDev = m_pVMMDev;
10115 AssertPtrReturn(pVMMDev, VERR_INVALID_POINTER);
10116
10117 VBOXHGCMSVCPARM parm;
10118 RT_ZERO(parm);
10119
10120 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
10121 parm.u.uint32 = aEnabled ? VBOX_SHCL_TRANSFER_MODE_F_ENABLED : VBOX_SHCL_TRANSFER_MODE_F_NONE;
10122
10123 int vrc = pVMMDev->hgcmHostCall("VBoxSharedClipboard", VBOX_SHCL_HOST_FN_SET_TRANSFER_MODE, 1 /* cParms */, &parm);
10124 if (RT_FAILURE(vrc))
10125 LogRel(("Shared Clipboard: Error changing file transfer mode: %Rrc\n", vrc));
10126
10127 return vrc;
10128#else
10129 RT_NOREF(aEnabled);
10130 return VERR_NOT_IMPLEMENTED;
10131#endif
10132}
10133
10134/**
10135 * Changes the drag and drop mode.
10136 *
10137 * @param aDnDMode new drag and drop mode.
10138 */
10139int Console::i_changeDnDMode(DnDMode_T aDnDMode)
10140{
10141 VMMDev *pVMMDev = m_pVMMDev;
10142 AssertPtrReturn(pVMMDev, VERR_INVALID_POINTER);
10143
10144 VBOXHGCMSVCPARM parm;
10145 RT_ZERO(parm);
10146 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
10147
10148 switch (aDnDMode)
10149 {
10150 default:
10151 case DnDMode_Disabled:
10152 LogRel(("Drag and drop mode: Off\n"));
10153 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_OFF;
10154 break;
10155 case DnDMode_GuestToHost:
10156 LogRel(("Drag and drop mode: Guest to Host\n"));
10157 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_GUEST_TO_HOST;
10158 break;
10159 case DnDMode_HostToGuest:
10160 LogRel(("Drag and drop mode: Host to Guest\n"));
10161 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_HOST_TO_GUEST;
10162 break;
10163 case DnDMode_Bidirectional:
10164 LogRel(("Drag and drop mode: Bidirectional\n"));
10165 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_BIDIRECTIONAL;
10166 break;
10167 }
10168
10169 int vrc = pVMMDev->hgcmHostCall("VBoxDragAndDropSvc", DragAndDropSvc::HOST_DND_FN_SET_MODE, 1 /* cParms */, &parm);
10170 if (RT_FAILURE(vrc))
10171 LogRel(("Error changing drag and drop mode: %Rrc\n", vrc));
10172
10173 return vrc;
10174}
10175
10176#ifdef VBOX_WITH_USB
10177/**
10178 * @interface_method_impl{REMOTEUSBIF,pfnQueryRemoteUsbBackend}
10179 */
10180/*static*/ DECLCALLBACK(PREMOTEUSBCALLBACK)
10181Console::i_usbQueryRemoteUsbBackend(void *pvUser, PCRTUUID pUuid, uint32_t idClient)
10182{
10183 Console *pConsole = (Console *)pvUser;
10184
10185 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
10186
10187 Guid const uuid(*pUuid);
10188 return (PREMOTEUSBCALLBACK)pConsole->i_consoleVRDPServer()->USBBackendRequestPointer(idClient, &uuid);
10189}
10190
10191
10192/**
10193 * Sends a request to VMM to attach the given host device.
10194 * After this method succeeds, the attached device will appear in the
10195 * mUSBDevices collection.
10196 *
10197 * @param aHostDevice device to attach
10198 *
10199 * @note Synchronously calls EMT.
10200 */
10201HRESULT Console::i_attachUSBDevice(IUSBDevice *aHostDevice, ULONG aMaskedIfs, const Utf8Str &aCaptureFilename)
10202{
10203 AssertReturn(aHostDevice, E_FAIL);
10204 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
10205
10206 HRESULT hrc;
10207
10208 /*
10209 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
10210 * method in EMT (using usbAttachCallback()).
10211 */
10212 Bstr bstrAddress;
10213 hrc = aHostDevice->COMGETTER(Address)(bstrAddress.asOutParam());
10214 ComAssertComRCRetRC(hrc);
10215 Utf8Str const Address(bstrAddress);
10216
10217 Bstr id;
10218 hrc = aHostDevice->COMGETTER(Id)(id.asOutParam());
10219 ComAssertComRCRetRC(hrc);
10220 Guid const uuid(id);
10221
10222 BOOL fRemote = FALSE;
10223 hrc = aHostDevice->COMGETTER(Remote)(&fRemote);
10224 ComAssertComRCRetRC(hrc);
10225
10226 Bstr bstrBackend;
10227 hrc = aHostDevice->COMGETTER(Backend)(bstrBackend.asOutParam());
10228 ComAssertComRCRetRC(hrc);
10229 Utf8Str const strBackend(bstrBackend);
10230
10231 /* Get the VM handle. */
10232 SafeVMPtr ptrVM(this);
10233 if (!ptrVM.isOk())
10234 return ptrVM.hrc();
10235
10236 LogFlowThisFunc(("Proxying USB device '%s' {%RTuuid}...\n", Address.c_str(), uuid.raw()));
10237
10238 PCFGMNODE pRemoteCfg = NULL;
10239 if (fRemote)
10240 {
10241 RemoteUSBDevice *pRemoteUSBDevice = static_cast<RemoteUSBDevice *>(aHostDevice);
10242
10243 pRemoteCfg = mpVMM->pfnCFGMR3CreateTree(ptrVM.rawUVM());
10244 if (pRemoteCfg)
10245 {
10246 int vrc = mpVMM->pfnCFGMR3InsertInteger(pRemoteCfg, "ClientId", pRemoteUSBDevice->clientId());
10247 if (RT_FAILURE(vrc))
10248 {
10249 mpVMM->pfnCFGMR3DestroyTree(pRemoteCfg);
10250 return setErrorBoth(E_FAIL, vrc, tr("Failed to create configuration for USB device."));
10251 }
10252 }
10253 else
10254 return setErrorBoth(E_OUTOFMEMORY, VERR_NO_MEMORY, tr("Failed to allocate config tree for USB device."));
10255 }
10256
10257 USBConnectionSpeed_T enmSpeed;
10258 hrc = aHostDevice->COMGETTER(Speed)(&enmSpeed);
10259 AssertComRCReturnRC(hrc);
10260
10261 int vrc = ptrVM.vtable()->pfnVMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
10262 (PFNRT)i_usbAttachCallback, 11,
10263 this, ptrVM.rawUVM(), ptrVM.vtable(), aHostDevice, uuid.raw(),
10264 strBackend.c_str(), Address.c_str(), pRemoteCfg, enmSpeed, aMaskedIfs,
10265 aCaptureFilename.isEmpty() ? NULL : aCaptureFilename.c_str());
10266 if (RT_SUCCESS(vrc))
10267 {
10268 /* Create a OUSBDevice and add it to the device list */
10269 ComObjPtr<OUSBDevice> pUSBDevice;
10270 pUSBDevice.createObject();
10271 hrc = pUSBDevice->init(aHostDevice);
10272 AssertComRC(hrc);
10273
10274 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10275 mUSBDevices.push_back(pUSBDevice);
10276 LogFlowFunc(("Attached device {%RTuuid}\n", pUSBDevice->i_id().raw()));
10277
10278 /* notify callbacks */
10279 alock.release();
10280 i_onUSBDeviceStateChange(pUSBDevice, true /* aAttached */, NULL);
10281 }
10282 else
10283 {
10284 Log1WarningThisFunc(("Failed to create proxy device for '%s' {%RTuuid} (%Rrc)\n", Address.c_str(), uuid.raw(), vrc));
10285 switch (vrc)
10286 {
10287 case VERR_VUSB_NO_PORTS:
10288 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to attach the USB device. (No available ports on the USB controller)."));
10289 break;
10290 case VERR_VUSB_USBFS_PERMISSION:
10291 hrc = setErrorBoth(E_FAIL, vrc, tr("Not permitted to open the USB device, check usbfs options"));
10292 break;
10293 default:
10294 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to create a proxy device for the USB device. (Error: %Rrc)"), vrc);
10295 break;
10296 }
10297 }
10298
10299 return hrc;
10300}
10301
10302/**
10303 * USB device attach callback used by AttachUSBDevice().
10304 * Note that AttachUSBDevice() doesn't return until this callback is executed,
10305 * so we don't use AutoCaller and don't care about reference counters of
10306 * interface pointers passed in.
10307 *
10308 * @thread EMT
10309 * @note Locks the console object for writing.
10310 */
10311//static
10312DECLCALLBACK(int)
10313Console::i_usbAttachCallback(Console *that, PUVM pUVM, PCVMMR3VTABLE pVMM, IUSBDevice *aHostDevice, PCRTUUID aUuid,
10314 const char *pszBackend, const char *aAddress, PCFGMNODE pRemoteCfg, USBConnectionSpeed_T aEnmSpeed,
10315 ULONG aMaskedIfs, const char *pszCaptureFilename)
10316{
10317 RT_NOREF(aHostDevice);
10318 LogFlowFuncEnter();
10319 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
10320
10321 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
10322 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
10323
10324 VUSBSPEED enmSpeed = VUSB_SPEED_UNKNOWN;
10325 switch (aEnmSpeed)
10326 {
10327 case USBConnectionSpeed_Low: enmSpeed = VUSB_SPEED_LOW; break;
10328 case USBConnectionSpeed_Full: enmSpeed = VUSB_SPEED_FULL; break;
10329 case USBConnectionSpeed_High: enmSpeed = VUSB_SPEED_HIGH; break;
10330 case USBConnectionSpeed_Super: enmSpeed = VUSB_SPEED_SUPER; break;
10331 case USBConnectionSpeed_SuperPlus: enmSpeed = VUSB_SPEED_SUPERPLUS; break;
10332 default: AssertFailed(); break;
10333 }
10334
10335 int vrc = pVMM->pfnPDMR3UsbCreateProxyDevice(pUVM, aUuid, pszBackend, aAddress, pRemoteCfg,
10336 enmSpeed, aMaskedIfs, pszCaptureFilename);
10337 LogFlowFunc(("vrc=%Rrc\n", vrc));
10338 LogFlowFuncLeave();
10339 return vrc;
10340}
10341
10342/**
10343 * Sends a request to VMM to detach the given host device. After this method
10344 * succeeds, the detached device will disappear from the mUSBDevices
10345 * collection.
10346 *
10347 * @param aHostDevice device to attach
10348 *
10349 * @note Synchronously calls EMT.
10350 */
10351HRESULT Console::i_detachUSBDevice(const ComObjPtr<OUSBDevice> &aHostDevice)
10352{
10353 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
10354
10355 /* Get the VM handle. */
10356 SafeVMPtr ptrVM(this);
10357 if (!ptrVM.isOk())
10358 return ptrVM.hrc();
10359
10360 /* if the device is attached, then there must at least one USB hub. */
10361 AssertReturn(ptrVM.vtable()->pfnPDMR3UsbHasHub(ptrVM.rawUVM()), E_FAIL);
10362
10363 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10364 LogFlowThisFunc(("Detaching USB proxy device {%RTuuid}...\n", aHostDevice->i_id().raw()));
10365
10366 /*
10367 * If this was a remote device, release the backend pointer.
10368 * The pointer was requested in usbAttachCallback.
10369 */
10370 BOOL fRemote = FALSE;
10371
10372 HRESULT hrc2 = aHostDevice->COMGETTER(Remote)(&fRemote);
10373 if (FAILED(hrc2))
10374 i_setErrorStatic(hrc2, "GetRemote() failed");
10375
10376 PCRTUUID pUuid = aHostDevice->i_id().raw();
10377 if (fRemote)
10378 {
10379 Guid guid(*pUuid);
10380 i_consoleVRDPServer()->USBBackendReleasePointer(&guid);
10381 }
10382
10383 alock.release();
10384 int vrc = ptrVM.vtable()->pfnVMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
10385 (PFNRT)i_usbDetachCallback, 4,
10386 this, ptrVM.rawUVM(), ptrVM.vtable(), pUuid);
10387 if (RT_SUCCESS(vrc))
10388 {
10389 LogFlowFunc(("Detached device {%RTuuid}\n", pUuid));
10390
10391 /* notify callbacks */
10392 i_onUSBDeviceStateChange(aHostDevice, false /* aAttached */, NULL);
10393 }
10394
10395 ComAssertRCRet(vrc, E_FAIL);
10396
10397 return S_OK;
10398}
10399
10400/**
10401 * USB device detach callback used by DetachUSBDevice().
10402 *
10403 * Note that DetachUSBDevice() doesn't return until this callback is executed,
10404 * so we don't use AutoCaller and don't care about reference counters of
10405 * interface pointers passed in.
10406 *
10407 * @thread EMT
10408 */
10409//static
10410DECLCALLBACK(int)
10411Console::i_usbDetachCallback(Console *that, PUVM pUVM, PCVMMR3VTABLE pVMM, PCRTUUID aUuid)
10412{
10413 LogFlowFuncEnter();
10414 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
10415
10416 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
10417 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
10418
10419 int vrc = pVMM->pfnPDMR3UsbDetachDevice(pUVM, aUuid);
10420
10421 LogFlowFunc(("vrc=%Rrc\n", vrc));
10422 LogFlowFuncLeave();
10423 return vrc;
10424}
10425#endif /* VBOX_WITH_USB */
10426
10427/* Note: FreeBSD needs this whether netflt is used or not. */
10428#if ((defined(RT_OS_LINUX) && !defined(VBOX_WITH_NETFLT)) || defined(RT_OS_FREEBSD))
10429
10430/**
10431 * Helper function to handle host interface device creation and attachment.
10432 *
10433 * @param networkAdapter the network adapter which attachment should be reset
10434 * @return COM status code
10435 *
10436 * @note The caller must lock this object for writing.
10437 *
10438 * @todo Move this back into the driver!
10439 */
10440HRESULT Console::i_attachToTapInterface(INetworkAdapter *networkAdapter)
10441{
10442 LogFlowThisFunc(("\n"));
10443 /* sanity check */
10444 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
10445
10446# ifdef VBOX_STRICT
10447 /* paranoia */
10448 NetworkAttachmentType_T attachment;
10449 networkAdapter->COMGETTER(AttachmentType)(&attachment);
10450 Assert(attachment == NetworkAttachmentType_Bridged);
10451# endif /* VBOX_STRICT */
10452
10453 ULONG slot = 0;
10454 HRESULT hrc = networkAdapter->COMGETTER(Slot)(&slot);
10455 AssertComRCReturnRC(hrc);
10456
10457# ifdef RT_OS_LINUX
10458 /*
10459 * Allocate a host interface device
10460 */
10461 int vrc = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
10462 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
10463 if (RT_SUCCESS(vrc))
10464 {
10465 /*
10466 * Set/obtain the tap interface.
10467 */
10468 struct ifreq IfReq;
10469 RT_ZERO(IfReq);
10470 /* The name of the TAP interface we are using */
10471 Bstr tapDeviceName;
10472 hrc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
10473 if (FAILED(hrc))
10474 tapDeviceName.setNull(); /* Is this necessary? */
10475 if (tapDeviceName.isEmpty())
10476 {
10477 LogRel(("No TAP device name was supplied.\n"));
10478 hrc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
10479 }
10480
10481 if (SUCCEEDED(hrc))
10482 {
10483 /* If we are using a static TAP device then try to open it. */
10484 Utf8Str str(tapDeviceName);
10485 RTStrCopy(IfReq.ifr_name, sizeof(IfReq.ifr_name), str.c_str()); /** @todo bitch about names which are too long... */
10486 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
10487 vrc = ioctl(RTFileToNative(maTapFD[slot]), TUNSETIFF, &IfReq);
10488 if (vrc != 0)
10489 {
10490 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
10491 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to open the host network interface %ls"), tapDeviceName.raw());
10492 }
10493 }
10494 if (SUCCEEDED(hrc))
10495 {
10496 /*
10497 * Make it pollable.
10498 */
10499 if (fcntl(RTFileToNative(maTapFD[slot]), F_SETFL, O_NONBLOCK) != -1)
10500 {
10501 Log(("i_attachToTapInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
10502 /*
10503 * Here is the right place to communicate the TAP file descriptor and
10504 * the host interface name to the server if/when it becomes really
10505 * necessary.
10506 */
10507 maTAPDeviceName[slot] = tapDeviceName;
10508 vrc = VINF_SUCCESS;
10509 }
10510 else
10511 {
10512 int iErr = errno;
10513
10514 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
10515 vrc = VERR_HOSTIF_BLOCKING;
10516 hrc = setErrorBoth(E_FAIL, vrc, tr("could not set up the host networking device for non blocking access: %s"),
10517 strerror(errno));
10518 }
10519 }
10520 }
10521 else
10522 {
10523 LogRel(("Configuration error: Failed to open /dev/net/tun vrc=%Rrc\n", vrc));
10524 switch (vrc)
10525 {
10526 case VERR_ACCESS_DENIED:
10527 /* will be handled by our caller */
10528 hrc = E_ACCESSDENIED;
10529 break;
10530 default:
10531 hrc = setErrorBoth(E_FAIL, vrc, tr("Could not set up the host networking device: %Rrc"), vrc);
10532 break;
10533 }
10534 }
10535
10536# elif defined(RT_OS_FREEBSD)
10537 /*
10538 * Set/obtain the tap interface.
10539 */
10540 /* The name of the TAP interface we are using */
10541 Bstr tapDeviceName;
10542 hrc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
10543 if (FAILED(hrc))
10544 tapDeviceName.setNull(); /* Is this necessary? */
10545 if (tapDeviceName.isEmpty())
10546 {
10547 LogRel(("No TAP device name was supplied.\n"));
10548 hrc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
10549 }
10550 char szTapdev[1024] = "/dev/";
10551 /* If we are using a static TAP device then try to open it. */
10552 Utf8Str str(tapDeviceName);
10553 if (str.length() + strlen(szTapdev) <= sizeof(szTapdev))
10554 strcat(szTapdev, str.c_str());
10555 else
10556 memcpy(szTapdev + strlen(szTapdev), str.c_str(),
10557 sizeof(szTapdev) - strlen(szTapdev) - 1); /** @todo bitch about names which are too long... */
10558 int vrc = RTFileOpen(&maTapFD[slot], szTapdev,
10559 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT | RTFILE_O_NON_BLOCK);
10560
10561 if (RT_SUCCESS(vrc))
10562 maTAPDeviceName[slot] = tapDeviceName;
10563 else
10564 {
10565 switch (vrc)
10566 {
10567 case VERR_ACCESS_DENIED:
10568 /* will be handled by our caller */
10569 hrc = E_ACCESSDENIED;
10570 break;
10571 default:
10572 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to open the host network interface %ls"), tapDeviceName.raw());
10573 break;
10574 }
10575 }
10576# else
10577# error "huh?"
10578# endif
10579 /* in case of failure, cleanup. */
10580 if (RT_FAILURE(vrc) && SUCCEEDED(hrc))
10581 {
10582 LogRel(("General failure attaching to host interface\n"));
10583 hrc = setErrorBoth(E_FAIL, vrc, tr("General failure attaching to host interface"));
10584 }
10585 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
10586 return hrc;
10587}
10588
10589
10590/**
10591 * Helper function to handle detachment from a host interface
10592 *
10593 * @param networkAdapter the network adapter which attachment should be reset
10594 * @return COM status code
10595 *
10596 * @note The caller must lock this object for writing.
10597 *
10598 * @todo Move this back into the driver!
10599 */
10600HRESULT Console::i_detachFromTapInterface(INetworkAdapter *networkAdapter)
10601{
10602 /* sanity check */
10603 LogFlowThisFunc(("\n"));
10604 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
10605
10606# ifdef VBOX_STRICT
10607 /* paranoia */
10608 NetworkAttachmentType_T attachment;
10609 networkAdapter->COMGETTER(AttachmentType)(&attachment);
10610 Assert(attachment == NetworkAttachmentType_Bridged);
10611# endif /* VBOX_STRICT */
10612
10613 ULONG slot = 0;
10614 HRESULT hrc = networkAdapter->COMGETTER(Slot)(&slot);
10615 AssertComRCReturnRC(hrc);
10616
10617 /* is there an open TAP device? */
10618 if (maTapFD[slot] != NIL_RTFILE)
10619 {
10620 /*
10621 * Close the file handle.
10622 */
10623 Bstr tapDeviceName, tapTerminateApplication;
10624 bool isStatic = true;
10625 hrc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
10626 if (FAILED(hrc) || tapDeviceName.isEmpty())
10627 {
10628 /* If the name is empty, this is a dynamic TAP device, so close it now,
10629 so that the termination script can remove the interface. Otherwise we still
10630 need the FD to pass to the termination script. */
10631 isStatic = false;
10632 int vrc = RTFileClose(maTapFD[slot]);
10633 AssertRC(vrc);
10634 maTapFD[slot] = NIL_RTFILE;
10635 }
10636 if (isStatic)
10637 {
10638 /* If we are using a static TAP device, we close it now, after having called the
10639 termination script. */
10640 int vrc = RTFileClose(maTapFD[slot]);
10641 AssertRC(vrc);
10642 }
10643 /* the TAP device name and handle are no longer valid */
10644 maTapFD[slot] = NIL_RTFILE;
10645 maTAPDeviceName[slot] = "";
10646 }
10647 LogFlowThisFunc(("returning %Rhrc\n", hrc));
10648 return hrc;
10649}
10650
10651#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
10652
10653/**
10654 * Called at power down to terminate host interface networking.
10655 *
10656 * @note The caller must lock this object for writing.
10657 */
10658HRESULT Console::i_powerDownHostInterfaces()
10659{
10660 LogFlowThisFunc(("\n"));
10661
10662 /* sanity check */
10663 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
10664
10665 /*
10666 * host interface termination handling
10667 */
10668 ComPtr<IVirtualBox> pVirtualBox;
10669 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
10670
10671 ComPtr<IPlatform> pPlatform;
10672 HRESULT hrc = mMachine->COMGETTER(Platform)(pPlatform.asOutParam());
10673 AssertComRC(hrc);
10674
10675 PlatformArchitecture_T platformArch;
10676 hrc = pPlatform->COMGETTER(Architecture)(&platformArch);
10677 AssertComRC(hrc);
10678
10679 ComPtr<IPlatformProperties> pPlatformProperties;
10680 hrc = pVirtualBox->GetPlatformProperties(platformArch, pPlatformProperties.asOutParam());
10681 AssertComRC(hrc);
10682
10683 ChipsetType_T chipsetType = ChipsetType_PIIX3; /** @todo BUGBUG ASSUMES x86! */
10684 pPlatform->COMGETTER(ChipsetType)(&chipsetType);
10685 AssertComRC(hrc);
10686
10687 ULONG maxNetworkAdapters = 0;
10688 hrc = pPlatformProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters);
10689 AssertComRC(hrc);
10690
10691 for (ULONG slot = 0; slot < maxNetworkAdapters; slot++)
10692 {
10693 ComPtr<INetworkAdapter> pNetworkAdapter;
10694 hrc = mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
10695 if (FAILED(hrc)) break;
10696
10697 BOOL enabled = FALSE;
10698 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
10699 if (!enabled)
10700 continue;
10701
10702 NetworkAttachmentType_T attachment;
10703 pNetworkAdapter->COMGETTER(AttachmentType)(&attachment);
10704 if (attachment == NetworkAttachmentType_Bridged)
10705 {
10706#if ((defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)) && !defined(VBOX_WITH_NETFLT))
10707 HRESULT hrc2 = i_detachFromTapInterface(pNetworkAdapter);
10708 if (FAILED(hrc2) && SUCCEEDED(hrc))
10709 hrc = hrc2;
10710#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
10711 }
10712 }
10713
10714 return hrc;
10715}
10716
10717
10718/**
10719 * Process callback handler for VMR3LoadFromFile, VMR3LoadFromStream, VMR3Save
10720 * and VMR3Teleport.
10721 *
10722 * @param pUVM The user mode VM handle.
10723 * @param uPercent Completion percentage (0-100).
10724 * @param pvUser Pointer to an IProgress instance.
10725 * @return VINF_SUCCESS.
10726 */
10727/*static*/
10728DECLCALLBACK(int) Console::i_stateProgressCallback(PUVM pUVM, unsigned uPercent, void *pvUser)
10729{
10730 IProgress *pProgress = static_cast<IProgress *>(pvUser);
10731
10732 /* update the progress object */
10733 if (pProgress)
10734 {
10735 ComPtr<IInternalProgressControl> pProgressControl(pProgress);
10736 AssertReturn(!!pProgressControl, VERR_INVALID_PARAMETER);
10737 pProgressControl->SetCurrentOperationProgress(uPercent);
10738 }
10739
10740 NOREF(pUVM);
10741 return VINF_SUCCESS;
10742}
10743
10744/**
10745 * @copydoc FNVMATERROR
10746 *
10747 * @remarks Might be some tiny serialization concerns with access to the string
10748 * object here...
10749 */
10750/*static*/ DECLCALLBACK(void)
10751Console::i_genericVMSetErrorCallback(PUVM pUVM, void *pvUser, int vrc, RT_SRC_POS_DECL, const char *pszFormat, va_list args)
10752{
10753 RT_SRC_POS_NOREF();
10754 Utf8Str *pErrorText = (Utf8Str *)pvUser;
10755 AssertPtr(pErrorText);
10756
10757 /* We ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users. */
10758 va_list va2;
10759 va_copy(va2, args);
10760
10761 /* Append to any the existing error message. */
10762 try
10763 {
10764 if (pErrorText->length())
10765 pErrorText->appendPrintf(".\n%N (%Rrc)", pszFormat, &va2, vrc, vrc);
10766 else
10767 pErrorText->printf("%N (%Rrc)", pszFormat, &va2, vrc, vrc);
10768 }
10769 catch (std::bad_alloc &)
10770 {
10771 }
10772
10773 va_end(va2);
10774
10775 NOREF(pUVM);
10776}
10777
10778/**
10779 * VM runtime error callback function (FNVMATRUNTIMEERROR).
10780 *
10781 * See VMSetRuntimeError for the detailed description of parameters.
10782 *
10783 * @param pUVM The user mode VM handle. Ignored, so passing NULL
10784 * is fine.
10785 * @param pvUser The user argument, pointer to the Console instance.
10786 * @param fFlags The action flags. See VMSETRTERR_FLAGS_*.
10787 * @param pszErrorId Error ID string.
10788 * @param pszFormat Error message format string.
10789 * @param va Error message arguments.
10790 * @thread EMT.
10791 */
10792/* static */ DECLCALLBACK(void)
10793Console::i_atVMRuntimeErrorCallback(PUVM pUVM, void *pvUser, uint32_t fFlags,
10794 const char *pszErrorId, const char *pszFormat, va_list va)
10795{
10796 bool const fFatal = !!(fFlags & VMSETRTERR_FLAGS_FATAL);
10797 LogFlowFuncEnter();
10798
10799 Console *that = static_cast<Console *>(pvUser);
10800 AssertReturnVoid(that);
10801
10802 Utf8Str message(pszFormat, va);
10803
10804 LogRel(("Console: VM runtime error: fatal=%RTbool, errorID=%s message=\"%s\"\n", fFatal, pszErrorId, message.c_str()));
10805 try
10806 {
10807 that->i_onRuntimeError(BOOL(fFatal), Bstr(pszErrorId).raw(), Bstr(message).raw());
10808 }
10809 catch (std::bad_alloc &)
10810 {
10811 }
10812 LogFlowFuncLeave(); NOREF(pUVM);
10813}
10814
10815/**
10816 * Captures USB devices that match filters of the VM.
10817 * Called at VM startup.
10818 *
10819 * @param pUVM The VM handle.
10820 */
10821HRESULT Console::i_captureUSBDevices(PUVM pUVM)
10822{
10823 RT_NOREF(pUVM);
10824 LogFlowThisFunc(("\n"));
10825
10826 /* sanity check */
10827 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
10828 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10829
10830 /* If the machine has a USB controller, ask the USB proxy service to
10831 * capture devices */
10832 if (mfVMHasUsbController)
10833 {
10834 /* release the lock before calling Host in VBoxSVC since Host may call
10835 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
10836 * produce an inter-process dead-lock otherwise. */
10837 alock.release();
10838
10839 HRESULT hrc = mControl->AutoCaptureUSBDevices();
10840 ComAssertComRCRetRC(hrc);
10841 }
10842
10843 return S_OK;
10844}
10845
10846
10847/**
10848 * Detach all USB device which are attached to the VM for the
10849 * purpose of clean up and such like.
10850 */
10851void Console::i_detachAllUSBDevices(bool aDone)
10852{
10853 LogFlowThisFunc(("aDone=%RTbool\n", aDone));
10854
10855 /* sanity check */
10856 AssertReturnVoid(!isWriteLockOnCurrentThread());
10857 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10858
10859 mUSBDevices.clear();
10860
10861 /* release the lock before calling Host in VBoxSVC since Host may call
10862 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
10863 * produce an inter-process dead-lock otherwise. */
10864 alock.release();
10865
10866 mControl->DetachAllUSBDevices(aDone);
10867}
10868
10869/* Make sure that the string is null-terminated and its size is less than cchMax bytes.
10870 * Replace invalid UTF8 bytes with '?'.
10871 */
10872static int validateUtf8String(char *psz, size_t cchMax)
10873{
10874 for (;;)
10875 {
10876 RTUNICP Cp;
10877 int vrc = RTStrGetCpNEx((const char **)&psz, &cchMax, &Cp);
10878 if (RT_SUCCESS(vrc))
10879 {
10880 if (!Cp)
10881 break;
10882 }
10883 else
10884 {
10885 if (!cchMax)
10886 return VERR_END_OF_STRING;
10887
10888 psz[-1] = '?';
10889 }
10890 }
10891 return VINF_SUCCESS;
10892}
10893
10894static int validateRemoteUSBDeviceDesc(VRDEUSBDEVICEDESC const *e, uint32_t cbRemaining, bool fDescExt)
10895{
10896 uint32_t const cbDesc = fDescExt ? sizeof(VRDEUSBDEVICEDESCEXT) : sizeof(VRDEUSBDEVICEDESC);
10897 if (cbDesc > cbRemaining)
10898 return VERR_INVALID_PARAMETER;
10899
10900 if ( e->oNext > cbRemaining /* It is OK for oNext to point to the end of buffer. */
10901 || e->oManufacturer >= cbRemaining
10902 || e->oProduct >= cbRemaining
10903 || e->oSerialNumber >= cbRemaining)
10904 return VERR_INVALID_PARAMETER;
10905
10906 int vrc;
10907 if (e->oManufacturer)
10908 {
10909 vrc = validateUtf8String((char *)e + e->oManufacturer, cbRemaining - e->oManufacturer);
10910 if (RT_FAILURE(vrc))
10911 return VERR_INVALID_PARAMETER;
10912 }
10913 if (e->oProduct)
10914 {
10915 vrc = validateUtf8String((char *)e + e->oProduct, cbRemaining - e->oProduct);
10916 if (RT_FAILURE(vrc))
10917 return VERR_INVALID_PARAMETER;
10918 }
10919 if (e->oSerialNumber)
10920 {
10921 vrc = validateUtf8String((char *)e + e->oSerialNumber, cbRemaining - e->oSerialNumber);
10922 if (RT_FAILURE(vrc))
10923 return VERR_INVALID_PARAMETER;
10924 }
10925
10926 return VINF_SUCCESS;
10927}
10928
10929/**
10930 * @note Locks this object for writing.
10931 */
10932void Console::i_processRemoteUSBDevices(uint32_t u32ClientId, VRDEUSBDEVICEDESC *pDevList, uint32_t cbDevList, bool fDescExt)
10933{
10934 LogFlowThisFuncEnter();
10935 LogFlowThisFunc(("u32ClientId = %d, pDevList=%p, cbDevList = %d, fDescExt = %d\n",
10936 u32ClientId, pDevList, cbDevList, fDescExt));
10937
10938 AutoCaller autoCaller(this);
10939 if (!autoCaller.isOk())
10940 {
10941 /* Console has been already uninitialized, deny request */
10942 AssertMsgFailed(("Console is already uninitialized\n"));
10943 LogFlowThisFunc(("Console is already uninitialized\n"));
10944 LogFlowThisFuncLeave();
10945 return;
10946 }
10947
10948 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
10949
10950 /*
10951 * Mark all existing remote USB devices as dirty.
10952 */
10953 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
10954 it != mRemoteUSBDevices.end();
10955 ++it)
10956 {
10957 (*it)->dirty(true);
10958 }
10959
10960 /*
10961 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
10962 */
10963 VRDEUSBDEVICEDESC *e = pDevList;
10964 uint32_t cbRemaining = cbDevList;
10965
10966 /* The cbRemaining condition must be checked first, because the function can
10967 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
10968 */
10969 while (cbRemaining >= sizeof(e->oNext) && e->oNext)
10970 {
10971 int const vrc = validateRemoteUSBDeviceDesc(e, cbRemaining, fDescExt);
10972 if (RT_FAILURE(vrc))
10973 break; /* Consider the rest of the list invalid too. */
10974
10975 LogFlowThisFunc(("vendor %04x, product %04x, name = %s\n",
10976 e->idVendor, e->idProduct, e->oProduct ? (char *)e + e->oProduct : ""));
10977
10978 bool fNewDevice = true;
10979
10980 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
10981 it != mRemoteUSBDevices.end();
10982 ++it)
10983 {
10984 if ( (*it)->devId() == e->id
10985 && (*it)->clientId() == u32ClientId)
10986 {
10987 /* The device is already in the list. */
10988 (*it)->dirty(false);
10989 fNewDevice = false;
10990 break;
10991 }
10992 }
10993
10994 if (fNewDevice)
10995 {
10996 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
10997 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""));
10998
10999 /* Create the device object and add the new device to list. */
11000 ComObjPtr<RemoteUSBDevice> pUSBDevice;
11001 pUSBDevice.createObject();
11002 pUSBDevice->init(u32ClientId, e, fDescExt);
11003
11004 mRemoteUSBDevices.push_back(pUSBDevice);
11005
11006 /* Check if the device is ok for current USB filters. */
11007 BOOL fMatched = FALSE;
11008 ULONG fMaskedIfs = 0;
11009 HRESULT hrc = mControl->RunUSBDeviceFilters(pUSBDevice, &fMatched, &fMaskedIfs);
11010
11011 AssertComRC(hrc);
11012
11013 LogFlowThisFunc(("USB filters return %d %#x\n", fMatched, fMaskedIfs));
11014
11015 if (fMatched)
11016 {
11017 alock.release();
11018 hrc = i_onUSBDeviceAttach(pUSBDevice, NULL, fMaskedIfs, Utf8Str());
11019 alock.acquire();
11020
11021 /// @todo (r=dmik) warning reporting subsystem
11022
11023 if (hrc == S_OK)
11024 {
11025 LogFlowThisFunc(("Device attached\n"));
11026 pUSBDevice->captured(true);
11027 }
11028 }
11029 }
11030
11031 AssertBreak(cbRemaining >= e->oNext); /* validateRemoteUSBDeviceDesc ensures this. */
11032 cbRemaining -= e->oNext;
11033
11034 e = (VRDEUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
11035 }
11036
11037 /*
11038 * Remove dirty devices, that is those which are not reported by the server anymore.
11039 */
11040 for (;;)
11041 {
11042 ComObjPtr<RemoteUSBDevice> pUSBDevice;
11043
11044 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
11045 while (it != mRemoteUSBDevices.end())
11046 {
11047 if ((*it)->dirty())
11048 {
11049 pUSBDevice = *it;
11050 break;
11051 }
11052
11053 ++it;
11054 }
11055
11056 if (!pUSBDevice)
11057 {
11058 break;
11059 }
11060
11061 USHORT vendorId = 0;
11062 pUSBDevice->COMGETTER(VendorId)(&vendorId);
11063
11064 USHORT productId = 0;
11065 pUSBDevice->COMGETTER(ProductId)(&productId);
11066
11067 Bstr product;
11068 pUSBDevice->COMGETTER(Product)(product.asOutParam());
11069
11070 LogRel(("Remote USB: ---- Vendor %04x. Product %04x. Name = [%ls].\n", vendorId, productId, product.raw()));
11071
11072 /* Detach the device from VM. */
11073 if (pUSBDevice->captured())
11074 {
11075 Bstr uuid;
11076 pUSBDevice->COMGETTER(Id)(uuid.asOutParam());
11077 alock.release();
11078 i_onUSBDeviceDetach(uuid.raw(), NULL);
11079 alock.acquire();
11080 }
11081
11082 /* And remove it from the list. */
11083 mRemoteUSBDevices.erase(it);
11084 }
11085
11086 LogFlowThisFuncLeave();
11087}
11088
11089
11090/**
11091 * Worker called by VMPowerUpTask::handler to start the VM (also from saved
11092 * state) and track progress.
11093 *
11094 * @param pTask The power up task.
11095 *
11096 * @note Locks the Console object for writing.
11097 */
11098/*static*/
11099void Console::i_powerUpThreadTask(VMPowerUpTask *pTask)
11100{
11101 LogFlowFuncEnter();
11102
11103 AssertReturnVoid(pTask);
11104 AssertReturnVoid(!pTask->mConsole.isNull());
11105 AssertReturnVoid(!pTask->mProgress.isNull());
11106
11107 VirtualBoxBase::initializeComForThread();
11108
11109 HRESULT hrc = S_OK;
11110 int vrc = VINF_SUCCESS;
11111
11112 /* Set up a build identifier so that it can be seen from core dumps what
11113 * exact build was used to produce the core. */
11114 static char s_szBuildID[48];
11115 RTStrPrintf(s_szBuildID, sizeof(s_szBuildID), "%s%s%s%s VirtualBox %s r%u %s%s%s%s",
11116 "BU", "IL", "DI", "D", RTBldCfgVersion(), RTBldCfgRevision(), "BU", "IL", "DI", "D");
11117
11118 ComObjPtr<Console> pConsole = pTask->mConsole;
11119
11120 /* Note: no need to use AutoCaller because VMPowerUpTask does that */
11121
11122 /* The lock is also used as a signal from the task initiator (which
11123 * releases it only after RTThreadCreate()) that we can start the job */
11124 AutoWriteLock alock(pConsole COMMA_LOCKVAL_SRC_POS);
11125
11126 /* sanity */
11127 Assert(pConsole->mpUVM == NULL);
11128
11129 try
11130 {
11131 // Create the VMM device object, which starts the HGCM thread; do this only
11132 // once for the console, for the pathological case that the same console
11133 // object is used to power up a VM twice.
11134 if (!pConsole->m_pVMMDev)
11135 {
11136 pConsole->m_pVMMDev = new VMMDev(pConsole);
11137 AssertReturnVoid(pConsole->m_pVMMDev);
11138 }
11139
11140 /* wait for auto reset ops to complete so that we can successfully lock
11141 * the attached hard disks by calling LockMedia() below */
11142 for (VMPowerUpTask::ProgressList::const_iterator
11143 it = pTask->hardDiskProgresses.begin();
11144 it != pTask->hardDiskProgresses.end(); ++it)
11145 {
11146 HRESULT hrc2 = (*it)->WaitForCompletion(-1);
11147 AssertComRC(hrc2);
11148
11149 hrc = pTask->mProgress->SetNextOperation(BstrFmt(tr("Disk Image Reset Operation - Immutable Image")).raw(), 1);
11150 AssertComRCReturnVoid(hrc);
11151 }
11152
11153 /*
11154 * Lock attached media. This method will also check their accessibility.
11155 * If we're a teleporter, we'll have to postpone this action so we can
11156 * migrate between local processes.
11157 *
11158 * Note! The media will be unlocked automatically by
11159 * SessionMachine::i_setMachineState() when the VM is powered down.
11160 */
11161 if (!pTask->mTeleporterEnabled)
11162 {
11163 hrc = pConsole->mControl->LockMedia();
11164 if (FAILED(hrc)) throw hrc;
11165 }
11166
11167 /* Create the VRDP server. In case of headless operation, this will
11168 * also create the framebuffer, required at VM creation.
11169 */
11170 ConsoleVRDPServer *server = pConsole->i_consoleVRDPServer();
11171 Assert(server);
11172
11173 /* Does VRDP server call Console from the other thread?
11174 * Not sure (and can change), so release the lock just in case.
11175 */
11176 alock.release();
11177 vrc = server->Launch();
11178 alock.acquire();
11179
11180 if (vrc != VINF_SUCCESS)
11181 {
11182 Utf8Str errMsg = pConsole->VRDPServerErrorToMsg(vrc);
11183 if ( RT_FAILURE(vrc)
11184 && vrc != VERR_NET_ADDRESS_IN_USE) /* not fatal */
11185 throw i_setErrorStaticBoth(E_FAIL, vrc, errMsg.c_str());
11186 }
11187
11188 ComPtr<IMachine> pMachine = pConsole->i_machine();
11189 ULONG cCpus = 1;
11190 pMachine->COMGETTER(CPUCount)(&cCpus);
11191
11192 VMProcPriority_T enmVMPriority = VMProcPriority_Default;
11193 pMachine->COMGETTER(VMProcessPriority)(&enmVMPriority);
11194
11195 /*
11196 * Create the VM
11197 *
11198 * Note! Release the lock since EMT will call Console. It's safe because
11199 * mMachineState is either Starting or Restoring state here.
11200 */
11201 alock.release();
11202
11203 if (enmVMPriority != VMProcPriority_Default)
11204 pConsole->i_onVMProcessPriorityChange(enmVMPriority);
11205
11206 PCVMMR3VTABLE pVMM = pConsole->mpVMM;
11207 PVM pVM = NULL;
11208 vrc = pVMM->pfnVMR3Create(cCpus,
11209 pConsole->mpVmm2UserMethods,
11210 0 /*fFlags*/,
11211 Console::i_genericVMSetErrorCallback,
11212 &pTask->mErrorMsg,
11213 pTask->mpfnConfigConstructor,
11214 static_cast<Console *>(pConsole),
11215 &pVM, NULL);
11216 alock.acquire();
11217 if (RT_SUCCESS(vrc))
11218 {
11219 do /* break "loop" */
11220 {
11221 /*
11222 * Register our load/save state file handlers
11223 */
11224 vrc = pVMM->pfnSSMR3RegisterExternal(pConsole->mpUVM, sSSMConsoleUnit, 0 /*iInstance*/,
11225 CONSOLE_SAVED_STATE_VERSION, 0 /* cbGuess */,
11226 NULL, NULL, NULL,
11227 NULL, i_saveStateFileExec, NULL,
11228 NULL, i_loadStateFileExec, NULL,
11229 static_cast<Console *>(pConsole));
11230 AssertRCBreak(vrc);
11231
11232 vrc = static_cast<Console *>(pConsole)->i_getDisplay()->i_registerSSM(pConsole->mpUVM);
11233 AssertRC(vrc);
11234 if (RT_FAILURE(vrc))
11235 break;
11236
11237 /*
11238 * Synchronize debugger settings
11239 */
11240 MachineDebugger *machineDebugger = pConsole->i_getMachineDebugger();
11241 if (machineDebugger)
11242 machineDebugger->i_flushQueuedSettings();
11243
11244 /*
11245 * Shared Folders
11246 */
11247 if (pConsole->m_pVMMDev->isShFlActive())
11248 {
11249 /* Does the code below call Console from the other thread?
11250 * Not sure, so release the lock just in case. */
11251 alock.release();
11252
11253 for (SharedFolderDataMap::const_iterator it = pTask->mSharedFolders.begin();
11254 it != pTask->mSharedFolders.end();
11255 ++it)
11256 {
11257 const SharedFolderData &d = it->second;
11258 hrc = pConsole->i_createSharedFolder(it->first, d);
11259 if (FAILED(hrc))
11260 {
11261 ErrorInfoKeeper eik;
11262 pConsole->i_atVMRuntimeErrorCallbackF(0, "BrokenSharedFolder",
11263 N_("The shared folder '%s' could not be set up: %ls.\n"
11264 "The shared folder setup will not be complete. It is recommended to power down the virtual "
11265 "machine and fix the shared folder settings while the machine is not running"),
11266 it->first.c_str(), eik.getText().raw());
11267 }
11268 }
11269 if (FAILED(hrc))
11270 hrc = S_OK; // do not fail with broken shared folders
11271
11272 /* acquire the lock again */
11273 alock.acquire();
11274 }
11275
11276#ifdef VBOX_WITH_AUDIO_VRDE
11277 /*
11278 * Attach the VRDE audio driver.
11279 */
11280 if (pConsole->i_getVRDEServer())
11281 {
11282 BOOL fVRDEEnabled = FALSE;
11283 hrc = pConsole->i_getVRDEServer()->COMGETTER(Enabled)(&fVRDEEnabled);
11284 AssertComRCBreak(hrc, RT_NOTHING);
11285
11286 if ( fVRDEEnabled
11287 && pConsole->mAudioVRDE)
11288 pConsole->mAudioVRDE->doAttachDriverViaEmt(pConsole->mpUVM, pVMM, &alock);
11289 }
11290#endif
11291
11292 /*
11293 * Enable client connections to the VRDP server.
11294 */
11295 pConsole->i_consoleVRDPServer()->EnableConnections();
11296
11297#ifdef VBOX_WITH_RECORDING
11298 /*
11299 * Enable recording if configured.
11300 */
11301 BOOL fRecordingEnabled = FALSE;
11302 {
11303 ComPtr<IRecordingSettings> ptrRecordingSettings;
11304 hrc = pConsole->mMachine->COMGETTER(RecordingSettings)(ptrRecordingSettings.asOutParam());
11305 AssertComRCBreak(hrc, RT_NOTHING);
11306
11307 hrc = ptrRecordingSettings->COMGETTER(Enabled)(&fRecordingEnabled);
11308 AssertComRCBreak(hrc, RT_NOTHING);
11309 }
11310 if (fRecordingEnabled)
11311 {
11312 vrc = pConsole->i_recordingEnable(fRecordingEnabled, &alock);
11313 if (RT_SUCCESS(vrc))
11314 ::FireRecordingChangedEvent(pConsole->mEventSource);
11315 else
11316 {
11317 LogRel(("Recording: Failed with %Rrc on VM power up\n", vrc));
11318 vrc = VINF_SUCCESS; /* do not fail with broken recording */
11319 }
11320 }
11321#endif
11322
11323 /* release the lock before a lengthy operation */
11324 alock.release();
11325
11326 /*
11327 * Capture USB devices.
11328 */
11329 hrc = pConsole->i_captureUSBDevices(pConsole->mpUVM);
11330 if (FAILED(hrc))
11331 {
11332 alock.acquire();
11333 break;
11334 }
11335
11336 /*
11337 * Load saved state?
11338 */
11339 if (pTask->mSavedStateFile.length())
11340 {
11341 LogFlowFunc(("Restoring saved state from '%s'...\n", pTask->mSavedStateFile.c_str()));
11342
11343#ifdef VBOX_WITH_FULL_VM_ENCRYPTION
11344 SsmStream ssmStream(pConsole, pVMM, pTask->m_pKeyStore, pTask->mKeyId, pTask->mKeyStore);
11345
11346 vrc = ssmStream.open(pTask->mSavedStateFile.c_str());
11347 if (RT_SUCCESS(vrc))
11348 {
11349 PCSSMSTRMOPS pStreamOps;
11350 void *pvStreamOpsUser;
11351
11352 vrc = ssmStream.querySsmStrmOps(&pStreamOps, &pvStreamOpsUser);
11353 if (RT_SUCCESS(vrc))
11354 vrc = pVMM->pfnVMR3LoadFromStream(pConsole->mpUVM,
11355 pStreamOps, pvStreamOpsUser,
11356 Console::i_stateProgressCallback,
11357 static_cast<IProgress *>(pTask->mProgress),
11358 false /*fTeleporting*/);
11359 }
11360#else
11361 vrc = pVMM->pfnVMR3LoadFromFile(pConsole->mpUVM,
11362 pTask->mSavedStateFile.c_str(),
11363 Console::i_stateProgressCallback,
11364 static_cast<IProgress *>(pTask->mProgress));
11365#endif
11366 if (RT_SUCCESS(vrc))
11367 {
11368 if (pTask->mStartPaused)
11369 /* done */
11370 pConsole->i_setMachineState(MachineState_Paused);
11371 else
11372 {
11373 /* Start/Resume the VM execution */
11374#ifdef VBOX_WITH_EXTPACK
11375 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM, pVMM);
11376#endif
11377 if (RT_SUCCESS(vrc))
11378 vrc = pVMM->pfnVMR3Resume(pConsole->mpUVM, VMRESUMEREASON_STATE_RESTORED);
11379 AssertLogRelRC(vrc);
11380 }
11381 }
11382
11383 /* Power off in case we failed loading or resuming the VM */
11384 if (RT_FAILURE(vrc))
11385 {
11386 int vrc2 = pVMM->pfnVMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
11387#ifdef VBOX_WITH_EXTPACK
11388 pConsole->mptrExtPackManager->i_callAllVmPowerOffHooks(pConsole, pVM, pVMM);
11389#endif
11390 }
11391 }
11392 else if (pTask->mTeleporterEnabled)
11393 {
11394 /* -> ConsoleImplTeleporter.cpp */
11395 bool fPowerOffOnFailure;
11396 hrc = pConsole->i_teleporterTrg(pConsole->mpUVM, pConsole->mpVMM, pMachine, &pTask->mErrorMsg,
11397 pTask->mStartPaused, pTask->mProgress, &fPowerOffOnFailure);
11398 if (FAILED(hrc) && fPowerOffOnFailure)
11399 {
11400 ErrorInfoKeeper eik;
11401 int vrc2 = pVMM->pfnVMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
11402#ifdef VBOX_WITH_EXTPACK
11403 pConsole->mptrExtPackManager->i_callAllVmPowerOffHooks(pConsole, pVM, pVMM);
11404#endif
11405 }
11406 }
11407 else if (pTask->mStartPaused)
11408 /* done */
11409 pConsole->i_setMachineState(MachineState_Paused);
11410 else
11411 {
11412 /* Power on the VM (i.e. start executing) */
11413#ifdef VBOX_WITH_EXTPACK
11414 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM, pVMM);
11415#endif
11416 if (RT_SUCCESS(vrc))
11417 vrc = pVMM->pfnVMR3PowerOn(pConsole->mpUVM);
11418 AssertLogRelRC(vrc);
11419 }
11420
11421 /* acquire the lock again */
11422 alock.acquire();
11423 }
11424 while (0);
11425
11426 /* On failure, destroy the VM */
11427 if (FAILED(hrc) || RT_FAILURE(vrc))
11428 {
11429 /* preserve existing error info */
11430 ErrorInfoKeeper eik;
11431
11432 /* powerDown() will call VMR3Destroy() and do all necessary
11433 * cleanup (VRDP, USB devices) */
11434 alock.release();
11435 HRESULT hrc2 = pConsole->i_powerDown();
11436 alock.acquire();
11437 AssertComRC(hrc2);
11438 }
11439 else
11440 {
11441 /*
11442 * Deregister the VMSetError callback. This is necessary as the
11443 * pfnVMAtError() function passed to VMR3Create() is supposed to
11444 * be sticky but our error callback isn't.
11445 */
11446 alock.release();
11447 pVMM->pfnVMR3AtErrorDeregister(pConsole->mpUVM, Console::i_genericVMSetErrorCallback, &pTask->mErrorMsg);
11448 /** @todo register another VMSetError callback? */
11449 alock.acquire();
11450 }
11451 }
11452 else
11453 {
11454 /*
11455 * If VMR3Create() failed it has released the VM memory.
11456 */
11457 if (pConsole->m_pVMMDev)
11458 {
11459 alock.release(); /* just to be on the safe side... */
11460 pConsole->m_pVMMDev->hgcmShutdown(true /*fUvmIsInvalid*/);
11461 alock.acquire();
11462 }
11463 pVMM->pfnVMR3ReleaseUVM(pConsole->mpUVM);
11464 pConsole->mpUVM = NULL;
11465 }
11466
11467 if (SUCCEEDED(hrc) && RT_FAILURE(vrc))
11468 {
11469 /* If VMR3Create() or one of the other calls in this function fail,
11470 * an appropriate error message has been set in pTask->mErrorMsg.
11471 * However since that happens via a callback, the hrc status code in
11472 * this function is not updated.
11473 */
11474 if (!pTask->mErrorMsg.length())
11475 {
11476 /* If the error message is not set but we've got a failure,
11477 * convert the VBox status code into a meaningful error message.
11478 * This becomes unused once all the sources of errors set the
11479 * appropriate error message themselves.
11480 */
11481 AssertMsgFailed(("Missing error message during powerup for status code %Rrc\n", vrc));
11482 pTask->mErrorMsg = Utf8StrFmt(tr("Failed to start VM execution (%Rrc)"), vrc);
11483 }
11484
11485 /* Set the error message as the COM error.
11486 * Progress::notifyComplete() will pick it up later. */
11487 throw i_setErrorStaticBoth(E_FAIL, vrc, pTask->mErrorMsg.c_str());
11488 }
11489 }
11490 catch (HRESULT hrcXcpt) { hrc = hrcXcpt; }
11491
11492 if ( pConsole->mMachineState == MachineState_Starting
11493 || pConsole->mMachineState == MachineState_Restoring
11494 || pConsole->mMachineState == MachineState_TeleportingIn
11495 )
11496 {
11497 /* We are still in the Starting/Restoring state. This means one of:
11498 *
11499 * 1) we failed before VMR3Create() was called;
11500 * 2) VMR3Create() failed.
11501 *
11502 * In both cases, there is no need to call powerDown(), but we still
11503 * need to go back to the PoweredOff/Saved state. Reuse
11504 * vmstateChangeCallback() for that purpose.
11505 */
11506
11507 /* preserve existing error info */
11508 ErrorInfoKeeper eik;
11509
11510 Assert(pConsole->mpUVM == NULL);
11511 i_vmstateChangeCallback(NULL, pConsole->mpVMM, VMSTATE_TERMINATED, VMSTATE_CREATING, pConsole);
11512 }
11513
11514 /*
11515 * Evaluate the final result. Note that the appropriate mMachineState value
11516 * is already set by vmstateChangeCallback() in all cases.
11517 */
11518
11519 /* release the lock, don't need it any more */
11520 alock.release();
11521
11522 if (SUCCEEDED(hrc))
11523 {
11524 /* Notify the progress object of the success */
11525 pTask->mProgress->i_notifyComplete(S_OK);
11526 }
11527 else
11528 {
11529 /* The progress object will fetch the current error info */
11530 pTask->mProgress->i_notifyComplete(hrc);
11531 LogRel(("Power up failed (vrc=%Rrc, hrc=%Rhrc (%#08X))\n", vrc, hrc, hrc));
11532 }
11533
11534 /* Notify VBoxSVC and any waiting openRemoteSession progress object. */
11535 pConsole->mControl->EndPowerUp(hrc);
11536
11537#if defined(RT_OS_WINDOWS)
11538 /* uninitialize COM */
11539 CoUninitialize();
11540#endif
11541
11542 LogFlowFuncLeave();
11543}
11544
11545
11546/**
11547 * Reconfigures a medium attachment (part of taking or deleting an online snapshot).
11548 *
11549 * @param pThis Reference to the console object.
11550 * @param pUVM The VM handle.
11551 * @param pVMM The VMM vtable.
11552 * @param pcszDevice The name of the controller type.
11553 * @param uInstance The instance of the controller.
11554 * @param enmBus The storage bus type of the controller.
11555 * @param fUseHostIOCache Use the host I/O cache (disable async I/O).
11556 * @param fBuiltinIOCache Use the builtin I/O cache.
11557 * @param fInsertDiskIntegrityDrv Flag whether to insert the disk integrity driver into the chain
11558 * for additionalk debugging aids.
11559 * @param fSetupMerge Whether to set up a medium merge
11560 * @param uMergeSource Merge source image index
11561 * @param uMergeTarget Merge target image index
11562 * @param aMediumAtt The medium attachment.
11563 * @param aMachineState The current machine state.
11564 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
11565 * @return VBox status code.
11566 */
11567/* static */
11568DECLCALLBACK(int) Console::i_reconfigureMediumAttachment(Console *pThis,
11569 PUVM pUVM,
11570 PCVMMR3VTABLE pVMM,
11571 const char *pcszDevice,
11572 unsigned uInstance,
11573 StorageBus_T enmBus,
11574 bool fUseHostIOCache,
11575 bool fBuiltinIOCache,
11576 bool fInsertDiskIntegrityDrv,
11577 bool fSetupMerge,
11578 unsigned uMergeSource,
11579 unsigned uMergeTarget,
11580 IMediumAttachment *aMediumAtt,
11581 MachineState_T aMachineState,
11582 HRESULT *phrc)
11583{
11584 LogFlowFunc(("pUVM=%p aMediumAtt=%p phrc=%p\n", pUVM, aMediumAtt, phrc));
11585
11586 HRESULT hrc;
11587 Bstr bstr;
11588 *phrc = S_OK;
11589#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%Rhrc (%#x)\n", hrc, hrc)); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
11590
11591 /* Ignore attachments other than hard disks, since at the moment they are
11592 * not subject to snapshotting in general. */
11593 DeviceType_T lType;
11594 hrc = aMediumAtt->COMGETTER(Type)(&lType); H();
11595 if (lType != DeviceType_HardDisk)
11596 return VINF_SUCCESS;
11597
11598 /* Update the device instance configuration. */
11599 int vrc = pThis->i_configMediumAttachment(pcszDevice,
11600 uInstance,
11601 enmBus,
11602 fUseHostIOCache,
11603 fBuiltinIOCache,
11604 fInsertDiskIntegrityDrv,
11605 fSetupMerge,
11606 uMergeSource,
11607 uMergeTarget,
11608 aMediumAtt,
11609 aMachineState,
11610 phrc,
11611 true /* fAttachDetach */,
11612 false /* fForceUnmount */,
11613 false /* fHotplug */,
11614 pUVM,
11615 pVMM,
11616 NULL /* paLedDevType */,
11617 NULL /* ppLunL0)*/);
11618 if (RT_FAILURE(vrc))
11619 {
11620 AssertMsgFailed(("vrc=%Rrc\n", vrc));
11621 return vrc;
11622 }
11623
11624#undef H
11625
11626 LogFlowFunc(("Returns success\n"));
11627 return VINF_SUCCESS;
11628}
11629
11630/**
11631 * Thread for powering down the Console.
11632 *
11633 * @param pTask The power down task.
11634 *
11635 * @note Locks the Console object for writing.
11636 */
11637/*static*/
11638void Console::i_powerDownThreadTask(VMPowerDownTask *pTask)
11639{
11640 int vrc = VINF_SUCCESS; /* only used in assertion */
11641 LogFlowFuncEnter();
11642 try
11643 {
11644 if (pTask->isOk() == false)
11645 vrc = VERR_GENERAL_FAILURE;
11646
11647 const ComObjPtr<Console> &that = pTask->mConsole;
11648
11649 /* Note: no need to use AutoCaller to protect Console because VMTask does
11650 * that */
11651
11652 /* wait until the method tat started us returns */
11653 AutoWriteLock thatLock(that COMMA_LOCKVAL_SRC_POS);
11654
11655 /* release VM caller to avoid the powerDown() deadlock */
11656 pTask->releaseVMCaller();
11657
11658 thatLock.release();
11659
11660 that->i_powerDown(pTask->mServerProgress);
11661
11662 /* complete the operation */
11663 that->mControl->EndPoweringDown(S_OK, Bstr().raw());
11664
11665 }
11666 catch (const std::exception &e)
11667 {
11668 AssertMsgFailed(("Exception %s was caught, vrc=%Rrc\n", e.what(), vrc));
11669 NOREF(e); NOREF(vrc);
11670 }
11671
11672 LogFlowFuncLeave();
11673}
11674
11675/**
11676 * @interface_method_impl{VMM2USERMETHODS,pfnSaveState}
11677 */
11678/*static*/ DECLCALLBACK(int)
11679Console::i_vmm2User_SaveState(PCVMM2USERMETHODS pThis, PUVM pUVM)
11680{
11681 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
11682 NOREF(pUVM);
11683
11684 /*
11685 * For now, just call SaveState. We should probably try notify the GUI so
11686 * it can pop up a progress object and stuff. The progress object created
11687 * by the call isn't returned to anyone and thus gets updated without
11688 * anyone noticing it.
11689 */
11690 ComPtr<IProgress> pProgress;
11691 HRESULT hrc = pConsole->mMachine->SaveState(pProgress.asOutParam());
11692 return SUCCEEDED(hrc) ? VINF_SUCCESS : Global::vboxStatusCodeFromCOM(hrc);
11693}
11694
11695/**
11696 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtInit}
11697 */
11698/*static*/ DECLCALLBACK(void)
11699Console::i_vmm2User_NotifyEmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
11700{
11701 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
11702 VirtualBoxBase::initializeComForThread();
11703}
11704
11705/**
11706 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtTerm}
11707 */
11708/*static*/ DECLCALLBACK(void)
11709Console::i_vmm2User_NotifyEmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
11710{
11711 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
11712 VirtualBoxBase::uninitializeComForThread();
11713}
11714
11715/**
11716 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtInit}
11717 */
11718/*static*/ DECLCALLBACK(void)
11719Console::i_vmm2User_NotifyPdmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM)
11720{
11721 NOREF(pThis); NOREF(pUVM);
11722 VirtualBoxBase::initializeComForThread();
11723}
11724
11725/**
11726 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtTerm}
11727 */
11728/*static*/ DECLCALLBACK(void)
11729Console::i_vmm2User_NotifyPdmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM)
11730{
11731 NOREF(pThis); NOREF(pUVM);
11732 VirtualBoxBase::uninitializeComForThread();
11733}
11734
11735/**
11736 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyResetTurnedIntoPowerOff}
11737 */
11738/*static*/ DECLCALLBACK(void)
11739Console::i_vmm2User_NotifyResetTurnedIntoPowerOff(PCVMM2USERMETHODS pThis, PUVM pUVM)
11740{
11741 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
11742 NOREF(pUVM);
11743
11744 pConsole->mfPowerOffCausedByReset = true;
11745}
11746
11747/**
11748 * Internal function to get LED set off of Console instance
11749 *
11750 * @returns pointer to PDMLED object
11751 *
11752 * @param iLedSet Index of LED set to fetch
11753 */
11754PPDMLED volatile *
11755Console::i_getLedSet(uint32_t iLedSet)
11756{
11757 AssertReturn(iLedSet < RT_ELEMENTS(maLedSets), NULL);
11758 return maLedSets[iLedSet].papLeds;
11759}
11760
11761/**
11762 * @interface_method_impl{VMM2USERMETHODS,pfnQueryGenericObject}
11763 */
11764/*static*/ DECLCALLBACK(void *)
11765Console::i_vmm2User_QueryGenericObject(PCVMM2USERMETHODS pThis, PUVM pUVM, PCRTUUID pUuid)
11766{
11767 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
11768 NOREF(pUVM);
11769
11770 /* To simplify comparison we copy the UUID into a com::Guid object. */
11771 com::Guid const UuidCopy(*pUuid);
11772
11773 if (UuidCopy == COM_IIDOF(IConsole))
11774 {
11775 IConsole *pIConsole = static_cast<IConsole *>(pConsole);
11776 return pIConsole;
11777 }
11778
11779 if (UuidCopy == COM_IIDOF(IMachine))
11780 {
11781 IMachine *pIMachine = pConsole->mMachine;
11782 return pIMachine;
11783 }
11784
11785 if (UuidCopy == COM_IIDOF(IKeyboard))
11786 {
11787 IKeyboard *pIKeyboard = pConsole->mKeyboard;
11788 return pIKeyboard;
11789 }
11790
11791 if (UuidCopy == COM_IIDOF(IMouse))
11792 {
11793 IMouse *pIMouse = pConsole->mMouse;
11794 return pIMouse;
11795 }
11796
11797 if (UuidCopy == COM_IIDOF(IDisplay))
11798 {
11799 IDisplay *pIDisplay = pConsole->mDisplay;
11800 return pIDisplay;
11801 }
11802
11803 if (UuidCopy == COM_IIDOF(INvramStore))
11804 {
11805 NvramStore *pNvramStore = static_cast<NvramStore *>(pConsole->mptrNvramStore);
11806 return pNvramStore;
11807 }
11808
11809#ifdef VBOX_WITH_VIRT_ARMV8
11810 if (UuidCopy == COM_IIDOF(IResourceStore))
11811 {
11812 ResourceStore *pResourceStore = static_cast<ResourceStore *>(pConsole->mptrResourceStore);
11813 return pResourceStore;
11814 }
11815#endif
11816
11817 if (UuidCopy == VMMDEV_OID)
11818 return pConsole->m_pVMMDev;
11819
11820 if (UuidCopy == USBCARDREADER_OID)
11821 return pConsole->mUsbCardReader;
11822
11823 if (UuidCopy == COM_IIDOF(ISnapshot))
11824 return ((MYVMM2USERMETHODS *)pThis)->pISnapshot;
11825
11826 if (UuidCopy == REMOTEUSBIF_OID)
11827 return &pConsole->mRemoteUsbIf;
11828
11829 if (UuidCopy == EMULATEDUSBIF_OID)
11830 return pConsole->mEmulatedUSB->i_getEmulatedUsbIf();
11831
11832 return NULL;
11833}
11834
11835
11836/**
11837 * @interface_method_impl{PDMISECKEY,pfnKeyRetain}
11838 */
11839/*static*/ DECLCALLBACK(int)
11840Console::i_pdmIfSecKey_KeyRetain(PPDMISECKEY pInterface, const char *pszId, const uint8_t **ppbKey, size_t *pcbKey)
11841{
11842 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
11843
11844 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
11845 SecretKey *pKey = NULL;
11846
11847 int vrc = pConsole->m_pKeyStore->retainSecretKey(Utf8Str(pszId), &pKey);
11848 if (RT_SUCCESS(vrc))
11849 {
11850 *ppbKey = (const uint8_t *)pKey->getKeyBuffer();
11851 *pcbKey = pKey->getKeySize();
11852 }
11853
11854 return vrc;
11855}
11856
11857/**
11858 * @interface_method_impl{PDMISECKEY,pfnKeyRelease}
11859 */
11860/*static*/ DECLCALLBACK(int)
11861Console::i_pdmIfSecKey_KeyRelease(PPDMISECKEY pInterface, const char *pszId)
11862{
11863 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
11864
11865 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
11866 return pConsole->m_pKeyStore->releaseSecretKey(Utf8Str(pszId));
11867}
11868
11869/**
11870 * @interface_method_impl{PDMISECKEY,pfnPasswordRetain}
11871 */
11872/*static*/ DECLCALLBACK(int)
11873Console::i_pdmIfSecKey_PasswordRetain(PPDMISECKEY pInterface, const char *pszId, const char **ppszPassword)
11874{
11875 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
11876
11877 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
11878 SecretKey *pKey = NULL;
11879
11880 int vrc = pConsole->m_pKeyStore->retainSecretKey(Utf8Str(pszId), &pKey);
11881 if (RT_SUCCESS(vrc))
11882 *ppszPassword = (const char *)pKey->getKeyBuffer();
11883
11884 return vrc;
11885}
11886
11887/**
11888 * @interface_method_impl{PDMISECKEY,pfnPasswordRelease}
11889 */
11890/*static*/ DECLCALLBACK(int)
11891Console::i_pdmIfSecKey_PasswordRelease(PPDMISECKEY pInterface, const char *pszId)
11892{
11893 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
11894
11895 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
11896 return pConsole->m_pKeyStore->releaseSecretKey(Utf8Str(pszId));
11897}
11898
11899/**
11900 * @interface_method_impl{PDMISECKEYHLP,pfnKeyMissingNotify}
11901 */
11902/*static*/ DECLCALLBACK(int)
11903Console::i_pdmIfSecKeyHlp_KeyMissingNotify(PPDMISECKEYHLP pInterface)
11904{
11905 Console *pConsole = ((MYPDMISECKEYHLP *)pInterface)->pConsole;
11906
11907 /* Set guest property only, the VM is paused in the media driver calling us. */
11908 pConsole->mMachine->DeleteGuestProperty(Bstr("/VirtualBox/HostInfo/DekMissing").raw());
11909 pConsole->mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/DekMissing").raw(),
11910 Bstr("1").raw(), Bstr("RDONLYGUEST").raw());
11911 pConsole->mMachine->SaveSettings();
11912
11913 return VINF_SUCCESS;
11914}
11915
11916
11917
11918/**
11919 * The Main status driver instance data.
11920 */
11921typedef struct DRVMAINSTATUS
11922{
11923 /** The LED connectors. */
11924 PDMILEDCONNECTORS ILedConnectors;
11925 /** Pointer to the LED ports interface above us. */
11926 PPDMILEDPORTS pLedPorts;
11927 /** Pointer to the array of LED pointers. */
11928 PPDMLED volatile *papLeds;
11929 /** The unit number corresponding to the first entry in the LED array. */
11930 uint32_t iFirstLUN;
11931 /** The unit number corresponding to the last entry in the LED array.
11932 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
11933 uint32_t iLastLUN;
11934 /** Pointer to the driver instance. */
11935 PPDMDRVINS pDrvIns;
11936 /** The Media Notify interface. */
11937 PDMIMEDIANOTIFY IMediaNotify;
11938 /** Set if there potentially are medium attachments. */
11939 bool fHasMediumAttachments;
11940 /** Device name+instance for mapping */
11941 char *pszDeviceInstance;
11942 /** Pointer to the Console object, for driver triggered activities. */
11943 Console *pConsole;
11944} DRVMAINSTATUS;
11945/** Pointer the instance data for a Main status driver. */
11946typedef DRVMAINSTATUS *PDRVMAINSTATUS;
11947
11948
11949/**
11950 * Notification about a unit which have been changed.
11951 *
11952 * The driver must discard any pointers to data owned by
11953 * the unit and requery it.
11954 *
11955 * @param pInterface Pointer to the interface structure containing the called function pointer.
11956 * @param iLUN The unit number.
11957 */
11958DECLCALLBACK(void) Console::i_drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
11959{
11960 PDRVMAINSTATUS pThis = RT_FROM_MEMBER(pInterface, DRVMAINSTATUS, ILedConnectors);
11961 if (iLUN >= pThis->iFirstLUN && iLUN <= pThis->iLastLUN)
11962 {
11963 /*
11964 * Query the pointer to the PDMLED field inside the target device
11965 * structure (owned by the virtual hardware device).
11966 */
11967 PPDMLED pLed;
11968 int vrc = pThis->pLedPorts->pfnQueryStatusLed(pThis->pLedPorts, iLUN, &pLed);
11969 if (RT_FAILURE(vrc))
11970 pLed = NULL;
11971
11972 /*
11973 * Update the corresponding papLeds[] entry.
11974 *
11975 * papLeds[] points to the struct PDMLED of each of this driver's
11976 * units. The entries are initialized here, called out of a loop
11977 * in Console::i_drvStatus_Construct(), which previously called
11978 * Console::i_attachStatusDriver() to allocate the array itself.
11979 *
11980 * The arrays (and thus individual LEDs) are eventually read out
11981 * by Console::getDeviceActivity(), which is itself called from
11982 * src/VBox/Frontends/VirtualBox/src/runtime/UIIndicatorsPool.cpp
11983 */
11984 /** @todo acquire Console::mLedLock here in exclusive mode? */
11985 ASMAtomicWritePtr(&pThis->papLeds[iLUN - pThis->iFirstLUN], pLed);
11986 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
11987 }
11988}
11989
11990
11991/**
11992 * Notification about a medium eject.
11993 *
11994 * @returns VBox status code.
11995 * @param pInterface Pointer to the interface structure containing the called function pointer.
11996 * @param uLUN The unit number.
11997 */
11998DECLCALLBACK(int) Console::i_drvStatus_MediumEjected(PPDMIMEDIANOTIFY pInterface, unsigned uLUN)
11999{
12000 PDRVMAINSTATUS pThis = RT_FROM_MEMBER(pInterface, DRVMAINSTATUS, IMediaNotify);
12001 LogFunc(("uLUN=%d\n", uLUN));
12002 if (pThis->fHasMediumAttachments)
12003 {
12004 Console * const pConsole = pThis->pConsole;
12005 AutoWriteLock alock(pConsole COMMA_LOCKVAL_SRC_POS);
12006
12007 ComPtr<IMediumAttachment> pMediumAtt;
12008 Utf8Str devicePath = Utf8StrFmt("%s/LUN#%u", pThis->pszDeviceInstance, uLUN);
12009 Console::MediumAttachmentMap::const_iterator end = pConsole->mapMediumAttachments.end();
12010 Console::MediumAttachmentMap::const_iterator it = pConsole->mapMediumAttachments.find(devicePath);
12011 if (it != end)
12012 pMediumAtt = it->second;
12013 Assert(!pMediumAtt.isNull());
12014 if (!pMediumAtt.isNull())
12015 {
12016 IMedium *pMedium = NULL;
12017 HRESULT hrc = pMediumAtt->COMGETTER(Medium)(&pMedium);
12018 AssertComRC(hrc);
12019 if (SUCCEEDED(hrc) && pMedium)
12020 {
12021 BOOL fHostDrive = FALSE;
12022 hrc = pMedium->COMGETTER(HostDrive)(&fHostDrive);
12023 AssertComRC(hrc);
12024 if (!fHostDrive)
12025 {
12026 alock.release();
12027
12028 ComPtr<IMediumAttachment> pNewMediumAtt;
12029 hrc = pThis->pConsole->mControl->EjectMedium(pMediumAtt, pNewMediumAtt.asOutParam());
12030 if (SUCCEEDED(hrc))
12031 {
12032 pThis->pConsole->mMachine->SaveSettings();
12033 ::FireMediumChangedEvent(pThis->pConsole->mEventSource, pNewMediumAtt);
12034 }
12035
12036 alock.acquire();
12037 if (pNewMediumAtt != pMediumAtt)
12038 {
12039 pConsole->mapMediumAttachments.erase(devicePath);
12040 pConsole->mapMediumAttachments.insert(std::make_pair(devicePath, pNewMediumAtt));
12041 }
12042 }
12043 }
12044 }
12045 }
12046 return VINF_SUCCESS;
12047}
12048
12049
12050/**
12051 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
12052 */
12053DECLCALLBACK(void *) Console::i_drvStatus_QueryInterface(PPDMIBASE pInterface, const char *pszIID)
12054{
12055 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
12056 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
12057 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
12058 PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDCONNECTORS, &pThis->ILedConnectors);
12059 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIANOTIFY, &pThis->IMediaNotify);
12060 return NULL;
12061}
12062
12063
12064/**
12065 * Destruct a status driver instance.
12066 *
12067 * @param pDrvIns The driver instance data.
12068 */
12069DECLCALLBACK(void) Console::i_drvStatus_Destruct(PPDMDRVINS pDrvIns)
12070{
12071 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
12072 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
12073 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
12074
12075 if (pThis->papLeds)
12076 {
12077 unsigned iLed = pThis->iLastLUN - pThis->iFirstLUN + 1;
12078 while (iLed-- > 0)
12079 ASMAtomicWriteNullPtr(&pThis->papLeds[iLed]);
12080 }
12081}
12082
12083
12084/**
12085 * Construct a status driver instance.
12086 *
12087 * @copydoc FNPDMDRVCONSTRUCT
12088 */
12089DECLCALLBACK(int) Console::i_drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
12090{
12091 RT_NOREF(fFlags);
12092 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
12093 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
12094 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
12095
12096 /*
12097 * Initialize data.
12098 */
12099 com::Guid ConsoleUuid(COM_IIDOF(IConsole));
12100 IConsole *pIConsole = (IConsole *)PDMDrvHlpQueryGenericUserObject(pDrvIns, ConsoleUuid.raw());
12101 AssertLogRelReturn(pIConsole, VERR_INTERNAL_ERROR_3);
12102 Console *pConsole = static_cast<Console *>(pIConsole);
12103 AssertLogRelReturn(pConsole, VERR_INTERNAL_ERROR_3);
12104
12105 pDrvIns->IBase.pfnQueryInterface = Console::i_drvStatus_QueryInterface;
12106 pThis->ILedConnectors.pfnUnitChanged = Console::i_drvStatus_UnitChanged;
12107 pThis->IMediaNotify.pfnEjected = Console::i_drvStatus_MediumEjected;
12108 pThis->pDrvIns = pDrvIns;
12109 pThis->pConsole = pConsole;
12110 pThis->fHasMediumAttachments = false;
12111 pThis->papLeds = NULL;
12112 pThis->pszDeviceInstance = NULL;
12113
12114 /*
12115 * Validate configuration.
12116 */
12117 PDMDRV_VALIDATE_CONFIG_RETURN(pDrvIns,
12118 "DeviceInstance|"
12119 "iLedSet|"
12120 "HasMediumAttachments|"
12121 "First|"
12122 "Last",
12123 "");
12124 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
12125 ("Configuration error: Not possible to attach anything to this driver!\n"),
12126 VERR_PDM_DRVINS_NO_ATTACH);
12127
12128 /*
12129 * Read config.
12130 */
12131 PCPDMDRVHLPR3 const pHlp = pDrvIns->pHlpR3;
12132
12133 uint32_t iLedSet;
12134 int vrc = pHlp->pfnCFGMQueryU32(pCfg, "iLedSet", &iLedSet);
12135 AssertLogRelMsgRCReturn(vrc, ("Configuration error: Failed to query the \"iLedSet\" value! vrc=%Rrc\n", vrc), vrc);
12136 pThis->papLeds = pConsole->i_getLedSet(iLedSet);
12137
12138 vrc = pHlp->pfnCFGMQueryBoolDef(pCfg, "HasMediumAttachments", &pThis->fHasMediumAttachments, false);
12139 AssertLogRelMsgRCReturn(vrc, ("Configuration error: Failed to query the \"HasMediumAttachments\" value! vrc=%Rrc\n", vrc), vrc);
12140
12141 if (pThis->fHasMediumAttachments)
12142 {
12143 vrc = pHlp->pfnCFGMQueryStringAlloc(pCfg, "DeviceInstance", &pThis->pszDeviceInstance);
12144 AssertLogRelMsgRCReturn(vrc, ("Configuration error: Failed to query the \"DeviceInstance\" value! vrc=%Rrc\n", vrc), vrc);
12145 }
12146
12147 vrc = pHlp->pfnCFGMQueryU32Def(pCfg, "First", &pThis->iFirstLUN, 0);
12148 AssertLogRelMsgRCReturn(vrc, ("Configuration error: Failed to query the \"First\" value! vrc=%Rrc\n", vrc), vrc);
12149
12150 vrc = pHlp->pfnCFGMQueryU32Def(pCfg, "Last", &pThis->iLastLUN, 0);
12151 AssertLogRelMsgRCReturn(vrc, ("Configuration error: Failed to query the \"Last\" value! vrc=%Rrc\n", vrc), vrc);
12152
12153 AssertLogRelMsgReturn(pThis->iFirstLUN <= pThis->iLastLUN,
12154 ("Configuration error: Invalid unit range %u-%u\n", pThis->iFirstLUN, pThis->iLastLUN),
12155 VERR_INVALID_PARAMETER);
12156
12157 /*
12158 * Get the ILedPorts interface of the above driver/device and
12159 * query the LEDs we want.
12160 */
12161 pThis->pLedPorts = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMILEDPORTS);
12162 AssertMsgReturn(pThis->pLedPorts, ("Configuration error: No led ports interface above!\n"),
12163 VERR_PDM_MISSING_INTERFACE_ABOVE);
12164
12165 for (unsigned i = pThis->iFirstLUN; i <= pThis->iLastLUN; ++i)
12166 Console::i_drvStatus_UnitChanged(&pThis->ILedConnectors, i);
12167
12168 return VINF_SUCCESS;
12169}
12170
12171
12172/**
12173 * Console status driver (LED) registration record.
12174 */
12175const PDMDRVREG Console::DrvStatusReg =
12176{
12177 /* u32Version */
12178 PDM_DRVREG_VERSION,
12179 /* szName */
12180 "MainStatus",
12181 /* szRCMod */
12182 "",
12183 /* szR0Mod */
12184 "",
12185 /* pszDescription */
12186 "Main status driver (Main as in the API).",
12187 /* fFlags */
12188 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
12189 /* fClass. */
12190 PDM_DRVREG_CLASS_STATUS,
12191 /* cMaxInstances */
12192 ~0U,
12193 /* cbInstance */
12194 sizeof(DRVMAINSTATUS),
12195 /* pfnConstruct */
12196 Console::i_drvStatus_Construct,
12197 /* pfnDestruct */
12198 Console::i_drvStatus_Destruct,
12199 /* pfnRelocate */
12200 NULL,
12201 /* pfnIOCtl */
12202 NULL,
12203 /* pfnPowerOn */
12204 NULL,
12205 /* pfnReset */
12206 NULL,
12207 /* pfnSuspend */
12208 NULL,
12209 /* pfnResume */
12210 NULL,
12211 /* pfnAttach */
12212 NULL,
12213 /* pfnDetach */
12214 NULL,
12215 /* pfnPowerOff */
12216 NULL,
12217 /* pfnSoftReset */
12218 NULL,
12219 /* u32EndVersion */
12220 PDM_DRVREG_VERSION
12221};
12222
12223
12224
12225/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use