VirtualBox

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

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

VideoRec: Overhauled configuration handling to also support audio configuration changes.

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