VirtualBox

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

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

NAT: Introduce PDMINETWORKNATCONFIG::pfnNotifyDnsChanged and call it
on IHostNameResolutionConfigurationChangeEvent. This is just the
plumbing so far, there's no actual callback yet.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 352.8 KB
Line 
1/* $Id: ConsoleImpl.cpp 54106 2015-02-08 00:43:35Z vboxsync $ */
2/** @file
3 * VBox Console COM Class implementation
4 */
5
6/*
7 * Copyright (C) 2005-2014 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18/** @todo Move the TAP mess back into the driver! */
19#if defined(RT_OS_WINDOWS)
20#elif defined(RT_OS_LINUX)
21# include <errno.h>
22# include <sys/ioctl.h>
23# include <sys/poll.h>
24# include <sys/fcntl.h>
25# include <sys/types.h>
26# include <sys/wait.h>
27# include <net/if.h>
28# include <linux/if_tun.h>
29# include <stdio.h>
30# include <stdlib.h>
31# include <string.h>
32#elif defined(RT_OS_FREEBSD)
33# include <errno.h>
34# include <sys/ioctl.h>
35# include <sys/poll.h>
36# include <sys/fcntl.h>
37# include <sys/types.h>
38# include <sys/wait.h>
39# include <stdio.h>
40# include <stdlib.h>
41# include <string.h>
42#elif defined(RT_OS_SOLARIS)
43# include <iprt/coredumper.h>
44#endif
45
46#include "ConsoleImpl.h"
47
48#include "Global.h"
49#include "VirtualBoxErrorInfoImpl.h"
50#include "GuestImpl.h"
51#include "KeyboardImpl.h"
52#include "MouseImpl.h"
53#include "DisplayImpl.h"
54#include "MachineDebuggerImpl.h"
55#include "USBDeviceImpl.h"
56#include "RemoteUSBDeviceImpl.h"
57#include "SharedFolderImpl.h"
58#ifdef VBOX_WITH_PDM_AUDIO_DRIVER
59#include "DrvAudioVRDE.h"
60#else
61#include "AudioSnifferInterface.h"
62#endif
63#include "Nvram.h"
64#ifdef VBOX_WITH_USB_CARDREADER
65# include "UsbCardReader.h"
66#endif
67#include "ProgressImpl.h"
68#include "ConsoleVRDPServer.h"
69#include "VMMDev.h"
70#ifdef VBOX_WITH_EXTPACK
71# include "ExtPackManagerImpl.h"
72#endif
73#include "BusAssignmentManager.h"
74#include "EmulatedUSBImpl.h"
75
76#include "VBoxEvents.h"
77#include "AutoCaller.h"
78#include "Logging.h"
79
80#include <VBox/com/array.h>
81#include "VBox/com/ErrorInfo.h"
82#include <VBox/com/listeners.h>
83
84#include <iprt/asm.h>
85#include <iprt/buildconfig.h>
86#include <iprt/cpp/utils.h>
87#include <iprt/dir.h>
88#include <iprt/file.h>
89#include <iprt/ldr.h>
90#include <iprt/path.h>
91#include <iprt/process.h>
92#include <iprt/string.h>
93#include <iprt/system.h>
94#include <iprt/base64.h>
95#include <iprt/memsafer.h>
96
97#include <VBox/vmm/vmapi.h>
98#include <VBox/vmm/vmm.h>
99#include <VBox/vmm/pdmapi.h>
100#include <VBox/vmm/pdmasynccompletion.h>
101#include <VBox/vmm/pdmnetifs.h>
102#ifdef VBOX_WITH_USB
103# include <VBox/vmm/pdmusb.h>
104#endif
105#ifdef VBOX_WITH_NETSHAPER
106# include <VBox/vmm/pdmnetshaper.h>
107#endif /* VBOX_WITH_NETSHAPER */
108#include <VBox/vmm/mm.h>
109#include <VBox/vmm/ftm.h>
110#include <VBox/vmm/ssm.h>
111#include <VBox/err.h>
112#include <VBox/param.h>
113#include <VBox/vusb.h>
114
115#include <VBox/VMMDev.h>
116
117#include <VBox/HostServices/VBoxClipboardSvc.h>
118#include <VBox/HostServices/DragAndDropSvc.h>
119#ifdef VBOX_WITH_GUEST_PROPS
120# include <VBox/HostServices/GuestPropertySvc.h>
121# include <VBox/com/array.h>
122#endif
123
124#ifdef VBOX_OPENSSL_FIPS
125# include <openssl/crypto.h>
126#endif
127
128#include <set>
129#include <algorithm>
130#include <memory> // for auto_ptr
131#include <vector>
132
133
134// VMTask and friends
135////////////////////////////////////////////////////////////////////////////////
136
137/**
138 * Task structure for asynchronous VM operations.
139 *
140 * Once created, the task structure adds itself as a Console caller. This means:
141 *
142 * 1. The user must check for #rc() before using the created structure
143 * (e.g. passing it as a thread function argument). If #rc() returns a
144 * failure, the Console object may not be used by the task (see
145 * Console::addCaller() for more details).
146 * 2. On successful initialization, the structure keeps the Console caller
147 * until destruction (to ensure Console remains in the Ready state and won't
148 * be accidentally uninitialized). Forgetting to delete the created task
149 * will lead to Console::uninit() stuck waiting for releasing all added
150 * callers.
151 *
152 * If \a aUsesVMPtr parameter is true, the task structure will also add itself
153 * as a Console::mpUVM caller with the same meaning as above. See
154 * Console::addVMCaller() for more info.
155 */
156struct VMTask
157{
158 VMTask(Console *aConsole,
159 Progress *aProgress,
160 const ComPtr<IProgress> &aServerProgress,
161 bool aUsesVMPtr)
162 : mConsole(aConsole),
163 mConsoleCaller(aConsole),
164 mProgress(aProgress),
165 mServerProgress(aServerProgress),
166 mpUVM(NULL),
167 mRC(E_FAIL),
168 mpSafeVMPtr(NULL)
169 {
170 AssertReturnVoid(aConsole);
171 mRC = mConsoleCaller.rc();
172 if (FAILED(mRC))
173 return;
174 if (aUsesVMPtr)
175 {
176 mpSafeVMPtr = new Console::SafeVMPtr(aConsole);
177 if (mpSafeVMPtr->isOk())
178 mpUVM = mpSafeVMPtr->rawUVM();
179 else
180 mRC = mpSafeVMPtr->rc();
181 }
182 }
183
184 ~VMTask()
185 {
186 releaseVMCaller();
187 }
188
189 HRESULT rc() const { return mRC; }
190 bool isOk() const { return SUCCEEDED(rc()); }
191
192 /** Releases the VM caller before destruction. Not normally necessary. */
193 void releaseVMCaller()
194 {
195 if (mpSafeVMPtr)
196 {
197 delete mpSafeVMPtr;
198 mpSafeVMPtr = NULL;
199 }
200 }
201
202 const ComObjPtr<Console> mConsole;
203 AutoCaller mConsoleCaller;
204 const ComObjPtr<Progress> mProgress;
205 Utf8Str mErrorMsg;
206 const ComPtr<IProgress> mServerProgress;
207 PUVM mpUVM;
208
209private:
210 HRESULT mRC;
211 Console::SafeVMPtr *mpSafeVMPtr;
212};
213
214struct VMTakeSnapshotTask : public VMTask
215{
216 VMTakeSnapshotTask(Console *aConsole,
217 Progress *aProgress,
218 IN_BSTR aName,
219 IN_BSTR aDescription)
220 : VMTask(aConsole, aProgress, NULL /* aServerProgress */,
221 false /* aUsesVMPtr */),
222 bstrName(aName),
223 bstrDescription(aDescription),
224 lastMachineState(MachineState_Null)
225 {}
226
227 Bstr bstrName,
228 bstrDescription;
229 Bstr bstrSavedStateFile; // received from BeginTakeSnapshot()
230 MachineState_T lastMachineState;
231 bool fTakingSnapshotOnline;
232 ULONG ulMemSize;
233};
234
235struct VMPowerUpTask : public VMTask
236{
237 VMPowerUpTask(Console *aConsole,
238 Progress *aProgress)
239 : VMTask(aConsole, aProgress, NULL /* aServerProgress */,
240 false /* aUsesVMPtr */),
241 mConfigConstructor(NULL),
242 mStartPaused(false),
243 mTeleporterEnabled(FALSE),
244 mEnmFaultToleranceState(FaultToleranceState_Inactive)
245 {}
246
247 PFNCFGMCONSTRUCTOR mConfigConstructor;
248 Utf8Str mSavedStateFile;
249 Console::SharedFolderDataMap mSharedFolders;
250 bool mStartPaused;
251 BOOL mTeleporterEnabled;
252 FaultToleranceState_T mEnmFaultToleranceState;
253
254 /* array of progress objects for hard disk reset operations */
255 typedef std::list<ComPtr<IProgress> > ProgressList;
256 ProgressList hardDiskProgresses;
257};
258
259struct VMPowerDownTask : public VMTask
260{
261 VMPowerDownTask(Console *aConsole,
262 const ComPtr<IProgress> &aServerProgress)
263 : VMTask(aConsole, NULL /* aProgress */, aServerProgress,
264 true /* aUsesVMPtr */)
265 {}
266};
267
268struct VMSaveTask : public VMTask
269{
270 VMSaveTask(Console *aConsole,
271 const ComPtr<IProgress> &aServerProgress,
272 const Utf8Str &aSavedStateFile,
273 MachineState_T aMachineStateBefore,
274 Reason_T aReason)
275 : VMTask(aConsole, NULL /* aProgress */, aServerProgress,
276 true /* aUsesVMPtr */),
277 mSavedStateFile(aSavedStateFile),
278 mMachineStateBefore(aMachineStateBefore),
279 mReason(aReason)
280 {}
281
282 Utf8Str mSavedStateFile;
283 /* The local machine state we had before. Required if something fails */
284 MachineState_T mMachineStateBefore;
285 /* The reason for saving state */
286 Reason_T mReason;
287};
288
289// Handler for global events
290////////////////////////////////////////////////////////////////////////////////
291inline static const char *networkAdapterTypeToName(NetworkAdapterType_T adapterType);
292
293class VmEventListener {
294public:
295 VmEventListener()
296 {}
297
298
299 HRESULT init(Console *aConsole)
300 {
301 mConsole = aConsole;
302 return S_OK;
303 }
304
305 void uninit()
306 {
307 }
308
309 virtual ~VmEventListener()
310 {
311 }
312
313 STDMETHOD(HandleEvent)(VBoxEventType_T aType, IEvent * aEvent)
314 {
315 switch(aType)
316 {
317 case VBoxEventType_OnNATRedirect:
318 {
319 Bstr id;
320 ComPtr<IMachine> pMachine = mConsole->i_machine();
321 ComPtr<INATRedirectEvent> pNREv = aEvent;
322 HRESULT rc = E_FAIL;
323 Assert(pNREv);
324
325 Bstr interestedId;
326 rc = pMachine->COMGETTER(Id)(interestedId.asOutParam());
327 AssertComRC(rc);
328 rc = pNREv->COMGETTER(MachineId)(id.asOutParam());
329 AssertComRC(rc);
330 if (id != interestedId)
331 break;
332 /* now we can operate with redirects */
333 NATProtocol_T proto;
334 pNREv->COMGETTER(Proto)(&proto);
335 BOOL fRemove;
336 pNREv->COMGETTER(Remove)(&fRemove);
337 bool fUdp = (proto == NATProtocol_UDP);
338 Bstr hostIp, guestIp;
339 LONG hostPort, guestPort;
340 pNREv->COMGETTER(HostIP)(hostIp.asOutParam());
341 pNREv->COMGETTER(HostPort)(&hostPort);
342 pNREv->COMGETTER(GuestIP)(guestIp.asOutParam());
343 pNREv->COMGETTER(GuestPort)(&guestPort);
344 ULONG ulSlot;
345 rc = pNREv->COMGETTER(Slot)(&ulSlot);
346 AssertComRC(rc);
347 if (FAILED(rc))
348 break;
349 mConsole->i_onNATRedirectRuleChange(ulSlot, fRemove, proto, hostIp.raw(), hostPort, guestIp.raw(), guestPort);
350 }
351 break;
352
353 case VBoxEventType_OnHostNameResolutionConfigurationChange:
354 {
355 mConsole->i_onNATDnsChanged();
356 break;
357 }
358
359 case VBoxEventType_OnHostPCIDevicePlug:
360 {
361 // handle if needed
362 break;
363 }
364
365 case VBoxEventType_OnExtraDataChanged:
366 {
367 ComPtr<IExtraDataChangedEvent> pEDCEv = aEvent;
368 Bstr strMachineId;
369 Bstr strKey;
370 Bstr strVal;
371 HRESULT hrc = S_OK;
372
373 hrc = pEDCEv->COMGETTER(MachineId)(strMachineId.asOutParam());
374 if (FAILED(hrc)) break;
375
376 hrc = pEDCEv->COMGETTER(Key)(strKey.asOutParam());
377 if (FAILED(hrc)) break;
378
379 hrc = pEDCEv->COMGETTER(Value)(strVal.asOutParam());
380 if (FAILED(hrc)) break;
381
382 mConsole->i_onExtraDataChange(strMachineId.raw(), strKey.raw(), strVal.raw());
383 break;
384 }
385
386 default:
387 AssertFailed();
388 }
389 return S_OK;
390 }
391private:
392 ComObjPtr<Console> mConsole;
393};
394
395typedef ListenerImpl<VmEventListener, Console*> VmEventListenerImpl;
396
397
398VBOX_LISTENER_DECLARE(VmEventListenerImpl)
399
400
401// constructor / destructor
402/////////////////////////////////////////////////////////////////////////////
403
404Console::Console()
405 : mSavedStateDataLoaded(false)
406 , mConsoleVRDPServer(NULL)
407 , mfVRDEChangeInProcess(false)
408 , mfVRDEChangePending(false)
409 , mpUVM(NULL)
410 , mVMCallers(0)
411 , mVMZeroCallersSem(NIL_RTSEMEVENT)
412 , mVMDestroying(false)
413 , mVMPoweredOff(false)
414 , mVMIsAlreadyPoweringOff(false)
415 , mfSnapshotFolderSizeWarningShown(false)
416 , mfSnapshotFolderExt4WarningShown(false)
417 , mfSnapshotFolderDiskTypeShown(false)
418 , mfVMHasUsbController(false)
419 , mfPowerOffCausedByReset(false)
420 , mpVmm2UserMethods(NULL)
421 , m_pVMMDev(NULL)
422#ifdef VBOX_WITH_PDM_AUDIO_DRIVER
423 , mAudioVRDE(NULL)
424#else
425 , mAudioSniffer(NULL)
426#endif
427 , mNvram(NULL)
428#ifdef VBOX_WITH_USB_CARDREADER
429 , mUsbCardReader(NULL)
430#endif
431 , mBusMgr(NULL)
432 , mpIfSecKey(NULL)
433 , mpIfSecKeyHlp(NULL)
434 , mVMStateChangeCallbackDisabled(false)
435 , mfUseHostClipboard(true)
436 , mMachineState(MachineState_PoweredOff)
437{
438}
439
440Console::~Console()
441{}
442
443HRESULT Console::FinalConstruct()
444{
445 LogFlowThisFunc(("\n"));
446
447 RT_ZERO(mapStorageLeds);
448 RT_ZERO(mapNetworkLeds);
449 RT_ZERO(mapUSBLed);
450 RT_ZERO(mapSharedFolderLed);
451 RT_ZERO(mapCrOglLed);
452
453 for (unsigned i = 0; i < RT_ELEMENTS(maStorageDevType); ++i)
454 maStorageDevType[i] = DeviceType_Null;
455
456 MYVMM2USERMETHODS *pVmm2UserMethods = (MYVMM2USERMETHODS *)RTMemAllocZ(sizeof(*mpVmm2UserMethods) + sizeof(Console *));
457 if (!pVmm2UserMethods)
458 return E_OUTOFMEMORY;
459 pVmm2UserMethods->u32Magic = VMM2USERMETHODS_MAGIC;
460 pVmm2UserMethods->u32Version = VMM2USERMETHODS_VERSION;
461 pVmm2UserMethods->pfnSaveState = Console::i_vmm2User_SaveState;
462 pVmm2UserMethods->pfnNotifyEmtInit = Console::i_vmm2User_NotifyEmtInit;
463 pVmm2UserMethods->pfnNotifyEmtTerm = Console::i_vmm2User_NotifyEmtTerm;
464 pVmm2UserMethods->pfnNotifyPdmtInit = Console::i_vmm2User_NotifyPdmtInit;
465 pVmm2UserMethods->pfnNotifyPdmtTerm = Console::i_vmm2User_NotifyPdmtTerm;
466 pVmm2UserMethods->pfnNotifyResetTurnedIntoPowerOff = Console::i_vmm2User_NotifyResetTurnedIntoPowerOff;
467 pVmm2UserMethods->u32EndMagic = VMM2USERMETHODS_MAGIC;
468 pVmm2UserMethods->pConsole = this;
469 mpVmm2UserMethods = pVmm2UserMethods;
470
471 MYPDMISECKEY *pIfSecKey = (MYPDMISECKEY *)RTMemAllocZ(sizeof(*mpIfSecKey) + sizeof(Console *));
472 if (!pIfSecKey)
473 return E_OUTOFMEMORY;
474 pIfSecKey->pfnKeyRetain = Console::i_pdmIfSecKey_KeyRetain;
475 pIfSecKey->pfnKeyRelease = Console::i_pdmIfSecKey_KeyRelease;
476 pIfSecKey->pConsole = this;
477 mpIfSecKey = pIfSecKey;
478
479 MYPDMISECKEYHLP *pIfSecKeyHlp = (MYPDMISECKEYHLP *)RTMemAllocZ(sizeof(*mpIfSecKeyHlp) + sizeof(Console *));
480 if (!pIfSecKeyHlp)
481 return E_OUTOFMEMORY;
482 pIfSecKeyHlp->pfnKeyMissingNotify = Console::i_pdmIfSecKeyHlp_KeyMissingNotify;
483 pIfSecKeyHlp->pConsole = this;
484 mpIfSecKeyHlp = pIfSecKeyHlp;
485
486 return BaseFinalConstruct();
487}
488
489void Console::FinalRelease()
490{
491 LogFlowThisFunc(("\n"));
492
493 uninit();
494
495 BaseFinalRelease();
496}
497
498// public initializer/uninitializer for internal purposes only
499/////////////////////////////////////////////////////////////////////////////
500
501HRESULT Console::init(IMachine *aMachine, IInternalMachineControl *aControl, LockType_T aLockType)
502{
503 AssertReturn(aMachine && aControl, E_INVALIDARG);
504
505 /* Enclose the state transition NotReady->InInit->Ready */
506 AutoInitSpan autoInitSpan(this);
507 AssertReturn(autoInitSpan.isOk(), E_FAIL);
508
509 LogFlowThisFuncEnter();
510 LogFlowThisFunc(("aMachine=%p, aControl=%p\n", aMachine, aControl));
511
512 HRESULT rc = E_FAIL;
513
514 unconst(mMachine) = aMachine;
515 unconst(mControl) = aControl;
516
517 /* Cache essential properties and objects, and create child objects */
518
519 rc = mMachine->COMGETTER(State)(&mMachineState);
520 AssertComRCReturnRC(rc);
521
522#ifdef VBOX_WITH_EXTPACK
523 unconst(mptrExtPackManager).createObject();
524 rc = mptrExtPackManager->initExtPackManager(NULL, VBOXEXTPACKCTX_VM_PROCESS);
525 AssertComRCReturnRC(rc);
526#endif
527
528 // Event source may be needed by other children
529 unconst(mEventSource).createObject();
530 rc = mEventSource->init();
531 AssertComRCReturnRC(rc);
532
533 mcAudioRefs = 0;
534 mcVRDPClients = 0;
535 mu32SingleRDPClientId = 0;
536 mcGuestCredentialsProvided = false;
537
538 /* Now the VM specific parts */
539 if (aLockType == LockType_VM)
540 {
541 rc = mMachine->COMGETTER(VRDEServer)(unconst(mVRDEServer).asOutParam());
542 AssertComRCReturnRC(rc);
543
544 unconst(mGuest).createObject();
545 rc = mGuest->init(this);
546 AssertComRCReturnRC(rc);
547
548 unconst(mKeyboard).createObject();
549 rc = mKeyboard->init(this);
550 AssertComRCReturnRC(rc);
551
552 unconst(mMouse).createObject();
553 rc = mMouse->init(this);
554 AssertComRCReturnRC(rc);
555
556 unconst(mDisplay).createObject();
557 rc = mDisplay->init(this);
558 AssertComRCReturnRC(rc);
559
560 unconst(mVRDEServerInfo).createObject();
561 rc = mVRDEServerInfo->init(this);
562 AssertComRCReturnRC(rc);
563
564 unconst(mEmulatedUSB).createObject();
565 rc = mEmulatedUSB->init(this);
566 AssertComRCReturnRC(rc);
567
568 /* Grab global and machine shared folder lists */
569
570 rc = i_fetchSharedFolders(true /* aGlobal */);
571 AssertComRCReturnRC(rc);
572 rc = i_fetchSharedFolders(false /* aGlobal */);
573 AssertComRCReturnRC(rc);
574
575 /* Create other child objects */
576
577 unconst(mConsoleVRDPServer) = new ConsoleVRDPServer(this);
578 AssertReturn(mConsoleVRDPServer, E_FAIL);
579
580 /* Figure out size of meAttachmentType vector */
581 ComPtr<IVirtualBox> pVirtualBox;
582 rc = aMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
583 AssertComRC(rc);
584 ComPtr<ISystemProperties> pSystemProperties;
585 if (pVirtualBox)
586 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
587 ChipsetType_T chipsetType = ChipsetType_PIIX3;
588 aMachine->COMGETTER(ChipsetType)(&chipsetType);
589 ULONG maxNetworkAdapters = 0;
590 if (pSystemProperties)
591 pSystemProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters);
592 meAttachmentType.resize(maxNetworkAdapters);
593 for (ULONG slot = 0; slot < maxNetworkAdapters; ++slot)
594 meAttachmentType[slot] = NetworkAttachmentType_Null;
595
596 // VirtualBox 4.0: We no longer initialize the VMMDev instance here,
597 // which starts the HGCM thread. Instead, this is now done in the
598 // power-up thread when a VM is actually being powered up to avoid
599 // having HGCM threads all over the place every time a session is
600 // opened, even if that session will not run a VM.
601 // unconst(m_pVMMDev) = new VMMDev(this);
602 // AssertReturn(mVMMDev, E_FAIL);
603
604#ifdef VBOX_WITH_PDM_AUDIO_DRIVER
605 unconst(mAudioVRDE) = new AudioVRDE(this);
606 AssertReturn(mAudioVRDE, E_FAIL);
607#else
608 unconst(mAudioSniffer) = new AudioSniffer(this);
609 AssertReturn(mAudioSniffer, E_FAIL);
610#endif
611 FirmwareType_T enmFirmwareType;
612 mMachine->COMGETTER(FirmwareType)(&enmFirmwareType);
613 if ( enmFirmwareType == FirmwareType_EFI
614 || enmFirmwareType == FirmwareType_EFI32
615 || enmFirmwareType == FirmwareType_EFI64
616 || enmFirmwareType == FirmwareType_EFIDUAL)
617 {
618 unconst(mNvram) = new Nvram(this);
619 AssertReturn(mNvram, E_FAIL);
620 }
621
622#ifdef VBOX_WITH_USB_CARDREADER
623 unconst(mUsbCardReader) = new UsbCardReader(this);
624 AssertReturn(mUsbCardReader, E_FAIL);
625#endif
626
627 /* VirtualBox events registration. */
628 {
629 ComPtr<IEventSource> pES;
630 rc = pVirtualBox->COMGETTER(EventSource)(pES.asOutParam());
631 AssertComRC(rc);
632 ComObjPtr<VmEventListenerImpl> aVmListener;
633 aVmListener.createObject();
634 aVmListener->init(new VmEventListener(), this);
635 mVmListener = aVmListener;
636 com::SafeArray<VBoxEventType_T> eventTypes;
637 eventTypes.push_back(VBoxEventType_OnNATRedirect);
638 eventTypes.push_back(VBoxEventType_OnHostNameResolutionConfigurationChange);
639 eventTypes.push_back(VBoxEventType_OnHostPCIDevicePlug);
640 eventTypes.push_back(VBoxEventType_OnExtraDataChanged);
641 rc = pES->RegisterListener(aVmListener, ComSafeArrayAsInParam(eventTypes), true);
642 AssertComRC(rc);
643 }
644 }
645
646 /* Confirm a successful initialization when it's the case */
647 autoInitSpan.setSucceeded();
648
649#ifdef VBOX_WITH_EXTPACK
650 /* Let the extension packs have a go at things (hold no locks). */
651 if (SUCCEEDED(rc))
652 mptrExtPackManager->i_callAllConsoleReadyHooks(this);
653#endif
654
655 LogFlowThisFuncLeave();
656
657 return S_OK;
658}
659
660/**
661 * Uninitializes the Console object.
662 */
663void Console::uninit()
664{
665 LogFlowThisFuncEnter();
666
667 /* Enclose the state transition Ready->InUninit->NotReady */
668 AutoUninitSpan autoUninitSpan(this);
669 if (autoUninitSpan.uninitDone())
670 {
671 LogFlowThisFunc(("Already uninitialized.\n"));
672 LogFlowThisFuncLeave();
673 return;
674 }
675
676 LogFlowThisFunc(("initFailed()=%d\n", autoUninitSpan.initFailed()));
677 if (mVmListener)
678 {
679 ComPtr<IEventSource> pES;
680 ComPtr<IVirtualBox> pVirtualBox;
681 HRESULT rc = mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
682 AssertComRC(rc);
683 if (SUCCEEDED(rc) && !pVirtualBox.isNull())
684 {
685 rc = pVirtualBox->COMGETTER(EventSource)(pES.asOutParam());
686 AssertComRC(rc);
687 if (!pES.isNull())
688 {
689 rc = pES->UnregisterListener(mVmListener);
690 AssertComRC(rc);
691 }
692 }
693 mVmListener.setNull();
694 }
695
696 /* power down the VM if necessary */
697 if (mpUVM)
698 {
699 i_powerDown();
700 Assert(mpUVM == NULL);
701 }
702
703 if (mVMZeroCallersSem != NIL_RTSEMEVENT)
704 {
705 RTSemEventDestroy(mVMZeroCallersSem);
706 mVMZeroCallersSem = NIL_RTSEMEVENT;
707 }
708
709 if (mpVmm2UserMethods)
710 {
711 RTMemFree((void *)mpVmm2UserMethods);
712 mpVmm2UserMethods = NULL;
713 }
714
715 if (mpIfSecKey)
716 {
717 RTMemFree((void *)mpIfSecKey);
718 mpIfSecKey = NULL;
719 }
720
721 if (mpIfSecKeyHlp)
722 {
723 RTMemFree((void *)mpIfSecKeyHlp);
724 mpIfSecKeyHlp = NULL;
725 }
726
727 if (mNvram)
728 {
729 delete mNvram;
730 unconst(mNvram) = NULL;
731 }
732
733#ifdef VBOX_WITH_USB_CARDREADER
734 if (mUsbCardReader)
735 {
736 delete mUsbCardReader;
737 unconst(mUsbCardReader) = NULL;
738 }
739#endif
740
741#ifdef VBOX_WITH_PDM_AUDIO_DRIVER
742 if (mAudioVRDE)
743 {
744 delete mAudioVRDE;
745 unconst(mAudioVRDE) = NULL;
746 }
747#else
748 if (mAudioSniffer)
749 {
750 delete mAudioSniffer;
751 unconst(mAudioSniffer) = NULL;
752 }
753#endif
754
755 // if the VM had a VMMDev with an HGCM thread, then remove that here
756 if (m_pVMMDev)
757 {
758 delete m_pVMMDev;
759 unconst(m_pVMMDev) = NULL;
760 }
761
762 if (mBusMgr)
763 {
764 mBusMgr->Release();
765 mBusMgr = NULL;
766 }
767
768 m_mapGlobalSharedFolders.clear();
769 m_mapMachineSharedFolders.clear();
770 m_mapSharedFolders.clear(); // console instances
771
772 mRemoteUSBDevices.clear();
773 mUSBDevices.clear();
774
775 for (SecretKeyMap::iterator it = m_mapSecretKeys.begin();
776 it != m_mapSecretKeys.end();
777 it++)
778 delete it->second;
779 m_mapSecretKeys.clear();
780
781 if (mVRDEServerInfo)
782 {
783 mVRDEServerInfo->uninit();
784 unconst(mVRDEServerInfo).setNull();
785 }
786
787 if (mEmulatedUSB)
788 {
789 mEmulatedUSB->uninit();
790 unconst(mEmulatedUSB).setNull();
791 }
792
793 if (mDebugger)
794 {
795 mDebugger->uninit();
796 unconst(mDebugger).setNull();
797 }
798
799 if (mDisplay)
800 {
801 mDisplay->uninit();
802 unconst(mDisplay).setNull();
803 }
804
805 if (mMouse)
806 {
807 mMouse->uninit();
808 unconst(mMouse).setNull();
809 }
810
811 if (mKeyboard)
812 {
813 mKeyboard->uninit();
814 unconst(mKeyboard).setNull();
815 }
816
817 if (mGuest)
818 {
819 mGuest->uninit();
820 unconst(mGuest).setNull();
821 }
822
823 if (mConsoleVRDPServer)
824 {
825 delete mConsoleVRDPServer;
826 unconst(mConsoleVRDPServer) = NULL;
827 }
828
829 unconst(mVRDEServer).setNull();
830
831 unconst(mControl).setNull();
832 unconst(mMachine).setNull();
833
834 // we don't perform uninit() as it's possible that some pending event refers to this source
835 unconst(mEventSource).setNull();
836
837 LogFlowThisFuncLeave();
838}
839
840#ifdef VBOX_WITH_GUEST_PROPS
841
842/**
843 * Handles guest properties on a VM reset.
844 *
845 * We must delete properties that are flagged TRANSRESET.
846 *
847 * @todo r=bird: Would be more efficient if we added a request to the HGCM
848 * service to do this instead of detouring thru VBoxSVC.
849 * (IMachine::SetGuestProperty ends up in VBoxSVC, which in turns calls
850 * back into the VM process and the HGCM service.)
851 */
852void Console::i_guestPropertiesHandleVMReset(void)
853{
854 std::vector<Utf8Str> names;
855 std::vector<Utf8Str> values;
856 std::vector<LONG64> timestamps;
857 std::vector<Utf8Str> flags;
858 HRESULT hrc = i_enumerateGuestProperties("*", names, values, timestamps, flags);
859 if (SUCCEEDED(hrc))
860 {
861 for (size_t i = 0; i < flags.size(); i++)
862 {
863 /* Delete all properties which have the flag "TRANSRESET". */
864 if (flags[i].contains("TRANSRESET", Utf8Str::CaseInsensitive))
865 {
866 hrc = mMachine->DeleteGuestProperty(Bstr(names[i]).raw());
867 if (FAILED(hrc))
868 LogRel(("RESET: Could not delete transient property \"%s\", rc=%Rhrc\n",
869 names[i].c_str(), hrc));
870 }
871 }
872 }
873 else
874 LogRel(("RESET: Unable to enumerate guest properties, rc=%Rhrc\n", hrc));
875}
876
877bool Console::i_guestPropertiesVRDPEnabled(void)
878{
879 Bstr value;
880 HRESULT hrc = mMachine->GetExtraData(Bstr("VBoxInternal2/EnableGuestPropertiesVRDP").raw(),
881 value.asOutParam());
882 if ( hrc == S_OK
883 && value == "1")
884 return true;
885 return false;
886}
887
888void Console::i_guestPropertiesVRDPUpdateLogon(uint32_t u32ClientId, const char *pszUser, const char *pszDomain)
889{
890 if (!i_guestPropertiesVRDPEnabled())
891 return;
892
893 LogFlowFunc(("\n"));
894
895 char szPropNm[256];
896 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
897
898 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Name", u32ClientId);
899 Bstr clientName;
900 mVRDEServerInfo->COMGETTER(ClientName)(clientName.asOutParam());
901
902 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
903 clientName.raw(),
904 bstrReadOnlyGuest.raw());
905
906 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/User", u32ClientId);
907 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
908 Bstr(pszUser).raw(),
909 bstrReadOnlyGuest.raw());
910
911 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Domain", u32ClientId);
912 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
913 Bstr(pszDomain).raw(),
914 bstrReadOnlyGuest.raw());
915
916 char szClientId[64];
917 RTStrPrintf(szClientId, sizeof(szClientId), "%u", u32ClientId);
918 mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VRDP/LastConnectedClient").raw(),
919 Bstr(szClientId).raw(),
920 bstrReadOnlyGuest.raw());
921
922 return;
923}
924
925void Console::i_guestPropertiesVRDPUpdateActiveClient(uint32_t u32ClientId)
926{
927 if (!i_guestPropertiesVRDPEnabled())
928 return;
929
930 LogFlowFunc(("%d\n", u32ClientId));
931
932 Bstr bstrFlags(L"RDONLYGUEST,TRANSIENT");
933
934 char szClientId[64];
935 RTStrPrintf(szClientId, sizeof(szClientId), "%u", u32ClientId);
936
937 mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VRDP/ActiveClient").raw(),
938 Bstr(szClientId).raw(),
939 bstrFlags.raw());
940
941 return;
942}
943
944void Console::i_guestPropertiesVRDPUpdateNameChange(uint32_t u32ClientId, const char *pszName)
945{
946 if (!i_guestPropertiesVRDPEnabled())
947 return;
948
949 LogFlowFunc(("\n"));
950
951 char szPropNm[256];
952 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
953
954 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Name", u32ClientId);
955 Bstr clientName(pszName);
956
957 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
958 clientName.raw(),
959 bstrReadOnlyGuest.raw());
960
961}
962
963void Console::i_guestPropertiesVRDPUpdateIPAddrChange(uint32_t u32ClientId, const char *pszIPAddr)
964{
965 if (!i_guestPropertiesVRDPEnabled())
966 return;
967
968 LogFlowFunc(("\n"));
969
970 char szPropNm[256];
971 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
972
973 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/IPAddr", u32ClientId);
974 Bstr clientIPAddr(pszIPAddr);
975
976 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
977 clientIPAddr.raw(),
978 bstrReadOnlyGuest.raw());
979
980}
981
982void Console::i_guestPropertiesVRDPUpdateLocationChange(uint32_t u32ClientId, const char *pszLocation)
983{
984 if (!i_guestPropertiesVRDPEnabled())
985 return;
986
987 LogFlowFunc(("\n"));
988
989 char szPropNm[256];
990 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
991
992 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Location", u32ClientId);
993 Bstr clientLocation(pszLocation);
994
995 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
996 clientLocation.raw(),
997 bstrReadOnlyGuest.raw());
998
999}
1000
1001void Console::i_guestPropertiesVRDPUpdateOtherInfoChange(uint32_t u32ClientId, const char *pszOtherInfo)
1002{
1003 if (!i_guestPropertiesVRDPEnabled())
1004 return;
1005
1006 LogFlowFunc(("\n"));
1007
1008 char szPropNm[256];
1009 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
1010
1011 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/OtherInfo", u32ClientId);
1012 Bstr clientOtherInfo(pszOtherInfo);
1013
1014 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
1015 clientOtherInfo.raw(),
1016 bstrReadOnlyGuest.raw());
1017
1018}
1019
1020void Console::i_guestPropertiesVRDPUpdateClientAttach(uint32_t u32ClientId, bool fAttached)
1021{
1022 if (!i_guestPropertiesVRDPEnabled())
1023 return;
1024
1025 LogFlowFunc(("\n"));
1026
1027 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
1028
1029 char szPropNm[256];
1030 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Attach", u32ClientId);
1031
1032 Bstr bstrValue = fAttached? "1": "0";
1033
1034 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
1035 bstrValue.raw(),
1036 bstrReadOnlyGuest.raw());
1037}
1038
1039void Console::i_guestPropertiesVRDPUpdateDisconnect(uint32_t u32ClientId)
1040{
1041 if (!i_guestPropertiesVRDPEnabled())
1042 return;
1043
1044 LogFlowFunc(("\n"));
1045
1046 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
1047
1048 char szPropNm[256];
1049 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Name", u32ClientId);
1050 mMachine->SetGuestProperty(Bstr(szPropNm).raw(), NULL,
1051 bstrReadOnlyGuest.raw());
1052
1053 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/User", u32ClientId);
1054 mMachine->SetGuestProperty(Bstr(szPropNm).raw(), NULL,
1055 bstrReadOnlyGuest.raw());
1056
1057 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Domain", u32ClientId);
1058 mMachine->SetGuestProperty(Bstr(szPropNm).raw(), NULL,
1059 bstrReadOnlyGuest.raw());
1060
1061 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Attach", u32ClientId);
1062 mMachine->SetGuestProperty(Bstr(szPropNm).raw(), NULL,
1063 bstrReadOnlyGuest.raw());
1064
1065 char szClientId[64];
1066 RTStrPrintf(szClientId, sizeof(szClientId), "%d", u32ClientId);
1067 mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VRDP/LastDisconnectedClient").raw(),
1068 Bstr(szClientId).raw(),
1069 bstrReadOnlyGuest.raw());
1070
1071 return;
1072}
1073
1074#endif /* VBOX_WITH_GUEST_PROPS */
1075
1076bool Console::i_isResetTurnedIntoPowerOff(void)
1077{
1078 Bstr value;
1079 HRESULT hrc = mMachine->GetExtraData(Bstr("VBoxInternal2/TurnResetIntoPowerOff").raw(),
1080 value.asOutParam());
1081 if ( hrc == S_OK
1082 && value == "1")
1083 return true;
1084 return false;
1085}
1086
1087#ifdef VBOX_WITH_EXTPACK
1088/**
1089 * Used by VRDEServer and others to talke to the extension pack manager.
1090 *
1091 * @returns The extension pack manager.
1092 */
1093ExtPackManager *Console::i_getExtPackManager()
1094{
1095 return mptrExtPackManager;
1096}
1097#endif
1098
1099
1100int Console::i_VRDPClientLogon(uint32_t u32ClientId, const char *pszUser, const char *pszPassword, const char *pszDomain)
1101{
1102 LogFlowFuncEnter();
1103 LogFlowFunc(("%d, %s, %s, %s\n", u32ClientId, pszUser, pszPassword, pszDomain));
1104
1105 AutoCaller autoCaller(this);
1106 if (!autoCaller.isOk())
1107 {
1108 /* Console has been already uninitialized, deny request */
1109 LogRel(("AUTH: Access denied (Console uninitialized).\n"));
1110 LogFlowFuncLeave();
1111 return VERR_ACCESS_DENIED;
1112 }
1113
1114 Bstr id;
1115 HRESULT hrc = mMachine->COMGETTER(Id)(id.asOutParam());
1116 Guid uuid = Guid(id);
1117
1118 AssertComRCReturn(hrc, VERR_ACCESS_DENIED);
1119
1120 AuthType_T authType = AuthType_Null;
1121 hrc = mVRDEServer->COMGETTER(AuthType)(&authType);
1122 AssertComRCReturn(hrc, VERR_ACCESS_DENIED);
1123
1124 ULONG authTimeout = 0;
1125 hrc = mVRDEServer->COMGETTER(AuthTimeout)(&authTimeout);
1126 AssertComRCReturn(hrc, VERR_ACCESS_DENIED);
1127
1128 AuthResult result = AuthResultAccessDenied;
1129 AuthGuestJudgement guestJudgement = AuthGuestNotAsked;
1130
1131 LogFlowFunc(("Auth type %d\n", authType));
1132
1133 LogRel(("AUTH: User: [%s]. Domain: [%s]. Authentication type: [%s]\n",
1134 pszUser, pszDomain,
1135 authType == AuthType_Null?
1136 "Null":
1137 (authType == AuthType_External?
1138 "External":
1139 (authType == AuthType_Guest?
1140 "Guest":
1141 "INVALID"
1142 )
1143 )
1144 ));
1145
1146 switch (authType)
1147 {
1148 case AuthType_Null:
1149 {
1150 result = AuthResultAccessGranted;
1151 break;
1152 }
1153
1154 case AuthType_External:
1155 {
1156 /* Call the external library. */
1157 result = mConsoleVRDPServer->Authenticate(uuid, guestJudgement, pszUser, pszPassword, pszDomain, u32ClientId);
1158
1159 if (result != AuthResultDelegateToGuest)
1160 {
1161 break;
1162 }
1163
1164 LogRel(("AUTH: Delegated to guest.\n"));
1165
1166 LogFlowFunc(("External auth asked for guest judgement\n"));
1167 } /* pass through */
1168
1169 case AuthType_Guest:
1170 {
1171 guestJudgement = AuthGuestNotReacted;
1172
1173 // @todo r=dj locking required here for m_pVMMDev?
1174 PPDMIVMMDEVPORT pDevPort;
1175 if ( (m_pVMMDev)
1176 && ((pDevPort = m_pVMMDev->getVMMDevPort()))
1177 )
1178 {
1179 /* Issue the request to guest. Assume that the call does not require EMT. It should not. */
1180
1181 /* Ask the guest to judge these credentials. */
1182 uint32_t u32GuestFlags = VMMDEV_SETCREDENTIALS_JUDGE;
1183
1184 int rc = pDevPort->pfnSetCredentials(pDevPort, pszUser, pszPassword, pszDomain, u32GuestFlags);
1185
1186 if (RT_SUCCESS(rc))
1187 {
1188 /* Wait for guest. */
1189 rc = m_pVMMDev->WaitCredentialsJudgement(authTimeout, &u32GuestFlags);
1190
1191 if (RT_SUCCESS(rc))
1192 {
1193 switch (u32GuestFlags & (VMMDEV_CREDENTIALS_JUDGE_OK | VMMDEV_CREDENTIALS_JUDGE_DENY |
1194 VMMDEV_CREDENTIALS_JUDGE_NOJUDGEMENT))
1195 {
1196 case VMMDEV_CREDENTIALS_JUDGE_DENY: guestJudgement = AuthGuestAccessDenied; break;
1197 case VMMDEV_CREDENTIALS_JUDGE_NOJUDGEMENT: guestJudgement = AuthGuestNoJudgement; break;
1198 case VMMDEV_CREDENTIALS_JUDGE_OK: guestJudgement = AuthGuestAccessGranted; break;
1199 default:
1200 LogFlowFunc(("Invalid guest flags %08X!!!\n", u32GuestFlags)); break;
1201 }
1202 }
1203 else
1204 {
1205 LogFlowFunc(("Wait for credentials judgement rc = %Rrc!!!\n", rc));
1206 }
1207
1208 LogFlowFunc(("Guest judgement %d\n", guestJudgement));
1209 }
1210 else
1211 {
1212 LogFlowFunc(("Could not set credentials rc = %Rrc!!!\n", rc));
1213 }
1214 }
1215
1216 if (authType == AuthType_External)
1217 {
1218 LogRel(("AUTH: Guest judgement %d.\n", guestJudgement));
1219 LogFlowFunc(("External auth called again with guest judgement = %d\n", guestJudgement));
1220 result = mConsoleVRDPServer->Authenticate(uuid, guestJudgement, pszUser, pszPassword, pszDomain, u32ClientId);
1221 }
1222 else
1223 {
1224 switch (guestJudgement)
1225 {
1226 case AuthGuestAccessGranted:
1227 result = AuthResultAccessGranted;
1228 break;
1229 default:
1230 result = AuthResultAccessDenied;
1231 break;
1232 }
1233 }
1234 } break;
1235
1236 default:
1237 AssertFailed();
1238 }
1239
1240 LogFlowFunc(("Result = %d\n", result));
1241 LogFlowFuncLeave();
1242
1243 if (result != AuthResultAccessGranted)
1244 {
1245 /* Reject. */
1246 LogRel(("AUTH: Access denied.\n"));
1247 return VERR_ACCESS_DENIED;
1248 }
1249
1250 LogRel(("AUTH: Access granted.\n"));
1251
1252 /* Multiconnection check must be made after authentication, so bad clients would not interfere with a good one. */
1253 BOOL allowMultiConnection = FALSE;
1254 hrc = mVRDEServer->COMGETTER(AllowMultiConnection)(&allowMultiConnection);
1255 AssertComRCReturn(hrc, VERR_ACCESS_DENIED);
1256
1257 BOOL reuseSingleConnection = FALSE;
1258 hrc = mVRDEServer->COMGETTER(ReuseSingleConnection)(&reuseSingleConnection);
1259 AssertComRCReturn(hrc, VERR_ACCESS_DENIED);
1260
1261 LogFlowFunc(("allowMultiConnection %d, reuseSingleConnection = %d, mcVRDPClients = %d, mu32SingleRDPClientId = %d\n",
1262 allowMultiConnection, reuseSingleConnection, mcVRDPClients, mu32SingleRDPClientId));
1263
1264 if (allowMultiConnection == FALSE)
1265 {
1266 /* Note: the 'mcVRDPClients' variable is incremented in ClientConnect callback, which is called when the client
1267 * is successfully connected, that is after the ClientLogon callback. Therefore the mcVRDPClients
1268 * value is 0 for first client.
1269 */
1270 if (mcVRDPClients != 0)
1271 {
1272 Assert(mcVRDPClients == 1);
1273 /* There is a client already.
1274 * If required drop the existing client connection and let the connecting one in.
1275 */
1276 if (reuseSingleConnection)
1277 {
1278 LogRel(("AUTH: Multiple connections are not enabled. Disconnecting existing client.\n"));
1279 mConsoleVRDPServer->DisconnectClient(mu32SingleRDPClientId, false);
1280 }
1281 else
1282 {
1283 /* Reject. */
1284 LogRel(("AUTH: Multiple connections are not enabled. Access denied.\n"));
1285 return VERR_ACCESS_DENIED;
1286 }
1287 }
1288
1289 /* Save the connected client id. From now on it will be necessary to disconnect this one. */
1290 mu32SingleRDPClientId = u32ClientId;
1291 }
1292
1293#ifdef VBOX_WITH_GUEST_PROPS
1294 i_guestPropertiesVRDPUpdateLogon(u32ClientId, pszUser, pszDomain);
1295#endif /* VBOX_WITH_GUEST_PROPS */
1296
1297 /* Check if the successfully verified credentials are to be sent to the guest. */
1298 BOOL fProvideGuestCredentials = FALSE;
1299
1300 Bstr value;
1301 hrc = mMachine->GetExtraData(Bstr("VRDP/ProvideGuestCredentials").raw(),
1302 value.asOutParam());
1303 if (SUCCEEDED(hrc) && value == "1")
1304 {
1305 /* Provide credentials only if there are no logged in users. */
1306 Utf8Str noLoggedInUsersValue;
1307 LONG64 ul64Timestamp = 0;
1308 Utf8Str flags;
1309
1310 hrc = i_getGuestProperty("/VirtualBox/GuestInfo/OS/NoLoggedInUsers",
1311 &noLoggedInUsersValue, &ul64Timestamp, &flags);
1312
1313 if (SUCCEEDED(hrc) && noLoggedInUsersValue != "false")
1314 {
1315 /* And only if there are no connected clients. */
1316 if (ASMAtomicCmpXchgBool(&mcGuestCredentialsProvided, true, false))
1317 {
1318 fProvideGuestCredentials = TRUE;
1319 }
1320 }
1321 }
1322
1323 // @todo r=dj locking required here for m_pVMMDev?
1324 if ( fProvideGuestCredentials
1325 && m_pVMMDev)
1326 {
1327 uint32_t u32GuestFlags = VMMDEV_SETCREDENTIALS_GUESTLOGON;
1328
1329 PPDMIVMMDEVPORT pDevPort = m_pVMMDev->getVMMDevPort();
1330 if (pDevPort)
1331 {
1332 int rc = pDevPort->pfnSetCredentials(m_pVMMDev->getVMMDevPort(),
1333 pszUser, pszPassword, pszDomain, u32GuestFlags);
1334 AssertRC(rc);
1335 }
1336 }
1337
1338 return VINF_SUCCESS;
1339}
1340
1341void Console::i_VRDPClientStatusChange(uint32_t u32ClientId, const char *pszStatus)
1342{
1343 LogFlowFuncEnter();
1344
1345 AutoCaller autoCaller(this);
1346 AssertComRCReturnVoid(autoCaller.rc());
1347
1348 LogFlowFunc(("%s\n", pszStatus));
1349
1350#ifdef VBOX_WITH_GUEST_PROPS
1351 /* Parse the status string. */
1352 if (RTStrICmp(pszStatus, "ATTACH") == 0)
1353 {
1354 i_guestPropertiesVRDPUpdateClientAttach(u32ClientId, true);
1355 }
1356 else if (RTStrICmp(pszStatus, "DETACH") == 0)
1357 {
1358 i_guestPropertiesVRDPUpdateClientAttach(u32ClientId, false);
1359 }
1360 else if (RTStrNICmp(pszStatus, "NAME=", strlen("NAME=")) == 0)
1361 {
1362 i_guestPropertiesVRDPUpdateNameChange(u32ClientId, pszStatus + strlen("NAME="));
1363 }
1364 else if (RTStrNICmp(pszStatus, "CIPA=", strlen("CIPA=")) == 0)
1365 {
1366 i_guestPropertiesVRDPUpdateIPAddrChange(u32ClientId, pszStatus + strlen("CIPA="));
1367 }
1368 else if (RTStrNICmp(pszStatus, "CLOCATION=", strlen("CLOCATION=")) == 0)
1369 {
1370 i_guestPropertiesVRDPUpdateLocationChange(u32ClientId, pszStatus + strlen("CLOCATION="));
1371 }
1372 else if (RTStrNICmp(pszStatus, "COINFO=", strlen("COINFO=")) == 0)
1373 {
1374 i_guestPropertiesVRDPUpdateOtherInfoChange(u32ClientId, pszStatus + strlen("COINFO="));
1375 }
1376#endif
1377
1378 LogFlowFuncLeave();
1379}
1380
1381void Console::i_VRDPClientConnect(uint32_t u32ClientId)
1382{
1383 LogFlowFuncEnter();
1384
1385 AutoCaller autoCaller(this);
1386 AssertComRCReturnVoid(autoCaller.rc());
1387
1388 uint32_t u32Clients = ASMAtomicIncU32(&mcVRDPClients);
1389 VMMDev *pDev;
1390 PPDMIVMMDEVPORT pPort;
1391 if ( (u32Clients == 1)
1392 && ((pDev = i_getVMMDev()))
1393 && ((pPort = pDev->getVMMDevPort()))
1394 )
1395 {
1396 pPort->pfnVRDPChange(pPort,
1397 true,
1398 VRDP_EXPERIENCE_LEVEL_FULL); // @todo configurable
1399 }
1400
1401 NOREF(u32ClientId);
1402 mDisplay->i_VideoAccelVRDP(true);
1403
1404#ifdef VBOX_WITH_GUEST_PROPS
1405 i_guestPropertiesVRDPUpdateActiveClient(u32ClientId);
1406#endif /* VBOX_WITH_GUEST_PROPS */
1407
1408 LogFlowFuncLeave();
1409 return;
1410}
1411
1412void Console::i_VRDPClientDisconnect(uint32_t u32ClientId,
1413 uint32_t fu32Intercepted)
1414{
1415 LogFlowFuncEnter();
1416
1417 AutoCaller autoCaller(this);
1418 AssertComRCReturnVoid(autoCaller.rc());
1419
1420 AssertReturnVoid(mConsoleVRDPServer);
1421
1422 uint32_t u32Clients = ASMAtomicDecU32(&mcVRDPClients);
1423 VMMDev *pDev;
1424 PPDMIVMMDEVPORT pPort;
1425
1426 if ( (u32Clients == 0)
1427 && ((pDev = i_getVMMDev()))
1428 && ((pPort = pDev->getVMMDevPort()))
1429 )
1430 {
1431 pPort->pfnVRDPChange(pPort,
1432 false,
1433 0);
1434 }
1435
1436 mDisplay->i_VideoAccelVRDP(false);
1437
1438 if (fu32Intercepted & VRDE_CLIENT_INTERCEPT_USB)
1439 {
1440 mConsoleVRDPServer->USBBackendDelete(u32ClientId);
1441 }
1442
1443 if (fu32Intercepted & VRDE_CLIENT_INTERCEPT_CLIPBOARD)
1444 {
1445 mConsoleVRDPServer->ClipboardDelete(u32ClientId);
1446 }
1447
1448 if (fu32Intercepted & VRDE_CLIENT_INTERCEPT_AUDIO)
1449 {
1450#ifdef VBOX_WITH_PDM_AUDIO_DRIVER
1451 if (mAudioVRDE)
1452 mAudioVRDE->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 ComPtr<IVirtualBox> pVirtualBox;
4319 hrc = mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
4320 if (FAILED(hrc))
4321 return S_OK;
4322
4323 ComPtr<IHost> pHost;
4324 hrc = pVirtualBox->COMGETTER(Host)(pHost.asOutParam());
4325 if (FAILED(hrc))
4326 return S_OK;
4327
4328 SafeArray<BSTR> aNameServers;
4329 hrc = pHost->COMGETTER(NameServers)(ComSafeArrayAsOutParam(aNameServers));
4330 if (FAILED(hrc))
4331 return S_OK;
4332
4333 const size_t cNameServers = aNameServers.size();
4334 Log(("DNS change - %zu nameservers\n", cNameServers));
4335
4336 for (size_t i = 0; i < cNameServers; ++i)
4337 {
4338 com::Utf8Str strNameServer(aNameServers[i]);
4339 Log(("- nameserver[%zu] = \"%s\"\n", i, strNameServer.c_str()));
4340 }
4341
4342 com::Bstr domain;
4343 pHost->COMGETTER(DomainName)(domain.asOutParam());
4344 Log(("domain name = \"%s\"\n", com::Utf8Str(domain).c_str()));
4345
4346
4347 ChipsetType_T enmChipsetType;
4348 hrc = mMachine->COMGETTER(ChipsetType)(&enmChipsetType);
4349 if (!FAILED(hrc))
4350 {
4351 SafeVMPtrQuiet ptrVM(this);
4352 if (ptrVM.isOk())
4353 {
4354 ULONG ulInstanceMax = (ULONG)Global::getMaxNetworkAdapters(enmChipsetType);
4355
4356 notifyNatDnsChange(ptrVM.rawUVM(), "pcnet", ulInstanceMax);
4357 notifyNatDnsChange(ptrVM.rawUVM(), "e1000", ulInstanceMax);
4358 notifyNatDnsChange(ptrVM.rawUVM(), "virtio-net", ulInstanceMax);
4359 }
4360 }
4361
4362 return S_OK;
4363}
4364
4365
4366/*
4367 * This routine walks over all network device instances, checking if
4368 * device instance has DrvNAT attachment and triggering DrvNAT DNS
4369 * change callback.
4370 */
4371void Console::notifyNatDnsChange(PUVM pUVM, const char *pszDevice, ULONG ulInstanceMax)
4372{
4373 Log(("notifyNatDnsChange: looking for DrvNAT attachment on %s device instances\n", pszDevice));
4374 for (ULONG ulInstance = 0; ulInstance < ulInstanceMax; ulInstance++)
4375 {
4376 PPDMIBASE pBase;
4377 int rc = PDMR3QueryDriverOnLun(pUVM, pszDevice, ulInstance, 0 /* iLun */, "NAT", &pBase);
4378 if (RT_FAILURE(rc))
4379 continue;
4380
4381 Log(("Instance %s#%d has DrvNAT attachment; do actual notify\n", pszDevice, ulInstance));
4382 if (pBase)
4383 {
4384 PPDMINETWORKNATCONFIG pNetNatCfg = NULL;
4385 pNetNatCfg = (PPDMINETWORKNATCONFIG)pBase->pfnQueryInterface(pBase, PDMINETWORKNATCONFIG_IID);
4386 if (pNetNatCfg && pNetNatCfg->pfnNotifyDnsChanged)
4387 pNetNatCfg->pfnNotifyDnsChanged(pNetNatCfg);
4388 }
4389 }
4390}
4391
4392
4393VMMDevMouseInterface *Console::i_getVMMDevMouseInterface()
4394{
4395 return m_pVMMDev;
4396}
4397
4398DisplayMouseInterface *Console::i_getDisplayMouseInterface()
4399{
4400 return mDisplay;
4401}
4402
4403/**
4404 * Parses one key value pair.
4405 *
4406 * @returns VBox status code.
4407 * @param psz Configuration string.
4408 * @param ppszEnd Where to store the pointer to the string following the key value pair.
4409 * @param ppszKey Where to store the key on success.
4410 * @param ppszVal Where to store the value on success.
4411 */
4412int Console::i_consoleParseKeyValue(const char *psz, const char **ppszEnd,
4413 char **ppszKey, char **ppszVal)
4414{
4415 int rc = VINF_SUCCESS;
4416 const char *pszKeyStart = psz;
4417 const char *pszValStart = NULL;
4418 size_t cchKey = 0;
4419 size_t cchVal = 0;
4420
4421 while ( *psz != '='
4422 && *psz)
4423 psz++;
4424
4425 /* End of string at this point is invalid. */
4426 if (*psz == '\0')
4427 return VERR_INVALID_PARAMETER;
4428
4429 cchKey = psz - pszKeyStart;
4430 psz++; /* Skip = character */
4431 pszValStart = psz;
4432
4433 while ( *psz != ','
4434 && *psz != '\n'
4435 && *psz != '\r'
4436 && *psz)
4437 psz++;
4438
4439 cchVal = psz - pszValStart;
4440
4441 if (cchKey && cchVal)
4442 {
4443 *ppszKey = RTStrDupN(pszKeyStart, cchKey);
4444 if (*ppszKey)
4445 {
4446 *ppszVal = RTStrDupN(pszValStart, cchVal);
4447 if (!*ppszVal)
4448 {
4449 RTStrFree(*ppszKey);
4450 rc = VERR_NO_MEMORY;
4451 }
4452 }
4453 else
4454 rc = VERR_NO_MEMORY;
4455 }
4456 else
4457 rc = VERR_INVALID_PARAMETER;
4458
4459 if (RT_SUCCESS(rc))
4460 *ppszEnd = psz;
4461
4462 return rc;
4463}
4464
4465/**
4466 * Removes the key interfaces from all disk attachments, useful when
4467 * changing the key store or dropping it.
4468 */
4469HRESULT Console::i_clearDiskEncryptionKeysOnAllAttachments(void)
4470{
4471 HRESULT hrc = S_OK;
4472 SafeIfaceArray<IMediumAttachment> sfaAttachments;
4473
4474 AutoCaller autoCaller(this);
4475 AssertComRCReturnRC(autoCaller.rc());
4476
4477 /* Get the VM - must be done before the read-locking. */
4478 SafeVMPtr ptrVM(this);
4479 if (!ptrVM.isOk())
4480 return ptrVM.rc();
4481
4482 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4483
4484 hrc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(sfaAttachments));
4485 AssertComRCReturnRC(hrc);
4486
4487 /* Find the correct attachment. */
4488 for (unsigned i = 0; i < sfaAttachments.size(); i++)
4489 {
4490 const ComPtr<IMediumAttachment> &pAtt = sfaAttachments[i];
4491
4492 /*
4493 * Query storage controller, port and device
4494 * to identify the correct driver.
4495 */
4496 ComPtr<IStorageController> pStorageCtrl;
4497 Bstr storageCtrlName;
4498 LONG lPort, lDev;
4499 ULONG ulStorageCtrlInst;
4500
4501 hrc = pAtt->COMGETTER(Controller)(storageCtrlName.asOutParam());
4502 AssertComRC(hrc);
4503
4504 hrc = pAtt->COMGETTER(Port)(&lPort);
4505 AssertComRC(hrc);
4506
4507 hrc = pAtt->COMGETTER(Device)(&lDev);
4508 AssertComRC(hrc);
4509
4510 hrc = mMachine->GetStorageControllerByName(storageCtrlName.raw(), pStorageCtrl.asOutParam());
4511 AssertComRC(hrc);
4512
4513 hrc = pStorageCtrl->COMGETTER(Instance)(&ulStorageCtrlInst);
4514 AssertComRC(hrc);
4515
4516 StorageControllerType_T enmCtrlType;
4517 hrc = pStorageCtrl->COMGETTER(ControllerType)(&enmCtrlType);
4518 AssertComRC(hrc);
4519 const char *pcszDevice = i_convertControllerTypeToDev(enmCtrlType);
4520
4521 StorageBus_T enmBus;
4522 hrc = pStorageCtrl->COMGETTER(Bus)(&enmBus);
4523 AssertComRC(hrc);
4524
4525 unsigned uLUN;
4526 hrc = Console::i_convertBusPortDeviceToLun(enmBus, lPort, lDev, uLUN);
4527 AssertComRC(hrc);
4528
4529 PPDMIBASE pIBase = NULL;
4530 PPDMIMEDIA pIMedium = NULL;
4531 int rc = PDMR3QueryDriverOnLun(ptrVM.rawUVM(), pcszDevice, ulStorageCtrlInst, uLUN, "VD", &pIBase);
4532 if (RT_SUCCESS(rc))
4533 {
4534 if (pIBase)
4535 {
4536 pIMedium = (PPDMIMEDIA)pIBase->pfnQueryInterface(pIBase, PDMIMEDIA_IID);
4537 if (pIMedium)
4538 {
4539 rc = pIMedium->pfnSetSecKeyIf(pIMedium, NULL, mpIfSecKeyHlp);
4540 Assert(RT_SUCCESS(rc) || rc == VERR_NOT_SUPPORTED);
4541 }
4542 }
4543 }
4544 }
4545
4546 return hrc;
4547}
4548
4549/**
4550 * Configures the encryption support for the disk identified by the gien UUID with
4551 * the given key.
4552 *
4553 * @returns COM status code.
4554 * @param pszUuid The UUID of the disk to configure encryption for.
4555 */
4556HRESULT Console::i_configureEncryptionForDisk(const char *pszUuid)
4557{
4558 HRESULT hrc = S_OK;
4559 SafeIfaceArray<IMediumAttachment> sfaAttachments;
4560
4561 AutoCaller autoCaller(this);
4562 AssertComRCReturnRC(autoCaller.rc());
4563
4564 /* Get the VM - must be done before the read-locking. */
4565 SafeVMPtr ptrVM(this);
4566 if (!ptrVM.isOk())
4567 return ptrVM.rc();
4568
4569 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4570
4571 hrc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(sfaAttachments));
4572 if (FAILED(hrc))
4573 return hrc;
4574
4575 /* Find the correct attachment. */
4576 for (unsigned i = 0; i < sfaAttachments.size(); i++)
4577 {
4578 const ComPtr<IMediumAttachment> &pAtt = sfaAttachments[i];
4579 ComPtr<IMedium> pMedium;
4580 ComPtr<IMedium> pBase;
4581 Bstr uuid;
4582
4583 hrc = pAtt->COMGETTER(Medium)(pMedium.asOutParam());
4584 if (FAILED(hrc))
4585 break;
4586
4587 /* Skip non hard disk attachments. */
4588 if (pMedium.isNull())
4589 continue;
4590
4591 /* Get the UUID of the base medium and compare. */
4592 hrc = pMedium->COMGETTER(Base)(pBase.asOutParam());
4593 if (FAILED(hrc))
4594 break;
4595
4596 hrc = pBase->COMGETTER(Id)(uuid.asOutParam());
4597 if (FAILED(hrc))
4598 break;
4599
4600 if (!RTUuidCompare2Strs(Utf8Str(uuid).c_str(), pszUuid))
4601 {
4602 /*
4603 * Found the matching medium, query storage controller, port and device
4604 * to identify the correct driver.
4605 */
4606 ComPtr<IStorageController> pStorageCtrl;
4607 Bstr storageCtrlName;
4608 LONG lPort, lDev;
4609 ULONG ulStorageCtrlInst;
4610
4611 hrc = pAtt->COMGETTER(Controller)(storageCtrlName.asOutParam());
4612 if (FAILED(hrc))
4613 break;
4614
4615 hrc = pAtt->COMGETTER(Port)(&lPort);
4616 if (FAILED(hrc))
4617 break;
4618
4619 hrc = pAtt->COMGETTER(Device)(&lDev);
4620 if (FAILED(hrc))
4621 break;
4622
4623 hrc = mMachine->GetStorageControllerByName(storageCtrlName.raw(), pStorageCtrl.asOutParam());
4624 if (FAILED(hrc))
4625 break;
4626
4627 hrc = pStorageCtrl->COMGETTER(Instance)(&ulStorageCtrlInst);
4628 if (FAILED(hrc))
4629 break;
4630
4631 StorageControllerType_T enmCtrlType;
4632 hrc = pStorageCtrl->COMGETTER(ControllerType)(&enmCtrlType);
4633 AssertComRC(hrc);
4634 const char *pcszDevice = i_convertControllerTypeToDev(enmCtrlType);
4635
4636 StorageBus_T enmBus;
4637 hrc = pStorageCtrl->COMGETTER(Bus)(&enmBus);
4638 AssertComRC(hrc);
4639
4640 unsigned uLUN;
4641 hrc = Console::i_convertBusPortDeviceToLun(enmBus, lPort, lDev, uLUN);
4642 AssertComRCReturnRC(hrc);
4643
4644 PPDMIBASE pIBase = NULL;
4645 PPDMIMEDIA pIMedium = NULL;
4646 int rc = PDMR3QueryDriverOnLun(ptrVM.rawUVM(), pcszDevice, ulStorageCtrlInst, uLUN, "VD", &pIBase);
4647 if (RT_SUCCESS(rc))
4648 {
4649 if (pIBase)
4650 {
4651 pIMedium = (PPDMIMEDIA)pIBase->pfnQueryInterface(pIBase, PDMIMEDIA_IID);
4652 if (!pIMedium)
4653 return setError(E_FAIL, tr("could not query medium interface of controller"));
4654 else
4655 {
4656 rc = pIMedium->pfnSetSecKeyIf(pIMedium, mpIfSecKey, mpIfSecKeyHlp);
4657 if (RT_FAILURE(rc))
4658 return setError(E_FAIL, tr("Failed to set the encryption key (%Rrc)"), rc);
4659 }
4660 }
4661 else
4662 return setError(E_FAIL, tr("could not query base interface of controller"));
4663 }
4664 }
4665 }
4666
4667 return hrc;
4668}
4669
4670/**
4671 * Parses the encryption configuration for one disk.
4672 *
4673 * @returns Pointer to the string following encryption configuration.
4674 * @param psz Pointer to the configuration for the encryption of one disk.
4675 */
4676HRESULT Console::i_consoleParseDiskEncryption(const char *psz, const char **ppszEnd)
4677{
4678 char *pszUuid = NULL;
4679 char *pszKeyEnc = NULL;
4680 int rc = VINF_SUCCESS;
4681 HRESULT hrc = S_OK;
4682
4683 while ( *psz
4684 && RT_SUCCESS(rc))
4685 {
4686 char *pszKey = NULL;
4687 char *pszVal = NULL;
4688 const char *pszEnd = NULL;
4689
4690 rc = i_consoleParseKeyValue(psz, &pszEnd, &pszKey, &pszVal);
4691 if (RT_SUCCESS(rc))
4692 {
4693 if (!RTStrCmp(pszKey, "uuid"))
4694 pszUuid = pszVal;
4695 else if (!RTStrCmp(pszKey, "dek"))
4696 pszKeyEnc = pszVal;
4697 else
4698 rc = VERR_INVALID_PARAMETER;
4699
4700 RTStrFree(pszKey);
4701
4702 if (*pszEnd == ',')
4703 psz = pszEnd + 1;
4704 else
4705 {
4706 /*
4707 * End of the configuration for the current disk, skip linefeed and
4708 * carriage returns.
4709 */
4710 while ( *pszEnd == '\n'
4711 || *pszEnd == '\r')
4712 pszEnd++;
4713
4714 psz = pszEnd;
4715 break; /* Stop parsing */
4716 }
4717
4718 }
4719 }
4720
4721 if ( RT_SUCCESS(rc)
4722 && pszUuid
4723 && pszKeyEnc)
4724 {
4725 ssize_t cbKey = 0;
4726
4727 /* Decode the key. */
4728 cbKey = RTBase64DecodedSize(pszKeyEnc, NULL);
4729 if (cbKey != -1)
4730 {
4731 uint8_t *pbKey;
4732 rc = RTMemSaferAllocZEx((void **)&pbKey, cbKey, RTMEMSAFER_F_REQUIRE_NOT_PAGABLE);
4733 if (RT_SUCCESS(rc))
4734 {
4735 rc = RTBase64Decode(pszKeyEnc, pbKey, cbKey, NULL, NULL);
4736 if (RT_SUCCESS(rc))
4737 {
4738 SecretKey *pKey = new SecretKey(pbKey, cbKey);
4739 /* Add the key to the map */
4740 m_mapSecretKeys.insert(std::make_pair(Utf8Str(pszUuid), pKey));
4741 hrc = i_configureEncryptionForDisk(pszUuid);
4742 if (FAILED(hrc))
4743 {
4744 /* Delete the key from the map. */
4745 m_mapSecretKeys.erase(Utf8Str(pszUuid));
4746 }
4747 }
4748 else
4749 hrc = setError(E_FAIL,
4750 tr("Failed to decode the key (%Rrc)"),
4751 rc);
4752 }
4753 else
4754 hrc = setError(E_FAIL,
4755 tr("Failed to allocate secure memory for the key (%Rrc)"), rc);
4756 }
4757 else
4758 hrc = setError(E_FAIL,
4759 tr("The base64 encoding of the passed key is incorrect"));
4760 }
4761 else if (RT_SUCCESS(rc))
4762 hrc = setError(E_FAIL,
4763 tr("The encryption configuration is incomplete"));
4764
4765 if (pszUuid)
4766 RTStrFree(pszUuid);
4767 if (pszKeyEnc)
4768 {
4769 RTMemWipeThoroughly(pszKeyEnc, strlen(pszKeyEnc), 10 /* cMinPasses */);
4770 RTStrFree(pszKeyEnc);
4771 }
4772
4773 if (ppszEnd)
4774 *ppszEnd = psz;
4775
4776 return hrc;
4777}
4778
4779HRESULT Console::i_setDiskEncryptionKeys(const Utf8Str &strCfg)
4780{
4781 HRESULT hrc = S_OK;
4782 const char *pszCfg = strCfg.c_str();
4783
4784 while ( *pszCfg
4785 && SUCCEEDED(hrc))
4786 {
4787 const char *pszNext = NULL;
4788 hrc = i_consoleParseDiskEncryption(pszCfg, &pszNext);
4789 pszCfg = pszNext;
4790 }
4791
4792 return hrc;
4793}
4794
4795/**
4796 * Process a network adaptor change.
4797 *
4798 * @returns COM status code.
4799 *
4800 * @parma pUVM The VM handle (caller hold this safely).
4801 * @param pszDevice The PDM device name.
4802 * @param uInstance The PDM device instance.
4803 * @param uLun The PDM LUN number of the drive.
4804 * @param aNetworkAdapter The network adapter whose attachment needs to be changed
4805 */
4806HRESULT Console::i_doNetworkAdapterChange(PUVM pUVM,
4807 const char *pszDevice,
4808 unsigned uInstance,
4809 unsigned uLun,
4810 INetworkAdapter *aNetworkAdapter)
4811{
4812 LogFlowThisFunc(("pszDevice=%p:{%s} uInstance=%u uLun=%u aNetworkAdapter=%p\n",
4813 pszDevice, pszDevice, uInstance, uLun, aNetworkAdapter));
4814
4815 AutoCaller autoCaller(this);
4816 AssertComRCReturnRC(autoCaller.rc());
4817
4818 /*
4819 * Suspend the VM first.
4820 */
4821 bool fResume = false;
4822 int rc = i_suspendBeforeConfigChange(pUVM, NULL, &fResume);
4823 if (FAILED(rc))
4824 return rc;
4825
4826 /*
4827 * Call worker in EMT, that's faster and safer than doing everything
4828 * using VM3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
4829 * here to make requests from under the lock in order to serialize them.
4830 */
4831 PVMREQ pReq;
4832 int vrc = VMR3ReqCallWaitU(pUVM, 0 /*idDstCpu*/,
4833 (PFNRT)i_changeNetworkAttachment, 6,
4834 this, pUVM, pszDevice, uInstance, uLun, aNetworkAdapter);
4835
4836 if (fResume)
4837 i_resumeAfterConfigChange(pUVM);
4838
4839 if (RT_SUCCESS(vrc))
4840 {
4841 LogFlowThisFunc(("Returns S_OK\n"));
4842 return S_OK;
4843 }
4844
4845 return setError(E_FAIL,
4846 tr("Could not change the network adaptor attachement type (%Rrc)"),
4847 vrc);
4848}
4849
4850
4851/**
4852 * Performs the Network Adaptor change in EMT.
4853 *
4854 * @returns VBox status code.
4855 *
4856 * @param pThis Pointer to the Console object.
4857 * @param pUVM The VM handle.
4858 * @param pszDevice The PDM device name.
4859 * @param uInstance The PDM device instance.
4860 * @param uLun The PDM LUN number of the drive.
4861 * @param aNetworkAdapter The network adapter whose attachment needs to be changed
4862 *
4863 * @thread EMT
4864 * @note Locks the Console object for writing.
4865 * @note The VM must not be running.
4866 */
4867DECLCALLBACK(int) Console::i_changeNetworkAttachment(Console *pThis,
4868 PUVM pUVM,
4869 const char *pszDevice,
4870 unsigned uInstance,
4871 unsigned uLun,
4872 INetworkAdapter *aNetworkAdapter)
4873{
4874 LogFlowFunc(("pThis=%p pszDevice=%p:{%s} uInstance=%u uLun=%u aNetworkAdapter=%p\n",
4875 pThis, pszDevice, pszDevice, uInstance, uLun, aNetworkAdapter));
4876
4877 AssertReturn(pThis, VERR_INVALID_PARAMETER);
4878
4879 AutoCaller autoCaller(pThis);
4880 AssertComRCReturn(autoCaller.rc(), VERR_ACCESS_DENIED);
4881
4882 ComPtr<IVirtualBox> pVirtualBox;
4883 pThis->mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
4884 ComPtr<ISystemProperties> pSystemProperties;
4885 if (pVirtualBox)
4886 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
4887 ChipsetType_T chipsetType = ChipsetType_PIIX3;
4888 pThis->mMachine->COMGETTER(ChipsetType)(&chipsetType);
4889 ULONG maxNetworkAdapters = 0;
4890 if (pSystemProperties)
4891 pSystemProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters);
4892 AssertMsg( ( !strcmp(pszDevice, "pcnet")
4893 || !strcmp(pszDevice, "e1000")
4894 || !strcmp(pszDevice, "virtio-net"))
4895 && uLun == 0
4896 && uInstance < maxNetworkAdapters,
4897 ("pszDevice=%s uLun=%d uInstance=%d\n", pszDevice, uLun, uInstance));
4898 Log(("pszDevice=%s uLun=%d uInstance=%d\n", pszDevice, uLun, uInstance));
4899
4900 /*
4901 * Check the VM for correct state.
4902 */
4903 VMSTATE enmVMState = VMR3GetStateU(pUVM);
4904 AssertReturn(enmVMState == VMSTATE_SUSPENDED, VERR_INVALID_STATE);
4905
4906 PCFGMNODE pCfg = NULL; /* /Devices/Dev/.../Config/ */
4907 PCFGMNODE pLunL0 = NULL; /* /Devices/Dev/0/LUN#0/ */
4908 PCFGMNODE pInst = CFGMR3GetChildF(CFGMR3GetRootU(pUVM), "Devices/%s/%d/", pszDevice, uInstance);
4909 AssertRelease(pInst);
4910
4911 int rc = pThis->i_configNetwork(pszDevice, uInstance, uLun, aNetworkAdapter, pCfg, pLunL0, pInst,
4912 true /*fAttachDetach*/, false /*fIgnoreConnectFailure*/);
4913
4914 LogFlowFunc(("Returning %Rrc\n", rc));
4915 return rc;
4916}
4917
4918
4919/**
4920 * Called by IInternalSessionControl::OnSerialPortChange().
4921 */
4922HRESULT Console::i_onSerialPortChange(ISerialPort *aSerialPort)
4923{
4924 LogFlowThisFunc(("\n"));
4925
4926 AutoCaller autoCaller(this);
4927 AssertComRCReturnRC(autoCaller.rc());
4928
4929 fireSerialPortChangedEvent(mEventSource, aSerialPort);
4930
4931 LogFlowThisFunc(("Leaving rc=%#x\n", S_OK));
4932 return S_OK;
4933}
4934
4935/**
4936 * Called by IInternalSessionControl::OnParallelPortChange().
4937 */
4938HRESULT Console::i_onParallelPortChange(IParallelPort *aParallelPort)
4939{
4940 LogFlowThisFunc(("\n"));
4941
4942 AutoCaller autoCaller(this);
4943 AssertComRCReturnRC(autoCaller.rc());
4944
4945 fireParallelPortChangedEvent(mEventSource, aParallelPort);
4946
4947 LogFlowThisFunc(("Leaving rc=%#x\n", S_OK));
4948 return S_OK;
4949}
4950
4951/**
4952 * Called by IInternalSessionControl::OnStorageControllerChange().
4953 */
4954HRESULT Console::i_onStorageControllerChange()
4955{
4956 LogFlowThisFunc(("\n"));
4957
4958 AutoCaller autoCaller(this);
4959 AssertComRCReturnRC(autoCaller.rc());
4960
4961 fireStorageControllerChangedEvent(mEventSource);
4962
4963 LogFlowThisFunc(("Leaving rc=%#x\n", S_OK));
4964 return S_OK;
4965}
4966
4967/**
4968 * Called by IInternalSessionControl::OnMediumChange().
4969 */
4970HRESULT Console::i_onMediumChange(IMediumAttachment *aMediumAttachment, BOOL aForce)
4971{
4972 LogFlowThisFunc(("\n"));
4973
4974 AutoCaller autoCaller(this);
4975 AssertComRCReturnRC(autoCaller.rc());
4976
4977 HRESULT rc = S_OK;
4978
4979 /* don't trigger medium changes if the VM isn't running */
4980 SafeVMPtrQuiet ptrVM(this);
4981 if (ptrVM.isOk())
4982 {
4983 rc = i_doMediumChange(aMediumAttachment, !!aForce, ptrVM.rawUVM());
4984 ptrVM.release();
4985 }
4986
4987 /* notify console callbacks on success */
4988 if (SUCCEEDED(rc))
4989 fireMediumChangedEvent(mEventSource, aMediumAttachment);
4990
4991 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
4992 return rc;
4993}
4994
4995/**
4996 * Called by IInternalSessionControl::OnCPUChange().
4997 *
4998 * @note Locks this object for writing.
4999 */
5000HRESULT Console::i_onCPUChange(ULONG aCPU, BOOL aRemove)
5001{
5002 LogFlowThisFunc(("\n"));
5003
5004 AutoCaller autoCaller(this);
5005 AssertComRCReturnRC(autoCaller.rc());
5006
5007 HRESULT rc = S_OK;
5008
5009 /* don't trigger CPU changes if the VM isn't running */
5010 SafeVMPtrQuiet ptrVM(this);
5011 if (ptrVM.isOk())
5012 {
5013 if (aRemove)
5014 rc = i_doCPURemove(aCPU, ptrVM.rawUVM());
5015 else
5016 rc = i_doCPUAdd(aCPU, ptrVM.rawUVM());
5017 ptrVM.release();
5018 }
5019
5020 /* notify console callbacks on success */
5021 if (SUCCEEDED(rc))
5022 fireCPUChangedEvent(mEventSource, aCPU, aRemove);
5023
5024 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
5025 return rc;
5026}
5027
5028/**
5029 * Called by IInternalSessionControl::OnCpuExecutionCapChange().
5030 *
5031 * @note Locks this object for writing.
5032 */
5033HRESULT Console::i_onCPUExecutionCapChange(ULONG aExecutionCap)
5034{
5035 LogFlowThisFunc(("\n"));
5036
5037 AutoCaller autoCaller(this);
5038 AssertComRCReturnRC(autoCaller.rc());
5039
5040 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5041
5042 HRESULT rc = S_OK;
5043
5044 /* don't trigger the CPU priority change if the VM isn't running */
5045 SafeVMPtrQuiet ptrVM(this);
5046 if (ptrVM.isOk())
5047 {
5048 if ( mMachineState == MachineState_Running
5049 || mMachineState == MachineState_Teleporting
5050 || mMachineState == MachineState_LiveSnapshotting
5051 )
5052 {
5053 /* No need to call in the EMT thread. */
5054 rc = VMR3SetCpuExecutionCap(ptrVM.rawUVM(), aExecutionCap);
5055 }
5056 else
5057 rc = i_setInvalidMachineStateError();
5058 ptrVM.release();
5059 }
5060
5061 /* notify console callbacks on success */
5062 if (SUCCEEDED(rc))
5063 {
5064 alock.release();
5065 fireCPUExecutionCapChangedEvent(mEventSource, aExecutionCap);
5066 }
5067
5068 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
5069 return rc;
5070}
5071
5072/**
5073 * Called by IInternalSessionControl::OnClipboardModeChange().
5074 *
5075 * @note Locks this object for writing.
5076 */
5077HRESULT Console::i_onClipboardModeChange(ClipboardMode_T aClipboardMode)
5078{
5079 LogFlowThisFunc(("\n"));
5080
5081 AutoCaller autoCaller(this);
5082 AssertComRCReturnRC(autoCaller.rc());
5083
5084 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5085
5086 HRESULT rc = S_OK;
5087
5088 /* don't trigger the clipboard mode change if the VM isn't running */
5089 SafeVMPtrQuiet ptrVM(this);
5090 if (ptrVM.isOk())
5091 {
5092 if ( mMachineState == MachineState_Running
5093 || mMachineState == MachineState_Teleporting
5094 || mMachineState == MachineState_LiveSnapshotting)
5095 i_changeClipboardMode(aClipboardMode);
5096 else
5097 rc = i_setInvalidMachineStateError();
5098 ptrVM.release();
5099 }
5100
5101 /* notify console callbacks on success */
5102 if (SUCCEEDED(rc))
5103 {
5104 alock.release();
5105 fireClipboardModeChangedEvent(mEventSource, aClipboardMode);
5106 }
5107
5108 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
5109 return rc;
5110}
5111
5112/**
5113 * Called by IInternalSessionControl::OnDnDModeChange().
5114 *
5115 * @note Locks this object for writing.
5116 */
5117HRESULT Console::i_onDnDModeChange(DnDMode_T aDnDMode)
5118{
5119 LogFlowThisFunc(("\n"));
5120
5121 AutoCaller autoCaller(this);
5122 AssertComRCReturnRC(autoCaller.rc());
5123
5124 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5125
5126 HRESULT rc = S_OK;
5127
5128 /* don't trigger the drag'n'drop mode change if the VM isn't running */
5129 SafeVMPtrQuiet ptrVM(this);
5130 if (ptrVM.isOk())
5131 {
5132 if ( mMachineState == MachineState_Running
5133 || mMachineState == MachineState_Teleporting
5134 || mMachineState == MachineState_LiveSnapshotting)
5135 i_changeDnDMode(aDnDMode);
5136 else
5137 rc = i_setInvalidMachineStateError();
5138 ptrVM.release();
5139 }
5140
5141 /* notify console callbacks on success */
5142 if (SUCCEEDED(rc))
5143 {
5144 alock.release();
5145 fireDnDModeChangedEvent(mEventSource, aDnDMode);
5146 }
5147
5148 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
5149 return rc;
5150}
5151
5152/**
5153 * Called by IInternalSessionControl::OnVRDEServerChange().
5154 *
5155 * @note Locks this object for writing.
5156 */
5157HRESULT Console::i_onVRDEServerChange(BOOL aRestart)
5158{
5159 AutoCaller autoCaller(this);
5160 AssertComRCReturnRC(autoCaller.rc());
5161
5162 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5163
5164 HRESULT rc = S_OK;
5165
5166 /* don't trigger VRDE server changes if the VM isn't running */
5167 SafeVMPtrQuiet ptrVM(this);
5168 if (ptrVM.isOk())
5169 {
5170 /* Serialize. */
5171 if (mfVRDEChangeInProcess)
5172 mfVRDEChangePending = true;
5173 else
5174 {
5175 do {
5176 mfVRDEChangeInProcess = true;
5177 mfVRDEChangePending = false;
5178
5179 if ( mVRDEServer
5180 && ( mMachineState == MachineState_Running
5181 || mMachineState == MachineState_Teleporting
5182 || mMachineState == MachineState_LiveSnapshotting
5183 || mMachineState == MachineState_Paused
5184 )
5185 )
5186 {
5187 BOOL vrdpEnabled = FALSE;
5188
5189 rc = mVRDEServer->COMGETTER(Enabled)(&vrdpEnabled);
5190 ComAssertComRCRetRC(rc);
5191
5192 if (aRestart)
5193 {
5194 /* VRDP server may call this Console object back from other threads (VRDP INPUT or OUTPUT). */
5195 alock.release();
5196
5197 if (vrdpEnabled)
5198 {
5199 // If there was no VRDP server started the 'stop' will do nothing.
5200 // However if a server was started and this notification was called,
5201 // we have to restart the server.
5202 mConsoleVRDPServer->Stop();
5203
5204 if (RT_FAILURE(mConsoleVRDPServer->Launch()))
5205 rc = E_FAIL;
5206 else
5207 mConsoleVRDPServer->EnableConnections();
5208 }
5209 else
5210 mConsoleVRDPServer->Stop();
5211
5212 alock.acquire();
5213 }
5214 }
5215 else
5216 rc = i_setInvalidMachineStateError();
5217
5218 mfVRDEChangeInProcess = false;
5219 } while (mfVRDEChangePending && SUCCEEDED(rc));
5220 }
5221
5222 ptrVM.release();
5223 }
5224
5225 /* notify console callbacks on success */
5226 if (SUCCEEDED(rc))
5227 {
5228 alock.release();
5229 fireVRDEServerChangedEvent(mEventSource);
5230 }
5231
5232 return rc;
5233}
5234
5235void Console::i_onVRDEServerInfoChange()
5236{
5237 AutoCaller autoCaller(this);
5238 AssertComRCReturnVoid(autoCaller.rc());
5239
5240 fireVRDEServerInfoChangedEvent(mEventSource);
5241}
5242
5243HRESULT Console::i_sendACPIMonitorHotPlugEvent()
5244{
5245 LogFlowThisFuncEnter();
5246
5247 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5248
5249 if ( mMachineState != MachineState_Running
5250 && mMachineState != MachineState_Teleporting
5251 && mMachineState != MachineState_LiveSnapshotting)
5252 return i_setInvalidMachineStateError();
5253
5254 /* get the VM handle. */
5255 SafeVMPtr ptrVM(this);
5256 if (!ptrVM.isOk())
5257 return ptrVM.rc();
5258
5259 // no need to release lock, as there are no cross-thread callbacks
5260
5261 /* get the acpi device interface and press the sleep button. */
5262 PPDMIBASE pBase;
5263 int vrc = PDMR3QueryDeviceLun(ptrVM.rawUVM(), "acpi", 0, 0, &pBase);
5264 if (RT_SUCCESS(vrc))
5265 {
5266 Assert(pBase);
5267 PPDMIACPIPORT pPort = PDMIBASE_QUERY_INTERFACE(pBase, PDMIACPIPORT);
5268 if (pPort)
5269 vrc = pPort->pfnMonitorHotPlugEvent(pPort);
5270 else
5271 vrc = VERR_PDM_MISSING_INTERFACE;
5272 }
5273
5274 HRESULT rc = RT_SUCCESS(vrc) ? S_OK :
5275 setError(VBOX_E_PDM_ERROR,
5276 tr("Sending monitor hot-plug event failed (%Rrc)"),
5277 vrc);
5278
5279 LogFlowThisFunc(("rc=%Rhrc\n", rc));
5280 LogFlowThisFuncLeave();
5281 return rc;
5282}
5283
5284HRESULT Console::i_onVideoCaptureChange()
5285{
5286 AutoCaller autoCaller(this);
5287 AssertComRCReturnRC(autoCaller.rc());
5288
5289 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5290
5291 HRESULT rc = S_OK;
5292
5293 /* don't trigger video capture changes if the VM isn't running */
5294 SafeVMPtrQuiet ptrVM(this);
5295 if (ptrVM.isOk())
5296 {
5297 BOOL fEnabled;
5298 rc = mMachine->COMGETTER(VideoCaptureEnabled)(&fEnabled);
5299 SafeArray<BOOL> screens;
5300 if (SUCCEEDED(rc))
5301 rc = mMachine->COMGETTER(VideoCaptureScreens)(ComSafeArrayAsOutParam(screens));
5302 if (mDisplay)
5303 {
5304 int vrc = VINF_SUCCESS;
5305 if (SUCCEEDED(rc))
5306 vrc = mDisplay->i_VideoCaptureEnableScreens(ComSafeArrayAsInParam(screens));
5307 if (RT_SUCCESS(vrc))
5308 {
5309 if (fEnabled)
5310 {
5311 vrc = mDisplay->i_VideoCaptureStart();
5312 if (RT_FAILURE(vrc))
5313 rc = setError(E_FAIL, tr("Unable to start video capturing (%Rrc)"), vrc);
5314 }
5315 else
5316 mDisplay->i_VideoCaptureStop();
5317 }
5318 else
5319 rc = setError(E_FAIL, tr("Unable to set screens for capturing (%Rrc)"), vrc);
5320 }
5321 ptrVM.release();
5322 }
5323
5324 /* notify console callbacks on success */
5325 if (SUCCEEDED(rc))
5326 {
5327 alock.release();
5328 fireVideoCaptureChangedEvent(mEventSource);
5329 }
5330
5331 return rc;
5332}
5333
5334/**
5335 * Called by IInternalSessionControl::OnUSBControllerChange().
5336 */
5337HRESULT Console::i_onUSBControllerChange()
5338{
5339 LogFlowThisFunc(("\n"));
5340
5341 AutoCaller autoCaller(this);
5342 AssertComRCReturnRC(autoCaller.rc());
5343
5344 fireUSBControllerChangedEvent(mEventSource);
5345
5346 return S_OK;
5347}
5348
5349/**
5350 * Called by IInternalSessionControl::OnSharedFolderChange().
5351 *
5352 * @note Locks this object for writing.
5353 */
5354HRESULT Console::i_onSharedFolderChange(BOOL aGlobal)
5355{
5356 LogFlowThisFunc(("aGlobal=%RTbool\n", aGlobal));
5357
5358 AutoCaller autoCaller(this);
5359 AssertComRCReturnRC(autoCaller.rc());
5360
5361 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5362
5363 HRESULT rc = i_fetchSharedFolders(aGlobal);
5364
5365 /* notify console callbacks on success */
5366 if (SUCCEEDED(rc))
5367 {
5368 alock.release();
5369 fireSharedFolderChangedEvent(mEventSource, aGlobal ? (Scope_T)Scope_Global : (Scope_T)Scope_Machine);
5370 }
5371
5372 return rc;
5373}
5374
5375/**
5376 * Called by IInternalSessionControl::OnUSBDeviceAttach() or locally by
5377 * processRemoteUSBDevices() after IInternalMachineControl::RunUSBDeviceFilters()
5378 * returns TRUE for a given remote USB device.
5379 *
5380 * @return S_OK if the device was attached to the VM.
5381 * @return failure if not attached.
5382 *
5383 * @param aDevice
5384 * The device in question.
5385 * @param aMaskedIfs
5386 * The interfaces to hide from the guest.
5387 *
5388 * @note Locks this object for writing.
5389 */
5390HRESULT Console::i_onUSBDeviceAttach(IUSBDevice *aDevice, IVirtualBoxErrorInfo *aError, ULONG aMaskedIfs,
5391 const Utf8Str &aCaptureFilename)
5392{
5393#ifdef VBOX_WITH_USB
5394 LogFlowThisFunc(("aDevice=%p aError=%p\n", aDevice, aError));
5395
5396 AutoCaller autoCaller(this);
5397 ComAssertComRCRetRC(autoCaller.rc());
5398
5399 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5400
5401 /* Get the VM pointer (we don't need error info, since it's a callback). */
5402 SafeVMPtrQuiet ptrVM(this);
5403 if (!ptrVM.isOk())
5404 {
5405 /* The VM may be no more operational when this message arrives
5406 * (e.g. it may be Saving or Stopping or just PoweredOff) --
5407 * autoVMCaller.rc() will return a failure in this case. */
5408 LogFlowThisFunc(("Attach request ignored (mMachineState=%d).\n",
5409 mMachineState));
5410 return ptrVM.rc();
5411 }
5412
5413 if (aError != NULL)
5414 {
5415 /* notify callbacks about the error */
5416 alock.release();
5417 i_onUSBDeviceStateChange(aDevice, true /* aAttached */, aError);
5418 return S_OK;
5419 }
5420
5421 /* Don't proceed unless there's at least one USB hub. */
5422 if (!PDMR3UsbHasHub(ptrVM.rawUVM()))
5423 {
5424 LogFlowThisFunc(("Attach request ignored (no USB controller).\n"));
5425 return E_FAIL;
5426 }
5427
5428 alock.release();
5429 HRESULT rc = i_attachUSBDevice(aDevice, aMaskedIfs, aCaptureFilename);
5430 if (FAILED(rc))
5431 {
5432 /* take the current error info */
5433 com::ErrorInfoKeeper eik;
5434 /* the error must be a VirtualBoxErrorInfo instance */
5435 ComPtr<IVirtualBoxErrorInfo> pError = eik.takeError();
5436 Assert(!pError.isNull());
5437 if (!pError.isNull())
5438 {
5439 /* notify callbacks about the error */
5440 i_onUSBDeviceStateChange(aDevice, true /* aAttached */, pError);
5441 }
5442 }
5443
5444 return rc;
5445
5446#else /* !VBOX_WITH_USB */
5447 return E_FAIL;
5448#endif /* !VBOX_WITH_USB */
5449}
5450
5451/**
5452 * Called by IInternalSessionControl::OnUSBDeviceDetach() and locally by
5453 * processRemoteUSBDevices().
5454 *
5455 * @note Locks this object for writing.
5456 */
5457HRESULT Console::i_onUSBDeviceDetach(IN_BSTR aId,
5458 IVirtualBoxErrorInfo *aError)
5459{
5460#ifdef VBOX_WITH_USB
5461 Guid Uuid(aId);
5462 LogFlowThisFunc(("aId={%RTuuid} aError=%p\n", Uuid.raw(), aError));
5463
5464 AutoCaller autoCaller(this);
5465 AssertComRCReturnRC(autoCaller.rc());
5466
5467 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5468
5469 /* Find the device. */
5470 ComObjPtr<OUSBDevice> pUSBDevice;
5471 USBDeviceList::iterator it = mUSBDevices.begin();
5472 while (it != mUSBDevices.end())
5473 {
5474 LogFlowThisFunc(("it={%RTuuid}\n", (*it)->i_id().raw()));
5475 if ((*it)->i_id() == Uuid)
5476 {
5477 pUSBDevice = *it;
5478 break;
5479 }
5480 ++it;
5481 }
5482
5483
5484 if (pUSBDevice.isNull())
5485 {
5486 LogFlowThisFunc(("USB device not found.\n"));
5487
5488 /* The VM may be no more operational when this message arrives
5489 * (e.g. it may be Saving or Stopping or just PoweredOff). Use
5490 * AutoVMCaller to detect it -- AutoVMCaller::rc() will return a
5491 * failure in this case. */
5492
5493 AutoVMCallerQuiet autoVMCaller(this);
5494 if (FAILED(autoVMCaller.rc()))
5495 {
5496 LogFlowThisFunc(("Detach request ignored (mMachineState=%d).\n",
5497 mMachineState));
5498 return autoVMCaller.rc();
5499 }
5500
5501 /* the device must be in the list otherwise */
5502 AssertFailedReturn(E_FAIL);
5503 }
5504
5505 if (aError != NULL)
5506 {
5507 /* notify callback about an error */
5508 alock.release();
5509 i_onUSBDeviceStateChange(pUSBDevice, false /* aAttached */, aError);
5510 return S_OK;
5511 }
5512
5513 /* Remove the device from the collection, it is re-added below for failures */
5514 mUSBDevices.erase(it);
5515
5516 alock.release();
5517 HRESULT rc = i_detachUSBDevice(pUSBDevice);
5518 if (FAILED(rc))
5519 {
5520 /* Re-add the device to the collection */
5521 alock.acquire();
5522 mUSBDevices.push_back(pUSBDevice);
5523 alock.release();
5524 /* take the current error info */
5525 com::ErrorInfoKeeper eik;
5526 /* the error must be a VirtualBoxErrorInfo instance */
5527 ComPtr<IVirtualBoxErrorInfo> pError = eik.takeError();
5528 Assert(!pError.isNull());
5529 if (!pError.isNull())
5530 {
5531 /* notify callbacks about the error */
5532 i_onUSBDeviceStateChange(pUSBDevice, false /* aAttached */, pError);
5533 }
5534 }
5535
5536 return rc;
5537
5538#else /* !VBOX_WITH_USB */
5539 return E_FAIL;
5540#endif /* !VBOX_WITH_USB */
5541}
5542
5543/**
5544 * Called by IInternalSessionControl::OnBandwidthGroupChange().
5545 *
5546 * @note Locks this object for writing.
5547 */
5548HRESULT Console::i_onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
5549{
5550 LogFlowThisFunc(("\n"));
5551
5552 AutoCaller autoCaller(this);
5553 AssertComRCReturnRC(autoCaller.rc());
5554
5555 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5556
5557 HRESULT rc = S_OK;
5558
5559 /* don't trigger bandwidth group changes if the VM isn't running */
5560 SafeVMPtrQuiet ptrVM(this);
5561 if (ptrVM.isOk())
5562 {
5563 if ( mMachineState == MachineState_Running
5564 || mMachineState == MachineState_Teleporting
5565 || mMachineState == MachineState_LiveSnapshotting
5566 )
5567 {
5568 /* No need to call in the EMT thread. */
5569 LONG64 cMax;
5570 Bstr strName;
5571 BandwidthGroupType_T enmType;
5572 rc = aBandwidthGroup->COMGETTER(Name)(strName.asOutParam());
5573 if (SUCCEEDED(rc))
5574 rc = aBandwidthGroup->COMGETTER(MaxBytesPerSec)(&cMax);
5575 if (SUCCEEDED(rc))
5576 rc = aBandwidthGroup->COMGETTER(Type)(&enmType);
5577
5578 if (SUCCEEDED(rc))
5579 {
5580 int vrc = VINF_SUCCESS;
5581 if (enmType == BandwidthGroupType_Disk)
5582 vrc = PDMR3AsyncCompletionBwMgrSetMaxForFile(ptrVM.rawUVM(), Utf8Str(strName).c_str(), (uint32_t)cMax);
5583#ifdef VBOX_WITH_NETSHAPER
5584 else if (enmType == BandwidthGroupType_Network)
5585 vrc = PDMR3NsBwGroupSetLimit(ptrVM.rawUVM(), Utf8Str(strName).c_str(), cMax);
5586 else
5587 rc = E_NOTIMPL;
5588#endif /* VBOX_WITH_NETSHAPER */
5589 AssertRC(vrc);
5590 }
5591 }
5592 else
5593 rc = i_setInvalidMachineStateError();
5594 ptrVM.release();
5595 }
5596
5597 /* notify console callbacks on success */
5598 if (SUCCEEDED(rc))
5599 {
5600 alock.release();
5601 fireBandwidthGroupChangedEvent(mEventSource, aBandwidthGroup);
5602 }
5603
5604 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
5605 return rc;
5606}
5607
5608/**
5609 * Called by IInternalSessionControl::OnStorageDeviceChange().
5610 *
5611 * @note Locks this object for writing.
5612 */
5613HRESULT Console::i_onStorageDeviceChange(IMediumAttachment *aMediumAttachment, BOOL aRemove, BOOL aSilent)
5614{
5615 LogFlowThisFunc(("\n"));
5616
5617 AutoCaller autoCaller(this);
5618 AssertComRCReturnRC(autoCaller.rc());
5619
5620 HRESULT rc = S_OK;
5621
5622 /* don't trigger medium changes if the VM isn't running */
5623 SafeVMPtrQuiet ptrVM(this);
5624 if (ptrVM.isOk())
5625 {
5626 if (aRemove)
5627 rc = i_doStorageDeviceDetach(aMediumAttachment, ptrVM.rawUVM(), RT_BOOL(aSilent));
5628 else
5629 rc = i_doStorageDeviceAttach(aMediumAttachment, ptrVM.rawUVM(), RT_BOOL(aSilent));
5630 ptrVM.release();
5631 }
5632
5633 /* notify console callbacks on success */
5634 if (SUCCEEDED(rc))
5635 fireStorageDeviceChangedEvent(mEventSource, aMediumAttachment, aRemove, aSilent);
5636
5637 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
5638 return rc;
5639}
5640
5641HRESULT Console::i_onExtraDataChange(IN_BSTR aMachineId, IN_BSTR aKey, IN_BSTR aVal)
5642{
5643 LogFlowThisFunc(("\n"));
5644
5645 AutoCaller autoCaller(this);
5646 if (FAILED(autoCaller.rc()))
5647 return autoCaller.rc();
5648
5649 if (!aMachineId)
5650 return S_OK;
5651
5652 HRESULT hrc = S_OK;
5653 Bstr idMachine(aMachineId);
5654 Bstr idSelf;
5655 hrc = mMachine->COMGETTER(Id)(idSelf.asOutParam());
5656 if ( FAILED(hrc)
5657 || idMachine != idSelf)
5658 return hrc;
5659
5660 /* don't do anything if the VM isn't running */
5661 SafeVMPtrQuiet ptrVM(this);
5662 if (ptrVM.isOk())
5663 {
5664 Bstr strKey(aKey);
5665 Bstr strVal(aVal);
5666
5667 if (strKey == "VBoxInternal2/TurnResetIntoPowerOff")
5668 {
5669 int vrc = VMR3SetPowerOffInsteadOfReset(ptrVM.rawUVM(), strVal == "1");
5670 AssertRC(vrc);
5671 }
5672
5673 ptrVM.release();
5674 }
5675
5676 /* notify console callbacks on success */
5677 if (SUCCEEDED(hrc))
5678 fireExtraDataChangedEvent(mEventSource, aMachineId, aKey, aVal);
5679
5680 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
5681 return hrc;
5682}
5683
5684/**
5685 * @note Temporarily locks this object for writing.
5686 */
5687HRESULT Console::i_getGuestProperty(const Utf8Str &aName, Utf8Str *aValue, LONG64 *aTimestamp, Utf8Str *aFlags)
5688{
5689#ifndef VBOX_WITH_GUEST_PROPS
5690 ReturnComNotImplemented();
5691#else /* VBOX_WITH_GUEST_PROPS */
5692 if (!RT_VALID_PTR(aValue))
5693 return E_POINTER;
5694 if (aTimestamp != NULL && !RT_VALID_PTR(aTimestamp))
5695 return E_POINTER;
5696 if (aFlags != NULL && !RT_VALID_PTR(aFlags))
5697 return E_POINTER;
5698
5699 AutoCaller autoCaller(this);
5700 AssertComRCReturnRC(autoCaller.rc());
5701
5702 /* protect mpUVM (if not NULL) */
5703 SafeVMPtrQuiet ptrVM(this);
5704 if (FAILED(ptrVM.rc()))
5705 return ptrVM.rc();
5706
5707 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
5708 * ptrVM, so there is no need to hold a lock of this */
5709
5710 HRESULT rc = E_UNEXPECTED;
5711 using namespace guestProp;
5712
5713 try
5714 {
5715 VBOXHGCMSVCPARM parm[4];
5716 char szBuffer[MAX_VALUE_LEN + MAX_FLAGS_LEN];
5717
5718 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
5719 parm[0].u.pointer.addr = (void*)aName.c_str();
5720 parm[0].u.pointer.size = (uint32_t)aName.length() + 1; /* The + 1 is the null terminator */
5721
5722 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
5723 parm[1].u.pointer.addr = szBuffer;
5724 parm[1].u.pointer.size = sizeof(szBuffer);
5725
5726 parm[2].type = VBOX_HGCM_SVC_PARM_64BIT;
5727 parm[2].u.uint64 = 0;
5728
5729 parm[3].type = VBOX_HGCM_SVC_PARM_32BIT;
5730 parm[3].u.uint32 = 0;
5731
5732 int vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GET_PROP_HOST,
5733 4, &parm[0]);
5734 /* The returned string should never be able to be greater than our buffer */
5735 AssertLogRel(vrc != VERR_BUFFER_OVERFLOW);
5736 AssertLogRel(RT_FAILURE(vrc) || parm[2].type == VBOX_HGCM_SVC_PARM_64BIT);
5737 if (RT_SUCCESS(vrc))
5738 {
5739 *aValue = szBuffer;
5740
5741 if (aTimestamp)
5742 *aTimestamp = parm[2].u.uint64;
5743
5744 if (aFlags)
5745 *aFlags = &szBuffer[strlen(szBuffer) + 1];
5746
5747 rc = S_OK;
5748 }
5749 else if (vrc == VERR_NOT_FOUND)
5750 {
5751 *aValue = "";
5752 rc = S_OK;
5753 }
5754 else
5755 rc = setError(VBOX_E_IPRT_ERROR,
5756 tr("The VBoxGuestPropSvc service call failed with the error %Rrc"),
5757 vrc);
5758 }
5759 catch(std::bad_alloc & /*e*/)
5760 {
5761 rc = E_OUTOFMEMORY;
5762 }
5763
5764 return rc;
5765#endif /* VBOX_WITH_GUEST_PROPS */
5766}
5767
5768/**
5769 * @note Temporarily locks this object for writing.
5770 */
5771HRESULT Console::i_setGuestProperty(const Utf8Str &aName, const Utf8Str &aValue, const Utf8Str &aFlags)
5772{
5773#ifndef VBOX_WITH_GUEST_PROPS
5774 ReturnComNotImplemented();
5775#else /* VBOX_WITH_GUEST_PROPS */
5776
5777 AutoCaller autoCaller(this);
5778 AssertComRCReturnRC(autoCaller.rc());
5779
5780 /* protect mpUVM (if not NULL) */
5781 SafeVMPtrQuiet ptrVM(this);
5782 if (FAILED(ptrVM.rc()))
5783 return ptrVM.rc();
5784
5785 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
5786 * ptrVM, so there is no need to hold a lock of this */
5787
5788 using namespace guestProp;
5789
5790 VBOXHGCMSVCPARM parm[3];
5791
5792 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
5793 parm[0].u.pointer.addr = (void*)aName.c_str();
5794 parm[0].u.pointer.size = (uint32_t)aName.length() + 1; /* The + 1 is the null terminator */
5795
5796 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
5797 parm[1].u.pointer.addr = (void *)aValue.c_str();
5798 parm[1].u.pointer.size = (uint32_t)aValue.length() + 1; /* The + 1 is the null terminator */
5799
5800 int vrc;
5801 if (aFlags.isEmpty())
5802 {
5803 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", SET_PROP_VALUE_HOST,
5804 2, &parm[0]);
5805 }
5806 else
5807 {
5808 parm[2].type = VBOX_HGCM_SVC_PARM_PTR;
5809 parm[2].u.pointer.addr = (void*)aFlags.c_str();
5810 parm[2].u.pointer.size = (uint32_t)aFlags.length() + 1; /* The + 1 is the null terminator */
5811
5812 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", SET_PROP_HOST,
5813 3, &parm[0]);
5814 }
5815
5816 HRESULT hrc = S_OK;
5817 if (RT_FAILURE(vrc))
5818 hrc = setError(VBOX_E_IPRT_ERROR, tr("The VBoxGuestPropSvc service call failed with the error %Rrc"), vrc);
5819 return hrc;
5820#endif /* VBOX_WITH_GUEST_PROPS */
5821}
5822
5823HRESULT Console::i_deleteGuestProperty(const Utf8Str &aName)
5824{
5825#ifndef VBOX_WITH_GUEST_PROPS
5826 ReturnComNotImplemented();
5827#else /* VBOX_WITH_GUEST_PROPS */
5828
5829 AutoCaller autoCaller(this);
5830 AssertComRCReturnRC(autoCaller.rc());
5831
5832 /* protect mpUVM (if not NULL) */
5833 SafeVMPtrQuiet ptrVM(this);
5834 if (FAILED(ptrVM.rc()))
5835 return ptrVM.rc();
5836
5837 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
5838 * ptrVM, so there is no need to hold a lock of this */
5839
5840 using namespace guestProp;
5841
5842 VBOXHGCMSVCPARM parm[1];
5843
5844 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
5845 parm[0].u.pointer.addr = (void*)aName.c_str();
5846 parm[0].u.pointer.size = (uint32_t)aName.length() + 1; /* The + 1 is the null terminator */
5847
5848 int vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", DEL_PROP_HOST,
5849 1, &parm[0]);
5850
5851 HRESULT hrc = S_OK;
5852 if (RT_FAILURE(vrc))
5853 hrc = setError(VBOX_E_IPRT_ERROR, tr("The VBoxGuestPropSvc service call failed with the error %Rrc"), vrc);
5854 return hrc;
5855#endif /* VBOX_WITH_GUEST_PROPS */
5856}
5857
5858/**
5859 * @note Temporarily locks this object for writing.
5860 */
5861HRESULT Console::i_enumerateGuestProperties(const Utf8Str &aPatterns,
5862 std::vector<Utf8Str> &aNames,
5863 std::vector<Utf8Str> &aValues,
5864 std::vector<LONG64> &aTimestamps,
5865 std::vector<Utf8Str> &aFlags)
5866{
5867#ifndef VBOX_WITH_GUEST_PROPS
5868 ReturnComNotImplemented();
5869#else /* VBOX_WITH_GUEST_PROPS */
5870
5871 AutoCaller autoCaller(this);
5872 AssertComRCReturnRC(autoCaller.rc());
5873
5874 /* protect mpUVM (if not NULL) */
5875 AutoVMCallerWeak autoVMCaller(this);
5876 if (FAILED(autoVMCaller.rc()))
5877 return autoVMCaller.rc();
5878
5879 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
5880 * autoVMCaller, so there is no need to hold a lock of this */
5881
5882 return i_doEnumerateGuestProperties(aPatterns, aNames, aValues, aTimestamps, aFlags);
5883#endif /* VBOX_WITH_GUEST_PROPS */
5884}
5885
5886
5887/*
5888 * Internal: helper function for connecting progress reporting
5889 */
5890static int onlineMergeMediumProgress(void *pvUser, unsigned uPercentage)
5891{
5892 HRESULT rc = S_OK;
5893 IProgress *pProgress = static_cast<IProgress *>(pvUser);
5894 if (pProgress)
5895 rc = pProgress->SetCurrentOperationProgress(uPercentage);
5896 return SUCCEEDED(rc) ? VINF_SUCCESS : VERR_GENERAL_FAILURE;
5897}
5898
5899/**
5900 * @note Temporarily locks this object for writing. bird: And/or reading?
5901 */
5902HRESULT Console::i_onlineMergeMedium(IMediumAttachment *aMediumAttachment,
5903 ULONG aSourceIdx, ULONG aTargetIdx,
5904 IProgress *aProgress)
5905{
5906 AutoCaller autoCaller(this);
5907 AssertComRCReturnRC(autoCaller.rc());
5908
5909 HRESULT rc = S_OK;
5910 int vrc = VINF_SUCCESS;
5911
5912 /* Get the VM - must be done before the read-locking. */
5913 SafeVMPtr ptrVM(this);
5914 if (!ptrVM.isOk())
5915 return ptrVM.rc();
5916
5917 /* We will need to release the lock before doing the actual merge */
5918 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5919
5920 /* paranoia - we don't want merges to happen while teleporting etc. */
5921 switch (mMachineState)
5922 {
5923 case MachineState_DeletingSnapshotOnline:
5924 case MachineState_DeletingSnapshotPaused:
5925 break;
5926
5927 default:
5928 return i_setInvalidMachineStateError();
5929 }
5930
5931 /** @todo AssertComRC -> AssertComRCReturn! Could potentially end up
5932 * using uninitialized variables here. */
5933 BOOL fBuiltinIOCache;
5934 rc = mMachine->COMGETTER(IOCacheEnabled)(&fBuiltinIOCache);
5935 AssertComRC(rc);
5936 SafeIfaceArray<IStorageController> ctrls;
5937 rc = mMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));
5938 AssertComRC(rc);
5939 LONG lDev;
5940 rc = aMediumAttachment->COMGETTER(Device)(&lDev);
5941 AssertComRC(rc);
5942 LONG lPort;
5943 rc = aMediumAttachment->COMGETTER(Port)(&lPort);
5944 AssertComRC(rc);
5945 IMedium *pMedium;
5946 rc = aMediumAttachment->COMGETTER(Medium)(&pMedium);
5947 AssertComRC(rc);
5948 Bstr mediumLocation;
5949 if (pMedium)
5950 {
5951 rc = pMedium->COMGETTER(Location)(mediumLocation.asOutParam());
5952 AssertComRC(rc);
5953 }
5954
5955 Bstr attCtrlName;
5956 rc = aMediumAttachment->COMGETTER(Controller)(attCtrlName.asOutParam());
5957 AssertComRC(rc);
5958 ComPtr<IStorageController> pStorageController;
5959 for (size_t i = 0; i < ctrls.size(); ++i)
5960 {
5961 Bstr ctrlName;
5962 rc = ctrls[i]->COMGETTER(Name)(ctrlName.asOutParam());
5963 AssertComRC(rc);
5964 if (attCtrlName == ctrlName)
5965 {
5966 pStorageController = ctrls[i];
5967 break;
5968 }
5969 }
5970 if (pStorageController.isNull())
5971 return setError(E_FAIL,
5972 tr("Could not find storage controller '%ls'"),
5973 attCtrlName.raw());
5974
5975 StorageControllerType_T enmCtrlType;
5976 rc = pStorageController->COMGETTER(ControllerType)(&enmCtrlType);
5977 AssertComRC(rc);
5978 const char *pcszDevice = i_convertControllerTypeToDev(enmCtrlType);
5979
5980 StorageBus_T enmBus;
5981 rc = pStorageController->COMGETTER(Bus)(&enmBus);
5982 AssertComRC(rc);
5983 ULONG uInstance;
5984 rc = pStorageController->COMGETTER(Instance)(&uInstance);
5985 AssertComRC(rc);
5986 BOOL fUseHostIOCache;
5987 rc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
5988 AssertComRC(rc);
5989
5990 unsigned uLUN;
5991 rc = Console::i_convertBusPortDeviceToLun(enmBus, lPort, lDev, uLUN);
5992 AssertComRCReturnRC(rc);
5993
5994 alock.release();
5995
5996 /* Pause the VM, as it might have pending IO on this drive */
5997 VMSTATE enmVMState = VMR3GetStateU(ptrVM.rawUVM());
5998 if (mMachineState == MachineState_DeletingSnapshotOnline)
5999 {
6000 LogFlowFunc(("Suspending the VM...\n"));
6001 /* disable the callback to prevent Console-level state change */
6002 mVMStateChangeCallbackDisabled = true;
6003 int vrc2 = VMR3Suspend(ptrVM.rawUVM(), VMSUSPENDREASON_RECONFIG);
6004 mVMStateChangeCallbackDisabled = false;
6005 AssertRCReturn(vrc2, E_FAIL);
6006 }
6007
6008 vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY,
6009 (PFNRT)i_reconfigureMediumAttachment, 13,
6010 this, ptrVM.rawUVM(), pcszDevice, uInstance, enmBus, fUseHostIOCache,
6011 fBuiltinIOCache, true /* fSetupMerge */, aSourceIdx, aTargetIdx,
6012 aMediumAttachment, mMachineState, &rc);
6013 /* error handling is after resuming the VM */
6014
6015 if (mMachineState == MachineState_DeletingSnapshotOnline)
6016 {
6017 LogFlowFunc(("Resuming the VM...\n"));
6018 /* disable the callback to prevent Console-level state change */
6019 mVMStateChangeCallbackDisabled = true;
6020 int vrc2 = VMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_RECONFIG);
6021 mVMStateChangeCallbackDisabled = false;
6022 if (RT_FAILURE(vrc2))
6023 {
6024 /* too bad, we failed. try to sync the console state with the VMM state */
6025 AssertLogRelRC(vrc2);
6026 i_vmstateChangeCallback(ptrVM.rawUVM(), VMSTATE_SUSPENDED, enmVMState, this);
6027 }
6028 }
6029
6030 if (RT_FAILURE(vrc))
6031 return setError(E_FAIL, tr("%Rrc"), vrc);
6032 if (FAILED(rc))
6033 return rc;
6034
6035 PPDMIBASE pIBase = NULL;
6036 PPDMIMEDIA pIMedium = NULL;
6037 vrc = PDMR3QueryDriverOnLun(ptrVM.rawUVM(), pcszDevice, uInstance, uLUN, "VD", &pIBase);
6038 if (RT_SUCCESS(vrc))
6039 {
6040 if (pIBase)
6041 {
6042 pIMedium = (PPDMIMEDIA)pIBase->pfnQueryInterface(pIBase, PDMIMEDIA_IID);
6043 if (!pIMedium)
6044 return setError(E_FAIL, tr("could not query medium interface of controller"));
6045 }
6046 else
6047 return setError(E_FAIL, tr("could not query base interface of controller"));
6048 }
6049
6050 /* Finally trigger the merge. */
6051 vrc = pIMedium->pfnMerge(pIMedium, onlineMergeMediumProgress, aProgress);
6052 if (RT_FAILURE(vrc))
6053 return setError(E_FAIL, tr("Failed to perform an online medium merge (%Rrc)"), vrc);
6054
6055 /* Pause the VM, as it might have pending IO on this drive */
6056 enmVMState = VMR3GetStateU(ptrVM.rawUVM());
6057 if (mMachineState == MachineState_DeletingSnapshotOnline)
6058 {
6059 LogFlowFunc(("Suspending the VM...\n"));
6060 /* disable the callback to prevent Console-level state change */
6061 mVMStateChangeCallbackDisabled = true;
6062 int vrc2 = VMR3Suspend(ptrVM.rawUVM(), VMSUSPENDREASON_RECONFIG);
6063 mVMStateChangeCallbackDisabled = false;
6064 AssertRCReturn(vrc2, E_FAIL);
6065 }
6066
6067 /* Update medium chain and state now, so that the VM can continue. */
6068 rc = mControl->FinishOnlineMergeMedium();
6069
6070 vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY,
6071 (PFNRT)i_reconfigureMediumAttachment, 13,
6072 this, ptrVM.rawUVM(), pcszDevice, uInstance, enmBus, fUseHostIOCache,
6073 fBuiltinIOCache, false /* fSetupMerge */, 0 /* uMergeSource */,
6074 0 /* uMergeTarget */, aMediumAttachment, mMachineState, &rc);
6075 /* error handling is after resuming the VM */
6076
6077 if (mMachineState == MachineState_DeletingSnapshotOnline)
6078 {
6079 LogFlowFunc(("Resuming the VM...\n"));
6080 /* disable the callback to prevent Console-level state change */
6081 mVMStateChangeCallbackDisabled = true;
6082 int vrc2 = VMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_RECONFIG);
6083 mVMStateChangeCallbackDisabled = false;
6084 AssertRC(vrc2);
6085 if (RT_FAILURE(vrc2))
6086 {
6087 /* too bad, we failed. try to sync the console state with the VMM state */
6088 i_vmstateChangeCallback(ptrVM.rawUVM(), VMSTATE_SUSPENDED, enmVMState, this);
6089 }
6090 }
6091
6092 if (RT_FAILURE(vrc))
6093 return setError(E_FAIL, tr("%Rrc"), vrc);
6094 if (FAILED(rc))
6095 return rc;
6096
6097 return rc;
6098}
6099
6100
6101/**
6102 * Load an HGCM service.
6103 *
6104 * Main purpose of this method is to allow extension packs to load HGCM
6105 * service modules, which they can't, because the HGCM functionality lives
6106 * in module VBoxC (and ConsoleImpl.cpp is part of it and thus can call it).
6107 * Extension modules must not link directly against VBoxC, (XP)COM is
6108 * handling this.
6109 */
6110int Console::i_hgcmLoadService(const char *pszServiceLibrary, const char *pszServiceName)
6111{
6112 /* Everyone seems to delegate all HGCM calls to VMMDev, so stick to this
6113 * convention. Adds one level of indirection for no obvious reason. */
6114 AssertPtrReturn(m_pVMMDev, VERR_INVALID_STATE);
6115 return m_pVMMDev->hgcmLoadService(pszServiceLibrary, pszServiceName);
6116}
6117
6118/**
6119 * Merely passes the call to Guest::enableVMMStatistics().
6120 */
6121void Console::i_enableVMMStatistics(BOOL aEnable)
6122{
6123 if (mGuest)
6124 mGuest->i_enableVMMStatistics(aEnable);
6125}
6126
6127/**
6128 * Worker for Console::Pause and internal entry point for pausing a VM for
6129 * a specific reason.
6130 */
6131HRESULT Console::i_pause(Reason_T aReason)
6132{
6133 LogFlowThisFuncEnter();
6134
6135 AutoCaller autoCaller(this);
6136 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6137
6138 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6139
6140 switch (mMachineState)
6141 {
6142 case MachineState_Running:
6143 case MachineState_Teleporting:
6144 case MachineState_LiveSnapshotting:
6145 break;
6146
6147 case MachineState_Paused:
6148 case MachineState_TeleportingPausedVM:
6149 case MachineState_Saving:
6150 return setError(VBOX_E_INVALID_VM_STATE, tr("Already paused"));
6151
6152 default:
6153 return i_setInvalidMachineStateError();
6154 }
6155
6156 /* get the VM handle. */
6157 SafeVMPtr ptrVM(this);
6158 if (!ptrVM.isOk())
6159 return ptrVM.rc();
6160
6161 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
6162 alock.release();
6163
6164 LogFlowThisFunc(("Sending PAUSE request...\n"));
6165 if (aReason != Reason_Unspecified)
6166 LogRel(("Pausing VM execution, reason \"%s\"\n", Global::stringifyReason(aReason)));
6167
6168 /** @todo r=klaus make use of aReason */
6169 VMSUSPENDREASON enmReason = VMSUSPENDREASON_USER;
6170 if (aReason == Reason_HostSuspend)
6171 enmReason = VMSUSPENDREASON_HOST_SUSPEND;
6172 else if (aReason == Reason_HostBatteryLow)
6173 enmReason = VMSUSPENDREASON_HOST_BATTERY_LOW;
6174 int vrc = VMR3Suspend(ptrVM.rawUVM(), enmReason);
6175
6176 HRESULT hrc = S_OK;
6177 if (RT_FAILURE(vrc))
6178 hrc = setError(VBOX_E_VM_ERROR, tr("Could not suspend the machine execution (%Rrc)"), vrc);
6179 else
6180 {
6181 /* Unconfigure disk encryption from all attachments. */
6182 i_clearDiskEncryptionKeysOnAllAttachments();
6183
6184 /* Clear any keys we have stored. */
6185 for (SecretKeyMap::iterator it = m_mapSecretKeys.begin();
6186 it != m_mapSecretKeys.end();
6187 it++)
6188 delete it->second;
6189 m_mapSecretKeys.clear();
6190 }
6191
6192 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
6193 LogFlowThisFuncLeave();
6194 return hrc;
6195}
6196
6197/**
6198 * Worker for Console::Resume and internal entry point for resuming a VM for
6199 * a specific reason.
6200 */
6201HRESULT Console::i_resume(Reason_T aReason)
6202{
6203 LogFlowThisFuncEnter();
6204
6205 AutoCaller autoCaller(this);
6206 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6207
6208 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6209
6210 if (mMachineState != MachineState_Paused)
6211 return setError(VBOX_E_INVALID_VM_STATE,
6212 tr("Cannot resume the machine as it is not paused (machine state: %s)"),
6213 Global::stringifyMachineState(mMachineState));
6214
6215 /* get the VM handle. */
6216 SafeVMPtr ptrVM(this);
6217 if (!ptrVM.isOk())
6218 return ptrVM.rc();
6219
6220 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
6221 alock.release();
6222
6223 LogFlowThisFunc(("Sending RESUME request...\n"));
6224 if (aReason != Reason_Unspecified)
6225 LogRel(("Resuming VM execution, reason \"%s\"\n", Global::stringifyReason(aReason)));
6226
6227 int vrc;
6228 if (VMR3GetStateU(ptrVM.rawUVM()) == VMSTATE_CREATED)
6229 {
6230#ifdef VBOX_WITH_EXTPACK
6231 vrc = mptrExtPackManager->i_callAllVmPowerOnHooks(this, VMR3GetVM(ptrVM.rawUVM()));
6232#else
6233 vrc = VINF_SUCCESS;
6234#endif
6235 if (RT_SUCCESS(vrc))
6236 vrc = VMR3PowerOn(ptrVM.rawUVM()); /* (PowerUpPaused) */
6237 }
6238 else
6239 {
6240 VMRESUMEREASON enmReason = VMRESUMEREASON_USER;
6241 if (aReason == Reason_HostResume)
6242 enmReason = VMRESUMEREASON_HOST_RESUME;
6243 vrc = VMR3Resume(ptrVM.rawUVM(), enmReason);
6244 }
6245
6246 HRESULT rc = RT_SUCCESS(vrc) ? S_OK :
6247 setError(VBOX_E_VM_ERROR,
6248 tr("Could not resume the machine execution (%Rrc)"),
6249 vrc);
6250
6251 LogFlowThisFunc(("rc=%Rhrc\n", rc));
6252 LogFlowThisFuncLeave();
6253 return rc;
6254}
6255
6256/**
6257 * Worker for Console::SaveState and internal entry point for saving state of
6258 * a VM for a specific reason.
6259 */
6260HRESULT Console::i_saveState(Reason_T aReason, IProgress **aProgress)
6261{
6262 LogFlowThisFuncEnter();
6263
6264 CheckComArgOutPointerValid(aProgress);
6265
6266 AutoCaller autoCaller(this);
6267 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6268
6269 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6270
6271 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
6272 if ( mMachineState != MachineState_Running
6273 && mMachineState != MachineState_Paused)
6274 {
6275 return setError(VBOX_E_INVALID_VM_STATE,
6276 tr("Cannot save the execution state as the machine is not running or paused (machine state: %s)"),
6277 Global::stringifyMachineState(mMachineState));
6278 }
6279
6280 Bstr strDisableSaveState;
6281 mMachine->GetExtraData(Bstr("VBoxInternal2/DisableSaveState").raw(), strDisableSaveState.asOutParam());
6282 if (strDisableSaveState == "1")
6283 return setError(VBOX_E_VM_ERROR,
6284 tr("Saving the execution state is disabled for this VM"));
6285
6286 if (aReason != Reason_Unspecified)
6287 LogRel(("Saving state of VM, reason \"%s\"\n", Global::stringifyReason(aReason)));
6288
6289 /* memorize the current machine state */
6290 MachineState_T lastMachineState = mMachineState;
6291
6292 if (mMachineState == MachineState_Running)
6293 {
6294 /* get the VM handle. */
6295 SafeVMPtr ptrVM(this);
6296 if (!ptrVM.isOk())
6297 return ptrVM.rc();
6298
6299 /* release the lock before a VMR3* call (EMT might wait for it, @bugref{7648})! */
6300 alock.release();
6301 VMSUSPENDREASON enmReason = VMSUSPENDREASON_USER;
6302 if (aReason == Reason_HostSuspend)
6303 enmReason = VMSUSPENDREASON_HOST_SUSPEND;
6304 else if (aReason == Reason_HostBatteryLow)
6305 enmReason = VMSUSPENDREASON_HOST_BATTERY_LOW;
6306 int vrc = VMR3Suspend(ptrVM.rawUVM(), enmReason);
6307 alock.acquire();
6308
6309 HRESULT hrc = S_OK;
6310 if (RT_FAILURE(vrc))
6311 hrc = setError(VBOX_E_VM_ERROR, tr("Could not suspend the machine execution (%Rrc)"), vrc);
6312 if (FAILED(hrc))
6313 return hrc;
6314 }
6315
6316 HRESULT rc = S_OK;
6317 bool fBeganSavingState = false;
6318 bool fTaskCreationFailed = false;
6319
6320 do
6321 {
6322 ComPtr<IProgress> pProgress;
6323 Bstr stateFilePath;
6324
6325 /*
6326 * request a saved state file path from the server
6327 * (this will set the machine state to Saving on the server to block
6328 * others from accessing this machine)
6329 */
6330 rc = mControl->BeginSavingState(pProgress.asOutParam(),
6331 stateFilePath.asOutParam());
6332 if (FAILED(rc))
6333 break;
6334
6335 fBeganSavingState = true;
6336
6337 /* sync the state with the server */
6338 i_setMachineStateLocally(MachineState_Saving);
6339
6340 /* ensure the directory for the saved state file exists */
6341 {
6342 Utf8Str dir = stateFilePath;
6343 dir.stripFilename();
6344 if (!RTDirExists(dir.c_str()))
6345 {
6346 int vrc = RTDirCreateFullPath(dir.c_str(), 0700);
6347 if (RT_FAILURE(vrc))
6348 {
6349 rc = setError(VBOX_E_FILE_ERROR,
6350 tr("Could not create a directory '%s' to save the state to (%Rrc)"),
6351 dir.c_str(), vrc);
6352 break;
6353 }
6354 }
6355 }
6356
6357 /* Create a task object early to ensure mpUVM protection is successful. */
6358 std::auto_ptr<VMSaveTask> task(new VMSaveTask(this, pProgress,
6359 stateFilePath,
6360 lastMachineState,
6361 aReason));
6362 rc = task->rc();
6363 /*
6364 * If we fail here it means a PowerDown() call happened on another
6365 * thread while we were doing Pause() (which releases the Console lock).
6366 * We assign PowerDown() a higher precedence than SaveState(),
6367 * therefore just return the error to the caller.
6368 */
6369 if (FAILED(rc))
6370 {
6371 fTaskCreationFailed = true;
6372 break;
6373 }
6374
6375 /* create a thread to wait until the VM state is saved */
6376 int vrc = RTThreadCreate(NULL, Console::i_saveStateThread, (void *)task.get(),
6377 0, RTTHREADTYPE_MAIN_WORKER, 0, "VMSave");
6378 if (RT_FAILURE(vrc))
6379 {
6380 rc = setError(E_FAIL, "Could not create VMSave thread (%Rrc)", vrc);
6381 break;
6382 }
6383
6384 /* task is now owned by saveStateThread(), so release it */
6385 task.release();
6386
6387 /* return the progress to the caller */
6388 pProgress.queryInterfaceTo(aProgress);
6389 } while (0);
6390
6391 if (FAILED(rc) && !fTaskCreationFailed)
6392 {
6393 /* preserve existing error info */
6394 ErrorInfoKeeper eik;
6395
6396 if (fBeganSavingState)
6397 {
6398 /*
6399 * cancel the requested save state procedure.
6400 * This will reset the machine state to the state it had right
6401 * before calling mControl->BeginSavingState().
6402 */
6403 mControl->EndSavingState(eik.getResultCode(), eik.getText().raw());
6404 }
6405
6406 if (lastMachineState == MachineState_Running)
6407 {
6408 /* restore the paused state if appropriate */
6409 i_setMachineStateLocally(MachineState_Paused);
6410 /* restore the running state if appropriate */
6411 SafeVMPtr ptrVM(this);
6412 if (ptrVM.isOk())
6413 {
6414 alock.release();
6415 VMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_STATE_RESTORED);
6416 alock.acquire();
6417 }
6418 }
6419 else
6420 i_setMachineStateLocally(lastMachineState);
6421 }
6422
6423 LogFlowThisFunc(("rc=%Rhrc\n", rc));
6424 LogFlowThisFuncLeave();
6425 return rc;
6426}
6427
6428/**
6429 * Gets called by Session::UpdateMachineState()
6430 * (IInternalSessionControl::updateMachineState()).
6431 *
6432 * Must be called only in certain cases (see the implementation).
6433 *
6434 * @note Locks this object for writing.
6435 */
6436HRESULT Console::i_updateMachineState(MachineState_T aMachineState)
6437{
6438 AutoCaller autoCaller(this);
6439 AssertComRCReturnRC(autoCaller.rc());
6440
6441 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6442
6443 AssertReturn( mMachineState == MachineState_Saving
6444 || mMachineState == MachineState_LiveSnapshotting
6445 || mMachineState == MachineState_RestoringSnapshot
6446 || mMachineState == MachineState_DeletingSnapshot
6447 || mMachineState == MachineState_DeletingSnapshotOnline
6448 || mMachineState == MachineState_DeletingSnapshotPaused
6449 , E_FAIL);
6450
6451 return i_setMachineStateLocally(aMachineState);
6452}
6453
6454void Console::i_onMousePointerShapeChange(bool fVisible, bool fAlpha,
6455 uint32_t xHot, uint32_t yHot,
6456 uint32_t width, uint32_t height,
6457 const uint8_t *pu8Shape,
6458 uint32_t cbShape)
6459{
6460#if 0
6461 LogFlowThisFuncEnter();
6462 LogFlowThisFunc(("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, height=%d, shape=%p\n",
6463 fVisible, fAlpha, xHot, yHot, width, height, pShape));
6464#endif
6465
6466 AutoCaller autoCaller(this);
6467 AssertComRCReturnVoid(autoCaller.rc());
6468
6469 if (!mMouse.isNull())
6470 mMouse->updateMousePointerShape(fVisible, fAlpha, xHot, yHot, width, height,
6471 pu8Shape, cbShape);
6472
6473 com::SafeArray<BYTE> shape(cbShape);
6474 if (pu8Shape)
6475 memcpy(shape.raw(), pu8Shape, cbShape);
6476 fireMousePointerShapeChangedEvent(mEventSource, fVisible, fAlpha, xHot, yHot, width, height, ComSafeArrayAsInParam(shape));
6477
6478#if 0
6479 LogFlowThisFuncLeave();
6480#endif
6481}
6482
6483void Console::i_onMouseCapabilityChange(BOOL supportsAbsolute, BOOL supportsRelative,
6484 BOOL supportsMT, BOOL needsHostCursor)
6485{
6486 LogFlowThisFunc(("supportsAbsolute=%d supportsRelative=%d needsHostCursor=%d\n",
6487 supportsAbsolute, supportsRelative, needsHostCursor));
6488
6489 AutoCaller autoCaller(this);
6490 AssertComRCReturnVoid(autoCaller.rc());
6491
6492 fireMouseCapabilityChangedEvent(mEventSource, supportsAbsolute, supportsRelative, supportsMT, needsHostCursor);
6493}
6494
6495void Console::i_onStateChange(MachineState_T machineState)
6496{
6497 AutoCaller autoCaller(this);
6498 AssertComRCReturnVoid(autoCaller.rc());
6499 fireStateChangedEvent(mEventSource, machineState);
6500}
6501
6502void Console::i_onAdditionsStateChange()
6503{
6504 AutoCaller autoCaller(this);
6505 AssertComRCReturnVoid(autoCaller.rc());
6506
6507 fireAdditionsStateChangedEvent(mEventSource);
6508}
6509
6510/**
6511 * @remarks This notification only is for reporting an incompatible
6512 * Guest Additions interface, *not* the Guest Additions version!
6513 *
6514 * The user will be notified inside the guest if new Guest
6515 * Additions are available (via VBoxTray/VBoxClient).
6516 */
6517void Console::i_onAdditionsOutdated()
6518{
6519 AutoCaller autoCaller(this);
6520 AssertComRCReturnVoid(autoCaller.rc());
6521
6522 /** @todo implement this */
6523}
6524
6525void Console::i_onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
6526{
6527 AutoCaller autoCaller(this);
6528 AssertComRCReturnVoid(autoCaller.rc());
6529
6530 fireKeyboardLedsChangedEvent(mEventSource, fNumLock, fCapsLock, fScrollLock);
6531}
6532
6533void Console::i_onUSBDeviceStateChange(IUSBDevice *aDevice, bool aAttached,
6534 IVirtualBoxErrorInfo *aError)
6535{
6536 AutoCaller autoCaller(this);
6537 AssertComRCReturnVoid(autoCaller.rc());
6538
6539 fireUSBDeviceStateChangedEvent(mEventSource, aDevice, aAttached, aError);
6540}
6541
6542void Console::i_onRuntimeError(BOOL aFatal, IN_BSTR aErrorID, IN_BSTR aMessage)
6543{
6544 AutoCaller autoCaller(this);
6545 AssertComRCReturnVoid(autoCaller.rc());
6546
6547 fireRuntimeErrorEvent(mEventSource, aFatal, aErrorID, aMessage);
6548}
6549
6550HRESULT Console::i_onShowWindow(BOOL aCheck, BOOL *aCanShow, LONG64 *aWinId)
6551{
6552 AssertReturn(aCanShow, E_POINTER);
6553 AssertReturn(aWinId, E_POINTER);
6554
6555 *aCanShow = FALSE;
6556 *aWinId = 0;
6557
6558 AutoCaller autoCaller(this);
6559 AssertComRCReturnRC(autoCaller.rc());
6560
6561 VBoxEventDesc evDesc;
6562 if (aCheck)
6563 {
6564 evDesc.init(mEventSource, VBoxEventType_OnCanShowWindow);
6565 BOOL fDelivered = evDesc.fire(5000); /* Wait up to 5 secs for delivery */
6566 //Assert(fDelivered);
6567 if (fDelivered)
6568 {
6569 ComPtr<IEvent> pEvent;
6570 evDesc.getEvent(pEvent.asOutParam());
6571 // bit clumsy
6572 ComPtr<ICanShowWindowEvent> pCanShowEvent = pEvent;
6573 if (pCanShowEvent)
6574 {
6575 BOOL fVetoed = FALSE;
6576 pCanShowEvent->IsVetoed(&fVetoed);
6577 *aCanShow = !fVetoed;
6578 }
6579 else
6580 {
6581 AssertFailed();
6582 *aCanShow = TRUE;
6583 }
6584 }
6585 else
6586 *aCanShow = TRUE;
6587 }
6588 else
6589 {
6590 evDesc.init(mEventSource, VBoxEventType_OnShowWindow, INT64_C(0));
6591 BOOL fDelivered = evDesc.fire(5000); /* Wait up to 5 secs for delivery */
6592 //Assert(fDelivered);
6593 if (fDelivered)
6594 {
6595 ComPtr<IEvent> pEvent;
6596 evDesc.getEvent(pEvent.asOutParam());
6597 ComPtr<IShowWindowEvent> pShowEvent = pEvent;
6598 if (pShowEvent)
6599 {
6600 LONG64 iEvWinId = 0;
6601 pShowEvent->COMGETTER(WinId)(&iEvWinId);
6602 if (iEvWinId != 0 && *aWinId == 0)
6603 *aWinId = iEvWinId;
6604 }
6605 else
6606 AssertFailed();
6607 }
6608 }
6609
6610 return S_OK;
6611}
6612
6613// private methods
6614////////////////////////////////////////////////////////////////////////////////
6615
6616/**
6617 * Increases the usage counter of the mpUVM pointer.
6618 *
6619 * Guarantees that VMR3Destroy() will not be called on it at least until
6620 * releaseVMCaller() is called.
6621 *
6622 * If this method returns a failure, the caller is not allowed to use mpUVM and
6623 * may return the failed result code to the upper level. This method sets the
6624 * extended error info on failure if \a aQuiet is false.
6625 *
6626 * Setting \a aQuiet to true is useful for methods that don't want to return
6627 * the failed result code to the caller when this method fails (e.g. need to
6628 * silently check for the mpUVM availability).
6629 *
6630 * When mpUVM is NULL but \a aAllowNullVM is true, a corresponding error will be
6631 * returned instead of asserting. Having it false is intended as a sanity check
6632 * for methods that have checked mMachineState and expect mpUVM *NOT* to be
6633 * NULL.
6634 *
6635 * @param aQuiet true to suppress setting error info
6636 * @param aAllowNullVM true to accept mpUVM being NULL and return a failure
6637 * (otherwise this method will assert if mpUVM is NULL)
6638 *
6639 * @note Locks this object for writing.
6640 */
6641HRESULT Console::i_addVMCaller(bool aQuiet /* = false */,
6642 bool aAllowNullVM /* = false */)
6643{
6644 AutoCaller autoCaller(this);
6645 /** @todo Fix race during console/VM reference destruction, refer @bugref{6318}
6646 * comment 25. */
6647 if (FAILED(autoCaller.rc()))
6648 return autoCaller.rc();
6649
6650 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6651
6652 if (mVMDestroying)
6653 {
6654 /* powerDown() is waiting for all callers to finish */
6655 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED,
6656 tr("The virtual machine is being powered down"));
6657 }
6658
6659 if (mpUVM == NULL)
6660 {
6661 Assert(aAllowNullVM == true);
6662
6663 /* The machine is not powered up */
6664 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED,
6665 tr("The virtual machine is not powered up"));
6666 }
6667
6668 ++mVMCallers;
6669
6670 return S_OK;
6671}
6672
6673/**
6674 * Decreases the usage counter of the mpUVM pointer.
6675 *
6676 * Must always complete the addVMCaller() call after the mpUVM pointer is no
6677 * more necessary.
6678 *
6679 * @note Locks this object for writing.
6680 */
6681void Console::i_releaseVMCaller()
6682{
6683 AutoCaller autoCaller(this);
6684 AssertComRCReturnVoid(autoCaller.rc());
6685
6686 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6687
6688 AssertReturnVoid(mpUVM != NULL);
6689
6690 Assert(mVMCallers > 0);
6691 --mVMCallers;
6692
6693 if (mVMCallers == 0 && mVMDestroying)
6694 {
6695 /* inform powerDown() there are no more callers */
6696 RTSemEventSignal(mVMZeroCallersSem);
6697 }
6698}
6699
6700
6701HRESULT Console::i_safeVMPtrRetainer(PUVM *a_ppUVM, bool a_Quiet)
6702{
6703 *a_ppUVM = NULL;
6704
6705 AutoCaller autoCaller(this);
6706 AssertComRCReturnRC(autoCaller.rc());
6707 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6708
6709 /*
6710 * Repeat the checks done by addVMCaller.
6711 */
6712 if (mVMDestroying) /* powerDown() is waiting for all callers to finish */
6713 return a_Quiet
6714 ? E_ACCESSDENIED
6715 : setError(E_ACCESSDENIED, tr("The virtual machine is being powered down"));
6716 PUVM pUVM = mpUVM;
6717 if (!pUVM)
6718 return a_Quiet
6719 ? E_ACCESSDENIED
6720 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
6721
6722 /*
6723 * Retain a reference to the user mode VM handle and get the global handle.
6724 */
6725 uint32_t cRefs = VMR3RetainUVM(pUVM);
6726 if (cRefs == UINT32_MAX)
6727 return a_Quiet
6728 ? E_ACCESSDENIED
6729 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
6730
6731 /* done */
6732 *a_ppUVM = pUVM;
6733 return S_OK;
6734}
6735
6736void Console::i_safeVMPtrReleaser(PUVM *a_ppUVM)
6737{
6738 if (*a_ppUVM)
6739 VMR3ReleaseUVM(*a_ppUVM);
6740 *a_ppUVM = NULL;
6741}
6742
6743
6744/**
6745 * Initialize the release logging facility. In case something
6746 * goes wrong, there will be no release logging. Maybe in the future
6747 * we can add some logic to use different file names in this case.
6748 * Note that the logic must be in sync with Machine::DeleteSettings().
6749 */
6750HRESULT Console::i_consoleInitReleaseLog(const ComPtr<IMachine> aMachine)
6751{
6752 HRESULT hrc = S_OK;
6753
6754 Bstr logFolder;
6755 hrc = aMachine->COMGETTER(LogFolder)(logFolder.asOutParam());
6756 if (FAILED(hrc))
6757 return hrc;
6758
6759 Utf8Str logDir = logFolder;
6760
6761 /* make sure the Logs folder exists */
6762 Assert(logDir.length());
6763 if (!RTDirExists(logDir.c_str()))
6764 RTDirCreateFullPath(logDir.c_str(), 0700);
6765
6766 Utf8Str logFile = Utf8StrFmt("%s%cVBox.log",
6767 logDir.c_str(), RTPATH_DELIMITER);
6768 Utf8Str pngFile = Utf8StrFmt("%s%cVBox.png",
6769 logDir.c_str(), RTPATH_DELIMITER);
6770
6771 /*
6772 * Age the old log files
6773 * Rename .(n-1) to .(n), .(n-2) to .(n-1), ..., and the last log file to .1
6774 * Overwrite target files in case they exist.
6775 */
6776 ComPtr<IVirtualBox> pVirtualBox;
6777 aMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
6778 ComPtr<ISystemProperties> pSystemProperties;
6779 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
6780 ULONG cHistoryFiles = 3;
6781 pSystemProperties->COMGETTER(LogHistoryCount)(&cHistoryFiles);
6782 if (cHistoryFiles)
6783 {
6784 for (int i = cHistoryFiles-1; i >= 0; i--)
6785 {
6786 Utf8Str *files[] = { &logFile, &pngFile };
6787 Utf8Str oldName, newName;
6788
6789 for (unsigned int j = 0; j < RT_ELEMENTS(files); ++j)
6790 {
6791 if (i > 0)
6792 oldName = Utf8StrFmt("%s.%d", files[j]->c_str(), i);
6793 else
6794 oldName = *files[j];
6795 newName = Utf8StrFmt("%s.%d", files[j]->c_str(), i + 1);
6796 /* If the old file doesn't exist, delete the new file (if it
6797 * exists) to provide correct rotation even if the sequence is
6798 * broken */
6799 if ( RTFileRename(oldName.c_str(), newName.c_str(), RTFILEMOVE_FLAGS_REPLACE)
6800 == VERR_FILE_NOT_FOUND)
6801 RTFileDelete(newName.c_str());
6802 }
6803 }
6804 }
6805
6806 char szError[RTPATH_MAX + 128];
6807 int vrc = com::VBoxLogRelCreate("VM", logFile.c_str(),
6808 RTLOGFLAGS_PREFIX_TIME_PROG | RTLOGFLAGS_RESTRICT_GROUPS,
6809 "all all.restrict -default.restrict",
6810 "VBOX_RELEASE_LOG", RTLOGDEST_FILE,
6811 32768 /* cMaxEntriesPerGroup */,
6812 0 /* cHistory */, 0 /* uHistoryFileTime */,
6813 0 /* uHistoryFileSize */, szError, sizeof(szError));
6814 if (RT_FAILURE(vrc))
6815 hrc = setError(E_FAIL, tr("Failed to open release log (%s, %Rrc)"),
6816 szError, vrc);
6817
6818 /* If we've made any directory changes, flush the directory to increase
6819 the likelihood that the log file will be usable after a system panic.
6820
6821 Tip: Try 'export VBOX_RELEASE_LOG_FLAGS=flush' if the last bits of the log
6822 is missing. Just don't have too high hopes for this to help. */
6823 if (SUCCEEDED(hrc) || cHistoryFiles)
6824 RTDirFlush(logDir.c_str());
6825
6826 return hrc;
6827}
6828
6829/**
6830 * Common worker for PowerUp and PowerUpPaused.
6831 *
6832 * @returns COM status code.
6833 *
6834 * @param aProgress Where to return the progress object.
6835 * @param aPaused true if PowerUpPaused called.
6836 */
6837HRESULT Console::i_powerUp(IProgress **aProgress, bool aPaused)
6838{
6839
6840 LogFlowThisFuncEnter();
6841
6842 CheckComArgOutPointerValid(aProgress);
6843
6844 AutoCaller autoCaller(this);
6845 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6846
6847 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6848
6849 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
6850 HRESULT rc = S_OK;
6851 ComObjPtr<Progress> pPowerupProgress;
6852 bool fBeganPoweringUp = false;
6853
6854 LONG cOperations = 1;
6855 LONG ulTotalOperationsWeight = 1;
6856
6857 try
6858 {
6859
6860 if (Global::IsOnlineOrTransient(mMachineState))
6861 throw setError(VBOX_E_INVALID_VM_STATE,
6862 tr("The virtual machine is already running or busy (machine state: %s)"),
6863 Global::stringifyMachineState(mMachineState));
6864
6865 /* Set up release logging as early as possible after the check if
6866 * there is already a running VM which we shouldn't disturb. */
6867 rc = i_consoleInitReleaseLog(mMachine);
6868 if (FAILED(rc))
6869 throw rc;
6870
6871#ifdef VBOX_OPENSSL_FIPS
6872 LogRel(("crypto: FIPS mode %s\n", FIPS_mode() ? "enabled" : "FAILED"));
6873#endif
6874
6875 /* test and clear the TeleporterEnabled property */
6876 BOOL fTeleporterEnabled;
6877 rc = mMachine->COMGETTER(TeleporterEnabled)(&fTeleporterEnabled);
6878 if (FAILED(rc))
6879 throw rc;
6880
6881#if 0 /** @todo we should save it afterwards, but that isn't necessarily a good idea. Find a better place for this (VBoxSVC). */
6882 if (fTeleporterEnabled)
6883 {
6884 rc = mMachine->COMSETTER(TeleporterEnabled)(FALSE);
6885 if (FAILED(rc))
6886 throw rc;
6887 }
6888#endif
6889
6890 /* test the FaultToleranceState property */
6891 FaultToleranceState_T enmFaultToleranceState;
6892 rc = mMachine->COMGETTER(FaultToleranceState)(&enmFaultToleranceState);
6893 if (FAILED(rc))
6894 throw rc;
6895 BOOL fFaultToleranceSyncEnabled = (enmFaultToleranceState == FaultToleranceState_Standby);
6896
6897 /* Create a progress object to track progress of this operation. Must
6898 * be done as early as possible (together with BeginPowerUp()) as this
6899 * is vital for communicating as much as possible early powerup
6900 * failure information to the API caller */
6901 pPowerupProgress.createObject();
6902 Bstr progressDesc;
6903 if (mMachineState == MachineState_Saved)
6904 progressDesc = tr("Restoring virtual machine");
6905 else if (fTeleporterEnabled)
6906 progressDesc = tr("Teleporting virtual machine");
6907 else if (fFaultToleranceSyncEnabled)
6908 progressDesc = tr("Fault Tolerance syncing of remote virtual machine");
6909 else
6910 progressDesc = tr("Starting virtual machine");
6911
6912 Bstr savedStateFile;
6913
6914 /*
6915 * Saved VMs will have to prove that their saved states seem kosher.
6916 */
6917 if (mMachineState == MachineState_Saved)
6918 {
6919 rc = mMachine->COMGETTER(StateFilePath)(savedStateFile.asOutParam());
6920 if (FAILED(rc))
6921 throw rc;
6922 ComAssertRet(!savedStateFile.isEmpty(), E_FAIL);
6923 int vrc = SSMR3ValidateFile(Utf8Str(savedStateFile).c_str(), false /* fChecksumIt */);
6924 if (RT_FAILURE(vrc))
6925 throw setError(VBOX_E_FILE_ERROR,
6926 tr("VM cannot start because the saved state file '%ls' is invalid (%Rrc). Delete the saved state prior to starting the VM"),
6927 savedStateFile.raw(), vrc);
6928 }
6929
6930 /* Read console data, including console shared folders, stored in the
6931 * saved state file (if not yet done).
6932 */
6933 rc = i_loadDataFromSavedState();
6934 if (FAILED(rc))
6935 throw rc;
6936
6937 /* Check all types of shared folders and compose a single list */
6938 SharedFolderDataMap sharedFolders;
6939 {
6940 /* first, insert global folders */
6941 for (SharedFolderDataMap::const_iterator it = m_mapGlobalSharedFolders.begin();
6942 it != m_mapGlobalSharedFolders.end();
6943 ++it)
6944 {
6945 const SharedFolderData &d = it->second;
6946 sharedFolders[it->first] = d;
6947 }
6948
6949 /* second, insert machine folders */
6950 for (SharedFolderDataMap::const_iterator it = m_mapMachineSharedFolders.begin();
6951 it != m_mapMachineSharedFolders.end();
6952 ++it)
6953 {
6954 const SharedFolderData &d = it->second;
6955 sharedFolders[it->first] = d;
6956 }
6957
6958 /* third, insert console folders */
6959 for (SharedFolderMap::const_iterator it = m_mapSharedFolders.begin();
6960 it != m_mapSharedFolders.end();
6961 ++it)
6962 {
6963 SharedFolder *pSF = it->second;
6964 AutoCaller sfCaller(pSF);
6965 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
6966 sharedFolders[it->first] = SharedFolderData(pSF->i_getHostPath(),
6967 pSF->i_isWritable(),
6968 pSF->i_isAutoMounted());
6969 }
6970 }
6971
6972 /* Setup task object and thread to carry out the operaton
6973 * Asycnhronously */
6974 std::auto_ptr<VMPowerUpTask> task(new VMPowerUpTask(this, pPowerupProgress));
6975 ComAssertComRCRetRC(task->rc());
6976
6977 task->mConfigConstructor = i_configConstructor;
6978 task->mSharedFolders = sharedFolders;
6979 task->mStartPaused = aPaused;
6980 if (mMachineState == MachineState_Saved)
6981 task->mSavedStateFile = savedStateFile;
6982 task->mTeleporterEnabled = fTeleporterEnabled;
6983 task->mEnmFaultToleranceState = enmFaultToleranceState;
6984
6985 /* Reset differencing hard disks for which autoReset is true,
6986 * but only if the machine has no snapshots OR the current snapshot
6987 * is an OFFLINE snapshot; otherwise we would reset the current
6988 * differencing image of an ONLINE snapshot which contains the disk
6989 * state of the machine while it was previously running, but without
6990 * the corresponding machine state, which is equivalent to powering
6991 * off a running machine and not good idea
6992 */
6993 ComPtr<ISnapshot> pCurrentSnapshot;
6994 rc = mMachine->COMGETTER(CurrentSnapshot)(pCurrentSnapshot.asOutParam());
6995 if (FAILED(rc))
6996 throw rc;
6997
6998 BOOL fCurrentSnapshotIsOnline = false;
6999 if (pCurrentSnapshot)
7000 {
7001 rc = pCurrentSnapshot->COMGETTER(Online)(&fCurrentSnapshotIsOnline);
7002 if (FAILED(rc))
7003 throw rc;
7004 }
7005
7006 if (!fCurrentSnapshotIsOnline)
7007 {
7008 LogFlowThisFunc(("Looking for immutable images to reset\n"));
7009
7010 com::SafeIfaceArray<IMediumAttachment> atts;
7011 rc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
7012 if (FAILED(rc))
7013 throw rc;
7014
7015 for (size_t i = 0;
7016 i < atts.size();
7017 ++i)
7018 {
7019 DeviceType_T devType;
7020 rc = atts[i]->COMGETTER(Type)(&devType);
7021 /** @todo later applies to floppies as well */
7022 if (devType == DeviceType_HardDisk)
7023 {
7024 ComPtr<IMedium> pMedium;
7025 rc = atts[i]->COMGETTER(Medium)(pMedium.asOutParam());
7026 if (FAILED(rc))
7027 throw rc;
7028
7029 /* needs autoreset? */
7030 BOOL autoReset = FALSE;
7031 rc = pMedium->COMGETTER(AutoReset)(&autoReset);
7032 if (FAILED(rc))
7033 throw rc;
7034
7035 if (autoReset)
7036 {
7037 ComPtr<IProgress> pResetProgress;
7038 rc = pMedium->Reset(pResetProgress.asOutParam());
7039 if (FAILED(rc))
7040 throw rc;
7041
7042 /* save for later use on the powerup thread */
7043 task->hardDiskProgresses.push_back(pResetProgress);
7044 }
7045 }
7046 }
7047 }
7048 else
7049 LogFlowThisFunc(("Machine has a current snapshot which is online, skipping immutable images reset\n"));
7050
7051 /* setup task object and thread to carry out the operation
7052 * asynchronously */
7053
7054#ifdef VBOX_WITH_EXTPACK
7055 mptrExtPackManager->i_dumpAllToReleaseLog();
7056#endif
7057
7058#ifdef RT_OS_SOLARIS
7059 /* setup host core dumper for the VM */
7060 Bstr value;
7061 HRESULT hrc = mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpEnabled").raw(), value.asOutParam());
7062 if (SUCCEEDED(hrc) && value == "1")
7063 {
7064 Bstr coreDumpDir, coreDumpReplaceSys, coreDumpLive;
7065 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpDir").raw(), coreDumpDir.asOutParam());
7066 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpReplaceSystemDump").raw(), coreDumpReplaceSys.asOutParam());
7067 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpLive").raw(), coreDumpLive.asOutParam());
7068
7069 uint32_t fCoreFlags = 0;
7070 if ( coreDumpReplaceSys.isEmpty() == false
7071 && Utf8Str(coreDumpReplaceSys).toUInt32() == 1)
7072 fCoreFlags |= RTCOREDUMPER_FLAGS_REPLACE_SYSTEM_DUMP;
7073
7074 if ( coreDumpLive.isEmpty() == false
7075 && Utf8Str(coreDumpLive).toUInt32() == 1)
7076 fCoreFlags |= RTCOREDUMPER_FLAGS_LIVE_CORE;
7077
7078 Utf8Str strDumpDir(coreDumpDir);
7079 const char *pszDumpDir = strDumpDir.c_str();
7080 if ( pszDumpDir
7081 && *pszDumpDir == '\0')
7082 pszDumpDir = NULL;
7083
7084 int vrc;
7085 if ( pszDumpDir
7086 && !RTDirExists(pszDumpDir))
7087 {
7088 /*
7089 * Try create the directory.
7090 */
7091 vrc = RTDirCreateFullPath(pszDumpDir, 0700);
7092 if (RT_FAILURE(vrc))
7093 throw setError(E_FAIL, "Failed to setup CoreDumper. Couldn't create dump directory '%s' (%Rrc)\n",
7094 pszDumpDir, vrc);
7095 }
7096
7097 vrc = RTCoreDumperSetup(pszDumpDir, fCoreFlags);
7098 if (RT_FAILURE(vrc))
7099 throw setError(E_FAIL, "Failed to setup CoreDumper (%Rrc)", vrc);
7100 else
7101 LogRel(("CoreDumper setup successful. pszDumpDir=%s fFlags=%#x\n", pszDumpDir ? pszDumpDir : ".", fCoreFlags));
7102 }
7103#endif
7104
7105
7106 // If there is immutable drive the process that.
7107 VMPowerUpTask::ProgressList progresses(task->hardDiskProgresses);
7108 if (aProgress && progresses.size() > 0){
7109
7110 for (VMPowerUpTask::ProgressList::const_iterator it = progresses.begin(); it != progresses.end(); ++it)
7111 {
7112 ++cOperations;
7113 ulTotalOperationsWeight += 1;
7114 }
7115 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7116 progressDesc.raw(),
7117 TRUE, // Cancelable
7118 cOperations,
7119 ulTotalOperationsWeight,
7120 Bstr(tr("Starting Hard Disk operations")).raw(),
7121 1);
7122 AssertComRCReturnRC(rc);
7123 }
7124 else if ( mMachineState == MachineState_Saved
7125 || (!fTeleporterEnabled && !fFaultToleranceSyncEnabled))
7126 {
7127 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7128 progressDesc.raw(),
7129 FALSE /* aCancelable */);
7130 }
7131 else if (fTeleporterEnabled)
7132 {
7133 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7134 progressDesc.raw(),
7135 TRUE /* aCancelable */,
7136 3 /* cOperations */,
7137 10 /* ulTotalOperationsWeight */,
7138 Bstr(tr("Teleporting virtual machine")).raw(),
7139 1 /* ulFirstOperationWeight */);
7140 }
7141 else if (fFaultToleranceSyncEnabled)
7142 {
7143 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
7144 progressDesc.raw(),
7145 TRUE /* aCancelable */,
7146 3 /* cOperations */,
7147 10 /* ulTotalOperationsWeight */,
7148 Bstr(tr("Fault Tolerance syncing of remote virtual machine")).raw(),
7149 1 /* ulFirstOperationWeight */);
7150 }
7151
7152 if (FAILED(rc))
7153 throw rc;
7154
7155 /* Tell VBoxSVC and Machine about the progress object so they can
7156 combine/proxy it to any openRemoteSession caller. */
7157 LogFlowThisFunc(("Calling BeginPowerUp...\n"));
7158 rc = mControl->BeginPowerUp(pPowerupProgress);
7159 if (FAILED(rc))
7160 {
7161 LogFlowThisFunc(("BeginPowerUp failed\n"));
7162 throw rc;
7163 }
7164 fBeganPoweringUp = true;
7165
7166 LogFlowThisFunc(("Checking if canceled...\n"));
7167 BOOL fCanceled;
7168 rc = pPowerupProgress->COMGETTER(Canceled)(&fCanceled);
7169 if (FAILED(rc))
7170 throw rc;
7171
7172 if (fCanceled)
7173 {
7174 LogFlowThisFunc(("Canceled in BeginPowerUp\n"));
7175 throw setError(E_FAIL, tr("Powerup was canceled"));
7176 }
7177 LogFlowThisFunc(("Not canceled yet.\n"));
7178
7179 /** @todo this code prevents starting a VM with unavailable bridged
7180 * networking interface. The only benefit is a slightly better error
7181 * message, which should be moved to the driver code. This is the
7182 * only reason why I left the code in for now. The driver allows
7183 * unavailable bridged networking interfaces in certain circumstances,
7184 * and this is sabotaged by this check. The VM will initially have no
7185 * network connectivity, but the user can fix this at runtime. */
7186#if 0
7187 /* the network cards will undergo a quick consistency check */
7188 for (ULONG slot = 0;
7189 slot < maxNetworkAdapters;
7190 ++slot)
7191 {
7192 ComPtr<INetworkAdapter> pNetworkAdapter;
7193 mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
7194 BOOL enabled = FALSE;
7195 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
7196 if (!enabled)
7197 continue;
7198
7199 NetworkAttachmentType_T netattach;
7200 pNetworkAdapter->COMGETTER(AttachmentType)(&netattach);
7201 switch (netattach)
7202 {
7203 case NetworkAttachmentType_Bridged:
7204 {
7205 /* a valid host interface must have been set */
7206 Bstr hostif;
7207 pNetworkAdapter->COMGETTER(HostInterface)(hostif.asOutParam());
7208 if (hostif.isEmpty())
7209 {
7210 throw setError(VBOX_E_HOST_ERROR,
7211 tr("VM cannot start because host interface networking requires a host interface name to be set"));
7212 }
7213 ComPtr<IVirtualBox> pVirtualBox;
7214 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
7215 ComPtr<IHost> pHost;
7216 pVirtualBox->COMGETTER(Host)(pHost.asOutParam());
7217 ComPtr<IHostNetworkInterface> pHostInterface;
7218 if (!SUCCEEDED(pHost->FindHostNetworkInterfaceByName(hostif.raw(),
7219 pHostInterface.asOutParam())))
7220 {
7221 throw setError(VBOX_E_HOST_ERROR,
7222 tr("VM cannot start because the host interface '%ls' does not exist"),
7223 hostif.raw());
7224 }
7225 break;
7226 }
7227 default:
7228 break;
7229 }
7230 }
7231#endif // 0
7232
7233 /* setup task object and thread to carry out the operation
7234 * asynchronously */
7235 if (aProgress){
7236 rc = pPowerupProgress.queryInterfaceTo(aProgress);
7237 AssertComRCReturnRC(rc);
7238 }
7239
7240 int vrc = RTThreadCreate(NULL, Console::i_powerUpThread,
7241 (void *)task.get(), 0,
7242 RTTHREADTYPE_MAIN_WORKER, 0, "VMPwrUp");
7243 if (RT_FAILURE(vrc))
7244 throw setError(E_FAIL, "Could not create VMPowerUp thread (%Rrc)", vrc);
7245
7246 /* task is now owned by powerUpThread(), so release it */
7247 task.release();
7248
7249 /* finally, set the state: no right to fail in this method afterwards
7250 * since we've already started the thread and it is now responsible for
7251 * any error reporting and appropriate state change! */
7252 if (mMachineState == MachineState_Saved)
7253 i_setMachineState(MachineState_Restoring);
7254 else if (fTeleporterEnabled)
7255 i_setMachineState(MachineState_TeleportingIn);
7256 else if (enmFaultToleranceState == FaultToleranceState_Standby)
7257 i_setMachineState(MachineState_FaultTolerantSyncing);
7258 else
7259 i_setMachineState(MachineState_Starting);
7260 }
7261 catch (HRESULT aRC) { rc = aRC; }
7262
7263 if (FAILED(rc) && fBeganPoweringUp)
7264 {
7265
7266 /* The progress object will fetch the current error info */
7267 if (!pPowerupProgress.isNull())
7268 pPowerupProgress->i_notifyComplete(rc);
7269
7270 /* Save the error info across the IPC below. Can't be done before the
7271 * progress notification above, as saving the error info deletes it
7272 * from the current context, and thus the progress object wouldn't be
7273 * updated correctly. */
7274 ErrorInfoKeeper eik;
7275
7276 /* signal end of operation */
7277 mControl->EndPowerUp(rc);
7278 }
7279
7280 LogFlowThisFunc(("mMachineState=%d, rc=%Rhrc\n", mMachineState, rc));
7281 LogFlowThisFuncLeave();
7282 return rc;
7283}
7284
7285/**
7286 * Internal power off worker routine.
7287 *
7288 * This method may be called only at certain places with the following meaning
7289 * as shown below:
7290 *
7291 * - if the machine state is either Running or Paused, a normal
7292 * Console-initiated powerdown takes place (e.g. PowerDown());
7293 * - if the machine state is Saving, saveStateThread() has successfully done its
7294 * job;
7295 * - if the machine state is Starting or Restoring, powerUpThread() has failed
7296 * to start/load the VM;
7297 * - if the machine state is Stopping, the VM has powered itself off (i.e. not
7298 * as a result of the powerDown() call).
7299 *
7300 * Calling it in situations other than the above will cause unexpected behavior.
7301 *
7302 * Note that this method should be the only one that destroys mpUVM and sets it
7303 * to NULL.
7304 *
7305 * @param aProgress Progress object to run (may be NULL).
7306 *
7307 * @note Locks this object for writing.
7308 *
7309 * @note Never call this method from a thread that called addVMCaller() or
7310 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
7311 * release(). Otherwise it will deadlock.
7312 */
7313HRESULT Console::i_powerDown(IProgress *aProgress /*= NULL*/)
7314{
7315 LogFlowThisFuncEnter();
7316
7317 AutoCaller autoCaller(this);
7318 AssertComRCReturnRC(autoCaller.rc());
7319
7320 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7321
7322 /* Total # of steps for the progress object. Must correspond to the
7323 * number of "advance percent count" comments in this method! */
7324 enum { StepCount = 7 };
7325 /* current step */
7326 ULONG step = 0;
7327
7328 HRESULT rc = S_OK;
7329 int vrc = VINF_SUCCESS;
7330
7331 /* sanity */
7332 Assert(mVMDestroying == false);
7333
7334 PUVM pUVM = mpUVM; Assert(pUVM != NULL);
7335 uint32_t cRefs = VMR3RetainUVM(pUVM); Assert(cRefs != UINT32_MAX);
7336
7337 AssertMsg( mMachineState == MachineState_Running
7338 || mMachineState == MachineState_Paused
7339 || mMachineState == MachineState_Stuck
7340 || mMachineState == MachineState_Starting
7341 || mMachineState == MachineState_Stopping
7342 || mMachineState == MachineState_Saving
7343 || mMachineState == MachineState_Restoring
7344 || mMachineState == MachineState_TeleportingPausedVM
7345 || mMachineState == MachineState_FaultTolerantSyncing
7346 || mMachineState == MachineState_TeleportingIn
7347 , ("Invalid machine state: %s\n", Global::stringifyMachineState(mMachineState)));
7348
7349 LogRel(("Console::powerDown(): A request to power off the VM has been issued (mMachineState=%s, InUninit=%d)\n",
7350 Global::stringifyMachineState(mMachineState), getObjectState().getState() == ObjectState::InUninit));
7351
7352 /* Check if we need to power off the VM. In case of mVMPoweredOff=true, the
7353 * VM has already powered itself off in vmstateChangeCallback() and is just
7354 * notifying Console about that. In case of Starting or Restoring,
7355 * powerUpThread() is calling us on failure, so the VM is already off at
7356 * that point. */
7357 if ( !mVMPoweredOff
7358 && ( mMachineState == MachineState_Starting
7359 || mMachineState == MachineState_Restoring
7360 || mMachineState == MachineState_FaultTolerantSyncing
7361 || mMachineState == MachineState_TeleportingIn)
7362 )
7363 mVMPoweredOff = true;
7364
7365 /*
7366 * Go to Stopping state if not already there.
7367 *
7368 * Note that we don't go from Saving/Restoring to Stopping because
7369 * vmstateChangeCallback() needs it to set the state to Saved on
7370 * VMSTATE_TERMINATED. In terms of protecting from inappropriate operations
7371 * while leaving the lock below, Saving or Restoring should be fine too.
7372 * Ditto for TeleportingPausedVM -> Teleported.
7373 */
7374 if ( mMachineState != MachineState_Saving
7375 && mMachineState != MachineState_Restoring
7376 && mMachineState != MachineState_Stopping
7377 && mMachineState != MachineState_TeleportingIn
7378 && mMachineState != MachineState_TeleportingPausedVM
7379 && mMachineState != MachineState_FaultTolerantSyncing
7380 )
7381 i_setMachineState(MachineState_Stopping);
7382
7383 /* ----------------------------------------------------------------------
7384 * DONE with necessary state changes, perform the power down actions (it's
7385 * safe to release the object lock now if needed)
7386 * ---------------------------------------------------------------------- */
7387
7388 if (mDisplay)
7389 {
7390 alock.release();
7391
7392 mDisplay->i_notifyPowerDown();
7393
7394 alock.acquire();
7395 }
7396
7397 /* Stop the VRDP server to prevent new clients connection while VM is being
7398 * powered off. */
7399 if (mConsoleVRDPServer)
7400 {
7401 LogFlowThisFunc(("Stopping VRDP server...\n"));
7402
7403 /* Leave the lock since EMT could call us back as addVMCaller() */
7404 alock.release();
7405
7406 mConsoleVRDPServer->Stop();
7407
7408 alock.acquire();
7409 }
7410
7411 /* advance percent count */
7412 if (aProgress)
7413 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount );
7414
7415
7416 /* ----------------------------------------------------------------------
7417 * Now, wait for all mpUVM callers to finish their work if there are still
7418 * some on other threads. NO methods that need mpUVM (or initiate other calls
7419 * that need it) may be called after this point
7420 * ---------------------------------------------------------------------- */
7421
7422 /* go to the destroying state to prevent from adding new callers */
7423 mVMDestroying = true;
7424
7425 if (mVMCallers > 0)
7426 {
7427 /* lazy creation */
7428 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
7429 RTSemEventCreate(&mVMZeroCallersSem);
7430
7431 LogFlowThisFunc(("Waiting for mpUVM callers (%d) to drop to zero...\n", mVMCallers));
7432
7433 alock.release();
7434
7435 RTSemEventWait(mVMZeroCallersSem, RT_INDEFINITE_WAIT);
7436
7437 alock.acquire();
7438 }
7439
7440 /* advance percent count */
7441 if (aProgress)
7442 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount );
7443
7444 vrc = VINF_SUCCESS;
7445
7446 /*
7447 * Power off the VM if not already done that.
7448 * Leave the lock since EMT will call vmstateChangeCallback.
7449 *
7450 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
7451 * VM-(guest-)initiated power off happened in parallel a ms before this
7452 * call. So far, we let this error pop up on the user's side.
7453 */
7454 if (!mVMPoweredOff)
7455 {
7456 LogFlowThisFunc(("Powering off the VM...\n"));
7457 alock.release();
7458 vrc = VMR3PowerOff(pUVM);
7459#ifdef VBOX_WITH_EXTPACK
7460 mptrExtPackManager->i_callAllVmPowerOffHooks(this, VMR3GetVM(pUVM));
7461#endif
7462 alock.acquire();
7463 }
7464
7465 /* advance percent count */
7466 if (aProgress)
7467 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount );
7468
7469#ifdef VBOX_WITH_HGCM
7470 /* Shutdown HGCM services before destroying the VM. */
7471 if (m_pVMMDev)
7472 {
7473 LogFlowThisFunc(("Shutdown HGCM...\n"));
7474
7475 /* Leave the lock since EMT might wait for it and will call us back as addVMCaller() */
7476 alock.release();
7477
7478 m_pVMMDev->hgcmShutdown();
7479
7480 alock.acquire();
7481 }
7482
7483 /* advance percent count */
7484 if (aProgress)
7485 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount);
7486
7487#endif /* VBOX_WITH_HGCM */
7488
7489 LogFlowThisFunc(("Ready for VM destruction.\n"));
7490
7491 /* If we are called from Console::uninit(), then try to destroy the VM even
7492 * on failure (this will most likely fail too, but what to do?..) */
7493 if (RT_SUCCESS(vrc) || getObjectState().getState() == ObjectState::InUninit)
7494 {
7495 /* If the machine has a USB controller, release all USB devices
7496 * (symmetric to the code in captureUSBDevices()) */
7497 if (mfVMHasUsbController)
7498 {
7499 alock.release();
7500 i_detachAllUSBDevices(false /* aDone */);
7501 alock.acquire();
7502 }
7503
7504 /* Now we've got to destroy the VM as well. (mpUVM is not valid beyond
7505 * this point). We release the lock before calling VMR3Destroy() because
7506 * it will result into calling destructors of drivers associated with
7507 * Console children which may in turn try to lock Console (e.g. by
7508 * instantiating SafeVMPtr to access mpUVM). It's safe here because
7509 * mVMDestroying is set which should prevent any activity. */
7510
7511 /* Set mpUVM to NULL early just in case if some old code is not using
7512 * addVMCaller()/releaseVMCaller(). (We have our own ref on pUVM.) */
7513 VMR3ReleaseUVM(mpUVM);
7514 mpUVM = NULL;
7515
7516 LogFlowThisFunc(("Destroying the VM...\n"));
7517
7518 alock.release();
7519
7520 vrc = VMR3Destroy(pUVM);
7521
7522 /* take the lock again */
7523 alock.acquire();
7524
7525 /* advance percent count */
7526 if (aProgress)
7527 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount);
7528
7529 if (RT_SUCCESS(vrc))
7530 {
7531 LogFlowThisFunc(("Machine has been destroyed (mMachineState=%d)\n",
7532 mMachineState));
7533 /* Note: the Console-level machine state change happens on the
7534 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
7535 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
7536 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
7537 * occurred yet. This is okay, because mMachineState is already
7538 * Stopping in this case, so any other attempt to call PowerDown()
7539 * will be rejected. */
7540 }
7541 else
7542 {
7543 /* bad bad bad, but what to do? (Give Console our UVM ref.) */
7544 mpUVM = pUVM;
7545 pUVM = NULL;
7546 rc = setError(VBOX_E_VM_ERROR,
7547 tr("Could not destroy the machine. (Error: %Rrc)"),
7548 vrc);
7549 }
7550
7551 /* Complete the detaching of the USB devices. */
7552 if (mfVMHasUsbController)
7553 {
7554 alock.release();
7555 i_detachAllUSBDevices(true /* aDone */);
7556 alock.acquire();
7557 }
7558
7559 /* advance percent count */
7560 if (aProgress)
7561 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount);
7562 }
7563 else
7564 {
7565 rc = setError(VBOX_E_VM_ERROR,
7566 tr("Could not power off the machine. (Error: %Rrc)"),
7567 vrc);
7568 }
7569
7570 /*
7571 * Finished with the destruction.
7572 *
7573 * Note that if something impossible happened and we've failed to destroy
7574 * the VM, mVMDestroying will remain true and mMachineState will be
7575 * something like Stopping, so most Console methods will return an error
7576 * to the caller.
7577 */
7578 if (pUVM != NULL)
7579 VMR3ReleaseUVM(pUVM);
7580 else
7581 mVMDestroying = false;
7582
7583 LogFlowThisFuncLeave();
7584 return rc;
7585}
7586
7587/**
7588 * @note Locks this object for writing.
7589 */
7590HRESULT Console::i_setMachineState(MachineState_T aMachineState,
7591 bool aUpdateServer /* = true */)
7592{
7593 AutoCaller autoCaller(this);
7594 AssertComRCReturnRC(autoCaller.rc());
7595
7596 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7597
7598 HRESULT rc = S_OK;
7599
7600 if (mMachineState != aMachineState)
7601 {
7602 LogThisFunc(("machineState=%s -> %s aUpdateServer=%RTbool\n",
7603 Global::stringifyMachineState(mMachineState), Global::stringifyMachineState(aMachineState), aUpdateServer));
7604 mMachineState = aMachineState;
7605
7606 /// @todo (dmik)
7607 // possibly, we need to redo onStateChange() using the dedicated
7608 // Event thread, like it is done in VirtualBox. This will make it
7609 // much safer (no deadlocks possible if someone tries to use the
7610 // console from the callback), however, listeners will lose the
7611 // ability to synchronously react to state changes (is it really
7612 // necessary??)
7613 LogFlowThisFunc(("Doing onStateChange()...\n"));
7614 i_onStateChange(aMachineState);
7615 LogFlowThisFunc(("Done onStateChange()\n"));
7616
7617 if (aUpdateServer)
7618 {
7619 /* Server notification MUST be done from under the lock; otherwise
7620 * the machine state here and on the server might go out of sync
7621 * which can lead to various unexpected results (like the machine
7622 * state being >= MachineState_Running on the server, while the
7623 * session state is already SessionState_Unlocked at the same time
7624 * there).
7625 *
7626 * Cross-lock conditions should be carefully watched out: calling
7627 * UpdateState we will require Machine and SessionMachine locks
7628 * (remember that here we're holding the Console lock here, and also
7629 * all locks that have been acquire by the thread before calling
7630 * this method).
7631 */
7632 LogFlowThisFunc(("Doing mControl->UpdateState()...\n"));
7633 rc = mControl->UpdateState(aMachineState);
7634 LogFlowThisFunc(("mControl->UpdateState()=%Rhrc\n", rc));
7635 }
7636 }
7637
7638 return rc;
7639}
7640
7641/**
7642 * Searches for a shared folder with the given logical name
7643 * in the collection of shared folders.
7644 *
7645 * @param aName logical name of the shared folder
7646 * @param aSharedFolder where to return the found object
7647 * @param aSetError whether to set the error info if the folder is
7648 * not found
7649 * @return
7650 * S_OK when found or E_INVALIDARG when not found
7651 *
7652 * @note The caller must lock this object for writing.
7653 */
7654HRESULT Console::i_findSharedFolder(const Utf8Str &strName,
7655 ComObjPtr<SharedFolder> &aSharedFolder,
7656 bool aSetError /* = false */)
7657{
7658 /* sanity check */
7659 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7660
7661 SharedFolderMap::const_iterator it = m_mapSharedFolders.find(strName);
7662 if (it != m_mapSharedFolders.end())
7663 {
7664 aSharedFolder = it->second;
7665 return S_OK;
7666 }
7667
7668 if (aSetError)
7669 setError(VBOX_E_FILE_ERROR,
7670 tr("Could not find a shared folder named '%s'."),
7671 strName.c_str());
7672
7673 return VBOX_E_FILE_ERROR;
7674}
7675
7676/**
7677 * Fetches the list of global or machine shared folders from the server.
7678 *
7679 * @param aGlobal true to fetch global folders.
7680 *
7681 * @note The caller must lock this object for writing.
7682 */
7683HRESULT Console::i_fetchSharedFolders(BOOL aGlobal)
7684{
7685 /* sanity check */
7686 AssertReturn( getObjectState().getState() == ObjectState::InInit
7687 || isWriteLockOnCurrentThread(), E_FAIL);
7688
7689 LogFlowThisFunc(("Entering\n"));
7690
7691 /* Check if we're online and keep it that way. */
7692 SafeVMPtrQuiet ptrVM(this);
7693 AutoVMCallerQuietWeak autoVMCaller(this);
7694 bool const online = ptrVM.isOk()
7695 && m_pVMMDev
7696 && m_pVMMDev->isShFlActive();
7697
7698 HRESULT rc = S_OK;
7699
7700 try
7701 {
7702 if (aGlobal)
7703 {
7704 /// @todo grab & process global folders when they are done
7705 }
7706 else
7707 {
7708 SharedFolderDataMap oldFolders;
7709 if (online)
7710 oldFolders = m_mapMachineSharedFolders;
7711
7712 m_mapMachineSharedFolders.clear();
7713
7714 SafeIfaceArray<ISharedFolder> folders;
7715 rc = mMachine->COMGETTER(SharedFolders)(ComSafeArrayAsOutParam(folders));
7716 if (FAILED(rc)) throw rc;
7717
7718 for (size_t i = 0; i < folders.size(); ++i)
7719 {
7720 ComPtr<ISharedFolder> pSharedFolder = folders[i];
7721
7722 Bstr bstrName;
7723 Bstr bstrHostPath;
7724 BOOL writable;
7725 BOOL autoMount;
7726
7727 rc = pSharedFolder->COMGETTER(Name)(bstrName.asOutParam());
7728 if (FAILED(rc)) throw rc;
7729 Utf8Str strName(bstrName);
7730
7731 rc = pSharedFolder->COMGETTER(HostPath)(bstrHostPath.asOutParam());
7732 if (FAILED(rc)) throw rc;
7733 Utf8Str strHostPath(bstrHostPath);
7734
7735 rc = pSharedFolder->COMGETTER(Writable)(&writable);
7736 if (FAILED(rc)) throw rc;
7737
7738 rc = pSharedFolder->COMGETTER(AutoMount)(&autoMount);
7739 if (FAILED(rc)) throw rc;
7740
7741 m_mapMachineSharedFolders.insert(std::make_pair(strName,
7742 SharedFolderData(strHostPath, !!writable, !!autoMount)));
7743
7744 /* send changes to HGCM if the VM is running */
7745 if (online)
7746 {
7747 SharedFolderDataMap::iterator it = oldFolders.find(strName);
7748 if ( it == oldFolders.end()
7749 || it->second.m_strHostPath != strHostPath)
7750 {
7751 /* a new machine folder is added or
7752 * the existing machine folder is changed */
7753 if (m_mapSharedFolders.find(strName) != m_mapSharedFolders.end())
7754 ; /* the console folder exists, nothing to do */
7755 else
7756 {
7757 /* remove the old machine folder (when changed)
7758 * or the global folder if any (when new) */
7759 if ( it != oldFolders.end()
7760 || m_mapGlobalSharedFolders.find(strName) != m_mapGlobalSharedFolders.end()
7761 )
7762 {
7763 rc = removeSharedFolder(strName);
7764 if (FAILED(rc)) throw rc;
7765 }
7766
7767 /* create the new machine folder */
7768 rc = i_createSharedFolder(strName,
7769 SharedFolderData(strHostPath, !!writable, !!autoMount));
7770 if (FAILED(rc)) throw rc;
7771 }
7772 }
7773 /* forget the processed (or identical) folder */
7774 if (it != oldFolders.end())
7775 oldFolders.erase(it);
7776 }
7777 }
7778
7779 /* process outdated (removed) folders */
7780 if (online)
7781 {
7782 for (SharedFolderDataMap::const_iterator it = oldFolders.begin();
7783 it != oldFolders.end(); ++it)
7784 {
7785 if (m_mapSharedFolders.find(it->first) != m_mapSharedFolders.end())
7786 ; /* the console folder exists, nothing to do */
7787 else
7788 {
7789 /* remove the outdated machine folder */
7790 rc = removeSharedFolder(it->first);
7791 if (FAILED(rc)) throw rc;
7792
7793 /* create the global folder if there is any */
7794 SharedFolderDataMap::const_iterator git =
7795 m_mapGlobalSharedFolders.find(it->first);
7796 if (git != m_mapGlobalSharedFolders.end())
7797 {
7798 rc = i_createSharedFolder(git->first, git->second);
7799 if (FAILED(rc)) throw rc;
7800 }
7801 }
7802 }
7803 }
7804 }
7805 }
7806 catch (HRESULT rc2)
7807 {
7808 rc = rc2;
7809 if (online)
7810 i_setVMRuntimeErrorCallbackF(0, "BrokenSharedFolder",
7811 N_("Broken shared folder!"));
7812 }
7813
7814 LogFlowThisFunc(("Leaving\n"));
7815
7816 return rc;
7817}
7818
7819/**
7820 * Searches for a shared folder with the given name in the list of machine
7821 * shared folders and then in the list of the global shared folders.
7822 *
7823 * @param aName Name of the folder to search for.
7824 * @param aIt Where to store the pointer to the found folder.
7825 * @return @c true if the folder was found and @c false otherwise.
7826 *
7827 * @note The caller must lock this object for reading.
7828 */
7829bool Console::i_findOtherSharedFolder(const Utf8Str &strName,
7830 SharedFolderDataMap::const_iterator &aIt)
7831{
7832 /* sanity check */
7833 AssertReturn(isWriteLockOnCurrentThread(), false);
7834
7835 /* first, search machine folders */
7836 aIt = m_mapMachineSharedFolders.find(strName);
7837 if (aIt != m_mapMachineSharedFolders.end())
7838 return true;
7839
7840 /* second, search machine folders */
7841 aIt = m_mapGlobalSharedFolders.find(strName);
7842 if (aIt != m_mapGlobalSharedFolders.end())
7843 return true;
7844
7845 return false;
7846}
7847
7848/**
7849 * Calls the HGCM service to add a shared folder definition.
7850 *
7851 * @param aName Shared folder name.
7852 * @param aHostPath Shared folder path.
7853 *
7854 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
7855 * @note Doesn't lock anything.
7856 */
7857HRESULT Console::i_createSharedFolder(const Utf8Str &strName, const SharedFolderData &aData)
7858{
7859 ComAssertRet(strName.isNotEmpty(), E_FAIL);
7860 ComAssertRet(aData.m_strHostPath.isNotEmpty(), E_FAIL);
7861
7862 /* sanity checks */
7863 AssertReturn(mpUVM, E_FAIL);
7864 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
7865
7866 VBOXHGCMSVCPARM parms[SHFL_CPARMS_ADD_MAPPING];
7867 SHFLSTRING *pFolderName, *pMapName;
7868 size_t cbString;
7869
7870 Bstr value;
7871 HRESULT hrc = mMachine->GetExtraData(BstrFmt("VBoxInternal2/SharedFoldersEnableSymlinksCreate/%s",
7872 strName.c_str()).raw(),
7873 value.asOutParam());
7874 bool fSymlinksCreate = hrc == S_OK && value == "1";
7875
7876 Log(("Adding shared folder '%s' -> '%s'\n", strName.c_str(), aData.m_strHostPath.c_str()));
7877
7878 // check whether the path is valid and exists
7879 char hostPathFull[RTPATH_MAX];
7880 int vrc = RTPathAbsEx(NULL,
7881 aData.m_strHostPath.c_str(),
7882 hostPathFull,
7883 sizeof(hostPathFull));
7884
7885 bool fMissing = false;
7886 if (RT_FAILURE(vrc))
7887 return setError(E_INVALIDARG,
7888 tr("Invalid shared folder path: '%s' (%Rrc)"),
7889 aData.m_strHostPath.c_str(), vrc);
7890 if (!RTPathExists(hostPathFull))
7891 fMissing = true;
7892
7893 /* Check whether the path is full (absolute) */
7894 if (RTPathCompare(aData.m_strHostPath.c_str(), hostPathFull) != 0)
7895 return setError(E_INVALIDARG,
7896 tr("Shared folder path '%s' is not absolute"),
7897 aData.m_strHostPath.c_str());
7898
7899 // now that we know the path is good, give it to HGCM
7900
7901 Bstr bstrName(strName);
7902 Bstr bstrHostPath(aData.m_strHostPath);
7903
7904 cbString = (bstrHostPath.length() + 1) * sizeof(RTUTF16);
7905 if (cbString >= UINT16_MAX)
7906 return setError(E_INVALIDARG, tr("The name is too long"));
7907 pFolderName = (SHFLSTRING*)RTMemAllocZ(SHFLSTRING_HEADER_SIZE + cbString);
7908 Assert(pFolderName);
7909 memcpy(pFolderName->String.ucs2, bstrHostPath.raw(), cbString);
7910
7911 pFolderName->u16Size = (uint16_t)cbString;
7912 pFolderName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
7913
7914 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
7915 parms[0].u.pointer.addr = pFolderName;
7916 parms[0].u.pointer.size = ShflStringSizeOfBuffer(pFolderName);
7917
7918 cbString = (bstrName.length() + 1) * sizeof(RTUTF16);
7919 if (cbString >= UINT16_MAX)
7920 {
7921 RTMemFree(pFolderName);
7922 return setError(E_INVALIDARG, tr("The host path is too long"));
7923 }
7924 pMapName = (SHFLSTRING*)RTMemAllocZ(SHFLSTRING_HEADER_SIZE + cbString);
7925 Assert(pMapName);
7926 memcpy(pMapName->String.ucs2, bstrName.raw(), cbString);
7927
7928 pMapName->u16Size = (uint16_t)cbString;
7929 pMapName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
7930
7931 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
7932 parms[1].u.pointer.addr = pMapName;
7933 parms[1].u.pointer.size = ShflStringSizeOfBuffer(pMapName);
7934
7935 parms[2].type = VBOX_HGCM_SVC_PARM_32BIT;
7936 parms[2].u.uint32 = (aData.m_fWritable ? SHFL_ADD_MAPPING_F_WRITABLE : 0)
7937 | (aData.m_fAutoMount ? SHFL_ADD_MAPPING_F_AUTOMOUNT : 0)
7938 | (fSymlinksCreate ? SHFL_ADD_MAPPING_F_CREATE_SYMLINKS : 0)
7939 | (fMissing ? SHFL_ADD_MAPPING_F_MISSING : 0)
7940 ;
7941
7942 vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders",
7943 SHFL_FN_ADD_MAPPING,
7944 SHFL_CPARMS_ADD_MAPPING, &parms[0]);
7945 RTMemFree(pFolderName);
7946 RTMemFree(pMapName);
7947
7948 if (RT_FAILURE(vrc))
7949 return setError(E_FAIL,
7950 tr("Could not create a shared folder '%s' mapped to '%s' (%Rrc)"),
7951 strName.c_str(), aData.m_strHostPath.c_str(), vrc);
7952
7953 if (fMissing)
7954 return setError(E_INVALIDARG,
7955 tr("Shared folder path '%s' does not exist on the host"),
7956 aData.m_strHostPath.c_str());
7957
7958 return S_OK;
7959}
7960
7961/**
7962 * Calls the HGCM service to remove the shared folder definition.
7963 *
7964 * @param aName Shared folder name.
7965 *
7966 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
7967 * @note Doesn't lock anything.
7968 */
7969HRESULT Console::i_removeSharedFolder(const Utf8Str &strName)
7970{
7971 ComAssertRet(strName.isNotEmpty(), E_FAIL);
7972
7973 /* sanity checks */
7974 AssertReturn(mpUVM, E_FAIL);
7975 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
7976
7977 VBOXHGCMSVCPARM parms;
7978 SHFLSTRING *pMapName;
7979 size_t cbString;
7980
7981 Log(("Removing shared folder '%s'\n", strName.c_str()));
7982
7983 Bstr bstrName(strName);
7984 cbString = (bstrName.length() + 1) * sizeof(RTUTF16);
7985 if (cbString >= UINT16_MAX)
7986 return setError(E_INVALIDARG, tr("The name is too long"));
7987 pMapName = (SHFLSTRING *) RTMemAllocZ(SHFLSTRING_HEADER_SIZE + cbString);
7988 Assert(pMapName);
7989 memcpy(pMapName->String.ucs2, bstrName.raw(), cbString);
7990
7991 pMapName->u16Size = (uint16_t)cbString;
7992 pMapName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
7993
7994 parms.type = VBOX_HGCM_SVC_PARM_PTR;
7995 parms.u.pointer.addr = pMapName;
7996 parms.u.pointer.size = ShflStringSizeOfBuffer(pMapName);
7997
7998 int vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders",
7999 SHFL_FN_REMOVE_MAPPING,
8000 1, &parms);
8001 RTMemFree(pMapName);
8002 if (RT_FAILURE(vrc))
8003 return setError(E_FAIL,
8004 tr("Could not remove the shared folder '%s' (%Rrc)"),
8005 strName.c_str(), vrc);
8006
8007 return S_OK;
8008}
8009
8010/** @callback_method_impl{FNVMATSTATE}
8011 *
8012 * @note Locks the Console object for writing.
8013 * @remarks The @a pUVM parameter can be NULL in one case where powerUpThread()
8014 * calls after the VM was destroyed.
8015 */
8016DECLCALLBACK(void) Console::i_vmstateChangeCallback(PUVM pUVM, VMSTATE enmState, VMSTATE enmOldState, void *pvUser)
8017{
8018 LogFlowFunc(("Changing state from %s to %s (pUVM=%p)\n",
8019 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState), pUVM));
8020
8021 Console *that = static_cast<Console *>(pvUser);
8022 AssertReturnVoid(that);
8023
8024 AutoCaller autoCaller(that);
8025
8026 /* Note that we must let this method proceed even if Console::uninit() has
8027 * been already called. In such case this VMSTATE change is a result of:
8028 * 1) powerDown() called from uninit() itself, or
8029 * 2) VM-(guest-)initiated power off. */
8030 AssertReturnVoid( autoCaller.isOk()
8031 || that->getObjectState().getState() == ObjectState::InUninit);
8032
8033 switch (enmState)
8034 {
8035 /*
8036 * The VM has terminated
8037 */
8038 case VMSTATE_OFF:
8039 {
8040#ifdef VBOX_WITH_GUEST_PROPS
8041 if (that->i_isResetTurnedIntoPowerOff())
8042 {
8043 Bstr strPowerOffReason;
8044
8045 if (that->mfPowerOffCausedByReset)
8046 strPowerOffReason = Bstr("Reset");
8047 else
8048 strPowerOffReason = Bstr("PowerOff");
8049
8050 that->mMachine->DeleteGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw());
8051 that->mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw(),
8052 strPowerOffReason.raw(), Bstr("RDONLYGUEST").raw());
8053 that->mMachine->SaveSettings();
8054 }
8055#endif
8056
8057 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8058
8059 if (that->mVMStateChangeCallbackDisabled)
8060 return;
8061
8062 /* Do we still think that it is running? It may happen if this is a
8063 * VM-(guest-)initiated shutdown/poweroff.
8064 */
8065 if ( that->mMachineState != MachineState_Stopping
8066 && that->mMachineState != MachineState_Saving
8067 && that->mMachineState != MachineState_Restoring
8068 && that->mMachineState != MachineState_TeleportingIn
8069 && that->mMachineState != MachineState_FaultTolerantSyncing
8070 && that->mMachineState != MachineState_TeleportingPausedVM
8071 && !that->mVMIsAlreadyPoweringOff
8072 )
8073 {
8074 LogFlowFunc(("VM has powered itself off but Console still thinks it is running. Notifying.\n"));
8075
8076 /*
8077 * Prevent powerDown() from calling VMR3PowerOff() again if this was called from
8078 * the power off state change.
8079 * When called from the Reset state make sure to call VMR3PowerOff() first.
8080 */
8081 Assert(that->mVMPoweredOff == false);
8082 that->mVMPoweredOff = true;
8083
8084 /*
8085 * request a progress object from the server
8086 * (this will set the machine state to Stopping on the server
8087 * to block others from accessing this machine)
8088 */
8089 ComPtr<IProgress> pProgress;
8090 HRESULT rc = that->mControl->BeginPoweringDown(pProgress.asOutParam());
8091 AssertComRC(rc);
8092
8093 /* sync the state with the server */
8094 that->i_setMachineStateLocally(MachineState_Stopping);
8095
8096 /* Setup task object and thread to carry out the operation
8097 * asynchronously (if we call powerDown() right here but there
8098 * is one or more mpUVM callers (added with addVMCaller()) we'll
8099 * deadlock).
8100 */
8101 std::auto_ptr<VMPowerDownTask> task(new VMPowerDownTask(that, pProgress));
8102
8103 /* If creating a task failed, this can currently mean one of
8104 * two: either Console::uninit() has been called just a ms
8105 * before (so a powerDown() call is already on the way), or
8106 * powerDown() itself is being already executed. Just do
8107 * nothing.
8108 */
8109 if (!task->isOk())
8110 {
8111 LogFlowFunc(("Console is already being uninitialized.\n"));
8112 return;
8113 }
8114
8115 int vrc = RTThreadCreate(NULL, Console::i_powerDownThread,
8116 (void *)task.get(), 0,
8117 RTTHREADTYPE_MAIN_WORKER, 0,
8118 "VMPwrDwn");
8119 AssertMsgRCReturnVoid(vrc, ("Could not create VMPowerDown thread (%Rrc)\n", vrc));
8120
8121 /* task is now owned by powerDownThread(), so release it */
8122 task.release();
8123 }
8124 break;
8125 }
8126
8127 /* The VM has been completely destroyed.
8128 *
8129 * Note: This state change can happen at two points:
8130 * 1) At the end of VMR3Destroy() if it was not called from EMT.
8131 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
8132 * called by EMT.
8133 */
8134 case VMSTATE_TERMINATED:
8135 {
8136 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8137
8138 if (that->mVMStateChangeCallbackDisabled)
8139 break;
8140
8141 /* Terminate host interface networking. If pUVM is NULL, we've been
8142 * manually called from powerUpThread() either before calling
8143 * VMR3Create() or after VMR3Create() failed, so no need to touch
8144 * networking.
8145 */
8146 if (pUVM)
8147 that->i_powerDownHostInterfaces();
8148
8149 /* From now on the machine is officially powered down or remains in
8150 * the Saved state.
8151 */
8152 switch (that->mMachineState)
8153 {
8154 default:
8155 AssertFailed();
8156 /* fall through */
8157 case MachineState_Stopping:
8158 /* successfully powered down */
8159 that->i_setMachineState(MachineState_PoweredOff);
8160 break;
8161 case MachineState_Saving:
8162 /* successfully saved */
8163 that->i_setMachineState(MachineState_Saved);
8164 break;
8165 case MachineState_Starting:
8166 /* failed to start, but be patient: set back to PoweredOff
8167 * (for similarity with the below) */
8168 that->i_setMachineState(MachineState_PoweredOff);
8169 break;
8170 case MachineState_Restoring:
8171 /* failed to load the saved state file, but be patient: set
8172 * back to Saved (to preserve the saved state file) */
8173 that->i_setMachineState(MachineState_Saved);
8174 break;
8175 case MachineState_TeleportingIn:
8176 /* Teleportation failed or was canceled. Back to powered off. */
8177 that->i_setMachineState(MachineState_PoweredOff);
8178 break;
8179 case MachineState_TeleportingPausedVM:
8180 /* Successfully teleported the VM. */
8181 that->i_setMachineState(MachineState_Teleported);
8182 break;
8183 case MachineState_FaultTolerantSyncing:
8184 /* Fault tolerant sync failed or was canceled. Back to powered off. */
8185 that->i_setMachineState(MachineState_PoweredOff);
8186 break;
8187 }
8188 break;
8189 }
8190
8191 case VMSTATE_RESETTING:
8192 {
8193#ifdef VBOX_WITH_GUEST_PROPS
8194 /* Do not take any read/write locks here! */
8195 that->i_guestPropertiesHandleVMReset();
8196#endif
8197 break;
8198 }
8199
8200 case VMSTATE_SUSPENDED:
8201 {
8202 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8203
8204 if (that->mVMStateChangeCallbackDisabled)
8205 break;
8206
8207 switch (that->mMachineState)
8208 {
8209 case MachineState_Teleporting:
8210 that->i_setMachineState(MachineState_TeleportingPausedVM);
8211 break;
8212
8213 case MachineState_LiveSnapshotting:
8214 that->i_setMachineState(MachineState_Saving);
8215 break;
8216
8217 case MachineState_TeleportingPausedVM:
8218 case MachineState_Saving:
8219 case MachineState_Restoring:
8220 case MachineState_Stopping:
8221 case MachineState_TeleportingIn:
8222 case MachineState_FaultTolerantSyncing:
8223 /* The worker thread handles the transition. */
8224 break;
8225
8226 default:
8227 AssertMsgFailed(("%s\n", Global::stringifyMachineState(that->mMachineState)));
8228 case MachineState_Running:
8229 that->i_setMachineState(MachineState_Paused);
8230 break;
8231
8232 case MachineState_Paused:
8233 /* Nothing to do. */
8234 break;
8235 }
8236 break;
8237 }
8238
8239 case VMSTATE_SUSPENDED_LS:
8240 case VMSTATE_SUSPENDED_EXT_LS:
8241 {
8242 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8243 if (that->mVMStateChangeCallbackDisabled)
8244 break;
8245 switch (that->mMachineState)
8246 {
8247 case MachineState_Teleporting:
8248 that->i_setMachineState(MachineState_TeleportingPausedVM);
8249 break;
8250
8251 case MachineState_LiveSnapshotting:
8252 that->i_setMachineState(MachineState_Saving);
8253 break;
8254
8255 case MachineState_TeleportingPausedVM:
8256 case MachineState_Saving:
8257 /* ignore */
8258 break;
8259
8260 default:
8261 AssertMsgFailed(("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState),
8262 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
8263 that->i_setMachineState(MachineState_Paused);
8264 break;
8265 }
8266 break;
8267 }
8268
8269 case VMSTATE_RUNNING:
8270 {
8271 if ( enmOldState == VMSTATE_POWERING_ON
8272 || enmOldState == VMSTATE_RESUMING
8273 || enmOldState == VMSTATE_RUNNING_FT)
8274 {
8275 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8276
8277 if (that->mVMStateChangeCallbackDisabled)
8278 break;
8279
8280 Assert( ( ( that->mMachineState == MachineState_Starting
8281 || that->mMachineState == MachineState_Paused)
8282 && enmOldState == VMSTATE_POWERING_ON)
8283 || ( ( that->mMachineState == MachineState_Restoring
8284 || that->mMachineState == MachineState_TeleportingIn
8285 || that->mMachineState == MachineState_Paused
8286 || that->mMachineState == MachineState_Saving
8287 )
8288 && enmOldState == VMSTATE_RESUMING)
8289 || ( that->mMachineState == MachineState_FaultTolerantSyncing
8290 && enmOldState == VMSTATE_RUNNING_FT));
8291
8292 that->i_setMachineState(MachineState_Running);
8293 }
8294
8295 break;
8296 }
8297
8298 case VMSTATE_RUNNING_LS:
8299 AssertMsg( that->mMachineState == MachineState_LiveSnapshotting
8300 || that->mMachineState == MachineState_Teleporting,
8301 ("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState),
8302 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
8303 break;
8304
8305 case VMSTATE_RUNNING_FT:
8306 AssertMsg(that->mMachineState == MachineState_FaultTolerantSyncing,
8307 ("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState),
8308 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
8309 break;
8310
8311 case VMSTATE_FATAL_ERROR:
8312 {
8313 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8314
8315 if (that->mVMStateChangeCallbackDisabled)
8316 break;
8317
8318 /* Fatal errors are only for running VMs. */
8319 Assert(Global::IsOnline(that->mMachineState));
8320
8321 /* Note! 'Pause' is used here in want of something better. There
8322 * are currently only two places where fatal errors might be
8323 * raised, so it is not worth adding a new externally
8324 * visible state for this yet. */
8325 that->i_setMachineState(MachineState_Paused);
8326 break;
8327 }
8328
8329 case VMSTATE_GURU_MEDITATION:
8330 {
8331 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
8332
8333 if (that->mVMStateChangeCallbackDisabled)
8334 break;
8335
8336 /* Guru are only for running VMs */
8337 Assert(Global::IsOnline(that->mMachineState));
8338
8339 that->i_setMachineState(MachineState_Stuck);
8340 break;
8341 }
8342
8343 case VMSTATE_POWERING_ON:
8344 {
8345 /*
8346 * We have to set the secret key helper interface for the VD drivers to
8347 * get notified about missing keys.
8348 */
8349 that->i_clearDiskEncryptionKeysOnAllAttachments();
8350 break;
8351 }
8352
8353 default: /* shut up gcc */
8354 break;
8355 }
8356}
8357
8358/**
8359 * Changes the clipboard mode.
8360 *
8361 * @param aClipboardMode new clipboard mode.
8362 */
8363void Console::i_changeClipboardMode(ClipboardMode_T aClipboardMode)
8364{
8365 VMMDev *pVMMDev = m_pVMMDev;
8366 Assert(pVMMDev);
8367
8368 VBOXHGCMSVCPARM parm;
8369 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
8370
8371 switch (aClipboardMode)
8372 {
8373 default:
8374 case ClipboardMode_Disabled:
8375 LogRel(("Shared clipboard mode: Off\n"));
8376 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_OFF;
8377 break;
8378 case ClipboardMode_GuestToHost:
8379 LogRel(("Shared clipboard mode: Guest to Host\n"));
8380 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_GUEST_TO_HOST;
8381 break;
8382 case ClipboardMode_HostToGuest:
8383 LogRel(("Shared clipboard mode: Host to Guest\n"));
8384 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_HOST_TO_GUEST;
8385 break;
8386 case ClipboardMode_Bidirectional:
8387 LogRel(("Shared clipboard mode: Bidirectional\n"));
8388 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_BIDIRECTIONAL;
8389 break;
8390 }
8391
8392 pVMMDev->hgcmHostCall("VBoxSharedClipboard", VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE, 1, &parm);
8393}
8394
8395/**
8396 * Changes the drag'n_drop mode.
8397 *
8398 * @param aDnDMode new drag'n'drop mode.
8399 */
8400int Console::i_changeDnDMode(DnDMode_T aDnDMode)
8401{
8402 VMMDev *pVMMDev = m_pVMMDev;
8403 AssertPtrReturn(pVMMDev, VERR_INVALID_POINTER);
8404
8405 VBOXHGCMSVCPARM parm;
8406 RT_ZERO(parm);
8407 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
8408
8409 switch (aDnDMode)
8410 {
8411 default:
8412 case DnDMode_Disabled:
8413 LogRel(("Changed drag'n drop mode to: Off\n"));
8414 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_OFF;
8415 break;
8416 case DnDMode_GuestToHost:
8417 LogRel(("Changed drag'n drop mode to: Guest to Host\n"));
8418 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_GUEST_TO_HOST;
8419 break;
8420 case DnDMode_HostToGuest:
8421 LogRel(("Changed drag'n drop mode to: Host to Guest\n"));
8422 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_HOST_TO_GUEST;
8423 break;
8424 case DnDMode_Bidirectional:
8425 LogRel(("Changed drag'n drop mode to: Bidirectional\n"));
8426 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_BIDIRECTIONAL;
8427 break;
8428 }
8429
8430 int rc = pVMMDev->hgcmHostCall("VBoxDragAndDropSvc",
8431 DragAndDropSvc::HOST_DND_SET_MODE, 1, &parm);
8432 LogFlowFunc(("rc=%Rrc\n", rc));
8433 return rc;
8434}
8435
8436#ifdef VBOX_WITH_USB
8437/**
8438 * Sends a request to VMM to attach the given host device.
8439 * After this method succeeds, the attached device will appear in the
8440 * mUSBDevices collection.
8441 *
8442 * @param aHostDevice device to attach
8443 *
8444 * @note Synchronously calls EMT.
8445 */
8446HRESULT Console::i_attachUSBDevice(IUSBDevice *aHostDevice, ULONG aMaskedIfs,
8447 const Utf8Str &aCaptureFilename)
8448{
8449 AssertReturn(aHostDevice, E_FAIL);
8450 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
8451
8452 HRESULT hrc;
8453
8454 /*
8455 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
8456 * method in EMT (using usbAttachCallback()).
8457 */
8458 Bstr BstrAddress;
8459 hrc = aHostDevice->COMGETTER(Address)(BstrAddress.asOutParam());
8460 ComAssertComRCRetRC(hrc);
8461
8462 Utf8Str Address(BstrAddress);
8463
8464 Bstr id;
8465 hrc = aHostDevice->COMGETTER(Id)(id.asOutParam());
8466 ComAssertComRCRetRC(hrc);
8467 Guid uuid(id);
8468
8469 BOOL fRemote = FALSE;
8470 hrc = aHostDevice->COMGETTER(Remote)(&fRemote);
8471 ComAssertComRCRetRC(hrc);
8472
8473 /* Get the VM handle. */
8474 SafeVMPtr ptrVM(this);
8475 if (!ptrVM.isOk())
8476 return ptrVM.rc();
8477
8478 LogFlowThisFunc(("Proxying USB device '%s' {%RTuuid}...\n",
8479 Address.c_str(), uuid.raw()));
8480
8481 void *pvRemoteBackend = NULL;
8482 if (fRemote)
8483 {
8484 RemoteUSBDevice *pRemoteUSBDevice = static_cast<RemoteUSBDevice *>(aHostDevice);
8485 pvRemoteBackend = i_consoleVRDPServer()->USBBackendRequestPointer(pRemoteUSBDevice->clientId(), &uuid);
8486 if (!pvRemoteBackend)
8487 return E_INVALIDARG; /* The clientId is invalid then. */
8488 }
8489
8490 USHORT portVersion = 0;
8491 hrc = aHostDevice->COMGETTER(PortVersion)(&portVersion);
8492 AssertComRCReturnRC(hrc);
8493 Assert(portVersion == 1 || portVersion == 2 || portVersion == 3);
8494
8495 int vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
8496 (PFNRT)i_usbAttachCallback, 10,
8497 this, ptrVM.rawUVM(), aHostDevice, uuid.raw(), fRemote,
8498 Address.c_str(), pvRemoteBackend, portVersion, aMaskedIfs,
8499 aCaptureFilename.isEmpty() ? NULL : aCaptureFilename.c_str());
8500 if (RT_SUCCESS(vrc))
8501 {
8502 /* Create a OUSBDevice and add it to the device list */
8503 ComObjPtr<OUSBDevice> pUSBDevice;
8504 pUSBDevice.createObject();
8505 hrc = pUSBDevice->init(aHostDevice);
8506 AssertComRC(hrc);
8507
8508 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8509 mUSBDevices.push_back(pUSBDevice);
8510 LogFlowFunc(("Attached device {%RTuuid}\n", pUSBDevice->i_id().raw()));
8511
8512 /* notify callbacks */
8513 alock.release();
8514 i_onUSBDeviceStateChange(pUSBDevice, true /* aAttached */, NULL);
8515 }
8516 else
8517 {
8518 LogWarningThisFunc(("Failed to create proxy device for '%s' {%RTuuid} (%Rrc)\n",
8519 Address.c_str(), uuid.raw(), vrc));
8520
8521 switch (vrc)
8522 {
8523 case VERR_VUSB_NO_PORTS:
8524 hrc = setError(E_FAIL, tr("Failed to attach the USB device. (No available ports on the USB controller)."));
8525 break;
8526 case VERR_VUSB_USBFS_PERMISSION:
8527 hrc = setError(E_FAIL, tr("Not permitted to open the USB device, check usbfs options"));
8528 break;
8529 default:
8530 hrc = setError(E_FAIL, tr("Failed to create a proxy device for the USB device. (Error: %Rrc)"), vrc);
8531 break;
8532 }
8533 }
8534
8535 return hrc;
8536}
8537
8538/**
8539 * USB device attach callback used by AttachUSBDevice().
8540 * Note that AttachUSBDevice() doesn't return until this callback is executed,
8541 * so we don't use AutoCaller and don't care about reference counters of
8542 * interface pointers passed in.
8543 *
8544 * @thread EMT
8545 * @note Locks the console object for writing.
8546 */
8547//static
8548DECLCALLBACK(int)
8549Console::i_usbAttachCallback(Console *that, PUVM pUVM, IUSBDevice *aHostDevice, PCRTUUID aUuid, bool aRemote,
8550 const char *aAddress, void *pvRemoteBackend, USHORT aPortVersion, ULONG aMaskedIfs,
8551 const char *pszCaptureFilename)
8552{
8553 LogFlowFuncEnter();
8554 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
8555
8556 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
8557 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
8558
8559 int vrc = PDMR3UsbCreateProxyDevice(pUVM, aUuid, aRemote, aAddress, pvRemoteBackend,
8560 aPortVersion == 3 ? VUSB_STDVER_30 :
8561 aPortVersion == 2 ? VUSB_STDVER_20 : VUSB_STDVER_11,
8562 aMaskedIfs, pszCaptureFilename);
8563 LogFlowFunc(("vrc=%Rrc\n", vrc));
8564 LogFlowFuncLeave();
8565 return vrc;
8566}
8567
8568/**
8569 * Sends a request to VMM to detach the given host device. After this method
8570 * succeeds, the detached device will disappear from the mUSBDevices
8571 * collection.
8572 *
8573 * @param aHostDevice device to attach
8574 *
8575 * @note Synchronously calls EMT.
8576 */
8577HRESULT Console::i_detachUSBDevice(const ComObjPtr<OUSBDevice> &aHostDevice)
8578{
8579 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
8580
8581 /* Get the VM handle. */
8582 SafeVMPtr ptrVM(this);
8583 if (!ptrVM.isOk())
8584 return ptrVM.rc();
8585
8586 /* if the device is attached, then there must at least one USB hub. */
8587 AssertReturn(PDMR3UsbHasHub(ptrVM.rawUVM()), E_FAIL);
8588
8589 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8590 LogFlowThisFunc(("Detaching USB proxy device {%RTuuid}...\n",
8591 aHostDevice->i_id().raw()));
8592
8593 /*
8594 * If this was a remote device, release the backend pointer.
8595 * The pointer was requested in usbAttachCallback.
8596 */
8597 BOOL fRemote = FALSE;
8598
8599 HRESULT hrc2 = aHostDevice->COMGETTER(Remote)(&fRemote);
8600 if (FAILED(hrc2))
8601 i_setErrorStatic(hrc2, "GetRemote() failed");
8602
8603 PCRTUUID pUuid = aHostDevice->i_id().raw();
8604 if (fRemote)
8605 {
8606 Guid guid(*pUuid);
8607 i_consoleVRDPServer()->USBBackendReleasePointer(&guid);
8608 }
8609
8610 alock.release();
8611 int vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
8612 (PFNRT)i_usbDetachCallback, 5,
8613 this, ptrVM.rawUVM(), pUuid);
8614 if (RT_SUCCESS(vrc))
8615 {
8616 LogFlowFunc(("Detached device {%RTuuid}\n", pUuid));
8617
8618 /* notify callbacks */
8619 i_onUSBDeviceStateChange(aHostDevice, false /* aAttached */, NULL);
8620 }
8621
8622 ComAssertRCRet(vrc, E_FAIL);
8623
8624 return S_OK;
8625}
8626
8627/**
8628 * USB device detach callback used by DetachUSBDevice().
8629 *
8630 * Note that DetachUSBDevice() doesn't return until this callback is executed,
8631 * so we don't use AutoCaller and don't care about reference counters of
8632 * interface pointers passed in.
8633 *
8634 * @thread EMT
8635 */
8636//static
8637DECLCALLBACK(int)
8638Console::i_usbDetachCallback(Console *that, PUVM pUVM, PCRTUUID aUuid)
8639{
8640 LogFlowFuncEnter();
8641 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
8642
8643 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
8644 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
8645
8646 int vrc = PDMR3UsbDetachDevice(pUVM, aUuid);
8647
8648 LogFlowFunc(("vrc=%Rrc\n", vrc));
8649 LogFlowFuncLeave();
8650 return vrc;
8651}
8652#endif /* VBOX_WITH_USB */
8653
8654/* Note: FreeBSD needs this whether netflt is used or not. */
8655#if ((defined(RT_OS_LINUX) && !defined(VBOX_WITH_NETFLT)) || defined(RT_OS_FREEBSD))
8656/**
8657 * Helper function to handle host interface device creation and attachment.
8658 *
8659 * @param networkAdapter the network adapter which attachment should be reset
8660 * @return COM status code
8661 *
8662 * @note The caller must lock this object for writing.
8663 *
8664 * @todo Move this back into the driver!
8665 */
8666HRESULT Console::i_attachToTapInterface(INetworkAdapter *networkAdapter)
8667{
8668 LogFlowThisFunc(("\n"));
8669 /* sanity check */
8670 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8671
8672# ifdef VBOX_STRICT
8673 /* paranoia */
8674 NetworkAttachmentType_T attachment;
8675 networkAdapter->COMGETTER(AttachmentType)(&attachment);
8676 Assert(attachment == NetworkAttachmentType_Bridged);
8677# endif /* VBOX_STRICT */
8678
8679 HRESULT rc = S_OK;
8680
8681 ULONG slot = 0;
8682 rc = networkAdapter->COMGETTER(Slot)(&slot);
8683 AssertComRC(rc);
8684
8685# ifdef RT_OS_LINUX
8686 /*
8687 * Allocate a host interface device
8688 */
8689 int rcVBox = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
8690 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
8691 if (RT_SUCCESS(rcVBox))
8692 {
8693 /*
8694 * Set/obtain the tap interface.
8695 */
8696 struct ifreq IfReq;
8697 RT_ZERO(IfReq);
8698 /* The name of the TAP interface we are using */
8699 Bstr tapDeviceName;
8700 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
8701 if (FAILED(rc))
8702 tapDeviceName.setNull(); /* Is this necessary? */
8703 if (tapDeviceName.isEmpty())
8704 {
8705 LogRel(("No TAP device name was supplied.\n"));
8706 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
8707 }
8708
8709 if (SUCCEEDED(rc))
8710 {
8711 /* If we are using a static TAP device then try to open it. */
8712 Utf8Str str(tapDeviceName);
8713 RTStrCopy(IfReq.ifr_name, sizeof(IfReq.ifr_name), str.c_str()); /** @todo bitch about names which are too long... */
8714 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
8715 rcVBox = ioctl(RTFileToNative(maTapFD[slot]), TUNSETIFF, &IfReq);
8716 if (rcVBox != 0)
8717 {
8718 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
8719 rc = setError(E_FAIL,
8720 tr("Failed to open the host network interface %ls"),
8721 tapDeviceName.raw());
8722 }
8723 }
8724 if (SUCCEEDED(rc))
8725 {
8726 /*
8727 * Make it pollable.
8728 */
8729 if (fcntl(RTFileToNative(maTapFD[slot]), F_SETFL, O_NONBLOCK) != -1)
8730 {
8731 Log(("i_attachToTapInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
8732 /*
8733 * Here is the right place to communicate the TAP file descriptor and
8734 * the host interface name to the server if/when it becomes really
8735 * necessary.
8736 */
8737 maTAPDeviceName[slot] = tapDeviceName;
8738 rcVBox = VINF_SUCCESS;
8739 }
8740 else
8741 {
8742 int iErr = errno;
8743
8744 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
8745 rcVBox = VERR_HOSTIF_BLOCKING;
8746 rc = setError(E_FAIL,
8747 tr("could not set up the host networking device for non blocking access: %s"),
8748 strerror(errno));
8749 }
8750 }
8751 }
8752 else
8753 {
8754 LogRel(("Configuration error: Failed to open /dev/net/tun rc=%Rrc\n", rcVBox));
8755 switch (rcVBox)
8756 {
8757 case VERR_ACCESS_DENIED:
8758 /* will be handled by our caller */
8759 rc = rcVBox;
8760 break;
8761 default:
8762 rc = setError(E_FAIL,
8763 tr("Could not set up the host networking device: %Rrc"),
8764 rcVBox);
8765 break;
8766 }
8767 }
8768
8769# elif defined(RT_OS_FREEBSD)
8770 /*
8771 * Set/obtain the tap interface.
8772 */
8773 /* The name of the TAP interface we are using */
8774 Bstr tapDeviceName;
8775 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
8776 if (FAILED(rc))
8777 tapDeviceName.setNull(); /* Is this necessary? */
8778 if (tapDeviceName.isEmpty())
8779 {
8780 LogRel(("No TAP device name was supplied.\n"));
8781 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
8782 }
8783 char szTapdev[1024] = "/dev/";
8784 /* If we are using a static TAP device then try to open it. */
8785 Utf8Str str(tapDeviceName);
8786 if (str.length() + strlen(szTapdev) <= sizeof(szTapdev))
8787 strcat(szTapdev, str.c_str());
8788 else
8789 memcpy(szTapdev + strlen(szTapdev), str.c_str(),
8790 sizeof(szTapdev) - strlen(szTapdev) - 1); /** @todo bitch about names which are too long... */
8791 int rcVBox = RTFileOpen(&maTapFD[slot], szTapdev,
8792 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT | RTFILE_O_NON_BLOCK);
8793
8794 if (RT_SUCCESS(rcVBox))
8795 maTAPDeviceName[slot] = tapDeviceName;
8796 else
8797 {
8798 switch (rcVBox)
8799 {
8800 case VERR_ACCESS_DENIED:
8801 /* will be handled by our caller */
8802 rc = rcVBox;
8803 break;
8804 default:
8805 rc = setError(E_FAIL,
8806 tr("Failed to open the host network interface %ls"),
8807 tapDeviceName.raw());
8808 break;
8809 }
8810 }
8811# else
8812# error "huh?"
8813# endif
8814 /* in case of failure, cleanup. */
8815 if (RT_FAILURE(rcVBox) && SUCCEEDED(rc))
8816 {
8817 LogRel(("General failure attaching to host interface\n"));
8818 rc = setError(E_FAIL,
8819 tr("General failure attaching to host interface"));
8820 }
8821 LogFlowThisFunc(("rc=%Rhrc\n", rc));
8822 return rc;
8823}
8824
8825
8826/**
8827 * Helper function to handle detachment from a host interface
8828 *
8829 * @param networkAdapter the network adapter which attachment should be reset
8830 * @return COM status code
8831 *
8832 * @note The caller must lock this object for writing.
8833 *
8834 * @todo Move this back into the driver!
8835 */
8836HRESULT Console::i_detachFromTapInterface(INetworkAdapter *networkAdapter)
8837{
8838 /* sanity check */
8839 LogFlowThisFunc(("\n"));
8840 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8841
8842 HRESULT rc = S_OK;
8843# ifdef VBOX_STRICT
8844 /* paranoia */
8845 NetworkAttachmentType_T attachment;
8846 networkAdapter->COMGETTER(AttachmentType)(&attachment);
8847 Assert(attachment == NetworkAttachmentType_Bridged);
8848# endif /* VBOX_STRICT */
8849
8850 ULONG slot = 0;
8851 rc = networkAdapter->COMGETTER(Slot)(&slot);
8852 AssertComRC(rc);
8853
8854 /* is there an open TAP device? */
8855 if (maTapFD[slot] != NIL_RTFILE)
8856 {
8857 /*
8858 * Close the file handle.
8859 */
8860 Bstr tapDeviceName, tapTerminateApplication;
8861 bool isStatic = true;
8862 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
8863 if (FAILED(rc) || tapDeviceName.isEmpty())
8864 {
8865 /* If the name is empty, this is a dynamic TAP device, so close it now,
8866 so that the termination script can remove the interface. Otherwise we still
8867 need the FD to pass to the termination script. */
8868 isStatic = false;
8869 int rcVBox = RTFileClose(maTapFD[slot]);
8870 AssertRC(rcVBox);
8871 maTapFD[slot] = NIL_RTFILE;
8872 }
8873 if (isStatic)
8874 {
8875 /* If we are using a static TAP device, we close it now, after having called the
8876 termination script. */
8877 int rcVBox = RTFileClose(maTapFD[slot]);
8878 AssertRC(rcVBox);
8879 }
8880 /* the TAP device name and handle are no longer valid */
8881 maTapFD[slot] = NIL_RTFILE;
8882 maTAPDeviceName[slot] = "";
8883 }
8884 LogFlowThisFunc(("returning %d\n", rc));
8885 return rc;
8886}
8887#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
8888
8889/**
8890 * Called at power down to terminate host interface networking.
8891 *
8892 * @note The caller must lock this object for writing.
8893 */
8894HRESULT Console::i_powerDownHostInterfaces()
8895{
8896 LogFlowThisFunc(("\n"));
8897
8898 /* sanity check */
8899 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8900
8901 /*
8902 * host interface termination handling
8903 */
8904 HRESULT rc = S_OK;
8905 ComPtr<IVirtualBox> pVirtualBox;
8906 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
8907 ComPtr<ISystemProperties> pSystemProperties;
8908 if (pVirtualBox)
8909 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
8910 ChipsetType_T chipsetType = ChipsetType_PIIX3;
8911 mMachine->COMGETTER(ChipsetType)(&chipsetType);
8912 ULONG maxNetworkAdapters = 0;
8913 if (pSystemProperties)
8914 pSystemProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters);
8915
8916 for (ULONG slot = 0; slot < maxNetworkAdapters; slot++)
8917 {
8918 ComPtr<INetworkAdapter> pNetworkAdapter;
8919 rc = mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
8920 if (FAILED(rc)) break;
8921
8922 BOOL enabled = FALSE;
8923 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
8924 if (!enabled)
8925 continue;
8926
8927 NetworkAttachmentType_T attachment;
8928 pNetworkAdapter->COMGETTER(AttachmentType)(&attachment);
8929 if (attachment == NetworkAttachmentType_Bridged)
8930 {
8931#if ((defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)) && !defined(VBOX_WITH_NETFLT))
8932 HRESULT rc2 = i_detachFromTapInterface(pNetworkAdapter);
8933 if (FAILED(rc2) && SUCCEEDED(rc))
8934 rc = rc2;
8935#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
8936 }
8937 }
8938
8939 return rc;
8940}
8941
8942
8943/**
8944 * Process callback handler for VMR3LoadFromFile, VMR3LoadFromStream, VMR3Save
8945 * and VMR3Teleport.
8946 *
8947 * @param pUVM The user mode VM handle.
8948 * @param uPercent Completion percentage (0-100).
8949 * @param pvUser Pointer to an IProgress instance.
8950 * @return VINF_SUCCESS.
8951 */
8952/*static*/
8953DECLCALLBACK(int) Console::i_stateProgressCallback(PUVM pUVM, unsigned uPercent, void *pvUser)
8954{
8955 IProgress *pProgress = static_cast<IProgress *>(pvUser);
8956
8957 /* update the progress object */
8958 if (pProgress)
8959 pProgress->SetCurrentOperationProgress(uPercent);
8960
8961 NOREF(pUVM);
8962 return VINF_SUCCESS;
8963}
8964
8965/**
8966 * @copydoc FNVMATERROR
8967 *
8968 * @remarks Might be some tiny serialization concerns with access to the string
8969 * object here...
8970 */
8971/*static*/ DECLCALLBACK(void)
8972Console::i_genericVMSetErrorCallback(PUVM pUVM, void *pvUser, int rc, RT_SRC_POS_DECL,
8973 const char *pszErrorFmt, va_list va)
8974{
8975 Utf8Str *pErrorText = (Utf8Str *)pvUser;
8976 AssertPtr(pErrorText);
8977
8978 /* We ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users. */
8979 va_list va2;
8980 va_copy(va2, va);
8981
8982 /* Append to any the existing error message. */
8983 if (pErrorText->length())
8984 *pErrorText = Utf8StrFmt("%s.\n%N (%Rrc)", pErrorText->c_str(),
8985 pszErrorFmt, &va2, rc, rc);
8986 else
8987 *pErrorText = Utf8StrFmt("%N (%Rrc)", pszErrorFmt, &va2, rc, rc);
8988
8989 va_end(va2);
8990
8991 NOREF(pUVM);
8992}
8993
8994/**
8995 * VM runtime error callback function.
8996 * See VMSetRuntimeError for the detailed description of parameters.
8997 *
8998 * @param pUVM The user mode VM handle. Ignored, so passing NULL
8999 * is fine.
9000 * @param pvUser The user argument, pointer to the Console instance.
9001 * @param fFlags The action flags. See VMSETRTERR_FLAGS_*.
9002 * @param pszErrorId Error ID string.
9003 * @param pszFormat Error message format string.
9004 * @param va Error message arguments.
9005 * @thread EMT.
9006 */
9007/* static */ DECLCALLBACK(void)
9008Console::i_setVMRuntimeErrorCallback(PUVM pUVM, void *pvUser, uint32_t fFlags,
9009 const char *pszErrorId,
9010 const char *pszFormat, va_list va)
9011{
9012 bool const fFatal = !!(fFlags & VMSETRTERR_FLAGS_FATAL);
9013 LogFlowFuncEnter();
9014
9015 Console *that = static_cast<Console *>(pvUser);
9016 AssertReturnVoid(that);
9017
9018 Utf8Str message(pszFormat, va);
9019
9020 LogRel(("Console: VM runtime error: fatal=%RTbool, errorID=%s message=\"%s\"\n",
9021 fFatal, pszErrorId, message.c_str()));
9022
9023 that->i_onRuntimeError(BOOL(fFatal), Bstr(pszErrorId).raw(), Bstr(message).raw());
9024
9025 LogFlowFuncLeave(); NOREF(pUVM);
9026}
9027
9028/**
9029 * Captures USB devices that match filters of the VM.
9030 * Called at VM startup.
9031 *
9032 * @param pUVM The VM handle.
9033 */
9034HRESULT Console::i_captureUSBDevices(PUVM pUVM)
9035{
9036 LogFlowThisFunc(("\n"));
9037
9038 /* sanity check */
9039 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
9040 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9041
9042 /* If the machine has a USB controller, ask the USB proxy service to
9043 * capture devices */
9044 if (mfVMHasUsbController)
9045 {
9046 /* release the lock before calling Host in VBoxSVC since Host may call
9047 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
9048 * produce an inter-process dead-lock otherwise. */
9049 alock.release();
9050
9051 HRESULT hrc = mControl->AutoCaptureUSBDevices();
9052 ComAssertComRCRetRC(hrc);
9053 }
9054
9055 return S_OK;
9056}
9057
9058
9059/**
9060 * Detach all USB device which are attached to the VM for the
9061 * purpose of clean up and such like.
9062 */
9063void Console::i_detachAllUSBDevices(bool aDone)
9064{
9065 LogFlowThisFunc(("aDone=%RTbool\n", aDone));
9066
9067 /* sanity check */
9068 AssertReturnVoid(!isWriteLockOnCurrentThread());
9069 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9070
9071 mUSBDevices.clear();
9072
9073 /* release the lock before calling Host in VBoxSVC since Host may call
9074 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
9075 * produce an inter-process dead-lock otherwise. */
9076 alock.release();
9077
9078 mControl->DetachAllUSBDevices(aDone);
9079}
9080
9081/**
9082 * @note Locks this object for writing.
9083 */
9084void Console::i_processRemoteUSBDevices(uint32_t u32ClientId, VRDEUSBDEVICEDESC *pDevList, uint32_t cbDevList, bool fDescExt)
9085{
9086 LogFlowThisFuncEnter();
9087 LogFlowThisFunc(("u32ClientId = %d, pDevList=%p, cbDevList = %d, fDescExt = %d\n",
9088 u32ClientId, pDevList, cbDevList, fDescExt));
9089
9090 AutoCaller autoCaller(this);
9091 if (!autoCaller.isOk())
9092 {
9093 /* Console has been already uninitialized, deny request */
9094 AssertMsgFailed(("Console is already uninitialized\n"));
9095 LogFlowThisFunc(("Console is already uninitialized\n"));
9096 LogFlowThisFuncLeave();
9097 return;
9098 }
9099
9100 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
9101
9102 /*
9103 * Mark all existing remote USB devices as dirty.
9104 */
9105 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
9106 it != mRemoteUSBDevices.end();
9107 ++it)
9108 {
9109 (*it)->dirty(true);
9110 }
9111
9112 /*
9113 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
9114 */
9115 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
9116 VRDEUSBDEVICEDESC *e = pDevList;
9117
9118 /* The cbDevList condition must be checked first, because the function can
9119 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
9120 */
9121 while (cbDevList >= 2 && e->oNext)
9122 {
9123 /* Sanitize incoming strings in case they aren't valid UTF-8. */
9124 if (e->oManufacturer)
9125 RTStrPurgeEncoding((char *)e + e->oManufacturer);
9126 if (e->oProduct)
9127 RTStrPurgeEncoding((char *)e + e->oProduct);
9128 if (e->oSerialNumber)
9129 RTStrPurgeEncoding((char *)e + e->oSerialNumber);
9130
9131 LogFlowThisFunc(("vendor %04X, product %04X, name = %s\n",
9132 e->idVendor, e->idProduct,
9133 e->oProduct? (char *)e + e->oProduct: ""));
9134
9135 bool fNewDevice = true;
9136
9137 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
9138 it != mRemoteUSBDevices.end();
9139 ++it)
9140 {
9141 if ((*it)->devId() == e->id
9142 && (*it)->clientId() == u32ClientId)
9143 {
9144 /* The device is already in the list. */
9145 (*it)->dirty(false);
9146 fNewDevice = false;
9147 break;
9148 }
9149 }
9150
9151 if (fNewDevice)
9152 {
9153 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
9154 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""));
9155
9156 /* Create the device object and add the new device to list. */
9157 ComObjPtr<RemoteUSBDevice> pUSBDevice;
9158 pUSBDevice.createObject();
9159 pUSBDevice->init(u32ClientId, e, fDescExt);
9160
9161 mRemoteUSBDevices.push_back(pUSBDevice);
9162
9163 /* Check if the device is ok for current USB filters. */
9164 BOOL fMatched = FALSE;
9165 ULONG fMaskedIfs = 0;
9166
9167 HRESULT hrc = mControl->RunUSBDeviceFilters(pUSBDevice, &fMatched, &fMaskedIfs);
9168
9169 AssertComRC(hrc);
9170
9171 LogFlowThisFunc(("USB filters return %d %#x\n", fMatched, fMaskedIfs));
9172
9173 if (fMatched)
9174 {
9175 alock.release();
9176 hrc = i_onUSBDeviceAttach(pUSBDevice, NULL, fMaskedIfs, Utf8Str());
9177 alock.acquire();
9178
9179 /// @todo (r=dmik) warning reporting subsystem
9180
9181 if (hrc == S_OK)
9182 {
9183 LogFlowThisFunc(("Device attached\n"));
9184 pUSBDevice->captured(true);
9185 }
9186 }
9187 }
9188
9189 if (cbDevList < e->oNext)
9190 {
9191 LogWarningThisFunc(("cbDevList %d > oNext %d\n",
9192 cbDevList, e->oNext));
9193 break;
9194 }
9195
9196 cbDevList -= e->oNext;
9197
9198 e = (VRDEUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
9199 }
9200
9201 /*
9202 * Remove dirty devices, that is those which are not reported by the server anymore.
9203 */
9204 for (;;)
9205 {
9206 ComObjPtr<RemoteUSBDevice> pUSBDevice;
9207
9208 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
9209 while (it != mRemoteUSBDevices.end())
9210 {
9211 if ((*it)->dirty())
9212 {
9213 pUSBDevice = *it;
9214 break;
9215 }
9216
9217 ++it;
9218 }
9219
9220 if (!pUSBDevice)
9221 {
9222 break;
9223 }
9224
9225 USHORT vendorId = 0;
9226 pUSBDevice->COMGETTER(VendorId)(&vendorId);
9227
9228 USHORT productId = 0;
9229 pUSBDevice->COMGETTER(ProductId)(&productId);
9230
9231 Bstr product;
9232 pUSBDevice->COMGETTER(Product)(product.asOutParam());
9233
9234 LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
9235 vendorId, productId, product.raw()));
9236
9237 /* Detach the device from VM. */
9238 if (pUSBDevice->captured())
9239 {
9240 Bstr uuid;
9241 pUSBDevice->COMGETTER(Id)(uuid.asOutParam());
9242 alock.release();
9243 i_onUSBDeviceDetach(uuid.raw(), NULL);
9244 alock.acquire();
9245 }
9246
9247 /* And remove it from the list. */
9248 mRemoteUSBDevices.erase(it);
9249 }
9250
9251 LogFlowThisFuncLeave();
9252}
9253
9254/**
9255 * Progress cancelation callback for fault tolerance VM poweron
9256 */
9257static void faultToleranceProgressCancelCallback(void *pvUser)
9258{
9259 PUVM pUVM = (PUVM)pvUser;
9260
9261 if (pUVM)
9262 FTMR3CancelStandby(pUVM);
9263}
9264
9265/**
9266 * Thread function which starts the VM (also from saved state) and
9267 * track progress.
9268 *
9269 * @param Thread The thread id.
9270 * @param pvUser Pointer to a VMPowerUpTask structure.
9271 * @return VINF_SUCCESS (ignored).
9272 *
9273 * @note Locks the Console object for writing.
9274 */
9275/*static*/
9276DECLCALLBACK(int) Console::i_powerUpThread(RTTHREAD Thread, void *pvUser)
9277{
9278 LogFlowFuncEnter();
9279
9280 std::auto_ptr<VMPowerUpTask> task(static_cast<VMPowerUpTask *>(pvUser));
9281 AssertReturn(task.get(), VERR_INVALID_PARAMETER);
9282
9283 AssertReturn(!task->mConsole.isNull(), VERR_INVALID_PARAMETER);
9284 AssertReturn(!task->mProgress.isNull(), VERR_INVALID_PARAMETER);
9285
9286 VirtualBoxBase::initializeComForThread();
9287
9288 HRESULT rc = S_OK;
9289 int vrc = VINF_SUCCESS;
9290
9291 /* Set up a build identifier so that it can be seen from core dumps what
9292 * exact build was used to produce the core. */
9293 static char saBuildID[40];
9294 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%u %s%s%s%s",
9295 "BU", "IL", "DI", "D", RTBldCfgVersion(), RTBldCfgRevision(), "BU", "IL", "DI", "D");
9296
9297 ComObjPtr<Console> pConsole = task->mConsole;
9298
9299 /* Note: no need to use addCaller() because VMPowerUpTask does that */
9300
9301 /* The lock is also used as a signal from the task initiator (which
9302 * releases it only after RTThreadCreate()) that we can start the job */
9303 AutoWriteLock alock(pConsole COMMA_LOCKVAL_SRC_POS);
9304
9305 /* sanity */
9306 Assert(pConsole->mpUVM == NULL);
9307
9308 try
9309 {
9310 // Create the VMM device object, which starts the HGCM thread; do this only
9311 // once for the console, for the pathological case that the same console
9312 // object is used to power up a VM twice. VirtualBox 4.0: we now do that
9313 // here instead of the Console constructor (see Console::init())
9314 if (!pConsole->m_pVMMDev)
9315 {
9316 pConsole->m_pVMMDev = new VMMDev(pConsole);
9317 AssertReturn(pConsole->m_pVMMDev, E_FAIL);
9318 }
9319
9320 /* wait for auto reset ops to complete so that we can successfully lock
9321 * the attached hard disks by calling LockMedia() below */
9322 for (VMPowerUpTask::ProgressList::const_iterator
9323 it = task->hardDiskProgresses.begin();
9324 it != task->hardDiskProgresses.end(); ++it)
9325 {
9326 HRESULT rc2 = (*it)->WaitForCompletion(-1);
9327 AssertComRC(rc2);
9328
9329 rc = task->mProgress->SetNextOperation(BstrFmt(tr("Disk Image Reset Operation - Immutable Image")).raw(), 1);
9330 AssertComRCReturnRC(rc);
9331 }
9332
9333 /*
9334 * Lock attached media. This method will also check their accessibility.
9335 * If we're a teleporter, we'll have to postpone this action so we can
9336 * migrate between local processes.
9337 *
9338 * Note! The media will be unlocked automatically by
9339 * SessionMachine::i_setMachineState() when the VM is powered down.
9340 */
9341 if ( !task->mTeleporterEnabled
9342 && task->mEnmFaultToleranceState != FaultToleranceState_Standby)
9343 {
9344 rc = pConsole->mControl->LockMedia();
9345 if (FAILED(rc)) throw rc;
9346 }
9347
9348 /* Create the VRDP server. In case of headless operation, this will
9349 * also create the framebuffer, required at VM creation.
9350 */
9351 ConsoleVRDPServer *server = pConsole->i_consoleVRDPServer();
9352 Assert(server);
9353
9354 /* Does VRDP server call Console from the other thread?
9355 * Not sure (and can change), so release the lock just in case.
9356 */
9357 alock.release();
9358 vrc = server->Launch();
9359 alock.acquire();
9360
9361 if (vrc == VERR_NET_ADDRESS_IN_USE)
9362 {
9363 Utf8Str errMsg;
9364 Bstr bstr;
9365 pConsole->mVRDEServer->GetVRDEProperty(Bstr("TCP/Ports").raw(), bstr.asOutParam());
9366 Utf8Str ports = bstr;
9367 errMsg = Utf8StrFmt(tr("VirtualBox Remote Desktop Extension server can't bind to the port: %s"),
9368 ports.c_str());
9369 LogRel(("VRDE: Warning: failed to launch VRDE server (%Rrc): '%s'\n",
9370 vrc, errMsg.c_str()));
9371 }
9372 else if (vrc == VINF_NOT_SUPPORTED)
9373 {
9374 /* This means that the VRDE is not installed. */
9375 LogRel(("VRDE: VirtualBox Remote Desktop Extension is not available.\n"));
9376 }
9377 else if (RT_FAILURE(vrc))
9378 {
9379 /* Fail, if the server is installed but can't start. */
9380 Utf8Str errMsg;
9381 switch (vrc)
9382 {
9383 case VERR_FILE_NOT_FOUND:
9384 {
9385 /* VRDE library file is missing. */
9386 errMsg = Utf8StrFmt(tr("Could not find the VirtualBox Remote Desktop Extension library."));
9387 break;
9388 }
9389 default:
9390 errMsg = Utf8StrFmt(tr("Failed to launch Remote Desktop Extension server (%Rrc)"),
9391 vrc);
9392 }
9393 LogRel(("VRDE: Failed: (%Rrc), error message: '%s'\n",
9394 vrc, errMsg.c_str()));
9395 throw i_setErrorStatic(E_FAIL, errMsg.c_str());
9396 }
9397
9398 ComPtr<IMachine> pMachine = pConsole->i_machine();
9399 ULONG cCpus = 1;
9400 pMachine->COMGETTER(CPUCount)(&cCpus);
9401
9402 /*
9403 * Create the VM
9404 *
9405 * Note! Release the lock since EMT will call Console. It's safe because
9406 * mMachineState is either Starting or Restoring state here.
9407 */
9408 alock.release();
9409
9410 PVM pVM;
9411 vrc = VMR3Create(cCpus,
9412 pConsole->mpVmm2UserMethods,
9413 Console::i_genericVMSetErrorCallback,
9414 &task->mErrorMsg,
9415 task->mConfigConstructor,
9416 static_cast<Console *>(pConsole),
9417 &pVM, NULL);
9418
9419 alock.acquire();
9420
9421 /* Enable client connections to the server. */
9422 pConsole->i_consoleVRDPServer()->EnableConnections();
9423
9424 if (RT_SUCCESS(vrc))
9425 {
9426 do
9427 {
9428 /*
9429 * Register our load/save state file handlers
9430 */
9431 vrc = SSMR3RegisterExternal(pConsole->mpUVM, sSSMConsoleUnit, 0 /*iInstance*/, sSSMConsoleVer, 0 /* cbGuess */,
9432 NULL, NULL, NULL,
9433 NULL, i_saveStateFileExec, NULL,
9434 NULL, i_loadStateFileExec, NULL,
9435 static_cast<Console *>(pConsole));
9436 AssertRCBreak(vrc);
9437
9438 vrc = static_cast<Console *>(pConsole)->i_getDisplay()->i_registerSSM(pConsole->mpUVM);
9439 AssertRC(vrc);
9440 if (RT_FAILURE(vrc))
9441 break;
9442
9443 /*
9444 * Synchronize debugger settings
9445 */
9446 MachineDebugger *machineDebugger = pConsole->i_getMachineDebugger();
9447 if (machineDebugger)
9448 machineDebugger->i_flushQueuedSettings();
9449
9450 /*
9451 * Shared Folders
9452 */
9453 if (pConsole->m_pVMMDev->isShFlActive())
9454 {
9455 /* Does the code below call Console from the other thread?
9456 * Not sure, so release the lock just in case. */
9457 alock.release();
9458
9459 for (SharedFolderDataMap::const_iterator it = task->mSharedFolders.begin();
9460 it != task->mSharedFolders.end();
9461 ++it)
9462 {
9463 const SharedFolderData &d = it->second;
9464 rc = pConsole->i_createSharedFolder(it->first, d);
9465 if (FAILED(rc))
9466 {
9467 ErrorInfoKeeper eik;
9468 pConsole->i_setVMRuntimeErrorCallbackF(0, "BrokenSharedFolder",
9469 N_("The shared folder '%s' could not be set up: %ls.\n"
9470 "The shared folder setup will not be complete. It is recommended to power down the virtual "
9471 "machine and fix the shared folder settings while the machine is not running"),
9472 it->first.c_str(), eik.getText().raw());
9473 }
9474 }
9475 if (FAILED(rc))
9476 rc = S_OK; // do not fail with broken shared folders
9477
9478 /* acquire the lock again */
9479 alock.acquire();
9480 }
9481
9482 /* release the lock before a lengthy operation */
9483 alock.release();
9484
9485 /*
9486 * Capture USB devices.
9487 */
9488 rc = pConsole->i_captureUSBDevices(pConsole->mpUVM);
9489 if (FAILED(rc))
9490 break;
9491
9492 /* Load saved state? */
9493 if (task->mSavedStateFile.length())
9494 {
9495 LogFlowFunc(("Restoring saved state from '%s'...\n",
9496 task->mSavedStateFile.c_str()));
9497
9498 vrc = VMR3LoadFromFile(pConsole->mpUVM,
9499 task->mSavedStateFile.c_str(),
9500 Console::i_stateProgressCallback,
9501 static_cast<IProgress *>(task->mProgress));
9502
9503 if (RT_SUCCESS(vrc))
9504 {
9505 if (task->mStartPaused)
9506 /* done */
9507 pConsole->i_setMachineState(MachineState_Paused);
9508 else
9509 {
9510 /* Start/Resume the VM execution */
9511#ifdef VBOX_WITH_EXTPACK
9512 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM);
9513#endif
9514 if (RT_SUCCESS(vrc))
9515 vrc = VMR3Resume(pConsole->mpUVM, VMRESUMEREASON_STATE_RESTORED);
9516 AssertLogRelRC(vrc);
9517 }
9518 }
9519
9520 /* Power off in case we failed loading or resuming the VM */
9521 if (RT_FAILURE(vrc))
9522 {
9523 int vrc2 = VMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
9524#ifdef VBOX_WITH_EXTPACK
9525 pConsole->mptrExtPackManager->i_callAllVmPowerOffHooks(pConsole, pVM);
9526#endif
9527 }
9528 }
9529 else if (task->mTeleporterEnabled)
9530 {
9531 /* -> ConsoleImplTeleporter.cpp */
9532 bool fPowerOffOnFailure;
9533 rc = pConsole->i_teleporterTrg(pConsole->mpUVM, pMachine, &task->mErrorMsg, task->mStartPaused,
9534 task->mProgress, &fPowerOffOnFailure);
9535 if (FAILED(rc) && fPowerOffOnFailure)
9536 {
9537 ErrorInfoKeeper eik;
9538 int vrc2 = VMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
9539#ifdef VBOX_WITH_EXTPACK
9540 pConsole->mptrExtPackManager->i_callAllVmPowerOffHooks(pConsole, pVM);
9541#endif
9542 }
9543 }
9544 else if (task->mEnmFaultToleranceState != FaultToleranceState_Inactive)
9545 {
9546 /*
9547 * Get the config.
9548 */
9549 ULONG uPort;
9550 ULONG uInterval;
9551 Bstr bstrAddress, bstrPassword;
9552
9553 rc = pMachine->COMGETTER(FaultTolerancePort)(&uPort);
9554 if (SUCCEEDED(rc))
9555 {
9556 rc = pMachine->COMGETTER(FaultToleranceSyncInterval)(&uInterval);
9557 if (SUCCEEDED(rc))
9558 rc = pMachine->COMGETTER(FaultToleranceAddress)(bstrAddress.asOutParam());
9559 if (SUCCEEDED(rc))
9560 rc = pMachine->COMGETTER(FaultTolerancePassword)(bstrPassword.asOutParam());
9561 }
9562 if (task->mProgress->i_setCancelCallback(faultToleranceProgressCancelCallback, pConsole->mpUVM))
9563 {
9564 if (SUCCEEDED(rc))
9565 {
9566 Utf8Str strAddress(bstrAddress);
9567 const char *pszAddress = strAddress.isEmpty() ? NULL : strAddress.c_str();
9568 Utf8Str strPassword(bstrPassword);
9569 const char *pszPassword = strPassword.isEmpty() ? NULL : strPassword.c_str();
9570
9571 /* Power on the FT enabled VM. */
9572#ifdef VBOX_WITH_EXTPACK
9573 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM);
9574#endif
9575 if (RT_SUCCESS(vrc))
9576 vrc = FTMR3PowerOn(pConsole->mpUVM,
9577 task->mEnmFaultToleranceState == FaultToleranceState_Master /* fMaster */,
9578 uInterval,
9579 pszAddress,
9580 uPort,
9581 pszPassword);
9582 AssertLogRelRC(vrc);
9583 }
9584 task->mProgress->i_setCancelCallback(NULL, NULL);
9585 }
9586 else
9587 rc = E_FAIL;
9588 }
9589 else if (task->mStartPaused)
9590 /* done */
9591 pConsole->i_setMachineState(MachineState_Paused);
9592 else
9593 {
9594 /* Power on the VM (i.e. start executing) */
9595#ifdef VBOX_WITH_EXTPACK
9596 vrc = pConsole->mptrExtPackManager->i_callAllVmPowerOnHooks(pConsole, pVM);
9597#endif
9598 if (RT_SUCCESS(vrc))
9599 vrc = VMR3PowerOn(pConsole->mpUVM);
9600 AssertLogRelRC(vrc);
9601 }
9602
9603 /* acquire the lock again */
9604 alock.acquire();
9605 }
9606 while (0);
9607
9608 /* On failure, destroy the VM */
9609 if (FAILED(rc) || RT_FAILURE(vrc))
9610 {
9611 /* preserve existing error info */
9612 ErrorInfoKeeper eik;
9613
9614 /* powerDown() will call VMR3Destroy() and do all necessary
9615 * cleanup (VRDP, USB devices) */
9616 alock.release();
9617 HRESULT rc2 = pConsole->i_powerDown();
9618 alock.acquire();
9619 AssertComRC(rc2);
9620 }
9621 else
9622 {
9623 /*
9624 * Deregister the VMSetError callback. This is necessary as the
9625 * pfnVMAtError() function passed to VMR3Create() is supposed to
9626 * be sticky but our error callback isn't.
9627 */
9628 alock.release();
9629 VMR3AtErrorDeregister(pConsole->mpUVM, Console::i_genericVMSetErrorCallback, &task->mErrorMsg);
9630 /** @todo register another VMSetError callback? */
9631 alock.acquire();
9632 }
9633 }
9634 else
9635 {
9636 /*
9637 * If VMR3Create() failed it has released the VM memory.
9638 */
9639 VMR3ReleaseUVM(pConsole->mpUVM);
9640 pConsole->mpUVM = NULL;
9641 }
9642
9643 if (SUCCEEDED(rc) && RT_FAILURE(vrc))
9644 {
9645 /* If VMR3Create() or one of the other calls in this function fail,
9646 * an appropriate error message has been set in task->mErrorMsg.
9647 * However since that happens via a callback, the rc status code in
9648 * this function is not updated.
9649 */
9650 if (!task->mErrorMsg.length())
9651 {
9652 /* If the error message is not set but we've got a failure,
9653 * convert the VBox status code into a meaningful error message.
9654 * This becomes unused once all the sources of errors set the
9655 * appropriate error message themselves.
9656 */
9657 AssertMsgFailed(("Missing error message during powerup for status code %Rrc\n", vrc));
9658 task->mErrorMsg = Utf8StrFmt(tr("Failed to start VM execution (%Rrc)"),
9659 vrc);
9660 }
9661
9662 /* Set the error message as the COM error.
9663 * Progress::notifyComplete() will pick it up later. */
9664 throw i_setErrorStatic(E_FAIL, task->mErrorMsg.c_str());
9665 }
9666 }
9667 catch (HRESULT aRC) { rc = aRC; }
9668
9669 if ( pConsole->mMachineState == MachineState_Starting
9670 || pConsole->mMachineState == MachineState_Restoring
9671 || pConsole->mMachineState == MachineState_TeleportingIn
9672 )
9673 {
9674 /* We are still in the Starting/Restoring state. This means one of:
9675 *
9676 * 1) we failed before VMR3Create() was called;
9677 * 2) VMR3Create() failed.
9678 *
9679 * In both cases, there is no need to call powerDown(), but we still
9680 * need to go back to the PoweredOff/Saved state. Reuse
9681 * vmstateChangeCallback() for that purpose.
9682 */
9683
9684 /* preserve existing error info */
9685 ErrorInfoKeeper eik;
9686
9687 Assert(pConsole->mpUVM == NULL);
9688 i_vmstateChangeCallback(NULL, VMSTATE_TERMINATED, VMSTATE_CREATING, pConsole);
9689 }
9690
9691 /*
9692 * Evaluate the final result. Note that the appropriate mMachineState value
9693 * is already set by vmstateChangeCallback() in all cases.
9694 */
9695
9696 /* release the lock, don't need it any more */
9697 alock.release();
9698
9699 if (SUCCEEDED(rc))
9700 {
9701 /* Notify the progress object of the success */
9702 task->mProgress->i_notifyComplete(S_OK);
9703 }
9704 else
9705 {
9706 /* The progress object will fetch the current error info */
9707 task->mProgress->i_notifyComplete(rc);
9708 LogRel(("Power up failed (vrc=%Rrc, rc=%Rhrc (%#08X))\n", vrc, rc, rc));
9709 }
9710
9711 /* Notify VBoxSVC and any waiting openRemoteSession progress object. */
9712 pConsole->mControl->EndPowerUp(rc);
9713
9714#if defined(RT_OS_WINDOWS)
9715 /* uninitialize COM */
9716 CoUninitialize();
9717#endif
9718
9719 LogFlowFuncLeave();
9720
9721 return VINF_SUCCESS;
9722}
9723
9724
9725/**
9726 * Reconfigures a medium attachment (part of taking or deleting an online snapshot).
9727 *
9728 * @param pThis Reference to the console object.
9729 * @param pUVM The VM handle.
9730 * @param lInstance The instance of the controller.
9731 * @param pcszDevice The name of the controller type.
9732 * @param enmBus The storage bus type of the controller.
9733 * @param fSetupMerge Whether to set up a medium merge
9734 * @param uMergeSource Merge source image index
9735 * @param uMergeTarget Merge target image index
9736 * @param aMediumAtt The medium attachment.
9737 * @param aMachineState The current machine state.
9738 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
9739 * @return VBox status code.
9740 */
9741/* static */
9742DECLCALLBACK(int) Console::i_reconfigureMediumAttachment(Console *pThis,
9743 PUVM pUVM,
9744 const char *pcszDevice,
9745 unsigned uInstance,
9746 StorageBus_T enmBus,
9747 bool fUseHostIOCache,
9748 bool fBuiltinIOCache,
9749 bool fSetupMerge,
9750 unsigned uMergeSource,
9751 unsigned uMergeTarget,
9752 IMediumAttachment *aMediumAtt,
9753 MachineState_T aMachineState,
9754 HRESULT *phrc)
9755{
9756 LogFlowFunc(("pUVM=%p aMediumAtt=%p phrc=%p\n", pUVM, aMediumAtt, phrc));
9757
9758 HRESULT hrc;
9759 Bstr bstr;
9760 *phrc = S_OK;
9761#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%Rhrc (%#x)\n", hrc, hrc)); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
9762
9763 /* Ignore attachments other than hard disks, since at the moment they are
9764 * not subject to snapshotting in general. */
9765 DeviceType_T lType;
9766 hrc = aMediumAtt->COMGETTER(Type)(&lType); H();
9767 if (lType != DeviceType_HardDisk)
9768 return VINF_SUCCESS;
9769
9770 /* Update the device instance configuration. */
9771 int rc = pThis->i_configMediumAttachment(pcszDevice,
9772 uInstance,
9773 enmBus,
9774 fUseHostIOCache,
9775 fBuiltinIOCache,
9776 fSetupMerge,
9777 uMergeSource,
9778 uMergeTarget,
9779 aMediumAtt,
9780 aMachineState,
9781 phrc,
9782 true /* fAttachDetach */,
9783 false /* fForceUnmount */,
9784 false /* fHotplug */,
9785 pUVM,
9786 NULL /* paLedDevType */,
9787 NULL /* ppLunL0)*/);
9788 if (RT_FAILURE(rc))
9789 {
9790 AssertMsgFailed(("rc=%Rrc\n", rc));
9791 return rc;
9792 }
9793
9794#undef H
9795
9796 LogFlowFunc(("Returns success\n"));
9797 return VINF_SUCCESS;
9798}
9799
9800/**
9801 * Progress cancelation callback employed by Console::fntTakeSnapshotWorker.
9802 */
9803static void takesnapshotProgressCancelCallback(void *pvUser)
9804{
9805 PUVM pUVM = (PUVM)pvUser;
9806 SSMR3Cancel(pUVM);
9807}
9808
9809/**
9810 * Worker thread created by Console::TakeSnapshot.
9811 * @param Thread The current thread (ignored).
9812 * @param pvUser The task.
9813 * @return VINF_SUCCESS (ignored).
9814 */
9815/*static*/
9816DECLCALLBACK(int) Console::i_fntTakeSnapshotWorker(RTTHREAD Thread, void *pvUser)
9817{
9818 VMTakeSnapshotTask *pTask = (VMTakeSnapshotTask*)pvUser;
9819
9820 // taking a snapshot consists of the following:
9821
9822 // 1) creating a diff image for each virtual hard disk, into which write operations go after
9823 // the snapshot has been created (done in VBoxSVC, in SessionMachine::BeginTakingSnapshot)
9824 // 2) creating a Snapshot object with the state of the machine (hardware + storage,
9825 // done in VBoxSVC, also in SessionMachine::BeginTakingSnapshot)
9826 // 3) saving the state of the virtual machine (here, in the VM process, if the machine is online)
9827
9828 Console *that = pTask->mConsole;
9829 bool fBeganTakingSnapshot = false;
9830 bool fSuspenededBySave = false;
9831
9832 AutoCaller autoCaller(that);
9833 if (FAILED(autoCaller.rc()))
9834 {
9835 that->mptrCancelableProgress.setNull();
9836 return autoCaller.rc();
9837 }
9838
9839 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9840
9841 HRESULT rc = S_OK;
9842
9843 try
9844 {
9845 /* STEP 1 + 2:
9846 * request creating the diff images on the server and create the snapshot object
9847 * (this will set the machine state to Saving on the server to block
9848 * others from accessing this machine)
9849 */
9850 rc = that->mControl->BeginTakingSnapshot(that,
9851 pTask->bstrName.raw(),
9852 pTask->bstrDescription.raw(),
9853 pTask->mProgress,
9854 pTask->fTakingSnapshotOnline,
9855 pTask->bstrSavedStateFile.asOutParam());
9856 if (FAILED(rc))
9857 throw rc;
9858
9859 fBeganTakingSnapshot = true;
9860
9861 /* Check sanity: for offline snapshots there must not be a saved state
9862 * file name. All other combinations are valid (even though online
9863 * snapshots without saved state file seems inconsistent - there are
9864 * some exotic use cases, which need to be explicitly enabled, see the
9865 * code of SessionMachine::BeginTakingSnapshot. */
9866 if ( !pTask->fTakingSnapshotOnline
9867 && !pTask->bstrSavedStateFile.isEmpty())
9868 throw i_setErrorStatic(E_FAIL, "Invalid state of saved state file");
9869
9870 /* sync the state with the server */
9871 if (pTask->lastMachineState == MachineState_Running)
9872 that->i_setMachineStateLocally(MachineState_LiveSnapshotting);
9873 else
9874 that->i_setMachineStateLocally(MachineState_Saving);
9875
9876 // STEP 3: save the VM state (if online)
9877 if (pTask->fTakingSnapshotOnline)
9878 {
9879 int vrc;
9880 SafeVMPtr ptrVM(that);
9881 if (!ptrVM.isOk())
9882 throw ptrVM.rc();
9883
9884 pTask->mProgress->SetNextOperation(Bstr(tr("Saving the machine state")).raw(),
9885 pTask->ulMemSize); // operation weight, same as computed
9886 // when setting up progress object
9887 if (!pTask->bstrSavedStateFile.isEmpty())
9888 {
9889 Utf8Str strSavedStateFile(pTask->bstrSavedStateFile);
9890
9891 pTask->mProgress->i_setCancelCallback(takesnapshotProgressCancelCallback, ptrVM.rawUVM());
9892
9893 alock.release();
9894 LogFlowFunc(("VMR3Save...\n"));
9895 vrc = VMR3Save(ptrVM.rawUVM(),
9896 strSavedStateFile.c_str(),
9897 true /*fContinueAfterwards*/,
9898 Console::i_stateProgressCallback,
9899 static_cast<IProgress *>(pTask->mProgress),
9900 &fSuspenededBySave);
9901 alock.acquire();
9902 if (RT_FAILURE(vrc))
9903 throw i_setErrorStatic(E_FAIL,
9904 tr("Failed to save the machine state to '%s' (%Rrc)"),
9905 strSavedStateFile.c_str(), vrc);
9906
9907 pTask->mProgress->i_setCancelCallback(NULL, NULL);
9908 }
9909 else
9910 LogRel(("Console: skipped saving state as part of online snapshot\n"));
9911
9912 if (!pTask->mProgress->i_notifyPointOfNoReturn())
9913 throw i_setErrorStatic(E_FAIL, tr("Canceled"));
9914 that->mptrCancelableProgress.setNull();
9915
9916 // STEP 4: reattach hard disks
9917 LogFlowFunc(("Reattaching new differencing hard disks...\n"));
9918
9919 pTask->mProgress->SetNextOperation(Bstr(tr("Reconfiguring medium attachments")).raw(),
9920 1); // operation weight, same as computed when setting up progress object
9921
9922 com::SafeIfaceArray<IMediumAttachment> atts;
9923 rc = that->mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
9924 if (FAILED(rc))
9925 throw rc;
9926
9927 for (size_t i = 0;
9928 i < atts.size();
9929 ++i)
9930 {
9931 ComPtr<IStorageController> pStorageController;
9932 Bstr controllerName;
9933 ULONG lInstance;
9934 StorageControllerType_T enmController;
9935 StorageBus_T enmBus;
9936 BOOL fUseHostIOCache;
9937
9938 /*
9939 * We can't pass a storage controller object directly
9940 * (g++ complains about not being able to pass non POD types through '...')
9941 * so we have to query needed values here and pass them.
9942 */
9943 rc = atts[i]->COMGETTER(Controller)(controllerName.asOutParam());
9944 if (FAILED(rc))
9945 throw rc;
9946
9947 rc = that->mMachine->GetStorageControllerByName(controllerName.raw(),
9948 pStorageController.asOutParam());
9949 if (FAILED(rc))
9950 throw rc;
9951
9952 rc = pStorageController->COMGETTER(ControllerType)(&enmController);
9953 if (FAILED(rc))
9954 throw rc;
9955 rc = pStorageController->COMGETTER(Instance)(&lInstance);
9956 if (FAILED(rc))
9957 throw rc;
9958 rc = pStorageController->COMGETTER(Bus)(&enmBus);
9959 if (FAILED(rc))
9960 throw rc;
9961 rc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
9962 if (FAILED(rc))
9963 throw rc;
9964
9965 const char *pcszDevice = Console::i_convertControllerTypeToDev(enmController);
9966
9967 BOOL fBuiltinIOCache;
9968 rc = that->mMachine->COMGETTER(IOCacheEnabled)(&fBuiltinIOCache);
9969 if (FAILED(rc))
9970 throw rc;
9971
9972 /*
9973 * don't release the lock since reconfigureMediumAttachment
9974 * isn't going to need the Console lock.
9975 */
9976
9977 /* TODO: do alock.release here as EMT might wait on it! See other places
9978 * where we do VMR3ReqCall requests. See @bugref{7648}. */
9979 vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY,
9980 (PFNRT)i_reconfigureMediumAttachment, 13,
9981 that, ptrVM.rawUVM(), pcszDevice, lInstance, enmBus, fUseHostIOCache,
9982 fBuiltinIOCache, false /* fSetupMerge */, 0 /* uMergeSource */,
9983 0 /* uMergeTarget */, atts[i], that->mMachineState, &rc);
9984 if (RT_FAILURE(vrc))
9985 throw i_setErrorStatic(E_FAIL, Console::tr("%Rrc"), vrc);
9986 if (FAILED(rc))
9987 throw rc;
9988 }
9989 }
9990
9991 /*
9992 * finalize the requested snapshot object.
9993 * This will reset the machine state to the state it had right
9994 * before calling mControl->BeginTakingSnapshot().
9995 */
9996 rc = that->mControl->EndTakingSnapshot(TRUE /*aSuccess*/);
9997 // do not throw rc here because we can't call EndTakingSnapshot() twice
9998 LogFlowFunc(("EndTakingSnapshot -> %Rhrc [mMachineState=%s]\n", rc, Global::stringifyMachineState(that->mMachineState)));
9999 }
10000 catch (HRESULT rcThrown)
10001 {
10002 /* preserve existing error info */
10003 ErrorInfoKeeper eik;
10004
10005 if (fBeganTakingSnapshot)
10006 that->mControl->EndTakingSnapshot(FALSE /*aSuccess*/);
10007
10008 rc = rcThrown;
10009 LogFunc(("Caught %Rhrc [mMachineState=%s]\n", rc, Global::stringifyMachineState(that->mMachineState)));
10010 }
10011 Assert(alock.isWriteLockOnCurrentThread());
10012
10013 if (FAILED(rc)) /* Must come before calling setMachineState. */
10014 pTask->mProgress->i_notifyComplete(rc);
10015
10016 /*
10017 * Fix up the machine state.
10018 *
10019 * For live snapshots we do all the work, for the two other variations we
10020 * just update the local copy.
10021 */
10022 MachineState_T enmMachineState;
10023 that->mMachine->COMGETTER(State)(&enmMachineState);
10024 if ( that->mMachineState == MachineState_LiveSnapshotting
10025 || that->mMachineState == MachineState_Saving)
10026 {
10027
10028 if (!pTask->fTakingSnapshotOnline)
10029 that->i_setMachineStateLocally(pTask->lastMachineState);
10030 else if (SUCCEEDED(rc))
10031 {
10032 Assert( pTask->lastMachineState == MachineState_Running
10033 || pTask->lastMachineState == MachineState_Paused);
10034 Assert(that->mMachineState == MachineState_Saving);
10035 if (pTask->lastMachineState == MachineState_Running)
10036 {
10037 LogFlowFunc(("VMR3Resume...\n"));
10038 SafeVMPtr ptrVM(that);
10039 alock.release();
10040 int vrc = VMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_STATE_SAVED);
10041 alock.acquire();
10042 if (RT_FAILURE(vrc))
10043 {
10044 rc = i_setErrorStatic(VBOX_E_VM_ERROR, tr("Could not resume the machine execution (%Rrc)"), vrc);
10045 pTask->mProgress->i_notifyComplete(rc);
10046 if (that->mMachineState == MachineState_Saving)
10047 that->i_setMachineStateLocally(MachineState_Paused);
10048 }
10049 }
10050 else
10051 that->i_setMachineStateLocally(MachineState_Paused);
10052 }
10053 else
10054 {
10055 /** @todo this could probably be made more generic and reused elsewhere. */
10056 /* paranoid cleanup on for a failed online snapshot. */
10057 VMSTATE enmVMState = VMR3GetStateU(that->mpUVM);
10058 switch (enmVMState)
10059 {
10060 case VMSTATE_RUNNING:
10061 case VMSTATE_RUNNING_LS:
10062 case VMSTATE_DEBUGGING:
10063 case VMSTATE_DEBUGGING_LS:
10064 case VMSTATE_POWERING_OFF:
10065 case VMSTATE_POWERING_OFF_LS:
10066 case VMSTATE_RESETTING:
10067 case VMSTATE_RESETTING_LS:
10068 Assert(!fSuspenededBySave);
10069 that->i_setMachineState(MachineState_Running);
10070 break;
10071
10072 case VMSTATE_GURU_MEDITATION:
10073 case VMSTATE_GURU_MEDITATION_LS:
10074 that->i_setMachineState(MachineState_Stuck);
10075 break;
10076
10077 case VMSTATE_FATAL_ERROR:
10078 case VMSTATE_FATAL_ERROR_LS:
10079 if (pTask->lastMachineState == MachineState_Paused)
10080 that->i_setMachineStateLocally(pTask->lastMachineState);
10081 else
10082 that->i_setMachineState(MachineState_Paused);
10083 break;
10084
10085 default:
10086 AssertMsgFailed(("%s\n", VMR3GetStateName(enmVMState)));
10087 case VMSTATE_SUSPENDED:
10088 case VMSTATE_SUSPENDED_LS:
10089 case VMSTATE_SUSPENDING:
10090 case VMSTATE_SUSPENDING_LS:
10091 case VMSTATE_SUSPENDING_EXT_LS:
10092 if (fSuspenededBySave)
10093 {
10094 Assert(pTask->lastMachineState == MachineState_Running);
10095 LogFlowFunc(("VMR3Resume (on failure)...\n"));
10096 SafeVMPtr ptrVM(that);
10097 alock.release();
10098 int vrc = VMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_STATE_SAVED); AssertLogRelRC(vrc);
10099 alock.acquire();
10100 if (RT_FAILURE(vrc))
10101 that->i_setMachineState(MachineState_Paused);
10102 }
10103 else if (pTask->lastMachineState == MachineState_Paused)
10104 that->i_setMachineStateLocally(pTask->lastMachineState);
10105 else
10106 that->i_setMachineState(MachineState_Paused);
10107 break;
10108 }
10109
10110 }
10111 }
10112 /*else: somebody else has change the state... Leave it. */
10113
10114 /* check the remote state to see that we got it right. */
10115 that->mMachine->COMGETTER(State)(&enmMachineState);
10116 AssertLogRelMsg(that->mMachineState == enmMachineState,
10117 ("mMachineState=%s enmMachineState=%s\n", Global::stringifyMachineState(that->mMachineState),
10118 Global::stringifyMachineState(enmMachineState) ));
10119
10120
10121 if (SUCCEEDED(rc)) /* The failure cases are handled above. */
10122 pTask->mProgress->i_notifyComplete(rc);
10123
10124 delete pTask;
10125
10126 LogFlowFuncLeave();
10127 return VINF_SUCCESS;
10128}
10129
10130/**
10131 * Thread for executing the saved state operation.
10132 *
10133 * @param Thread The thread handle.
10134 * @param pvUser Pointer to a VMSaveTask structure.
10135 * @return VINF_SUCCESS (ignored).
10136 *
10137 * @note Locks the Console object for writing.
10138 */
10139/*static*/
10140DECLCALLBACK(int) Console::i_saveStateThread(RTTHREAD Thread, void *pvUser)
10141{
10142 LogFlowFuncEnter();
10143
10144 std::auto_ptr<VMSaveTask> task(static_cast<VMSaveTask*>(pvUser));
10145 AssertReturn(task.get(), VERR_INVALID_PARAMETER);
10146
10147 Assert(task->mSavedStateFile.length());
10148 Assert(task->mProgress.isNull());
10149 Assert(!task->mServerProgress.isNull());
10150
10151 const ComObjPtr<Console> &that = task->mConsole;
10152 Utf8Str errMsg;
10153 HRESULT rc = S_OK;
10154
10155 LogFlowFunc(("Saving the state to '%s'...\n", task->mSavedStateFile.c_str()));
10156
10157 bool fSuspenededBySave;
10158 int vrc = VMR3Save(task->mpUVM,
10159 task->mSavedStateFile.c_str(),
10160 false, /*fContinueAfterwards*/
10161 Console::i_stateProgressCallback,
10162 static_cast<IProgress *>(task->mServerProgress),
10163 &fSuspenededBySave);
10164 if (RT_FAILURE(vrc))
10165 {
10166 errMsg = Utf8StrFmt(Console::tr("Failed to save the machine state to '%s' (%Rrc)"),
10167 task->mSavedStateFile.c_str(), vrc);
10168 rc = E_FAIL;
10169 }
10170 Assert(!fSuspenededBySave);
10171
10172 /* lock the console once we're going to access it */
10173 AutoWriteLock thatLock(that COMMA_LOCKVAL_SRC_POS);
10174
10175 /* synchronize the state with the server */
10176 if (SUCCEEDED(rc))
10177 {
10178 /*
10179 * The machine has been successfully saved, so power it down
10180 * (vmstateChangeCallback() will set state to Saved on success).
10181 * Note: we release the task's VM caller, otherwise it will
10182 * deadlock.
10183 */
10184 task->releaseVMCaller();
10185 thatLock.release();
10186 rc = that->i_powerDown();
10187 thatLock.acquire();
10188 }
10189
10190 /*
10191 * If we failed, reset the local machine state.
10192 */
10193 if (FAILED(rc))
10194 that->i_setMachineStateLocally(task->mMachineStateBefore);
10195
10196 /*
10197 * Finalize the requested save state procedure. In case of failure it will
10198 * reset the machine state to the state it had right before calling
10199 * mControl->BeginSavingState(). This must be the last thing because it
10200 * will set the progress to completed, and that means that the frontend
10201 * can immediately uninit the associated console object.
10202 */
10203 that->mControl->EndSavingState(rc, Bstr(errMsg).raw());
10204
10205 LogFlowFuncLeave();
10206 return VINF_SUCCESS;
10207}
10208
10209/**
10210 * Thread for powering down the Console.
10211 *
10212 * @param Thread The thread handle.
10213 * @param pvUser Pointer to the VMTask structure.
10214 * @return VINF_SUCCESS (ignored).
10215 *
10216 * @note Locks the Console object for writing.
10217 */
10218/*static*/
10219DECLCALLBACK(int) Console::i_powerDownThread(RTTHREAD Thread, void *pvUser)
10220{
10221 LogFlowFuncEnter();
10222
10223 std::auto_ptr<VMPowerDownTask> task(static_cast<VMPowerDownTask *>(pvUser));
10224 AssertReturn(task.get(), VERR_INVALID_PARAMETER);
10225
10226 AssertReturn(task->isOk(), VERR_GENERAL_FAILURE);
10227
10228 Assert(task->mProgress.isNull());
10229
10230 const ComObjPtr<Console> &that = task->mConsole;
10231
10232 /* Note: no need to use addCaller() to protect Console because VMTask does
10233 * that */
10234
10235 /* wait until the method tat started us returns */
10236 AutoWriteLock thatLock(that COMMA_LOCKVAL_SRC_POS);
10237
10238 /* release VM caller to avoid the powerDown() deadlock */
10239 task->releaseVMCaller();
10240
10241 thatLock.release();
10242
10243 that->i_powerDown(task->mServerProgress);
10244
10245 /* complete the operation */
10246 that->mControl->EndPoweringDown(S_OK, Bstr().raw());
10247
10248 LogFlowFuncLeave();
10249 return VINF_SUCCESS;
10250}
10251
10252
10253/**
10254 * @interface_method_impl{VMM2USERMETHODS,pfnSaveState}
10255 */
10256/*static*/ DECLCALLBACK(int)
10257Console::i_vmm2User_SaveState(PCVMM2USERMETHODS pThis, PUVM pUVM)
10258{
10259 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
10260 NOREF(pUVM);
10261
10262 /*
10263 * For now, just call SaveState. We should probably try notify the GUI so
10264 * it can pop up a progress object and stuff.
10265 */
10266 HRESULT hrc = pConsole->SaveState(NULL);
10267 return SUCCEEDED(hrc) ? VINF_SUCCESS : Global::vboxStatusCodeFromCOM(hrc);
10268}
10269
10270/**
10271 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtInit}
10272 */
10273/*static*/ DECLCALLBACK(void)
10274Console::i_vmm2User_NotifyEmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
10275{
10276 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
10277 VirtualBoxBase::initializeComForThread();
10278}
10279
10280/**
10281 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtTerm}
10282 */
10283/*static*/ DECLCALLBACK(void)
10284Console::i_vmm2User_NotifyEmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
10285{
10286 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
10287 VirtualBoxBase::uninitializeComForThread();
10288}
10289
10290/**
10291 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtInit}
10292 */
10293/*static*/ DECLCALLBACK(void)
10294Console::i_vmm2User_NotifyPdmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM)
10295{
10296 NOREF(pThis); NOREF(pUVM);
10297 VirtualBoxBase::initializeComForThread();
10298}
10299
10300/**
10301 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtTerm}
10302 */
10303/*static*/ DECLCALLBACK(void)
10304Console::i_vmm2User_NotifyPdmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM)
10305{
10306 NOREF(pThis); NOREF(pUVM);
10307 VirtualBoxBase::uninitializeComForThread();
10308}
10309
10310/**
10311 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyResetTurnedIntoPowerOff}
10312 */
10313/*static*/ DECLCALLBACK(void)
10314Console::i_vmm2User_NotifyResetTurnedIntoPowerOff(PCVMM2USERMETHODS pThis, PUVM pUVM)
10315{
10316 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
10317 NOREF(pUVM);
10318
10319 pConsole->mfPowerOffCausedByReset = true;
10320}
10321
10322
10323
10324
10325/**
10326 * @interface_method_impl{PDMISECKEY,pfnKeyRetain}
10327 */
10328/*static*/ DECLCALLBACK(int)
10329Console::i_pdmIfSecKey_KeyRetain(PPDMISECKEY pInterface, const char *pszId, const uint8_t **ppbKey,
10330 size_t *pcbKey)
10331{
10332 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
10333
10334 SecretKeyMap::const_iterator it = pConsole->m_mapSecretKeys.find(Utf8Str(pszId));
10335 if (it != pConsole->m_mapSecretKeys.end())
10336 {
10337 SecretKey *pKey = (*it).second;
10338
10339 ASMAtomicIncU32(&pKey->m_cRefs);
10340 *ppbKey = pKey->m_pbKey;
10341 *pcbKey = pKey->m_cbKey;
10342 return VINF_SUCCESS;
10343 }
10344
10345 return VERR_NOT_FOUND;
10346}
10347
10348/**
10349 * @interface_method_impl{PDMISECKEY,pfnKeyRelease}
10350 */
10351/*static*/ DECLCALLBACK(int)
10352Console::i_pdmIfSecKey_KeyRelease(PPDMISECKEY pInterface, const char *pszId)
10353{
10354 Console *pConsole = ((MYPDMISECKEY *)pInterface)->pConsole;
10355 SecretKeyMap::const_iterator it = pConsole->m_mapSecretKeys.find(Utf8Str(pszId));
10356 if (it != pConsole->m_mapSecretKeys.end())
10357 {
10358 SecretKey *pKey = (*it).second;
10359 ASMAtomicDecU32(&pKey->m_cRefs);
10360 return VINF_SUCCESS;
10361 }
10362
10363 return VERR_NOT_FOUND;
10364}
10365
10366/**
10367 * @interface_method_impl{PDMISECKEYHLP,pfnKeyMissingNotify}
10368 */
10369/*static*/ DECLCALLBACK(int)
10370Console::i_pdmIfSecKeyHlp_KeyMissingNotify(PPDMISECKEYHLP pInterface)
10371{
10372 Console *pConsole = ((MYPDMISECKEYHLP *)pInterface)->pConsole;
10373
10374 /* Set guest property only, the VM is paused in the media driver calling us. */
10375 pConsole->mMachine->DeleteGuestProperty(Bstr("/VirtualBox/HostInfo/DekMissing").raw());
10376 pConsole->mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/DekMissing").raw(),
10377 Bstr("1").raw(), Bstr("RDONLYGUEST").raw());
10378 pConsole->mMachine->SaveSettings();
10379
10380 return VINF_SUCCESS;
10381}
10382
10383
10384
10385/**
10386 * The Main status driver instance data.
10387 */
10388typedef struct DRVMAINSTATUS
10389{
10390 /** The LED connectors. */
10391 PDMILEDCONNECTORS ILedConnectors;
10392 /** Pointer to the LED ports interface above us. */
10393 PPDMILEDPORTS pLedPorts;
10394 /** Pointer to the array of LED pointers. */
10395 PPDMLED *papLeds;
10396 /** The unit number corresponding to the first entry in the LED array. */
10397 RTUINT iFirstLUN;
10398 /** The unit number corresponding to the last entry in the LED array.
10399 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
10400 RTUINT iLastLUN;
10401 /** Pointer to the driver instance. */
10402 PPDMDRVINS pDrvIns;
10403 /** The Media Notify interface. */
10404 PDMIMEDIANOTIFY IMediaNotify;
10405 /** Map for translating PDM storage controller/LUN information to
10406 * IMediumAttachment references. */
10407 Console::MediumAttachmentMap *pmapMediumAttachments;
10408 /** Device name+instance for mapping */
10409 char *pszDeviceInstance;
10410 /** Pointer to the Console object, for driver triggered activities. */
10411 Console *pConsole;
10412} DRVMAINSTATUS, *PDRVMAINSTATUS;
10413
10414
10415/**
10416 * Notification about a unit which have been changed.
10417 *
10418 * The driver must discard any pointers to data owned by
10419 * the unit and requery it.
10420 *
10421 * @param pInterface Pointer to the interface structure containing the called function pointer.
10422 * @param iLUN The unit number.
10423 */
10424DECLCALLBACK(void) Console::i_drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
10425{
10426 PDRVMAINSTATUS pThis = RT_FROM_MEMBER(pInterface, DRVMAINSTATUS, ILedConnectors);
10427 if (iLUN >= pThis->iFirstLUN && iLUN <= pThis->iLastLUN)
10428 {
10429 PPDMLED pLed;
10430 int rc = pThis->pLedPorts->pfnQueryStatusLed(pThis->pLedPorts, iLUN, &pLed);
10431 if (RT_FAILURE(rc))
10432 pLed = NULL;
10433 ASMAtomicWritePtr(&pThis->papLeds[iLUN - pThis->iFirstLUN], pLed);
10434 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
10435 }
10436}
10437
10438
10439/**
10440 * Notification about a medium eject.
10441 *
10442 * @returns VBox status.
10443 * @param pInterface Pointer to the interface structure containing the called function pointer.
10444 * @param uLUN The unit number.
10445 */
10446DECLCALLBACK(int) Console::i_drvStatus_MediumEjected(PPDMIMEDIANOTIFY pInterface, unsigned uLUN)
10447{
10448 PDRVMAINSTATUS pThis = RT_FROM_MEMBER(pInterface, DRVMAINSTATUS, IMediaNotify);
10449 PPDMDRVINS pDrvIns = pThis->pDrvIns;
10450 LogFunc(("uLUN=%d\n", uLUN));
10451 if (pThis->pmapMediumAttachments)
10452 {
10453 AutoWriteLock alock(pThis->pConsole COMMA_LOCKVAL_SRC_POS);
10454
10455 ComPtr<IMediumAttachment> pMediumAtt;
10456 Utf8Str devicePath = Utf8StrFmt("%s/LUN#%u", pThis->pszDeviceInstance, uLUN);
10457 Console::MediumAttachmentMap::const_iterator end = pThis->pmapMediumAttachments->end();
10458 Console::MediumAttachmentMap::const_iterator it = pThis->pmapMediumAttachments->find(devicePath);
10459 if (it != end)
10460 pMediumAtt = it->second;
10461 Assert(!pMediumAtt.isNull());
10462 if (!pMediumAtt.isNull())
10463 {
10464 IMedium *pMedium = NULL;
10465 HRESULT rc = pMediumAtt->COMGETTER(Medium)(&pMedium);
10466 AssertComRC(rc);
10467 if (SUCCEEDED(rc) && pMedium)
10468 {
10469 BOOL fHostDrive = FALSE;
10470 rc = pMedium->COMGETTER(HostDrive)(&fHostDrive);
10471 AssertComRC(rc);
10472 if (!fHostDrive)
10473 {
10474 alock.release();
10475
10476 ComPtr<IMediumAttachment> pNewMediumAtt;
10477 rc = pThis->pConsole->mControl->EjectMedium(pMediumAtt, pNewMediumAtt.asOutParam());
10478 if (SUCCEEDED(rc))
10479 fireMediumChangedEvent(pThis->pConsole->mEventSource, pNewMediumAtt);
10480
10481 alock.acquire();
10482 if (pNewMediumAtt != pMediumAtt)
10483 {
10484 pThis->pmapMediumAttachments->erase(devicePath);
10485 pThis->pmapMediumAttachments->insert(std::make_pair(devicePath, pNewMediumAtt));
10486 }
10487 }
10488 }
10489 }
10490 }
10491 return VINF_SUCCESS;
10492}
10493
10494
10495/**
10496 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
10497 */
10498DECLCALLBACK(void *) Console::i_drvStatus_QueryInterface(PPDMIBASE pInterface, const char *pszIID)
10499{
10500 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
10501 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10502 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
10503 PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDCONNECTORS, &pThis->ILedConnectors);
10504 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIANOTIFY, &pThis->IMediaNotify);
10505 return NULL;
10506}
10507
10508
10509/**
10510 * Destruct a status driver instance.
10511 *
10512 * @returns VBox status.
10513 * @param pDrvIns The driver instance data.
10514 */
10515DECLCALLBACK(void) Console::i_drvStatus_Destruct(PPDMDRVINS pDrvIns)
10516{
10517 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
10518 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10519 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
10520
10521 if (pThis->papLeds)
10522 {
10523 unsigned iLed = pThis->iLastLUN - pThis->iFirstLUN + 1;
10524 while (iLed-- > 0)
10525 ASMAtomicWriteNullPtr(&pThis->papLeds[iLed]);
10526 }
10527}
10528
10529
10530/**
10531 * Construct a status driver instance.
10532 *
10533 * @copydoc FNPDMDRVCONSTRUCT
10534 */
10535DECLCALLBACK(int) Console::i_drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
10536{
10537 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
10538 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10539 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
10540
10541 /*
10542 * Validate configuration.
10543 */
10544 if (!CFGMR3AreValuesValid(pCfg, "papLeds\0pmapMediumAttachments\0DeviceInstance\0pConsole\0First\0Last\0"))
10545 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
10546 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
10547 ("Configuration error: Not possible to attach anything to this driver!\n"),
10548 VERR_PDM_DRVINS_NO_ATTACH);
10549
10550 /*
10551 * Data.
10552 */
10553 pDrvIns->IBase.pfnQueryInterface = Console::i_drvStatus_QueryInterface;
10554 pThis->ILedConnectors.pfnUnitChanged = Console::i_drvStatus_UnitChanged;
10555 pThis->IMediaNotify.pfnEjected = Console::i_drvStatus_MediumEjected;
10556 pThis->pDrvIns = pDrvIns;
10557 pThis->pszDeviceInstance = NULL;
10558
10559 /*
10560 * Read config.
10561 */
10562 int rc = CFGMR3QueryPtr(pCfg, "papLeds", (void **)&pThis->papLeds);
10563 if (RT_FAILURE(rc))
10564 {
10565 AssertMsgFailed(("Configuration error: Failed to query the \"papLeds\" value! rc=%Rrc\n", rc));
10566 return rc;
10567 }
10568
10569 rc = CFGMR3QueryPtrDef(pCfg, "pmapMediumAttachments", (void **)&pThis->pmapMediumAttachments, NULL);
10570 if (RT_FAILURE(rc))
10571 {
10572 AssertMsgFailed(("Configuration error: Failed to query the \"pmapMediumAttachments\" value! rc=%Rrc\n", rc));
10573 return rc;
10574 }
10575 if (pThis->pmapMediumAttachments)
10576 {
10577 rc = CFGMR3QueryStringAlloc(pCfg, "DeviceInstance", &pThis->pszDeviceInstance);
10578 if (RT_FAILURE(rc))
10579 {
10580 AssertMsgFailed(("Configuration error: Failed to query the \"DeviceInstance\" value! rc=%Rrc\n", rc));
10581 return rc;
10582 }
10583 rc = CFGMR3QueryPtr(pCfg, "pConsole", (void **)&pThis->pConsole);
10584 if (RT_FAILURE(rc))
10585 {
10586 AssertMsgFailed(("Configuration error: Failed to query the \"pConsole\" value! rc=%Rrc\n", rc));
10587 return rc;
10588 }
10589 }
10590
10591 rc = CFGMR3QueryU32(pCfg, "First", &pThis->iFirstLUN);
10592 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
10593 pThis->iFirstLUN = 0;
10594 else if (RT_FAILURE(rc))
10595 {
10596 AssertMsgFailed(("Configuration error: Failed to query the \"First\" value! rc=%Rrc\n", rc));
10597 return rc;
10598 }
10599
10600 rc = CFGMR3QueryU32(pCfg, "Last", &pThis->iLastLUN);
10601 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
10602 pThis->iLastLUN = 0;
10603 else if (RT_FAILURE(rc))
10604 {
10605 AssertMsgFailed(("Configuration error: Failed to query the \"Last\" value! rc=%Rrc\n", rc));
10606 return rc;
10607 }
10608 if (pThis->iFirstLUN > pThis->iLastLUN)
10609 {
10610 AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pThis->iFirstLUN, pThis->iLastLUN));
10611 return VERR_GENERAL_FAILURE;
10612 }
10613
10614 /*
10615 * Get the ILedPorts interface of the above driver/device and
10616 * query the LEDs we want.
10617 */
10618 pThis->pLedPorts = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMILEDPORTS);
10619 AssertMsgReturn(pThis->pLedPorts, ("Configuration error: No led ports interface above!\n"),
10620 VERR_PDM_MISSING_INTERFACE_ABOVE);
10621
10622 for (unsigned i = pThis->iFirstLUN; i <= pThis->iLastLUN; ++i)
10623 Console::i_drvStatus_UnitChanged(&pThis->ILedConnectors, i);
10624
10625 return VINF_SUCCESS;
10626}
10627
10628
10629/**
10630 * Console status driver (LED) registration record.
10631 */
10632const PDMDRVREG Console::DrvStatusReg =
10633{
10634 /* u32Version */
10635 PDM_DRVREG_VERSION,
10636 /* szName */
10637 "MainStatus",
10638 /* szRCMod */
10639 "",
10640 /* szR0Mod */
10641 "",
10642 /* pszDescription */
10643 "Main status driver (Main as in the API).",
10644 /* fFlags */
10645 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
10646 /* fClass. */
10647 PDM_DRVREG_CLASS_STATUS,
10648 /* cMaxInstances */
10649 ~0U,
10650 /* cbInstance */
10651 sizeof(DRVMAINSTATUS),
10652 /* pfnConstruct */
10653 Console::i_drvStatus_Construct,
10654 /* pfnDestruct */
10655 Console::i_drvStatus_Destruct,
10656 /* pfnRelocate */
10657 NULL,
10658 /* pfnIOCtl */
10659 NULL,
10660 /* pfnPowerOn */
10661 NULL,
10662 /* pfnReset */
10663 NULL,
10664 /* pfnSuspend */
10665 NULL,
10666 /* pfnResume */
10667 NULL,
10668 /* pfnAttach */
10669 NULL,
10670 /* pfnDetach */
10671 NULL,
10672 /* pfnPowerOff */
10673 NULL,
10674 /* pfnSoftReset */
10675 NULL,
10676 /* u32EndVersion */
10677 PDM_DRVREG_VERSION
10678};
10679
10680
10681
10682/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

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