VirtualBox

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

Last change on this file since 56085 was 56085, checked in by vboxsync, 10 years ago

PDM/Audio: Removed old audio architecture.

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