VirtualBox

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

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

Backed out r154357,r154358,r154360,r154361,r154364 because it still doesn't build, old files weren't renamed or removed, and the changes for bugref:10180 and bugref:4787 got mixed up, making it difficult to selectively revert the latter one only.

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

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