VirtualBox

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

Last change on this file since 54230 was 54230, checked in by vboxsync, 10 years ago

PDM/Audio: Update.

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

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