VirtualBox

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

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

Main/Console: improved NDIS version detection (#7849)

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