VirtualBox

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

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

Main/Console: more forgotten build fixes for r134142

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