VirtualBox

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

Last change on this file since 99844 was 99808, checked in by vboxsync, 19 months ago

Main/ConsoleImpl: Work around compilation under parfait, bugref:3409

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