VirtualBox

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

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

Shared Clipboard/HostService: Emphasize that VBOX_SHCL_TRANSFER_MODE actually is a flag and not just a number (-> VBOX_SHCL_TRANSFER_MODE_F_XXX). bugref:9437

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

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