VirtualBox

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

Last change on this file since 81603 was 81603, checked in by vboxsync, 6 years ago

Main: Added PCnet-ISA/NE2100/Am79C960 to the API (the device side is long in place).

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette