VirtualBox

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

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

Recording/Main: Logging.

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