VirtualBox

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

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

VideoRec: Renaming (be more consistent): video capture vs. video recording.

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

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