VirtualBox

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

Last change on this file since 85286 was 85286, checked in by vboxsync, 4 years ago

Main: Refactored the generated event code implementation as Clang 11 claims va_start() on an VBoxEventType_T may trigger undefined behaviour due to type promotion (or something to that effect), but also because that variadict approach was horrible from the start. Refactored code as a dedicated factory method for each event, removing a dependency on VBoxEventDesc in veto cases. The fireXxxxEvent functions now return a HRESULT are no longer DECLINLINE (no need to compile all of them all the time). Reusable events got a ReinitXxxxxEvent function for helping with that. The VirtualBox::CallbackEvent stuff was a horrid misdesign from the start, it could've been done with a single class carrying a VBoxEventDesc member that the i_onXxxx methods would init() with all the event specific parameters and stuff. Refactored code passes a IEvent around, as that's even easier. I've left much of the old code in place for reference, but will remove once I've had a chance to test it a bit more (still struggling building VBox on the mac). bugref:9790

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