VirtualBox

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

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

Main/comimpl.xsl,++: Try use the Utf8Str versions of the event stuff where possible. bugref:9790

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

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