VirtualBox

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

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

Build fix.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 351.9 KB
Line 
1/* $Id: ConsoleImpl.cpp 68801 2017-09-20 10:54:50Z 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# ifdef VBOX_WITH_AUDIO_VIDEOREC
5506 VIDEORECFEATURES fFeatures = mDisplay->i_videoCaptureGetEnabled();
5507
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,
5532 RT_BOOL(fFeatures & VIDEORECFEATURE_AUDIO));
5533 if (RT_FAILURE(rc2))
5534 LogRel(("VideoRec: Failed to %s audio recording, rc=%Rrc\n",
5535 fFeatures & VIDEORECFEATURE_AUDIO ? "enable" : "disable", ulLUN, rc2));
5536 }
5537
5538 break; /* Driver found, no need to continue. */
5539 }
5540 }
5541 }
5542# endif /* VBOX_WITH_AUDIO_VIDEOREC */
5543
5544 if (!mDisplay->i_videoCaptureStarted())
5545 {
5546 vrc = mDisplay->i_videoCaptureStart();
5547 if (RT_FAILURE(vrc))
5548 rc = setError(E_FAIL, tr("Unable to start video capturing (%Rrc)"), vrc);
5549 }
5550 else
5551 mDisplay->i_videoCaptureStop();
5552 }
5553 else
5554 rc = setError(E_FAIL, tr("Unable to set screens for capturing (%Rrc)"), vrc);
5555 }
5556
5557 ptrVM.release();
5558 }
5559#endif /* VBOX_WITH_VIDEOREC */
5560
5561 /* notify console callbacks on success */
5562 if (SUCCEEDED(rc))
5563 {
5564 alock.release();
5565 fireVideoCaptureChangedEvent(mEventSource);
5566 }
5567
5568 return rc;
5569}
5570
5571/**
5572 * Called by IInternalSessionControl::OnUSBControllerChange().
5573 */
5574HRESULT Console::i_onUSBControllerChange()
5575{
5576 LogFlowThisFunc(("\n"));
5577
5578 AutoCaller autoCaller(this);
5579 AssertComRCReturnRC(autoCaller.rc());
5580
5581 fireUSBControllerChangedEvent(mEventSource);
5582
5583 return S_OK;
5584}
5585
5586/**
5587 * Called by IInternalSessionControl::OnSharedFolderChange().
5588 *
5589 * @note Locks this object for writing.
5590 */
5591HRESULT Console::i_onSharedFolderChange(BOOL aGlobal)
5592{
5593 LogFlowThisFunc(("aGlobal=%RTbool\n", aGlobal));
5594
5595 AutoCaller autoCaller(this);
5596 AssertComRCReturnRC(autoCaller.rc());
5597
5598 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5599
5600 HRESULT rc = i_fetchSharedFolders(aGlobal);
5601
5602 /* notify console callbacks on success */
5603 if (SUCCEEDED(rc))
5604 {
5605 alock.release();
5606 fireSharedFolderChangedEvent(mEventSource, aGlobal ? (Scope_T)Scope_Global : (Scope_T)Scope_Machine);
5607 }
5608
5609 return rc;
5610}
5611
5612/**
5613 * Called by IInternalSessionControl::OnUSBDeviceAttach() or locally by
5614 * processRemoteUSBDevices() after IInternalMachineControl::RunUSBDeviceFilters()
5615 * returns TRUE for a given remote USB device.
5616 *
5617 * @return S_OK if the device was attached to the VM.
5618 * @return failure if not attached.
5619 *
5620 * @param aDevice The device in question.
5621 * @param aError Error information.
5622 * @param aMaskedIfs The interfaces to hide from the guest.
5623 * @param aCaptureFilename File name where to store the USB traffic.
5624 *
5625 * @note Locks this object for writing.
5626 */
5627HRESULT Console::i_onUSBDeviceAttach(IUSBDevice *aDevice, IVirtualBoxErrorInfo *aError, ULONG aMaskedIfs,
5628 const Utf8Str &aCaptureFilename)
5629{
5630#ifdef VBOX_WITH_USB
5631 LogFlowThisFunc(("aDevice=%p aError=%p\n", aDevice, aError));
5632
5633 AutoCaller autoCaller(this);
5634 ComAssertComRCRetRC(autoCaller.rc());
5635
5636 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5637
5638 /* Get the VM pointer (we don't need error info, since it's a callback). */
5639 SafeVMPtrQuiet ptrVM(this);
5640 if (!ptrVM.isOk())
5641 {
5642 /* The VM may be no more operational when this message arrives
5643 * (e.g. it may be Saving or Stopping or just PoweredOff) --
5644 * autoVMCaller.rc() will return a failure in this case. */
5645 LogFlowThisFunc(("Attach request ignored (mMachineState=%d).\n",
5646 mMachineState));
5647 return ptrVM.rc();
5648 }
5649
5650 if (aError != NULL)
5651 {
5652 /* notify callbacks about the error */
5653 alock.release();
5654 i_onUSBDeviceStateChange(aDevice, true /* aAttached */, aError);
5655 return S_OK;
5656 }
5657
5658 /* Don't proceed unless there's at least one USB hub. */
5659 if (!PDMR3UsbHasHub(ptrVM.rawUVM()))
5660 {
5661 LogFlowThisFunc(("Attach request ignored (no USB controller).\n"));
5662 return E_FAIL;
5663 }
5664
5665 alock.release();
5666 HRESULT rc = i_attachUSBDevice(aDevice, aMaskedIfs, aCaptureFilename);
5667 if (FAILED(rc))
5668 {
5669 /* take the current error info */
5670 com::ErrorInfoKeeper eik;
5671 /* the error must be a VirtualBoxErrorInfo instance */
5672 ComPtr<IVirtualBoxErrorInfo> pError = eik.takeError();
5673 Assert(!pError.isNull());
5674 if (!pError.isNull())
5675 {
5676 /* notify callbacks about the error */
5677 i_onUSBDeviceStateChange(aDevice, true /* aAttached */, pError);
5678 }
5679 }
5680
5681 return rc;
5682
5683#else /* !VBOX_WITH_USB */
5684 return E_FAIL;
5685#endif /* !VBOX_WITH_USB */
5686}
5687
5688/**
5689 * Called by IInternalSessionControl::OnUSBDeviceDetach() and locally by
5690 * processRemoteUSBDevices().
5691 *
5692 * @note Locks this object for writing.
5693 */
5694HRESULT Console::i_onUSBDeviceDetach(IN_BSTR aId,
5695 IVirtualBoxErrorInfo *aError)
5696{
5697#ifdef VBOX_WITH_USB
5698 Guid Uuid(aId);
5699 LogFlowThisFunc(("aId={%RTuuid} aError=%p\n", Uuid.raw(), aError));
5700
5701 AutoCaller autoCaller(this);
5702 AssertComRCReturnRC(autoCaller.rc());
5703
5704 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5705
5706 /* Find the device. */
5707 ComObjPtr<OUSBDevice> pUSBDevice;
5708 USBDeviceList::iterator it = mUSBDevices.begin();
5709 while (it != mUSBDevices.end())
5710 {
5711 LogFlowThisFunc(("it={%RTuuid}\n", (*it)->i_id().raw()));
5712 if ((*it)->i_id() == Uuid)
5713 {
5714 pUSBDevice = *it;
5715 break;
5716 }
5717 ++it;
5718 }
5719
5720
5721 if (pUSBDevice.isNull())
5722 {
5723 LogFlowThisFunc(("USB device not found.\n"));
5724
5725 /* The VM may be no more operational when this message arrives
5726 * (e.g. it may be Saving or Stopping or just PoweredOff). Use
5727 * AutoVMCaller to detect it -- AutoVMCaller::rc() will return a
5728 * failure in this case. */
5729
5730 AutoVMCallerQuiet autoVMCaller(this);
5731 if (FAILED(autoVMCaller.rc()))
5732 {
5733 LogFlowThisFunc(("Detach request ignored (mMachineState=%d).\n",
5734 mMachineState));
5735 return autoVMCaller.rc();
5736 }
5737
5738 /* the device must be in the list otherwise */
5739 AssertFailedReturn(E_FAIL);
5740 }
5741
5742 if (aError != NULL)
5743 {
5744 /* notify callback about an error */
5745 alock.release();
5746 i_onUSBDeviceStateChange(pUSBDevice, false /* aAttached */, aError);
5747 return S_OK;
5748 }
5749
5750 /* Remove the device from the collection, it is re-added below for failures */
5751 mUSBDevices.erase(it);
5752
5753 alock.release();
5754 HRESULT rc = i_detachUSBDevice(pUSBDevice);
5755 if (FAILED(rc))
5756 {
5757 /* Re-add the device to the collection */
5758 alock.acquire();
5759 mUSBDevices.push_back(pUSBDevice);
5760 alock.release();
5761 /* take the current error info */
5762 com::ErrorInfoKeeper eik;
5763 /* the error must be a VirtualBoxErrorInfo instance */
5764 ComPtr<IVirtualBoxErrorInfo> pError = eik.takeError();
5765 Assert(!pError.isNull());
5766 if (!pError.isNull())
5767 {
5768 /* notify callbacks about the error */
5769 i_onUSBDeviceStateChange(pUSBDevice, false /* aAttached */, pError);
5770 }
5771 }
5772
5773 return rc;
5774
5775#else /* !VBOX_WITH_USB */
5776 return E_FAIL;
5777#endif /* !VBOX_WITH_USB */
5778}
5779
5780/**
5781 * Called by IInternalSessionControl::OnBandwidthGroupChange().
5782 *
5783 * @note Locks this object for writing.
5784 */
5785HRESULT Console::i_onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
5786{
5787 LogFlowThisFunc(("\n"));
5788
5789 AutoCaller autoCaller(this);
5790 AssertComRCReturnRC(autoCaller.rc());
5791
5792 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5793
5794 HRESULT rc = S_OK;
5795
5796 /* don't trigger bandwidth group changes if the VM isn't running */
5797 SafeVMPtrQuiet ptrVM(this);
5798 if (ptrVM.isOk())
5799 {
5800 if ( mMachineState == MachineState_Running
5801 || mMachineState == MachineState_Teleporting
5802 || mMachineState == MachineState_LiveSnapshotting
5803 )
5804 {
5805 /* No need to call in the EMT thread. */
5806 Bstr strName;
5807 rc = aBandwidthGroup->COMGETTER(Name)(strName.asOutParam());
5808 if (SUCCEEDED(rc))
5809 {
5810 LONG64 cMax;
5811 rc = aBandwidthGroup->COMGETTER(MaxBytesPerSec)(&cMax);
5812 if (SUCCEEDED(rc))
5813 {
5814 BandwidthGroupType_T enmType;
5815 rc = aBandwidthGroup->COMGETTER(Type)(&enmType);
5816 if (SUCCEEDED(rc))
5817 {
5818 int vrc = VINF_SUCCESS;
5819 if (enmType == BandwidthGroupType_Disk)
5820 vrc = PDMR3AsyncCompletionBwMgrSetMaxForFile(ptrVM.rawUVM(), Utf8Str(strName).c_str(), (uint32_t)cMax);
5821#ifdef VBOX_WITH_NETSHAPER
5822 else if (enmType == BandwidthGroupType_Network)
5823 vrc = PDMR3NsBwGroupSetLimit(ptrVM.rawUVM(), Utf8Str(strName).c_str(), cMax);
5824 else
5825 rc = E_NOTIMPL;
5826#endif
5827 AssertRC(vrc);
5828 }
5829 }
5830 }
5831 }
5832 else
5833 rc = i_setInvalidMachineStateError();
5834 ptrVM.release();
5835 }
5836
5837 /* notify console callbacks on success */
5838 if (SUCCEEDED(rc))
5839 {
5840 alock.release();
5841 fireBandwidthGroupChangedEvent(mEventSource, aBandwidthGroup);
5842 }
5843
5844 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
5845 return rc;
5846}
5847
5848/**
5849 * Called by IInternalSessionControl::OnStorageDeviceChange().
5850 *
5851 * @note Locks this object for writing.
5852 */
5853HRESULT Console::i_onStorageDeviceChange(IMediumAttachment *aMediumAttachment, BOOL aRemove, BOOL aSilent)
5854{
5855 LogFlowThisFunc(("\n"));
5856
5857 AutoCaller autoCaller(this);
5858 AssertComRCReturnRC(autoCaller.rc());
5859
5860 HRESULT rc = S_OK;
5861
5862 /* don't trigger medium changes if the VM isn't running */
5863 SafeVMPtrQuiet ptrVM(this);
5864 if (ptrVM.isOk())
5865 {
5866 if (aRemove)
5867 rc = i_doStorageDeviceDetach(aMediumAttachment, ptrVM.rawUVM(), RT_BOOL(aSilent));
5868 else
5869 rc = i_doStorageDeviceAttach(aMediumAttachment, ptrVM.rawUVM(), RT_BOOL(aSilent));
5870 ptrVM.release();
5871 }
5872
5873 /* notify console callbacks on success */
5874 if (SUCCEEDED(rc))
5875 fireStorageDeviceChangedEvent(mEventSource, aMediumAttachment, aRemove, aSilent);
5876
5877 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
5878 return rc;
5879}
5880
5881HRESULT Console::i_onExtraDataChange(IN_BSTR aMachineId, IN_BSTR aKey, IN_BSTR aVal)
5882{
5883 LogFlowThisFunc(("\n"));
5884
5885 AutoCaller autoCaller(this);
5886 if (FAILED(autoCaller.rc()))
5887 return autoCaller.rc();
5888
5889 if (!aMachineId)
5890 return S_OK;
5891
5892 HRESULT hrc = S_OK;
5893 Bstr idMachine(aMachineId);
5894 if ( FAILED(hrc)
5895 || idMachine != i_getId())
5896 return hrc;
5897
5898 /* don't do anything if the VM isn't running */
5899 SafeVMPtrQuiet ptrVM(this);
5900 if (ptrVM.isOk())
5901 {
5902 Bstr strKey(aKey);
5903 Bstr strVal(aVal);
5904
5905 if (strKey == "VBoxInternal2/TurnResetIntoPowerOff")
5906 {
5907 int vrc = VMR3SetPowerOffInsteadOfReset(ptrVM.rawUVM(), strVal == "1");
5908 AssertRC(vrc);
5909 }
5910
5911 ptrVM.release();
5912 }
5913
5914 /* notify console callbacks on success */
5915 if (SUCCEEDED(hrc))
5916 fireExtraDataChangedEvent(mEventSource, aMachineId, aKey, aVal);
5917
5918 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
5919 return hrc;
5920}
5921
5922/**
5923 * @note Temporarily locks this object for writing.
5924 */
5925HRESULT Console::i_getGuestProperty(const Utf8Str &aName, Utf8Str *aValue, LONG64 *aTimestamp, Utf8Str *aFlags)
5926{
5927#ifndef VBOX_WITH_GUEST_PROPS
5928 ReturnComNotImplemented();
5929#else /* VBOX_WITH_GUEST_PROPS */
5930 if (!RT_VALID_PTR(aValue))
5931 return E_POINTER;
5932 if (aTimestamp != NULL && !RT_VALID_PTR(aTimestamp))
5933 return E_POINTER;
5934 if (aFlags != NULL && !RT_VALID_PTR(aFlags))
5935 return E_POINTER;
5936
5937 AutoCaller autoCaller(this);
5938 AssertComRCReturnRC(autoCaller.rc());
5939
5940 /* protect mpUVM (if not NULL) */
5941 SafeVMPtrQuiet ptrVM(this);
5942 if (FAILED(ptrVM.rc()))
5943 return ptrVM.rc();
5944
5945 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
5946 * ptrVM, so there is no need to hold a lock of this */
5947
5948 HRESULT rc = E_UNEXPECTED;
5949 using namespace guestProp;
5950
5951 try
5952 {
5953 VBOXHGCMSVCPARM parm[4];
5954 char szBuffer[MAX_VALUE_LEN + MAX_FLAGS_LEN];
5955
5956 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
5957 parm[0].u.pointer.addr = (void*)aName.c_str();
5958 parm[0].u.pointer.size = (uint32_t)aName.length() + 1; /* The + 1 is the null terminator */
5959
5960 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
5961 parm[1].u.pointer.addr = szBuffer;
5962 parm[1].u.pointer.size = sizeof(szBuffer);
5963
5964 parm[2].type = VBOX_HGCM_SVC_PARM_64BIT;
5965 parm[2].u.uint64 = 0;
5966
5967 parm[3].type = VBOX_HGCM_SVC_PARM_32BIT;
5968 parm[3].u.uint32 = 0;
5969
5970 int vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GET_PROP_HOST,
5971 4, &parm[0]);
5972 /* The returned string should never be able to be greater than our buffer */
5973 AssertLogRel(vrc != VERR_BUFFER_OVERFLOW);
5974 AssertLogRel(RT_FAILURE(vrc) || parm[2].type == VBOX_HGCM_SVC_PARM_64BIT);
5975 if (RT_SUCCESS(vrc))
5976 {
5977 *aValue = szBuffer;
5978
5979 if (aTimestamp)
5980 *aTimestamp = parm[2].u.uint64;
5981
5982 if (aFlags)
5983 *aFlags = &szBuffer[strlen(szBuffer) + 1];
5984
5985 rc = S_OK;
5986 }
5987 else if (vrc == VERR_NOT_FOUND)
5988 {
5989 *aValue = "";
5990 rc = S_OK;
5991 }
5992 else
5993 rc = setError(VBOX_E_IPRT_ERROR,
5994 tr("The VBoxGuestPropSvc service call failed with the error %Rrc"),
5995 vrc);
5996 }
5997 catch(std::bad_alloc & /*e*/)
5998 {
5999 rc = E_OUTOFMEMORY;
6000 }
6001
6002 return rc;
6003#endif /* VBOX_WITH_GUEST_PROPS */
6004}
6005
6006/**
6007 * @note Temporarily locks this object for writing.
6008 */
6009HRESULT Console::i_setGuestProperty(const Utf8Str &aName, const Utf8Str &aValue, const Utf8Str &aFlags)
6010{
6011#ifndef VBOX_WITH_GUEST_PROPS
6012 ReturnComNotImplemented();
6013#else /* VBOX_WITH_GUEST_PROPS */
6014
6015 AutoCaller autoCaller(this);
6016 AssertComRCReturnRC(autoCaller.rc());
6017
6018 /* protect mpUVM (if not NULL) */
6019 SafeVMPtrQuiet ptrVM(this);
6020 if (FAILED(ptrVM.rc()))
6021 return ptrVM.rc();
6022
6023 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
6024 * ptrVM, so there is no need to hold a lock of this */
6025
6026 using namespace guestProp;
6027
6028 VBOXHGCMSVCPARM parm[3];
6029
6030 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
6031 parm[0].u.pointer.addr = (void*)aName.c_str();
6032 parm[0].u.pointer.size = (uint32_t)aName.length() + 1; /* The + 1 is the null terminator */
6033
6034 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
6035 parm[1].u.pointer.addr = (void *)aValue.c_str();
6036 parm[1].u.pointer.size = (uint32_t)aValue.length() + 1; /* The + 1 is the null terminator */
6037
6038 int vrc;
6039 if (aFlags.isEmpty())
6040 {
6041 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", SET_PROP_VALUE_HOST,
6042 2, &parm[0]);
6043 }
6044 else
6045 {
6046 parm[2].type = VBOX_HGCM_SVC_PARM_PTR;
6047 parm[2].u.pointer.addr = (void*)aFlags.c_str();
6048 parm[2].u.pointer.size = (uint32_t)aFlags.length() + 1; /* The + 1 is the null terminator */
6049
6050 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", SET_PROP_HOST,
6051 3, &parm[0]);
6052 }
6053
6054 HRESULT hrc = S_OK;
6055 if (RT_FAILURE(vrc))
6056 hrc = setError(VBOX_E_IPRT_ERROR, tr("The VBoxGuestPropSvc service call failed with the error %Rrc"), vrc);
6057 return hrc;
6058#endif /* VBOX_WITH_GUEST_PROPS */
6059}
6060
6061HRESULT Console::i_deleteGuestProperty(const Utf8Str &aName)
6062{
6063#ifndef VBOX_WITH_GUEST_PROPS
6064 ReturnComNotImplemented();
6065#else /* VBOX_WITH_GUEST_PROPS */
6066
6067 AutoCaller autoCaller(this);
6068 AssertComRCReturnRC(autoCaller.rc());
6069
6070 /* protect mpUVM (if not NULL) */
6071 SafeVMPtrQuiet ptrVM(this);
6072 if (FAILED(ptrVM.rc()))
6073 return ptrVM.rc();
6074
6075 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
6076 * ptrVM, so there is no need to hold a lock of this */
6077
6078 using namespace guestProp;
6079
6080 VBOXHGCMSVCPARM parm[1];
6081
6082 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
6083 parm[0].u.pointer.addr = (void*)aName.c_str();
6084 parm[0].u.pointer.size = (uint32_t)aName.length() + 1; /* The + 1 is the null terminator */
6085
6086 int vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", DEL_PROP_HOST,
6087 1, &parm[0]);
6088
6089 HRESULT hrc = S_OK;
6090 if (RT_FAILURE(vrc))
6091 hrc = setError(VBOX_E_IPRT_ERROR, tr("The VBoxGuestPropSvc service call failed with the error %Rrc"), vrc);
6092 return hrc;
6093#endif /* VBOX_WITH_GUEST_PROPS */
6094}
6095
6096/**
6097 * @note Temporarily locks this object for writing.
6098 */
6099HRESULT Console::i_enumerateGuestProperties(const Utf8Str &aPatterns,
6100 std::vector<Utf8Str> &aNames,
6101 std::vector<Utf8Str> &aValues,
6102 std::vector<LONG64> &aTimestamps,
6103 std::vector<Utf8Str> &aFlags)
6104{
6105#ifndef VBOX_WITH_GUEST_PROPS
6106 ReturnComNotImplemented();
6107#else /* VBOX_WITH_GUEST_PROPS */
6108
6109 AutoCaller autoCaller(this);
6110 AssertComRCReturnRC(autoCaller.rc());
6111
6112 /* protect mpUVM (if not NULL) */
6113 AutoVMCallerWeak autoVMCaller(this);
6114 if (FAILED(autoVMCaller.rc()))
6115 return autoVMCaller.rc();
6116
6117 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
6118 * autoVMCaller, so there is no need to hold a lock of this */
6119
6120 return i_doEnumerateGuestProperties(aPatterns, aNames, aValues, aTimestamps, aFlags);
6121#endif /* VBOX_WITH_GUEST_PROPS */
6122}
6123
6124
6125/*
6126 * Internal: helper function for connecting progress reporting
6127 */
6128static DECLCALLBACK(int) onlineMergeMediumProgress(void *pvUser, unsigned uPercentage)
6129{
6130 HRESULT rc = S_OK;
6131 IProgress *pProgress = static_cast<IProgress *>(pvUser);
6132 if (pProgress)
6133 rc = pProgress->SetCurrentOperationProgress(uPercentage);
6134 return SUCCEEDED(rc) ? VINF_SUCCESS : VERR_GENERAL_FAILURE;
6135}
6136
6137/**
6138 * @note Temporarily locks this object for writing. bird: And/or reading?
6139 */
6140HRESULT Console::i_onlineMergeMedium(IMediumAttachment *aMediumAttachment,
6141 ULONG aSourceIdx, ULONG aTargetIdx,
6142 IProgress *aProgress)
6143{
6144 AutoCaller autoCaller(this);
6145 AssertComRCReturnRC(autoCaller.rc());
6146
6147 HRESULT rc = S_OK;
6148 int vrc = VINF_SUCCESS;
6149
6150 /* Get the VM - must be done before the read-locking. */
6151 SafeVMPtr ptrVM(this);
6152 if (!ptrVM.isOk())
6153 return ptrVM.rc();
6154
6155 /* We will need to release the lock before doing the actual merge */
6156 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6157
6158 /* paranoia - we don't want merges to happen while teleporting etc. */
6159 switch (mMachineState)
6160 {
6161 case MachineState_DeletingSnapshotOnline:
6162 case MachineState_DeletingSnapshotPaused:
6163 break;
6164
6165 default:
6166 return i_setInvalidMachineStateError();
6167 }
6168
6169 /** @todo AssertComRC -> AssertComRCReturn! Could potentially end up
6170 * using uninitialized variables here. */
6171 BOOL fBuiltinIOCache;
6172 rc = mMachine->COMGETTER(IOCacheEnabled)(&fBuiltinIOCache);
6173 AssertComRC(rc);
6174 SafeIfaceArray<IStorageController> ctrls;
6175 rc = mMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));
6176 AssertComRC(rc);
6177 LONG lDev;
6178 rc = aMediumAttachment->COMGETTER(Device)(&lDev);
6179 AssertComRC(rc);
6180 LONG lPort;
6181 rc = aMediumAttachment->COMGETTER(Port)(&lPort);
6182 AssertComRC(rc);
6183 IMedium *pMedium;
6184 rc = aMediumAttachment->COMGETTER(Medium)(&pMedium);
6185 AssertComRC(rc);
6186 Bstr mediumLocation;
6187 if (pMedium)
6188 {
6189 rc = pMedium->COMGETTER(Location)(mediumLocation.asOutParam());
6190 AssertComRC(rc);
6191 }
6192
6193 Bstr attCtrlName;
6194 rc = aMediumAttachment->COMGETTER(Controller)(attCtrlName.asOutParam());
6195 AssertComRC(rc);
6196 ComPtr<IStorageController> pStorageController;
6197 for (size_t i = 0; i < ctrls.size(); ++i)
6198 {
6199 Bstr ctrlName;
6200 rc = ctrls[i]->COMGETTER(Name)(ctrlName.asOutParam());
6201 AssertComRC(rc);
6202 if (attCtrlName == ctrlName)
6203 {
6204 pStorageController = ctrls[i];
6205 break;
6206 }
6207 }
6208 if (pStorageController.isNull())
6209 return setError(E_FAIL,
6210 tr("Could not find storage controller '%ls'"),
6211 attCtrlName.raw());
6212
6213 StorageControllerType_T enmCtrlType;
6214 rc = pStorageController->COMGETTER(ControllerType)(&enmCtrlType);
6215 AssertComRC(rc);
6216 const char *pcszDevice = i_convertControllerTypeToDev(enmCtrlType);
6217
6218 StorageBus_T enmBus;
6219 rc = pStorageController->COMGETTER(Bus)(&enmBus);
6220 AssertComRC(rc);
6221 ULONG uInstance;
6222 rc = pStorageController->COMGETTER(Instance)(&uInstance);
6223 AssertComRC(rc);
6224 BOOL fUseHostIOCache;
6225 rc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
6226 AssertComRC(rc);
6227
6228 unsigned uLUN;
6229 rc = Console::i_convertBusPortDeviceToLun(enmBus, lPort, lDev, uLUN);
6230 AssertComRCReturnRC(rc);
6231
6232 Assert(mMachineState == MachineState_DeletingSnapshotOnline);
6233
6234 /* Pause the VM, as it might have pending IO on this drive */
6235 bool fResume = false;
6236 rc = i_suspendBeforeConfigChange(ptrVM.rawUVM(), &alock, &fResume);
6237 if (FAILED(rc))
6238 return rc;
6239
6240 bool fInsertDiskIntegrityDrv = false;
6241 Bstr strDiskIntegrityFlag;
6242 rc = mMachine->GetExtraData(Bstr("VBoxInternal2/EnableDiskIntegrityDriver").raw(),
6243 strDiskIntegrityFlag.asOutParam());
6244 if ( rc == S_OK
6245 && strDiskIntegrityFlag == "1")
6246 fInsertDiskIntegrityDrv = true;
6247
6248 alock.release();
6249 vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY,
6250 (PFNRT)i_reconfigureMediumAttachment, 14,
6251 this, ptrVM.rawUVM(), pcszDevice, uInstance, enmBus, fUseHostIOCache,
6252 fBuiltinIOCache, fInsertDiskIntegrityDrv, true /* fSetupMerge */,
6253 aSourceIdx, aTargetIdx, aMediumAttachment, mMachineState, &rc);
6254 /* error handling is after resuming the VM */
6255
6256 if (fResume)
6257 i_resumeAfterConfigChange(ptrVM.rawUVM());
6258
6259 if (RT_FAILURE(vrc))
6260 return setError(E_FAIL, tr("%Rrc"), vrc);
6261 if (FAILED(rc))
6262 return rc;
6263
6264 PPDMIBASE pIBase = NULL;
6265 PPDMIMEDIA pIMedium = NULL;
6266 vrc = PDMR3QueryDriverOnLun(ptrVM.rawUVM(), pcszDevice, uInstance, uLUN, "VD", &pIBase);
6267 if (RT_SUCCESS(vrc))
6268 {
6269 if (pIBase)
6270 {
6271 pIMedium = (PPDMIMEDIA)pIBase->pfnQueryInterface(pIBase, PDMIMEDIA_IID);
6272 if (!pIMedium)
6273 return setError(E_FAIL, tr("could not query medium interface of controller"));
6274 }
6275 else
6276 return setError(E_FAIL, tr("could not query base interface of controller"));
6277 }
6278
6279 /* Finally trigger the merge. */
6280 vrc = pIMedium->pfnMerge(pIMedium, onlineMergeMediumProgress, aProgress);
6281 if (RT_FAILURE(vrc))
6282 return setError(E_FAIL, tr("Failed to perform an online medium merge (%Rrc)"), vrc);
6283
6284 alock.acquire();
6285 /* Pause the VM, as it might have pending IO on this drive */
6286 rc = i_suspendBeforeConfigChange(ptrVM.rawUVM(), &alock, &fResume);
6287 if (FAILED(rc))
6288 return rc;
6289 alock.release();
6290
6291 /* Update medium chain and state now, so that the VM can continue. */
6292 rc = mControl->FinishOnlineMergeMedium();
6293
6294 vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY,
6295 (PFNRT)i_reconfigureMediumAttachment, 14,
6296 this, ptrVM.rawUVM(), pcszDevice, uInstance, enmBus, fUseHostIOCache,
6297 fBuiltinIOCache, fInsertDiskIntegrityDrv, false /* fSetupMerge */,
6298 0 /* uMergeSource */, 0 /* uMergeTarget */, aMediumAttachment,
6299 mMachineState, &rc);
6300 /* error handling is after resuming the VM */
6301
6302 if (fResume)
6303 i_resumeAfterConfigChange(ptrVM.rawUVM());
6304
6305 if (RT_FAILURE(vrc))
6306 return setError(E_FAIL, tr("%Rrc"), vrc);
6307 if (FAILED(rc))
6308 return rc;
6309
6310 return rc;
6311}
6312
6313HRESULT Console::i_reconfigureMediumAttachments(const std::vector<ComPtr<IMediumAttachment> > &aAttachments)
6314{
6315 HRESULT rc = S_OK;
6316
6317 AutoCaller autoCaller(this);
6318 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6319
6320 /* get the VM handle. */
6321 SafeVMPtr ptrVM(this);
6322 if (!ptrVM.isOk())
6323 return ptrVM.rc();
6324
6325 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6326
6327 for (size_t i = 0; i < aAttachments.size(); ++i)
6328 {
6329 ComPtr<IStorageController> pStorageController;
6330 Bstr controllerName;
6331 ULONG lInstance;
6332 StorageControllerType_T enmController;
6333 StorageBus_T enmBus;
6334 BOOL fUseHostIOCache;
6335
6336 /*
6337 * We could pass the objects, but then EMT would have to do lots of
6338 * IPC (to VBoxSVC) which takes a significant amount of time.
6339 * Better query needed values here and pass them.
6340 */
6341 rc = aAttachments[i]->COMGETTER(Controller)(controllerName.asOutParam());
6342 if (FAILED(rc))
6343 throw rc;
6344
6345 rc = mMachine->GetStorageControllerByName(controllerName.raw(),
6346 pStorageController.asOutParam());
6347 if (FAILED(rc))
6348 throw rc;
6349
6350 rc = pStorageController->COMGETTER(ControllerType)(&enmController);
6351 if (FAILED(rc))
6352 throw rc;
6353 rc = pStorageController->COMGETTER(Instance)(&lInstance);
6354 if (FAILED(rc))
6355 throw rc;
6356 rc = pStorageController->COMGETTER(Bus)(&enmBus);
6357 if (FAILED(rc))
6358 throw rc;
6359 rc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
6360 if (FAILED(rc))
6361 throw rc;
6362
6363 const char *pcszDevice = i_convertControllerTypeToDev(enmController);
6364
6365 BOOL fBuiltinIOCache;
6366 rc = mMachine->COMGETTER(IOCacheEnabled)(&fBuiltinIOCache);
6367 if (FAILED(rc))
6368 throw rc;
6369
6370 bool fInsertDiskIntegrityDrv = false;
6371 Bstr strDiskIntegrityFlag;
6372 rc = mMachine->GetExtraData(Bstr("VBoxInternal2/EnableDiskIntegrityDriver").raw(),
6373 strDiskIntegrityFlag.asOutParam());
6374 if ( rc == S_OK
6375 && strDiskIntegrityFlag == "1")
6376 fInsertDiskIntegrityDrv = true;
6377
6378 alock.release();
6379
6380 IMediumAttachment *pAttachment = aAttachments[i];
6381 int vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY,
6382 (PFNRT)i_reconfigureMediumAttachment, 14,
6383 this, ptrVM.rawUVM(), pcszDevice, lInstance, enmBus, fUseHostIOCache,
6384 fBuiltinIOCache, fInsertDiskIntegrityDrv,
6385 false /* fSetupMerge */, 0 /* uMergeSource */, 0 /* uMergeTarget */,
6386 pAttachment, mMachineState, &rc);
6387 if (RT_FAILURE(vrc))
6388 throw setError(E_FAIL, tr("%Rrc"), vrc);
6389 if (FAILED(rc))
6390 throw rc;
6391
6392 alock.acquire();
6393 }
6394
6395 return rc;
6396}
6397
6398
6399/**
6400 * Load an HGCM service.
6401 *
6402 * Main purpose of this method is to allow extension packs to load HGCM
6403 * service modules, which they can't, because the HGCM functionality lives
6404 * in module VBoxC (and ConsoleImpl.cpp is part of it and thus can call it).
6405 * Extension modules must not link directly against VBoxC, (XP)COM is
6406 * handling this.
6407 */
6408int Console::i_hgcmLoadService(const char *pszServiceLibrary, const char *pszServiceName)
6409{
6410 /* Everyone seems to delegate all HGCM calls to VMMDev, so stick to this
6411 * convention. Adds one level of indirection for no obvious reason. */
6412 AssertPtrReturn(m_pVMMDev, VERR_INVALID_STATE);
6413 return m_pVMMDev->hgcmLoadService(pszServiceLibrary, pszServiceName);
6414}
6415
6416/**
6417 * Merely passes the call to Guest::enableVMMStatistics().
6418 */
6419void Console::i_enableVMMStatistics(BOOL aEnable)
6420{
6421 if (mGuest)
6422 mGuest->i_enableVMMStatistics(aEnable);
6423}
6424
6425/**
6426 * Worker for Console::Pause and internal entry point for pausing a VM for
6427 * a specific reason.
6428 */
6429HRESULT Console::i_pause(Reason_T aReason)
6430{
6431 LogFlowThisFuncEnter();
6432
6433 AutoCaller autoCaller(this);
6434 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6435
6436 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6437
6438 switch (mMachineState)
6439 {
6440 case MachineState_Running:
6441 case MachineState_Teleporting:
6442 case MachineState_LiveSnapshotting:
6443 break;
6444
6445 case MachineState_Paused:
6446 case MachineState_TeleportingPausedVM:
6447 case MachineState_OnlineSnapshotting:
6448 /* Remove any keys which are supposed to be removed on a suspend. */
6449 if ( aReason == Reason_HostSuspend
6450 || aReason == Reason_HostBatteryLow)
6451 {
6452 i_removeSecretKeysOnSuspend();
6453 return S_OK;
6454 }
6455 return setError(VBOX_E_INVALID_VM_STATE, tr("Already paused"));
6456
6457 default:
6458 return i_setInvalidMachineStateError();
6459 }
6460
6461 /* get the VM handle. */
6462 SafeVMPtr ptrVM(this);
6463 if (!ptrVM.isOk())
6464 return ptrVM.rc();
6465
6466 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
6467 alock.release();
6468
6469 LogFlowThisFunc(("Sending PAUSE request...\n"));
6470 if (aReason != Reason_Unspecified)
6471 LogRel(("Pausing VM execution, reason '%s'\n", Global::stringifyReason(aReason)));
6472
6473 /** @todo r=klaus make use of aReason */
6474 VMSUSPENDREASON enmReason = VMSUSPENDREASON_USER;
6475 if (aReason == Reason_HostSuspend)
6476 enmReason = VMSUSPENDREASON_HOST_SUSPEND;
6477 else if (aReason == Reason_HostBatteryLow)
6478 enmReason = VMSUSPENDREASON_HOST_BATTERY_LOW;
6479 int vrc = VMR3Suspend(ptrVM.rawUVM(), enmReason);
6480
6481 HRESULT hrc = S_OK;
6482 if (RT_FAILURE(vrc))
6483 hrc = setError(VBOX_E_VM_ERROR, tr("Could not suspend the machine execution (%Rrc)"), vrc);
6484 else if ( aReason == Reason_HostSuspend
6485 || aReason == Reason_HostBatteryLow)
6486 {
6487 alock.acquire();
6488 i_removeSecretKeysOnSuspend();
6489 }
6490
6491 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
6492 LogFlowThisFuncLeave();
6493 return hrc;
6494}
6495
6496/**
6497 * Worker for Console::Resume and internal entry point for resuming a VM for
6498 * a specific reason.
6499 */
6500HRESULT Console::i_resume(Reason_T aReason, AutoWriteLock &alock)
6501{
6502 LogFlowThisFuncEnter();
6503
6504 AutoCaller autoCaller(this);
6505 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6506
6507 /* get the VM handle. */
6508 SafeVMPtr ptrVM(this);
6509 if (!ptrVM.isOk())
6510 return ptrVM.rc();
6511
6512 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
6513 alock.release();
6514
6515 LogFlowThisFunc(("Sending RESUME request...\n"));
6516 if (aReason != Reason_Unspecified)
6517 LogRel(("Resuming VM execution, reason '%s'\n", Global::stringifyReason(aReason)));
6518
6519 int vrc;
6520 if (VMR3GetStateU(ptrVM.rawUVM()) == VMSTATE_CREATED)
6521 {
6522#ifdef VBOX_WITH_EXTPACK
6523 vrc = mptrExtPackManager->i_callAllVmPowerOnHooks(this, VMR3GetVM(ptrVM.rawUVM()));
6524#else
6525 vrc = VINF_SUCCESS;
6526#endif
6527 if (RT_SUCCESS(vrc))
6528 vrc = VMR3PowerOn(ptrVM.rawUVM()); /* (PowerUpPaused) */
6529 }
6530 else
6531 {
6532 VMRESUMEREASON enmReason;
6533 if (aReason == Reason_HostResume)
6534 {
6535 /*
6536 * Host resume may be called multiple times successively. We don't want to VMR3Resume->vmR3Resume->vmR3TrySetState()
6537 * to assert on us, hence check for the VM state here and bail if it's not in the 'suspended' state.
6538 * See @bugref{3495}.
6539 *
6540 * Also, don't resume the VM through a host-resume unless it was suspended due to a host-suspend.
6541 */
6542 if (VMR3GetStateU(ptrVM.rawUVM()) != VMSTATE_SUSPENDED)
6543 {
6544 LogRel(("Ignoring VM resume request, VM is currently not suspended\n"));
6545 return S_OK;
6546 }
6547 if (VMR3GetSuspendReason(ptrVM.rawUVM()) != VMSUSPENDREASON_HOST_SUSPEND)
6548 {
6549 LogRel(("Ignoring VM resume request, VM was not suspended due to host-suspend\n"));
6550 return S_OK;
6551 }
6552
6553 enmReason = VMRESUMEREASON_HOST_RESUME;
6554 }
6555 else
6556 {
6557 /*
6558 * Any other reason to resume the VM throws an error when the VM was suspended due to a host suspend.
6559 * See @bugref{7836}.
6560 */
6561 if ( VMR3GetStateU(ptrVM.rawUVM()) == VMSTATE_SUSPENDED
6562 && VMR3GetSuspendReason(ptrVM.rawUVM()) == VMSUSPENDREASON_HOST_SUSPEND)
6563 return setError(VBOX_E_INVALID_VM_STATE, tr("VM is paused due to host power management"));
6564
6565 enmReason = aReason == Reason_Snapshot ? VMRESUMEREASON_STATE_SAVED : VMRESUMEREASON_USER;
6566 }
6567
6568 // for snapshots: no state change callback, VBoxSVC does everything
6569 if (aReason == Reason_Snapshot)
6570 mVMStateChangeCallbackDisabled = true;
6571 vrc = VMR3Resume(ptrVM.rawUVM(), enmReason);
6572 if (aReason == Reason_Snapshot)
6573 mVMStateChangeCallbackDisabled = false;
6574 }
6575
6576 HRESULT rc = RT_SUCCESS(vrc) ? S_OK :
6577 setError(VBOX_E_VM_ERROR,
6578 tr("Could not resume the machine execution (%Rrc)"),
6579 vrc);
6580
6581 LogFlowThisFunc(("rc=%Rhrc\n", rc));
6582 LogFlowThisFuncLeave();
6583 return rc;
6584}
6585
6586/**
6587 * Internal entry point for saving state of a VM for a specific reason. This
6588 * method is completely synchronous.
6589 *
6590 * The machine state is already set appropriately. It is only changed when
6591 * saving state actually paused the VM (happens with live snapshots and
6592 * teleportation), and in this case reflects the now paused variant.
6593 *
6594 * @note Locks this object for writing.
6595 */
6596HRESULT Console::i_saveState(Reason_T aReason, const ComPtr<IProgress> &aProgress, const Utf8Str &aStateFilePath, bool aPauseVM, bool &aLeftPaused)
6597{
6598 LogFlowThisFuncEnter();
6599 aLeftPaused = false;
6600
6601 AssertReturn(!aProgress.isNull(), E_INVALIDARG);
6602 AssertReturn(!aStateFilePath.isEmpty(), E_INVALIDARG);
6603
6604 AutoCaller autoCaller(this);
6605 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6606
6607 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6608
6609 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
6610 if ( mMachineState != MachineState_Saving
6611 && mMachineState != MachineState_LiveSnapshotting
6612 && mMachineState != MachineState_OnlineSnapshotting
6613 && mMachineState != MachineState_Teleporting
6614 && mMachineState != MachineState_TeleportingPausedVM)
6615 {
6616 return setError(VBOX_E_INVALID_VM_STATE,
6617 tr("Cannot save the execution state as the machine is not running or paused (machine state: %s)"),
6618 Global::stringifyMachineState(mMachineState));
6619 }
6620 bool fContinueAfterwards = mMachineState != MachineState_Saving;
6621
6622 Bstr strDisableSaveState;
6623 mMachine->GetExtraData(Bstr("VBoxInternal2/DisableSaveState").raw(), strDisableSaveState.asOutParam());
6624 if (strDisableSaveState == "1")
6625 return setError(VBOX_E_VM_ERROR,
6626 tr("Saving the execution state is disabled for this VM"));
6627
6628 if (aReason != Reason_Unspecified)
6629 LogRel(("Saving state of VM, reason '%s'\n", Global::stringifyReason(aReason)));
6630
6631 /* ensure the directory for the saved state file exists */
6632 {
6633 Utf8Str dir = aStateFilePath;
6634 dir.stripFilename();
6635 if (!RTDirExists(dir.c_str()))
6636 {
6637 int vrc = RTDirCreateFullPath(dir.c_str(), 0700);
6638 if (RT_FAILURE(vrc))
6639 return setError(VBOX_E_FILE_ERROR,
6640 tr("Could not create a directory '%s' to save the state to (%Rrc)"),
6641 dir.c_str(), vrc);
6642 }
6643 }
6644
6645 /* Get the VM handle early, we need it in several places. */
6646 SafeVMPtr ptrVM(this);
6647 if (!ptrVM.isOk())
6648 return ptrVM.rc();
6649
6650 bool fPaused = false;
6651 if (aPauseVM)
6652 {
6653 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
6654 alock.release();
6655 VMSUSPENDREASON enmReason = VMSUSPENDREASON_USER;
6656 if (aReason == Reason_HostSuspend)
6657 enmReason = VMSUSPENDREASON_HOST_SUSPEND;
6658 else if (aReason == Reason_HostBatteryLow)
6659 enmReason = VMSUSPENDREASON_HOST_BATTERY_LOW;
6660 int vrc = VMR3Suspend(ptrVM.rawUVM(), enmReason);
6661 alock.acquire();
6662
6663 if (RT_FAILURE(vrc))
6664 return setError(VBOX_E_VM_ERROR, tr("Could not suspend the machine execution (%Rrc)"), vrc);
6665 fPaused = true;
6666 }
6667
6668 LogFlowFunc(("Saving the state to '%s'...\n", aStateFilePath.c_str()));
6669
6670 mptrCancelableProgress = aProgress;
6671 alock.release();
6672 int vrc = VMR3Save(ptrVM.rawUVM(),
6673 aStateFilePath.c_str(),
6674 fContinueAfterwards,
6675 Console::i_stateProgressCallback,
6676 static_cast<IProgress *>(aProgress),
6677 &aLeftPaused);
6678 alock.acquire();
6679 mptrCancelableProgress.setNull();
6680 if (RT_FAILURE(vrc))
6681 {
6682 if (fPaused)
6683 {
6684 alock.release();
6685 VMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_STATE_RESTORED);
6686 alock.acquire();
6687 }
6688 return setError(E_FAIL, tr("Failed to save the machine state to '%s' (%Rrc)"),
6689 aStateFilePath.c_str(), vrc);
6690 }
6691 Assert(fContinueAfterwards || !aLeftPaused);
6692
6693 if (!fContinueAfterwards)
6694 {
6695 /*
6696 * The machine has been successfully saved, so power it down
6697 * (vmstateChangeCallback() will set state to Saved on success).
6698 * Note: we release the VM caller, otherwise it will deadlock.
6699 */
6700 ptrVM.release();
6701 alock.release();
6702 autoCaller.release();
6703 HRESULT rc = i_powerDown();
6704 AssertComRC(rc);
6705 autoCaller.add();
6706 alock.acquire();
6707 }
6708 else
6709 {
6710 if (fPaused)
6711 aLeftPaused = true;
6712 }
6713
6714 LogFlowFuncLeave();
6715 return S_OK;
6716}
6717
6718/**
6719 * Internal entry point for cancelling a VM save state.
6720 *
6721 * @note Locks this object for writing.
6722 */
6723HRESULT Console::i_cancelSaveState()
6724{
6725 LogFlowThisFuncEnter();
6726
6727 AutoCaller autoCaller(this);
6728 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6729
6730 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6731
6732 /* Get the VM handle. */
6733 SafeVMPtr ptrVM(this);
6734 if (!ptrVM.isOk())
6735 return ptrVM.rc();
6736
6737 SSMR3Cancel(ptrVM.rawUVM());
6738
6739 LogFlowFuncLeave();
6740 return S_OK;
6741}
6742
6743#ifdef VBOX_WITH_AUDIO_VIDEOREC
6744/**
6745 * Sends audio (frame) data to the display's video capturing routines.
6746 *
6747 * @returns HRESULT
6748 * @param pvData Audio data to send.
6749 * @param cbData Size (in bytes) of audio data to send.
6750 * @param uTimestampMs Time stamp (in ms) of audio data.
6751 */
6752HRESULT Console::i_audioVideoRecSendAudio(const void *pvData, size_t cbData, uint64_t uTimestampMs)
6753{
6754 if (mDisplay)
6755 {
6756 int rc2 = mDisplay->i_videoCaptureSendAudio(pvData, cbData, uTimestampMs);
6757 AssertRC(rc2);
6758 }
6759
6760 return S_OK;
6761}
6762#endif /* VBOX_WITH_AUDIO_VIDEOREC */
6763
6764/**
6765 * Gets called by Session::UpdateMachineState()
6766 * (IInternalSessionControl::updateMachineState()).
6767 *
6768 * Must be called only in certain cases (see the implementation).
6769 *
6770 * @note Locks this object for writing.
6771 */
6772HRESULT Console::i_updateMachineState(MachineState_T aMachineState)
6773{
6774 AutoCaller autoCaller(this);
6775 AssertComRCReturnRC(autoCaller.rc());
6776
6777 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6778
6779 AssertReturn( mMachineState == MachineState_Saving
6780 || mMachineState == MachineState_OnlineSnapshotting
6781 || mMachineState == MachineState_LiveSnapshotting
6782 || mMachineState == MachineState_DeletingSnapshotOnline
6783 || mMachineState == MachineState_DeletingSnapshotPaused
6784 || aMachineState == MachineState_Saving
6785 || aMachineState == MachineState_OnlineSnapshotting
6786 || aMachineState == MachineState_LiveSnapshotting
6787 || aMachineState == MachineState_DeletingSnapshotOnline
6788 || aMachineState == MachineState_DeletingSnapshotPaused
6789 , E_FAIL);
6790
6791 return i_setMachineStateLocally(aMachineState);
6792}
6793
6794/**
6795 * Gets called by Session::COMGETTER(NominalState)()
6796 * (IInternalSessionControl::getNominalState()).
6797 *
6798 * @note Locks this object for reading.
6799 */
6800HRESULT Console::i_getNominalState(MachineState_T &aNominalState)
6801{
6802 LogFlowThisFuncEnter();
6803
6804 AutoCaller autoCaller(this);
6805 AssertComRCReturnRC(autoCaller.rc());
6806
6807 /* Get the VM handle. */
6808 SafeVMPtr ptrVM(this);
6809 if (!ptrVM.isOk())
6810 return ptrVM.rc();
6811
6812 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6813
6814 MachineState_T enmMachineState = MachineState_Null;
6815 VMSTATE enmVMState = VMR3GetStateU(ptrVM.rawUVM());
6816 switch (enmVMState)
6817 {
6818 case VMSTATE_CREATING:
6819 case VMSTATE_CREATED:
6820 case VMSTATE_POWERING_ON:
6821 enmMachineState = MachineState_Starting;
6822 break;
6823 case VMSTATE_LOADING:
6824 enmMachineState = MachineState_Restoring;
6825 break;
6826 case VMSTATE_RESUMING:
6827 case VMSTATE_SUSPENDING:
6828 case VMSTATE_SUSPENDING_LS:
6829 case VMSTATE_SUSPENDING_EXT_LS:
6830 case VMSTATE_SUSPENDED:
6831 case VMSTATE_SUSPENDED_LS:
6832 case VMSTATE_SUSPENDED_EXT_LS:
6833 enmMachineState = MachineState_Paused;
6834 break;
6835 case VMSTATE_RUNNING:
6836 case VMSTATE_RUNNING_LS:
6837 case VMSTATE_RUNNING_FT:
6838 case VMSTATE_RESETTING:
6839 case VMSTATE_RESETTING_LS:
6840 case VMSTATE_SOFT_RESETTING:
6841 case VMSTATE_SOFT_RESETTING_LS:
6842 case VMSTATE_DEBUGGING:
6843 case VMSTATE_DEBUGGING_LS:
6844 enmMachineState = MachineState_Running;
6845 break;
6846 case VMSTATE_SAVING:
6847 enmMachineState = MachineState_Saving;
6848 break;
6849 case VMSTATE_POWERING_OFF:
6850 case VMSTATE_POWERING_OFF_LS:
6851 case VMSTATE_DESTROYING:
6852 enmMachineState = MachineState_Stopping;
6853 break;
6854 case VMSTATE_OFF:
6855 case VMSTATE_OFF_LS:
6856 case VMSTATE_FATAL_ERROR:
6857 case VMSTATE_FATAL_ERROR_LS:
6858 case VMSTATE_LOAD_FAILURE:
6859 case VMSTATE_TERMINATED:
6860 enmMachineState = MachineState_PoweredOff;
6861 break;
6862 case VMSTATE_GURU_MEDITATION:
6863 case VMSTATE_GURU_MEDITATION_LS:
6864 enmMachineState = MachineState_Stuck;
6865 break;
6866 default:
6867 AssertMsgFailed(("%s\n", VMR3GetStateName(enmVMState)));
6868 enmMachineState = MachineState_PoweredOff;
6869 }
6870 aNominalState = enmMachineState;
6871
6872 LogFlowFuncLeave();
6873 return S_OK;
6874}
6875
6876void Console::i_onMousePointerShapeChange(bool fVisible, bool fAlpha,
6877 uint32_t xHot, uint32_t yHot,
6878 uint32_t width, uint32_t height,
6879 const uint8_t *pu8Shape,
6880 uint32_t cbShape)
6881{
6882#if 0
6883 LogFlowThisFuncEnter();
6884 LogFlowThisFunc(("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, height=%d, shape=%p\n",
6885 fVisible, fAlpha, xHot, yHot, width, height, pShape));
6886#endif
6887
6888 AutoCaller autoCaller(this);
6889 AssertComRCReturnVoid(autoCaller.rc());
6890
6891 if (!mMouse.isNull())
6892 mMouse->updateMousePointerShape(fVisible, fAlpha, xHot, yHot, width, height,
6893 pu8Shape, cbShape);
6894
6895 com::SafeArray<BYTE> shape(cbShape);
6896 if (pu8Shape)
6897 memcpy(shape.raw(), pu8Shape, cbShape);
6898 fireMousePointerShapeChangedEvent(mEventSource, fVisible, fAlpha, xHot, yHot, width, height, ComSafeArrayAsInParam(shape));
6899
6900#if 0
6901 LogFlowThisFuncLeave();
6902#endif
6903}
6904
6905void Console::i_onMouseCapabilityChange(BOOL supportsAbsolute, BOOL supportsRelative,
6906 BOOL supportsMT, BOOL needsHostCursor)
6907{
6908 LogFlowThisFunc(("supportsAbsolute=%d supportsRelative=%d needsHostCursor=%d\n",
6909 supportsAbsolute, supportsRelative, needsHostCursor));
6910
6911 AutoCaller autoCaller(this);
6912 AssertComRCReturnVoid(autoCaller.rc());
6913
6914 fireMouseCapabilityChangedEvent(mEventSource, supportsAbsolute, supportsRelative, supportsMT, needsHostCursor);
6915}
6916
6917void Console::i_onStateChange(MachineState_T machineState)
6918{
6919 AutoCaller autoCaller(this);
6920 AssertComRCReturnVoid(autoCaller.rc());
6921 fireStateChangedEvent(mEventSource, machineState);
6922}
6923
6924void Console::i_onAdditionsStateChange()
6925{
6926 AutoCaller autoCaller(this);
6927 AssertComRCReturnVoid(autoCaller.rc());
6928
6929 fireAdditionsStateChangedEvent(mEventSource);
6930}
6931
6932/**
6933 * @remarks This notification only is for reporting an incompatible
6934 * Guest Additions interface, *not* the Guest Additions version!
6935 *
6936 * The user will be notified inside the guest if new Guest
6937 * Additions are available (via VBoxTray/VBoxClient).
6938 */
6939void Console::i_onAdditionsOutdated()
6940{
6941 AutoCaller autoCaller(this);
6942 AssertComRCReturnVoid(autoCaller.rc());
6943
6944 /** @todo implement this */
6945}
6946
6947void Console::i_onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
6948{
6949 AutoCaller autoCaller(this);
6950 AssertComRCReturnVoid(autoCaller.rc());
6951
6952 fireKeyboardLedsChangedEvent(mEventSource, fNumLock, fCapsLock, fScrollLock);
6953}
6954
6955void Console::i_onUSBDeviceStateChange(IUSBDevice *aDevice, bool aAttached,
6956 IVirtualBoxErrorInfo *aError)
6957{
6958 AutoCaller autoCaller(this);
6959 AssertComRCReturnVoid(autoCaller.rc());
6960
6961 fireUSBDeviceStateChangedEvent(mEventSource, aDevice, aAttached, aError);
6962}
6963
6964void Console::i_onRuntimeError(BOOL aFatal, IN_BSTR aErrorID, IN_BSTR aMessage)
6965{
6966 AutoCaller autoCaller(this);
6967 AssertComRCReturnVoid(autoCaller.rc());
6968
6969 fireRuntimeErrorEvent(mEventSource, aFatal, aErrorID, aMessage);
6970}
6971
6972HRESULT Console::i_onShowWindow(BOOL aCheck, BOOL *aCanShow, LONG64 *aWinId)
6973{
6974 AssertReturn(aCanShow, E_POINTER);
6975 AssertReturn(aWinId, E_POINTER);
6976
6977 *aCanShow = FALSE;
6978 *aWinId = 0;
6979
6980 AutoCaller autoCaller(this);
6981 AssertComRCReturnRC(autoCaller.rc());
6982
6983 VBoxEventDesc evDesc;
6984 if (aCheck)
6985 {
6986 evDesc.init(mEventSource, VBoxEventType_OnCanShowWindow);
6987 BOOL fDelivered = evDesc.fire(5000); /* Wait up to 5 secs for delivery */
6988 //Assert(fDelivered);
6989 if (fDelivered)
6990 {
6991 ComPtr<IEvent> pEvent;
6992 evDesc.getEvent(pEvent.asOutParam());
6993 // bit clumsy
6994 ComPtr<ICanShowWindowEvent> pCanShowEvent = pEvent;
6995 if (pCanShowEvent)
6996 {
6997 BOOL fVetoed = FALSE;
6998 BOOL fApproved = FALSE;
6999 pCanShowEvent->IsVetoed(&fVetoed);
7000 pCanShowEvent->IsApproved(&fApproved);
7001 *aCanShow = fApproved || !fVetoed;
7002 }
7003 else
7004 {
7005 AssertFailed();
7006 *aCanShow = TRUE;
7007 }
7008 }
7009 else
7010 *aCanShow = TRUE;
7011 }
7012 else
7013 {
7014 evDesc.init(mEventSource, VBoxEventType_OnShowWindow, INT64_C(0));
7015 BOOL fDelivered = evDesc.fire(5000); /* Wait up to 5 secs for delivery */
7016 //Assert(fDelivered);
7017 if (fDelivered)
7018 {
7019 ComPtr<IEvent> pEvent;
7020 evDesc.getEvent(pEvent.asOutParam());
7021 ComPtr<IShowWindowEvent> pShowEvent = pEvent;
7022 if (pShowEvent)
7023 {
7024 LONG64 iEvWinId = 0;
7025 pShowEvent->COMGETTER(WinId)(&iEvWinId);
7026 if (iEvWinId != 0 && *aWinId == 0)
7027 *aWinId = iEvWinId;
7028 }
7029 else
7030 AssertFailed();
7031 }
7032 }
7033
7034 return S_OK;
7035}
7036
7037// private methods
7038////////////////////////////////////////////////////////////////////////////////
7039
7040/**
7041 * Increases the usage counter of the mpUVM pointer.
7042 *
7043 * Guarantees that VMR3Destroy() will not be called on it at least until
7044 * releaseVMCaller() is called.
7045 *
7046 * If this method returns a failure, the caller is not allowed to use mpUVM and
7047 * may return the failed result code to the upper level. This method sets the
7048 * extended error info on failure if \a aQuiet is false.
7049 *
7050 * Setting \a aQuiet to true is useful for methods that don't want to return
7051 * the failed result code to the caller when this method fails (e.g. need to
7052 * silently check for the mpUVM availability).
7053 *
7054 * When mpUVM is NULL but \a aAllowNullVM is true, a corresponding error will be
7055 * returned instead of asserting. Having it false is intended as a sanity check
7056 * for methods that have checked mMachineState and expect mpUVM *NOT* to be
7057 * NULL.
7058 *
7059 * @param aQuiet true to suppress setting error info
7060 * @param aAllowNullVM true to accept mpUVM being NULL and return a failure
7061 * (otherwise this method will assert if mpUVM is NULL)
7062 *
7063 * @note Locks this object for writing.
7064 */
7065HRESULT Console::i_addVMCaller(bool aQuiet /* = false */,
7066 bool aAllowNullVM /* = false */)
7067{
7068 RT_NOREF(aAllowNullVM);
7069 AutoCaller autoCaller(this);
7070 /** @todo Fix race during console/VM reference destruction, refer @bugref{6318}
7071 * comment 25. */
7072 if (FAILED(autoCaller.rc()))
7073 return autoCaller.rc();
7074
7075 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7076
7077 if (mVMDestroying)
7078 {
7079 /* powerDown() is waiting for all callers to finish */
7080 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED,
7081 tr("The virtual machine is being powered down"));
7082 }
7083
7084 if (mpUVM == NULL)
7085 {
7086 Assert(aAllowNullVM == true);
7087
7088 /* The machine is not powered up */
7089 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED,
7090 tr("The virtual machine is not powered up"));
7091 }
7092
7093 ++mVMCallers;
7094
7095 return S_OK;
7096}
7097
7098/**
7099 * Decreases the usage counter of the mpUVM pointer.
7100 *
7101 * Must always complete the addVMCaller() call after the mpUVM pointer is no
7102 * more necessary.
7103 *
7104 * @note Locks this object for writing.
7105 */
7106void Console::i_releaseVMCaller()
7107{
7108 AutoCaller autoCaller(this);
7109 AssertComRCReturnVoid(autoCaller.rc());
7110
7111 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7112
7113 AssertReturnVoid(mpUVM != NULL);
7114
7115 Assert(mVMCallers > 0);
7116 --mVMCallers;
7117
7118 if (mVMCallers == 0 && mVMDestroying)
7119 {
7120 /* inform powerDown() there are no more callers */
7121 RTSemEventSignal(mVMZeroCallersSem);
7122 }
7123}
7124
7125
7126HRESULT Console::i_safeVMPtrRetainer(PUVM *a_ppUVM, bool a_Quiet)
7127{
7128 *a_ppUVM = NULL;
7129
7130 AutoCaller autoCaller(this);
7131 AssertComRCReturnRC(autoCaller.rc());
7132 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7133
7134 /*
7135 * Repeat the checks done by addVMCaller.
7136 */
7137 if (mVMDestroying) /* powerDown() is waiting for all callers to finish */
7138 return a_Quiet
7139 ? E_ACCESSDENIED
7140 : setError(E_ACCESSDENIED, tr("The virtual machine is being powered down"));
7141 PUVM pUVM = mpUVM;
7142 if (!pUVM)
7143 return a_Quiet
7144 ? E_ACCESSDENIED
7145 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
7146
7147 /*
7148 * Retain a reference to the user mode VM handle and get the global handle.
7149 */
7150 uint32_t cRefs = VMR3RetainUVM(pUVM);
7151 if (cRefs == UINT32_MAX)
7152 return a_Quiet
7153 ? E_ACCESSDENIED
7154 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
7155
7156 /* done */
7157 *a_ppUVM = pUVM;
7158 return S_OK;
7159}
7160
7161void Console::i_safeVMPtrReleaser(PUVM *a_ppUVM)
7162{
7163 if (*a_ppUVM)
7164 VMR3ReleaseUVM(*a_ppUVM);
7165 *a_ppUVM = NULL;
7166}
7167
7168
7169/**
7170 * Initialize the release logging facility. In case something
7171 * goes wrong, there will be no release logging. Maybe in the future
7172 * we can add some logic to use different file names in this case.
7173 * Note that the logic must be in sync with Machine::DeleteSettings().
7174 */
7175HRESULT Console::i_consoleInitReleaseLog(const ComPtr<IMachine> aMachine)
7176{
7177 HRESULT hrc = S_OK;
7178
7179 Bstr logFolder;
7180 hrc = aMachine->COMGETTER(LogFolder)(logFolder.asOutParam());
7181 if (FAILED(hrc))
7182 return hrc;
7183
7184 Utf8Str logDir = logFolder;
7185
7186 /* make sure the Logs folder exists */
7187 Assert(logDir.length());
7188 if (!RTDirExists(logDir.c_str()))
7189 RTDirCreateFullPath(logDir.c_str(), 0700);
7190
7191 Utf8Str logFile = Utf8StrFmt("%s%cVBox.log",
7192 logDir.c_str(), RTPATH_DELIMITER);
7193 Utf8Str pngFile = Utf8StrFmt("%s%cVBox.png",
7194 logDir.c_str(), RTPATH_DELIMITER);
7195
7196 /*
7197 * Age the old log files
7198 * Rename .(n-1) to .(n), .(n-2) to .(n-1), ..., and the last log file to .1
7199 * Overwrite target files in case they exist.
7200 */
7201 ComPtr<IVirtualBox> pVirtualBox;
7202 aMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
7203 ComPtr<ISystemProperties> pSystemProperties;
7204 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
7205 ULONG cHistoryFiles = 3;
7206 pSystemProperties->COMGETTER(LogHistoryCount)(&cHistoryFiles);
7207 if (cHistoryFiles)
7208 {
7209 for (int i = cHistoryFiles-1; i >= 0; i--)
7210 {
7211 Utf8Str *files[] = { &logFile, &pngFile };
7212 Utf8Str oldName, newName;
7213
7214 for (unsigned int j = 0; j < RT_ELEMENTS(files); ++j)
7215 {
7216 if (i > 0)
7217 oldName = Utf8StrFmt("%s.%d", files[j]->c_str(), i);
7218 else
7219 oldName = *files[j];
7220 newName = Utf8StrFmt("%s.%d", files[j]->c_str(), i + 1);
7221 /* If the old file doesn't exist, delete the new file (if it
7222 * exists) to provide correct rotation even if the sequence is
7223 * broken */
7224 if ( RTFileRename(oldName.c_str(), newName.c_str(), RTFILEMOVE_FLAGS_REPLACE)
7225 == VERR_FILE_NOT_FOUND)
7226 RTFileDelete(newName.c_str());
7227 }
7228 }
7229 }
7230
7231 char szError[RTPATH_MAX + 128];
7232 int vrc = com::VBoxLogRelCreate("VM", logFile.c_str(),
7233 RTLOGFLAGS_PREFIX_TIME_PROG | RTLOGFLAGS_RESTRICT_GROUPS,
7234 "all all.restrict -default.restrict",
7235 "VBOX_RELEASE_LOG", RTLOGDEST_FILE,
7236 32768 /* cMaxEntriesPerGroup */,
7237 0 /* cHistory */, 0 /* uHistoryFileTime */,
7238 0 /* uHistoryFileSize */, szError, sizeof(szError));
7239 if (RT_FAILURE(vrc))
7240 hrc = setError(E_FAIL, tr("Failed to open release log (%s, %Rrc)"),
7241 szError, vrc);
7242
7243 /* If we've made any directory changes, flush the directory to increase
7244 the likelihood that the log file will be usable after a system panic.
7245
7246 Tip: Try 'export VBOX_RELEASE_LOG_FLAGS=flush' if the last bits of the log
7247 is missing. Just don't have too high hopes for this to help. */
7248 if (SUCCEEDED(hrc) || cHistoryFiles)
7249 RTDirFlush(logDir.c_str());
7250
7251 return hrc;
7252}
7253
7254/**
7255 * Common worker for PowerUp and PowerUpPaused.
7256 *
7257 * @returns COM status code.
7258 *
7259 * @param aProgress Where to return the progress object.
7260 * @param aPaused true if PowerUpPaused called.
7261 */
7262HRESULT Console::i_powerUp(IProgress **aProgress, bool aPaused)
7263{
7264 LogFlowThisFuncEnter();
7265
7266 CheckComArgOutPointerValid(aProgress);
7267
7268 AutoCaller autoCaller(this);
7269 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7270
7271 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7272
7273 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
7274 HRESULT rc = S_OK;
7275 ComObjPtr<Progress> pPowerupProgress;
7276 bool fBeganPoweringUp = false;
7277
7278 LONG cOperations = 1;
7279 LONG ulTotalOperationsWeight = 1;
7280 VMPowerUpTask* task = NULL;
7281
7282 try
7283 {
7284 if (Global::IsOnlineOrTransient(mMachineState))
7285 throw setError(VBOX_E_INVALID_VM_STATE,
7286 tr("The virtual machine is already running or busy (machine state: %s)"),
7287 Global::stringifyMachineState(mMachineState));
7288
7289 /* Set up release logging as early as possible after the check if
7290 * there is already a running VM which we shouldn't disturb. */
7291 rc = i_consoleInitReleaseLog(mMachine);
7292 if (FAILED(rc))
7293 throw rc;
7294
7295#ifdef VBOX_OPENSSL_FIPS
7296 LogRel(("crypto: FIPS mode %s\n", FIPS_mode() ? "enabled" : "FAILED"));
7297#endif
7298
7299 /* test and clear the TeleporterEnabled property */
7300 BOOL fTeleporterEnabled;
7301 rc = mMachine->COMGETTER(TeleporterEnabled)(&fTeleporterEnabled);
7302 if (FAILED(rc))
7303 throw rc;
7304
7305#if 0 /** @todo we should save it afterwards, but that isn't necessarily a good idea. Find a better place for this (VBoxSVC). */
7306 if (fTeleporterEnabled)
7307 {
7308 rc = mMachine->COMSETTER(TeleporterEnabled)(FALSE);
7309 if (FAILED(rc))
7310 throw rc;
7311 }
7312#endif
7313
7314 /* test the FaultToleranceState property */
7315 FaultToleranceState_T enmFaultToleranceState;
7316 rc = mMachine->COMGETTER(FaultToleranceState)(&enmFaultToleranceState);
7317 if (FAILED(rc))
7318 throw rc;
7319 BOOL fFaultToleranceSyncEnabled = (enmFaultToleranceState == FaultToleranceState_Standby);
7320
7321 /* Create a progress object to track progress of this operation. Must
7322 * be done as early as possible (together with BeginPowerUp()) as this
7323 * is vital for communicating as much as possible early powerup
7324 * failure information to the API caller */
7325 pPowerupProgress.createObject();
7326 Bstr progressDesc;
7327 if (mMachineState == MachineState_Saved)
7328 progressDesc = tr("Restoring virtual machine");
7329 else if (fTeleporterEnabled)
7330 progressDesc = tr("Teleporting virtual machine");
7331 else if (fFaultToleranceSyncEnabled)
7332 progressDesc = tr("Fault Tolerance syncing of remote virtual machine");
7333 else
7334 progressDesc = tr("Starting virtual machine");
7335
7336 Bstr savedStateFile;
7337
7338 /*
7339 * Saved VMs will have to prove that their saved states seem kosher.
7340 */
7341 if (mMachineState == MachineState_Saved)
7342 {
7343 rc = mMachine->COMGETTER(StateFilePath)(savedStateFile.asOutParam());
7344 if (FAILED(rc))
7345 throw rc;
7346 ComAssertRet(!savedStateFile.isEmpty(), E_FAIL);
7347 int vrc = SSMR3ValidateFile(Utf8Str(savedStateFile).c_str(), false /* fChecksumIt */);
7348 if (RT_FAILURE(vrc))
7349 throw setError(VBOX_E_FILE_ERROR,
7350 tr("VM cannot start because the saved state file '%ls' is invalid (%Rrc). Delete the saved state prior to starting the VM"),
7351 savedStateFile.raw(), vrc);
7352 }
7353
7354 /* Read console data, including console shared folders, stored in the
7355 * saved state file (if not yet done).
7356 */
7357 rc = i_loadDataFromSavedState();
7358 if (FAILED(rc))
7359 throw rc;
7360
7361 /* Check all types of shared folders and compose a single list */
7362 SharedFolderDataMap sharedFolders;
7363 {
7364 /* first, insert global folders */
7365 for (SharedFolderDataMap::const_iterator it = m_mapGlobalSharedFolders.begin();
7366 it != m_mapGlobalSharedFolders.end();
7367 ++it)
7368 {
7369 const SharedFolderData &d = it->second;
7370 sharedFolders[it->first] = d;
7371 }
7372
7373 /* second, insert machine folders */
7374 for (SharedFolderDataMap::const_iterator it = m_mapMachineSharedFolders.begin();
7375 it != m_mapMachineSharedFolders.end();
7376 ++it)
7377 {
7378 const SharedFolderData &d = it->second;
7379 sharedFolders[it->first] = d;
7380 }
7381
7382 /* third, insert console folders */
7383 for (SharedFolderMap::const_iterator it = m_mapSharedFolders.begin();
7384 it != m_mapSharedFolders.end();
7385 ++it)
7386 {
7387 SharedFolder *pSF = it->second;
7388 AutoCaller sfCaller(pSF);
7389 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
7390 sharedFolders[it->first] = SharedFolderData(pSF->i_getHostPath(),
7391 pSF->i_isWritable(),
7392 pSF->i_isAutoMounted());
7393 }
7394 }
7395
7396
7397 /* Setup task object and thread to carry out the operation
7398 * asynchronously */
7399 try
7400 {
7401 task = new VMPowerUpTask(this, pPowerupProgress);
7402 if (!task->isOk())
7403 {
7404 throw E_FAIL;
7405 }
7406 }
7407 catch(...)
7408 {
7409 delete task;
7410 rc = setError(E_FAIL, "Could not create VMPowerUpTask object \n");
7411 throw rc;
7412 }
7413
7414 task->mConfigConstructor = i_configConstructor;
7415 task->mSharedFolders = sharedFolders;
7416 task->mStartPaused = aPaused;
7417 if (mMachineState == MachineState_Saved)
7418 task->mSavedStateFile = savedStateFile;
7419 task->mTeleporterEnabled = fTeleporterEnabled;
7420 task->mEnmFaultToleranceState = enmFaultToleranceState;
7421
7422 /* Reset differencing hard disks for which autoReset is true,
7423 * but only if the machine has no snapshots OR the current snapshot
7424 * is an OFFLINE snapshot; otherwise we would reset the current
7425 * differencing image of an ONLINE snapshot which contains the disk
7426 * state of the machine while it was previously running, but without
7427 * the corresponding machine state, which is equivalent to powering
7428 * off a running machine and not good idea
7429 */
7430 ComPtr<ISnapshot> pCurrentSnapshot;
7431 rc = mMachine->COMGETTER(CurrentSnapshot)(pCurrentSnapshot.asOutParam());
7432 if (FAILED(rc))
7433 throw rc;
7434
7435 BOOL fCurrentSnapshotIsOnline = false;
7436 if (pCurrentSnapshot)
7437 {
7438 rc = pCurrentSnapshot->COMGETTER(Online)(&fCurrentSnapshotIsOnline);
7439 if (FAILED(rc))
7440 throw rc;
7441 }
7442
7443 if (savedStateFile.isEmpty() && !fCurrentSnapshotIsOnline)
7444 {
7445 LogFlowThisFunc(("Looking for immutable images to reset\n"));
7446
7447 com::SafeIfaceArray<IMediumAttachment> atts;
7448 rc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
7449 if (FAILED(rc))
7450 throw rc;
7451
7452 for (size_t i = 0;
7453 i < atts.size();
7454 ++i)
7455 {
7456 DeviceType_T devType;
7457 rc = atts[i]->COMGETTER(Type)(&devType);
7458 /** @todo later applies to floppies as well */
7459 if (devType == DeviceType_HardDisk)
7460 {
7461 ComPtr<IMedium> pMedium;
7462 rc = atts[i]->COMGETTER(Medium)(pMedium.asOutParam());
7463 if (FAILED(rc))
7464 throw rc;
7465
7466 /* needs autoreset? */
7467 BOOL autoReset = FALSE;
7468 rc = pMedium->COMGETTER(AutoReset)(&autoReset);
7469 if (FAILED(rc))
7470 throw rc;
7471
7472 if (autoReset)
7473 {
7474 ComPtr<IProgress> pResetProgress;
7475 rc = pMedium->Reset(pResetProgress.asOutParam());
7476 if (FAILED(rc))
7477 throw rc;
7478
7479 /* save for later use on the powerup thread */
7480 task->hardDiskProgresses.push_back(pResetProgress);
7481 }
7482 }
7483 }
7484 }
7485 else
7486 LogFlowThisFunc(("Machine has a current snapshot which is online, skipping immutable images reset\n"));
7487
7488 /* setup task object and thread to carry out the operation
7489 * asynchronously */
7490
7491#ifdef VBOX_WITH_EXTPACK
7492 mptrExtPackManager->i_dumpAllToReleaseLog();
7493#endif
7494
7495#ifdef RT_OS_SOLARIS
7496 /* setup host core dumper for the VM */
7497 Bstr value;
7498 HRESULT hrc = mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpEnabled").raw(), value.asOutParam());
7499 if (SUCCEEDED(hrc) && value == "1")
7500 {
7501 Bstr coreDumpDir, coreDumpReplaceSys, coreDumpLive;
7502 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpDir").raw(), coreDumpDir.asOutParam());
7503 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpReplaceSystemDump").raw(), coreDumpReplaceSys.asOutParam());
7504 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpLive").raw(), coreDumpLive.asOutParam());
7505
7506 uint32_t fCoreFlags = 0;
7507 if ( coreDumpReplaceSys.isEmpty() == false
7508 && Utf8Str(coreDumpReplaceSys).toUInt32() == 1)
7509 fCoreFlags |= RTCOREDUMPER_FLAGS_REPLACE_SYSTEM_DUMP;
7510
7511 if ( coreDumpLive.isEmpty() == false
7512 && Utf8Str(coreDumpLive).toUInt32() == 1)
7513 fCoreFlags |= RTCOREDUMPER_FLAGS_LIVE_CORE;
7514
7515 Utf8Str strDumpDir(coreDumpDir);
7516 const char *pszDumpDir = strDumpDir.c_str();
7517 if ( pszDumpDir
7518 && *pszDumpDir == '\0')
7519 pszDumpDir = NULL;
7520
7521 int vrc;
7522 if ( pszDumpDir
7523 && !RTDirExists(pszDumpDir))
7524 {
7525 /*
7526 * Try create the directory.
7527 */
7528 vrc = RTDirCreateFullPath(pszDumpDir, 0700);
7529 if (RT_FAILURE(vrc))
7530 throw setError(E_FAIL, "Failed to setup CoreDumper. Couldn't create dump directory '%s' (%Rrc)\n",
7531 pszDumpDir, vrc);
7532 }
7533
7534 vrc = RTCoreDumperSetup(pszDumpDir, fCoreFlags);
7535 if (RT_FAILURE(vrc))
7536 throw setError(E_FAIL, "Failed to setup CoreDumper (%Rrc)", vrc);
7537 else
7538 LogRel(("CoreDumper setup successful. pszDumpDir=%s fFlags=%#x\n", pszDumpDir ? pszDumpDir : ".", fCoreFlags));
7539 }
7540#endif
7541
7542
7543 // If there is immutable drive the process that.
7544 VMPowerUpTask::ProgressList progresses(task->hardDiskProgresses);
7545 if (aProgress && progresses.size() > 0)
7546 {
7547 for (VMPowerUpTask::ProgressList::const_iterator it = progresses.begin(); it != progresses.end(); ++it)
7548 {
7549 ++cOperations;
7550 ulTotalOperationsWeight += 1;
7551 }
7552 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7553 progressDesc.raw(),
7554 TRUE, // Cancelable
7555 cOperations,
7556 ulTotalOperationsWeight,
7557 Bstr(tr("Starting Hard Disk operations")).raw(),
7558 1);
7559 AssertComRCReturnRC(rc);
7560 }
7561 else if ( mMachineState == MachineState_Saved
7562 || (!fTeleporterEnabled && !fFaultToleranceSyncEnabled))
7563 {
7564 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7565 progressDesc.raw(),
7566 FALSE /* aCancelable */);
7567 }
7568 else if (fTeleporterEnabled)
7569 {
7570 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7571 progressDesc.raw(),
7572 TRUE /* aCancelable */,
7573 3 /* cOperations */,
7574 10 /* ulTotalOperationsWeight */,
7575 Bstr(tr("Teleporting virtual machine")).raw(),
7576 1 /* ulFirstOperationWeight */);
7577 }
7578 else if (fFaultToleranceSyncEnabled)
7579 {
7580 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7581 progressDesc.raw(),
7582 TRUE /* aCancelable */,
7583 3 /* cOperations */,
7584 10 /* ulTotalOperationsWeight */,
7585 Bstr(tr("Fault Tolerance syncing of remote virtual machine")).raw(),
7586 1 /* ulFirstOperationWeight */);
7587 }
7588
7589 if (FAILED(rc))
7590 throw rc;
7591
7592 /* Tell VBoxSVC and Machine about the progress object so they can
7593 combine/proxy it to any openRemoteSession caller. */
7594 LogFlowThisFunc(("Calling BeginPowerUp...\n"));
7595 rc = mControl->BeginPowerUp(pPowerupProgress);
7596 if (FAILED(rc))
7597 {
7598 LogFlowThisFunc(("BeginPowerUp failed\n"));
7599 throw rc;
7600 }
7601 fBeganPoweringUp = true;
7602
7603 LogFlowThisFunc(("Checking if canceled...\n"));
7604 BOOL fCanceled;
7605 rc = pPowerupProgress->COMGETTER(Canceled)(&fCanceled);
7606 if (FAILED(rc))
7607 throw rc;
7608
7609 if (fCanceled)
7610 {
7611 LogFlowThisFunc(("Canceled in BeginPowerUp\n"));
7612 throw setError(E_FAIL, tr("Powerup was canceled"));
7613 }
7614 LogFlowThisFunc(("Not canceled yet.\n"));
7615
7616 /** @todo this code prevents starting a VM with unavailable bridged
7617 * networking interface. The only benefit is a slightly better error
7618 * message, which should be moved to the driver code. This is the
7619 * only reason why I left the code in for now. The driver allows
7620 * unavailable bridged networking interfaces in certain circumstances,
7621 * and this is sabotaged by this check. The VM will initially have no
7622 * network connectivity, but the user can fix this at runtime. */
7623#if 0
7624 /* the network cards will undergo a quick consistency check */
7625 for (ULONG slot = 0;
7626 slot < maxNetworkAdapters;
7627 ++slot)
7628 {
7629 ComPtr<INetworkAdapter> pNetworkAdapter;
7630 mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
7631 BOOL enabled = FALSE;
7632 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
7633 if (!enabled)
7634 continue;
7635
7636 NetworkAttachmentType_T netattach;
7637 pNetworkAdapter->COMGETTER(AttachmentType)(&netattach);
7638 switch (netattach)
7639 {
7640 case NetworkAttachmentType_Bridged:
7641 {
7642 /* a valid host interface must have been set */
7643 Bstr hostif;
7644 pNetworkAdapter->COMGETTER(HostInterface)(hostif.asOutParam());
7645 if (hostif.isEmpty())
7646 {
7647 throw setError(VBOX_E_HOST_ERROR,
7648 tr("VM cannot start because host interface networking requires a host interface name to be set"));
7649 }
7650 ComPtr<IVirtualBox> pVirtualBox;
7651 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
7652 ComPtr<IHost> pHost;
7653 pVirtualBox->COMGETTER(Host)(pHost.asOutParam());
7654 ComPtr<IHostNetworkInterface> pHostInterface;
7655 if (!SUCCEEDED(pHost->FindHostNetworkInterfaceByName(hostif.raw(),
7656 pHostInterface.asOutParam())))
7657 {
7658 throw setError(VBOX_E_HOST_ERROR,
7659 tr("VM cannot start because the host interface '%ls' does not exist"),
7660 hostif.raw());
7661 }
7662 break;
7663 }
7664 default:
7665 break;
7666 }
7667 }
7668#endif // 0
7669
7670
7671 /* setup task object and thread to carry out the operation
7672 * asynchronously */
7673 if (aProgress){
7674 rc = pPowerupProgress.queryInterfaceTo(aProgress);
7675 AssertComRCReturnRC(rc);
7676 }
7677
7678 rc = task->createThread();
7679
7680 if (FAILED(rc))
7681 throw rc;
7682
7683 /* finally, set the state: no right to fail in this method afterwards
7684 * since we've already started the thread and it is now responsible for
7685 * any error reporting and appropriate state change! */
7686 if (mMachineState == MachineState_Saved)
7687 i_setMachineState(MachineState_Restoring);
7688 else if (fTeleporterEnabled)
7689 i_setMachineState(MachineState_TeleportingIn);
7690 else if (enmFaultToleranceState == FaultToleranceState_Standby)
7691 i_setMachineState(MachineState_FaultTolerantSyncing);
7692 else
7693 i_setMachineState(MachineState_Starting);
7694 }
7695 catch (HRESULT aRC) { rc = aRC; }
7696
7697 if (FAILED(rc) && fBeganPoweringUp)
7698 {
7699
7700 /* The progress object will fetch the current error info */
7701 if (!pPowerupProgress.isNull())
7702 pPowerupProgress->i_notifyComplete(rc);
7703
7704 /* Save the error info across the IPC below. Can't be done before the
7705 * progress notification above, as saving the error info deletes it
7706 * from the current context, and thus the progress object wouldn't be
7707 * updated correctly. */
7708 ErrorInfoKeeper eik;
7709
7710 /* signal end of operation */
7711 mControl->EndPowerUp(rc);
7712 }
7713
7714 LogFlowThisFunc(("mMachineState=%d, rc=%Rhrc\n", mMachineState, rc));
7715 LogFlowThisFuncLeave();
7716 return rc;
7717}
7718
7719/**
7720 * Internal power off worker routine.
7721 *
7722 * This method may be called only at certain places with the following meaning
7723 * as shown below:
7724 *
7725 * - if the machine state is either Running or Paused, a normal
7726 * Console-initiated powerdown takes place (e.g. PowerDown());
7727 * - if the machine state is Saving, saveStateThread() has successfully done its
7728 * job;
7729 * - if the machine state is Starting or Restoring, powerUpThread() has failed
7730 * to start/load the VM;
7731 * - if the machine state is Stopping, the VM has powered itself off (i.e. not
7732 * as a result of the powerDown() call).
7733 *
7734 * Calling it in situations other than the above will cause unexpected behavior.
7735 *
7736 * Note that this method should be the only one that destroys mpUVM and sets it
7737 * to NULL.
7738 *
7739 * @param aProgress Progress object to run (may be NULL).
7740 *
7741 * @note Locks this object for writing.
7742 *
7743 * @note Never call this method from a thread that called addVMCaller() or
7744 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
7745 * release(). Otherwise it will deadlock.
7746 */
7747HRESULT Console::i_powerDown(IProgress *aProgress /*= NULL*/)
7748{
7749 LogFlowThisFuncEnter();
7750
7751 AutoCaller autoCaller(this);
7752 AssertComRCReturnRC(autoCaller.rc());
7753
7754 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7755
7756 /* Total # of steps for the progress object. Must correspond to the
7757 * number of "advance percent count" comments in this method! */
7758 enum { StepCount = 7 };
7759 /* current step */
7760 ULONG step = 0;
7761
7762 HRESULT rc = S_OK;
7763 int vrc = VINF_SUCCESS;
7764
7765 /* sanity */
7766 Assert(mVMDestroying == false);
7767
7768 PUVM pUVM = mpUVM; Assert(pUVM != NULL);
7769 uint32_t cRefs = VMR3RetainUVM(pUVM); Assert(cRefs != UINT32_MAX); NOREF(cRefs);
7770
7771 AssertMsg( mMachineState == MachineState_Running
7772 || mMachineState == MachineState_Paused
7773 || mMachineState == MachineState_Stuck
7774 || mMachineState == MachineState_Starting
7775 || mMachineState == MachineState_Stopping
7776 || mMachineState == MachineState_Saving
7777 || mMachineState == MachineState_Restoring
7778 || mMachineState == MachineState_TeleportingPausedVM
7779 || mMachineState == MachineState_FaultTolerantSyncing
7780 || mMachineState == MachineState_TeleportingIn
7781 , ("Invalid machine state: %s\n", Global::stringifyMachineState(mMachineState)));
7782
7783 LogRel(("Console::powerDown(): A request to power off the VM has been issued (mMachineState=%s, InUninit=%d)\n",
7784 Global::stringifyMachineState(mMachineState), getObjectState().getState() == ObjectState::InUninit));
7785
7786 /* Check if we need to power off the VM. In case of mVMPoweredOff=true, the
7787 * VM has already powered itself off in vmstateChangeCallback() and is just
7788 * notifying Console about that. In case of Starting or Restoring,
7789 * powerUpThread() is calling us on failure, so the VM is already off at
7790 * that point. */
7791 if ( !mVMPoweredOff
7792 && ( mMachineState == MachineState_Starting
7793 || mMachineState == MachineState_Restoring
7794 || mMachineState == MachineState_FaultTolerantSyncing
7795 || mMachineState == MachineState_TeleportingIn)
7796 )
7797 mVMPoweredOff = true;
7798
7799 /*
7800 * Go to Stopping state if not already there.
7801 *
7802 * Note that we don't go from Saving/Restoring to Stopping because
7803 * vmstateChangeCallback() needs it to set the state to Saved on
7804 * VMSTATE_TERMINATED. In terms of protecting from inappropriate operations
7805 * while leaving the lock below, Saving or Restoring should be fine too.
7806 * Ditto for TeleportingPausedVM -> Teleported.
7807 */
7808 if ( mMachineState != MachineState_Saving
7809 && mMachineState != MachineState_Restoring
7810 && mMachineState != MachineState_Stopping
7811 && mMachineState != MachineState_TeleportingIn
7812 && mMachineState != MachineState_TeleportingPausedVM
7813 && mMachineState != MachineState_FaultTolerantSyncing
7814 )
7815 i_setMachineState(MachineState_Stopping);
7816
7817 /* ----------------------------------------------------------------------
7818 * DONE with necessary state changes, perform the power down actions (it's
7819 * safe to release the object lock now if needed)
7820 * ---------------------------------------------------------------------- */
7821
7822 if (mDisplay)
7823 {
7824 alock.release();
7825
7826 mDisplay->i_notifyPowerDown();
7827
7828 alock.acquire();
7829 }
7830
7831 /* Stop the VRDP server to prevent new clients connection while VM is being
7832 * powered off. */
7833 if (mConsoleVRDPServer)
7834 {
7835 LogFlowThisFunc(("Stopping VRDP server...\n"));
7836
7837 /* Leave the lock since EMT could call us back as addVMCaller() */
7838 alock.release();
7839
7840 mConsoleVRDPServer->Stop();
7841
7842 alock.acquire();
7843 }
7844
7845 /* advance percent count */
7846 if (aProgress)
7847 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount );
7848
7849
7850 /* ----------------------------------------------------------------------
7851 * Now, wait for all mpUVM callers to finish their work if there are still
7852 * some on other threads. NO methods that need mpUVM (or initiate other calls
7853 * that need it) may be called after this point
7854 * ---------------------------------------------------------------------- */
7855
7856 /* go to the destroying state to prevent from adding new callers */
7857 mVMDestroying = true;
7858
7859 if (mVMCallers > 0)
7860 {
7861 /* lazy creation */
7862 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
7863 RTSemEventCreate(&mVMZeroCallersSem);
7864
7865 LogFlowThisFunc(("Waiting for mpUVM callers (%d) to drop to zero...\n", mVMCallers));
7866
7867 alock.release();
7868
7869 RTSemEventWait(mVMZeroCallersSem, RT_INDEFINITE_WAIT);
7870
7871 alock.acquire();
7872 }
7873
7874 /* advance percent count */
7875 if (aProgress)
7876 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount );
7877
7878 vrc = VINF_SUCCESS;
7879
7880 /*
7881 * Power off the VM if not already done that.
7882 * Leave the lock since EMT will call vmstateChangeCallback.
7883 *
7884 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
7885 * VM-(guest-)initiated power off happened in parallel a ms before this
7886 * call. So far, we let this error pop up on the user's side.
7887 */
7888 if (!mVMPoweredOff)
7889 {
7890 LogFlowThisFunc(("Powering off the VM...\n"));
7891 alock.release();
7892 vrc = VMR3PowerOff(pUVM);
7893#ifdef VBOX_WITH_EXTPACK
7894 mptrExtPackManager->i_callAllVmPowerOffHooks(this, VMR3GetVM(pUVM));
7895#endif
7896 alock.acquire();
7897 }
7898
7899 /* advance percent count */
7900 if (aProgress)
7901 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount );
7902
7903#ifdef VBOX_WITH_HGCM
7904 /* Shutdown HGCM services before destroying the VM. */
7905 if (m_pVMMDev)
7906 {
7907 LogFlowThisFunc(("Shutdown HGCM...\n"));
7908
7909 /* Leave the lock since EMT might wait for it and will call us back as addVMCaller() */
7910 alock.release();
7911
7912 m_pVMMDev->hgcmShutdown();
7913
7914 alock.acquire();
7915 }
7916
7917 /* advance percent count */
7918 if (aProgress)
7919 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount);
7920
7921#endif /* VBOX_WITH_HGCM */
7922
7923 LogFlowThisFunc(("Ready for VM destruction.\n"));
7924
7925 /* If we are called from Console::uninit(), then try to destroy the VM even
7926 * on failure (this will most likely fail too, but what to do?..) */
7927 if (RT_SUCCESS(vrc) || getObjectState().getState() == ObjectState::InUninit)
7928 {
7929 /* If the machine has a USB controller, release all USB devices
7930 * (symmetric to the code in captureUSBDevices()) */
7931 if (mfVMHasUsbController)
7932 {
7933 alock.release();
7934 i_detachAllUSBDevices(false /* aDone */);
7935 alock.acquire();
7936 }
7937
7938 /* Now we've got to destroy the VM as well. (mpUVM is not valid beyond
7939 * this point). We release the lock before calling VMR3Destroy() because
7940 * it will result into calling destructors of drivers associated with
7941 * Console children which may in turn try to lock Console (e.g. by
7942 * instantiating SafeVMPtr to access mpUVM). It's safe here because
7943 * mVMDestroying is set which should prevent any activity. */
7944
7945 /* Set mpUVM to NULL early just in case if some old code is not using
7946 * addVMCaller()/releaseVMCaller(). (We have our own ref on pUVM.) */
7947 VMR3ReleaseUVM(mpUVM);
7948 mpUVM = NULL;
7949
7950 LogFlowThisFunc(("Destroying the VM...\n"));
7951
7952 alock.release();
7953
7954 vrc = VMR3Destroy(pUVM);
7955
7956 /* take the lock again */
7957 alock.acquire();
7958
7959 /* advance percent count */
7960 if (aProgress)
7961 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount);
7962
7963 if (RT_SUCCESS(vrc))
7964 {
7965 LogFlowThisFunc(("Machine has been destroyed (mMachineState=%d)\n",
7966 mMachineState));
7967 /* Note: the Console-level machine state change happens on the
7968 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
7969 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
7970 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
7971 * occurred yet. This is okay, because mMachineState is already
7972 * Stopping in this case, so any other attempt to call PowerDown()
7973 * will be rejected. */
7974 }
7975 else
7976 {
7977 /* bad bad bad, but what to do? (Give Console our UVM ref.) */
7978 mpUVM = pUVM;
7979 pUVM = NULL;
7980 rc = setError(VBOX_E_VM_ERROR,
7981 tr("Could not destroy the machine. (Error: %Rrc)"),
7982 vrc);
7983 }
7984
7985 /* Complete the detaching of the USB devices. */
7986 if (mfVMHasUsbController)
7987 {
7988 alock.release();
7989 i_detachAllUSBDevices(true /* aDone */);
7990 alock.acquire();
7991 }
7992
7993 /* advance percent count */
7994 if (aProgress)
7995 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount);
7996 }
7997 else
7998 {
7999 rc = setError(VBOX_E_VM_ERROR,
8000 tr("Could not power off the machine. (Error: %Rrc)"),
8001 vrc);
8002 }
8003
8004 /*
8005 * Finished with the destruction.
8006 *
8007 * Note that if something impossible happened and we've failed to destroy
8008 * the VM, mVMDestroying will remain true and mMachineState will be
8009 * something like Stopping, so most Console methods will return an error
8010 * to the caller.
8011 */
8012 if (pUVM != NULL)
8013 VMR3ReleaseUVM(pUVM);
8014 else
8015 mVMDestroying = false;
8016
8017 LogFlowThisFuncLeave();
8018 return rc;
8019}
8020
8021/**
8022 * @note Locks this object for writing.
8023 */
8024HRESULT Console::i_setMachineState(MachineState_T aMachineState,
8025 bool aUpdateServer /* = true */)
8026{
8027 AutoCaller autoCaller(this);
8028 AssertComRCReturnRC(autoCaller.rc());
8029
8030 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8031
8032 HRESULT rc = S_OK;
8033
8034 if (mMachineState != aMachineState)
8035 {
8036 LogThisFunc(("machineState=%s -> %s aUpdateServer=%RTbool\n",
8037 Global::stringifyMachineState(mMachineState), Global::stringifyMachineState(aMachineState), aUpdateServer));
8038 LogRel(("Console: Machine state changed to '%s'\n", Global::stringifyMachineState(aMachineState)));
8039 mMachineState = aMachineState;
8040
8041 /// @todo (dmik)
8042 // possibly, we need to redo onStateChange() using the dedicated
8043 // Event thread, like it is done in VirtualBox. This will make it
8044 // much safer (no deadlocks possible if someone tries to use the
8045 // console from the callback), however, listeners will lose the
8046 // ability to synchronously react to state changes (is it really
8047 // necessary??)
8048 LogFlowThisFunc(("Doing onStateChange()...\n"));
8049 i_onStateChange(aMachineState);
8050 LogFlowThisFunc(("Done onStateChange()\n"));
8051
8052 if (aUpdateServer)
8053 {
8054 /* Server notification MUST be done from under the lock; otherwise
8055 * the machine state here and on the server might go out of sync
8056 * which can lead to various unexpected results (like the machine
8057 * state being >= MachineState_Running on the server, while the
8058 * session state is already SessionState_Unlocked at the same time
8059 * there).
8060 *
8061 * Cross-lock conditions should be carefully watched out: calling
8062 * UpdateState we will require Machine and SessionMachine locks
8063 * (remember that here we're holding the Console lock here, and also
8064 * all locks that have been acquire by the thread before calling
8065 * this method).
8066 */
8067 LogFlowThisFunc(("Doing mControl->UpdateState()...\n"));
8068 rc = mControl->UpdateState(aMachineState);
8069 LogFlowThisFunc(("mControl->UpdateState()=%Rhrc\n", rc));
8070 }
8071 }
8072
8073 return rc;
8074}
8075
8076/**
8077 * Searches for a shared folder with the given logical name
8078 * in the collection of shared folders.
8079 *
8080 * @param strName logical name of the shared folder
8081 * @param aSharedFolder where to return the found object
8082 * @param aSetError whether to set the error info if the folder is
8083 * not found
8084 * @return
8085 * S_OK when found or E_INVALIDARG when not found
8086 *
8087 * @note The caller must lock this object for writing.
8088 */
8089HRESULT Console::i_findSharedFolder(const Utf8Str &strName,
8090 ComObjPtr<SharedFolder> &aSharedFolder,
8091 bool aSetError /* = false */)
8092{
8093 /* sanity check */
8094 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8095
8096 SharedFolderMap::const_iterator it = m_mapSharedFolders.find(strName);
8097 if (it != m_mapSharedFolders.end())
8098 {
8099 aSharedFolder = it->second;
8100 return S_OK;
8101 }
8102
8103 if (aSetError)
8104 setError(VBOX_E_FILE_ERROR,
8105 tr("Could not find a shared folder named '%s'."),
8106 strName.c_str());
8107
8108 return VBOX_E_FILE_ERROR;
8109}
8110
8111/**
8112 * Fetches the list of global or machine shared folders from the server.
8113 *
8114 * @param aGlobal true to fetch global folders.
8115 *
8116 * @note The caller must lock this object for writing.
8117 */
8118HRESULT Console::i_fetchSharedFolders(BOOL aGlobal)
8119{
8120 /* sanity check */
8121 AssertReturn( getObjectState().getState() == ObjectState::InInit
8122 || isWriteLockOnCurrentThread(), E_FAIL);
8123
8124 LogFlowThisFunc(("Entering\n"));
8125
8126 /* Check if we're online and keep it that way. */
8127 SafeVMPtrQuiet ptrVM(this);
8128 AutoVMCallerQuietWeak autoVMCaller(this);
8129 bool const online = ptrVM.isOk()
8130 && m_pVMMDev
8131 && m_pVMMDev->isShFlActive();
8132
8133 HRESULT rc = S_OK;
8134
8135 try
8136 {
8137 if (aGlobal)
8138 {
8139 /// @todo grab & process global folders when they are done
8140 }
8141 else
8142 {
8143 SharedFolderDataMap oldFolders;
8144 if (online)
8145 oldFolders = m_mapMachineSharedFolders;
8146
8147 m_mapMachineSharedFolders.clear();
8148
8149 SafeIfaceArray<ISharedFolder> folders;
8150 rc = mMachine->COMGETTER(SharedFolders)(ComSafeArrayAsOutParam(folders));
8151 if (FAILED(rc)) throw rc;
8152
8153 for (size_t i = 0; i < folders.size(); ++i)
8154 {
8155 ComPtr<ISharedFolder> pSharedFolder = folders[i];
8156
8157 Bstr bstrName;
8158 Bstr bstrHostPath;
8159 BOOL writable;
8160 BOOL autoMount;
8161
8162 rc = pSharedFolder->COMGETTER(Name)(bstrName.asOutParam());
8163 if (FAILED(rc)) throw rc;
8164 Utf8Str strName(bstrName);
8165
8166 rc = pSharedFolder->COMGETTER(HostPath)(bstrHostPath.asOutParam());
8167 if (FAILED(rc)) throw rc;
8168 Utf8Str strHostPath(bstrHostPath);
8169
8170 rc = pSharedFolder->COMGETTER(Writable)(&writable);
8171 if (FAILED(rc)) throw rc;
8172
8173 rc = pSharedFolder->COMGETTER(AutoMount)(&autoMount);
8174 if (FAILED(rc)) throw rc;
8175
8176 m_mapMachineSharedFolders.insert(std::make_pair(strName,
8177 SharedFolderData(strHostPath, !!writable, !!autoMount)));
8178
8179 /* send changes to HGCM if the VM is running */
8180 if (online)
8181 {
8182 SharedFolderDataMap::iterator it = oldFolders.find(strName);
8183 if ( it == oldFolders.end()
8184 || it->second.m_strHostPath != strHostPath)
8185 {
8186 /* a new machine folder is added or
8187 * the existing machine folder is changed */
8188 if (m_mapSharedFolders.find(strName) != m_mapSharedFolders.end())
8189 ; /* the console folder exists, nothing to do */
8190 else
8191 {
8192 /* remove the old machine folder (when changed)
8193 * or the global folder if any (when new) */
8194 if ( it != oldFolders.end()
8195 || m_mapGlobalSharedFolders.find(strName) != m_mapGlobalSharedFolders.end()
8196 )
8197 {
8198 rc = i_removeSharedFolder(strName);
8199 if (FAILED(rc)) throw rc;
8200 }
8201
8202 /* create the new machine folder */
8203 rc = i_createSharedFolder(strName,
8204 SharedFolderData(strHostPath, !!writable, !!autoMount));
8205 if (FAILED(rc)) throw rc;
8206 }
8207 }
8208 /* forget the processed (or identical) folder */
8209 if (it != oldFolders.end())
8210 oldFolders.erase(it);
8211 }
8212 }
8213
8214 /* process outdated (removed) folders */
8215 if (online)
8216 {
8217 for (SharedFolderDataMap::const_iterator it = oldFolders.begin();
8218 it != oldFolders.end(); ++it)
8219 {
8220 if (m_mapSharedFolders.find(it->first) != m_mapSharedFolders.end())
8221 ; /* the console folder exists, nothing to do */
8222 else
8223 {
8224 /* remove the outdated machine folder */
8225 rc = i_removeSharedFolder(it->first);
8226 if (FAILED(rc)) throw rc;
8227
8228 /* create the global folder if there is any */
8229 SharedFolderDataMap::const_iterator git =
8230 m_mapGlobalSharedFolders.find(it->first);
8231 if (git != m_mapGlobalSharedFolders.end())
8232 {
8233 rc = i_createSharedFolder(git->first, git->second);
8234 if (FAILED(rc)) throw rc;
8235 }
8236 }
8237 }
8238 }
8239 }
8240 }
8241 catch (HRESULT rc2)
8242 {
8243 rc = rc2;
8244 if (online)
8245 i_atVMRuntimeErrorCallbackF(0, "BrokenSharedFolder", N_("Broken shared folder!"));
8246 }
8247
8248 LogFlowThisFunc(("Leaving\n"));
8249
8250 return rc;
8251}
8252
8253/**
8254 * Searches for a shared folder with the given name in the list of machine
8255 * shared folders and then in the list of the global shared folders.
8256 *
8257 * @param strName Name of the folder to search for.
8258 * @param aIt Where to store the pointer to the found folder.
8259 * @return @c true if the folder was found and @c false otherwise.
8260 *
8261 * @note The caller must lock this object for reading.
8262 */
8263bool Console::i_findOtherSharedFolder(const Utf8Str &strName,
8264 SharedFolderDataMap::const_iterator &aIt)
8265{
8266 /* sanity check */
8267 AssertReturn(isWriteLockOnCurrentThread(), false);
8268
8269 /* first, search machine folders */
8270 aIt = m_mapMachineSharedFolders.find(strName);
8271 if (aIt != m_mapMachineSharedFolders.end())
8272 return true;
8273
8274 /* second, search machine folders */
8275 aIt = m_mapGlobalSharedFolders.find(strName);
8276 if (aIt != m_mapGlobalSharedFolders.end())
8277 return true;
8278
8279 return false;
8280}
8281
8282/**
8283 * Calls the HGCM service to add a shared folder definition.
8284 *
8285 * @param strName Shared folder name.
8286 * @param aData Shared folder data.
8287 *
8288 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
8289 * @note Doesn't lock anything.
8290 */
8291HRESULT Console::i_createSharedFolder(const Utf8Str &strName, const SharedFolderData &aData)
8292{
8293 ComAssertRet(strName.isNotEmpty(), E_FAIL);
8294 ComAssertRet(aData.m_strHostPath.isNotEmpty(), E_FAIL);
8295
8296 /* sanity checks */
8297 AssertReturn(mpUVM, E_FAIL);
8298 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
8299
8300 VBOXHGCMSVCPARM parms[SHFL_CPARMS_ADD_MAPPING];
8301 SHFLSTRING *pFolderName, *pMapName;
8302 size_t cbString;
8303
8304 Bstr value;
8305 HRESULT hrc = mMachine->GetExtraData(BstrFmt("VBoxInternal2/SharedFoldersEnableSymlinksCreate/%s",
8306 strName.c_str()).raw(),
8307 value.asOutParam());
8308 bool fSymlinksCreate = hrc == S_OK && value == "1";
8309
8310 Log(("Adding shared folder '%s' -> '%s'\n", strName.c_str(), aData.m_strHostPath.c_str()));
8311
8312 // check whether the path is valid and exists
8313 char hostPathFull[RTPATH_MAX];
8314 int vrc = RTPathAbsEx(NULL,
8315 aData.m_strHostPath.c_str(),
8316 hostPathFull,
8317 sizeof(hostPathFull));
8318
8319 bool fMissing = false;
8320 if (RT_FAILURE(vrc))
8321 return setError(E_INVALIDARG,
8322 tr("Invalid shared folder path: '%s' (%Rrc)"),
8323 aData.m_strHostPath.c_str(), vrc);
8324 if (!RTPathExists(hostPathFull))
8325 fMissing = true;
8326
8327 /* Check whether the path is full (absolute) */
8328 if (RTPathCompare(aData.m_strHostPath.c_str(), hostPathFull) != 0)
8329 return setError(E_INVALIDARG,
8330 tr("Shared folder path '%s' is not absolute"),
8331 aData.m_strHostPath.c_str());
8332
8333 // now that we know the path is good, give it to HGCM
8334
8335 Bstr bstrName(strName);
8336 Bstr bstrHostPath(aData.m_strHostPath);
8337
8338 cbString = (bstrHostPath.length() + 1) * sizeof(RTUTF16);
8339 if (cbString >= UINT16_MAX)
8340 return setError(E_INVALIDARG, tr("The name is too long"));
8341 pFolderName = (SHFLSTRING*)RTMemAllocZ(SHFLSTRING_HEADER_SIZE + cbString);
8342 Assert(pFolderName);
8343 memcpy(pFolderName->String.ucs2, bstrHostPath.raw(), cbString);
8344
8345 pFolderName->u16Size = (uint16_t)cbString;
8346 pFolderName->u16Length = (uint16_t)(cbString - sizeof(RTUTF16));
8347
8348 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
8349 parms[0].u.pointer.addr = pFolderName;
8350 parms[0].u.pointer.size = ShflStringSizeOfBuffer(pFolderName);
8351
8352 cbString = (bstrName.length() + 1) * sizeof(RTUTF16);
8353 if (cbString >= UINT16_MAX)
8354 {
8355 RTMemFree(pFolderName);
8356 return setError(E_INVALIDARG, tr("The host path is too long"));
8357 }
8358 pMapName = (SHFLSTRING*)RTMemAllocZ(SHFLSTRING_HEADER_SIZE + cbString);
8359 Assert(pMapName);
8360 memcpy(pMapName->String.ucs2, bstrName.raw(), cbString);
8361
8362 pMapName->u16Size = (uint16_t)cbString;
8363 pMapName->u16Length = (uint16_t)(cbString - sizeof(RTUTF16));
8364
8365 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
8366 parms[1].u.pointer.addr = pMapName;
8367 parms[1].u.pointer.size = ShflStringSizeOfBuffer(pMapName);
8368
8369 parms[2].type = VBOX_HGCM_SVC_PARM_32BIT;
8370 parms[2].u.uint32 = (aData.m_fWritable ? SHFL_ADD_MAPPING_F_WRITABLE : 0)
8371 | (aData.m_fAutoMount ? SHFL_ADD_MAPPING_F_AUTOMOUNT : 0)
8372 | (fSymlinksCreate ? SHFL_ADD_MAPPING_F_CREATE_SYMLINKS : 0)
8373 | (fMissing ? SHFL_ADD_MAPPING_F_MISSING : 0)
8374 ;
8375
8376 vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders",
8377 SHFL_FN_ADD_MAPPING,
8378 SHFL_CPARMS_ADD_MAPPING, &parms[0]);
8379 RTMemFree(pFolderName);
8380 RTMemFree(pMapName);
8381
8382 if (RT_FAILURE(vrc))
8383 return setError(E_FAIL,
8384 tr("Could not create a shared folder '%s' mapped to '%s' (%Rrc)"),
8385 strName.c_str(), aData.m_strHostPath.c_str(), vrc);
8386
8387 if (fMissing)
8388 return setError(E_INVALIDARG,
8389 tr("Shared folder path '%s' does not exist on the host"),
8390 aData.m_strHostPath.c_str());
8391
8392 return S_OK;
8393}
8394
8395/**
8396 * Calls the HGCM service to remove the shared folder definition.
8397 *
8398 * @param strName Shared folder name.
8399 *
8400 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
8401 * @note Doesn't lock anything.
8402 */
8403HRESULT Console::i_removeSharedFolder(const Utf8Str &strName)
8404{
8405 ComAssertRet(strName.isNotEmpty(), E_FAIL);
8406
8407 /* sanity checks */
8408 AssertReturn(mpUVM, E_FAIL);
8409 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
8410
8411 VBOXHGCMSVCPARM parms;
8412 SHFLSTRING *pMapName;
8413 size_t cbString;
8414
8415 Log(("Removing shared folder '%s'\n", strName.c_str()));
8416
8417 Bstr bstrName(strName);
8418 cbString = (bstrName.length() + 1) * sizeof(RTUTF16);
8419 if (cbString >= UINT16_MAX)
8420 return setError(E_INVALIDARG, tr("The name is too long"));
8421 pMapName = (SHFLSTRING *) RTMemAllocZ(SHFLSTRING_HEADER_SIZE + cbString);
8422 Assert(pMapName);
8423 memcpy(pMapName->String.ucs2, bstrName.raw(), cbString);
8424
8425 pMapName->u16Size = (uint16_t)cbString;
8426 pMapName->u16Length = (uint16_t)(cbString - sizeof(RTUTF16));
8427
8428 parms.type = VBOX_HGCM_SVC_PARM_PTR;
8429 parms.u.pointer.addr = pMapName;
8430 parms.u.pointer.size = ShflStringSizeOfBuffer(pMapName);
8431
8432 int vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders",
8433 SHFL_FN_REMOVE_MAPPING,
8434 1, &parms);
8435 RTMemFree(pMapName);
8436 if (RT_FAILURE(vrc))
8437 return setError(E_FAIL,
8438 tr("Could not remove the shared folder '%s' (%Rrc)"),
8439 strName.c_str(), vrc);
8440
8441 return S_OK;
8442}
8443
8444/** @callback_method_impl{FNVMATSTATE}
8445 *
8446 * @note Locks the Console object for writing.
8447 * @remarks The @a pUVM parameter can be NULL in one case where powerUpThread()
8448 * calls after the VM was destroyed.
8449 */
8450DECLCALLBACK(void) Console::i_vmstateChangeCallback(PUVM pUVM, VMSTATE enmState, VMSTATE enmOldState, void *pvUser)
8451{
8452 LogFlowFunc(("Changing state from %s to %s (pUVM=%p)\n",
8453 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState), pUVM));
8454
8455 Console *that = static_cast<Console *>(pvUser);
8456 AssertReturnVoid(that);
8457
8458 AutoCaller autoCaller(that);
8459
8460 /* Note that we must let this method proceed even if Console::uninit() has
8461 * been already called. In such case this VMSTATE change is a result of:
8462 * 1) powerDown() called from uninit() itself, or
8463 * 2) VM-(guest-)initiated power off. */
8464 AssertReturnVoid( autoCaller.isOk()
8465 || that->getObjectState().getState() == ObjectState::InUninit);
8466
8467 switch (enmState)
8468 {
8469 /*
8470 * The VM has terminated
8471 */
8472 case VMSTATE_OFF:
8473 {
8474#ifdef VBOX_WITH_GUEST_PROPS
8475 if (that->i_isResetTurnedIntoPowerOff())
8476 {
8477 Bstr strPowerOffReason;
8478
8479 if (that->mfPowerOffCausedByReset)
8480 strPowerOffReason = Bstr("Reset");
8481 else
8482 strPowerOffReason = Bstr("PowerOff");
8483
8484 that->mMachine->DeleteGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw());
8485 that->mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw(),
8486 strPowerOffReason.raw(), Bstr("RDONLYGUEST").raw());
8487 that->mMachine->SaveSettings();
8488 }
8489#endif
8490
8491 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8492
8493 if (that->mVMStateChangeCallbackDisabled)
8494 return;
8495
8496 /* Do we still think that it is running? It may happen if this is a
8497 * VM-(guest-)initiated shutdown/poweroff.
8498 */
8499 if ( that->mMachineState != MachineState_Stopping
8500 && that->mMachineState != MachineState_Saving
8501 && that->mMachineState != MachineState_Restoring
8502 && that->mMachineState != MachineState_TeleportingIn
8503 && that->mMachineState != MachineState_FaultTolerantSyncing
8504 && that->mMachineState != MachineState_TeleportingPausedVM
8505 && !that->mVMIsAlreadyPoweringOff
8506 )
8507 {
8508 LogFlowFunc(("VM has powered itself off but Console still thinks it is running. Notifying.\n"));
8509
8510 /*
8511 * Prevent powerDown() from calling VMR3PowerOff() again if this was called from
8512 * the power off state change.
8513 * When called from the Reset state make sure to call VMR3PowerOff() first.
8514 */
8515 Assert(that->mVMPoweredOff == false);
8516 that->mVMPoweredOff = true;
8517
8518 /*
8519 * request a progress object from the server
8520 * (this will set the machine state to Stopping on the server
8521 * to block others from accessing this machine)
8522 */
8523 ComPtr<IProgress> pProgress;
8524 HRESULT rc = that->mControl->BeginPoweringDown(pProgress.asOutParam());
8525 AssertComRC(rc);
8526
8527 /* sync the state with the server */
8528 that->i_setMachineStateLocally(MachineState_Stopping);
8529
8530 /* Setup task object and thread to carry out the operation
8531 * asynchronously (if we call powerDown() right here but there
8532 * is one or more mpUVM callers (added with addVMCaller()) we'll
8533 * deadlock).
8534 */
8535 VMPowerDownTask* task = NULL;
8536 try
8537 {
8538 task = new VMPowerDownTask(that, pProgress);
8539 /* If creating a task failed, this can currently mean one of
8540 * two: either Console::uninit() has been called just a ms
8541 * before (so a powerDown() call is already on the way), or
8542 * powerDown() itself is being already executed. Just do
8543 * nothing.
8544 */
8545 if (!task->isOk())
8546 {
8547 LogFlowFunc(("Console is already being uninitialized. \n"));
8548 throw E_FAIL;
8549 }
8550 }
8551 catch(...)
8552 {
8553 delete task;
8554 LogFlowFunc(("Problem with creating VMPowerDownTask object. \n"));
8555 }
8556
8557 rc = task->createThread();
8558
8559 if (FAILED(rc))
8560 {
8561 LogFlowFunc(("Problem with creating thread for VMPowerDownTask. \n"));
8562 }
8563
8564 }
8565 break;
8566 }
8567
8568 /* The VM has been completely destroyed.
8569 *
8570 * Note: This state change can happen at two points:
8571 * 1) At the end of VMR3Destroy() if it was not called from EMT.
8572 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
8573 * called by EMT.
8574 */
8575 case VMSTATE_TERMINATED:
8576 {
8577 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8578
8579 if (that->mVMStateChangeCallbackDisabled)
8580 break;
8581
8582 /* Terminate host interface networking. If pUVM is NULL, we've been
8583 * manually called from powerUpThread() either before calling
8584 * VMR3Create() or after VMR3Create() failed, so no need to touch
8585 * networking.
8586 */
8587 if (pUVM)
8588 that->i_powerDownHostInterfaces();
8589
8590 /* From now on the machine is officially powered down or remains in
8591 * the Saved state.
8592 */
8593 switch (that->mMachineState)
8594 {
8595 default:
8596 AssertFailed();
8597 /* fall through */
8598 case MachineState_Stopping:
8599 /* successfully powered down */
8600 that->i_setMachineState(MachineState_PoweredOff);
8601 break;
8602 case MachineState_Saving:
8603 /* successfully saved */
8604 that->i_setMachineState(MachineState_Saved);
8605 break;
8606 case MachineState_Starting:
8607 /* failed to start, but be patient: set back to PoweredOff
8608 * (for similarity with the below) */
8609 that->i_setMachineState(MachineState_PoweredOff);
8610 break;
8611 case MachineState_Restoring:
8612 /* failed to load the saved state file, but be patient: set
8613 * back to Saved (to preserve the saved state file) */
8614 that->i_setMachineState(MachineState_Saved);
8615 break;
8616 case MachineState_TeleportingIn:
8617 /* Teleportation failed or was canceled. Back to powered off. */
8618 that->i_setMachineState(MachineState_PoweredOff);
8619 break;
8620 case MachineState_TeleportingPausedVM:
8621 /* Successfully teleported the VM. */
8622 that->i_setMachineState(MachineState_Teleported);
8623 break;
8624 case MachineState_FaultTolerantSyncing:
8625 /* Fault tolerant sync failed or was canceled. Back to powered off. */
8626 that->i_setMachineState(MachineState_PoweredOff);
8627 break;
8628 }
8629 break;
8630 }
8631
8632 case VMSTATE_RESETTING:
8633 /** @todo shouldn't VMSTATE_RESETTING_LS be here? */
8634 {
8635#ifdef VBOX_WITH_GUEST_PROPS
8636 /* Do not take any read/write locks here! */
8637 that->i_guestPropertiesHandleVMReset();
8638#endif
8639 break;
8640 }
8641
8642 case VMSTATE_SOFT_RESETTING:
8643 case VMSTATE_SOFT_RESETTING_LS:
8644 /* Shouldn't do anything here! */
8645 break;
8646
8647 case VMSTATE_SUSPENDED:
8648 {
8649 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8650
8651 if (that->mVMStateChangeCallbackDisabled)
8652 break;
8653
8654 switch (that->mMachineState)
8655 {
8656 case MachineState_Teleporting:
8657 that->i_setMachineState(MachineState_TeleportingPausedVM);
8658 break;
8659
8660 case MachineState_LiveSnapshotting:
8661 that->i_setMachineState(MachineState_OnlineSnapshotting);
8662 break;
8663
8664 case MachineState_TeleportingPausedVM:
8665 case MachineState_Saving:
8666 case MachineState_Restoring:
8667 case MachineState_Stopping:
8668 case MachineState_TeleportingIn:
8669 case MachineState_FaultTolerantSyncing:
8670 case MachineState_OnlineSnapshotting:
8671 /* The worker thread handles the transition. */
8672 break;
8673
8674 case MachineState_Running:
8675 that->i_setMachineState(MachineState_Paused);
8676 break;
8677
8678 case MachineState_Paused:
8679 /* Nothing to do. */
8680 break;
8681
8682 default:
8683 AssertMsgFailed(("%s\n", Global::stringifyMachineState(that->mMachineState)));
8684 }
8685 break;
8686 }
8687
8688 case VMSTATE_SUSPENDED_LS:
8689 case VMSTATE_SUSPENDED_EXT_LS:
8690 {
8691 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8692 if (that->mVMStateChangeCallbackDisabled)
8693 break;
8694 switch (that->mMachineState)
8695 {
8696 case MachineState_Teleporting:
8697 that->i_setMachineState(MachineState_TeleportingPausedVM);
8698 break;
8699
8700 case MachineState_LiveSnapshotting:
8701 that->i_setMachineState(MachineState_OnlineSnapshotting);
8702 break;
8703
8704 case MachineState_TeleportingPausedVM:
8705 case MachineState_Saving:
8706 /* ignore */
8707 break;
8708
8709 default:
8710 AssertMsgFailed(("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState),
8711 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
8712 that->i_setMachineState(MachineState_Paused);
8713 break;
8714 }
8715 break;
8716 }
8717
8718 case VMSTATE_RUNNING:
8719 {
8720 if ( enmOldState == VMSTATE_POWERING_ON
8721 || enmOldState == VMSTATE_RESUMING
8722 || enmOldState == VMSTATE_RUNNING_FT)
8723 {
8724 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8725
8726 if (that->mVMStateChangeCallbackDisabled)
8727 break;
8728
8729 Assert( ( ( that->mMachineState == MachineState_Starting
8730 || that->mMachineState == MachineState_Paused)
8731 && enmOldState == VMSTATE_POWERING_ON)
8732 || ( ( that->mMachineState == MachineState_Restoring
8733 || that->mMachineState == MachineState_TeleportingIn
8734 || that->mMachineState == MachineState_Paused
8735 || that->mMachineState == MachineState_Saving
8736 )
8737 && enmOldState == VMSTATE_RESUMING)
8738 || ( that->mMachineState == MachineState_FaultTolerantSyncing
8739 && enmOldState == VMSTATE_RUNNING_FT));
8740
8741 that->i_setMachineState(MachineState_Running);
8742 }
8743
8744 break;
8745 }
8746
8747 case VMSTATE_RUNNING_LS:
8748 AssertMsg( that->mMachineState == MachineState_LiveSnapshotting
8749 || that->mMachineState == MachineState_Teleporting,
8750 ("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState),
8751 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
8752 break;
8753
8754 case VMSTATE_RUNNING_FT:
8755 AssertMsg(that->mMachineState == MachineState_FaultTolerantSyncing,
8756 ("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState),
8757 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
8758 break;
8759
8760 case VMSTATE_FATAL_ERROR:
8761 {
8762 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8763
8764 if (that->mVMStateChangeCallbackDisabled)
8765 break;
8766
8767 /* Fatal errors are only for running VMs. */
8768 Assert(Global::IsOnline(that->mMachineState));
8769
8770 /* Note! 'Pause' is used here in want of something better. There
8771 * are currently only two places where fatal errors might be
8772 * raised, so it is not worth adding a new externally
8773 * visible state for this yet. */
8774 that->i_setMachineState(MachineState_Paused);
8775 break;
8776 }
8777
8778 case VMSTATE_GURU_MEDITATION:
8779 {
8780 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8781
8782 if (that->mVMStateChangeCallbackDisabled)
8783 break;
8784
8785 /* Guru are only for running VMs */
8786 Assert(Global::IsOnline(that->mMachineState));
8787
8788 that->i_setMachineState(MachineState_Stuck);
8789 break;
8790 }
8791
8792 case VMSTATE_CREATED:
8793 {
8794 /*
8795 * We have to set the secret key helper interface for the VD drivers to
8796 * get notified about missing keys.
8797 */
8798 that->i_initSecretKeyIfOnAllAttachments();
8799 break;
8800 }
8801
8802 default: /* shut up gcc */
8803 break;
8804 }
8805}
8806
8807/**
8808 * Changes the clipboard mode.
8809 *
8810 * @param aClipboardMode new clipboard mode.
8811 */
8812void Console::i_changeClipboardMode(ClipboardMode_T aClipboardMode)
8813{
8814 VMMDev *pVMMDev = m_pVMMDev;
8815 Assert(pVMMDev);
8816
8817 VBOXHGCMSVCPARM parm;
8818 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
8819
8820 switch (aClipboardMode)
8821 {
8822 default:
8823 case ClipboardMode_Disabled:
8824 LogRel(("Shared clipboard mode: Off\n"));
8825 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_OFF;
8826 break;
8827 case ClipboardMode_GuestToHost:
8828 LogRel(("Shared clipboard mode: Guest to Host\n"));
8829 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_GUEST_TO_HOST;
8830 break;
8831 case ClipboardMode_HostToGuest:
8832 LogRel(("Shared clipboard mode: Host to Guest\n"));
8833 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_HOST_TO_GUEST;
8834 break;
8835 case ClipboardMode_Bidirectional:
8836 LogRel(("Shared clipboard mode: Bidirectional\n"));
8837 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_BIDIRECTIONAL;
8838 break;
8839 }
8840
8841 pVMMDev->hgcmHostCall("VBoxSharedClipboard", VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE, 1, &parm);
8842}
8843
8844/**
8845 * Changes the drag and drop mode.
8846 *
8847 * @param aDnDMode new drag and drop mode.
8848 */
8849int Console::i_changeDnDMode(DnDMode_T aDnDMode)
8850{
8851 VMMDev *pVMMDev = m_pVMMDev;
8852 AssertPtrReturn(pVMMDev, VERR_INVALID_POINTER);
8853
8854 VBOXHGCMSVCPARM parm;
8855 RT_ZERO(parm);
8856 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
8857
8858 switch (aDnDMode)
8859 {
8860 default:
8861 case DnDMode_Disabled:
8862 LogRel(("Drag and drop mode: Off\n"));
8863 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_OFF;
8864 break;
8865 case DnDMode_GuestToHost:
8866 LogRel(("Drag and drop mode: Guest to Host\n"));
8867 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_GUEST_TO_HOST;
8868 break;
8869 case DnDMode_HostToGuest:
8870 LogRel(("Drag and drop mode: Host to Guest\n"));
8871 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_HOST_TO_GUEST;
8872 break;
8873 case DnDMode_Bidirectional:
8874 LogRel(("Drag and drop mode: Bidirectional\n"));
8875 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_BIDIRECTIONAL;
8876 break;
8877 }
8878
8879 int rc = pVMMDev->hgcmHostCall("VBoxDragAndDropSvc",
8880 DragAndDropSvc::HOST_DND_SET_MODE, 1 /* cParms */, &parm);
8881 if (RT_FAILURE(rc))
8882 LogRel(("Error changing drag and drop mode: %Rrc\n", rc));
8883
8884 return rc;
8885}
8886
8887#ifdef VBOX_WITH_USB
8888/**
8889 * Sends a request to VMM to attach the given host device.
8890 * After this method succeeds, the attached device will appear in the
8891 * mUSBDevices collection.
8892 *
8893 * @param aHostDevice device to attach
8894 *
8895 * @note Synchronously calls EMT.
8896 */
8897HRESULT Console::i_attachUSBDevice(IUSBDevice *aHostDevice, ULONG aMaskedIfs,
8898 const Utf8Str &aCaptureFilename)
8899{
8900 AssertReturn(aHostDevice, E_FAIL);
8901 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
8902
8903 HRESULT hrc;
8904
8905 /*
8906 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
8907 * method in EMT (using usbAttachCallback()).
8908 */
8909 Bstr BstrAddress;
8910 hrc = aHostDevice->COMGETTER(Address)(BstrAddress.asOutParam());
8911 ComAssertComRCRetRC(hrc);
8912
8913 Utf8Str Address(BstrAddress);
8914
8915 Bstr id;
8916 hrc = aHostDevice->COMGETTER(Id)(id.asOutParam());
8917 ComAssertComRCRetRC(hrc);
8918 Guid uuid(id);
8919
8920 BOOL fRemote = FALSE;
8921 hrc = aHostDevice->COMGETTER(Remote)(&fRemote);
8922 ComAssertComRCRetRC(hrc);
8923
8924 Bstr BstrBackend;
8925 hrc = aHostDevice->COMGETTER(Backend)(BstrBackend.asOutParam());
8926 ComAssertComRCRetRC(hrc);
8927
8928 Utf8Str Backend(BstrBackend);
8929
8930 /* Get the VM handle. */
8931 SafeVMPtr ptrVM(this);
8932 if (!ptrVM.isOk())
8933 return ptrVM.rc();
8934
8935 LogFlowThisFunc(("Proxying USB device '%s' {%RTuuid}...\n",
8936 Address.c_str(), uuid.raw()));
8937
8938 void *pvRemoteBackend = NULL;
8939 if (fRemote)
8940 {
8941 RemoteUSBDevice *pRemoteUSBDevice = static_cast<RemoteUSBDevice *>(aHostDevice);
8942 pvRemoteBackend = i_consoleVRDPServer()->USBBackendRequestPointer(pRemoteUSBDevice->clientId(), &uuid);
8943 if (!pvRemoteBackend)
8944 return E_INVALIDARG; /* The clientId is invalid then. */
8945 }
8946
8947 USHORT portVersion = 0;
8948 hrc = aHostDevice->COMGETTER(PortVersion)(&portVersion);
8949 AssertComRCReturnRC(hrc);
8950 Assert(portVersion == 1 || portVersion == 2 || portVersion == 3);
8951
8952 int vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
8953 (PFNRT)i_usbAttachCallback, 10,
8954 this, ptrVM.rawUVM(), aHostDevice, uuid.raw(), Backend.c_str(),
8955 Address.c_str(), pvRemoteBackend, portVersion, aMaskedIfs,
8956 aCaptureFilename.isEmpty() ? NULL : aCaptureFilename.c_str());
8957 if (RT_SUCCESS(vrc))
8958 {
8959 /* Create a OUSBDevice and add it to the device list */
8960 ComObjPtr<OUSBDevice> pUSBDevice;
8961 pUSBDevice.createObject();
8962 hrc = pUSBDevice->init(aHostDevice);
8963 AssertComRC(hrc);
8964
8965 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8966 mUSBDevices.push_back(pUSBDevice);
8967 LogFlowFunc(("Attached device {%RTuuid}\n", pUSBDevice->i_id().raw()));
8968
8969 /* notify callbacks */
8970 alock.release();
8971 i_onUSBDeviceStateChange(pUSBDevice, true /* aAttached */, NULL);
8972 }
8973 else
8974 {
8975 Log1WarningThisFunc(("Failed to create proxy device for '%s' {%RTuuid} (%Rrc)\n", Address.c_str(), uuid.raw(), vrc));
8976
8977 switch (vrc)
8978 {
8979 case VERR_VUSB_NO_PORTS:
8980 hrc = setError(E_FAIL, tr("Failed to attach the USB device. (No available ports on the USB controller)."));
8981 break;
8982 case VERR_VUSB_USBFS_PERMISSION:
8983 hrc = setError(E_FAIL, tr("Not permitted to open the USB device, check usbfs options"));
8984 break;
8985 default:
8986 hrc = setError(E_FAIL, tr("Failed to create a proxy device for the USB device. (Error: %Rrc)"), vrc);
8987 break;
8988 }
8989 }
8990
8991 return hrc;
8992}
8993
8994/**
8995 * USB device attach callback used by AttachUSBDevice().
8996 * Note that AttachUSBDevice() doesn't return until this callback is executed,
8997 * so we don't use AutoCaller and don't care about reference counters of
8998 * interface pointers passed in.
8999 *
9000 * @thread EMT
9001 * @note Locks the console object for writing.
9002 */
9003//static
9004DECLCALLBACK(int)
9005Console::i_usbAttachCallback(Console *that, PUVM pUVM, IUSBDevice *aHostDevice, PCRTUUID aUuid, const char *pszBackend,
9006 const char *aAddress, void *pvRemoteBackend, USHORT aPortVersion, ULONG aMaskedIfs,
9007 const char *pszCaptureFilename)
9008{
9009 RT_NOREF(aHostDevice);
9010 LogFlowFuncEnter();
9011 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
9012
9013 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
9014 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
9015
9016 int vrc = PDMR3UsbCreateProxyDevice(pUVM, aUuid, pszBackend, aAddress, pvRemoteBackend,
9017 aPortVersion == 3 ? VUSB_STDVER_30 :
9018 aPortVersion == 2 ? VUSB_STDVER_20 : VUSB_STDVER_11,
9019 aMaskedIfs, pszCaptureFilename);
9020 LogFlowFunc(("vrc=%Rrc\n", vrc));
9021 LogFlowFuncLeave();
9022 return vrc;
9023}
9024
9025/**
9026 * Sends a request to VMM to detach the given host device. After this method
9027 * succeeds, the detached device will disappear from the mUSBDevices
9028 * collection.
9029 *
9030 * @param aHostDevice device to attach
9031 *
9032 * @note Synchronously calls EMT.
9033 */
9034HRESULT Console::i_detachUSBDevice(const ComObjPtr<OUSBDevice> &aHostDevice)
9035{
9036 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
9037
9038 /* Get the VM handle. */
9039 SafeVMPtr ptrVM(this);
9040 if (!ptrVM.isOk())
9041 return ptrVM.rc();
9042
9043 /* if the device is attached, then there must at least one USB hub. */
9044 AssertReturn(PDMR3UsbHasHub(ptrVM.rawUVM()), E_FAIL);
9045
9046 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9047 LogFlowThisFunc(("Detaching USB proxy device {%RTuuid}...\n",
9048 aHostDevice->i_id().raw()));
9049
9050 /*
9051 * If this was a remote device, release the backend pointer.
9052 * The pointer was requested in usbAttachCallback.
9053 */
9054 BOOL fRemote = FALSE;
9055
9056 HRESULT hrc2 = aHostDevice->COMGETTER(Remote)(&fRemote);
9057 if (FAILED(hrc2))
9058 i_setErrorStatic(hrc2, "GetRemote() failed");
9059
9060 PCRTUUID pUuid = aHostDevice->i_id().raw();
9061 if (fRemote)
9062 {
9063 Guid guid(*pUuid);
9064 i_consoleVRDPServer()->USBBackendReleasePointer(&guid);
9065 }
9066
9067 alock.release();
9068 int vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
9069 (PFNRT)i_usbDetachCallback, 5,
9070 this, ptrVM.rawUVM(), pUuid);
9071 if (RT_SUCCESS(vrc))
9072 {
9073 LogFlowFunc(("Detached device {%RTuuid}\n", pUuid));
9074
9075 /* notify callbacks */
9076 i_onUSBDeviceStateChange(aHostDevice, false /* aAttached */, NULL);
9077 }
9078
9079 ComAssertRCRet(vrc, E_FAIL);
9080
9081 return S_OK;
9082}
9083
9084/**
9085 * USB device detach callback used by DetachUSBDevice().
9086 *
9087 * Note that DetachUSBDevice() doesn't return until this callback is executed,
9088 * so we don't use AutoCaller and don't care about reference counters of
9089 * interface pointers passed in.
9090 *
9091 * @thread EMT
9092 */
9093//static
9094DECLCALLBACK(int)
9095Console::i_usbDetachCallback(Console *that, PUVM pUVM, PCRTUUID aUuid)
9096{
9097 LogFlowFuncEnter();
9098 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
9099
9100 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
9101 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
9102
9103 int vrc = PDMR3UsbDetachDevice(pUVM, aUuid);
9104
9105 LogFlowFunc(("vrc=%Rrc\n", vrc));
9106 LogFlowFuncLeave();
9107 return vrc;
9108}
9109#endif /* VBOX_WITH_USB */
9110
9111/* Note: FreeBSD needs this whether netflt is used or not. */
9112#if ((defined(RT_OS_LINUX) && !defined(VBOX_WITH_NETFLT)) || defined(RT_OS_FREEBSD))
9113/**
9114 * Helper function to handle host interface device creation and attachment.
9115 *
9116 * @param networkAdapter the network adapter which attachment should be reset
9117 * @return COM status code
9118 *
9119 * @note The caller must lock this object for writing.
9120 *
9121 * @todo Move this back into the driver!
9122 */
9123HRESULT Console::i_attachToTapInterface(INetworkAdapter *networkAdapter)
9124{
9125 LogFlowThisFunc(("\n"));
9126 /* sanity check */
9127 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9128
9129# ifdef VBOX_STRICT
9130 /* paranoia */
9131 NetworkAttachmentType_T attachment;
9132 networkAdapter->COMGETTER(AttachmentType)(&attachment);
9133 Assert(attachment == NetworkAttachmentType_Bridged);
9134# endif /* VBOX_STRICT */
9135
9136 HRESULT rc = S_OK;
9137
9138 ULONG slot = 0;
9139 rc = networkAdapter->COMGETTER(Slot)(&slot);
9140 AssertComRC(rc);
9141
9142# ifdef RT_OS_LINUX
9143 /*
9144 * Allocate a host interface device
9145 */
9146 int rcVBox = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
9147 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
9148 if (RT_SUCCESS(rcVBox))
9149 {
9150 /*
9151 * Set/obtain the tap interface.
9152 */
9153 struct ifreq IfReq;
9154 RT_ZERO(IfReq);
9155 /* The name of the TAP interface we are using */
9156 Bstr tapDeviceName;
9157 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
9158 if (FAILED(rc))
9159 tapDeviceName.setNull(); /* Is this necessary? */
9160 if (tapDeviceName.isEmpty())
9161 {
9162 LogRel(("No TAP device name was supplied.\n"));
9163 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
9164 }
9165
9166 if (SUCCEEDED(rc))
9167 {
9168 /* If we are using a static TAP device then try to open it. */
9169 Utf8Str str(tapDeviceName);
9170 RTStrCopy(IfReq.ifr_name, sizeof(IfReq.ifr_name), str.c_str()); /** @todo bitch about names which are too long... */
9171 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
9172 rcVBox = ioctl(RTFileToNative(maTapFD[slot]), TUNSETIFF, &IfReq);
9173 if (rcVBox != 0)
9174 {
9175 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
9176 rc = setError(E_FAIL,
9177 tr("Failed to open the host network interface %ls"),
9178 tapDeviceName.raw());
9179 }
9180 }
9181 if (SUCCEEDED(rc))
9182 {
9183 /*
9184 * Make it pollable.
9185 */
9186 if (fcntl(RTFileToNative(maTapFD[slot]), F_SETFL, O_NONBLOCK) != -1)
9187 {
9188 Log(("i_attachToTapInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
9189 /*
9190 * Here is the right place to communicate the TAP file descriptor and
9191 * the host interface name to the server if/when it becomes really
9192 * necessary.
9193 */
9194 maTAPDeviceName[slot] = tapDeviceName;
9195 rcVBox = VINF_SUCCESS;
9196 }
9197 else
9198 {
9199 int iErr = errno;
9200
9201 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
9202 rcVBox = VERR_HOSTIF_BLOCKING;
9203 rc = setError(E_FAIL,
9204 tr("could not set up the host networking device for non blocking access: %s"),
9205 strerror(errno));
9206 }
9207 }
9208 }
9209 else
9210 {
9211 LogRel(("Configuration error: Failed to open /dev/net/tun rc=%Rrc\n", rcVBox));
9212 switch (rcVBox)
9213 {
9214 case VERR_ACCESS_DENIED:
9215 /* will be handled by our caller */
9216 rc = rcVBox;
9217 break;
9218 default:
9219 rc = setError(E_FAIL,
9220 tr("Could not set up the host networking device: %Rrc"),
9221 rcVBox);
9222 break;
9223 }
9224 }
9225
9226# elif defined(RT_OS_FREEBSD)
9227 /*
9228 * Set/obtain the tap interface.
9229 */
9230 /* The name of the TAP interface we are using */
9231 Bstr tapDeviceName;
9232 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
9233 if (FAILED(rc))
9234 tapDeviceName.setNull(); /* Is this necessary? */
9235 if (tapDeviceName.isEmpty())
9236 {
9237 LogRel(("No TAP device name was supplied.\n"));
9238 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
9239 }
9240 char szTapdev[1024] = "/dev/";
9241 /* If we are using a static TAP device then try to open it. */
9242 Utf8Str str(tapDeviceName);
9243 if (str.length() + strlen(szTapdev) <= sizeof(szTapdev))
9244 strcat(szTapdev, str.c_str());
9245 else
9246 memcpy(szTapdev + strlen(szTapdev), str.c_str(),
9247 sizeof(szTapdev) - strlen(szTapdev) - 1); /** @todo bitch about names which are too long... */
9248 int rcVBox = RTFileOpen(&maTapFD[slot], szTapdev,
9249 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT | RTFILE_O_NON_BLOCK);
9250
9251 if (RT_SUCCESS(rcVBox))
9252 maTAPDeviceName[slot] = tapDeviceName;
9253 else
9254 {
9255 switch (rcVBox)
9256 {
9257 case VERR_ACCESS_DENIED:
9258 /* will be handled by our caller */
9259 rc = rcVBox;
9260 break;
9261 default:
9262 rc = setError(E_FAIL,
9263 tr("Failed to open the host network interface %ls"),
9264 tapDeviceName.raw());
9265 break;
9266 }
9267 }
9268# else
9269# error "huh?"
9270# endif
9271 /* in case of failure, cleanup. */
9272 if (RT_FAILURE(rcVBox) && SUCCEEDED(rc))
9273 {
9274 LogRel(("General failure attaching to host interface\n"));
9275 rc = setError(E_FAIL,
9276 tr("General failure attaching to host interface"));
9277 }
9278 LogFlowThisFunc(("rc=%Rhrc\n", rc));
9279 return rc;
9280}
9281
9282
9283/**
9284 * Helper function to handle detachment from a host interface
9285 *
9286 * @param networkAdapter the network adapter which attachment should be reset
9287 * @return COM status code
9288 *
9289 * @note The caller must lock this object for writing.
9290 *
9291 * @todo Move this back into the driver!
9292 */
9293HRESULT Console::i_detachFromTapInterface(INetworkAdapter *networkAdapter)
9294{
9295 /* sanity check */
9296 LogFlowThisFunc(("\n"));
9297 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9298
9299 HRESULT rc = S_OK;
9300# ifdef VBOX_STRICT
9301 /* paranoia */
9302 NetworkAttachmentType_T attachment;
9303 networkAdapter->COMGETTER(AttachmentType)(&attachment);
9304 Assert(attachment == NetworkAttachmentType_Bridged);
9305# endif /* VBOX_STRICT */
9306
9307 ULONG slot = 0;
9308 rc = networkAdapter->COMGETTER(Slot)(&slot);
9309 AssertComRC(rc);
9310
9311 /* is there an open TAP device? */
9312 if (maTapFD[slot] != NIL_RTFILE)
9313 {
9314 /*
9315 * Close the file handle.
9316 */
9317 Bstr tapDeviceName, tapTerminateApplication;
9318 bool isStatic = true;
9319 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
9320 if (FAILED(rc) || tapDeviceName.isEmpty())
9321 {
9322 /* If the name is empty, this is a dynamic TAP device, so close it now,
9323 so that the termination script can remove the interface. Otherwise we still
9324 need the FD to pass to the termination script. */
9325 isStatic = false;
9326 int rcVBox = RTFileClose(maTapFD[slot]);
9327 AssertRC(rcVBox);
9328 maTapFD[slot] = NIL_RTFILE;
9329 }
9330 if (isStatic)
9331 {
9332 /* If we are using a static TAP device, we close it now, after having called the
9333 termination script. */
9334 int rcVBox = RTFileClose(maTapFD[slot]);
9335 AssertRC(rcVBox);
9336 }
9337 /* the TAP device name and handle are no longer valid */
9338 maTapFD[slot] = NIL_RTFILE;
9339 maTAPDeviceName[slot] = "";
9340 }
9341 LogFlowThisFunc(("returning %d\n", rc));
9342 return rc;
9343}
9344#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
9345
9346/**
9347 * Called at power down to terminate host interface networking.
9348 *
9349 * @note The caller must lock this object for writing.
9350 */
9351HRESULT Console::i_powerDownHostInterfaces()
9352{
9353 LogFlowThisFunc(("\n"));
9354
9355 /* sanity check */
9356 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
9357
9358 /*
9359 * host interface termination handling
9360 */
9361 HRESULT rc = S_OK;
9362 ComPtr<IVirtualBox> pVirtualBox;
9363 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
9364 ComPtr<ISystemProperties> pSystemProperties;
9365 if (pVirtualBox)
9366 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
9367 ChipsetType_T chipsetType = ChipsetType_PIIX3;
9368 mMachine->COMGETTER(ChipsetType)(&chipsetType);
9369 ULONG maxNetworkAdapters = 0;
9370 if (pSystemProperties)
9371 pSystemProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters);
9372
9373 for (ULONG slot = 0; slot < maxNetworkAdapters; slot++)
9374 {
9375 ComPtr<INetworkAdapter> pNetworkAdapter;
9376 rc = mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
9377 if (FAILED(rc)) break;
9378
9379 BOOL enabled = FALSE;
9380 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
9381 if (!enabled)
9382 continue;
9383
9384 NetworkAttachmentType_T attachment;
9385 pNetworkAdapter->COMGETTER(AttachmentType)(&attachment);
9386 if (attachment == NetworkAttachmentType_Bridged)
9387 {
9388#if ((defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)) && !defined(VBOX_WITH_NETFLT))
9389 HRESULT rc2 = i_detachFromTapInterface(pNetworkAdapter);
9390 if (FAILED(rc2) && SUCCEEDED(rc))
9391 rc = rc2;
9392#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
9393 }
9394 }
9395
9396 return rc;
9397}
9398
9399
9400/**
9401 * Process callback handler for VMR3LoadFromFile, VMR3LoadFromStream, VMR3Save
9402 * and VMR3Teleport.
9403 *
9404 * @param pUVM The user mode VM handle.
9405 * @param uPercent Completion percentage (0-100).
9406 * @param pvUser Pointer to an IProgress instance.
9407 * @return VINF_SUCCESS.
9408 */
9409/*static*/
9410DECLCALLBACK(int) Console::i_stateProgressCallback(PUVM pUVM, unsigned uPercent, void *pvUser)
9411{
9412 IProgress *pProgress = static_cast<IProgress *>(pvUser);
9413
9414 /* update the progress object */
9415 if (pProgress)
9416 pProgress->SetCurrentOperationProgress(uPercent);
9417
9418 NOREF(pUVM);
9419 return VINF_SUCCESS;
9420}
9421
9422/**
9423 * @copydoc FNVMATERROR
9424 *
9425 * @remarks Might be some tiny serialization concerns with access to the string
9426 * object here...
9427 */
9428/*static*/ DECLCALLBACK(void)
9429Console::i_genericVMSetErrorCallback(PUVM pUVM, void *pvUser, int rc, RT_SRC_POS_DECL,
9430 const char *pszFormat, va_list args)
9431{
9432 RT_SRC_POS_NOREF();
9433 Utf8Str *pErrorText = (Utf8Str *)pvUser;
9434 AssertPtr(pErrorText);
9435
9436 /* We ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users. */
9437 va_list va2;
9438 va_copy(va2, args);
9439
9440 /* Append to any the existing error message. */
9441 if (pErrorText->length())
9442 *pErrorText = Utf8StrFmt("%s.\n%N (%Rrc)", pErrorText->c_str(),
9443 pszFormat, &va2, rc, rc);
9444 else
9445 *pErrorText = Utf8StrFmt("%N (%Rrc)", pszFormat, &va2, rc, rc);
9446
9447 va_end(va2);
9448
9449 NOREF(pUVM);
9450}
9451
9452/**
9453 * VM runtime error callback function (FNVMATRUNTIMEERROR).
9454 *
9455 * See VMSetRuntimeError for the detailed description of parameters.
9456 *
9457 * @param pUVM The user mode VM handle. Ignored, so passing NULL
9458 * is fine.
9459 * @param pvUser The user argument, pointer to the Console instance.
9460 * @param fFlags The action flags. See VMSETRTERR_FLAGS_*.
9461 * @param pszErrorId Error ID string.
9462 * @param pszFormat Error message format string.
9463 * @param va Error message arguments.
9464 * @thread EMT.
9465 */
9466/* static */ DECLCALLBACK(void)
9467Console::i_atVMRuntimeErrorCallback(PUVM pUVM, void *pvUser, uint32_t fFlags,
9468 const char *pszErrorId, const char *pszFormat, va_list va)
9469{
9470 bool const fFatal = !!(fFlags & VMSETRTERR_FLAGS_FATAL);
9471 LogFlowFuncEnter();
9472
9473 Console *that = static_cast<Console *>(pvUser);
9474 AssertReturnVoid(that);
9475
9476 Utf8Str message(pszFormat, va);
9477
9478 LogRel(("Console: VM runtime error: fatal=%RTbool, errorID=%s message=\"%s\"\n",
9479 fFatal, pszErrorId, message.c_str()));
9480
9481 that->i_onRuntimeError(BOOL(fFatal), Bstr(pszErrorId).raw(), Bstr(message).raw());
9482
9483 LogFlowFuncLeave(); NOREF(pUVM);
9484}
9485
9486/**
9487 * Captures USB devices that match filters of the VM.
9488 * Called at VM startup.
9489 *
9490 * @param pUVM The VM handle.
9491 */
9492HRESULT Console::i_captureUSBDevices(PUVM pUVM)
9493{
9494 RT_NOREF(pUVM);
9495 LogFlowThisFunc(("\n"));
9496
9497 /* sanity check */
9498 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
9499 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9500
9501 /* If the machine has a USB controller, ask the USB proxy service to
9502 * capture devices */
9503 if (mfVMHasUsbController)
9504 {
9505 /* release the lock before calling Host in VBoxSVC since Host may call
9506 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
9507 * produce an inter-process dead-lock otherwise. */
9508 alock.release();
9509
9510 HRESULT hrc = mControl->AutoCaptureUSBDevices();
9511 ComAssertComRCRetRC(hrc);
9512 }
9513
9514 return S_OK;
9515}
9516
9517
9518/**
9519 * Detach all USB device which are attached to the VM for the
9520 * purpose of clean up and such like.
9521 */
9522void Console::i_detachAllUSBDevices(bool aDone)
9523{
9524 LogFlowThisFunc(("aDone=%RTbool\n", aDone));
9525
9526 /* sanity check */
9527 AssertReturnVoid(!isWriteLockOnCurrentThread());
9528 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9529
9530 mUSBDevices.clear();
9531
9532 /* release the lock before calling Host in VBoxSVC since Host may call
9533 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
9534 * produce an inter-process dead-lock otherwise. */
9535 alock.release();
9536
9537 mControl->DetachAllUSBDevices(aDone);
9538}
9539
9540/**
9541 * @note Locks this object for writing.
9542 */
9543void Console::i_processRemoteUSBDevices(uint32_t u32ClientId, VRDEUSBDEVICEDESC *pDevList, uint32_t cbDevList, bool fDescExt)
9544{
9545 LogFlowThisFuncEnter();
9546 LogFlowThisFunc(("u32ClientId = %d, pDevList=%p, cbDevList = %d, fDescExt = %d\n",
9547 u32ClientId, pDevList, cbDevList, fDescExt));
9548
9549 AutoCaller autoCaller(this);
9550 if (!autoCaller.isOk())
9551 {
9552 /* Console has been already uninitialized, deny request */
9553 AssertMsgFailed(("Console is already uninitialized\n"));
9554 LogFlowThisFunc(("Console is already uninitialized\n"));
9555 LogFlowThisFuncLeave();
9556 return;
9557 }
9558
9559 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9560
9561 /*
9562 * Mark all existing remote USB devices as dirty.
9563 */
9564 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
9565 it != mRemoteUSBDevices.end();
9566 ++it)
9567 {
9568 (*it)->dirty(true);
9569 }
9570
9571 /*
9572 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
9573 */
9574 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
9575 VRDEUSBDEVICEDESC *e = pDevList;
9576
9577 /* The cbDevList condition must be checked first, because the function can
9578 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
9579 */
9580 while (cbDevList >= 2 && e->oNext)
9581 {
9582 /* Sanitize incoming strings in case they aren't valid UTF-8. */
9583 if (e->oManufacturer)
9584 RTStrPurgeEncoding((char *)e + e->oManufacturer);
9585 if (e->oProduct)
9586 RTStrPurgeEncoding((char *)e + e->oProduct);
9587 if (e->oSerialNumber)
9588 RTStrPurgeEncoding((char *)e + e->oSerialNumber);
9589
9590 LogFlowThisFunc(("vendor %04X, product %04X, name = %s\n",
9591 e->idVendor, e->idProduct,
9592 e->oProduct? (char *)e + e->oProduct: ""));
9593
9594 bool fNewDevice = true;
9595
9596 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
9597 it != mRemoteUSBDevices.end();
9598 ++it)
9599 {
9600 if ((*it)->devId() == e->id
9601 && (*it)->clientId() == u32ClientId)
9602 {
9603 /* The device is already in the list. */
9604 (*it)->dirty(false);
9605 fNewDevice = false;
9606 break;
9607 }
9608 }
9609
9610 if (fNewDevice)
9611 {
9612 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
9613 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""));
9614
9615 /* Create the device object and add the new device to list. */
9616 ComObjPtr<RemoteUSBDevice> pUSBDevice;
9617 pUSBDevice.createObject();
9618 pUSBDevice->init(u32ClientId, e, fDescExt);
9619
9620 mRemoteUSBDevices.push_back(pUSBDevice);
9621
9622 /* Check if the device is ok for current USB filters. */
9623 BOOL fMatched = FALSE;
9624 ULONG fMaskedIfs = 0;
9625
9626 HRESULT hrc = mControl->RunUSBDeviceFilters(pUSBDevice, &fMatched, &fMaskedIfs);
9627
9628 AssertComRC(hrc);
9629
9630 LogFlowThisFunc(("USB filters return %d %#x\n", fMatched, fMaskedIfs));
9631
9632 if (fMatched)
9633 {
9634 alock.release();
9635 hrc = i_onUSBDeviceAttach(pUSBDevice, NULL, fMaskedIfs, Utf8Str());
9636 alock.acquire();
9637
9638 /// @todo (r=dmik) warning reporting subsystem
9639
9640 if (hrc == S_OK)
9641 {
9642 LogFlowThisFunc(("Device attached\n"));
9643 pUSBDevice->captured(true);
9644 }
9645 }
9646 }
9647
9648 if (cbDevList < e->oNext)
9649 {
9650 Log1WarningThisFunc(("cbDevList %d > oNext %d\n", cbDevList, e->oNext));
9651 break;
9652 }
9653
9654 cbDevList -= e->oNext;
9655
9656 e = (VRDEUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
9657 }
9658
9659 /*
9660 * Remove dirty devices, that is those which are not reported by the server anymore.
9661 */
9662 for (;;)
9663 {
9664 ComObjPtr<RemoteUSBDevice> pUSBDevice;
9665
9666 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
9667 while (it != mRemoteUSBDevices.end())
9668 {
9669 if ((*it)->dirty())
9670 {
9671 pUSBDevice = *it;
9672 break;
9673 }
9674
9675 ++it;
9676 }
9677
9678 if (!pUSBDevice)
9679 {
9680 break;
9681 }
9682
9683 USHORT vendorId = 0;
9684 pUSBDevice->COMGETTER(VendorId)(&vendorId);
9685
9686 USHORT productId = 0;
9687 pUSBDevice->COMGETTER(ProductId)(&productId);
9688
9689 Bstr product;
9690 pUSBDevice->COMGETTER(Product)(product.asOutParam());
9691
9692 LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
9693 vendorId, productId, product.raw()));
9694
9695 /* Detach the device from VM. */
9696 if (pUSBDevice->captured())
9697 {
9698 Bstr uuid;
9699 pUSBDevice->COMGETTER(Id)(uuid.asOutParam());
9700 alock.release();
9701 i_onUSBDeviceDetach(uuid.raw(), NULL);
9702 alock.acquire();
9703 }
9704
9705 /* And remove it from the list. */
9706 mRemoteUSBDevices.erase(it);
9707 }
9708
9709 LogFlowThisFuncLeave();
9710}
9711
9712/**
9713 * Progress cancelation callback for fault tolerance VM poweron
9714 */
9715static void faultToleranceProgressCancelCallback(void *pvUser)
9716{
9717 PUVM pUVM = (PUVM)pvUser;
9718
9719 if (pUVM)
9720 FTMR3CancelStandby(pUVM);
9721}
9722
9723/**
9724 * Worker called by VMPowerUpTask::handler to start the VM (also from saved
9725 * state) and track progress.
9726 *
9727 * @param pTask The power up task.
9728 *
9729 * @note Locks the Console object for writing.
9730 */
9731/*static*/
9732void Console::i_powerUpThreadTask(VMPowerUpTask *pTask)
9733{
9734 LogFlowFuncEnter();
9735
9736 AssertReturnVoid(pTask);
9737 AssertReturnVoid(!pTask->mConsole.isNull());
9738 AssertReturnVoid(!pTask->mProgress.isNull());
9739
9740 VirtualBoxBase::initializeComForThread();
9741
9742 HRESULT rc = S_OK;
9743 int vrc = VINF_SUCCESS;
9744
9745 /* Set up a build identifier so that it can be seen from core dumps what
9746 * exact build was used to produce the core. */
9747 static char saBuildID[48];
9748 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%u %s%s%s%s",
9749 "BU", "IL", "DI", "D", RTBldCfgVersion(), RTBldCfgRevision(), "BU", "IL", "DI", "D");
9750
9751 ComObjPtr<Console> pConsole = pTask->mConsole;
9752
9753 /* Note: no need to use AutoCaller because VMPowerUpTask does that */
9754
9755 /* The lock is also used as a signal from the task initiator (which
9756 * releases it only after RTThreadCreate()) that we can start the job */
9757 AutoWriteLock alock(pConsole COMMA_LOCKVAL_SRC_POS);
9758
9759 /* sanity */
9760 Assert(pConsole->mpUVM == NULL);
9761
9762 try
9763 {
9764 // Create the VMM device object, which starts the HGCM thread; do this only
9765 // once for the console, for the pathological case that the same console
9766 // object is used to power up a VM twice.
9767 if (!pConsole->m_pVMMDev)
9768 {
9769 pConsole->m_pVMMDev = new VMMDev(pConsole);
9770 AssertReturnVoid(pConsole->m_pVMMDev);
9771 }
9772
9773 /* wait for auto reset ops to complete so that we can successfully lock
9774 * the attached hard disks by calling LockMedia() below */
9775 for (VMPowerUpTask::ProgressList::const_iterator
9776 it = pTask->hardDiskProgresses.begin();
9777 it != pTask->hardDiskProgresses.end(); ++it)
9778 {
9779 HRESULT rc2 = (*it)->WaitForCompletion(-1);
9780 AssertComRC(rc2);
9781
9782 rc = pTask->mProgress->SetNextOperation(BstrFmt(tr("Disk Image Reset Operation - Immutable Image")).raw(), 1);
9783 AssertComRCReturnVoid(rc);
9784 }
9785
9786 /*
9787 * Lock attached media. This method will also check their accessibility.
9788 * If we're a teleporter, we'll have to postpone this action so we can
9789 * migrate between local processes.
9790 *
9791 * Note! The media will be unlocked automatically by
9792 * SessionMachine::i_setMachineState() when the VM is powered down.
9793 */
9794 if ( !pTask->mTeleporterEnabled
9795 && pTask->mEnmFaultToleranceState != FaultToleranceState_Standby)
9796 {
9797 rc = pConsole->mControl->LockMedia();
9798 if (FAILED(rc)) throw rc;
9799 }
9800
9801 /* Create the VRDP server. In case of headless operation, this will
9802 * also create the framebuffer, required at VM creation.
9803 */
9804 ConsoleVRDPServer *server = pConsole->i_consoleVRDPServer();
9805 Assert(server);
9806
9807 /* Does VRDP server call Console from the other thread?
9808 * Not sure (and can change), so release the lock just in case.
9809 */
9810 alock.release();
9811 vrc = server->Launch();
9812 alock.acquire();
9813
9814 if (vrc != VINF_SUCCESS)
9815 {
9816 Utf8Str errMsg = pConsole->VRDPServerErrorToMsg(vrc);
9817 if ( RT_FAILURE(vrc)
9818 && vrc != VERR_NET_ADDRESS_IN_USE) /* not fatal */
9819 throw i_setErrorStatic(E_FAIL, errMsg.c_str());
9820 }
9821
9822 ComPtr<IMachine> pMachine = pConsole->i_machine();
9823 ULONG cCpus = 1;
9824 pMachine->COMGETTER(CPUCount)(&cCpus);
9825
9826 /*
9827 * Create the VM
9828 *
9829 * Note! Release the lock since EMT will call Console. It's safe because
9830 * mMachineState is either Starting or Restoring state here.
9831 */
9832 alock.release();
9833
9834 PVM pVM;
9835 vrc = VMR3Create(cCpus,
9836 pConsole->mpVmm2UserMethods,
9837 Console::i_genericVMSetErrorCallback,
9838 &pTask->mErrorMsg,
9839 pTask->mConfigConstructor,
9840 static_cast<Console *>(pConsole),
9841 &pVM, NULL);
9842
9843 alock.acquire();
9844
9845 /* Enable client connections to the server. */
9846 pConsole->i_consoleVRDPServer()->EnableConnections();
9847
9848 if (RT_SUCCESS(vrc))
9849 {
9850 do
9851 {
9852 /*
9853 * Register our load/save state file handlers
9854 */
9855 vrc = SSMR3RegisterExternal(pConsole->mpUVM, sSSMConsoleUnit, 0 /*iInstance*/, sSSMConsoleVer, 0 /* cbGuess */,
9856 NULL, NULL, NULL,
9857 NULL, i_saveStateFileExec, NULL,
9858 NULL, i_loadStateFileExec, NULL,
9859 static_cast<Console *>(pConsole));
9860 AssertRCBreak(vrc);
9861
9862 vrc = static_cast<Console *>(pConsole)->i_getDisplay()->i_registerSSM(pConsole->mpUVM);
9863 AssertRC(vrc);
9864 if (RT_FAILURE(vrc))
9865 break;
9866
9867 /*
9868 * Synchronize debugger settings
9869 */
9870 MachineDebugger *machineDebugger = pConsole->i_getMachineDebugger();
9871 if (machineDebugger)
9872 machineDebugger->i_flushQueuedSettings();
9873
9874 /*
9875 * Shared Folders
9876 */
9877 if (pConsole->m_pVMMDev->isShFlActive())
9878 {
9879 /* Does the code below call Console from the other thread?
9880 * Not sure, so release the lock just in case. */
9881 alock.release();
9882
9883 for (SharedFolderDataMap::const_iterator it = pTask->mSharedFolders.begin();
9884 it != pTask->mSharedFolders.end();
9885 ++it)
9886 {
9887 const SharedFolderData &d = it->second;
9888 rc = pConsole->i_createSharedFolder(it->first, d);
9889 if (FAILED(rc))
9890 {
9891 ErrorInfoKeeper eik;
9892 pConsole->i_atVMRuntimeErrorCallbackF(0, "BrokenSharedFolder",
9893 N_("The shared folder '%s' could not be set up: %ls.\n"
9894 "The shared folder setup will not be complete. It is recommended to power down the virtual "
9895 "machine and fix the shared folder settings while the machine is not running"),
9896 it->first.c_str(), eik.getText().raw());
9897 }
9898 }
9899 if (FAILED(rc))
9900 rc = S_OK; // do not fail with broken shared folders
9901
9902 /* acquire the lock again */
9903 alock.acquire();
9904 }
9905
9906 /* release the lock before a lengthy operation */
9907 alock.release();
9908
9909 /*
9910 * Capture USB devices.
9911 */
9912 rc = pConsole->i_captureUSBDevices(pConsole->mpUVM);
9913 if (FAILED(rc))
9914 {
9915 alock.acquire();
9916 break;
9917 }
9918
9919 /* Load saved state? */
9920 if (pTask->mSavedStateFile.length())
9921 {
9922 LogFlowFunc(("Restoring saved state from '%s'...\n", pTask->mSavedStateFile.c_str()));
9923
9924 vrc = VMR3LoadFromFile(pConsole->mpUVM,
9925 pTask->mSavedStateFile.c_str(),
9926 Console::i_stateProgressCallback,
9927 static_cast<IProgress *>(pTask->mProgress));
9928
9929 if (RT_SUCCESS(vrc))
9930 {
9931 if (pTask->mStartPaused)
9932 /* done */
9933 pConsole->i_setMachineState(MachineState_Paused);
9934 else
9935 {
9936 /* Start/Resume the VM execution */
9937#ifdef VBOX_WITH_EXTPACK
9938 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM);
9939#endif
9940 if (RT_SUCCESS(vrc))
9941 vrc = VMR3Resume(pConsole->mpUVM, VMRESUMEREASON_STATE_RESTORED);
9942 AssertLogRelRC(vrc);
9943 }
9944 }
9945
9946 /* Power off in case we failed loading or resuming the VM */
9947 if (RT_FAILURE(vrc))
9948 {
9949 int vrc2 = VMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
9950#ifdef VBOX_WITH_EXTPACK
9951 pConsole->mptrExtPackManager->i_callAllVmPowerOffHooks(pConsole, pVM);
9952#endif
9953 }
9954 }
9955 else if (pTask->mTeleporterEnabled)
9956 {
9957 /* -> ConsoleImplTeleporter.cpp */
9958 bool fPowerOffOnFailure;
9959 rc = pConsole->i_teleporterTrg(pConsole->mpUVM, pMachine, &pTask->mErrorMsg, pTask->mStartPaused,
9960 pTask->mProgress, &fPowerOffOnFailure);
9961 if (FAILED(rc) && fPowerOffOnFailure)
9962 {
9963 ErrorInfoKeeper eik;
9964 int vrc2 = VMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
9965#ifdef VBOX_WITH_EXTPACK
9966 pConsole->mptrExtPackManager->i_callAllVmPowerOffHooks(pConsole, pVM);
9967#endif
9968 }
9969 }
9970 else if (pTask->mEnmFaultToleranceState != FaultToleranceState_Inactive)
9971 {
9972 /*
9973 * Get the config.
9974 */
9975 ULONG uPort;
9976 rc = pMachine->COMGETTER(FaultTolerancePort)(&uPort);
9977 if (SUCCEEDED(rc))
9978 {
9979 ULONG uInterval;
9980 rc = pMachine->COMGETTER(FaultToleranceSyncInterval)(&uInterval);
9981 if (SUCCEEDED(rc))
9982 {
9983 Bstr bstrAddress;
9984 rc = pMachine->COMGETTER(FaultToleranceAddress)(bstrAddress.asOutParam());
9985 if (SUCCEEDED(rc))
9986 {
9987 Bstr bstrPassword;
9988 rc = pMachine->COMGETTER(FaultTolerancePassword)(bstrPassword.asOutParam());
9989 if (SUCCEEDED(rc))
9990 {
9991 if (pTask->mProgress->i_setCancelCallback(faultToleranceProgressCancelCallback,
9992 pConsole->mpUVM))
9993 {
9994 if (SUCCEEDED(rc))
9995 {
9996 Utf8Str strAddress(bstrAddress);
9997 const char *pszAddress = strAddress.isEmpty() ? NULL : strAddress.c_str();
9998 Utf8Str strPassword(bstrPassword);
9999 const char *pszPassword = strPassword.isEmpty() ? NULL : strPassword.c_str();
10000
10001 /* Power on the FT enabled VM. */
10002#ifdef VBOX_WITH_EXTPACK
10003 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM);
10004#endif
10005 if (RT_SUCCESS(vrc))
10006 vrc = FTMR3PowerOn(pConsole->mpUVM,
10007 pTask->mEnmFaultToleranceState == FaultToleranceState_Master /* fMaster */,
10008 uInterval,
10009 pszAddress,
10010 uPort,
10011 pszPassword);
10012 AssertLogRelRC(vrc);
10013 }
10014 pTask->mProgress->i_setCancelCallback(NULL, NULL);
10015 }
10016 else
10017 rc = E_FAIL;
10018
10019 }
10020 }
10021 }
10022 }
10023 }
10024 else if (pTask->mStartPaused)
10025 /* done */
10026 pConsole->i_setMachineState(MachineState_Paused);
10027 else
10028 {
10029 /* Power on the VM (i.e. start executing) */
10030#ifdef VBOX_WITH_EXTPACK
10031 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM);
10032#endif
10033 if (RT_SUCCESS(vrc))
10034 vrc = VMR3PowerOn(pConsole->mpUVM);
10035 AssertLogRelRC(vrc);
10036 }
10037
10038 /* acquire the lock again */
10039 alock.acquire();
10040 }
10041 while (0);
10042
10043 /* On failure, destroy the VM */
10044 if (FAILED(rc) || RT_FAILURE(vrc))
10045 {
10046 /* preserve existing error info */
10047 ErrorInfoKeeper eik;
10048
10049 /* powerDown() will call VMR3Destroy() and do all necessary
10050 * cleanup (VRDP, USB devices) */
10051 alock.release();
10052 HRESULT rc2 = pConsole->i_powerDown();
10053 alock.acquire();
10054 AssertComRC(rc2);
10055 }
10056 else
10057 {
10058 /*
10059 * Deregister the VMSetError callback. This is necessary as the
10060 * pfnVMAtError() function passed to VMR3Create() is supposed to
10061 * be sticky but our error callback isn't.
10062 */
10063 alock.release();
10064 VMR3AtErrorDeregister(pConsole->mpUVM, Console::i_genericVMSetErrorCallback, &pTask->mErrorMsg);
10065 /** @todo register another VMSetError callback? */
10066 alock.acquire();
10067 }
10068 }
10069 else
10070 {
10071 /*
10072 * If VMR3Create() failed it has released the VM memory.
10073 */
10074 VMR3ReleaseUVM(pConsole->mpUVM);
10075 pConsole->mpUVM = NULL;
10076 }
10077
10078 if (SUCCEEDED(rc) && RT_FAILURE(vrc))
10079 {
10080 /* If VMR3Create() or one of the other calls in this function fail,
10081 * an appropriate error message has been set in pTask->mErrorMsg.
10082 * However since that happens via a callback, the rc status code in
10083 * this function is not updated.
10084 */
10085 if (!pTask->mErrorMsg.length())
10086 {
10087 /* If the error message is not set but we've got a failure,
10088 * convert the VBox status code into a meaningful error message.
10089 * This becomes unused once all the sources of errors set the
10090 * appropriate error message themselves.
10091 */
10092 AssertMsgFailed(("Missing error message during powerup for status code %Rrc\n", vrc));
10093 pTask->mErrorMsg = Utf8StrFmt(tr("Failed to start VM execution (%Rrc)"), vrc);
10094 }
10095
10096 /* Set the error message as the COM error.
10097 * Progress::notifyComplete() will pick it up later. */
10098 throw i_setErrorStatic(E_FAIL, pTask->mErrorMsg.c_str());
10099 }
10100 }
10101 catch (HRESULT aRC) { rc = aRC; }
10102
10103 if ( pConsole->mMachineState == MachineState_Starting
10104 || pConsole->mMachineState == MachineState_Restoring
10105 || pConsole->mMachineState == MachineState_TeleportingIn
10106 )
10107 {
10108 /* We are still in the Starting/Restoring state. This means one of:
10109 *
10110 * 1) we failed before VMR3Create() was called;
10111 * 2) VMR3Create() failed.
10112 *
10113 * In both cases, there is no need to call powerDown(), but we still
10114 * need to go back to the PoweredOff/Saved state. Reuse
10115 * vmstateChangeCallback() for that purpose.
10116 */
10117
10118 /* preserve existing error info */
10119 ErrorInfoKeeper eik;
10120
10121 Assert(pConsole->mpUVM == NULL);
10122 i_vmstateChangeCallback(NULL, VMSTATE_TERMINATED, VMSTATE_CREATING, pConsole);
10123 }
10124
10125 /*
10126 * Evaluate the final result. Note that the appropriate mMachineState value
10127 * is already set by vmstateChangeCallback() in all cases.
10128 */
10129
10130 /* release the lock, don't need it any more */
10131 alock.release();
10132
10133 if (SUCCEEDED(rc))
10134 {
10135 /* Notify the progress object of the success */
10136 pTask->mProgress->i_notifyComplete(S_OK);
10137 }
10138 else
10139 {
10140 /* The progress object will fetch the current error info */
10141 pTask->mProgress->i_notifyComplete(rc);
10142 LogRel(("Power up failed (vrc=%Rrc, rc=%Rhrc (%#08X))\n", vrc, rc, rc));
10143 }
10144
10145 /* Notify VBoxSVC and any waiting openRemoteSession progress object. */
10146 pConsole->mControl->EndPowerUp(rc);
10147
10148#if defined(RT_OS_WINDOWS)
10149 /* uninitialize COM */
10150 CoUninitialize();
10151#endif
10152
10153 LogFlowFuncLeave();
10154}
10155
10156
10157/**
10158 * Reconfigures a medium attachment (part of taking or deleting an online snapshot).
10159 *
10160 * @param pThis Reference to the console object.
10161 * @param pUVM The VM handle.
10162 * @param pcszDevice The name of the controller type.
10163 * @param uInstance The instance of the controller.
10164 * @param enmBus The storage bus type of the controller.
10165 * @param fUseHostIOCache Use the host I/O cache (disable async I/O).
10166 * @param fBuiltinIOCache Use the builtin I/O cache.
10167 * @param fInsertDiskIntegrityDrv Flag whether to insert the disk integrity driver into the chain
10168 * for additionalk debugging aids.
10169 * @param fSetupMerge Whether to set up a medium merge
10170 * @param uMergeSource Merge source image index
10171 * @param uMergeTarget Merge target image index
10172 * @param aMediumAtt The medium attachment.
10173 * @param aMachineState The current machine state.
10174 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
10175 * @return VBox status code.
10176 */
10177/* static */
10178DECLCALLBACK(int) Console::i_reconfigureMediumAttachment(Console *pThis,
10179 PUVM pUVM,
10180 const char *pcszDevice,
10181 unsigned uInstance,
10182 StorageBus_T enmBus,
10183 bool fUseHostIOCache,
10184 bool fBuiltinIOCache,
10185 bool fInsertDiskIntegrityDrv,
10186 bool fSetupMerge,
10187 unsigned uMergeSource,
10188 unsigned uMergeTarget,
10189 IMediumAttachment *aMediumAtt,
10190 MachineState_T aMachineState,
10191 HRESULT *phrc)
10192{
10193 LogFlowFunc(("pUVM=%p aMediumAtt=%p phrc=%p\n", pUVM, aMediumAtt, phrc));
10194
10195 HRESULT hrc;
10196 Bstr bstr;
10197 *phrc = S_OK;
10198#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%Rhrc (%#x)\n", hrc, hrc)); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
10199
10200 /* Ignore attachments other than hard disks, since at the moment they are
10201 * not subject to snapshotting in general. */
10202 DeviceType_T lType;
10203 hrc = aMediumAtt->COMGETTER(Type)(&lType); H();
10204 if (lType != DeviceType_HardDisk)
10205 return VINF_SUCCESS;
10206
10207 /* Update the device instance configuration. */
10208 int rc = pThis->i_configMediumAttachment(pcszDevice,
10209 uInstance,
10210 enmBus,
10211 fUseHostIOCache,
10212 fBuiltinIOCache,
10213 fInsertDiskIntegrityDrv,
10214 fSetupMerge,
10215 uMergeSource,
10216 uMergeTarget,
10217 aMediumAtt,
10218 aMachineState,
10219 phrc,
10220 true /* fAttachDetach */,
10221 false /* fForceUnmount */,
10222 false /* fHotplug */,
10223 pUVM,
10224 NULL /* paLedDevType */,
10225 NULL /* ppLunL0)*/);
10226 if (RT_FAILURE(rc))
10227 {
10228 AssertMsgFailed(("rc=%Rrc\n", rc));
10229 return rc;
10230 }
10231
10232#undef H
10233
10234 LogFlowFunc(("Returns success\n"));
10235 return VINF_SUCCESS;
10236}
10237
10238/**
10239 * Thread for powering down the Console.
10240 *
10241 * @param pTask The power down task.
10242 *
10243 * @note Locks the Console object for writing.
10244 */
10245/*static*/
10246void Console::i_powerDownThreadTask(VMPowerDownTask *pTask)
10247{
10248 int rc = VINF_SUCCESS; /* only used in assertion */
10249 LogFlowFuncEnter();
10250 try
10251 {
10252 if (pTask->isOk() == false)
10253 rc = VERR_GENERAL_FAILURE;
10254
10255 const ComObjPtr<Console> &that = pTask->mConsole;
10256
10257 /* Note: no need to use AutoCaller to protect Console because VMTask does
10258 * that */
10259
10260 /* wait until the method tat started us returns */
10261 AutoWriteLock thatLock(that COMMA_LOCKVAL_SRC_POS);
10262
10263 /* release VM caller to avoid the powerDown() deadlock */
10264 pTask->releaseVMCaller();
10265
10266 thatLock.release();
10267
10268 that->i_powerDown(pTask->mServerProgress);
10269
10270 /* complete the operation */
10271 that->mControl->EndPoweringDown(S_OK, Bstr().raw());
10272
10273 }
10274 catch (const std::exception &e)
10275 {
10276 AssertMsgFailed(("Exception %s was caught, rc=%Rrc\n", e.what(), rc));
10277 NOREF(e); NOREF(rc);
10278 }
10279
10280 LogFlowFuncLeave();
10281}
10282
10283/**
10284 * @interface_method_impl{VMM2USERMETHODS,pfnSaveState}
10285 */
10286/*static*/ DECLCALLBACK(int)
10287Console::i_vmm2User_SaveState(PCVMM2USERMETHODS pThis, PUVM pUVM)
10288{
10289 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
10290 NOREF(pUVM);
10291
10292 /*
10293 * For now, just call SaveState. We should probably try notify the GUI so
10294 * it can pop up a progress object and stuff. The progress object created
10295 * by the call isn't returned to anyone and thus gets updated without
10296 * anyone noticing it.
10297 */
10298 ComPtr<IProgress> pProgress;
10299 HRESULT hrc = pConsole->mMachine->SaveState(pProgress.asOutParam());
10300 return SUCCEEDED(hrc) ? VINF_SUCCESS : Global::vboxStatusCodeFromCOM(hrc);
10301}
10302
10303/**
10304 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtInit}
10305 */
10306/*static*/ DECLCALLBACK(void)
10307Console::i_vmm2User_NotifyEmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
10308{
10309 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
10310 VirtualBoxBase::initializeComForThread();
10311}
10312
10313/**
10314 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtTerm}
10315 */
10316/*static*/ DECLCALLBACK(void)
10317Console::i_vmm2User_NotifyEmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
10318{
10319 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
10320 VirtualBoxBase::uninitializeComForThread();
10321}
10322
10323/**
10324 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtInit}
10325 */
10326/*static*/ DECLCALLBACK(void)
10327Console::i_vmm2User_NotifyPdmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM)
10328{
10329 NOREF(pThis); NOREF(pUVM);
10330 VirtualBoxBase::initializeComForThread();
10331}
10332
10333/**
10334 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtTerm}
10335 */
10336/*static*/ DECLCALLBACK(void)
10337Console::i_vmm2User_NotifyPdmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM)
10338{
10339 NOREF(pThis); NOREF(pUVM);
10340 VirtualBoxBase::uninitializeComForThread();
10341}
10342
10343/**
10344 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyResetTurnedIntoPowerOff}
10345 */
10346/*static*/ DECLCALLBACK(void)
10347Console::i_vmm2User_NotifyResetTurnedIntoPowerOff(PCVMM2USERMETHODS pThis, PUVM pUVM)
10348{
10349 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
10350 NOREF(pUVM);
10351
10352 pConsole->mfPowerOffCausedByReset = true;
10353}
10354
10355
10356
10357
10358/**
10359 * @interface_method_impl{PDMISECKEY,pfnKeyRetain}
10360 */
10361/*static*/ DECLCALLBACK(int)
10362Console::i_pdmIfSecKey_KeyRetain(PPDMISECKEY pInterface, const char *pszId, const uint8_t **ppbKey,
10363 size_t *pcbKey)
10364{
10365 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
10366
10367 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
10368 SecretKey *pKey = NULL;
10369
10370 int rc = pConsole->m_pKeyStore->retainSecretKey(Utf8Str(pszId), &pKey);
10371 if (RT_SUCCESS(rc))
10372 {
10373 *ppbKey = (const uint8_t *)pKey->getKeyBuffer();
10374 *pcbKey = pKey->getKeySize();
10375 }
10376
10377 return rc;
10378}
10379
10380/**
10381 * @interface_method_impl{PDMISECKEY,pfnKeyRelease}
10382 */
10383/*static*/ DECLCALLBACK(int)
10384Console::i_pdmIfSecKey_KeyRelease(PPDMISECKEY pInterface, const char *pszId)
10385{
10386 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
10387
10388 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
10389 return pConsole->m_pKeyStore->releaseSecretKey(Utf8Str(pszId));
10390}
10391
10392/**
10393 * @interface_method_impl{PDMISECKEY,pfnPasswordRetain}
10394 */
10395/*static*/ DECLCALLBACK(int)
10396Console::i_pdmIfSecKey_PasswordRetain(PPDMISECKEY pInterface, const char *pszId, const char **ppszPassword)
10397{
10398 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
10399
10400 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
10401 SecretKey *pKey = NULL;
10402
10403 int rc = pConsole->m_pKeyStore->retainSecretKey(Utf8Str(pszId), &pKey);
10404 if (RT_SUCCESS(rc))
10405 *ppszPassword = (const char *)pKey->getKeyBuffer();
10406
10407 return rc;
10408}
10409
10410/**
10411 * @interface_method_impl{PDMISECKEY,pfnPasswordRelease}
10412 */
10413/*static*/ DECLCALLBACK(int)
10414Console::i_pdmIfSecKey_PasswordRelease(PPDMISECKEY pInterface, const char *pszId)
10415{
10416 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
10417
10418 AutoReadLock thatLock(pConsole COMMA_LOCKVAL_SRC_POS);
10419 return pConsole->m_pKeyStore->releaseSecretKey(Utf8Str(pszId));
10420}
10421
10422/**
10423 * @interface_method_impl{PDMISECKEYHLP,pfnKeyMissingNotify}
10424 */
10425/*static*/ DECLCALLBACK(int)
10426Console::i_pdmIfSecKeyHlp_KeyMissingNotify(PPDMISECKEYHLP pInterface)
10427{
10428 Console *pConsole = ((MYPDMISECKEYHLP *)pInterface)->pConsole;
10429
10430 /* Set guest property only, the VM is paused in the media driver calling us. */
10431 pConsole->mMachine->DeleteGuestProperty(Bstr("/VirtualBox/HostInfo/DekMissing").raw());
10432 pConsole->mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/DekMissing").raw(),
10433 Bstr("1").raw(), Bstr("RDONLYGUEST").raw());
10434 pConsole->mMachine->SaveSettings();
10435
10436 return VINF_SUCCESS;
10437}
10438
10439
10440
10441/**
10442 * The Main status driver instance data.
10443 */
10444typedef struct DRVMAINSTATUS
10445{
10446 /** The LED connectors. */
10447 PDMILEDCONNECTORS ILedConnectors;
10448 /** Pointer to the LED ports interface above us. */
10449 PPDMILEDPORTS pLedPorts;
10450 /** Pointer to the array of LED pointers. */
10451 PPDMLED *papLeds;
10452 /** The unit number corresponding to the first entry in the LED array. */
10453 RTUINT iFirstLUN;
10454 /** The unit number corresponding to the last entry in the LED array.
10455 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
10456 RTUINT iLastLUN;
10457 /** Pointer to the driver instance. */
10458 PPDMDRVINS pDrvIns;
10459 /** The Media Notify interface. */
10460 PDMIMEDIANOTIFY IMediaNotify;
10461 /** Map for translating PDM storage controller/LUN information to
10462 * IMediumAttachment references. */
10463 Console::MediumAttachmentMap *pmapMediumAttachments;
10464 /** Device name+instance for mapping */
10465 char *pszDeviceInstance;
10466 /** Pointer to the Console object, for driver triggered activities. */
10467 Console *pConsole;
10468} DRVMAINSTATUS, *PDRVMAINSTATUS;
10469
10470
10471/**
10472 * Notification about a unit which have been changed.
10473 *
10474 * The driver must discard any pointers to data owned by
10475 * the unit and requery it.
10476 *
10477 * @param pInterface Pointer to the interface structure containing the called function pointer.
10478 * @param iLUN The unit number.
10479 */
10480DECLCALLBACK(void) Console::i_drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
10481{
10482 PDRVMAINSTATUS pThis = RT_FROM_MEMBER(pInterface, DRVMAINSTATUS, ILedConnectors);
10483 if (iLUN >= pThis->iFirstLUN && iLUN <= pThis->iLastLUN)
10484 {
10485 PPDMLED pLed;
10486 int rc = pThis->pLedPorts->pfnQueryStatusLed(pThis->pLedPorts, iLUN, &pLed);
10487 if (RT_FAILURE(rc))
10488 pLed = NULL;
10489 ASMAtomicWritePtr(&pThis->papLeds[iLUN - pThis->iFirstLUN], pLed);
10490 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
10491 }
10492}
10493
10494
10495/**
10496 * Notification about a medium eject.
10497 *
10498 * @returns VBox status code.
10499 * @param pInterface Pointer to the interface structure containing the called function pointer.
10500 * @param uLUN The unit number.
10501 */
10502DECLCALLBACK(int) Console::i_drvStatus_MediumEjected(PPDMIMEDIANOTIFY pInterface, unsigned uLUN)
10503{
10504 PDRVMAINSTATUS pThis = RT_FROM_MEMBER(pInterface, DRVMAINSTATUS, IMediaNotify);
10505 LogFunc(("uLUN=%d\n", uLUN));
10506 if (pThis->pmapMediumAttachments)
10507 {
10508 AutoWriteLock alock(pThis->pConsole COMMA_LOCKVAL_SRC_POS);
10509
10510 ComPtr<IMediumAttachment> pMediumAtt;
10511 Utf8Str devicePath = Utf8StrFmt("%s/LUN#%u", pThis->pszDeviceInstance, uLUN);
10512 Console::MediumAttachmentMap::const_iterator end = pThis->pmapMediumAttachments->end();
10513 Console::MediumAttachmentMap::const_iterator it = pThis->pmapMediumAttachments->find(devicePath);
10514 if (it != end)
10515 pMediumAtt = it->second;
10516 Assert(!pMediumAtt.isNull());
10517 if (!pMediumAtt.isNull())
10518 {
10519 IMedium *pMedium = NULL;
10520 HRESULT rc = pMediumAtt->COMGETTER(Medium)(&pMedium);
10521 AssertComRC(rc);
10522 if (SUCCEEDED(rc) && pMedium)
10523 {
10524 BOOL fHostDrive = FALSE;
10525 rc = pMedium->COMGETTER(HostDrive)(&fHostDrive);
10526 AssertComRC(rc);
10527 if (!fHostDrive)
10528 {
10529 alock.release();
10530
10531 ComPtr<IMediumAttachment> pNewMediumAtt;
10532 rc = pThis->pConsole->mControl->EjectMedium(pMediumAtt, pNewMediumAtt.asOutParam());
10533 if (SUCCEEDED(rc))
10534 {
10535 pThis->pConsole->mMachine->SaveSettings();
10536 fireMediumChangedEvent(pThis->pConsole->mEventSource, pNewMediumAtt);
10537 }
10538
10539 alock.acquire();
10540 if (pNewMediumAtt != pMediumAtt)
10541 {
10542 pThis->pmapMediumAttachments->erase(devicePath);
10543 pThis->pmapMediumAttachments->insert(std::make_pair(devicePath, pNewMediumAtt));
10544 }
10545 }
10546 }
10547 }
10548 }
10549 return VINF_SUCCESS;
10550}
10551
10552
10553/**
10554 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
10555 */
10556DECLCALLBACK(void *) Console::i_drvStatus_QueryInterface(PPDMIBASE pInterface, const char *pszIID)
10557{
10558 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
10559 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10560 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
10561 PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDCONNECTORS, &pThis->ILedConnectors);
10562 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIANOTIFY, &pThis->IMediaNotify);
10563 return NULL;
10564}
10565
10566
10567/**
10568 * Destruct a status driver instance.
10569 *
10570 * @returns VBox status code.
10571 * @param pDrvIns The driver instance data.
10572 */
10573DECLCALLBACK(void) Console::i_drvStatus_Destruct(PPDMDRVINS pDrvIns)
10574{
10575 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
10576 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10577 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
10578
10579 if (pThis->papLeds)
10580 {
10581 unsigned iLed = pThis->iLastLUN - pThis->iFirstLUN + 1;
10582 while (iLed-- > 0)
10583 ASMAtomicWriteNullPtr(&pThis->papLeds[iLed]);
10584 }
10585}
10586
10587
10588/**
10589 * Construct a status driver instance.
10590 *
10591 * @copydoc FNPDMDRVCONSTRUCT
10592 */
10593DECLCALLBACK(int) Console::i_drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
10594{
10595 RT_NOREF(fFlags);
10596 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
10597 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10598 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
10599
10600 /*
10601 * Validate configuration.
10602 */
10603 if (!CFGMR3AreValuesValid(pCfg, "papLeds\0pmapMediumAttachments\0DeviceInstance\0pConsole\0First\0Last\0"))
10604 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
10605 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
10606 ("Configuration error: Not possible to attach anything to this driver!\n"),
10607 VERR_PDM_DRVINS_NO_ATTACH);
10608
10609 /*
10610 * Data.
10611 */
10612 pDrvIns->IBase.pfnQueryInterface = Console::i_drvStatus_QueryInterface;
10613 pThis->ILedConnectors.pfnUnitChanged = Console::i_drvStatus_UnitChanged;
10614 pThis->IMediaNotify.pfnEjected = Console::i_drvStatus_MediumEjected;
10615 pThis->pDrvIns = pDrvIns;
10616 pThis->pszDeviceInstance = NULL;
10617
10618 /*
10619 * Read config.
10620 */
10621 int rc = CFGMR3QueryPtr(pCfg, "papLeds", (void **)&pThis->papLeds);
10622 if (RT_FAILURE(rc))
10623 {
10624 AssertMsgFailed(("Configuration error: Failed to query the \"papLeds\" value! rc=%Rrc\n", rc));
10625 return rc;
10626 }
10627
10628 rc = CFGMR3QueryPtrDef(pCfg, "pmapMediumAttachments", (void **)&pThis->pmapMediumAttachments, NULL);
10629 if (RT_FAILURE(rc))
10630 {
10631 AssertMsgFailed(("Configuration error: Failed to query the \"pmapMediumAttachments\" value! rc=%Rrc\n", rc));
10632 return rc;
10633 }
10634 if (pThis->pmapMediumAttachments)
10635 {
10636 rc = CFGMR3QueryStringAlloc(pCfg, "DeviceInstance", &pThis->pszDeviceInstance);
10637 if (RT_FAILURE(rc))
10638 {
10639 AssertMsgFailed(("Configuration error: Failed to query the \"DeviceInstance\" value! rc=%Rrc\n", rc));
10640 return rc;
10641 }
10642 rc = CFGMR3QueryPtr(pCfg, "pConsole", (void **)&pThis->pConsole);
10643 if (RT_FAILURE(rc))
10644 {
10645 AssertMsgFailed(("Configuration error: Failed to query the \"pConsole\" value! rc=%Rrc\n", rc));
10646 return rc;
10647 }
10648 }
10649
10650 rc = CFGMR3QueryU32(pCfg, "First", &pThis->iFirstLUN);
10651 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
10652 pThis->iFirstLUN = 0;
10653 else if (RT_FAILURE(rc))
10654 {
10655 AssertMsgFailed(("Configuration error: Failed to query the \"First\" value! rc=%Rrc\n", rc));
10656 return rc;
10657 }
10658
10659 rc = CFGMR3QueryU32(pCfg, "Last", &pThis->iLastLUN);
10660 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
10661 pThis->iLastLUN = 0;
10662 else if (RT_FAILURE(rc))
10663 {
10664 AssertMsgFailed(("Configuration error: Failed to query the \"Last\" value! rc=%Rrc\n", rc));
10665 return rc;
10666 }
10667 if (pThis->iFirstLUN > pThis->iLastLUN)
10668 {
10669 AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pThis->iFirstLUN, pThis->iLastLUN));
10670 return VERR_GENERAL_FAILURE;
10671 }
10672
10673 /*
10674 * Get the ILedPorts interface of the above driver/device and
10675 * query the LEDs we want.
10676 */
10677 pThis->pLedPorts = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMILEDPORTS);
10678 AssertMsgReturn(pThis->pLedPorts, ("Configuration error: No led ports interface above!\n"),
10679 VERR_PDM_MISSING_INTERFACE_ABOVE);
10680
10681 for (unsigned i = pThis->iFirstLUN; i <= pThis->iLastLUN; ++i)
10682 Console::i_drvStatus_UnitChanged(&pThis->ILedConnectors, i);
10683
10684 return VINF_SUCCESS;
10685}
10686
10687
10688/**
10689 * Console status driver (LED) registration record.
10690 */
10691const PDMDRVREG Console::DrvStatusReg =
10692{
10693 /* u32Version */
10694 PDM_DRVREG_VERSION,
10695 /* szName */
10696 "MainStatus",
10697 /* szRCMod */
10698 "",
10699 /* szR0Mod */
10700 "",
10701 /* pszDescription */
10702 "Main status driver (Main as in the API).",
10703 /* fFlags */
10704 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
10705 /* fClass. */
10706 PDM_DRVREG_CLASS_STATUS,
10707 /* cMaxInstances */
10708 ~0U,
10709 /* cbInstance */
10710 sizeof(DRVMAINSTATUS),
10711 /* pfnConstruct */
10712 Console::i_drvStatus_Construct,
10713 /* pfnDestruct */
10714 Console::i_drvStatus_Destruct,
10715 /* pfnRelocate */
10716 NULL,
10717 /* pfnIOCtl */
10718 NULL,
10719 /* pfnPowerOn */
10720 NULL,
10721 /* pfnReset */
10722 NULL,
10723 /* pfnSuspend */
10724 NULL,
10725 /* pfnResume */
10726 NULL,
10727 /* pfnAttach */
10728 NULL,
10729 /* pfnDetach */
10730 NULL,
10731 /* pfnPowerOff */
10732 NULL,
10733 /* pfnSoftReset */
10734 NULL,
10735 /* u32EndVersion */
10736 PDM_DRVREG_VERSION
10737};
10738
10739
10740
10741/* 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