VirtualBox

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

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

postfix iterator => prefix iterator and stlSize => stlEmpty where appropriate

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