VirtualBox

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

Last change on this file since 80662 was 80662, checked in by vboxsync, 5 years ago

Shared Clipboard: Renaming (SHAREDCLIPBOARD -> SHCL and VBOXCLIPBOARD -> SHCL).

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