VirtualBox

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

Last change on this file since 75361 was 75361, checked in by vboxsync, 6 years ago

Recording/Main: Renamed the IRecord* interfaces again to IRecording* to make it more standardized.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 365.3 KB
Line 
1/* $Id: ConsoleImpl.cpp 75361 2018-11-09 12:56:40Z 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_RECORDING
65# include "DrvAudioRec.h"
66#endif
67#include "Nvram.h"
68#ifdef VBOX_WITH_USB_CARDREADER
69# include "UsbCardReader.h"
70#endif
71#include "ProgressImpl.h"
72#include "ConsoleVRDPServer.h"
73#include "VMMDev.h"
74#ifdef VBOX_WITH_EXTPACK
75# include "ExtPackManagerImpl.h"
76#endif
77#include "BusAssignmentManager.h"
78#include "PCIDeviceAttachmentImpl.h"
79#include "EmulatedUSBImpl.h"
80
81#include "VBoxEvents.h"
82#include "AutoCaller.h"
83#include "ThreadTask.h"
84
85#ifdef VBOX_WITH_RECORDING
86# include "Recording.h"
87#endif
88
89#include <VBox/com/array.h>
90#include "VBox/com/ErrorInfo.h"
91#include <VBox/com/listeners.h>
92
93#include <iprt/asm.h>
94#include <iprt/buildconfig.h>
95#include <iprt/cpp/utils.h>
96#include <iprt/dir.h>
97#include <iprt/file.h>
98#include <iprt/ldr.h>
99#include <iprt/path.h>
100#include <iprt/process.h>
101#include <iprt/string.h>
102#include <iprt/system.h>
103#include <iprt/base64.h>
104#include <iprt/memsafer.h>
105
106#include <VBox/vmm/vmapi.h>
107#include <VBox/vmm/vmm.h>
108#include <VBox/vmm/pdmapi.h>
109#include <VBox/vmm/pdmaudioifs.h>
110#include <VBox/vmm/pdmasynccompletion.h>
111#include <VBox/vmm/pdmnetifs.h>
112#include <VBox/vmm/pdmstorageifs.h>
113#ifdef VBOX_WITH_USB
114# include <VBox/vmm/pdmusb.h>
115#endif
116#ifdef VBOX_WITH_NETSHAPER
117# include <VBox/vmm/pdmnetshaper.h>
118#endif /* VBOX_WITH_NETSHAPER */
119#include <VBox/vmm/mm.h>
120#include <VBox/vmm/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_RECORDING
589 unconst(Recording.mAudioRec) = new AudioVideoRec(this);
590 AssertReturn(Recording.mAudioRec, 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_RECORDING
737 if (Recording.mAudioRec)
738 {
739 delete Recording.mAudioRec;
740 unconst(Recording.mAudioRec) = 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_RECORDING
5602/**
5603 * Enables or disables recording of a VM.
5604 *
5605 * @returns IPRT status code. Will return VERR_NO_CHANGE if the recording state has not been changed.
5606 * @param fEnable Whether to enable or disable the recording.
5607 * @param pAutoLock Pointer to auto write lock to use for attaching/detaching required driver(s) at runtime.
5608 */
5609int Console::i_recordingEnable(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 = Recording.mpCtx
5619 && Recording.mpCtx->IsStarted();
5620
5621 if (RT_BOOL(fEnable) != fIsEnabled)
5622 {
5623 LogRel(("Recording: %s\n", fEnable ? "Enabling" : "Disabling"));
5624
5625 pDisplay->i_recordingInvalidate();
5626
5627 if (fEnable)
5628 {
5629 vrc = i_recordingCreate();
5630 if (RT_SUCCESS(vrc))
5631 {
5632# ifdef VBOX_WITH_AUDIO_RECORDING
5633 /* Attach the video recording audio driver if required. */
5634 if ( Recording.mpCtx->IsFeatureEnabled(RecordingFeature_Audio)
5635 && Recording.mAudioRec)
5636 {
5637 vrc = Recording.mAudioRec->applyConfiguration(Recording.mpCtx->GetConfig());
5638 if (RT_SUCCESS(vrc))
5639 vrc = Recording.mAudioRec->doAttachDriverViaEmt(mpUVM, pAutoLock);
5640 }
5641# endif
5642 if ( RT_SUCCESS(vrc)
5643 && Recording.mpCtx->IsReady()) /* Any video recording (audio and/or video) feature enabled? */
5644 {
5645 vrc = i_recordingStart();
5646 }
5647 }
5648 }
5649 else
5650 {
5651 i_recordingStop();
5652# ifdef VBOX_WITH_AUDIO_RECORDING
5653 Recording.mAudioRec->doDetachDriverViaEmt(mpUVM, pAutoLock);
5654# endif
5655 i_recordingDestroy();
5656 }
5657
5658 if (RT_FAILURE(vrc))
5659 LogRel(("Recording: %s failed with %Rrc\n", fEnable ? "Enabling" : "Disabling", vrc));
5660 }
5661 else /* Should not happen. */
5662 vrc = VERR_NO_CHANGE;
5663 }
5664
5665 return vrc;
5666}
5667#endif /* VBOX_WITH_RECORDING */
5668
5669HRESULT Console::i_onRecordingChange()
5670{
5671 AutoCaller autoCaller(this);
5672 AssertComRCReturnRC(autoCaller.rc());
5673
5674 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5675
5676 HRESULT rc = S_OK;
5677#ifdef VBOX_WITH_RECORDING
5678 /* Don't trigger recording changes if the VM isn't running. */
5679 SafeVMPtrQuiet ptrVM(this);
5680 if (ptrVM.isOk())
5681 {
5682 ComPtr<IRecordingSettings> recordingSettings;
5683 rc = mMachine->COMGETTER(RecordingSettings)(recordingSettings.asOutParam());
5684 AssertComRCReturnRC(rc);
5685
5686 BOOL fEnabled;
5687 rc = recordingSettings->COMGETTER(Enabled)(&fEnabled);
5688 AssertComRCReturnRC(rc);
5689
5690 int vrc = i_recordingEnable(fEnabled, &alock);
5691 if (RT_SUCCESS(vrc))
5692 {
5693 alock.release();
5694 fireRecordingChangedEvent(mEventSource);
5695 }
5696
5697 ptrVM.release();
5698 }
5699#endif /* VBOX_WITH_RECORDING */
5700
5701 return rc;
5702}
5703
5704/**
5705 * Called by IInternalSessionControl::OnUSBControllerChange().
5706 */
5707HRESULT Console::i_onUSBControllerChange()
5708{
5709 LogFlowThisFunc(("\n"));
5710
5711 AutoCaller autoCaller(this);
5712 AssertComRCReturnRC(autoCaller.rc());
5713
5714 fireUSBControllerChangedEvent(mEventSource);
5715
5716 return S_OK;
5717}
5718
5719/**
5720 * Called by IInternalSessionControl::OnSharedFolderChange().
5721 *
5722 * @note Locks this object for writing.
5723 */
5724HRESULT Console::i_onSharedFolderChange(BOOL aGlobal)
5725{
5726 LogFlowThisFunc(("aGlobal=%RTbool\n", aGlobal));
5727
5728 AutoCaller autoCaller(this);
5729 AssertComRCReturnRC(autoCaller.rc());
5730
5731 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5732
5733 HRESULT rc = i_fetchSharedFolders(aGlobal);
5734
5735 /* notify console callbacks on success */
5736 if (SUCCEEDED(rc))
5737 {
5738 alock.release();
5739 fireSharedFolderChangedEvent(mEventSource, aGlobal ? Scope_Global : Scope_Machine);
5740 }
5741
5742 return rc;
5743}
5744
5745/**
5746 * Called by IInternalSessionControl::OnUSBDeviceAttach() or locally by
5747 * processRemoteUSBDevices() after IInternalMachineControl::RunUSBDeviceFilters()
5748 * returns TRUE for a given remote USB device.
5749 *
5750 * @return S_OK if the device was attached to the VM.
5751 * @return failure if not attached.
5752 *
5753 * @param aDevice The device in question.
5754 * @param aError Error information.
5755 * @param aMaskedIfs The interfaces to hide from the guest.
5756 * @param aCaptureFilename File name where to store the USB traffic.
5757 *
5758 * @note Locks this object for writing.
5759 */
5760HRESULT Console::i_onUSBDeviceAttach(IUSBDevice *aDevice, IVirtualBoxErrorInfo *aError, ULONG aMaskedIfs,
5761 const Utf8Str &aCaptureFilename)
5762{
5763#ifdef VBOX_WITH_USB
5764 LogFlowThisFunc(("aDevice=%p aError=%p\n", aDevice, aError));
5765
5766 AutoCaller autoCaller(this);
5767 ComAssertComRCRetRC(autoCaller.rc());
5768
5769 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5770
5771 /* Get the VM pointer (we don't need error info, since it's a callback). */
5772 SafeVMPtrQuiet ptrVM(this);
5773 if (!ptrVM.isOk())
5774 {
5775 /* The VM may be no more operational when this message arrives
5776 * (e.g. it may be Saving or Stopping or just PoweredOff) --
5777 * autoVMCaller.rc() will return a failure in this case. */
5778 LogFlowThisFunc(("Attach request ignored (mMachineState=%d).\n",
5779 mMachineState));
5780 return ptrVM.rc();
5781 }
5782
5783 if (aError != NULL)
5784 {
5785 /* notify callbacks about the error */
5786 alock.release();
5787 i_onUSBDeviceStateChange(aDevice, true /* aAttached */, aError);
5788 return S_OK;
5789 }
5790
5791 /* Don't proceed unless there's at least one USB hub. */
5792 if (!PDMR3UsbHasHub(ptrVM.rawUVM()))
5793 {
5794 LogFlowThisFunc(("Attach request ignored (no USB controller).\n"));
5795 return E_FAIL;
5796 }
5797
5798 alock.release();
5799 HRESULT rc = i_attachUSBDevice(aDevice, aMaskedIfs, aCaptureFilename);
5800 if (FAILED(rc))
5801 {
5802 /* take the current error info */
5803 com::ErrorInfoKeeper eik;
5804 /* the error must be a VirtualBoxErrorInfo instance */
5805 ComPtr<IVirtualBoxErrorInfo> pError = eik.takeError();
5806 Assert(!pError.isNull());
5807 if (!pError.isNull())
5808 {
5809 /* notify callbacks about the error */
5810 i_onUSBDeviceStateChange(aDevice, true /* aAttached */, pError);
5811 }
5812 }
5813
5814 return rc;
5815
5816#else /* !VBOX_WITH_USB */
5817 return E_FAIL;
5818#endif /* !VBOX_WITH_USB */
5819}
5820
5821/**
5822 * Called by IInternalSessionControl::OnUSBDeviceDetach() and locally by
5823 * processRemoteUSBDevices().
5824 *
5825 * @note Locks this object for writing.
5826 */
5827HRESULT Console::i_onUSBDeviceDetach(IN_BSTR aId,
5828 IVirtualBoxErrorInfo *aError)
5829{
5830#ifdef VBOX_WITH_USB
5831 Guid Uuid(aId);
5832 LogFlowThisFunc(("aId={%RTuuid} aError=%p\n", Uuid.raw(), aError));
5833
5834 AutoCaller autoCaller(this);
5835 AssertComRCReturnRC(autoCaller.rc());
5836
5837 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5838
5839 /* Find the device. */
5840 ComObjPtr<OUSBDevice> pUSBDevice;
5841 USBDeviceList::iterator it = mUSBDevices.begin();
5842 while (it != mUSBDevices.end())
5843 {
5844 LogFlowThisFunc(("it={%RTuuid}\n", (*it)->i_id().raw()));
5845 if ((*it)->i_id() == Uuid)
5846 {
5847 pUSBDevice = *it;
5848 break;
5849 }
5850 ++it;
5851 }
5852
5853
5854 if (pUSBDevice.isNull())
5855 {
5856 LogFlowThisFunc(("USB device not found.\n"));
5857
5858 /* The VM may be no more operational when this message arrives
5859 * (e.g. it may be Saving or Stopping or just PoweredOff). Use
5860 * AutoVMCaller to detect it -- AutoVMCaller::rc() will return a
5861 * failure in this case. */
5862
5863 AutoVMCallerQuiet autoVMCaller(this);
5864 if (FAILED(autoVMCaller.rc()))
5865 {
5866 LogFlowThisFunc(("Detach request ignored (mMachineState=%d).\n",
5867 mMachineState));
5868 return autoVMCaller.rc();
5869 }
5870
5871 /* the device must be in the list otherwise */
5872 AssertFailedReturn(E_FAIL);
5873 }
5874
5875 if (aError != NULL)
5876 {
5877 /* notify callback about an error */
5878 alock.release();
5879 i_onUSBDeviceStateChange(pUSBDevice, false /* aAttached */, aError);
5880 return S_OK;
5881 }
5882
5883 /* Remove the device from the collection, it is re-added below for failures */
5884 mUSBDevices.erase(it);
5885
5886 alock.release();
5887 HRESULT rc = i_detachUSBDevice(pUSBDevice);
5888 if (FAILED(rc))
5889 {
5890 /* Re-add the device to the collection */
5891 alock.acquire();
5892 mUSBDevices.push_back(pUSBDevice);
5893 alock.release();
5894 /* take the current error info */
5895 com::ErrorInfoKeeper eik;
5896 /* the error must be a VirtualBoxErrorInfo instance */
5897 ComPtr<IVirtualBoxErrorInfo> pError = eik.takeError();
5898 Assert(!pError.isNull());
5899 if (!pError.isNull())
5900 {
5901 /* notify callbacks about the error */
5902 i_onUSBDeviceStateChange(pUSBDevice, false /* aAttached */, pError);
5903 }
5904 }
5905
5906 return rc;
5907
5908#else /* !VBOX_WITH_USB */
5909 return E_FAIL;
5910#endif /* !VBOX_WITH_USB */
5911}
5912
5913/**
5914 * Called by IInternalSessionControl::OnBandwidthGroupChange().
5915 *
5916 * @note Locks this object for writing.
5917 */
5918HRESULT Console::i_onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
5919{
5920 LogFlowThisFunc(("\n"));
5921
5922 AutoCaller autoCaller(this);
5923 AssertComRCReturnRC(autoCaller.rc());
5924
5925 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5926
5927 HRESULT rc = S_OK;
5928
5929 /* don't trigger bandwidth group changes if the VM isn't running */
5930 SafeVMPtrQuiet ptrVM(this);
5931 if (ptrVM.isOk())
5932 {
5933 if ( mMachineState == MachineState_Running
5934 || mMachineState == MachineState_Teleporting
5935 || mMachineState == MachineState_LiveSnapshotting
5936 )
5937 {
5938 /* No need to call in the EMT thread. */
5939 Bstr strName;
5940 rc = aBandwidthGroup->COMGETTER(Name)(strName.asOutParam());
5941 if (SUCCEEDED(rc))
5942 {
5943 LONG64 cMax;
5944 rc = aBandwidthGroup->COMGETTER(MaxBytesPerSec)(&cMax);
5945 if (SUCCEEDED(rc))
5946 {
5947 BandwidthGroupType_T enmType;
5948 rc = aBandwidthGroup->COMGETTER(Type)(&enmType);
5949 if (SUCCEEDED(rc))
5950 {
5951 int vrc = VINF_SUCCESS;
5952 if (enmType == BandwidthGroupType_Disk)
5953 vrc = PDMR3AsyncCompletionBwMgrSetMaxForFile(ptrVM.rawUVM(), Utf8Str(strName).c_str(), (uint32_t)cMax);
5954#ifdef VBOX_WITH_NETSHAPER
5955 else if (enmType == BandwidthGroupType_Network)
5956 vrc = PDMR3NsBwGroupSetLimit(ptrVM.rawUVM(), Utf8Str(strName).c_str(), cMax);
5957 else
5958 rc = E_NOTIMPL;
5959#endif
5960 AssertRC(vrc);
5961 }
5962 }
5963 }
5964 }
5965 else
5966 rc = i_setInvalidMachineStateError();
5967 ptrVM.release();
5968 }
5969
5970 /* notify console callbacks on success */
5971 if (SUCCEEDED(rc))
5972 {
5973 alock.release();
5974 fireBandwidthGroupChangedEvent(mEventSource, aBandwidthGroup);
5975 }
5976
5977 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
5978 return rc;
5979}
5980
5981/**
5982 * Called by IInternalSessionControl::OnStorageDeviceChange().
5983 *
5984 * @note Locks this object for writing.
5985 */
5986HRESULT Console::i_onStorageDeviceChange(IMediumAttachment *aMediumAttachment, BOOL aRemove, BOOL aSilent)
5987{
5988 LogFlowThisFunc(("\n"));
5989
5990 AutoCaller autoCaller(this);
5991 AssertComRCReturnRC(autoCaller.rc());
5992
5993 HRESULT rc = S_OK;
5994
5995 /* don't trigger medium changes if the VM isn't running */
5996 SafeVMPtrQuiet ptrVM(this);
5997 if (ptrVM.isOk())
5998 {
5999 if (aRemove)
6000 rc = i_doStorageDeviceDetach(aMediumAttachment, ptrVM.rawUVM(), RT_BOOL(aSilent));
6001 else
6002 rc = i_doStorageDeviceAttach(aMediumAttachment, ptrVM.rawUVM(), RT_BOOL(aSilent));
6003 ptrVM.release();
6004 }
6005
6006 /* notify console callbacks on success */
6007 if (SUCCEEDED(rc))
6008 fireStorageDeviceChangedEvent(mEventSource, aMediumAttachment, aRemove, aSilent);
6009
6010 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
6011 return rc;
6012}
6013
6014HRESULT Console::i_onExtraDataChange(IN_BSTR aMachineId, IN_BSTR aKey, IN_BSTR aVal)
6015{
6016 LogFlowThisFunc(("\n"));
6017
6018 AutoCaller autoCaller(this);
6019 if (FAILED(autoCaller.rc()))
6020 return autoCaller.rc();
6021
6022 if (!aMachineId)
6023 return S_OK;
6024
6025 HRESULT hrc = S_OK;
6026 Bstr idMachine(aMachineId);
6027 if ( FAILED(hrc)
6028 || idMachine != i_getId())
6029 return hrc;
6030
6031 /* don't do anything if the VM isn't running */
6032 SafeVMPtrQuiet ptrVM(this);
6033 if (ptrVM.isOk())
6034 {
6035 Bstr strKey(aKey);
6036 Bstr strVal(aVal);
6037
6038 if (strKey == "VBoxInternal2/TurnResetIntoPowerOff")
6039 {
6040 int vrc = VMR3SetPowerOffInsteadOfReset(ptrVM.rawUVM(), strVal == "1");
6041 AssertRC(vrc);
6042 }
6043
6044 ptrVM.release();
6045 }
6046
6047 /* notify console callbacks on success */
6048 if (SUCCEEDED(hrc))
6049 fireExtraDataChangedEvent(mEventSource, aMachineId, aKey, aVal);
6050
6051 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
6052 return hrc;
6053}
6054
6055/**
6056 * @note Temporarily locks this object for writing.
6057 */
6058HRESULT Console::i_getGuestProperty(const Utf8Str &aName, Utf8Str *aValue, LONG64 *aTimestamp, Utf8Str *aFlags)
6059{
6060#ifndef VBOX_WITH_GUEST_PROPS
6061 ReturnComNotImplemented();
6062#else /* VBOX_WITH_GUEST_PROPS */
6063 if (!RT_VALID_PTR(aValue))
6064 return E_POINTER;
6065 if (aTimestamp != NULL && !RT_VALID_PTR(aTimestamp))
6066 return E_POINTER;
6067 if (aFlags != NULL && !RT_VALID_PTR(aFlags))
6068 return E_POINTER;
6069
6070 AutoCaller autoCaller(this);
6071 AssertComRCReturnRC(autoCaller.rc());
6072
6073 /* protect mpUVM (if not NULL) */
6074 SafeVMPtrQuiet ptrVM(this);
6075 if (FAILED(ptrVM.rc()))
6076 return ptrVM.rc();
6077
6078 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
6079 * ptrVM, so there is no need to hold a lock of this */
6080
6081 HRESULT rc = E_UNEXPECTED;
6082 try
6083 {
6084 VBOXHGCMSVCPARM parm[4];
6085 char szBuffer[GUEST_PROP_MAX_VALUE_LEN + GUEST_PROP_MAX_FLAGS_LEN];
6086
6087 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
6088 parm[0].u.pointer.addr = (void*)aName.c_str();
6089 parm[0].u.pointer.size = (uint32_t)aName.length() + 1; /* The + 1 is the null terminator */
6090
6091 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
6092 parm[1].u.pointer.addr = szBuffer;
6093 parm[1].u.pointer.size = sizeof(szBuffer);
6094
6095 parm[2].type = VBOX_HGCM_SVC_PARM_64BIT;
6096 parm[2].u.uint64 = 0;
6097
6098 parm[3].type = VBOX_HGCM_SVC_PARM_32BIT;
6099 parm[3].u.uint32 = 0;
6100
6101 int vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GUEST_PROP_FN_HOST_GET_PROP,
6102 4, &parm[0]);
6103 /* The returned string should never be able to be greater than our buffer */
6104 AssertLogRel(vrc != VERR_BUFFER_OVERFLOW);
6105 AssertLogRel(RT_FAILURE(vrc) || parm[2].type == VBOX_HGCM_SVC_PARM_64BIT);
6106 if (RT_SUCCESS(vrc))
6107 {
6108 *aValue = szBuffer;
6109
6110 if (aTimestamp)
6111 *aTimestamp = parm[2].u.uint64;
6112
6113 if (aFlags)
6114 *aFlags = &szBuffer[strlen(szBuffer) + 1];
6115
6116 rc = S_OK;
6117 }
6118 else if (vrc == VERR_NOT_FOUND)
6119 {
6120 *aValue = "";
6121 rc = S_OK;
6122 }
6123 else
6124 rc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("The VBoxGuestPropSvc service call failed with the error %Rrc"), vrc);
6125 }
6126 catch(std::bad_alloc & /*e*/)
6127 {
6128 rc = E_OUTOFMEMORY;
6129 }
6130
6131 return rc;
6132#endif /* VBOX_WITH_GUEST_PROPS */
6133}
6134
6135/**
6136 * @note Temporarily locks this object for writing.
6137 */
6138HRESULT Console::i_setGuestProperty(const Utf8Str &aName, const Utf8Str &aValue, const Utf8Str &aFlags)
6139{
6140#ifndef VBOX_WITH_GUEST_PROPS
6141 ReturnComNotImplemented();
6142#else /* VBOX_WITH_GUEST_PROPS */
6143
6144 AutoCaller autoCaller(this);
6145 AssertComRCReturnRC(autoCaller.rc());
6146
6147 /* protect mpUVM (if not NULL) */
6148 SafeVMPtrQuiet ptrVM(this);
6149 if (FAILED(ptrVM.rc()))
6150 return ptrVM.rc();
6151
6152 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
6153 * ptrVM, so there is no need to hold a lock of this */
6154
6155 VBOXHGCMSVCPARM parm[3];
6156
6157 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
6158 parm[0].u.pointer.addr = (void*)aName.c_str();
6159 parm[0].u.pointer.size = (uint32_t)aName.length() + 1; /* The + 1 is the null terminator */
6160
6161 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
6162 parm[1].u.pointer.addr = (void *)aValue.c_str();
6163 parm[1].u.pointer.size = (uint32_t)aValue.length() + 1; /* The + 1 is the null terminator */
6164
6165 int vrc;
6166 if (aFlags.isEmpty())
6167 {
6168 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GUEST_PROP_FN_HOST_SET_PROP_VALUE, 2, &parm[0]);
6169 }
6170 else
6171 {
6172 parm[2].type = VBOX_HGCM_SVC_PARM_PTR;
6173 parm[2].u.pointer.addr = (void*)aFlags.c_str();
6174 parm[2].u.pointer.size = (uint32_t)aFlags.length() + 1; /* The + 1 is the null terminator */
6175
6176 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GUEST_PROP_FN_HOST_SET_PROP, 3, &parm[0]);
6177 }
6178
6179 HRESULT hrc = S_OK;
6180 if (RT_FAILURE(vrc))
6181 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("The VBoxGuestPropSvc service call failed with the error %Rrc"), vrc);
6182 return hrc;
6183#endif /* VBOX_WITH_GUEST_PROPS */
6184}
6185
6186HRESULT Console::i_deleteGuestProperty(const Utf8Str &aName)
6187{
6188#ifndef VBOX_WITH_GUEST_PROPS
6189 ReturnComNotImplemented();
6190#else /* VBOX_WITH_GUEST_PROPS */
6191
6192 AutoCaller autoCaller(this);
6193 AssertComRCReturnRC(autoCaller.rc());
6194
6195 /* protect mpUVM (if not NULL) */
6196 SafeVMPtrQuiet ptrVM(this);
6197 if (FAILED(ptrVM.rc()))
6198 return ptrVM.rc();
6199
6200 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
6201 * ptrVM, so there is no need to hold a lock of this */
6202
6203 VBOXHGCMSVCPARM parm[1];
6204 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
6205 parm[0].u.pointer.addr = (void*)aName.c_str();
6206 parm[0].u.pointer.size = (uint32_t)aName.length() + 1; /* The + 1 is the null terminator */
6207
6208 int vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GUEST_PROP_FN_HOST_DEL_PROP, 1, &parm[0]);
6209
6210 HRESULT hrc = S_OK;
6211 if (RT_FAILURE(vrc))
6212 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("The VBoxGuestPropSvc service call failed with the error %Rrc"), vrc);
6213 return hrc;
6214#endif /* VBOX_WITH_GUEST_PROPS */
6215}
6216
6217/**
6218 * @note Temporarily locks this object for writing.
6219 */
6220HRESULT Console::i_enumerateGuestProperties(const Utf8Str &aPatterns,
6221 std::vector<Utf8Str> &aNames,
6222 std::vector<Utf8Str> &aValues,
6223 std::vector<LONG64> &aTimestamps,
6224 std::vector<Utf8Str> &aFlags)
6225{
6226#ifndef VBOX_WITH_GUEST_PROPS
6227 ReturnComNotImplemented();
6228#else /* VBOX_WITH_GUEST_PROPS */
6229
6230 AutoCaller autoCaller(this);
6231 AssertComRCReturnRC(autoCaller.rc());
6232
6233 /* protect mpUVM (if not NULL) */
6234 AutoVMCallerWeak autoVMCaller(this);
6235 if (FAILED(autoVMCaller.rc()))
6236 return autoVMCaller.rc();
6237
6238 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
6239 * autoVMCaller, so there is no need to hold a lock of this */
6240
6241 return i_doEnumerateGuestProperties(aPatterns, aNames, aValues, aTimestamps, aFlags);
6242#endif /* VBOX_WITH_GUEST_PROPS */
6243}
6244
6245
6246/*
6247 * Internal: helper function for connecting progress reporting
6248 */
6249static DECLCALLBACK(int) onlineMergeMediumProgress(void *pvUser, unsigned uPercentage)
6250{
6251 HRESULT rc = S_OK;
6252 IProgress *pProgress = static_cast<IProgress *>(pvUser);
6253 if (pProgress)
6254 {
6255 ComPtr<IInternalProgressControl> pProgressControl(pProgress);
6256 AssertReturn(!!pProgressControl, VERR_INVALID_PARAMETER);
6257 rc = pProgressControl->SetCurrentOperationProgress(uPercentage);
6258 }
6259 return SUCCEEDED(rc) ? VINF_SUCCESS : VERR_GENERAL_FAILURE;
6260}
6261
6262/**
6263 * @note Temporarily locks this object for writing. bird: And/or reading?
6264 */
6265HRESULT Console::i_onlineMergeMedium(IMediumAttachment *aMediumAttachment,
6266 ULONG aSourceIdx, ULONG aTargetIdx,
6267 IProgress *aProgress)
6268{
6269 AutoCaller autoCaller(this);
6270 AssertComRCReturnRC(autoCaller.rc());
6271
6272 HRESULT rc = S_OK;
6273 int vrc = VINF_SUCCESS;
6274
6275 /* Get the VM - must be done before the read-locking. */
6276 SafeVMPtr ptrVM(this);
6277 if (!ptrVM.isOk())
6278 return ptrVM.rc();
6279
6280 /* We will need to release the lock before doing the actual merge */
6281 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6282
6283 /* paranoia - we don't want merges to happen while teleporting etc. */
6284 switch (mMachineState)
6285 {
6286 case MachineState_DeletingSnapshotOnline:
6287 case MachineState_DeletingSnapshotPaused:
6288 break;
6289
6290 default:
6291 return i_setInvalidMachineStateError();
6292 }
6293
6294 /** @todo AssertComRC -> AssertComRCReturn! Could potentially end up
6295 * using uninitialized variables here. */
6296 BOOL fBuiltinIOCache;
6297 rc = mMachine->COMGETTER(IOCacheEnabled)(&fBuiltinIOCache);
6298 AssertComRC(rc);
6299 SafeIfaceArray<IStorageController> ctrls;
6300 rc = mMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));
6301 AssertComRC(rc);
6302 LONG lDev;
6303 rc = aMediumAttachment->COMGETTER(Device)(&lDev);
6304 AssertComRC(rc);
6305 LONG lPort;
6306 rc = aMediumAttachment->COMGETTER(Port)(&lPort);
6307 AssertComRC(rc);
6308 IMedium *pMedium;
6309 rc = aMediumAttachment->COMGETTER(Medium)(&pMedium);
6310 AssertComRC(rc);
6311 Bstr mediumLocation;
6312 if (pMedium)
6313 {
6314 rc = pMedium->COMGETTER(Location)(mediumLocation.asOutParam());
6315 AssertComRC(rc);
6316 }
6317
6318 Bstr attCtrlName;
6319 rc = aMediumAttachment->COMGETTER(Controller)(attCtrlName.asOutParam());
6320 AssertComRC(rc);
6321 ComPtr<IStorageController> pStorageController;
6322 for (size_t i = 0; i < ctrls.size(); ++i)
6323 {
6324 Bstr ctrlName;
6325 rc = ctrls[i]->COMGETTER(Name)(ctrlName.asOutParam());
6326 AssertComRC(rc);
6327 if (attCtrlName == ctrlName)
6328 {
6329 pStorageController = ctrls[i];
6330 break;
6331 }
6332 }
6333 if (pStorageController.isNull())
6334 return setError(E_FAIL,
6335 tr("Could not find storage controller '%ls'"),
6336 attCtrlName.raw());
6337
6338 StorageControllerType_T enmCtrlType;
6339 rc = pStorageController->COMGETTER(ControllerType)(&enmCtrlType);
6340 AssertComRC(rc);
6341 const char *pcszDevice = i_storageControllerTypeToStr(enmCtrlType);
6342
6343 StorageBus_T enmBus;
6344 rc = pStorageController->COMGETTER(Bus)(&enmBus);
6345 AssertComRC(rc);
6346 ULONG uInstance;
6347 rc = pStorageController->COMGETTER(Instance)(&uInstance);
6348 AssertComRC(rc);
6349 BOOL fUseHostIOCache;
6350 rc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
6351 AssertComRC(rc);
6352
6353 unsigned uLUN;
6354 rc = Console::i_storageBusPortDeviceToLun(enmBus, lPort, lDev, uLUN);
6355 AssertComRCReturnRC(rc);
6356
6357 Assert(mMachineState == MachineState_DeletingSnapshotOnline);
6358
6359 /* Pause the VM, as it might have pending IO on this drive */
6360 bool fResume = false;
6361 rc = i_suspendBeforeConfigChange(ptrVM.rawUVM(), &alock, &fResume);
6362 if (FAILED(rc))
6363 return rc;
6364
6365 bool fInsertDiskIntegrityDrv = false;
6366 Bstr strDiskIntegrityFlag;
6367 rc = mMachine->GetExtraData(Bstr("VBoxInternal2/EnableDiskIntegrityDriver").raw(),
6368 strDiskIntegrityFlag.asOutParam());
6369 if ( rc == S_OK
6370 && strDiskIntegrityFlag == "1")
6371 fInsertDiskIntegrityDrv = true;
6372
6373 alock.release();
6374 vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY,
6375 (PFNRT)i_reconfigureMediumAttachment, 14,
6376 this, ptrVM.rawUVM(), pcszDevice, uInstance, enmBus, fUseHostIOCache,
6377 fBuiltinIOCache, fInsertDiskIntegrityDrv, true /* fSetupMerge */,
6378 aSourceIdx, aTargetIdx, aMediumAttachment, mMachineState, &rc);
6379 /* error handling is after resuming the VM */
6380
6381 if (fResume)
6382 i_resumeAfterConfigChange(ptrVM.rawUVM());
6383
6384 if (RT_FAILURE(vrc))
6385 return setErrorBoth(E_FAIL, vrc, tr("%Rrc"), vrc);
6386 if (FAILED(rc))
6387 return rc;
6388
6389 PPDMIBASE pIBase = NULL;
6390 PPDMIMEDIA pIMedium = NULL;
6391 vrc = PDMR3QueryDriverOnLun(ptrVM.rawUVM(), pcszDevice, uInstance, uLUN, "VD", &pIBase);
6392 if (RT_SUCCESS(vrc))
6393 {
6394 if (pIBase)
6395 {
6396 pIMedium = (PPDMIMEDIA)pIBase->pfnQueryInterface(pIBase, PDMIMEDIA_IID);
6397 if (!pIMedium)
6398 return setError(E_FAIL, tr("could not query medium interface of controller"));
6399 }
6400 else
6401 return setError(E_FAIL, tr("could not query base interface of controller"));
6402 }
6403
6404 /* Finally trigger the merge. */
6405 vrc = pIMedium->pfnMerge(pIMedium, onlineMergeMediumProgress, aProgress);
6406 if (RT_FAILURE(vrc))
6407 return setErrorBoth(E_FAIL, vrc, tr("Failed to perform an online medium merge (%Rrc)"), vrc);
6408
6409 alock.acquire();
6410 /* Pause the VM, as it might have pending IO on this drive */
6411 rc = i_suspendBeforeConfigChange(ptrVM.rawUVM(), &alock, &fResume);
6412 if (FAILED(rc))
6413 return rc;
6414 alock.release();
6415
6416 /* Update medium chain and state now, so that the VM can continue. */
6417 rc = mControl->FinishOnlineMergeMedium();
6418
6419 vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY,
6420 (PFNRT)i_reconfigureMediumAttachment, 14,
6421 this, ptrVM.rawUVM(), pcszDevice, uInstance, enmBus, fUseHostIOCache,
6422 fBuiltinIOCache, fInsertDiskIntegrityDrv, false /* fSetupMerge */,
6423 0 /* uMergeSource */, 0 /* uMergeTarget */, aMediumAttachment,
6424 mMachineState, &rc);
6425 /* error handling is after resuming the VM */
6426
6427 if (fResume)
6428 i_resumeAfterConfigChange(ptrVM.rawUVM());
6429
6430 if (RT_FAILURE(vrc))
6431 return setErrorBoth(E_FAIL, vrc, tr("%Rrc"), vrc);
6432 if (FAILED(rc))
6433 return rc;
6434
6435 return rc;
6436}
6437
6438HRESULT Console::i_reconfigureMediumAttachments(const std::vector<ComPtr<IMediumAttachment> > &aAttachments)
6439{
6440 HRESULT rc = S_OK;
6441
6442 AutoCaller autoCaller(this);
6443 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6444
6445 /* get the VM handle. */
6446 SafeVMPtr ptrVM(this);
6447 if (!ptrVM.isOk())
6448 return ptrVM.rc();
6449
6450 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6451
6452 for (size_t i = 0; i < aAttachments.size(); ++i)
6453 {
6454 ComPtr<IStorageController> pStorageController;
6455 Bstr controllerName;
6456 ULONG lInstance;
6457 StorageControllerType_T enmController;
6458 StorageBus_T enmBus;
6459 BOOL fUseHostIOCache;
6460
6461 /*
6462 * We could pass the objects, but then EMT would have to do lots of
6463 * IPC (to VBoxSVC) which takes a significant amount of time.
6464 * Better query needed values here and pass them.
6465 */
6466 rc = aAttachments[i]->COMGETTER(Controller)(controllerName.asOutParam());
6467 if (FAILED(rc))
6468 throw rc;
6469
6470 rc = mMachine->GetStorageControllerByName(controllerName.raw(),
6471 pStorageController.asOutParam());
6472 if (FAILED(rc))
6473 throw rc;
6474
6475 rc = pStorageController->COMGETTER(ControllerType)(&enmController);
6476 if (FAILED(rc))
6477 throw rc;
6478 rc = pStorageController->COMGETTER(Instance)(&lInstance);
6479 if (FAILED(rc))
6480 throw rc;
6481 rc = pStorageController->COMGETTER(Bus)(&enmBus);
6482 if (FAILED(rc))
6483 throw rc;
6484 rc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
6485 if (FAILED(rc))
6486 throw rc;
6487
6488 const char *pcszDevice = i_storageControllerTypeToStr(enmController);
6489
6490 BOOL fBuiltinIOCache;
6491 rc = mMachine->COMGETTER(IOCacheEnabled)(&fBuiltinIOCache);
6492 if (FAILED(rc))
6493 throw rc;
6494
6495 bool fInsertDiskIntegrityDrv = false;
6496 Bstr strDiskIntegrityFlag;
6497 rc = mMachine->GetExtraData(Bstr("VBoxInternal2/EnableDiskIntegrityDriver").raw(),
6498 strDiskIntegrityFlag.asOutParam());
6499 if ( rc == S_OK
6500 && strDiskIntegrityFlag == "1")
6501 fInsertDiskIntegrityDrv = true;
6502
6503 alock.release();
6504
6505 IMediumAttachment *pAttachment = aAttachments[i];
6506 int vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY,
6507 (PFNRT)i_reconfigureMediumAttachment, 14,
6508 this, ptrVM.rawUVM(), pcszDevice, lInstance, enmBus, fUseHostIOCache,
6509 fBuiltinIOCache, fInsertDiskIntegrityDrv,
6510 false /* fSetupMerge */, 0 /* uMergeSource */, 0 /* uMergeTarget */,
6511 pAttachment, mMachineState, &rc);
6512 if (RT_FAILURE(vrc))
6513 throw setErrorBoth(E_FAIL, vrc, tr("%Rrc"), vrc);
6514 if (FAILED(rc))
6515 throw rc;
6516
6517 alock.acquire();
6518 }
6519
6520 return rc;
6521}
6522
6523
6524/**
6525 * Load an HGCM service.
6526 *
6527 * Main purpose of this method is to allow extension packs to load HGCM
6528 * service modules, which they can't, because the HGCM functionality lives
6529 * in module VBoxC (and ConsoleImpl.cpp is part of it and thus can call it).
6530 * Extension modules must not link directly against VBoxC, (XP)COM is
6531 * handling this.
6532 */
6533int Console::i_hgcmLoadService(const char *pszServiceLibrary, const char *pszServiceName)
6534{
6535 /* Everyone seems to delegate all HGCM calls to VMMDev, so stick to this
6536 * convention. Adds one level of indirection for no obvious reason. */
6537 AssertPtrReturn(m_pVMMDev, VERR_INVALID_STATE);
6538 return m_pVMMDev->hgcmLoadService(pszServiceLibrary, pszServiceName);
6539}
6540
6541/**
6542 * Merely passes the call to Guest::enableVMMStatistics().
6543 */
6544void Console::i_enableVMMStatistics(BOOL aEnable)
6545{
6546 if (mGuest)
6547 mGuest->i_enableVMMStatistics(aEnable);
6548}
6549
6550/**
6551 * Worker for Console::Pause and internal entry point for pausing a VM for
6552 * a specific reason.
6553 */
6554HRESULT Console::i_pause(Reason_T aReason)
6555{
6556 LogFlowThisFuncEnter();
6557
6558 AutoCaller autoCaller(this);
6559 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6560
6561 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6562
6563 switch (mMachineState)
6564 {
6565 case MachineState_Running:
6566 case MachineState_Teleporting:
6567 case MachineState_LiveSnapshotting:
6568 break;
6569
6570 case MachineState_Paused:
6571 case MachineState_TeleportingPausedVM:
6572 case MachineState_OnlineSnapshotting:
6573 /* Remove any keys which are supposed to be removed on a suspend. */
6574 if ( aReason == Reason_HostSuspend
6575 || aReason == Reason_HostBatteryLow)
6576 {
6577 i_removeSecretKeysOnSuspend();
6578 return S_OK;
6579 }
6580 return setError(VBOX_E_INVALID_VM_STATE, tr("Already paused"));
6581
6582 default:
6583 return i_setInvalidMachineStateError();
6584 }
6585
6586 /* get the VM handle. */
6587 SafeVMPtr ptrVM(this);
6588 if (!ptrVM.isOk())
6589 return ptrVM.rc();
6590
6591 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
6592 alock.release();
6593
6594 LogFlowThisFunc(("Sending PAUSE request...\n"));
6595 if (aReason != Reason_Unspecified)
6596 LogRel(("Pausing VM execution, reason '%s'\n", Global::stringifyReason(aReason)));
6597
6598 /** @todo r=klaus make use of aReason */
6599 VMSUSPENDREASON enmReason = VMSUSPENDREASON_USER;
6600 if (aReason == Reason_HostSuspend)
6601 enmReason = VMSUSPENDREASON_HOST_SUSPEND;
6602 else if (aReason == Reason_HostBatteryLow)
6603 enmReason = VMSUSPENDREASON_HOST_BATTERY_LOW;
6604 int vrc = VMR3Suspend(ptrVM.rawUVM(), enmReason);
6605
6606 HRESULT hrc = S_OK;
6607 if (RT_FAILURE(vrc))
6608 hrc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not suspend the machine execution (%Rrc)"), vrc);
6609 else if ( aReason == Reason_HostSuspend
6610 || aReason == Reason_HostBatteryLow)
6611 {
6612 alock.acquire();
6613 i_removeSecretKeysOnSuspend();
6614 }
6615
6616 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
6617 LogFlowThisFuncLeave();
6618 return hrc;
6619}
6620
6621/**
6622 * Worker for Console::Resume and internal entry point for resuming a VM for
6623 * a specific reason.
6624 */
6625HRESULT Console::i_resume(Reason_T aReason, AutoWriteLock &alock)
6626{
6627 LogFlowThisFuncEnter();
6628
6629 AutoCaller autoCaller(this);
6630 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6631
6632 /* get the VM handle. */
6633 SafeVMPtr ptrVM(this);
6634 if (!ptrVM.isOk())
6635 return ptrVM.rc();
6636
6637 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
6638 alock.release();
6639
6640 LogFlowThisFunc(("Sending RESUME request...\n"));
6641 if (aReason != Reason_Unspecified)
6642 LogRel(("Resuming VM execution, reason '%s'\n", Global::stringifyReason(aReason)));
6643
6644 int vrc;
6645 if (VMR3GetStateU(ptrVM.rawUVM()) == VMSTATE_CREATED)
6646 {
6647#ifdef VBOX_WITH_EXTPACK
6648 vrc = mptrExtPackManager->i_callAllVmPowerOnHooks(this, VMR3GetVM(ptrVM.rawUVM()));
6649#else
6650 vrc = VINF_SUCCESS;
6651#endif
6652 if (RT_SUCCESS(vrc))
6653 vrc = VMR3PowerOn(ptrVM.rawUVM()); /* (PowerUpPaused) */
6654 }
6655 else
6656 {
6657 VMRESUMEREASON enmReason;
6658 if (aReason == Reason_HostResume)
6659 {
6660 /*
6661 * Host resume may be called multiple times successively. We don't want to VMR3Resume->vmR3Resume->vmR3TrySetState()
6662 * to assert on us, hence check for the VM state here and bail if it's not in the 'suspended' state.
6663 * See @bugref{3495}.
6664 *
6665 * Also, don't resume the VM through a host-resume unless it was suspended due to a host-suspend.
6666 */
6667 if (VMR3GetStateU(ptrVM.rawUVM()) != VMSTATE_SUSPENDED)
6668 {
6669 LogRel(("Ignoring VM resume request, VM is currently not suspended\n"));
6670 return S_OK;
6671 }
6672 if (VMR3GetSuspendReason(ptrVM.rawUVM()) != VMSUSPENDREASON_HOST_SUSPEND)
6673 {
6674 LogRel(("Ignoring VM resume request, VM was not suspended due to host-suspend\n"));
6675 return S_OK;
6676 }
6677
6678 enmReason = VMRESUMEREASON_HOST_RESUME;
6679 }
6680 else
6681 {
6682 /*
6683 * Any other reason to resume the VM throws an error when the VM was suspended due to a host suspend.
6684 * See @bugref{7836}.
6685 */
6686 if ( VMR3GetStateU(ptrVM.rawUVM()) == VMSTATE_SUSPENDED
6687 && VMR3GetSuspendReason(ptrVM.rawUVM()) == VMSUSPENDREASON_HOST_SUSPEND)
6688 return setError(VBOX_E_INVALID_VM_STATE, tr("VM is paused due to host power management"));
6689
6690 enmReason = aReason == Reason_Snapshot ? VMRESUMEREASON_STATE_SAVED : VMRESUMEREASON_USER;
6691 }
6692
6693 // for snapshots: no state change callback, VBoxSVC does everything
6694 if (aReason == Reason_Snapshot)
6695 mVMStateChangeCallbackDisabled = true;
6696 vrc = VMR3Resume(ptrVM.rawUVM(), enmReason);
6697 if (aReason == Reason_Snapshot)
6698 mVMStateChangeCallbackDisabled = false;
6699 }
6700
6701 HRESULT rc = RT_SUCCESS(vrc) ? S_OK
6702 : setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not resume the machine execution (%Rrc)"), vrc);
6703
6704 LogFlowThisFunc(("rc=%Rhrc\n", rc));
6705 LogFlowThisFuncLeave();
6706 return rc;
6707}
6708
6709/**
6710 * Internal entry point for saving state of a VM for a specific reason. This
6711 * method is completely synchronous.
6712 *
6713 * The machine state is already set appropriately. It is only changed when
6714 * saving state actually paused the VM (happens with live snapshots and
6715 * teleportation), and in this case reflects the now paused variant.
6716 *
6717 * @note Locks this object for writing.
6718 */
6719HRESULT Console::i_saveState(Reason_T aReason, const ComPtr<IProgress> &aProgress,
6720 const ComPtr<ISnapshot> &aSnapshot,
6721 const Utf8Str &aStateFilePath, bool aPauseVM, bool &aLeftPaused)
6722{
6723 LogFlowThisFuncEnter();
6724 aLeftPaused = false;
6725
6726 AssertReturn(!aProgress.isNull(), E_INVALIDARG);
6727 AssertReturn(!aStateFilePath.isEmpty(), E_INVALIDARG);
6728 Assert(aSnapshot.isNull() || aReason == Reason_Snapshot);
6729
6730 AutoCaller autoCaller(this);
6731 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6732
6733 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6734
6735 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
6736 if ( mMachineState != MachineState_Saving
6737 && mMachineState != MachineState_LiveSnapshotting
6738 && mMachineState != MachineState_OnlineSnapshotting
6739 && mMachineState != MachineState_Teleporting
6740 && mMachineState != MachineState_TeleportingPausedVM)
6741 {
6742 return setError(VBOX_E_INVALID_VM_STATE,
6743 tr("Cannot save the execution state as the machine is not running or paused (machine state: %s)"),
6744 Global::stringifyMachineState(mMachineState));
6745 }
6746 bool fContinueAfterwards = mMachineState != MachineState_Saving;
6747
6748 Bstr strDisableSaveState;
6749 mMachine->GetExtraData(Bstr("VBoxInternal2/DisableSaveState").raw(), strDisableSaveState.asOutParam());
6750 if (strDisableSaveState == "1")
6751 return setError(VBOX_E_VM_ERROR,
6752 tr("Saving the execution state is disabled for this VM"));
6753
6754 if (aReason != Reason_Unspecified)
6755 LogRel(("Saving state of VM, reason '%s'\n", Global::stringifyReason(aReason)));
6756
6757 /* ensure the directory for the saved state file exists */
6758 {
6759 Utf8Str dir = aStateFilePath;
6760 dir.stripFilename();
6761 if (!RTDirExists(dir.c_str()))
6762 {
6763 int vrc = RTDirCreateFullPath(dir.c_str(), 0700);
6764 if (RT_FAILURE(vrc))
6765 return setErrorBoth(VBOX_E_FILE_ERROR, vrc, tr("Could not create a directory '%s' to save the state to (%Rrc)"),
6766 dir.c_str(), vrc);
6767 }
6768 }
6769
6770 /* Get the VM handle early, we need it in several places. */
6771 SafeVMPtr ptrVM(this);
6772 if (!ptrVM.isOk())
6773 return ptrVM.rc();
6774
6775 bool fPaused = false;
6776 if (aPauseVM)
6777 {
6778 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
6779 alock.release();
6780 VMSUSPENDREASON enmReason = VMSUSPENDREASON_USER;
6781 if (aReason == Reason_HostSuspend)
6782 enmReason = VMSUSPENDREASON_HOST_SUSPEND;
6783 else if (aReason == Reason_HostBatteryLow)
6784 enmReason = VMSUSPENDREASON_HOST_BATTERY_LOW;
6785 int vrc = VMR3Suspend(ptrVM.rawUVM(), enmReason);
6786 alock.acquire();
6787
6788 if (RT_FAILURE(vrc))
6789 return setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not suspend the machine execution (%Rrc)"), vrc);
6790 fPaused = true;
6791 }
6792
6793 LogFlowFunc(("Saving the state to '%s'...\n", aStateFilePath.c_str()));
6794
6795 mpVmm2UserMethods->pISnapshot = aSnapshot;
6796 mptrCancelableProgress = aProgress;
6797 alock.release();
6798 int vrc = VMR3Save(ptrVM.rawUVM(),
6799 aStateFilePath.c_str(),
6800 fContinueAfterwards,
6801 Console::i_stateProgressCallback,
6802 static_cast<IProgress *>(aProgress),
6803 &aLeftPaused);
6804 alock.acquire();
6805 mpVmm2UserMethods->pISnapshot = NULL;
6806 mptrCancelableProgress.setNull();
6807 if (RT_FAILURE(vrc))
6808 {
6809 if (fPaused)
6810 {
6811 alock.release();
6812 VMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_STATE_RESTORED);
6813 alock.acquire();
6814 }
6815 return setErrorBoth(E_FAIL, vrc, tr("Failed to save the machine state to '%s' (%Rrc)"), aStateFilePath.c_str(), vrc);
6816 }
6817 Assert(fContinueAfterwards || !aLeftPaused);
6818
6819 if (!fContinueAfterwards)
6820 {
6821 /*
6822 * The machine has been successfully saved, so power it down
6823 * (vmstateChangeCallback() will set state to Saved on success).
6824 * Note: we release the VM caller, otherwise it will deadlock.
6825 */
6826 ptrVM.release();
6827 alock.release();
6828 autoCaller.release();
6829 HRESULT rc = i_powerDown();
6830 AssertComRC(rc);
6831 autoCaller.add();
6832 alock.acquire();
6833 }
6834 else
6835 {
6836 if (fPaused)
6837 aLeftPaused = true;
6838 }
6839
6840 LogFlowFuncLeave();
6841 return S_OK;
6842}
6843
6844/**
6845 * Internal entry point for cancelling a VM save state.
6846 *
6847 * @note Locks this object for writing.
6848 */
6849HRESULT Console::i_cancelSaveState()
6850{
6851 LogFlowThisFuncEnter();
6852
6853 AutoCaller autoCaller(this);
6854 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6855
6856 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6857
6858 /* Get the VM handle. */
6859 SafeVMPtr ptrVM(this);
6860 if (!ptrVM.isOk())
6861 return ptrVM.rc();
6862
6863 SSMR3Cancel(ptrVM.rawUVM());
6864
6865 LogFlowFuncLeave();
6866 return S_OK;
6867}
6868
6869#ifdef VBOX_WITH_AUDIO_RECORDING
6870/**
6871 * Sends audio (frame) data to the display's video capturing routines.
6872 *
6873 * @returns HRESULT
6874 * @param pvData Audio data to send.
6875 * @param cbData Size (in bytes) of audio data to send.
6876 * @param uTimestampMs Timestamp (in ms) of audio data.
6877 */
6878HRESULT Console::i_recordingSendAudio(const void *pvData, size_t cbData, uint64_t uTimestampMs)
6879{
6880 if (!Recording.mpCtx)
6881 return S_OK;
6882
6883 if ( Recording.mpCtx->IsStarted()
6884 && Recording.mpCtx->IsFeatureEnabled(RecordingFeature_Audio))
6885 {
6886 return Recording.mpCtx->SendAudioFrame(pvData, cbData, uTimestampMs);
6887 }
6888
6889 return S_OK;
6890}
6891#endif /* VBOX_WITH_AUDIO_RECORDING */
6892
6893#ifdef VBOX_WITH_RECORDING
6894int Console::i_recordingGetSettings(settings::RecordingSettings &Settings)
6895{
6896 Assert(mMachine.isNotNull());
6897
6898 Settings.applyDefaults();
6899
6900 ComPtr<IRecordingSettings> pRecordSettings;
6901 HRESULT hrc = mMachine->COMGETTER(RecordingSettings)(pRecordSettings.asOutParam());
6902 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
6903
6904 BOOL fTemp;
6905 hrc = pRecordSettings->COMGETTER(Enabled)(&fTemp);
6906 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
6907 Settings.fEnabled = RT_BOOL(fTemp);
6908
6909 SafeIfaceArray<IRecordingScreenSettings> paRecordingScreens;
6910 hrc = pRecordSettings->COMGETTER(Screens)(ComSafeArrayAsOutParam(paRecordingScreens));
6911 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
6912
6913 for (unsigned long i = 0; i < (unsigned long)paRecordingScreens.size(); ++i)
6914 {
6915 settings::RecordingScreenSettings RecordScreenSettings;
6916 ComPtr<IRecordingScreenSettings> pRecordScreenSettings = paRecordingScreens[i];
6917
6918 hrc = pRecordScreenSettings->COMGETTER(Enabled)(&fTemp);
6919 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
6920 RecordScreenSettings.fEnabled = RT_BOOL(fTemp);
6921 hrc = pRecordScreenSettings->COMGETTER(MaxTime)((ULONG *)&RecordScreenSettings.ulMaxTimeS);
6922 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
6923 hrc = pRecordScreenSettings->COMGETTER(MaxFileSize)((ULONG *)&RecordScreenSettings.File.ulMaxSizeMB);
6924 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
6925 Bstr bstrTemp;
6926 hrc = pRecordScreenSettings->COMGETTER(FileName)(bstrTemp.asOutParam());
6927 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
6928 RecordScreenSettings.File.strName = bstrTemp;
6929 hrc = pRecordScreenSettings->COMGETTER(Options)(bstrTemp.asOutParam());
6930 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
6931 RecordScreenSettings.strOptions = bstrTemp;
6932 hrc = pRecordScreenSettings->COMGETTER(VideoWidth)((ULONG *)&RecordScreenSettings.Video.ulWidth);
6933 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
6934 hrc = pRecordScreenSettings->COMGETTER(VideoHeight)((ULONG *)&RecordScreenSettings.Video.ulHeight);
6935 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
6936 hrc = pRecordScreenSettings->COMGETTER(VideoRate)((ULONG *)&RecordScreenSettings.Video.ulRate);
6937 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
6938 hrc = pRecordScreenSettings->COMGETTER(VideoFPS)((ULONG *)&RecordScreenSettings.Video.ulFPS);
6939 AssertComRCReturn(hrc, VERR_INVALID_PARAMETER);
6940
6941 Settings.mapScreens[i] = RecordScreenSettings;
6942 }
6943
6944 Assert(Settings.mapScreens.size() == paRecordingScreens.size());
6945
6946 return VINF_SUCCESS;
6947}
6948
6949/**
6950 * Creates the recording context.
6951 *
6952 * @returns IPRT status code.
6953 */
6954int Console::i_recordingCreate(void)
6955{
6956 AssertReturn(Recording.mpCtx == NULL, VERR_WRONG_ORDER);
6957
6958 int rc = VINF_SUCCESS;
6959
6960 try
6961 {
6962 Recording.mpCtx = new RecordingContext(this);
6963 }
6964 catch (std::bad_alloc &)
6965 {
6966 return VERR_NO_MEMORY;
6967 }
6968 catch (int &rc2)
6969 {
6970 return rc2;
6971 }
6972
6973 settings::RecordingSettings Settings;
6974 rc = i_recordingGetSettings(Settings);
6975 if (RT_SUCCESS(rc))
6976 {
6977 AssertPtr(Recording.mpCtx);
6978 rc = Recording.mpCtx->Create(Settings);
6979 }
6980
6981 LogFlowFuncLeaveRC(rc);
6982 return rc;
6983}
6984
6985/**
6986 * Destroys the recording context.
6987 */
6988void Console::i_recordingDestroy(void)
6989{
6990 if (Recording.mpCtx)
6991 {
6992 delete Recording.mpCtx;
6993 Recording.mpCtx = NULL;
6994 }
6995
6996 LogFlowThisFuncLeave();
6997}
6998
6999/**
7000 * Starts capturing. Does nothing if capturing is already active.
7001 *
7002 * @returns IPRT status code.
7003 */
7004int Console::i_recordingStart(void)
7005{
7006 AssertPtrReturn(Recording.mpCtx, VERR_WRONG_ORDER);
7007
7008 if (Recording.mpCtx->IsStarted())
7009 return VINF_SUCCESS;
7010
7011 LogRel(("Recording: Starting ...\n"));
7012
7013 int rc = Recording.mpCtx->Start();
7014 if (RT_SUCCESS(rc))
7015 {
7016 for (unsigned uScreen = 0; uScreen < Recording.mpCtx->GetStreamCount(); uScreen++)
7017 mDisplay->i_recordingScreenChanged(uScreen);
7018 }
7019
7020 if (RT_FAILURE(rc))
7021 LogRel(("Recording: Failed to start video recording (%Rrc)\n", rc));
7022
7023 LogFlowFuncLeaveRC(rc);
7024 return rc;
7025}
7026
7027/**
7028 * Stops capturing. Does nothing if capturing is not active.
7029 */
7030int Console::i_recordingStop(void)
7031{
7032 if ( !Recording.mpCtx
7033 || !Recording.mpCtx->IsStarted())
7034 return VINF_SUCCESS;
7035
7036 LogRel(("Recording: Stopping ...\n"));
7037
7038 int rc = Recording.mpCtx->Stop();
7039 if (RT_SUCCESS(rc))
7040 {
7041 const size_t cStreams = Recording.mpCtx->GetStreamCount();
7042 for (unsigned uScreen = 0; uScreen < cStreams; ++uScreen)
7043 mDisplay->i_recordingScreenChanged(uScreen);
7044
7045 ComPtr<IRecordingSettings> pRecordSettings;
7046 HRESULT hrc = mMachine->COMGETTER(RecordingSettings)(pRecordSettings.asOutParam());
7047 ComAssertComRC(hrc);
7048 hrc = pRecordSettings->COMSETTER(Enabled)(false);
7049 ComAssertComRC(hrc);
7050
7051 LogRel(("Recording: Stopped\n"));
7052 }
7053 else
7054 LogRel(("Recording: Failed to stop video recording (%Rrc)\n", rc));
7055
7056 LogFlowFuncLeaveRC(rc);
7057 return rc;
7058}
7059#endif /* VBOX_WITH_RECORDING */
7060
7061/**
7062 * Gets called by Session::UpdateMachineState()
7063 * (IInternalSessionControl::updateMachineState()).
7064 *
7065 * Must be called only in certain cases (see the implementation).
7066 *
7067 * @note Locks this object for writing.
7068 */
7069HRESULT Console::i_updateMachineState(MachineState_T aMachineState)
7070{
7071 AutoCaller autoCaller(this);
7072 AssertComRCReturnRC(autoCaller.rc());
7073
7074 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7075
7076 AssertReturn( mMachineState == MachineState_Saving
7077 || mMachineState == MachineState_OnlineSnapshotting
7078 || mMachineState == MachineState_LiveSnapshotting
7079 || mMachineState == MachineState_DeletingSnapshotOnline
7080 || mMachineState == MachineState_DeletingSnapshotPaused
7081 || aMachineState == MachineState_Saving
7082 || aMachineState == MachineState_OnlineSnapshotting
7083 || aMachineState == MachineState_LiveSnapshotting
7084 || aMachineState == MachineState_DeletingSnapshotOnline
7085 || aMachineState == MachineState_DeletingSnapshotPaused
7086 , E_FAIL);
7087
7088 return i_setMachineStateLocally(aMachineState);
7089}
7090
7091/**
7092 * Gets called by Session::COMGETTER(NominalState)()
7093 * (IInternalSessionControl::getNominalState()).
7094 *
7095 * @note Locks this object for reading.
7096 */
7097HRESULT Console::i_getNominalState(MachineState_T &aNominalState)
7098{
7099 LogFlowThisFuncEnter();
7100
7101 AutoCaller autoCaller(this);
7102 AssertComRCReturnRC(autoCaller.rc());
7103
7104 /* Get the VM handle. */
7105 SafeVMPtr ptrVM(this);
7106 if (!ptrVM.isOk())
7107 return ptrVM.rc();
7108
7109 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7110
7111 MachineState_T enmMachineState = MachineState_Null;
7112 VMSTATE enmVMState = VMR3GetStateU(ptrVM.rawUVM());
7113 switch (enmVMState)
7114 {
7115 case VMSTATE_CREATING:
7116 case VMSTATE_CREATED:
7117 case VMSTATE_POWERING_ON:
7118 enmMachineState = MachineState_Starting;
7119 break;
7120 case VMSTATE_LOADING:
7121 enmMachineState = MachineState_Restoring;
7122 break;
7123 case VMSTATE_RESUMING:
7124 case VMSTATE_SUSPENDING:
7125 case VMSTATE_SUSPENDING_LS:
7126 case VMSTATE_SUSPENDING_EXT_LS:
7127 case VMSTATE_SUSPENDED:
7128 case VMSTATE_SUSPENDED_LS:
7129 case VMSTATE_SUSPENDED_EXT_LS:
7130 enmMachineState = MachineState_Paused;
7131 break;
7132 case VMSTATE_RUNNING:
7133 case VMSTATE_RUNNING_LS:
7134 case VMSTATE_RUNNING_FT:
7135 case VMSTATE_RESETTING:
7136 case VMSTATE_RESETTING_LS:
7137 case VMSTATE_SOFT_RESETTING:
7138 case VMSTATE_SOFT_RESETTING_LS:
7139 case VMSTATE_DEBUGGING:
7140 case VMSTATE_DEBUGGING_LS:
7141 enmMachineState = MachineState_Running;
7142 break;
7143 case VMSTATE_SAVING:
7144 enmMachineState = MachineState_Saving;
7145 break;
7146 case VMSTATE_POWERING_OFF:
7147 case VMSTATE_POWERING_OFF_LS:
7148 case VMSTATE_DESTROYING:
7149 enmMachineState = MachineState_Stopping;
7150 break;
7151 case VMSTATE_OFF:
7152 case VMSTATE_OFF_LS:
7153 case VMSTATE_FATAL_ERROR:
7154 case VMSTATE_FATAL_ERROR_LS:
7155 case VMSTATE_LOAD_FAILURE:
7156 case VMSTATE_TERMINATED:
7157 enmMachineState = MachineState_PoweredOff;
7158 break;
7159 case VMSTATE_GURU_MEDITATION:
7160 case VMSTATE_GURU_MEDITATION_LS:
7161 enmMachineState = MachineState_Stuck;
7162 break;
7163 default:
7164 AssertMsgFailed(("%s\n", VMR3GetStateName(enmVMState)));
7165 enmMachineState = MachineState_PoweredOff;
7166 }
7167 aNominalState = enmMachineState;
7168
7169 LogFlowFuncLeave();
7170 return S_OK;
7171}
7172
7173void Console::i_onMousePointerShapeChange(bool fVisible, bool fAlpha,
7174 uint32_t xHot, uint32_t yHot,
7175 uint32_t width, uint32_t height,
7176 const uint8_t *pu8Shape,
7177 uint32_t cbShape)
7178{
7179#if 0
7180 LogFlowThisFuncEnter();
7181 LogFlowThisFunc(("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, height=%d, shape=%p\n",
7182 fVisible, fAlpha, xHot, yHot, width, height, pShape));
7183#endif
7184
7185 AutoCaller autoCaller(this);
7186 AssertComRCReturnVoid(autoCaller.rc());
7187
7188 if (!mMouse.isNull())
7189 mMouse->updateMousePointerShape(fVisible, fAlpha, xHot, yHot, width, height,
7190 pu8Shape, cbShape);
7191
7192 com::SafeArray<BYTE> shape(cbShape);
7193 if (pu8Shape)
7194 memcpy(shape.raw(), pu8Shape, cbShape);
7195 fireMousePointerShapeChangedEvent(mEventSource, fVisible, fAlpha, xHot, yHot, width, height, ComSafeArrayAsInParam(shape));
7196
7197#if 0
7198 LogFlowThisFuncLeave();
7199#endif
7200}
7201
7202void Console::i_onMouseCapabilityChange(BOOL supportsAbsolute, BOOL supportsRelative,
7203 BOOL supportsMT, BOOL needsHostCursor)
7204{
7205 LogFlowThisFunc(("supportsAbsolute=%d supportsRelative=%d needsHostCursor=%d\n",
7206 supportsAbsolute, supportsRelative, needsHostCursor));
7207
7208 AutoCaller autoCaller(this);
7209 AssertComRCReturnVoid(autoCaller.rc());
7210
7211 fireMouseCapabilityChangedEvent(mEventSource, supportsAbsolute, supportsRelative, supportsMT, needsHostCursor);
7212}
7213
7214void Console::i_onStateChange(MachineState_T machineState)
7215{
7216 AutoCaller autoCaller(this);
7217 AssertComRCReturnVoid(autoCaller.rc());
7218 fireStateChangedEvent(mEventSource, machineState);
7219}
7220
7221void Console::i_onAdditionsStateChange()
7222{
7223 AutoCaller autoCaller(this);
7224 AssertComRCReturnVoid(autoCaller.rc());
7225
7226 fireAdditionsStateChangedEvent(mEventSource);
7227}
7228
7229/**
7230 * @remarks This notification only is for reporting an incompatible
7231 * Guest Additions interface, *not* the Guest Additions version!
7232 *
7233 * The user will be notified inside the guest if new Guest
7234 * Additions are available (via VBoxTray/VBoxClient).
7235 */
7236void Console::i_onAdditionsOutdated()
7237{
7238 AutoCaller autoCaller(this);
7239 AssertComRCReturnVoid(autoCaller.rc());
7240
7241 /** @todo implement this */
7242}
7243
7244void Console::i_onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
7245{
7246 AutoCaller autoCaller(this);
7247 AssertComRCReturnVoid(autoCaller.rc());
7248
7249 fireKeyboardLedsChangedEvent(mEventSource, fNumLock, fCapsLock, fScrollLock);
7250}
7251
7252void Console::i_onUSBDeviceStateChange(IUSBDevice *aDevice, bool aAttached,
7253 IVirtualBoxErrorInfo *aError)
7254{
7255 AutoCaller autoCaller(this);
7256 AssertComRCReturnVoid(autoCaller.rc());
7257
7258 fireUSBDeviceStateChangedEvent(mEventSource, aDevice, aAttached, aError);
7259}
7260
7261void Console::i_onRuntimeError(BOOL aFatal, IN_BSTR aErrorID, IN_BSTR aMessage)
7262{
7263 AutoCaller autoCaller(this);
7264 AssertComRCReturnVoid(autoCaller.rc());
7265
7266 fireRuntimeErrorEvent(mEventSource, aFatal, aErrorID, aMessage);
7267}
7268
7269HRESULT Console::i_onShowWindow(BOOL aCheck, BOOL *aCanShow, LONG64 *aWinId)
7270{
7271 AssertReturn(aCanShow, E_POINTER);
7272 AssertReturn(aWinId, E_POINTER);
7273
7274 *aCanShow = FALSE;
7275 *aWinId = 0;
7276
7277 AutoCaller autoCaller(this);
7278 AssertComRCReturnRC(autoCaller.rc());
7279
7280 VBoxEventDesc evDesc;
7281 if (aCheck)
7282 {
7283 evDesc.init(mEventSource, VBoxEventType_OnCanShowWindow);
7284 BOOL fDelivered = evDesc.fire(5000); /* Wait up to 5 secs for delivery */
7285 //Assert(fDelivered);
7286 if (fDelivered)
7287 {
7288 ComPtr<IEvent> pEvent;
7289 evDesc.getEvent(pEvent.asOutParam());
7290 // bit clumsy
7291 ComPtr<ICanShowWindowEvent> pCanShowEvent = pEvent;
7292 if (pCanShowEvent)
7293 {
7294 BOOL fVetoed = FALSE;
7295 BOOL fApproved = FALSE;
7296 pCanShowEvent->IsVetoed(&fVetoed);
7297 pCanShowEvent->IsApproved(&fApproved);
7298 *aCanShow = fApproved || !fVetoed;
7299 }
7300 else
7301 {
7302 AssertFailed();
7303 *aCanShow = TRUE;
7304 }
7305 }
7306 else
7307 *aCanShow = TRUE;
7308 }
7309 else
7310 {
7311 evDesc.init(mEventSource, VBoxEventType_OnShowWindow, INT64_C(0));
7312 BOOL fDelivered = evDesc.fire(5000); /* Wait up to 5 secs for delivery */
7313 //Assert(fDelivered);
7314 if (fDelivered)
7315 {
7316 ComPtr<IEvent> pEvent;
7317 evDesc.getEvent(pEvent.asOutParam());
7318 ComPtr<IShowWindowEvent> pShowEvent = pEvent;
7319 if (pShowEvent)
7320 {
7321 LONG64 iEvWinId = 0;
7322 pShowEvent->COMGETTER(WinId)(&iEvWinId);
7323 if (iEvWinId != 0 && *aWinId == 0)
7324 *aWinId = iEvWinId;
7325 }
7326 else
7327 AssertFailed();
7328 }
7329 }
7330
7331 return S_OK;
7332}
7333
7334// private methods
7335////////////////////////////////////////////////////////////////////////////////
7336
7337/**
7338 * Increases the usage counter of the mpUVM pointer.
7339 *
7340 * Guarantees that VMR3Destroy() will not be called on it at least until
7341 * releaseVMCaller() is called.
7342 *
7343 * If this method returns a failure, the caller is not allowed to use mpUVM and
7344 * may return the failed result code to the upper level. This method sets the
7345 * extended error info on failure if \a aQuiet is false.
7346 *
7347 * Setting \a aQuiet to true is useful for methods that don't want to return
7348 * the failed result code to the caller when this method fails (e.g. need to
7349 * silently check for the mpUVM availability).
7350 *
7351 * When mpUVM is NULL but \a aAllowNullVM is true, a corresponding error will be
7352 * returned instead of asserting. Having it false is intended as a sanity check
7353 * for methods that have checked mMachineState and expect mpUVM *NOT* to be
7354 * NULL.
7355 *
7356 * @param aQuiet true to suppress setting error info
7357 * @param aAllowNullVM true to accept mpUVM being NULL and return a failure
7358 * (otherwise this method will assert if mpUVM is NULL)
7359 *
7360 * @note Locks this object for writing.
7361 */
7362HRESULT Console::i_addVMCaller(bool aQuiet /* = false */,
7363 bool aAllowNullVM /* = false */)
7364{
7365 RT_NOREF(aAllowNullVM);
7366 AutoCaller autoCaller(this);
7367 /** @todo Fix race during console/VM reference destruction, refer @bugref{6318}
7368 * comment 25. */
7369 if (FAILED(autoCaller.rc()))
7370 return autoCaller.rc();
7371
7372 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7373
7374 if (mVMDestroying)
7375 {
7376 /* powerDown() is waiting for all callers to finish */
7377 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED, tr("The virtual machine is being powered down"));
7378 }
7379
7380 if (mpUVM == NULL)
7381 {
7382 Assert(aAllowNullVM == true);
7383
7384 /* The machine is not powered up */
7385 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED, tr("The virtual machine is not powered up"));
7386 }
7387
7388 ++mVMCallers;
7389
7390 return S_OK;
7391}
7392
7393/**
7394 * Decreases the usage counter of the mpUVM pointer.
7395 *
7396 * Must always complete the addVMCaller() call after the mpUVM pointer is no
7397 * more necessary.
7398 *
7399 * @note Locks this object for writing.
7400 */
7401void Console::i_releaseVMCaller()
7402{
7403 AutoCaller autoCaller(this);
7404 AssertComRCReturnVoid(autoCaller.rc());
7405
7406 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7407
7408 AssertReturnVoid(mpUVM != NULL);
7409
7410 Assert(mVMCallers > 0);
7411 --mVMCallers;
7412
7413 if (mVMCallers == 0 && mVMDestroying)
7414 {
7415 /* inform powerDown() there are no more callers */
7416 RTSemEventSignal(mVMZeroCallersSem);
7417 }
7418}
7419
7420
7421HRESULT Console::i_safeVMPtrRetainer(PUVM *a_ppUVM, bool a_Quiet)
7422{
7423 *a_ppUVM = NULL;
7424
7425 AutoCaller autoCaller(this);
7426 AssertComRCReturnRC(autoCaller.rc());
7427 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7428
7429 /*
7430 * Repeat the checks done by addVMCaller.
7431 */
7432 if (mVMDestroying) /* powerDown() is waiting for all callers to finish */
7433 return a_Quiet
7434 ? E_ACCESSDENIED
7435 : setError(E_ACCESSDENIED, tr("The virtual machine is being powered down"));
7436 PUVM pUVM = mpUVM;
7437 if (!pUVM)
7438 return a_Quiet
7439 ? E_ACCESSDENIED
7440 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
7441
7442 /*
7443 * Retain a reference to the user mode VM handle and get the global handle.
7444 */
7445 uint32_t cRefs = VMR3RetainUVM(pUVM);
7446 if (cRefs == UINT32_MAX)
7447 return a_Quiet
7448 ? E_ACCESSDENIED
7449 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
7450
7451 /* done */
7452 *a_ppUVM = pUVM;
7453 return S_OK;
7454}
7455
7456void Console::i_safeVMPtrReleaser(PUVM *a_ppUVM)
7457{
7458 if (*a_ppUVM)
7459 VMR3ReleaseUVM(*a_ppUVM);
7460 *a_ppUVM = NULL;
7461}
7462
7463
7464/**
7465 * Initialize the release logging facility. In case something
7466 * goes wrong, there will be no release logging. Maybe in the future
7467 * we can add some logic to use different file names in this case.
7468 * Note that the logic must be in sync with Machine::DeleteSettings().
7469 */
7470HRESULT Console::i_consoleInitReleaseLog(const ComPtr<IMachine> aMachine)
7471{
7472 HRESULT hrc = S_OK;
7473
7474 Bstr logFolder;
7475 hrc = aMachine->COMGETTER(LogFolder)(logFolder.asOutParam());
7476 if (FAILED(hrc))
7477 return hrc;
7478
7479 Utf8Str logDir = logFolder;
7480
7481 /* make sure the Logs folder exists */
7482 Assert(logDir.length());
7483 if (!RTDirExists(logDir.c_str()))
7484 RTDirCreateFullPath(logDir.c_str(), 0700);
7485
7486 Utf8Str logFile = Utf8StrFmt("%s%cVBox.log",
7487 logDir.c_str(), RTPATH_DELIMITER);
7488 Utf8Str pngFile = Utf8StrFmt("%s%cVBox.png",
7489 logDir.c_str(), RTPATH_DELIMITER);
7490
7491 /*
7492 * Age the old log files
7493 * Rename .(n-1) to .(n), .(n-2) to .(n-1), ..., and the last log file to .1
7494 * Overwrite target files in case they exist.
7495 */
7496 ComPtr<IVirtualBox> pVirtualBox;
7497 aMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
7498 ComPtr<ISystemProperties> pSystemProperties;
7499 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
7500 ULONG cHistoryFiles = 3;
7501 pSystemProperties->COMGETTER(LogHistoryCount)(&cHistoryFiles);
7502 if (cHistoryFiles)
7503 {
7504 for (int i = cHistoryFiles-1; i >= 0; i--)
7505 {
7506 Utf8Str *files[] = { &logFile, &pngFile };
7507 Utf8Str oldName, newName;
7508
7509 for (unsigned int j = 0; j < RT_ELEMENTS(files); ++j)
7510 {
7511 if (i > 0)
7512 oldName = Utf8StrFmt("%s.%d", files[j]->c_str(), i);
7513 else
7514 oldName = *files[j];
7515 newName = Utf8StrFmt("%s.%d", files[j]->c_str(), i + 1);
7516 /* If the old file doesn't exist, delete the new file (if it
7517 * exists) to provide correct rotation even if the sequence is
7518 * broken */
7519 if ( RTFileRename(oldName.c_str(), newName.c_str(), RTFILEMOVE_FLAGS_REPLACE)
7520 == VERR_FILE_NOT_FOUND)
7521 RTFileDelete(newName.c_str());
7522 }
7523 }
7524 }
7525
7526 RTERRINFOSTATIC ErrInfo;
7527 int vrc = com::VBoxLogRelCreate("VM", logFile.c_str(),
7528 RTLOGFLAGS_PREFIX_TIME_PROG | RTLOGFLAGS_RESTRICT_GROUPS,
7529 "all all.restrict -default.restrict",
7530 "VBOX_RELEASE_LOG", RTLOGDEST_FILE,
7531 32768 /* cMaxEntriesPerGroup */,
7532 0 /* cHistory */, 0 /* uHistoryFileTime */,
7533 0 /* uHistoryFileSize */, RTErrInfoInitStatic(&ErrInfo));
7534 if (RT_FAILURE(vrc))
7535 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to open release log (%s, %Rrc)"), ErrInfo.Core.pszMsg, vrc);
7536
7537 /* If we've made any directory changes, flush the directory to increase
7538 the likelihood that the log file will be usable after a system panic.
7539
7540 Tip: Try 'export VBOX_RELEASE_LOG_FLAGS=flush' if the last bits of the log
7541 is missing. Just don't have too high hopes for this to help. */
7542 if (SUCCEEDED(hrc) || cHistoryFiles)
7543 RTDirFlush(logDir.c_str());
7544
7545 return hrc;
7546}
7547
7548/**
7549 * Common worker for PowerUp and PowerUpPaused.
7550 *
7551 * @returns COM status code.
7552 *
7553 * @param aProgress Where to return the progress object.
7554 * @param aPaused true if PowerUpPaused called.
7555 */
7556HRESULT Console::i_powerUp(IProgress **aProgress, bool aPaused)
7557{
7558 LogFlowThisFuncEnter();
7559
7560 CheckComArgOutPointerValid(aProgress);
7561
7562 AutoCaller autoCaller(this);
7563 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7564
7565 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7566
7567 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
7568 HRESULT rc = S_OK;
7569 ComObjPtr<Progress> pPowerupProgress;
7570 bool fBeganPoweringUp = false;
7571
7572 LONG cOperations = 1;
7573 LONG ulTotalOperationsWeight = 1;
7574 VMPowerUpTask* task = NULL;
7575
7576 try
7577 {
7578 if (Global::IsOnlineOrTransient(mMachineState))
7579 throw setError(VBOX_E_INVALID_VM_STATE, tr("The virtual machine is already running or busy (machine state: %s)"),
7580 Global::stringifyMachineState(mMachineState));
7581
7582 /* Set up release logging as early as possible after the check if
7583 * there is already a running VM which we shouldn't disturb. */
7584 rc = i_consoleInitReleaseLog(mMachine);
7585 if (FAILED(rc))
7586 throw rc;
7587
7588#ifdef VBOX_OPENSSL_FIPS
7589 LogRel(("crypto: FIPS mode %s\n", FIPS_mode() ? "enabled" : "FAILED"));
7590#endif
7591
7592 /* test and clear the TeleporterEnabled property */
7593 BOOL fTeleporterEnabled;
7594 rc = mMachine->COMGETTER(TeleporterEnabled)(&fTeleporterEnabled);
7595 if (FAILED(rc))
7596 throw rc;
7597
7598#if 0 /** @todo we should save it afterwards, but that isn't necessarily a good idea. Find a better place for this (VBoxSVC). */
7599 if (fTeleporterEnabled)
7600 {
7601 rc = mMachine->COMSETTER(TeleporterEnabled)(FALSE);
7602 if (FAILED(rc))
7603 throw rc;
7604 }
7605#endif
7606
7607 /* test the FaultToleranceState property */
7608 FaultToleranceState_T enmFaultToleranceState;
7609 rc = mMachine->COMGETTER(FaultToleranceState)(&enmFaultToleranceState);
7610 if (FAILED(rc))
7611 throw rc;
7612 BOOL fFaultToleranceSyncEnabled = (enmFaultToleranceState == FaultToleranceState_Standby);
7613
7614 /* Create a progress object to track progress of this operation. Must
7615 * be done as early as possible (together with BeginPowerUp()) as this
7616 * is vital for communicating as much as possible early powerup
7617 * failure information to the API caller */
7618 pPowerupProgress.createObject();
7619 Bstr progressDesc;
7620 if (mMachineState == MachineState_Saved)
7621 progressDesc = tr("Restoring virtual machine");
7622 else if (fTeleporterEnabled)
7623 progressDesc = tr("Teleporting virtual machine");
7624 else if (fFaultToleranceSyncEnabled)
7625 progressDesc = tr("Fault Tolerance syncing of remote virtual machine");
7626 else
7627 progressDesc = tr("Starting virtual machine");
7628
7629 Bstr savedStateFile;
7630
7631 /*
7632 * Saved VMs will have to prove that their saved states seem kosher.
7633 */
7634 if (mMachineState == MachineState_Saved)
7635 {
7636 rc = mMachine->COMGETTER(StateFilePath)(savedStateFile.asOutParam());
7637 if (FAILED(rc))
7638 throw rc;
7639 ComAssertRet(!savedStateFile.isEmpty(), E_FAIL);
7640 int vrc = SSMR3ValidateFile(Utf8Str(savedStateFile).c_str(), false /* fChecksumIt */);
7641 if (RT_FAILURE(vrc))
7642 throw setErrorBoth(VBOX_E_FILE_ERROR, vrc,
7643 tr("VM cannot start because the saved state file '%ls' is invalid (%Rrc). Delete the saved state prior to starting the VM"),
7644 savedStateFile.raw(), vrc);
7645 }
7646
7647 /* Read console data, including console shared folders, stored in the
7648 * saved state file (if not yet done).
7649 */
7650 rc = i_loadDataFromSavedState();
7651 if (FAILED(rc))
7652 throw rc;
7653
7654 /* Check all types of shared folders and compose a single list */
7655 SharedFolderDataMap sharedFolders;
7656 {
7657 /* first, insert global folders */
7658 for (SharedFolderDataMap::const_iterator it = m_mapGlobalSharedFolders.begin();
7659 it != m_mapGlobalSharedFolders.end();
7660 ++it)
7661 {
7662 const SharedFolderData &d = it->second;
7663 sharedFolders[it->first] = d;
7664 }
7665
7666 /* second, insert machine folders */
7667 for (SharedFolderDataMap::const_iterator it = m_mapMachineSharedFolders.begin();
7668 it != m_mapMachineSharedFolders.end();
7669 ++it)
7670 {
7671 const SharedFolderData &d = it->second;
7672 sharedFolders[it->first] = d;
7673 }
7674
7675 /* third, insert console folders */
7676 for (SharedFolderMap::const_iterator it = m_mapSharedFolders.begin();
7677 it != m_mapSharedFolders.end();
7678 ++it)
7679 {
7680 SharedFolder *pSF = it->second;
7681 AutoCaller sfCaller(pSF);
7682 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
7683 sharedFolders[it->first] = SharedFolderData(pSF->i_getHostPath(),
7684 pSF->i_isWritable(),
7685 pSF->i_isAutoMounted());
7686 }
7687 }
7688
7689
7690 /* Setup task object and thread to carry out the operation
7691 * asynchronously */
7692 try
7693 {
7694 task = new VMPowerUpTask(this, pPowerupProgress);
7695 if (!task->isOk())
7696 {
7697 throw E_FAIL;
7698 }
7699 }
7700 catch(...)
7701 {
7702 delete task;
7703 rc = setError(E_FAIL, "Could not create VMPowerUpTask object \n");
7704 throw rc;
7705 }
7706
7707 task->mConfigConstructor = i_configConstructor;
7708 task->mSharedFolders = sharedFolders;
7709 task->mStartPaused = aPaused;
7710 if (mMachineState == MachineState_Saved)
7711 task->mSavedStateFile = savedStateFile;
7712 task->mTeleporterEnabled = fTeleporterEnabled;
7713 task->mEnmFaultToleranceState = enmFaultToleranceState;
7714
7715 /* Reset differencing hard disks for which autoReset is true,
7716 * but only if the machine has no snapshots OR the current snapshot
7717 * is an OFFLINE snapshot; otherwise we would reset the current
7718 * differencing image of an ONLINE snapshot which contains the disk
7719 * state of the machine while it was previously running, but without
7720 * the corresponding machine state, which is equivalent to powering
7721 * off a running machine and not good idea
7722 */
7723 ComPtr<ISnapshot> pCurrentSnapshot;
7724 rc = mMachine->COMGETTER(CurrentSnapshot)(pCurrentSnapshot.asOutParam());
7725 if (FAILED(rc))
7726 throw rc;
7727
7728 BOOL fCurrentSnapshotIsOnline = false;
7729 if (pCurrentSnapshot)
7730 {
7731 rc = pCurrentSnapshot->COMGETTER(Online)(&fCurrentSnapshotIsOnline);
7732 if (FAILED(rc))
7733 throw rc;
7734 }
7735
7736 if (savedStateFile.isEmpty() && !fCurrentSnapshotIsOnline)
7737 {
7738 LogFlowThisFunc(("Looking for immutable images to reset\n"));
7739
7740 com::SafeIfaceArray<IMediumAttachment> atts;
7741 rc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
7742 if (FAILED(rc))
7743 throw rc;
7744
7745 for (size_t i = 0;
7746 i < atts.size();
7747 ++i)
7748 {
7749 DeviceType_T devType;
7750 rc = atts[i]->COMGETTER(Type)(&devType);
7751 /** @todo later applies to floppies as well */
7752 if (devType == DeviceType_HardDisk)
7753 {
7754 ComPtr<IMedium> pMedium;
7755 rc = atts[i]->COMGETTER(Medium)(pMedium.asOutParam());
7756 if (FAILED(rc))
7757 throw rc;
7758
7759 /* needs autoreset? */
7760 BOOL autoReset = FALSE;
7761 rc = pMedium->COMGETTER(AutoReset)(&autoReset);
7762 if (FAILED(rc))
7763 throw rc;
7764
7765 if (autoReset)
7766 {
7767 ComPtr<IProgress> pResetProgress;
7768 rc = pMedium->Reset(pResetProgress.asOutParam());
7769 if (FAILED(rc))
7770 throw rc;
7771
7772 /* save for later use on the powerup thread */
7773 task->hardDiskProgresses.push_back(pResetProgress);
7774 }
7775 }
7776 }
7777 }
7778 else
7779 LogFlowThisFunc(("Machine has a current snapshot which is online, skipping immutable images reset\n"));
7780
7781 /* setup task object and thread to carry out the operation
7782 * asynchronously */
7783
7784#ifdef VBOX_WITH_EXTPACK
7785 mptrExtPackManager->i_dumpAllToReleaseLog();
7786#endif
7787
7788#ifdef RT_OS_SOLARIS
7789 /* setup host core dumper for the VM */
7790 Bstr value;
7791 HRESULT hrc = mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpEnabled").raw(), value.asOutParam());
7792 if (SUCCEEDED(hrc) && value == "1")
7793 {
7794 Bstr coreDumpDir, coreDumpReplaceSys, coreDumpLive;
7795 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpDir").raw(), coreDumpDir.asOutParam());
7796 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpReplaceSystemDump").raw(), coreDumpReplaceSys.asOutParam());
7797 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpLive").raw(), coreDumpLive.asOutParam());
7798
7799 uint32_t fCoreFlags = 0;
7800 if ( coreDumpReplaceSys.isEmpty() == false
7801 && Utf8Str(coreDumpReplaceSys).toUInt32() == 1)
7802 fCoreFlags |= RTCOREDUMPER_FLAGS_REPLACE_SYSTEM_DUMP;
7803
7804 if ( coreDumpLive.isEmpty() == false
7805 && Utf8Str(coreDumpLive).toUInt32() == 1)
7806 fCoreFlags |= RTCOREDUMPER_FLAGS_LIVE_CORE;
7807
7808 Utf8Str strDumpDir(coreDumpDir);
7809 const char *pszDumpDir = strDumpDir.c_str();
7810 if ( pszDumpDir
7811 && *pszDumpDir == '\0')
7812 pszDumpDir = NULL;
7813
7814 int vrc;
7815 if ( pszDumpDir
7816 && !RTDirExists(pszDumpDir))
7817 {
7818 /*
7819 * Try create the directory.
7820 */
7821 vrc = RTDirCreateFullPath(pszDumpDir, 0700);
7822 if (RT_FAILURE(vrc))
7823 throw setErrorBoth(E_FAIL, vrc, "Failed to setup CoreDumper. Couldn't create dump directory '%s' (%Rrc)\n",
7824 pszDumpDir, vrc);
7825 }
7826
7827 vrc = RTCoreDumperSetup(pszDumpDir, fCoreFlags);
7828 if (RT_FAILURE(vrc))
7829 throw setErrorBoth(E_FAIL, vrc, "Failed to setup CoreDumper (%Rrc)", vrc);
7830 LogRel(("CoreDumper setup successful. pszDumpDir=%s fFlags=%#x\n", pszDumpDir ? pszDumpDir : ".", fCoreFlags));
7831 }
7832#endif
7833
7834
7835 // If there is immutable drive the process that.
7836 VMPowerUpTask::ProgressList progresses(task->hardDiskProgresses);
7837 if (aProgress && !progresses.empty())
7838 {
7839 for (VMPowerUpTask::ProgressList::const_iterator it = progresses.begin(); it != progresses.end(); ++it)
7840 {
7841 ++cOperations;
7842 ulTotalOperationsWeight += 1;
7843 }
7844 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7845 progressDesc.raw(),
7846 TRUE, // Cancelable
7847 cOperations,
7848 ulTotalOperationsWeight,
7849 Bstr(tr("Starting Hard Disk operations")).raw(),
7850 1);
7851 AssertComRCReturnRC(rc);
7852 }
7853 else if ( mMachineState == MachineState_Saved
7854 || (!fTeleporterEnabled && !fFaultToleranceSyncEnabled))
7855 {
7856 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7857 progressDesc.raw(),
7858 FALSE /* aCancelable */);
7859 }
7860 else if (fTeleporterEnabled)
7861 {
7862 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7863 progressDesc.raw(),
7864 TRUE /* aCancelable */,
7865 3 /* cOperations */,
7866 10 /* ulTotalOperationsWeight */,
7867 Bstr(tr("Teleporting virtual machine")).raw(),
7868 1 /* ulFirstOperationWeight */);
7869 }
7870 else if (fFaultToleranceSyncEnabled)
7871 {
7872 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7873 progressDesc.raw(),
7874 TRUE /* aCancelable */,
7875 3 /* cOperations */,
7876 10 /* ulTotalOperationsWeight */,
7877 Bstr(tr("Fault Tolerance syncing of remote virtual machine")).raw(),
7878 1 /* ulFirstOperationWeight */);
7879 }
7880
7881 if (FAILED(rc))
7882 throw rc;
7883
7884 /* Tell VBoxSVC and Machine about the progress object so they can
7885 combine/proxy it to any openRemoteSession caller. */
7886 LogFlowThisFunc(("Calling BeginPowerUp...\n"));
7887 rc = mControl->BeginPowerUp(pPowerupProgress);
7888 if (FAILED(rc))
7889 {
7890 LogFlowThisFunc(("BeginPowerUp failed\n"));
7891 throw rc;
7892 }
7893 fBeganPoweringUp = true;
7894
7895 LogFlowThisFunc(("Checking if canceled...\n"));
7896 BOOL fCanceled;
7897 rc = pPowerupProgress->COMGETTER(Canceled)(&fCanceled);
7898 if (FAILED(rc))
7899 throw rc;
7900
7901 if (fCanceled)
7902 {
7903 LogFlowThisFunc(("Canceled in BeginPowerUp\n"));
7904 throw setError(E_FAIL, tr("Powerup was canceled"));
7905 }
7906 LogFlowThisFunc(("Not canceled yet.\n"));
7907
7908 /** @todo this code prevents starting a VM with unavailable bridged
7909 * networking interface. The only benefit is a slightly better error
7910 * message, which should be moved to the driver code. This is the
7911 * only reason why I left the code in for now. The driver allows
7912 * unavailable bridged networking interfaces in certain circumstances,
7913 * and this is sabotaged by this check. The VM will initially have no
7914 * network connectivity, but the user can fix this at runtime. */
7915#if 0
7916 /* the network cards will undergo a quick consistency check */
7917 for (ULONG slot = 0;
7918 slot < maxNetworkAdapters;
7919 ++slot)
7920 {
7921 ComPtr<INetworkAdapter> pNetworkAdapter;
7922 mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
7923 BOOL enabled = FALSE;
7924 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
7925 if (!enabled)
7926 continue;
7927
7928 NetworkAttachmentType_T netattach;
7929 pNetworkAdapter->COMGETTER(AttachmentType)(&netattach);
7930 switch (netattach)
7931 {
7932 case NetworkAttachmentType_Bridged:
7933 {
7934 /* a valid host interface must have been set */
7935 Bstr hostif;
7936 pNetworkAdapter->COMGETTER(HostInterface)(hostif.asOutParam());
7937 if (hostif.isEmpty())
7938 {
7939 throw setError(VBOX_E_HOST_ERROR,
7940 tr("VM cannot start because host interface networking requires a host interface name to be set"));
7941 }
7942 ComPtr<IVirtualBox> pVirtualBox;
7943 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
7944 ComPtr<IHost> pHost;
7945 pVirtualBox->COMGETTER(Host)(pHost.asOutParam());
7946 ComPtr<IHostNetworkInterface> pHostInterface;
7947 if (!SUCCEEDED(pHost->FindHostNetworkInterfaceByName(hostif.raw(),
7948 pHostInterface.asOutParam())))
7949 {
7950 throw setError(VBOX_E_HOST_ERROR,
7951 tr("VM cannot start because the host interface '%ls' does not exist"), hostif.raw());
7952 }
7953 break;
7954 }
7955 default:
7956 break;
7957 }
7958 }
7959#endif // 0
7960
7961
7962 /* setup task object and thread to carry out the operation
7963 * asynchronously */
7964 if (aProgress){
7965 rc = pPowerupProgress.queryInterfaceTo(aProgress);
7966 AssertComRCReturnRC(rc);
7967 }
7968
7969 rc = task->createThread();
7970
7971 if (FAILED(rc))
7972 throw rc;
7973
7974 /* finally, set the state: no right to fail in this method afterwards
7975 * since we've already started the thread and it is now responsible for
7976 * any error reporting and appropriate state change! */
7977 if (mMachineState == MachineState_Saved)
7978 i_setMachineState(MachineState_Restoring);
7979 else if (fTeleporterEnabled)
7980 i_setMachineState(MachineState_TeleportingIn);
7981 else if (enmFaultToleranceState == FaultToleranceState_Standby)
7982 i_setMachineState(MachineState_FaultTolerantSyncing);
7983 else
7984 i_setMachineState(MachineState_Starting);
7985 }
7986 catch (HRESULT aRC) { rc = aRC; }
7987
7988 if (FAILED(rc) && fBeganPoweringUp)
7989 {
7990
7991 /* The progress object will fetch the current error info */
7992 if (!pPowerupProgress.isNull())
7993 pPowerupProgress->i_notifyComplete(rc);
7994
7995 /* Save the error info across the IPC below. Can't be done before the
7996 * progress notification above, as saving the error info deletes it
7997 * from the current context, and thus the progress object wouldn't be
7998 * updated correctly. */
7999 ErrorInfoKeeper eik;
8000
8001 /* signal end of operation */
8002 mControl->EndPowerUp(rc);
8003 }
8004
8005 LogFlowThisFunc(("mMachineState=%d, rc=%Rhrc\n", mMachineState, rc));
8006 LogFlowThisFuncLeave();
8007 return rc;
8008}
8009
8010/**
8011 * Internal power off worker routine.
8012 *
8013 * This method may be called only at certain places with the following meaning
8014 * as shown below:
8015 *
8016 * - if the machine state is either Running or Paused, a normal
8017 * Console-initiated powerdown takes place (e.g. PowerDown());
8018 * - if the machine state is Saving, saveStateThread() has successfully done its
8019 * job;
8020 * - if the machine state is Starting or Restoring, powerUpThread() has failed
8021 * to start/load the VM;
8022 * - if the machine state is Stopping, the VM has powered itself off (i.e. not
8023 * as a result of the powerDown() call).
8024 *
8025 * Calling it in situations other than the above will cause unexpected behavior.
8026 *
8027 * Note that this method should be the only one that destroys mpUVM and sets it
8028 * to NULL.
8029 *
8030 * @param aProgress Progress object to run (may be NULL).
8031 *
8032 * @note Locks this object for writing.
8033 *
8034 * @note Never call this method from a thread that called addVMCaller() or
8035 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
8036 * release(). Otherwise it will deadlock.
8037 */
8038HRESULT Console::i_powerDown(IProgress *aProgress /*= NULL*/)
8039{
8040 LogFlowThisFuncEnter();
8041
8042 AutoCaller autoCaller(this);
8043 AssertComRCReturnRC(autoCaller.rc());
8044
8045 ComPtr<IInternalProgressControl> pProgressControl(aProgress);
8046
8047 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8048
8049 /* Total # of steps for the progress object. Must correspond to the
8050 * number of "advance percent count" comments in this method! */
8051 enum { StepCount = 7 };
8052 /* current step */
8053 ULONG step = 0;
8054
8055 HRESULT rc = S_OK;
8056 int vrc = VINF_SUCCESS;
8057
8058 /* sanity */
8059 Assert(mVMDestroying == false);
8060
8061 PUVM pUVM = mpUVM; Assert(pUVM != NULL);
8062 uint32_t cRefs = VMR3RetainUVM(pUVM); Assert(cRefs != UINT32_MAX); NOREF(cRefs);
8063
8064 AssertMsg( mMachineState == MachineState_Running
8065 || mMachineState == MachineState_Paused
8066 || mMachineState == MachineState_Stuck
8067 || mMachineState == MachineState_Starting
8068 || mMachineState == MachineState_Stopping
8069 || mMachineState == MachineState_Saving
8070 || mMachineState == MachineState_Restoring
8071 || mMachineState == MachineState_TeleportingPausedVM
8072 || mMachineState == MachineState_FaultTolerantSyncing
8073 || mMachineState == MachineState_TeleportingIn
8074 , ("Invalid machine state: %s\n", Global::stringifyMachineState(mMachineState)));
8075
8076 LogRel(("Console::powerDown(): A request to power off the VM has been issued (mMachineState=%s, InUninit=%d)\n",
8077 Global::stringifyMachineState(mMachineState), getObjectState().getState() == ObjectState::InUninit));
8078
8079 /* Check if we need to power off the VM. In case of mVMPoweredOff=true, the
8080 * VM has already powered itself off in vmstateChangeCallback() and is just
8081 * notifying Console about that. In case of Starting or Restoring,
8082 * powerUpThread() is calling us on failure, so the VM is already off at
8083 * that point. */
8084 if ( !mVMPoweredOff
8085 && ( mMachineState == MachineState_Starting
8086 || mMachineState == MachineState_Restoring
8087 || mMachineState == MachineState_FaultTolerantSyncing
8088 || mMachineState == MachineState_TeleportingIn)
8089 )
8090 mVMPoweredOff = true;
8091
8092 /*
8093 * Go to Stopping state if not already there.
8094 *
8095 * Note that we don't go from Saving/Restoring to Stopping because
8096 * vmstateChangeCallback() needs it to set the state to Saved on
8097 * VMSTATE_TERMINATED. In terms of protecting from inappropriate operations
8098 * while leaving the lock below, Saving or Restoring should be fine too.
8099 * Ditto for TeleportingPausedVM -> Teleported.
8100 */
8101 if ( mMachineState != MachineState_Saving
8102 && mMachineState != MachineState_Restoring
8103 && mMachineState != MachineState_Stopping
8104 && mMachineState != MachineState_TeleportingIn
8105 && mMachineState != MachineState_TeleportingPausedVM
8106 && mMachineState != MachineState_FaultTolerantSyncing
8107 )
8108 i_setMachineState(MachineState_Stopping);
8109
8110 /* ----------------------------------------------------------------------
8111 * DONE with necessary state changes, perform the power down actions (it's
8112 * safe to release the object lock now if needed)
8113 * ---------------------------------------------------------------------- */
8114
8115 if (mDisplay)
8116 {
8117 alock.release();
8118
8119 mDisplay->i_notifyPowerDown();
8120
8121 alock.acquire();
8122 }
8123
8124 /* Stop the VRDP server to prevent new clients connection while VM is being
8125 * powered off. */
8126 if (mConsoleVRDPServer)
8127 {
8128 LogFlowThisFunc(("Stopping VRDP server...\n"));
8129
8130 /* Leave the lock since EMT could call us back as addVMCaller() */
8131 alock.release();
8132
8133 mConsoleVRDPServer->Stop();
8134
8135 alock.acquire();
8136 }
8137
8138 /* advance percent count */
8139 if (pProgressControl)
8140 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8141
8142
8143 /* ----------------------------------------------------------------------
8144 * Now, wait for all mpUVM callers to finish their work if there are still
8145 * some on other threads. NO methods that need mpUVM (or initiate other calls
8146 * that need it) may be called after this point
8147 * ---------------------------------------------------------------------- */
8148
8149 /* go to the destroying state to prevent from adding new callers */
8150 mVMDestroying = true;
8151
8152 if (mVMCallers > 0)
8153 {
8154 /* lazy creation */
8155 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
8156 RTSemEventCreate(&mVMZeroCallersSem);
8157
8158 LogFlowThisFunc(("Waiting for mpUVM callers (%d) to drop to zero...\n", mVMCallers));
8159
8160 alock.release();
8161
8162 RTSemEventWait(mVMZeroCallersSem, RT_INDEFINITE_WAIT);
8163
8164 alock.acquire();
8165 }
8166
8167 /* advance percent count */
8168 if (pProgressControl)
8169 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8170
8171 vrc = VINF_SUCCESS;
8172
8173 /*
8174 * Power off the VM if not already done that.
8175 * Leave the lock since EMT will call vmstateChangeCallback.
8176 *
8177 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
8178 * VM-(guest-)initiated power off happened in parallel a ms before this
8179 * call. So far, we let this error pop up on the user's side.
8180 */
8181 if (!mVMPoweredOff)
8182 {
8183 LogFlowThisFunc(("Powering off the VM...\n"));
8184 alock.release();
8185 vrc = VMR3PowerOff(pUVM);
8186#ifdef VBOX_WITH_EXTPACK
8187 mptrExtPackManager->i_callAllVmPowerOffHooks(this, VMR3GetVM(pUVM));
8188#endif
8189 alock.acquire();
8190 }
8191
8192 /* advance percent count */
8193 if (pProgressControl)
8194 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8195
8196#ifdef VBOX_WITH_HGCM
8197 /* Shutdown HGCM services before destroying the VM. */
8198 if (m_pVMMDev)
8199 {
8200 LogFlowThisFunc(("Shutdown HGCM...\n"));
8201
8202 /* Leave the lock since EMT might wait for it and will call us back as addVMCaller() */
8203 alock.release();
8204
8205 DBGFR3InfoDeregisterExternal(pUVM, "guestprops"); /* will crash in unloaded code if we guru later */
8206 m_pVMMDev->hgcmShutdown();
8207
8208 alock.acquire();
8209 }
8210
8211 /* advance percent count */
8212 if (pProgressControl)
8213 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8214
8215#endif /* VBOX_WITH_HGCM */
8216
8217 LogFlowThisFunc(("Ready for VM destruction.\n"));
8218
8219 /* If we are called from Console::uninit(), then try to destroy the VM even
8220 * on failure (this will most likely fail too, but what to do?..) */
8221 if (RT_SUCCESS(vrc) || getObjectState().getState() == ObjectState::InUninit)
8222 {
8223 /* If the machine has a USB controller, release all USB devices
8224 * (symmetric to the code in captureUSBDevices()) */
8225 if (mfVMHasUsbController)
8226 {
8227 alock.release();
8228 i_detachAllUSBDevices(false /* aDone */);
8229 alock.acquire();
8230 }
8231
8232 /* Now we've got to destroy the VM as well. (mpUVM is not valid beyond
8233 * this point). We release the lock before calling VMR3Destroy() because
8234 * it will result into calling destructors of drivers associated with
8235 * Console children which may in turn try to lock Console (e.g. by
8236 * instantiating SafeVMPtr to access mpUVM). It's safe here because
8237 * mVMDestroying is set which should prevent any activity. */
8238
8239 /* Set mpUVM to NULL early just in case if some old code is not using
8240 * addVMCaller()/releaseVMCaller(). (We have our own ref on pUVM.) */
8241 VMR3ReleaseUVM(mpUVM);
8242 mpUVM = NULL;
8243
8244 LogFlowThisFunc(("Destroying the VM...\n"));
8245
8246 alock.release();
8247
8248 vrc = VMR3Destroy(pUVM);
8249
8250 /* take the lock again */
8251 alock.acquire();
8252
8253 /* advance percent count */
8254 if (pProgressControl)
8255 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8256
8257 if (RT_SUCCESS(vrc))
8258 {
8259 LogFlowThisFunc(("Machine has been destroyed (mMachineState=%d)\n",
8260 mMachineState));
8261 /* Note: the Console-level machine state change happens on the
8262 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
8263 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
8264 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
8265 * occurred yet. This is okay, because mMachineState is already
8266 * Stopping in this case, so any other attempt to call PowerDown()
8267 * will be rejected. */
8268 }
8269 else
8270 {
8271 /* bad bad bad, but what to do? (Give Console our UVM ref.) */
8272 mpUVM = pUVM;
8273 pUVM = NULL;
8274 rc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not destroy the machine. (Error: %Rrc)"), vrc);
8275 }
8276
8277 /* Complete the detaching of the USB devices. */
8278 if (mfVMHasUsbController)
8279 {
8280 alock.release();
8281 i_detachAllUSBDevices(true /* aDone */);
8282 alock.acquire();
8283 }
8284
8285 /* advance percent count */
8286 if (pProgressControl)
8287 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8288 }
8289 else
8290 rc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not power off the machine. (Error: %Rrc)"), vrc);
8291
8292 /*
8293 * Finished with the destruction.
8294 *
8295 * Note that if something impossible happened and we've failed to destroy
8296 * the VM, mVMDestroying will remain true and mMachineState will be
8297 * something like Stopping, so most Console methods will return an error
8298 * to the caller.
8299 */
8300 if (pUVM != NULL)
8301 VMR3ReleaseUVM(pUVM);
8302 else
8303 mVMDestroying = false;
8304
8305 LogFlowThisFuncLeave();
8306 return rc;
8307}
8308
8309/**
8310 * @note Locks this object for writing.
8311 */
8312HRESULT Console::i_setMachineState(MachineState_T aMachineState,
8313 bool aUpdateServer /* = true */)
8314{
8315 AutoCaller autoCaller(this);
8316 AssertComRCReturnRC(autoCaller.rc());
8317
8318 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8319
8320 HRESULT rc = S_OK;
8321
8322 if (mMachineState != aMachineState)
8323 {
8324 LogThisFunc(("machineState=%s -> %s aUpdateServer=%RTbool\n",
8325 Global::stringifyMachineState(mMachineState), Global::stringifyMachineState(aMachineState), aUpdateServer));
8326 LogRel(("Console: Machine state changed to '%s'\n", Global::stringifyMachineState(aMachineState)));
8327 mMachineState = aMachineState;
8328
8329 /// @todo (dmik)
8330 // possibly, we need to redo onStateChange() using the dedicated
8331 // Event thread, like it is done in VirtualBox. This will make it
8332 // much safer (no deadlocks possible if someone tries to use the
8333 // console from the callback), however, listeners will lose the
8334 // ability to synchronously react to state changes (is it really
8335 // necessary??)
8336 LogFlowThisFunc(("Doing onStateChange()...\n"));
8337 i_onStateChange(aMachineState);
8338 LogFlowThisFunc(("Done onStateChange()\n"));
8339
8340 if (aUpdateServer)
8341 {
8342 /* Server notification MUST be done from under the lock; otherwise
8343 * the machine state here and on the server might go out of sync
8344 * which can lead to various unexpected results (like the machine
8345 * state being >= MachineState_Running on the server, while the
8346 * session state is already SessionState_Unlocked at the same time
8347 * there).
8348 *
8349 * Cross-lock conditions should be carefully watched out: calling
8350 * UpdateState we will require Machine and SessionMachine locks
8351 * (remember that here we're holding the Console lock here, and also
8352 * all locks that have been acquire by the thread before calling
8353 * this method).
8354 */
8355 LogFlowThisFunc(("Doing mControl->UpdateState()...\n"));
8356 rc = mControl->UpdateState(aMachineState);
8357 LogFlowThisFunc(("mControl->UpdateState()=%Rhrc\n", rc));
8358 }
8359 }
8360
8361 return rc;
8362}
8363
8364/**
8365 * Searches for a shared folder with the given logical name
8366 * in the collection of shared folders.
8367 *
8368 * @param strName logical name of the shared folder
8369 * @param aSharedFolder where to return the found object
8370 * @param aSetError whether to set the error info if the folder is
8371 * not found
8372 * @return
8373 * S_OK when found or E_INVALIDARG when not found
8374 *
8375 * @note The caller must lock this object for writing.
8376 */
8377HRESULT Console::i_findSharedFolder(const Utf8Str &strName,
8378 ComObjPtr<SharedFolder> &aSharedFolder,
8379 bool aSetError /* = false */)
8380{
8381 /* sanity check */
8382 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8383
8384 SharedFolderMap::const_iterator it = m_mapSharedFolders.find(strName);
8385 if (it != m_mapSharedFolders.end())
8386 {
8387 aSharedFolder = it->second;
8388 return S_OK;
8389 }
8390
8391 if (aSetError)
8392 setError(VBOX_E_FILE_ERROR, tr("Could not find a shared folder named '%s'."), strName.c_str());
8393
8394 return VBOX_E_FILE_ERROR;
8395}
8396
8397/**
8398 * Fetches the list of global or machine shared folders from the server.
8399 *
8400 * @param aGlobal true to fetch global folders.
8401 *
8402 * @note The caller must lock this object for writing.
8403 */
8404HRESULT Console::i_fetchSharedFolders(BOOL aGlobal)
8405{
8406 /* sanity check */
8407 AssertReturn( getObjectState().getState() == ObjectState::InInit
8408 || isWriteLockOnCurrentThread(), E_FAIL);
8409
8410 LogFlowThisFunc(("Entering\n"));
8411
8412 /* Check if we're online and keep it that way. */
8413 SafeVMPtrQuiet ptrVM(this);
8414 AutoVMCallerQuietWeak autoVMCaller(this);
8415 bool const online = ptrVM.isOk()
8416 && m_pVMMDev
8417 && m_pVMMDev->isShFlActive();
8418
8419 HRESULT rc = S_OK;
8420
8421 try
8422 {
8423 if (aGlobal)
8424 {
8425 /// @todo grab & process global folders when they are done
8426 }
8427 else
8428 {
8429 SharedFolderDataMap oldFolders;
8430 if (online)
8431 oldFolders = m_mapMachineSharedFolders;
8432
8433 m_mapMachineSharedFolders.clear();
8434
8435 SafeIfaceArray<ISharedFolder> folders;
8436 rc = mMachine->COMGETTER(SharedFolders)(ComSafeArrayAsOutParam(folders));
8437 if (FAILED(rc)) throw rc;
8438
8439 for (size_t i = 0; i < folders.size(); ++i)
8440 {
8441 ComPtr<ISharedFolder> pSharedFolder = folders[i];
8442
8443 Bstr bstrName;
8444 Bstr bstrHostPath;
8445 BOOL writable;
8446 BOOL autoMount;
8447
8448 rc = pSharedFolder->COMGETTER(Name)(bstrName.asOutParam());
8449 if (FAILED(rc)) throw rc;
8450 Utf8Str strName(bstrName);
8451
8452 rc = pSharedFolder->COMGETTER(HostPath)(bstrHostPath.asOutParam());
8453 if (FAILED(rc)) throw rc;
8454 Utf8Str strHostPath(bstrHostPath);
8455
8456 rc = pSharedFolder->COMGETTER(Writable)(&writable);
8457 if (FAILED(rc)) throw rc;
8458
8459 rc = pSharedFolder->COMGETTER(AutoMount)(&autoMount);
8460 if (FAILED(rc)) throw rc;
8461
8462 m_mapMachineSharedFolders.insert(std::make_pair(strName,
8463 SharedFolderData(strHostPath, !!writable, !!autoMount)));
8464
8465 /* send changes to HGCM if the VM is running */
8466 if (online)
8467 {
8468 SharedFolderDataMap::iterator it = oldFolders.find(strName);
8469 if ( it == oldFolders.end()
8470 || it->second.m_strHostPath != strHostPath)
8471 {
8472 /* a new machine folder is added or
8473 * the existing machine folder is changed */
8474 if (m_mapSharedFolders.find(strName) != m_mapSharedFolders.end())
8475 ; /* the console folder exists, nothing to do */
8476 else
8477 {
8478 /* remove the old machine folder (when changed)
8479 * or the global folder if any (when new) */
8480 if ( it != oldFolders.end()
8481 || m_mapGlobalSharedFolders.find(strName) != m_mapGlobalSharedFolders.end()
8482 )
8483 {
8484 rc = i_removeSharedFolder(strName);
8485 if (FAILED(rc)) throw rc;
8486 }
8487
8488 /* create the new machine folder */
8489 rc = i_createSharedFolder(strName,
8490 SharedFolderData(strHostPath, !!writable, !!autoMount));
8491 if (FAILED(rc)) throw rc;
8492 }
8493 }
8494 /* forget the processed (or identical) folder */
8495 if (it != oldFolders.end())
8496 oldFolders.erase(it);
8497 }
8498 }
8499
8500 /* process outdated (removed) folders */
8501 if (online)
8502 {
8503 for (SharedFolderDataMap::const_iterator it = oldFolders.begin();
8504 it != oldFolders.end(); ++it)
8505 {
8506 if (m_mapSharedFolders.find(it->first) != m_mapSharedFolders.end())
8507 ; /* the console folder exists, nothing to do */
8508 else
8509 {
8510 /* remove the outdated machine folder */
8511 rc = i_removeSharedFolder(it->first);
8512 if (FAILED(rc)) throw rc;
8513
8514 /* create the global folder if there is any */
8515 SharedFolderDataMap::const_iterator git =
8516 m_mapGlobalSharedFolders.find(it->first);
8517 if (git != m_mapGlobalSharedFolders.end())
8518 {
8519 rc = i_createSharedFolder(git->first, git->second);
8520 if (FAILED(rc)) throw rc;
8521 }
8522 }
8523 }
8524 }
8525 }
8526 }
8527 catch (HRESULT rc2)
8528 {
8529 rc = rc2;
8530 if (online)
8531 i_atVMRuntimeErrorCallbackF(0, "BrokenSharedFolder", N_("Broken shared folder!"));
8532 }
8533
8534 LogFlowThisFunc(("Leaving\n"));
8535
8536 return rc;
8537}
8538
8539/**
8540 * Searches for a shared folder with the given name in the list of machine
8541 * shared folders and then in the list of the global shared folders.
8542 *
8543 * @param strName Name of the folder to search for.
8544 * @param aIt Where to store the pointer to the found folder.
8545 * @return @c true if the folder was found and @c false otherwise.
8546 *
8547 * @note The caller must lock this object for reading.
8548 */
8549bool Console::i_findOtherSharedFolder(const Utf8Str &strName,
8550 SharedFolderDataMap::const_iterator &aIt)
8551{
8552 /* sanity check */
8553 AssertReturn(isWriteLockOnCurrentThread(), false);
8554
8555 /* first, search machine folders */
8556 aIt = m_mapMachineSharedFolders.find(strName);
8557 if (aIt != m_mapMachineSharedFolders.end())
8558 return true;
8559
8560 /* second, search machine folders */
8561 aIt = m_mapGlobalSharedFolders.find(strName);
8562 if (aIt != m_mapGlobalSharedFolders.end())
8563 return true;
8564
8565 return false;
8566}
8567
8568/**
8569 * Calls the HGCM service to add a shared folder definition.
8570 *
8571 * @param strName Shared folder name.
8572 * @param aData Shared folder data.
8573 *
8574 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
8575 * @note Doesn't lock anything.
8576 */
8577HRESULT Console::i_createSharedFolder(const Utf8Str &strName, const SharedFolderData &aData)
8578{
8579 ComAssertRet(strName.isNotEmpty(), E_FAIL);
8580 ComAssertRet(aData.m_strHostPath.isNotEmpty(), E_FAIL);
8581
8582 /* sanity checks */
8583 AssertReturn(mpUVM, E_FAIL);
8584 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
8585
8586 VBOXHGCMSVCPARM parms[SHFL_CPARMS_ADD_MAPPING];
8587 SHFLSTRING *pFolderName, *pMapName;
8588 size_t cbString;
8589
8590 Bstr value;
8591 HRESULT hrc = mMachine->GetExtraData(BstrFmt("VBoxInternal2/SharedFoldersEnableSymlinksCreate/%s",
8592 strName.c_str()).raw(),
8593 value.asOutParam());
8594 bool fSymlinksCreate = hrc == S_OK && value == "1";
8595
8596 Log(("Adding shared folder '%s' -> '%s'\n", strName.c_str(), aData.m_strHostPath.c_str()));
8597
8598 // check whether the path is valid and exists
8599 char hostPathFull[RTPATH_MAX];
8600 int vrc = RTPathAbsEx(NULL,
8601 aData.m_strHostPath.c_str(),
8602 hostPathFull,
8603 sizeof(hostPathFull));
8604
8605 bool fMissing = false;
8606 if (RT_FAILURE(vrc))
8607 return setErrorBoth(E_INVALIDARG, vrc, tr("Invalid shared folder path: '%s' (%Rrc)"), aData.m_strHostPath.c_str(), vrc);
8608 if (!RTPathExists(hostPathFull))
8609 fMissing = true;
8610
8611 /* Check whether the path is full (absolute) */
8612 if (RTPathCompare(aData.m_strHostPath.c_str(), hostPathFull) != 0)
8613 return setError(E_INVALIDARG,
8614 tr("Shared folder path '%s' is not absolute"),
8615 aData.m_strHostPath.c_str());
8616
8617 // now that we know the path is good, give it to HGCM
8618
8619 Bstr bstrName(strName);
8620 Bstr bstrHostPath(aData.m_strHostPath);
8621
8622 cbString = (bstrHostPath.length() + 1) * sizeof(RTUTF16);
8623 if (cbString >= UINT16_MAX)
8624 return setError(E_INVALIDARG, tr("The name is too long"));
8625 pFolderName = (SHFLSTRING*)RTMemAllocZ(SHFLSTRING_HEADER_SIZE + cbString);
8626 Assert(pFolderName);
8627 memcpy(pFolderName->String.ucs2, bstrHostPath.raw(), cbString);
8628
8629 pFolderName->u16Size = (uint16_t)cbString;
8630 pFolderName->u16Length = (uint16_t)(cbString - sizeof(RTUTF16));
8631
8632 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
8633 parms[0].u.pointer.addr = pFolderName;
8634 parms[0].u.pointer.size = ShflStringSizeOfBuffer(pFolderName);
8635
8636 cbString = (bstrName.length() + 1) * sizeof(RTUTF16);
8637 if (cbString >= UINT16_MAX)
8638 {
8639 RTMemFree(pFolderName);
8640 return setError(E_INVALIDARG, tr("The host path is too long"));
8641 }
8642 pMapName = (SHFLSTRING*)RTMemAllocZ(SHFLSTRING_HEADER_SIZE + cbString);
8643 Assert(pMapName);
8644 memcpy(pMapName->String.ucs2, bstrName.raw(), cbString);
8645
8646 pMapName->u16Size = (uint16_t)cbString;
8647 pMapName->u16Length = (uint16_t)(cbString - sizeof(RTUTF16));
8648
8649 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
8650 parms[1].u.pointer.addr = pMapName;
8651 parms[1].u.pointer.size = ShflStringSizeOfBuffer(pMapName);
8652
8653 parms[2].type = VBOX_HGCM_SVC_PARM_32BIT;
8654 parms[2].u.uint32 = (aData.m_fWritable ? SHFL_ADD_MAPPING_F_WRITABLE : 0)
8655 | (aData.m_fAutoMount ? SHFL_ADD_MAPPING_F_AUTOMOUNT : 0)
8656 | (fSymlinksCreate ? SHFL_ADD_MAPPING_F_CREATE_SYMLINKS : 0)
8657 | (fMissing ? SHFL_ADD_MAPPING_F_MISSING : 0)
8658 ;
8659
8660 vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders",
8661 SHFL_FN_ADD_MAPPING,
8662 SHFL_CPARMS_ADD_MAPPING, &parms[0]);
8663 RTMemFree(pFolderName);
8664 RTMemFree(pMapName);
8665
8666 if (RT_FAILURE(vrc))
8667 return setErrorBoth(E_FAIL, vrc, tr("Could not create a shared folder '%s' mapped to '%s' (%Rrc)"),
8668 strName.c_str(), aData.m_strHostPath.c_str(), vrc);
8669
8670 if (fMissing)
8671 return setError(E_INVALIDARG,
8672 tr("Shared folder path '%s' does not exist on the host"),
8673 aData.m_strHostPath.c_str());
8674
8675 return S_OK;
8676}
8677
8678/**
8679 * Calls the HGCM service to remove the shared folder definition.
8680 *
8681 * @param strName Shared folder name.
8682 *
8683 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
8684 * @note Doesn't lock anything.
8685 */
8686HRESULT Console::i_removeSharedFolder(const Utf8Str &strName)
8687{
8688 ComAssertRet(strName.isNotEmpty(), E_FAIL);
8689
8690 /* sanity checks */
8691 AssertReturn(mpUVM, E_FAIL);
8692 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
8693
8694 VBOXHGCMSVCPARM parms;
8695 SHFLSTRING *pMapName;
8696 size_t cbString;
8697
8698 Log(("Removing shared folder '%s'\n", strName.c_str()));
8699
8700 Bstr bstrName(strName);
8701 cbString = (bstrName.length() + 1) * sizeof(RTUTF16);
8702 if (cbString >= UINT16_MAX)
8703 return setError(E_INVALIDARG, tr("The name is too long"));
8704 pMapName = (SHFLSTRING *) RTMemAllocZ(SHFLSTRING_HEADER_SIZE + cbString);
8705 Assert(pMapName);
8706 memcpy(pMapName->String.ucs2, bstrName.raw(), cbString);
8707
8708 pMapName->u16Size = (uint16_t)cbString;
8709 pMapName->u16Length = (uint16_t)(cbString - sizeof(RTUTF16));
8710
8711 parms.type = VBOX_HGCM_SVC_PARM_PTR;
8712 parms.u.pointer.addr = pMapName;
8713 parms.u.pointer.size = ShflStringSizeOfBuffer(pMapName);
8714
8715 int vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders",
8716 SHFL_FN_REMOVE_MAPPING,
8717 1, &parms);
8718 RTMemFree(pMapName);
8719 if (RT_FAILURE(vrc))
8720 return setErrorBoth(E_FAIL, vrc, tr("Could not remove the shared folder '%s' (%Rrc)"), strName.c_str(), vrc);
8721
8722 return S_OK;
8723}
8724
8725/** @callback_method_impl{FNVMATSTATE}
8726 *
8727 * @note Locks the Console object for writing.
8728 * @remarks The @a pUVM parameter can be NULL in one case where powerUpThread()
8729 * calls after the VM was destroyed.
8730 */
8731DECLCALLBACK(void) Console::i_vmstateChangeCallback(PUVM pUVM, VMSTATE enmState, VMSTATE enmOldState, void *pvUser)
8732{
8733 LogFlowFunc(("Changing state from %s to %s (pUVM=%p)\n",
8734 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState), pUVM));
8735
8736 Console *that = static_cast<Console *>(pvUser);
8737 AssertReturnVoid(that);
8738
8739 AutoCaller autoCaller(that);
8740
8741 /* Note that we must let this method proceed even if Console::uninit() has
8742 * been already called. In such case this VMSTATE change is a result of:
8743 * 1) powerDown() called from uninit() itself, or
8744 * 2) VM-(guest-)initiated power off. */
8745 AssertReturnVoid( autoCaller.isOk()
8746 || that->getObjectState().getState() == ObjectState::InUninit);
8747
8748 switch (enmState)
8749 {
8750 /*
8751 * The VM has terminated
8752 */
8753 case VMSTATE_OFF:
8754 {
8755#ifdef VBOX_WITH_GUEST_PROPS
8756 if (that->i_isResetTurnedIntoPowerOff())
8757 {
8758 Bstr strPowerOffReason;
8759
8760 if (that->mfPowerOffCausedByReset)
8761 strPowerOffReason = Bstr("Reset");
8762 else
8763 strPowerOffReason = Bstr("PowerOff");
8764
8765 that->mMachine->DeleteGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw());
8766 that->mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw(),
8767 strPowerOffReason.raw(), Bstr("RDONLYGUEST").raw());
8768 that->mMachine->SaveSettings();
8769 }
8770#endif
8771
8772 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8773
8774 if (that->mVMStateChangeCallbackDisabled)
8775 return;
8776
8777 /* Do we still think that it is running? It may happen if this is a
8778 * VM-(guest-)initiated shutdown/poweroff.
8779 */
8780 if ( that->mMachineState != MachineState_Stopping
8781 && that->mMachineState != MachineState_Saving
8782 && that->mMachineState != MachineState_Restoring
8783 && that->mMachineState != MachineState_TeleportingIn
8784 && that->mMachineState != MachineState_FaultTolerantSyncing
8785 && that->mMachineState != MachineState_TeleportingPausedVM
8786 && !that->mVMIsAlreadyPoweringOff
8787 )
8788 {
8789 LogFlowFunc(("VM has powered itself off but Console still thinks it is running. Notifying.\n"));
8790
8791 /*
8792 * Prevent powerDown() from calling VMR3PowerOff() again if this was called from
8793 * the power off state change.
8794 * When called from the Reset state make sure to call VMR3PowerOff() first.
8795 */
8796 Assert(that->mVMPoweredOff == false);
8797 that->mVMPoweredOff = true;
8798
8799 /*
8800 * request a progress object from the server
8801 * (this will set the machine state to Stopping on the server
8802 * to block others from accessing this machine)
8803 */
8804 ComPtr<IProgress> pProgress;
8805 HRESULT rc = that->mControl->BeginPoweringDown(pProgress.asOutParam());
8806 AssertComRC(rc);
8807
8808 /* sync the state with the server */
8809 that->i_setMachineStateLocally(MachineState_Stopping);
8810
8811 /* Setup task object and thread to carry out the operation
8812 * asynchronously (if we call powerDown() right here but there
8813 * is one or more mpUVM callers (added with addVMCaller()) we'll
8814 * deadlock).
8815 */
8816 VMPowerDownTask* task = NULL;
8817 try
8818 {
8819 task = new VMPowerDownTask(that, pProgress);
8820 /* If creating a task failed, this can currently mean one of
8821 * two: either Console::uninit() has been called just a ms
8822 * before (so a powerDown() call is already on the way), or
8823 * powerDown() itself is being already executed. Just do
8824 * nothing.
8825 */
8826 if (!task->isOk())
8827 {
8828 LogFlowFunc(("Console is already being uninitialized. \n"));
8829 throw E_FAIL;
8830 }
8831 }
8832 catch(...)
8833 {
8834 delete task;
8835 LogFlowFunc(("Problem with creating VMPowerDownTask object. \n"));
8836 }
8837
8838 rc = task->createThread();
8839
8840 if (FAILED(rc))
8841 {
8842 LogFlowFunc(("Problem with creating thread for VMPowerDownTask. \n"));
8843 }
8844
8845 }
8846 break;
8847 }
8848
8849 /* The VM has been completely destroyed.
8850 *
8851 * Note: This state change can happen at two points:
8852 * 1) At the end of VMR3Destroy() if it was not called from EMT.
8853 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
8854 * called by EMT.
8855 */
8856 case VMSTATE_TERMINATED:
8857 {
8858 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8859
8860 if (that->mVMStateChangeCallbackDisabled)
8861 break;
8862
8863 /* Terminate host interface networking. If pUVM is NULL, we've been
8864 * manually called from powerUpThread() either before calling
8865 * VMR3Create() or after VMR3Create() failed, so no need to touch
8866 * networking.
8867 */
8868 if (pUVM)
8869 that->i_powerDownHostInterfaces();
8870
8871 /* From now on the machine is officially powered down or remains in
8872 * the Saved state.
8873 */
8874 switch (that->mMachineState)
8875 {
8876 default:
8877 AssertFailed();
8878 RT_FALL_THRU();
8879 case MachineState_Stopping:
8880 /* successfully powered down */
8881 that->i_setMachineState(MachineState_PoweredOff);
8882 break;
8883 case MachineState_Saving:
8884 /* successfully saved */
8885 that->i_setMachineState(MachineState_Saved);
8886 break;
8887 case MachineState_Starting:
8888 /* failed to start, but be patient: set back to PoweredOff
8889 * (for similarity with the below) */
8890 that->i_setMachineState(MachineState_PoweredOff);
8891 break;
8892 case MachineState_Restoring:
8893 /* failed to load the saved state file, but be patient: set
8894 * back to Saved (to preserve the saved state file) */
8895 that->i_setMachineState(MachineState_Saved);
8896 break;
8897 case MachineState_TeleportingIn:
8898 /* Teleportation failed or was canceled. Back to powered off. */
8899 that->i_setMachineState(MachineState_PoweredOff);
8900 break;
8901 case MachineState_TeleportingPausedVM:
8902 /* Successfully teleported the VM. */
8903 that->i_setMachineState(MachineState_Teleported);
8904 break;
8905 case MachineState_FaultTolerantSyncing:
8906 /* Fault tolerant sync failed or was canceled. Back to powered off. */
8907 that->i_setMachineState(MachineState_PoweredOff);
8908 break;
8909 }
8910 break;
8911 }
8912
8913 case VMSTATE_RESETTING:
8914 /** @todo shouldn't VMSTATE_RESETTING_LS be here? */
8915 {
8916#ifdef VBOX_WITH_GUEST_PROPS
8917 /* Do not take any read/write locks here! */
8918 that->i_guestPropertiesHandleVMReset();
8919#endif
8920 break;
8921 }
8922
8923 case VMSTATE_SOFT_RESETTING:
8924 case VMSTATE_SOFT_RESETTING_LS:
8925 /* Shouldn't do anything here! */
8926 break;
8927
8928 case VMSTATE_SUSPENDED:
8929 {
8930 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8931
8932 if (that->mVMStateChangeCallbackDisabled)
8933 break;
8934
8935 switch (that->mMachineState)
8936 {
8937 case MachineState_Teleporting:
8938 that->i_setMachineState(MachineState_TeleportingPausedVM);
8939 break;
8940
8941 case MachineState_LiveSnapshotting:
8942 that->i_setMachineState(MachineState_OnlineSnapshotting);
8943 break;
8944
8945 case MachineState_TeleportingPausedVM:
8946 case MachineState_Saving:
8947 case MachineState_Restoring:
8948 case MachineState_Stopping:
8949 case MachineState_TeleportingIn:
8950 case MachineState_FaultTolerantSyncing:
8951 case MachineState_OnlineSnapshotting:
8952 /* The worker thread handles the transition. */
8953 break;
8954
8955 case MachineState_Running:
8956 that->i_setMachineState(MachineState_Paused);
8957 break;
8958
8959 case MachineState_Paused:
8960 /* Nothing to do. */
8961 break;
8962
8963 default:
8964 AssertMsgFailed(("%s\n", Global::stringifyMachineState(that->mMachineState)));
8965 }
8966 break;
8967 }
8968
8969 case VMSTATE_SUSPENDED_LS:
8970 case VMSTATE_SUSPENDED_EXT_LS:
8971 {
8972 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8973 if (that->mVMStateChangeCallbackDisabled)
8974 break;
8975 switch (that->mMachineState)
8976 {
8977 case MachineState_Teleporting:
8978 that->i_setMachineState(MachineState_TeleportingPausedVM);
8979 break;
8980
8981 case MachineState_LiveSnapshotting:
8982 that->i_setMachineState(MachineState_OnlineSnapshotting);
8983 break;
8984
8985 case MachineState_TeleportingPausedVM:
8986 case MachineState_Saving:
8987 /* ignore */
8988 break;
8989
8990 default:
8991 AssertMsgFailed(("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState),
8992 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
8993 that->i_setMachineState(MachineState_Paused);
8994 break;
8995 }
8996 break;
8997 }
8998
8999 case VMSTATE_RUNNING:
9000 {
9001 if ( enmOldState == VMSTATE_POWERING_ON
9002 || enmOldState == VMSTATE_RESUMING
9003 || enmOldState == VMSTATE_RUNNING_FT)
9004 {
9005 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9006
9007 if (that->mVMStateChangeCallbackDisabled)
9008 break;
9009
9010 Assert( ( ( that->mMachineState == MachineState_Starting
9011 || that->mMachineState == MachineState_Paused)
9012 && enmOldState == VMSTATE_POWERING_ON)
9013 || ( ( that->mMachineState == MachineState_Restoring
9014 || that->mMachineState == MachineState_TeleportingIn
9015 || that->mMachineState == MachineState_Paused
9016 || that->mMachineState == MachineState_Saving
9017 )
9018 && enmOldState == VMSTATE_RESUMING)
9019 || ( that->mMachineState == MachineState_FaultTolerantSyncing
9020 && enmOldState == VMSTATE_RUNNING_FT));
9021
9022 that->i_setMachineState(MachineState_Running);
9023 }
9024
9025 break;
9026 }
9027
9028 case VMSTATE_RUNNING_LS:
9029 AssertMsg( that->mMachineState == MachineState_LiveSnapshotting
9030 || that->mMachineState == MachineState_Teleporting,
9031 ("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState),
9032 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
9033 break;
9034
9035 case VMSTATE_RUNNING_FT:
9036 AssertMsg(that->mMachineState == MachineState_FaultTolerantSyncing,
9037 ("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState),
9038 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
9039 break;
9040
9041 case VMSTATE_FATAL_ERROR:
9042 {
9043 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9044
9045 if (that->mVMStateChangeCallbackDisabled)
9046 break;
9047
9048 /* Fatal errors are only for running VMs. */
9049 Assert(Global::IsOnline(that->mMachineState));
9050
9051 /* Note! 'Pause' is used here in want of something better. There
9052 * are currently only two places where fatal errors might be
9053 * raised, so it is not worth adding a new externally
9054 * visible state for this yet. */
9055 that->i_setMachineState(MachineState_Paused);
9056 break;
9057 }
9058
9059 case VMSTATE_GURU_MEDITATION:
9060 {
9061 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9062
9063 if (that->mVMStateChangeCallbackDisabled)
9064 break;
9065
9066 /* Guru are only for running VMs */
9067 Assert(Global::IsOnline(that->mMachineState));
9068
9069 that->i_setMachineState(MachineState_Stuck);
9070 break;
9071 }
9072
9073 case VMSTATE_CREATED:
9074 {
9075 /*
9076 * We have to set the secret key helper interface for the VD drivers to
9077 * get notified about missing keys.
9078 */
9079 that->i_initSecretKeyIfOnAllAttachments();
9080 break;
9081 }
9082
9083 default: /* shut up gcc */
9084 break;
9085 }
9086}
9087
9088/**
9089 * Changes the clipboard mode.
9090 *
9091 * @param aClipboardMode new clipboard mode.
9092 */
9093void Console::i_changeClipboardMode(ClipboardMode_T aClipboardMode)
9094{
9095 VMMDev *pVMMDev = m_pVMMDev;
9096 Assert(pVMMDev);
9097
9098 VBOXHGCMSVCPARM parm;
9099 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
9100
9101 switch (aClipboardMode)
9102 {
9103 default:
9104 case ClipboardMode_Disabled:
9105 LogRel(("Shared clipboard mode: Off\n"));
9106 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_OFF;
9107 break;
9108 case ClipboardMode_GuestToHost:
9109 LogRel(("Shared clipboard mode: Guest to Host\n"));
9110 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_GUEST_TO_HOST;
9111 break;
9112 case ClipboardMode_HostToGuest:
9113 LogRel(("Shared clipboard mode: Host to Guest\n"));
9114 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_HOST_TO_GUEST;
9115 break;
9116 case ClipboardMode_Bidirectional:
9117 LogRel(("Shared clipboard mode: Bidirectional\n"));
9118 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_BIDIRECTIONAL;
9119 break;
9120 }
9121
9122 pVMMDev->hgcmHostCall("VBoxSharedClipboard", VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE, 1, &parm);
9123}
9124
9125/**
9126 * Changes the drag and drop mode.
9127 *
9128 * @param aDnDMode new drag and drop mode.
9129 */
9130int Console::i_changeDnDMode(DnDMode_T aDnDMode)
9131{
9132 VMMDev *pVMMDev = m_pVMMDev;
9133 AssertPtrReturn(pVMMDev, VERR_INVALID_POINTER);
9134
9135 VBOXHGCMSVCPARM parm;
9136 RT_ZERO(parm);
9137 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
9138
9139 switch (aDnDMode)
9140 {
9141 default:
9142 case DnDMode_Disabled:
9143 LogRel(("Drag and drop mode: Off\n"));
9144 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_OFF;
9145 break;
9146 case DnDMode_GuestToHost:
9147 LogRel(("Drag and drop mode: Guest to Host\n"));
9148 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_GUEST_TO_HOST;
9149 break;
9150 case DnDMode_HostToGuest:
9151 LogRel(("Drag and drop mode: Host to Guest\n"));
9152 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_HOST_TO_GUEST;
9153 break;
9154 case DnDMode_Bidirectional:
9155 LogRel(("Drag and drop mode: Bidirectional\n"));
9156 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_BIDIRECTIONAL;
9157 break;
9158 }
9159
9160 int rc = pVMMDev->hgcmHostCall("VBoxDragAndDropSvc",
9161 DragAndDropSvc::HOST_DND_SET_MODE, 1 /* cParms */, &parm);
9162 if (RT_FAILURE(rc))
9163 LogRel(("Error changing drag and drop mode: %Rrc\n", rc));
9164
9165 return rc;
9166}
9167
9168#ifdef VBOX_WITH_USB
9169/**
9170 * Sends a request to VMM to attach the given host device.
9171 * After this method succeeds, the attached device will appear in the
9172 * mUSBDevices collection.
9173 *
9174 * @param aHostDevice device to attach
9175 *
9176 * @note Synchronously calls EMT.
9177 */
9178HRESULT Console::i_attachUSBDevice(IUSBDevice *aHostDevice, ULONG aMaskedIfs,
9179 const Utf8Str &aCaptureFilename)
9180{
9181 AssertReturn(aHostDevice, E_FAIL);
9182 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
9183
9184 HRESULT hrc;
9185
9186 /*
9187 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
9188 * method in EMT (using usbAttachCallback()).
9189 */
9190 Bstr BstrAddress;
9191 hrc = aHostDevice->COMGETTER(Address)(BstrAddress.asOutParam());
9192 ComAssertComRCRetRC(hrc);
9193
9194 Utf8Str Address(BstrAddress);
9195
9196 Bstr id;
9197 hrc = aHostDevice->COMGETTER(Id)(id.asOutParam());
9198 ComAssertComRCRetRC(hrc);
9199 Guid uuid(id);
9200
9201 BOOL fRemote = FALSE;
9202 hrc = aHostDevice->COMGETTER(Remote)(&fRemote);
9203 ComAssertComRCRetRC(hrc);
9204
9205 Bstr BstrBackend;
9206 hrc = aHostDevice->COMGETTER(Backend)(BstrBackend.asOutParam());
9207 ComAssertComRCRetRC(hrc);
9208
9209 Utf8Str Backend(BstrBackend);
9210
9211 /* Get the VM handle. */
9212 SafeVMPtr ptrVM(this);
9213 if (!ptrVM.isOk())
9214 return ptrVM.rc();
9215
9216 LogFlowThisFunc(("Proxying USB device '%s' {%RTuuid}...\n",
9217 Address.c_str(), uuid.raw()));
9218
9219 void *pvRemoteBackend = NULL;
9220 if (fRemote)
9221 {
9222 RemoteUSBDevice *pRemoteUSBDevice = static_cast<RemoteUSBDevice *>(aHostDevice);
9223 pvRemoteBackend = i_consoleVRDPServer()->USBBackendRequestPointer(pRemoteUSBDevice->clientId(), &uuid);
9224 if (!pvRemoteBackend)
9225 return E_INVALIDARG; /* The clientId is invalid then. */
9226 }
9227
9228 USBConnectionSpeed_T enmSpeed;
9229 hrc = aHostDevice->COMGETTER(Speed)(&enmSpeed);
9230 AssertComRCReturnRC(hrc);
9231
9232 int vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
9233 (PFNRT)i_usbAttachCallback, 10,
9234 this, ptrVM.rawUVM(), aHostDevice, uuid.raw(), Backend.c_str(),
9235 Address.c_str(), pvRemoteBackend, enmSpeed, aMaskedIfs,
9236 aCaptureFilename.isEmpty() ? NULL : aCaptureFilename.c_str());
9237 if (RT_SUCCESS(vrc))
9238 {
9239 /* Create a OUSBDevice and add it to the device list */
9240 ComObjPtr<OUSBDevice> pUSBDevice;
9241 pUSBDevice.createObject();
9242 hrc = pUSBDevice->init(aHostDevice);
9243 AssertComRC(hrc);
9244
9245 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9246 mUSBDevices.push_back(pUSBDevice);
9247 LogFlowFunc(("Attached device {%RTuuid}\n", pUSBDevice->i_id().raw()));
9248
9249 /* notify callbacks */
9250 alock.release();
9251 i_onUSBDeviceStateChange(pUSBDevice, true /* aAttached */, NULL);
9252 }
9253 else
9254 {
9255 Log1WarningThisFunc(("Failed to create proxy device for '%s' {%RTuuid} (%Rrc)\n", Address.c_str(), uuid.raw(), vrc));
9256
9257 switch (vrc)
9258 {
9259 case VERR_VUSB_NO_PORTS:
9260 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to attach the USB device. (No available ports on the USB controller)."));
9261 break;
9262 case VERR_VUSB_USBFS_PERMISSION:
9263 hrc = setErrorBoth(E_FAIL, vrc, tr("Not permitted to open the USB device, check usbfs options"));
9264 break;
9265 default:
9266 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to create a proxy device for the USB device. (Error: %Rrc)"), vrc);
9267 break;
9268 }
9269 }
9270
9271 return hrc;
9272}
9273
9274/**
9275 * USB device attach callback used by AttachUSBDevice().
9276 * Note that AttachUSBDevice() doesn't return until this callback is executed,
9277 * so we don't use AutoCaller and don't care about reference counters of
9278 * interface pointers passed in.
9279 *
9280 * @thread EMT
9281 * @note Locks the console object for writing.
9282 */
9283//static
9284DECLCALLBACK(int)
9285Console::i_usbAttachCallback(Console *that, PUVM pUVM, IUSBDevice *aHostDevice, PCRTUUID aUuid, const char *pszBackend,
9286 const char *aAddress, void *pvRemoteBackend, USBConnectionSpeed_T aEnmSpeed, ULONG aMaskedIfs,
9287 const char *pszCaptureFilename)
9288{
9289 RT_NOREF(aHostDevice);
9290 LogFlowFuncEnter();
9291 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
9292
9293 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
9294 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
9295
9296 VUSBSPEED enmSpeed = VUSB_SPEED_UNKNOWN;
9297 switch (aEnmSpeed)
9298 {
9299 case USBConnectionSpeed_Low: enmSpeed = VUSB_SPEED_LOW; break;
9300 case USBConnectionSpeed_Full: enmSpeed = VUSB_SPEED_FULL; break;
9301 case USBConnectionSpeed_High: enmSpeed = VUSB_SPEED_HIGH; break;
9302 case USBConnectionSpeed_Super: enmSpeed = VUSB_SPEED_SUPER; break;
9303 case USBConnectionSpeed_SuperPlus: enmSpeed = VUSB_SPEED_SUPERPLUS; break;
9304 default: AssertFailed(); break;
9305 }
9306
9307 int vrc = PDMR3UsbCreateProxyDevice(pUVM, aUuid, pszBackend, aAddress, pvRemoteBackend,
9308 enmSpeed, aMaskedIfs, pszCaptureFilename);
9309 LogFlowFunc(("vrc=%Rrc\n", vrc));
9310 LogFlowFuncLeave();
9311 return vrc;
9312}
9313
9314/**
9315 * Sends a request to VMM to detach the given host device. After this method
9316 * succeeds, the detached device will disappear from the mUSBDevices
9317 * collection.
9318 *
9319 * @param aHostDevice device to attach
9320 *
9321 * @note Synchronously calls EMT.
9322 */
9323HRESULT Console::i_detachUSBDevice(const ComObjPtr<OUSBDevice> &aHostDevice)
9324{
9325 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
9326
9327 /* Get the VM handle. */
9328 SafeVMPtr ptrVM(this);
9329 if (!ptrVM.isOk())
9330 return ptrVM.rc();
9331
9332 /* if the device is attached, then there must at least one USB hub. */
9333 AssertReturn(PDMR3UsbHasHub(ptrVM.rawUVM()), E_FAIL);
9334
9335 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9336 LogFlowThisFunc(("Detaching USB proxy device {%RTuuid}...\n",
9337 aHostDevice->i_id().raw()));
9338
9339 /*
9340 * If this was a remote device, release the backend pointer.
9341 * The pointer was requested in usbAttachCallback.
9342 */
9343 BOOL fRemote = FALSE;
9344
9345 HRESULT hrc2 = aHostDevice->COMGETTER(Remote)(&fRemote);
9346 if (FAILED(hrc2))
9347 i_setErrorStatic(hrc2, "GetRemote() failed");
9348
9349 PCRTUUID pUuid = aHostDevice->i_id().raw();
9350 if (fRemote)
9351 {
9352 Guid guid(*pUuid);
9353 i_consoleVRDPServer()->USBBackendReleasePointer(&guid);
9354 }
9355
9356 alock.release();
9357 int vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
9358 (PFNRT)i_usbDetachCallback, 5,
9359 this, ptrVM.rawUVM(), pUuid);
9360 if (RT_SUCCESS(vrc))
9361 {
9362 LogFlowFunc(("Detached device {%RTuuid}\n", pUuid));
9363
9364 /* notify callbacks */
9365 i_onUSBDeviceStateChange(aHostDevice, false /* aAttached */, NULL);
9366 }
9367
9368 ComAssertRCRet(vrc, E_FAIL);
9369
9370 return S_OK;
9371}
9372
9373/**
9374 * USB device detach callback used by DetachUSBDevice().
9375 *
9376 * Note that DetachUSBDevice() doesn't return until this callback is executed,
9377 * so we don't use AutoCaller and don't care about reference counters of
9378 * interface pointers passed in.
9379 *
9380 * @thread EMT
9381 */
9382//static
9383DECLCALLBACK(int)
9384Console::i_usbDetachCallback(Console *that, PUVM pUVM, PCRTUUID aUuid)
9385{
9386 LogFlowFuncEnter();
9387 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
9388
9389 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
9390 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
9391
9392 int vrc = PDMR3UsbDetachDevice(pUVM, aUuid);
9393
9394 LogFlowFunc(("vrc=%Rrc\n", vrc));
9395 LogFlowFuncLeave();
9396 return vrc;
9397}
9398#endif /* VBOX_WITH_USB */
9399
9400/* Note: FreeBSD needs this whether netflt is used or not. */
9401#if ((defined(RT_OS_LINUX) && !defined(VBOX_WITH_NETFLT)) || defined(RT_OS_FREEBSD))
9402/**
9403 * Helper function to handle host interface device creation and attachment.
9404 *
9405 * @param networkAdapter the network adapter which attachment should be reset
9406 * @return COM status code
9407 *
9408 * @note The caller must lock this object for writing.
9409 *
9410 * @todo Move this back into the driver!
9411 */
9412HRESULT Console::i_attachToTapInterface(INetworkAdapter *networkAdapter)
9413{
9414 LogFlowThisFunc(("\n"));
9415 /* sanity check */
9416 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9417
9418# ifdef VBOX_STRICT
9419 /* paranoia */
9420 NetworkAttachmentType_T attachment;
9421 networkAdapter->COMGETTER(AttachmentType)(&attachment);
9422 Assert(attachment == NetworkAttachmentType_Bridged);
9423# endif /* VBOX_STRICT */
9424
9425 HRESULT rc = S_OK;
9426
9427 ULONG slot = 0;
9428 rc = networkAdapter->COMGETTER(Slot)(&slot);
9429 AssertComRC(rc);
9430
9431# ifdef RT_OS_LINUX
9432 /*
9433 * Allocate a host interface device
9434 */
9435 int vrc = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
9436 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
9437 if (RT_SUCCESS(vrc))
9438 {
9439 /*
9440 * Set/obtain the tap interface.
9441 */
9442 struct ifreq IfReq;
9443 RT_ZERO(IfReq);
9444 /* The name of the TAP interface we are using */
9445 Bstr tapDeviceName;
9446 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
9447 if (FAILED(rc))
9448 tapDeviceName.setNull(); /* Is this necessary? */
9449 if (tapDeviceName.isEmpty())
9450 {
9451 LogRel(("No TAP device name was supplied.\n"));
9452 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
9453 }
9454
9455 if (SUCCEEDED(rc))
9456 {
9457 /* If we are using a static TAP device then try to open it. */
9458 Utf8Str str(tapDeviceName);
9459 RTStrCopy(IfReq.ifr_name, sizeof(IfReq.ifr_name), str.c_str()); /** @todo bitch about names which are too long... */
9460 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
9461 vrc = ioctl(RTFileToNative(maTapFD[slot]), TUNSETIFF, &IfReq);
9462 if (vrc != 0)
9463 {
9464 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
9465 rc = setErrorBoth(E_FAIL, vrc, tr("Failed to open the host network interface %ls"), tapDeviceName.raw());
9466 }
9467 }
9468 if (SUCCEEDED(rc))
9469 {
9470 /*
9471 * Make it pollable.
9472 */
9473 if (fcntl(RTFileToNative(maTapFD[slot]), F_SETFL, O_NONBLOCK) != -1)
9474 {
9475 Log(("i_attachToTapInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
9476 /*
9477 * Here is the right place to communicate the TAP file descriptor and
9478 * the host interface name to the server if/when it becomes really
9479 * necessary.
9480 */
9481 maTAPDeviceName[slot] = tapDeviceName;
9482 vrc = VINF_SUCCESS;
9483 }
9484 else
9485 {
9486 int iErr = errno;
9487
9488 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
9489 vrc = VERR_HOSTIF_BLOCKING;
9490 rc = setErrorBoth(E_FAIL, vrc, tr("could not set up the host networking device for non blocking access: %s"),
9491 strerror(errno));
9492 }
9493 }
9494 }
9495 else
9496 {
9497 LogRel(("Configuration error: Failed to open /dev/net/tun rc=%Rrc\n", vrc));
9498 switch (vrc)
9499 {
9500 case VERR_ACCESS_DENIED:
9501 /* will be handled by our caller */
9502 rc = vrc;
9503 break;
9504 default:
9505 rc = setErrorBoth(E_FAIL, vrc, tr("Could not set up the host networking device: %Rrc"), vrc);
9506 break;
9507 }
9508 }
9509
9510# elif defined(RT_OS_FREEBSD)
9511 /*
9512 * Set/obtain the tap interface.
9513 */
9514 /* The name of the TAP interface we are using */
9515 Bstr tapDeviceName;
9516 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
9517 if (FAILED(rc))
9518 tapDeviceName.setNull(); /* Is this necessary? */
9519 if (tapDeviceName.isEmpty())
9520 {
9521 LogRel(("No TAP device name was supplied.\n"));
9522 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
9523 }
9524 char szTapdev[1024] = "/dev/";
9525 /* If we are using a static TAP device then try to open it. */
9526 Utf8Str str(tapDeviceName);
9527 if (str.length() + strlen(szTapdev) <= sizeof(szTapdev))
9528 strcat(szTapdev, str.c_str());
9529 else
9530 memcpy(szTapdev + strlen(szTapdev), str.c_str(),
9531 sizeof(szTapdev) - strlen(szTapdev) - 1); /** @todo bitch about names which are too long... */
9532 int vrc = RTFileOpen(&maTapFD[slot], szTapdev,
9533 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT | RTFILE_O_NON_BLOCK);
9534
9535 if (RT_SUCCESS(vrc))
9536 maTAPDeviceName[slot] = tapDeviceName;
9537 else
9538 {
9539 switch (vrc)
9540 {
9541 case VERR_ACCESS_DENIED:
9542 /* will be handled by our caller */
9543 rc = vrc;
9544 break;
9545 default:
9546 rc = setErrorBoth(E_FAIL, vrc, tr("Failed to open the host network interface %ls"), tapDeviceName.raw());
9547 break;
9548 }
9549 }
9550# else
9551# error "huh?"
9552# endif
9553 /* in case of failure, cleanup. */
9554 if (RT_FAILURE(vrc) && SUCCEEDED(rc))
9555 {
9556 LogRel(("General failure attaching to host interface\n"));
9557 rc = setErrorBoth(E_FAIL, vrc, tr("General failure attaching to host interface"));
9558 }
9559 LogFlowThisFunc(("rc=%Rhrc\n", rc));
9560 return rc;
9561}
9562
9563
9564/**
9565 * Helper function to handle detachment from a host interface
9566 *
9567 * @param networkAdapter the network adapter which attachment should be reset
9568 * @return COM status code
9569 *
9570 * @note The caller must lock this object for writing.
9571 *
9572 * @todo Move this back into the driver!
9573 */
9574HRESULT Console::i_detachFromTapInterface(INetworkAdapter *networkAdapter)
9575{
9576 /* sanity check */
9577 LogFlowThisFunc(("\n"));
9578 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9579
9580 HRESULT rc = S_OK;
9581# ifdef VBOX_STRICT
9582 /* paranoia */
9583 NetworkAttachmentType_T attachment;
9584 networkAdapter->COMGETTER(AttachmentType)(&attachment);
9585 Assert(attachment == NetworkAttachmentType_Bridged);
9586# endif /* VBOX_STRICT */
9587
9588 ULONG slot = 0;
9589 rc = networkAdapter->COMGETTER(Slot)(&slot);
9590 AssertComRC(rc);
9591
9592 /* is there an open TAP device? */
9593 if (maTapFD[slot] != NIL_RTFILE)
9594 {
9595 /*
9596 * Close the file handle.
9597 */
9598 Bstr tapDeviceName, tapTerminateApplication;
9599 bool isStatic = true;
9600 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
9601 if (FAILED(rc) || tapDeviceName.isEmpty())
9602 {
9603 /* If the name is empty, this is a dynamic TAP device, so close it now,
9604 so that the termination script can remove the interface. Otherwise we still
9605 need the FD to pass to the termination script. */
9606 isStatic = false;
9607 int rcVBox = RTFileClose(maTapFD[slot]);
9608 AssertRC(rcVBox);
9609 maTapFD[slot] = NIL_RTFILE;
9610 }
9611 if (isStatic)
9612 {
9613 /* If we are using a static TAP device, we close it now, after having called the
9614 termination script. */
9615 int rcVBox = RTFileClose(maTapFD[slot]);
9616 AssertRC(rcVBox);
9617 }
9618 /* the TAP device name and handle are no longer valid */
9619 maTapFD[slot] = NIL_RTFILE;
9620 maTAPDeviceName[slot] = "";
9621 }
9622 LogFlowThisFunc(("returning %d\n", rc));
9623 return rc;
9624}
9625#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
9626
9627/**
9628 * Called at power down to terminate host interface networking.
9629 *
9630 * @note The caller must lock this object for writing.
9631 */
9632HRESULT Console::i_powerDownHostInterfaces()
9633{
9634 LogFlowThisFunc(("\n"));
9635
9636 /* sanity check */
9637 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9638
9639 /*
9640 * host interface termination handling
9641 */
9642 HRESULT rc = S_OK;
9643 ComPtr<IVirtualBox> pVirtualBox;
9644 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
9645 ComPtr<ISystemProperties> pSystemProperties;
9646 if (pVirtualBox)
9647 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
9648 ChipsetType_T chipsetType = ChipsetType_PIIX3;
9649 mMachine->COMGETTER(ChipsetType)(&chipsetType);
9650 ULONG maxNetworkAdapters = 0;
9651 if (pSystemProperties)
9652 pSystemProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters);
9653
9654 for (ULONG slot = 0; slot < maxNetworkAdapters; slot++)
9655 {
9656 ComPtr<INetworkAdapter> pNetworkAdapter;
9657 rc = mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
9658 if (FAILED(rc)) break;
9659
9660 BOOL enabled = FALSE;
9661 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
9662 if (!enabled)
9663 continue;
9664
9665 NetworkAttachmentType_T attachment;
9666 pNetworkAdapter->COMGETTER(AttachmentType)(&attachment);
9667 if (attachment == NetworkAttachmentType_Bridged)
9668 {
9669#if ((defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)) && !defined(VBOX_WITH_NETFLT))
9670 HRESULT rc2 = i_detachFromTapInterface(pNetworkAdapter);
9671 if (FAILED(rc2) && SUCCEEDED(rc))
9672 rc = rc2;
9673#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
9674 }
9675 }
9676
9677 return rc;
9678}
9679
9680
9681/**
9682 * Process callback handler for VMR3LoadFromFile, VMR3LoadFromStream, VMR3Save
9683 * and VMR3Teleport.
9684 *
9685 * @param pUVM The user mode VM handle.
9686 * @param uPercent Completion percentage (0-100).
9687 * @param pvUser Pointer to an IProgress instance.
9688 * @return VINF_SUCCESS.
9689 */
9690/*static*/
9691DECLCALLBACK(int) Console::i_stateProgressCallback(PUVM pUVM, unsigned uPercent, void *pvUser)
9692{
9693 IProgress *pProgress = static_cast<IProgress *>(pvUser);
9694
9695 /* update the progress object */
9696 if (pProgress)
9697 {
9698 ComPtr<IInternalProgressControl> pProgressControl(pProgress);
9699 AssertReturn(!!pProgressControl, VERR_INVALID_PARAMETER);
9700 pProgressControl->SetCurrentOperationProgress(uPercent);
9701 }
9702
9703 NOREF(pUVM);
9704 return VINF_SUCCESS;
9705}
9706
9707/**
9708 * @copydoc FNVMATERROR
9709 *
9710 * @remarks Might be some tiny serialization concerns with access to the string
9711 * object here...
9712 */
9713/*static*/ DECLCALLBACK(void)
9714Console::i_genericVMSetErrorCallback(PUVM pUVM, void *pvUser, int rc, RT_SRC_POS_DECL,
9715 const char *pszFormat, va_list args)
9716{
9717 RT_SRC_POS_NOREF();
9718 Utf8Str *pErrorText = (Utf8Str *)pvUser;
9719 AssertPtr(pErrorText);
9720
9721 /* We ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users. */
9722 va_list va2;
9723 va_copy(va2, args);
9724
9725 /* Append to any the existing error message. */
9726 if (pErrorText->length())
9727 *pErrorText = Utf8StrFmt("%s.\n%N (%Rrc)", pErrorText->c_str(),
9728 pszFormat, &va2, rc, rc);
9729 else
9730 *pErrorText = Utf8StrFmt("%N (%Rrc)", pszFormat, &va2, rc, rc);
9731
9732 va_end(va2);
9733
9734 NOREF(pUVM);
9735}
9736
9737/**
9738 * VM runtime error callback function (FNVMATRUNTIMEERROR).
9739 *
9740 * See VMSetRuntimeError for the detailed description of parameters.
9741 *
9742 * @param pUVM The user mode VM handle. Ignored, so passing NULL
9743 * is fine.
9744 * @param pvUser The user argument, pointer to the Console instance.
9745 * @param fFlags The action flags. See VMSETRTERR_FLAGS_*.
9746 * @param pszErrorId Error ID string.
9747 * @param pszFormat Error message format string.
9748 * @param va Error message arguments.
9749 * @thread EMT.
9750 */
9751/* static */ DECLCALLBACK(void)
9752Console::i_atVMRuntimeErrorCallback(PUVM pUVM, void *pvUser, uint32_t fFlags,
9753 const char *pszErrorId, const char *pszFormat, va_list va)
9754{
9755 bool const fFatal = !!(fFlags & VMSETRTERR_FLAGS_FATAL);
9756 LogFlowFuncEnter();
9757
9758 Console *that = static_cast<Console *>(pvUser);
9759 AssertReturnVoid(that);
9760
9761 Utf8Str message(pszFormat, va);
9762
9763 LogRel(("Console: VM runtime error: fatal=%RTbool, errorID=%s message=\"%s\"\n",
9764 fFatal, pszErrorId, message.c_str()));
9765
9766 that->i_onRuntimeError(BOOL(fFatal), Bstr(pszErrorId).raw(), Bstr(message).raw());
9767
9768 LogFlowFuncLeave(); NOREF(pUVM);
9769}
9770
9771/**
9772 * Captures USB devices that match filters of the VM.
9773 * Called at VM startup.
9774 *
9775 * @param pUVM The VM handle.
9776 */
9777HRESULT Console::i_captureUSBDevices(PUVM pUVM)
9778{
9779 RT_NOREF(pUVM);
9780 LogFlowThisFunc(("\n"));
9781
9782 /* sanity check */
9783 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
9784 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9785
9786 /* If the machine has a USB controller, ask the USB proxy service to
9787 * capture devices */
9788 if (mfVMHasUsbController)
9789 {
9790 /* release the lock before calling Host in VBoxSVC since Host may call
9791 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
9792 * produce an inter-process dead-lock otherwise. */
9793 alock.release();
9794
9795 HRESULT hrc = mControl->AutoCaptureUSBDevices();
9796 ComAssertComRCRetRC(hrc);
9797 }
9798
9799 return S_OK;
9800}
9801
9802
9803/**
9804 * Detach all USB device which are attached to the VM for the
9805 * purpose of clean up and such like.
9806 */
9807void Console::i_detachAllUSBDevices(bool aDone)
9808{
9809 LogFlowThisFunc(("aDone=%RTbool\n", aDone));
9810
9811 /* sanity check */
9812 AssertReturnVoid(!isWriteLockOnCurrentThread());
9813 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9814
9815 mUSBDevices.clear();
9816
9817 /* release the lock before calling Host in VBoxSVC since Host may call
9818 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
9819 * produce an inter-process dead-lock otherwise. */
9820 alock.release();
9821
9822 mControl->DetachAllUSBDevices(aDone);
9823}
9824
9825/**
9826 * @note Locks this object for writing.
9827 */
9828void Console::i_processRemoteUSBDevices(uint32_t u32ClientId, VRDEUSBDEVICEDESC *pDevList, uint32_t cbDevList, bool fDescExt)
9829{
9830 LogFlowThisFuncEnter();
9831 LogFlowThisFunc(("u32ClientId = %d, pDevList=%p, cbDevList = %d, fDescExt = %d\n",
9832 u32ClientId, pDevList, cbDevList, fDescExt));
9833
9834 AutoCaller autoCaller(this);
9835 if (!autoCaller.isOk())
9836 {
9837 /* Console has been already uninitialized, deny request */
9838 AssertMsgFailed(("Console is already uninitialized\n"));
9839 LogFlowThisFunc(("Console is already uninitialized\n"));
9840 LogFlowThisFuncLeave();
9841 return;
9842 }
9843
9844 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9845
9846 /*
9847 * Mark all existing remote USB devices as dirty.
9848 */
9849 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
9850 it != mRemoteUSBDevices.end();
9851 ++it)
9852 {
9853 (*it)->dirty(true);
9854 }
9855
9856 /*
9857 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
9858 */
9859 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
9860 VRDEUSBDEVICEDESC *e = pDevList;
9861
9862 /* The cbDevList condition must be checked first, because the function can
9863 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
9864 */
9865 while (cbDevList >= 2 && e->oNext)
9866 {
9867 /* Sanitize incoming strings in case they aren't valid UTF-8. */
9868 if (e->oManufacturer)
9869 RTStrPurgeEncoding((char *)e + e->oManufacturer);
9870 if (e->oProduct)
9871 RTStrPurgeEncoding((char *)e + e->oProduct);
9872 if (e->oSerialNumber)
9873 RTStrPurgeEncoding((char *)e + e->oSerialNumber);
9874
9875 LogFlowThisFunc(("vendor %04X, product %04X, name = %s\n",
9876 e->idVendor, e->idProduct,
9877 e->oProduct? (char *)e + e->oProduct: ""));
9878
9879 bool fNewDevice = true;
9880
9881 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
9882 it != mRemoteUSBDevices.end();
9883 ++it)
9884 {
9885 if ((*it)->devId() == e->id
9886 && (*it)->clientId() == u32ClientId)
9887 {
9888 /* The device is already in the list. */
9889 (*it)->dirty(false);
9890 fNewDevice = false;
9891 break;
9892 }
9893 }
9894
9895 if (fNewDevice)
9896 {
9897 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
9898 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""));
9899
9900 /* Create the device object and add the new device to list. */
9901 ComObjPtr<RemoteUSBDevice> pUSBDevice;
9902 pUSBDevice.createObject();
9903 pUSBDevice->init(u32ClientId, e, fDescExt);
9904
9905 mRemoteUSBDevices.push_back(pUSBDevice);
9906
9907 /* Check if the device is ok for current USB filters. */
9908 BOOL fMatched = FALSE;
9909 ULONG fMaskedIfs = 0;
9910
9911 HRESULT hrc = mControl->RunUSBDeviceFilters(pUSBDevice, &fMatched, &fMaskedIfs);
9912
9913 AssertComRC(hrc);
9914
9915 LogFlowThisFunc(("USB filters return %d %#x\n", fMatched, fMaskedIfs));
9916
9917 if (fMatched)
9918 {
9919 alock.release();
9920 hrc = i_onUSBDeviceAttach(pUSBDevice, NULL, fMaskedIfs, Utf8Str());
9921 alock.acquire();
9922
9923 /// @todo (r=dmik) warning reporting subsystem
9924
9925 if (hrc == S_OK)
9926 {
9927 LogFlowThisFunc(("Device attached\n"));
9928 pUSBDevice->captured(true);
9929 }
9930 }
9931 }
9932
9933 if (cbDevList < e->oNext)
9934 {
9935 Log1WarningThisFunc(("cbDevList %d > oNext %d\n", cbDevList, e->oNext));
9936 break;
9937 }
9938
9939 cbDevList -= e->oNext;
9940
9941 e = (VRDEUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
9942 }
9943
9944 /*
9945 * Remove dirty devices, that is those which are not reported by the server anymore.
9946 */
9947 for (;;)
9948 {
9949 ComObjPtr<RemoteUSBDevice> pUSBDevice;
9950
9951 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
9952 while (it != mRemoteUSBDevices.end())
9953 {
9954 if ((*it)->dirty())
9955 {
9956 pUSBDevice = *it;
9957 break;
9958 }
9959
9960 ++it;
9961 }
9962
9963 if (!pUSBDevice)
9964 {
9965 break;
9966 }
9967
9968 USHORT vendorId = 0;
9969 pUSBDevice->COMGETTER(VendorId)(&vendorId);
9970
9971 USHORT productId = 0;
9972 pUSBDevice->COMGETTER(ProductId)(&productId);
9973
9974 Bstr product;
9975 pUSBDevice->COMGETTER(Product)(product.asOutParam());
9976
9977 LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
9978 vendorId, productId, product.raw()));
9979
9980 /* Detach the device from VM. */
9981 if (pUSBDevice->captured())
9982 {
9983 Bstr uuid;
9984 pUSBDevice->COMGETTER(Id)(uuid.asOutParam());
9985 alock.release();
9986 i_onUSBDeviceDetach(uuid.raw(), NULL);
9987 alock.acquire();
9988 }
9989
9990 /* And remove it from the list. */
9991 mRemoteUSBDevices.erase(it);
9992 }
9993
9994 LogFlowThisFuncLeave();
9995}
9996
9997/**
9998 * Progress cancelation callback for fault tolerance VM poweron
9999 */
10000static void faultToleranceProgressCancelCallback(void *pvUser)
10001{
10002 PUVM pUVM = (PUVM)pvUser;
10003
10004 if (pUVM)
10005 FTMR3CancelStandby(pUVM);
10006}
10007
10008/**
10009 * Worker called by VMPowerUpTask::handler to start the VM (also from saved
10010 * state) and track progress.
10011 *
10012 * @param pTask The power up task.
10013 *
10014 * @note Locks the Console object for writing.
10015 */
10016/*static*/
10017void Console::i_powerUpThreadTask(VMPowerUpTask *pTask)
10018{
10019 LogFlowFuncEnter();
10020
10021 AssertReturnVoid(pTask);
10022 AssertReturnVoid(!pTask->mConsole.isNull());
10023 AssertReturnVoid(!pTask->mProgress.isNull());
10024
10025 VirtualBoxBase::initializeComForThread();
10026
10027 HRESULT rc = S_OK;
10028 int vrc = VINF_SUCCESS;
10029
10030 /* Set up a build identifier so that it can be seen from core dumps what
10031 * exact build was used to produce the core. */
10032 static char saBuildID[48];
10033 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%u %s%s%s%s",
10034 "BU", "IL", "DI", "D", RTBldCfgVersion(), RTBldCfgRevision(), "BU", "IL", "DI", "D");
10035
10036 ComObjPtr<Console> pConsole = pTask->mConsole;
10037
10038 /* Note: no need to use AutoCaller because VMPowerUpTask does that */
10039
10040 /* The lock is also used as a signal from the task initiator (which
10041 * releases it only after RTThreadCreate()) that we can start the job */
10042 AutoWriteLock alock(pConsole COMMA_LOCKVAL_SRC_POS);
10043
10044 /* sanity */
10045 Assert(pConsole->mpUVM == NULL);
10046
10047 try
10048 {
10049 // Create the VMM device object, which starts the HGCM thread; do this only
10050 // once for the console, for the pathological case that the same console
10051 // object is used to power up a VM twice.
10052 if (!pConsole->m_pVMMDev)
10053 {
10054 pConsole->m_pVMMDev = new VMMDev(pConsole);
10055 AssertReturnVoid(pConsole->m_pVMMDev);
10056 }
10057
10058 /* wait for auto reset ops to complete so that we can successfully lock
10059 * the attached hard disks by calling LockMedia() below */
10060 for (VMPowerUpTask::ProgressList::const_iterator
10061 it = pTask->hardDiskProgresses.begin();
10062 it != pTask->hardDiskProgresses.end(); ++it)
10063 {
10064 HRESULT rc2 = (*it)->WaitForCompletion(-1);
10065 AssertComRC(rc2);
10066
10067 rc = pTask->mProgress->SetNextOperation(BstrFmt(tr("Disk Image Reset Operation - Immutable Image")).raw(), 1);
10068 AssertComRCReturnVoid(rc);
10069 }
10070
10071 /*
10072 * Lock attached media. This method will also check their accessibility.
10073 * If we're a teleporter, we'll have to postpone this action so we can
10074 * migrate between local processes.
10075 *
10076 * Note! The media will be unlocked automatically by
10077 * SessionMachine::i_setMachineState() when the VM is powered down.
10078 */
10079 if ( !pTask->mTeleporterEnabled
10080 && pTask->mEnmFaultToleranceState != FaultToleranceState_Standby)
10081 {
10082 rc = pConsole->mControl->LockMedia();
10083 if (FAILED(rc)) throw rc;
10084 }
10085
10086 /* Create the VRDP server. In case of headless operation, this will
10087 * also create the framebuffer, required at VM creation.
10088 */
10089 ConsoleVRDPServer *server = pConsole->i_consoleVRDPServer();
10090 Assert(server);
10091
10092 /* Does VRDP server call Console from the other thread?
10093 * Not sure (and can change), so release the lock just in case.
10094 */
10095 alock.release();
10096 vrc = server->Launch();
10097 alock.acquire();
10098
10099 if (vrc != VINF_SUCCESS)
10100 {
10101 Utf8Str errMsg = pConsole->VRDPServerErrorToMsg(vrc);
10102 if ( RT_FAILURE(vrc)
10103 && vrc != VERR_NET_ADDRESS_IN_USE) /* not fatal */
10104 throw i_setErrorStaticBoth(E_FAIL, vrc, errMsg.c_str());
10105 }
10106
10107 ComPtr<IMachine> pMachine = pConsole->i_machine();
10108 ULONG cCpus = 1;
10109 pMachine->COMGETTER(CPUCount)(&cCpus);
10110
10111 /*
10112 * Create the VM
10113 *
10114 * Note! Release the lock since EMT will call Console. It's safe because
10115 * mMachineState is either Starting or Restoring state here.
10116 */
10117 alock.release();
10118
10119 PVM pVM;
10120 vrc = VMR3Create(cCpus,
10121 pConsole->mpVmm2UserMethods,
10122 Console::i_genericVMSetErrorCallback,
10123 &pTask->mErrorMsg,
10124 pTask->mConfigConstructor,
10125 static_cast<Console *>(pConsole),
10126 &pVM, NULL);
10127 alock.acquire();
10128
10129#ifdef VBOX_WITH_AUDIO_VRDE
10130 /* Attach the VRDE audio driver. */
10131 IVRDEServer *pVRDEServer = pConsole->i_getVRDEServer();
10132 if (pVRDEServer)
10133 {
10134 BOOL fVRDEEnabled = FALSE;
10135 rc = pVRDEServer->COMGETTER(Enabled)(&fVRDEEnabled);
10136 AssertComRCReturnVoid(rc);
10137
10138 if ( fVRDEEnabled
10139 && pConsole->mAudioVRDE)
10140 pConsole->mAudioVRDE->doAttachDriverViaEmt(pConsole->mpUVM, &alock);
10141 }
10142#endif
10143
10144 /* Enable client connections to the VRDP server. */
10145 pConsole->i_consoleVRDPServer()->EnableConnections();
10146
10147#ifdef VBOX_WITH_RECORDING
10148 ComPtr<IRecordingSettings> recordingSettings;
10149 rc = pConsole->mMachine->COMGETTER(RecordingSettings)(recordingSettings.asOutParam());
10150 AssertComRCReturnVoid(rc);
10151
10152 BOOL fRecordingEnabled;
10153 rc = recordingSettings->COMGETTER(Enabled)(&fRecordingEnabled);
10154 AssertComRCReturnVoid(rc);
10155
10156 if (fRecordingEnabled)
10157 {
10158 int vrc2 = pConsole->i_recordingEnable(fRecordingEnabled, &alock);
10159 if (RT_SUCCESS(vrc2))
10160 {
10161 fireRecordingChangedEvent(pConsole->mEventSource);
10162 }
10163 else
10164 LogRel(("Recording: Failed with %Rrc on VM power up\n", vrc2));
10165
10166 /** Note: Do not use vrc here, as starting the video recording isn't critical to
10167 * powering up the VM. */
10168 }
10169#endif
10170
10171 if (RT_SUCCESS(vrc))
10172 {
10173 do
10174 {
10175 /*
10176 * Register our load/save state file handlers
10177 */
10178 vrc = SSMR3RegisterExternal(pConsole->mpUVM, sSSMConsoleUnit, 0 /*iInstance*/, sSSMConsoleVer, 0 /* cbGuess */,
10179 NULL, NULL, NULL,
10180 NULL, i_saveStateFileExec, NULL,
10181 NULL, i_loadStateFileExec, NULL,
10182 static_cast<Console *>(pConsole));
10183 AssertRCBreak(vrc);
10184
10185 vrc = static_cast<Console *>(pConsole)->i_getDisplay()->i_registerSSM(pConsole->mpUVM);
10186 AssertRC(vrc);
10187 if (RT_FAILURE(vrc))
10188 break;
10189
10190 /*
10191 * Synchronize debugger settings
10192 */
10193 MachineDebugger *machineDebugger = pConsole->i_getMachineDebugger();
10194 if (machineDebugger)
10195 machineDebugger->i_flushQueuedSettings();
10196
10197 /*
10198 * Shared Folders
10199 */
10200 if (pConsole->m_pVMMDev->isShFlActive())
10201 {
10202 /* Does the code below call Console from the other thread?
10203 * Not sure, so release the lock just in case. */
10204 alock.release();
10205
10206 for (SharedFolderDataMap::const_iterator it = pTask->mSharedFolders.begin();
10207 it != pTask->mSharedFolders.end();
10208 ++it)
10209 {
10210 const SharedFolderData &d = it->second;
10211 rc = pConsole->i_createSharedFolder(it->first, d);
10212 if (FAILED(rc))
10213 {
10214 ErrorInfoKeeper eik;
10215 pConsole->i_atVMRuntimeErrorCallbackF(0, "BrokenSharedFolder",
10216 N_("The shared folder '%s' could not be set up: %ls.\n"
10217 "The shared folder setup will not be complete. It is recommended to power down the virtual "
10218 "machine and fix the shared folder settings while the machine is not running"),
10219 it->first.c_str(), eik.getText().raw());
10220 }
10221 }
10222 if (FAILED(rc))
10223 rc = S_OK; // do not fail with broken shared folders
10224
10225 /* acquire the lock again */
10226 alock.acquire();
10227 }
10228
10229 /* release the lock before a lengthy operation */
10230 alock.release();
10231
10232 /*
10233 * Capture USB devices.
10234 */
10235 rc = pConsole->i_captureUSBDevices(pConsole->mpUVM);
10236 if (FAILED(rc))
10237 {
10238 alock.acquire();
10239 break;
10240 }
10241
10242 /* Load saved state? */
10243 if (pTask->mSavedStateFile.length())
10244 {
10245 LogFlowFunc(("Restoring saved state from '%s'...\n", pTask->mSavedStateFile.c_str()));
10246
10247 vrc = VMR3LoadFromFile(pConsole->mpUVM,
10248 pTask->mSavedStateFile.c_str(),
10249 Console::i_stateProgressCallback,
10250 static_cast<IProgress *>(pTask->mProgress));
10251
10252 if (RT_SUCCESS(vrc))
10253 {
10254 if (pTask->mStartPaused)
10255 /* done */
10256 pConsole->i_setMachineState(MachineState_Paused);
10257 else
10258 {
10259 /* Start/Resume the VM execution */
10260#ifdef VBOX_WITH_EXTPACK
10261 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM);
10262#endif
10263 if (RT_SUCCESS(vrc))
10264 vrc = VMR3Resume(pConsole->mpUVM, VMRESUMEREASON_STATE_RESTORED);
10265 AssertLogRelRC(vrc);
10266 }
10267 }
10268
10269 /* Power off in case we failed loading or resuming the VM */
10270 if (RT_FAILURE(vrc))
10271 {
10272 int vrc2 = VMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
10273#ifdef VBOX_WITH_EXTPACK
10274 pConsole->mptrExtPackManager->i_callAllVmPowerOffHooks(pConsole, pVM);
10275#endif
10276 }
10277 }
10278 else if (pTask->mTeleporterEnabled)
10279 {
10280 /* -> ConsoleImplTeleporter.cpp */
10281 bool fPowerOffOnFailure;
10282 rc = pConsole->i_teleporterTrg(pConsole->mpUVM, pMachine, &pTask->mErrorMsg, pTask->mStartPaused,
10283 pTask->mProgress, &fPowerOffOnFailure);
10284 if (FAILED(rc) && fPowerOffOnFailure)
10285 {
10286 ErrorInfoKeeper eik;
10287 int vrc2 = VMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
10288#ifdef VBOX_WITH_EXTPACK
10289 pConsole->mptrExtPackManager->i_callAllVmPowerOffHooks(pConsole, pVM);
10290#endif
10291 }
10292 }
10293 else if (pTask->mEnmFaultToleranceState != FaultToleranceState_Inactive)
10294 {
10295 /*
10296 * Get the config.
10297 */
10298 ULONG uPort;
10299 rc = pMachine->COMGETTER(FaultTolerancePort)(&uPort);
10300 if (SUCCEEDED(rc))
10301 {
10302 ULONG uInterval;
10303 rc = pMachine->COMGETTER(FaultToleranceSyncInterval)(&uInterval);
10304 if (SUCCEEDED(rc))
10305 {
10306 Bstr bstrAddress;
10307 rc = pMachine->COMGETTER(FaultToleranceAddress)(bstrAddress.asOutParam());
10308 if (SUCCEEDED(rc))
10309 {
10310 Bstr bstrPassword;
10311 rc = pMachine->COMGETTER(FaultTolerancePassword)(bstrPassword.asOutParam());
10312 if (SUCCEEDED(rc))
10313 {
10314 if (pTask->mProgress->i_setCancelCallback(faultToleranceProgressCancelCallback,
10315 pConsole->mpUVM))
10316 {
10317 if (SUCCEEDED(rc))
10318 {
10319 Utf8Str strAddress(bstrAddress);
10320 const char *pszAddress = strAddress.isEmpty() ? NULL : strAddress.c_str();
10321 Utf8Str strPassword(bstrPassword);
10322 const char *pszPassword = strPassword.isEmpty() ? NULL : strPassword.c_str();
10323
10324 /* Power on the FT enabled VM. */
10325#ifdef VBOX_WITH_EXTPACK
10326 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM);
10327#endif
10328 if (RT_SUCCESS(vrc))
10329 vrc = FTMR3PowerOn(pConsole->mpUVM,
10330 pTask->mEnmFaultToleranceState == FaultToleranceState_Master /* fMaster */,
10331 uInterval,
10332 pszAddress,
10333 uPort,
10334 pszPassword);
10335 AssertLogRelRC(vrc);
10336 }
10337 pTask->mProgress->i_setCancelCallback(NULL, NULL);
10338 }
10339 else
10340 rc = E_FAIL;
10341
10342 }
10343 }
10344 }
10345 }
10346 }
10347 else if (pTask->mStartPaused)
10348 /* done */
10349 pConsole->i_setMachineState(MachineState_Paused);
10350 else
10351 {
10352 /* Power on the VM (i.e. start executing) */
10353#ifdef VBOX_WITH_EXTPACK
10354 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM);
10355#endif
10356 if (RT_SUCCESS(vrc))
10357 vrc = VMR3PowerOn(pConsole->mpUVM);
10358 AssertLogRelRC(vrc);
10359 }
10360
10361 /* acquire the lock again */
10362 alock.acquire();
10363 }
10364 while (0);
10365
10366 /* On failure, destroy the VM */
10367 if (FAILED(rc) || RT_FAILURE(vrc))
10368 {
10369 /* preserve existing error info */
10370 ErrorInfoKeeper eik;
10371
10372 /* powerDown() will call VMR3Destroy() and do all necessary
10373 * cleanup (VRDP, USB devices) */
10374 alock.release();
10375 HRESULT rc2 = pConsole->i_powerDown();
10376 alock.acquire();
10377 AssertComRC(rc2);
10378 }
10379 else
10380 {
10381 /*
10382 * Deregister the VMSetError callback. This is necessary as the
10383 * pfnVMAtError() function passed to VMR3Create() is supposed to
10384 * be sticky but our error callback isn't.
10385 */
10386 alock.release();
10387 VMR3AtErrorDeregister(pConsole->mpUVM, Console::i_genericVMSetErrorCallback, &pTask->mErrorMsg);
10388 /** @todo register another VMSetError callback? */
10389 alock.acquire();
10390 }
10391 }
10392 else
10393 {
10394 /*
10395 * If VMR3Create() failed it has released the VM memory.
10396 */
10397 VMR3ReleaseUVM(pConsole->mpUVM);
10398 pConsole->mpUVM = NULL;
10399 }
10400
10401 if (SUCCEEDED(rc) && RT_FAILURE(vrc))
10402 {
10403 /* If VMR3Create() or one of the other calls in this function fail,
10404 * an appropriate error message has been set in pTask->mErrorMsg.
10405 * However since that happens via a callback, the rc status code in
10406 * this function is not updated.
10407 */
10408 if (!pTask->mErrorMsg.length())
10409 {
10410 /* If the error message is not set but we've got a failure,
10411 * convert the VBox status code into a meaningful error message.
10412 * This becomes unused once all the sources of errors set the
10413 * appropriate error message themselves.
10414 */
10415 AssertMsgFailed(("Missing error message during powerup for status code %Rrc\n", vrc));
10416 pTask->mErrorMsg = Utf8StrFmt(tr("Failed to start VM execution (%Rrc)"), vrc);
10417 }
10418
10419 /* Set the error message as the COM error.
10420 * Progress::notifyComplete() will pick it up later. */
10421 throw i_setErrorStaticBoth(E_FAIL, vrc, pTask->mErrorMsg.c_str());
10422 }
10423 }
10424 catch (HRESULT aRC) { rc = aRC; }
10425
10426 if ( pConsole->mMachineState == MachineState_Starting
10427 || pConsole->mMachineState == MachineState_Restoring
10428 || pConsole->mMachineState == MachineState_TeleportingIn
10429 )
10430 {
10431 /* We are still in the Starting/Restoring state. This means one of:
10432 *
10433 * 1) we failed before VMR3Create() was called;
10434 * 2) VMR3Create() failed.
10435 *
10436 * In both cases, there is no need to call powerDown(), but we still
10437 * need to go back to the PoweredOff/Saved state. Reuse
10438 * vmstateChangeCallback() for that purpose.
10439 */
10440
10441 /* preserve existing error info */
10442 ErrorInfoKeeper eik;
10443
10444 Assert(pConsole->mpUVM == NULL);
10445 i_vmstateChangeCallback(NULL, VMSTATE_TERMINATED, VMSTATE_CREATING, pConsole);
10446 }
10447
10448 /*
10449 * Evaluate the final result. Note that the appropriate mMachineState value
10450 * is already set by vmstateChangeCallback() in all cases.
10451 */
10452
10453 /* release the lock, don't need it any more */
10454 alock.release();
10455
10456 if (SUCCEEDED(rc))
10457 {
10458 /* Notify the progress object of the success */
10459 pTask->mProgress->i_notifyComplete(S_OK);
10460 }
10461 else
10462 {
10463 /* The progress object will fetch the current error info */
10464 pTask->mProgress->i_notifyComplete(rc);
10465 LogRel(("Power up failed (vrc=%Rrc, rc=%Rhrc (%#08X))\n", vrc, rc, rc));
10466 }
10467
10468 /* Notify VBoxSVC and any waiting openRemoteSession progress object. */
10469 pConsole->mControl->EndPowerUp(rc);
10470
10471#if defined(RT_OS_WINDOWS)
10472 /* uninitialize COM */
10473 CoUninitialize();
10474#endif
10475
10476 LogFlowFuncLeave();
10477}
10478
10479
10480/**
10481 * Reconfigures a medium attachment (part of taking or deleting an online snapshot).
10482 *
10483 * @param pThis Reference to the console object.
10484 * @param pUVM The VM handle.
10485 * @param pcszDevice The name of the controller type.
10486 * @param uInstance The instance of the controller.
10487 * @param enmBus The storage bus type of the controller.
10488 * @param fUseHostIOCache Use the host I/O cache (disable async I/O).
10489 * @param fBuiltinIOCache Use the builtin I/O cache.
10490 * @param fInsertDiskIntegrityDrv Flag whether to insert the disk integrity driver into the chain
10491 * for additionalk debugging aids.
10492 * @param fSetupMerge Whether to set up a medium merge
10493 * @param uMergeSource Merge source image index
10494 * @param uMergeTarget Merge target image index
10495 * @param aMediumAtt The medium attachment.
10496 * @param aMachineState The current machine state.
10497 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
10498 * @return VBox status code.
10499 */
10500/* static */
10501DECLCALLBACK(int) Console::i_reconfigureMediumAttachment(Console *pThis,
10502 PUVM pUVM,
10503 const char *pcszDevice,
10504 unsigned uInstance,
10505 StorageBus_T enmBus,
10506 bool fUseHostIOCache,
10507 bool fBuiltinIOCache,
10508 bool fInsertDiskIntegrityDrv,
10509 bool fSetupMerge,
10510 unsigned uMergeSource,
10511 unsigned uMergeTarget,
10512 IMediumAttachment *aMediumAtt,
10513 MachineState_T aMachineState,
10514 HRESULT *phrc)
10515{
10516 LogFlowFunc(("pUVM=%p aMediumAtt=%p phrc=%p\n", pUVM, aMediumAtt, phrc));
10517
10518 HRESULT hrc;
10519 Bstr bstr;
10520 *phrc = S_OK;
10521#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%Rhrc (%#x)\n", hrc, hrc)); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
10522
10523 /* Ignore attachments other than hard disks, since at the moment they are
10524 * not subject to snapshotting in general. */
10525 DeviceType_T lType;
10526 hrc = aMediumAtt->COMGETTER(Type)(&lType); H();
10527 if (lType != DeviceType_HardDisk)
10528 return VINF_SUCCESS;
10529
10530 /* Update the device instance configuration. */
10531 int rc = pThis->i_configMediumAttachment(pcszDevice,
10532 uInstance,
10533 enmBus,
10534 fUseHostIOCache,
10535 fBuiltinIOCache,
10536 fInsertDiskIntegrityDrv,
10537 fSetupMerge,
10538 uMergeSource,
10539 uMergeTarget,
10540 aMediumAtt,
10541 aMachineState,
10542 phrc,
10543 true /* fAttachDetach */,
10544 false /* fForceUnmount */,
10545 false /* fHotplug */,
10546 pUVM,
10547 NULL /* paLedDevType */,
10548 NULL /* ppLunL0)*/);
10549 if (RT_FAILURE(rc))
10550 {
10551 AssertMsgFailed(("rc=%Rrc\n", rc));
10552 return rc;
10553 }
10554
10555#undef H
10556
10557 LogFlowFunc(("Returns success\n"));
10558 return VINF_SUCCESS;
10559}
10560
10561/**
10562 * Thread for powering down the Console.
10563 *
10564 * @param pTask The power down task.
10565 *
10566 * @note Locks the Console object for writing.
10567 */
10568/*static*/
10569void Console::i_powerDownThreadTask(VMPowerDownTask *pTask)
10570{
10571 int rc = VINF_SUCCESS; /* only used in assertion */
10572 LogFlowFuncEnter();
10573 try
10574 {
10575 if (pTask->isOk() == false)
10576 rc = VERR_GENERAL_FAILURE;
10577
10578 const ComObjPtr<Console> &that = pTask->mConsole;
10579
10580 /* Note: no need to use AutoCaller to protect Console because VMTask does
10581 * that */
10582
10583 /* wait until the method tat started us returns */
10584 AutoWriteLock thatLock(that COMMA_LOCKVAL_SRC_POS);
10585
10586 /* release VM caller to avoid the powerDown() deadlock */
10587 pTask->releaseVMCaller();
10588
10589 thatLock.release();
10590
10591 that->i_powerDown(pTask->mServerProgress);
10592
10593 /* complete the operation */
10594 that->mControl->EndPoweringDown(S_OK, Bstr().raw());
10595
10596 }
10597 catch (const std::exception &e)
10598 {
10599 AssertMsgFailed(("Exception %s was caught, rc=%Rrc\n", e.what(), rc));
10600 NOREF(e); NOREF(rc);
10601 }
10602
10603 LogFlowFuncLeave();
10604}
10605
10606/**
10607 * @interface_method_impl{VMM2USERMETHODS,pfnSaveState}
10608 */
10609/*static*/ DECLCALLBACK(int)
10610Console::i_vmm2User_SaveState(PCVMM2USERMETHODS pThis, PUVM pUVM)
10611{
10612 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
10613 NOREF(pUVM);
10614
10615 /*
10616 * For now, just call SaveState. We should probably try notify the GUI so
10617 * it can pop up a progress object and stuff. The progress object created
10618 * by the call isn't returned to anyone and thus gets updated without
10619 * anyone noticing it.
10620 */
10621 ComPtr<IProgress> pProgress;
10622 HRESULT hrc = pConsole->mMachine->SaveState(pProgress.asOutParam());
10623 return SUCCEEDED(hrc) ? VINF_SUCCESS : Global::vboxStatusCodeFromCOM(hrc);
10624}
10625
10626/**
10627 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtInit}
10628 */
10629/*static*/ DECLCALLBACK(void)
10630Console::i_vmm2User_NotifyEmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
10631{
10632 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
10633 VirtualBoxBase::initializeComForThread();
10634}
10635
10636/**
10637 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtTerm}
10638 */
10639/*static*/ DECLCALLBACK(void)
10640Console::i_vmm2User_NotifyEmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
10641{
10642 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
10643 VirtualBoxBase::uninitializeComForThread();
10644}
10645
10646/**
10647 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtInit}
10648 */
10649/*static*/ DECLCALLBACK(void)
10650Console::i_vmm2User_NotifyPdmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM)
10651{
10652 NOREF(pThis); NOREF(pUVM);
10653 VirtualBoxBase::initializeComForThread();
10654}
10655
10656/**
10657 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtTerm}
10658 */
10659/*static*/ DECLCALLBACK(void)
10660Console::i_vmm2User_NotifyPdmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM)
10661{
10662 NOREF(pThis); NOREF(pUVM);
10663 VirtualBoxBase::uninitializeComForThread();
10664}
10665
10666/**
10667 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyResetTurnedIntoPowerOff}
10668 */
10669/*static*/ DECLCALLBACK(void)
10670Console::i_vmm2User_NotifyResetTurnedIntoPowerOff(PCVMM2USERMETHODS pThis, PUVM pUVM)
10671{
10672 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
10673 NOREF(pUVM);
10674
10675 pConsole->mfPowerOffCausedByReset = true;
10676}
10677
10678/**
10679 * @interface_method_impl{VMM2USERMETHODS,pfnQueryGenericObject}
10680 */
10681/*static*/ DECLCALLBACK(void *)
10682Console::i_vmm2User_QueryGenericObject(PCVMM2USERMETHODS pThis, PUVM pUVM, PCRTUUID pUuid)
10683{
10684 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
10685 NOREF(pUVM);
10686
10687 /* To simplify comparison we copy the UUID into a com::Guid object. */
10688 com::Guid const UuidCopy(*pUuid);
10689
10690 if (UuidCopy == COM_IIDOF(IConsole))
10691 {
10692 IConsole *pIConsole = static_cast<IConsole *>(pConsole);
10693 return pIConsole;
10694 }
10695
10696 if (UuidCopy == COM_IIDOF(IMachine))
10697 {
10698 IMachine *pIMachine = pConsole->mMachine;
10699 return pIMachine;
10700 }
10701
10702 if (UuidCopy == COM_IIDOF(ISnapshot))
10703 return ((MYVMM2USERMETHODS *)pThis)->pISnapshot;
10704
10705 return NULL;
10706}
10707
10708
10709/**
10710 * @interface_method_impl{PDMISECKEY,pfnKeyRetain}
10711 */
10712/*static*/ DECLCALLBACK(int)
10713Console::i_pdmIfSecKey_KeyRetain(PPDMISECKEY pInterface, const char *pszId, const uint8_t **ppbKey,
10714 size_t *pcbKey)
10715{
10716 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
10717
10718 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
10719 SecretKey *pKey = NULL;
10720
10721 int rc = pConsole->m_pKeyStore->retainSecretKey(Utf8Str(pszId), &pKey);
10722 if (RT_SUCCESS(rc))
10723 {
10724 *ppbKey = (const uint8_t *)pKey->getKeyBuffer();
10725 *pcbKey = pKey->getKeySize();
10726 }
10727
10728 return rc;
10729}
10730
10731/**
10732 * @interface_method_impl{PDMISECKEY,pfnKeyRelease}
10733 */
10734/*static*/ DECLCALLBACK(int)
10735Console::i_pdmIfSecKey_KeyRelease(PPDMISECKEY pInterface, const char *pszId)
10736{
10737 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
10738
10739 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
10740 return pConsole->m_pKeyStore->releaseSecretKey(Utf8Str(pszId));
10741}
10742
10743/**
10744 * @interface_method_impl{PDMISECKEY,pfnPasswordRetain}
10745 */
10746/*static*/ DECLCALLBACK(int)
10747Console::i_pdmIfSecKey_PasswordRetain(PPDMISECKEY pInterface, const char *pszId, const char **ppszPassword)
10748{
10749 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
10750
10751 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
10752 SecretKey *pKey = NULL;
10753
10754 int rc = pConsole->m_pKeyStore->retainSecretKey(Utf8Str(pszId), &pKey);
10755 if (RT_SUCCESS(rc))
10756 *ppszPassword = (const char *)pKey->getKeyBuffer();
10757
10758 return rc;
10759}
10760
10761/**
10762 * @interface_method_impl{PDMISECKEY,pfnPasswordRelease}
10763 */
10764/*static*/ DECLCALLBACK(int)
10765Console::i_pdmIfSecKey_PasswordRelease(PPDMISECKEY pInterface, const char *pszId)
10766{
10767 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
10768
10769 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
10770 return pConsole->m_pKeyStore->releaseSecretKey(Utf8Str(pszId));
10771}
10772
10773/**
10774 * @interface_method_impl{PDMISECKEYHLP,pfnKeyMissingNotify}
10775 */
10776/*static*/ DECLCALLBACK(int)
10777Console::i_pdmIfSecKeyHlp_KeyMissingNotify(PPDMISECKEYHLP pInterface)
10778{
10779 Console *pConsole = ((MYPDMISECKEYHLP *)pInterface)->pConsole;
10780
10781 /* Set guest property only, the VM is paused in the media driver calling us. */
10782 pConsole->mMachine->DeleteGuestProperty(Bstr("/VirtualBox/HostInfo/DekMissing").raw());
10783 pConsole->mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/DekMissing").raw(),
10784 Bstr("1").raw(), Bstr("RDONLYGUEST").raw());
10785 pConsole->mMachine->SaveSettings();
10786
10787 return VINF_SUCCESS;
10788}
10789
10790
10791
10792/**
10793 * The Main status driver instance data.
10794 */
10795typedef struct DRVMAINSTATUS
10796{
10797 /** The LED connectors. */
10798 PDMILEDCONNECTORS ILedConnectors;
10799 /** Pointer to the LED ports interface above us. */
10800 PPDMILEDPORTS pLedPorts;
10801 /** Pointer to the array of LED pointers. */
10802 PPDMLED *papLeds;
10803 /** The unit number corresponding to the first entry in the LED array. */
10804 RTUINT iFirstLUN;
10805 /** The unit number corresponding to the last entry in the LED array.
10806 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
10807 RTUINT iLastLUN;
10808 /** Pointer to the driver instance. */
10809 PPDMDRVINS pDrvIns;
10810 /** The Media Notify interface. */
10811 PDMIMEDIANOTIFY IMediaNotify;
10812 /** Map for translating PDM storage controller/LUN information to
10813 * IMediumAttachment references. */
10814 Console::MediumAttachmentMap *pmapMediumAttachments;
10815 /** Device name+instance for mapping */
10816 char *pszDeviceInstance;
10817 /** Pointer to the Console object, for driver triggered activities. */
10818 Console *pConsole;
10819} DRVMAINSTATUS, *PDRVMAINSTATUS;
10820
10821
10822/**
10823 * Notification about a unit which have been changed.
10824 *
10825 * The driver must discard any pointers to data owned by
10826 * the unit and requery it.
10827 *
10828 * @param pInterface Pointer to the interface structure containing the called function pointer.
10829 * @param iLUN The unit number.
10830 */
10831DECLCALLBACK(void) Console::i_drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
10832{
10833 PDRVMAINSTATUS pThis = RT_FROM_MEMBER(pInterface, DRVMAINSTATUS, ILedConnectors);
10834 if (iLUN >= pThis->iFirstLUN && iLUN <= pThis->iLastLUN)
10835 {
10836 PPDMLED pLed;
10837 int rc = pThis->pLedPorts->pfnQueryStatusLed(pThis->pLedPorts, iLUN, &pLed);
10838 if (RT_FAILURE(rc))
10839 pLed = NULL;
10840 ASMAtomicWritePtr(&pThis->papLeds[iLUN - pThis->iFirstLUN], pLed);
10841 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
10842 }
10843}
10844
10845
10846/**
10847 * Notification about a medium eject.
10848 *
10849 * @returns VBox status code.
10850 * @param pInterface Pointer to the interface structure containing the called function pointer.
10851 * @param uLUN The unit number.
10852 */
10853DECLCALLBACK(int) Console::i_drvStatus_MediumEjected(PPDMIMEDIANOTIFY pInterface, unsigned uLUN)
10854{
10855 PDRVMAINSTATUS pThis = RT_FROM_MEMBER(pInterface, DRVMAINSTATUS, IMediaNotify);
10856 LogFunc(("uLUN=%d\n", uLUN));
10857 if (pThis->pmapMediumAttachments)
10858 {
10859 AutoWriteLock alock(pThis->pConsole COMMA_LOCKVAL_SRC_POS);
10860
10861 ComPtr<IMediumAttachment> pMediumAtt;
10862 Utf8Str devicePath = Utf8StrFmt("%s/LUN#%u", pThis->pszDeviceInstance, uLUN);
10863 Console::MediumAttachmentMap::const_iterator end = pThis->pmapMediumAttachments->end();
10864 Console::MediumAttachmentMap::const_iterator it = pThis->pmapMediumAttachments->find(devicePath);
10865 if (it != end)
10866 pMediumAtt = it->second;
10867 Assert(!pMediumAtt.isNull());
10868 if (!pMediumAtt.isNull())
10869 {
10870 IMedium *pMedium = NULL;
10871 HRESULT rc = pMediumAtt->COMGETTER(Medium)(&pMedium);
10872 AssertComRC(rc);
10873 if (SUCCEEDED(rc) && pMedium)
10874 {
10875 BOOL fHostDrive = FALSE;
10876 rc = pMedium->COMGETTER(HostDrive)(&fHostDrive);
10877 AssertComRC(rc);
10878 if (!fHostDrive)
10879 {
10880 alock.release();
10881
10882 ComPtr<IMediumAttachment> pNewMediumAtt;
10883 rc = pThis->pConsole->mControl->EjectMedium(pMediumAtt, pNewMediumAtt.asOutParam());
10884 if (SUCCEEDED(rc))
10885 {
10886 pThis->pConsole->mMachine->SaveSettings();
10887 fireMediumChangedEvent(pThis->pConsole->mEventSource, pNewMediumAtt);
10888 }
10889
10890 alock.acquire();
10891 if (pNewMediumAtt != pMediumAtt)
10892 {
10893 pThis->pmapMediumAttachments->erase(devicePath);
10894 pThis->pmapMediumAttachments->insert(std::make_pair(devicePath, pNewMediumAtt));
10895 }
10896 }
10897 }
10898 }
10899 }
10900 return VINF_SUCCESS;
10901}
10902
10903
10904/**
10905 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
10906 */
10907DECLCALLBACK(void *) Console::i_drvStatus_QueryInterface(PPDMIBASE pInterface, const char *pszIID)
10908{
10909 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
10910 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10911 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
10912 PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDCONNECTORS, &pThis->ILedConnectors);
10913 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIANOTIFY, &pThis->IMediaNotify);
10914 return NULL;
10915}
10916
10917
10918/**
10919 * Destruct a status driver instance.
10920 *
10921 * @returns VBox status code.
10922 * @param pDrvIns The driver instance data.
10923 */
10924DECLCALLBACK(void) Console::i_drvStatus_Destruct(PPDMDRVINS pDrvIns)
10925{
10926 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
10927 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10928 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
10929
10930 if (pThis->papLeds)
10931 {
10932 unsigned iLed = pThis->iLastLUN - pThis->iFirstLUN + 1;
10933 while (iLed-- > 0)
10934 ASMAtomicWriteNullPtr(&pThis->papLeds[iLed]);
10935 }
10936}
10937
10938
10939/**
10940 * Construct a status driver instance.
10941 *
10942 * @copydoc FNPDMDRVCONSTRUCT
10943 */
10944DECLCALLBACK(int) Console::i_drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
10945{
10946 RT_NOREF(fFlags);
10947 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
10948 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10949 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
10950
10951 /*
10952 * Validate configuration.
10953 */
10954 if (!CFGMR3AreValuesValid(pCfg, "papLeds\0pmapMediumAttachments\0DeviceInstance\0pConsole\0First\0Last\0"))
10955 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
10956 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
10957 ("Configuration error: Not possible to attach anything to this driver!\n"),
10958 VERR_PDM_DRVINS_NO_ATTACH);
10959
10960 /*
10961 * Data.
10962 */
10963 pDrvIns->IBase.pfnQueryInterface = Console::i_drvStatus_QueryInterface;
10964 pThis->ILedConnectors.pfnUnitChanged = Console::i_drvStatus_UnitChanged;
10965 pThis->IMediaNotify.pfnEjected = Console::i_drvStatus_MediumEjected;
10966 pThis->pDrvIns = pDrvIns;
10967 pThis->pszDeviceInstance = NULL;
10968
10969 /*
10970 * Read config.
10971 */
10972 int rc = CFGMR3QueryPtr(pCfg, "papLeds", (void **)&pThis->papLeds);
10973 if (RT_FAILURE(rc))
10974 {
10975 AssertMsgFailed(("Configuration error: Failed to query the \"papLeds\" value! rc=%Rrc\n", rc));
10976 return rc;
10977 }
10978
10979 rc = CFGMR3QueryPtrDef(pCfg, "pmapMediumAttachments", (void **)&pThis->pmapMediumAttachments, NULL);
10980 if (RT_FAILURE(rc))
10981 {
10982 AssertMsgFailed(("Configuration error: Failed to query the \"pmapMediumAttachments\" value! rc=%Rrc\n", rc));
10983 return rc;
10984 }
10985 if (pThis->pmapMediumAttachments)
10986 {
10987 rc = CFGMR3QueryStringAlloc(pCfg, "DeviceInstance", &pThis->pszDeviceInstance);
10988 if (RT_FAILURE(rc))
10989 {
10990 AssertMsgFailed(("Configuration error: Failed to query the \"DeviceInstance\" value! rc=%Rrc\n", rc));
10991 return rc;
10992 }
10993 rc = CFGMR3QueryPtr(pCfg, "pConsole", (void **)&pThis->pConsole);
10994 if (RT_FAILURE(rc))
10995 {
10996 AssertMsgFailed(("Configuration error: Failed to query the \"pConsole\" value! rc=%Rrc\n", rc));
10997 return rc;
10998 }
10999 }
11000
11001 rc = CFGMR3QueryU32(pCfg, "First", &pThis->iFirstLUN);
11002 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
11003 pThis->iFirstLUN = 0;
11004 else if (RT_FAILURE(rc))
11005 {
11006 AssertMsgFailed(("Configuration error: Failed to query the \"First\" value! rc=%Rrc\n", rc));
11007 return rc;
11008 }
11009
11010 rc = CFGMR3QueryU32(pCfg, "Last", &pThis->iLastLUN);
11011 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
11012 pThis->iLastLUN = 0;
11013 else if (RT_FAILURE(rc))
11014 {
11015 AssertMsgFailed(("Configuration error: Failed to query the \"Last\" value! rc=%Rrc\n", rc));
11016 return rc;
11017 }
11018 if (pThis->iFirstLUN > pThis->iLastLUN)
11019 {
11020 AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pThis->iFirstLUN, pThis->iLastLUN));
11021 return VERR_GENERAL_FAILURE;
11022 }
11023
11024 /*
11025 * Get the ILedPorts interface of the above driver/device and
11026 * query the LEDs we want.
11027 */
11028 pThis->pLedPorts = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMILEDPORTS);
11029 AssertMsgReturn(pThis->pLedPorts, ("Configuration error: No led ports interface above!\n"),
11030 VERR_PDM_MISSING_INTERFACE_ABOVE);
11031
11032 for (unsigned i = pThis->iFirstLUN; i <= pThis->iLastLUN; ++i)
11033 Console::i_drvStatus_UnitChanged(&pThis->ILedConnectors, i);
11034
11035 return VINF_SUCCESS;
11036}
11037
11038
11039/**
11040 * Console status driver (LED) registration record.
11041 */
11042const PDMDRVREG Console::DrvStatusReg =
11043{
11044 /* u32Version */
11045 PDM_DRVREG_VERSION,
11046 /* szName */
11047 "MainStatus",
11048 /* szRCMod */
11049 "",
11050 /* szR0Mod */
11051 "",
11052 /* pszDescription */
11053 "Main status driver (Main as in the API).",
11054 /* fFlags */
11055 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
11056 /* fClass. */
11057 PDM_DRVREG_CLASS_STATUS,
11058 /* cMaxInstances */
11059 ~0U,
11060 /* cbInstance */
11061 sizeof(DRVMAINSTATUS),
11062 /* pfnConstruct */
11063 Console::i_drvStatus_Construct,
11064 /* pfnDestruct */
11065 Console::i_drvStatus_Destruct,
11066 /* pfnRelocate */
11067 NULL,
11068 /* pfnIOCtl */
11069 NULL,
11070 /* pfnPowerOn */
11071 NULL,
11072 /* pfnReset */
11073 NULL,
11074 /* pfnSuspend */
11075 NULL,
11076 /* pfnResume */
11077 NULL,
11078 /* pfnAttach */
11079 NULL,
11080 /* pfnDetach */
11081 NULL,
11082 /* pfnPowerOff */
11083 NULL,
11084 /* pfnSoftReset */
11085 NULL,
11086 /* u32EndVersion */
11087 PDM_DRVREG_VERSION
11088};
11089
11090
11091
11092/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

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