VirtualBox

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

Last change on this file since 98123 was 98123, checked in by vboxsync, 23 months ago

Main/Console: Todo wrt MSD hotplugging and some coding style nits.

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