VirtualBox

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

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

Capturing/Main: Bugfixes for startup.

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

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