VirtualBox

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

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

Oops

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