VirtualBox

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

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

Main/HGCM: Must deregister the 'guestprops' info item before shutting down HGCM, otherwise we risk calling into freed DLL memory should a guru happen later in the VM destruction/whatever process.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 359.5 KB
Line 
1/* $Id: ConsoleImpl.cpp 75167 2018-10-29 21:03:40Z 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 {
5634 vrc = mAudioVideoRec->applyConfiguration(pDisplay->i_videoRecGetConfig());
5635 if (RT_SUCCESS(vrc))
5636 vrc = mAudioVideoRec->doAttachDriverViaEmt(mpUVM, pAutoLock);
5637 }
5638# endif
5639 if ( RT_SUCCESS(vrc)
5640 && pDisplay->i_videoRecGetFeatures()) /* Any video recording (audio and/or video) feature enabled? */
5641 {
5642 vrc = pDisplay->i_videoRecStart();
5643 }
5644 }
5645 else
5646 {
5647 mDisplay->i_videoRecStop();
5648# ifdef VBOX_WITH_AUDIO_VIDEOREC
5649 mAudioVideoRec->doDetachDriverViaEmt(mpUVM, pAutoLock);
5650# endif
5651 }
5652
5653 if (RT_FAILURE(vrc))
5654 LogRel(("VideoRec: %s failed with %Rrc\n", fEnable ? "Enabling" : "Disabling", vrc));
5655 }
5656 else /* Should not happen. */
5657 vrc = VERR_NO_CHANGE;
5658 }
5659
5660 return vrc;
5661}
5662#endif /* VBOX_WITH_VIDEOREC */
5663
5664HRESULT Console::i_onVideoCaptureChange()
5665{
5666 AutoCaller autoCaller(this);
5667 AssertComRCReturnRC(autoCaller.rc());
5668
5669 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5670
5671 HRESULT rc = S_OK;
5672#ifdef VBOX_WITH_VIDEOREC
5673 /* Don't trigger video capture changes if the VM isn't running. */
5674 SafeVMPtrQuiet ptrVM(this);
5675 if (ptrVM.isOk())
5676 {
5677 BOOL fEnabled;
5678 rc = mMachine->COMGETTER(VideoCaptureEnabled)(&fEnabled);
5679 AssertComRCReturnRC(rc);
5680
5681 int vrc = i_videoCaptureEnable(fEnabled, &alock);
5682 if (RT_SUCCESS(vrc))
5683 {
5684 alock.release();
5685 fireVideoCaptureChangedEvent(mEventSource);
5686 }
5687
5688 ptrVM.release();
5689 }
5690#endif /* VBOX_WITH_VIDEOREC */
5691
5692 return rc;
5693}
5694
5695/**
5696 * Called by IInternalSessionControl::OnUSBControllerChange().
5697 */
5698HRESULT Console::i_onUSBControllerChange()
5699{
5700 LogFlowThisFunc(("\n"));
5701
5702 AutoCaller autoCaller(this);
5703 AssertComRCReturnRC(autoCaller.rc());
5704
5705 fireUSBControllerChangedEvent(mEventSource);
5706
5707 return S_OK;
5708}
5709
5710/**
5711 * Called by IInternalSessionControl::OnSharedFolderChange().
5712 *
5713 * @note Locks this object for writing.
5714 */
5715HRESULT Console::i_onSharedFolderChange(BOOL aGlobal)
5716{
5717 LogFlowThisFunc(("aGlobal=%RTbool\n", aGlobal));
5718
5719 AutoCaller autoCaller(this);
5720 AssertComRCReturnRC(autoCaller.rc());
5721
5722 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5723
5724 HRESULT rc = i_fetchSharedFolders(aGlobal);
5725
5726 /* notify console callbacks on success */
5727 if (SUCCEEDED(rc))
5728 {
5729 alock.release();
5730 fireSharedFolderChangedEvent(mEventSource, aGlobal ? Scope_Global : Scope_Machine);
5731 }
5732
5733 return rc;
5734}
5735
5736/**
5737 * Called by IInternalSessionControl::OnUSBDeviceAttach() or locally by
5738 * processRemoteUSBDevices() after IInternalMachineControl::RunUSBDeviceFilters()
5739 * returns TRUE for a given remote USB device.
5740 *
5741 * @return S_OK if the device was attached to the VM.
5742 * @return failure if not attached.
5743 *
5744 * @param aDevice The device in question.
5745 * @param aError Error information.
5746 * @param aMaskedIfs The interfaces to hide from the guest.
5747 * @param aCaptureFilename File name where to store the USB traffic.
5748 *
5749 * @note Locks this object for writing.
5750 */
5751HRESULT Console::i_onUSBDeviceAttach(IUSBDevice *aDevice, IVirtualBoxErrorInfo *aError, ULONG aMaskedIfs,
5752 const Utf8Str &aCaptureFilename)
5753{
5754#ifdef VBOX_WITH_USB
5755 LogFlowThisFunc(("aDevice=%p aError=%p\n", aDevice, aError));
5756
5757 AutoCaller autoCaller(this);
5758 ComAssertComRCRetRC(autoCaller.rc());
5759
5760 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5761
5762 /* Get the VM pointer (we don't need error info, since it's a callback). */
5763 SafeVMPtrQuiet ptrVM(this);
5764 if (!ptrVM.isOk())
5765 {
5766 /* The VM may be no more operational when this message arrives
5767 * (e.g. it may be Saving or Stopping or just PoweredOff) --
5768 * autoVMCaller.rc() will return a failure in this case. */
5769 LogFlowThisFunc(("Attach request ignored (mMachineState=%d).\n",
5770 mMachineState));
5771 return ptrVM.rc();
5772 }
5773
5774 if (aError != NULL)
5775 {
5776 /* notify callbacks about the error */
5777 alock.release();
5778 i_onUSBDeviceStateChange(aDevice, true /* aAttached */, aError);
5779 return S_OK;
5780 }
5781
5782 /* Don't proceed unless there's at least one USB hub. */
5783 if (!PDMR3UsbHasHub(ptrVM.rawUVM()))
5784 {
5785 LogFlowThisFunc(("Attach request ignored (no USB controller).\n"));
5786 return E_FAIL;
5787 }
5788
5789 alock.release();
5790 HRESULT rc = i_attachUSBDevice(aDevice, aMaskedIfs, aCaptureFilename);
5791 if (FAILED(rc))
5792 {
5793 /* take the current error info */
5794 com::ErrorInfoKeeper eik;
5795 /* the error must be a VirtualBoxErrorInfo instance */
5796 ComPtr<IVirtualBoxErrorInfo> pError = eik.takeError();
5797 Assert(!pError.isNull());
5798 if (!pError.isNull())
5799 {
5800 /* notify callbacks about the error */
5801 i_onUSBDeviceStateChange(aDevice, true /* aAttached */, pError);
5802 }
5803 }
5804
5805 return rc;
5806
5807#else /* !VBOX_WITH_USB */
5808 return E_FAIL;
5809#endif /* !VBOX_WITH_USB */
5810}
5811
5812/**
5813 * Called by IInternalSessionControl::OnUSBDeviceDetach() and locally by
5814 * processRemoteUSBDevices().
5815 *
5816 * @note Locks this object for writing.
5817 */
5818HRESULT Console::i_onUSBDeviceDetach(IN_BSTR aId,
5819 IVirtualBoxErrorInfo *aError)
5820{
5821#ifdef VBOX_WITH_USB
5822 Guid Uuid(aId);
5823 LogFlowThisFunc(("aId={%RTuuid} aError=%p\n", Uuid.raw(), aError));
5824
5825 AutoCaller autoCaller(this);
5826 AssertComRCReturnRC(autoCaller.rc());
5827
5828 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5829
5830 /* Find the device. */
5831 ComObjPtr<OUSBDevice> pUSBDevice;
5832 USBDeviceList::iterator it = mUSBDevices.begin();
5833 while (it != mUSBDevices.end())
5834 {
5835 LogFlowThisFunc(("it={%RTuuid}\n", (*it)->i_id().raw()));
5836 if ((*it)->i_id() == Uuid)
5837 {
5838 pUSBDevice = *it;
5839 break;
5840 }
5841 ++it;
5842 }
5843
5844
5845 if (pUSBDevice.isNull())
5846 {
5847 LogFlowThisFunc(("USB device not found.\n"));
5848
5849 /* The VM may be no more operational when this message arrives
5850 * (e.g. it may be Saving or Stopping or just PoweredOff). Use
5851 * AutoVMCaller to detect it -- AutoVMCaller::rc() will return a
5852 * failure in this case. */
5853
5854 AutoVMCallerQuiet autoVMCaller(this);
5855 if (FAILED(autoVMCaller.rc()))
5856 {
5857 LogFlowThisFunc(("Detach request ignored (mMachineState=%d).\n",
5858 mMachineState));
5859 return autoVMCaller.rc();
5860 }
5861
5862 /* the device must be in the list otherwise */
5863 AssertFailedReturn(E_FAIL);
5864 }
5865
5866 if (aError != NULL)
5867 {
5868 /* notify callback about an error */
5869 alock.release();
5870 i_onUSBDeviceStateChange(pUSBDevice, false /* aAttached */, aError);
5871 return S_OK;
5872 }
5873
5874 /* Remove the device from the collection, it is re-added below for failures */
5875 mUSBDevices.erase(it);
5876
5877 alock.release();
5878 HRESULT rc = i_detachUSBDevice(pUSBDevice);
5879 if (FAILED(rc))
5880 {
5881 /* Re-add the device to the collection */
5882 alock.acquire();
5883 mUSBDevices.push_back(pUSBDevice);
5884 alock.release();
5885 /* take the current error info */
5886 com::ErrorInfoKeeper eik;
5887 /* the error must be a VirtualBoxErrorInfo instance */
5888 ComPtr<IVirtualBoxErrorInfo> pError = eik.takeError();
5889 Assert(!pError.isNull());
5890 if (!pError.isNull())
5891 {
5892 /* notify callbacks about the error */
5893 i_onUSBDeviceStateChange(pUSBDevice, false /* aAttached */, pError);
5894 }
5895 }
5896
5897 return rc;
5898
5899#else /* !VBOX_WITH_USB */
5900 return E_FAIL;
5901#endif /* !VBOX_WITH_USB */
5902}
5903
5904/**
5905 * Called by IInternalSessionControl::OnBandwidthGroupChange().
5906 *
5907 * @note Locks this object for writing.
5908 */
5909HRESULT Console::i_onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
5910{
5911 LogFlowThisFunc(("\n"));
5912
5913 AutoCaller autoCaller(this);
5914 AssertComRCReturnRC(autoCaller.rc());
5915
5916 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5917
5918 HRESULT rc = S_OK;
5919
5920 /* don't trigger bandwidth group changes if the VM isn't running */
5921 SafeVMPtrQuiet ptrVM(this);
5922 if (ptrVM.isOk())
5923 {
5924 if ( mMachineState == MachineState_Running
5925 || mMachineState == MachineState_Teleporting
5926 || mMachineState == MachineState_LiveSnapshotting
5927 )
5928 {
5929 /* No need to call in the EMT thread. */
5930 Bstr strName;
5931 rc = aBandwidthGroup->COMGETTER(Name)(strName.asOutParam());
5932 if (SUCCEEDED(rc))
5933 {
5934 LONG64 cMax;
5935 rc = aBandwidthGroup->COMGETTER(MaxBytesPerSec)(&cMax);
5936 if (SUCCEEDED(rc))
5937 {
5938 BandwidthGroupType_T enmType;
5939 rc = aBandwidthGroup->COMGETTER(Type)(&enmType);
5940 if (SUCCEEDED(rc))
5941 {
5942 int vrc = VINF_SUCCESS;
5943 if (enmType == BandwidthGroupType_Disk)
5944 vrc = PDMR3AsyncCompletionBwMgrSetMaxForFile(ptrVM.rawUVM(), Utf8Str(strName).c_str(), (uint32_t)cMax);
5945#ifdef VBOX_WITH_NETSHAPER
5946 else if (enmType == BandwidthGroupType_Network)
5947 vrc = PDMR3NsBwGroupSetLimit(ptrVM.rawUVM(), Utf8Str(strName).c_str(), cMax);
5948 else
5949 rc = E_NOTIMPL;
5950#endif
5951 AssertRC(vrc);
5952 }
5953 }
5954 }
5955 }
5956 else
5957 rc = i_setInvalidMachineStateError();
5958 ptrVM.release();
5959 }
5960
5961 /* notify console callbacks on success */
5962 if (SUCCEEDED(rc))
5963 {
5964 alock.release();
5965 fireBandwidthGroupChangedEvent(mEventSource, aBandwidthGroup);
5966 }
5967
5968 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
5969 return rc;
5970}
5971
5972/**
5973 * Called by IInternalSessionControl::OnStorageDeviceChange().
5974 *
5975 * @note Locks this object for writing.
5976 */
5977HRESULT Console::i_onStorageDeviceChange(IMediumAttachment *aMediumAttachment, BOOL aRemove, BOOL aSilent)
5978{
5979 LogFlowThisFunc(("\n"));
5980
5981 AutoCaller autoCaller(this);
5982 AssertComRCReturnRC(autoCaller.rc());
5983
5984 HRESULT rc = S_OK;
5985
5986 /* don't trigger medium changes if the VM isn't running */
5987 SafeVMPtrQuiet ptrVM(this);
5988 if (ptrVM.isOk())
5989 {
5990 if (aRemove)
5991 rc = i_doStorageDeviceDetach(aMediumAttachment, ptrVM.rawUVM(), RT_BOOL(aSilent));
5992 else
5993 rc = i_doStorageDeviceAttach(aMediumAttachment, ptrVM.rawUVM(), RT_BOOL(aSilent));
5994 ptrVM.release();
5995 }
5996
5997 /* notify console callbacks on success */
5998 if (SUCCEEDED(rc))
5999 fireStorageDeviceChangedEvent(mEventSource, aMediumAttachment, aRemove, aSilent);
6000
6001 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
6002 return rc;
6003}
6004
6005HRESULT Console::i_onExtraDataChange(IN_BSTR aMachineId, IN_BSTR aKey, IN_BSTR aVal)
6006{
6007 LogFlowThisFunc(("\n"));
6008
6009 AutoCaller autoCaller(this);
6010 if (FAILED(autoCaller.rc()))
6011 return autoCaller.rc();
6012
6013 if (!aMachineId)
6014 return S_OK;
6015
6016 HRESULT hrc = S_OK;
6017 Bstr idMachine(aMachineId);
6018 if ( FAILED(hrc)
6019 || idMachine != i_getId())
6020 return hrc;
6021
6022 /* don't do anything if the VM isn't running */
6023 SafeVMPtrQuiet ptrVM(this);
6024 if (ptrVM.isOk())
6025 {
6026 Bstr strKey(aKey);
6027 Bstr strVal(aVal);
6028
6029 if (strKey == "VBoxInternal2/TurnResetIntoPowerOff")
6030 {
6031 int vrc = VMR3SetPowerOffInsteadOfReset(ptrVM.rawUVM(), strVal == "1");
6032 AssertRC(vrc);
6033 }
6034
6035 ptrVM.release();
6036 }
6037
6038 /* notify console callbacks on success */
6039 if (SUCCEEDED(hrc))
6040 fireExtraDataChangedEvent(mEventSource, aMachineId, aKey, aVal);
6041
6042 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
6043 return hrc;
6044}
6045
6046/**
6047 * @note Temporarily locks this object for writing.
6048 */
6049HRESULT Console::i_getGuestProperty(const Utf8Str &aName, Utf8Str *aValue, LONG64 *aTimestamp, Utf8Str *aFlags)
6050{
6051#ifndef VBOX_WITH_GUEST_PROPS
6052 ReturnComNotImplemented();
6053#else /* VBOX_WITH_GUEST_PROPS */
6054 if (!RT_VALID_PTR(aValue))
6055 return E_POINTER;
6056 if (aTimestamp != NULL && !RT_VALID_PTR(aTimestamp))
6057 return E_POINTER;
6058 if (aFlags != NULL && !RT_VALID_PTR(aFlags))
6059 return E_POINTER;
6060
6061 AutoCaller autoCaller(this);
6062 AssertComRCReturnRC(autoCaller.rc());
6063
6064 /* protect mpUVM (if not NULL) */
6065 SafeVMPtrQuiet ptrVM(this);
6066 if (FAILED(ptrVM.rc()))
6067 return ptrVM.rc();
6068
6069 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
6070 * ptrVM, so there is no need to hold a lock of this */
6071
6072 HRESULT rc = E_UNEXPECTED;
6073 try
6074 {
6075 VBOXHGCMSVCPARM parm[4];
6076 char szBuffer[GUEST_PROP_MAX_VALUE_LEN + GUEST_PROP_MAX_FLAGS_LEN];
6077
6078 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
6079 parm[0].u.pointer.addr = (void*)aName.c_str();
6080 parm[0].u.pointer.size = (uint32_t)aName.length() + 1; /* The + 1 is the null terminator */
6081
6082 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
6083 parm[1].u.pointer.addr = szBuffer;
6084 parm[1].u.pointer.size = sizeof(szBuffer);
6085
6086 parm[2].type = VBOX_HGCM_SVC_PARM_64BIT;
6087 parm[2].u.uint64 = 0;
6088
6089 parm[3].type = VBOX_HGCM_SVC_PARM_32BIT;
6090 parm[3].u.uint32 = 0;
6091
6092 int vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GUEST_PROP_FN_HOST_GET_PROP,
6093 4, &parm[0]);
6094 /* The returned string should never be able to be greater than our buffer */
6095 AssertLogRel(vrc != VERR_BUFFER_OVERFLOW);
6096 AssertLogRel(RT_FAILURE(vrc) || parm[2].type == VBOX_HGCM_SVC_PARM_64BIT);
6097 if (RT_SUCCESS(vrc))
6098 {
6099 *aValue = szBuffer;
6100
6101 if (aTimestamp)
6102 *aTimestamp = parm[2].u.uint64;
6103
6104 if (aFlags)
6105 *aFlags = &szBuffer[strlen(szBuffer) + 1];
6106
6107 rc = S_OK;
6108 }
6109 else if (vrc == VERR_NOT_FOUND)
6110 {
6111 *aValue = "";
6112 rc = S_OK;
6113 }
6114 else
6115 rc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("The VBoxGuestPropSvc service call failed with the error %Rrc"), vrc);
6116 }
6117 catch(std::bad_alloc & /*e*/)
6118 {
6119 rc = E_OUTOFMEMORY;
6120 }
6121
6122 return rc;
6123#endif /* VBOX_WITH_GUEST_PROPS */
6124}
6125
6126/**
6127 * @note Temporarily locks this object for writing.
6128 */
6129HRESULT Console::i_setGuestProperty(const Utf8Str &aName, const Utf8Str &aValue, const Utf8Str &aFlags)
6130{
6131#ifndef VBOX_WITH_GUEST_PROPS
6132 ReturnComNotImplemented();
6133#else /* VBOX_WITH_GUEST_PROPS */
6134
6135 AutoCaller autoCaller(this);
6136 AssertComRCReturnRC(autoCaller.rc());
6137
6138 /* protect mpUVM (if not NULL) */
6139 SafeVMPtrQuiet ptrVM(this);
6140 if (FAILED(ptrVM.rc()))
6141 return ptrVM.rc();
6142
6143 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
6144 * ptrVM, so there is no need to hold a lock of this */
6145
6146 VBOXHGCMSVCPARM parm[3];
6147
6148 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
6149 parm[0].u.pointer.addr = (void*)aName.c_str();
6150 parm[0].u.pointer.size = (uint32_t)aName.length() + 1; /* The + 1 is the null terminator */
6151
6152 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
6153 parm[1].u.pointer.addr = (void *)aValue.c_str();
6154 parm[1].u.pointer.size = (uint32_t)aValue.length() + 1; /* The + 1 is the null terminator */
6155
6156 int vrc;
6157 if (aFlags.isEmpty())
6158 {
6159 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GUEST_PROP_FN_HOST_SET_PROP_VALUE, 2, &parm[0]);
6160 }
6161 else
6162 {
6163 parm[2].type = VBOX_HGCM_SVC_PARM_PTR;
6164 parm[2].u.pointer.addr = (void*)aFlags.c_str();
6165 parm[2].u.pointer.size = (uint32_t)aFlags.length() + 1; /* The + 1 is the null terminator */
6166
6167 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GUEST_PROP_FN_HOST_SET_PROP, 3, &parm[0]);
6168 }
6169
6170 HRESULT hrc = S_OK;
6171 if (RT_FAILURE(vrc))
6172 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("The VBoxGuestPropSvc service call failed with the error %Rrc"), vrc);
6173 return hrc;
6174#endif /* VBOX_WITH_GUEST_PROPS */
6175}
6176
6177HRESULT Console::i_deleteGuestProperty(const Utf8Str &aName)
6178{
6179#ifndef VBOX_WITH_GUEST_PROPS
6180 ReturnComNotImplemented();
6181#else /* VBOX_WITH_GUEST_PROPS */
6182
6183 AutoCaller autoCaller(this);
6184 AssertComRCReturnRC(autoCaller.rc());
6185
6186 /* protect mpUVM (if not NULL) */
6187 SafeVMPtrQuiet ptrVM(this);
6188 if (FAILED(ptrVM.rc()))
6189 return ptrVM.rc();
6190
6191 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
6192 * ptrVM, so there is no need to hold a lock of this */
6193
6194 VBOXHGCMSVCPARM parm[1];
6195 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
6196 parm[0].u.pointer.addr = (void*)aName.c_str();
6197 parm[0].u.pointer.size = (uint32_t)aName.length() + 1; /* The + 1 is the null terminator */
6198
6199 int vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GUEST_PROP_FN_HOST_DEL_PROP, 1, &parm[0]);
6200
6201 HRESULT hrc = S_OK;
6202 if (RT_FAILURE(vrc))
6203 hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("The VBoxGuestPropSvc service call failed with the error %Rrc"), vrc);
6204 return hrc;
6205#endif /* VBOX_WITH_GUEST_PROPS */
6206}
6207
6208/**
6209 * @note Temporarily locks this object for writing.
6210 */
6211HRESULT Console::i_enumerateGuestProperties(const Utf8Str &aPatterns,
6212 std::vector<Utf8Str> &aNames,
6213 std::vector<Utf8Str> &aValues,
6214 std::vector<LONG64> &aTimestamps,
6215 std::vector<Utf8Str> &aFlags)
6216{
6217#ifndef VBOX_WITH_GUEST_PROPS
6218 ReturnComNotImplemented();
6219#else /* VBOX_WITH_GUEST_PROPS */
6220
6221 AutoCaller autoCaller(this);
6222 AssertComRCReturnRC(autoCaller.rc());
6223
6224 /* protect mpUVM (if not NULL) */
6225 AutoVMCallerWeak autoVMCaller(this);
6226 if (FAILED(autoVMCaller.rc()))
6227 return autoVMCaller.rc();
6228
6229 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
6230 * autoVMCaller, so there is no need to hold a lock of this */
6231
6232 return i_doEnumerateGuestProperties(aPatterns, aNames, aValues, aTimestamps, aFlags);
6233#endif /* VBOX_WITH_GUEST_PROPS */
6234}
6235
6236
6237/*
6238 * Internal: helper function for connecting progress reporting
6239 */
6240static DECLCALLBACK(int) onlineMergeMediumProgress(void *pvUser, unsigned uPercentage)
6241{
6242 HRESULT rc = S_OK;
6243 IProgress *pProgress = static_cast<IProgress *>(pvUser);
6244 if (pProgress)
6245 {
6246 ComPtr<IInternalProgressControl> pProgressControl(pProgress);
6247 AssertReturn(!!pProgressControl, VERR_INVALID_PARAMETER);
6248 rc = pProgressControl->SetCurrentOperationProgress(uPercentage);
6249 }
6250 return SUCCEEDED(rc) ? VINF_SUCCESS : VERR_GENERAL_FAILURE;
6251}
6252
6253/**
6254 * @note Temporarily locks this object for writing. bird: And/or reading?
6255 */
6256HRESULT Console::i_onlineMergeMedium(IMediumAttachment *aMediumAttachment,
6257 ULONG aSourceIdx, ULONG aTargetIdx,
6258 IProgress *aProgress)
6259{
6260 AutoCaller autoCaller(this);
6261 AssertComRCReturnRC(autoCaller.rc());
6262
6263 HRESULT rc = S_OK;
6264 int vrc = VINF_SUCCESS;
6265
6266 /* Get the VM - must be done before the read-locking. */
6267 SafeVMPtr ptrVM(this);
6268 if (!ptrVM.isOk())
6269 return ptrVM.rc();
6270
6271 /* We will need to release the lock before doing the actual merge */
6272 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6273
6274 /* paranoia - we don't want merges to happen while teleporting etc. */
6275 switch (mMachineState)
6276 {
6277 case MachineState_DeletingSnapshotOnline:
6278 case MachineState_DeletingSnapshotPaused:
6279 break;
6280
6281 default:
6282 return i_setInvalidMachineStateError();
6283 }
6284
6285 /** @todo AssertComRC -> AssertComRCReturn! Could potentially end up
6286 * using uninitialized variables here. */
6287 BOOL fBuiltinIOCache;
6288 rc = mMachine->COMGETTER(IOCacheEnabled)(&fBuiltinIOCache);
6289 AssertComRC(rc);
6290 SafeIfaceArray<IStorageController> ctrls;
6291 rc = mMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));
6292 AssertComRC(rc);
6293 LONG lDev;
6294 rc = aMediumAttachment->COMGETTER(Device)(&lDev);
6295 AssertComRC(rc);
6296 LONG lPort;
6297 rc = aMediumAttachment->COMGETTER(Port)(&lPort);
6298 AssertComRC(rc);
6299 IMedium *pMedium;
6300 rc = aMediumAttachment->COMGETTER(Medium)(&pMedium);
6301 AssertComRC(rc);
6302 Bstr mediumLocation;
6303 if (pMedium)
6304 {
6305 rc = pMedium->COMGETTER(Location)(mediumLocation.asOutParam());
6306 AssertComRC(rc);
6307 }
6308
6309 Bstr attCtrlName;
6310 rc = aMediumAttachment->COMGETTER(Controller)(attCtrlName.asOutParam());
6311 AssertComRC(rc);
6312 ComPtr<IStorageController> pStorageController;
6313 for (size_t i = 0; i < ctrls.size(); ++i)
6314 {
6315 Bstr ctrlName;
6316 rc = ctrls[i]->COMGETTER(Name)(ctrlName.asOutParam());
6317 AssertComRC(rc);
6318 if (attCtrlName == ctrlName)
6319 {
6320 pStorageController = ctrls[i];
6321 break;
6322 }
6323 }
6324 if (pStorageController.isNull())
6325 return setError(E_FAIL,
6326 tr("Could not find storage controller '%ls'"),
6327 attCtrlName.raw());
6328
6329 StorageControllerType_T enmCtrlType;
6330 rc = pStorageController->COMGETTER(ControllerType)(&enmCtrlType);
6331 AssertComRC(rc);
6332 const char *pcszDevice = i_storageControllerTypeToStr(enmCtrlType);
6333
6334 StorageBus_T enmBus;
6335 rc = pStorageController->COMGETTER(Bus)(&enmBus);
6336 AssertComRC(rc);
6337 ULONG uInstance;
6338 rc = pStorageController->COMGETTER(Instance)(&uInstance);
6339 AssertComRC(rc);
6340 BOOL fUseHostIOCache;
6341 rc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
6342 AssertComRC(rc);
6343
6344 unsigned uLUN;
6345 rc = Console::i_storageBusPortDeviceToLun(enmBus, lPort, lDev, uLUN);
6346 AssertComRCReturnRC(rc);
6347
6348 Assert(mMachineState == MachineState_DeletingSnapshotOnline);
6349
6350 /* Pause the VM, as it might have pending IO on this drive */
6351 bool fResume = false;
6352 rc = i_suspendBeforeConfigChange(ptrVM.rawUVM(), &alock, &fResume);
6353 if (FAILED(rc))
6354 return rc;
6355
6356 bool fInsertDiskIntegrityDrv = false;
6357 Bstr strDiskIntegrityFlag;
6358 rc = mMachine->GetExtraData(Bstr("VBoxInternal2/EnableDiskIntegrityDriver").raw(),
6359 strDiskIntegrityFlag.asOutParam());
6360 if ( rc == S_OK
6361 && strDiskIntegrityFlag == "1")
6362 fInsertDiskIntegrityDrv = true;
6363
6364 alock.release();
6365 vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY,
6366 (PFNRT)i_reconfigureMediumAttachment, 14,
6367 this, ptrVM.rawUVM(), pcszDevice, uInstance, enmBus, fUseHostIOCache,
6368 fBuiltinIOCache, fInsertDiskIntegrityDrv, true /* fSetupMerge */,
6369 aSourceIdx, aTargetIdx, aMediumAttachment, mMachineState, &rc);
6370 /* error handling is after resuming the VM */
6371
6372 if (fResume)
6373 i_resumeAfterConfigChange(ptrVM.rawUVM());
6374
6375 if (RT_FAILURE(vrc))
6376 return setErrorBoth(E_FAIL, vrc, tr("%Rrc"), vrc);
6377 if (FAILED(rc))
6378 return rc;
6379
6380 PPDMIBASE pIBase = NULL;
6381 PPDMIMEDIA pIMedium = NULL;
6382 vrc = PDMR3QueryDriverOnLun(ptrVM.rawUVM(), pcszDevice, uInstance, uLUN, "VD", &pIBase);
6383 if (RT_SUCCESS(vrc))
6384 {
6385 if (pIBase)
6386 {
6387 pIMedium = (PPDMIMEDIA)pIBase->pfnQueryInterface(pIBase, PDMIMEDIA_IID);
6388 if (!pIMedium)
6389 return setError(E_FAIL, tr("could not query medium interface of controller"));
6390 }
6391 else
6392 return setError(E_FAIL, tr("could not query base interface of controller"));
6393 }
6394
6395 /* Finally trigger the merge. */
6396 vrc = pIMedium->pfnMerge(pIMedium, onlineMergeMediumProgress, aProgress);
6397 if (RT_FAILURE(vrc))
6398 return setErrorBoth(E_FAIL, vrc, tr("Failed to perform an online medium merge (%Rrc)"), vrc);
6399
6400 alock.acquire();
6401 /* Pause the VM, as it might have pending IO on this drive */
6402 rc = i_suspendBeforeConfigChange(ptrVM.rawUVM(), &alock, &fResume);
6403 if (FAILED(rc))
6404 return rc;
6405 alock.release();
6406
6407 /* Update medium chain and state now, so that the VM can continue. */
6408 rc = mControl->FinishOnlineMergeMedium();
6409
6410 vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY,
6411 (PFNRT)i_reconfigureMediumAttachment, 14,
6412 this, ptrVM.rawUVM(), pcszDevice, uInstance, enmBus, fUseHostIOCache,
6413 fBuiltinIOCache, fInsertDiskIntegrityDrv, false /* fSetupMerge */,
6414 0 /* uMergeSource */, 0 /* uMergeTarget */, aMediumAttachment,
6415 mMachineState, &rc);
6416 /* error handling is after resuming the VM */
6417
6418 if (fResume)
6419 i_resumeAfterConfigChange(ptrVM.rawUVM());
6420
6421 if (RT_FAILURE(vrc))
6422 return setErrorBoth(E_FAIL, vrc, tr("%Rrc"), vrc);
6423 if (FAILED(rc))
6424 return rc;
6425
6426 return rc;
6427}
6428
6429HRESULT Console::i_reconfigureMediumAttachments(const std::vector<ComPtr<IMediumAttachment> > &aAttachments)
6430{
6431 HRESULT rc = S_OK;
6432
6433 AutoCaller autoCaller(this);
6434 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6435
6436 /* get the VM handle. */
6437 SafeVMPtr ptrVM(this);
6438 if (!ptrVM.isOk())
6439 return ptrVM.rc();
6440
6441 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6442
6443 for (size_t i = 0; i < aAttachments.size(); ++i)
6444 {
6445 ComPtr<IStorageController> pStorageController;
6446 Bstr controllerName;
6447 ULONG lInstance;
6448 StorageControllerType_T enmController;
6449 StorageBus_T enmBus;
6450 BOOL fUseHostIOCache;
6451
6452 /*
6453 * We could pass the objects, but then EMT would have to do lots of
6454 * IPC (to VBoxSVC) which takes a significant amount of time.
6455 * Better query needed values here and pass them.
6456 */
6457 rc = aAttachments[i]->COMGETTER(Controller)(controllerName.asOutParam());
6458 if (FAILED(rc))
6459 throw rc;
6460
6461 rc = mMachine->GetStorageControllerByName(controllerName.raw(),
6462 pStorageController.asOutParam());
6463 if (FAILED(rc))
6464 throw rc;
6465
6466 rc = pStorageController->COMGETTER(ControllerType)(&enmController);
6467 if (FAILED(rc))
6468 throw rc;
6469 rc = pStorageController->COMGETTER(Instance)(&lInstance);
6470 if (FAILED(rc))
6471 throw rc;
6472 rc = pStorageController->COMGETTER(Bus)(&enmBus);
6473 if (FAILED(rc))
6474 throw rc;
6475 rc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
6476 if (FAILED(rc))
6477 throw rc;
6478
6479 const char *pcszDevice = i_storageControllerTypeToStr(enmController);
6480
6481 BOOL fBuiltinIOCache;
6482 rc = mMachine->COMGETTER(IOCacheEnabled)(&fBuiltinIOCache);
6483 if (FAILED(rc))
6484 throw rc;
6485
6486 bool fInsertDiskIntegrityDrv = false;
6487 Bstr strDiskIntegrityFlag;
6488 rc = mMachine->GetExtraData(Bstr("VBoxInternal2/EnableDiskIntegrityDriver").raw(),
6489 strDiskIntegrityFlag.asOutParam());
6490 if ( rc == S_OK
6491 && strDiskIntegrityFlag == "1")
6492 fInsertDiskIntegrityDrv = true;
6493
6494 alock.release();
6495
6496 IMediumAttachment *pAttachment = aAttachments[i];
6497 int vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY,
6498 (PFNRT)i_reconfigureMediumAttachment, 14,
6499 this, ptrVM.rawUVM(), pcszDevice, lInstance, enmBus, fUseHostIOCache,
6500 fBuiltinIOCache, fInsertDiskIntegrityDrv,
6501 false /* fSetupMerge */, 0 /* uMergeSource */, 0 /* uMergeTarget */,
6502 pAttachment, mMachineState, &rc);
6503 if (RT_FAILURE(vrc))
6504 throw setErrorBoth(E_FAIL, vrc, tr("%Rrc"), vrc);
6505 if (FAILED(rc))
6506 throw rc;
6507
6508 alock.acquire();
6509 }
6510
6511 return rc;
6512}
6513
6514
6515/**
6516 * Load an HGCM service.
6517 *
6518 * Main purpose of this method is to allow extension packs to load HGCM
6519 * service modules, which they can't, because the HGCM functionality lives
6520 * in module VBoxC (and ConsoleImpl.cpp is part of it and thus can call it).
6521 * Extension modules must not link directly against VBoxC, (XP)COM is
6522 * handling this.
6523 */
6524int Console::i_hgcmLoadService(const char *pszServiceLibrary, const char *pszServiceName)
6525{
6526 /* Everyone seems to delegate all HGCM calls to VMMDev, so stick to this
6527 * convention. Adds one level of indirection for no obvious reason. */
6528 AssertPtrReturn(m_pVMMDev, VERR_INVALID_STATE);
6529 return m_pVMMDev->hgcmLoadService(pszServiceLibrary, pszServiceName);
6530}
6531
6532/**
6533 * Merely passes the call to Guest::enableVMMStatistics().
6534 */
6535void Console::i_enableVMMStatistics(BOOL aEnable)
6536{
6537 if (mGuest)
6538 mGuest->i_enableVMMStatistics(aEnable);
6539}
6540
6541/**
6542 * Worker for Console::Pause and internal entry point for pausing a VM for
6543 * a specific reason.
6544 */
6545HRESULT Console::i_pause(Reason_T aReason)
6546{
6547 LogFlowThisFuncEnter();
6548
6549 AutoCaller autoCaller(this);
6550 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6551
6552 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6553
6554 switch (mMachineState)
6555 {
6556 case MachineState_Running:
6557 case MachineState_Teleporting:
6558 case MachineState_LiveSnapshotting:
6559 break;
6560
6561 case MachineState_Paused:
6562 case MachineState_TeleportingPausedVM:
6563 case MachineState_OnlineSnapshotting:
6564 /* Remove any keys which are supposed to be removed on a suspend. */
6565 if ( aReason == Reason_HostSuspend
6566 || aReason == Reason_HostBatteryLow)
6567 {
6568 i_removeSecretKeysOnSuspend();
6569 return S_OK;
6570 }
6571 return setError(VBOX_E_INVALID_VM_STATE, tr("Already paused"));
6572
6573 default:
6574 return i_setInvalidMachineStateError();
6575 }
6576
6577 /* get the VM handle. */
6578 SafeVMPtr ptrVM(this);
6579 if (!ptrVM.isOk())
6580 return ptrVM.rc();
6581
6582 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
6583 alock.release();
6584
6585 LogFlowThisFunc(("Sending PAUSE request...\n"));
6586 if (aReason != Reason_Unspecified)
6587 LogRel(("Pausing VM execution, reason '%s'\n", Global::stringifyReason(aReason)));
6588
6589 /** @todo r=klaus make use of aReason */
6590 VMSUSPENDREASON enmReason = VMSUSPENDREASON_USER;
6591 if (aReason == Reason_HostSuspend)
6592 enmReason = VMSUSPENDREASON_HOST_SUSPEND;
6593 else if (aReason == Reason_HostBatteryLow)
6594 enmReason = VMSUSPENDREASON_HOST_BATTERY_LOW;
6595 int vrc = VMR3Suspend(ptrVM.rawUVM(), enmReason);
6596
6597 HRESULT hrc = S_OK;
6598 if (RT_FAILURE(vrc))
6599 hrc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not suspend the machine execution (%Rrc)"), vrc);
6600 else if ( aReason == Reason_HostSuspend
6601 || aReason == Reason_HostBatteryLow)
6602 {
6603 alock.acquire();
6604 i_removeSecretKeysOnSuspend();
6605 }
6606
6607 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
6608 LogFlowThisFuncLeave();
6609 return hrc;
6610}
6611
6612/**
6613 * Worker for Console::Resume and internal entry point for resuming a VM for
6614 * a specific reason.
6615 */
6616HRESULT Console::i_resume(Reason_T aReason, AutoWriteLock &alock)
6617{
6618 LogFlowThisFuncEnter();
6619
6620 AutoCaller autoCaller(this);
6621 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6622
6623 /* get the VM handle. */
6624 SafeVMPtr ptrVM(this);
6625 if (!ptrVM.isOk())
6626 return ptrVM.rc();
6627
6628 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
6629 alock.release();
6630
6631 LogFlowThisFunc(("Sending RESUME request...\n"));
6632 if (aReason != Reason_Unspecified)
6633 LogRel(("Resuming VM execution, reason '%s'\n", Global::stringifyReason(aReason)));
6634
6635 int vrc;
6636 if (VMR3GetStateU(ptrVM.rawUVM()) == VMSTATE_CREATED)
6637 {
6638#ifdef VBOX_WITH_EXTPACK
6639 vrc = mptrExtPackManager->i_callAllVmPowerOnHooks(this, VMR3GetVM(ptrVM.rawUVM()));
6640#else
6641 vrc = VINF_SUCCESS;
6642#endif
6643 if (RT_SUCCESS(vrc))
6644 vrc = VMR3PowerOn(ptrVM.rawUVM()); /* (PowerUpPaused) */
6645 }
6646 else
6647 {
6648 VMRESUMEREASON enmReason;
6649 if (aReason == Reason_HostResume)
6650 {
6651 /*
6652 * Host resume may be called multiple times successively. We don't want to VMR3Resume->vmR3Resume->vmR3TrySetState()
6653 * to assert on us, hence check for the VM state here and bail if it's not in the 'suspended' state.
6654 * See @bugref{3495}.
6655 *
6656 * Also, don't resume the VM through a host-resume unless it was suspended due to a host-suspend.
6657 */
6658 if (VMR3GetStateU(ptrVM.rawUVM()) != VMSTATE_SUSPENDED)
6659 {
6660 LogRel(("Ignoring VM resume request, VM is currently not suspended\n"));
6661 return S_OK;
6662 }
6663 if (VMR3GetSuspendReason(ptrVM.rawUVM()) != VMSUSPENDREASON_HOST_SUSPEND)
6664 {
6665 LogRel(("Ignoring VM resume request, VM was not suspended due to host-suspend\n"));
6666 return S_OK;
6667 }
6668
6669 enmReason = VMRESUMEREASON_HOST_RESUME;
6670 }
6671 else
6672 {
6673 /*
6674 * Any other reason to resume the VM throws an error when the VM was suspended due to a host suspend.
6675 * See @bugref{7836}.
6676 */
6677 if ( VMR3GetStateU(ptrVM.rawUVM()) == VMSTATE_SUSPENDED
6678 && VMR3GetSuspendReason(ptrVM.rawUVM()) == VMSUSPENDREASON_HOST_SUSPEND)
6679 return setError(VBOX_E_INVALID_VM_STATE, tr("VM is paused due to host power management"));
6680
6681 enmReason = aReason == Reason_Snapshot ? VMRESUMEREASON_STATE_SAVED : VMRESUMEREASON_USER;
6682 }
6683
6684 // for snapshots: no state change callback, VBoxSVC does everything
6685 if (aReason == Reason_Snapshot)
6686 mVMStateChangeCallbackDisabled = true;
6687 vrc = VMR3Resume(ptrVM.rawUVM(), enmReason);
6688 if (aReason == Reason_Snapshot)
6689 mVMStateChangeCallbackDisabled = false;
6690 }
6691
6692 HRESULT rc = RT_SUCCESS(vrc) ? S_OK
6693 : setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not resume the machine execution (%Rrc)"), vrc);
6694
6695 LogFlowThisFunc(("rc=%Rhrc\n", rc));
6696 LogFlowThisFuncLeave();
6697 return rc;
6698}
6699
6700/**
6701 * Internal entry point for saving state of a VM for a specific reason. This
6702 * method is completely synchronous.
6703 *
6704 * The machine state is already set appropriately. It is only changed when
6705 * saving state actually paused the VM (happens with live snapshots and
6706 * teleportation), and in this case reflects the now paused variant.
6707 *
6708 * @note Locks this object for writing.
6709 */
6710HRESULT Console::i_saveState(Reason_T aReason, const ComPtr<IProgress> &aProgress,
6711 const ComPtr<ISnapshot> &aSnapshot,
6712 const Utf8Str &aStateFilePath, bool aPauseVM, bool &aLeftPaused)
6713{
6714 LogFlowThisFuncEnter();
6715 aLeftPaused = false;
6716
6717 AssertReturn(!aProgress.isNull(), E_INVALIDARG);
6718 AssertReturn(!aStateFilePath.isEmpty(), E_INVALIDARG);
6719 Assert(aSnapshot.isNull() || aReason == Reason_Snapshot);
6720
6721 AutoCaller autoCaller(this);
6722 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6723
6724 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6725
6726 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
6727 if ( mMachineState != MachineState_Saving
6728 && mMachineState != MachineState_LiveSnapshotting
6729 && mMachineState != MachineState_OnlineSnapshotting
6730 && mMachineState != MachineState_Teleporting
6731 && mMachineState != MachineState_TeleportingPausedVM)
6732 {
6733 return setError(VBOX_E_INVALID_VM_STATE,
6734 tr("Cannot save the execution state as the machine is not running or paused (machine state: %s)"),
6735 Global::stringifyMachineState(mMachineState));
6736 }
6737 bool fContinueAfterwards = mMachineState != MachineState_Saving;
6738
6739 Bstr strDisableSaveState;
6740 mMachine->GetExtraData(Bstr("VBoxInternal2/DisableSaveState").raw(), strDisableSaveState.asOutParam());
6741 if (strDisableSaveState == "1")
6742 return setError(VBOX_E_VM_ERROR,
6743 tr("Saving the execution state is disabled for this VM"));
6744
6745 if (aReason != Reason_Unspecified)
6746 LogRel(("Saving state of VM, reason '%s'\n", Global::stringifyReason(aReason)));
6747
6748 /* ensure the directory for the saved state file exists */
6749 {
6750 Utf8Str dir = aStateFilePath;
6751 dir.stripFilename();
6752 if (!RTDirExists(dir.c_str()))
6753 {
6754 int vrc = RTDirCreateFullPath(dir.c_str(), 0700);
6755 if (RT_FAILURE(vrc))
6756 return setErrorBoth(VBOX_E_FILE_ERROR, vrc, tr("Could not create a directory '%s' to save the state to (%Rrc)"),
6757 dir.c_str(), vrc);
6758 }
6759 }
6760
6761 /* Get the VM handle early, we need it in several places. */
6762 SafeVMPtr ptrVM(this);
6763 if (!ptrVM.isOk())
6764 return ptrVM.rc();
6765
6766 bool fPaused = false;
6767 if (aPauseVM)
6768 {
6769 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
6770 alock.release();
6771 VMSUSPENDREASON enmReason = VMSUSPENDREASON_USER;
6772 if (aReason == Reason_HostSuspend)
6773 enmReason = VMSUSPENDREASON_HOST_SUSPEND;
6774 else if (aReason == Reason_HostBatteryLow)
6775 enmReason = VMSUSPENDREASON_HOST_BATTERY_LOW;
6776 int vrc = VMR3Suspend(ptrVM.rawUVM(), enmReason);
6777 alock.acquire();
6778
6779 if (RT_FAILURE(vrc))
6780 return setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not suspend the machine execution (%Rrc)"), vrc);
6781 fPaused = true;
6782 }
6783
6784 LogFlowFunc(("Saving the state to '%s'...\n", aStateFilePath.c_str()));
6785
6786 mpVmm2UserMethods->pISnapshot = aSnapshot;
6787 mptrCancelableProgress = aProgress;
6788 alock.release();
6789 int vrc = VMR3Save(ptrVM.rawUVM(),
6790 aStateFilePath.c_str(),
6791 fContinueAfterwards,
6792 Console::i_stateProgressCallback,
6793 static_cast<IProgress *>(aProgress),
6794 &aLeftPaused);
6795 alock.acquire();
6796 mpVmm2UserMethods->pISnapshot = NULL;
6797 mptrCancelableProgress.setNull();
6798 if (RT_FAILURE(vrc))
6799 {
6800 if (fPaused)
6801 {
6802 alock.release();
6803 VMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_STATE_RESTORED);
6804 alock.acquire();
6805 }
6806 return setErrorBoth(E_FAIL, vrc, tr("Failed to save the machine state to '%s' (%Rrc)"), aStateFilePath.c_str(), vrc);
6807 }
6808 Assert(fContinueAfterwards || !aLeftPaused);
6809
6810 if (!fContinueAfterwards)
6811 {
6812 /*
6813 * The machine has been successfully saved, so power it down
6814 * (vmstateChangeCallback() will set state to Saved on success).
6815 * Note: we release the VM caller, otherwise it will deadlock.
6816 */
6817 ptrVM.release();
6818 alock.release();
6819 autoCaller.release();
6820 HRESULT rc = i_powerDown();
6821 AssertComRC(rc);
6822 autoCaller.add();
6823 alock.acquire();
6824 }
6825 else
6826 {
6827 if (fPaused)
6828 aLeftPaused = true;
6829 }
6830
6831 LogFlowFuncLeave();
6832 return S_OK;
6833}
6834
6835/**
6836 * Internal entry point for cancelling a VM save state.
6837 *
6838 * @note Locks this object for writing.
6839 */
6840HRESULT Console::i_cancelSaveState()
6841{
6842 LogFlowThisFuncEnter();
6843
6844 AutoCaller autoCaller(this);
6845 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6846
6847 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6848
6849 /* Get the VM handle. */
6850 SafeVMPtr ptrVM(this);
6851 if (!ptrVM.isOk())
6852 return ptrVM.rc();
6853
6854 SSMR3Cancel(ptrVM.rawUVM());
6855
6856 LogFlowFuncLeave();
6857 return S_OK;
6858}
6859
6860#ifdef VBOX_WITH_AUDIO_VIDEOREC
6861/**
6862 * Sends audio (frame) data to the display's video capturing routines.
6863 *
6864 * @returns HRESULT
6865 * @param pvData Audio data to send.
6866 * @param cbData Size (in bytes) of audio data to send.
6867 * @param uTimestampMs Timestamp (in ms) of audio data.
6868 */
6869HRESULT Console::i_audioVideoRecSendAudio(const void *pvData, size_t cbData, uint64_t uTimestampMs)
6870{
6871 if (mDisplay)
6872 {
6873 int rc2 = mDisplay->i_videoRecSendAudio(pvData, cbData, uTimestampMs);
6874 AssertRC(rc2);
6875 }
6876
6877 return S_OK;
6878}
6879#endif /* VBOX_WITH_AUDIO_VIDEOREC */
6880
6881/**
6882 * Gets called by Session::UpdateMachineState()
6883 * (IInternalSessionControl::updateMachineState()).
6884 *
6885 * Must be called only in certain cases (see the implementation).
6886 *
6887 * @note Locks this object for writing.
6888 */
6889HRESULT Console::i_updateMachineState(MachineState_T aMachineState)
6890{
6891 AutoCaller autoCaller(this);
6892 AssertComRCReturnRC(autoCaller.rc());
6893
6894 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6895
6896 AssertReturn( mMachineState == MachineState_Saving
6897 || mMachineState == MachineState_OnlineSnapshotting
6898 || mMachineState == MachineState_LiveSnapshotting
6899 || mMachineState == MachineState_DeletingSnapshotOnline
6900 || mMachineState == MachineState_DeletingSnapshotPaused
6901 || aMachineState == MachineState_Saving
6902 || aMachineState == MachineState_OnlineSnapshotting
6903 || aMachineState == MachineState_LiveSnapshotting
6904 || aMachineState == MachineState_DeletingSnapshotOnline
6905 || aMachineState == MachineState_DeletingSnapshotPaused
6906 , E_FAIL);
6907
6908 return i_setMachineStateLocally(aMachineState);
6909}
6910
6911/**
6912 * Gets called by Session::COMGETTER(NominalState)()
6913 * (IInternalSessionControl::getNominalState()).
6914 *
6915 * @note Locks this object for reading.
6916 */
6917HRESULT Console::i_getNominalState(MachineState_T &aNominalState)
6918{
6919 LogFlowThisFuncEnter();
6920
6921 AutoCaller autoCaller(this);
6922 AssertComRCReturnRC(autoCaller.rc());
6923
6924 /* Get the VM handle. */
6925 SafeVMPtr ptrVM(this);
6926 if (!ptrVM.isOk())
6927 return ptrVM.rc();
6928
6929 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6930
6931 MachineState_T enmMachineState = MachineState_Null;
6932 VMSTATE enmVMState = VMR3GetStateU(ptrVM.rawUVM());
6933 switch (enmVMState)
6934 {
6935 case VMSTATE_CREATING:
6936 case VMSTATE_CREATED:
6937 case VMSTATE_POWERING_ON:
6938 enmMachineState = MachineState_Starting;
6939 break;
6940 case VMSTATE_LOADING:
6941 enmMachineState = MachineState_Restoring;
6942 break;
6943 case VMSTATE_RESUMING:
6944 case VMSTATE_SUSPENDING:
6945 case VMSTATE_SUSPENDING_LS:
6946 case VMSTATE_SUSPENDING_EXT_LS:
6947 case VMSTATE_SUSPENDED:
6948 case VMSTATE_SUSPENDED_LS:
6949 case VMSTATE_SUSPENDED_EXT_LS:
6950 enmMachineState = MachineState_Paused;
6951 break;
6952 case VMSTATE_RUNNING:
6953 case VMSTATE_RUNNING_LS:
6954 case VMSTATE_RUNNING_FT:
6955 case VMSTATE_RESETTING:
6956 case VMSTATE_RESETTING_LS:
6957 case VMSTATE_SOFT_RESETTING:
6958 case VMSTATE_SOFT_RESETTING_LS:
6959 case VMSTATE_DEBUGGING:
6960 case VMSTATE_DEBUGGING_LS:
6961 enmMachineState = MachineState_Running;
6962 break;
6963 case VMSTATE_SAVING:
6964 enmMachineState = MachineState_Saving;
6965 break;
6966 case VMSTATE_POWERING_OFF:
6967 case VMSTATE_POWERING_OFF_LS:
6968 case VMSTATE_DESTROYING:
6969 enmMachineState = MachineState_Stopping;
6970 break;
6971 case VMSTATE_OFF:
6972 case VMSTATE_OFF_LS:
6973 case VMSTATE_FATAL_ERROR:
6974 case VMSTATE_FATAL_ERROR_LS:
6975 case VMSTATE_LOAD_FAILURE:
6976 case VMSTATE_TERMINATED:
6977 enmMachineState = MachineState_PoweredOff;
6978 break;
6979 case VMSTATE_GURU_MEDITATION:
6980 case VMSTATE_GURU_MEDITATION_LS:
6981 enmMachineState = MachineState_Stuck;
6982 break;
6983 default:
6984 AssertMsgFailed(("%s\n", VMR3GetStateName(enmVMState)));
6985 enmMachineState = MachineState_PoweredOff;
6986 }
6987 aNominalState = enmMachineState;
6988
6989 LogFlowFuncLeave();
6990 return S_OK;
6991}
6992
6993void Console::i_onMousePointerShapeChange(bool fVisible, bool fAlpha,
6994 uint32_t xHot, uint32_t yHot,
6995 uint32_t width, uint32_t height,
6996 const uint8_t *pu8Shape,
6997 uint32_t cbShape)
6998{
6999#if 0
7000 LogFlowThisFuncEnter();
7001 LogFlowThisFunc(("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, height=%d, shape=%p\n",
7002 fVisible, fAlpha, xHot, yHot, width, height, pShape));
7003#endif
7004
7005 AutoCaller autoCaller(this);
7006 AssertComRCReturnVoid(autoCaller.rc());
7007
7008 if (!mMouse.isNull())
7009 mMouse->updateMousePointerShape(fVisible, fAlpha, xHot, yHot, width, height,
7010 pu8Shape, cbShape);
7011
7012 com::SafeArray<BYTE> shape(cbShape);
7013 if (pu8Shape)
7014 memcpy(shape.raw(), pu8Shape, cbShape);
7015 fireMousePointerShapeChangedEvent(mEventSource, fVisible, fAlpha, xHot, yHot, width, height, ComSafeArrayAsInParam(shape));
7016
7017#if 0
7018 LogFlowThisFuncLeave();
7019#endif
7020}
7021
7022void Console::i_onMouseCapabilityChange(BOOL supportsAbsolute, BOOL supportsRelative,
7023 BOOL supportsMT, BOOL needsHostCursor)
7024{
7025 LogFlowThisFunc(("supportsAbsolute=%d supportsRelative=%d needsHostCursor=%d\n",
7026 supportsAbsolute, supportsRelative, needsHostCursor));
7027
7028 AutoCaller autoCaller(this);
7029 AssertComRCReturnVoid(autoCaller.rc());
7030
7031 fireMouseCapabilityChangedEvent(mEventSource, supportsAbsolute, supportsRelative, supportsMT, needsHostCursor);
7032}
7033
7034void Console::i_onStateChange(MachineState_T machineState)
7035{
7036 AutoCaller autoCaller(this);
7037 AssertComRCReturnVoid(autoCaller.rc());
7038 fireStateChangedEvent(mEventSource, machineState);
7039}
7040
7041void Console::i_onAdditionsStateChange()
7042{
7043 AutoCaller autoCaller(this);
7044 AssertComRCReturnVoid(autoCaller.rc());
7045
7046 fireAdditionsStateChangedEvent(mEventSource);
7047}
7048
7049/**
7050 * @remarks This notification only is for reporting an incompatible
7051 * Guest Additions interface, *not* the Guest Additions version!
7052 *
7053 * The user will be notified inside the guest if new Guest
7054 * Additions are available (via VBoxTray/VBoxClient).
7055 */
7056void Console::i_onAdditionsOutdated()
7057{
7058 AutoCaller autoCaller(this);
7059 AssertComRCReturnVoid(autoCaller.rc());
7060
7061 /** @todo implement this */
7062}
7063
7064void Console::i_onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
7065{
7066 AutoCaller autoCaller(this);
7067 AssertComRCReturnVoid(autoCaller.rc());
7068
7069 fireKeyboardLedsChangedEvent(mEventSource, fNumLock, fCapsLock, fScrollLock);
7070}
7071
7072void Console::i_onUSBDeviceStateChange(IUSBDevice *aDevice, bool aAttached,
7073 IVirtualBoxErrorInfo *aError)
7074{
7075 AutoCaller autoCaller(this);
7076 AssertComRCReturnVoid(autoCaller.rc());
7077
7078 fireUSBDeviceStateChangedEvent(mEventSource, aDevice, aAttached, aError);
7079}
7080
7081void Console::i_onRuntimeError(BOOL aFatal, IN_BSTR aErrorID, IN_BSTR aMessage)
7082{
7083 AutoCaller autoCaller(this);
7084 AssertComRCReturnVoid(autoCaller.rc());
7085
7086 fireRuntimeErrorEvent(mEventSource, aFatal, aErrorID, aMessage);
7087}
7088
7089HRESULT Console::i_onShowWindow(BOOL aCheck, BOOL *aCanShow, LONG64 *aWinId)
7090{
7091 AssertReturn(aCanShow, E_POINTER);
7092 AssertReturn(aWinId, E_POINTER);
7093
7094 *aCanShow = FALSE;
7095 *aWinId = 0;
7096
7097 AutoCaller autoCaller(this);
7098 AssertComRCReturnRC(autoCaller.rc());
7099
7100 VBoxEventDesc evDesc;
7101 if (aCheck)
7102 {
7103 evDesc.init(mEventSource, VBoxEventType_OnCanShowWindow);
7104 BOOL fDelivered = evDesc.fire(5000); /* Wait up to 5 secs for delivery */
7105 //Assert(fDelivered);
7106 if (fDelivered)
7107 {
7108 ComPtr<IEvent> pEvent;
7109 evDesc.getEvent(pEvent.asOutParam());
7110 // bit clumsy
7111 ComPtr<ICanShowWindowEvent> pCanShowEvent = pEvent;
7112 if (pCanShowEvent)
7113 {
7114 BOOL fVetoed = FALSE;
7115 BOOL fApproved = FALSE;
7116 pCanShowEvent->IsVetoed(&fVetoed);
7117 pCanShowEvent->IsApproved(&fApproved);
7118 *aCanShow = fApproved || !fVetoed;
7119 }
7120 else
7121 {
7122 AssertFailed();
7123 *aCanShow = TRUE;
7124 }
7125 }
7126 else
7127 *aCanShow = TRUE;
7128 }
7129 else
7130 {
7131 evDesc.init(mEventSource, VBoxEventType_OnShowWindow, INT64_C(0));
7132 BOOL fDelivered = evDesc.fire(5000); /* Wait up to 5 secs for delivery */
7133 //Assert(fDelivered);
7134 if (fDelivered)
7135 {
7136 ComPtr<IEvent> pEvent;
7137 evDesc.getEvent(pEvent.asOutParam());
7138 ComPtr<IShowWindowEvent> pShowEvent = pEvent;
7139 if (pShowEvent)
7140 {
7141 LONG64 iEvWinId = 0;
7142 pShowEvent->COMGETTER(WinId)(&iEvWinId);
7143 if (iEvWinId != 0 && *aWinId == 0)
7144 *aWinId = iEvWinId;
7145 }
7146 else
7147 AssertFailed();
7148 }
7149 }
7150
7151 return S_OK;
7152}
7153
7154// private methods
7155////////////////////////////////////////////////////////////////////////////////
7156
7157/**
7158 * Increases the usage counter of the mpUVM pointer.
7159 *
7160 * Guarantees that VMR3Destroy() will not be called on it at least until
7161 * releaseVMCaller() is called.
7162 *
7163 * If this method returns a failure, the caller is not allowed to use mpUVM and
7164 * may return the failed result code to the upper level. This method sets the
7165 * extended error info on failure if \a aQuiet is false.
7166 *
7167 * Setting \a aQuiet to true is useful for methods that don't want to return
7168 * the failed result code to the caller when this method fails (e.g. need to
7169 * silently check for the mpUVM availability).
7170 *
7171 * When mpUVM is NULL but \a aAllowNullVM is true, a corresponding error will be
7172 * returned instead of asserting. Having it false is intended as a sanity check
7173 * for methods that have checked mMachineState and expect mpUVM *NOT* to be
7174 * NULL.
7175 *
7176 * @param aQuiet true to suppress setting error info
7177 * @param aAllowNullVM true to accept mpUVM being NULL and return a failure
7178 * (otherwise this method will assert if mpUVM is NULL)
7179 *
7180 * @note Locks this object for writing.
7181 */
7182HRESULT Console::i_addVMCaller(bool aQuiet /* = false */,
7183 bool aAllowNullVM /* = false */)
7184{
7185 RT_NOREF(aAllowNullVM);
7186 AutoCaller autoCaller(this);
7187 /** @todo Fix race during console/VM reference destruction, refer @bugref{6318}
7188 * comment 25. */
7189 if (FAILED(autoCaller.rc()))
7190 return autoCaller.rc();
7191
7192 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7193
7194 if (mVMDestroying)
7195 {
7196 /* powerDown() is waiting for all callers to finish */
7197 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED, tr("The virtual machine is being powered down"));
7198 }
7199
7200 if (mpUVM == NULL)
7201 {
7202 Assert(aAllowNullVM == true);
7203
7204 /* The machine is not powered up */
7205 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED, tr("The virtual machine is not powered up"));
7206 }
7207
7208 ++mVMCallers;
7209
7210 return S_OK;
7211}
7212
7213/**
7214 * Decreases the usage counter of the mpUVM pointer.
7215 *
7216 * Must always complete the addVMCaller() call after the mpUVM pointer is no
7217 * more necessary.
7218 *
7219 * @note Locks this object for writing.
7220 */
7221void Console::i_releaseVMCaller()
7222{
7223 AutoCaller autoCaller(this);
7224 AssertComRCReturnVoid(autoCaller.rc());
7225
7226 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7227
7228 AssertReturnVoid(mpUVM != NULL);
7229
7230 Assert(mVMCallers > 0);
7231 --mVMCallers;
7232
7233 if (mVMCallers == 0 && mVMDestroying)
7234 {
7235 /* inform powerDown() there are no more callers */
7236 RTSemEventSignal(mVMZeroCallersSem);
7237 }
7238}
7239
7240
7241HRESULT Console::i_safeVMPtrRetainer(PUVM *a_ppUVM, bool a_Quiet)
7242{
7243 *a_ppUVM = NULL;
7244
7245 AutoCaller autoCaller(this);
7246 AssertComRCReturnRC(autoCaller.rc());
7247 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7248
7249 /*
7250 * Repeat the checks done by addVMCaller.
7251 */
7252 if (mVMDestroying) /* powerDown() is waiting for all callers to finish */
7253 return a_Quiet
7254 ? E_ACCESSDENIED
7255 : setError(E_ACCESSDENIED, tr("The virtual machine is being powered down"));
7256 PUVM pUVM = mpUVM;
7257 if (!pUVM)
7258 return a_Quiet
7259 ? E_ACCESSDENIED
7260 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
7261
7262 /*
7263 * Retain a reference to the user mode VM handle and get the global handle.
7264 */
7265 uint32_t cRefs = VMR3RetainUVM(pUVM);
7266 if (cRefs == UINT32_MAX)
7267 return a_Quiet
7268 ? E_ACCESSDENIED
7269 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
7270
7271 /* done */
7272 *a_ppUVM = pUVM;
7273 return S_OK;
7274}
7275
7276void Console::i_safeVMPtrReleaser(PUVM *a_ppUVM)
7277{
7278 if (*a_ppUVM)
7279 VMR3ReleaseUVM(*a_ppUVM);
7280 *a_ppUVM = NULL;
7281}
7282
7283
7284/**
7285 * Initialize the release logging facility. In case something
7286 * goes wrong, there will be no release logging. Maybe in the future
7287 * we can add some logic to use different file names in this case.
7288 * Note that the logic must be in sync with Machine::DeleteSettings().
7289 */
7290HRESULT Console::i_consoleInitReleaseLog(const ComPtr<IMachine> aMachine)
7291{
7292 HRESULT hrc = S_OK;
7293
7294 Bstr logFolder;
7295 hrc = aMachine->COMGETTER(LogFolder)(logFolder.asOutParam());
7296 if (FAILED(hrc))
7297 return hrc;
7298
7299 Utf8Str logDir = logFolder;
7300
7301 /* make sure the Logs folder exists */
7302 Assert(logDir.length());
7303 if (!RTDirExists(logDir.c_str()))
7304 RTDirCreateFullPath(logDir.c_str(), 0700);
7305
7306 Utf8Str logFile = Utf8StrFmt("%s%cVBox.log",
7307 logDir.c_str(), RTPATH_DELIMITER);
7308 Utf8Str pngFile = Utf8StrFmt("%s%cVBox.png",
7309 logDir.c_str(), RTPATH_DELIMITER);
7310
7311 /*
7312 * Age the old log files
7313 * Rename .(n-1) to .(n), .(n-2) to .(n-1), ..., and the last log file to .1
7314 * Overwrite target files in case they exist.
7315 */
7316 ComPtr<IVirtualBox> pVirtualBox;
7317 aMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
7318 ComPtr<ISystemProperties> pSystemProperties;
7319 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
7320 ULONG cHistoryFiles = 3;
7321 pSystemProperties->COMGETTER(LogHistoryCount)(&cHistoryFiles);
7322 if (cHistoryFiles)
7323 {
7324 for (int i = cHistoryFiles-1; i >= 0; i--)
7325 {
7326 Utf8Str *files[] = { &logFile, &pngFile };
7327 Utf8Str oldName, newName;
7328
7329 for (unsigned int j = 0; j < RT_ELEMENTS(files); ++j)
7330 {
7331 if (i > 0)
7332 oldName = Utf8StrFmt("%s.%d", files[j]->c_str(), i);
7333 else
7334 oldName = *files[j];
7335 newName = Utf8StrFmt("%s.%d", files[j]->c_str(), i + 1);
7336 /* If the old file doesn't exist, delete the new file (if it
7337 * exists) to provide correct rotation even if the sequence is
7338 * broken */
7339 if ( RTFileRename(oldName.c_str(), newName.c_str(), RTFILEMOVE_FLAGS_REPLACE)
7340 == VERR_FILE_NOT_FOUND)
7341 RTFileDelete(newName.c_str());
7342 }
7343 }
7344 }
7345
7346 RTERRINFOSTATIC ErrInfo;
7347 int vrc = com::VBoxLogRelCreate("VM", logFile.c_str(),
7348 RTLOGFLAGS_PREFIX_TIME_PROG | RTLOGFLAGS_RESTRICT_GROUPS,
7349 "all all.restrict -default.restrict",
7350 "VBOX_RELEASE_LOG", RTLOGDEST_FILE,
7351 32768 /* cMaxEntriesPerGroup */,
7352 0 /* cHistory */, 0 /* uHistoryFileTime */,
7353 0 /* uHistoryFileSize */, RTErrInfoInitStatic(&ErrInfo));
7354 if (RT_FAILURE(vrc))
7355 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to open release log (%s, %Rrc)"), ErrInfo.Core.pszMsg, vrc);
7356
7357 /* If we've made any directory changes, flush the directory to increase
7358 the likelihood that the log file will be usable after a system panic.
7359
7360 Tip: Try 'export VBOX_RELEASE_LOG_FLAGS=flush' if the last bits of the log
7361 is missing. Just don't have too high hopes for this to help. */
7362 if (SUCCEEDED(hrc) || cHistoryFiles)
7363 RTDirFlush(logDir.c_str());
7364
7365 return hrc;
7366}
7367
7368/**
7369 * Common worker for PowerUp and PowerUpPaused.
7370 *
7371 * @returns COM status code.
7372 *
7373 * @param aProgress Where to return the progress object.
7374 * @param aPaused true if PowerUpPaused called.
7375 */
7376HRESULT Console::i_powerUp(IProgress **aProgress, bool aPaused)
7377{
7378 LogFlowThisFuncEnter();
7379
7380 CheckComArgOutPointerValid(aProgress);
7381
7382 AutoCaller autoCaller(this);
7383 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7384
7385 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7386
7387 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
7388 HRESULT rc = S_OK;
7389 ComObjPtr<Progress> pPowerupProgress;
7390 bool fBeganPoweringUp = false;
7391
7392 LONG cOperations = 1;
7393 LONG ulTotalOperationsWeight = 1;
7394 VMPowerUpTask* task = NULL;
7395
7396 try
7397 {
7398 if (Global::IsOnlineOrTransient(mMachineState))
7399 throw setError(VBOX_E_INVALID_VM_STATE, tr("The virtual machine is already running or busy (machine state: %s)"),
7400 Global::stringifyMachineState(mMachineState));
7401
7402 /* Set up release logging as early as possible after the check if
7403 * there is already a running VM which we shouldn't disturb. */
7404 rc = i_consoleInitReleaseLog(mMachine);
7405 if (FAILED(rc))
7406 throw rc;
7407
7408#ifdef VBOX_OPENSSL_FIPS
7409 LogRel(("crypto: FIPS mode %s\n", FIPS_mode() ? "enabled" : "FAILED"));
7410#endif
7411
7412 /* test and clear the TeleporterEnabled property */
7413 BOOL fTeleporterEnabled;
7414 rc = mMachine->COMGETTER(TeleporterEnabled)(&fTeleporterEnabled);
7415 if (FAILED(rc))
7416 throw rc;
7417
7418#if 0 /** @todo we should save it afterwards, but that isn't necessarily a good idea. Find a better place for this (VBoxSVC). */
7419 if (fTeleporterEnabled)
7420 {
7421 rc = mMachine->COMSETTER(TeleporterEnabled)(FALSE);
7422 if (FAILED(rc))
7423 throw rc;
7424 }
7425#endif
7426
7427 /* test the FaultToleranceState property */
7428 FaultToleranceState_T enmFaultToleranceState;
7429 rc = mMachine->COMGETTER(FaultToleranceState)(&enmFaultToleranceState);
7430 if (FAILED(rc))
7431 throw rc;
7432 BOOL fFaultToleranceSyncEnabled = (enmFaultToleranceState == FaultToleranceState_Standby);
7433
7434 /* Create a progress object to track progress of this operation. Must
7435 * be done as early as possible (together with BeginPowerUp()) as this
7436 * is vital for communicating as much as possible early powerup
7437 * failure information to the API caller */
7438 pPowerupProgress.createObject();
7439 Bstr progressDesc;
7440 if (mMachineState == MachineState_Saved)
7441 progressDesc = tr("Restoring virtual machine");
7442 else if (fTeleporterEnabled)
7443 progressDesc = tr("Teleporting virtual machine");
7444 else if (fFaultToleranceSyncEnabled)
7445 progressDesc = tr("Fault Tolerance syncing of remote virtual machine");
7446 else
7447 progressDesc = tr("Starting virtual machine");
7448
7449 Bstr savedStateFile;
7450
7451 /*
7452 * Saved VMs will have to prove that their saved states seem kosher.
7453 */
7454 if (mMachineState == MachineState_Saved)
7455 {
7456 rc = mMachine->COMGETTER(StateFilePath)(savedStateFile.asOutParam());
7457 if (FAILED(rc))
7458 throw rc;
7459 ComAssertRet(!savedStateFile.isEmpty(), E_FAIL);
7460 int vrc = SSMR3ValidateFile(Utf8Str(savedStateFile).c_str(), false /* fChecksumIt */);
7461 if (RT_FAILURE(vrc))
7462 throw setErrorBoth(VBOX_E_FILE_ERROR, vrc,
7463 tr("VM cannot start because the saved state file '%ls' is invalid (%Rrc). Delete the saved state prior to starting the VM"),
7464 savedStateFile.raw(), vrc);
7465 }
7466
7467 /* Read console data, including console shared folders, stored in the
7468 * saved state file (if not yet done).
7469 */
7470 rc = i_loadDataFromSavedState();
7471 if (FAILED(rc))
7472 throw rc;
7473
7474 /* Check all types of shared folders and compose a single list */
7475 SharedFolderDataMap sharedFolders;
7476 {
7477 /* first, insert global folders */
7478 for (SharedFolderDataMap::const_iterator it = m_mapGlobalSharedFolders.begin();
7479 it != m_mapGlobalSharedFolders.end();
7480 ++it)
7481 {
7482 const SharedFolderData &d = it->second;
7483 sharedFolders[it->first] = d;
7484 }
7485
7486 /* second, insert machine folders */
7487 for (SharedFolderDataMap::const_iterator it = m_mapMachineSharedFolders.begin();
7488 it != m_mapMachineSharedFolders.end();
7489 ++it)
7490 {
7491 const SharedFolderData &d = it->second;
7492 sharedFolders[it->first] = d;
7493 }
7494
7495 /* third, insert console folders */
7496 for (SharedFolderMap::const_iterator it = m_mapSharedFolders.begin();
7497 it != m_mapSharedFolders.end();
7498 ++it)
7499 {
7500 SharedFolder *pSF = it->second;
7501 AutoCaller sfCaller(pSF);
7502 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
7503 sharedFolders[it->first] = SharedFolderData(pSF->i_getHostPath(),
7504 pSF->i_isWritable(),
7505 pSF->i_isAutoMounted());
7506 }
7507 }
7508
7509
7510 /* Setup task object and thread to carry out the operation
7511 * asynchronously */
7512 try
7513 {
7514 task = new VMPowerUpTask(this, pPowerupProgress);
7515 if (!task->isOk())
7516 {
7517 throw E_FAIL;
7518 }
7519 }
7520 catch(...)
7521 {
7522 delete task;
7523 rc = setError(E_FAIL, "Could not create VMPowerUpTask object \n");
7524 throw rc;
7525 }
7526
7527 task->mConfigConstructor = i_configConstructor;
7528 task->mSharedFolders = sharedFolders;
7529 task->mStartPaused = aPaused;
7530 if (mMachineState == MachineState_Saved)
7531 task->mSavedStateFile = savedStateFile;
7532 task->mTeleporterEnabled = fTeleporterEnabled;
7533 task->mEnmFaultToleranceState = enmFaultToleranceState;
7534
7535 /* Reset differencing hard disks for which autoReset is true,
7536 * but only if the machine has no snapshots OR the current snapshot
7537 * is an OFFLINE snapshot; otherwise we would reset the current
7538 * differencing image of an ONLINE snapshot which contains the disk
7539 * state of the machine while it was previously running, but without
7540 * the corresponding machine state, which is equivalent to powering
7541 * off a running machine and not good idea
7542 */
7543 ComPtr<ISnapshot> pCurrentSnapshot;
7544 rc = mMachine->COMGETTER(CurrentSnapshot)(pCurrentSnapshot.asOutParam());
7545 if (FAILED(rc))
7546 throw rc;
7547
7548 BOOL fCurrentSnapshotIsOnline = false;
7549 if (pCurrentSnapshot)
7550 {
7551 rc = pCurrentSnapshot->COMGETTER(Online)(&fCurrentSnapshotIsOnline);
7552 if (FAILED(rc))
7553 throw rc;
7554 }
7555
7556 if (savedStateFile.isEmpty() && !fCurrentSnapshotIsOnline)
7557 {
7558 LogFlowThisFunc(("Looking for immutable images to reset\n"));
7559
7560 com::SafeIfaceArray<IMediumAttachment> atts;
7561 rc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
7562 if (FAILED(rc))
7563 throw rc;
7564
7565 for (size_t i = 0;
7566 i < atts.size();
7567 ++i)
7568 {
7569 DeviceType_T devType;
7570 rc = atts[i]->COMGETTER(Type)(&devType);
7571 /** @todo later applies to floppies as well */
7572 if (devType == DeviceType_HardDisk)
7573 {
7574 ComPtr<IMedium> pMedium;
7575 rc = atts[i]->COMGETTER(Medium)(pMedium.asOutParam());
7576 if (FAILED(rc))
7577 throw rc;
7578
7579 /* needs autoreset? */
7580 BOOL autoReset = FALSE;
7581 rc = pMedium->COMGETTER(AutoReset)(&autoReset);
7582 if (FAILED(rc))
7583 throw rc;
7584
7585 if (autoReset)
7586 {
7587 ComPtr<IProgress> pResetProgress;
7588 rc = pMedium->Reset(pResetProgress.asOutParam());
7589 if (FAILED(rc))
7590 throw rc;
7591
7592 /* save for later use on the powerup thread */
7593 task->hardDiskProgresses.push_back(pResetProgress);
7594 }
7595 }
7596 }
7597 }
7598 else
7599 LogFlowThisFunc(("Machine has a current snapshot which is online, skipping immutable images reset\n"));
7600
7601 /* setup task object and thread to carry out the operation
7602 * asynchronously */
7603
7604#ifdef VBOX_WITH_EXTPACK
7605 mptrExtPackManager->i_dumpAllToReleaseLog();
7606#endif
7607
7608#ifdef RT_OS_SOLARIS
7609 /* setup host core dumper for the VM */
7610 Bstr value;
7611 HRESULT hrc = mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpEnabled").raw(), value.asOutParam());
7612 if (SUCCEEDED(hrc) && value == "1")
7613 {
7614 Bstr coreDumpDir, coreDumpReplaceSys, coreDumpLive;
7615 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpDir").raw(), coreDumpDir.asOutParam());
7616 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpReplaceSystemDump").raw(), coreDumpReplaceSys.asOutParam());
7617 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpLive").raw(), coreDumpLive.asOutParam());
7618
7619 uint32_t fCoreFlags = 0;
7620 if ( coreDumpReplaceSys.isEmpty() == false
7621 && Utf8Str(coreDumpReplaceSys).toUInt32() == 1)
7622 fCoreFlags |= RTCOREDUMPER_FLAGS_REPLACE_SYSTEM_DUMP;
7623
7624 if ( coreDumpLive.isEmpty() == false
7625 && Utf8Str(coreDumpLive).toUInt32() == 1)
7626 fCoreFlags |= RTCOREDUMPER_FLAGS_LIVE_CORE;
7627
7628 Utf8Str strDumpDir(coreDumpDir);
7629 const char *pszDumpDir = strDumpDir.c_str();
7630 if ( pszDumpDir
7631 && *pszDumpDir == '\0')
7632 pszDumpDir = NULL;
7633
7634 int vrc;
7635 if ( pszDumpDir
7636 && !RTDirExists(pszDumpDir))
7637 {
7638 /*
7639 * Try create the directory.
7640 */
7641 vrc = RTDirCreateFullPath(pszDumpDir, 0700);
7642 if (RT_FAILURE(vrc))
7643 throw setErrorBoth(E_FAIL, vrc, "Failed to setup CoreDumper. Couldn't create dump directory '%s' (%Rrc)\n",
7644 pszDumpDir, vrc);
7645 }
7646
7647 vrc = RTCoreDumperSetup(pszDumpDir, fCoreFlags);
7648 if (RT_FAILURE(vrc))
7649 throw setErrorBoth(E_FAIL, vrc, "Failed to setup CoreDumper (%Rrc)", vrc);
7650 LogRel(("CoreDumper setup successful. pszDumpDir=%s fFlags=%#x\n", pszDumpDir ? pszDumpDir : ".", fCoreFlags));
7651 }
7652#endif
7653
7654
7655 // If there is immutable drive the process that.
7656 VMPowerUpTask::ProgressList progresses(task->hardDiskProgresses);
7657 if (aProgress && !progresses.empty())
7658 {
7659 for (VMPowerUpTask::ProgressList::const_iterator it = progresses.begin(); it != progresses.end(); ++it)
7660 {
7661 ++cOperations;
7662 ulTotalOperationsWeight += 1;
7663 }
7664 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7665 progressDesc.raw(),
7666 TRUE, // Cancelable
7667 cOperations,
7668 ulTotalOperationsWeight,
7669 Bstr(tr("Starting Hard Disk operations")).raw(),
7670 1);
7671 AssertComRCReturnRC(rc);
7672 }
7673 else if ( mMachineState == MachineState_Saved
7674 || (!fTeleporterEnabled && !fFaultToleranceSyncEnabled))
7675 {
7676 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7677 progressDesc.raw(),
7678 FALSE /* aCancelable */);
7679 }
7680 else if (fTeleporterEnabled)
7681 {
7682 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7683 progressDesc.raw(),
7684 TRUE /* aCancelable */,
7685 3 /* cOperations */,
7686 10 /* ulTotalOperationsWeight */,
7687 Bstr(tr("Teleporting virtual machine")).raw(),
7688 1 /* ulFirstOperationWeight */);
7689 }
7690 else if (fFaultToleranceSyncEnabled)
7691 {
7692 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7693 progressDesc.raw(),
7694 TRUE /* aCancelable */,
7695 3 /* cOperations */,
7696 10 /* ulTotalOperationsWeight */,
7697 Bstr(tr("Fault Tolerance syncing of remote virtual machine")).raw(),
7698 1 /* ulFirstOperationWeight */);
7699 }
7700
7701 if (FAILED(rc))
7702 throw rc;
7703
7704 /* Tell VBoxSVC and Machine about the progress object so they can
7705 combine/proxy it to any openRemoteSession caller. */
7706 LogFlowThisFunc(("Calling BeginPowerUp...\n"));
7707 rc = mControl->BeginPowerUp(pPowerupProgress);
7708 if (FAILED(rc))
7709 {
7710 LogFlowThisFunc(("BeginPowerUp failed\n"));
7711 throw rc;
7712 }
7713 fBeganPoweringUp = true;
7714
7715 LogFlowThisFunc(("Checking if canceled...\n"));
7716 BOOL fCanceled;
7717 rc = pPowerupProgress->COMGETTER(Canceled)(&fCanceled);
7718 if (FAILED(rc))
7719 throw rc;
7720
7721 if (fCanceled)
7722 {
7723 LogFlowThisFunc(("Canceled in BeginPowerUp\n"));
7724 throw setError(E_FAIL, tr("Powerup was canceled"));
7725 }
7726 LogFlowThisFunc(("Not canceled yet.\n"));
7727
7728 /** @todo this code prevents starting a VM with unavailable bridged
7729 * networking interface. The only benefit is a slightly better error
7730 * message, which should be moved to the driver code. This is the
7731 * only reason why I left the code in for now. The driver allows
7732 * unavailable bridged networking interfaces in certain circumstances,
7733 * and this is sabotaged by this check. The VM will initially have no
7734 * network connectivity, but the user can fix this at runtime. */
7735#if 0
7736 /* the network cards will undergo a quick consistency check */
7737 for (ULONG slot = 0;
7738 slot < maxNetworkAdapters;
7739 ++slot)
7740 {
7741 ComPtr<INetworkAdapter> pNetworkAdapter;
7742 mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
7743 BOOL enabled = FALSE;
7744 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
7745 if (!enabled)
7746 continue;
7747
7748 NetworkAttachmentType_T netattach;
7749 pNetworkAdapter->COMGETTER(AttachmentType)(&netattach);
7750 switch (netattach)
7751 {
7752 case NetworkAttachmentType_Bridged:
7753 {
7754 /* a valid host interface must have been set */
7755 Bstr hostif;
7756 pNetworkAdapter->COMGETTER(HostInterface)(hostif.asOutParam());
7757 if (hostif.isEmpty())
7758 {
7759 throw setError(VBOX_E_HOST_ERROR,
7760 tr("VM cannot start because host interface networking requires a host interface name to be set"));
7761 }
7762 ComPtr<IVirtualBox> pVirtualBox;
7763 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
7764 ComPtr<IHost> pHost;
7765 pVirtualBox->COMGETTER(Host)(pHost.asOutParam());
7766 ComPtr<IHostNetworkInterface> pHostInterface;
7767 if (!SUCCEEDED(pHost->FindHostNetworkInterfaceByName(hostif.raw(),
7768 pHostInterface.asOutParam())))
7769 {
7770 throw setError(VBOX_E_HOST_ERROR,
7771 tr("VM cannot start because the host interface '%ls' does not exist"), hostif.raw());
7772 }
7773 break;
7774 }
7775 default:
7776 break;
7777 }
7778 }
7779#endif // 0
7780
7781
7782 /* setup task object and thread to carry out the operation
7783 * asynchronously */
7784 if (aProgress){
7785 rc = pPowerupProgress.queryInterfaceTo(aProgress);
7786 AssertComRCReturnRC(rc);
7787 }
7788
7789 rc = task->createThread();
7790
7791 if (FAILED(rc))
7792 throw rc;
7793
7794 /* finally, set the state: no right to fail in this method afterwards
7795 * since we've already started the thread and it is now responsible for
7796 * any error reporting and appropriate state change! */
7797 if (mMachineState == MachineState_Saved)
7798 i_setMachineState(MachineState_Restoring);
7799 else if (fTeleporterEnabled)
7800 i_setMachineState(MachineState_TeleportingIn);
7801 else if (enmFaultToleranceState == FaultToleranceState_Standby)
7802 i_setMachineState(MachineState_FaultTolerantSyncing);
7803 else
7804 i_setMachineState(MachineState_Starting);
7805 }
7806 catch (HRESULT aRC) { rc = aRC; }
7807
7808 if (FAILED(rc) && fBeganPoweringUp)
7809 {
7810
7811 /* The progress object will fetch the current error info */
7812 if (!pPowerupProgress.isNull())
7813 pPowerupProgress->i_notifyComplete(rc);
7814
7815 /* Save the error info across the IPC below. Can't be done before the
7816 * progress notification above, as saving the error info deletes it
7817 * from the current context, and thus the progress object wouldn't be
7818 * updated correctly. */
7819 ErrorInfoKeeper eik;
7820
7821 /* signal end of operation */
7822 mControl->EndPowerUp(rc);
7823 }
7824
7825 LogFlowThisFunc(("mMachineState=%d, rc=%Rhrc\n", mMachineState, rc));
7826 LogFlowThisFuncLeave();
7827 return rc;
7828}
7829
7830/**
7831 * Internal power off worker routine.
7832 *
7833 * This method may be called only at certain places with the following meaning
7834 * as shown below:
7835 *
7836 * - if the machine state is either Running or Paused, a normal
7837 * Console-initiated powerdown takes place (e.g. PowerDown());
7838 * - if the machine state is Saving, saveStateThread() has successfully done its
7839 * job;
7840 * - if the machine state is Starting or Restoring, powerUpThread() has failed
7841 * to start/load the VM;
7842 * - if the machine state is Stopping, the VM has powered itself off (i.e. not
7843 * as a result of the powerDown() call).
7844 *
7845 * Calling it in situations other than the above will cause unexpected behavior.
7846 *
7847 * Note that this method should be the only one that destroys mpUVM and sets it
7848 * to NULL.
7849 *
7850 * @param aProgress Progress object to run (may be NULL).
7851 *
7852 * @note Locks this object for writing.
7853 *
7854 * @note Never call this method from a thread that called addVMCaller() or
7855 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
7856 * release(). Otherwise it will deadlock.
7857 */
7858HRESULT Console::i_powerDown(IProgress *aProgress /*= NULL*/)
7859{
7860 LogFlowThisFuncEnter();
7861
7862 AutoCaller autoCaller(this);
7863 AssertComRCReturnRC(autoCaller.rc());
7864
7865 ComPtr<IInternalProgressControl> pProgressControl(aProgress);
7866
7867 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7868
7869 /* Total # of steps for the progress object. Must correspond to the
7870 * number of "advance percent count" comments in this method! */
7871 enum { StepCount = 7 };
7872 /* current step */
7873 ULONG step = 0;
7874
7875 HRESULT rc = S_OK;
7876 int vrc = VINF_SUCCESS;
7877
7878 /* sanity */
7879 Assert(mVMDestroying == false);
7880
7881 PUVM pUVM = mpUVM; Assert(pUVM != NULL);
7882 uint32_t cRefs = VMR3RetainUVM(pUVM); Assert(cRefs != UINT32_MAX); NOREF(cRefs);
7883
7884 AssertMsg( mMachineState == MachineState_Running
7885 || mMachineState == MachineState_Paused
7886 || mMachineState == MachineState_Stuck
7887 || mMachineState == MachineState_Starting
7888 || mMachineState == MachineState_Stopping
7889 || mMachineState == MachineState_Saving
7890 || mMachineState == MachineState_Restoring
7891 || mMachineState == MachineState_TeleportingPausedVM
7892 || mMachineState == MachineState_FaultTolerantSyncing
7893 || mMachineState == MachineState_TeleportingIn
7894 , ("Invalid machine state: %s\n", Global::stringifyMachineState(mMachineState)));
7895
7896 LogRel(("Console::powerDown(): A request to power off the VM has been issued (mMachineState=%s, InUninit=%d)\n",
7897 Global::stringifyMachineState(mMachineState), getObjectState().getState() == ObjectState::InUninit));
7898
7899 /* Check if we need to power off the VM. In case of mVMPoweredOff=true, the
7900 * VM has already powered itself off in vmstateChangeCallback() and is just
7901 * notifying Console about that. In case of Starting or Restoring,
7902 * powerUpThread() is calling us on failure, so the VM is already off at
7903 * that point. */
7904 if ( !mVMPoweredOff
7905 && ( mMachineState == MachineState_Starting
7906 || mMachineState == MachineState_Restoring
7907 || mMachineState == MachineState_FaultTolerantSyncing
7908 || mMachineState == MachineState_TeleportingIn)
7909 )
7910 mVMPoweredOff = true;
7911
7912 /*
7913 * Go to Stopping state if not already there.
7914 *
7915 * Note that we don't go from Saving/Restoring to Stopping because
7916 * vmstateChangeCallback() needs it to set the state to Saved on
7917 * VMSTATE_TERMINATED. In terms of protecting from inappropriate operations
7918 * while leaving the lock below, Saving or Restoring should be fine too.
7919 * Ditto for TeleportingPausedVM -> Teleported.
7920 */
7921 if ( mMachineState != MachineState_Saving
7922 && mMachineState != MachineState_Restoring
7923 && mMachineState != MachineState_Stopping
7924 && mMachineState != MachineState_TeleportingIn
7925 && mMachineState != MachineState_TeleportingPausedVM
7926 && mMachineState != MachineState_FaultTolerantSyncing
7927 )
7928 i_setMachineState(MachineState_Stopping);
7929
7930 /* ----------------------------------------------------------------------
7931 * DONE with necessary state changes, perform the power down actions (it's
7932 * safe to release the object lock now if needed)
7933 * ---------------------------------------------------------------------- */
7934
7935 if (mDisplay)
7936 {
7937 alock.release();
7938
7939 mDisplay->i_notifyPowerDown();
7940
7941 alock.acquire();
7942 }
7943
7944 /* Stop the VRDP server to prevent new clients connection while VM is being
7945 * powered off. */
7946 if (mConsoleVRDPServer)
7947 {
7948 LogFlowThisFunc(("Stopping VRDP server...\n"));
7949
7950 /* Leave the lock since EMT could call us back as addVMCaller() */
7951 alock.release();
7952
7953 mConsoleVRDPServer->Stop();
7954
7955 alock.acquire();
7956 }
7957
7958 /* advance percent count */
7959 if (pProgressControl)
7960 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
7961
7962
7963 /* ----------------------------------------------------------------------
7964 * Now, wait for all mpUVM callers to finish their work if there are still
7965 * some on other threads. NO methods that need mpUVM (or initiate other calls
7966 * that need it) may be called after this point
7967 * ---------------------------------------------------------------------- */
7968
7969 /* go to the destroying state to prevent from adding new callers */
7970 mVMDestroying = true;
7971
7972 if (mVMCallers > 0)
7973 {
7974 /* lazy creation */
7975 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
7976 RTSemEventCreate(&mVMZeroCallersSem);
7977
7978 LogFlowThisFunc(("Waiting for mpUVM callers (%d) to drop to zero...\n", mVMCallers));
7979
7980 alock.release();
7981
7982 RTSemEventWait(mVMZeroCallersSem, RT_INDEFINITE_WAIT);
7983
7984 alock.acquire();
7985 }
7986
7987 /* advance percent count */
7988 if (pProgressControl)
7989 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
7990
7991 vrc = VINF_SUCCESS;
7992
7993 /*
7994 * Power off the VM if not already done that.
7995 * Leave the lock since EMT will call vmstateChangeCallback.
7996 *
7997 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
7998 * VM-(guest-)initiated power off happened in parallel a ms before this
7999 * call. So far, we let this error pop up on the user's side.
8000 */
8001 if (!mVMPoweredOff)
8002 {
8003 LogFlowThisFunc(("Powering off the VM...\n"));
8004 alock.release();
8005 vrc = VMR3PowerOff(pUVM);
8006#ifdef VBOX_WITH_EXTPACK
8007 mptrExtPackManager->i_callAllVmPowerOffHooks(this, VMR3GetVM(pUVM));
8008#endif
8009 alock.acquire();
8010 }
8011
8012 /* advance percent count */
8013 if (pProgressControl)
8014 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8015
8016#ifdef VBOX_WITH_HGCM
8017 /* Shutdown HGCM services before destroying the VM. */
8018 if (m_pVMMDev)
8019 {
8020 LogFlowThisFunc(("Shutdown HGCM...\n"));
8021
8022 /* Leave the lock since EMT might wait for it and will call us back as addVMCaller() */
8023 alock.release();
8024
8025 DBGFR3InfoDeregisterExternal(pUVM, "guestprops"); /* will crash in unloaded code if we guru later */
8026 m_pVMMDev->hgcmShutdown();
8027
8028 alock.acquire();
8029 }
8030
8031 /* advance percent count */
8032 if (pProgressControl)
8033 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8034
8035#endif /* VBOX_WITH_HGCM */
8036
8037 LogFlowThisFunc(("Ready for VM destruction.\n"));
8038
8039 /* If we are called from Console::uninit(), then try to destroy the VM even
8040 * on failure (this will most likely fail too, but what to do?..) */
8041 if (RT_SUCCESS(vrc) || getObjectState().getState() == ObjectState::InUninit)
8042 {
8043 /* If the machine has a USB controller, release all USB devices
8044 * (symmetric to the code in captureUSBDevices()) */
8045 if (mfVMHasUsbController)
8046 {
8047 alock.release();
8048 i_detachAllUSBDevices(false /* aDone */);
8049 alock.acquire();
8050 }
8051
8052 /* Now we've got to destroy the VM as well. (mpUVM is not valid beyond
8053 * this point). We release the lock before calling VMR3Destroy() because
8054 * it will result into calling destructors of drivers associated with
8055 * Console children which may in turn try to lock Console (e.g. by
8056 * instantiating SafeVMPtr to access mpUVM). It's safe here because
8057 * mVMDestroying is set which should prevent any activity. */
8058
8059 /* Set mpUVM to NULL early just in case if some old code is not using
8060 * addVMCaller()/releaseVMCaller(). (We have our own ref on pUVM.) */
8061 VMR3ReleaseUVM(mpUVM);
8062 mpUVM = NULL;
8063
8064 LogFlowThisFunc(("Destroying the VM...\n"));
8065
8066 alock.release();
8067
8068 vrc = VMR3Destroy(pUVM);
8069
8070 /* take the lock again */
8071 alock.acquire();
8072
8073 /* advance percent count */
8074 if (pProgressControl)
8075 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8076
8077 if (RT_SUCCESS(vrc))
8078 {
8079 LogFlowThisFunc(("Machine has been destroyed (mMachineState=%d)\n",
8080 mMachineState));
8081 /* Note: the Console-level machine state change happens on the
8082 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
8083 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
8084 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
8085 * occurred yet. This is okay, because mMachineState is already
8086 * Stopping in this case, so any other attempt to call PowerDown()
8087 * will be rejected. */
8088 }
8089 else
8090 {
8091 /* bad bad bad, but what to do? (Give Console our UVM ref.) */
8092 mpUVM = pUVM;
8093 pUVM = NULL;
8094 rc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not destroy the machine. (Error: %Rrc)"), vrc);
8095 }
8096
8097 /* Complete the detaching of the USB devices. */
8098 if (mfVMHasUsbController)
8099 {
8100 alock.release();
8101 i_detachAllUSBDevices(true /* aDone */);
8102 alock.acquire();
8103 }
8104
8105 /* advance percent count */
8106 if (pProgressControl)
8107 pProgressControl->SetCurrentOperationProgress(99 * (++step) / StepCount);
8108 }
8109 else
8110 rc = setErrorBoth(VBOX_E_VM_ERROR, vrc, tr("Could not power off the machine. (Error: %Rrc)"), vrc);
8111
8112 /*
8113 * Finished with the destruction.
8114 *
8115 * Note that if something impossible happened and we've failed to destroy
8116 * the VM, mVMDestroying will remain true and mMachineState will be
8117 * something like Stopping, so most Console methods will return an error
8118 * to the caller.
8119 */
8120 if (pUVM != NULL)
8121 VMR3ReleaseUVM(pUVM);
8122 else
8123 mVMDestroying = false;
8124
8125 LogFlowThisFuncLeave();
8126 return rc;
8127}
8128
8129/**
8130 * @note Locks this object for writing.
8131 */
8132HRESULT Console::i_setMachineState(MachineState_T aMachineState,
8133 bool aUpdateServer /* = true */)
8134{
8135 AutoCaller autoCaller(this);
8136 AssertComRCReturnRC(autoCaller.rc());
8137
8138 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8139
8140 HRESULT rc = S_OK;
8141
8142 if (mMachineState != aMachineState)
8143 {
8144 LogThisFunc(("machineState=%s -> %s aUpdateServer=%RTbool\n",
8145 Global::stringifyMachineState(mMachineState), Global::stringifyMachineState(aMachineState), aUpdateServer));
8146 LogRel(("Console: Machine state changed to '%s'\n", Global::stringifyMachineState(aMachineState)));
8147 mMachineState = aMachineState;
8148
8149 /// @todo (dmik)
8150 // possibly, we need to redo onStateChange() using the dedicated
8151 // Event thread, like it is done in VirtualBox. This will make it
8152 // much safer (no deadlocks possible if someone tries to use the
8153 // console from the callback), however, listeners will lose the
8154 // ability to synchronously react to state changes (is it really
8155 // necessary??)
8156 LogFlowThisFunc(("Doing onStateChange()...\n"));
8157 i_onStateChange(aMachineState);
8158 LogFlowThisFunc(("Done onStateChange()\n"));
8159
8160 if (aUpdateServer)
8161 {
8162 /* Server notification MUST be done from under the lock; otherwise
8163 * the machine state here and on the server might go out of sync
8164 * which can lead to various unexpected results (like the machine
8165 * state being >= MachineState_Running on the server, while the
8166 * session state is already SessionState_Unlocked at the same time
8167 * there).
8168 *
8169 * Cross-lock conditions should be carefully watched out: calling
8170 * UpdateState we will require Machine and SessionMachine locks
8171 * (remember that here we're holding the Console lock here, and also
8172 * all locks that have been acquire by the thread before calling
8173 * this method).
8174 */
8175 LogFlowThisFunc(("Doing mControl->UpdateState()...\n"));
8176 rc = mControl->UpdateState(aMachineState);
8177 LogFlowThisFunc(("mControl->UpdateState()=%Rhrc\n", rc));
8178 }
8179 }
8180
8181 return rc;
8182}
8183
8184/**
8185 * Searches for a shared folder with the given logical name
8186 * in the collection of shared folders.
8187 *
8188 * @param strName logical name of the shared folder
8189 * @param aSharedFolder where to return the found object
8190 * @param aSetError whether to set the error info if the folder is
8191 * not found
8192 * @return
8193 * S_OK when found or E_INVALIDARG when not found
8194 *
8195 * @note The caller must lock this object for writing.
8196 */
8197HRESULT Console::i_findSharedFolder(const Utf8Str &strName,
8198 ComObjPtr<SharedFolder> &aSharedFolder,
8199 bool aSetError /* = false */)
8200{
8201 /* sanity check */
8202 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8203
8204 SharedFolderMap::const_iterator it = m_mapSharedFolders.find(strName);
8205 if (it != m_mapSharedFolders.end())
8206 {
8207 aSharedFolder = it->second;
8208 return S_OK;
8209 }
8210
8211 if (aSetError)
8212 setError(VBOX_E_FILE_ERROR, tr("Could not find a shared folder named '%s'."), strName.c_str());
8213
8214 return VBOX_E_FILE_ERROR;
8215}
8216
8217/**
8218 * Fetches the list of global or machine shared folders from the server.
8219 *
8220 * @param aGlobal true to fetch global folders.
8221 *
8222 * @note The caller must lock this object for writing.
8223 */
8224HRESULT Console::i_fetchSharedFolders(BOOL aGlobal)
8225{
8226 /* sanity check */
8227 AssertReturn( getObjectState().getState() == ObjectState::InInit
8228 || isWriteLockOnCurrentThread(), E_FAIL);
8229
8230 LogFlowThisFunc(("Entering\n"));
8231
8232 /* Check if we're online and keep it that way. */
8233 SafeVMPtrQuiet ptrVM(this);
8234 AutoVMCallerQuietWeak autoVMCaller(this);
8235 bool const online = ptrVM.isOk()
8236 && m_pVMMDev
8237 && m_pVMMDev->isShFlActive();
8238
8239 HRESULT rc = S_OK;
8240
8241 try
8242 {
8243 if (aGlobal)
8244 {
8245 /// @todo grab & process global folders when they are done
8246 }
8247 else
8248 {
8249 SharedFolderDataMap oldFolders;
8250 if (online)
8251 oldFolders = m_mapMachineSharedFolders;
8252
8253 m_mapMachineSharedFolders.clear();
8254
8255 SafeIfaceArray<ISharedFolder> folders;
8256 rc = mMachine->COMGETTER(SharedFolders)(ComSafeArrayAsOutParam(folders));
8257 if (FAILED(rc)) throw rc;
8258
8259 for (size_t i = 0; i < folders.size(); ++i)
8260 {
8261 ComPtr<ISharedFolder> pSharedFolder = folders[i];
8262
8263 Bstr bstrName;
8264 Bstr bstrHostPath;
8265 BOOL writable;
8266 BOOL autoMount;
8267
8268 rc = pSharedFolder->COMGETTER(Name)(bstrName.asOutParam());
8269 if (FAILED(rc)) throw rc;
8270 Utf8Str strName(bstrName);
8271
8272 rc = pSharedFolder->COMGETTER(HostPath)(bstrHostPath.asOutParam());
8273 if (FAILED(rc)) throw rc;
8274 Utf8Str strHostPath(bstrHostPath);
8275
8276 rc = pSharedFolder->COMGETTER(Writable)(&writable);
8277 if (FAILED(rc)) throw rc;
8278
8279 rc = pSharedFolder->COMGETTER(AutoMount)(&autoMount);
8280 if (FAILED(rc)) throw rc;
8281
8282 m_mapMachineSharedFolders.insert(std::make_pair(strName,
8283 SharedFolderData(strHostPath, !!writable, !!autoMount)));
8284
8285 /* send changes to HGCM if the VM is running */
8286 if (online)
8287 {
8288 SharedFolderDataMap::iterator it = oldFolders.find(strName);
8289 if ( it == oldFolders.end()
8290 || it->second.m_strHostPath != strHostPath)
8291 {
8292 /* a new machine folder is added or
8293 * the existing machine folder is changed */
8294 if (m_mapSharedFolders.find(strName) != m_mapSharedFolders.end())
8295 ; /* the console folder exists, nothing to do */
8296 else
8297 {
8298 /* remove the old machine folder (when changed)
8299 * or the global folder if any (when new) */
8300 if ( it != oldFolders.end()
8301 || m_mapGlobalSharedFolders.find(strName) != m_mapGlobalSharedFolders.end()
8302 )
8303 {
8304 rc = i_removeSharedFolder(strName);
8305 if (FAILED(rc)) throw rc;
8306 }
8307
8308 /* create the new machine folder */
8309 rc = i_createSharedFolder(strName,
8310 SharedFolderData(strHostPath, !!writable, !!autoMount));
8311 if (FAILED(rc)) throw rc;
8312 }
8313 }
8314 /* forget the processed (or identical) folder */
8315 if (it != oldFolders.end())
8316 oldFolders.erase(it);
8317 }
8318 }
8319
8320 /* process outdated (removed) folders */
8321 if (online)
8322 {
8323 for (SharedFolderDataMap::const_iterator it = oldFolders.begin();
8324 it != oldFolders.end(); ++it)
8325 {
8326 if (m_mapSharedFolders.find(it->first) != m_mapSharedFolders.end())
8327 ; /* the console folder exists, nothing to do */
8328 else
8329 {
8330 /* remove the outdated machine folder */
8331 rc = i_removeSharedFolder(it->first);
8332 if (FAILED(rc)) throw rc;
8333
8334 /* create the global folder if there is any */
8335 SharedFolderDataMap::const_iterator git =
8336 m_mapGlobalSharedFolders.find(it->first);
8337 if (git != m_mapGlobalSharedFolders.end())
8338 {
8339 rc = i_createSharedFolder(git->first, git->second);
8340 if (FAILED(rc)) throw rc;
8341 }
8342 }
8343 }
8344 }
8345 }
8346 }
8347 catch (HRESULT rc2)
8348 {
8349 rc = rc2;
8350 if (online)
8351 i_atVMRuntimeErrorCallbackF(0, "BrokenSharedFolder", N_("Broken shared folder!"));
8352 }
8353
8354 LogFlowThisFunc(("Leaving\n"));
8355
8356 return rc;
8357}
8358
8359/**
8360 * Searches for a shared folder with the given name in the list of machine
8361 * shared folders and then in the list of the global shared folders.
8362 *
8363 * @param strName Name of the folder to search for.
8364 * @param aIt Where to store the pointer to the found folder.
8365 * @return @c true if the folder was found and @c false otherwise.
8366 *
8367 * @note The caller must lock this object for reading.
8368 */
8369bool Console::i_findOtherSharedFolder(const Utf8Str &strName,
8370 SharedFolderDataMap::const_iterator &aIt)
8371{
8372 /* sanity check */
8373 AssertReturn(isWriteLockOnCurrentThread(), false);
8374
8375 /* first, search machine folders */
8376 aIt = m_mapMachineSharedFolders.find(strName);
8377 if (aIt != m_mapMachineSharedFolders.end())
8378 return true;
8379
8380 /* second, search machine folders */
8381 aIt = m_mapGlobalSharedFolders.find(strName);
8382 if (aIt != m_mapGlobalSharedFolders.end())
8383 return true;
8384
8385 return false;
8386}
8387
8388/**
8389 * Calls the HGCM service to add a shared folder definition.
8390 *
8391 * @param strName Shared folder name.
8392 * @param aData Shared folder data.
8393 *
8394 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
8395 * @note Doesn't lock anything.
8396 */
8397HRESULT Console::i_createSharedFolder(const Utf8Str &strName, const SharedFolderData &aData)
8398{
8399 ComAssertRet(strName.isNotEmpty(), E_FAIL);
8400 ComAssertRet(aData.m_strHostPath.isNotEmpty(), E_FAIL);
8401
8402 /* sanity checks */
8403 AssertReturn(mpUVM, E_FAIL);
8404 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
8405
8406 VBOXHGCMSVCPARM parms[SHFL_CPARMS_ADD_MAPPING];
8407 SHFLSTRING *pFolderName, *pMapName;
8408 size_t cbString;
8409
8410 Bstr value;
8411 HRESULT hrc = mMachine->GetExtraData(BstrFmt("VBoxInternal2/SharedFoldersEnableSymlinksCreate/%s",
8412 strName.c_str()).raw(),
8413 value.asOutParam());
8414 bool fSymlinksCreate = hrc == S_OK && value == "1";
8415
8416 Log(("Adding shared folder '%s' -> '%s'\n", strName.c_str(), aData.m_strHostPath.c_str()));
8417
8418 // check whether the path is valid and exists
8419 char hostPathFull[RTPATH_MAX];
8420 int vrc = RTPathAbsEx(NULL,
8421 aData.m_strHostPath.c_str(),
8422 hostPathFull,
8423 sizeof(hostPathFull));
8424
8425 bool fMissing = false;
8426 if (RT_FAILURE(vrc))
8427 return setErrorBoth(E_INVALIDARG, vrc, tr("Invalid shared folder path: '%s' (%Rrc)"), aData.m_strHostPath.c_str(), vrc);
8428 if (!RTPathExists(hostPathFull))
8429 fMissing = true;
8430
8431 /* Check whether the path is full (absolute) */
8432 if (RTPathCompare(aData.m_strHostPath.c_str(), hostPathFull) != 0)
8433 return setError(E_INVALIDARG,
8434 tr("Shared folder path '%s' is not absolute"),
8435 aData.m_strHostPath.c_str());
8436
8437 // now that we know the path is good, give it to HGCM
8438
8439 Bstr bstrName(strName);
8440 Bstr bstrHostPath(aData.m_strHostPath);
8441
8442 cbString = (bstrHostPath.length() + 1) * sizeof(RTUTF16);
8443 if (cbString >= UINT16_MAX)
8444 return setError(E_INVALIDARG, tr("The name is too long"));
8445 pFolderName = (SHFLSTRING*)RTMemAllocZ(SHFLSTRING_HEADER_SIZE + cbString);
8446 Assert(pFolderName);
8447 memcpy(pFolderName->String.ucs2, bstrHostPath.raw(), cbString);
8448
8449 pFolderName->u16Size = (uint16_t)cbString;
8450 pFolderName->u16Length = (uint16_t)(cbString - sizeof(RTUTF16));
8451
8452 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
8453 parms[0].u.pointer.addr = pFolderName;
8454 parms[0].u.pointer.size = ShflStringSizeOfBuffer(pFolderName);
8455
8456 cbString = (bstrName.length() + 1) * sizeof(RTUTF16);
8457 if (cbString >= UINT16_MAX)
8458 {
8459 RTMemFree(pFolderName);
8460 return setError(E_INVALIDARG, tr("The host path is too long"));
8461 }
8462 pMapName = (SHFLSTRING*)RTMemAllocZ(SHFLSTRING_HEADER_SIZE + cbString);
8463 Assert(pMapName);
8464 memcpy(pMapName->String.ucs2, bstrName.raw(), cbString);
8465
8466 pMapName->u16Size = (uint16_t)cbString;
8467 pMapName->u16Length = (uint16_t)(cbString - sizeof(RTUTF16));
8468
8469 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
8470 parms[1].u.pointer.addr = pMapName;
8471 parms[1].u.pointer.size = ShflStringSizeOfBuffer(pMapName);
8472
8473 parms[2].type = VBOX_HGCM_SVC_PARM_32BIT;
8474 parms[2].u.uint32 = (aData.m_fWritable ? SHFL_ADD_MAPPING_F_WRITABLE : 0)
8475 | (aData.m_fAutoMount ? SHFL_ADD_MAPPING_F_AUTOMOUNT : 0)
8476 | (fSymlinksCreate ? SHFL_ADD_MAPPING_F_CREATE_SYMLINKS : 0)
8477 | (fMissing ? SHFL_ADD_MAPPING_F_MISSING : 0)
8478 ;
8479
8480 vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders",
8481 SHFL_FN_ADD_MAPPING,
8482 SHFL_CPARMS_ADD_MAPPING, &parms[0]);
8483 RTMemFree(pFolderName);
8484 RTMemFree(pMapName);
8485
8486 if (RT_FAILURE(vrc))
8487 return setErrorBoth(E_FAIL, vrc, tr("Could not create a shared folder '%s' mapped to '%s' (%Rrc)"),
8488 strName.c_str(), aData.m_strHostPath.c_str(), vrc);
8489
8490 if (fMissing)
8491 return setError(E_INVALIDARG,
8492 tr("Shared folder path '%s' does not exist on the host"),
8493 aData.m_strHostPath.c_str());
8494
8495 return S_OK;
8496}
8497
8498/**
8499 * Calls the HGCM service to remove the shared folder definition.
8500 *
8501 * @param strName Shared folder name.
8502 *
8503 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
8504 * @note Doesn't lock anything.
8505 */
8506HRESULT Console::i_removeSharedFolder(const Utf8Str &strName)
8507{
8508 ComAssertRet(strName.isNotEmpty(), E_FAIL);
8509
8510 /* sanity checks */
8511 AssertReturn(mpUVM, E_FAIL);
8512 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
8513
8514 VBOXHGCMSVCPARM parms;
8515 SHFLSTRING *pMapName;
8516 size_t cbString;
8517
8518 Log(("Removing shared folder '%s'\n", strName.c_str()));
8519
8520 Bstr bstrName(strName);
8521 cbString = (bstrName.length() + 1) * sizeof(RTUTF16);
8522 if (cbString >= UINT16_MAX)
8523 return setError(E_INVALIDARG, tr("The name is too long"));
8524 pMapName = (SHFLSTRING *) RTMemAllocZ(SHFLSTRING_HEADER_SIZE + cbString);
8525 Assert(pMapName);
8526 memcpy(pMapName->String.ucs2, bstrName.raw(), cbString);
8527
8528 pMapName->u16Size = (uint16_t)cbString;
8529 pMapName->u16Length = (uint16_t)(cbString - sizeof(RTUTF16));
8530
8531 parms.type = VBOX_HGCM_SVC_PARM_PTR;
8532 parms.u.pointer.addr = pMapName;
8533 parms.u.pointer.size = ShflStringSizeOfBuffer(pMapName);
8534
8535 int vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders",
8536 SHFL_FN_REMOVE_MAPPING,
8537 1, &parms);
8538 RTMemFree(pMapName);
8539 if (RT_FAILURE(vrc))
8540 return setErrorBoth(E_FAIL, vrc, tr("Could not remove the shared folder '%s' (%Rrc)"), strName.c_str(), vrc);
8541
8542 return S_OK;
8543}
8544
8545/** @callback_method_impl{FNVMATSTATE}
8546 *
8547 * @note Locks the Console object for writing.
8548 * @remarks The @a pUVM parameter can be NULL in one case where powerUpThread()
8549 * calls after the VM was destroyed.
8550 */
8551DECLCALLBACK(void) Console::i_vmstateChangeCallback(PUVM pUVM, VMSTATE enmState, VMSTATE enmOldState, void *pvUser)
8552{
8553 LogFlowFunc(("Changing state from %s to %s (pUVM=%p)\n",
8554 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState), pUVM));
8555
8556 Console *that = static_cast<Console *>(pvUser);
8557 AssertReturnVoid(that);
8558
8559 AutoCaller autoCaller(that);
8560
8561 /* Note that we must let this method proceed even if Console::uninit() has
8562 * been already called. In such case this VMSTATE change is a result of:
8563 * 1) powerDown() called from uninit() itself, or
8564 * 2) VM-(guest-)initiated power off. */
8565 AssertReturnVoid( autoCaller.isOk()
8566 || that->getObjectState().getState() == ObjectState::InUninit);
8567
8568 switch (enmState)
8569 {
8570 /*
8571 * The VM has terminated
8572 */
8573 case VMSTATE_OFF:
8574 {
8575#ifdef VBOX_WITH_GUEST_PROPS
8576 if (that->i_isResetTurnedIntoPowerOff())
8577 {
8578 Bstr strPowerOffReason;
8579
8580 if (that->mfPowerOffCausedByReset)
8581 strPowerOffReason = Bstr("Reset");
8582 else
8583 strPowerOffReason = Bstr("PowerOff");
8584
8585 that->mMachine->DeleteGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw());
8586 that->mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw(),
8587 strPowerOffReason.raw(), Bstr("RDONLYGUEST").raw());
8588 that->mMachine->SaveSettings();
8589 }
8590#endif
8591
8592 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8593
8594 if (that->mVMStateChangeCallbackDisabled)
8595 return;
8596
8597 /* Do we still think that it is running? It may happen if this is a
8598 * VM-(guest-)initiated shutdown/poweroff.
8599 */
8600 if ( that->mMachineState != MachineState_Stopping
8601 && that->mMachineState != MachineState_Saving
8602 && that->mMachineState != MachineState_Restoring
8603 && that->mMachineState != MachineState_TeleportingIn
8604 && that->mMachineState != MachineState_FaultTolerantSyncing
8605 && that->mMachineState != MachineState_TeleportingPausedVM
8606 && !that->mVMIsAlreadyPoweringOff
8607 )
8608 {
8609 LogFlowFunc(("VM has powered itself off but Console still thinks it is running. Notifying.\n"));
8610
8611 /*
8612 * Prevent powerDown() from calling VMR3PowerOff() again if this was called from
8613 * the power off state change.
8614 * When called from the Reset state make sure to call VMR3PowerOff() first.
8615 */
8616 Assert(that->mVMPoweredOff == false);
8617 that->mVMPoweredOff = true;
8618
8619 /*
8620 * request a progress object from the server
8621 * (this will set the machine state to Stopping on the server
8622 * to block others from accessing this machine)
8623 */
8624 ComPtr<IProgress> pProgress;
8625 HRESULT rc = that->mControl->BeginPoweringDown(pProgress.asOutParam());
8626 AssertComRC(rc);
8627
8628 /* sync the state with the server */
8629 that->i_setMachineStateLocally(MachineState_Stopping);
8630
8631 /* Setup task object and thread to carry out the operation
8632 * asynchronously (if we call powerDown() right here but there
8633 * is one or more mpUVM callers (added with addVMCaller()) we'll
8634 * deadlock).
8635 */
8636 VMPowerDownTask* task = NULL;
8637 try
8638 {
8639 task = new VMPowerDownTask(that, pProgress);
8640 /* If creating a task failed, this can currently mean one of
8641 * two: either Console::uninit() has been called just a ms
8642 * before (so a powerDown() call is already on the way), or
8643 * powerDown() itself is being already executed. Just do
8644 * nothing.
8645 */
8646 if (!task->isOk())
8647 {
8648 LogFlowFunc(("Console is already being uninitialized. \n"));
8649 throw E_FAIL;
8650 }
8651 }
8652 catch(...)
8653 {
8654 delete task;
8655 LogFlowFunc(("Problem with creating VMPowerDownTask object. \n"));
8656 }
8657
8658 rc = task->createThread();
8659
8660 if (FAILED(rc))
8661 {
8662 LogFlowFunc(("Problem with creating thread for VMPowerDownTask. \n"));
8663 }
8664
8665 }
8666 break;
8667 }
8668
8669 /* The VM has been completely destroyed.
8670 *
8671 * Note: This state change can happen at two points:
8672 * 1) At the end of VMR3Destroy() if it was not called from EMT.
8673 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
8674 * called by EMT.
8675 */
8676 case VMSTATE_TERMINATED:
8677 {
8678 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8679
8680 if (that->mVMStateChangeCallbackDisabled)
8681 break;
8682
8683 /* Terminate host interface networking. If pUVM is NULL, we've been
8684 * manually called from powerUpThread() either before calling
8685 * VMR3Create() or after VMR3Create() failed, so no need to touch
8686 * networking.
8687 */
8688 if (pUVM)
8689 that->i_powerDownHostInterfaces();
8690
8691 /* From now on the machine is officially powered down or remains in
8692 * the Saved state.
8693 */
8694 switch (that->mMachineState)
8695 {
8696 default:
8697 AssertFailed();
8698 RT_FALL_THRU();
8699 case MachineState_Stopping:
8700 /* successfully powered down */
8701 that->i_setMachineState(MachineState_PoweredOff);
8702 break;
8703 case MachineState_Saving:
8704 /* successfully saved */
8705 that->i_setMachineState(MachineState_Saved);
8706 break;
8707 case MachineState_Starting:
8708 /* failed to start, but be patient: set back to PoweredOff
8709 * (for similarity with the below) */
8710 that->i_setMachineState(MachineState_PoweredOff);
8711 break;
8712 case MachineState_Restoring:
8713 /* failed to load the saved state file, but be patient: set
8714 * back to Saved (to preserve the saved state file) */
8715 that->i_setMachineState(MachineState_Saved);
8716 break;
8717 case MachineState_TeleportingIn:
8718 /* Teleportation failed or was canceled. Back to powered off. */
8719 that->i_setMachineState(MachineState_PoweredOff);
8720 break;
8721 case MachineState_TeleportingPausedVM:
8722 /* Successfully teleported the VM. */
8723 that->i_setMachineState(MachineState_Teleported);
8724 break;
8725 case MachineState_FaultTolerantSyncing:
8726 /* Fault tolerant sync failed or was canceled. Back to powered off. */
8727 that->i_setMachineState(MachineState_PoweredOff);
8728 break;
8729 }
8730 break;
8731 }
8732
8733 case VMSTATE_RESETTING:
8734 /** @todo shouldn't VMSTATE_RESETTING_LS be here? */
8735 {
8736#ifdef VBOX_WITH_GUEST_PROPS
8737 /* Do not take any read/write locks here! */
8738 that->i_guestPropertiesHandleVMReset();
8739#endif
8740 break;
8741 }
8742
8743 case VMSTATE_SOFT_RESETTING:
8744 case VMSTATE_SOFT_RESETTING_LS:
8745 /* Shouldn't do anything here! */
8746 break;
8747
8748 case VMSTATE_SUSPENDED:
8749 {
8750 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8751
8752 if (that->mVMStateChangeCallbackDisabled)
8753 break;
8754
8755 switch (that->mMachineState)
8756 {
8757 case MachineState_Teleporting:
8758 that->i_setMachineState(MachineState_TeleportingPausedVM);
8759 break;
8760
8761 case MachineState_LiveSnapshotting:
8762 that->i_setMachineState(MachineState_OnlineSnapshotting);
8763 break;
8764
8765 case MachineState_TeleportingPausedVM:
8766 case MachineState_Saving:
8767 case MachineState_Restoring:
8768 case MachineState_Stopping:
8769 case MachineState_TeleportingIn:
8770 case MachineState_FaultTolerantSyncing:
8771 case MachineState_OnlineSnapshotting:
8772 /* The worker thread handles the transition. */
8773 break;
8774
8775 case MachineState_Running:
8776 that->i_setMachineState(MachineState_Paused);
8777 break;
8778
8779 case MachineState_Paused:
8780 /* Nothing to do. */
8781 break;
8782
8783 default:
8784 AssertMsgFailed(("%s\n", Global::stringifyMachineState(that->mMachineState)));
8785 }
8786 break;
8787 }
8788
8789 case VMSTATE_SUSPENDED_LS:
8790 case VMSTATE_SUSPENDED_EXT_LS:
8791 {
8792 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8793 if (that->mVMStateChangeCallbackDisabled)
8794 break;
8795 switch (that->mMachineState)
8796 {
8797 case MachineState_Teleporting:
8798 that->i_setMachineState(MachineState_TeleportingPausedVM);
8799 break;
8800
8801 case MachineState_LiveSnapshotting:
8802 that->i_setMachineState(MachineState_OnlineSnapshotting);
8803 break;
8804
8805 case MachineState_TeleportingPausedVM:
8806 case MachineState_Saving:
8807 /* ignore */
8808 break;
8809
8810 default:
8811 AssertMsgFailed(("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState),
8812 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
8813 that->i_setMachineState(MachineState_Paused);
8814 break;
8815 }
8816 break;
8817 }
8818
8819 case VMSTATE_RUNNING:
8820 {
8821 if ( enmOldState == VMSTATE_POWERING_ON
8822 || enmOldState == VMSTATE_RESUMING
8823 || enmOldState == VMSTATE_RUNNING_FT)
8824 {
8825 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8826
8827 if (that->mVMStateChangeCallbackDisabled)
8828 break;
8829
8830 Assert( ( ( that->mMachineState == MachineState_Starting
8831 || that->mMachineState == MachineState_Paused)
8832 && enmOldState == VMSTATE_POWERING_ON)
8833 || ( ( that->mMachineState == MachineState_Restoring
8834 || that->mMachineState == MachineState_TeleportingIn
8835 || that->mMachineState == MachineState_Paused
8836 || that->mMachineState == MachineState_Saving
8837 )
8838 && enmOldState == VMSTATE_RESUMING)
8839 || ( that->mMachineState == MachineState_FaultTolerantSyncing
8840 && enmOldState == VMSTATE_RUNNING_FT));
8841
8842 that->i_setMachineState(MachineState_Running);
8843 }
8844
8845 break;
8846 }
8847
8848 case VMSTATE_RUNNING_LS:
8849 AssertMsg( that->mMachineState == MachineState_LiveSnapshotting
8850 || that->mMachineState == MachineState_Teleporting,
8851 ("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState),
8852 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
8853 break;
8854
8855 case VMSTATE_RUNNING_FT:
8856 AssertMsg(that->mMachineState == MachineState_FaultTolerantSyncing,
8857 ("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState),
8858 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
8859 break;
8860
8861 case VMSTATE_FATAL_ERROR:
8862 {
8863 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8864
8865 if (that->mVMStateChangeCallbackDisabled)
8866 break;
8867
8868 /* Fatal errors are only for running VMs. */
8869 Assert(Global::IsOnline(that->mMachineState));
8870
8871 /* Note! 'Pause' is used here in want of something better. There
8872 * are currently only two places where fatal errors might be
8873 * raised, so it is not worth adding a new externally
8874 * visible state for this yet. */
8875 that->i_setMachineState(MachineState_Paused);
8876 break;
8877 }
8878
8879 case VMSTATE_GURU_MEDITATION:
8880 {
8881 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8882
8883 if (that->mVMStateChangeCallbackDisabled)
8884 break;
8885
8886 /* Guru are only for running VMs */
8887 Assert(Global::IsOnline(that->mMachineState));
8888
8889 that->i_setMachineState(MachineState_Stuck);
8890 break;
8891 }
8892
8893 case VMSTATE_CREATED:
8894 {
8895 /*
8896 * We have to set the secret key helper interface for the VD drivers to
8897 * get notified about missing keys.
8898 */
8899 that->i_initSecretKeyIfOnAllAttachments();
8900 break;
8901 }
8902
8903 default: /* shut up gcc */
8904 break;
8905 }
8906}
8907
8908/**
8909 * Changes the clipboard mode.
8910 *
8911 * @param aClipboardMode new clipboard mode.
8912 */
8913void Console::i_changeClipboardMode(ClipboardMode_T aClipboardMode)
8914{
8915 VMMDev *pVMMDev = m_pVMMDev;
8916 Assert(pVMMDev);
8917
8918 VBOXHGCMSVCPARM parm;
8919 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
8920
8921 switch (aClipboardMode)
8922 {
8923 default:
8924 case ClipboardMode_Disabled:
8925 LogRel(("Shared clipboard mode: Off\n"));
8926 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_OFF;
8927 break;
8928 case ClipboardMode_GuestToHost:
8929 LogRel(("Shared clipboard mode: Guest to Host\n"));
8930 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_GUEST_TO_HOST;
8931 break;
8932 case ClipboardMode_HostToGuest:
8933 LogRel(("Shared clipboard mode: Host to Guest\n"));
8934 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_HOST_TO_GUEST;
8935 break;
8936 case ClipboardMode_Bidirectional:
8937 LogRel(("Shared clipboard mode: Bidirectional\n"));
8938 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_BIDIRECTIONAL;
8939 break;
8940 }
8941
8942 pVMMDev->hgcmHostCall("VBoxSharedClipboard", VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE, 1, &parm);
8943}
8944
8945/**
8946 * Changes the drag and drop mode.
8947 *
8948 * @param aDnDMode new drag and drop mode.
8949 */
8950int Console::i_changeDnDMode(DnDMode_T aDnDMode)
8951{
8952 VMMDev *pVMMDev = m_pVMMDev;
8953 AssertPtrReturn(pVMMDev, VERR_INVALID_POINTER);
8954
8955 VBOXHGCMSVCPARM parm;
8956 RT_ZERO(parm);
8957 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
8958
8959 switch (aDnDMode)
8960 {
8961 default:
8962 case DnDMode_Disabled:
8963 LogRel(("Drag and drop mode: Off\n"));
8964 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_OFF;
8965 break;
8966 case DnDMode_GuestToHost:
8967 LogRel(("Drag and drop mode: Guest to Host\n"));
8968 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_GUEST_TO_HOST;
8969 break;
8970 case DnDMode_HostToGuest:
8971 LogRel(("Drag and drop mode: Host to Guest\n"));
8972 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_HOST_TO_GUEST;
8973 break;
8974 case DnDMode_Bidirectional:
8975 LogRel(("Drag and drop mode: Bidirectional\n"));
8976 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_BIDIRECTIONAL;
8977 break;
8978 }
8979
8980 int rc = pVMMDev->hgcmHostCall("VBoxDragAndDropSvc",
8981 DragAndDropSvc::HOST_DND_SET_MODE, 1 /* cParms */, &parm);
8982 if (RT_FAILURE(rc))
8983 LogRel(("Error changing drag and drop mode: %Rrc\n", rc));
8984
8985 return rc;
8986}
8987
8988#ifdef VBOX_WITH_USB
8989/**
8990 * Sends a request to VMM to attach the given host device.
8991 * After this method succeeds, the attached device will appear in the
8992 * mUSBDevices collection.
8993 *
8994 * @param aHostDevice device to attach
8995 *
8996 * @note Synchronously calls EMT.
8997 */
8998HRESULT Console::i_attachUSBDevice(IUSBDevice *aHostDevice, ULONG aMaskedIfs,
8999 const Utf8Str &aCaptureFilename)
9000{
9001 AssertReturn(aHostDevice, E_FAIL);
9002 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
9003
9004 HRESULT hrc;
9005
9006 /*
9007 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
9008 * method in EMT (using usbAttachCallback()).
9009 */
9010 Bstr BstrAddress;
9011 hrc = aHostDevice->COMGETTER(Address)(BstrAddress.asOutParam());
9012 ComAssertComRCRetRC(hrc);
9013
9014 Utf8Str Address(BstrAddress);
9015
9016 Bstr id;
9017 hrc = aHostDevice->COMGETTER(Id)(id.asOutParam());
9018 ComAssertComRCRetRC(hrc);
9019 Guid uuid(id);
9020
9021 BOOL fRemote = FALSE;
9022 hrc = aHostDevice->COMGETTER(Remote)(&fRemote);
9023 ComAssertComRCRetRC(hrc);
9024
9025 Bstr BstrBackend;
9026 hrc = aHostDevice->COMGETTER(Backend)(BstrBackend.asOutParam());
9027 ComAssertComRCRetRC(hrc);
9028
9029 Utf8Str Backend(BstrBackend);
9030
9031 /* Get the VM handle. */
9032 SafeVMPtr ptrVM(this);
9033 if (!ptrVM.isOk())
9034 return ptrVM.rc();
9035
9036 LogFlowThisFunc(("Proxying USB device '%s' {%RTuuid}...\n",
9037 Address.c_str(), uuid.raw()));
9038
9039 void *pvRemoteBackend = NULL;
9040 if (fRemote)
9041 {
9042 RemoteUSBDevice *pRemoteUSBDevice = static_cast<RemoteUSBDevice *>(aHostDevice);
9043 pvRemoteBackend = i_consoleVRDPServer()->USBBackendRequestPointer(pRemoteUSBDevice->clientId(), &uuid);
9044 if (!pvRemoteBackend)
9045 return E_INVALIDARG; /* The clientId is invalid then. */
9046 }
9047
9048 USBConnectionSpeed_T enmSpeed;
9049 hrc = aHostDevice->COMGETTER(Speed)(&enmSpeed);
9050 AssertComRCReturnRC(hrc);
9051
9052 int vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
9053 (PFNRT)i_usbAttachCallback, 10,
9054 this, ptrVM.rawUVM(), aHostDevice, uuid.raw(), Backend.c_str(),
9055 Address.c_str(), pvRemoteBackend, enmSpeed, aMaskedIfs,
9056 aCaptureFilename.isEmpty() ? NULL : aCaptureFilename.c_str());
9057 if (RT_SUCCESS(vrc))
9058 {
9059 /* Create a OUSBDevice and add it to the device list */
9060 ComObjPtr<OUSBDevice> pUSBDevice;
9061 pUSBDevice.createObject();
9062 hrc = pUSBDevice->init(aHostDevice);
9063 AssertComRC(hrc);
9064
9065 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9066 mUSBDevices.push_back(pUSBDevice);
9067 LogFlowFunc(("Attached device {%RTuuid}\n", pUSBDevice->i_id().raw()));
9068
9069 /* notify callbacks */
9070 alock.release();
9071 i_onUSBDeviceStateChange(pUSBDevice, true /* aAttached */, NULL);
9072 }
9073 else
9074 {
9075 Log1WarningThisFunc(("Failed to create proxy device for '%s' {%RTuuid} (%Rrc)\n", Address.c_str(), uuid.raw(), vrc));
9076
9077 switch (vrc)
9078 {
9079 case VERR_VUSB_NO_PORTS:
9080 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to attach the USB device. (No available ports on the USB controller)."));
9081 break;
9082 case VERR_VUSB_USBFS_PERMISSION:
9083 hrc = setErrorBoth(E_FAIL, vrc, tr("Not permitted to open the USB device, check usbfs options"));
9084 break;
9085 default:
9086 hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to create a proxy device for the USB device. (Error: %Rrc)"), vrc);
9087 break;
9088 }
9089 }
9090
9091 return hrc;
9092}
9093
9094/**
9095 * USB device attach callback used by AttachUSBDevice().
9096 * Note that AttachUSBDevice() doesn't return until this callback is executed,
9097 * so we don't use AutoCaller and don't care about reference counters of
9098 * interface pointers passed in.
9099 *
9100 * @thread EMT
9101 * @note Locks the console object for writing.
9102 */
9103//static
9104DECLCALLBACK(int)
9105Console::i_usbAttachCallback(Console *that, PUVM pUVM, IUSBDevice *aHostDevice, PCRTUUID aUuid, const char *pszBackend,
9106 const char *aAddress, void *pvRemoteBackend, USBConnectionSpeed_T aEnmSpeed, ULONG aMaskedIfs,
9107 const char *pszCaptureFilename)
9108{
9109 RT_NOREF(aHostDevice);
9110 LogFlowFuncEnter();
9111 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
9112
9113 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
9114 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
9115
9116 VUSBSPEED enmSpeed = VUSB_SPEED_UNKNOWN;
9117 switch (aEnmSpeed)
9118 {
9119 case USBConnectionSpeed_Low: enmSpeed = VUSB_SPEED_LOW; break;
9120 case USBConnectionSpeed_Full: enmSpeed = VUSB_SPEED_FULL; break;
9121 case USBConnectionSpeed_High: enmSpeed = VUSB_SPEED_HIGH; break;
9122 case USBConnectionSpeed_Super: enmSpeed = VUSB_SPEED_SUPER; break;
9123 case USBConnectionSpeed_SuperPlus: enmSpeed = VUSB_SPEED_SUPERPLUS; break;
9124 default: AssertFailed(); break;
9125 }
9126
9127 int vrc = PDMR3UsbCreateProxyDevice(pUVM, aUuid, pszBackend, aAddress, pvRemoteBackend,
9128 enmSpeed, aMaskedIfs, pszCaptureFilename);
9129 LogFlowFunc(("vrc=%Rrc\n", vrc));
9130 LogFlowFuncLeave();
9131 return vrc;
9132}
9133
9134/**
9135 * Sends a request to VMM to detach the given host device. After this method
9136 * succeeds, the detached device will disappear from the mUSBDevices
9137 * collection.
9138 *
9139 * @param aHostDevice device to attach
9140 *
9141 * @note Synchronously calls EMT.
9142 */
9143HRESULT Console::i_detachUSBDevice(const ComObjPtr<OUSBDevice> &aHostDevice)
9144{
9145 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
9146
9147 /* Get the VM handle. */
9148 SafeVMPtr ptrVM(this);
9149 if (!ptrVM.isOk())
9150 return ptrVM.rc();
9151
9152 /* if the device is attached, then there must at least one USB hub. */
9153 AssertReturn(PDMR3UsbHasHub(ptrVM.rawUVM()), E_FAIL);
9154
9155 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9156 LogFlowThisFunc(("Detaching USB proxy device {%RTuuid}...\n",
9157 aHostDevice->i_id().raw()));
9158
9159 /*
9160 * If this was a remote device, release the backend pointer.
9161 * The pointer was requested in usbAttachCallback.
9162 */
9163 BOOL fRemote = FALSE;
9164
9165 HRESULT hrc2 = aHostDevice->COMGETTER(Remote)(&fRemote);
9166 if (FAILED(hrc2))
9167 i_setErrorStatic(hrc2, "GetRemote() failed");
9168
9169 PCRTUUID pUuid = aHostDevice->i_id().raw();
9170 if (fRemote)
9171 {
9172 Guid guid(*pUuid);
9173 i_consoleVRDPServer()->USBBackendReleasePointer(&guid);
9174 }
9175
9176 alock.release();
9177 int vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
9178 (PFNRT)i_usbDetachCallback, 5,
9179 this, ptrVM.rawUVM(), pUuid);
9180 if (RT_SUCCESS(vrc))
9181 {
9182 LogFlowFunc(("Detached device {%RTuuid}\n", pUuid));
9183
9184 /* notify callbacks */
9185 i_onUSBDeviceStateChange(aHostDevice, false /* aAttached */, NULL);
9186 }
9187
9188 ComAssertRCRet(vrc, E_FAIL);
9189
9190 return S_OK;
9191}
9192
9193/**
9194 * USB device detach callback used by DetachUSBDevice().
9195 *
9196 * Note that DetachUSBDevice() doesn't return until this callback is executed,
9197 * so we don't use AutoCaller and don't care about reference counters of
9198 * interface pointers passed in.
9199 *
9200 * @thread EMT
9201 */
9202//static
9203DECLCALLBACK(int)
9204Console::i_usbDetachCallback(Console *that, PUVM pUVM, PCRTUUID aUuid)
9205{
9206 LogFlowFuncEnter();
9207 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
9208
9209 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
9210 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
9211
9212 int vrc = PDMR3UsbDetachDevice(pUVM, aUuid);
9213
9214 LogFlowFunc(("vrc=%Rrc\n", vrc));
9215 LogFlowFuncLeave();
9216 return vrc;
9217}
9218#endif /* VBOX_WITH_USB */
9219
9220/* Note: FreeBSD needs this whether netflt is used or not. */
9221#if ((defined(RT_OS_LINUX) && !defined(VBOX_WITH_NETFLT)) || defined(RT_OS_FREEBSD))
9222/**
9223 * Helper function to handle host interface device creation and attachment.
9224 *
9225 * @param networkAdapter the network adapter which attachment should be reset
9226 * @return COM status code
9227 *
9228 * @note The caller must lock this object for writing.
9229 *
9230 * @todo Move this back into the driver!
9231 */
9232HRESULT Console::i_attachToTapInterface(INetworkAdapter *networkAdapter)
9233{
9234 LogFlowThisFunc(("\n"));
9235 /* sanity check */
9236 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9237
9238# ifdef VBOX_STRICT
9239 /* paranoia */
9240 NetworkAttachmentType_T attachment;
9241 networkAdapter->COMGETTER(AttachmentType)(&attachment);
9242 Assert(attachment == NetworkAttachmentType_Bridged);
9243# endif /* VBOX_STRICT */
9244
9245 HRESULT rc = S_OK;
9246
9247 ULONG slot = 0;
9248 rc = networkAdapter->COMGETTER(Slot)(&slot);
9249 AssertComRC(rc);
9250
9251# ifdef RT_OS_LINUX
9252 /*
9253 * Allocate a host interface device
9254 */
9255 int vrc = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
9256 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
9257 if (RT_SUCCESS(vrc))
9258 {
9259 /*
9260 * Set/obtain the tap interface.
9261 */
9262 struct ifreq IfReq;
9263 RT_ZERO(IfReq);
9264 /* The name of the TAP interface we are using */
9265 Bstr tapDeviceName;
9266 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
9267 if (FAILED(rc))
9268 tapDeviceName.setNull(); /* Is this necessary? */
9269 if (tapDeviceName.isEmpty())
9270 {
9271 LogRel(("No TAP device name was supplied.\n"));
9272 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
9273 }
9274
9275 if (SUCCEEDED(rc))
9276 {
9277 /* If we are using a static TAP device then try to open it. */
9278 Utf8Str str(tapDeviceName);
9279 RTStrCopy(IfReq.ifr_name, sizeof(IfReq.ifr_name), str.c_str()); /** @todo bitch about names which are too long... */
9280 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
9281 vrc = ioctl(RTFileToNative(maTapFD[slot]), TUNSETIFF, &IfReq);
9282 if (vrc != 0)
9283 {
9284 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
9285 rc = setErrorBoth(E_FAIL, vrc, tr("Failed to open the host network interface %ls"), tapDeviceName.raw());
9286 }
9287 }
9288 if (SUCCEEDED(rc))
9289 {
9290 /*
9291 * Make it pollable.
9292 */
9293 if (fcntl(RTFileToNative(maTapFD[slot]), F_SETFL, O_NONBLOCK) != -1)
9294 {
9295 Log(("i_attachToTapInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
9296 /*
9297 * Here is the right place to communicate the TAP file descriptor and
9298 * the host interface name to the server if/when it becomes really
9299 * necessary.
9300 */
9301 maTAPDeviceName[slot] = tapDeviceName;
9302 vrc = VINF_SUCCESS;
9303 }
9304 else
9305 {
9306 int iErr = errno;
9307
9308 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
9309 vrc = VERR_HOSTIF_BLOCKING;
9310 rc = setErrorBoth(E_FAIL, vrc, tr("could not set up the host networking device for non blocking access: %s"),
9311 strerror(errno));
9312 }
9313 }
9314 }
9315 else
9316 {
9317 LogRel(("Configuration error: Failed to open /dev/net/tun rc=%Rrc\n", vrc));
9318 switch (vrc)
9319 {
9320 case VERR_ACCESS_DENIED:
9321 /* will be handled by our caller */
9322 rc = vrc;
9323 break;
9324 default:
9325 rc = setErrorBoth(E_FAIL, vrc, tr("Could not set up the host networking device: %Rrc"), vrc);
9326 break;
9327 }
9328 }
9329
9330# elif defined(RT_OS_FREEBSD)
9331 /*
9332 * Set/obtain the tap interface.
9333 */
9334 /* The name of the TAP interface we are using */
9335 Bstr tapDeviceName;
9336 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
9337 if (FAILED(rc))
9338 tapDeviceName.setNull(); /* Is this necessary? */
9339 if (tapDeviceName.isEmpty())
9340 {
9341 LogRel(("No TAP device name was supplied.\n"));
9342 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
9343 }
9344 char szTapdev[1024] = "/dev/";
9345 /* If we are using a static TAP device then try to open it. */
9346 Utf8Str str(tapDeviceName);
9347 if (str.length() + strlen(szTapdev) <= sizeof(szTapdev))
9348 strcat(szTapdev, str.c_str());
9349 else
9350 memcpy(szTapdev + strlen(szTapdev), str.c_str(),
9351 sizeof(szTapdev) - strlen(szTapdev) - 1); /** @todo bitch about names which are too long... */
9352 int vrc = RTFileOpen(&maTapFD[slot], szTapdev,
9353 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT | RTFILE_O_NON_BLOCK);
9354
9355 if (RT_SUCCESS(vrc))
9356 maTAPDeviceName[slot] = tapDeviceName;
9357 else
9358 {
9359 switch (vrc)
9360 {
9361 case VERR_ACCESS_DENIED:
9362 /* will be handled by our caller */
9363 rc = vrc;
9364 break;
9365 default:
9366 rc = setErrorBoth(E_FAIL, vrc, tr("Failed to open the host network interface %ls"), tapDeviceName.raw());
9367 break;
9368 }
9369 }
9370# else
9371# error "huh?"
9372# endif
9373 /* in case of failure, cleanup. */
9374 if (RT_FAILURE(vrc) && SUCCEEDED(rc))
9375 {
9376 LogRel(("General failure attaching to host interface\n"));
9377 rc = setErrorBoth(E_FAIL, vrc, tr("General failure attaching to host interface"));
9378 }
9379 LogFlowThisFunc(("rc=%Rhrc\n", rc));
9380 return rc;
9381}
9382
9383
9384/**
9385 * Helper function to handle detachment from a host interface
9386 *
9387 * @param networkAdapter the network adapter which attachment should be reset
9388 * @return COM status code
9389 *
9390 * @note The caller must lock this object for writing.
9391 *
9392 * @todo Move this back into the driver!
9393 */
9394HRESULT Console::i_detachFromTapInterface(INetworkAdapter *networkAdapter)
9395{
9396 /* sanity check */
9397 LogFlowThisFunc(("\n"));
9398 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9399
9400 HRESULT rc = S_OK;
9401# ifdef VBOX_STRICT
9402 /* paranoia */
9403 NetworkAttachmentType_T attachment;
9404 networkAdapter->COMGETTER(AttachmentType)(&attachment);
9405 Assert(attachment == NetworkAttachmentType_Bridged);
9406# endif /* VBOX_STRICT */
9407
9408 ULONG slot = 0;
9409 rc = networkAdapter->COMGETTER(Slot)(&slot);
9410 AssertComRC(rc);
9411
9412 /* is there an open TAP device? */
9413 if (maTapFD[slot] != NIL_RTFILE)
9414 {
9415 /*
9416 * Close the file handle.
9417 */
9418 Bstr tapDeviceName, tapTerminateApplication;
9419 bool isStatic = true;
9420 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
9421 if (FAILED(rc) || tapDeviceName.isEmpty())
9422 {
9423 /* If the name is empty, this is a dynamic TAP device, so close it now,
9424 so that the termination script can remove the interface. Otherwise we still
9425 need the FD to pass to the termination script. */
9426 isStatic = false;
9427 int rcVBox = RTFileClose(maTapFD[slot]);
9428 AssertRC(rcVBox);
9429 maTapFD[slot] = NIL_RTFILE;
9430 }
9431 if (isStatic)
9432 {
9433 /* If we are using a static TAP device, we close it now, after having called the
9434 termination script. */
9435 int rcVBox = RTFileClose(maTapFD[slot]);
9436 AssertRC(rcVBox);
9437 }
9438 /* the TAP device name and handle are no longer valid */
9439 maTapFD[slot] = NIL_RTFILE;
9440 maTAPDeviceName[slot] = "";
9441 }
9442 LogFlowThisFunc(("returning %d\n", rc));
9443 return rc;
9444}
9445#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
9446
9447/**
9448 * Called at power down to terminate host interface networking.
9449 *
9450 * @note The caller must lock this object for writing.
9451 */
9452HRESULT Console::i_powerDownHostInterfaces()
9453{
9454 LogFlowThisFunc(("\n"));
9455
9456 /* sanity check */
9457 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9458
9459 /*
9460 * host interface termination handling
9461 */
9462 HRESULT rc = S_OK;
9463 ComPtr<IVirtualBox> pVirtualBox;
9464 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
9465 ComPtr<ISystemProperties> pSystemProperties;
9466 if (pVirtualBox)
9467 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
9468 ChipsetType_T chipsetType = ChipsetType_PIIX3;
9469 mMachine->COMGETTER(ChipsetType)(&chipsetType);
9470 ULONG maxNetworkAdapters = 0;
9471 if (pSystemProperties)
9472 pSystemProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters);
9473
9474 for (ULONG slot = 0; slot < maxNetworkAdapters; slot++)
9475 {
9476 ComPtr<INetworkAdapter> pNetworkAdapter;
9477 rc = mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
9478 if (FAILED(rc)) break;
9479
9480 BOOL enabled = FALSE;
9481 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
9482 if (!enabled)
9483 continue;
9484
9485 NetworkAttachmentType_T attachment;
9486 pNetworkAdapter->COMGETTER(AttachmentType)(&attachment);
9487 if (attachment == NetworkAttachmentType_Bridged)
9488 {
9489#if ((defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)) && !defined(VBOX_WITH_NETFLT))
9490 HRESULT rc2 = i_detachFromTapInterface(pNetworkAdapter);
9491 if (FAILED(rc2) && SUCCEEDED(rc))
9492 rc = rc2;
9493#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
9494 }
9495 }
9496
9497 return rc;
9498}
9499
9500
9501/**
9502 * Process callback handler for VMR3LoadFromFile, VMR3LoadFromStream, VMR3Save
9503 * and VMR3Teleport.
9504 *
9505 * @param pUVM The user mode VM handle.
9506 * @param uPercent Completion percentage (0-100).
9507 * @param pvUser Pointer to an IProgress instance.
9508 * @return VINF_SUCCESS.
9509 */
9510/*static*/
9511DECLCALLBACK(int) Console::i_stateProgressCallback(PUVM pUVM, unsigned uPercent, void *pvUser)
9512{
9513 IProgress *pProgress = static_cast<IProgress *>(pvUser);
9514
9515 /* update the progress object */
9516 if (pProgress)
9517 {
9518 ComPtr<IInternalProgressControl> pProgressControl(pProgress);
9519 AssertReturn(!!pProgressControl, VERR_INVALID_PARAMETER);
9520 pProgressControl->SetCurrentOperationProgress(uPercent);
9521 }
9522
9523 NOREF(pUVM);
9524 return VINF_SUCCESS;
9525}
9526
9527/**
9528 * @copydoc FNVMATERROR
9529 *
9530 * @remarks Might be some tiny serialization concerns with access to the string
9531 * object here...
9532 */
9533/*static*/ DECLCALLBACK(void)
9534Console::i_genericVMSetErrorCallback(PUVM pUVM, void *pvUser, int rc, RT_SRC_POS_DECL,
9535 const char *pszFormat, va_list args)
9536{
9537 RT_SRC_POS_NOREF();
9538 Utf8Str *pErrorText = (Utf8Str *)pvUser;
9539 AssertPtr(pErrorText);
9540
9541 /* We ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users. */
9542 va_list va2;
9543 va_copy(va2, args);
9544
9545 /* Append to any the existing error message. */
9546 if (pErrorText->length())
9547 *pErrorText = Utf8StrFmt("%s.\n%N (%Rrc)", pErrorText->c_str(),
9548 pszFormat, &va2, rc, rc);
9549 else
9550 *pErrorText = Utf8StrFmt("%N (%Rrc)", pszFormat, &va2, rc, rc);
9551
9552 va_end(va2);
9553
9554 NOREF(pUVM);
9555}
9556
9557/**
9558 * VM runtime error callback function (FNVMATRUNTIMEERROR).
9559 *
9560 * See VMSetRuntimeError for the detailed description of parameters.
9561 *
9562 * @param pUVM The user mode VM handle. Ignored, so passing NULL
9563 * is fine.
9564 * @param pvUser The user argument, pointer to the Console instance.
9565 * @param fFlags The action flags. See VMSETRTERR_FLAGS_*.
9566 * @param pszErrorId Error ID string.
9567 * @param pszFormat Error message format string.
9568 * @param va Error message arguments.
9569 * @thread EMT.
9570 */
9571/* static */ DECLCALLBACK(void)
9572Console::i_atVMRuntimeErrorCallback(PUVM pUVM, void *pvUser, uint32_t fFlags,
9573 const char *pszErrorId, const char *pszFormat, va_list va)
9574{
9575 bool const fFatal = !!(fFlags & VMSETRTERR_FLAGS_FATAL);
9576 LogFlowFuncEnter();
9577
9578 Console *that = static_cast<Console *>(pvUser);
9579 AssertReturnVoid(that);
9580
9581 Utf8Str message(pszFormat, va);
9582
9583 LogRel(("Console: VM runtime error: fatal=%RTbool, errorID=%s message=\"%s\"\n",
9584 fFatal, pszErrorId, message.c_str()));
9585
9586 that->i_onRuntimeError(BOOL(fFatal), Bstr(pszErrorId).raw(), Bstr(message).raw());
9587
9588 LogFlowFuncLeave(); NOREF(pUVM);
9589}
9590
9591/**
9592 * Captures USB devices that match filters of the VM.
9593 * Called at VM startup.
9594 *
9595 * @param pUVM The VM handle.
9596 */
9597HRESULT Console::i_captureUSBDevices(PUVM pUVM)
9598{
9599 RT_NOREF(pUVM);
9600 LogFlowThisFunc(("\n"));
9601
9602 /* sanity check */
9603 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
9604 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9605
9606 /* If the machine has a USB controller, ask the USB proxy service to
9607 * capture devices */
9608 if (mfVMHasUsbController)
9609 {
9610 /* release the lock before calling Host in VBoxSVC since Host may call
9611 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
9612 * produce an inter-process dead-lock otherwise. */
9613 alock.release();
9614
9615 HRESULT hrc = mControl->AutoCaptureUSBDevices();
9616 ComAssertComRCRetRC(hrc);
9617 }
9618
9619 return S_OK;
9620}
9621
9622
9623/**
9624 * Detach all USB device which are attached to the VM for the
9625 * purpose of clean up and such like.
9626 */
9627void Console::i_detachAllUSBDevices(bool aDone)
9628{
9629 LogFlowThisFunc(("aDone=%RTbool\n", aDone));
9630
9631 /* sanity check */
9632 AssertReturnVoid(!isWriteLockOnCurrentThread());
9633 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9634
9635 mUSBDevices.clear();
9636
9637 /* release the lock before calling Host in VBoxSVC since Host may call
9638 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
9639 * produce an inter-process dead-lock otherwise. */
9640 alock.release();
9641
9642 mControl->DetachAllUSBDevices(aDone);
9643}
9644
9645/**
9646 * @note Locks this object for writing.
9647 */
9648void Console::i_processRemoteUSBDevices(uint32_t u32ClientId, VRDEUSBDEVICEDESC *pDevList, uint32_t cbDevList, bool fDescExt)
9649{
9650 LogFlowThisFuncEnter();
9651 LogFlowThisFunc(("u32ClientId = %d, pDevList=%p, cbDevList = %d, fDescExt = %d\n",
9652 u32ClientId, pDevList, cbDevList, fDescExt));
9653
9654 AutoCaller autoCaller(this);
9655 if (!autoCaller.isOk())
9656 {
9657 /* Console has been already uninitialized, deny request */
9658 AssertMsgFailed(("Console is already uninitialized\n"));
9659 LogFlowThisFunc(("Console is already uninitialized\n"));
9660 LogFlowThisFuncLeave();
9661 return;
9662 }
9663
9664 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9665
9666 /*
9667 * Mark all existing remote USB devices as dirty.
9668 */
9669 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
9670 it != mRemoteUSBDevices.end();
9671 ++it)
9672 {
9673 (*it)->dirty(true);
9674 }
9675
9676 /*
9677 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
9678 */
9679 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
9680 VRDEUSBDEVICEDESC *e = pDevList;
9681
9682 /* The cbDevList condition must be checked first, because the function can
9683 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
9684 */
9685 while (cbDevList >= 2 && e->oNext)
9686 {
9687 /* Sanitize incoming strings in case they aren't valid UTF-8. */
9688 if (e->oManufacturer)
9689 RTStrPurgeEncoding((char *)e + e->oManufacturer);
9690 if (e->oProduct)
9691 RTStrPurgeEncoding((char *)e + e->oProduct);
9692 if (e->oSerialNumber)
9693 RTStrPurgeEncoding((char *)e + e->oSerialNumber);
9694
9695 LogFlowThisFunc(("vendor %04X, product %04X, name = %s\n",
9696 e->idVendor, e->idProduct,
9697 e->oProduct? (char *)e + e->oProduct: ""));
9698
9699 bool fNewDevice = true;
9700
9701 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
9702 it != mRemoteUSBDevices.end();
9703 ++it)
9704 {
9705 if ((*it)->devId() == e->id
9706 && (*it)->clientId() == u32ClientId)
9707 {
9708 /* The device is already in the list. */
9709 (*it)->dirty(false);
9710 fNewDevice = false;
9711 break;
9712 }
9713 }
9714
9715 if (fNewDevice)
9716 {
9717 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
9718 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""));
9719
9720 /* Create the device object and add the new device to list. */
9721 ComObjPtr<RemoteUSBDevice> pUSBDevice;
9722 pUSBDevice.createObject();
9723 pUSBDevice->init(u32ClientId, e, fDescExt);
9724
9725 mRemoteUSBDevices.push_back(pUSBDevice);
9726
9727 /* Check if the device is ok for current USB filters. */
9728 BOOL fMatched = FALSE;
9729 ULONG fMaskedIfs = 0;
9730
9731 HRESULT hrc = mControl->RunUSBDeviceFilters(pUSBDevice, &fMatched, &fMaskedIfs);
9732
9733 AssertComRC(hrc);
9734
9735 LogFlowThisFunc(("USB filters return %d %#x\n", fMatched, fMaskedIfs));
9736
9737 if (fMatched)
9738 {
9739 alock.release();
9740 hrc = i_onUSBDeviceAttach(pUSBDevice, NULL, fMaskedIfs, Utf8Str());
9741 alock.acquire();
9742
9743 /// @todo (r=dmik) warning reporting subsystem
9744
9745 if (hrc == S_OK)
9746 {
9747 LogFlowThisFunc(("Device attached\n"));
9748 pUSBDevice->captured(true);
9749 }
9750 }
9751 }
9752
9753 if (cbDevList < e->oNext)
9754 {
9755 Log1WarningThisFunc(("cbDevList %d > oNext %d\n", cbDevList, e->oNext));
9756 break;
9757 }
9758
9759 cbDevList -= e->oNext;
9760
9761 e = (VRDEUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
9762 }
9763
9764 /*
9765 * Remove dirty devices, that is those which are not reported by the server anymore.
9766 */
9767 for (;;)
9768 {
9769 ComObjPtr<RemoteUSBDevice> pUSBDevice;
9770
9771 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
9772 while (it != mRemoteUSBDevices.end())
9773 {
9774 if ((*it)->dirty())
9775 {
9776 pUSBDevice = *it;
9777 break;
9778 }
9779
9780 ++it;
9781 }
9782
9783 if (!pUSBDevice)
9784 {
9785 break;
9786 }
9787
9788 USHORT vendorId = 0;
9789 pUSBDevice->COMGETTER(VendorId)(&vendorId);
9790
9791 USHORT productId = 0;
9792 pUSBDevice->COMGETTER(ProductId)(&productId);
9793
9794 Bstr product;
9795 pUSBDevice->COMGETTER(Product)(product.asOutParam());
9796
9797 LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
9798 vendorId, productId, product.raw()));
9799
9800 /* Detach the device from VM. */
9801 if (pUSBDevice->captured())
9802 {
9803 Bstr uuid;
9804 pUSBDevice->COMGETTER(Id)(uuid.asOutParam());
9805 alock.release();
9806 i_onUSBDeviceDetach(uuid.raw(), NULL);
9807 alock.acquire();
9808 }
9809
9810 /* And remove it from the list. */
9811 mRemoteUSBDevices.erase(it);
9812 }
9813
9814 LogFlowThisFuncLeave();
9815}
9816
9817/**
9818 * Progress cancelation callback for fault tolerance VM poweron
9819 */
9820static void faultToleranceProgressCancelCallback(void *pvUser)
9821{
9822 PUVM pUVM = (PUVM)pvUser;
9823
9824 if (pUVM)
9825 FTMR3CancelStandby(pUVM);
9826}
9827
9828/**
9829 * Worker called by VMPowerUpTask::handler to start the VM (also from saved
9830 * state) and track progress.
9831 *
9832 * @param pTask The power up task.
9833 *
9834 * @note Locks the Console object for writing.
9835 */
9836/*static*/
9837void Console::i_powerUpThreadTask(VMPowerUpTask *pTask)
9838{
9839 LogFlowFuncEnter();
9840
9841 AssertReturnVoid(pTask);
9842 AssertReturnVoid(!pTask->mConsole.isNull());
9843 AssertReturnVoid(!pTask->mProgress.isNull());
9844
9845 VirtualBoxBase::initializeComForThread();
9846
9847 HRESULT rc = S_OK;
9848 int vrc = VINF_SUCCESS;
9849
9850 /* Set up a build identifier so that it can be seen from core dumps what
9851 * exact build was used to produce the core. */
9852 static char saBuildID[48];
9853 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%u %s%s%s%s",
9854 "BU", "IL", "DI", "D", RTBldCfgVersion(), RTBldCfgRevision(), "BU", "IL", "DI", "D");
9855
9856 ComObjPtr<Console> pConsole = pTask->mConsole;
9857
9858 /* Note: no need to use AutoCaller because VMPowerUpTask does that */
9859
9860 /* The lock is also used as a signal from the task initiator (which
9861 * releases it only after RTThreadCreate()) that we can start the job */
9862 AutoWriteLock alock(pConsole COMMA_LOCKVAL_SRC_POS);
9863
9864 /* sanity */
9865 Assert(pConsole->mpUVM == NULL);
9866
9867 try
9868 {
9869 // Create the VMM device object, which starts the HGCM thread; do this only
9870 // once for the console, for the pathological case that the same console
9871 // object is used to power up a VM twice.
9872 if (!pConsole->m_pVMMDev)
9873 {
9874 pConsole->m_pVMMDev = new VMMDev(pConsole);
9875 AssertReturnVoid(pConsole->m_pVMMDev);
9876 }
9877
9878 /* wait for auto reset ops to complete so that we can successfully lock
9879 * the attached hard disks by calling LockMedia() below */
9880 for (VMPowerUpTask::ProgressList::const_iterator
9881 it = pTask->hardDiskProgresses.begin();
9882 it != pTask->hardDiskProgresses.end(); ++it)
9883 {
9884 HRESULT rc2 = (*it)->WaitForCompletion(-1);
9885 AssertComRC(rc2);
9886
9887 rc = pTask->mProgress->SetNextOperation(BstrFmt(tr("Disk Image Reset Operation - Immutable Image")).raw(), 1);
9888 AssertComRCReturnVoid(rc);
9889 }
9890
9891 /*
9892 * Lock attached media. This method will also check their accessibility.
9893 * If we're a teleporter, we'll have to postpone this action so we can
9894 * migrate between local processes.
9895 *
9896 * Note! The media will be unlocked automatically by
9897 * SessionMachine::i_setMachineState() when the VM is powered down.
9898 */
9899 if ( !pTask->mTeleporterEnabled
9900 && pTask->mEnmFaultToleranceState != FaultToleranceState_Standby)
9901 {
9902 rc = pConsole->mControl->LockMedia();
9903 if (FAILED(rc)) throw rc;
9904 }
9905
9906 /* Create the VRDP server. In case of headless operation, this will
9907 * also create the framebuffer, required at VM creation.
9908 */
9909 ConsoleVRDPServer *server = pConsole->i_consoleVRDPServer();
9910 Assert(server);
9911
9912 /* Does VRDP server call Console from the other thread?
9913 * Not sure (and can change), so release the lock just in case.
9914 */
9915 alock.release();
9916 vrc = server->Launch();
9917 alock.acquire();
9918
9919 if (vrc != VINF_SUCCESS)
9920 {
9921 Utf8Str errMsg = pConsole->VRDPServerErrorToMsg(vrc);
9922 if ( RT_FAILURE(vrc)
9923 && vrc != VERR_NET_ADDRESS_IN_USE) /* not fatal */
9924 throw i_setErrorStaticBoth(E_FAIL, vrc, errMsg.c_str());
9925 }
9926
9927 ComPtr<IMachine> pMachine = pConsole->i_machine();
9928 ULONG cCpus = 1;
9929 pMachine->COMGETTER(CPUCount)(&cCpus);
9930
9931 /*
9932 * Create the VM
9933 *
9934 * Note! Release the lock since EMT will call Console. It's safe because
9935 * mMachineState is either Starting or Restoring state here.
9936 */
9937 alock.release();
9938
9939 PVM pVM;
9940 vrc = VMR3Create(cCpus,
9941 pConsole->mpVmm2UserMethods,
9942 Console::i_genericVMSetErrorCallback,
9943 &pTask->mErrorMsg,
9944 pTask->mConfigConstructor,
9945 static_cast<Console *>(pConsole),
9946 &pVM, NULL);
9947 alock.acquire();
9948
9949#ifdef VBOX_WITH_AUDIO_VRDE
9950 /* Attach the VRDE audio driver. */
9951 IVRDEServer *pVRDEServer = pConsole->i_getVRDEServer();
9952 if (pVRDEServer)
9953 {
9954 BOOL fVRDEEnabled = FALSE;
9955 rc = pVRDEServer->COMGETTER(Enabled)(&fVRDEEnabled);
9956 AssertComRCReturnVoid(rc);
9957
9958 if ( fVRDEEnabled
9959 && pConsole->mAudioVRDE)
9960 pConsole->mAudioVRDE->doAttachDriverViaEmt(pConsole->mpUVM, &alock);
9961 }
9962#endif
9963
9964 /* Enable client connections to the VRDP server. */
9965 pConsole->i_consoleVRDPServer()->EnableConnections();
9966
9967#ifdef VBOX_WITH_VIDEOREC
9968 BOOL fVideoRecEnabled = FALSE;
9969 rc = pConsole->mMachine->COMGETTER(VideoCaptureEnabled)(&fVideoRecEnabled);
9970 AssertComRCReturnVoid(rc);
9971
9972 if (fVideoRecEnabled)
9973 {
9974 int vrc2 = pConsole->i_videoCaptureEnable(fVideoRecEnabled, &alock);
9975 if (RT_SUCCESS(vrc2))
9976 {
9977 fireVideoCaptureChangedEvent(pConsole->mEventSource);
9978 }
9979 else
9980 LogRel(("VideoRec: Failed with %Rrc on VM power up\n", vrc2));
9981
9982 /** Note: Do not use vrc here, as starting the video recording isn't critical to
9983 * powering up the VM. */
9984 }
9985#endif
9986
9987 if (RT_SUCCESS(vrc))
9988 {
9989 do
9990 {
9991 /*
9992 * Register our load/save state file handlers
9993 */
9994 vrc = SSMR3RegisterExternal(pConsole->mpUVM, sSSMConsoleUnit, 0 /*iInstance*/, sSSMConsoleVer, 0 /* cbGuess */,
9995 NULL, NULL, NULL,
9996 NULL, i_saveStateFileExec, NULL,
9997 NULL, i_loadStateFileExec, NULL,
9998 static_cast<Console *>(pConsole));
9999 AssertRCBreak(vrc);
10000
10001 vrc = static_cast<Console *>(pConsole)->i_getDisplay()->i_registerSSM(pConsole->mpUVM);
10002 AssertRC(vrc);
10003 if (RT_FAILURE(vrc))
10004 break;
10005
10006 /*
10007 * Synchronize debugger settings
10008 */
10009 MachineDebugger *machineDebugger = pConsole->i_getMachineDebugger();
10010 if (machineDebugger)
10011 machineDebugger->i_flushQueuedSettings();
10012
10013 /*
10014 * Shared Folders
10015 */
10016 if (pConsole->m_pVMMDev->isShFlActive())
10017 {
10018 /* Does the code below call Console from the other thread?
10019 * Not sure, so release the lock just in case. */
10020 alock.release();
10021
10022 for (SharedFolderDataMap::const_iterator it = pTask->mSharedFolders.begin();
10023 it != pTask->mSharedFolders.end();
10024 ++it)
10025 {
10026 const SharedFolderData &d = it->second;
10027 rc = pConsole->i_createSharedFolder(it->first, d);
10028 if (FAILED(rc))
10029 {
10030 ErrorInfoKeeper eik;
10031 pConsole->i_atVMRuntimeErrorCallbackF(0, "BrokenSharedFolder",
10032 N_("The shared folder '%s' could not be set up: %ls.\n"
10033 "The shared folder setup will not be complete. It is recommended to power down the virtual "
10034 "machine and fix the shared folder settings while the machine is not running"),
10035 it->first.c_str(), eik.getText().raw());
10036 }
10037 }
10038 if (FAILED(rc))
10039 rc = S_OK; // do not fail with broken shared folders
10040
10041 /* acquire the lock again */
10042 alock.acquire();
10043 }
10044
10045 /* release the lock before a lengthy operation */
10046 alock.release();
10047
10048 /*
10049 * Capture USB devices.
10050 */
10051 rc = pConsole->i_captureUSBDevices(pConsole->mpUVM);
10052 if (FAILED(rc))
10053 {
10054 alock.acquire();
10055 break;
10056 }
10057
10058 /* Load saved state? */
10059 if (pTask->mSavedStateFile.length())
10060 {
10061 LogFlowFunc(("Restoring saved state from '%s'...\n", pTask->mSavedStateFile.c_str()));
10062
10063 vrc = VMR3LoadFromFile(pConsole->mpUVM,
10064 pTask->mSavedStateFile.c_str(),
10065 Console::i_stateProgressCallback,
10066 static_cast<IProgress *>(pTask->mProgress));
10067
10068 if (RT_SUCCESS(vrc))
10069 {
10070 if (pTask->mStartPaused)
10071 /* done */
10072 pConsole->i_setMachineState(MachineState_Paused);
10073 else
10074 {
10075 /* Start/Resume the VM execution */
10076#ifdef VBOX_WITH_EXTPACK
10077 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM);
10078#endif
10079 if (RT_SUCCESS(vrc))
10080 vrc = VMR3Resume(pConsole->mpUVM, VMRESUMEREASON_STATE_RESTORED);
10081 AssertLogRelRC(vrc);
10082 }
10083 }
10084
10085 /* Power off in case we failed loading or resuming the VM */
10086 if (RT_FAILURE(vrc))
10087 {
10088 int vrc2 = VMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
10089#ifdef VBOX_WITH_EXTPACK
10090 pConsole->mptrExtPackManager->i_callAllVmPowerOffHooks(pConsole, pVM);
10091#endif
10092 }
10093 }
10094 else if (pTask->mTeleporterEnabled)
10095 {
10096 /* -> ConsoleImplTeleporter.cpp */
10097 bool fPowerOffOnFailure;
10098 rc = pConsole->i_teleporterTrg(pConsole->mpUVM, pMachine, &pTask->mErrorMsg, pTask->mStartPaused,
10099 pTask->mProgress, &fPowerOffOnFailure);
10100 if (FAILED(rc) && fPowerOffOnFailure)
10101 {
10102 ErrorInfoKeeper eik;
10103 int vrc2 = VMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
10104#ifdef VBOX_WITH_EXTPACK
10105 pConsole->mptrExtPackManager->i_callAllVmPowerOffHooks(pConsole, pVM);
10106#endif
10107 }
10108 }
10109 else if (pTask->mEnmFaultToleranceState != FaultToleranceState_Inactive)
10110 {
10111 /*
10112 * Get the config.
10113 */
10114 ULONG uPort;
10115 rc = pMachine->COMGETTER(FaultTolerancePort)(&uPort);
10116 if (SUCCEEDED(rc))
10117 {
10118 ULONG uInterval;
10119 rc = pMachine->COMGETTER(FaultToleranceSyncInterval)(&uInterval);
10120 if (SUCCEEDED(rc))
10121 {
10122 Bstr bstrAddress;
10123 rc = pMachine->COMGETTER(FaultToleranceAddress)(bstrAddress.asOutParam());
10124 if (SUCCEEDED(rc))
10125 {
10126 Bstr bstrPassword;
10127 rc = pMachine->COMGETTER(FaultTolerancePassword)(bstrPassword.asOutParam());
10128 if (SUCCEEDED(rc))
10129 {
10130 if (pTask->mProgress->i_setCancelCallback(faultToleranceProgressCancelCallback,
10131 pConsole->mpUVM))
10132 {
10133 if (SUCCEEDED(rc))
10134 {
10135 Utf8Str strAddress(bstrAddress);
10136 const char *pszAddress = strAddress.isEmpty() ? NULL : strAddress.c_str();
10137 Utf8Str strPassword(bstrPassword);
10138 const char *pszPassword = strPassword.isEmpty() ? NULL : strPassword.c_str();
10139
10140 /* Power on the FT enabled VM. */
10141#ifdef VBOX_WITH_EXTPACK
10142 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM);
10143#endif
10144 if (RT_SUCCESS(vrc))
10145 vrc = FTMR3PowerOn(pConsole->mpUVM,
10146 pTask->mEnmFaultToleranceState == FaultToleranceState_Master /* fMaster */,
10147 uInterval,
10148 pszAddress,
10149 uPort,
10150 pszPassword);
10151 AssertLogRelRC(vrc);
10152 }
10153 pTask->mProgress->i_setCancelCallback(NULL, NULL);
10154 }
10155 else
10156 rc = E_FAIL;
10157
10158 }
10159 }
10160 }
10161 }
10162 }
10163 else if (pTask->mStartPaused)
10164 /* done */
10165 pConsole->i_setMachineState(MachineState_Paused);
10166 else
10167 {
10168 /* Power on the VM (i.e. start executing) */
10169#ifdef VBOX_WITH_EXTPACK
10170 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM);
10171#endif
10172 if (RT_SUCCESS(vrc))
10173 vrc = VMR3PowerOn(pConsole->mpUVM);
10174 AssertLogRelRC(vrc);
10175 }
10176
10177 /* acquire the lock again */
10178 alock.acquire();
10179 }
10180 while (0);
10181
10182 /* On failure, destroy the VM */
10183 if (FAILED(rc) || RT_FAILURE(vrc))
10184 {
10185 /* preserve existing error info */
10186 ErrorInfoKeeper eik;
10187
10188 /* powerDown() will call VMR3Destroy() and do all necessary
10189 * cleanup (VRDP, USB devices) */
10190 alock.release();
10191 HRESULT rc2 = pConsole->i_powerDown();
10192 alock.acquire();
10193 AssertComRC(rc2);
10194 }
10195 else
10196 {
10197 /*
10198 * Deregister the VMSetError callback. This is necessary as the
10199 * pfnVMAtError() function passed to VMR3Create() is supposed to
10200 * be sticky but our error callback isn't.
10201 */
10202 alock.release();
10203 VMR3AtErrorDeregister(pConsole->mpUVM, Console::i_genericVMSetErrorCallback, &pTask->mErrorMsg);
10204 /** @todo register another VMSetError callback? */
10205 alock.acquire();
10206 }
10207 }
10208 else
10209 {
10210 /*
10211 * If VMR3Create() failed it has released the VM memory.
10212 */
10213 VMR3ReleaseUVM(pConsole->mpUVM);
10214 pConsole->mpUVM = NULL;
10215 }
10216
10217 if (SUCCEEDED(rc) && RT_FAILURE(vrc))
10218 {
10219 /* If VMR3Create() or one of the other calls in this function fail,
10220 * an appropriate error message has been set in pTask->mErrorMsg.
10221 * However since that happens via a callback, the rc status code in
10222 * this function is not updated.
10223 */
10224 if (!pTask->mErrorMsg.length())
10225 {
10226 /* If the error message is not set but we've got a failure,
10227 * convert the VBox status code into a meaningful error message.
10228 * This becomes unused once all the sources of errors set the
10229 * appropriate error message themselves.
10230 */
10231 AssertMsgFailed(("Missing error message during powerup for status code %Rrc\n", vrc));
10232 pTask->mErrorMsg = Utf8StrFmt(tr("Failed to start VM execution (%Rrc)"), vrc);
10233 }
10234
10235 /* Set the error message as the COM error.
10236 * Progress::notifyComplete() will pick it up later. */
10237 throw i_setErrorStaticBoth(E_FAIL, vrc, pTask->mErrorMsg.c_str());
10238 }
10239 }
10240 catch (HRESULT aRC) { rc = aRC; }
10241
10242 if ( pConsole->mMachineState == MachineState_Starting
10243 || pConsole->mMachineState == MachineState_Restoring
10244 || pConsole->mMachineState == MachineState_TeleportingIn
10245 )
10246 {
10247 /* We are still in the Starting/Restoring state. This means one of:
10248 *
10249 * 1) we failed before VMR3Create() was called;
10250 * 2) VMR3Create() failed.
10251 *
10252 * In both cases, there is no need to call powerDown(), but we still
10253 * need to go back to the PoweredOff/Saved state. Reuse
10254 * vmstateChangeCallback() for that purpose.
10255 */
10256
10257 /* preserve existing error info */
10258 ErrorInfoKeeper eik;
10259
10260 Assert(pConsole->mpUVM == NULL);
10261 i_vmstateChangeCallback(NULL, VMSTATE_TERMINATED, VMSTATE_CREATING, pConsole);
10262 }
10263
10264 /*
10265 * Evaluate the final result. Note that the appropriate mMachineState value
10266 * is already set by vmstateChangeCallback() in all cases.
10267 */
10268
10269 /* release the lock, don't need it any more */
10270 alock.release();
10271
10272 if (SUCCEEDED(rc))
10273 {
10274 /* Notify the progress object of the success */
10275 pTask->mProgress->i_notifyComplete(S_OK);
10276 }
10277 else
10278 {
10279 /* The progress object will fetch the current error info */
10280 pTask->mProgress->i_notifyComplete(rc);
10281 LogRel(("Power up failed (vrc=%Rrc, rc=%Rhrc (%#08X))\n", vrc, rc, rc));
10282 }
10283
10284 /* Notify VBoxSVC and any waiting openRemoteSession progress object. */
10285 pConsole->mControl->EndPowerUp(rc);
10286
10287#if defined(RT_OS_WINDOWS)
10288 /* uninitialize COM */
10289 CoUninitialize();
10290#endif
10291
10292 LogFlowFuncLeave();
10293}
10294
10295
10296/**
10297 * Reconfigures a medium attachment (part of taking or deleting an online snapshot).
10298 *
10299 * @param pThis Reference to the console object.
10300 * @param pUVM The VM handle.
10301 * @param pcszDevice The name of the controller type.
10302 * @param uInstance The instance of the controller.
10303 * @param enmBus The storage bus type of the controller.
10304 * @param fUseHostIOCache Use the host I/O cache (disable async I/O).
10305 * @param fBuiltinIOCache Use the builtin I/O cache.
10306 * @param fInsertDiskIntegrityDrv Flag whether to insert the disk integrity driver into the chain
10307 * for additionalk debugging aids.
10308 * @param fSetupMerge Whether to set up a medium merge
10309 * @param uMergeSource Merge source image index
10310 * @param uMergeTarget Merge target image index
10311 * @param aMediumAtt The medium attachment.
10312 * @param aMachineState The current machine state.
10313 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
10314 * @return VBox status code.
10315 */
10316/* static */
10317DECLCALLBACK(int) Console::i_reconfigureMediumAttachment(Console *pThis,
10318 PUVM pUVM,
10319 const char *pcszDevice,
10320 unsigned uInstance,
10321 StorageBus_T enmBus,
10322 bool fUseHostIOCache,
10323 bool fBuiltinIOCache,
10324 bool fInsertDiskIntegrityDrv,
10325 bool fSetupMerge,
10326 unsigned uMergeSource,
10327 unsigned uMergeTarget,
10328 IMediumAttachment *aMediumAtt,
10329 MachineState_T aMachineState,
10330 HRESULT *phrc)
10331{
10332 LogFlowFunc(("pUVM=%p aMediumAtt=%p phrc=%p\n", pUVM, aMediumAtt, phrc));
10333
10334 HRESULT hrc;
10335 Bstr bstr;
10336 *phrc = S_OK;
10337#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%Rhrc (%#x)\n", hrc, hrc)); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
10338
10339 /* Ignore attachments other than hard disks, since at the moment they are
10340 * not subject to snapshotting in general. */
10341 DeviceType_T lType;
10342 hrc = aMediumAtt->COMGETTER(Type)(&lType); H();
10343 if (lType != DeviceType_HardDisk)
10344 return VINF_SUCCESS;
10345
10346 /* Update the device instance configuration. */
10347 int rc = pThis->i_configMediumAttachment(pcszDevice,
10348 uInstance,
10349 enmBus,
10350 fUseHostIOCache,
10351 fBuiltinIOCache,
10352 fInsertDiskIntegrityDrv,
10353 fSetupMerge,
10354 uMergeSource,
10355 uMergeTarget,
10356 aMediumAtt,
10357 aMachineState,
10358 phrc,
10359 true /* fAttachDetach */,
10360 false /* fForceUnmount */,
10361 false /* fHotplug */,
10362 pUVM,
10363 NULL /* paLedDevType */,
10364 NULL /* ppLunL0)*/);
10365 if (RT_FAILURE(rc))
10366 {
10367 AssertMsgFailed(("rc=%Rrc\n", rc));
10368 return rc;
10369 }
10370
10371#undef H
10372
10373 LogFlowFunc(("Returns success\n"));
10374 return VINF_SUCCESS;
10375}
10376
10377/**
10378 * Thread for powering down the Console.
10379 *
10380 * @param pTask The power down task.
10381 *
10382 * @note Locks the Console object for writing.
10383 */
10384/*static*/
10385void Console::i_powerDownThreadTask(VMPowerDownTask *pTask)
10386{
10387 int rc = VINF_SUCCESS; /* only used in assertion */
10388 LogFlowFuncEnter();
10389 try
10390 {
10391 if (pTask->isOk() == false)
10392 rc = VERR_GENERAL_FAILURE;
10393
10394 const ComObjPtr<Console> &that = pTask->mConsole;
10395
10396 /* Note: no need to use AutoCaller to protect Console because VMTask does
10397 * that */
10398
10399 /* wait until the method tat started us returns */
10400 AutoWriteLock thatLock(that COMMA_LOCKVAL_SRC_POS);
10401
10402 /* release VM caller to avoid the powerDown() deadlock */
10403 pTask->releaseVMCaller();
10404
10405 thatLock.release();
10406
10407 that->i_powerDown(pTask->mServerProgress);
10408
10409 /* complete the operation */
10410 that->mControl->EndPoweringDown(S_OK, Bstr().raw());
10411
10412 }
10413 catch (const std::exception &e)
10414 {
10415 AssertMsgFailed(("Exception %s was caught, rc=%Rrc\n", e.what(), rc));
10416 NOREF(e); NOREF(rc);
10417 }
10418
10419 LogFlowFuncLeave();
10420}
10421
10422/**
10423 * @interface_method_impl{VMM2USERMETHODS,pfnSaveState}
10424 */
10425/*static*/ DECLCALLBACK(int)
10426Console::i_vmm2User_SaveState(PCVMM2USERMETHODS pThis, PUVM pUVM)
10427{
10428 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
10429 NOREF(pUVM);
10430
10431 /*
10432 * For now, just call SaveState. We should probably try notify the GUI so
10433 * it can pop up a progress object and stuff. The progress object created
10434 * by the call isn't returned to anyone and thus gets updated without
10435 * anyone noticing it.
10436 */
10437 ComPtr<IProgress> pProgress;
10438 HRESULT hrc = pConsole->mMachine->SaveState(pProgress.asOutParam());
10439 return SUCCEEDED(hrc) ? VINF_SUCCESS : Global::vboxStatusCodeFromCOM(hrc);
10440}
10441
10442/**
10443 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtInit}
10444 */
10445/*static*/ DECLCALLBACK(void)
10446Console::i_vmm2User_NotifyEmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
10447{
10448 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
10449 VirtualBoxBase::initializeComForThread();
10450}
10451
10452/**
10453 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtTerm}
10454 */
10455/*static*/ DECLCALLBACK(void)
10456Console::i_vmm2User_NotifyEmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
10457{
10458 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
10459 VirtualBoxBase::uninitializeComForThread();
10460}
10461
10462/**
10463 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtInit}
10464 */
10465/*static*/ DECLCALLBACK(void)
10466Console::i_vmm2User_NotifyPdmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM)
10467{
10468 NOREF(pThis); NOREF(pUVM);
10469 VirtualBoxBase::initializeComForThread();
10470}
10471
10472/**
10473 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtTerm}
10474 */
10475/*static*/ DECLCALLBACK(void)
10476Console::i_vmm2User_NotifyPdmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM)
10477{
10478 NOREF(pThis); NOREF(pUVM);
10479 VirtualBoxBase::uninitializeComForThread();
10480}
10481
10482/**
10483 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyResetTurnedIntoPowerOff}
10484 */
10485/*static*/ DECLCALLBACK(void)
10486Console::i_vmm2User_NotifyResetTurnedIntoPowerOff(PCVMM2USERMETHODS pThis, PUVM pUVM)
10487{
10488 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
10489 NOREF(pUVM);
10490
10491 pConsole->mfPowerOffCausedByReset = true;
10492}
10493
10494/**
10495 * @interface_method_impl{VMM2USERMETHODS,pfnQueryGenericObject}
10496 */
10497/*static*/ DECLCALLBACK(void *)
10498Console::i_vmm2User_QueryGenericObject(PCVMM2USERMETHODS pThis, PUVM pUVM, PCRTUUID pUuid)
10499{
10500 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
10501 NOREF(pUVM);
10502
10503 /* To simplify comparison we copy the UUID into a com::Guid object. */
10504 com::Guid const UuidCopy(*pUuid);
10505
10506 if (UuidCopy == COM_IIDOF(IConsole))
10507 {
10508 IConsole *pIConsole = static_cast<IConsole *>(pConsole);
10509 return pIConsole;
10510 }
10511
10512 if (UuidCopy == COM_IIDOF(IMachine))
10513 {
10514 IMachine *pIMachine = pConsole->mMachine;
10515 return pIMachine;
10516 }
10517
10518 if (UuidCopy == COM_IIDOF(ISnapshot))
10519 return ((MYVMM2USERMETHODS *)pThis)->pISnapshot;
10520
10521 return NULL;
10522}
10523
10524
10525/**
10526 * @interface_method_impl{PDMISECKEY,pfnKeyRetain}
10527 */
10528/*static*/ DECLCALLBACK(int)
10529Console::i_pdmIfSecKey_KeyRetain(PPDMISECKEY pInterface, const char *pszId, const uint8_t **ppbKey,
10530 size_t *pcbKey)
10531{
10532 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
10533
10534 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
10535 SecretKey *pKey = NULL;
10536
10537 int rc = pConsole->m_pKeyStore->retainSecretKey(Utf8Str(pszId), &pKey);
10538 if (RT_SUCCESS(rc))
10539 {
10540 *ppbKey = (const uint8_t *)pKey->getKeyBuffer();
10541 *pcbKey = pKey->getKeySize();
10542 }
10543
10544 return rc;
10545}
10546
10547/**
10548 * @interface_method_impl{PDMISECKEY,pfnKeyRelease}
10549 */
10550/*static*/ DECLCALLBACK(int)
10551Console::i_pdmIfSecKey_KeyRelease(PPDMISECKEY pInterface, const char *pszId)
10552{
10553 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
10554
10555 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
10556 return pConsole->m_pKeyStore->releaseSecretKey(Utf8Str(pszId));
10557}
10558
10559/**
10560 * @interface_method_impl{PDMISECKEY,pfnPasswordRetain}
10561 */
10562/*static*/ DECLCALLBACK(int)
10563Console::i_pdmIfSecKey_PasswordRetain(PPDMISECKEY pInterface, const char *pszId, const char **ppszPassword)
10564{
10565 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
10566
10567 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
10568 SecretKey *pKey = NULL;
10569
10570 int rc = pConsole->m_pKeyStore->retainSecretKey(Utf8Str(pszId), &pKey);
10571 if (RT_SUCCESS(rc))
10572 *ppszPassword = (const char *)pKey->getKeyBuffer();
10573
10574 return rc;
10575}
10576
10577/**
10578 * @interface_method_impl{PDMISECKEY,pfnPasswordRelease}
10579 */
10580/*static*/ DECLCALLBACK(int)
10581Console::i_pdmIfSecKey_PasswordRelease(PPDMISECKEY pInterface, const char *pszId)
10582{
10583 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
10584
10585 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
10586 return pConsole->m_pKeyStore->releaseSecretKey(Utf8Str(pszId));
10587}
10588
10589/**
10590 * @interface_method_impl{PDMISECKEYHLP,pfnKeyMissingNotify}
10591 */
10592/*static*/ DECLCALLBACK(int)
10593Console::i_pdmIfSecKeyHlp_KeyMissingNotify(PPDMISECKEYHLP pInterface)
10594{
10595 Console *pConsole = ((MYPDMISECKEYHLP *)pInterface)->pConsole;
10596
10597 /* Set guest property only, the VM is paused in the media driver calling us. */
10598 pConsole->mMachine->DeleteGuestProperty(Bstr("/VirtualBox/HostInfo/DekMissing").raw());
10599 pConsole->mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/DekMissing").raw(),
10600 Bstr("1").raw(), Bstr("RDONLYGUEST").raw());
10601 pConsole->mMachine->SaveSettings();
10602
10603 return VINF_SUCCESS;
10604}
10605
10606
10607
10608/**
10609 * The Main status driver instance data.
10610 */
10611typedef struct DRVMAINSTATUS
10612{
10613 /** The LED connectors. */
10614 PDMILEDCONNECTORS ILedConnectors;
10615 /** Pointer to the LED ports interface above us. */
10616 PPDMILEDPORTS pLedPorts;
10617 /** Pointer to the array of LED pointers. */
10618 PPDMLED *papLeds;
10619 /** The unit number corresponding to the first entry in the LED array. */
10620 RTUINT iFirstLUN;
10621 /** The unit number corresponding to the last entry in the LED array.
10622 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
10623 RTUINT iLastLUN;
10624 /** Pointer to the driver instance. */
10625 PPDMDRVINS pDrvIns;
10626 /** The Media Notify interface. */
10627 PDMIMEDIANOTIFY IMediaNotify;
10628 /** Map for translating PDM storage controller/LUN information to
10629 * IMediumAttachment references. */
10630 Console::MediumAttachmentMap *pmapMediumAttachments;
10631 /** Device name+instance for mapping */
10632 char *pszDeviceInstance;
10633 /** Pointer to the Console object, for driver triggered activities. */
10634 Console *pConsole;
10635} DRVMAINSTATUS, *PDRVMAINSTATUS;
10636
10637
10638/**
10639 * Notification about a unit which have been changed.
10640 *
10641 * The driver must discard any pointers to data owned by
10642 * the unit and requery it.
10643 *
10644 * @param pInterface Pointer to the interface structure containing the called function pointer.
10645 * @param iLUN The unit number.
10646 */
10647DECLCALLBACK(void) Console::i_drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
10648{
10649 PDRVMAINSTATUS pThis = RT_FROM_MEMBER(pInterface, DRVMAINSTATUS, ILedConnectors);
10650 if (iLUN >= pThis->iFirstLUN && iLUN <= pThis->iLastLUN)
10651 {
10652 PPDMLED pLed;
10653 int rc = pThis->pLedPorts->pfnQueryStatusLed(pThis->pLedPorts, iLUN, &pLed);
10654 if (RT_FAILURE(rc))
10655 pLed = NULL;
10656 ASMAtomicWritePtr(&pThis->papLeds[iLUN - pThis->iFirstLUN], pLed);
10657 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
10658 }
10659}
10660
10661
10662/**
10663 * Notification about a medium eject.
10664 *
10665 * @returns VBox status code.
10666 * @param pInterface Pointer to the interface structure containing the called function pointer.
10667 * @param uLUN The unit number.
10668 */
10669DECLCALLBACK(int) Console::i_drvStatus_MediumEjected(PPDMIMEDIANOTIFY pInterface, unsigned uLUN)
10670{
10671 PDRVMAINSTATUS pThis = RT_FROM_MEMBER(pInterface, DRVMAINSTATUS, IMediaNotify);
10672 LogFunc(("uLUN=%d\n", uLUN));
10673 if (pThis->pmapMediumAttachments)
10674 {
10675 AutoWriteLock alock(pThis->pConsole COMMA_LOCKVAL_SRC_POS);
10676
10677 ComPtr<IMediumAttachment> pMediumAtt;
10678 Utf8Str devicePath = Utf8StrFmt("%s/LUN#%u", pThis->pszDeviceInstance, uLUN);
10679 Console::MediumAttachmentMap::const_iterator end = pThis->pmapMediumAttachments->end();
10680 Console::MediumAttachmentMap::const_iterator it = pThis->pmapMediumAttachments->find(devicePath);
10681 if (it != end)
10682 pMediumAtt = it->second;
10683 Assert(!pMediumAtt.isNull());
10684 if (!pMediumAtt.isNull())
10685 {
10686 IMedium *pMedium = NULL;
10687 HRESULT rc = pMediumAtt->COMGETTER(Medium)(&pMedium);
10688 AssertComRC(rc);
10689 if (SUCCEEDED(rc) && pMedium)
10690 {
10691 BOOL fHostDrive = FALSE;
10692 rc = pMedium->COMGETTER(HostDrive)(&fHostDrive);
10693 AssertComRC(rc);
10694 if (!fHostDrive)
10695 {
10696 alock.release();
10697
10698 ComPtr<IMediumAttachment> pNewMediumAtt;
10699 rc = pThis->pConsole->mControl->EjectMedium(pMediumAtt, pNewMediumAtt.asOutParam());
10700 if (SUCCEEDED(rc))
10701 {
10702 pThis->pConsole->mMachine->SaveSettings();
10703 fireMediumChangedEvent(pThis->pConsole->mEventSource, pNewMediumAtt);
10704 }
10705
10706 alock.acquire();
10707 if (pNewMediumAtt != pMediumAtt)
10708 {
10709 pThis->pmapMediumAttachments->erase(devicePath);
10710 pThis->pmapMediumAttachments->insert(std::make_pair(devicePath, pNewMediumAtt));
10711 }
10712 }
10713 }
10714 }
10715 }
10716 return VINF_SUCCESS;
10717}
10718
10719
10720/**
10721 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
10722 */
10723DECLCALLBACK(void *) Console::i_drvStatus_QueryInterface(PPDMIBASE pInterface, const char *pszIID)
10724{
10725 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
10726 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10727 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
10728 PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDCONNECTORS, &pThis->ILedConnectors);
10729 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIANOTIFY, &pThis->IMediaNotify);
10730 return NULL;
10731}
10732
10733
10734/**
10735 * Destruct a status driver instance.
10736 *
10737 * @returns VBox status code.
10738 * @param pDrvIns The driver instance data.
10739 */
10740DECLCALLBACK(void) Console::i_drvStatus_Destruct(PPDMDRVINS pDrvIns)
10741{
10742 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
10743 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10744 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
10745
10746 if (pThis->papLeds)
10747 {
10748 unsigned iLed = pThis->iLastLUN - pThis->iFirstLUN + 1;
10749 while (iLed-- > 0)
10750 ASMAtomicWriteNullPtr(&pThis->papLeds[iLed]);
10751 }
10752}
10753
10754
10755/**
10756 * Construct a status driver instance.
10757 *
10758 * @copydoc FNPDMDRVCONSTRUCT
10759 */
10760DECLCALLBACK(int) Console::i_drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
10761{
10762 RT_NOREF(fFlags);
10763 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
10764 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10765 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
10766
10767 /*
10768 * Validate configuration.
10769 */
10770 if (!CFGMR3AreValuesValid(pCfg, "papLeds\0pmapMediumAttachments\0DeviceInstance\0pConsole\0First\0Last\0"))
10771 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
10772 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
10773 ("Configuration error: Not possible to attach anything to this driver!\n"),
10774 VERR_PDM_DRVINS_NO_ATTACH);
10775
10776 /*
10777 * Data.
10778 */
10779 pDrvIns->IBase.pfnQueryInterface = Console::i_drvStatus_QueryInterface;
10780 pThis->ILedConnectors.pfnUnitChanged = Console::i_drvStatus_UnitChanged;
10781 pThis->IMediaNotify.pfnEjected = Console::i_drvStatus_MediumEjected;
10782 pThis->pDrvIns = pDrvIns;
10783 pThis->pszDeviceInstance = NULL;
10784
10785 /*
10786 * Read config.
10787 */
10788 int rc = CFGMR3QueryPtr(pCfg, "papLeds", (void **)&pThis->papLeds);
10789 if (RT_FAILURE(rc))
10790 {
10791 AssertMsgFailed(("Configuration error: Failed to query the \"papLeds\" value! rc=%Rrc\n", rc));
10792 return rc;
10793 }
10794
10795 rc = CFGMR3QueryPtrDef(pCfg, "pmapMediumAttachments", (void **)&pThis->pmapMediumAttachments, NULL);
10796 if (RT_FAILURE(rc))
10797 {
10798 AssertMsgFailed(("Configuration error: Failed to query the \"pmapMediumAttachments\" value! rc=%Rrc\n", rc));
10799 return rc;
10800 }
10801 if (pThis->pmapMediumAttachments)
10802 {
10803 rc = CFGMR3QueryStringAlloc(pCfg, "DeviceInstance", &pThis->pszDeviceInstance);
10804 if (RT_FAILURE(rc))
10805 {
10806 AssertMsgFailed(("Configuration error: Failed to query the \"DeviceInstance\" value! rc=%Rrc\n", rc));
10807 return rc;
10808 }
10809 rc = CFGMR3QueryPtr(pCfg, "pConsole", (void **)&pThis->pConsole);
10810 if (RT_FAILURE(rc))
10811 {
10812 AssertMsgFailed(("Configuration error: Failed to query the \"pConsole\" value! rc=%Rrc\n", rc));
10813 return rc;
10814 }
10815 }
10816
10817 rc = CFGMR3QueryU32(pCfg, "First", &pThis->iFirstLUN);
10818 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
10819 pThis->iFirstLUN = 0;
10820 else if (RT_FAILURE(rc))
10821 {
10822 AssertMsgFailed(("Configuration error: Failed to query the \"First\" value! rc=%Rrc\n", rc));
10823 return rc;
10824 }
10825
10826 rc = CFGMR3QueryU32(pCfg, "Last", &pThis->iLastLUN);
10827 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
10828 pThis->iLastLUN = 0;
10829 else if (RT_FAILURE(rc))
10830 {
10831 AssertMsgFailed(("Configuration error: Failed to query the \"Last\" value! rc=%Rrc\n", rc));
10832 return rc;
10833 }
10834 if (pThis->iFirstLUN > pThis->iLastLUN)
10835 {
10836 AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pThis->iFirstLUN, pThis->iLastLUN));
10837 return VERR_GENERAL_FAILURE;
10838 }
10839
10840 /*
10841 * Get the ILedPorts interface of the above driver/device and
10842 * query the LEDs we want.
10843 */
10844 pThis->pLedPorts = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMILEDPORTS);
10845 AssertMsgReturn(pThis->pLedPorts, ("Configuration error: No led ports interface above!\n"),
10846 VERR_PDM_MISSING_INTERFACE_ABOVE);
10847
10848 for (unsigned i = pThis->iFirstLUN; i <= pThis->iLastLUN; ++i)
10849 Console::i_drvStatus_UnitChanged(&pThis->ILedConnectors, i);
10850
10851 return VINF_SUCCESS;
10852}
10853
10854
10855/**
10856 * Console status driver (LED) registration record.
10857 */
10858const PDMDRVREG Console::DrvStatusReg =
10859{
10860 /* u32Version */
10861 PDM_DRVREG_VERSION,
10862 /* szName */
10863 "MainStatus",
10864 /* szRCMod */
10865 "",
10866 /* szR0Mod */
10867 "",
10868 /* pszDescription */
10869 "Main status driver (Main as in the API).",
10870 /* fFlags */
10871 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
10872 /* fClass. */
10873 PDM_DRVREG_CLASS_STATUS,
10874 /* cMaxInstances */
10875 ~0U,
10876 /* cbInstance */
10877 sizeof(DRVMAINSTATUS),
10878 /* pfnConstruct */
10879 Console::i_drvStatus_Construct,
10880 /* pfnDestruct */
10881 Console::i_drvStatus_Destruct,
10882 /* pfnRelocate */
10883 NULL,
10884 /* pfnIOCtl */
10885 NULL,
10886 /* pfnPowerOn */
10887 NULL,
10888 /* pfnReset */
10889 NULL,
10890 /* pfnSuspend */
10891 NULL,
10892 /* pfnResume */
10893 NULL,
10894 /* pfnAttach */
10895 NULL,
10896 /* pfnDetach */
10897 NULL,
10898 /* pfnPowerOff */
10899 NULL,
10900 /* pfnSoftReset */
10901 NULL,
10902 /* u32EndVersion */
10903 PDM_DRVREG_VERSION
10904};
10905
10906
10907
10908/* 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