VirtualBox

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

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

Docs.

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

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