VirtualBox

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

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

Main/HGCM: Shutdown HGCM on VM construction failure, indicating that pUVM is invalid preventing info and stats deregistration calls.

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