VirtualBox

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

Last change on this file since 90943 was 90828, checked in by vboxsync, 3 years ago

Main: bugref:1909: Added API localization

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