VirtualBox

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

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

ConsoleImpl: removed unnecessary local variable.

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

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