VirtualBox

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

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

Main/ConsoleImpl: some tiny cleanups.

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