VirtualBox

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

Last change on this file since 98103 was 98103, checked in by vboxsync, 17 months ago

Copyright year updates by scm.

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

© 2023 Oracle
ContactPrivacy policyTerms of Use