VirtualBox

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

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

Main/VideoRec: Made the audio driver's LUN assignment more flexible by keeping the initial LUN# around when (re-)attaching the driver.

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

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