VirtualBox

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

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

Capturing: Build fix.

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