VirtualBox

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

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

Main: Cache the VBoxInternal2/TurnResetIntoPowerOff value so we don't have to release the console lock in Console::powerDown when it's not active, as this introduces a race condition wrt the VM state. It also avoid some IPC during power off, which is nice.

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