VirtualBox

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

Last change on this file since 90160 was 89953, checked in by vboxsync, 3 years ago

Main/{DisplayImpl,ConsoleImpl): Drop passing pointers through CFGM in favor of using VMM2USERMETHODS::pfnQueryGenericObject, bugref:10053

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