VirtualBox

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

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

scm copyright and license note update

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