VirtualBox

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

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

Capturing: Fixed checking for capturing context in Console::i_videoRecStop().

  • 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 75276 2018-11-06 11:46:15Z 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.215389.xyz. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#define LOG_GROUP LOG_GROUP_MAIN_CONSOLE
19#include "LoggingNew.h"
20
21/** @todo Move the TAP mess back into the driver! */
22#if defined(RT_OS_WINDOWS)
23#elif defined(RT_OS_LINUX)
24# include <errno.h>
25# include <sys/ioctl.h>
26# include <sys/poll.h>
27# include <sys/fcntl.h>
28# include <sys/types.h>
29# include <sys/wait.h>
30# include <net/if.h>
31# include <linux/if_tun.h>
32# include <stdio.h>
33# include <stdlib.h>
34# include <string.h>
35#elif defined(RT_OS_FREEBSD)
36# include <errno.h>
37# include <sys/ioctl.h>
38# include <sys/poll.h>
39# include <sys/fcntl.h>
40# include <sys/types.h>
41# include <sys/wait.h>
42# include <stdio.h>
43# include <stdlib.h>
44# include <string.h>
45#elif defined(RT_OS_SOLARIS)
46# include <iprt/coredumper.h>
47#endif
48
49#include "ConsoleImpl.h"
50
51#include "Global.h"
52#include "VirtualBoxErrorInfoImpl.h"
53#include "GuestImpl.h"
54#include "KeyboardImpl.h"
55#include "MouseImpl.h"
56#include "DisplayImpl.h"
57#include "MachineDebuggerImpl.h"
58#include "USBDeviceImpl.h"
59#include "RemoteUSBDeviceImpl.h"
60#include "SharedFolderImpl.h"
61#ifdef VBOX_WITH_AUDIO_VRDE
62# include "DrvAudioVRDE.h"
63#endif
64#ifdef VBOX_WITH_AUDIO_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 for (unsigned uScreen = 0; uScreen < cStreams; ++uScreen)
6986 mDisplay->i_videoRecScreenChanged(uScreen);
6987
6988 delete Capture.mpVideoRecCtx;
6989 Capture.mpVideoRecCtx = NULL;
6990
6991 ComPtr<ICaptureSettings> pCaptureSettings;
6992 HRESULT hrc = mMachine->COMGETTER(CaptureSettings)(pCaptureSettings.asOutParam());
6993 ComAssertComRC(hrc);
6994 hrc = pCaptureSettings->COMSETTER(Enabled)(false);
6995 ComAssertComRC(hrc);
6996
6997 LogRel(("VideoRec: Stopped\n"));
6998
6999 return VINF_SUCCESS;
7000}
7001#endif /* VBOX_WITH_VIDEOREC */
7002
7003/**
7004 * Gets called by Session::UpdateMachineState()
7005 * (IInternalSessionControl::updateMachineState()).
7006 *
7007 * Must be called only in certain cases (see the implementation).
7008 *
7009 * @note Locks this object for writing.
7010 */
7011HRESULT Console::i_updateMachineState(MachineState_T aMachineState)
7012{
7013 AutoCaller autoCaller(this);
7014 AssertComRCReturnRC(autoCaller.rc());
7015
7016 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7017
7018 AssertReturn( mMachineState == MachineState_Saving
7019 || mMachineState == MachineState_OnlineSnapshotting
7020 || mMachineState == MachineState_LiveSnapshotting
7021 || mMachineState == MachineState_DeletingSnapshotOnline
7022 || mMachineState == MachineState_DeletingSnapshotPaused
7023 || aMachineState == MachineState_Saving
7024 || aMachineState == MachineState_OnlineSnapshotting
7025 || aMachineState == MachineState_LiveSnapshotting
7026 || aMachineState == MachineState_DeletingSnapshotOnline
7027 || aMachineState == MachineState_DeletingSnapshotPaused
7028 , E_FAIL);
7029
7030 return i_setMachineStateLocally(aMachineState);
7031}
7032
7033/**
7034 * Gets called by Session::COMGETTER(NominalState)()
7035 * (IInternalSessionControl::getNominalState()).
7036 *
7037 * @note Locks this object for reading.
7038 */
7039HRESULT Console::i_getNominalState(MachineState_T &aNominalState)
7040{
7041 LogFlowThisFuncEnter();
7042
7043 AutoCaller autoCaller(this);
7044 AssertComRCReturnRC(autoCaller.rc());
7045
7046 /* Get the VM handle. */
7047 SafeVMPtr ptrVM(this);
7048 if (!ptrVM.isOk())
7049 return ptrVM.rc();
7050
7051 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7052
7053 MachineState_T enmMachineState = MachineState_Null;
7054 VMSTATE enmVMState = VMR3GetStateU(ptrVM.rawUVM());
7055 switch (enmVMState)
7056 {
7057 case VMSTATE_CREATING:
7058 case VMSTATE_CREATED:
7059 case VMSTATE_POWERING_ON:
7060 enmMachineState = MachineState_Starting;
7061 break;
7062 case VMSTATE_LOADING:
7063 enmMachineState = MachineState_Restoring;
7064 break;
7065 case VMSTATE_RESUMING:
7066 case VMSTATE_SUSPENDING:
7067 case VMSTATE_SUSPENDING_LS:
7068 case VMSTATE_SUSPENDING_EXT_LS:
7069 case VMSTATE_SUSPENDED:
7070 case VMSTATE_SUSPENDED_LS:
7071 case VMSTATE_SUSPENDED_EXT_LS:
7072 enmMachineState = MachineState_Paused;
7073 break;
7074 case VMSTATE_RUNNING:
7075 case VMSTATE_RUNNING_LS:
7076 case VMSTATE_RUNNING_FT:
7077 case VMSTATE_RESETTING:
7078 case VMSTATE_RESETTING_LS:
7079 case VMSTATE_SOFT_RESETTING:
7080 case VMSTATE_SOFT_RESETTING_LS:
7081 case VMSTATE_DEBUGGING:
7082 case VMSTATE_DEBUGGING_LS:
7083 enmMachineState = MachineState_Running;
7084 break;
7085 case VMSTATE_SAVING:
7086 enmMachineState = MachineState_Saving;
7087 break;
7088 case VMSTATE_POWERING_OFF:
7089 case VMSTATE_POWERING_OFF_LS:
7090 case VMSTATE_DESTROYING:
7091 enmMachineState = MachineState_Stopping;
7092 break;
7093 case VMSTATE_OFF:
7094 case VMSTATE_OFF_LS:
7095 case VMSTATE_FATAL_ERROR:
7096 case VMSTATE_FATAL_ERROR_LS:
7097 case VMSTATE_LOAD_FAILURE:
7098 case VMSTATE_TERMINATED:
7099 enmMachineState = MachineState_PoweredOff;
7100 break;
7101 case VMSTATE_GURU_MEDITATION:
7102 case VMSTATE_GURU_MEDITATION_LS:
7103 enmMachineState = MachineState_Stuck;
7104 break;
7105 default:
7106 AssertMsgFailed(("%s\n", VMR3GetStateName(enmVMState)));
7107 enmMachineState = MachineState_PoweredOff;
7108 }
7109 aNominalState = enmMachineState;
7110
7111 LogFlowFuncLeave();
7112 return S_OK;
7113}
7114
7115void Console::i_onMousePointerShapeChange(bool fVisible, bool fAlpha,
7116 uint32_t xHot, uint32_t yHot,
7117 uint32_t width, uint32_t height,
7118 const uint8_t *pu8Shape,
7119 uint32_t cbShape)
7120{
7121#if 0
7122 LogFlowThisFuncEnter();
7123 LogFlowThisFunc(("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, height=%d, shape=%p\n",
7124 fVisible, fAlpha, xHot, yHot, width, height, pShape));
7125#endif
7126
7127 AutoCaller autoCaller(this);
7128 AssertComRCReturnVoid(autoCaller.rc());
7129
7130 if (!mMouse.isNull())
7131 mMouse->updateMousePointerShape(fVisible, fAlpha, xHot, yHot, width, height,
7132 pu8Shape, cbShape);
7133
7134 com::SafeArray<BYTE> shape(cbShape);
7135 if (pu8Shape)
7136 memcpy(shape.raw(), pu8Shape, cbShape);
7137 fireMousePointerShapeChangedEvent(mEventSource, fVisible, fAlpha, xHot, yHot, width, height, ComSafeArrayAsInParam(shape));
7138
7139#if 0
7140 LogFlowThisFuncLeave();
7141#endif
7142}
7143
7144void Console::i_onMouseCapabilityChange(BOOL supportsAbsolute, BOOL supportsRelative,
7145 BOOL supportsMT, BOOL needsHostCursor)
7146{
7147 LogFlowThisFunc(("supportsAbsolute=%d supportsRelative=%d needsHostCursor=%d\n",
7148 supportsAbsolute, supportsRelative, needsHostCursor));
7149
7150 AutoCaller autoCaller(this);
7151 AssertComRCReturnVoid(autoCaller.rc());
7152
7153 fireMouseCapabilityChangedEvent(mEventSource, supportsAbsolute, supportsRelative, supportsMT, needsHostCursor);
7154}
7155
7156void Console::i_onStateChange(MachineState_T machineState)
7157{
7158 AutoCaller autoCaller(this);
7159 AssertComRCReturnVoid(autoCaller.rc());
7160 fireStateChangedEvent(mEventSource, machineState);
7161}
7162
7163void Console::i_onAdditionsStateChange()
7164{
7165 AutoCaller autoCaller(this);
7166 AssertComRCReturnVoid(autoCaller.rc());
7167
7168 fireAdditionsStateChangedEvent(mEventSource);
7169}
7170
7171/**
7172 * @remarks This notification only is for reporting an incompatible
7173 * Guest Additions interface, *not* the Guest Additions version!
7174 *
7175 * The user will be notified inside the guest if new Guest
7176 * Additions are available (via VBoxTray/VBoxClient).
7177 */
7178void Console::i_onAdditionsOutdated()
7179{
7180 AutoCaller autoCaller(this);
7181 AssertComRCReturnVoid(autoCaller.rc());
7182
7183 /** @todo implement this */
7184}
7185
7186void Console::i_onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
7187{
7188 AutoCaller autoCaller(this);
7189 AssertComRCReturnVoid(autoCaller.rc());
7190
7191 fireKeyboardLedsChangedEvent(mEventSource, fNumLock, fCapsLock, fScrollLock);
7192}
7193
7194void Console::i_onUSBDeviceStateChange(IUSBDevice *aDevice, bool aAttached,
7195 IVirtualBoxErrorInfo *aError)
7196{
7197 AutoCaller autoCaller(this);
7198 AssertComRCReturnVoid(autoCaller.rc());
7199
7200 fireUSBDeviceStateChangedEvent(mEventSource, aDevice, aAttached, aError);
7201}
7202
7203void Console::i_onRuntimeError(BOOL aFatal, IN_BSTR aErrorID, IN_BSTR aMessage)
7204{
7205 AutoCaller autoCaller(this);
7206 AssertComRCReturnVoid(autoCaller.rc());
7207
7208 fireRuntimeErrorEvent(mEventSource, aFatal, aErrorID, aMessage);
7209}
7210
7211HRESULT Console::i_onShowWindow(BOOL aCheck, BOOL *aCanShow, LONG64 *aWinId)
7212{
7213 AssertReturn(aCanShow, E_POINTER);
7214 AssertReturn(aWinId, E_POINTER);
7215
7216 *aCanShow = FALSE;
7217 *aWinId = 0;
7218
7219 AutoCaller autoCaller(this);
7220 AssertComRCReturnRC(autoCaller.rc());
7221
7222 VBoxEventDesc evDesc;
7223 if (aCheck)
7224 {
7225 evDesc.init(mEventSource, VBoxEventType_OnCanShowWindow);
7226 BOOL fDelivered = evDesc.fire(5000); /* Wait up to 5 secs for delivery */
7227 //Assert(fDelivered);
7228 if (fDelivered)
7229 {
7230 ComPtr<IEvent> pEvent;
7231 evDesc.getEvent(pEvent.asOutParam());
7232 // bit clumsy
7233 ComPtr<ICanShowWindowEvent> pCanShowEvent = pEvent;
7234 if (pCanShowEvent)
7235 {
7236 BOOL fVetoed = FALSE;
7237 BOOL fApproved = FALSE;
7238 pCanShowEvent->IsVetoed(&fVetoed);
7239 pCanShowEvent->IsApproved(&fApproved);
7240 *aCanShow = fApproved || !fVetoed;
7241 }
7242 else
7243 {
7244 AssertFailed();
7245 *aCanShow = TRUE;
7246 }
7247 }
7248 else
7249 *aCanShow = TRUE;
7250 }
7251 else
7252 {
7253 evDesc.init(mEventSource, VBoxEventType_OnShowWindow, INT64_C(0));
7254 BOOL fDelivered = evDesc.fire(5000); /* Wait up to 5 secs for delivery */
7255 //Assert(fDelivered);
7256 if (fDelivered)
7257 {
7258 ComPtr<IEvent> pEvent;
7259 evDesc.getEvent(pEvent.asOutParam());
7260 ComPtr<IShowWindowEvent> pShowEvent = pEvent;
7261 if (pShowEvent)
7262 {
7263 LONG64 iEvWinId = 0;
7264 pShowEvent->COMGETTER(WinId)(&iEvWinId);
7265 if (iEvWinId != 0 && *aWinId == 0)
7266 *aWinId = iEvWinId;
7267 }
7268 else
7269 AssertFailed();
7270 }
7271 }
7272
7273 return S_OK;
7274}
7275
7276// private methods
7277////////////////////////////////////////////////////////////////////////////////
7278
7279/**
7280 * Increases the usage counter of the mpUVM pointer.
7281 *
7282 * Guarantees that VMR3Destroy() will not be called on it at least until
7283 * releaseVMCaller() is called.
7284 *
7285 * If this method returns a failure, the caller is not allowed to use mpUVM and
7286 * may return the failed result code to the upper level. This method sets the
7287 * extended error info on failure if \a aQuiet is false.
7288 *
7289 * Setting \a aQuiet to true is useful for methods that don't want to return
7290 * the failed result code to the caller when this method fails (e.g. need to
7291 * silently check for the mpUVM availability).
7292 *
7293 * When mpUVM is NULL but \a aAllowNullVM is true, a corresponding error will be
7294 * returned instead of asserting. Having it false is intended as a sanity check
7295 * for methods that have checked mMachineState and expect mpUVM *NOT* to be
7296 * NULL.
7297 *
7298 * @param aQuiet true to suppress setting error info
7299 * @param aAllowNullVM true to accept mpUVM being NULL and return a failure
7300 * (otherwise this method will assert if mpUVM is NULL)
7301 *
7302 * @note Locks this object for writing.
7303 */
7304HRESULT Console::i_addVMCaller(bool aQuiet /* = false */,
7305 bool aAllowNullVM /* = false */)
7306{
7307 RT_NOREF(aAllowNullVM);
7308 AutoCaller autoCaller(this);
7309 /** @todo Fix race during console/VM reference destruction, refer @bugref{6318}
7310 * comment 25. */
7311 if (FAILED(autoCaller.rc()))
7312 return autoCaller.rc();
7313
7314 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7315
7316 if (mVMDestroying)
7317 {
7318 /* powerDown() is waiting for all callers to finish */
7319 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED, tr("The virtual machine is being powered down"));
7320 }
7321
7322 if (mpUVM == NULL)
7323 {
7324 Assert(aAllowNullVM == true);
7325
7326 /* The machine is not powered up */
7327 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED, tr("The virtual machine is not powered up"));
7328 }
7329
7330 ++mVMCallers;
7331
7332 return S_OK;
7333}
7334
7335/**
7336 * Decreases the usage counter of the mpUVM pointer.
7337 *
7338 * Must always complete the addVMCaller() call after the mpUVM pointer is no
7339 * more necessary.
7340 *
7341 * @note Locks this object for writing.
7342 */
7343void Console::i_releaseVMCaller()
7344{
7345 AutoCaller autoCaller(this);
7346 AssertComRCReturnVoid(autoCaller.rc());
7347
7348 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7349
7350 AssertReturnVoid(mpUVM != NULL);
7351
7352 Assert(mVMCallers > 0);
7353 --mVMCallers;
7354
7355 if (mVMCallers == 0 && mVMDestroying)
7356 {
7357 /* inform powerDown() there are no more callers */
7358 RTSemEventSignal(mVMZeroCallersSem);
7359 }
7360}
7361
7362
7363HRESULT Console::i_safeVMPtrRetainer(PUVM *a_ppUVM, bool a_Quiet)
7364{
7365 *a_ppUVM = NULL;
7366
7367 AutoCaller autoCaller(this);
7368 AssertComRCReturnRC(autoCaller.rc());
7369 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7370
7371 /*
7372 * Repeat the checks done by addVMCaller.
7373 */
7374 if (mVMDestroying) /* powerDown() is waiting for all callers to finish */
7375 return a_Quiet
7376 ? E_ACCESSDENIED
7377 : setError(E_ACCESSDENIED, tr("The virtual machine is being powered down"));
7378 PUVM pUVM = mpUVM;
7379 if (!pUVM)
7380 return a_Quiet
7381 ? E_ACCESSDENIED
7382 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
7383
7384 /*
7385 * Retain a reference to the user mode VM handle and get the global handle.
7386 */
7387 uint32_t cRefs = VMR3RetainUVM(pUVM);
7388 if (cRefs == UINT32_MAX)
7389 return a_Quiet
7390 ? E_ACCESSDENIED
7391 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
7392
7393 /* done */
7394 *a_ppUVM = pUVM;
7395 return S_OK;
7396}
7397
7398void Console::i_safeVMPtrReleaser(PUVM *a_ppUVM)
7399{
7400 if (*a_ppUVM)
7401 VMR3ReleaseUVM(*a_ppUVM);
7402 *a_ppUVM = NULL;
7403}
7404
7405
7406/**
7407 * Initialize the release logging facility. In case something
7408 * goes wrong, there will be no release logging. Maybe in the future
7409 * we can add some logic to use different file names in this case.
7410 * Note that the logic must be in sync with Machine::DeleteSettings().
7411 */
7412HRESULT Console::i_consoleInitReleaseLog(const ComPtr<IMachine> aMachine)
7413{
7414 HRESULT hrc = S_OK;
7415
7416 Bstr logFolder;
7417 hrc = aMachine->COMGETTER(LogFolder)(logFolder.asOutParam());
7418 if (FAILED(hrc))
7419 return hrc;
7420
7421 Utf8Str logDir = logFolder;
7422
7423 /* make sure the Logs folder exists */
7424 Assert(logDir.length());
7425 if (!RTDirExists(logDir.c_str()))
7426 RTDirCreateFullPath(logDir.c_str(), 0700);
7427
7428 Utf8Str logFile = Utf8StrFmt("%s%cVBox.log",
7429 logDir.c_str(), RTPATH_DELIMITER);
7430 Utf8Str pngFile = Utf8StrFmt("%s%cVBox.png",
7431 logDir.c_str(), RTPATH_DELIMITER);
7432
7433 /*
7434 * Age the old log files
7435 * Rename .(n-1) to .(n), .(n-2) to .(n-1), ..., and the last log file to .1
7436 * Overwrite target files in case they exist.
7437 */
7438 ComPtr<IVirtualBox> pVirtualBox;
7439 aMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
7440 ComPtr<ISystemProperties> pSystemProperties;
7441 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
7442 ULONG cHistoryFiles = 3;
7443 pSystemProperties->COMGETTER(LogHistoryCount)(&cHistoryFiles);
7444 if (cHistoryFiles)
7445 {
7446 for (int i = cHistoryFiles-1; i >= 0; i--)
7447 {
7448 Utf8Str *files[] = { &logFile, &pngFile };
7449 Utf8Str oldName, newName;
7450
7451 for (unsigned int j = 0; j < RT_ELEMENTS(files); ++j)
7452 {
7453 if (i > 0)
7454 oldName = Utf8StrFmt("%s.%d", files[j]->c_str(), i);
7455 else
7456 oldName = *files[j];
7457 newName = Utf8StrFmt("%s.%d", files[j]->c_str(), i + 1);
7458 /* If the old file doesn't exist, delete the new file (if it
7459 * exists) to provide correct rotation even if the sequence is
7460 * broken */
7461 if ( RTFileRename(oldName.c_str(), newName.c_str(), RTFILEMOVE_FLAGS_REPLACE)
7462 == VERR_FILE_NOT_FOUND)
7463 RTFileDelete(newName.c_str());
7464 }
7465 }
7466 }
7467
7468 RTERRINFOSTATIC ErrInfo;
7469 int vrc = com::VBoxLogRelCreate("VM", logFile.c_str(),
7470 RTLOGFLAGS_PREFIX_TIME_PROG | RTLOGFLAGS_RESTRICT_GROUPS,
7471 "all all.restrict -default.restrict",
7472 "VBOX_RELEASE_LOG", RTLOGDEST_FILE,
7473 32768 /* cMaxEntriesPerGroup */,
7474 0 /* cHistory */, 0 /* uHistoryFileTime */,
7475 0 /* uHistoryFileSize */, RTErrInfoInitStatic(&ErrInfo));
7476 if (RT_FAILURE(vrc))
7477 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to open release log (%s, %Rrc)"), ErrInfo.Core.pszMsg, vrc);
7478
7479 /* If we've made any directory changes, flush the directory to increase
7480 the likelihood that the log file will be usable after a system panic.
7481
7482 Tip: Try 'export VBOX_RELEASE_LOG_FLAGS=flush' if the last bits of the log
7483 is missing. Just don't have too high hopes for this to help. */
7484 if (SUCCEEDED(hrc) || cHistoryFiles)
7485 RTDirFlush(logDir.c_str());
7486
7487 return hrc;
7488}
7489
7490/**
7491 * Common worker for PowerUp and PowerUpPaused.
7492 *
7493 * @returns COM status code.
7494 *
7495 * @param aProgress Where to return the progress object.
7496 * @param aPaused true if PowerUpPaused called.
7497 */
7498HRESULT Console::i_powerUp(IProgress **aProgress, bool aPaused)
7499{
7500 LogFlowThisFuncEnter();
7501
7502 CheckComArgOutPointerValid(aProgress);
7503
7504 AutoCaller autoCaller(this);
7505 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7506
7507 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7508
7509 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
7510 HRESULT rc = S_OK;
7511 ComObjPtr<Progress> pPowerupProgress;
7512 bool fBeganPoweringUp = false;
7513
7514 LONG cOperations = 1;
7515 LONG ulTotalOperationsWeight = 1;
7516 VMPowerUpTask* task = NULL;
7517
7518 try
7519 {
7520 if (Global::IsOnlineOrTransient(mMachineState))
7521 throw setError(VBOX_E_INVALID_VM_STATE, tr("The virtual machine is already running or busy (machine state: %s)"),
7522 Global::stringifyMachineState(mMachineState));
7523
7524 /* Set up release logging as early as possible after the check if
7525 * there is already a running VM which we shouldn't disturb. */
7526 rc = i_consoleInitReleaseLog(mMachine);
7527 if (FAILED(rc))
7528 throw rc;
7529
7530#ifdef VBOX_OPENSSL_FIPS
7531 LogRel(("crypto: FIPS mode %s\n", FIPS_mode() ? "enabled" : "FAILED"));
7532#endif
7533
7534 /* test and clear the TeleporterEnabled property */
7535 BOOL fTeleporterEnabled;
7536 rc = mMachine->COMGETTER(TeleporterEnabled)(&fTeleporterEnabled);
7537 if (FAILED(rc))
7538 throw rc;
7539
7540#if 0 /** @todo we should save it afterwards, but that isn't necessarily a good idea. Find a better place for this (VBoxSVC). */
7541 if (fTeleporterEnabled)
7542 {
7543 rc = mMachine->COMSETTER(TeleporterEnabled)(FALSE);
7544 if (FAILED(rc))
7545 throw rc;
7546 }
7547#endif
7548
7549 /* test the FaultToleranceState property */
7550 FaultToleranceState_T enmFaultToleranceState;
7551 rc = mMachine->COMGETTER(FaultToleranceState)(&enmFaultToleranceState);
7552 if (FAILED(rc))
7553 throw rc;
7554 BOOL fFaultToleranceSyncEnabled = (enmFaultToleranceState == FaultToleranceState_Standby);
7555
7556 /* Create a progress object to track progress of this operation. Must
7557 * be done as early as possible (together with BeginPowerUp()) as this
7558 * is vital for communicating as much as possible early powerup
7559 * failure information to the API caller */
7560 pPowerupProgress.createObject();
7561 Bstr progressDesc;
7562 if (mMachineState == MachineState_Saved)
7563 progressDesc = tr("Restoring virtual machine");
7564 else if (fTeleporterEnabled)
7565 progressDesc = tr("Teleporting virtual machine");
7566 else if (fFaultToleranceSyncEnabled)
7567 progressDesc = tr("Fault Tolerance syncing of remote virtual machine");
7568 else
7569 progressDesc = tr("Starting virtual machine");
7570
7571 Bstr savedStateFile;
7572
7573 /*
7574 * Saved VMs will have to prove that their saved states seem kosher.
7575 */
7576 if (mMachineState == MachineState_Saved)
7577 {
7578 rc = mMachine->COMGETTER(StateFilePath)(savedStateFile.asOutParam());
7579 if (FAILED(rc))
7580 throw rc;
7581 ComAssertRet(!savedStateFile.isEmpty(), E_FAIL);
7582 int vrc = SSMR3ValidateFile(Utf8Str(savedStateFile).c_str(), false /* fChecksumIt */);
7583 if (RT_FAILURE(vrc))
7584 throw setErrorBoth(VBOX_E_FILE_ERROR, vrc,
7585 tr("VM cannot start because the saved state file '%ls' is invalid (%Rrc). Delete the saved state prior to starting the VM"),
7586 savedStateFile.raw(), vrc);
7587 }
7588
7589 /* Read console data, including console shared folders, stored in the
7590 * saved state file (if not yet done).
7591 */
7592 rc = i_loadDataFromSavedState();
7593 if (FAILED(rc))
7594 throw rc;
7595
7596 /* Check all types of shared folders and compose a single list */
7597 SharedFolderDataMap sharedFolders;
7598 {
7599 /* first, insert global folders */
7600 for (SharedFolderDataMap::const_iterator it = m_mapGlobalSharedFolders.begin();
7601 it != m_mapGlobalSharedFolders.end();
7602 ++it)
7603 {
7604 const SharedFolderData &d = it->second;
7605 sharedFolders[it->first] = d;
7606 }
7607
7608 /* second, insert machine folders */
7609 for (SharedFolderDataMap::const_iterator it = m_mapMachineSharedFolders.begin();
7610 it != m_mapMachineSharedFolders.end();
7611 ++it)
7612 {
7613 const SharedFolderData &d = it->second;
7614 sharedFolders[it->first] = d;
7615 }
7616
7617 /* third, insert console folders */
7618 for (SharedFolderMap::const_iterator it = m_mapSharedFolders.begin();
7619 it != m_mapSharedFolders.end();
7620 ++it)
7621 {
7622 SharedFolder *pSF = it->second;
7623 AutoCaller sfCaller(pSF);
7624 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
7625 sharedFolders[it->first] = SharedFolderData(pSF->i_getHostPath(),
7626 pSF->i_isWritable(),
7627 pSF->i_isAutoMounted());
7628 }
7629 }
7630
7631
7632 /* Setup task object and thread to carry out the operation
7633 * asynchronously */
7634 try
7635 {
7636 task = new VMPowerUpTask(this, pPowerupProgress);
7637 if (!task->isOk())
7638 {
7639 throw E_FAIL;
7640 }
7641 }
7642 catch(...)
7643 {
7644 delete task;
7645 rc = setError(E_FAIL, "Could not create VMPowerUpTask object \n");
7646 throw rc;
7647 }
7648
7649 task->mConfigConstructor = i_configConstructor;
7650 task->mSharedFolders = sharedFolders;
7651 task->mStartPaused = aPaused;
7652 if (mMachineState == MachineState_Saved)
7653 task->mSavedStateFile = savedStateFile;
7654 task->mTeleporterEnabled = fTeleporterEnabled;
7655 task->mEnmFaultToleranceState = enmFaultToleranceState;
7656
7657 /* Reset differencing hard disks for which autoReset is true,
7658 * but only if the machine has no snapshots OR the current snapshot
7659 * is an OFFLINE snapshot; otherwise we would reset the current
7660 * differencing image of an ONLINE snapshot which contains the disk
7661 * state of the machine while it was previously running, but without
7662 * the corresponding machine state, which is equivalent to powering
7663 * off a running machine and not good idea
7664 */
7665 ComPtr<ISnapshot> pCurrentSnapshot;
7666 rc = mMachine->COMGETTER(CurrentSnapshot)(pCurrentSnapshot.asOutParam());
7667 if (FAILED(rc))
7668 throw rc;
7669
7670 BOOL fCurrentSnapshotIsOnline = false;
7671 if (pCurrentSnapshot)
7672 {
7673 rc = pCurrentSnapshot->COMGETTER(Online)(&fCurrentSnapshotIsOnline);
7674 if (FAILED(rc))
7675 throw rc;
7676 }
7677
7678 if (savedStateFile.isEmpty() && !fCurrentSnapshotIsOnline)
7679 {
7680 LogFlowThisFunc(("Looking for immutable images to reset\n"));
7681
7682 com::SafeIfaceArray<IMediumAttachment> atts;
7683 rc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
7684 if (FAILED(rc))
7685 throw rc;
7686
7687 for (size_t i = 0;
7688 i < atts.size();
7689 ++i)
7690 {
7691 DeviceType_T devType;
7692 rc = atts[i]->COMGETTER(Type)(&devType);
7693 /** @todo later applies to floppies as well */
7694 if (devType == DeviceType_HardDisk)
7695 {
7696 ComPtr<IMedium> pMedium;
7697 rc = atts[i]->COMGETTER(Medium)(pMedium.asOutParam());
7698 if (FAILED(rc))
7699 throw rc;
7700
7701 /* needs autoreset? */
7702 BOOL autoReset = FALSE;
7703 rc = pMedium->COMGETTER(AutoReset)(&autoReset);
7704 if (FAILED(rc))
7705 throw rc;
7706
7707 if (autoReset)
7708 {
7709 ComPtr<IProgress> pResetProgress;
7710 rc = pMedium->Reset(pResetProgress.asOutParam());
7711 if (FAILED(rc))
7712 throw rc;
7713
7714 /* save for later use on the powerup thread */
7715 task->hardDiskProgresses.push_back(pResetProgress);
7716 }
7717 }
7718 }
7719 }
7720 else
7721 LogFlowThisFunc(("Machine has a current snapshot which is online, skipping immutable images reset\n"));
7722
7723 /* setup task object and thread to carry out the operation
7724 * asynchronously */
7725
7726#ifdef VBOX_WITH_EXTPACK
7727 mptrExtPackManager->i_dumpAllToReleaseLog();
7728#endif
7729
7730#ifdef RT_OS_SOLARIS
7731 /* setup host core dumper for the VM */
7732 Bstr value;
7733 HRESULT hrc = mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpEnabled").raw(), value.asOutParam());
7734 if (SUCCEEDED(hrc) && value == "1")
7735 {
7736 Bstr coreDumpDir, coreDumpReplaceSys, coreDumpLive;
7737 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpDir").raw(), coreDumpDir.asOutParam());
7738 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpReplaceSystemDump").raw(), coreDumpReplaceSys.asOutParam());
7739 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpLive").raw(), coreDumpLive.asOutParam());
7740
7741 uint32_t fCoreFlags = 0;
7742 if ( coreDumpReplaceSys.isEmpty() == false
7743 && Utf8Str(coreDumpReplaceSys).toUInt32() == 1)
7744 fCoreFlags |= RTCOREDUMPER_FLAGS_REPLACE_SYSTEM_DUMP;
7745
7746 if ( coreDumpLive.isEmpty() == false
7747 && Utf8Str(coreDumpLive).toUInt32() == 1)
7748 fCoreFlags |= RTCOREDUMPER_FLAGS_LIVE_CORE;
7749
7750 Utf8Str strDumpDir(coreDumpDir);
7751 const char *pszDumpDir = strDumpDir.c_str();
7752 if ( pszDumpDir
7753 && *pszDumpDir == '\0')
7754 pszDumpDir = NULL;
7755
7756 int vrc;
7757 if ( pszDumpDir
7758 && !RTDirExists(pszDumpDir))
7759 {
7760 /*
7761 * Try create the directory.
7762 */
7763 vrc = RTDirCreateFullPath(pszDumpDir, 0700);
7764 if (RT_FAILURE(vrc))
7765 throw setErrorBoth(E_FAIL, vrc, "Failed to setup CoreDumper. Couldn't create dump directory '%s' (%Rrc)\n",
7766 pszDumpDir, vrc);
7767 }
7768
7769 vrc = RTCoreDumperSetup(pszDumpDir, fCoreFlags);
7770 if (RT_FAILURE(vrc))
7771 throw setErrorBoth(E_FAIL, vrc, "Failed to setup CoreDumper (%Rrc)", vrc);
7772 LogRel(("CoreDumper setup successful. pszDumpDir=%s fFlags=%#x\n", pszDumpDir ? pszDumpDir : ".", fCoreFlags));
7773 }
7774#endif
7775
7776
7777 // If there is immutable drive the process that.
7778 VMPowerUpTask::ProgressList progresses(task->hardDiskProgresses);
7779 if (aProgress && !progresses.empty())
7780 {
7781 for (VMPowerUpTask::ProgressList::const_iterator it = progresses.begin(); it != progresses.end(); ++it)
7782 {
7783 ++cOperations;
7784 ulTotalOperationsWeight += 1;
7785 }
7786 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7787 progressDesc.raw(),
7788 TRUE, // Cancelable
7789 cOperations,
7790 ulTotalOperationsWeight,
7791 Bstr(tr("Starting Hard Disk operations")).raw(),
7792 1);
7793 AssertComRCReturnRC(rc);
7794 }
7795 else if ( mMachineState == MachineState_Saved
7796 || (!fTeleporterEnabled && !fFaultToleranceSyncEnabled))
7797 {
7798 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7799 progressDesc.raw(),
7800 FALSE /* aCancelable */);
7801 }
7802 else if (fTeleporterEnabled)
7803 {
7804 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7805 progressDesc.raw(),
7806 TRUE /* aCancelable */,
7807 3 /* cOperations */,
7808 10 /* ulTotalOperationsWeight */,
7809 Bstr(tr("Teleporting virtual machine")).raw(),
7810 1 /* ulFirstOperationWeight */);
7811 }
7812 else if (fFaultToleranceSyncEnabled)
7813 {
7814 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7815 progressDesc.raw(),
7816 TRUE /* aCancelable */,
7817 3 /* cOperations */,
7818 10 /* ulTotalOperationsWeight */,
7819 Bstr(tr("Fault Tolerance syncing of remote virtual machine")).raw(),
7820 1 /* ulFirstOperationWeight */);
7821 }
7822
7823 if (FAILED(rc))
7824 throw rc;
7825
7826 /* Tell VBoxSVC and Machine about the progress object so they can
7827 combine/proxy it to any openRemoteSession caller. */
7828 LogFlowThisFunc(("Calling BeginPowerUp...\n"));
7829 rc = mControl->BeginPowerUp(pPowerupProgress);
7830 if (FAILED(rc))
7831 {
7832 LogFlowThisFunc(("BeginPowerUp failed\n"));
7833 throw rc;
7834 }
7835 fBeganPoweringUp = true;
7836
7837 LogFlowThisFunc(("Checking if canceled...\n"));
7838 BOOL fCanceled;
7839 rc = pPowerupProgress->COMGETTER(Canceled)(&fCanceled);
7840 if (FAILED(rc))
7841 throw rc;
7842
7843 if (fCanceled)
7844 {
7845 LogFlowThisFunc(("Canceled in BeginPowerUp\n"));
7846 throw setError(E_FAIL, tr("Powerup was canceled"));
7847 }
7848 LogFlowThisFunc(("Not canceled yet.\n"));
7849
7850 /** @todo this code prevents starting a VM with unavailable bridged
7851 * networking interface. The only benefit is a slightly better error
7852 * message, which should be moved to the driver code. This is the
7853 * only reason why I left the code in for now. The driver allows
7854 * unavailable bridged networking interfaces in certain circumstances,
7855 * and this is sabotaged by this check. The VM will initially have no
7856 * network connectivity, but the user can fix this at runtime. */
7857#if 0
7858 /* the network cards will undergo a quick consistency check */
7859 for (ULONG slot = 0;
7860 slot < maxNetworkAdapters;
7861 ++slot)
7862 {
7863 ComPtr<INetworkAdapter> pNetworkAdapter;
7864 mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
7865 BOOL enabled = FALSE;
7866 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
7867 if (!enabled)
7868 continue;
7869
7870 NetworkAttachmentType_T netattach;
7871 pNetworkAdapter->COMGETTER(AttachmentType)(&netattach);
7872 switch (netattach)
7873 {
7874 case NetworkAttachmentType_Bridged:
7875 {
7876 /* a valid host interface must have been set */
7877 Bstr hostif;
7878 pNetworkAdapter->COMGETTER(HostInterface)(hostif.asOutParam());
7879 if (hostif.isEmpty())
7880 {
7881 throw setError(VBOX_E_HOST_ERROR,
7882 tr("VM cannot start because host interface networking requires a host interface name to be set"));
7883 }
7884 ComPtr<IVirtualBox> pVirtualBox;
7885 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
7886 ComPtr<IHost> pHost;
7887 pVirtualBox->COMGETTER(Host)(pHost.asOutParam());
7888 ComPtr<IHostNetworkInterface> pHostInterface;
7889 if (!SUCCEEDED(pHost->FindHostNetworkInterfaceByName(hostif.raw(),
7890 pHostInterface.asOutParam())))
7891 {
7892 throw setError(VBOX_E_HOST_ERROR,
7893 tr("VM cannot start because the host interface '%ls' does not exist"), hostif.raw());
7894 }
7895 break;
7896 }
7897 default:
7898 break;
7899 }
7900 }
7901#endif // 0
7902
7903
7904 /* setup task object and thread to carry out the operation
7905 * asynchronously */
7906 if (aProgress){
7907 rc = pPowerupProgress.queryInterfaceTo(aProgress);
7908 AssertComRCReturnRC(rc);
7909 }
7910
7911 rc = task->createThread();
7912
7913 if (FAILED(rc))
7914 throw rc;
7915
7916 /* finally, set the state: no right to fail in this method afterwards
7917 * since we've already started the thread and it is now responsible for
7918 * any error reporting and appropriate state change! */
7919 if (mMachineState == MachineState_Saved)
7920 i_setMachineState(MachineState_Restoring);
7921 else if (fTeleporterEnabled)
7922 i_setMachineState(MachineState_TeleportingIn);
7923 else if (enmFaultToleranceState == FaultToleranceState_Standby)
7924 i_setMachineState(MachineState_FaultTolerantSyncing);
7925 else
7926 i_setMachineState(MachineState_Starting);
7927 }
7928 catch (HRESULT aRC) { rc = aRC; }
7929
7930 if (FAILED(rc) && fBeganPoweringUp)
7931 {
7932
7933 /* The progress object will fetch the current error info */
7934 if (!pPowerupProgress.isNull())
7935 pPowerupProgress->i_notifyComplete(rc);
7936
7937 /* Save the error info across the IPC below. Can't be done before the
7938 * progress notification above, as saving the error info deletes it
7939 * from the current context, and thus the progress object wouldn't be
7940 * updated correctly. */
7941 ErrorInfoKeeper eik;
7942
7943 /* signal end of operation */
7944 mControl->EndPowerUp(rc);
7945 }
7946
7947 LogFlowThisFunc(("mMachineState=%d, rc=%Rhrc\n", mMachineState, rc));
7948 LogFlowThisFuncLeave();
7949 return rc;
7950}
7951
7952/**
7953 * Internal power off worker routine.
7954 *
7955 * This method may be called only at certain places with the following meaning
7956 * as shown below:
7957 *
7958 * - if the machine state is either Running or Paused, a normal
7959 * Console-initiated powerdown takes place (e.g. PowerDown());
7960 * - if the machine state is Saving, saveStateThread() has successfully done its
7961 * job;
7962 * - if the machine state is Starting or Restoring, powerUpThread() has failed
7963 * to start/load the VM;
7964 * - if the machine state is Stopping, the VM has powered itself off (i.e. not
7965 * as a result of the powerDown() call).
7966 *
7967 * Calling it in situations other than the above will cause unexpected behavior.
7968 *
7969 * Note that this method should be the only one that destroys mpUVM and sets it
7970 * to NULL.
7971 *
7972 * @param aProgress Progress object to run (may be NULL).
7973 *
7974 * @note Locks this object for writing.
7975 *
7976 * @note Never call this method from a thread that called addVMCaller() or
7977 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
7978 * release(). Otherwise it will deadlock.
7979 */
7980HRESULT Console::i_powerDown(IProgress *aProgress /*= NULL*/)
7981{
7982 LogFlowThisFuncEnter();
7983
7984 AutoCaller autoCaller(this);
7985 AssertComRCReturnRC(autoCaller.rc());
7986
7987 ComPtr<IInternalProgressControl> pProgressControl(aProgress);
7988
7989 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7990
7991 /* Total # of steps for the progress object. Must correspond to the
7992 * number of "advance percent count" comments in this method! */
7993 enum { StepCount = 7 };
7994 /* current step */
7995 ULONG step = 0;
7996
7997 HRESULT rc = S_OK;
7998 int vrc = VINF_SUCCESS;
7999
8000 /* sanity */
8001 Assert(mVMDestroying == false);
8002
8003 PUVM pUVM = mpUVM; Assert(pUVM != NULL);
8004 uint32_t cRefs = VMR3RetainUVM(pUVM); Assert(cRefs != UINT32_MAX); NOREF(cRefs);
8005
8006 AssertMsg( mMachineState == MachineState_Running
8007 || mMachineState == MachineState_Paused
8008 || mMachineState == MachineState_Stuck
8009 || mMachineState == MachineState_Starting
8010 || mMachineState == MachineState_Stopping
8011 || mMachineState == MachineState_Saving
8012 || mMachineState == MachineState_Restoring
8013 || mMachineState == MachineState_TeleportingPausedVM
8014 || mMachineState == MachineState_FaultTolerantSyncing
8015 || mMachineState == MachineState_TeleportingIn
8016 , ("Invalid machine state: %s\n", Global::stringifyMachineState(mMachineState)));
8017
8018 LogRel(("Console::powerDown(): A request to power off the VM has been issued (mMachineState=%s, InUninit=%d)\n",
8019 Global::stringifyMachineState(mMachineState), getObjectState().getState() == ObjectState::InUninit));
8020
8021 /* Check if we need to power off the VM. In case of mVMPoweredOff=true, the
8022 * VM has already powered itself off in vmstateChangeCallback() and is just
8023 * notifying Console about that. In case of Starting or Restoring,
8024 * powerUpThread() is calling us on failure, so the VM is already off at
8025 * that point. */
8026 if ( !mVMPoweredOff
8027 && ( mMachineState == MachineState_Starting
8028 || mMachineState == MachineState_Restoring
8029 || mMachineState == MachineState_FaultTolerantSyncing
8030 || mMachineState == MachineState_TeleportingIn)
8031 )
8032 mVMPoweredOff = true;
8033
8034 /*
8035 * Go to Stopping state if not already there.
8036 *
8037 * Note that we don't go from Saving/Restoring to Stopping because
8038 * vmstateChangeCallback() needs it to set the state to Saved on
8039 * VMSTATE_TERMINATED. In terms of protecting from inappropriate operations
8040 * while leaving the lock below, Saving or Restoring should be fine too.
8041 * Ditto for TeleportingPausedVM -> Teleported.
8042 */
8043 if ( mMachineState != MachineState_Saving
8044 && mMachineState != MachineState_Restoring
8045 && mMachineState != MachineState_Stopping
8046 && mMachineState != MachineState_TeleportingIn
8047 && mMachineState != MachineState_TeleportingPausedVM
8048 && mMachineState != MachineState_FaultTolerantSyncing
8049 )
8050 i_setMachineState(MachineState_Stopping);
8051
8052 /* ----------------------------------------------------------------------
8053 * DONE with necessary state changes, perform the power down actions (it's
8054 * safe to release the object lock now if needed)
8055 * ---------------------------------------------------------------------- */
8056
8057 if (mDisplay)
8058 {
8059 alock.release();
8060
8061 mDisplay->i_notifyPowerDown();
8062
8063 alock.acquire();
8064 }
8065
8066 /* Stop the VRDP server to prevent new clients connection while VM is being
8067 * powered off. */
8068 if (mConsoleVRDPServer)
8069 {
8070 LogFlowThisFunc(("Stopping VRDP server...\n"));
8071
8072 /* Leave the lock since EMT could call us back as addVMCaller() */
8073 alock.release();
8074
8075 mConsoleVRDPServer->Stop();
8076
8077 alock.acquire();
8078 }
8079
8080 /* advance percent count */
8081 if (pProgressControl)
8082 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8083
8084
8085 /* ----------------------------------------------------------------------
8086 * Now, wait for all mpUVM callers to finish their work if there are still
8087 * some on other threads. NO methods that need mpUVM (or initiate other calls
8088 * that need it) may be called after this point
8089 * ---------------------------------------------------------------------- */
8090
8091 /* go to the destroying state to prevent from adding new callers */
8092 mVMDestroying = true;
8093
8094 if (mVMCallers > 0)
8095 {
8096 /* lazy creation */
8097 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
8098 RTSemEventCreate(&mVMZeroCallersSem);
8099
8100 LogFlowThisFunc(("Waiting for mpUVM callers (%d) to drop to zero...\n", mVMCallers));
8101
8102 alock.release();
8103
8104 RTSemEventWait(mVMZeroCallersSem, RT_INDEFINITE_WAIT);
8105
8106 alock.acquire();
8107 }
8108
8109 /* advance percent count */
8110 if (pProgressControl)
8111 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8112
8113 vrc = VINF_SUCCESS;
8114
8115 /*
8116 * Power off the VM if not already done that.
8117 * Leave the lock since EMT will call vmstateChangeCallback.
8118 *
8119 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
8120 * VM-(guest-)initiated power off happened in parallel a ms before this
8121 * call. So far, we let this error pop up on the user's side.
8122 */
8123 if (!mVMPoweredOff)
8124 {
8125 LogFlowThisFunc(("Powering off the VM...\n"));
8126 alock.release();
8127 vrc = VMR3PowerOff(pUVM);
8128#ifdef VBOX_WITH_EXTPACK
8129 mptrExtPackManager->i_callAllVmPowerOffHooks(this, VMR3GetVM(pUVM));
8130#endif
8131 alock.acquire();
8132 }
8133
8134 /* advance percent count */
8135 if (pProgressControl)
8136 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8137
8138#ifdef VBOX_WITH_HGCM
8139 /* Shutdown HGCM services before destroying the VM. */
8140 if (m_pVMMDev)
8141 {
8142 LogFlowThisFunc(("Shutdown HGCM...\n"));
8143
8144 /* Leave the lock since EMT might wait for it and will call us back as addVMCaller() */
8145 alock.release();
8146
8147 DBGFR3InfoDeregisterExternal(pUVM, "guestprops"); /* will crash in unloaded code if we guru later */
8148 m_pVMMDev->hgcmShutdown();
8149
8150 alock.acquire();
8151 }
8152
8153 /* advance percent count */
8154 if (pProgressControl)
8155 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8156
8157#endif /* VBOX_WITH_HGCM */
8158
8159 LogFlowThisFunc(("Ready for VM destruction.\n"));
8160
8161 /* If we are called from Console::uninit(), then try to destroy the VM even
8162 * on failure (this will most likely fail too, but what to do?..) */
8163 if (RT_SUCCESS(vrc) || getObjectState().getState() == ObjectState::InUninit)
8164 {
8165 /* If the machine has a USB controller, release all USB devices
8166 * (symmetric to the code in captureUSBDevices()) */
8167 if (mfVMHasUsbController)
8168 {
8169 alock.release();
8170 i_detachAllUSBDevices(false /* aDone */);
8171 alock.acquire();
8172 }
8173
8174 /* Now we've got to destroy the VM as well. (mpUVM is not valid beyond
8175 * this point). We release the lock before calling VMR3Destroy() because
8176 * it will result into calling destructors of drivers associated with
8177 * Console children which may in turn try to lock Console (e.g. by
8178 * instantiating SafeVMPtr to access mpUVM). It's safe here because
8179 * mVMDestroying is set which should prevent any activity. */
8180
8181 /* Set mpUVM to NULL early just in case if some old code is not using
8182 * addVMCaller()/releaseVMCaller(). (We have our own ref on pUVM.) */
8183 VMR3ReleaseUVM(mpUVM);
8184 mpUVM = NULL;
8185
8186 LogFlowThisFunc(("Destroying the VM...\n"));
8187
8188 alock.release();
8189
8190 vrc = VMR3Destroy(pUVM);
8191
8192 /* take the lock again */
8193 alock.acquire();
8194
8195 /* advance percent count */
8196 if (pProgressControl)
8197 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8198
8199 if (RT_SUCCESS(vrc))
8200 {
8201 LogFlowThisFunc(("Machine has been destroyed (mMachineState=%d)\n",
8202 mMachineState));
8203 /* Note: the Console-level machine state change happens on the
8204 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
8205 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
8206 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
8207 * occurred yet. This is okay, because mMachineState is already
8208 * Stopping in this case, so any other attempt to call PowerDown()
8209 * will be rejected. */
8210 }
8211 else
8212 {
8213 /* bad bad bad, but what to do? (Give Console our UVM ref.) */
8214 mpUVM = pUVM;
8215 pUVM = NULL;
8216 rc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not destroy the machine. (Error: %Rrc)"), vrc);
8217 }
8218
8219 /* Complete the detaching of the USB devices. */
8220 if (mfVMHasUsbController)
8221 {
8222 alock.release();
8223 i_detachAllUSBDevices(true /* aDone */);
8224 alock.acquire();
8225 }
8226
8227 /* advance percent count */
8228 if (pProgressControl)
8229 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8230 }
8231 else
8232 rc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not power off the machine. (Error: %Rrc)"), vrc);
8233
8234 /*
8235 * Finished with the destruction.
8236 *
8237 * Note that if something impossible happened and we've failed to destroy
8238 * the VM, mVMDestroying will remain true and mMachineState will be
8239 * something like Stopping, so most Console methods will return an error
8240 * to the caller.
8241 */
8242 if (pUVM != NULL)
8243 VMR3ReleaseUVM(pUVM);
8244 else
8245 mVMDestroying = false;
8246
8247 LogFlowThisFuncLeave();
8248 return rc;
8249}
8250
8251/**
8252 * @note Locks this object for writing.
8253 */
8254HRESULT Console::i_setMachineState(MachineState_T aMachineState,
8255 bool aUpdateServer /* = true */)
8256{
8257 AutoCaller autoCaller(this);
8258 AssertComRCReturnRC(autoCaller.rc());
8259
8260 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8261
8262 HRESULT rc = S_OK;
8263
8264 if (mMachineState != aMachineState)
8265 {
8266 LogThisFunc(("machineState=%s -> %s aUpdateServer=%RTbool\n",
8267 Global::stringifyMachineState(mMachineState), Global::stringifyMachineState(aMachineState), aUpdateServer));
8268 LogRel(("Console: Machine state changed to '%s'\n", Global::stringifyMachineState(aMachineState)));
8269 mMachineState = aMachineState;
8270
8271 /// @todo (dmik)
8272 // possibly, we need to redo onStateChange() using the dedicated
8273 // Event thread, like it is done in VirtualBox. This will make it
8274 // much safer (no deadlocks possible if someone tries to use the
8275 // console from the callback), however, listeners will lose the
8276 // ability to synchronously react to state changes (is it really
8277 // necessary??)
8278 LogFlowThisFunc(("Doing onStateChange()...\n"));
8279 i_onStateChange(aMachineState);
8280 LogFlowThisFunc(("Done onStateChange()\n"));
8281
8282 if (aUpdateServer)
8283 {
8284 /* Server notification MUST be done from under the lock; otherwise
8285 * the machine state here and on the server might go out of sync
8286 * which can lead to various unexpected results (like the machine
8287 * state being >= MachineState_Running on the server, while the
8288 * session state is already SessionState_Unlocked at the same time
8289 * there).
8290 *
8291 * Cross-lock conditions should be carefully watched out: calling
8292 * UpdateState we will require Machine and SessionMachine locks
8293 * (remember that here we're holding the Console lock here, and also
8294 * all locks that have been acquire by the thread before calling
8295 * this method).
8296 */
8297 LogFlowThisFunc(("Doing mControl->UpdateState()...\n"));
8298 rc = mControl->UpdateState(aMachineState);
8299 LogFlowThisFunc(("mControl->UpdateState()=%Rhrc\n", rc));
8300 }
8301 }
8302
8303 return rc;
8304}
8305
8306/**
8307 * Searches for a shared folder with the given logical name
8308 * in the collection of shared folders.
8309 *
8310 * @param strName logical name of the shared folder
8311 * @param aSharedFolder where to return the found object
8312 * @param aSetError whether to set the error info if the folder is
8313 * not found
8314 * @return
8315 * S_OK when found or E_INVALIDARG when not found
8316 *
8317 * @note The caller must lock this object for writing.
8318 */
8319HRESULT Console::i_findSharedFolder(const Utf8Str &strName,
8320 ComObjPtr<SharedFolder> &aSharedFolder,
8321 bool aSetError /* = false */)
8322{
8323 /* sanity check */
8324 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8325
8326 SharedFolderMap::const_iterator it = m_mapSharedFolders.find(strName);
8327 if (it != m_mapSharedFolders.end())
8328 {
8329 aSharedFolder = it->second;
8330 return S_OK;
8331 }
8332
8333 if (aSetError)
8334 setError(VBOX_E_FILE_ERROR, tr("Could not find a shared folder named '%s'."), strName.c_str());
8335
8336 return VBOX_E_FILE_ERROR;
8337}
8338
8339/**
8340 * Fetches the list of global or machine shared folders from the server.
8341 *
8342 * @param aGlobal true to fetch global folders.
8343 *
8344 * @note The caller must lock this object for writing.
8345 */
8346HRESULT Console::i_fetchSharedFolders(BOOL aGlobal)
8347{
8348 /* sanity check */
8349 AssertReturn( getObjectState().getState() == ObjectState::InInit
8350 || isWriteLockOnCurrentThread(), E_FAIL);
8351
8352 LogFlowThisFunc(("Entering\n"));
8353
8354 /* Check if we're online and keep it that way. */
8355 SafeVMPtrQuiet ptrVM(this);
8356 AutoVMCallerQuietWeak autoVMCaller(this);
8357 bool const online = ptrVM.isOk()
8358 && m_pVMMDev
8359 && m_pVMMDev->isShFlActive();
8360
8361 HRESULT rc = S_OK;
8362
8363 try
8364 {
8365 if (aGlobal)
8366 {
8367 /// @todo grab & process global folders when they are done
8368 }
8369 else
8370 {
8371 SharedFolderDataMap oldFolders;
8372 if (online)
8373 oldFolders = m_mapMachineSharedFolders;
8374
8375 m_mapMachineSharedFolders.clear();
8376
8377 SafeIfaceArray<ISharedFolder> folders;
8378 rc = mMachine->COMGETTER(SharedFolders)(ComSafeArrayAsOutParam(folders));
8379 if (FAILED(rc)) throw rc;
8380
8381 for (size_t i = 0; i < folders.size(); ++i)
8382 {
8383 ComPtr<ISharedFolder> pSharedFolder = folders[i];
8384
8385 Bstr bstrName;
8386 Bstr bstrHostPath;
8387 BOOL writable;
8388 BOOL autoMount;
8389
8390 rc = pSharedFolder->COMGETTER(Name)(bstrName.asOutParam());
8391 if (FAILED(rc)) throw rc;
8392 Utf8Str strName(bstrName);
8393
8394 rc = pSharedFolder->COMGETTER(HostPath)(bstrHostPath.asOutParam());
8395 if (FAILED(rc)) throw rc;
8396 Utf8Str strHostPath(bstrHostPath);
8397
8398 rc = pSharedFolder->COMGETTER(Writable)(&writable);
8399 if (FAILED(rc)) throw rc;
8400
8401 rc = pSharedFolder->COMGETTER(AutoMount)(&autoMount);
8402 if (FAILED(rc)) throw rc;
8403
8404 m_mapMachineSharedFolders.insert(std::make_pair(strName,
8405 SharedFolderData(strHostPath, !!writable, !!autoMount)));
8406
8407 /* send changes to HGCM if the VM is running */
8408 if (online)
8409 {
8410 SharedFolderDataMap::iterator it = oldFolders.find(strName);
8411 if ( it == oldFolders.end()
8412 || it->second.m_strHostPath != strHostPath)
8413 {
8414 /* a new machine folder is added or
8415 * the existing machine folder is changed */
8416 if (m_mapSharedFolders.find(strName) != m_mapSharedFolders.end())
8417 ; /* the console folder exists, nothing to do */
8418 else
8419 {
8420 /* remove the old machine folder (when changed)
8421 * or the global folder if any (when new) */
8422 if ( it != oldFolders.end()
8423 || m_mapGlobalSharedFolders.find(strName) != m_mapGlobalSharedFolders.end()
8424 )
8425 {
8426 rc = i_removeSharedFolder(strName);
8427 if (FAILED(rc)) throw rc;
8428 }
8429
8430 /* create the new machine folder */
8431 rc = i_createSharedFolder(strName,
8432 SharedFolderData(strHostPath, !!writable, !!autoMount));
8433 if (FAILED(rc)) throw rc;
8434 }
8435 }
8436 /* forget the processed (or identical) folder */
8437 if (it != oldFolders.end())
8438 oldFolders.erase(it);
8439 }
8440 }
8441
8442 /* process outdated (removed) folders */
8443 if (online)
8444 {
8445 for (SharedFolderDataMap::const_iterator it = oldFolders.begin();
8446 it != oldFolders.end(); ++it)
8447 {
8448 if (m_mapSharedFolders.find(it->first) != m_mapSharedFolders.end())
8449 ; /* the console folder exists, nothing to do */
8450 else
8451 {
8452 /* remove the outdated machine folder */
8453 rc = i_removeSharedFolder(it->first);
8454 if (FAILED(rc)) throw rc;
8455
8456 /* create the global folder if there is any */
8457 SharedFolderDataMap::const_iterator git =
8458 m_mapGlobalSharedFolders.find(it->first);
8459 if (git != m_mapGlobalSharedFolders.end())
8460 {
8461 rc = i_createSharedFolder(git->first, git->second);
8462 if (FAILED(rc)) throw rc;
8463 }
8464 }
8465 }
8466 }
8467 }
8468 }
8469 catch (HRESULT rc2)
8470 {
8471 rc = rc2;
8472 if (online)
8473 i_atVMRuntimeErrorCallbackF(0, "BrokenSharedFolder", N_("Broken shared folder!"));
8474 }
8475
8476 LogFlowThisFunc(("Leaving\n"));
8477
8478 return rc;
8479}
8480
8481/**
8482 * Searches for a shared folder with the given name in the list of machine
8483 * shared folders and then in the list of the global shared folders.
8484 *
8485 * @param strName Name of the folder to search for.
8486 * @param aIt Where to store the pointer to the found folder.
8487 * @return @c true if the folder was found and @c false otherwise.
8488 *
8489 * @note The caller must lock this object for reading.
8490 */
8491bool Console::i_findOtherSharedFolder(const Utf8Str &strName,
8492 SharedFolderDataMap::const_iterator &aIt)
8493{
8494 /* sanity check */
8495 AssertReturn(isWriteLockOnCurrentThread(), false);
8496
8497 /* first, search machine folders */
8498 aIt = m_mapMachineSharedFolders.find(strName);
8499 if (aIt != m_mapMachineSharedFolders.end())
8500 return true;
8501
8502 /* second, search machine folders */
8503 aIt = m_mapGlobalSharedFolders.find(strName);
8504 if (aIt != m_mapGlobalSharedFolders.end())
8505 return true;
8506
8507 return false;
8508}
8509
8510/**
8511 * Calls the HGCM service to add a shared folder definition.
8512 *
8513 * @param strName Shared folder name.
8514 * @param aData Shared folder data.
8515 *
8516 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
8517 * @note Doesn't lock anything.
8518 */
8519HRESULT Console::i_createSharedFolder(const Utf8Str &strName, const SharedFolderData &aData)
8520{
8521 ComAssertRet(strName.isNotEmpty(), E_FAIL);
8522 ComAssertRet(aData.m_strHostPath.isNotEmpty(), E_FAIL);
8523
8524 /* sanity checks */
8525 AssertReturn(mpUVM, E_FAIL);
8526 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
8527
8528 VBOXHGCMSVCPARM parms[SHFL_CPARMS_ADD_MAPPING];
8529 SHFLSTRING *pFolderName, *pMapName;
8530 size_t cbString;
8531
8532 Bstr value;
8533 HRESULT hrc = mMachine->GetExtraData(BstrFmt("VBoxInternal2/SharedFoldersEnableSymlinksCreate/%s",
8534 strName.c_str()).raw(),
8535 value.asOutParam());
8536 bool fSymlinksCreate = hrc == S_OK && value == "1";
8537
8538 Log(("Adding shared folder '%s' -> '%s'\n", strName.c_str(), aData.m_strHostPath.c_str()));
8539
8540 // check whether the path is valid and exists
8541 char hostPathFull[RTPATH_MAX];
8542 int vrc = RTPathAbsEx(NULL,
8543 aData.m_strHostPath.c_str(),
8544 hostPathFull,
8545 sizeof(hostPathFull));
8546
8547 bool fMissing = false;
8548 if (RT_FAILURE(vrc))
8549 return setErrorBoth(E_INVALIDARG, vrc, tr("Invalid shared folder path: '%s' (%Rrc)"), aData.m_strHostPath.c_str(), vrc);
8550 if (!RTPathExists(hostPathFull))
8551 fMissing = true;
8552
8553 /* Check whether the path is full (absolute) */
8554 if (RTPathCompare(aData.m_strHostPath.c_str(), hostPathFull) != 0)
8555 return setError(E_INVALIDARG,
8556 tr("Shared folder path '%s' is not absolute"),
8557 aData.m_strHostPath.c_str());
8558
8559 // now that we know the path is good, give it to HGCM
8560
8561 Bstr bstrName(strName);
8562 Bstr bstrHostPath(aData.m_strHostPath);
8563
8564 cbString = (bstrHostPath.length() + 1) * sizeof(RTUTF16);
8565 if (cbString >= UINT16_MAX)
8566 return setError(E_INVALIDARG, tr("The name is too long"));
8567 pFolderName = (SHFLSTRING*)RTMemAllocZ(SHFLSTRING_HEADER_SIZE + cbString);
8568 Assert(pFolderName);
8569 memcpy(pFolderName->String.ucs2, bstrHostPath.raw(), cbString);
8570
8571 pFolderName->u16Size = (uint16_t)cbString;
8572 pFolderName->u16Length = (uint16_t)(cbString - sizeof(RTUTF16));
8573
8574 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
8575 parms[0].u.pointer.addr = pFolderName;
8576 parms[0].u.pointer.size = ShflStringSizeOfBuffer(pFolderName);
8577
8578 cbString = (bstrName.length() + 1) * sizeof(RTUTF16);
8579 if (cbString >= UINT16_MAX)
8580 {
8581 RTMemFree(pFolderName);
8582 return setError(E_INVALIDARG, tr("The host path is too long"));
8583 }
8584 pMapName = (SHFLSTRING*)RTMemAllocZ(SHFLSTRING_HEADER_SIZE + cbString);
8585 Assert(pMapName);
8586 memcpy(pMapName->String.ucs2, bstrName.raw(), cbString);
8587
8588 pMapName->u16Size = (uint16_t)cbString;
8589 pMapName->u16Length = (uint16_t)(cbString - sizeof(RTUTF16));
8590
8591 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
8592 parms[1].u.pointer.addr = pMapName;
8593 parms[1].u.pointer.size = ShflStringSizeOfBuffer(pMapName);
8594
8595 parms[2].type = VBOX_HGCM_SVC_PARM_32BIT;
8596 parms[2].u.uint32 = (aData.m_fWritable ? SHFL_ADD_MAPPING_F_WRITABLE : 0)
8597 | (aData.m_fAutoMount ? SHFL_ADD_MAPPING_F_AUTOMOUNT : 0)
8598 | (fSymlinksCreate ? SHFL_ADD_MAPPING_F_CREATE_SYMLINKS : 0)
8599 | (fMissing ? SHFL_ADD_MAPPING_F_MISSING : 0)
8600 ;
8601
8602 vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders",
8603 SHFL_FN_ADD_MAPPING,
8604 SHFL_CPARMS_ADD_MAPPING, &parms[0]);
8605 RTMemFree(pFolderName);
8606 RTMemFree(pMapName);
8607
8608 if (RT_FAILURE(vrc))
8609 return setErrorBoth(E_FAIL, vrc, tr("Could not create a shared folder '%s' mapped to '%s' (%Rrc)"),
8610 strName.c_str(), aData.m_strHostPath.c_str(), vrc);
8611
8612 if (fMissing)
8613 return setError(E_INVALIDARG,
8614 tr("Shared folder path '%s' does not exist on the host"),
8615 aData.m_strHostPath.c_str());
8616
8617 return S_OK;
8618}
8619
8620/**
8621 * Calls the HGCM service to remove the shared folder definition.
8622 *
8623 * @param strName Shared folder name.
8624 *
8625 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
8626 * @note Doesn't lock anything.
8627 */
8628HRESULT Console::i_removeSharedFolder(const Utf8Str &strName)
8629{
8630 ComAssertRet(strName.isNotEmpty(), E_FAIL);
8631
8632 /* sanity checks */
8633 AssertReturn(mpUVM, E_FAIL);
8634 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
8635
8636 VBOXHGCMSVCPARM parms;
8637 SHFLSTRING *pMapName;
8638 size_t cbString;
8639
8640 Log(("Removing shared folder '%s'\n", strName.c_str()));
8641
8642 Bstr bstrName(strName);
8643 cbString = (bstrName.length() + 1) * sizeof(RTUTF16);
8644 if (cbString >= UINT16_MAX)
8645 return setError(E_INVALIDARG, tr("The name is too long"));
8646 pMapName = (SHFLSTRING *) RTMemAllocZ(SHFLSTRING_HEADER_SIZE + cbString);
8647 Assert(pMapName);
8648 memcpy(pMapName->String.ucs2, bstrName.raw(), cbString);
8649
8650 pMapName->u16Size = (uint16_t)cbString;
8651 pMapName->u16Length = (uint16_t)(cbString - sizeof(RTUTF16));
8652
8653 parms.type = VBOX_HGCM_SVC_PARM_PTR;
8654 parms.u.pointer.addr = pMapName;
8655 parms.u.pointer.size = ShflStringSizeOfBuffer(pMapName);
8656
8657 int vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders",
8658 SHFL_FN_REMOVE_MAPPING,
8659 1, &parms);
8660 RTMemFree(pMapName);
8661 if (RT_FAILURE(vrc))
8662 return setErrorBoth(E_FAIL, vrc, tr("Could not remove the shared folder '%s' (%Rrc)"), strName.c_str(), vrc);
8663
8664 return S_OK;
8665}
8666
8667/** @callback_method_impl{FNVMATSTATE}
8668 *
8669 * @note Locks the Console object for writing.
8670 * @remarks The @a pUVM parameter can be NULL in one case where powerUpThread()
8671 * calls after the VM was destroyed.
8672 */
8673DECLCALLBACK(void) Console::i_vmstateChangeCallback(PUVM pUVM, VMSTATE enmState, VMSTATE enmOldState, void *pvUser)
8674{
8675 LogFlowFunc(("Changing state from %s to %s (pUVM=%p)\n",
8676 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState), pUVM));
8677
8678 Console *that = static_cast<Console *>(pvUser);
8679 AssertReturnVoid(that);
8680
8681 AutoCaller autoCaller(that);
8682
8683 /* Note that we must let this method proceed even if Console::uninit() has
8684 * been already called. In such case this VMSTATE change is a result of:
8685 * 1) powerDown() called from uninit() itself, or
8686 * 2) VM-(guest-)initiated power off. */
8687 AssertReturnVoid( autoCaller.isOk()
8688 || that->getObjectState().getState() == ObjectState::InUninit);
8689
8690 switch (enmState)
8691 {
8692 /*
8693 * The VM has terminated
8694 */
8695 case VMSTATE_OFF:
8696 {
8697#ifdef VBOX_WITH_GUEST_PROPS
8698 if (that->i_isResetTurnedIntoPowerOff())
8699 {
8700 Bstr strPowerOffReason;
8701
8702 if (that->mfPowerOffCausedByReset)
8703 strPowerOffReason = Bstr("Reset");
8704 else
8705 strPowerOffReason = Bstr("PowerOff");
8706
8707 that->mMachine->DeleteGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw());
8708 that->mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw(),
8709 strPowerOffReason.raw(), Bstr("RDONLYGUEST").raw());
8710 that->mMachine->SaveSettings();
8711 }
8712#endif
8713
8714 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8715
8716 if (that->mVMStateChangeCallbackDisabled)
8717 return;
8718
8719 /* Do we still think that it is running? It may happen if this is a
8720 * VM-(guest-)initiated shutdown/poweroff.
8721 */
8722 if ( that->mMachineState != MachineState_Stopping
8723 && that->mMachineState != MachineState_Saving
8724 && that->mMachineState != MachineState_Restoring
8725 && that->mMachineState != MachineState_TeleportingIn
8726 && that->mMachineState != MachineState_FaultTolerantSyncing
8727 && that->mMachineState != MachineState_TeleportingPausedVM
8728 && !that->mVMIsAlreadyPoweringOff
8729 )
8730 {
8731 LogFlowFunc(("VM has powered itself off but Console still thinks it is running. Notifying.\n"));
8732
8733 /*
8734 * Prevent powerDown() from calling VMR3PowerOff() again if this was called from
8735 * the power off state change.
8736 * When called from the Reset state make sure to call VMR3PowerOff() first.
8737 */
8738 Assert(that->mVMPoweredOff == false);
8739 that->mVMPoweredOff = true;
8740
8741 /*
8742 * request a progress object from the server
8743 * (this will set the machine state to Stopping on the server
8744 * to block others from accessing this machine)
8745 */
8746 ComPtr<IProgress> pProgress;
8747 HRESULT rc = that->mControl->BeginPoweringDown(pProgress.asOutParam());
8748 AssertComRC(rc);
8749
8750 /* sync the state with the server */
8751 that->i_setMachineStateLocally(MachineState_Stopping);
8752
8753 /* Setup task object and thread to carry out the operation
8754 * asynchronously (if we call powerDown() right here but there
8755 * is one or more mpUVM callers (added with addVMCaller()) we'll
8756 * deadlock).
8757 */
8758 VMPowerDownTask* task = NULL;
8759 try
8760 {
8761 task = new VMPowerDownTask(that, pProgress);
8762 /* If creating a task failed, this can currently mean one of
8763 * two: either Console::uninit() has been called just a ms
8764 * before (so a powerDown() call is already on the way), or
8765 * powerDown() itself is being already executed. Just do
8766 * nothing.
8767 */
8768 if (!task->isOk())
8769 {
8770 LogFlowFunc(("Console is already being uninitialized. \n"));
8771 throw E_FAIL;
8772 }
8773 }
8774 catch(...)
8775 {
8776 delete task;
8777 LogFlowFunc(("Problem with creating VMPowerDownTask object. \n"));
8778 }
8779
8780 rc = task->createThread();
8781
8782 if (FAILED(rc))
8783 {
8784 LogFlowFunc(("Problem with creating thread for VMPowerDownTask. \n"));
8785 }
8786
8787 }
8788 break;
8789 }
8790
8791 /* The VM has been completely destroyed.
8792 *
8793 * Note: This state change can happen at two points:
8794 * 1) At the end of VMR3Destroy() if it was not called from EMT.
8795 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
8796 * called by EMT.
8797 */
8798 case VMSTATE_TERMINATED:
8799 {
8800 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8801
8802 if (that->mVMStateChangeCallbackDisabled)
8803 break;
8804
8805 /* Terminate host interface networking. If pUVM is NULL, we've been
8806 * manually called from powerUpThread() either before calling
8807 * VMR3Create() or after VMR3Create() failed, so no need to touch
8808 * networking.
8809 */
8810 if (pUVM)
8811 that->i_powerDownHostInterfaces();
8812
8813 /* From now on the machine is officially powered down or remains in
8814 * the Saved state.
8815 */
8816 switch (that->mMachineState)
8817 {
8818 default:
8819 AssertFailed();
8820 RT_FALL_THRU();
8821 case MachineState_Stopping:
8822 /* successfully powered down */
8823 that->i_setMachineState(MachineState_PoweredOff);
8824 break;
8825 case MachineState_Saving:
8826 /* successfully saved */
8827 that->i_setMachineState(MachineState_Saved);
8828 break;
8829 case MachineState_Starting:
8830 /* failed to start, but be patient: set back to PoweredOff
8831 * (for similarity with the below) */
8832 that->i_setMachineState(MachineState_PoweredOff);
8833 break;
8834 case MachineState_Restoring:
8835 /* failed to load the saved state file, but be patient: set
8836 * back to Saved (to preserve the saved state file) */
8837 that->i_setMachineState(MachineState_Saved);
8838 break;
8839 case MachineState_TeleportingIn:
8840 /* Teleportation failed or was canceled. Back to powered off. */
8841 that->i_setMachineState(MachineState_PoweredOff);
8842 break;
8843 case MachineState_TeleportingPausedVM:
8844 /* Successfully teleported the VM. */
8845 that->i_setMachineState(MachineState_Teleported);
8846 break;
8847 case MachineState_FaultTolerantSyncing:
8848 /* Fault tolerant sync failed or was canceled. Back to powered off. */
8849 that->i_setMachineState(MachineState_PoweredOff);
8850 break;
8851 }
8852 break;
8853 }
8854
8855 case VMSTATE_RESETTING:
8856 /** @todo shouldn't VMSTATE_RESETTING_LS be here? */
8857 {
8858#ifdef VBOX_WITH_GUEST_PROPS
8859 /* Do not take any read/write locks here! */
8860 that->i_guestPropertiesHandleVMReset();
8861#endif
8862 break;
8863 }
8864
8865 case VMSTATE_SOFT_RESETTING:
8866 case VMSTATE_SOFT_RESETTING_LS:
8867 /* Shouldn't do anything here! */
8868 break;
8869
8870 case VMSTATE_SUSPENDED:
8871 {
8872 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8873
8874 if (that->mVMStateChangeCallbackDisabled)
8875 break;
8876
8877 switch (that->mMachineState)
8878 {
8879 case MachineState_Teleporting:
8880 that->i_setMachineState(MachineState_TeleportingPausedVM);
8881 break;
8882
8883 case MachineState_LiveSnapshotting:
8884 that->i_setMachineState(MachineState_OnlineSnapshotting);
8885 break;
8886
8887 case MachineState_TeleportingPausedVM:
8888 case MachineState_Saving:
8889 case MachineState_Restoring:
8890 case MachineState_Stopping:
8891 case MachineState_TeleportingIn:
8892 case MachineState_FaultTolerantSyncing:
8893 case MachineState_OnlineSnapshotting:
8894 /* The worker thread handles the transition. */
8895 break;
8896
8897 case MachineState_Running:
8898 that->i_setMachineState(MachineState_Paused);
8899 break;
8900
8901 case MachineState_Paused:
8902 /* Nothing to do. */
8903 break;
8904
8905 default:
8906 AssertMsgFailed(("%s\n", Global::stringifyMachineState(that->mMachineState)));
8907 }
8908 break;
8909 }
8910
8911 case VMSTATE_SUSPENDED_LS:
8912 case VMSTATE_SUSPENDED_EXT_LS:
8913 {
8914 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8915 if (that->mVMStateChangeCallbackDisabled)
8916 break;
8917 switch (that->mMachineState)
8918 {
8919 case MachineState_Teleporting:
8920 that->i_setMachineState(MachineState_TeleportingPausedVM);
8921 break;
8922
8923 case MachineState_LiveSnapshotting:
8924 that->i_setMachineState(MachineState_OnlineSnapshotting);
8925 break;
8926
8927 case MachineState_TeleportingPausedVM:
8928 case MachineState_Saving:
8929 /* ignore */
8930 break;
8931
8932 default:
8933 AssertMsgFailed(("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState),
8934 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
8935 that->i_setMachineState(MachineState_Paused);
8936 break;
8937 }
8938 break;
8939 }
8940
8941 case VMSTATE_RUNNING:
8942 {
8943 if ( enmOldState == VMSTATE_POWERING_ON
8944 || enmOldState == VMSTATE_RESUMING
8945 || enmOldState == VMSTATE_RUNNING_FT)
8946 {
8947 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8948
8949 if (that->mVMStateChangeCallbackDisabled)
8950 break;
8951
8952 Assert( ( ( that->mMachineState == MachineState_Starting
8953 || that->mMachineState == MachineState_Paused)
8954 && enmOldState == VMSTATE_POWERING_ON)
8955 || ( ( that->mMachineState == MachineState_Restoring
8956 || that->mMachineState == MachineState_TeleportingIn
8957 || that->mMachineState == MachineState_Paused
8958 || that->mMachineState == MachineState_Saving
8959 )
8960 && enmOldState == VMSTATE_RESUMING)
8961 || ( that->mMachineState == MachineState_FaultTolerantSyncing
8962 && enmOldState == VMSTATE_RUNNING_FT));
8963
8964 that->i_setMachineState(MachineState_Running);
8965 }
8966
8967 break;
8968 }
8969
8970 case VMSTATE_RUNNING_LS:
8971 AssertMsg( that->mMachineState == MachineState_LiveSnapshotting
8972 || that->mMachineState == MachineState_Teleporting,
8973 ("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState),
8974 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
8975 break;
8976
8977 case VMSTATE_RUNNING_FT:
8978 AssertMsg(that->mMachineState == MachineState_FaultTolerantSyncing,
8979 ("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState),
8980 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
8981 break;
8982
8983 case VMSTATE_FATAL_ERROR:
8984 {
8985 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8986
8987 if (that->mVMStateChangeCallbackDisabled)
8988 break;
8989
8990 /* Fatal errors are only for running VMs. */
8991 Assert(Global::IsOnline(that->mMachineState));
8992
8993 /* Note! 'Pause' is used here in want of something better. There
8994 * are currently only two places where fatal errors might be
8995 * raised, so it is not worth adding a new externally
8996 * visible state for this yet. */
8997 that->i_setMachineState(MachineState_Paused);
8998 break;
8999 }
9000
9001 case VMSTATE_GURU_MEDITATION:
9002 {
9003 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9004
9005 if (that->mVMStateChangeCallbackDisabled)
9006 break;
9007
9008 /* Guru are only for running VMs */
9009 Assert(Global::IsOnline(that->mMachineState));
9010
9011 that->i_setMachineState(MachineState_Stuck);
9012 break;
9013 }
9014
9015 case VMSTATE_CREATED:
9016 {
9017 /*
9018 * We have to set the secret key helper interface for the VD drivers to
9019 * get notified about missing keys.
9020 */
9021 that->i_initSecretKeyIfOnAllAttachments();
9022 break;
9023 }
9024
9025 default: /* shut up gcc */
9026 break;
9027 }
9028}
9029
9030/**
9031 * Changes the clipboard mode.
9032 *
9033 * @param aClipboardMode new clipboard mode.
9034 */
9035void Console::i_changeClipboardMode(ClipboardMode_T aClipboardMode)
9036{
9037 VMMDev *pVMMDev = m_pVMMDev;
9038 Assert(pVMMDev);
9039
9040 VBOXHGCMSVCPARM parm;
9041 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
9042
9043 switch (aClipboardMode)
9044 {
9045 default:
9046 case ClipboardMode_Disabled:
9047 LogRel(("Shared clipboard mode: Off\n"));
9048 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_OFF;
9049 break;
9050 case ClipboardMode_GuestToHost:
9051 LogRel(("Shared clipboard mode: Guest to Host\n"));
9052 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_GUEST_TO_HOST;
9053 break;
9054 case ClipboardMode_HostToGuest:
9055 LogRel(("Shared clipboard mode: Host to Guest\n"));
9056 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_HOST_TO_GUEST;
9057 break;
9058 case ClipboardMode_Bidirectional:
9059 LogRel(("Shared clipboard mode: Bidirectional\n"));
9060 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_BIDIRECTIONAL;
9061 break;
9062 }
9063
9064 pVMMDev->hgcmHostCall("VBoxSharedClipboard", VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE, 1, &parm);
9065}
9066
9067/**
9068 * Changes the drag and drop mode.
9069 *
9070 * @param aDnDMode new drag and drop mode.
9071 */
9072int Console::i_changeDnDMode(DnDMode_T aDnDMode)
9073{
9074 VMMDev *pVMMDev = m_pVMMDev;
9075 AssertPtrReturn(pVMMDev, VERR_INVALID_POINTER);
9076
9077 VBOXHGCMSVCPARM parm;
9078 RT_ZERO(parm);
9079 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
9080
9081 switch (aDnDMode)
9082 {
9083 default:
9084 case DnDMode_Disabled:
9085 LogRel(("Drag and drop mode: Off\n"));
9086 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_OFF;
9087 break;
9088 case DnDMode_GuestToHost:
9089 LogRel(("Drag and drop mode: Guest to Host\n"));
9090 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_GUEST_TO_HOST;
9091 break;
9092 case DnDMode_HostToGuest:
9093 LogRel(("Drag and drop mode: Host to Guest\n"));
9094 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_HOST_TO_GUEST;
9095 break;
9096 case DnDMode_Bidirectional:
9097 LogRel(("Drag and drop mode: Bidirectional\n"));
9098 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_BIDIRECTIONAL;
9099 break;
9100 }
9101
9102 int rc = pVMMDev->hgcmHostCall("VBoxDragAndDropSvc",
9103 DragAndDropSvc::HOST_DND_SET_MODE, 1 /* cParms */, &parm);
9104 if (RT_FAILURE(rc))
9105 LogRel(("Error changing drag and drop mode: %Rrc\n", rc));
9106
9107 return rc;
9108}
9109
9110#ifdef VBOX_WITH_USB
9111/**
9112 * Sends a request to VMM to attach the given host device.
9113 * After this method succeeds, the attached device will appear in the
9114 * mUSBDevices collection.
9115 *
9116 * @param aHostDevice device to attach
9117 *
9118 * @note Synchronously calls EMT.
9119 */
9120HRESULT Console::i_attachUSBDevice(IUSBDevice *aHostDevice, ULONG aMaskedIfs,
9121 const Utf8Str &aCaptureFilename)
9122{
9123 AssertReturn(aHostDevice, E_FAIL);
9124 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
9125
9126 HRESULT hrc;
9127
9128 /*
9129 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
9130 * method in EMT (using usbAttachCallback()).
9131 */
9132 Bstr BstrAddress;
9133 hrc = aHostDevice->COMGETTER(Address)(BstrAddress.asOutParam());
9134 ComAssertComRCRetRC(hrc);
9135
9136 Utf8Str Address(BstrAddress);
9137
9138 Bstr id;
9139 hrc = aHostDevice->COMGETTER(Id)(id.asOutParam());
9140 ComAssertComRCRetRC(hrc);
9141 Guid uuid(id);
9142
9143 BOOL fRemote = FALSE;
9144 hrc = aHostDevice->COMGETTER(Remote)(&fRemote);
9145 ComAssertComRCRetRC(hrc);
9146
9147 Bstr BstrBackend;
9148 hrc = aHostDevice->COMGETTER(Backend)(BstrBackend.asOutParam());
9149 ComAssertComRCRetRC(hrc);
9150
9151 Utf8Str Backend(BstrBackend);
9152
9153 /* Get the VM handle. */
9154 SafeVMPtr ptrVM(this);
9155 if (!ptrVM.isOk())
9156 return ptrVM.rc();
9157
9158 LogFlowThisFunc(("Proxying USB device '%s' {%RTuuid}...\n",
9159 Address.c_str(), uuid.raw()));
9160
9161 void *pvRemoteBackend = NULL;
9162 if (fRemote)
9163 {
9164 RemoteUSBDevice *pRemoteUSBDevice = static_cast<RemoteUSBDevice *>(aHostDevice);
9165 pvRemoteBackend = i_consoleVRDPServer()->USBBackendRequestPointer(pRemoteUSBDevice->clientId(), &uuid);
9166 if (!pvRemoteBackend)
9167 return E_INVALIDARG; /* The clientId is invalid then. */
9168 }
9169
9170 USBConnectionSpeed_T enmSpeed;
9171 hrc = aHostDevice->COMGETTER(Speed)(&enmSpeed);
9172 AssertComRCReturnRC(hrc);
9173
9174 int vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
9175 (PFNRT)i_usbAttachCallback, 10,
9176 this, ptrVM.rawUVM(), aHostDevice, uuid.raw(), Backend.c_str(),
9177 Address.c_str(), pvRemoteBackend, enmSpeed, aMaskedIfs,
9178 aCaptureFilename.isEmpty() ? NULL : aCaptureFilename.c_str());
9179 if (RT_SUCCESS(vrc))
9180 {
9181 /* Create a OUSBDevice and add it to the device list */
9182 ComObjPtr<OUSBDevice> pUSBDevice;
9183 pUSBDevice.createObject();
9184 hrc = pUSBDevice->init(aHostDevice);
9185 AssertComRC(hrc);
9186
9187 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9188 mUSBDevices.push_back(pUSBDevice);
9189 LogFlowFunc(("Attached device {%RTuuid}\n", pUSBDevice->i_id().raw()));
9190
9191 /* notify callbacks */
9192 alock.release();
9193 i_onUSBDeviceStateChange(pUSBDevice, true /* aAttached */, NULL);
9194 }
9195 else
9196 {
9197 Log1WarningThisFunc(("Failed to create proxy device for '%s' {%RTuuid} (%Rrc)\n", Address.c_str(), uuid.raw(), vrc));
9198
9199 switch (vrc)
9200 {
9201 case VERR_VUSB_NO_PORTS:
9202 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to attach the USB device. (No available ports on the USB controller)."));
9203 break;
9204 case VERR_VUSB_USBFS_PERMISSION:
9205 hrc = setErrorBoth(E_FAIL, vrc, tr("Not permitted to open the USB device, check usbfs options"));
9206 break;
9207 default:
9208 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to create a proxy device for the USB device. (Error: %Rrc)"), vrc);
9209 break;
9210 }
9211 }
9212
9213 return hrc;
9214}
9215
9216/**
9217 * USB device attach callback used by AttachUSBDevice().
9218 * Note that AttachUSBDevice() doesn't return until this callback is executed,
9219 * so we don't use AutoCaller and don't care about reference counters of
9220 * interface pointers passed in.
9221 *
9222 * @thread EMT
9223 * @note Locks the console object for writing.
9224 */
9225//static
9226DECLCALLBACK(int)
9227Console::i_usbAttachCallback(Console *that, PUVM pUVM, IUSBDevice *aHostDevice, PCRTUUID aUuid, const char *pszBackend,
9228 const char *aAddress, void *pvRemoteBackend, USBConnectionSpeed_T aEnmSpeed, ULONG aMaskedIfs,
9229 const char *pszCaptureFilename)
9230{
9231 RT_NOREF(aHostDevice);
9232 LogFlowFuncEnter();
9233 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
9234
9235 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
9236 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
9237
9238 VUSBSPEED enmSpeed = VUSB_SPEED_UNKNOWN;
9239 switch (aEnmSpeed)
9240 {
9241 case USBConnectionSpeed_Low: enmSpeed = VUSB_SPEED_LOW; break;
9242 case USBConnectionSpeed_Full: enmSpeed = VUSB_SPEED_FULL; break;
9243 case USBConnectionSpeed_High: enmSpeed = VUSB_SPEED_HIGH; break;
9244 case USBConnectionSpeed_Super: enmSpeed = VUSB_SPEED_SUPER; break;
9245 case USBConnectionSpeed_SuperPlus: enmSpeed = VUSB_SPEED_SUPERPLUS; break;
9246 default: AssertFailed(); break;
9247 }
9248
9249 int vrc = PDMR3UsbCreateProxyDevice(pUVM, aUuid, pszBackend, aAddress, pvRemoteBackend,
9250 enmSpeed, aMaskedIfs, pszCaptureFilename);
9251 LogFlowFunc(("vrc=%Rrc\n", vrc));
9252 LogFlowFuncLeave();
9253 return vrc;
9254}
9255
9256/**
9257 * Sends a request to VMM to detach the given host device. After this method
9258 * succeeds, the detached device will disappear from the mUSBDevices
9259 * collection.
9260 *
9261 * @param aHostDevice device to attach
9262 *
9263 * @note Synchronously calls EMT.
9264 */
9265HRESULT Console::i_detachUSBDevice(const ComObjPtr<OUSBDevice> &aHostDevice)
9266{
9267 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
9268
9269 /* Get the VM handle. */
9270 SafeVMPtr ptrVM(this);
9271 if (!ptrVM.isOk())
9272 return ptrVM.rc();
9273
9274 /* if the device is attached, then there must at least one USB hub. */
9275 AssertReturn(PDMR3UsbHasHub(ptrVM.rawUVM()), E_FAIL);
9276
9277 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9278 LogFlowThisFunc(("Detaching USB proxy device {%RTuuid}...\n",
9279 aHostDevice->i_id().raw()));
9280
9281 /*
9282 * If this was a remote device, release the backend pointer.
9283 * The pointer was requested in usbAttachCallback.
9284 */
9285 BOOL fRemote = FALSE;
9286
9287 HRESULT hrc2 = aHostDevice->COMGETTER(Remote)(&fRemote);
9288 if (FAILED(hrc2))
9289 i_setErrorStatic(hrc2, "GetRemote() failed");
9290
9291 PCRTUUID pUuid = aHostDevice->i_id().raw();
9292 if (fRemote)
9293 {
9294 Guid guid(*pUuid);
9295 i_consoleVRDPServer()->USBBackendReleasePointer(&guid);
9296 }
9297
9298 alock.release();
9299 int vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
9300 (PFNRT)i_usbDetachCallback, 5,
9301 this, ptrVM.rawUVM(), pUuid);
9302 if (RT_SUCCESS(vrc))
9303 {
9304 LogFlowFunc(("Detached device {%RTuuid}\n", pUuid));
9305
9306 /* notify callbacks */
9307 i_onUSBDeviceStateChange(aHostDevice, false /* aAttached */, NULL);
9308 }
9309
9310 ComAssertRCRet(vrc, E_FAIL);
9311
9312 return S_OK;
9313}
9314
9315/**
9316 * USB device detach callback used by DetachUSBDevice().
9317 *
9318 * Note that DetachUSBDevice() doesn't return until this callback is executed,
9319 * so we don't use AutoCaller and don't care about reference counters of
9320 * interface pointers passed in.
9321 *
9322 * @thread EMT
9323 */
9324//static
9325DECLCALLBACK(int)
9326Console::i_usbDetachCallback(Console *that, PUVM pUVM, PCRTUUID aUuid)
9327{
9328 LogFlowFuncEnter();
9329 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
9330
9331 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
9332 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
9333
9334 int vrc = PDMR3UsbDetachDevice(pUVM, aUuid);
9335
9336 LogFlowFunc(("vrc=%Rrc\n", vrc));
9337 LogFlowFuncLeave();
9338 return vrc;
9339}
9340#endif /* VBOX_WITH_USB */
9341
9342/* Note: FreeBSD needs this whether netflt is used or not. */
9343#if ((defined(RT_OS_LINUX) && !defined(VBOX_WITH_NETFLT)) || defined(RT_OS_FREEBSD))
9344/**
9345 * Helper function to handle host interface device creation and attachment.
9346 *
9347 * @param networkAdapter the network adapter which attachment should be reset
9348 * @return COM status code
9349 *
9350 * @note The caller must lock this object for writing.
9351 *
9352 * @todo Move this back into the driver!
9353 */
9354HRESULT Console::i_attachToTapInterface(INetworkAdapter *networkAdapter)
9355{
9356 LogFlowThisFunc(("\n"));
9357 /* sanity check */
9358 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9359
9360# ifdef VBOX_STRICT
9361 /* paranoia */
9362 NetworkAttachmentType_T attachment;
9363 networkAdapter->COMGETTER(AttachmentType)(&attachment);
9364 Assert(attachment == NetworkAttachmentType_Bridged);
9365# endif /* VBOX_STRICT */
9366
9367 HRESULT rc = S_OK;
9368
9369 ULONG slot = 0;
9370 rc = networkAdapter->COMGETTER(Slot)(&slot);
9371 AssertComRC(rc);
9372
9373# ifdef RT_OS_LINUX
9374 /*
9375 * Allocate a host interface device
9376 */
9377 int vrc = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
9378 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
9379 if (RT_SUCCESS(vrc))
9380 {
9381 /*
9382 * Set/obtain the tap interface.
9383 */
9384 struct ifreq IfReq;
9385 RT_ZERO(IfReq);
9386 /* The name of the TAP interface we are using */
9387 Bstr tapDeviceName;
9388 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
9389 if (FAILED(rc))
9390 tapDeviceName.setNull(); /* Is this necessary? */
9391 if (tapDeviceName.isEmpty())
9392 {
9393 LogRel(("No TAP device name was supplied.\n"));
9394 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
9395 }
9396
9397 if (SUCCEEDED(rc))
9398 {
9399 /* If we are using a static TAP device then try to open it. */
9400 Utf8Str str(tapDeviceName);
9401 RTStrCopy(IfReq.ifr_name, sizeof(IfReq.ifr_name), str.c_str()); /** @todo bitch about names which are too long... */
9402 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
9403 vrc = ioctl(RTFileToNative(maTapFD[slot]), TUNSETIFF, &IfReq);
9404 if (vrc != 0)
9405 {
9406 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
9407 rc = setErrorBoth(E_FAIL, vrc, tr("Failed to open the host network interface %ls"), tapDeviceName.raw());
9408 }
9409 }
9410 if (SUCCEEDED(rc))
9411 {
9412 /*
9413 * Make it pollable.
9414 */
9415 if (fcntl(RTFileToNative(maTapFD[slot]), F_SETFL, O_NONBLOCK) != -1)
9416 {
9417 Log(("i_attachToTapInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
9418 /*
9419 * Here is the right place to communicate the TAP file descriptor and
9420 * the host interface name to the server if/when it becomes really
9421 * necessary.
9422 */
9423 maTAPDeviceName[slot] = tapDeviceName;
9424 vrc = VINF_SUCCESS;
9425 }
9426 else
9427 {
9428 int iErr = errno;
9429
9430 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
9431 vrc = VERR_HOSTIF_BLOCKING;
9432 rc = setErrorBoth(E_FAIL, vrc, tr("could not set up the host networking device for non blocking access: %s"),
9433 strerror(errno));
9434 }
9435 }
9436 }
9437 else
9438 {
9439 LogRel(("Configuration error: Failed to open /dev/net/tun rc=%Rrc\n", vrc));
9440 switch (vrc)
9441 {
9442 case VERR_ACCESS_DENIED:
9443 /* will be handled by our caller */
9444 rc = vrc;
9445 break;
9446 default:
9447 rc = setErrorBoth(E_FAIL, vrc, tr("Could not set up the host networking device: %Rrc"), vrc);
9448 break;
9449 }
9450 }
9451
9452# elif defined(RT_OS_FREEBSD)
9453 /*
9454 * Set/obtain the tap interface.
9455 */
9456 /* The name of the TAP interface we are using */
9457 Bstr tapDeviceName;
9458 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
9459 if (FAILED(rc))
9460 tapDeviceName.setNull(); /* Is this necessary? */
9461 if (tapDeviceName.isEmpty())
9462 {
9463 LogRel(("No TAP device name was supplied.\n"));
9464 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
9465 }
9466 char szTapdev[1024] = "/dev/";
9467 /* If we are using a static TAP device then try to open it. */
9468 Utf8Str str(tapDeviceName);
9469 if (str.length() + strlen(szTapdev) <= sizeof(szTapdev))
9470 strcat(szTapdev, str.c_str());
9471 else
9472 memcpy(szTapdev + strlen(szTapdev), str.c_str(),
9473 sizeof(szTapdev) - strlen(szTapdev) - 1); /** @todo bitch about names which are too long... */
9474 int vrc = RTFileOpen(&maTapFD[slot], szTapdev,
9475 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT | RTFILE_O_NON_BLOCK);
9476
9477 if (RT_SUCCESS(vrc))
9478 maTAPDeviceName[slot] = tapDeviceName;
9479 else
9480 {
9481 switch (vrc)
9482 {
9483 case VERR_ACCESS_DENIED:
9484 /* will be handled by our caller */
9485 rc = vrc;
9486 break;
9487 default:
9488 rc = setErrorBoth(E_FAIL, vrc, tr("Failed to open the host network interface %ls"), tapDeviceName.raw());
9489 break;
9490 }
9491 }
9492# else
9493# error "huh?"
9494# endif
9495 /* in case of failure, cleanup. */
9496 if (RT_FAILURE(vrc) && SUCCEEDED(rc))
9497 {
9498 LogRel(("General failure attaching to host interface\n"));
9499 rc = setErrorBoth(E_FAIL, vrc, tr("General failure attaching to host interface"));
9500 }
9501 LogFlowThisFunc(("rc=%Rhrc\n", rc));
9502 return rc;
9503}
9504
9505
9506/**
9507 * Helper function to handle detachment from a host interface
9508 *
9509 * @param networkAdapter the network adapter which attachment should be reset
9510 * @return COM status code
9511 *
9512 * @note The caller must lock this object for writing.
9513 *
9514 * @todo Move this back into the driver!
9515 */
9516HRESULT Console::i_detachFromTapInterface(INetworkAdapter *networkAdapter)
9517{
9518 /* sanity check */
9519 LogFlowThisFunc(("\n"));
9520 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9521
9522 HRESULT rc = S_OK;
9523# ifdef VBOX_STRICT
9524 /* paranoia */
9525 NetworkAttachmentType_T attachment;
9526 networkAdapter->COMGETTER(AttachmentType)(&attachment);
9527 Assert(attachment == NetworkAttachmentType_Bridged);
9528# endif /* VBOX_STRICT */
9529
9530 ULONG slot = 0;
9531 rc = networkAdapter->COMGETTER(Slot)(&slot);
9532 AssertComRC(rc);
9533
9534 /* is there an open TAP device? */
9535 if (maTapFD[slot] != NIL_RTFILE)
9536 {
9537 /*
9538 * Close the file handle.
9539 */
9540 Bstr tapDeviceName, tapTerminateApplication;
9541 bool isStatic = true;
9542 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
9543 if (FAILED(rc) || tapDeviceName.isEmpty())
9544 {
9545 /* If the name is empty, this is a dynamic TAP device, so close it now,
9546 so that the termination script can remove the interface. Otherwise we still
9547 need the FD to pass to the termination script. */
9548 isStatic = false;
9549 int rcVBox = RTFileClose(maTapFD[slot]);
9550 AssertRC(rcVBox);
9551 maTapFD[slot] = NIL_RTFILE;
9552 }
9553 if (isStatic)
9554 {
9555 /* If we are using a static TAP device, we close it now, after having called the
9556 termination script. */
9557 int rcVBox = RTFileClose(maTapFD[slot]);
9558 AssertRC(rcVBox);
9559 }
9560 /* the TAP device name and handle are no longer valid */
9561 maTapFD[slot] = NIL_RTFILE;
9562 maTAPDeviceName[slot] = "";
9563 }
9564 LogFlowThisFunc(("returning %d\n", rc));
9565 return rc;
9566}
9567#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
9568
9569/**
9570 * Called at power down to terminate host interface networking.
9571 *
9572 * @note The caller must lock this object for writing.
9573 */
9574HRESULT Console::i_powerDownHostInterfaces()
9575{
9576 LogFlowThisFunc(("\n"));
9577
9578 /* sanity check */
9579 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9580
9581 /*
9582 * host interface termination handling
9583 */
9584 HRESULT rc = S_OK;
9585 ComPtr<IVirtualBox> pVirtualBox;
9586 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
9587 ComPtr<ISystemProperties> pSystemProperties;
9588 if (pVirtualBox)
9589 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
9590 ChipsetType_T chipsetType = ChipsetType_PIIX3;
9591 mMachine->COMGETTER(ChipsetType)(&chipsetType);
9592 ULONG maxNetworkAdapters = 0;
9593 if (pSystemProperties)
9594 pSystemProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters);
9595
9596 for (ULONG slot = 0; slot < maxNetworkAdapters; slot++)
9597 {
9598 ComPtr<INetworkAdapter> pNetworkAdapter;
9599 rc = mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
9600 if (FAILED(rc)) break;
9601
9602 BOOL enabled = FALSE;
9603 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
9604 if (!enabled)
9605 continue;
9606
9607 NetworkAttachmentType_T attachment;
9608 pNetworkAdapter->COMGETTER(AttachmentType)(&attachment);
9609 if (attachment == NetworkAttachmentType_Bridged)
9610 {
9611#if ((defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)) && !defined(VBOX_WITH_NETFLT))
9612 HRESULT rc2 = i_detachFromTapInterface(pNetworkAdapter);
9613 if (FAILED(rc2) && SUCCEEDED(rc))
9614 rc = rc2;
9615#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
9616 }
9617 }
9618
9619 return rc;
9620}
9621
9622
9623/**
9624 * Process callback handler for VMR3LoadFromFile, VMR3LoadFromStream, VMR3Save
9625 * and VMR3Teleport.
9626 *
9627 * @param pUVM The user mode VM handle.
9628 * @param uPercent Completion percentage (0-100).
9629 * @param pvUser Pointer to an IProgress instance.
9630 * @return VINF_SUCCESS.
9631 */
9632/*static*/
9633DECLCALLBACK(int) Console::i_stateProgressCallback(PUVM pUVM, unsigned uPercent, void *pvUser)
9634{
9635 IProgress *pProgress = static_cast<IProgress *>(pvUser);
9636
9637 /* update the progress object */
9638 if (pProgress)
9639 {
9640 ComPtr<IInternalProgressControl> pProgressControl(pProgress);
9641 AssertReturn(!!pProgressControl, VERR_INVALID_PARAMETER);
9642 pProgressControl->SetCurrentOperationProgress(uPercent);
9643 }
9644
9645 NOREF(pUVM);
9646 return VINF_SUCCESS;
9647}
9648
9649/**
9650 * @copydoc FNVMATERROR
9651 *
9652 * @remarks Might be some tiny serialization concerns with access to the string
9653 * object here...
9654 */
9655/*static*/ DECLCALLBACK(void)
9656Console::i_genericVMSetErrorCallback(PUVM pUVM, void *pvUser, int rc, RT_SRC_POS_DECL,
9657 const char *pszFormat, va_list args)
9658{
9659 RT_SRC_POS_NOREF();
9660 Utf8Str *pErrorText = (Utf8Str *)pvUser;
9661 AssertPtr(pErrorText);
9662
9663 /* We ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users. */
9664 va_list va2;
9665 va_copy(va2, args);
9666
9667 /* Append to any the existing error message. */
9668 if (pErrorText->length())
9669 *pErrorText = Utf8StrFmt("%s.\n%N (%Rrc)", pErrorText->c_str(),
9670 pszFormat, &va2, rc, rc);
9671 else
9672 *pErrorText = Utf8StrFmt("%N (%Rrc)", pszFormat, &va2, rc, rc);
9673
9674 va_end(va2);
9675
9676 NOREF(pUVM);
9677}
9678
9679/**
9680 * VM runtime error callback function (FNVMATRUNTIMEERROR).
9681 *
9682 * See VMSetRuntimeError for the detailed description of parameters.
9683 *
9684 * @param pUVM The user mode VM handle. Ignored, so passing NULL
9685 * is fine.
9686 * @param pvUser The user argument, pointer to the Console instance.
9687 * @param fFlags The action flags. See VMSETRTERR_FLAGS_*.
9688 * @param pszErrorId Error ID string.
9689 * @param pszFormat Error message format string.
9690 * @param va Error message arguments.
9691 * @thread EMT.
9692 */
9693/* static */ DECLCALLBACK(void)
9694Console::i_atVMRuntimeErrorCallback(PUVM pUVM, void *pvUser, uint32_t fFlags,
9695 const char *pszErrorId, const char *pszFormat, va_list va)
9696{
9697 bool const fFatal = !!(fFlags & VMSETRTERR_FLAGS_FATAL);
9698 LogFlowFuncEnter();
9699
9700 Console *that = static_cast<Console *>(pvUser);
9701 AssertReturnVoid(that);
9702
9703 Utf8Str message(pszFormat, va);
9704
9705 LogRel(("Console: VM runtime error: fatal=%RTbool, errorID=%s message=\"%s\"\n",
9706 fFatal, pszErrorId, message.c_str()));
9707
9708 that->i_onRuntimeError(BOOL(fFatal), Bstr(pszErrorId).raw(), Bstr(message).raw());
9709
9710 LogFlowFuncLeave(); NOREF(pUVM);
9711}
9712
9713/**
9714 * Captures USB devices that match filters of the VM.
9715 * Called at VM startup.
9716 *
9717 * @param pUVM The VM handle.
9718 */
9719HRESULT Console::i_captureUSBDevices(PUVM pUVM)
9720{
9721 RT_NOREF(pUVM);
9722 LogFlowThisFunc(("\n"));
9723
9724 /* sanity check */
9725 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
9726 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9727
9728 /* If the machine has a USB controller, ask the USB proxy service to
9729 * capture devices */
9730 if (mfVMHasUsbController)
9731 {
9732 /* release the lock before calling Host in VBoxSVC since Host may call
9733 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
9734 * produce an inter-process dead-lock otherwise. */
9735 alock.release();
9736
9737 HRESULT hrc = mControl->AutoCaptureUSBDevices();
9738 ComAssertComRCRetRC(hrc);
9739 }
9740
9741 return S_OK;
9742}
9743
9744
9745/**
9746 * Detach all USB device which are attached to the VM for the
9747 * purpose of clean up and such like.
9748 */
9749void Console::i_detachAllUSBDevices(bool aDone)
9750{
9751 LogFlowThisFunc(("aDone=%RTbool\n", aDone));
9752
9753 /* sanity check */
9754 AssertReturnVoid(!isWriteLockOnCurrentThread());
9755 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9756
9757 mUSBDevices.clear();
9758
9759 /* release the lock before calling Host in VBoxSVC since Host may call
9760 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
9761 * produce an inter-process dead-lock otherwise. */
9762 alock.release();
9763
9764 mControl->DetachAllUSBDevices(aDone);
9765}
9766
9767/**
9768 * @note Locks this object for writing.
9769 */
9770void Console::i_processRemoteUSBDevices(uint32_t u32ClientId, VRDEUSBDEVICEDESC *pDevList, uint32_t cbDevList, bool fDescExt)
9771{
9772 LogFlowThisFuncEnter();
9773 LogFlowThisFunc(("u32ClientId = %d, pDevList=%p, cbDevList = %d, fDescExt = %d\n",
9774 u32ClientId, pDevList, cbDevList, fDescExt));
9775
9776 AutoCaller autoCaller(this);
9777 if (!autoCaller.isOk())
9778 {
9779 /* Console has been already uninitialized, deny request */
9780 AssertMsgFailed(("Console is already uninitialized\n"));
9781 LogFlowThisFunc(("Console is already uninitialized\n"));
9782 LogFlowThisFuncLeave();
9783 return;
9784 }
9785
9786 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9787
9788 /*
9789 * Mark all existing remote USB devices as dirty.
9790 */
9791 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
9792 it != mRemoteUSBDevices.end();
9793 ++it)
9794 {
9795 (*it)->dirty(true);
9796 }
9797
9798 /*
9799 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
9800 */
9801 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
9802 VRDEUSBDEVICEDESC *e = pDevList;
9803
9804 /* The cbDevList condition must be checked first, because the function can
9805 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
9806 */
9807 while (cbDevList >= 2 && e->oNext)
9808 {
9809 /* Sanitize incoming strings in case they aren't valid UTF-8. */
9810 if (e->oManufacturer)
9811 RTStrPurgeEncoding((char *)e + e->oManufacturer);
9812 if (e->oProduct)
9813 RTStrPurgeEncoding((char *)e + e->oProduct);
9814 if (e->oSerialNumber)
9815 RTStrPurgeEncoding((char *)e + e->oSerialNumber);
9816
9817 LogFlowThisFunc(("vendor %04X, product %04X, name = %s\n",
9818 e->idVendor, e->idProduct,
9819 e->oProduct? (char *)e + e->oProduct: ""));
9820
9821 bool fNewDevice = true;
9822
9823 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
9824 it != mRemoteUSBDevices.end();
9825 ++it)
9826 {
9827 if ((*it)->devId() == e->id
9828 && (*it)->clientId() == u32ClientId)
9829 {
9830 /* The device is already in the list. */
9831 (*it)->dirty(false);
9832 fNewDevice = false;
9833 break;
9834 }
9835 }
9836
9837 if (fNewDevice)
9838 {
9839 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
9840 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""));
9841
9842 /* Create the device object and add the new device to list. */
9843 ComObjPtr<RemoteUSBDevice> pUSBDevice;
9844 pUSBDevice.createObject();
9845 pUSBDevice->init(u32ClientId, e, fDescExt);
9846
9847 mRemoteUSBDevices.push_back(pUSBDevice);
9848
9849 /* Check if the device is ok for current USB filters. */
9850 BOOL fMatched = FALSE;
9851 ULONG fMaskedIfs = 0;
9852
9853 HRESULT hrc = mControl->RunUSBDeviceFilters(pUSBDevice, &fMatched, &fMaskedIfs);
9854
9855 AssertComRC(hrc);
9856
9857 LogFlowThisFunc(("USB filters return %d %#x\n", fMatched, fMaskedIfs));
9858
9859 if (fMatched)
9860 {
9861 alock.release();
9862 hrc = i_onUSBDeviceAttach(pUSBDevice, NULL, fMaskedIfs, Utf8Str());
9863 alock.acquire();
9864
9865 /// @todo (r=dmik) warning reporting subsystem
9866
9867 if (hrc == S_OK)
9868 {
9869 LogFlowThisFunc(("Device attached\n"));
9870 pUSBDevice->captured(true);
9871 }
9872 }
9873 }
9874
9875 if (cbDevList < e->oNext)
9876 {
9877 Log1WarningThisFunc(("cbDevList %d > oNext %d\n", cbDevList, e->oNext));
9878 break;
9879 }
9880
9881 cbDevList -= e->oNext;
9882
9883 e = (VRDEUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
9884 }
9885
9886 /*
9887 * Remove dirty devices, that is those which are not reported by the server anymore.
9888 */
9889 for (;;)
9890 {
9891 ComObjPtr<RemoteUSBDevice> pUSBDevice;
9892
9893 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
9894 while (it != mRemoteUSBDevices.end())
9895 {
9896 if ((*it)->dirty())
9897 {
9898 pUSBDevice = *it;
9899 break;
9900 }
9901
9902 ++it;
9903 }
9904
9905 if (!pUSBDevice)
9906 {
9907 break;
9908 }
9909
9910 USHORT vendorId = 0;
9911 pUSBDevice->COMGETTER(VendorId)(&vendorId);
9912
9913 USHORT productId = 0;
9914 pUSBDevice->COMGETTER(ProductId)(&productId);
9915
9916 Bstr product;
9917 pUSBDevice->COMGETTER(Product)(product.asOutParam());
9918
9919 LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
9920 vendorId, productId, product.raw()));
9921
9922 /* Detach the device from VM. */
9923 if (pUSBDevice->captured())
9924 {
9925 Bstr uuid;
9926 pUSBDevice->COMGETTER(Id)(uuid.asOutParam());
9927 alock.release();
9928 i_onUSBDeviceDetach(uuid.raw(), NULL);
9929 alock.acquire();
9930 }
9931
9932 /* And remove it from the list. */
9933 mRemoteUSBDevices.erase(it);
9934 }
9935
9936 LogFlowThisFuncLeave();
9937}
9938
9939/**
9940 * Progress cancelation callback for fault tolerance VM poweron
9941 */
9942static void faultToleranceProgressCancelCallback(void *pvUser)
9943{
9944 PUVM pUVM = (PUVM)pvUser;
9945
9946 if (pUVM)
9947 FTMR3CancelStandby(pUVM);
9948}
9949
9950/**
9951 * Worker called by VMPowerUpTask::handler to start the VM (also from saved
9952 * state) and track progress.
9953 *
9954 * @param pTask The power up task.
9955 *
9956 * @note Locks the Console object for writing.
9957 */
9958/*static*/
9959void Console::i_powerUpThreadTask(VMPowerUpTask *pTask)
9960{
9961 LogFlowFuncEnter();
9962
9963 AssertReturnVoid(pTask);
9964 AssertReturnVoid(!pTask->mConsole.isNull());
9965 AssertReturnVoid(!pTask->mProgress.isNull());
9966
9967 VirtualBoxBase::initializeComForThread();
9968
9969 HRESULT rc = S_OK;
9970 int vrc = VINF_SUCCESS;
9971
9972 /* Set up a build identifier so that it can be seen from core dumps what
9973 * exact build was used to produce the core. */
9974 static char saBuildID[48];
9975 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%u %s%s%s%s",
9976 "BU", "IL", "DI", "D", RTBldCfgVersion(), RTBldCfgRevision(), "BU", "IL", "DI", "D");
9977
9978 ComObjPtr<Console> pConsole = pTask->mConsole;
9979
9980 /* Note: no need to use AutoCaller because VMPowerUpTask does that */
9981
9982 /* The lock is also used as a signal from the task initiator (which
9983 * releases it only after RTThreadCreate()) that we can start the job */
9984 AutoWriteLock alock(pConsole COMMA_LOCKVAL_SRC_POS);
9985
9986 /* sanity */
9987 Assert(pConsole->mpUVM == NULL);
9988
9989 try
9990 {
9991 // Create the VMM device object, which starts the HGCM thread; do this only
9992 // once for the console, for the pathological case that the same console
9993 // object is used to power up a VM twice.
9994 if (!pConsole->m_pVMMDev)
9995 {
9996 pConsole->m_pVMMDev = new VMMDev(pConsole);
9997 AssertReturnVoid(pConsole->m_pVMMDev);
9998 }
9999
10000 /* wait for auto reset ops to complete so that we can successfully lock
10001 * the attached hard disks by calling LockMedia() below */
10002 for (VMPowerUpTask::ProgressList::const_iterator
10003 it = pTask->hardDiskProgresses.begin();
10004 it != pTask->hardDiskProgresses.end(); ++it)
10005 {
10006 HRESULT rc2 = (*it)->WaitForCompletion(-1);
10007 AssertComRC(rc2);
10008
10009 rc = pTask->mProgress->SetNextOperation(BstrFmt(tr("Disk Image Reset Operation - Immutable Image")).raw(), 1);
10010 AssertComRCReturnVoid(rc);
10011 }
10012
10013 /*
10014 * Lock attached media. This method will also check their accessibility.
10015 * If we're a teleporter, we'll have to postpone this action so we can
10016 * migrate between local processes.
10017 *
10018 * Note! The media will be unlocked automatically by
10019 * SessionMachine::i_setMachineState() when the VM is powered down.
10020 */
10021 if ( !pTask->mTeleporterEnabled
10022 && pTask->mEnmFaultToleranceState != FaultToleranceState_Standby)
10023 {
10024 rc = pConsole->mControl->LockMedia();
10025 if (FAILED(rc)) throw rc;
10026 }
10027
10028 /* Create the VRDP server. In case of headless operation, this will
10029 * also create the framebuffer, required at VM creation.
10030 */
10031 ConsoleVRDPServer *server = pConsole->i_consoleVRDPServer();
10032 Assert(server);
10033
10034 /* Does VRDP server call Console from the other thread?
10035 * Not sure (and can change), so release the lock just in case.
10036 */
10037 alock.release();
10038 vrc = server->Launch();
10039 alock.acquire();
10040
10041 if (vrc != VINF_SUCCESS)
10042 {
10043 Utf8Str errMsg = pConsole->VRDPServerErrorToMsg(vrc);
10044 if ( RT_FAILURE(vrc)
10045 && vrc != VERR_NET_ADDRESS_IN_USE) /* not fatal */
10046 throw i_setErrorStaticBoth(E_FAIL, vrc, errMsg.c_str());
10047 }
10048
10049 ComPtr<IMachine> pMachine = pConsole->i_machine();
10050 ULONG cCpus = 1;
10051 pMachine->COMGETTER(CPUCount)(&cCpus);
10052
10053 /*
10054 * Create the VM
10055 *
10056 * Note! Release the lock since EMT will call Console. It's safe because
10057 * mMachineState is either Starting or Restoring state here.
10058 */
10059 alock.release();
10060
10061 PVM pVM;
10062 vrc = VMR3Create(cCpus,
10063 pConsole->mpVmm2UserMethods,
10064 Console::i_genericVMSetErrorCallback,
10065 &pTask->mErrorMsg,
10066 pTask->mConfigConstructor,
10067 static_cast<Console *>(pConsole),
10068 &pVM, NULL);
10069 alock.acquire();
10070
10071#ifdef VBOX_WITH_AUDIO_VRDE
10072 /* Attach the VRDE audio driver. */
10073 IVRDEServer *pVRDEServer = pConsole->i_getVRDEServer();
10074 if (pVRDEServer)
10075 {
10076 BOOL fVRDEEnabled = FALSE;
10077 rc = pVRDEServer->COMGETTER(Enabled)(&fVRDEEnabled);
10078 AssertComRCReturnVoid(rc);
10079
10080 if ( fVRDEEnabled
10081 && pConsole->mAudioVRDE)
10082 pConsole->mAudioVRDE->doAttachDriverViaEmt(pConsole->mpUVM, &alock);
10083 }
10084#endif
10085
10086 /* Enable client connections to the VRDP server. */
10087 pConsole->i_consoleVRDPServer()->EnableConnections();
10088
10089#ifdef VBOX_WITH_VIDEOREC
10090 ComPtr<ICaptureSettings> CaptureSettings;
10091 rc = pConsole->mMachine->COMGETTER(CaptureSettings)(CaptureSettings.asOutParam());
10092 AssertComRCReturnVoid(rc);
10093
10094 BOOL fCaptureEnabled;
10095 rc = CaptureSettings->COMGETTER(Enabled)(&fCaptureEnabled);
10096 AssertComRCReturnVoid(rc);
10097
10098 if (fCaptureEnabled)
10099 {
10100 int vrc2 = pConsole->i_videoCaptureEnable(fCaptureEnabled, &alock);
10101 if (RT_SUCCESS(vrc2))
10102 {
10103 fireCaptureChangedEvent(pConsole->mEventSource);
10104 }
10105 else
10106 LogRel(("VideoRec: Failed with %Rrc on VM power up\n", vrc2));
10107
10108 /** Note: Do not use vrc here, as starting the video recording isn't critical to
10109 * powering up the VM. */
10110 }
10111#endif
10112
10113 if (RT_SUCCESS(vrc))
10114 {
10115 do
10116 {
10117 /*
10118 * Register our load/save state file handlers
10119 */
10120 vrc = SSMR3RegisterExternal(pConsole->mpUVM, sSSMConsoleUnit, 0 /*iInstance*/, sSSMConsoleVer, 0 /* cbGuess */,
10121 NULL, NULL, NULL,
10122 NULL, i_saveStateFileExec, NULL,
10123 NULL, i_loadStateFileExec, NULL,
10124 static_cast<Console *>(pConsole));
10125 AssertRCBreak(vrc);
10126
10127 vrc = static_cast<Console *>(pConsole)->i_getDisplay()->i_registerSSM(pConsole->mpUVM);
10128 AssertRC(vrc);
10129 if (RT_FAILURE(vrc))
10130 break;
10131
10132 /*
10133 * Synchronize debugger settings
10134 */
10135 MachineDebugger *machineDebugger = pConsole->i_getMachineDebugger();
10136 if (machineDebugger)
10137 machineDebugger->i_flushQueuedSettings();
10138
10139 /*
10140 * Shared Folders
10141 */
10142 if (pConsole->m_pVMMDev->isShFlActive())
10143 {
10144 /* Does the code below call Console from the other thread?
10145 * Not sure, so release the lock just in case. */
10146 alock.release();
10147
10148 for (SharedFolderDataMap::const_iterator it = pTask->mSharedFolders.begin();
10149 it != pTask->mSharedFolders.end();
10150 ++it)
10151 {
10152 const SharedFolderData &d = it->second;
10153 rc = pConsole->i_createSharedFolder(it->first, d);
10154 if (FAILED(rc))
10155 {
10156 ErrorInfoKeeper eik;
10157 pConsole->i_atVMRuntimeErrorCallbackF(0, "BrokenSharedFolder",
10158 N_("The shared folder '%s' could not be set up: %ls.\n"
10159 "The shared folder setup will not be complete. It is recommended to power down the virtual "
10160 "machine and fix the shared folder settings while the machine is not running"),
10161 it->first.c_str(), eik.getText().raw());
10162 }
10163 }
10164 if (FAILED(rc))
10165 rc = S_OK; // do not fail with broken shared folders
10166
10167 /* acquire the lock again */
10168 alock.acquire();
10169 }
10170
10171 /* release the lock before a lengthy operation */
10172 alock.release();
10173
10174 /*
10175 * Capture USB devices.
10176 */
10177 rc = pConsole->i_captureUSBDevices(pConsole->mpUVM);
10178 if (FAILED(rc))
10179 {
10180 alock.acquire();
10181 break;
10182 }
10183
10184 /* Load saved state? */
10185 if (pTask->mSavedStateFile.length())
10186 {
10187 LogFlowFunc(("Restoring saved state from '%s'...\n", pTask->mSavedStateFile.c_str()));
10188
10189 vrc = VMR3LoadFromFile(pConsole->mpUVM,
10190 pTask->mSavedStateFile.c_str(),
10191 Console::i_stateProgressCallback,
10192 static_cast<IProgress *>(pTask->mProgress));
10193
10194 if (RT_SUCCESS(vrc))
10195 {
10196 if (pTask->mStartPaused)
10197 /* done */
10198 pConsole->i_setMachineState(MachineState_Paused);
10199 else
10200 {
10201 /* Start/Resume the VM execution */
10202#ifdef VBOX_WITH_EXTPACK
10203 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM);
10204#endif
10205 if (RT_SUCCESS(vrc))
10206 vrc = VMR3Resume(pConsole->mpUVM, VMRESUMEREASON_STATE_RESTORED);
10207 AssertLogRelRC(vrc);
10208 }
10209 }
10210
10211 /* Power off in case we failed loading or resuming the VM */
10212 if (RT_FAILURE(vrc))
10213 {
10214 int vrc2 = VMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
10215#ifdef VBOX_WITH_EXTPACK
10216 pConsole->mptrExtPackManager->i_callAllVmPowerOffHooks(pConsole, pVM);
10217#endif
10218 }
10219 }
10220 else if (pTask->mTeleporterEnabled)
10221 {
10222 /* -> ConsoleImplTeleporter.cpp */
10223 bool fPowerOffOnFailure;
10224 rc = pConsole->i_teleporterTrg(pConsole->mpUVM, pMachine, &pTask->mErrorMsg, pTask->mStartPaused,
10225 pTask->mProgress, &fPowerOffOnFailure);
10226 if (FAILED(rc) && fPowerOffOnFailure)
10227 {
10228 ErrorInfoKeeper eik;
10229 int vrc2 = VMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
10230#ifdef VBOX_WITH_EXTPACK
10231 pConsole->mptrExtPackManager->i_callAllVmPowerOffHooks(pConsole, pVM);
10232#endif
10233 }
10234 }
10235 else if (pTask->mEnmFaultToleranceState != FaultToleranceState_Inactive)
10236 {
10237 /*
10238 * Get the config.
10239 */
10240 ULONG uPort;
10241 rc = pMachine->COMGETTER(FaultTolerancePort)(&uPort);
10242 if (SUCCEEDED(rc))
10243 {
10244 ULONG uInterval;
10245 rc = pMachine->COMGETTER(FaultToleranceSyncInterval)(&uInterval);
10246 if (SUCCEEDED(rc))
10247 {
10248 Bstr bstrAddress;
10249 rc = pMachine->COMGETTER(FaultToleranceAddress)(bstrAddress.asOutParam());
10250 if (SUCCEEDED(rc))
10251 {
10252 Bstr bstrPassword;
10253 rc = pMachine->COMGETTER(FaultTolerancePassword)(bstrPassword.asOutParam());
10254 if (SUCCEEDED(rc))
10255 {
10256 if (pTask->mProgress->i_setCancelCallback(faultToleranceProgressCancelCallback,
10257 pConsole->mpUVM))
10258 {
10259 if (SUCCEEDED(rc))
10260 {
10261 Utf8Str strAddress(bstrAddress);
10262 const char *pszAddress = strAddress.isEmpty() ? NULL : strAddress.c_str();
10263 Utf8Str strPassword(bstrPassword);
10264 const char *pszPassword = strPassword.isEmpty() ? NULL : strPassword.c_str();
10265
10266 /* Power on the FT enabled VM. */
10267#ifdef VBOX_WITH_EXTPACK
10268 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM);
10269#endif
10270 if (RT_SUCCESS(vrc))
10271 vrc = FTMR3PowerOn(pConsole->mpUVM,
10272 pTask->mEnmFaultToleranceState == FaultToleranceState_Master /* fMaster */,
10273 uInterval,
10274 pszAddress,
10275 uPort,
10276 pszPassword);
10277 AssertLogRelRC(vrc);
10278 }
10279 pTask->mProgress->i_setCancelCallback(NULL, NULL);
10280 }
10281 else
10282 rc = E_FAIL;
10283
10284 }
10285 }
10286 }
10287 }
10288 }
10289 else if (pTask->mStartPaused)
10290 /* done */
10291 pConsole->i_setMachineState(MachineState_Paused);
10292 else
10293 {
10294 /* Power on the VM (i.e. start executing) */
10295#ifdef VBOX_WITH_EXTPACK
10296 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM);
10297#endif
10298 if (RT_SUCCESS(vrc))
10299 vrc = VMR3PowerOn(pConsole->mpUVM);
10300 AssertLogRelRC(vrc);
10301 }
10302
10303 /* acquire the lock again */
10304 alock.acquire();
10305 }
10306 while (0);
10307
10308 /* On failure, destroy the VM */
10309 if (FAILED(rc) || RT_FAILURE(vrc))
10310 {
10311 /* preserve existing error info */
10312 ErrorInfoKeeper eik;
10313
10314 /* powerDown() will call VMR3Destroy() and do all necessary
10315 * cleanup (VRDP, USB devices) */
10316 alock.release();
10317 HRESULT rc2 = pConsole->i_powerDown();
10318 alock.acquire();
10319 AssertComRC(rc2);
10320 }
10321 else
10322 {
10323 /*
10324 * Deregister the VMSetError callback. This is necessary as the
10325 * pfnVMAtError() function passed to VMR3Create() is supposed to
10326 * be sticky but our error callback isn't.
10327 */
10328 alock.release();
10329 VMR3AtErrorDeregister(pConsole->mpUVM, Console::i_genericVMSetErrorCallback, &pTask->mErrorMsg);
10330 /** @todo register another VMSetError callback? */
10331 alock.acquire();
10332 }
10333 }
10334 else
10335 {
10336 /*
10337 * If VMR3Create() failed it has released the VM memory.
10338 */
10339 VMR3ReleaseUVM(pConsole->mpUVM);
10340 pConsole->mpUVM = NULL;
10341 }
10342
10343 if (SUCCEEDED(rc) && RT_FAILURE(vrc))
10344 {
10345 /* If VMR3Create() or one of the other calls in this function fail,
10346 * an appropriate error message has been set in pTask->mErrorMsg.
10347 * However since that happens via a callback, the rc status code in
10348 * this function is not updated.
10349 */
10350 if (!pTask->mErrorMsg.length())
10351 {
10352 /* If the error message is not set but we've got a failure,
10353 * convert the VBox status code into a meaningful error message.
10354 * This becomes unused once all the sources of errors set the
10355 * appropriate error message themselves.
10356 */
10357 AssertMsgFailed(("Missing error message during powerup for status code %Rrc\n", vrc));
10358 pTask->mErrorMsg = Utf8StrFmt(tr("Failed to start VM execution (%Rrc)"), vrc);
10359 }
10360
10361 /* Set the error message as the COM error.
10362 * Progress::notifyComplete() will pick it up later. */
10363 throw i_setErrorStaticBoth(E_FAIL, vrc, pTask->mErrorMsg.c_str());
10364 }
10365 }
10366 catch (HRESULT aRC) { rc = aRC; }
10367
10368 if ( pConsole->mMachineState == MachineState_Starting
10369 || pConsole->mMachineState == MachineState_Restoring
10370 || pConsole->mMachineState == MachineState_TeleportingIn
10371 )
10372 {
10373 /* We are still in the Starting/Restoring state. This means one of:
10374 *
10375 * 1) we failed before VMR3Create() was called;
10376 * 2) VMR3Create() failed.
10377 *
10378 * In both cases, there is no need to call powerDown(), but we still
10379 * need to go back to the PoweredOff/Saved state. Reuse
10380 * vmstateChangeCallback() for that purpose.
10381 */
10382
10383 /* preserve existing error info */
10384 ErrorInfoKeeper eik;
10385
10386 Assert(pConsole->mpUVM == NULL);
10387 i_vmstateChangeCallback(NULL, VMSTATE_TERMINATED, VMSTATE_CREATING, pConsole);
10388 }
10389
10390 /*
10391 * Evaluate the final result. Note that the appropriate mMachineState value
10392 * is already set by vmstateChangeCallback() in all cases.
10393 */
10394
10395 /* release the lock, don't need it any more */
10396 alock.release();
10397
10398 if (SUCCEEDED(rc))
10399 {
10400 /* Notify the progress object of the success */
10401 pTask->mProgress->i_notifyComplete(S_OK);
10402 }
10403 else
10404 {
10405 /* The progress object will fetch the current error info */
10406 pTask->mProgress->i_notifyComplete(rc);
10407 LogRel(("Power up failed (vrc=%Rrc, rc=%Rhrc (%#08X))\n", vrc, rc, rc));
10408 }
10409
10410 /* Notify VBoxSVC and any waiting openRemoteSession progress object. */
10411 pConsole->mControl->EndPowerUp(rc);
10412
10413#if defined(RT_OS_WINDOWS)
10414 /* uninitialize COM */
10415 CoUninitialize();
10416#endif
10417
10418 LogFlowFuncLeave();
10419}
10420
10421
10422/**
10423 * Reconfigures a medium attachment (part of taking or deleting an online snapshot).
10424 *
10425 * @param pThis Reference to the console object.
10426 * @param pUVM The VM handle.
10427 * @param pcszDevice The name of the controller type.
10428 * @param uInstance The instance of the controller.
10429 * @param enmBus The storage bus type of the controller.
10430 * @param fUseHostIOCache Use the host I/O cache (disable async I/O).
10431 * @param fBuiltinIOCache Use the builtin I/O cache.
10432 * @param fInsertDiskIntegrityDrv Flag whether to insert the disk integrity driver into the chain
10433 * for additionalk debugging aids.
10434 * @param fSetupMerge Whether to set up a medium merge
10435 * @param uMergeSource Merge source image index
10436 * @param uMergeTarget Merge target image index
10437 * @param aMediumAtt The medium attachment.
10438 * @param aMachineState The current machine state.
10439 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
10440 * @return VBox status code.
10441 */
10442/* static */
10443DECLCALLBACK(int) Console::i_reconfigureMediumAttachment(Console *pThis,
10444 PUVM pUVM,
10445 const char *pcszDevice,
10446 unsigned uInstance,
10447 StorageBus_T enmBus,
10448 bool fUseHostIOCache,
10449 bool fBuiltinIOCache,
10450 bool fInsertDiskIntegrityDrv,
10451 bool fSetupMerge,
10452 unsigned uMergeSource,
10453 unsigned uMergeTarget,
10454 IMediumAttachment *aMediumAtt,
10455 MachineState_T aMachineState,
10456 HRESULT *phrc)
10457{
10458 LogFlowFunc(("pUVM=%p aMediumAtt=%p phrc=%p\n", pUVM, aMediumAtt, phrc));
10459
10460 HRESULT hrc;
10461 Bstr bstr;
10462 *phrc = S_OK;
10463#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%Rhrc (%#x)\n", hrc, hrc)); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
10464
10465 /* Ignore attachments other than hard disks, since at the moment they are
10466 * not subject to snapshotting in general. */
10467 DeviceType_T lType;
10468 hrc = aMediumAtt->COMGETTER(Type)(&lType); H();
10469 if (lType != DeviceType_HardDisk)
10470 return VINF_SUCCESS;
10471
10472 /* Update the device instance configuration. */
10473 int rc = pThis->i_configMediumAttachment(pcszDevice,
10474 uInstance,
10475 enmBus,
10476 fUseHostIOCache,
10477 fBuiltinIOCache,
10478 fInsertDiskIntegrityDrv,
10479 fSetupMerge,
10480 uMergeSource,
10481 uMergeTarget,
10482 aMediumAtt,
10483 aMachineState,
10484 phrc,
10485 true /* fAttachDetach */,
10486 false /* fForceUnmount */,
10487 false /* fHotplug */,
10488 pUVM,
10489 NULL /* paLedDevType */,
10490 NULL /* ppLunL0)*/);
10491 if (RT_FAILURE(rc))
10492 {
10493 AssertMsgFailed(("rc=%Rrc\n", rc));
10494 return rc;
10495 }
10496
10497#undef H
10498
10499 LogFlowFunc(("Returns success\n"));
10500 return VINF_SUCCESS;
10501}
10502
10503/**
10504 * Thread for powering down the Console.
10505 *
10506 * @param pTask The power down task.
10507 *
10508 * @note Locks the Console object for writing.
10509 */
10510/*static*/
10511void Console::i_powerDownThreadTask(VMPowerDownTask *pTask)
10512{
10513 int rc = VINF_SUCCESS; /* only used in assertion */
10514 LogFlowFuncEnter();
10515 try
10516 {
10517 if (pTask->isOk() == false)
10518 rc = VERR_GENERAL_FAILURE;
10519
10520 const ComObjPtr<Console> &that = pTask->mConsole;
10521
10522 /* Note: no need to use AutoCaller to protect Console because VMTask does
10523 * that */
10524
10525 /* wait until the method tat started us returns */
10526 AutoWriteLock thatLock(that COMMA_LOCKVAL_SRC_POS);
10527
10528 /* release VM caller to avoid the powerDown() deadlock */
10529 pTask->releaseVMCaller();
10530
10531 thatLock.release();
10532
10533 that->i_powerDown(pTask->mServerProgress);
10534
10535 /* complete the operation */
10536 that->mControl->EndPoweringDown(S_OK, Bstr().raw());
10537
10538 }
10539 catch (const std::exception &e)
10540 {
10541 AssertMsgFailed(("Exception %s was caught, rc=%Rrc\n", e.what(), rc));
10542 NOREF(e); NOREF(rc);
10543 }
10544
10545 LogFlowFuncLeave();
10546}
10547
10548/**
10549 * @interface_method_impl{VMM2USERMETHODS,pfnSaveState}
10550 */
10551/*static*/ DECLCALLBACK(int)
10552Console::i_vmm2User_SaveState(PCVMM2USERMETHODS pThis, PUVM pUVM)
10553{
10554 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
10555 NOREF(pUVM);
10556
10557 /*
10558 * For now, just call SaveState. We should probably try notify the GUI so
10559 * it can pop up a progress object and stuff. The progress object created
10560 * by the call isn't returned to anyone and thus gets updated without
10561 * anyone noticing it.
10562 */
10563 ComPtr<IProgress> pProgress;
10564 HRESULT hrc = pConsole->mMachine->SaveState(pProgress.asOutParam());
10565 return SUCCEEDED(hrc) ? VINF_SUCCESS : Global::vboxStatusCodeFromCOM(hrc);
10566}
10567
10568/**
10569 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtInit}
10570 */
10571/*static*/ DECLCALLBACK(void)
10572Console::i_vmm2User_NotifyEmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
10573{
10574 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
10575 VirtualBoxBase::initializeComForThread();
10576}
10577
10578/**
10579 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtTerm}
10580 */
10581/*static*/ DECLCALLBACK(void)
10582Console::i_vmm2User_NotifyEmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
10583{
10584 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
10585 VirtualBoxBase::uninitializeComForThread();
10586}
10587
10588/**
10589 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtInit}
10590 */
10591/*static*/ DECLCALLBACK(void)
10592Console::i_vmm2User_NotifyPdmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM)
10593{
10594 NOREF(pThis); NOREF(pUVM);
10595 VirtualBoxBase::initializeComForThread();
10596}
10597
10598/**
10599 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtTerm}
10600 */
10601/*static*/ DECLCALLBACK(void)
10602Console::i_vmm2User_NotifyPdmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM)
10603{
10604 NOREF(pThis); NOREF(pUVM);
10605 VirtualBoxBase::uninitializeComForThread();
10606}
10607
10608/**
10609 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyResetTurnedIntoPowerOff}
10610 */
10611/*static*/ DECLCALLBACK(void)
10612Console::i_vmm2User_NotifyResetTurnedIntoPowerOff(PCVMM2USERMETHODS pThis, PUVM pUVM)
10613{
10614 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
10615 NOREF(pUVM);
10616
10617 pConsole->mfPowerOffCausedByReset = true;
10618}
10619
10620/**
10621 * @interface_method_impl{VMM2USERMETHODS,pfnQueryGenericObject}
10622 */
10623/*static*/ DECLCALLBACK(void *)
10624Console::i_vmm2User_QueryGenericObject(PCVMM2USERMETHODS pThis, PUVM pUVM, PCRTUUID pUuid)
10625{
10626 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
10627 NOREF(pUVM);
10628
10629 /* To simplify comparison we copy the UUID into a com::Guid object. */
10630 com::Guid const UuidCopy(*pUuid);
10631
10632 if (UuidCopy == COM_IIDOF(IConsole))
10633 {
10634 IConsole *pIConsole = static_cast<IConsole *>(pConsole);
10635 return pIConsole;
10636 }
10637
10638 if (UuidCopy == COM_IIDOF(IMachine))
10639 {
10640 IMachine *pIMachine = pConsole->mMachine;
10641 return pIMachine;
10642 }
10643
10644 if (UuidCopy == COM_IIDOF(ISnapshot))
10645 return ((MYVMM2USERMETHODS *)pThis)->pISnapshot;
10646
10647 return NULL;
10648}
10649
10650
10651/**
10652 * @interface_method_impl{PDMISECKEY,pfnKeyRetain}
10653 */
10654/*static*/ DECLCALLBACK(int)
10655Console::i_pdmIfSecKey_KeyRetain(PPDMISECKEY pInterface, const char *pszId, const uint8_t **ppbKey,
10656 size_t *pcbKey)
10657{
10658 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
10659
10660 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
10661 SecretKey *pKey = NULL;
10662
10663 int rc = pConsole->m_pKeyStore->retainSecretKey(Utf8Str(pszId), &pKey);
10664 if (RT_SUCCESS(rc))
10665 {
10666 *ppbKey = (const uint8_t *)pKey->getKeyBuffer();
10667 *pcbKey = pKey->getKeySize();
10668 }
10669
10670 return rc;
10671}
10672
10673/**
10674 * @interface_method_impl{PDMISECKEY,pfnKeyRelease}
10675 */
10676/*static*/ DECLCALLBACK(int)
10677Console::i_pdmIfSecKey_KeyRelease(PPDMISECKEY pInterface, const char *pszId)
10678{
10679 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
10680
10681 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
10682 return pConsole->m_pKeyStore->releaseSecretKey(Utf8Str(pszId));
10683}
10684
10685/**
10686 * @interface_method_impl{PDMISECKEY,pfnPasswordRetain}
10687 */
10688/*static*/ DECLCALLBACK(int)
10689Console::i_pdmIfSecKey_PasswordRetain(PPDMISECKEY pInterface, const char *pszId, const char **ppszPassword)
10690{
10691 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
10692
10693 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
10694 SecretKey *pKey = NULL;
10695
10696 int rc = pConsole->m_pKeyStore->retainSecretKey(Utf8Str(pszId), &pKey);
10697 if (RT_SUCCESS(rc))
10698 *ppszPassword = (const char *)pKey->getKeyBuffer();
10699
10700 return rc;
10701}
10702
10703/**
10704 * @interface_method_impl{PDMISECKEY,pfnPasswordRelease}
10705 */
10706/*static*/ DECLCALLBACK(int)
10707Console::i_pdmIfSecKey_PasswordRelease(PPDMISECKEY pInterface, const char *pszId)
10708{
10709 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
10710
10711 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
10712 return pConsole->m_pKeyStore->releaseSecretKey(Utf8Str(pszId));
10713}
10714
10715/**
10716 * @interface_method_impl{PDMISECKEYHLP,pfnKeyMissingNotify}
10717 */
10718/*static*/ DECLCALLBACK(int)
10719Console::i_pdmIfSecKeyHlp_KeyMissingNotify(PPDMISECKEYHLP pInterface)
10720{
10721 Console *pConsole = ((MYPDMISECKEYHLP *)pInterface)->pConsole;
10722
10723 /* Set guest property only, the VM is paused in the media driver calling us. */
10724 pConsole->mMachine->DeleteGuestProperty(Bstr("/VirtualBox/HostInfo/DekMissing").raw());
10725 pConsole->mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/DekMissing").raw(),
10726 Bstr("1").raw(), Bstr("RDONLYGUEST").raw());
10727 pConsole->mMachine->SaveSettings();
10728
10729 return VINF_SUCCESS;
10730}
10731
10732
10733
10734/**
10735 * The Main status driver instance data.
10736 */
10737typedef struct DRVMAINSTATUS
10738{
10739 /** The LED connectors. */
10740 PDMILEDCONNECTORS ILedConnectors;
10741 /** Pointer to the LED ports interface above us. */
10742 PPDMILEDPORTS pLedPorts;
10743 /** Pointer to the array of LED pointers. */
10744 PPDMLED *papLeds;
10745 /** The unit number corresponding to the first entry in the LED array. */
10746 RTUINT iFirstLUN;
10747 /** The unit number corresponding to the last entry in the LED array.
10748 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
10749 RTUINT iLastLUN;
10750 /** Pointer to the driver instance. */
10751 PPDMDRVINS pDrvIns;
10752 /** The Media Notify interface. */
10753 PDMIMEDIANOTIFY IMediaNotify;
10754 /** Map for translating PDM storage controller/LUN information to
10755 * IMediumAttachment references. */
10756 Console::MediumAttachmentMap *pmapMediumAttachments;
10757 /** Device name+instance for mapping */
10758 char *pszDeviceInstance;
10759 /** Pointer to the Console object, for driver triggered activities. */
10760 Console *pConsole;
10761} DRVMAINSTATUS, *PDRVMAINSTATUS;
10762
10763
10764/**
10765 * Notification about a unit which have been changed.
10766 *
10767 * The driver must discard any pointers to data owned by
10768 * the unit and requery it.
10769 *
10770 * @param pInterface Pointer to the interface structure containing the called function pointer.
10771 * @param iLUN The unit number.
10772 */
10773DECLCALLBACK(void) Console::i_drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
10774{
10775 PDRVMAINSTATUS pThis = RT_FROM_MEMBER(pInterface, DRVMAINSTATUS, ILedConnectors);
10776 if (iLUN >= pThis->iFirstLUN && iLUN <= pThis->iLastLUN)
10777 {
10778 PPDMLED pLed;
10779 int rc = pThis->pLedPorts->pfnQueryStatusLed(pThis->pLedPorts, iLUN, &pLed);
10780 if (RT_FAILURE(rc))
10781 pLed = NULL;
10782 ASMAtomicWritePtr(&pThis->papLeds[iLUN - pThis->iFirstLUN], pLed);
10783 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
10784 }
10785}
10786
10787
10788/**
10789 * Notification about a medium eject.
10790 *
10791 * @returns VBox status code.
10792 * @param pInterface Pointer to the interface structure containing the called function pointer.
10793 * @param uLUN The unit number.
10794 */
10795DECLCALLBACK(int) Console::i_drvStatus_MediumEjected(PPDMIMEDIANOTIFY pInterface, unsigned uLUN)
10796{
10797 PDRVMAINSTATUS pThis = RT_FROM_MEMBER(pInterface, DRVMAINSTATUS, IMediaNotify);
10798 LogFunc(("uLUN=%d\n", uLUN));
10799 if (pThis->pmapMediumAttachments)
10800 {
10801 AutoWriteLock alock(pThis->pConsole COMMA_LOCKVAL_SRC_POS);
10802
10803 ComPtr<IMediumAttachment> pMediumAtt;
10804 Utf8Str devicePath = Utf8StrFmt("%s/LUN#%u", pThis->pszDeviceInstance, uLUN);
10805 Console::MediumAttachmentMap::const_iterator end = pThis->pmapMediumAttachments->end();
10806 Console::MediumAttachmentMap::const_iterator it = pThis->pmapMediumAttachments->find(devicePath);
10807 if (it != end)
10808 pMediumAtt = it->second;
10809 Assert(!pMediumAtt.isNull());
10810 if (!pMediumAtt.isNull())
10811 {
10812 IMedium *pMedium = NULL;
10813 HRESULT rc = pMediumAtt->COMGETTER(Medium)(&pMedium);
10814 AssertComRC(rc);
10815 if (SUCCEEDED(rc) && pMedium)
10816 {
10817 BOOL fHostDrive = FALSE;
10818 rc = pMedium->COMGETTER(HostDrive)(&fHostDrive);
10819 AssertComRC(rc);
10820 if (!fHostDrive)
10821 {
10822 alock.release();
10823
10824 ComPtr<IMediumAttachment> pNewMediumAtt;
10825 rc = pThis->pConsole->mControl->EjectMedium(pMediumAtt, pNewMediumAtt.asOutParam());
10826 if (SUCCEEDED(rc))
10827 {
10828 pThis->pConsole->mMachine->SaveSettings();
10829 fireMediumChangedEvent(pThis->pConsole->mEventSource, pNewMediumAtt);
10830 }
10831
10832 alock.acquire();
10833 if (pNewMediumAtt != pMediumAtt)
10834 {
10835 pThis->pmapMediumAttachments->erase(devicePath);
10836 pThis->pmapMediumAttachments->insert(std::make_pair(devicePath, pNewMediumAtt));
10837 }
10838 }
10839 }
10840 }
10841 }
10842 return VINF_SUCCESS;
10843}
10844
10845
10846/**
10847 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
10848 */
10849DECLCALLBACK(void *) Console::i_drvStatus_QueryInterface(PPDMIBASE pInterface, const char *pszIID)
10850{
10851 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
10852 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10853 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
10854 PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDCONNECTORS, &pThis->ILedConnectors);
10855 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIANOTIFY, &pThis->IMediaNotify);
10856 return NULL;
10857}
10858
10859
10860/**
10861 * Destruct a status driver instance.
10862 *
10863 * @returns VBox status code.
10864 * @param pDrvIns The driver instance data.
10865 */
10866DECLCALLBACK(void) Console::i_drvStatus_Destruct(PPDMDRVINS pDrvIns)
10867{
10868 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
10869 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10870 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
10871
10872 if (pThis->papLeds)
10873 {
10874 unsigned iLed = pThis->iLastLUN - pThis->iFirstLUN + 1;
10875 while (iLed-- > 0)
10876 ASMAtomicWriteNullPtr(&pThis->papLeds[iLed]);
10877 }
10878}
10879
10880
10881/**
10882 * Construct a status driver instance.
10883 *
10884 * @copydoc FNPDMDRVCONSTRUCT
10885 */
10886DECLCALLBACK(int) Console::i_drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
10887{
10888 RT_NOREF(fFlags);
10889 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
10890 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10891 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
10892
10893 /*
10894 * Validate configuration.
10895 */
10896 if (!CFGMR3AreValuesValid(pCfg, "papLeds\0pmapMediumAttachments\0DeviceInstance\0pConsole\0First\0Last\0"))
10897 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
10898 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
10899 ("Configuration error: Not possible to attach anything to this driver!\n"),
10900 VERR_PDM_DRVINS_NO_ATTACH);
10901
10902 /*
10903 * Data.
10904 */
10905 pDrvIns->IBase.pfnQueryInterface = Console::i_drvStatus_QueryInterface;
10906 pThis->ILedConnectors.pfnUnitChanged = Console::i_drvStatus_UnitChanged;
10907 pThis->IMediaNotify.pfnEjected = Console::i_drvStatus_MediumEjected;
10908 pThis->pDrvIns = pDrvIns;
10909 pThis->pszDeviceInstance = NULL;
10910
10911 /*
10912 * Read config.
10913 */
10914 int rc = CFGMR3QueryPtr(pCfg, "papLeds", (void **)&pThis->papLeds);
10915 if (RT_FAILURE(rc))
10916 {
10917 AssertMsgFailed(("Configuration error: Failed to query the \"papLeds\" value! rc=%Rrc\n", rc));
10918 return rc;
10919 }
10920
10921 rc = CFGMR3QueryPtrDef(pCfg, "pmapMediumAttachments", (void **)&pThis->pmapMediumAttachments, NULL);
10922 if (RT_FAILURE(rc))
10923 {
10924 AssertMsgFailed(("Configuration error: Failed to query the \"pmapMediumAttachments\" value! rc=%Rrc\n", rc));
10925 return rc;
10926 }
10927 if (pThis->pmapMediumAttachments)
10928 {
10929 rc = CFGMR3QueryStringAlloc(pCfg, "DeviceInstance", &pThis->pszDeviceInstance);
10930 if (RT_FAILURE(rc))
10931 {
10932 AssertMsgFailed(("Configuration error: Failed to query the \"DeviceInstance\" value! rc=%Rrc\n", rc));
10933 return rc;
10934 }
10935 rc = CFGMR3QueryPtr(pCfg, "pConsole", (void **)&pThis->pConsole);
10936 if (RT_FAILURE(rc))
10937 {
10938 AssertMsgFailed(("Configuration error: Failed to query the \"pConsole\" value! rc=%Rrc\n", rc));
10939 return rc;
10940 }
10941 }
10942
10943 rc = CFGMR3QueryU32(pCfg, "First", &pThis->iFirstLUN);
10944 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
10945 pThis->iFirstLUN = 0;
10946 else if (RT_FAILURE(rc))
10947 {
10948 AssertMsgFailed(("Configuration error: Failed to query the \"First\" value! rc=%Rrc\n", rc));
10949 return rc;
10950 }
10951
10952 rc = CFGMR3QueryU32(pCfg, "Last", &pThis->iLastLUN);
10953 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
10954 pThis->iLastLUN = 0;
10955 else if (RT_FAILURE(rc))
10956 {
10957 AssertMsgFailed(("Configuration error: Failed to query the \"Last\" value! rc=%Rrc\n", rc));
10958 return rc;
10959 }
10960 if (pThis->iFirstLUN > pThis->iLastLUN)
10961 {
10962 AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pThis->iFirstLUN, pThis->iLastLUN));
10963 return VERR_GENERAL_FAILURE;
10964 }
10965
10966 /*
10967 * Get the ILedPorts interface of the above driver/device and
10968 * query the LEDs we want.
10969 */
10970 pThis->pLedPorts = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMILEDPORTS);
10971 AssertMsgReturn(pThis->pLedPorts, ("Configuration error: No led ports interface above!\n"),
10972 VERR_PDM_MISSING_INTERFACE_ABOVE);
10973
10974 for (unsigned i = pThis->iFirstLUN; i <= pThis->iLastLUN; ++i)
10975 Console::i_drvStatus_UnitChanged(&pThis->ILedConnectors, i);
10976
10977 return VINF_SUCCESS;
10978}
10979
10980
10981/**
10982 * Console status driver (LED) registration record.
10983 */
10984const PDMDRVREG Console::DrvStatusReg =
10985{
10986 /* u32Version */
10987 PDM_DRVREG_VERSION,
10988 /* szName */
10989 "MainStatus",
10990 /* szRCMod */
10991 "",
10992 /* szR0Mod */
10993 "",
10994 /* pszDescription */
10995 "Main status driver (Main as in the API).",
10996 /* fFlags */
10997 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
10998 /* fClass. */
10999 PDM_DRVREG_CLASS_STATUS,
11000 /* cMaxInstances */
11001 ~0U,
11002 /* cbInstance */
11003 sizeof(DRVMAINSTATUS),
11004 /* pfnConstruct */
11005 Console::i_drvStatus_Construct,
11006 /* pfnDestruct */
11007 Console::i_drvStatus_Destruct,
11008 /* pfnRelocate */
11009 NULL,
11010 /* pfnIOCtl */
11011 NULL,
11012 /* pfnPowerOn */
11013 NULL,
11014 /* pfnReset */
11015 NULL,
11016 /* pfnSuspend */
11017 NULL,
11018 /* pfnResume */
11019 NULL,
11020 /* pfnAttach */
11021 NULL,
11022 /* pfnDetach */
11023 NULL,
11024 /* pfnPowerOff */
11025 NULL,
11026 /* pfnSoftReset */
11027 NULL,
11028 /* u32EndVersion */
11029 PDM_DRVREG_VERSION
11030};
11031
11032
11033
11034/* 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