VirtualBox

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

Last change on this file since 65434 was 65434, checked in by vboxsync, 8 years ago

Docs.

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

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