VirtualBox

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

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

Main/NvramStore,FE/VBoxManage: Allow multiple NVRAM states (UEFI,TPM,etc.) to exist for a VM and and manage them in a central place. This allows to collect them in a single tar archive and provide a single interface to get access to the individual states (work in progress), bugref:10098

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

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