VirtualBox

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

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

Main/Console: make resume attempts over the API fail with a corresponding error message when the VM is paused due to host power management

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

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