VirtualBox

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

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

Changed RTLogCreateEx[V] to take a RTERRINFO pointer rather than plain char * and size_t. Turned out a several callers didn't actually make use of the error message even.

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