VirtualBox

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

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

Main/Progress: Split into safe public interface and a private one which is used purely by API implementation code (for updating). Needed quite a few minor adjustments elsewhere.

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