VirtualBox

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

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

Global: replace fall-through comments with RT_FALL_THRU().
bugref:8192: gcc warnings

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