VirtualBox

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

Last change on this file since 98085 was 98085, checked in by vboxsync, 2 years ago

Main/ConsoleImpl: Added @todo's to getDeviceActivity regarding outstanding issues. bugref:9892

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

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