VirtualBox

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

最後變更 在這個檔案從93015是 92996,由 vboxsync 提交於 3 年 前

virtio-net works on linux in local testing, and virtio-scsi works on windows. Integrating the switchover to make DevVirtioNet_1_0.cpp the 'virtio-net' option in the Virtual Network Controller list.

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

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