VirtualBox

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

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

Main/Console: Remove wrong alock.release() call introduced in r97548, the lock is already released at this point (triggered debug assertions)

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