VirtualBox

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

Last change on this file since 78897 was 78897, checked in by vboxsync, 6 years ago

Shared Clipboard/URI: Update.

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

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