VirtualBox

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

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

Main/Console+ConsoleVRDPServer+ApplianceExport+Host+Machine+USBDeviceFilters: fix missing RT_NOREF(...) if VBOX_WITH_USB is undefined

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