VirtualBox

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

Last change on this file since 81286 was 81286, checked in by vboxsync, 5 years ago

Shared Clipboard/Transfers: Added IMachine::clipboardFileTransfersEnabled attribute (getter/setter) for enabling/disabling the feature. Disabled by default.

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

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