VirtualBox

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

Last change on this file since 79036 was 79036, checked in by vboxsync, 5 years ago

Shared Clipboard/URI: Update.

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