VirtualBox

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

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

Fixes for disk encryption when working with snapshots

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