VirtualBox

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

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

Shared Clipboard/URI: Update.

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