VirtualBox

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

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

Main,VBoxManage,FE/Qt: Extended the createSharedFolder and ISharedFolder methods with a mount poit parameter/attribute for use when auto-mounting. This is especially useful for Windows and OS/2 guests which operates with drive letters. The change has not yet trickled down to the guest interface and VBoxService.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 366.5 KB
Line 
1/* $Id: ConsoleImpl.cpp 75380 2018-11-09 22:25:30Z 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 if (RT_FAILURE(rc))
7036 LogRel(("Recording: Failed to start video recording (%Rrc)\n", rc));
7037
7038 LogFlowFuncLeaveRC(rc);
7039 return rc;
7040}
7041
7042/**
7043 * Stops capturing. Does nothing if capturing is not active.
7044 */
7045int Console::i_recordingStop(void)
7046{
7047 if ( !Recording.mpCtx
7048 || !Recording.mpCtx->IsStarted())
7049 return VINF_SUCCESS;
7050
7051 LogRel(("Recording: Stopping ...\n"));
7052
7053 int rc = Recording.mpCtx->Stop();
7054 if (RT_SUCCESS(rc))
7055 {
7056 const size_t cStreams = Recording.mpCtx->GetStreamCount();
7057 for (unsigned uScreen = 0; uScreen < cStreams; ++uScreen)
7058 mDisplay->i_recordingScreenChanged(uScreen);
7059
7060 ComPtr<IRecordingSettings> pRecordSettings;
7061 HRESULT hrc = mMachine->COMGETTER(RecordingSettings)(pRecordSettings.asOutParam());
7062 ComAssertComRC(hrc);
7063 hrc = pRecordSettings->COMSETTER(Enabled)(false);
7064 ComAssertComRC(hrc);
7065
7066 LogRel(("Recording: Stopped\n"));
7067 }
7068 else
7069 LogRel(("Recording: Failed to stop video recording (%Rrc)\n", rc));
7070
7071 LogFlowFuncLeaveRC(rc);
7072 return rc;
7073}
7074#endif /* VBOX_WITH_RECORDING */
7075
7076/**
7077 * Gets called by Session::UpdateMachineState()
7078 * (IInternalSessionControl::updateMachineState()).
7079 *
7080 * Must be called only in certain cases (see the implementation).
7081 *
7082 * @note Locks this object for writing.
7083 */
7084HRESULT Console::i_updateMachineState(MachineState_T aMachineState)
7085{
7086 AutoCaller autoCaller(this);
7087 AssertComRCReturnRC(autoCaller.rc());
7088
7089 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7090
7091 AssertReturn( mMachineState == MachineState_Saving
7092 || mMachineState == MachineState_OnlineSnapshotting
7093 || mMachineState == MachineState_LiveSnapshotting
7094 || mMachineState == MachineState_DeletingSnapshotOnline
7095 || mMachineState == MachineState_DeletingSnapshotPaused
7096 || aMachineState == MachineState_Saving
7097 || aMachineState == MachineState_OnlineSnapshotting
7098 || aMachineState == MachineState_LiveSnapshotting
7099 || aMachineState == MachineState_DeletingSnapshotOnline
7100 || aMachineState == MachineState_DeletingSnapshotPaused
7101 , E_FAIL);
7102
7103 return i_setMachineStateLocally(aMachineState);
7104}
7105
7106/**
7107 * Gets called by Session::COMGETTER(NominalState)()
7108 * (IInternalSessionControl::getNominalState()).
7109 *
7110 * @note Locks this object for reading.
7111 */
7112HRESULT Console::i_getNominalState(MachineState_T &aNominalState)
7113{
7114 LogFlowThisFuncEnter();
7115
7116 AutoCaller autoCaller(this);
7117 AssertComRCReturnRC(autoCaller.rc());
7118
7119 /* Get the VM handle. */
7120 SafeVMPtr ptrVM(this);
7121 if (!ptrVM.isOk())
7122 return ptrVM.rc();
7123
7124 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
7125
7126 MachineState_T enmMachineState = MachineState_Null;
7127 VMSTATE enmVMState = VMR3GetStateU(ptrVM.rawUVM());
7128 switch (enmVMState)
7129 {
7130 case VMSTATE_CREATING:
7131 case VMSTATE_CREATED:
7132 case VMSTATE_POWERING_ON:
7133 enmMachineState = MachineState_Starting;
7134 break;
7135 case VMSTATE_LOADING:
7136 enmMachineState = MachineState_Restoring;
7137 break;
7138 case VMSTATE_RESUMING:
7139 case VMSTATE_SUSPENDING:
7140 case VMSTATE_SUSPENDING_LS:
7141 case VMSTATE_SUSPENDING_EXT_LS:
7142 case VMSTATE_SUSPENDED:
7143 case VMSTATE_SUSPENDED_LS:
7144 case VMSTATE_SUSPENDED_EXT_LS:
7145 enmMachineState = MachineState_Paused;
7146 break;
7147 case VMSTATE_RUNNING:
7148 case VMSTATE_RUNNING_LS:
7149 case VMSTATE_RUNNING_FT:
7150 case VMSTATE_RESETTING:
7151 case VMSTATE_RESETTING_LS:
7152 case VMSTATE_SOFT_RESETTING:
7153 case VMSTATE_SOFT_RESETTING_LS:
7154 case VMSTATE_DEBUGGING:
7155 case VMSTATE_DEBUGGING_LS:
7156 enmMachineState = MachineState_Running;
7157 break;
7158 case VMSTATE_SAVING:
7159 enmMachineState = MachineState_Saving;
7160 break;
7161 case VMSTATE_POWERING_OFF:
7162 case VMSTATE_POWERING_OFF_LS:
7163 case VMSTATE_DESTROYING:
7164 enmMachineState = MachineState_Stopping;
7165 break;
7166 case VMSTATE_OFF:
7167 case VMSTATE_OFF_LS:
7168 case VMSTATE_FATAL_ERROR:
7169 case VMSTATE_FATAL_ERROR_LS:
7170 case VMSTATE_LOAD_FAILURE:
7171 case VMSTATE_TERMINATED:
7172 enmMachineState = MachineState_PoweredOff;
7173 break;
7174 case VMSTATE_GURU_MEDITATION:
7175 case VMSTATE_GURU_MEDITATION_LS:
7176 enmMachineState = MachineState_Stuck;
7177 break;
7178 default:
7179 AssertMsgFailed(("%s\n", VMR3GetStateName(enmVMState)));
7180 enmMachineState = MachineState_PoweredOff;
7181 }
7182 aNominalState = enmMachineState;
7183
7184 LogFlowFuncLeave();
7185 return S_OK;
7186}
7187
7188void Console::i_onMousePointerShapeChange(bool fVisible, bool fAlpha,
7189 uint32_t xHot, uint32_t yHot,
7190 uint32_t width, uint32_t height,
7191 const uint8_t *pu8Shape,
7192 uint32_t cbShape)
7193{
7194#if 0
7195 LogFlowThisFuncEnter();
7196 LogFlowThisFunc(("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, height=%d, shape=%p\n",
7197 fVisible, fAlpha, xHot, yHot, width, height, pShape));
7198#endif
7199
7200 AutoCaller autoCaller(this);
7201 AssertComRCReturnVoid(autoCaller.rc());
7202
7203 if (!mMouse.isNull())
7204 mMouse->updateMousePointerShape(fVisible, fAlpha, xHot, yHot, width, height,
7205 pu8Shape, cbShape);
7206
7207 com::SafeArray<BYTE> shape(cbShape);
7208 if (pu8Shape)
7209 memcpy(shape.raw(), pu8Shape, cbShape);
7210 fireMousePointerShapeChangedEvent(mEventSource, fVisible, fAlpha, xHot, yHot, width, height, ComSafeArrayAsInParam(shape));
7211
7212#if 0
7213 LogFlowThisFuncLeave();
7214#endif
7215}
7216
7217void Console::i_onMouseCapabilityChange(BOOL supportsAbsolute, BOOL supportsRelative,
7218 BOOL supportsMT, BOOL needsHostCursor)
7219{
7220 LogFlowThisFunc(("supportsAbsolute=%d supportsRelative=%d needsHostCursor=%d\n",
7221 supportsAbsolute, supportsRelative, needsHostCursor));
7222
7223 AutoCaller autoCaller(this);
7224 AssertComRCReturnVoid(autoCaller.rc());
7225
7226 fireMouseCapabilityChangedEvent(mEventSource, supportsAbsolute, supportsRelative, supportsMT, needsHostCursor);
7227}
7228
7229void Console::i_onStateChange(MachineState_T machineState)
7230{
7231 AutoCaller autoCaller(this);
7232 AssertComRCReturnVoid(autoCaller.rc());
7233 fireStateChangedEvent(mEventSource, machineState);
7234}
7235
7236void Console::i_onAdditionsStateChange()
7237{
7238 AutoCaller autoCaller(this);
7239 AssertComRCReturnVoid(autoCaller.rc());
7240
7241 fireAdditionsStateChangedEvent(mEventSource);
7242}
7243
7244/**
7245 * @remarks This notification only is for reporting an incompatible
7246 * Guest Additions interface, *not* the Guest Additions version!
7247 *
7248 * The user will be notified inside the guest if new Guest
7249 * Additions are available (via VBoxTray/VBoxClient).
7250 */
7251void Console::i_onAdditionsOutdated()
7252{
7253 AutoCaller autoCaller(this);
7254 AssertComRCReturnVoid(autoCaller.rc());
7255
7256 /** @todo implement this */
7257}
7258
7259void Console::i_onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
7260{
7261 AutoCaller autoCaller(this);
7262 AssertComRCReturnVoid(autoCaller.rc());
7263
7264 fireKeyboardLedsChangedEvent(mEventSource, fNumLock, fCapsLock, fScrollLock);
7265}
7266
7267void Console::i_onUSBDeviceStateChange(IUSBDevice *aDevice, bool aAttached,
7268 IVirtualBoxErrorInfo *aError)
7269{
7270 AutoCaller autoCaller(this);
7271 AssertComRCReturnVoid(autoCaller.rc());
7272
7273 fireUSBDeviceStateChangedEvent(mEventSource, aDevice, aAttached, aError);
7274}
7275
7276void Console::i_onRuntimeError(BOOL aFatal, IN_BSTR aErrorID, IN_BSTR aMessage)
7277{
7278 AutoCaller autoCaller(this);
7279 AssertComRCReturnVoid(autoCaller.rc());
7280
7281 fireRuntimeErrorEvent(mEventSource, aFatal, aErrorID, aMessage);
7282}
7283
7284HRESULT Console::i_onShowWindow(BOOL aCheck, BOOL *aCanShow, LONG64 *aWinId)
7285{
7286 AssertReturn(aCanShow, E_POINTER);
7287 AssertReturn(aWinId, E_POINTER);
7288
7289 *aCanShow = FALSE;
7290 *aWinId = 0;
7291
7292 AutoCaller autoCaller(this);
7293 AssertComRCReturnRC(autoCaller.rc());
7294
7295 VBoxEventDesc evDesc;
7296 if (aCheck)
7297 {
7298 evDesc.init(mEventSource, VBoxEventType_OnCanShowWindow);
7299 BOOL fDelivered = evDesc.fire(5000); /* Wait up to 5 secs for delivery */
7300 //Assert(fDelivered);
7301 if (fDelivered)
7302 {
7303 ComPtr<IEvent> pEvent;
7304 evDesc.getEvent(pEvent.asOutParam());
7305 // bit clumsy
7306 ComPtr<ICanShowWindowEvent> pCanShowEvent = pEvent;
7307 if (pCanShowEvent)
7308 {
7309 BOOL fVetoed = FALSE;
7310 BOOL fApproved = FALSE;
7311 pCanShowEvent->IsVetoed(&fVetoed);
7312 pCanShowEvent->IsApproved(&fApproved);
7313 *aCanShow = fApproved || !fVetoed;
7314 }
7315 else
7316 {
7317 AssertFailed();
7318 *aCanShow = TRUE;
7319 }
7320 }
7321 else
7322 *aCanShow = TRUE;
7323 }
7324 else
7325 {
7326 evDesc.init(mEventSource, VBoxEventType_OnShowWindow, INT64_C(0));
7327 BOOL fDelivered = evDesc.fire(5000); /* Wait up to 5 secs for delivery */
7328 //Assert(fDelivered);
7329 if (fDelivered)
7330 {
7331 ComPtr<IEvent> pEvent;
7332 evDesc.getEvent(pEvent.asOutParam());
7333 ComPtr<IShowWindowEvent> pShowEvent = pEvent;
7334 if (pShowEvent)
7335 {
7336 LONG64 iEvWinId = 0;
7337 pShowEvent->COMGETTER(WinId)(&iEvWinId);
7338 if (iEvWinId != 0 && *aWinId == 0)
7339 *aWinId = iEvWinId;
7340 }
7341 else
7342 AssertFailed();
7343 }
7344 }
7345
7346 return S_OK;
7347}
7348
7349// private methods
7350////////////////////////////////////////////////////////////////////////////////
7351
7352/**
7353 * Increases the usage counter of the mpUVM pointer.
7354 *
7355 * Guarantees that VMR3Destroy() will not be called on it at least until
7356 * releaseVMCaller() is called.
7357 *
7358 * If this method returns a failure, the caller is not allowed to use mpUVM and
7359 * may return the failed result code to the upper level. This method sets the
7360 * extended error info on failure if \a aQuiet is false.
7361 *
7362 * Setting \a aQuiet to true is useful for methods that don't want to return
7363 * the failed result code to the caller when this method fails (e.g. need to
7364 * silently check for the mpUVM availability).
7365 *
7366 * When mpUVM is NULL but \a aAllowNullVM is true, a corresponding error will be
7367 * returned instead of asserting. Having it false is intended as a sanity check
7368 * for methods that have checked mMachineState and expect mpUVM *NOT* to be
7369 * NULL.
7370 *
7371 * @param aQuiet true to suppress setting error info
7372 * @param aAllowNullVM true to accept mpUVM being NULL and return a failure
7373 * (otherwise this method will assert if mpUVM is NULL)
7374 *
7375 * @note Locks this object for writing.
7376 */
7377HRESULT Console::i_addVMCaller(bool aQuiet /* = false */,
7378 bool aAllowNullVM /* = false */)
7379{
7380 RT_NOREF(aAllowNullVM);
7381 AutoCaller autoCaller(this);
7382 /** @todo Fix race during console/VM reference destruction, refer @bugref{6318}
7383 * comment 25. */
7384 if (FAILED(autoCaller.rc()))
7385 return autoCaller.rc();
7386
7387 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7388
7389 if (mVMDestroying)
7390 {
7391 /* powerDown() is waiting for all callers to finish */
7392 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED, tr("The virtual machine is being powered down"));
7393 }
7394
7395 if (mpUVM == NULL)
7396 {
7397 Assert(aAllowNullVM == true);
7398
7399 /* The machine is not powered up */
7400 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED, tr("The virtual machine is not powered up"));
7401 }
7402
7403 ++mVMCallers;
7404
7405 return S_OK;
7406}
7407
7408/**
7409 * Decreases the usage counter of the mpUVM pointer.
7410 *
7411 * Must always complete the addVMCaller() call after the mpUVM pointer is no
7412 * more necessary.
7413 *
7414 * @note Locks this object for writing.
7415 */
7416void Console::i_releaseVMCaller()
7417{
7418 AutoCaller autoCaller(this);
7419 AssertComRCReturnVoid(autoCaller.rc());
7420
7421 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7422
7423 AssertReturnVoid(mpUVM != NULL);
7424
7425 Assert(mVMCallers > 0);
7426 --mVMCallers;
7427
7428 if (mVMCallers == 0 && mVMDestroying)
7429 {
7430 /* inform powerDown() there are no more callers */
7431 RTSemEventSignal(mVMZeroCallersSem);
7432 }
7433}
7434
7435
7436HRESULT Console::i_safeVMPtrRetainer(PUVM *a_ppUVM, bool a_Quiet)
7437{
7438 *a_ppUVM = NULL;
7439
7440 AutoCaller autoCaller(this);
7441 AssertComRCReturnRC(autoCaller.rc());
7442 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7443
7444 /*
7445 * Repeat the checks done by addVMCaller.
7446 */
7447 if (mVMDestroying) /* powerDown() is waiting for all callers to finish */
7448 return a_Quiet
7449 ? E_ACCESSDENIED
7450 : setError(E_ACCESSDENIED, tr("The virtual machine is being powered down"));
7451 PUVM pUVM = mpUVM;
7452 if (!pUVM)
7453 return a_Quiet
7454 ? E_ACCESSDENIED
7455 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
7456
7457 /*
7458 * Retain a reference to the user mode VM handle and get the global handle.
7459 */
7460 uint32_t cRefs = VMR3RetainUVM(pUVM);
7461 if (cRefs == UINT32_MAX)
7462 return a_Quiet
7463 ? E_ACCESSDENIED
7464 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
7465
7466 /* done */
7467 *a_ppUVM = pUVM;
7468 return S_OK;
7469}
7470
7471void Console::i_safeVMPtrReleaser(PUVM *a_ppUVM)
7472{
7473 if (*a_ppUVM)
7474 VMR3ReleaseUVM(*a_ppUVM);
7475 *a_ppUVM = NULL;
7476}
7477
7478
7479/**
7480 * Initialize the release logging facility. In case something
7481 * goes wrong, there will be no release logging. Maybe in the future
7482 * we can add some logic to use different file names in this case.
7483 * Note that the logic must be in sync with Machine::DeleteSettings().
7484 */
7485HRESULT Console::i_consoleInitReleaseLog(const ComPtr<IMachine> aMachine)
7486{
7487 HRESULT hrc = S_OK;
7488
7489 Bstr logFolder;
7490 hrc = aMachine->COMGETTER(LogFolder)(logFolder.asOutParam());
7491 if (FAILED(hrc))
7492 return hrc;
7493
7494 Utf8Str logDir = logFolder;
7495
7496 /* make sure the Logs folder exists */
7497 Assert(logDir.length());
7498 if (!RTDirExists(logDir.c_str()))
7499 RTDirCreateFullPath(logDir.c_str(), 0700);
7500
7501 Utf8Str logFile = Utf8StrFmt("%s%cVBox.log",
7502 logDir.c_str(), RTPATH_DELIMITER);
7503 Utf8Str pngFile = Utf8StrFmt("%s%cVBox.png",
7504 logDir.c_str(), RTPATH_DELIMITER);
7505
7506 /*
7507 * Age the old log files
7508 * Rename .(n-1) to .(n), .(n-2) to .(n-1), ..., and the last log file to .1
7509 * Overwrite target files in case they exist.
7510 */
7511 ComPtr<IVirtualBox> pVirtualBox;
7512 aMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
7513 ComPtr<ISystemProperties> pSystemProperties;
7514 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
7515 ULONG cHistoryFiles = 3;
7516 pSystemProperties->COMGETTER(LogHistoryCount)(&cHistoryFiles);
7517 if (cHistoryFiles)
7518 {
7519 for (int i = cHistoryFiles-1; i >= 0; i--)
7520 {
7521 Utf8Str *files[] = { &logFile, &pngFile };
7522 Utf8Str oldName, newName;
7523
7524 for (unsigned int j = 0; j < RT_ELEMENTS(files); ++j)
7525 {
7526 if (i > 0)
7527 oldName = Utf8StrFmt("%s.%d", files[j]->c_str(), i);
7528 else
7529 oldName = *files[j];
7530 newName = Utf8StrFmt("%s.%d", files[j]->c_str(), i + 1);
7531 /* If the old file doesn't exist, delete the new file (if it
7532 * exists) to provide correct rotation even if the sequence is
7533 * broken */
7534 if ( RTFileRename(oldName.c_str(), newName.c_str(), RTFILEMOVE_FLAGS_REPLACE)
7535 == VERR_FILE_NOT_FOUND)
7536 RTFileDelete(newName.c_str());
7537 }
7538 }
7539 }
7540
7541 RTERRINFOSTATIC ErrInfo;
7542 int vrc = com::VBoxLogRelCreate("VM", logFile.c_str(),
7543 RTLOGFLAGS_PREFIX_TIME_PROG | RTLOGFLAGS_RESTRICT_GROUPS,
7544 "all all.restrict -default.restrict",
7545 "VBOX_RELEASE_LOG", RTLOGDEST_FILE,
7546 32768 /* cMaxEntriesPerGroup */,
7547 0 /* cHistory */, 0 /* uHistoryFileTime */,
7548 0 /* uHistoryFileSize */, RTErrInfoInitStatic(&ErrInfo));
7549 if (RT_FAILURE(vrc))
7550 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to open release log (%s, %Rrc)"), ErrInfo.Core.pszMsg, vrc);
7551
7552 /* If we've made any directory changes, flush the directory to increase
7553 the likelihood that the log file will be usable after a system panic.
7554
7555 Tip: Try 'export VBOX_RELEASE_LOG_FLAGS=flush' if the last bits of the log
7556 is missing. Just don't have too high hopes for this to help. */
7557 if (SUCCEEDED(hrc) || cHistoryFiles)
7558 RTDirFlush(logDir.c_str());
7559
7560 return hrc;
7561}
7562
7563/**
7564 * Common worker for PowerUp and PowerUpPaused.
7565 *
7566 * @returns COM status code.
7567 *
7568 * @param aProgress Where to return the progress object.
7569 * @param aPaused true if PowerUpPaused called.
7570 */
7571HRESULT Console::i_powerUp(IProgress **aProgress, bool aPaused)
7572{
7573 LogFlowThisFuncEnter();
7574
7575 CheckComArgOutPointerValid(aProgress);
7576
7577 AutoCaller autoCaller(this);
7578 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7579
7580 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7581
7582 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
7583 HRESULT rc = S_OK;
7584 ComObjPtr<Progress> pPowerupProgress;
7585 bool fBeganPoweringUp = false;
7586
7587 LONG cOperations = 1;
7588 LONG ulTotalOperationsWeight = 1;
7589 VMPowerUpTask* task = NULL;
7590
7591 try
7592 {
7593 if (Global::IsOnlineOrTransient(mMachineState))
7594 throw setError(VBOX_E_INVALID_VM_STATE, tr("The virtual machine is already running or busy (machine state: %s)"),
7595 Global::stringifyMachineState(mMachineState));
7596
7597 /* Set up release logging as early as possible after the check if
7598 * there is already a running VM which we shouldn't disturb. */
7599 rc = i_consoleInitReleaseLog(mMachine);
7600 if (FAILED(rc))
7601 throw rc;
7602
7603#ifdef VBOX_OPENSSL_FIPS
7604 LogRel(("crypto: FIPS mode %s\n", FIPS_mode() ? "enabled" : "FAILED"));
7605#endif
7606
7607 /* test and clear the TeleporterEnabled property */
7608 BOOL fTeleporterEnabled;
7609 rc = mMachine->COMGETTER(TeleporterEnabled)(&fTeleporterEnabled);
7610 if (FAILED(rc))
7611 throw rc;
7612
7613#if 0 /** @todo we should save it afterwards, but that isn't necessarily a good idea. Find a better place for this (VBoxSVC). */
7614 if (fTeleporterEnabled)
7615 {
7616 rc = mMachine->COMSETTER(TeleporterEnabled)(FALSE);
7617 if (FAILED(rc))
7618 throw rc;
7619 }
7620#endif
7621
7622 /* test the FaultToleranceState property */
7623 FaultToleranceState_T enmFaultToleranceState;
7624 rc = mMachine->COMGETTER(FaultToleranceState)(&enmFaultToleranceState);
7625 if (FAILED(rc))
7626 throw rc;
7627 BOOL fFaultToleranceSyncEnabled = (enmFaultToleranceState == FaultToleranceState_Standby);
7628
7629 /* Create a progress object to track progress of this operation. Must
7630 * be done as early as possible (together with BeginPowerUp()) as this
7631 * is vital for communicating as much as possible early powerup
7632 * failure information to the API caller */
7633 pPowerupProgress.createObject();
7634 Bstr progressDesc;
7635 if (mMachineState == MachineState_Saved)
7636 progressDesc = tr("Restoring virtual machine");
7637 else if (fTeleporterEnabled)
7638 progressDesc = tr("Teleporting virtual machine");
7639 else if (fFaultToleranceSyncEnabled)
7640 progressDesc = tr("Fault Tolerance syncing of remote virtual machine");
7641 else
7642 progressDesc = tr("Starting virtual machine");
7643
7644 Bstr savedStateFile;
7645
7646 /*
7647 * Saved VMs will have to prove that their saved states seem kosher.
7648 */
7649 if (mMachineState == MachineState_Saved)
7650 {
7651 rc = mMachine->COMGETTER(StateFilePath)(savedStateFile.asOutParam());
7652 if (FAILED(rc))
7653 throw rc;
7654 ComAssertRet(!savedStateFile.isEmpty(), E_FAIL);
7655 int vrc = SSMR3ValidateFile(Utf8Str(savedStateFile).c_str(), false /* fChecksumIt */);
7656 if (RT_FAILURE(vrc))
7657 throw setErrorBoth(VBOX_E_FILE_ERROR, vrc,
7658 tr("VM cannot start because the saved state file '%ls' is invalid (%Rrc). Delete the saved state prior to starting the VM"),
7659 savedStateFile.raw(), vrc);
7660 }
7661
7662 /* Read console data, including console shared folders, stored in the
7663 * saved state file (if not yet done).
7664 */
7665 rc = i_loadDataFromSavedState();
7666 if (FAILED(rc))
7667 throw rc;
7668
7669 /* Check all types of shared folders and compose a single list */
7670 SharedFolderDataMap sharedFolders;
7671 {
7672 /* first, insert global folders */
7673 for (SharedFolderDataMap::const_iterator it = m_mapGlobalSharedFolders.begin();
7674 it != m_mapGlobalSharedFolders.end();
7675 ++it)
7676 {
7677 const SharedFolderData &d = it->second;
7678 sharedFolders[it->first] = d;
7679 }
7680
7681 /* second, insert machine folders */
7682 for (SharedFolderDataMap::const_iterator it = m_mapMachineSharedFolders.begin();
7683 it != m_mapMachineSharedFolders.end();
7684 ++it)
7685 {
7686 const SharedFolderData &d = it->second;
7687 sharedFolders[it->first] = d;
7688 }
7689
7690 /* third, insert console folders */
7691 for (SharedFolderMap::const_iterator it = m_mapSharedFolders.begin();
7692 it != m_mapSharedFolders.end();
7693 ++it)
7694 {
7695 SharedFolder *pSF = it->second;
7696 AutoCaller sfCaller(pSF);
7697 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
7698 sharedFolders[it->first] = SharedFolderData(pSF->i_getHostPath(),
7699 pSF->i_isWritable(),
7700 pSF->i_isAutoMounted(),
7701 pSF->i_getAutoMountPoint());
7702 }
7703 }
7704
7705
7706 /* Setup task object and thread to carry out the operation
7707 * asynchronously */
7708 try
7709 {
7710 task = new VMPowerUpTask(this, pPowerupProgress);
7711 if (!task->isOk())
7712 {
7713 throw E_FAIL;
7714 }
7715 }
7716 catch(...)
7717 {
7718 delete task;
7719 rc = setError(E_FAIL, "Could not create VMPowerUpTask object \n");
7720 throw rc;
7721 }
7722
7723 task->mConfigConstructor = i_configConstructor;
7724 task->mSharedFolders = sharedFolders;
7725 task->mStartPaused = aPaused;
7726 if (mMachineState == MachineState_Saved)
7727 task->mSavedStateFile = savedStateFile;
7728 task->mTeleporterEnabled = fTeleporterEnabled;
7729 task->mEnmFaultToleranceState = enmFaultToleranceState;
7730
7731 /* Reset differencing hard disks for which autoReset is true,
7732 * but only if the machine has no snapshots OR the current snapshot
7733 * is an OFFLINE snapshot; otherwise we would reset the current
7734 * differencing image of an ONLINE snapshot which contains the disk
7735 * state of the machine while it was previously running, but without
7736 * the corresponding machine state, which is equivalent to powering
7737 * off a running machine and not good idea
7738 */
7739 ComPtr<ISnapshot> pCurrentSnapshot;
7740 rc = mMachine->COMGETTER(CurrentSnapshot)(pCurrentSnapshot.asOutParam());
7741 if (FAILED(rc))
7742 throw rc;
7743
7744 BOOL fCurrentSnapshotIsOnline = false;
7745 if (pCurrentSnapshot)
7746 {
7747 rc = pCurrentSnapshot->COMGETTER(Online)(&fCurrentSnapshotIsOnline);
7748 if (FAILED(rc))
7749 throw rc;
7750 }
7751
7752 if (savedStateFile.isEmpty() && !fCurrentSnapshotIsOnline)
7753 {
7754 LogFlowThisFunc(("Looking for immutable images to reset\n"));
7755
7756 com::SafeIfaceArray<IMediumAttachment> atts;
7757 rc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
7758 if (FAILED(rc))
7759 throw rc;
7760
7761 for (size_t i = 0;
7762 i < atts.size();
7763 ++i)
7764 {
7765 DeviceType_T devType;
7766 rc = atts[i]->COMGETTER(Type)(&devType);
7767 /** @todo later applies to floppies as well */
7768 if (devType == DeviceType_HardDisk)
7769 {
7770 ComPtr<IMedium> pMedium;
7771 rc = atts[i]->COMGETTER(Medium)(pMedium.asOutParam());
7772 if (FAILED(rc))
7773 throw rc;
7774
7775 /* needs autoreset? */
7776 BOOL autoReset = FALSE;
7777 rc = pMedium->COMGETTER(AutoReset)(&autoReset);
7778 if (FAILED(rc))
7779 throw rc;
7780
7781 if (autoReset)
7782 {
7783 ComPtr<IProgress> pResetProgress;
7784 rc = pMedium->Reset(pResetProgress.asOutParam());
7785 if (FAILED(rc))
7786 throw rc;
7787
7788 /* save for later use on the powerup thread */
7789 task->hardDiskProgresses.push_back(pResetProgress);
7790 }
7791 }
7792 }
7793 }
7794 else
7795 LogFlowThisFunc(("Machine has a current snapshot which is online, skipping immutable images reset\n"));
7796
7797 /* setup task object and thread to carry out the operation
7798 * asynchronously */
7799
7800#ifdef VBOX_WITH_EXTPACK
7801 mptrExtPackManager->i_dumpAllToReleaseLog();
7802#endif
7803
7804#ifdef RT_OS_SOLARIS
7805 /* setup host core dumper for the VM */
7806 Bstr value;
7807 HRESULT hrc = mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpEnabled").raw(), value.asOutParam());
7808 if (SUCCEEDED(hrc) && value == "1")
7809 {
7810 Bstr coreDumpDir, coreDumpReplaceSys, coreDumpLive;
7811 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpDir").raw(), coreDumpDir.asOutParam());
7812 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpReplaceSystemDump").raw(), coreDumpReplaceSys.asOutParam());
7813 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpLive").raw(), coreDumpLive.asOutParam());
7814
7815 uint32_t fCoreFlags = 0;
7816 if ( coreDumpReplaceSys.isEmpty() == false
7817 && Utf8Str(coreDumpReplaceSys).toUInt32() == 1)
7818 fCoreFlags |= RTCOREDUMPER_FLAGS_REPLACE_SYSTEM_DUMP;
7819
7820 if ( coreDumpLive.isEmpty() == false
7821 && Utf8Str(coreDumpLive).toUInt32() == 1)
7822 fCoreFlags |= RTCOREDUMPER_FLAGS_LIVE_CORE;
7823
7824 Utf8Str strDumpDir(coreDumpDir);
7825 const char *pszDumpDir = strDumpDir.c_str();
7826 if ( pszDumpDir
7827 && *pszDumpDir == '\0')
7828 pszDumpDir = NULL;
7829
7830 int vrc;
7831 if ( pszDumpDir
7832 && !RTDirExists(pszDumpDir))
7833 {
7834 /*
7835 * Try create the directory.
7836 */
7837 vrc = RTDirCreateFullPath(pszDumpDir, 0700);
7838 if (RT_FAILURE(vrc))
7839 throw setErrorBoth(E_FAIL, vrc, "Failed to setup CoreDumper. Couldn't create dump directory '%s' (%Rrc)\n",
7840 pszDumpDir, vrc);
7841 }
7842
7843 vrc = RTCoreDumperSetup(pszDumpDir, fCoreFlags);
7844 if (RT_FAILURE(vrc))
7845 throw setErrorBoth(E_FAIL, vrc, "Failed to setup CoreDumper (%Rrc)", vrc);
7846 LogRel(("CoreDumper setup successful. pszDumpDir=%s fFlags=%#x\n", pszDumpDir ? pszDumpDir : ".", fCoreFlags));
7847 }
7848#endif
7849
7850
7851 // If there is immutable drive the process that.
7852 VMPowerUpTask::ProgressList progresses(task->hardDiskProgresses);
7853 if (aProgress && !progresses.empty())
7854 {
7855 for (VMPowerUpTask::ProgressList::const_iterator it = progresses.begin(); it != progresses.end(); ++it)
7856 {
7857 ++cOperations;
7858 ulTotalOperationsWeight += 1;
7859 }
7860 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7861 progressDesc.raw(),
7862 TRUE, // Cancelable
7863 cOperations,
7864 ulTotalOperationsWeight,
7865 Bstr(tr("Starting Hard Disk operations")).raw(),
7866 1);
7867 AssertComRCReturnRC(rc);
7868 }
7869 else if ( mMachineState == MachineState_Saved
7870 || (!fTeleporterEnabled && !fFaultToleranceSyncEnabled))
7871 {
7872 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7873 progressDesc.raw(),
7874 FALSE /* aCancelable */);
7875 }
7876 else if (fTeleporterEnabled)
7877 {
7878 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7879 progressDesc.raw(),
7880 TRUE /* aCancelable */,
7881 3 /* cOperations */,
7882 10 /* ulTotalOperationsWeight */,
7883 Bstr(tr("Teleporting virtual machine")).raw(),
7884 1 /* ulFirstOperationWeight */);
7885 }
7886 else if (fFaultToleranceSyncEnabled)
7887 {
7888 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7889 progressDesc.raw(),
7890 TRUE /* aCancelable */,
7891 3 /* cOperations */,
7892 10 /* ulTotalOperationsWeight */,
7893 Bstr(tr("Fault Tolerance syncing of remote virtual machine")).raw(),
7894 1 /* ulFirstOperationWeight */);
7895 }
7896
7897 if (FAILED(rc))
7898 throw rc;
7899
7900 /* Tell VBoxSVC and Machine about the progress object so they can
7901 combine/proxy it to any openRemoteSession caller. */
7902 LogFlowThisFunc(("Calling BeginPowerUp...\n"));
7903 rc = mControl->BeginPowerUp(pPowerupProgress);
7904 if (FAILED(rc))
7905 {
7906 LogFlowThisFunc(("BeginPowerUp failed\n"));
7907 throw rc;
7908 }
7909 fBeganPoweringUp = true;
7910
7911 LogFlowThisFunc(("Checking if canceled...\n"));
7912 BOOL fCanceled;
7913 rc = pPowerupProgress->COMGETTER(Canceled)(&fCanceled);
7914 if (FAILED(rc))
7915 throw rc;
7916
7917 if (fCanceled)
7918 {
7919 LogFlowThisFunc(("Canceled in BeginPowerUp\n"));
7920 throw setError(E_FAIL, tr("Powerup was canceled"));
7921 }
7922 LogFlowThisFunc(("Not canceled yet.\n"));
7923
7924 /** @todo this code prevents starting a VM with unavailable bridged
7925 * networking interface. The only benefit is a slightly better error
7926 * message, which should be moved to the driver code. This is the
7927 * only reason why I left the code in for now. The driver allows
7928 * unavailable bridged networking interfaces in certain circumstances,
7929 * and this is sabotaged by this check. The VM will initially have no
7930 * network connectivity, but the user can fix this at runtime. */
7931#if 0
7932 /* the network cards will undergo a quick consistency check */
7933 for (ULONG slot = 0;
7934 slot < maxNetworkAdapters;
7935 ++slot)
7936 {
7937 ComPtr<INetworkAdapter> pNetworkAdapter;
7938 mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
7939 BOOL enabled = FALSE;
7940 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
7941 if (!enabled)
7942 continue;
7943
7944 NetworkAttachmentType_T netattach;
7945 pNetworkAdapter->COMGETTER(AttachmentType)(&netattach);
7946 switch (netattach)
7947 {
7948 case NetworkAttachmentType_Bridged:
7949 {
7950 /* a valid host interface must have been set */
7951 Bstr hostif;
7952 pNetworkAdapter->COMGETTER(HostInterface)(hostif.asOutParam());
7953 if (hostif.isEmpty())
7954 {
7955 throw setError(VBOX_E_HOST_ERROR,
7956 tr("VM cannot start because host interface networking requires a host interface name to be set"));
7957 }
7958 ComPtr<IVirtualBox> pVirtualBox;
7959 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
7960 ComPtr<IHost> pHost;
7961 pVirtualBox->COMGETTER(Host)(pHost.asOutParam());
7962 ComPtr<IHostNetworkInterface> pHostInterface;
7963 if (!SUCCEEDED(pHost->FindHostNetworkInterfaceByName(hostif.raw(),
7964 pHostInterface.asOutParam())))
7965 {
7966 throw setError(VBOX_E_HOST_ERROR,
7967 tr("VM cannot start because the host interface '%ls' does not exist"), hostif.raw());
7968 }
7969 break;
7970 }
7971 default:
7972 break;
7973 }
7974 }
7975#endif // 0
7976
7977
7978 /* setup task object and thread to carry out the operation
7979 * asynchronously */
7980 if (aProgress){
7981 rc = pPowerupProgress.queryInterfaceTo(aProgress);
7982 AssertComRCReturnRC(rc);
7983 }
7984
7985 rc = task->createThread();
7986
7987 if (FAILED(rc))
7988 throw rc;
7989
7990 /* finally, set the state: no right to fail in this method afterwards
7991 * since we've already started the thread and it is now responsible for
7992 * any error reporting and appropriate state change! */
7993 if (mMachineState == MachineState_Saved)
7994 i_setMachineState(MachineState_Restoring);
7995 else if (fTeleporterEnabled)
7996 i_setMachineState(MachineState_TeleportingIn);
7997 else if (enmFaultToleranceState == FaultToleranceState_Standby)
7998 i_setMachineState(MachineState_FaultTolerantSyncing);
7999 else
8000 i_setMachineState(MachineState_Starting);
8001 }
8002 catch (HRESULT aRC) { rc = aRC; }
8003
8004 if (FAILED(rc) && fBeganPoweringUp)
8005 {
8006
8007 /* The progress object will fetch the current error info */
8008 if (!pPowerupProgress.isNull())
8009 pPowerupProgress->i_notifyComplete(rc);
8010
8011 /* Save the error info across the IPC below. Can't be done before the
8012 * progress notification above, as saving the error info deletes it
8013 * from the current context, and thus the progress object wouldn't be
8014 * updated correctly. */
8015 ErrorInfoKeeper eik;
8016
8017 /* signal end of operation */
8018 mControl->EndPowerUp(rc);
8019 }
8020
8021 LogFlowThisFunc(("mMachineState=%d, rc=%Rhrc\n", mMachineState, rc));
8022 LogFlowThisFuncLeave();
8023 return rc;
8024}
8025
8026/**
8027 * Internal power off worker routine.
8028 *
8029 * This method may be called only at certain places with the following meaning
8030 * as shown below:
8031 *
8032 * - if the machine state is either Running or Paused, a normal
8033 * Console-initiated powerdown takes place (e.g. PowerDown());
8034 * - if the machine state is Saving, saveStateThread() has successfully done its
8035 * job;
8036 * - if the machine state is Starting or Restoring, powerUpThread() has failed
8037 * to start/load the VM;
8038 * - if the machine state is Stopping, the VM has powered itself off (i.e. not
8039 * as a result of the powerDown() call).
8040 *
8041 * Calling it in situations other than the above will cause unexpected behavior.
8042 *
8043 * Note that this method should be the only one that destroys mpUVM and sets it
8044 * to NULL.
8045 *
8046 * @param aProgress Progress object to run (may be NULL).
8047 *
8048 * @note Locks this object for writing.
8049 *
8050 * @note Never call this method from a thread that called addVMCaller() or
8051 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
8052 * release(). Otherwise it will deadlock.
8053 */
8054HRESULT Console::i_powerDown(IProgress *aProgress /*= NULL*/)
8055{
8056 LogFlowThisFuncEnter();
8057
8058 AutoCaller autoCaller(this);
8059 AssertComRCReturnRC(autoCaller.rc());
8060
8061 ComPtr<IInternalProgressControl> pProgressControl(aProgress);
8062
8063 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8064
8065 /* Total # of steps for the progress object. Must correspond to the
8066 * number of "advance percent count" comments in this method! */
8067 enum { StepCount = 7 };
8068 /* current step */
8069 ULONG step = 0;
8070
8071 HRESULT rc = S_OK;
8072 int vrc = VINF_SUCCESS;
8073
8074 /* sanity */
8075 Assert(mVMDestroying == false);
8076
8077 PUVM pUVM = mpUVM; Assert(pUVM != NULL);
8078 uint32_t cRefs = VMR3RetainUVM(pUVM); Assert(cRefs != UINT32_MAX); NOREF(cRefs);
8079
8080 AssertMsg( mMachineState == MachineState_Running
8081 || mMachineState == MachineState_Paused
8082 || mMachineState == MachineState_Stuck
8083 || mMachineState == MachineState_Starting
8084 || mMachineState == MachineState_Stopping
8085 || mMachineState == MachineState_Saving
8086 || mMachineState == MachineState_Restoring
8087 || mMachineState == MachineState_TeleportingPausedVM
8088 || mMachineState == MachineState_FaultTolerantSyncing
8089 || mMachineState == MachineState_TeleportingIn
8090 , ("Invalid machine state: %s\n", Global::stringifyMachineState(mMachineState)));
8091
8092 LogRel(("Console::powerDown(): A request to power off the VM has been issued (mMachineState=%s, InUninit=%d)\n",
8093 Global::stringifyMachineState(mMachineState), getObjectState().getState() == ObjectState::InUninit));
8094
8095 /* Check if we need to power off the VM. In case of mVMPoweredOff=true, the
8096 * VM has already powered itself off in vmstateChangeCallback() and is just
8097 * notifying Console about that. In case of Starting or Restoring,
8098 * powerUpThread() is calling us on failure, so the VM is already off at
8099 * that point. */
8100 if ( !mVMPoweredOff
8101 && ( mMachineState == MachineState_Starting
8102 || mMachineState == MachineState_Restoring
8103 || mMachineState == MachineState_FaultTolerantSyncing
8104 || mMachineState == MachineState_TeleportingIn)
8105 )
8106 mVMPoweredOff = true;
8107
8108 /*
8109 * Go to Stopping state if not already there.
8110 *
8111 * Note that we don't go from Saving/Restoring to Stopping because
8112 * vmstateChangeCallback() needs it to set the state to Saved on
8113 * VMSTATE_TERMINATED. In terms of protecting from inappropriate operations
8114 * while leaving the lock below, Saving or Restoring should be fine too.
8115 * Ditto for TeleportingPausedVM -> Teleported.
8116 */
8117 if ( mMachineState != MachineState_Saving
8118 && mMachineState != MachineState_Restoring
8119 && mMachineState != MachineState_Stopping
8120 && mMachineState != MachineState_TeleportingIn
8121 && mMachineState != MachineState_TeleportingPausedVM
8122 && mMachineState != MachineState_FaultTolerantSyncing
8123 )
8124 i_setMachineState(MachineState_Stopping);
8125
8126 /* ----------------------------------------------------------------------
8127 * DONE with necessary state changes, perform the power down actions (it's
8128 * safe to release the object lock now if needed)
8129 * ---------------------------------------------------------------------- */
8130
8131 if (mDisplay)
8132 {
8133 alock.release();
8134
8135 mDisplay->i_notifyPowerDown();
8136
8137 alock.acquire();
8138 }
8139
8140 /* Stop the VRDP server to prevent new clients connection while VM is being
8141 * powered off. */
8142 if (mConsoleVRDPServer)
8143 {
8144 LogFlowThisFunc(("Stopping VRDP server...\n"));
8145
8146 /* Leave the lock since EMT could call us back as addVMCaller() */
8147 alock.release();
8148
8149 mConsoleVRDPServer->Stop();
8150
8151 alock.acquire();
8152 }
8153
8154 /* advance percent count */
8155 if (pProgressControl)
8156 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8157
8158
8159 /* ----------------------------------------------------------------------
8160 * Now, wait for all mpUVM callers to finish their work if there are still
8161 * some on other threads. NO methods that need mpUVM (or initiate other calls
8162 * that need it) may be called after this point
8163 * ---------------------------------------------------------------------- */
8164
8165 /* go to the destroying state to prevent from adding new callers */
8166 mVMDestroying = true;
8167
8168 if (mVMCallers > 0)
8169 {
8170 /* lazy creation */
8171 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
8172 RTSemEventCreate(&mVMZeroCallersSem);
8173
8174 LogFlowThisFunc(("Waiting for mpUVM callers (%d) to drop to zero...\n", mVMCallers));
8175
8176 alock.release();
8177
8178 RTSemEventWait(mVMZeroCallersSem, RT_INDEFINITE_WAIT);
8179
8180 alock.acquire();
8181 }
8182
8183 /* advance percent count */
8184 if (pProgressControl)
8185 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8186
8187 vrc = VINF_SUCCESS;
8188
8189 /*
8190 * Power off the VM if not already done that.
8191 * Leave the lock since EMT will call vmstateChangeCallback.
8192 *
8193 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
8194 * VM-(guest-)initiated power off happened in parallel a ms before this
8195 * call. So far, we let this error pop up on the user's side.
8196 */
8197 if (!mVMPoweredOff)
8198 {
8199 LogFlowThisFunc(("Powering off the VM...\n"));
8200 alock.release();
8201 vrc = VMR3PowerOff(pUVM);
8202#ifdef VBOX_WITH_EXTPACK
8203 mptrExtPackManager->i_callAllVmPowerOffHooks(this, VMR3GetVM(pUVM));
8204#endif
8205 alock.acquire();
8206 }
8207
8208 /* advance percent count */
8209 if (pProgressControl)
8210 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8211
8212#ifdef VBOX_WITH_HGCM
8213 /* Shutdown HGCM services before destroying the VM. */
8214 if (m_pVMMDev)
8215 {
8216 LogFlowThisFunc(("Shutdown HGCM...\n"));
8217
8218 /* Leave the lock since EMT might wait for it and will call us back as addVMCaller() */
8219 alock.release();
8220
8221 DBGFR3InfoDeregisterExternal(pUVM, "guestprops"); /* will crash in unloaded code if we guru later */
8222 m_pVMMDev->hgcmShutdown();
8223
8224 alock.acquire();
8225 }
8226
8227 /* advance percent count */
8228 if (pProgressControl)
8229 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8230
8231#endif /* VBOX_WITH_HGCM */
8232
8233 LogFlowThisFunc(("Ready for VM destruction.\n"));
8234
8235 /* If we are called from Console::uninit(), then try to destroy the VM even
8236 * on failure (this will most likely fail too, but what to do?..) */
8237 if (RT_SUCCESS(vrc) || getObjectState().getState() == ObjectState::InUninit)
8238 {
8239 /* If the machine has a USB controller, release all USB devices
8240 * (symmetric to the code in captureUSBDevices()) */
8241 if (mfVMHasUsbController)
8242 {
8243 alock.release();
8244 i_detachAllUSBDevices(false /* aDone */);
8245 alock.acquire();
8246 }
8247
8248 /* Now we've got to destroy the VM as well. (mpUVM is not valid beyond
8249 * this point). We release the lock before calling VMR3Destroy() because
8250 * it will result into calling destructors of drivers associated with
8251 * Console children which may in turn try to lock Console (e.g. by
8252 * instantiating SafeVMPtr to access mpUVM). It's safe here because
8253 * mVMDestroying is set which should prevent any activity. */
8254
8255 /* Set mpUVM to NULL early just in case if some old code is not using
8256 * addVMCaller()/releaseVMCaller(). (We have our own ref on pUVM.) */
8257 VMR3ReleaseUVM(mpUVM);
8258 mpUVM = NULL;
8259
8260 LogFlowThisFunc(("Destroying the VM...\n"));
8261
8262 alock.release();
8263
8264 vrc = VMR3Destroy(pUVM);
8265
8266 /* take the lock again */
8267 alock.acquire();
8268
8269 /* advance percent count */
8270 if (pProgressControl)
8271 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8272
8273 if (RT_SUCCESS(vrc))
8274 {
8275 LogFlowThisFunc(("Machine has been destroyed (mMachineState=%d)\n",
8276 mMachineState));
8277 /* Note: the Console-level machine state change happens on the
8278 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
8279 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
8280 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
8281 * occurred yet. This is okay, because mMachineState is already
8282 * Stopping in this case, so any other attempt to call PowerDown()
8283 * will be rejected. */
8284 }
8285 else
8286 {
8287 /* bad bad bad, but what to do? (Give Console our UVM ref.) */
8288 mpUVM = pUVM;
8289 pUVM = NULL;
8290 rc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not destroy the machine. (Error: %Rrc)"), vrc);
8291 }
8292
8293 /* Complete the detaching of the USB devices. */
8294 if (mfVMHasUsbController)
8295 {
8296 alock.release();
8297 i_detachAllUSBDevices(true /* aDone */);
8298 alock.acquire();
8299 }
8300
8301 /* advance percent count */
8302 if (pProgressControl)
8303 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8304 }
8305 else
8306 rc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not power off the machine. (Error: %Rrc)"), vrc);
8307
8308 /*
8309 * Finished with the destruction.
8310 *
8311 * Note that if something impossible happened and we've failed to destroy
8312 * the VM, mVMDestroying will remain true and mMachineState will be
8313 * something like Stopping, so most Console methods will return an error
8314 * to the caller.
8315 */
8316 if (pUVM != NULL)
8317 VMR3ReleaseUVM(pUVM);
8318 else
8319 mVMDestroying = false;
8320
8321 LogFlowThisFuncLeave();
8322 return rc;
8323}
8324
8325/**
8326 * @note Locks this object for writing.
8327 */
8328HRESULT Console::i_setMachineState(MachineState_T aMachineState,
8329 bool aUpdateServer /* = true */)
8330{
8331 AutoCaller autoCaller(this);
8332 AssertComRCReturnRC(autoCaller.rc());
8333
8334 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8335
8336 HRESULT rc = S_OK;
8337
8338 if (mMachineState != aMachineState)
8339 {
8340 LogThisFunc(("machineState=%s -> %s aUpdateServer=%RTbool\n",
8341 Global::stringifyMachineState(mMachineState), Global::stringifyMachineState(aMachineState), aUpdateServer));
8342 LogRel(("Console: Machine state changed to '%s'\n", Global::stringifyMachineState(aMachineState)));
8343 mMachineState = aMachineState;
8344
8345 /// @todo (dmik)
8346 // possibly, we need to redo onStateChange() using the dedicated
8347 // Event thread, like it is done in VirtualBox. This will make it
8348 // much safer (no deadlocks possible if someone tries to use the
8349 // console from the callback), however, listeners will lose the
8350 // ability to synchronously react to state changes (is it really
8351 // necessary??)
8352 LogFlowThisFunc(("Doing onStateChange()...\n"));
8353 i_onStateChange(aMachineState);
8354 LogFlowThisFunc(("Done onStateChange()\n"));
8355
8356 if (aUpdateServer)
8357 {
8358 /* Server notification MUST be done from under the lock; otherwise
8359 * the machine state here and on the server might go out of sync
8360 * which can lead to various unexpected results (like the machine
8361 * state being >= MachineState_Running on the server, while the
8362 * session state is already SessionState_Unlocked at the same time
8363 * there).
8364 *
8365 * Cross-lock conditions should be carefully watched out: calling
8366 * UpdateState we will require Machine and SessionMachine locks
8367 * (remember that here we're holding the Console lock here, and also
8368 * all locks that have been acquire by the thread before calling
8369 * this method).
8370 */
8371 LogFlowThisFunc(("Doing mControl->UpdateState()...\n"));
8372 rc = mControl->UpdateState(aMachineState);
8373 LogFlowThisFunc(("mControl->UpdateState()=%Rhrc\n", rc));
8374 }
8375 }
8376
8377 return rc;
8378}
8379
8380/**
8381 * Searches for a shared folder with the given logical name
8382 * in the collection of shared folders.
8383 *
8384 * @param strName logical name of the shared folder
8385 * @param aSharedFolder where to return the found object
8386 * @param aSetError whether to set the error info if the folder is
8387 * not found
8388 * @return
8389 * S_OK when found or E_INVALIDARG when not found
8390 *
8391 * @note The caller must lock this object for writing.
8392 */
8393HRESULT Console::i_findSharedFolder(const Utf8Str &strName,
8394 ComObjPtr<SharedFolder> &aSharedFolder,
8395 bool aSetError /* = false */)
8396{
8397 /* sanity check */
8398 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8399
8400 SharedFolderMap::const_iterator it = m_mapSharedFolders.find(strName);
8401 if (it != m_mapSharedFolders.end())
8402 {
8403 aSharedFolder = it->second;
8404 return S_OK;
8405 }
8406
8407 if (aSetError)
8408 setError(VBOX_E_FILE_ERROR, tr("Could not find a shared folder named '%s'."), strName.c_str());
8409
8410 return VBOX_E_FILE_ERROR;
8411}
8412
8413/**
8414 * Fetches the list of global or machine shared folders from the server.
8415 *
8416 * @param aGlobal true to fetch global folders.
8417 *
8418 * @note The caller must lock this object for writing.
8419 */
8420HRESULT Console::i_fetchSharedFolders(BOOL aGlobal)
8421{
8422 /* sanity check */
8423 AssertReturn( getObjectState().getState() == ObjectState::InInit
8424 || isWriteLockOnCurrentThread(), E_FAIL);
8425
8426 LogFlowThisFunc(("Entering\n"));
8427
8428 /* Check if we're online and keep it that way. */
8429 SafeVMPtrQuiet ptrVM(this);
8430 AutoVMCallerQuietWeak autoVMCaller(this);
8431 bool const online = ptrVM.isOk()
8432 && m_pVMMDev
8433 && m_pVMMDev->isShFlActive();
8434
8435 HRESULT rc = S_OK;
8436
8437 try
8438 {
8439 if (aGlobal)
8440 {
8441 /// @todo grab & process global folders when they are done
8442 }
8443 else
8444 {
8445 SharedFolderDataMap oldFolders;
8446 if (online)
8447 oldFolders = m_mapMachineSharedFolders;
8448
8449 m_mapMachineSharedFolders.clear();
8450
8451 SafeIfaceArray<ISharedFolder> folders;
8452 rc = mMachine->COMGETTER(SharedFolders)(ComSafeArrayAsOutParam(folders));
8453 if (FAILED(rc)) throw rc;
8454
8455 for (size_t i = 0; i < folders.size(); ++i)
8456 {
8457 ComPtr<ISharedFolder> pSharedFolder = folders[i];
8458
8459 Bstr bstr;
8460 rc = pSharedFolder->COMGETTER(Name)(bstr.asOutParam());
8461 if (FAILED(rc)) throw rc;
8462 Utf8Str strName(bstr);
8463
8464 rc = pSharedFolder->COMGETTER(HostPath)(bstr.asOutParam());
8465 if (FAILED(rc)) throw rc;
8466 Utf8Str strHostPath(bstr);
8467
8468 BOOL writable;
8469 rc = pSharedFolder->COMGETTER(Writable)(&writable);
8470 if (FAILED(rc)) throw rc;
8471
8472 BOOL autoMount;
8473 rc = pSharedFolder->COMGETTER(AutoMount)(&autoMount);
8474 if (FAILED(rc)) throw rc;
8475
8476 rc = pSharedFolder->COMGETTER(AutoMountPoint)(bstr.asOutParam());
8477 if (FAILED(rc)) throw rc;
8478 Utf8Str strAutoMountPoint(bstr);
8479
8480 m_mapMachineSharedFolders.insert(std::make_pair(strName,
8481 SharedFolderData(strHostPath, !!writable,
8482 !!autoMount, strAutoMountPoint)));
8483
8484 /* send changes to HGCM if the VM is running */
8485 if (online)
8486 {
8487 SharedFolderDataMap::iterator it = oldFolders.find(strName);
8488 if ( it == oldFolders.end()
8489 || it->second.m_strHostPath != strHostPath)
8490 {
8491 /* a new machine folder is added or
8492 * the existing machine folder is changed */
8493 if (m_mapSharedFolders.find(strName) != m_mapSharedFolders.end())
8494 ; /* the console folder exists, nothing to do */
8495 else
8496 {
8497 /* remove the old machine folder (when changed)
8498 * or the global folder if any (when new) */
8499 if ( it != oldFolders.end()
8500 || m_mapGlobalSharedFolders.find(strName) != m_mapGlobalSharedFolders.end()
8501 )
8502 {
8503 rc = i_removeSharedFolder(strName);
8504 if (FAILED(rc)) throw rc;
8505 }
8506
8507 /* create the new machine folder */
8508 rc = i_createSharedFolder(strName,
8509 SharedFolderData(strHostPath, !!writable, !!autoMount, strAutoMountPoint));
8510 if (FAILED(rc)) throw rc;
8511 }
8512 }
8513 /* forget the processed (or identical) folder */
8514 if (it != oldFolders.end())
8515 oldFolders.erase(it);
8516 }
8517 }
8518
8519 /* process outdated (removed) folders */
8520 if (online)
8521 {
8522 for (SharedFolderDataMap::const_iterator it = oldFolders.begin();
8523 it != oldFolders.end(); ++it)
8524 {
8525 if (m_mapSharedFolders.find(it->first) != m_mapSharedFolders.end())
8526 ; /* the console folder exists, nothing to do */
8527 else
8528 {
8529 /* remove the outdated machine folder */
8530 rc = i_removeSharedFolder(it->first);
8531 if (FAILED(rc)) throw rc;
8532
8533 /* create the global folder if there is any */
8534 SharedFolderDataMap::const_iterator git =
8535 m_mapGlobalSharedFolders.find(it->first);
8536 if (git != m_mapGlobalSharedFolders.end())
8537 {
8538 rc = i_createSharedFolder(git->first, git->second);
8539 if (FAILED(rc)) throw rc;
8540 }
8541 }
8542 }
8543 }
8544 }
8545 }
8546 catch (HRESULT rc2)
8547 {
8548 rc = rc2;
8549 if (online)
8550 i_atVMRuntimeErrorCallbackF(0, "BrokenSharedFolder", N_("Broken shared folder!"));
8551 }
8552
8553 LogFlowThisFunc(("Leaving\n"));
8554
8555 return rc;
8556}
8557
8558/**
8559 * Searches for a shared folder with the given name in the list of machine
8560 * shared folders and then in the list of the global shared folders.
8561 *
8562 * @param strName Name of the folder to search for.
8563 * @param aIt Where to store the pointer to the found folder.
8564 * @return @c true if the folder was found and @c false otherwise.
8565 *
8566 * @note The caller must lock this object for reading.
8567 */
8568bool Console::i_findOtherSharedFolder(const Utf8Str &strName,
8569 SharedFolderDataMap::const_iterator &aIt)
8570{
8571 /* sanity check */
8572 AssertReturn(isWriteLockOnCurrentThread(), false);
8573
8574 /* first, search machine folders */
8575 aIt = m_mapMachineSharedFolders.find(strName);
8576 if (aIt != m_mapMachineSharedFolders.end())
8577 return true;
8578
8579 /* second, search machine folders */
8580 aIt = m_mapGlobalSharedFolders.find(strName);
8581 if (aIt != m_mapGlobalSharedFolders.end())
8582 return true;
8583
8584 return false;
8585}
8586
8587/**
8588 * Calls the HGCM service to add a shared folder definition.
8589 *
8590 * @param strName Shared folder name.
8591 * @param aData Shared folder data.
8592 *
8593 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
8594 * @note Doesn't lock anything.
8595 */
8596HRESULT Console::i_createSharedFolder(const Utf8Str &strName, const SharedFolderData &aData)
8597{
8598 Log(("Adding shared folder '%s' -> '%s'\n", strName.c_str(), aData.m_strHostPath.c_str()));
8599
8600 /*
8601 * Sanity checks
8602 */
8603 ComAssertRet(strName.isNotEmpty(), E_FAIL);
8604 ComAssertRet(aData.m_strHostPath.isNotEmpty(), E_FAIL);
8605
8606 AssertReturn(mpUVM, E_FAIL);
8607 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
8608
8609 /*
8610 * Find out whether we should allow symbolic link creation.
8611 */
8612 Bstr bstrValue;
8613 HRESULT hrc = mMachine->GetExtraData(BstrFmt("VBoxInternal2/SharedFoldersEnableSymlinksCreate/%s", strName.c_str()).raw(),
8614 bstrValue.asOutParam());
8615 bool fSymlinksCreate = hrc == S_OK && bstrValue == "1";
8616
8617 /*
8618 * Check whether the path is valid and exists.
8619 */
8620 char szAbsHostPath[RTPATH_MAX];
8621 int vrc = RTPathAbsEx(NULL, aData.m_strHostPath.c_str(), szAbsHostPath, sizeof(szAbsHostPath));
8622 if (RT_FAILURE(vrc))
8623 return setErrorBoth(E_INVALIDARG, vrc, tr("Invalid shared folder path: '%s' (%Rrc)"), aData.m_strHostPath.c_str(), vrc);
8624
8625 /* Check whether the path is full (absolute). ASSUMING a RTPATH_MAX of ~4K
8626 this also checks that the length is within bounds of a SHFLSTRING. */
8627 if (RTPathCompare(aData.m_strHostPath.c_str(), szAbsHostPath) != 0)
8628 return setError(E_INVALIDARG,
8629 tr("Shared folder path '%s' is not absolute"),
8630 aData.m_strHostPath.c_str());
8631
8632 bool const fMissing = !RTPathExists(szAbsHostPath);
8633
8634 /*
8635 * Check the other two string lengths before converting them all to SHFLSTRINGS.
8636 */
8637 if (strName.length() >= _2K)
8638 return setError(E_INVALIDARG, tr("Shared folder name is too long: %zu bytes"), strName.length());
8639 if (aData.m_strAutoMountPoint.length() >= RTPATH_MAX)
8640 return setError(E_INVALIDARG, tr("Shared folder mountp point too long: %zu bytes"), aData.m_strAutoMountPoint.length());
8641
8642 PSHFLSTRING pHostPath = ShflStringDupUtf8AsUtf16(aData.m_strHostPath.c_str());
8643 PSHFLSTRING pName = ShflStringDupUtf8AsUtf16(strName.c_str());
8644 PSHFLSTRING pAutoMountPoint = ShflStringDupUtf8AsUtf16(aData.m_strAutoMountPoint.c_str());
8645 if (pHostPath && pName && pAutoMountPoint)
8646 {
8647 /*
8648 * Make a SHFL_FN_ADD_MAPPING call to tell the service about folder.
8649 */
8650 VBOXHGCMSVCPARM aParams[SHFL_CPARMS_ADD_MAPPING];
8651 SHFLSTRING_TO_HGMC_PARAM(&aParams[0], pHostPath);
8652 SHFLSTRING_TO_HGMC_PARAM(&aParams[1], pName);
8653 aParams[2].setUInt32( (aData.m_fWritable ? SHFL_ADD_MAPPING_F_WRITABLE : 0)
8654 | (aData.m_fAutoMount ? SHFL_ADD_MAPPING_F_AUTOMOUNT : 0)
8655 | (fSymlinksCreate ? SHFL_ADD_MAPPING_F_CREATE_SYMLINKS : 0)
8656 | (fMissing ? SHFL_ADD_MAPPING_F_MISSING : 0));
8657 SHFLSTRING_TO_HGMC_PARAM(&aParams[3], pAutoMountPoint);
8658 AssertCompile(SHFL_CPARMS_ADD_MAPPING == 4);
8659
8660 vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders", SHFL_FN_ADD_MAPPING, SHFL_CPARMS_ADD_MAPPING, aParams);
8661 if (RT_FAILURE(vrc))
8662 hrc = setErrorBoth(E_FAIL, vrc, tr("Could not create a shared folder '%s' mapped to '%s' (%Rrc)"),
8663 strName.c_str(), aData.m_strHostPath.c_str(), vrc);
8664
8665 else if (fMissing)
8666 hrc = setError(E_INVALIDARG,
8667 tr("Shared folder path '%s' does not exist on the host"),
8668 aData.m_strHostPath.c_str());
8669 else
8670 hrc = S_OK;
8671 }
8672 else
8673 hrc = E_OUTOFMEMORY;
8674 RTMemFree(pAutoMountPoint);
8675 RTMemFree(pName);
8676 RTMemFree(pHostPath);
8677 return hrc;
8678}
8679
8680/**
8681 * Calls the HGCM service to remove the shared folder definition.
8682 *
8683 * @param strName Shared folder name.
8684 *
8685 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
8686 * @note Doesn't lock anything.
8687 */
8688HRESULT Console::i_removeSharedFolder(const Utf8Str &strName)
8689{
8690 ComAssertRet(strName.isNotEmpty(), E_FAIL);
8691
8692 /* sanity checks */
8693 AssertReturn(mpUVM, E_FAIL);
8694 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
8695
8696 VBOXHGCMSVCPARM parms;
8697 SHFLSTRING *pMapName;
8698 size_t cbString;
8699
8700 Log(("Removing shared folder '%s'\n", strName.c_str()));
8701
8702 Bstr bstrName(strName);
8703 cbString = (bstrName.length() + 1) * sizeof(RTUTF16);
8704 if (cbString >= UINT16_MAX)
8705 return setError(E_INVALIDARG, tr("The name is too long"));
8706 pMapName = (SHFLSTRING *) RTMemAllocZ(SHFLSTRING_HEADER_SIZE + cbString);
8707 Assert(pMapName);
8708 memcpy(pMapName->String.ucs2, bstrName.raw(), cbString);
8709
8710 pMapName->u16Size = (uint16_t)cbString;
8711 pMapName->u16Length = (uint16_t)(cbString - sizeof(RTUTF16));
8712
8713 parms.type = VBOX_HGCM_SVC_PARM_PTR;
8714 parms.u.pointer.addr = pMapName;
8715 parms.u.pointer.size = ShflStringSizeOfBuffer(pMapName);
8716
8717 int vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders",
8718 SHFL_FN_REMOVE_MAPPING,
8719 1, &parms);
8720 RTMemFree(pMapName);
8721 if (RT_FAILURE(vrc))
8722 return setErrorBoth(E_FAIL, vrc, tr("Could not remove the shared folder '%s' (%Rrc)"), strName.c_str(), vrc);
8723
8724 return S_OK;
8725}
8726
8727/** @callback_method_impl{FNVMATSTATE}
8728 *
8729 * @note Locks the Console object for writing.
8730 * @remarks The @a pUVM parameter can be NULL in one case where powerUpThread()
8731 * calls after the VM was destroyed.
8732 */
8733DECLCALLBACK(void) Console::i_vmstateChangeCallback(PUVM pUVM, VMSTATE enmState, VMSTATE enmOldState, void *pvUser)
8734{
8735 LogFlowFunc(("Changing state from %s to %s (pUVM=%p)\n",
8736 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState), pUVM));
8737
8738 Console *that = static_cast<Console *>(pvUser);
8739 AssertReturnVoid(that);
8740
8741 AutoCaller autoCaller(that);
8742
8743 /* Note that we must let this method proceed even if Console::uninit() has
8744 * been already called. In such case this VMSTATE change is a result of:
8745 * 1) powerDown() called from uninit() itself, or
8746 * 2) VM-(guest-)initiated power off. */
8747 AssertReturnVoid( autoCaller.isOk()
8748 || that->getObjectState().getState() == ObjectState::InUninit);
8749
8750 switch (enmState)
8751 {
8752 /*
8753 * The VM has terminated
8754 */
8755 case VMSTATE_OFF:
8756 {
8757#ifdef VBOX_WITH_GUEST_PROPS
8758 if (that->i_isResetTurnedIntoPowerOff())
8759 {
8760 Bstr strPowerOffReason;
8761
8762 if (that->mfPowerOffCausedByReset)
8763 strPowerOffReason = Bstr("Reset");
8764 else
8765 strPowerOffReason = Bstr("PowerOff");
8766
8767 that->mMachine->DeleteGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw());
8768 that->mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw(),
8769 strPowerOffReason.raw(), Bstr("RDONLYGUEST").raw());
8770 that->mMachine->SaveSettings();
8771 }
8772#endif
8773
8774 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8775
8776 if (that->mVMStateChangeCallbackDisabled)
8777 return;
8778
8779 /* Do we still think that it is running? It may happen if this is a
8780 * VM-(guest-)initiated shutdown/poweroff.
8781 */
8782 if ( that->mMachineState != MachineState_Stopping
8783 && that->mMachineState != MachineState_Saving
8784 && that->mMachineState != MachineState_Restoring
8785 && that->mMachineState != MachineState_TeleportingIn
8786 && that->mMachineState != MachineState_FaultTolerantSyncing
8787 && that->mMachineState != MachineState_TeleportingPausedVM
8788 && !that->mVMIsAlreadyPoweringOff
8789 )
8790 {
8791 LogFlowFunc(("VM has powered itself off but Console still thinks it is running. Notifying.\n"));
8792
8793 /*
8794 * Prevent powerDown() from calling VMR3PowerOff() again if this was called from
8795 * the power off state change.
8796 * When called from the Reset state make sure to call VMR3PowerOff() first.
8797 */
8798 Assert(that->mVMPoweredOff == false);
8799 that->mVMPoweredOff = true;
8800
8801 /*
8802 * request a progress object from the server
8803 * (this will set the machine state to Stopping on the server
8804 * to block others from accessing this machine)
8805 */
8806 ComPtr<IProgress> pProgress;
8807 HRESULT rc = that->mControl->BeginPoweringDown(pProgress.asOutParam());
8808 AssertComRC(rc);
8809
8810 /* sync the state with the server */
8811 that->i_setMachineStateLocally(MachineState_Stopping);
8812
8813 /* Setup task object and thread to carry out the operation
8814 * asynchronously (if we call powerDown() right here but there
8815 * is one or more mpUVM callers (added with addVMCaller()) we'll
8816 * deadlock).
8817 */
8818 VMPowerDownTask* task = NULL;
8819 try
8820 {
8821 task = new VMPowerDownTask(that, pProgress);
8822 /* If creating a task failed, this can currently mean one of
8823 * two: either Console::uninit() has been called just a ms
8824 * before (so a powerDown() call is already on the way), or
8825 * powerDown() itself is being already executed. Just do
8826 * nothing.
8827 */
8828 if (!task->isOk())
8829 {
8830 LogFlowFunc(("Console is already being uninitialized. \n"));
8831 throw E_FAIL;
8832 }
8833 }
8834 catch(...)
8835 {
8836 delete task;
8837 LogFlowFunc(("Problem with creating VMPowerDownTask object. \n"));
8838 }
8839
8840 rc = task->createThread();
8841
8842 if (FAILED(rc))
8843 {
8844 LogFlowFunc(("Problem with creating thread for VMPowerDownTask. \n"));
8845 }
8846
8847 }
8848 break;
8849 }
8850
8851 /* The VM has been completely destroyed.
8852 *
8853 * Note: This state change can happen at two points:
8854 * 1) At the end of VMR3Destroy() if it was not called from EMT.
8855 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
8856 * called by EMT.
8857 */
8858 case VMSTATE_TERMINATED:
8859 {
8860 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8861
8862 if (that->mVMStateChangeCallbackDisabled)
8863 break;
8864
8865 /* Terminate host interface networking. If pUVM is NULL, we've been
8866 * manually called from powerUpThread() either before calling
8867 * VMR3Create() or after VMR3Create() failed, so no need to touch
8868 * networking.
8869 */
8870 if (pUVM)
8871 that->i_powerDownHostInterfaces();
8872
8873 /* From now on the machine is officially powered down or remains in
8874 * the Saved state.
8875 */
8876 switch (that->mMachineState)
8877 {
8878 default:
8879 AssertFailed();
8880 RT_FALL_THRU();
8881 case MachineState_Stopping:
8882 /* successfully powered down */
8883 that->i_setMachineState(MachineState_PoweredOff);
8884 break;
8885 case MachineState_Saving:
8886 /* successfully saved */
8887 that->i_setMachineState(MachineState_Saved);
8888 break;
8889 case MachineState_Starting:
8890 /* failed to start, but be patient: set back to PoweredOff
8891 * (for similarity with the below) */
8892 that->i_setMachineState(MachineState_PoweredOff);
8893 break;
8894 case MachineState_Restoring:
8895 /* failed to load the saved state file, but be patient: set
8896 * back to Saved (to preserve the saved state file) */
8897 that->i_setMachineState(MachineState_Saved);
8898 break;
8899 case MachineState_TeleportingIn:
8900 /* Teleportation failed or was canceled. Back to powered off. */
8901 that->i_setMachineState(MachineState_PoweredOff);
8902 break;
8903 case MachineState_TeleportingPausedVM:
8904 /* Successfully teleported the VM. */
8905 that->i_setMachineState(MachineState_Teleported);
8906 break;
8907 case MachineState_FaultTolerantSyncing:
8908 /* Fault tolerant sync failed or was canceled. Back to powered off. */
8909 that->i_setMachineState(MachineState_PoweredOff);
8910 break;
8911 }
8912 break;
8913 }
8914
8915 case VMSTATE_RESETTING:
8916 /** @todo shouldn't VMSTATE_RESETTING_LS be here? */
8917 {
8918#ifdef VBOX_WITH_GUEST_PROPS
8919 /* Do not take any read/write locks here! */
8920 that->i_guestPropertiesHandleVMReset();
8921#endif
8922 break;
8923 }
8924
8925 case VMSTATE_SOFT_RESETTING:
8926 case VMSTATE_SOFT_RESETTING_LS:
8927 /* Shouldn't do anything here! */
8928 break;
8929
8930 case VMSTATE_SUSPENDED:
8931 {
8932 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8933
8934 if (that->mVMStateChangeCallbackDisabled)
8935 break;
8936
8937 switch (that->mMachineState)
8938 {
8939 case MachineState_Teleporting:
8940 that->i_setMachineState(MachineState_TeleportingPausedVM);
8941 break;
8942
8943 case MachineState_LiveSnapshotting:
8944 that->i_setMachineState(MachineState_OnlineSnapshotting);
8945 break;
8946
8947 case MachineState_TeleportingPausedVM:
8948 case MachineState_Saving:
8949 case MachineState_Restoring:
8950 case MachineState_Stopping:
8951 case MachineState_TeleportingIn:
8952 case MachineState_FaultTolerantSyncing:
8953 case MachineState_OnlineSnapshotting:
8954 /* The worker thread handles the transition. */
8955 break;
8956
8957 case MachineState_Running:
8958 that->i_setMachineState(MachineState_Paused);
8959 break;
8960
8961 case MachineState_Paused:
8962 /* Nothing to do. */
8963 break;
8964
8965 default:
8966 AssertMsgFailed(("%s\n", Global::stringifyMachineState(that->mMachineState)));
8967 }
8968 break;
8969 }
8970
8971 case VMSTATE_SUSPENDED_LS:
8972 case VMSTATE_SUSPENDED_EXT_LS:
8973 {
8974 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8975 if (that->mVMStateChangeCallbackDisabled)
8976 break;
8977 switch (that->mMachineState)
8978 {
8979 case MachineState_Teleporting:
8980 that->i_setMachineState(MachineState_TeleportingPausedVM);
8981 break;
8982
8983 case MachineState_LiveSnapshotting:
8984 that->i_setMachineState(MachineState_OnlineSnapshotting);
8985 break;
8986
8987 case MachineState_TeleportingPausedVM:
8988 case MachineState_Saving:
8989 /* ignore */
8990 break;
8991
8992 default:
8993 AssertMsgFailed(("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState),
8994 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
8995 that->i_setMachineState(MachineState_Paused);
8996 break;
8997 }
8998 break;
8999 }
9000
9001 case VMSTATE_RUNNING:
9002 {
9003 if ( enmOldState == VMSTATE_POWERING_ON
9004 || enmOldState == VMSTATE_RESUMING
9005 || enmOldState == VMSTATE_RUNNING_FT)
9006 {
9007 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9008
9009 if (that->mVMStateChangeCallbackDisabled)
9010 break;
9011
9012 Assert( ( ( that->mMachineState == MachineState_Starting
9013 || that->mMachineState == MachineState_Paused)
9014 && enmOldState == VMSTATE_POWERING_ON)
9015 || ( ( that->mMachineState == MachineState_Restoring
9016 || that->mMachineState == MachineState_TeleportingIn
9017 || that->mMachineState == MachineState_Paused
9018 || that->mMachineState == MachineState_Saving
9019 )
9020 && enmOldState == VMSTATE_RESUMING)
9021 || ( that->mMachineState == MachineState_FaultTolerantSyncing
9022 && enmOldState == VMSTATE_RUNNING_FT));
9023
9024 that->i_setMachineState(MachineState_Running);
9025 }
9026
9027 break;
9028 }
9029
9030 case VMSTATE_RUNNING_LS:
9031 AssertMsg( that->mMachineState == MachineState_LiveSnapshotting
9032 || that->mMachineState == MachineState_Teleporting,
9033 ("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState),
9034 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
9035 break;
9036
9037 case VMSTATE_RUNNING_FT:
9038 AssertMsg(that->mMachineState == MachineState_FaultTolerantSyncing,
9039 ("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState),
9040 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
9041 break;
9042
9043 case VMSTATE_FATAL_ERROR:
9044 {
9045 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9046
9047 if (that->mVMStateChangeCallbackDisabled)
9048 break;
9049
9050 /* Fatal errors are only for running VMs. */
9051 Assert(Global::IsOnline(that->mMachineState));
9052
9053 /* Note! 'Pause' is used here in want of something better. There
9054 * are currently only two places where fatal errors might be
9055 * raised, so it is not worth adding a new externally
9056 * visible state for this yet. */
9057 that->i_setMachineState(MachineState_Paused);
9058 break;
9059 }
9060
9061 case VMSTATE_GURU_MEDITATION:
9062 {
9063 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9064
9065 if (that->mVMStateChangeCallbackDisabled)
9066 break;
9067
9068 /* Guru are only for running VMs */
9069 Assert(Global::IsOnline(that->mMachineState));
9070
9071 that->i_setMachineState(MachineState_Stuck);
9072 break;
9073 }
9074
9075 case VMSTATE_CREATED:
9076 {
9077 /*
9078 * We have to set the secret key helper interface for the VD drivers to
9079 * get notified about missing keys.
9080 */
9081 that->i_initSecretKeyIfOnAllAttachments();
9082 break;
9083 }
9084
9085 default: /* shut up gcc */
9086 break;
9087 }
9088}
9089
9090/**
9091 * Changes the clipboard mode.
9092 *
9093 * @param aClipboardMode new clipboard mode.
9094 */
9095void Console::i_changeClipboardMode(ClipboardMode_T aClipboardMode)
9096{
9097 VMMDev *pVMMDev = m_pVMMDev;
9098 Assert(pVMMDev);
9099
9100 VBOXHGCMSVCPARM parm;
9101 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
9102
9103 switch (aClipboardMode)
9104 {
9105 default:
9106 case ClipboardMode_Disabled:
9107 LogRel(("Shared clipboard mode: Off\n"));
9108 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_OFF;
9109 break;
9110 case ClipboardMode_GuestToHost:
9111 LogRel(("Shared clipboard mode: Guest to Host\n"));
9112 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_GUEST_TO_HOST;
9113 break;
9114 case ClipboardMode_HostToGuest:
9115 LogRel(("Shared clipboard mode: Host to Guest\n"));
9116 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_HOST_TO_GUEST;
9117 break;
9118 case ClipboardMode_Bidirectional:
9119 LogRel(("Shared clipboard mode: Bidirectional\n"));
9120 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_BIDIRECTIONAL;
9121 break;
9122 }
9123
9124 pVMMDev->hgcmHostCall("VBoxSharedClipboard", VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE, 1, &parm);
9125}
9126
9127/**
9128 * Changes the drag and drop mode.
9129 *
9130 * @param aDnDMode new drag and drop mode.
9131 */
9132int Console::i_changeDnDMode(DnDMode_T aDnDMode)
9133{
9134 VMMDev *pVMMDev = m_pVMMDev;
9135 AssertPtrReturn(pVMMDev, VERR_INVALID_POINTER);
9136
9137 VBOXHGCMSVCPARM parm;
9138 RT_ZERO(parm);
9139 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
9140
9141 switch (aDnDMode)
9142 {
9143 default:
9144 case DnDMode_Disabled:
9145 LogRel(("Drag and drop mode: Off\n"));
9146 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_OFF;
9147 break;
9148 case DnDMode_GuestToHost:
9149 LogRel(("Drag and drop mode: Guest to Host\n"));
9150 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_GUEST_TO_HOST;
9151 break;
9152 case DnDMode_HostToGuest:
9153 LogRel(("Drag and drop mode: Host to Guest\n"));
9154 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_HOST_TO_GUEST;
9155 break;
9156 case DnDMode_Bidirectional:
9157 LogRel(("Drag and drop mode: Bidirectional\n"));
9158 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_BIDIRECTIONAL;
9159 break;
9160 }
9161
9162 int rc = pVMMDev->hgcmHostCall("VBoxDragAndDropSvc",
9163 DragAndDropSvc::HOST_DND_SET_MODE, 1 /* cParms */, &parm);
9164 if (RT_FAILURE(rc))
9165 LogRel(("Error changing drag and drop mode: %Rrc\n", rc));
9166
9167 return rc;
9168}
9169
9170#ifdef VBOX_WITH_USB
9171/**
9172 * Sends a request to VMM to attach the given host device.
9173 * After this method succeeds, the attached device will appear in the
9174 * mUSBDevices collection.
9175 *
9176 * @param aHostDevice device to attach
9177 *
9178 * @note Synchronously calls EMT.
9179 */
9180HRESULT Console::i_attachUSBDevice(IUSBDevice *aHostDevice, ULONG aMaskedIfs,
9181 const Utf8Str &aCaptureFilename)
9182{
9183 AssertReturn(aHostDevice, E_FAIL);
9184 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
9185
9186 HRESULT hrc;
9187
9188 /*
9189 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
9190 * method in EMT (using usbAttachCallback()).
9191 */
9192 Bstr BstrAddress;
9193 hrc = aHostDevice->COMGETTER(Address)(BstrAddress.asOutParam());
9194 ComAssertComRCRetRC(hrc);
9195
9196 Utf8Str Address(BstrAddress);
9197
9198 Bstr id;
9199 hrc = aHostDevice->COMGETTER(Id)(id.asOutParam());
9200 ComAssertComRCRetRC(hrc);
9201 Guid uuid(id);
9202
9203 BOOL fRemote = FALSE;
9204 hrc = aHostDevice->COMGETTER(Remote)(&fRemote);
9205 ComAssertComRCRetRC(hrc);
9206
9207 Bstr BstrBackend;
9208 hrc = aHostDevice->COMGETTER(Backend)(BstrBackend.asOutParam());
9209 ComAssertComRCRetRC(hrc);
9210
9211 Utf8Str Backend(BstrBackend);
9212
9213 /* Get the VM handle. */
9214 SafeVMPtr ptrVM(this);
9215 if (!ptrVM.isOk())
9216 return ptrVM.rc();
9217
9218 LogFlowThisFunc(("Proxying USB device '%s' {%RTuuid}...\n",
9219 Address.c_str(), uuid.raw()));
9220
9221 void *pvRemoteBackend = NULL;
9222 if (fRemote)
9223 {
9224 RemoteUSBDevice *pRemoteUSBDevice = static_cast<RemoteUSBDevice *>(aHostDevice);
9225 pvRemoteBackend = i_consoleVRDPServer()->USBBackendRequestPointer(pRemoteUSBDevice->clientId(), &uuid);
9226 if (!pvRemoteBackend)
9227 return E_INVALIDARG; /* The clientId is invalid then. */
9228 }
9229
9230 USBConnectionSpeed_T enmSpeed;
9231 hrc = aHostDevice->COMGETTER(Speed)(&enmSpeed);
9232 AssertComRCReturnRC(hrc);
9233
9234 int vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
9235 (PFNRT)i_usbAttachCallback, 10,
9236 this, ptrVM.rawUVM(), aHostDevice, uuid.raw(), Backend.c_str(),
9237 Address.c_str(), pvRemoteBackend, enmSpeed, aMaskedIfs,
9238 aCaptureFilename.isEmpty() ? NULL : aCaptureFilename.c_str());
9239 if (RT_SUCCESS(vrc))
9240 {
9241 /* Create a OUSBDevice and add it to the device list */
9242 ComObjPtr<OUSBDevice> pUSBDevice;
9243 pUSBDevice.createObject();
9244 hrc = pUSBDevice->init(aHostDevice);
9245 AssertComRC(hrc);
9246
9247 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9248 mUSBDevices.push_back(pUSBDevice);
9249 LogFlowFunc(("Attached device {%RTuuid}\n", pUSBDevice->i_id().raw()));
9250
9251 /* notify callbacks */
9252 alock.release();
9253 i_onUSBDeviceStateChange(pUSBDevice, true /* aAttached */, NULL);
9254 }
9255 else
9256 {
9257 Log1WarningThisFunc(("Failed to create proxy device for '%s' {%RTuuid} (%Rrc)\n", Address.c_str(), uuid.raw(), vrc));
9258
9259 switch (vrc)
9260 {
9261 case VERR_VUSB_NO_PORTS:
9262 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to attach the USB device. (No available ports on the USB controller)."));
9263 break;
9264 case VERR_VUSB_USBFS_PERMISSION:
9265 hrc = setErrorBoth(E_FAIL, vrc, tr("Not permitted to open the USB device, check usbfs options"));
9266 break;
9267 default:
9268 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to create a proxy device for the USB device. (Error: %Rrc)"), vrc);
9269 break;
9270 }
9271 }
9272
9273 return hrc;
9274}
9275
9276/**
9277 * USB device attach callback used by AttachUSBDevice().
9278 * Note that AttachUSBDevice() doesn't return until this callback is executed,
9279 * so we don't use AutoCaller and don't care about reference counters of
9280 * interface pointers passed in.
9281 *
9282 * @thread EMT
9283 * @note Locks the console object for writing.
9284 */
9285//static
9286DECLCALLBACK(int)
9287Console::i_usbAttachCallback(Console *that, PUVM pUVM, IUSBDevice *aHostDevice, PCRTUUID aUuid, const char *pszBackend,
9288 const char *aAddress, void *pvRemoteBackend, USBConnectionSpeed_T aEnmSpeed, ULONG aMaskedIfs,
9289 const char *pszCaptureFilename)
9290{
9291 RT_NOREF(aHostDevice);
9292 LogFlowFuncEnter();
9293 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
9294
9295 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
9296 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
9297
9298 VUSBSPEED enmSpeed = VUSB_SPEED_UNKNOWN;
9299 switch (aEnmSpeed)
9300 {
9301 case USBConnectionSpeed_Low: enmSpeed = VUSB_SPEED_LOW; break;
9302 case USBConnectionSpeed_Full: enmSpeed = VUSB_SPEED_FULL; break;
9303 case USBConnectionSpeed_High: enmSpeed = VUSB_SPEED_HIGH; break;
9304 case USBConnectionSpeed_Super: enmSpeed = VUSB_SPEED_SUPER; break;
9305 case USBConnectionSpeed_SuperPlus: enmSpeed = VUSB_SPEED_SUPERPLUS; break;
9306 default: AssertFailed(); break;
9307 }
9308
9309 int vrc = PDMR3UsbCreateProxyDevice(pUVM, aUuid, pszBackend, aAddress, pvRemoteBackend,
9310 enmSpeed, aMaskedIfs, pszCaptureFilename);
9311 LogFlowFunc(("vrc=%Rrc\n", vrc));
9312 LogFlowFuncLeave();
9313 return vrc;
9314}
9315
9316/**
9317 * Sends a request to VMM to detach the given host device. After this method
9318 * succeeds, the detached device will disappear from the mUSBDevices
9319 * collection.
9320 *
9321 * @param aHostDevice device to attach
9322 *
9323 * @note Synchronously calls EMT.
9324 */
9325HRESULT Console::i_detachUSBDevice(const ComObjPtr<OUSBDevice> &aHostDevice)
9326{
9327 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
9328
9329 /* Get the VM handle. */
9330 SafeVMPtr ptrVM(this);
9331 if (!ptrVM.isOk())
9332 return ptrVM.rc();
9333
9334 /* if the device is attached, then there must at least one USB hub. */
9335 AssertReturn(PDMR3UsbHasHub(ptrVM.rawUVM()), E_FAIL);
9336
9337 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9338 LogFlowThisFunc(("Detaching USB proxy device {%RTuuid}...\n",
9339 aHostDevice->i_id().raw()));
9340
9341 /*
9342 * If this was a remote device, release the backend pointer.
9343 * The pointer was requested in usbAttachCallback.
9344 */
9345 BOOL fRemote = FALSE;
9346
9347 HRESULT hrc2 = aHostDevice->COMGETTER(Remote)(&fRemote);
9348 if (FAILED(hrc2))
9349 i_setErrorStatic(hrc2, "GetRemote() failed");
9350
9351 PCRTUUID pUuid = aHostDevice->i_id().raw();
9352 if (fRemote)
9353 {
9354 Guid guid(*pUuid);
9355 i_consoleVRDPServer()->USBBackendReleasePointer(&guid);
9356 }
9357
9358 alock.release();
9359 int vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
9360 (PFNRT)i_usbDetachCallback, 5,
9361 this, ptrVM.rawUVM(), pUuid);
9362 if (RT_SUCCESS(vrc))
9363 {
9364 LogFlowFunc(("Detached device {%RTuuid}\n", pUuid));
9365
9366 /* notify callbacks */
9367 i_onUSBDeviceStateChange(aHostDevice, false /* aAttached */, NULL);
9368 }
9369
9370 ComAssertRCRet(vrc, E_FAIL);
9371
9372 return S_OK;
9373}
9374
9375/**
9376 * USB device detach callback used by DetachUSBDevice().
9377 *
9378 * Note that DetachUSBDevice() doesn't return until this callback is executed,
9379 * so we don't use AutoCaller and don't care about reference counters of
9380 * interface pointers passed in.
9381 *
9382 * @thread EMT
9383 */
9384//static
9385DECLCALLBACK(int)
9386Console::i_usbDetachCallback(Console *that, PUVM pUVM, PCRTUUID aUuid)
9387{
9388 LogFlowFuncEnter();
9389 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
9390
9391 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
9392 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
9393
9394 int vrc = PDMR3UsbDetachDevice(pUVM, aUuid);
9395
9396 LogFlowFunc(("vrc=%Rrc\n", vrc));
9397 LogFlowFuncLeave();
9398 return vrc;
9399}
9400#endif /* VBOX_WITH_USB */
9401
9402/* Note: FreeBSD needs this whether netflt is used or not. */
9403#if ((defined(RT_OS_LINUX) && !defined(VBOX_WITH_NETFLT)) || defined(RT_OS_FREEBSD))
9404/**
9405 * Helper function to handle host interface device creation and attachment.
9406 *
9407 * @param networkAdapter the network adapter which attachment should be reset
9408 * @return COM status code
9409 *
9410 * @note The caller must lock this object for writing.
9411 *
9412 * @todo Move this back into the driver!
9413 */
9414HRESULT Console::i_attachToTapInterface(INetworkAdapter *networkAdapter)
9415{
9416 LogFlowThisFunc(("\n"));
9417 /* sanity check */
9418 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9419
9420# ifdef VBOX_STRICT
9421 /* paranoia */
9422 NetworkAttachmentType_T attachment;
9423 networkAdapter->COMGETTER(AttachmentType)(&attachment);
9424 Assert(attachment == NetworkAttachmentType_Bridged);
9425# endif /* VBOX_STRICT */
9426
9427 HRESULT rc = S_OK;
9428
9429 ULONG slot = 0;
9430 rc = networkAdapter->COMGETTER(Slot)(&slot);
9431 AssertComRC(rc);
9432
9433# ifdef RT_OS_LINUX
9434 /*
9435 * Allocate a host interface device
9436 */
9437 int vrc = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
9438 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
9439 if (RT_SUCCESS(vrc))
9440 {
9441 /*
9442 * Set/obtain the tap interface.
9443 */
9444 struct ifreq IfReq;
9445 RT_ZERO(IfReq);
9446 /* The name of the TAP interface we are using */
9447 Bstr tapDeviceName;
9448 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
9449 if (FAILED(rc))
9450 tapDeviceName.setNull(); /* Is this necessary? */
9451 if (tapDeviceName.isEmpty())
9452 {
9453 LogRel(("No TAP device name was supplied.\n"));
9454 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
9455 }
9456
9457 if (SUCCEEDED(rc))
9458 {
9459 /* If we are using a static TAP device then try to open it. */
9460 Utf8Str str(tapDeviceName);
9461 RTStrCopy(IfReq.ifr_name, sizeof(IfReq.ifr_name), str.c_str()); /** @todo bitch about names which are too long... */
9462 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
9463 vrc = ioctl(RTFileToNative(maTapFD[slot]), TUNSETIFF, &IfReq);
9464 if (vrc != 0)
9465 {
9466 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
9467 rc = setErrorBoth(E_FAIL, vrc, tr("Failed to open the host network interface %ls"), tapDeviceName.raw());
9468 }
9469 }
9470 if (SUCCEEDED(rc))
9471 {
9472 /*
9473 * Make it pollable.
9474 */
9475 if (fcntl(RTFileToNative(maTapFD[slot]), F_SETFL, O_NONBLOCK) != -1)
9476 {
9477 Log(("i_attachToTapInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
9478 /*
9479 * Here is the right place to communicate the TAP file descriptor and
9480 * the host interface name to the server if/when it becomes really
9481 * necessary.
9482 */
9483 maTAPDeviceName[slot] = tapDeviceName;
9484 vrc = VINF_SUCCESS;
9485 }
9486 else
9487 {
9488 int iErr = errno;
9489
9490 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
9491 vrc = VERR_HOSTIF_BLOCKING;
9492 rc = setErrorBoth(E_FAIL, vrc, tr("could not set up the host networking device for non blocking access: %s"),
9493 strerror(errno));
9494 }
9495 }
9496 }
9497 else
9498 {
9499 LogRel(("Configuration error: Failed to open /dev/net/tun rc=%Rrc\n", vrc));
9500 switch (vrc)
9501 {
9502 case VERR_ACCESS_DENIED:
9503 /* will be handled by our caller */
9504 rc = vrc;
9505 break;
9506 default:
9507 rc = setErrorBoth(E_FAIL, vrc, tr("Could not set up the host networking device: %Rrc"), vrc);
9508 break;
9509 }
9510 }
9511
9512# elif defined(RT_OS_FREEBSD)
9513 /*
9514 * Set/obtain the tap interface.
9515 */
9516 /* The name of the TAP interface we are using */
9517 Bstr tapDeviceName;
9518 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
9519 if (FAILED(rc))
9520 tapDeviceName.setNull(); /* Is this necessary? */
9521 if (tapDeviceName.isEmpty())
9522 {
9523 LogRel(("No TAP device name was supplied.\n"));
9524 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
9525 }
9526 char szTapdev[1024] = "/dev/";
9527 /* If we are using a static TAP device then try to open it. */
9528 Utf8Str str(tapDeviceName);
9529 if (str.length() + strlen(szTapdev) <= sizeof(szTapdev))
9530 strcat(szTapdev, str.c_str());
9531 else
9532 memcpy(szTapdev + strlen(szTapdev), str.c_str(),
9533 sizeof(szTapdev) - strlen(szTapdev) - 1); /** @todo bitch about names which are too long... */
9534 int vrc = RTFileOpen(&maTapFD[slot], szTapdev,
9535 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT | RTFILE_O_NON_BLOCK);
9536
9537 if (RT_SUCCESS(vrc))
9538 maTAPDeviceName[slot] = tapDeviceName;
9539 else
9540 {
9541 switch (vrc)
9542 {
9543 case VERR_ACCESS_DENIED:
9544 /* will be handled by our caller */
9545 rc = vrc;
9546 break;
9547 default:
9548 rc = setErrorBoth(E_FAIL, vrc, tr("Failed to open the host network interface %ls"), tapDeviceName.raw());
9549 break;
9550 }
9551 }
9552# else
9553# error "huh?"
9554# endif
9555 /* in case of failure, cleanup. */
9556 if (RT_FAILURE(vrc) && SUCCEEDED(rc))
9557 {
9558 LogRel(("General failure attaching to host interface\n"));
9559 rc = setErrorBoth(E_FAIL, vrc, tr("General failure attaching to host interface"));
9560 }
9561 LogFlowThisFunc(("rc=%Rhrc\n", rc));
9562 return rc;
9563}
9564
9565
9566/**
9567 * Helper function to handle detachment from a host interface
9568 *
9569 * @param networkAdapter the network adapter which attachment should be reset
9570 * @return COM status code
9571 *
9572 * @note The caller must lock this object for writing.
9573 *
9574 * @todo Move this back into the driver!
9575 */
9576HRESULT Console::i_detachFromTapInterface(INetworkAdapter *networkAdapter)
9577{
9578 /* sanity check */
9579 LogFlowThisFunc(("\n"));
9580 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9581
9582 HRESULT rc = S_OK;
9583# ifdef VBOX_STRICT
9584 /* paranoia */
9585 NetworkAttachmentType_T attachment;
9586 networkAdapter->COMGETTER(AttachmentType)(&attachment);
9587 Assert(attachment == NetworkAttachmentType_Bridged);
9588# endif /* VBOX_STRICT */
9589
9590 ULONG slot = 0;
9591 rc = networkAdapter->COMGETTER(Slot)(&slot);
9592 AssertComRC(rc);
9593
9594 /* is there an open TAP device? */
9595 if (maTapFD[slot] != NIL_RTFILE)
9596 {
9597 /*
9598 * Close the file handle.
9599 */
9600 Bstr tapDeviceName, tapTerminateApplication;
9601 bool isStatic = true;
9602 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
9603 if (FAILED(rc) || tapDeviceName.isEmpty())
9604 {
9605 /* If the name is empty, this is a dynamic TAP device, so close it now,
9606 so that the termination script can remove the interface. Otherwise we still
9607 need the FD to pass to the termination script. */
9608 isStatic = false;
9609 int rcVBox = RTFileClose(maTapFD[slot]);
9610 AssertRC(rcVBox);
9611 maTapFD[slot] = NIL_RTFILE;
9612 }
9613 if (isStatic)
9614 {
9615 /* If we are using a static TAP device, we close it now, after having called the
9616 termination script. */
9617 int rcVBox = RTFileClose(maTapFD[slot]);
9618 AssertRC(rcVBox);
9619 }
9620 /* the TAP device name and handle are no longer valid */
9621 maTapFD[slot] = NIL_RTFILE;
9622 maTAPDeviceName[slot] = "";
9623 }
9624 LogFlowThisFunc(("returning %d\n", rc));
9625 return rc;
9626}
9627#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
9628
9629/**
9630 * Called at power down to terminate host interface networking.
9631 *
9632 * @note The caller must lock this object for writing.
9633 */
9634HRESULT Console::i_powerDownHostInterfaces()
9635{
9636 LogFlowThisFunc(("\n"));
9637
9638 /* sanity check */
9639 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9640
9641 /*
9642 * host interface termination handling
9643 */
9644 HRESULT rc = S_OK;
9645 ComPtr<IVirtualBox> pVirtualBox;
9646 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
9647 ComPtr<ISystemProperties> pSystemProperties;
9648 if (pVirtualBox)
9649 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
9650 ChipsetType_T chipsetType = ChipsetType_PIIX3;
9651 mMachine->COMGETTER(ChipsetType)(&chipsetType);
9652 ULONG maxNetworkAdapters = 0;
9653 if (pSystemProperties)
9654 pSystemProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters);
9655
9656 for (ULONG slot = 0; slot < maxNetworkAdapters; slot++)
9657 {
9658 ComPtr<INetworkAdapter> pNetworkAdapter;
9659 rc = mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
9660 if (FAILED(rc)) break;
9661
9662 BOOL enabled = FALSE;
9663 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
9664 if (!enabled)
9665 continue;
9666
9667 NetworkAttachmentType_T attachment;
9668 pNetworkAdapter->COMGETTER(AttachmentType)(&attachment);
9669 if (attachment == NetworkAttachmentType_Bridged)
9670 {
9671#if ((defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)) && !defined(VBOX_WITH_NETFLT))
9672 HRESULT rc2 = i_detachFromTapInterface(pNetworkAdapter);
9673 if (FAILED(rc2) && SUCCEEDED(rc))
9674 rc = rc2;
9675#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
9676 }
9677 }
9678
9679 return rc;
9680}
9681
9682
9683/**
9684 * Process callback handler for VMR3LoadFromFile, VMR3LoadFromStream, VMR3Save
9685 * and VMR3Teleport.
9686 *
9687 * @param pUVM The user mode VM handle.
9688 * @param uPercent Completion percentage (0-100).
9689 * @param pvUser Pointer to an IProgress instance.
9690 * @return VINF_SUCCESS.
9691 */
9692/*static*/
9693DECLCALLBACK(int) Console::i_stateProgressCallback(PUVM pUVM, unsigned uPercent, void *pvUser)
9694{
9695 IProgress *pProgress = static_cast<IProgress *>(pvUser);
9696
9697 /* update the progress object */
9698 if (pProgress)
9699 {
9700 ComPtr<IInternalProgressControl> pProgressControl(pProgress);
9701 AssertReturn(!!pProgressControl, VERR_INVALID_PARAMETER);
9702 pProgressControl->SetCurrentOperationProgress(uPercent);
9703 }
9704
9705 NOREF(pUVM);
9706 return VINF_SUCCESS;
9707}
9708
9709/**
9710 * @copydoc FNVMATERROR
9711 *
9712 * @remarks Might be some tiny serialization concerns with access to the string
9713 * object here...
9714 */
9715/*static*/ DECLCALLBACK(void)
9716Console::i_genericVMSetErrorCallback(PUVM pUVM, void *pvUser, int rc, RT_SRC_POS_DECL,
9717 const char *pszFormat, va_list args)
9718{
9719 RT_SRC_POS_NOREF();
9720 Utf8Str *pErrorText = (Utf8Str *)pvUser;
9721 AssertPtr(pErrorText);
9722
9723 /* We ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users. */
9724 va_list va2;
9725 va_copy(va2, args);
9726
9727 /* Append to any the existing error message. */
9728 if (pErrorText->length())
9729 *pErrorText = Utf8StrFmt("%s.\n%N (%Rrc)", pErrorText->c_str(),
9730 pszFormat, &va2, rc, rc);
9731 else
9732 *pErrorText = Utf8StrFmt("%N (%Rrc)", pszFormat, &va2, rc, rc);
9733
9734 va_end(va2);
9735
9736 NOREF(pUVM);
9737}
9738
9739/**
9740 * VM runtime error callback function (FNVMATRUNTIMEERROR).
9741 *
9742 * See VMSetRuntimeError for the detailed description of parameters.
9743 *
9744 * @param pUVM The user mode VM handle. Ignored, so passing NULL
9745 * is fine.
9746 * @param pvUser The user argument, pointer to the Console instance.
9747 * @param fFlags The action flags. See VMSETRTERR_FLAGS_*.
9748 * @param pszErrorId Error ID string.
9749 * @param pszFormat Error message format string.
9750 * @param va Error message arguments.
9751 * @thread EMT.
9752 */
9753/* static */ DECLCALLBACK(void)
9754Console::i_atVMRuntimeErrorCallback(PUVM pUVM, void *pvUser, uint32_t fFlags,
9755 const char *pszErrorId, const char *pszFormat, va_list va)
9756{
9757 bool const fFatal = !!(fFlags & VMSETRTERR_FLAGS_FATAL);
9758 LogFlowFuncEnter();
9759
9760 Console *that = static_cast<Console *>(pvUser);
9761 AssertReturnVoid(that);
9762
9763 Utf8Str message(pszFormat, va);
9764
9765 LogRel(("Console: VM runtime error: fatal=%RTbool, errorID=%s message=\"%s\"\n",
9766 fFatal, pszErrorId, message.c_str()));
9767
9768 that->i_onRuntimeError(BOOL(fFatal), Bstr(pszErrorId).raw(), Bstr(message).raw());
9769
9770 LogFlowFuncLeave(); NOREF(pUVM);
9771}
9772
9773/**
9774 * Captures USB devices that match filters of the VM.
9775 * Called at VM startup.
9776 *
9777 * @param pUVM The VM handle.
9778 */
9779HRESULT Console::i_captureUSBDevices(PUVM pUVM)
9780{
9781 RT_NOREF(pUVM);
9782 LogFlowThisFunc(("\n"));
9783
9784 /* sanity check */
9785 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
9786 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9787
9788 /* If the machine has a USB controller, ask the USB proxy service to
9789 * capture devices */
9790 if (mfVMHasUsbController)
9791 {
9792 /* release the lock before calling Host in VBoxSVC since Host may call
9793 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
9794 * produce an inter-process dead-lock otherwise. */
9795 alock.release();
9796
9797 HRESULT hrc = mControl->AutoCaptureUSBDevices();
9798 ComAssertComRCRetRC(hrc);
9799 }
9800
9801 return S_OK;
9802}
9803
9804
9805/**
9806 * Detach all USB device which are attached to the VM for the
9807 * purpose of clean up and such like.
9808 */
9809void Console::i_detachAllUSBDevices(bool aDone)
9810{
9811 LogFlowThisFunc(("aDone=%RTbool\n", aDone));
9812
9813 /* sanity check */
9814 AssertReturnVoid(!isWriteLockOnCurrentThread());
9815 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9816
9817 mUSBDevices.clear();
9818
9819 /* release the lock before calling Host in VBoxSVC since Host may call
9820 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
9821 * produce an inter-process dead-lock otherwise. */
9822 alock.release();
9823
9824 mControl->DetachAllUSBDevices(aDone);
9825}
9826
9827/**
9828 * @note Locks this object for writing.
9829 */
9830void Console::i_processRemoteUSBDevices(uint32_t u32ClientId, VRDEUSBDEVICEDESC *pDevList, uint32_t cbDevList, bool fDescExt)
9831{
9832 LogFlowThisFuncEnter();
9833 LogFlowThisFunc(("u32ClientId = %d, pDevList=%p, cbDevList = %d, fDescExt = %d\n",
9834 u32ClientId, pDevList, cbDevList, fDescExt));
9835
9836 AutoCaller autoCaller(this);
9837 if (!autoCaller.isOk())
9838 {
9839 /* Console has been already uninitialized, deny request */
9840 AssertMsgFailed(("Console is already uninitialized\n"));
9841 LogFlowThisFunc(("Console is already uninitialized\n"));
9842 LogFlowThisFuncLeave();
9843 return;
9844 }
9845
9846 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9847
9848 /*
9849 * Mark all existing remote USB devices as dirty.
9850 */
9851 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
9852 it != mRemoteUSBDevices.end();
9853 ++it)
9854 {
9855 (*it)->dirty(true);
9856 }
9857
9858 /*
9859 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
9860 */
9861 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
9862 VRDEUSBDEVICEDESC *e = pDevList;
9863
9864 /* The cbDevList condition must be checked first, because the function can
9865 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
9866 */
9867 while (cbDevList >= 2 && e->oNext)
9868 {
9869 /* Sanitize incoming strings in case they aren't valid UTF-8. */
9870 if (e->oManufacturer)
9871 RTStrPurgeEncoding((char *)e + e->oManufacturer);
9872 if (e->oProduct)
9873 RTStrPurgeEncoding((char *)e + e->oProduct);
9874 if (e->oSerialNumber)
9875 RTStrPurgeEncoding((char *)e + e->oSerialNumber);
9876
9877 LogFlowThisFunc(("vendor %04X, product %04X, name = %s\n",
9878 e->idVendor, e->idProduct,
9879 e->oProduct? (char *)e + e->oProduct: ""));
9880
9881 bool fNewDevice = true;
9882
9883 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
9884 it != mRemoteUSBDevices.end();
9885 ++it)
9886 {
9887 if ((*it)->devId() == e->id
9888 && (*it)->clientId() == u32ClientId)
9889 {
9890 /* The device is already in the list. */
9891 (*it)->dirty(false);
9892 fNewDevice = false;
9893 break;
9894 }
9895 }
9896
9897 if (fNewDevice)
9898 {
9899 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
9900 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""));
9901
9902 /* Create the device object and add the new device to list. */
9903 ComObjPtr<RemoteUSBDevice> pUSBDevice;
9904 pUSBDevice.createObject();
9905 pUSBDevice->init(u32ClientId, e, fDescExt);
9906
9907 mRemoteUSBDevices.push_back(pUSBDevice);
9908
9909 /* Check if the device is ok for current USB filters. */
9910 BOOL fMatched = FALSE;
9911 ULONG fMaskedIfs = 0;
9912
9913 HRESULT hrc = mControl->RunUSBDeviceFilters(pUSBDevice, &fMatched, &fMaskedIfs);
9914
9915 AssertComRC(hrc);
9916
9917 LogFlowThisFunc(("USB filters return %d %#x\n", fMatched, fMaskedIfs));
9918
9919 if (fMatched)
9920 {
9921 alock.release();
9922 hrc = i_onUSBDeviceAttach(pUSBDevice, NULL, fMaskedIfs, Utf8Str());
9923 alock.acquire();
9924
9925 /// @todo (r=dmik) warning reporting subsystem
9926
9927 if (hrc == S_OK)
9928 {
9929 LogFlowThisFunc(("Device attached\n"));
9930 pUSBDevice->captured(true);
9931 }
9932 }
9933 }
9934
9935 if (cbDevList < e->oNext)
9936 {
9937 Log1WarningThisFunc(("cbDevList %d > oNext %d\n", cbDevList, e->oNext));
9938 break;
9939 }
9940
9941 cbDevList -= e->oNext;
9942
9943 e = (VRDEUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
9944 }
9945
9946 /*
9947 * Remove dirty devices, that is those which are not reported by the server anymore.
9948 */
9949 for (;;)
9950 {
9951 ComObjPtr<RemoteUSBDevice> pUSBDevice;
9952
9953 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
9954 while (it != mRemoteUSBDevices.end())
9955 {
9956 if ((*it)->dirty())
9957 {
9958 pUSBDevice = *it;
9959 break;
9960 }
9961
9962 ++it;
9963 }
9964
9965 if (!pUSBDevice)
9966 {
9967 break;
9968 }
9969
9970 USHORT vendorId = 0;
9971 pUSBDevice->COMGETTER(VendorId)(&vendorId);
9972
9973 USHORT productId = 0;
9974 pUSBDevice->COMGETTER(ProductId)(&productId);
9975
9976 Bstr product;
9977 pUSBDevice->COMGETTER(Product)(product.asOutParam());
9978
9979 LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
9980 vendorId, productId, product.raw()));
9981
9982 /* Detach the device from VM. */
9983 if (pUSBDevice->captured())
9984 {
9985 Bstr uuid;
9986 pUSBDevice->COMGETTER(Id)(uuid.asOutParam());
9987 alock.release();
9988 i_onUSBDeviceDetach(uuid.raw(), NULL);
9989 alock.acquire();
9990 }
9991
9992 /* And remove it from the list. */
9993 mRemoteUSBDevices.erase(it);
9994 }
9995
9996 LogFlowThisFuncLeave();
9997}
9998
9999/**
10000 * Progress cancelation callback for fault tolerance VM poweron
10001 */
10002static void faultToleranceProgressCancelCallback(void *pvUser)
10003{
10004 PUVM pUVM = (PUVM)pvUser;
10005
10006 if (pUVM)
10007 FTMR3CancelStandby(pUVM);
10008}
10009
10010/**
10011 * Worker called by VMPowerUpTask::handler to start the VM (also from saved
10012 * state) and track progress.
10013 *
10014 * @param pTask The power up task.
10015 *
10016 * @note Locks the Console object for writing.
10017 */
10018/*static*/
10019void Console::i_powerUpThreadTask(VMPowerUpTask *pTask)
10020{
10021 LogFlowFuncEnter();
10022
10023 AssertReturnVoid(pTask);
10024 AssertReturnVoid(!pTask->mConsole.isNull());
10025 AssertReturnVoid(!pTask->mProgress.isNull());
10026
10027 VirtualBoxBase::initializeComForThread();
10028
10029 HRESULT rc = S_OK;
10030 int vrc = VINF_SUCCESS;
10031
10032 /* Set up a build identifier so that it can be seen from core dumps what
10033 * exact build was used to produce the core. */
10034 static char saBuildID[48];
10035 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%u %s%s%s%s",
10036 "BU", "IL", "DI", "D", RTBldCfgVersion(), RTBldCfgRevision(), "BU", "IL", "DI", "D");
10037
10038 ComObjPtr<Console> pConsole = pTask->mConsole;
10039
10040 /* Note: no need to use AutoCaller because VMPowerUpTask does that */
10041
10042 /* The lock is also used as a signal from the task initiator (which
10043 * releases it only after RTThreadCreate()) that we can start the job */
10044 AutoWriteLock alock(pConsole COMMA_LOCKVAL_SRC_POS);
10045
10046 /* sanity */
10047 Assert(pConsole->mpUVM == NULL);
10048
10049 try
10050 {
10051 // Create the VMM device object, which starts the HGCM thread; do this only
10052 // once for the console, for the pathological case that the same console
10053 // object is used to power up a VM twice.
10054 if (!pConsole->m_pVMMDev)
10055 {
10056 pConsole->m_pVMMDev = new VMMDev(pConsole);
10057 AssertReturnVoid(pConsole->m_pVMMDev);
10058 }
10059
10060 /* wait for auto reset ops to complete so that we can successfully lock
10061 * the attached hard disks by calling LockMedia() below */
10062 for (VMPowerUpTask::ProgressList::const_iterator
10063 it = pTask->hardDiskProgresses.begin();
10064 it != pTask->hardDiskProgresses.end(); ++it)
10065 {
10066 HRESULT rc2 = (*it)->WaitForCompletion(-1);
10067 AssertComRC(rc2);
10068
10069 rc = pTask->mProgress->SetNextOperation(BstrFmt(tr("Disk Image Reset Operation - Immutable Image")).raw(), 1);
10070 AssertComRCReturnVoid(rc);
10071 }
10072
10073 /*
10074 * Lock attached media. This method will also check their accessibility.
10075 * If we're a teleporter, we'll have to postpone this action so we can
10076 * migrate between local processes.
10077 *
10078 * Note! The media will be unlocked automatically by
10079 * SessionMachine::i_setMachineState() when the VM is powered down.
10080 */
10081 if ( !pTask->mTeleporterEnabled
10082 && pTask->mEnmFaultToleranceState != FaultToleranceState_Standby)
10083 {
10084 rc = pConsole->mControl->LockMedia();
10085 if (FAILED(rc)) throw rc;
10086 }
10087
10088 /* Create the VRDP server. In case of headless operation, this will
10089 * also create the framebuffer, required at VM creation.
10090 */
10091 ConsoleVRDPServer *server = pConsole->i_consoleVRDPServer();
10092 Assert(server);
10093
10094 /* Does VRDP server call Console from the other thread?
10095 * Not sure (and can change), so release the lock just in case.
10096 */
10097 alock.release();
10098 vrc = server->Launch();
10099 alock.acquire();
10100
10101 if (vrc != VINF_SUCCESS)
10102 {
10103 Utf8Str errMsg = pConsole->VRDPServerErrorToMsg(vrc);
10104 if ( RT_FAILURE(vrc)
10105 && vrc != VERR_NET_ADDRESS_IN_USE) /* not fatal */
10106 throw i_setErrorStaticBoth(E_FAIL, vrc, errMsg.c_str());
10107 }
10108
10109 ComPtr<IMachine> pMachine = pConsole->i_machine();
10110 ULONG cCpus = 1;
10111 pMachine->COMGETTER(CPUCount)(&cCpus);
10112
10113 /*
10114 * Create the VM
10115 *
10116 * Note! Release the lock since EMT will call Console. It's safe because
10117 * mMachineState is either Starting or Restoring state here.
10118 */
10119 alock.release();
10120
10121 PVM pVM;
10122 vrc = VMR3Create(cCpus,
10123 pConsole->mpVmm2UserMethods,
10124 Console::i_genericVMSetErrorCallback,
10125 &pTask->mErrorMsg,
10126 pTask->mConfigConstructor,
10127 static_cast<Console *>(pConsole),
10128 &pVM, NULL);
10129 alock.acquire();
10130
10131#ifdef VBOX_WITH_AUDIO_VRDE
10132 /* Attach the VRDE audio driver. */
10133 IVRDEServer *pVRDEServer = pConsole->i_getVRDEServer();
10134 if (pVRDEServer)
10135 {
10136 BOOL fVRDEEnabled = FALSE;
10137 rc = pVRDEServer->COMGETTER(Enabled)(&fVRDEEnabled);
10138 AssertComRCReturnVoid(rc);
10139
10140 if ( fVRDEEnabled
10141 && pConsole->mAudioVRDE)
10142 pConsole->mAudioVRDE->doAttachDriverViaEmt(pConsole->mpUVM, &alock);
10143 }
10144#endif
10145
10146 /* Enable client connections to the VRDP server. */
10147 pConsole->i_consoleVRDPServer()->EnableConnections();
10148
10149#ifdef VBOX_WITH_RECORDING
10150 ComPtr<IRecordingSettings> recordingSettings;
10151 rc = pConsole->mMachine->COMGETTER(RecordingSettings)(recordingSettings.asOutParam());
10152 AssertComRCReturnVoid(rc);
10153
10154 BOOL fRecordingEnabled;
10155 rc = recordingSettings->COMGETTER(Enabled)(&fRecordingEnabled);
10156 AssertComRCReturnVoid(rc);
10157
10158 if (fRecordingEnabled)
10159 {
10160 int vrc2 = pConsole->i_recordingEnable(fRecordingEnabled, &alock);
10161 if (RT_SUCCESS(vrc2))
10162 {
10163 fireRecordingChangedEvent(pConsole->mEventSource);
10164 }
10165 else
10166 LogRel(("Recording: Failed with %Rrc on VM power up\n", vrc2));
10167
10168 /** Note: Do not use vrc here, as starting the video recording isn't critical to
10169 * powering up the VM. */
10170 }
10171#endif
10172
10173 if (RT_SUCCESS(vrc))
10174 {
10175 do
10176 {
10177 /*
10178 * Register our load/save state file handlers
10179 */
10180 vrc = SSMR3RegisterExternal(pConsole->mpUVM, sSSMConsoleUnit, 0 /*iInstance*/,
10181 CONSOLE_SAVED_STATE_VERSION, 0 /* cbGuess */,
10182 NULL, NULL, NULL,
10183 NULL, i_saveStateFileExec, NULL,
10184 NULL, i_loadStateFileExec, NULL,
10185 static_cast<Console *>(pConsole));
10186 AssertRCBreak(vrc);
10187
10188 vrc = static_cast<Console *>(pConsole)->i_getDisplay()->i_registerSSM(pConsole->mpUVM);
10189 AssertRC(vrc);
10190 if (RT_FAILURE(vrc))
10191 break;
10192
10193 /*
10194 * Synchronize debugger settings
10195 */
10196 MachineDebugger *machineDebugger = pConsole->i_getMachineDebugger();
10197 if (machineDebugger)
10198 machineDebugger->i_flushQueuedSettings();
10199
10200 /*
10201 * Shared Folders
10202 */
10203 if (pConsole->m_pVMMDev->isShFlActive())
10204 {
10205 /* Does the code below call Console from the other thread?
10206 * Not sure, so release the lock just in case. */
10207 alock.release();
10208
10209 for (SharedFolderDataMap::const_iterator it = pTask->mSharedFolders.begin();
10210 it != pTask->mSharedFolders.end();
10211 ++it)
10212 {
10213 const SharedFolderData &d = it->second;
10214 rc = pConsole->i_createSharedFolder(it->first, d);
10215 if (FAILED(rc))
10216 {
10217 ErrorInfoKeeper eik;
10218 pConsole->i_atVMRuntimeErrorCallbackF(0, "BrokenSharedFolder",
10219 N_("The shared folder '%s' could not be set up: %ls.\n"
10220 "The shared folder setup will not be complete. It is recommended to power down the virtual "
10221 "machine and fix the shared folder settings while the machine is not running"),
10222 it->first.c_str(), eik.getText().raw());
10223 }
10224 }
10225 if (FAILED(rc))
10226 rc = S_OK; // do not fail with broken shared folders
10227
10228 /* acquire the lock again */
10229 alock.acquire();
10230 }
10231
10232 /* release the lock before a lengthy operation */
10233 alock.release();
10234
10235 /*
10236 * Capture USB devices.
10237 */
10238 rc = pConsole->i_captureUSBDevices(pConsole->mpUVM);
10239 if (FAILED(rc))
10240 {
10241 alock.acquire();
10242 break;
10243 }
10244
10245 /* Load saved state? */
10246 if (pTask->mSavedStateFile.length())
10247 {
10248 LogFlowFunc(("Restoring saved state from '%s'...\n", pTask->mSavedStateFile.c_str()));
10249
10250 vrc = VMR3LoadFromFile(pConsole->mpUVM,
10251 pTask->mSavedStateFile.c_str(),
10252 Console::i_stateProgressCallback,
10253 static_cast<IProgress *>(pTask->mProgress));
10254
10255 if (RT_SUCCESS(vrc))
10256 {
10257 if (pTask->mStartPaused)
10258 /* done */
10259 pConsole->i_setMachineState(MachineState_Paused);
10260 else
10261 {
10262 /* Start/Resume the VM execution */
10263#ifdef VBOX_WITH_EXTPACK
10264 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM);
10265#endif
10266 if (RT_SUCCESS(vrc))
10267 vrc = VMR3Resume(pConsole->mpUVM, VMRESUMEREASON_STATE_RESTORED);
10268 AssertLogRelRC(vrc);
10269 }
10270 }
10271
10272 /* Power off in case we failed loading or resuming the VM */
10273 if (RT_FAILURE(vrc))
10274 {
10275 int vrc2 = VMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
10276#ifdef VBOX_WITH_EXTPACK
10277 pConsole->mptrExtPackManager->i_callAllVmPowerOffHooks(pConsole, pVM);
10278#endif
10279 }
10280 }
10281 else if (pTask->mTeleporterEnabled)
10282 {
10283 /* -> ConsoleImplTeleporter.cpp */
10284 bool fPowerOffOnFailure;
10285 rc = pConsole->i_teleporterTrg(pConsole->mpUVM, pMachine, &pTask->mErrorMsg, pTask->mStartPaused,
10286 pTask->mProgress, &fPowerOffOnFailure);
10287 if (FAILED(rc) && fPowerOffOnFailure)
10288 {
10289 ErrorInfoKeeper eik;
10290 int vrc2 = VMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
10291#ifdef VBOX_WITH_EXTPACK
10292 pConsole->mptrExtPackManager->i_callAllVmPowerOffHooks(pConsole, pVM);
10293#endif
10294 }
10295 }
10296 else if (pTask->mEnmFaultToleranceState != FaultToleranceState_Inactive)
10297 {
10298 /*
10299 * Get the config.
10300 */
10301 ULONG uPort;
10302 rc = pMachine->COMGETTER(FaultTolerancePort)(&uPort);
10303 if (SUCCEEDED(rc))
10304 {
10305 ULONG uInterval;
10306 rc = pMachine->COMGETTER(FaultToleranceSyncInterval)(&uInterval);
10307 if (SUCCEEDED(rc))
10308 {
10309 Bstr bstrAddress;
10310 rc = pMachine->COMGETTER(FaultToleranceAddress)(bstrAddress.asOutParam());
10311 if (SUCCEEDED(rc))
10312 {
10313 Bstr bstrPassword;
10314 rc = pMachine->COMGETTER(FaultTolerancePassword)(bstrPassword.asOutParam());
10315 if (SUCCEEDED(rc))
10316 {
10317 if (pTask->mProgress->i_setCancelCallback(faultToleranceProgressCancelCallback,
10318 pConsole->mpUVM))
10319 {
10320 if (SUCCEEDED(rc))
10321 {
10322 Utf8Str strAddress(bstrAddress);
10323 const char *pszAddress = strAddress.isEmpty() ? NULL : strAddress.c_str();
10324 Utf8Str strPassword(bstrPassword);
10325 const char *pszPassword = strPassword.isEmpty() ? NULL : strPassword.c_str();
10326
10327 /* Power on the FT enabled VM. */
10328#ifdef VBOX_WITH_EXTPACK
10329 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM);
10330#endif
10331 if (RT_SUCCESS(vrc))
10332 vrc = FTMR3PowerOn(pConsole->mpUVM,
10333 pTask->mEnmFaultToleranceState == FaultToleranceState_Master /* fMaster */,
10334 uInterval,
10335 pszAddress,
10336 uPort,
10337 pszPassword);
10338 AssertLogRelRC(vrc);
10339 }
10340 pTask->mProgress->i_setCancelCallback(NULL, NULL);
10341 }
10342 else
10343 rc = E_FAIL;
10344
10345 }
10346 }
10347 }
10348 }
10349 }
10350 else if (pTask->mStartPaused)
10351 /* done */
10352 pConsole->i_setMachineState(MachineState_Paused);
10353 else
10354 {
10355 /* Power on the VM (i.e. start executing) */
10356#ifdef VBOX_WITH_EXTPACK
10357 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM);
10358#endif
10359 if (RT_SUCCESS(vrc))
10360 vrc = VMR3PowerOn(pConsole->mpUVM);
10361 AssertLogRelRC(vrc);
10362 }
10363
10364 /* acquire the lock again */
10365 alock.acquire();
10366 }
10367 while (0);
10368
10369 /* On failure, destroy the VM */
10370 if (FAILED(rc) || RT_FAILURE(vrc))
10371 {
10372 /* preserve existing error info */
10373 ErrorInfoKeeper eik;
10374
10375 /* powerDown() will call VMR3Destroy() and do all necessary
10376 * cleanup (VRDP, USB devices) */
10377 alock.release();
10378 HRESULT rc2 = pConsole->i_powerDown();
10379 alock.acquire();
10380 AssertComRC(rc2);
10381 }
10382 else
10383 {
10384 /*
10385 * Deregister the VMSetError callback. This is necessary as the
10386 * pfnVMAtError() function passed to VMR3Create() is supposed to
10387 * be sticky but our error callback isn't.
10388 */
10389 alock.release();
10390 VMR3AtErrorDeregister(pConsole->mpUVM, Console::i_genericVMSetErrorCallback, &pTask->mErrorMsg);
10391 /** @todo register another VMSetError callback? */
10392 alock.acquire();
10393 }
10394 }
10395 else
10396 {
10397 /*
10398 * If VMR3Create() failed it has released the VM memory.
10399 */
10400 VMR3ReleaseUVM(pConsole->mpUVM);
10401 pConsole->mpUVM = NULL;
10402 }
10403
10404 if (SUCCEEDED(rc) && RT_FAILURE(vrc))
10405 {
10406 /* If VMR3Create() or one of the other calls in this function fail,
10407 * an appropriate error message has been set in pTask->mErrorMsg.
10408 * However since that happens via a callback, the rc status code in
10409 * this function is not updated.
10410 */
10411 if (!pTask->mErrorMsg.length())
10412 {
10413 /* If the error message is not set but we've got a failure,
10414 * convert the VBox status code into a meaningful error message.
10415 * This becomes unused once all the sources of errors set the
10416 * appropriate error message themselves.
10417 */
10418 AssertMsgFailed(("Missing error message during powerup for status code %Rrc\n", vrc));
10419 pTask->mErrorMsg = Utf8StrFmt(tr("Failed to start VM execution (%Rrc)"), vrc);
10420 }
10421
10422 /* Set the error message as the COM error.
10423 * Progress::notifyComplete() will pick it up later. */
10424 throw i_setErrorStaticBoth(E_FAIL, vrc, pTask->mErrorMsg.c_str());
10425 }
10426 }
10427 catch (HRESULT aRC) { rc = aRC; }
10428
10429 if ( pConsole->mMachineState == MachineState_Starting
10430 || pConsole->mMachineState == MachineState_Restoring
10431 || pConsole->mMachineState == MachineState_TeleportingIn
10432 )
10433 {
10434 /* We are still in the Starting/Restoring state. This means one of:
10435 *
10436 * 1) we failed before VMR3Create() was called;
10437 * 2) VMR3Create() failed.
10438 *
10439 * In both cases, there is no need to call powerDown(), but we still
10440 * need to go back to the PoweredOff/Saved state. Reuse
10441 * vmstateChangeCallback() for that purpose.
10442 */
10443
10444 /* preserve existing error info */
10445 ErrorInfoKeeper eik;
10446
10447 Assert(pConsole->mpUVM == NULL);
10448 i_vmstateChangeCallback(NULL, VMSTATE_TERMINATED, VMSTATE_CREATING, pConsole);
10449 }
10450
10451 /*
10452 * Evaluate the final result. Note that the appropriate mMachineState value
10453 * is already set by vmstateChangeCallback() in all cases.
10454 */
10455
10456 /* release the lock, don't need it any more */
10457 alock.release();
10458
10459 if (SUCCEEDED(rc))
10460 {
10461 /* Notify the progress object of the success */
10462 pTask->mProgress->i_notifyComplete(S_OK);
10463 }
10464 else
10465 {
10466 /* The progress object will fetch the current error info */
10467 pTask->mProgress->i_notifyComplete(rc);
10468 LogRel(("Power up failed (vrc=%Rrc, rc=%Rhrc (%#08X))\n", vrc, rc, rc));
10469 }
10470
10471 /* Notify VBoxSVC and any waiting openRemoteSession progress object. */
10472 pConsole->mControl->EndPowerUp(rc);
10473
10474#if defined(RT_OS_WINDOWS)
10475 /* uninitialize COM */
10476 CoUninitialize();
10477#endif
10478
10479 LogFlowFuncLeave();
10480}
10481
10482
10483/**
10484 * Reconfigures a medium attachment (part of taking or deleting an online snapshot).
10485 *
10486 * @param pThis Reference to the console object.
10487 * @param pUVM The VM handle.
10488 * @param pcszDevice The name of the controller type.
10489 * @param uInstance The instance of the controller.
10490 * @param enmBus The storage bus type of the controller.
10491 * @param fUseHostIOCache Use the host I/O cache (disable async I/O).
10492 * @param fBuiltinIOCache Use the builtin I/O cache.
10493 * @param fInsertDiskIntegrityDrv Flag whether to insert the disk integrity driver into the chain
10494 * for additionalk debugging aids.
10495 * @param fSetupMerge Whether to set up a medium merge
10496 * @param uMergeSource Merge source image index
10497 * @param uMergeTarget Merge target image index
10498 * @param aMediumAtt The medium attachment.
10499 * @param aMachineState The current machine state.
10500 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
10501 * @return VBox status code.
10502 */
10503/* static */
10504DECLCALLBACK(int) Console::i_reconfigureMediumAttachment(Console *pThis,
10505 PUVM pUVM,
10506 const char *pcszDevice,
10507 unsigned uInstance,
10508 StorageBus_T enmBus,
10509 bool fUseHostIOCache,
10510 bool fBuiltinIOCache,
10511 bool fInsertDiskIntegrityDrv,
10512 bool fSetupMerge,
10513 unsigned uMergeSource,
10514 unsigned uMergeTarget,
10515 IMediumAttachment *aMediumAtt,
10516 MachineState_T aMachineState,
10517 HRESULT *phrc)
10518{
10519 LogFlowFunc(("pUVM=%p aMediumAtt=%p phrc=%p\n", pUVM, aMediumAtt, phrc));
10520
10521 HRESULT hrc;
10522 Bstr bstr;
10523 *phrc = S_OK;
10524#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%Rhrc (%#x)\n", hrc, hrc)); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
10525
10526 /* Ignore attachments other than hard disks, since at the moment they are
10527 * not subject to snapshotting in general. */
10528 DeviceType_T lType;
10529 hrc = aMediumAtt->COMGETTER(Type)(&lType); H();
10530 if (lType != DeviceType_HardDisk)
10531 return VINF_SUCCESS;
10532
10533 /* Update the device instance configuration. */
10534 int rc = pThis->i_configMediumAttachment(pcszDevice,
10535 uInstance,
10536 enmBus,
10537 fUseHostIOCache,
10538 fBuiltinIOCache,
10539 fInsertDiskIntegrityDrv,
10540 fSetupMerge,
10541 uMergeSource,
10542 uMergeTarget,
10543 aMediumAtt,
10544 aMachineState,
10545 phrc,
10546 true /* fAttachDetach */,
10547 false /* fForceUnmount */,
10548 false /* fHotplug */,
10549 pUVM,
10550 NULL /* paLedDevType */,
10551 NULL /* ppLunL0)*/);
10552 if (RT_FAILURE(rc))
10553 {
10554 AssertMsgFailed(("rc=%Rrc\n", rc));
10555 return rc;
10556 }
10557
10558#undef H
10559
10560 LogFlowFunc(("Returns success\n"));
10561 return VINF_SUCCESS;
10562}
10563
10564/**
10565 * Thread for powering down the Console.
10566 *
10567 * @param pTask The power down task.
10568 *
10569 * @note Locks the Console object for writing.
10570 */
10571/*static*/
10572void Console::i_powerDownThreadTask(VMPowerDownTask *pTask)
10573{
10574 int rc = VINF_SUCCESS; /* only used in assertion */
10575 LogFlowFuncEnter();
10576 try
10577 {
10578 if (pTask->isOk() == false)
10579 rc = VERR_GENERAL_FAILURE;
10580
10581 const ComObjPtr<Console> &that = pTask->mConsole;
10582
10583 /* Note: no need to use AutoCaller to protect Console because VMTask does
10584 * that */
10585
10586 /* wait until the method tat started us returns */
10587 AutoWriteLock thatLock(that COMMA_LOCKVAL_SRC_POS);
10588
10589 /* release VM caller to avoid the powerDown() deadlock */
10590 pTask->releaseVMCaller();
10591
10592 thatLock.release();
10593
10594 that->i_powerDown(pTask->mServerProgress);
10595
10596 /* complete the operation */
10597 that->mControl->EndPoweringDown(S_OK, Bstr().raw());
10598
10599 }
10600 catch (const std::exception &e)
10601 {
10602 AssertMsgFailed(("Exception %s was caught, rc=%Rrc\n", e.what(), rc));
10603 NOREF(e); NOREF(rc);
10604 }
10605
10606 LogFlowFuncLeave();
10607}
10608
10609/**
10610 * @interface_method_impl{VMM2USERMETHODS,pfnSaveState}
10611 */
10612/*static*/ DECLCALLBACK(int)
10613Console::i_vmm2User_SaveState(PCVMM2USERMETHODS pThis, PUVM pUVM)
10614{
10615 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
10616 NOREF(pUVM);
10617
10618 /*
10619 * For now, just call SaveState. We should probably try notify the GUI so
10620 * it can pop up a progress object and stuff. The progress object created
10621 * by the call isn't returned to anyone and thus gets updated without
10622 * anyone noticing it.
10623 */
10624 ComPtr<IProgress> pProgress;
10625 HRESULT hrc = pConsole->mMachine->SaveState(pProgress.asOutParam());
10626 return SUCCEEDED(hrc) ? VINF_SUCCESS : Global::vboxStatusCodeFromCOM(hrc);
10627}
10628
10629/**
10630 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtInit}
10631 */
10632/*static*/ DECLCALLBACK(void)
10633Console::i_vmm2User_NotifyEmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
10634{
10635 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
10636 VirtualBoxBase::initializeComForThread();
10637}
10638
10639/**
10640 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtTerm}
10641 */
10642/*static*/ DECLCALLBACK(void)
10643Console::i_vmm2User_NotifyEmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
10644{
10645 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
10646 VirtualBoxBase::uninitializeComForThread();
10647}
10648
10649/**
10650 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtInit}
10651 */
10652/*static*/ DECLCALLBACK(void)
10653Console::i_vmm2User_NotifyPdmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM)
10654{
10655 NOREF(pThis); NOREF(pUVM);
10656 VirtualBoxBase::initializeComForThread();
10657}
10658
10659/**
10660 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtTerm}
10661 */
10662/*static*/ DECLCALLBACK(void)
10663Console::i_vmm2User_NotifyPdmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM)
10664{
10665 NOREF(pThis); NOREF(pUVM);
10666 VirtualBoxBase::uninitializeComForThread();
10667}
10668
10669/**
10670 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyResetTurnedIntoPowerOff}
10671 */
10672/*static*/ DECLCALLBACK(void)
10673Console::i_vmm2User_NotifyResetTurnedIntoPowerOff(PCVMM2USERMETHODS pThis, PUVM pUVM)
10674{
10675 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
10676 NOREF(pUVM);
10677
10678 pConsole->mfPowerOffCausedByReset = true;
10679}
10680
10681/**
10682 * @interface_method_impl{VMM2USERMETHODS,pfnQueryGenericObject}
10683 */
10684/*static*/ DECLCALLBACK(void *)
10685Console::i_vmm2User_QueryGenericObject(PCVMM2USERMETHODS pThis, PUVM pUVM, PCRTUUID pUuid)
10686{
10687 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
10688 NOREF(pUVM);
10689
10690 /* To simplify comparison we copy the UUID into a com::Guid object. */
10691 com::Guid const UuidCopy(*pUuid);
10692
10693 if (UuidCopy == COM_IIDOF(IConsole))
10694 {
10695 IConsole *pIConsole = static_cast<IConsole *>(pConsole);
10696 return pIConsole;
10697 }
10698
10699 if (UuidCopy == COM_IIDOF(IMachine))
10700 {
10701 IMachine *pIMachine = pConsole->mMachine;
10702 return pIMachine;
10703 }
10704
10705 if (UuidCopy == COM_IIDOF(ISnapshot))
10706 return ((MYVMM2USERMETHODS *)pThis)->pISnapshot;
10707
10708 return NULL;
10709}
10710
10711
10712/**
10713 * @interface_method_impl{PDMISECKEY,pfnKeyRetain}
10714 */
10715/*static*/ DECLCALLBACK(int)
10716Console::i_pdmIfSecKey_KeyRetain(PPDMISECKEY pInterface, const char *pszId, const uint8_t **ppbKey,
10717 size_t *pcbKey)
10718{
10719 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
10720
10721 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
10722 SecretKey *pKey = NULL;
10723
10724 int rc = pConsole->m_pKeyStore->retainSecretKey(Utf8Str(pszId), &pKey);
10725 if (RT_SUCCESS(rc))
10726 {
10727 *ppbKey = (const uint8_t *)pKey->getKeyBuffer();
10728 *pcbKey = pKey->getKeySize();
10729 }
10730
10731 return rc;
10732}
10733
10734/**
10735 * @interface_method_impl{PDMISECKEY,pfnKeyRelease}
10736 */
10737/*static*/ DECLCALLBACK(int)
10738Console::i_pdmIfSecKey_KeyRelease(PPDMISECKEY pInterface, const char *pszId)
10739{
10740 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
10741
10742 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
10743 return pConsole->m_pKeyStore->releaseSecretKey(Utf8Str(pszId));
10744}
10745
10746/**
10747 * @interface_method_impl{PDMISECKEY,pfnPasswordRetain}
10748 */
10749/*static*/ DECLCALLBACK(int)
10750Console::i_pdmIfSecKey_PasswordRetain(PPDMISECKEY pInterface, const char *pszId, const char **ppszPassword)
10751{
10752 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
10753
10754 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
10755 SecretKey *pKey = NULL;
10756
10757 int rc = pConsole->m_pKeyStore->retainSecretKey(Utf8Str(pszId), &pKey);
10758 if (RT_SUCCESS(rc))
10759 *ppszPassword = (const char *)pKey->getKeyBuffer();
10760
10761 return rc;
10762}
10763
10764/**
10765 * @interface_method_impl{PDMISECKEY,pfnPasswordRelease}
10766 */
10767/*static*/ DECLCALLBACK(int)
10768Console::i_pdmIfSecKey_PasswordRelease(PPDMISECKEY pInterface, const char *pszId)
10769{
10770 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
10771
10772 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
10773 return pConsole->m_pKeyStore->releaseSecretKey(Utf8Str(pszId));
10774}
10775
10776/**
10777 * @interface_method_impl{PDMISECKEYHLP,pfnKeyMissingNotify}
10778 */
10779/*static*/ DECLCALLBACK(int)
10780Console::i_pdmIfSecKeyHlp_KeyMissingNotify(PPDMISECKEYHLP pInterface)
10781{
10782 Console *pConsole = ((MYPDMISECKEYHLP *)pInterface)->pConsole;
10783
10784 /* Set guest property only, the VM is paused in the media driver calling us. */
10785 pConsole->mMachine->DeleteGuestProperty(Bstr("/VirtualBox/HostInfo/DekMissing").raw());
10786 pConsole->mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/DekMissing").raw(),
10787 Bstr("1").raw(), Bstr("RDONLYGUEST").raw());
10788 pConsole->mMachine->SaveSettings();
10789
10790 return VINF_SUCCESS;
10791}
10792
10793
10794
10795/**
10796 * The Main status driver instance data.
10797 */
10798typedef struct DRVMAINSTATUS
10799{
10800 /** The LED connectors. */
10801 PDMILEDCONNECTORS ILedConnectors;
10802 /** Pointer to the LED ports interface above us. */
10803 PPDMILEDPORTS pLedPorts;
10804 /** Pointer to the array of LED pointers. */
10805 PPDMLED *papLeds;
10806 /** The unit number corresponding to the first entry in the LED array. */
10807 RTUINT iFirstLUN;
10808 /** The unit number corresponding to the last entry in the LED array.
10809 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
10810 RTUINT iLastLUN;
10811 /** Pointer to the driver instance. */
10812 PPDMDRVINS pDrvIns;
10813 /** The Media Notify interface. */
10814 PDMIMEDIANOTIFY IMediaNotify;
10815 /** Map for translating PDM storage controller/LUN information to
10816 * IMediumAttachment references. */
10817 Console::MediumAttachmentMap *pmapMediumAttachments;
10818 /** Device name+instance for mapping */
10819 char *pszDeviceInstance;
10820 /** Pointer to the Console object, for driver triggered activities. */
10821 Console *pConsole;
10822} DRVMAINSTATUS, *PDRVMAINSTATUS;
10823
10824
10825/**
10826 * Notification about a unit which have been changed.
10827 *
10828 * The driver must discard any pointers to data owned by
10829 * the unit and requery it.
10830 *
10831 * @param pInterface Pointer to the interface structure containing the called function pointer.
10832 * @param iLUN The unit number.
10833 */
10834DECLCALLBACK(void) Console::i_drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
10835{
10836 PDRVMAINSTATUS pThis = RT_FROM_MEMBER(pInterface, DRVMAINSTATUS, ILedConnectors);
10837 if (iLUN >= pThis->iFirstLUN && iLUN <= pThis->iLastLUN)
10838 {
10839 PPDMLED pLed;
10840 int rc = pThis->pLedPorts->pfnQueryStatusLed(pThis->pLedPorts, iLUN, &pLed);
10841 if (RT_FAILURE(rc))
10842 pLed = NULL;
10843 ASMAtomicWritePtr(&pThis->papLeds[iLUN - pThis->iFirstLUN], pLed);
10844 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
10845 }
10846}
10847
10848
10849/**
10850 * Notification about a medium eject.
10851 *
10852 * @returns VBox status code.
10853 * @param pInterface Pointer to the interface structure containing the called function pointer.
10854 * @param uLUN The unit number.
10855 */
10856DECLCALLBACK(int) Console::i_drvStatus_MediumEjected(PPDMIMEDIANOTIFY pInterface, unsigned uLUN)
10857{
10858 PDRVMAINSTATUS pThis = RT_FROM_MEMBER(pInterface, DRVMAINSTATUS, IMediaNotify);
10859 LogFunc(("uLUN=%d\n", uLUN));
10860 if (pThis->pmapMediumAttachments)
10861 {
10862 AutoWriteLock alock(pThis->pConsole COMMA_LOCKVAL_SRC_POS);
10863
10864 ComPtr<IMediumAttachment> pMediumAtt;
10865 Utf8Str devicePath = Utf8StrFmt("%s/LUN#%u", pThis->pszDeviceInstance, uLUN);
10866 Console::MediumAttachmentMap::const_iterator end = pThis->pmapMediumAttachments->end();
10867 Console::MediumAttachmentMap::const_iterator it = pThis->pmapMediumAttachments->find(devicePath);
10868 if (it != end)
10869 pMediumAtt = it->second;
10870 Assert(!pMediumAtt.isNull());
10871 if (!pMediumAtt.isNull())
10872 {
10873 IMedium *pMedium = NULL;
10874 HRESULT rc = pMediumAtt->COMGETTER(Medium)(&pMedium);
10875 AssertComRC(rc);
10876 if (SUCCEEDED(rc) && pMedium)
10877 {
10878 BOOL fHostDrive = FALSE;
10879 rc = pMedium->COMGETTER(HostDrive)(&fHostDrive);
10880 AssertComRC(rc);
10881 if (!fHostDrive)
10882 {
10883 alock.release();
10884
10885 ComPtr<IMediumAttachment> pNewMediumAtt;
10886 rc = pThis->pConsole->mControl->EjectMedium(pMediumAtt, pNewMediumAtt.asOutParam());
10887 if (SUCCEEDED(rc))
10888 {
10889 pThis->pConsole->mMachine->SaveSettings();
10890 fireMediumChangedEvent(pThis->pConsole->mEventSource, pNewMediumAtt);
10891 }
10892
10893 alock.acquire();
10894 if (pNewMediumAtt != pMediumAtt)
10895 {
10896 pThis->pmapMediumAttachments->erase(devicePath);
10897 pThis->pmapMediumAttachments->insert(std::make_pair(devicePath, pNewMediumAtt));
10898 }
10899 }
10900 }
10901 }
10902 }
10903 return VINF_SUCCESS;
10904}
10905
10906
10907/**
10908 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
10909 */
10910DECLCALLBACK(void *) Console::i_drvStatus_QueryInterface(PPDMIBASE pInterface, const char *pszIID)
10911{
10912 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
10913 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10914 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
10915 PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDCONNECTORS, &pThis->ILedConnectors);
10916 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIANOTIFY, &pThis->IMediaNotify);
10917 return NULL;
10918}
10919
10920
10921/**
10922 * Destruct a status driver instance.
10923 *
10924 * @returns VBox status code.
10925 * @param pDrvIns The driver instance data.
10926 */
10927DECLCALLBACK(void) Console::i_drvStatus_Destruct(PPDMDRVINS pDrvIns)
10928{
10929 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
10930 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10931 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
10932
10933 if (pThis->papLeds)
10934 {
10935 unsigned iLed = pThis->iLastLUN - pThis->iFirstLUN + 1;
10936 while (iLed-- > 0)
10937 ASMAtomicWriteNullPtr(&pThis->papLeds[iLed]);
10938 }
10939}
10940
10941
10942/**
10943 * Construct a status driver instance.
10944 *
10945 * @copydoc FNPDMDRVCONSTRUCT
10946 */
10947DECLCALLBACK(int) Console::i_drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
10948{
10949 RT_NOREF(fFlags);
10950 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
10951 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10952 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
10953
10954 /*
10955 * Validate configuration.
10956 */
10957 if (!CFGMR3AreValuesValid(pCfg, "papLeds\0pmapMediumAttachments\0DeviceInstance\0pConsole\0First\0Last\0"))
10958 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
10959 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
10960 ("Configuration error: Not possible to attach anything to this driver!\n"),
10961 VERR_PDM_DRVINS_NO_ATTACH);
10962
10963 /*
10964 * Data.
10965 */
10966 pDrvIns->IBase.pfnQueryInterface = Console::i_drvStatus_QueryInterface;
10967 pThis->ILedConnectors.pfnUnitChanged = Console::i_drvStatus_UnitChanged;
10968 pThis->IMediaNotify.pfnEjected = Console::i_drvStatus_MediumEjected;
10969 pThis->pDrvIns = pDrvIns;
10970 pThis->pszDeviceInstance = NULL;
10971
10972 /*
10973 * Read config.
10974 */
10975 int rc = CFGMR3QueryPtr(pCfg, "papLeds", (void **)&pThis->papLeds);
10976 if (RT_FAILURE(rc))
10977 {
10978 AssertMsgFailed(("Configuration error: Failed to query the \"papLeds\" value! rc=%Rrc\n", rc));
10979 return rc;
10980 }
10981
10982 rc = CFGMR3QueryPtrDef(pCfg, "pmapMediumAttachments", (void **)&pThis->pmapMediumAttachments, NULL);
10983 if (RT_FAILURE(rc))
10984 {
10985 AssertMsgFailed(("Configuration error: Failed to query the \"pmapMediumAttachments\" value! rc=%Rrc\n", rc));
10986 return rc;
10987 }
10988 if (pThis->pmapMediumAttachments)
10989 {
10990 rc = CFGMR3QueryStringAlloc(pCfg, "DeviceInstance", &pThis->pszDeviceInstance);
10991 if (RT_FAILURE(rc))
10992 {
10993 AssertMsgFailed(("Configuration error: Failed to query the \"DeviceInstance\" value! rc=%Rrc\n", rc));
10994 return rc;
10995 }
10996 rc = CFGMR3QueryPtr(pCfg, "pConsole", (void **)&pThis->pConsole);
10997 if (RT_FAILURE(rc))
10998 {
10999 AssertMsgFailed(("Configuration error: Failed to query the \"pConsole\" value! rc=%Rrc\n", rc));
11000 return rc;
11001 }
11002 }
11003
11004 rc = CFGMR3QueryU32(pCfg, "First", &pThis->iFirstLUN);
11005 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
11006 pThis->iFirstLUN = 0;
11007 else if (RT_FAILURE(rc))
11008 {
11009 AssertMsgFailed(("Configuration error: Failed to query the \"First\" value! rc=%Rrc\n", rc));
11010 return rc;
11011 }
11012
11013 rc = CFGMR3QueryU32(pCfg, "Last", &pThis->iLastLUN);
11014 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
11015 pThis->iLastLUN = 0;
11016 else if (RT_FAILURE(rc))
11017 {
11018 AssertMsgFailed(("Configuration error: Failed to query the \"Last\" value! rc=%Rrc\n", rc));
11019 return rc;
11020 }
11021 if (pThis->iFirstLUN > pThis->iLastLUN)
11022 {
11023 AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pThis->iFirstLUN, pThis->iLastLUN));
11024 return VERR_GENERAL_FAILURE;
11025 }
11026
11027 /*
11028 * Get the ILedPorts interface of the above driver/device and
11029 * query the LEDs we want.
11030 */
11031 pThis->pLedPorts = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMILEDPORTS);
11032 AssertMsgReturn(pThis->pLedPorts, ("Configuration error: No led ports interface above!\n"),
11033 VERR_PDM_MISSING_INTERFACE_ABOVE);
11034
11035 for (unsigned i = pThis->iFirstLUN; i <= pThis->iLastLUN; ++i)
11036 Console::i_drvStatus_UnitChanged(&pThis->ILedConnectors, i);
11037
11038 return VINF_SUCCESS;
11039}
11040
11041
11042/**
11043 * Console status driver (LED) registration record.
11044 */
11045const PDMDRVREG Console::DrvStatusReg =
11046{
11047 /* u32Version */
11048 PDM_DRVREG_VERSION,
11049 /* szName */
11050 "MainStatus",
11051 /* szRCMod */
11052 "",
11053 /* szR0Mod */
11054 "",
11055 /* pszDescription */
11056 "Main status driver (Main as in the API).",
11057 /* fFlags */
11058 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
11059 /* fClass. */
11060 PDM_DRVREG_CLASS_STATUS,
11061 /* cMaxInstances */
11062 ~0U,
11063 /* cbInstance */
11064 sizeof(DRVMAINSTATUS),
11065 /* pfnConstruct */
11066 Console::i_drvStatus_Construct,
11067 /* pfnDestruct */
11068 Console::i_drvStatus_Destruct,
11069 /* pfnRelocate */
11070 NULL,
11071 /* pfnIOCtl */
11072 NULL,
11073 /* pfnPowerOn */
11074 NULL,
11075 /* pfnReset */
11076 NULL,
11077 /* pfnSuspend */
11078 NULL,
11079 /* pfnResume */
11080 NULL,
11081 /* pfnAttach */
11082 NULL,
11083 /* pfnDetach */
11084 NULL,
11085 /* pfnPowerOff */
11086 NULL,
11087 /* pfnSoftReset */
11088 NULL,
11089 /* u32EndVersion */
11090 PDM_DRVREG_VERSION
11091};
11092
11093
11094
11095/* 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