VirtualBox

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

Last change on this file since 68944 was 68944, checked in by vboxsync, 7 years ago

VideoRec/Main: Implemented support for attaching + detaching the video recording audio driver on runtime, e.g. only when recording something.

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

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