VirtualBox

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

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

Main/Console: some g++ versions complain and need help to get the POD

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

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