VirtualBox

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

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

Main: Try harder using the Utf8Str versions of the event stuff where possible. bugref:9790

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

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