VirtualBox

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

Last change on this file since 83309 was 82968, checked in by vboxsync, 5 years ago

Copyright year updates by scm.

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

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