VirtualBox

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

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

Main,VMM: Implemented most of the functionality for encrypted VMs (encrypting log files is still missing), bugref:9955

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

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