VirtualBox

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

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

Main/ConsoleImpl: Modified the LED set enmType to a bitmap containing all possible types, thus allowing us to skip scanning the paSubTypes array when present. Also simplified i_attachStatusDriver a little. bugref:9892

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