VirtualBox

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

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

ConsoleImpl: Ifdef out the code to retrieve DNS info in
Console::i_onNATDnsChanged since we don't yet pass it to
pfnNotifyDnsChanged anyway.

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