VirtualBox

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

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

Main/ConsoleImpl.cpp: rc -> hrc/vrc. bugref:10223

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