VirtualBox

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

Last change on this file since 57818 was 57818, checked in by vboxsync, 9 years ago

pr7179. as example, first attempt to replace auto_ptr on generic C++ pointer. only VMPowerDown task was affected

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