VirtualBox

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

Last change on this file since 74765 was 74765, checked in by vboxsync, 7 years ago

VideoRec/Main: Condensed code for enabling / disabling video (audio) recording at VM startup and onVideoCaptureChange handler.

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

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