VirtualBox

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

Last change on this file since 93410 was 93410, checked in by vboxsync, 3 years ago

Main: Generate enum value to string conversion functions for the API. Use these for logging instead of the Global::stringify* ones as they are untranslated, the Global:: ones are for use in error message when translated enum value names are desired (questionable).

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette