VirtualBox

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

Last change on this file since 93318 was 93312, checked in by vboxsync, 3 years ago

CloudNet: ​bugref:9469 Replace local gateway with DrvCloudTunnel. Build 25519 encryption support in libssh. Add missing version bump in machine settings to 1.18 if cloud attachment is used.

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