VirtualBox

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

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

Main: build fixes

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

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