VirtualBox

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

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

Recording: Bugfixes for Main and FE/Qt.

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