VirtualBox

source: vbox/trunk/src/VBox/Main/ConsoleImpl.cpp@ 4246

Last change on this file since 4246 was 4234, checked in by vboxsync, 17 years ago

gcc warning

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 270.0 KB
Line 
1/** @file
2 *
3 * VBox Console COM Class implementation
4 */
5
6/*
7 * Copyright (C) 2006-2007 innotek GmbH
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 as published by the Free Software Foundation,
13 * in version 2 as it comes in the "COPYING" file of the VirtualBox OSE
14 * distribution. VirtualBox OSE is distributed in the hope that it will
15 * be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#if defined(RT_OS_WINDOWS)
19#elif defined(RT_OS_LINUX)
20# include <errno.h>
21# include <sys/ioctl.h>
22# include <sys/poll.h>
23# include <sys/fcntl.h>
24# include <sys/types.h>
25# include <sys/wait.h>
26# include <net/if.h>
27# include <linux/if_tun.h>
28# include <stdio.h>
29# include <stdlib.h>
30# include <string.h>
31#endif
32
33#include "ConsoleImpl.h"
34#include "GuestImpl.h"
35#include "KeyboardImpl.h"
36#include "MouseImpl.h"
37#include "DisplayImpl.h"
38#include "MachineDebuggerImpl.h"
39#include "USBDeviceImpl.h"
40#include "RemoteUSBDeviceImpl.h"
41#include "SharedFolderImpl.h"
42#include "AudioSnifferInterface.h"
43#include "ConsoleVRDPServer.h"
44#include "VMMDev.h"
45
46// generated header
47#include "SchemaDefs.h"
48
49#include "Logging.h"
50
51#include <iprt/string.h>
52#include <iprt/asm.h>
53#include <iprt/file.h>
54#include <iprt/path.h>
55#include <iprt/dir.h>
56#include <iprt/process.h>
57#include <iprt/ldr.h>
58#include <iprt/cpputils.h>
59
60#include <VBox/vmapi.h>
61#include <VBox/err.h>
62#include <VBox/param.h>
63#include <VBox/vusb.h>
64#include <VBox/mm.h>
65#include <VBox/ssm.h>
66#include <VBox/version.h>
67
68#include <VBox/VBoxDev.h>
69
70#include <VBox/HostServices/VBoxClipboardSvc.h>
71
72#include <set>
73#include <algorithm>
74#include <memory> // for auto_ptr
75
76
77// VMTask and friends
78////////////////////////////////////////////////////////////////////////////////
79
80/**
81 * Task structure for asynchronous VM operations.
82 *
83 * Once created, the task structure adds itself as a Console caller.
84 * This means:
85 *
86 * 1. The user must check for #rc() before using the created structure
87 * (e.g. passing it as a thread function argument). If #rc() returns a
88 * failure, the Console object may not be used by the task (see
89 Console::addCaller() for more details).
90 * 2. On successful initialization, the structure keeps the Console caller
91 * until destruction (to ensure Console remains in the Ready state and won't
92 * be accidentially uninitialized). Forgetting to delete the created task
93 * will lead to Console::uninit() stuck waiting for releasing all added
94 * callers.
95 *
96 * If \a aUsesVMPtr parameter is true, the task structure will also add itself
97 * as a Console::mpVM caller with the same meaning as above. See
98 * Console::addVMCaller() for more info.
99 */
100struct VMTask
101{
102 VMTask (Console *aConsole, bool aUsesVMPtr)
103 : mConsole (aConsole), mCallerAdded (false), mVMCallerAdded (false)
104 {
105 AssertReturnVoid (aConsole);
106 mRC = aConsole->addCaller();
107 if (SUCCEEDED (mRC))
108 {
109 mCallerAdded = true;
110 if (aUsesVMPtr)
111 {
112 mRC = aConsole->addVMCaller();
113 if (SUCCEEDED (mRC))
114 mVMCallerAdded = true;
115 }
116 }
117 }
118
119 ~VMTask()
120 {
121 if (mVMCallerAdded)
122 mConsole->releaseVMCaller();
123 if (mCallerAdded)
124 mConsole->releaseCaller();
125 }
126
127 HRESULT rc() const { return mRC; }
128 bool isOk() const { return SUCCEEDED (rc()); }
129
130 /** Releases the Console caller before destruction. Not normally necessary. */
131 void releaseCaller()
132 {
133 AssertReturnVoid (mCallerAdded);
134 mConsole->releaseCaller();
135 mCallerAdded = false;
136 }
137
138 /** Releases the VM caller before destruction. Not normally necessary. */
139 void releaseVMCaller()
140 {
141 AssertReturnVoid (mVMCallerAdded);
142 mConsole->releaseVMCaller();
143 mVMCallerAdded = false;
144 }
145
146 const ComObjPtr <Console> mConsole;
147
148private:
149
150 HRESULT mRC;
151 bool mCallerAdded : 1;
152 bool mVMCallerAdded : 1;
153};
154
155struct VMProgressTask : public VMTask
156{
157 VMProgressTask (Console *aConsole, Progress *aProgress, bool aUsesVMPtr)
158 : VMTask (aConsole, aUsesVMPtr), mProgress (aProgress) {}
159
160 const ComObjPtr <Progress> mProgress;
161};
162
163struct VMPowerUpTask : public VMProgressTask
164{
165 VMPowerUpTask (Console *aConsole, Progress *aProgress)
166 : VMProgressTask (aConsole, aProgress, false /* aUsesVMPtr */)
167 , mSetVMErrorCallback (NULL), mConfigConstructor (NULL) {}
168
169 PFNVMATERROR mSetVMErrorCallback;
170 PFNCFGMCONSTRUCTOR mConfigConstructor;
171 Utf8Str mSavedStateFile;
172 Console::SharedFolderDataMap mSharedFolders;
173};
174
175struct VMSaveTask : public VMProgressTask
176{
177 VMSaveTask (Console *aConsole, Progress *aProgress)
178 : VMProgressTask (aConsole, aProgress, true /* aUsesVMPtr */)
179 , mIsSnapshot (false)
180 , mLastMachineState (MachineState_InvalidMachineState) {}
181
182 bool mIsSnapshot;
183 Utf8Str mSavedStateFile;
184 MachineState_T mLastMachineState;
185 ComPtr <IProgress> mServerProgress;
186};
187
188
189// constructor / desctructor
190/////////////////////////////////////////////////////////////////////////////
191
192Console::Console()
193 : mSavedStateDataLoaded (false)
194 , mConsoleVRDPServer (NULL)
195 , mpVM (NULL)
196 , mVMCallers (0)
197 , mVMZeroCallersSem (NIL_RTSEMEVENT)
198 , mVMDestroying (false)
199 , meDVDState (DriveState_NotMounted)
200 , meFloppyState (DriveState_NotMounted)
201 , mVMMDev (NULL)
202 , mAudioSniffer (NULL)
203 , mVMStateChangeCallbackDisabled (false)
204 , mMachineState (MachineState_PoweredOff)
205{}
206
207Console::~Console()
208{}
209
210HRESULT Console::FinalConstruct()
211{
212 LogFlowThisFunc (("\n"));
213
214 memset(mapFDLeds, 0, sizeof(mapFDLeds));
215 memset(mapIDELeds, 0, sizeof(mapIDELeds));
216 memset(mapNetworkLeds, 0, sizeof(mapNetworkLeds));
217 memset(&mapUSBLed, 0, sizeof(mapUSBLed));
218 memset(&mapSharedFolderLed, 0, sizeof(mapSharedFolderLed));
219
220#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
221 Assert(ELEMENTS(maTapFD) == ELEMENTS(maTAPDeviceName));
222 Assert(ELEMENTS(maTapFD) >= SchemaDefs::NetworkAdapterCount);
223 for (unsigned i = 0; i < ELEMENTS(maTapFD); i++)
224 {
225 maTapFD[i] = NIL_RTFILE;
226 maTAPDeviceName[i] = "";
227 }
228#endif
229
230 return S_OK;
231}
232
233void Console::FinalRelease()
234{
235 LogFlowThisFunc (("\n"));
236
237 uninit();
238}
239
240// public initializer/uninitializer for internal purposes only
241/////////////////////////////////////////////////////////////////////////////
242
243HRESULT Console::init (IMachine *aMachine, IInternalMachineControl *aControl)
244{
245 AssertReturn (aMachine && aControl, E_INVALIDARG);
246
247 /* Enclose the state transition NotReady->InInit->Ready */
248 AutoInitSpan autoInitSpan (this);
249 AssertReturn (autoInitSpan.isOk(), E_UNEXPECTED);
250
251 LogFlowThisFuncEnter();
252 LogFlowThisFunc(("aMachine=%p, aControl=%p\n", aMachine, aControl));
253
254 HRESULT rc = E_FAIL;
255
256 unconst (mMachine) = aMachine;
257 unconst (mControl) = aControl;
258
259 memset (&mCallbackData, 0, sizeof (mCallbackData));
260
261 /* Cache essential properties and objects */
262
263 rc = mMachine->COMGETTER(State) (&mMachineState);
264 AssertComRCReturnRC (rc);
265
266#ifdef VBOX_VRDP
267 rc = mMachine->COMGETTER(VRDPServer) (unconst (mVRDPServer).asOutParam());
268 AssertComRCReturnRC (rc);
269#endif
270
271 rc = mMachine->COMGETTER(DVDDrive) (unconst (mDVDDrive).asOutParam());
272 AssertComRCReturnRC (rc);
273
274 rc = mMachine->COMGETTER(FloppyDrive) (unconst (mFloppyDrive).asOutParam());
275 AssertComRCReturnRC (rc);
276
277 /* Create associated child COM objects */
278
279 unconst (mGuest).createObject();
280 rc = mGuest->init (this);
281 AssertComRCReturnRC (rc);
282
283 unconst (mKeyboard).createObject();
284 rc = mKeyboard->init (this);
285 AssertComRCReturnRC (rc);
286
287 unconst (mMouse).createObject();
288 rc = mMouse->init (this);
289 AssertComRCReturnRC (rc);
290
291 unconst (mDisplay).createObject();
292 rc = mDisplay->init (this);
293 AssertComRCReturnRC (rc);
294
295 unconst (mRemoteDisplayInfo).createObject();
296 rc = mRemoteDisplayInfo->init (this);
297 AssertComRCReturnRC (rc);
298
299 /* Grab global and machine shared folder lists */
300
301 rc = fetchSharedFolders (true /* aGlobal */);
302 AssertComRCReturnRC (rc);
303 rc = fetchSharedFolders (false /* aGlobal */);
304 AssertComRCReturnRC (rc);
305
306 /* Create other child objects */
307
308 unconst (mConsoleVRDPServer) = new ConsoleVRDPServer (this);
309 AssertReturn (mConsoleVRDPServer, E_FAIL);
310
311 mcAudioRefs = 0;
312 mcVRDPClients = 0;
313
314 unconst (mVMMDev) = new VMMDev(this);
315 AssertReturn (mVMMDev, E_FAIL);
316
317 unconst (mAudioSniffer) = new AudioSniffer(this);
318 AssertReturn (mAudioSniffer, E_FAIL);
319
320 /* Confirm a successful initialization when it's the case */
321 autoInitSpan.setSucceeded();
322
323 LogFlowThisFuncLeave();
324
325 return S_OK;
326}
327
328/**
329 * Uninitializes the Console object.
330 */
331void Console::uninit()
332{
333 LogFlowThisFuncEnter();
334
335 /* Enclose the state transition Ready->InUninit->NotReady */
336 AutoUninitSpan autoUninitSpan (this);
337 if (autoUninitSpan.uninitDone())
338 {
339 LogFlowThisFunc (("Already uninitialized.\n"));
340 LogFlowThisFuncLeave();
341 return;
342 }
343
344 LogFlowThisFunc (("initFailed()=%d\n", autoUninitSpan.initFailed()));
345
346 /*
347 * Uninit all children that ise addDependentChild()/removeDependentChild()
348 * in their init()/uninit() methods.
349 */
350 uninitDependentChildren();
351
352 /* This should be the first, since this may cause detaching remote USB devices. */
353 if (mConsoleVRDPServer)
354 {
355 delete mConsoleVRDPServer;
356 unconst (mConsoleVRDPServer) = NULL;
357 }
358
359 /* power down the VM if necessary */
360 if (mpVM)
361 {
362 powerDown();
363 Assert (mpVM == NULL);
364 }
365
366 if (mVMZeroCallersSem != NIL_RTSEMEVENT)
367 {
368 RTSemEventDestroy (mVMZeroCallersSem);
369 mVMZeroCallersSem = NIL_RTSEMEVENT;
370 }
371
372 if (mAudioSniffer)
373 {
374 delete mAudioSniffer;
375 unconst (mAudioSniffer) = NULL;
376 }
377
378 if (mVMMDev)
379 {
380 delete mVMMDev;
381 unconst (mVMMDev) = NULL;
382 }
383
384 mGlobalSharedFolders.clear();
385 mMachineSharedFolders.clear();
386
387 mSharedFolders.clear();
388 mRemoteUSBDevices.clear();
389 mUSBDevices.clear();
390
391 if (mRemoteDisplayInfo)
392 {
393 mRemoteDisplayInfo->uninit();
394 unconst (mRemoteDisplayInfo).setNull();;
395 }
396
397 if (mDebugger)
398 {
399 mDebugger->uninit();
400 unconst (mDebugger).setNull();
401 }
402
403 if (mDisplay)
404 {
405 mDisplay->uninit();
406 unconst (mDisplay).setNull();
407 }
408
409 if (mMouse)
410 {
411 mMouse->uninit();
412 unconst (mMouse).setNull();
413 }
414
415 if (mKeyboard)
416 {
417 mKeyboard->uninit();
418 unconst (mKeyboard).setNull();;
419 }
420
421 if (mGuest)
422 {
423 mGuest->uninit();
424 unconst (mGuest).setNull();;
425 }
426
427 unconst (mFloppyDrive).setNull();
428 unconst (mDVDDrive).setNull();
429#ifdef VBOX_VRDP
430 unconst (mVRDPServer).setNull();
431#endif
432
433 unconst (mControl).setNull();
434 unconst (mMachine).setNull();
435
436 /* Release all callbacks. Do this after uninitializing the components,
437 * as some of them are well-behaved and unregister their callbacks.
438 * These would trigger error messages complaining about trying to
439 * unregister a non-registered callback. */
440 mCallbacks.clear();
441
442 /* dynamically allocated members of mCallbackData are uninitialized
443 * at the end of powerDown() */
444 Assert (!mCallbackData.mpsc.valid && mCallbackData.mpsc.shape == NULL);
445 Assert (!mCallbackData.mcc.valid);
446 Assert (!mCallbackData.klc.valid);
447
448 LogFlowThisFuncLeave();
449}
450
451#ifdef VRDP_NO_COM
452int Console::VRDPClientLogon (uint32_t u32ClientId, const char *pszUser, const char *pszPassword, const char *pszDomain)
453#else
454DECLCALLBACK(int) Console::vrdp_ClientLogon (void *pvUser,
455 uint32_t u32ClientId,
456 const char *pszUser,
457 const char *pszPassword,
458 const char *pszDomain)
459#endif /* VRDP_NO_COM */
460{
461 LogFlowFuncEnter();
462 LogFlowFunc (("%d, %s, %s, %s\n", u32ClientId, pszUser, pszPassword, pszDomain));
463
464#ifdef VRDP_NO_COM
465 Console *console = this;
466#else
467 Console *console = static_cast <Console *> (pvUser);
468#endif /* VRDP_NO_COM */
469 AssertReturn (console, VERR_INVALID_POINTER);
470
471 AutoCaller autoCaller (console);
472 if (!autoCaller.isOk())
473 {
474 /* Console has been already uninitialized, deny request */
475 LogRel(("VRDPAUTH: Access denied (Console uninitialized).\n"));
476 LogFlowFuncLeave();
477 return VERR_ACCESS_DENIED;
478 }
479
480 Guid uuid;
481 HRESULT hrc = console->mMachine->COMGETTER (Id) (uuid.asOutParam());
482 AssertComRCReturn (hrc, VERR_ACCESS_DENIED);
483
484 VRDPAuthType_T authType = VRDPAuthType_VRDPAuthNull;
485 hrc = console->mVRDPServer->COMGETTER(AuthType) (&authType);
486 AssertComRCReturn (hrc, VERR_ACCESS_DENIED);
487
488 ULONG authTimeout = 0;
489 hrc = console->mVRDPServer->COMGETTER(AuthTimeout) (&authTimeout);
490 AssertComRCReturn (hrc, VERR_ACCESS_DENIED);
491
492 VRDPAuthResult result = VRDPAuthAccessDenied;
493 VRDPAuthGuestJudgement guestJudgement = VRDPAuthGuestNotAsked;
494
495 LogFlowFunc(("Auth type %d\n", authType));
496
497 LogRel (("VRDPAUTH: User: [%s]. Domain: [%s]. Authentication type: [%s]\n",
498 pszUser, pszDomain,
499 authType == VRDPAuthType_VRDPAuthNull?
500 "null":
501 (authType == VRDPAuthType_VRDPAuthExternal?
502 "external":
503 (authType == VRDPAuthType_VRDPAuthGuest?
504 "guest":
505 "INVALID"
506 )
507 )
508 ));
509
510 /* Multiconnection check. */
511 BOOL allowMultiConnection = FALSE;
512 hrc = console->mVRDPServer->COMGETTER(AllowMultiConnection) (&allowMultiConnection);
513 AssertComRCReturn (hrc, VERR_ACCESS_DENIED);
514
515 LogFlowFunc(("allowMultiConnection %d, console->mcVRDPClients = %d\n", allowMultiConnection, console->mcVRDPClients));
516
517 if (allowMultiConnection == FALSE)
518 {
519 /* Note: the variable is incremented in ClientConnect callback, which is called when the client
520 * is successfully connected, that is after the ClientLogon callback. Therefore the mcVRDPClients
521 * value is 0 for first client.
522 */
523 if (console->mcVRDPClients > 0)
524 {
525 /* Reject. */
526 LogRel(("VRDPAUTH: Multiple connections are not enabled. Access denied.\n"));
527 return VERR_ACCESS_DENIED;
528 }
529 }
530
531 switch (authType)
532 {
533 case VRDPAuthType_VRDPAuthNull:
534 {
535 result = VRDPAuthAccessGranted;
536 break;
537 }
538
539 case VRDPAuthType_VRDPAuthExternal:
540 {
541 /* Call the external library. */
542 result = console->mConsoleVRDPServer->Authenticate (uuid, guestJudgement, pszUser, pszPassword, pszDomain, u32ClientId);
543
544 if (result != VRDPAuthDelegateToGuest)
545 {
546 break;
547 }
548
549 LogRel(("VRDPAUTH: Delegated to guest.\n"));
550
551 LogFlowFunc (("External auth asked for guest judgement\n"));
552 } /* pass through */
553
554 case VRDPAuthType_VRDPAuthGuest:
555 {
556 guestJudgement = VRDPAuthGuestNotReacted;
557
558 if (console->mVMMDev)
559 {
560 /* Issue the request to guest. Assume that the call does not require EMT. It should not. */
561
562 /* Ask the guest to judge these credentials. */
563 uint32_t u32GuestFlags = VMMDEV_SETCREDENTIALS_JUDGE;
564
565 int rc = console->mVMMDev->getVMMDevPort()->pfnSetCredentials (console->mVMMDev->getVMMDevPort(),
566 pszUser, pszPassword, pszDomain, u32GuestFlags);
567
568 if (VBOX_SUCCESS (rc))
569 {
570 /* Wait for guest. */
571 rc = console->mVMMDev->WaitCredentialsJudgement (authTimeout, &u32GuestFlags);
572
573 if (VBOX_SUCCESS (rc))
574 {
575 switch (u32GuestFlags & (VMMDEV_CREDENTIALS_JUDGE_OK | VMMDEV_CREDENTIALS_JUDGE_DENY | VMMDEV_CREDENTIALS_JUDGE_NOJUDGEMENT))
576 {
577 case VMMDEV_CREDENTIALS_JUDGE_DENY: guestJudgement = VRDPAuthGuestAccessDenied; break;
578 case VMMDEV_CREDENTIALS_JUDGE_NOJUDGEMENT: guestJudgement = VRDPAuthGuestNoJudgement; break;
579 case VMMDEV_CREDENTIALS_JUDGE_OK: guestJudgement = VRDPAuthGuestAccessGranted; break;
580 default:
581 LogFlowFunc (("Invalid guest flags %08X!!!\n", u32GuestFlags)); break;
582 }
583 }
584 else
585 {
586 LogFlowFunc (("Wait for credentials judgement rc = %Vrc!!!\n", rc));
587 }
588
589 LogFlowFunc (("Guest judgement %d\n", guestJudgement));
590 }
591 else
592 {
593 LogFlowFunc (("Could not set credentials rc = %Vrc!!!\n", rc));
594 }
595 }
596
597 if (authType == VRDPAuthType_VRDPAuthExternal)
598 {
599 LogRel(("VRDPAUTH: Guest judgement %d.\n", guestJudgement));
600 LogFlowFunc (("External auth called again with guest judgement = %d\n", guestJudgement));
601 result = console->mConsoleVRDPServer->Authenticate (uuid, guestJudgement, pszUser, pszPassword, pszDomain, u32ClientId);
602 }
603 else
604 {
605 switch (guestJudgement)
606 {
607 case VRDPAuthGuestAccessGranted:
608 result = VRDPAuthAccessGranted;
609 break;
610 default:
611 result = VRDPAuthAccessDenied;
612 break;
613 }
614 }
615 } break;
616
617 default:
618 AssertFailed();
619 }
620
621 LogFlowFunc (("Result = %d\n", result));
622 LogFlowFuncLeave();
623
624 if (result == VRDPAuthAccessGranted)
625 {
626 LogRel(("VRDPAUTH: Access granted.\n"));
627 return VINF_SUCCESS;
628 }
629
630 /* Reject. */
631 LogRel(("VRDPAUTH: Access denied.\n"));
632 return VERR_ACCESS_DENIED;
633}
634
635#ifdef VRDP_NO_COM
636void Console::VRDPClientConnect (uint32_t u32ClientId)
637#else
638DECLCALLBACK(void) Console::vrdp_ClientConnect (void *pvUser,
639 uint32_t u32ClientId)
640#endif /* VRDP_NO_COM */
641{
642 LogFlowFuncEnter();
643
644#ifdef VRDP_NO_COM
645 Console *console = this;
646#else
647 Console *console = static_cast <Console *> (pvUser);
648#endif /* VRDP_NO_COM */
649 AssertReturnVoid (console);
650
651 AutoCaller autoCaller (console);
652 AssertComRCReturnVoid (autoCaller.rc());
653
654#ifdef VBOX_VRDP
655 ASMAtomicIncU32(&console->mcVRDPClients);
656
657 NOREF(u32ClientId);
658 console->mDisplay->VideoAccelVRDP (true);
659#endif /* VBOX_VRDP */
660
661 LogFlowFuncLeave();
662 return;
663}
664
665#ifdef VRDP_NO_COM
666void Console::VRDPClientDisconnect (uint32_t u32ClientId,
667 uint32_t fu32Intercepted)
668#else
669DECLCALLBACK(void) Console::vrdp_ClientDisconnect (void *pvUser,
670 uint32_t u32ClientId,
671 uint32_t fu32Intercepted)
672#endif /* VRDP_NO_COM */
673{
674 LogFlowFuncEnter();
675
676#ifdef VRDP_NO_COM
677 Console *console = this;
678#else
679 Console *console = static_cast <Console *> (pvUser);
680#endif /* VRDP_NO_COM */
681 AssertReturnVoid (console);
682
683 AutoCaller autoCaller (console);
684 AssertComRCReturnVoid (autoCaller.rc());
685
686 AssertReturnVoid (console->mConsoleVRDPServer);
687
688#ifdef VBOX_VRDP
689 ASMAtomicDecU32(&console->mcVRDPClients);
690
691 console->mDisplay->VideoAccelVRDP (false);
692#endif /* VBOX_VRDP */
693
694 if (fu32Intercepted & VRDP_CLIENT_INTERCEPT_USB)
695 {
696 console->mConsoleVRDPServer->USBBackendDelete (u32ClientId);
697 }
698
699#ifdef VBOX_VRDP
700 if (fu32Intercepted & VRDP_CLIENT_INTERCEPT_CLIPBOARD)
701 {
702 console->mConsoleVRDPServer->ClipboardDelete (u32ClientId);
703 }
704
705 if (fu32Intercepted & VRDP_CLIENT_INTERCEPT_AUDIO)
706 {
707 console->mcAudioRefs--;
708
709 if (console->mcAudioRefs <= 0)
710 {
711 if (console->mAudioSniffer)
712 {
713 PPDMIAUDIOSNIFFERPORT port = console->mAudioSniffer->getAudioSnifferPort();
714 if (port)
715 {
716 port->pfnSetup (port, false, false);
717 }
718 }
719 }
720 }
721#endif /* VBOX_VRDP */
722
723 Guid uuid;
724 HRESULT hrc = console->mMachine->COMGETTER (Id) (uuid.asOutParam());
725 AssertComRC (hrc);
726
727 VRDPAuthType_T authType = VRDPAuthType_VRDPAuthNull;
728 hrc = console->mVRDPServer->COMGETTER(AuthType) (&authType);
729 AssertComRC (hrc);
730
731 if (authType == VRDPAuthType_VRDPAuthExternal)
732 console->mConsoleVRDPServer->AuthDisconnect (uuid, u32ClientId);
733
734 LogFlowFuncLeave();
735 return;
736}
737
738#ifdef VRDP_NO_COM
739void Console::VRDPInterceptAudio (uint32_t u32ClientId)
740#else
741DECLCALLBACK(void) Console::vrdp_InterceptAudio (void *pvUser,
742 uint32_t u32ClientId)
743#endif /* VRDP_NO_COM */
744{
745 LogFlowFuncEnter();
746
747#ifdef VRDP_NO_COM
748 Console *console = this;
749#else
750 Console *console = static_cast <Console *> (pvUser);
751#endif /* VRDP_NO_COM */
752 AssertReturnVoid (console);
753
754 AutoCaller autoCaller (console);
755 AssertComRCReturnVoid (autoCaller.rc());
756
757 LogFlowFunc (("mAudioSniffer %p, u32ClientId %d.\n",
758 console->mAudioSniffer, u32ClientId));
759 NOREF(u32ClientId);
760
761#ifdef VBOX_VRDP
762 console->mcAudioRefs++;
763
764 if (console->mcAudioRefs == 1)
765 {
766 if (console->mAudioSniffer)
767 {
768 PPDMIAUDIOSNIFFERPORT port = console->mAudioSniffer->getAudioSnifferPort();
769 if (port)
770 {
771 port->pfnSetup (port, true, true);
772 }
773 }
774 }
775#endif
776
777 LogFlowFuncLeave();
778 return;
779}
780
781#ifdef VRDP_NO_COM
782void Console::VRDPInterceptUSB (uint32_t u32ClientId)
783#else
784DECLCALLBACK(void) Console::vrdp_InterceptUSB (void *pvUser,
785 uint32_t u32ClientId,
786 PFNVRDPUSBCALLBACK *ppfn,
787 void **ppv)
788#endif /* VRDP_NO_COM */
789{
790 LogFlowFuncEnter();
791
792#ifdef VRDP_NO_COM
793 Console *console = this;
794#else
795 Console *console = static_cast <Console *> (pvUser);
796#endif /* VRDP_NO_COM */
797 AssertReturnVoid (console);
798
799 AutoCaller autoCaller (console);
800 AssertComRCReturnVoid (autoCaller.rc());
801
802 AssertReturnVoid (console->mConsoleVRDPServer);
803
804#ifdef VRDP_NO_COM
805 mConsoleVRDPServer->USBBackendCreate (u32ClientId);
806#else
807 console->mConsoleVRDPServer->USBBackendCreate (u32ClientId, ppfn, ppv);
808#endif /* VRDP_NO_COM */
809
810 LogFlowFuncLeave();
811 return;
812}
813
814#ifdef VRDP_NO_COM
815void Console::VRDPInterceptClipboard (uint32_t u32ClientId)
816#else
817DECLCALLBACK(void) Console::vrdp_InterceptClipboard (void *pvUser,
818 uint32_t u32ClientId,
819 PFNVRDPCLIPBOARDCALLBACK *ppfn,
820 void **ppv)
821#endif /* VRDP_NO_COM */
822{
823 LogFlowFuncEnter();
824
825#ifdef VRDP_NO_COM
826 Console *console = this;
827#else
828 Console *console = static_cast <Console *> (pvUser);
829#endif /* VRDP_NO_COM */
830 AssertReturnVoid (console);
831
832 AutoCaller autoCaller (console);
833 AssertComRCReturnVoid (autoCaller.rc());
834
835 AssertReturnVoid (console->mConsoleVRDPServer);
836
837#ifdef VBOX_VRDP
838#ifdef VRDP_NO_COM
839 mConsoleVRDPServer->ClipboardCreate (u32ClientId);
840#else
841 console->mConsoleVRDPServer->ClipboardCreate (u32ClientId, ppfn, ppv);
842#endif /* VRDP_NO_COM */
843#endif /* VBOX_VRDP */
844
845 LogFlowFuncLeave();
846 return;
847}
848
849
850#ifdef VRDP_NO_COM
851#else
852// static
853VRDPSERVERCALLBACK Console::sVrdpServerCallback =
854{
855 vrdp_ClientLogon,
856 vrdp_ClientConnect,
857 vrdp_ClientDisconnect,
858 vrdp_InterceptAudio,
859 vrdp_InterceptUSB,
860 vrdp_InterceptClipboard
861};
862#endif /* VRDP_NO_COM */
863
864//static
865const char *Console::sSSMConsoleUnit = "ConsoleData";
866//static
867uint32_t Console::sSSMConsoleVer = 0x00010000;
868
869/**
870 * Loads various console data stored in the saved state file.
871 * This method does validation of the state file and returns an error info
872 * when appropriate.
873 *
874 * The method does nothing if the machine is not in the Saved file or if
875 * console data from it has already been loaded.
876 *
877 * @note The caller must lock this object for writing.
878 */
879HRESULT Console::loadDataFromSavedState()
880{
881 if (mMachineState != MachineState_Saved || mSavedStateDataLoaded)
882 return S_OK;
883
884 Bstr savedStateFile;
885 HRESULT rc = mMachine->COMGETTER(StateFilePath) (savedStateFile.asOutParam());
886 if (FAILED (rc))
887 return rc;
888
889 PSSMHANDLE ssm;
890 int vrc = SSMR3Open (Utf8Str(savedStateFile), 0, &ssm);
891 if (VBOX_SUCCESS (vrc))
892 {
893 uint32_t version = 0;
894 vrc = SSMR3Seek (ssm, sSSMConsoleUnit, 0 /* iInstance */, &version);
895 if (version == sSSMConsoleVer)
896 {
897 if (VBOX_SUCCESS (vrc))
898 vrc = loadStateFileExec (ssm, this, 0);
899 else if (vrc == VERR_SSM_UNIT_NOT_FOUND)
900 vrc = VINF_SUCCESS;
901 }
902 else
903 vrc = VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
904
905 SSMR3Close (ssm);
906 }
907
908 if (VBOX_FAILURE (vrc))
909 rc = setError (E_FAIL,
910 tr ("The saved state file '%ls' is invalid (%Vrc). "
911 "Discard the saved state and try again"),
912 savedStateFile.raw(), vrc);
913
914 mSavedStateDataLoaded = true;
915
916 return rc;
917}
918
919/**
920 * Callback handler to save various console data to the state file,
921 * called when the user saves the VM state.
922 *
923 * @param pvUser pointer to Console
924 *
925 * @note Locks the Console object for reading.
926 */
927//static
928DECLCALLBACK(void)
929Console::saveStateFileExec (PSSMHANDLE pSSM, void *pvUser)
930{
931 LogFlowFunc (("\n"));
932
933 Console *that = static_cast <Console *> (pvUser);
934 AssertReturnVoid (that);
935
936 AutoCaller autoCaller (that);
937 AssertComRCReturnVoid (autoCaller.rc());
938
939 AutoReaderLock alock (that);
940
941 int vrc = SSMR3PutU32 (pSSM, that->mSharedFolders.size());
942 AssertRC (vrc);
943
944 for (SharedFolderMap::const_iterator it = that->mSharedFolders.begin();
945 it != that->mSharedFolders.end();
946 ++ it)
947 {
948 ComObjPtr <SharedFolder> folder = (*it).second;
949 // don't lock the folder because methods we access are const
950
951 Utf8Str name = folder->name();
952 vrc = SSMR3PutU32 (pSSM, name.length() + 1 /* term. 0 */);
953 AssertRC (vrc);
954 vrc = SSMR3PutStrZ (pSSM, name);
955 AssertRC (vrc);
956
957 Utf8Str hostPath = folder->hostPath();
958 vrc = SSMR3PutU32 (pSSM, hostPath.length() + 1 /* term. 0 */);
959 AssertRC (vrc);
960 vrc = SSMR3PutStrZ (pSSM, hostPath);
961 AssertRC (vrc);
962 }
963
964 return;
965}
966
967/**
968 * Callback handler to load various console data from the state file.
969 * When \a u32Version is 0, this method is called from #loadDataFromSavedState,
970 * otherwise it is called when the VM is being restored from the saved state.
971 *
972 * @param pvUser pointer to Console
973 * @param u32Version Console unit version.
974 * When not 0, should match sSSMConsoleVer.
975 *
976 * @note Locks the Console object for writing.
977 */
978//static
979DECLCALLBACK(int)
980Console::loadStateFileExec (PSSMHANDLE pSSM, void *pvUser, uint32_t u32Version)
981{
982 LogFlowFunc (("\n"));
983
984 if (u32Version != 0 && u32Version != sSSMConsoleVer)
985 return VERR_VERSION_MISMATCH;
986
987 if (u32Version != 0)
988 {
989 /* currently, nothing to do when we've been called from VMR3Load */
990 return VINF_SUCCESS;
991 }
992
993 Console *that = static_cast <Console *> (pvUser);
994 AssertReturn (that, VERR_INVALID_PARAMETER);
995
996 AutoCaller autoCaller (that);
997 AssertComRCReturn (autoCaller.rc(), VERR_ACCESS_DENIED);
998
999 AutoLock alock (that);
1000
1001 AssertReturn (that->mSharedFolders.size() == 0, VERR_INTERNAL_ERROR);
1002
1003 uint32_t size = 0;
1004 int vrc = SSMR3GetU32 (pSSM, &size);
1005 AssertRCReturn (vrc, vrc);
1006
1007 for (uint32_t i = 0; i < size; ++ i)
1008 {
1009 Bstr name;
1010 Bstr hostPath;
1011
1012 uint32_t szBuf = 0;
1013 char *buf = NULL;
1014
1015 vrc = SSMR3GetU32 (pSSM, &szBuf);
1016 AssertRCReturn (vrc, vrc);
1017 buf = new char [szBuf];
1018 vrc = SSMR3GetStrZ (pSSM, buf, szBuf);
1019 AssertRC (vrc);
1020 name = buf;
1021 delete[] buf;
1022
1023 vrc = SSMR3GetU32 (pSSM, &szBuf);
1024 AssertRCReturn (vrc, vrc);
1025 buf = new char [szBuf];
1026 vrc = SSMR3GetStrZ (pSSM, buf, szBuf);
1027 AssertRC (vrc);
1028 hostPath = buf;
1029 delete[] buf;
1030
1031 ComObjPtr <SharedFolder> sharedFolder;
1032 sharedFolder.createObject();
1033 HRESULT rc = sharedFolder->init (that, name, hostPath);
1034 AssertComRCReturn (rc, VERR_INTERNAL_ERROR);
1035
1036 that->mSharedFolders.insert (std::make_pair (name, sharedFolder));
1037 }
1038
1039 return VINF_SUCCESS;
1040}
1041
1042// IConsole properties
1043/////////////////////////////////////////////////////////////////////////////
1044
1045STDMETHODIMP Console::COMGETTER(Machine) (IMachine **aMachine)
1046{
1047 if (!aMachine)
1048 return E_POINTER;
1049
1050 AutoCaller autoCaller (this);
1051 CheckComRCReturnRC (autoCaller.rc());
1052
1053 /* mMachine is constant during life time, no need to lock */
1054 mMachine.queryInterfaceTo (aMachine);
1055
1056 return S_OK;
1057}
1058
1059STDMETHODIMP Console::COMGETTER(State) (MachineState_T *aMachineState)
1060{
1061 if (!aMachineState)
1062 return E_POINTER;
1063
1064 AutoCaller autoCaller (this);
1065 CheckComRCReturnRC (autoCaller.rc());
1066
1067 AutoReaderLock alock (this);
1068
1069 /* we return our local state (since it's always the same as on the server) */
1070 *aMachineState = mMachineState;
1071
1072 return S_OK;
1073}
1074
1075STDMETHODIMP Console::COMGETTER(Guest) (IGuest **aGuest)
1076{
1077 if (!aGuest)
1078 return E_POINTER;
1079
1080 AutoCaller autoCaller (this);
1081 CheckComRCReturnRC (autoCaller.rc());
1082
1083 /* mGuest is constant during life time, no need to lock */
1084 mGuest.queryInterfaceTo (aGuest);
1085
1086 return S_OK;
1087}
1088
1089STDMETHODIMP Console::COMGETTER(Keyboard) (IKeyboard **aKeyboard)
1090{
1091 if (!aKeyboard)
1092 return E_POINTER;
1093
1094 AutoCaller autoCaller (this);
1095 CheckComRCReturnRC (autoCaller.rc());
1096
1097 /* mKeyboard is constant during life time, no need to lock */
1098 mKeyboard.queryInterfaceTo (aKeyboard);
1099
1100 return S_OK;
1101}
1102
1103STDMETHODIMP Console::COMGETTER(Mouse) (IMouse **aMouse)
1104{
1105 if (!aMouse)
1106 return E_POINTER;
1107
1108 AutoCaller autoCaller (this);
1109 CheckComRCReturnRC (autoCaller.rc());
1110
1111 /* mMouse is constant during life time, no need to lock */
1112 mMouse.queryInterfaceTo (aMouse);
1113
1114 return S_OK;
1115}
1116
1117STDMETHODIMP Console::COMGETTER(Display) (IDisplay **aDisplay)
1118{
1119 if (!aDisplay)
1120 return E_POINTER;
1121
1122 AutoCaller autoCaller (this);
1123 CheckComRCReturnRC (autoCaller.rc());
1124
1125 /* mDisplay is constant during life time, no need to lock */
1126 mDisplay.queryInterfaceTo (aDisplay);
1127
1128 return S_OK;
1129}
1130
1131STDMETHODIMP Console::COMGETTER(Debugger) (IMachineDebugger **aDebugger)
1132{
1133 if (!aDebugger)
1134 return E_POINTER;
1135
1136 AutoCaller autoCaller (this);
1137 CheckComRCReturnRC (autoCaller.rc());
1138
1139 /* we need a write lock because of the lazy mDebugger initialization*/
1140 AutoLock alock (this);
1141
1142 /* check if we have to create the debugger object */
1143 if (!mDebugger)
1144 {
1145 unconst (mDebugger).createObject();
1146 mDebugger->init (this);
1147 }
1148
1149 mDebugger.queryInterfaceTo (aDebugger);
1150
1151 return S_OK;
1152}
1153
1154STDMETHODIMP Console::COMGETTER(USBDevices) (IUSBDeviceCollection **aUSBDevices)
1155{
1156 if (!aUSBDevices)
1157 return E_POINTER;
1158
1159 AutoCaller autoCaller (this);
1160 CheckComRCReturnRC (autoCaller.rc());
1161
1162 AutoReaderLock alock (this);
1163
1164 ComObjPtr <OUSBDeviceCollection> collection;
1165 collection.createObject();
1166 collection->init (mUSBDevices);
1167 collection.queryInterfaceTo (aUSBDevices);
1168
1169 return S_OK;
1170}
1171
1172STDMETHODIMP Console::COMGETTER(RemoteUSBDevices) (IHostUSBDeviceCollection **aRemoteUSBDevices)
1173{
1174 if (!aRemoteUSBDevices)
1175 return E_POINTER;
1176
1177 AutoCaller autoCaller (this);
1178 CheckComRCReturnRC (autoCaller.rc());
1179
1180 AutoReaderLock alock (this);
1181
1182 ComObjPtr <RemoteUSBDeviceCollection> collection;
1183 collection.createObject();
1184 collection->init (mRemoteUSBDevices);
1185 collection.queryInterfaceTo (aRemoteUSBDevices);
1186
1187 return S_OK;
1188}
1189
1190STDMETHODIMP Console::COMGETTER(RemoteDisplayInfo) (IRemoteDisplayInfo **aRemoteDisplayInfo)
1191{
1192 if (!aRemoteDisplayInfo)
1193 return E_POINTER;
1194
1195 AutoCaller autoCaller (this);
1196 CheckComRCReturnRC (autoCaller.rc());
1197
1198 /* mDisplay is constant during life time, no need to lock */
1199 mRemoteDisplayInfo.queryInterfaceTo (aRemoteDisplayInfo);
1200
1201 return S_OK;
1202}
1203
1204STDMETHODIMP
1205Console::COMGETTER(SharedFolders) (ISharedFolderCollection **aSharedFolders)
1206{
1207 if (!aSharedFolders)
1208 return E_POINTER;
1209
1210 AutoCaller autoCaller (this);
1211 CheckComRCReturnRC (autoCaller.rc());
1212
1213 /* loadDataFromSavedState() needs a write lock */
1214 AutoLock alock (this);
1215
1216 /* Read console data stored in the saved state file (if not yet done) */
1217 HRESULT rc = loadDataFromSavedState();
1218 CheckComRCReturnRC (rc);
1219
1220 ComObjPtr <SharedFolderCollection> coll;
1221 coll.createObject();
1222 coll->init (mSharedFolders);
1223 coll.queryInterfaceTo (aSharedFolders);
1224
1225 return S_OK;
1226}
1227
1228// IConsole methods
1229/////////////////////////////////////////////////////////////////////////////
1230
1231STDMETHODIMP Console::PowerUp (IProgress **aProgress)
1232{
1233 LogFlowThisFuncEnter();
1234 LogFlowThisFunc (("mMachineState=%d\n", mMachineState));
1235
1236 AutoCaller autoCaller (this);
1237 CheckComRCReturnRC (autoCaller.rc());
1238
1239 AutoLock alock (this);
1240
1241 if (mMachineState >= MachineState_Running)
1242 return setError(E_FAIL, tr ("Cannot power up the machine as it is "
1243 "already running (machine state: %d)"),
1244 mMachineState);
1245
1246 /*
1247 * First check whether all disks are accessible. This is not a 100%
1248 * bulletproof approach (race condition, it might become inaccessible
1249 * right after the check) but it's convenient as it will cover 99.9%
1250 * of the cases and here, we're able to provide meaningful error
1251 * information.
1252 */
1253 ComPtr<IHardDiskAttachmentCollection> coll;
1254 mMachine->COMGETTER(HardDiskAttachments)(coll.asOutParam());
1255 ComPtr<IHardDiskAttachmentEnumerator> enumerator;
1256 coll->Enumerate(enumerator.asOutParam());
1257 BOOL fHasMore;
1258 while (SUCCEEDED(enumerator->HasMore(&fHasMore)) && fHasMore)
1259 {
1260 ComPtr<IHardDiskAttachment> attach;
1261 enumerator->GetNext(attach.asOutParam());
1262 ComPtr<IHardDisk> hdd;
1263 attach->COMGETTER(HardDisk)(hdd.asOutParam());
1264 Assert(hdd);
1265 BOOL fAccessible;
1266 HRESULT rc = hdd->COMGETTER(AllAccessible)(&fAccessible);
1267 CheckComRCReturnRC (rc);
1268 if (!fAccessible)
1269 {
1270 Bstr loc;
1271 hdd->COMGETTER(Location) (loc.asOutParam());
1272 Bstr errMsg;
1273 hdd->COMGETTER(LastAccessError) (errMsg.asOutParam());
1274 return setError (E_FAIL,
1275 tr ("VM cannot start because the hard disk '%ls' is not accessible "
1276 "(%ls)"),
1277 loc.raw(), errMsg.raw());
1278 }
1279 }
1280
1281 /* now perform the same check if a ISO is mounted */
1282 ComPtr<IDVDDrive> dvdDrive;
1283 mMachine->COMGETTER(DVDDrive)(dvdDrive.asOutParam());
1284 ComPtr<IDVDImage> dvdImage;
1285 dvdDrive->GetImage(dvdImage.asOutParam());
1286 if (dvdImage)
1287 {
1288 BOOL fAccessible;
1289 HRESULT rc = dvdImage->COMGETTER(Accessible)(&fAccessible);
1290 CheckComRCReturnRC (rc);
1291 if (!fAccessible)
1292 {
1293 Bstr filePath;
1294 dvdImage->COMGETTER(FilePath)(filePath.asOutParam());
1295 /// @todo (r=dmik) grab the last access error once
1296 // IDVDImage::lastAccessError is there
1297 return setError (E_FAIL,
1298 tr ("VM cannot start because the DVD image '%ls' is not accessible"),
1299 filePath.raw());
1300 }
1301 }
1302
1303 /* now perform the same check if a floppy is mounted */
1304 ComPtr<IFloppyDrive> floppyDrive;
1305 mMachine->COMGETTER(FloppyDrive)(floppyDrive.asOutParam());
1306 ComPtr<IFloppyImage> floppyImage;
1307 floppyDrive->GetImage(floppyImage.asOutParam());
1308 if (floppyImage)
1309 {
1310 BOOL fAccessible;
1311 HRESULT rc = floppyImage->COMGETTER(Accessible)(&fAccessible);
1312 CheckComRCReturnRC (rc);
1313 if (!fAccessible)
1314 {
1315 Bstr filePath;
1316 floppyImage->COMGETTER(FilePath)(filePath.asOutParam());
1317 /// @todo (r=dmik) grab the last access error once
1318 // IDVDImage::lastAccessError is there
1319 return setError (E_FAIL,
1320 tr ("VM cannot start because the floppy image '%ls' is not accessible"),
1321 filePath.raw());
1322 }
1323 }
1324
1325 /* now the network cards will undergo a quick consistency check */
1326 for (ULONG slot = 0; slot < SchemaDefs::NetworkAdapterCount; slot ++)
1327 {
1328 ComPtr<INetworkAdapter> adapter;
1329 mMachine->GetNetworkAdapter (slot, adapter.asOutParam());
1330 BOOL enabled = FALSE;
1331 adapter->COMGETTER(Enabled) (&enabled);
1332 if (!enabled)
1333 continue;
1334
1335 NetworkAttachmentType_T netattach;
1336 adapter->COMGETTER(AttachmentType)(&netattach);
1337 switch (netattach)
1338 {
1339 case NetworkAttachmentType_HostInterfaceNetworkAttachment:
1340 {
1341#ifdef RT_OS_WINDOWS
1342 /* a valid host interface must have been set */
1343 Bstr hostif;
1344 adapter->COMGETTER(HostInterface)(hostif.asOutParam());
1345 if (!hostif)
1346 {
1347 return setError (E_FAIL,
1348 tr ("VM cannot start because host interface networking "
1349 "requires a host interface name to be set"));
1350 }
1351 ComPtr<IVirtualBox> virtualBox;
1352 mMachine->COMGETTER(Parent)(virtualBox.asOutParam());
1353 ComPtr<IHost> host;
1354 virtualBox->COMGETTER(Host)(host.asOutParam());
1355 ComPtr<IHostNetworkInterfaceCollection> coll;
1356 host->COMGETTER(NetworkInterfaces)(coll.asOutParam());
1357 ComPtr<IHostNetworkInterface> hostInterface;
1358 if (!SUCCEEDED(coll->FindByName(hostif, hostInterface.asOutParam())))
1359 {
1360 return setError (E_FAIL,
1361 tr ("VM cannot start because the host interface '%ls' "
1362 "does not exist"),
1363 hostif.raw());
1364 }
1365#endif /* RT_OS_WINDOWS */
1366 break;
1367 }
1368 default:
1369 break;
1370 }
1371 }
1372
1373 /* Read console data stored in the saved state file (if not yet done) */
1374 {
1375 HRESULT rc = loadDataFromSavedState();
1376 CheckComRCReturnRC (rc);
1377 }
1378
1379 /* Check all types of shared folders and compose a single list */
1380 SharedFolderDataMap sharedFolders;
1381 {
1382 /* first, insert global folders */
1383 for (SharedFolderDataMap::const_iterator it = mGlobalSharedFolders.begin();
1384 it != mGlobalSharedFolders.end(); ++ it)
1385 sharedFolders [it->first] = it->second;
1386
1387 /* second, insert machine folders */
1388 for (SharedFolderDataMap::const_iterator it = mMachineSharedFolders.begin();
1389 it != mMachineSharedFolders.end(); ++ it)
1390 sharedFolders [it->first] = it->second;
1391
1392 /* third, insert console folders */
1393 for (SharedFolderMap::const_iterator it = mSharedFolders.begin();
1394 it != mSharedFolders.end(); ++ it)
1395 sharedFolders [it->first] = it->second->hostPath();
1396 }
1397
1398 Bstr savedStateFile;
1399
1400 /*
1401 * Saved VMs will have to prove that their saved states are kosher.
1402 */
1403 if (mMachineState == MachineState_Saved)
1404 {
1405 HRESULT rc = mMachine->COMGETTER(StateFilePath) (savedStateFile.asOutParam());
1406 CheckComRCReturnRC (rc);
1407 ComAssertRet (!!savedStateFile, E_FAIL);
1408 int vrc = SSMR3ValidateFile (Utf8Str (savedStateFile));
1409 if (VBOX_FAILURE (vrc))
1410 return setError (E_FAIL,
1411 tr ("VM cannot start because the saved state file '%ls' is invalid (%Vrc). "
1412 "Discard the saved state prior to starting the VM"),
1413 savedStateFile.raw(), vrc);
1414 }
1415
1416 /* create an IProgress object to track progress of this operation */
1417 ComObjPtr <Progress> progress;
1418 progress.createObject();
1419 Bstr progressDesc;
1420 if (mMachineState == MachineState_Saved)
1421 progressDesc = tr ("Restoring the virtual machine");
1422 else
1423 progressDesc = tr ("Starting the virtual machine");
1424 progress->init ((IConsole *) this, progressDesc, FALSE /* aCancelable */);
1425
1426 /* pass reference to caller if requested */
1427 if (aProgress)
1428 progress.queryInterfaceTo (aProgress);
1429
1430 /* setup task object and thread to carry out the operation asynchronously */
1431 std::auto_ptr <VMPowerUpTask> task (new VMPowerUpTask (this, progress));
1432 ComAssertComRCRetRC (task->rc());
1433
1434 task->mSetVMErrorCallback = setVMErrorCallback;
1435 task->mConfigConstructor = configConstructor;
1436 task->mSharedFolders = sharedFolders;
1437 if (mMachineState == MachineState_Saved)
1438 task->mSavedStateFile = savedStateFile;
1439
1440 int vrc = RTThreadCreate (NULL, Console::powerUpThread, (void *) task.get(),
1441 0, RTTHREADTYPE_MAIN_WORKER, 0, "VMPowerUp");
1442
1443 ComAssertMsgRCRet (vrc, ("Could not create VMPowerUp thread (%Vrc)\n", vrc),
1444 E_FAIL);
1445
1446 /* task is now owned by powerUpThread(), so release it */
1447 task.release();
1448
1449 if (mMachineState == MachineState_Saved)
1450 setMachineState (MachineState_Restoring);
1451 else
1452 setMachineState (MachineState_Starting);
1453
1454 LogFlowThisFunc (("mMachineState=%d\n", mMachineState));
1455 LogFlowThisFuncLeave();
1456 return S_OK;
1457}
1458
1459STDMETHODIMP Console::PowerDown()
1460{
1461 LogFlowThisFuncEnter();
1462 LogFlowThisFunc (("mMachineState=%d\n", mMachineState));
1463
1464 AutoCaller autoCaller (this);
1465 CheckComRCReturnRC (autoCaller.rc());
1466
1467 AutoLock alock (this);
1468
1469 if (mMachineState != MachineState_Running &&
1470 mMachineState != MachineState_Paused)
1471 {
1472 /* extra nice error message for a common case */
1473 if (mMachineState == MachineState_Saved)
1474 return setError(E_FAIL, tr ("Cannot power off a saved machine"));
1475 else
1476 return setError(E_FAIL, tr ("Cannot power off the machine as it is "
1477 "not running or paused (machine state: %d)"),
1478 mMachineState);
1479 }
1480
1481 LogFlowThisFunc (("Sending SHUTDOWN request...\n"));
1482
1483 HRESULT rc = powerDown();
1484
1485 LogFlowThisFunc (("mMachineState=%d, rc=%08X\n", mMachineState, rc));
1486 LogFlowThisFuncLeave();
1487 return rc;
1488}
1489
1490STDMETHODIMP Console::Reset()
1491{
1492 LogFlowThisFuncEnter();
1493 LogFlowThisFunc (("mMachineState=%d\n", mMachineState));
1494
1495 AutoCaller autoCaller (this);
1496 CheckComRCReturnRC (autoCaller.rc());
1497
1498 AutoLock alock (this);
1499
1500 if (mMachineState != MachineState_Running)
1501 return setError(E_FAIL, tr ("Cannot reset the machine as it is "
1502 "not running (machine state: %d)"),
1503 mMachineState);
1504
1505 /* protect mpVM */
1506 AutoVMCaller autoVMCaller (this);
1507 CheckComRCReturnRC (autoVMCaller.rc());
1508
1509 /* leave the lock before a VMR3* call (EMT will call us back)! */
1510 alock.leave();
1511
1512 int vrc = VMR3Reset (mpVM);
1513
1514 HRESULT rc = VBOX_SUCCESS (vrc) ? S_OK :
1515 setError (E_FAIL, tr ("Could not reset the machine (%Vrc)"), vrc);
1516
1517 LogFlowThisFunc (("mMachineState=%d, rc=%08X\n", mMachineState, rc));
1518 LogFlowThisFuncLeave();
1519 return rc;
1520}
1521
1522STDMETHODIMP Console::Pause()
1523{
1524 LogFlowThisFuncEnter();
1525
1526 AutoCaller autoCaller (this);
1527 CheckComRCReturnRC (autoCaller.rc());
1528
1529 AutoLock alock (this);
1530
1531 if (mMachineState != MachineState_Running)
1532 return setError (E_FAIL, tr ("Cannot pause the machine as it is "
1533 "not running (machine state: %d)"),
1534 mMachineState);
1535
1536 /* protect mpVM */
1537 AutoVMCaller autoVMCaller (this);
1538 CheckComRCReturnRC (autoVMCaller.rc());
1539
1540 LogFlowThisFunc (("Sending PAUSE request...\n"));
1541
1542 /* leave the lock before a VMR3* call (EMT will call us back)! */
1543 alock.leave();
1544
1545 int vrc = VMR3Suspend (mpVM);
1546
1547 HRESULT rc = VBOX_SUCCESS (vrc) ? S_OK :
1548 setError (E_FAIL,
1549 tr ("Could not suspend the machine execution (%Vrc)"), vrc);
1550
1551 LogFlowThisFunc (("rc=%08X\n", rc));
1552 LogFlowThisFuncLeave();
1553 return rc;
1554}
1555
1556STDMETHODIMP Console::Resume()
1557{
1558 LogFlowThisFuncEnter();
1559
1560 AutoCaller autoCaller (this);
1561 CheckComRCReturnRC (autoCaller.rc());
1562
1563 AutoLock alock (this);
1564
1565 if (mMachineState != MachineState_Paused)
1566 return setError (E_FAIL, tr ("Cannot resume the machine as it is "
1567 "not paused (machine state: %d)"),
1568 mMachineState);
1569
1570 /* protect mpVM */
1571 AutoVMCaller autoVMCaller (this);
1572 CheckComRCReturnRC (autoVMCaller.rc());
1573
1574 LogFlowThisFunc (("Sending RESUME request...\n"));
1575
1576 /* leave the lock before a VMR3* call (EMT will call us back)! */
1577 alock.leave();
1578
1579 int vrc = VMR3Resume (mpVM);
1580
1581 HRESULT rc = VBOX_SUCCESS (vrc) ? S_OK :
1582 setError (E_FAIL,
1583 tr ("Could not resume the machine execution (%Vrc)"), vrc);
1584
1585 LogFlowThisFunc (("rc=%08X\n", rc));
1586 LogFlowThisFuncLeave();
1587 return rc;
1588}
1589
1590STDMETHODIMP Console::PowerButton()
1591{
1592 LogFlowThisFuncEnter();
1593
1594 AutoCaller autoCaller (this);
1595 CheckComRCReturnRC (autoCaller.rc());
1596
1597 AutoLock lock (this);
1598
1599 if (mMachineState != MachineState_Running)
1600 return setError (E_FAIL, tr ("Cannot power off the machine as it is "
1601 "not running (machine state: %d)"),
1602 mMachineState);
1603
1604 /* protect mpVM */
1605 AutoVMCaller autoVMCaller (this);
1606 CheckComRCReturnRC (autoVMCaller.rc());
1607
1608 PPDMIBASE pBase;
1609 int vrc = PDMR3QueryDeviceLun (mpVM, "acpi", 0, 0, &pBase);
1610 if (VBOX_SUCCESS (vrc))
1611 {
1612 Assert (pBase);
1613 PPDMIACPIPORT pPort =
1614 (PPDMIACPIPORT) pBase->pfnQueryInterface(pBase, PDMINTERFACE_ACPI_PORT);
1615 vrc = pPort ? pPort->pfnPowerButtonPress(pPort) : VERR_INVALID_POINTER;
1616 }
1617
1618 HRESULT rc = VBOX_SUCCESS (vrc) ? S_OK :
1619 setError (E_FAIL,
1620 tr ("Controlled power off failed (%Vrc)"), vrc);
1621
1622 LogFlowThisFunc (("rc=%08X\n", rc));
1623 LogFlowThisFuncLeave();
1624 return rc;
1625}
1626
1627STDMETHODIMP Console::SaveState (IProgress **aProgress)
1628{
1629 LogFlowThisFuncEnter();
1630 LogFlowThisFunc (("mMachineState=%d\n", mMachineState));
1631
1632 if (!aProgress)
1633 return E_POINTER;
1634
1635 AutoCaller autoCaller (this);
1636 CheckComRCReturnRC (autoCaller.rc());
1637
1638 AutoLock alock (this);
1639
1640 if (mMachineState != MachineState_Running &&
1641 mMachineState != MachineState_Paused)
1642 {
1643 return setError (E_FAIL,
1644 tr ("Cannot save the execution state as the machine "
1645 "is not running (machine state: %d)"), mMachineState);
1646 }
1647
1648 /* memorize the current machine state */
1649 MachineState_T lastMachineState = mMachineState;
1650
1651 if (mMachineState == MachineState_Running)
1652 {
1653 HRESULT rc = Pause();
1654 CheckComRCReturnRC (rc);
1655 }
1656
1657 HRESULT rc = S_OK;
1658
1659 /* create a progress object to track operation completion */
1660 ComObjPtr <Progress> progress;
1661 progress.createObject();
1662 progress->init ((IConsole *) this,
1663 Bstr (tr ("Saving the execution state of the virtual machine")),
1664 FALSE /* aCancelable */);
1665
1666 bool beganSavingState = false;
1667 bool taskCreationFailed = false;
1668
1669 do
1670 {
1671 /* create a task object early to ensure mpVM protection is successful */
1672 std::auto_ptr <VMSaveTask> task (new VMSaveTask (this, progress));
1673 rc = task->rc();
1674 /*
1675 * If we fail here it means a PowerDown() call happened on another
1676 * thread while we were doing Pause() (which leaves the Console lock).
1677 * We assign PowerDown() a higher precendence than SaveState(),
1678 * therefore just return the error to the caller.
1679 */
1680 if (FAILED (rc))
1681 {
1682 taskCreationFailed = true;
1683 break;
1684 }
1685
1686 Bstr stateFilePath;
1687
1688 /*
1689 * request a saved state file path from the server
1690 * (this will set the machine state to Saving on the server to block
1691 * others from accessing this machine)
1692 */
1693 rc = mControl->BeginSavingState (progress, stateFilePath.asOutParam());
1694 CheckComRCBreakRC (rc);
1695
1696 beganSavingState = true;
1697
1698 /* sync the state with the server */
1699 setMachineStateLocally (MachineState_Saving);
1700
1701 /* ensure the directory for the saved state file exists */
1702 {
1703 Utf8Str dir = stateFilePath;
1704 RTPathStripFilename (dir.mutableRaw());
1705 if (!RTDirExists (dir))
1706 {
1707 int vrc = RTDirCreateFullPath (dir, 0777);
1708 if (VBOX_FAILURE (vrc))
1709 {
1710 rc = setError (E_FAIL,
1711 tr ("Could not create a directory '%s' to save the state to (%Vrc)"),
1712 dir.raw(), vrc);
1713 break;
1714 }
1715 }
1716 }
1717
1718 /* setup task object and thread to carry out the operation asynchronously */
1719 task->mIsSnapshot = false;
1720 task->mSavedStateFile = stateFilePath;
1721 /* set the state the operation thread will restore when it is finished */
1722 task->mLastMachineState = lastMachineState;
1723
1724 /* create a thread to wait until the VM state is saved */
1725 int vrc = RTThreadCreate (NULL, Console::saveStateThread, (void *) task.get(),
1726 0, RTTHREADTYPE_MAIN_WORKER, 0, "VMSave");
1727
1728 ComAssertMsgRCBreak (vrc, ("Could not create VMSave thread (%Vrc)\n", vrc),
1729 rc = E_FAIL);
1730
1731 /* task is now owned by saveStateThread(), so release it */
1732 task.release();
1733
1734 /* return the progress to the caller */
1735 progress.queryInterfaceTo (aProgress);
1736 }
1737 while (0);
1738
1739 if (FAILED (rc) && !taskCreationFailed)
1740 {
1741 /* preserve existing error info */
1742 ErrorInfoKeeper eik;
1743
1744 if (beganSavingState)
1745 {
1746 /*
1747 * cancel the requested save state procedure.
1748 * This will reset the machine state to the state it had right
1749 * before calling mControl->BeginSavingState().
1750 */
1751 mControl->EndSavingState (FALSE);
1752 }
1753
1754 if (lastMachineState == MachineState_Running)
1755 {
1756 /* restore the paused state if appropriate */
1757 setMachineStateLocally (MachineState_Paused);
1758 /* restore the running state if appropriate */
1759 Resume();
1760 }
1761 else
1762 setMachineStateLocally (lastMachineState);
1763 }
1764
1765 LogFlowThisFunc (("rc=%08X\n", rc));
1766 LogFlowThisFuncLeave();
1767 return rc;
1768}
1769
1770STDMETHODIMP Console::DiscardSavedState()
1771{
1772 AutoCaller autoCaller (this);
1773 CheckComRCReturnRC (autoCaller.rc());
1774
1775 AutoLock alock (this);
1776
1777 if (mMachineState != MachineState_Saved)
1778 return setError (E_FAIL,
1779 tr ("Cannot discard the machine state as the machine is "
1780 "not in the saved state (machine state: %d)"),
1781 mMachineState);
1782
1783 /*
1784 * Saved -> PoweredOff transition will be detected in the SessionMachine
1785 * and properly handled.
1786 */
1787 setMachineState (MachineState_PoweredOff);
1788
1789 return S_OK;
1790}
1791
1792/** read the value of a LEd. */
1793inline uint32_t readAndClearLed(PPDMLED pLed)
1794{
1795 if (!pLed)
1796 return 0;
1797 uint32_t u32 = pLed->Actual.u32 | pLed->Asserted.u32;
1798 pLed->Asserted.u32 = 0;
1799 return u32;
1800}
1801
1802STDMETHODIMP Console::GetDeviceActivity (DeviceType_T aDeviceType,
1803 DeviceActivity_T *aDeviceActivity)
1804{
1805 if (!aDeviceActivity)
1806 return E_INVALIDARG;
1807
1808 AutoCaller autoCaller (this);
1809 CheckComRCReturnRC (autoCaller.rc());
1810
1811 /*
1812 * Note: we don't lock the console object here because
1813 * readAndClearLed() should be thread safe.
1814 */
1815
1816 /* Get LED array to read */
1817 PDMLEDCORE SumLed = {0};
1818 switch (aDeviceType)
1819 {
1820 case DeviceType_FloppyDevice:
1821 {
1822 for (unsigned i = 0; i < ELEMENTS(mapFDLeds); i++)
1823 SumLed.u32 |= readAndClearLed(mapFDLeds[i]);
1824 break;
1825 }
1826
1827 case DeviceType_DVDDevice:
1828 {
1829 SumLed.u32 |= readAndClearLed(mapIDELeds[2]);
1830 break;
1831 }
1832
1833 case DeviceType_HardDiskDevice:
1834 {
1835 SumLed.u32 |= readAndClearLed(mapIDELeds[0]);
1836 SumLed.u32 |= readAndClearLed(mapIDELeds[1]);
1837 SumLed.u32 |= readAndClearLed(mapIDELeds[3]);
1838 break;
1839 }
1840
1841 case DeviceType_NetworkDevice:
1842 {
1843 for (unsigned i = 0; i < ELEMENTS(mapNetworkLeds); i++)
1844 SumLed.u32 |= readAndClearLed(mapNetworkLeds[i]);
1845 break;
1846 }
1847
1848 case DeviceType_USBDevice:
1849 {
1850 SumLed.u32 |= readAndClearLed(mapUSBLed);
1851 break;
1852 }
1853
1854 case DeviceType_SharedFolderDevice:
1855 {
1856 SumLed.u32 |= readAndClearLed(mapSharedFolderLed);
1857 break;
1858 }
1859
1860 default:
1861 return setError (E_INVALIDARG,
1862 tr ("Invalid device type: %d"), aDeviceType);
1863 }
1864
1865 /* Compose the result */
1866 switch (SumLed.u32 & (PDMLED_READING | PDMLED_WRITING))
1867 {
1868 case 0:
1869 *aDeviceActivity = DeviceActivity_DeviceIdle;
1870 break;
1871 case PDMLED_READING:
1872 *aDeviceActivity = DeviceActivity_DeviceReading;
1873 break;
1874 case PDMLED_WRITING:
1875 case PDMLED_READING | PDMLED_WRITING:
1876 *aDeviceActivity = DeviceActivity_DeviceWriting;
1877 break;
1878 }
1879
1880 return S_OK;
1881}
1882
1883STDMETHODIMP Console::AttachUSBDevice (INPTR GUIDPARAM aId)
1884{
1885 AutoCaller autoCaller (this);
1886 CheckComRCReturnRC (autoCaller.rc());
1887
1888 AutoLock alock (this);
1889
1890 /// @todo (r=dmik) is it legal to attach USB devices when the machine is
1891 // Paused, Starting, Saving, Stopping, etc? if not, we should make a
1892 // stricter check (mMachineState != MachineState_Running).
1893 /* bird: It is not permitted to attach or detach while the VM is saving, is restoring
1894 * or has stopped - definintly not.
1895 *
1896 * Attaching while starting, well, if you don't create any deadlock it should work...
1897 * Paused should work I guess, but we shouldn't push our luck if we're pausing because an
1898 * runtime error condition was raised (which is one of the reasons there better be a separate
1899 * state for that in the VMM).
1900 */
1901 if (mMachineState < MachineState_Running)
1902 return setError (E_FAIL,
1903 tr ("Cannot attach a USB device to a machine which is not running "
1904 "(machine state: %d)"), mMachineState);
1905
1906 /* protect mpVM */
1907 AutoVMCaller autoVMCaller (this);
1908 CheckComRCReturnRC (autoVMCaller.rc());
1909
1910 /* Don't proceed unless we've found the usb controller. */
1911 PPDMIBASE pBase = NULL;
1912 int vrc = PDMR3QueryLun (mpVM, "usb-ohci", 0, 0, &pBase);
1913 if (VBOX_FAILURE (vrc))
1914 return setError (E_FAIL,
1915 tr ("The virtual machine does not have a USB controller"));
1916
1917 /* leave the lock because the USB Proxy service may call us back
1918 * (via onUSBDeviceAttach()) */
1919 alock.leave();
1920
1921 /* Request the device capture */
1922 HRESULT rc = mControl->CaptureUSBDevice (aId);
1923 CheckComRCReturnRC (rc);
1924
1925 return rc;
1926}
1927
1928STDMETHODIMP Console::DetachUSBDevice (INPTR GUIDPARAM aId, IUSBDevice **aDevice)
1929{
1930 if (!aDevice)
1931 return E_POINTER;
1932
1933 AutoCaller autoCaller (this);
1934 CheckComRCReturnRC (autoCaller.rc());
1935
1936 AutoLock alock (this);
1937
1938 /* Find it. */
1939 ComObjPtr <OUSBDevice> device;
1940 USBDeviceList::iterator it = mUSBDevices.begin();
1941 while (it != mUSBDevices.end())
1942 {
1943 if ((*it)->id() == aId)
1944 {
1945 device = *it;
1946 break;
1947 }
1948 ++ it;
1949 }
1950
1951 if (!device)
1952 return setError (E_INVALIDARG,
1953 tr ("USB device with UUID {%Vuuid} is not attached to this machine"),
1954 Guid (aId).raw());
1955
1956#ifdef RT_OS_DARWIN
1957 /* Notify the USB Proxy that we're about to detach the device. Since
1958 * we don't dare do IPC when holding the console lock, so we'll have
1959 * to revalidate the device when we get back. */
1960 alock.leave();
1961 HRESULT rc2 = mControl->DetachUSBDevice (aId, false /* aDone */);
1962 if (FAILED (rc2))
1963 return rc2;
1964 alock.enter();
1965
1966 for (it = mUSBDevices.begin(); it != mUSBDevices.end(); ++ it)
1967 if ((*it)->id() == aId)
1968 break;
1969 if (it == mUSBDevices.end())
1970 return S_OK;
1971#endif
1972
1973 /* First, request VMM to detach the device */
1974 HRESULT rc = detachUSBDevice (it);
1975
1976 if (SUCCEEDED (rc))
1977 {
1978 /* leave the lock since we don't need it any more (note though that
1979 * the USB Proxy service must not call us back here) */
1980 alock.leave();
1981
1982 /* Request the device release. Even if it fails, the device will
1983 * remain as held by proxy, which is OK for us (the VM process). */
1984 rc = mControl->DetachUSBDevice (aId, true /* aDone */);
1985 }
1986
1987 return rc;
1988}
1989
1990STDMETHODIMP
1991Console::CreateSharedFolder (INPTR BSTR aName, INPTR BSTR aHostPath)
1992{
1993 if (!aName || !aHostPath)
1994 return E_INVALIDARG;
1995
1996 AutoCaller autoCaller (this);
1997 CheckComRCReturnRC (autoCaller.rc());
1998
1999 AutoLock alock (this);
2000
2001 if (mMachineState == MachineState_Saved)
2002 return setError (E_FAIL,
2003 tr ("Cannot create a transient shared folder on a "
2004 "machine in the saved state"));
2005
2006 ComObjPtr <SharedFolder> sharedFolder;
2007 HRESULT rc = findSharedFolder (aName, sharedFolder, false /* aSetError */);
2008 if (SUCCEEDED (rc))
2009 return setError (E_FAIL,
2010 tr ("Shared folder named '%ls' already exists"), aName);
2011
2012 sharedFolder.createObject();
2013 rc = sharedFolder->init (this, aName, aHostPath);
2014 CheckComRCReturnRC (rc);
2015
2016 BOOL accessible = FALSE;
2017 rc = sharedFolder->COMGETTER(Accessible) (&accessible);
2018 CheckComRCReturnRC (rc);
2019
2020 if (!accessible)
2021 return setError (E_FAIL,
2022 tr ("Shared folder host path '%ls' is not accessible"), aHostPath);
2023
2024 /* protect mpVM (if not NULL) */
2025 AutoVMCallerQuietWeak autoVMCaller (this);
2026
2027 if (mpVM && autoVMCaller.isOk() && mVMMDev->isShFlActive())
2028 {
2029 /* If the VM is online and supports shared folders, share this folder
2030 * under the specified name. */
2031
2032 /* first, remove the machine or the global folder if there is any */
2033 SharedFolderDataMap::const_iterator it;
2034 if (findOtherSharedFolder (aName, it))
2035 {
2036 rc = removeSharedFolder (aName);
2037 CheckComRCReturnRC (rc);
2038 }
2039
2040 /* second, create the given folder */
2041 rc = createSharedFolder (aName, aHostPath);
2042 CheckComRCReturnRC (rc);
2043 }
2044
2045 mSharedFolders.insert (std::make_pair (aName, sharedFolder));
2046
2047 /* notify console callbacks after the folder is added to the list */
2048 {
2049 CallbackList::iterator it = mCallbacks.begin();
2050 while (it != mCallbacks.end())
2051 (*it++)->OnSharedFolderChange (Scope_SessionScope);
2052 }
2053
2054 return rc;
2055}
2056
2057STDMETHODIMP Console::RemoveSharedFolder (INPTR BSTR aName)
2058{
2059 if (!aName)
2060 return E_INVALIDARG;
2061
2062 AutoCaller autoCaller (this);
2063 CheckComRCReturnRC (autoCaller.rc());
2064
2065 AutoLock alock (this);
2066
2067 if (mMachineState == MachineState_Saved)
2068 return setError (E_FAIL,
2069 tr ("Cannot remove a transient shared folder when the "
2070 "machine is in the saved state."));
2071
2072 ComObjPtr <SharedFolder> sharedFolder;
2073 HRESULT rc = findSharedFolder (aName, sharedFolder, true /* aSetError */);
2074 CheckComRCReturnRC (rc);
2075
2076 /* protect mpVM (if not NULL) */
2077 AutoVMCallerQuietWeak autoVMCaller (this);
2078
2079 if (mpVM && autoVMCaller.isOk() && mVMMDev->isShFlActive())
2080 {
2081 /* if the VM is online and supports shared folders, UNshare this
2082 * folder. */
2083
2084 /* first, remove the given folder */
2085 rc = removeSharedFolder (aName);
2086 CheckComRCReturnRC (rc);
2087
2088 /* first, remove the machine or the global folder if there is any */
2089 SharedFolderDataMap::const_iterator it;
2090 if (findOtherSharedFolder (aName, it))
2091 {
2092 rc = createSharedFolder (aName, it->second);
2093 /* don't check rc here because we need to remove the console
2094 * folder from the collection even on failure */
2095 }
2096 }
2097
2098 mSharedFolders.erase (aName);
2099
2100 /* notify console callbacks after the folder is removed to the list */
2101 {
2102 CallbackList::iterator it = mCallbacks.begin();
2103 while (it != mCallbacks.end())
2104 (*it++)->OnSharedFolderChange (Scope_SessionScope);
2105 }
2106
2107 return rc;
2108}
2109
2110STDMETHODIMP Console::TakeSnapshot (INPTR BSTR aName, INPTR BSTR aDescription,
2111 IProgress **aProgress)
2112{
2113 LogFlowThisFuncEnter();
2114 LogFlowThisFunc (("aName='%ls' mMachineState=%08X\n", aName, mMachineState));
2115
2116 if (!aName)
2117 return E_INVALIDARG;
2118 if (!aProgress)
2119 return E_POINTER;
2120
2121 AutoCaller autoCaller (this);
2122 CheckComRCReturnRC (autoCaller.rc());
2123
2124 AutoLock alock (this);
2125
2126 if (mMachineState > MachineState_Running &&
2127 mMachineState != MachineState_Paused)
2128 {
2129 return setError (E_FAIL,
2130 tr ("Cannot take a snapshot of a machine while it is changing state. (Machine state: %d)"), mMachineState);
2131 }
2132
2133 /* memorize the current machine state */
2134 MachineState_T lastMachineState = mMachineState;
2135
2136 if (mMachineState == MachineState_Running)
2137 {
2138 HRESULT rc = Pause();
2139 CheckComRCReturnRC (rc);
2140 }
2141
2142 HRESULT rc = S_OK;
2143
2144 bool takingSnapshotOnline = mMachineState == MachineState_Paused;
2145
2146 /*
2147 * create a descriptionless VM-side progress object
2148 * (only when creating a snapshot online)
2149 */
2150 ComObjPtr <Progress> saveProgress;
2151 if (takingSnapshotOnline)
2152 {
2153 saveProgress.createObject();
2154 rc = saveProgress->init (FALSE, 1, Bstr (tr ("Saving the execution state")));
2155 AssertComRCReturn (rc, rc);
2156 }
2157
2158 bool beganTakingSnapshot = false;
2159 bool taskCreationFailed = false;
2160
2161 do
2162 {
2163 /* create a task object early to ensure mpVM protection is successful */
2164 std::auto_ptr <VMSaveTask> task;
2165 if (takingSnapshotOnline)
2166 {
2167 task.reset (new VMSaveTask (this, saveProgress));
2168 rc = task->rc();
2169 /*
2170 * If we fail here it means a PowerDown() call happened on another
2171 * thread while we were doing Pause() (which leaves the Console lock).
2172 * We assign PowerDown() a higher precendence than TakeSnapshot(),
2173 * therefore just return the error to the caller.
2174 */
2175 if (FAILED (rc))
2176 {
2177 taskCreationFailed = true;
2178 break;
2179 }
2180 }
2181
2182 Bstr stateFilePath;
2183 ComPtr <IProgress> serverProgress;
2184
2185 /*
2186 * request taking a new snapshot object on the server
2187 * (this will set the machine state to Saving on the server to block
2188 * others from accessing this machine)
2189 */
2190 rc = mControl->BeginTakingSnapshot (this, aName, aDescription,
2191 saveProgress, stateFilePath.asOutParam(),
2192 serverProgress.asOutParam());
2193 if (FAILED (rc))
2194 break;
2195
2196 /*
2197 * state file is non-null only when the VM is paused
2198 * (i.e. createing a snapshot online)
2199 */
2200 ComAssertBreak (
2201 (!stateFilePath.isNull() && takingSnapshotOnline) ||
2202 (stateFilePath.isNull() && !takingSnapshotOnline),
2203 rc = E_FAIL);
2204
2205 beganTakingSnapshot = true;
2206
2207 /* sync the state with the server */
2208 setMachineStateLocally (MachineState_Saving);
2209
2210 /*
2211 * create a combined VM-side progress object and start the save task
2212 * (only when creating a snapshot online)
2213 */
2214 ComObjPtr <CombinedProgress> combinedProgress;
2215 if (takingSnapshotOnline)
2216 {
2217 combinedProgress.createObject();
2218 rc = combinedProgress->init ((IConsole *) this,
2219 Bstr (tr ("Taking snapshot of virtual machine")),
2220 serverProgress, saveProgress);
2221 AssertComRCBreakRC (rc);
2222
2223 /* setup task object and thread to carry out the operation asynchronously */
2224 task->mIsSnapshot = true;
2225 task->mSavedStateFile = stateFilePath;
2226 task->mServerProgress = serverProgress;
2227 /* set the state the operation thread will restore when it is finished */
2228 task->mLastMachineState = lastMachineState;
2229
2230 /* create a thread to wait until the VM state is saved */
2231 int vrc = RTThreadCreate (NULL, Console::saveStateThread, (void *) task.get(),
2232 0, RTTHREADTYPE_MAIN_WORKER, 0, "VMTakeSnap");
2233
2234 ComAssertMsgRCBreak (vrc, ("Could not create VMTakeSnap thread (%Vrc)\n", vrc),
2235 rc = E_FAIL);
2236
2237 /* task is now owned by saveStateThread(), so release it */
2238 task.release();
2239 }
2240
2241 if (SUCCEEDED (rc))
2242 {
2243 /* return the correct progress to the caller */
2244 if (combinedProgress)
2245 combinedProgress.queryInterfaceTo (aProgress);
2246 else
2247 serverProgress.queryInterfaceTo (aProgress);
2248 }
2249 }
2250 while (0);
2251
2252 if (FAILED (rc) && !taskCreationFailed)
2253 {
2254 /* preserve existing error info */
2255 ErrorInfoKeeper eik;
2256
2257 if (beganTakingSnapshot && takingSnapshotOnline)
2258 {
2259 /*
2260 * cancel the requested snapshot (only when creating a snapshot
2261 * online, otherwise the server will cancel the snapshot itself).
2262 * This will reset the machine state to the state it had right
2263 * before calling mControl->BeginTakingSnapshot().
2264 */
2265 mControl->EndTakingSnapshot (FALSE);
2266 }
2267
2268 if (lastMachineState == MachineState_Running)
2269 {
2270 /* restore the paused state if appropriate */
2271 setMachineStateLocally (MachineState_Paused);
2272 /* restore the running state if appropriate */
2273 Resume();
2274 }
2275 else
2276 setMachineStateLocally (lastMachineState);
2277 }
2278
2279 LogFlowThisFunc (("rc=%08X\n", rc));
2280 LogFlowThisFuncLeave();
2281 return rc;
2282}
2283
2284STDMETHODIMP Console::DiscardSnapshot (INPTR GUIDPARAM aId, IProgress **aProgress)
2285{
2286 if (Guid (aId).isEmpty())
2287 return E_INVALIDARG;
2288 if (!aProgress)
2289 return E_POINTER;
2290
2291 AutoCaller autoCaller (this);
2292 CheckComRCReturnRC (autoCaller.rc());
2293
2294 AutoLock alock (this);
2295
2296 if (mMachineState >= MachineState_Running)
2297 return setError (E_FAIL,
2298 tr ("Cannot discard a snapshot on a running machine (Machine state: %d)"), mMachineState);
2299
2300 MachineState_T machineState = MachineState_InvalidMachineState;
2301 HRESULT rc = mControl->DiscardSnapshot (this, aId, &machineState, aProgress);
2302 CheckComRCReturnRC (rc);
2303
2304 setMachineStateLocally (machineState);
2305 return S_OK;
2306}
2307
2308STDMETHODIMP Console::DiscardCurrentState (IProgress **aProgress)
2309{
2310 AutoCaller autoCaller (this);
2311 CheckComRCReturnRC (autoCaller.rc());
2312
2313 AutoLock alock (this);
2314
2315 if (mMachineState >= MachineState_Running)
2316 return setError (E_FAIL,
2317 tr ("Cannot discard the current state of a running machine. (Machine state: %d)"), mMachineState);
2318
2319 MachineState_T machineState = MachineState_InvalidMachineState;
2320 HRESULT rc = mControl->DiscardCurrentState (this, &machineState, aProgress);
2321 CheckComRCReturnRC (rc);
2322
2323 setMachineStateLocally (machineState);
2324 return S_OK;
2325}
2326
2327STDMETHODIMP Console::DiscardCurrentSnapshotAndState (IProgress **aProgress)
2328{
2329 AutoCaller autoCaller (this);
2330 CheckComRCReturnRC (autoCaller.rc());
2331
2332 AutoLock alock (this);
2333
2334 if (mMachineState >= MachineState_Running)
2335 return setError (E_FAIL,
2336 tr ("Cannot discard the current snapshot and state on a running machine. (Machine state: %d)"), mMachineState);
2337
2338 MachineState_T machineState = MachineState_InvalidMachineState;
2339 HRESULT rc =
2340 mControl->DiscardCurrentSnapshotAndState (this, &machineState, aProgress);
2341 CheckComRCReturnRC (rc);
2342
2343 setMachineStateLocally (machineState);
2344 return S_OK;
2345}
2346
2347STDMETHODIMP Console::RegisterCallback (IConsoleCallback *aCallback)
2348{
2349 if (!aCallback)
2350 return E_INVALIDARG;
2351
2352 AutoCaller autoCaller (this);
2353 CheckComRCReturnRC (autoCaller.rc());
2354
2355 AutoLock alock (this);
2356
2357 mCallbacks.push_back (CallbackList::value_type (aCallback));
2358
2359 /* Inform the callback about the current status (for example, the new
2360 * callback must know the current mouse capabilities and the pointer
2361 * shape in order to properly integrate the mouse pointer). */
2362
2363 if (mCallbackData.mpsc.valid)
2364 aCallback->OnMousePointerShapeChange (mCallbackData.mpsc.visible,
2365 mCallbackData.mpsc.alpha,
2366 mCallbackData.mpsc.xHot,
2367 mCallbackData.mpsc.yHot,
2368 mCallbackData.mpsc.width,
2369 mCallbackData.mpsc.height,
2370 mCallbackData.mpsc.shape);
2371 if (mCallbackData.mcc.valid)
2372 aCallback->OnMouseCapabilityChange (mCallbackData.mcc.supportsAbsolute,
2373 mCallbackData.mcc.needsHostCursor);
2374
2375 aCallback->OnAdditionsStateChange();
2376
2377 if (mCallbackData.klc.valid)
2378 aCallback->OnKeyboardLedsChange (mCallbackData.klc.numLock,
2379 mCallbackData.klc.capsLock,
2380 mCallbackData.klc.scrollLock);
2381
2382 /* Note: we don't call OnStateChange for new callbacks because the
2383 * machine state is a) not actually changed on callback registration
2384 * and b) can be always queried from Console. */
2385
2386 return S_OK;
2387}
2388
2389STDMETHODIMP Console::UnregisterCallback (IConsoleCallback *aCallback)
2390{
2391 if (!aCallback)
2392 return E_INVALIDARG;
2393
2394 AutoCaller autoCaller (this);
2395 CheckComRCReturnRC (autoCaller.rc());
2396
2397 AutoLock alock (this);
2398
2399 CallbackList::iterator it;
2400 it = std::find (mCallbacks.begin(),
2401 mCallbacks.end(),
2402 CallbackList::value_type (aCallback));
2403 if (it == mCallbacks.end())
2404 return setError (E_INVALIDARG,
2405 tr ("The given callback handler is not registered"));
2406
2407 mCallbacks.erase (it);
2408 return S_OK;
2409}
2410
2411// Non-interface public methods
2412/////////////////////////////////////////////////////////////////////////////
2413
2414/**
2415 * Called by IInternalSessionControl::OnDVDDriveChange().
2416 *
2417 * @note Locks this object for reading.
2418 */
2419HRESULT Console::onDVDDriveChange()
2420{
2421 LogFlowThisFunc (("\n"));
2422
2423 AutoCaller autoCaller (this);
2424 AssertComRCReturnRC (autoCaller.rc());
2425
2426 AutoReaderLock alock (this);
2427
2428 /* Ignore callbacks when there's no VM around */
2429 if (!mpVM)
2430 return S_OK;
2431
2432 /* protect mpVM */
2433 AutoVMCaller autoVMCaller (this);
2434 CheckComRCReturnRC (autoVMCaller.rc());
2435
2436 /* Get the current DVD state */
2437 HRESULT rc;
2438 DriveState_T eState;
2439
2440 rc = mDVDDrive->COMGETTER (State) (&eState);
2441 ComAssertComRCRetRC (rc);
2442
2443 /* Paranoia */
2444 if ( eState == DriveState_NotMounted
2445 && meDVDState == DriveState_NotMounted)
2446 {
2447 LogFlowThisFunc (("Returns (NotMounted -> NotMounted)\n"));
2448 return S_OK;
2449 }
2450
2451 /* Get the path string and other relevant properties */
2452 Bstr Path;
2453 bool fPassthrough = false;
2454 switch (eState)
2455 {
2456 case DriveState_ImageMounted:
2457 {
2458 ComPtr <IDVDImage> ImagePtr;
2459 rc = mDVDDrive->GetImage (ImagePtr.asOutParam());
2460 if (SUCCEEDED (rc))
2461 rc = ImagePtr->COMGETTER(FilePath) (Path.asOutParam());
2462 break;
2463 }
2464
2465 case DriveState_HostDriveCaptured:
2466 {
2467 ComPtr <IHostDVDDrive> DrivePtr;
2468 BOOL enabled;
2469 rc = mDVDDrive->GetHostDrive (DrivePtr.asOutParam());
2470 if (SUCCEEDED (rc))
2471 rc = DrivePtr->COMGETTER (Name) (Path.asOutParam());
2472 if (SUCCEEDED (rc))
2473 rc = mDVDDrive->COMGETTER (Passthrough) (&enabled);
2474 if (SUCCEEDED (rc))
2475 fPassthrough = !!enabled;
2476 break;
2477 }
2478
2479 case DriveState_NotMounted:
2480 break;
2481
2482 default:
2483 AssertMsgFailed (("Invalid DriveState: %d\n", eState));
2484 rc = E_FAIL;
2485 break;
2486 }
2487
2488 AssertComRC (rc);
2489 if (FAILED (rc))
2490 {
2491 LogFlowThisFunc (("Returns %#x\n", rc));
2492 return rc;
2493 }
2494
2495 rc = doDriveChange ("piix3ide", 0, 2, eState, &meDVDState,
2496 Utf8Str (Path).raw(), fPassthrough);
2497
2498 /* notify console callbacks on success */
2499 if (SUCCEEDED (rc))
2500 {
2501 CallbackList::iterator it = mCallbacks.begin();
2502 while (it != mCallbacks.end())
2503 (*it++)->OnDVDDriveChange();
2504 }
2505
2506 return rc;
2507}
2508
2509
2510/**
2511 * Called by IInternalSessionControl::OnFloppyDriveChange().
2512 *
2513 * @note Locks this object for reading.
2514 */
2515HRESULT Console::onFloppyDriveChange()
2516{
2517 LogFlowThisFunc (("\n"));
2518
2519 AutoCaller autoCaller (this);
2520 AssertComRCReturnRC (autoCaller.rc());
2521
2522 AutoReaderLock alock (this);
2523
2524 /* Ignore callbacks when there's no VM around */
2525 if (!mpVM)
2526 return S_OK;
2527
2528 /* protect mpVM */
2529 AutoVMCaller autoVMCaller (this);
2530 CheckComRCReturnRC (autoVMCaller.rc());
2531
2532 /* Get the current floppy state */
2533 HRESULT rc;
2534 DriveState_T eState;
2535
2536 /* If the floppy drive is disabled, we're not interested */
2537 BOOL fEnabled;
2538 rc = mFloppyDrive->COMGETTER (Enabled) (&fEnabled);
2539 ComAssertComRCRetRC (rc);
2540
2541 if (!fEnabled)
2542 return S_OK;
2543
2544 rc = mFloppyDrive->COMGETTER (State) (&eState);
2545 ComAssertComRCRetRC (rc);
2546
2547 Log2 (("onFloppyDriveChange: eState=%d meFloppyState=%d\n", eState, meFloppyState));
2548
2549
2550 /* Paranoia */
2551 if ( eState == DriveState_NotMounted
2552 && meFloppyState == DriveState_NotMounted)
2553 {
2554 LogFlowThisFunc (("Returns (NotMounted -> NotMounted)\n"));
2555 return S_OK;
2556 }
2557
2558 /* Get the path string and other relevant properties */
2559 Bstr Path;
2560 switch (eState)
2561 {
2562 case DriveState_ImageMounted:
2563 {
2564 ComPtr <IFloppyImage> ImagePtr;
2565 rc = mFloppyDrive->GetImage (ImagePtr.asOutParam());
2566 if (SUCCEEDED (rc))
2567 rc = ImagePtr->COMGETTER(FilePath) (Path.asOutParam());
2568 break;
2569 }
2570
2571 case DriveState_HostDriveCaptured:
2572 {
2573 ComPtr <IHostFloppyDrive> DrivePtr;
2574 rc = mFloppyDrive->GetHostDrive (DrivePtr.asOutParam());
2575 if (SUCCEEDED (rc))
2576 rc = DrivePtr->COMGETTER (Name) (Path.asOutParam());
2577 break;
2578 }
2579
2580 case DriveState_NotMounted:
2581 break;
2582
2583 default:
2584 AssertMsgFailed (("Invalid DriveState: %d\n", eState));
2585 rc = E_FAIL;
2586 break;
2587 }
2588
2589 AssertComRC (rc);
2590 if (FAILED (rc))
2591 {
2592 LogFlowThisFunc (("Returns %#x\n", rc));
2593 return rc;
2594 }
2595
2596 rc = doDriveChange ("i82078", 0, 0, eState, &meFloppyState,
2597 Utf8Str (Path).raw(), false);
2598
2599 /* notify console callbacks on success */
2600 if (SUCCEEDED (rc))
2601 {
2602 CallbackList::iterator it = mCallbacks.begin();
2603 while (it != mCallbacks.end())
2604 (*it++)->OnFloppyDriveChange();
2605 }
2606
2607 return rc;
2608}
2609
2610
2611/**
2612 * Process a floppy or dvd change.
2613 *
2614 * @returns COM status code.
2615 *
2616 * @param pszDevice The PDM device name.
2617 * @param uInstance The PDM device instance.
2618 * @param uLun The PDM LUN number of the drive.
2619 * @param eState The new state.
2620 * @param peState Pointer to the variable keeping the actual state of the drive.
2621 * This will be both read and updated to eState or other appropriate state.
2622 * @param pszPath The path to the media / drive which is now being mounted / captured.
2623 * If NULL no media or drive is attached and the lun will be configured with
2624 * the default block driver with no media. This will also be the state if
2625 * mounting / capturing the specified media / drive fails.
2626 * @param fPassthrough Enables using passthrough mode of the host DVD drive if applicable.
2627 *
2628 * @note Locks this object for reading.
2629 */
2630HRESULT Console::doDriveChange (const char *pszDevice, unsigned uInstance, unsigned uLun, DriveState_T eState,
2631 DriveState_T *peState, const char *pszPath, bool fPassthrough)
2632{
2633 LogFlowThisFunc (("pszDevice=%p:{%s} uInstance=%u uLun=%u eState=%d "
2634 "peState=%p:{%d} pszPath=%p:{%s} fPassthrough=%d\n",
2635 pszDevice, pszDevice, uInstance, uLun, eState,
2636 peState, *peState, pszPath, pszPath, fPassthrough));
2637
2638 AutoCaller autoCaller (this);
2639 AssertComRCReturnRC (autoCaller.rc());
2640
2641 AutoReaderLock alock (this);
2642
2643 /* protect mpVM */
2644 AutoVMCaller autoVMCaller (this);
2645 CheckComRCReturnRC (autoVMCaller.rc());
2646
2647 /*
2648 * Call worker in EMT, that's faster and safer than doing everything
2649 * using VM3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
2650 * here to make requests from under the lock in order to serialize them.
2651 */
2652 PVMREQ pReq;
2653 int vrc = VMR3ReqCall (mpVM, &pReq, 0 /* no wait! */,
2654 (PFNRT) Console::changeDrive, 8,
2655 this, pszDevice, uInstance, uLun, eState, peState,
2656 pszPath, fPassthrough);
2657 /// @todo (r=dmik) bird, it would be nice to have a special VMR3Req method
2658 // for that purpose, that doesn't return useless VERR_TIMEOUT
2659 if (vrc == VERR_TIMEOUT)
2660 vrc = VINF_SUCCESS;
2661
2662 /* leave the lock before waiting for a result (EMT will call us back!) */
2663 alock.leave();
2664
2665 if (VBOX_SUCCESS (vrc))
2666 {
2667 vrc = VMR3ReqWait (pReq, RT_INDEFINITE_WAIT);
2668 AssertRC (vrc);
2669 if (VBOX_SUCCESS (vrc))
2670 vrc = pReq->iStatus;
2671 }
2672 VMR3ReqFree (pReq);
2673
2674 if (VBOX_SUCCESS (vrc))
2675 {
2676 LogFlowThisFunc (("Returns S_OK\n"));
2677 return S_OK;
2678 }
2679
2680 if (pszPath)
2681 return setError (E_FAIL,
2682 tr ("Could not mount the media/drive '%s' (%Vrc)"), pszPath, vrc);
2683
2684 return setError (E_FAIL,
2685 tr ("Could not unmount the currently mounted media/drive (%Vrc)"), vrc);
2686}
2687
2688
2689/**
2690 * Performs the Floppy/DVD change in EMT.
2691 *
2692 * @returns VBox status code.
2693 *
2694 * @param pThis Pointer to the Console object.
2695 * @param pszDevice The PDM device name.
2696 * @param uInstance The PDM device instance.
2697 * @param uLun The PDM LUN number of the drive.
2698 * @param eState The new state.
2699 * @param peState Pointer to the variable keeping the actual state of the drive.
2700 * This will be both read and updated to eState or other appropriate state.
2701 * @param pszPath The path to the media / drive which is now being mounted / captured.
2702 * If NULL no media or drive is attached and the lun will be configured with
2703 * the default block driver with no media. This will also be the state if
2704 * mounting / capturing the specified media / drive fails.
2705 * @param fPassthrough Enables using passthrough mode of the host DVD drive if applicable.
2706 *
2707 * @thread EMT
2708 * @note Locks the Console object for writing
2709 */
2710DECLCALLBACK(int) Console::changeDrive (Console *pThis, const char *pszDevice, unsigned uInstance, unsigned uLun,
2711 DriveState_T eState, DriveState_T *peState,
2712 const char *pszPath, bool fPassthrough)
2713{
2714 LogFlowFunc (("pThis=%p pszDevice=%p:{%s} uInstance=%u uLun=%u eState=%d "
2715 "peState=%p:{%d} pszPath=%p:{%s} fPassthrough=%d\n",
2716 pThis, pszDevice, pszDevice, uInstance, uLun, eState,
2717 peState, *peState, pszPath, pszPath, fPassthrough));
2718
2719 AssertReturn (pThis, VERR_INVALID_PARAMETER);
2720
2721 AssertMsg ( (!strcmp (pszDevice, "i82078") && uLun == 0 && uInstance == 0)
2722 || (!strcmp (pszDevice, "piix3ide") && uLun == 2 && uInstance == 0),
2723 ("pszDevice=%s uLun=%d uInstance=%d\n", pszDevice, uLun, uInstance));
2724
2725 AutoCaller autoCaller (pThis);
2726 AssertComRCReturn (autoCaller.rc(), VERR_ACCESS_DENIED);
2727
2728 /*
2729 * Locking the object before doing VMR3* calls is quite safe here,
2730 * since we're on EMT. Write lock is necessary because we're indirectly
2731 * modify the meDVDState/meFloppyState members (pointed to by peState).
2732 */
2733 AutoLock alock (pThis);
2734
2735 /* protect mpVM */
2736 AutoVMCaller autoVMCaller (pThis);
2737 CheckComRCReturnRC (autoVMCaller.rc());
2738
2739 PVM pVM = pThis->mpVM;
2740
2741 /*
2742 * Suspend the VM first.
2743 *
2744 * The VM must not be running since it might have pending I/O to
2745 * the drive which is being changed.
2746 */
2747 bool fResume;
2748 VMSTATE enmVMState = VMR3GetState (pVM);
2749 switch (enmVMState)
2750 {
2751 case VMSTATE_RESETTING:
2752 case VMSTATE_RUNNING:
2753 {
2754 LogFlowFunc (("Suspending the VM...\n"));
2755 /* disable the callback to prevent Console-level state change */
2756 pThis->mVMStateChangeCallbackDisabled = true;
2757 int rc = VMR3Suspend (pVM);
2758 pThis->mVMStateChangeCallbackDisabled = false;
2759 AssertRCReturn (rc, rc);
2760 fResume = true;
2761 break;
2762 }
2763
2764 case VMSTATE_SUSPENDED:
2765 case VMSTATE_CREATED:
2766 case VMSTATE_OFF:
2767 fResume = false;
2768 break;
2769
2770 default:
2771 AssertMsgFailedReturn (("enmVMState=%d\n", enmVMState), VERR_ACCESS_DENIED);
2772 }
2773
2774 int rc = VINF_SUCCESS;
2775 int rcRet = VINF_SUCCESS;
2776
2777 do
2778 {
2779 /*
2780 * Unmount existing media / detach host drive.
2781 */
2782 PPDMIMOUNT pIMount = NULL;
2783 switch (*peState)
2784 {
2785
2786 case DriveState_ImageMounted:
2787 {
2788 /*
2789 * Resolve the interface.
2790 */
2791 PPDMIBASE pBase;
2792 rc = PDMR3QueryLun (pVM, pszDevice, uInstance, uLun, &pBase);
2793 if (VBOX_FAILURE (rc))
2794 {
2795 if (rc == VERR_PDM_LUN_NOT_FOUND)
2796 rc = VINF_SUCCESS;
2797 AssertRC (rc);
2798 break;
2799 }
2800
2801 pIMount = (PPDMIMOUNT) pBase->pfnQueryInterface (pBase, PDMINTERFACE_MOUNT);
2802 AssertBreak (pIMount, rc = VERR_INVALID_POINTER);
2803
2804 /*
2805 * Unmount the media.
2806 */
2807 rc = pIMount->pfnUnmount (pIMount, false);
2808 if (rc == VERR_PDM_MEDIA_NOT_MOUNTED)
2809 rc = VINF_SUCCESS;
2810 break;
2811 }
2812
2813 case DriveState_HostDriveCaptured:
2814 {
2815 rc = PDMR3DeviceDetach (pVM, pszDevice, uInstance, uLun);
2816 if (rc == VINF_PDM_NO_DRIVER_ATTACHED_TO_LUN)
2817 rc = VINF_SUCCESS;
2818 AssertRC (rc);
2819 break;
2820 }
2821
2822 case DriveState_NotMounted:
2823 break;
2824
2825 default:
2826 AssertMsgFailed (("Invalid *peState: %d\n", peState));
2827 break;
2828 }
2829
2830 if (VBOX_FAILURE (rc))
2831 {
2832 rcRet = rc;
2833 break;
2834 }
2835
2836 /*
2837 * Nothing is currently mounted.
2838 */
2839 *peState = DriveState_NotMounted;
2840
2841
2842 /*
2843 * Process the HostDriveCaptured state first, as the fallback path
2844 * means mounting the normal block driver without media.
2845 */
2846 if (eState == DriveState_HostDriveCaptured)
2847 {
2848 /*
2849 * Detach existing driver chain (block).
2850 */
2851 int rc = PDMR3DeviceDetach (pVM, pszDevice, uInstance, uLun);
2852 if (VBOX_FAILURE (rc))
2853 {
2854 if (rc == VERR_PDM_LUN_NOT_FOUND)
2855 rc = VINF_SUCCESS;
2856 AssertReleaseRC (rc);
2857 break; /* we're toast */
2858 }
2859 pIMount = NULL;
2860
2861 /*
2862 * Construct a new driver configuration.
2863 */
2864 PCFGMNODE pInst = CFGMR3GetChildF (CFGMR3GetRoot (pVM), "Devices/%s/%d/", pszDevice, uInstance);
2865 AssertRelease (pInst);
2866 /* nuke anything which might have been left behind. */
2867 CFGMR3RemoveNode (CFGMR3GetChildF (pInst, "LUN#%d", uLun));
2868
2869 /* create a new block driver config */
2870 PCFGMNODE pLunL0;
2871 PCFGMNODE pCfg;
2872 if ( VBOX_SUCCESS (rc = CFGMR3InsertNodeF (pInst, &pLunL0, "LUN#%u", uLun))
2873 && VBOX_SUCCESS (rc = CFGMR3InsertString (pLunL0, "Driver", !strcmp (pszDevice, "i82078") ? "HostFloppy" : "HostDVD"))
2874 && VBOX_SUCCESS (rc = CFGMR3InsertNode (pLunL0, "Config", &pCfg))
2875 && VBOX_SUCCESS (rc = CFGMR3InsertString (pCfg, "Path", pszPath))
2876 && VBOX_SUCCESS (rc = !strcmp (pszDevice, "i82078") ? VINF_SUCCESS : CFGMR3InsertInteger(pCfg, "Passthrough", fPassthrough)))
2877 {
2878 /*
2879 * Attempt to attach the driver.
2880 */
2881 rc = PDMR3DeviceAttach (pVM, pszDevice, uInstance, uLun, NULL);
2882 AssertRC (rc);
2883 }
2884 if (VBOX_FAILURE (rc))
2885 rcRet = rc;
2886 }
2887
2888 /*
2889 * Process the ImageMounted, NotMounted and failed HostDriveCapture cases.
2890 */
2891 rc = VINF_SUCCESS;
2892 switch (eState)
2893 {
2894#define RC_CHECK() do { if (VBOX_FAILURE (rc)) { AssertReleaseRC (rc); break; } } while (0)
2895
2896 case DriveState_HostDriveCaptured:
2897 if (VBOX_SUCCESS (rcRet))
2898 break;
2899 /* fallback: umounted block driver. */
2900 pszPath = NULL;
2901 eState = DriveState_NotMounted;
2902 /* fallthru */
2903 case DriveState_ImageMounted:
2904 case DriveState_NotMounted:
2905 {
2906 /*
2907 * Resolve the drive interface / create the driver.
2908 */
2909 if (!pIMount)
2910 {
2911 PPDMIBASE pBase;
2912 rc = PDMR3QueryLun (pVM, pszDevice, uInstance, uLun, &pBase);
2913 if (rc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
2914 {
2915 /*
2916 * We have to create it, so we'll do the full config setup and everything.
2917 */
2918 PCFGMNODE pIdeInst = CFGMR3GetChildF (CFGMR3GetRoot (pVM), "Devices/%s/%d/", pszDevice, uInstance);
2919 AssertRelease (pIdeInst);
2920
2921 /* nuke anything which might have been left behind. */
2922 CFGMR3RemoveNode (CFGMR3GetChildF (pIdeInst, "LUN#%d", uLun));
2923
2924 /* create a new block driver config */
2925 PCFGMNODE pLunL0;
2926 rc = CFGMR3InsertNodeF (pIdeInst, &pLunL0, "LUN#%d", uLun); RC_CHECK();
2927 rc = CFGMR3InsertString (pLunL0, "Driver", "Block"); RC_CHECK();
2928 PCFGMNODE pCfg;
2929 rc = CFGMR3InsertNode (pLunL0, "Config", &pCfg); RC_CHECK();
2930 rc = CFGMR3InsertString (pCfg, "Type", !strcmp (pszDevice, "i82078") ? "Floppy 1.44" : "DVD");
2931 RC_CHECK();
2932 rc = CFGMR3InsertInteger (pCfg, "Mountable", 1); RC_CHECK();
2933
2934 /*
2935 * Attach the driver.
2936 */
2937 rc = PDMR3DeviceAttach (pVM, pszDevice, uInstance, uLun, &pBase);
2938 RC_CHECK();
2939 }
2940 else if (VBOX_FAILURE(rc))
2941 {
2942 AssertRC (rc);
2943 return rc;
2944 }
2945
2946 pIMount = (PPDMIMOUNT) pBase->pfnQueryInterface (pBase, PDMINTERFACE_MOUNT);
2947 if (!pIMount)
2948 {
2949 AssertFailed();
2950 return rc;
2951 }
2952 }
2953
2954 /*
2955 * If we've got an image, let's mount it.
2956 */
2957 if (pszPath && *pszPath)
2958 {
2959 rc = pIMount->pfnMount (pIMount, pszPath, strcmp (pszDevice, "i82078") ? "MediaISO" : "RawImage");
2960 if (VBOX_FAILURE (rc))
2961 eState = DriveState_NotMounted;
2962 }
2963 break;
2964 }
2965
2966 default:
2967 AssertMsgFailed (("Invalid eState: %d\n", eState));
2968 break;
2969
2970#undef RC_CHECK
2971 }
2972
2973 if (VBOX_FAILURE (rc) && VBOX_SUCCESS (rcRet))
2974 rcRet = rc;
2975
2976 *peState = eState;
2977 }
2978 while (0);
2979
2980 /*
2981 * Resume the VM if necessary.
2982 */
2983 if (fResume)
2984 {
2985 LogFlowFunc (("Resuming the VM...\n"));
2986 /* disable the callback to prevent Console-level state change */
2987 pThis->mVMStateChangeCallbackDisabled = true;
2988 rc = VMR3Resume (pVM);
2989 pThis->mVMStateChangeCallbackDisabled = false;
2990 AssertRC (rc);
2991 if (VBOX_FAILURE (rc))
2992 {
2993 /* too bad, we failed. try to sync the console state with the VMM state */
2994 vmstateChangeCallback (pVM, VMSTATE_SUSPENDED, enmVMState, pThis);
2995 }
2996 /// @todo (r=dmik) if we failed with drive mount, then the VMR3Resume
2997 // error (if any) will be hidden from the caller. For proper reporting
2998 // of such multiple errors to the caller we need to enhance the
2999 // IVurtualBoxError interface. For now, give the first error the higher
3000 // priority.
3001 if (VBOX_SUCCESS (rcRet))
3002 rcRet = rc;
3003 }
3004
3005 LogFlowFunc (("Returning %Vrc\n", rcRet));
3006 return rcRet;
3007}
3008
3009
3010/**
3011 * Called by IInternalSessionControl::OnNetworkAdapterChange().
3012 *
3013 * @note Locks this object for writing.
3014 */
3015HRESULT Console::onNetworkAdapterChange (INetworkAdapter *aNetworkAdapter)
3016{
3017 LogFlowThisFunc (("\n"));
3018
3019 AutoCaller autoCaller (this);
3020 AssertComRCReturnRC (autoCaller.rc());
3021
3022 AutoLock alock (this);
3023
3024 /* Don't do anything if the VM isn't running */
3025 if (!mpVM)
3026 return S_OK;
3027
3028 /* protect mpVM */
3029 AutoVMCaller autoVMCaller (this);
3030 CheckComRCReturnRC (autoVMCaller.rc());
3031
3032 /* Get the properties we need from the adapter */
3033 BOOL fCableConnected;
3034 HRESULT rc = aNetworkAdapter->COMGETTER(CableConnected) (&fCableConnected);
3035 AssertComRC(rc);
3036 if (SUCCEEDED(rc))
3037 {
3038 ULONG ulInstance;
3039 rc = aNetworkAdapter->COMGETTER(Slot) (&ulInstance);
3040 AssertComRC (rc);
3041 if (SUCCEEDED (rc))
3042 {
3043 /*
3044 * Find the pcnet instance, get the config interface and update
3045 * the link state.
3046 */
3047 PPDMIBASE pBase;
3048 int vrc = PDMR3QueryDeviceLun (mpVM, "pcnet", (unsigned) ulInstance,
3049 0, &pBase);
3050 ComAssertRC (vrc);
3051 if (VBOX_SUCCESS (vrc))
3052 {
3053 Assert(pBase);
3054 PPDMINETWORKCONFIG pINetCfg = (PPDMINETWORKCONFIG) pBase->
3055 pfnQueryInterface(pBase, PDMINTERFACE_NETWORK_CONFIG);
3056 if (pINetCfg)
3057 {
3058 Log (("Console::onNetworkAdapterChange: setting link state to %d\n",
3059 fCableConnected));
3060 vrc = pINetCfg->pfnSetLinkState (pINetCfg,
3061 fCableConnected ? PDMNETWORKLINKSTATE_UP
3062 : PDMNETWORKLINKSTATE_DOWN);
3063 ComAssertRC (vrc);
3064 }
3065 }
3066
3067 if (VBOX_FAILURE (vrc))
3068 rc = E_FAIL;
3069 }
3070 }
3071
3072 /* notify console callbacks on success */
3073 if (SUCCEEDED (rc))
3074 {
3075 CallbackList::iterator it = mCallbacks.begin();
3076 while (it != mCallbacks.end())
3077 (*it++)->OnNetworkAdapterChange (aNetworkAdapter);
3078 }
3079
3080 LogFlowThisFunc (("Leaving rc=%#x\n", rc));
3081 return rc;
3082}
3083
3084/**
3085 * Called by IInternalSessionControl::OnSerialPortChange().
3086 *
3087 * @note Locks this object for writing.
3088 */
3089HRESULT Console::onSerialPortChange (ISerialPort *aSerialPort)
3090{
3091 LogFlowThisFunc (("\n"));
3092
3093 AutoCaller autoCaller (this);
3094 AssertComRCReturnRC (autoCaller.rc());
3095
3096 AutoLock alock (this);
3097
3098 /* Don't do anything if the VM isn't running */
3099 if (!mpVM)
3100 return S_OK;
3101
3102 HRESULT rc = S_OK;
3103
3104 /* protect mpVM */
3105 AutoVMCaller autoVMCaller (this);
3106 CheckComRCReturnRC (autoVMCaller.rc());
3107
3108 /* nothing to do so far */
3109
3110 /* notify console callbacks on success */
3111 if (SUCCEEDED (rc))
3112 {
3113 CallbackList::iterator it = mCallbacks.begin();
3114 while (it != mCallbacks.end())
3115 (*it++)->OnSerialPortChange (aSerialPort);
3116 }
3117
3118 LogFlowThisFunc (("Leaving rc=%#x\n", rc));
3119 return rc;
3120}
3121
3122/**
3123 * Called by IInternalSessionControl::OnParallelPortChange().
3124 *
3125 * @note Locks this object for writing.
3126 */
3127HRESULT Console::onParallelPortChange (IParallelPort *aParallelPort)
3128{
3129 LogFlowThisFunc (("\n"));
3130
3131 AutoCaller autoCaller (this);
3132 AssertComRCReturnRC (autoCaller.rc());
3133
3134 AutoLock alock (this);
3135
3136 /* Don't do anything if the VM isn't running */
3137 if (!mpVM)
3138 return S_OK;
3139
3140 HRESULT rc = S_OK;
3141
3142 /* protect mpVM */
3143 AutoVMCaller autoVMCaller (this);
3144 CheckComRCReturnRC (autoVMCaller.rc());
3145
3146 /* nothing to do so far */
3147
3148 /* notify console callbacks on success */
3149 if (SUCCEEDED (rc))
3150 {
3151 CallbackList::iterator it = mCallbacks.begin();
3152 while (it != mCallbacks.end())
3153 (*it++)->OnParallelPortChange (aParallelPort);
3154 }
3155
3156 LogFlowThisFunc (("Leaving rc=%#x\n", rc));
3157 return rc;
3158}
3159
3160/**
3161 * Called by IInternalSessionControl::OnVRDPServerChange().
3162 *
3163 * @note Locks this object for writing.
3164 */
3165HRESULT Console::onVRDPServerChange()
3166{
3167 AutoCaller autoCaller (this);
3168 AssertComRCReturnRC (autoCaller.rc());
3169
3170 AutoLock alock (this);
3171
3172 HRESULT rc = S_OK;
3173
3174 if (mVRDPServer && mMachineState == MachineState_Running)
3175 {
3176 BOOL vrdpEnabled = FALSE;
3177
3178 rc = mVRDPServer->COMGETTER(Enabled) (&vrdpEnabled);
3179 ComAssertComRCRetRC (rc);
3180
3181 if (vrdpEnabled)
3182 {
3183 // If there was no VRDP server started the 'stop' will do nothing.
3184 // However if a server was started and this notification was called,
3185 // we have to restart the server.
3186 mConsoleVRDPServer->Stop ();
3187
3188 if (VBOX_FAILURE(mConsoleVRDPServer->Launch ()))
3189 {
3190 rc = E_FAIL;
3191 }
3192 else
3193 {
3194#ifdef VRDP_NO_COM
3195 mConsoleVRDPServer->EnableConnections ();
3196#else
3197 mConsoleVRDPServer->SetCallback ();
3198#endif /* VRDP_NO_COM */
3199 }
3200 }
3201 else
3202 {
3203 mConsoleVRDPServer->Stop ();
3204 }
3205 }
3206
3207 /* notify console callbacks on success */
3208 if (SUCCEEDED (rc))
3209 {
3210 CallbackList::iterator it = mCallbacks.begin();
3211 while (it != mCallbacks.end())
3212 (*it++)->OnVRDPServerChange();
3213 }
3214
3215 return rc;
3216}
3217
3218/**
3219 * Called by IInternalSessionControl::OnUSBControllerChange().
3220 *
3221 * @note Locks this object for writing.
3222 */
3223HRESULT Console::onUSBControllerChange()
3224{
3225 LogFlowThisFunc (("\n"));
3226
3227 AutoCaller autoCaller (this);
3228 AssertComRCReturnRC (autoCaller.rc());
3229
3230 AutoLock alock (this);
3231
3232 /* Ignore if no VM is running yet. */
3233 if (!mpVM)
3234 return S_OK;
3235
3236 HRESULT rc = S_OK;
3237
3238/// @todo (dmik)
3239// check for the Enabled state and disable virtual USB controller??
3240// Anyway, if we want to query the machine's USB Controller we need to cache
3241// it to to mUSBController in #init() (as it is done with mDVDDrive).
3242//
3243// bird: While the VM supports hot-plugging, I doubt any guest can handle it at this time... :-)
3244//
3245// /* protect mpVM */
3246// AutoVMCaller autoVMCaller (this);
3247// CheckComRCReturnRC (autoVMCaller.rc());
3248
3249 /* notify console callbacks on success */
3250 if (SUCCEEDED (rc))
3251 {
3252 CallbackList::iterator it = mCallbacks.begin();
3253 while (it != mCallbacks.end())
3254 (*it++)->OnUSBControllerChange();
3255 }
3256
3257 return rc;
3258}
3259
3260/**
3261 * Called by IInternalSessionControl::OnSharedFolderChange().
3262 *
3263 * @note Locks this object for writing.
3264 */
3265HRESULT Console::onSharedFolderChange (BOOL aGlobal)
3266{
3267 LogFlowThisFunc (("aGlobal=%RTbool\n", aGlobal));
3268
3269 AutoCaller autoCaller (this);
3270 AssertComRCReturnRC (autoCaller.rc());
3271
3272 AutoLock alock (this);
3273
3274 HRESULT rc = fetchSharedFolders (aGlobal);
3275
3276 /* notify console callbacks on success */
3277 if (SUCCEEDED (rc))
3278 {
3279 CallbackList::iterator it = mCallbacks.begin();
3280 while (it != mCallbacks.end())
3281 (*it++)->OnSharedFolderChange (aGlobal ? (Scope_T)Scope_GlobalScope
3282 : (Scope_T)Scope_MachineScope);
3283 }
3284
3285 return rc;
3286}
3287
3288/**
3289 * Called by IInternalSessionControl::OnUSBDeviceAttach() or locally by
3290 * processRemoteUSBDevices() after IInternalMachineControl::RunUSBDeviceFilters()
3291 * returns TRUE for a given remote USB device.
3292 *
3293 * @return S_OK if the device was attached to the VM.
3294 * @return failure if not attached.
3295 *
3296 * @param aDevice
3297 * The device in question.
3298 *
3299 * @note Locks this object for writing.
3300 */
3301HRESULT Console::onUSBDeviceAttach (IUSBDevice *aDevice, IVirtualBoxErrorInfo *aError)
3302{
3303 LogFlowThisFunc (("aDevice=%p aError=%p\n", aDevice, aError));
3304
3305 AutoCaller autoCaller (this);
3306 ComAssertComRCRetRC (autoCaller.rc());
3307
3308 AutoLock alock (this);
3309
3310 /* protect mpVM (we don't need error info, since it's a callback) */
3311 AutoVMCallerQuiet autoVMCaller (this);
3312 if (FAILED (autoVMCaller.rc()))
3313 {
3314 /* The VM may be no more operational when this message arrives
3315 * (e.g. it may be Saving or Stopping or just PoweredOff) --
3316 * autoVMCaller.rc() will return a failure in this case. */
3317 LogFlowThisFunc (("Attach request ignored (mMachineState=%d).\n",
3318 mMachineState));
3319 return autoVMCaller.rc();
3320 }
3321
3322 if (aError != NULL)
3323 {
3324 /* notify callbacks about the error */
3325 onUSBDeviceStateChange (aDevice, true /* aAttached */, aError);
3326 return S_OK;
3327 }
3328
3329#if 1
3330 /* Don't proceed unless we've found the usb controller. */
3331 PPDMIBASE pBase = NULL;
3332 int vrc = PDMR3QueryLun (mpVM, "usb-ohci", 0, 0, &pBase);
3333 if (VBOX_FAILURE (vrc))
3334 {
3335 LogFlowThisFunc (("Attach request ignored (no USB controller).\n"));
3336 return E_FAIL;
3337 }
3338
3339 PVUSBIRHCONFIG pRhConfig = (PVUSBIRHCONFIG) pBase->
3340 pfnQueryInterface (pBase, PDMINTERFACE_VUSB_RH_CONFIG);
3341 ComAssertRet (pRhConfig, E_FAIL);
3342
3343 HRESULT rc = attachUSBDevice (aDevice, pRhConfig);
3344#else /* PDMUsb */
3345 /* Don't proceed unless there's a USB hub. */
3346 if (!PDMR3USBHasHub (m_VM))
3347 {
3348 LogFlowThisFunc (("Attach request ignored (no USB controller).\n"));
3349 return E_FAIL;
3350 }
3351
3352 HRESULT rc = attachUSBDevice (aDevice);
3353#endif /* PDMUsb */
3354
3355 if (FAILED (rc))
3356 {
3357 /* take the current error info */
3358 com::ErrorInfoKeeper eik;
3359 /* the error must be a VirtualBoxErrorInfo instance */
3360 ComPtr <IVirtualBoxErrorInfo> error = eik.takeError();
3361 Assert (!error.isNull());
3362 if (!error.isNull())
3363 {
3364 /* notify callbacks about the error */
3365 onUSBDeviceStateChange (aDevice, true /* aAttached */, error);
3366 }
3367 }
3368
3369 return rc;
3370}
3371
3372/**
3373 * Called by IInternalSessionControl::OnUSBDeviceDetach() and locally by
3374 * processRemoteUSBDevices().
3375 *
3376 * @note Locks this object for writing.
3377 */
3378HRESULT Console::onUSBDeviceDetach (INPTR GUIDPARAM aId,
3379 IVirtualBoxErrorInfo *aError)
3380{
3381 Guid Uuid (aId);
3382 LogFlowThisFunc (("aId={%Vuuid} aError=%p\n", Uuid.raw(), aError));
3383
3384 AutoCaller autoCaller (this);
3385 AssertComRCReturnRC (autoCaller.rc());
3386
3387 AutoLock alock (this);
3388
3389 /* Find the device. */
3390 ComObjPtr <OUSBDevice> device;
3391 USBDeviceList::iterator it = mUSBDevices.begin();
3392 while (it != mUSBDevices.end())
3393 {
3394 LogFlowThisFunc (("it={%Vuuid}\n", (*it)->id().raw()));
3395 if ((*it)->id() == Uuid)
3396 {
3397 device = *it;
3398 break;
3399 }
3400 ++ it;
3401 }
3402
3403
3404 if (device.isNull())
3405 {
3406 LogFlowThisFunc (("USB device not found.\n"));
3407
3408 /* The VM may be no more operational when this message arrives
3409 * (e.g. it may be Saving or Stopping or just PoweredOff). Use
3410 * AutoVMCaller to detect it -- AutoVMCaller::rc() will return a
3411 * failure in this case. */
3412
3413 AutoVMCallerQuiet autoVMCaller (this);
3414 if (FAILED (autoVMCaller.rc()))
3415 {
3416 LogFlowThisFunc (("Detach request ignored (mMachineState=%d).\n",
3417 mMachineState));
3418 return autoVMCaller.rc();
3419 }
3420
3421 /* the device must be in the list otherwise */
3422 AssertFailedReturn (E_FAIL);
3423 }
3424
3425 if (aError != NULL)
3426 {
3427 /* notify callback about an error */
3428 onUSBDeviceStateChange (device, false /* aAttached */, aError);
3429 return S_OK;
3430 }
3431
3432 HRESULT rc = detachUSBDevice (it);
3433
3434 if (FAILED (rc))
3435 {
3436 /* take the current error info */
3437 com::ErrorInfoKeeper eik;
3438 /* the error must be a VirtualBoxErrorInfo instance */
3439 ComPtr <IVirtualBoxErrorInfo> error = eik.takeError();
3440 Assert (!error.isNull());
3441 if (!error.isNull())
3442 {
3443 /* notify callbacks about the error */
3444 onUSBDeviceStateChange (device, false /* aAttached */, error);
3445 }
3446 }
3447
3448 return rc;
3449}
3450
3451/**
3452 * Gets called by Session::UpdateMachineState()
3453 * (IInternalSessionControl::updateMachineState()).
3454 *
3455 * Must be called only in certain cases (see the implementation).
3456 *
3457 * @note Locks this object for writing.
3458 */
3459HRESULT Console::updateMachineState (MachineState_T aMachineState)
3460{
3461 AutoCaller autoCaller (this);
3462 AssertComRCReturnRC (autoCaller.rc());
3463
3464 AutoLock alock (this);
3465
3466 AssertReturn (mMachineState == MachineState_Saving ||
3467 mMachineState == MachineState_Discarding,
3468 E_FAIL);
3469
3470 return setMachineStateLocally (aMachineState);
3471}
3472
3473/**
3474 * @note Locks this object for writing.
3475 */
3476void Console::onMousePointerShapeChange(bool fVisible, bool fAlpha,
3477 uint32_t xHot, uint32_t yHot,
3478 uint32_t width, uint32_t height,
3479 void *pShape)
3480{
3481#if 0
3482 LogFlowThisFuncEnter();
3483 LogFlowThisFunc (("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, "
3484 "height=%d, shape=%p\n",
3485 fVisible, fAlpha, xHot, yHot, width, height, pShape));
3486#endif
3487
3488 AutoCaller autoCaller (this);
3489 AssertComRCReturnVoid (autoCaller.rc());
3490
3491 /* We need a write lock because we alter the cached callback data */
3492 AutoLock alock (this);
3493
3494 /* Save the callback arguments */
3495 mCallbackData.mpsc.visible = fVisible;
3496 mCallbackData.mpsc.alpha = fAlpha;
3497 mCallbackData.mpsc.xHot = xHot;
3498 mCallbackData.mpsc.yHot = yHot;
3499 mCallbackData.mpsc.width = width;
3500 mCallbackData.mpsc.height = height;
3501
3502 /* start with not valid */
3503 bool wasValid = mCallbackData.mpsc.valid;
3504 mCallbackData.mpsc.valid = false;
3505
3506 if (pShape != NULL)
3507 {
3508 size_t cb = (width + 7) / 8 * height; /* size of the AND mask */
3509 cb += ((cb + 3) & ~3) + width * 4 * height; /* + gap + size of the XOR mask */
3510 /* try to reuse the old shape buffer if the size is the same */
3511 if (!wasValid)
3512 mCallbackData.mpsc.shape = NULL;
3513 else
3514 if (mCallbackData.mpsc.shape != NULL && mCallbackData.mpsc.shapeSize != cb)
3515 {
3516 RTMemFree (mCallbackData.mpsc.shape);
3517 mCallbackData.mpsc.shape = NULL;
3518 }
3519 if (mCallbackData.mpsc.shape == NULL)
3520 {
3521 mCallbackData.mpsc.shape = (BYTE *) RTMemAllocZ (cb);
3522 AssertReturnVoid (mCallbackData.mpsc.shape);
3523 }
3524 mCallbackData.mpsc.shapeSize = cb;
3525 memcpy (mCallbackData.mpsc.shape, pShape, cb);
3526 }
3527 else
3528 {
3529 if (wasValid && mCallbackData.mpsc.shape != NULL)
3530 RTMemFree (mCallbackData.mpsc.shape);
3531 mCallbackData.mpsc.shape = NULL;
3532 mCallbackData.mpsc.shapeSize = 0;
3533 }
3534
3535 mCallbackData.mpsc.valid = true;
3536
3537 CallbackList::iterator it = mCallbacks.begin();
3538 while (it != mCallbacks.end())
3539 (*it++)->OnMousePointerShapeChange (fVisible, fAlpha, xHot, yHot,
3540 width, height, (BYTE *) pShape);
3541
3542#if 0
3543 LogFlowThisFuncLeave();
3544#endif
3545}
3546
3547/**
3548 * @note Locks this object for writing.
3549 */
3550void Console::onMouseCapabilityChange (BOOL supportsAbsolute, BOOL needsHostCursor)
3551{
3552 LogFlowThisFunc (("supportsAbsolute=%d needsHostCursor=%d\n",
3553 supportsAbsolute, needsHostCursor));
3554
3555 AutoCaller autoCaller (this);
3556 AssertComRCReturnVoid (autoCaller.rc());
3557
3558 /* We need a write lock because we alter the cached callback data */
3559 AutoLock alock (this);
3560
3561 /* save the callback arguments */
3562 mCallbackData.mcc.supportsAbsolute = supportsAbsolute;
3563 mCallbackData.mcc.needsHostCursor = needsHostCursor;
3564 mCallbackData.mcc.valid = true;
3565
3566 CallbackList::iterator it = mCallbacks.begin();
3567 while (it != mCallbacks.end())
3568 {
3569 Log2(("Console::onMouseCapabilityChange: calling %p\n", (void*)*it));
3570 (*it++)->OnMouseCapabilityChange (supportsAbsolute, needsHostCursor);
3571 }
3572}
3573
3574/**
3575 * @note Locks this object for reading.
3576 */
3577void Console::onStateChange (MachineState_T machineState)
3578{
3579 AutoCaller autoCaller (this);
3580 AssertComRCReturnVoid (autoCaller.rc());
3581
3582 AutoReaderLock alock (this);
3583
3584 CallbackList::iterator it = mCallbacks.begin();
3585 while (it != mCallbacks.end())
3586 (*it++)->OnStateChange (machineState);
3587}
3588
3589/**
3590 * @note Locks this object for reading.
3591 */
3592void Console::onAdditionsStateChange()
3593{
3594 AutoCaller autoCaller (this);
3595 AssertComRCReturnVoid (autoCaller.rc());
3596
3597 AutoReaderLock alock (this);
3598
3599 CallbackList::iterator it = mCallbacks.begin();
3600 while (it != mCallbacks.end())
3601 (*it++)->OnAdditionsStateChange();
3602}
3603
3604/**
3605 * @note Locks this object for reading.
3606 */
3607void Console::onAdditionsOutdated()
3608{
3609 AutoCaller autoCaller (this);
3610 AssertComRCReturnVoid (autoCaller.rc());
3611
3612 AutoReaderLock alock (this);
3613
3614 /** @todo Use the On-Screen Display feature to report the fact.
3615 * The user should be told to install additions that are
3616 * provided with the current VBox build:
3617 * VBOX_VERSION_MAJOR.VBOX_VERSION_MINOR.VBOX_VERSION_BUILD
3618 */
3619}
3620
3621/**
3622 * @note Locks this object for writing.
3623 */
3624void Console::onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
3625{
3626 AutoCaller autoCaller (this);
3627 AssertComRCReturnVoid (autoCaller.rc());
3628
3629 /* We need a write lock because we alter the cached callback data */
3630 AutoLock alock (this);
3631
3632 /* save the callback arguments */
3633 mCallbackData.klc.numLock = fNumLock;
3634 mCallbackData.klc.capsLock = fCapsLock;
3635 mCallbackData.klc.scrollLock = fScrollLock;
3636 mCallbackData.klc.valid = true;
3637
3638 CallbackList::iterator it = mCallbacks.begin();
3639 while (it != mCallbacks.end())
3640 (*it++)->OnKeyboardLedsChange(fNumLock, fCapsLock, fScrollLock);
3641}
3642
3643/**
3644 * @note Locks this object for reading.
3645 */
3646void Console::onUSBDeviceStateChange (IUSBDevice *aDevice, bool aAttached,
3647 IVirtualBoxErrorInfo *aError)
3648{
3649 AutoCaller autoCaller (this);
3650 AssertComRCReturnVoid (autoCaller.rc());
3651
3652 AutoReaderLock alock (this);
3653
3654 CallbackList::iterator it = mCallbacks.begin();
3655 while (it != mCallbacks.end())
3656 (*it++)->OnUSBDeviceStateChange (aDevice, aAttached, aError);
3657}
3658
3659/**
3660 * @note Locks this object for reading.
3661 */
3662void Console::onRuntimeError (BOOL aFatal, INPTR BSTR aErrorID, INPTR BSTR aMessage)
3663{
3664 AutoCaller autoCaller (this);
3665 AssertComRCReturnVoid (autoCaller.rc());
3666
3667 AutoReaderLock alock (this);
3668
3669 CallbackList::iterator it = mCallbacks.begin();
3670 while (it != mCallbacks.end())
3671 (*it++)->OnRuntimeError (aFatal, aErrorID, aMessage);
3672}
3673
3674/**
3675 * @note Locks this object for reading.
3676 */
3677HRESULT Console::onShowWindow (BOOL aCheck, BOOL *aCanShow, ULONG64 *aWinId)
3678{
3679 AssertReturn (aCanShow, E_POINTER);
3680 AssertReturn (aWinId, E_POINTER);
3681
3682 *aCanShow = FALSE;
3683 *aWinId = 0;
3684
3685 AutoCaller autoCaller (this);
3686 AssertComRCReturnRC (autoCaller.rc());
3687
3688 AutoReaderLock alock (this);
3689
3690 HRESULT rc = S_OK;
3691 CallbackList::iterator it = mCallbacks.begin();
3692
3693 if (aCheck)
3694 {
3695 while (it != mCallbacks.end())
3696 {
3697 BOOL canShow = FALSE;
3698 rc = (*it++)->OnCanShowWindow (&canShow);
3699 AssertComRC (rc);
3700 if (FAILED (rc) || !canShow)
3701 return rc;
3702 }
3703 *aCanShow = TRUE;
3704 }
3705 else
3706 {
3707 while (it != mCallbacks.end())
3708 {
3709 ULONG64 winId = 0;
3710 rc = (*it++)->OnShowWindow (&winId);
3711 AssertComRC (rc);
3712 if (FAILED (rc))
3713 return rc;
3714 /* only one callback may return non-null winId */
3715 Assert (*aWinId == 0 || winId == 0);
3716 if (*aWinId == 0)
3717 *aWinId = winId;
3718 }
3719 }
3720
3721 return S_OK;
3722}
3723
3724// private mehtods
3725////////////////////////////////////////////////////////////////////////////////
3726
3727/**
3728 * Increases the usage counter of the mpVM pointer. Guarantees that
3729 * VMR3Destroy() will not be called on it at least until releaseVMCaller()
3730 * is called.
3731 *
3732 * If this method returns a failure, the caller is not allowed to use mpVM
3733 * and may return the failed result code to the upper level. This method sets
3734 * the extended error info on failure if \a aQuiet is false.
3735 *
3736 * Setting \a aQuiet to true is useful for methods that don't want to return
3737 * the failed result code to the caller when this method fails (e.g. need to
3738 * silently check for the mpVM avaliability).
3739 *
3740 * When mpVM is NULL but \a aAllowNullVM is true, a corresponding error will be
3741 * returned instead of asserting. Having it false is intended as a sanity check
3742 * for methods that have checked mMachineState and expect mpVM *NOT* to be NULL.
3743 *
3744 * @param aQuiet true to suppress setting error info
3745 * @param aAllowNullVM true to accept mpVM being NULL and return a failure
3746 * (otherwise this method will assert if mpVM is NULL)
3747 *
3748 * @note Locks this object for writing.
3749 */
3750HRESULT Console::addVMCaller (bool aQuiet /* = false */,
3751 bool aAllowNullVM /* = false */)
3752{
3753 AutoCaller autoCaller (this);
3754 AssertComRCReturnRC (autoCaller.rc());
3755
3756 AutoLock alock (this);
3757
3758 if (mVMDestroying)
3759 {
3760 /* powerDown() is waiting for all callers to finish */
3761 return aQuiet ? E_ACCESSDENIED : setError (E_ACCESSDENIED,
3762 tr ("Virtual machine is being powered down"));
3763 }
3764
3765 if (mpVM == NULL)
3766 {
3767 Assert (aAllowNullVM == true);
3768
3769 /* The machine is not powered up */
3770 return aQuiet ? E_ACCESSDENIED : setError (E_ACCESSDENIED,
3771 tr ("Virtual machine is not powered up"));
3772 }
3773
3774 ++ mVMCallers;
3775
3776 return S_OK;
3777}
3778
3779/**
3780 * Decreases the usage counter of the mpVM pointer. Must always complete
3781 * the addVMCaller() call after the mpVM pointer is no more necessary.
3782 *
3783 * @note Locks this object for writing.
3784 */
3785void Console::releaseVMCaller()
3786{
3787 AutoCaller autoCaller (this);
3788 AssertComRCReturnVoid (autoCaller.rc());
3789
3790 AutoLock alock (this);
3791
3792 AssertReturnVoid (mpVM != NULL);
3793
3794 Assert (mVMCallers > 0);
3795 -- mVMCallers;
3796
3797 if (mVMCallers == 0 && mVMDestroying)
3798 {
3799 /* inform powerDown() there are no more callers */
3800 RTSemEventSignal (mVMZeroCallersSem);
3801 }
3802}
3803
3804/**
3805 * Internal power off worker routine.
3806 *
3807 * This method may be called only at certain places with the folliwing meaning
3808 * as shown below:
3809 *
3810 * - if the machine state is either Running or Paused, a normal
3811 * Console-initiated powerdown takes place (e.g. PowerDown());
3812 * - if the machine state is Saving, saveStateThread() has successfully
3813 * done its job;
3814 * - if the machine state is Starting or Restoring, powerUpThread() has
3815 * failed to start/load the VM;
3816 * - if the machine state is Stopping, the VM has powered itself off
3817 * (i.e. not as a result of the powerDown() call).
3818 *
3819 * Calling it in situations other than the above will cause unexpected
3820 * behavior.
3821 *
3822 * Note that this method should be the only one that destroys mpVM and sets
3823 * it to NULL.
3824 *
3825 * @note Locks this object for writing.
3826 *
3827 * @note Never call this method from a thread that called addVMCaller() or
3828 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
3829 * release(). Otherwise it will deadlock.
3830 */
3831HRESULT Console::powerDown()
3832{
3833 LogFlowThisFuncEnter();
3834
3835 AutoCaller autoCaller (this);
3836 AssertComRCReturnRC (autoCaller.rc());
3837
3838 AutoLock alock (this);
3839
3840 /* sanity */
3841 AssertReturn (mVMDestroying == false, E_FAIL);
3842
3843 LogRel (("Console::powerDown(): a request to power off the VM has been issued "
3844 "(mMachineState=%d, InUninit=%d)\n",
3845 mMachineState, autoCaller.state() == InUninit));
3846
3847 /* First, wait for all mpVM callers to finish their work if necessary */
3848 if (mVMCallers > 0)
3849 {
3850 /* go to the destroying state to prevent from adding new callers */
3851 mVMDestroying = true;
3852
3853 /* lazy creation */
3854 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
3855 RTSemEventCreate (&mVMZeroCallersSem);
3856
3857 LogFlowThisFunc (("Waiting for mpVM callers (%d) to drop to zero...\n",
3858 mVMCallers));
3859
3860 alock.leave();
3861
3862 RTSemEventWait (mVMZeroCallersSem, RT_INDEFINITE_WAIT);
3863
3864 alock.enter();
3865 }
3866
3867 AssertReturn (mpVM, E_FAIL);
3868
3869 AssertMsg (mMachineState == MachineState_Running ||
3870 mMachineState == MachineState_Paused ||
3871 mMachineState == MachineState_Saving ||
3872 mMachineState == MachineState_Starting ||
3873 mMachineState == MachineState_Restoring ||
3874 mMachineState == MachineState_Stopping,
3875 ("Invalid machine state: %d\n", mMachineState));
3876
3877 HRESULT rc = S_OK;
3878 int vrc = VINF_SUCCESS;
3879
3880 /*
3881 * Power off the VM if not already done that. In case of Stopping, the VM
3882 * has powered itself off and notified Console in vmstateChangeCallback().
3883 * In case of Starting or Restoring, powerUpThread() is calling us on
3884 * failure, so the VM is already off at that point.
3885 */
3886 if (mMachineState != MachineState_Stopping &&
3887 mMachineState != MachineState_Starting &&
3888 mMachineState != MachineState_Restoring)
3889 {
3890 /*
3891 * don't go from Saving to Stopping, vmstateChangeCallback needs it
3892 * to set the state to Saved on VMSTATE_TERMINATED.
3893 */
3894 if (mMachineState != MachineState_Saving)
3895 setMachineState (MachineState_Stopping);
3896
3897 LogFlowThisFunc (("Powering off the VM...\n"));
3898
3899 /* Leave the lock since EMT will call us back on VMR3PowerOff() */
3900 alock.leave();
3901
3902 vrc = VMR3PowerOff (mpVM);
3903 /*
3904 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
3905 * VM-(guest-)initiated power off happened in parallel a ms before
3906 * this call. So far, we let this error pop up on the user's side.
3907 */
3908
3909 alock.enter();
3910 }
3911
3912 LogFlowThisFunc (("Ready for VM destruction\n"));
3913
3914 /*
3915 * If we are called from Console::uninit(), then try to destroy the VM
3916 * even on failure (this will most likely fail too, but what to do?..)
3917 */
3918 if (VBOX_SUCCESS (vrc) || autoCaller.state() == InUninit)
3919 {
3920 /*
3921 * Stop the VRDP server and release all USB device.
3922 * (When called from uninit mConsoleVRDPServer is already destroyed.)
3923 */
3924 if (mConsoleVRDPServer)
3925 {
3926 LogFlowThisFunc (("Stopping VRDP server...\n"));
3927
3928 /* Leave the lock since EMT will call us back as addVMCaller in updateDisplayData(). */
3929 alock.leave();
3930
3931 mConsoleVRDPServer->Stop();
3932
3933 alock.enter();
3934 }
3935
3936 /* If the machine has an USB comtroller, release all USB devices
3937 * (symmetric to the code in captureUSBDevices()) */
3938 bool fHasUSBController = false;
3939 {
3940 PPDMIBASE pBase;
3941 int vrc = PDMR3QueryLun (mpVM, "usb-ohci", 0, 0, &pBase);
3942 if (VBOX_SUCCESS (vrc))
3943 {
3944 fHasUSBController = true;
3945 detachAllUSBDevices (false /* aDone */);
3946 }
3947 }
3948
3949 /*
3950 * Now we've got to destroy the VM as well. (mpVM is not valid
3951 * beyond this point). We leave the lock before calling VMR3Destroy()
3952 * because it will result into calling destructors of drivers
3953 * associated with Console children which may in turn try to lock
3954 * Console (e.g. by instantiating SafeVMPtr to access mpVM). It's safe
3955 * here because mVMDestroying is set which should prevent any activity.
3956 */
3957
3958 /*
3959 * Set mpVM to NULL early just in case if some old code is not using
3960 * addVMCaller()/releaseVMCaller().
3961 */
3962 PVM pVM = mpVM;
3963 mpVM = NULL;
3964
3965 LogFlowThisFunc (("Destroying the VM...\n"));
3966
3967 alock.leave();
3968
3969 vrc = VMR3Destroy (pVM);
3970
3971 /* take the lock again */
3972 alock.enter();
3973
3974 if (VBOX_SUCCESS (vrc))
3975 {
3976 LogFlowThisFunc (("Machine has been destroyed (mMachineState=%d)\n",
3977 mMachineState));
3978 /*
3979 * Note: the Console-level machine state change happens on the
3980 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
3981 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
3982 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
3983 * occured yet. This is okay, because mMachineState is already
3984 * Stopping in this case, so any other attempt to call PowerDown()
3985 * will be rejected.
3986 */
3987 }
3988 else
3989 {
3990 /* bad bad bad, but what to do? */
3991 mpVM = pVM;
3992 rc = setError (E_FAIL,
3993 tr ("Could not destroy the machine. (Error: %Vrc)"), vrc);
3994 }
3995
3996 /*
3997 * Complete the detaching of the USB devices.
3998 */
3999 if (fHasUSBController)
4000 detachAllUSBDevices (true /* aDone */);
4001 }
4002 else
4003 {
4004 rc = setError (E_FAIL,
4005 tr ("Could not power off the machine. (Error: %Vrc)"), vrc);
4006 }
4007
4008 /*
4009 * Finished with destruction. Note that if something impossible happened
4010 * and we've failed to destroy the VM, mVMDestroying will remain false and
4011 * mMachineState will be something like Stopping, so most Console methods
4012 * will return an error to the caller.
4013 */
4014 if (mpVM == NULL)
4015 mVMDestroying = false;
4016
4017 if (SUCCEEDED (rc))
4018 {
4019 /* uninit dynamically allocated members of mCallbackData */
4020 if (mCallbackData.mpsc.valid)
4021 {
4022 if (mCallbackData.mpsc.shape != NULL)
4023 RTMemFree (mCallbackData.mpsc.shape);
4024 }
4025 memset (&mCallbackData, 0, sizeof (mCallbackData));
4026 }
4027
4028 LogFlowThisFuncLeave();
4029 return rc;
4030}
4031
4032/**
4033 * @note Locks this object for writing.
4034 */
4035HRESULT Console::setMachineState (MachineState_T aMachineState,
4036 bool aUpdateServer /* = true */)
4037{
4038 AutoCaller autoCaller (this);
4039 AssertComRCReturnRC (autoCaller.rc());
4040
4041 AutoLock alock (this);
4042
4043 HRESULT rc = S_OK;
4044
4045 if (mMachineState != aMachineState)
4046 {
4047 LogFlowThisFunc (("machineState=%d\n", aMachineState));
4048 mMachineState = aMachineState;
4049
4050 /// @todo (dmik)
4051 // possibly, we need to redo onStateChange() using the dedicated
4052 // Event thread, like it is done in VirtualBox. This will make it
4053 // much safer (no deadlocks possible if someone tries to use the
4054 // console from the callback), however, listeners will lose the
4055 // ability to synchronously react to state changes (is it really
4056 // necessary??)
4057 LogFlowThisFunc (("Doing onStateChange()...\n"));
4058 onStateChange (aMachineState);
4059 LogFlowThisFunc (("Done onStateChange()\n"));
4060
4061 if (aUpdateServer)
4062 {
4063 /*
4064 * Server notification MUST be done from under the lock; otherwise
4065 * the machine state here and on the server might go out of sync, that
4066 * can lead to various unexpected results (like the machine state being
4067 * >= MachineState_Running on the server, while the session state is
4068 * already SessionState_SessionClosed at the same time there).
4069 *
4070 * Cross-lock conditions should be carefully watched out: calling
4071 * UpdateState we will require Machine and SessionMachine locks
4072 * (remember that here we're holding the Console lock here, and
4073 * also all locks that have been entered by the thread before calling
4074 * this method).
4075 */
4076 LogFlowThisFunc (("Doing mControl->UpdateState()...\n"));
4077 rc = mControl->UpdateState (aMachineState);
4078 LogFlowThisFunc (("mControl->UpdateState()=%08X\n", rc));
4079 }
4080 }
4081
4082 return rc;
4083}
4084
4085/**
4086 * Searches for a shared folder with the given logical name
4087 * in the collection of shared folders.
4088 *
4089 * @param aName logical name of the shared folder
4090 * @param aSharedFolder where to return the found object
4091 * @param aSetError whether to set the error info if the folder is
4092 * not found
4093 * @return
4094 * S_OK when found or E_INVALIDARG when not found
4095 *
4096 * @note The caller must lock this object for writing.
4097 */
4098HRESULT Console::findSharedFolder (const BSTR aName,
4099 ComObjPtr <SharedFolder> &aSharedFolder,
4100 bool aSetError /* = false */)
4101{
4102 /* sanity check */
4103 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
4104
4105 SharedFolderMap::const_iterator it = mSharedFolders.find (aName);
4106 if (it != mSharedFolders.end())
4107 {
4108 aSharedFolder = it->second;
4109 return S_OK;
4110 }
4111
4112 if (aSetError)
4113 setError (E_INVALIDARG,
4114 tr ("Could not find a shared folder named '%ls'."), aName);
4115
4116 return E_INVALIDARG;
4117}
4118
4119/**
4120 * Fetches the list of global or machine shared folders from the server.
4121 *
4122 * @param aGlobal true to fetch global folders.
4123 *
4124 * @note The caller must lock this object for writing.
4125 */
4126HRESULT Console::fetchSharedFolders (BOOL aGlobal)
4127{
4128 /* sanity check */
4129 AssertReturn (AutoCaller (this).state() == InInit ||
4130 isLockedOnCurrentThread(), E_FAIL);
4131
4132 /* protect mpVM (if not NULL) */
4133 AutoVMCallerQuietWeak autoVMCaller (this);
4134
4135 HRESULT rc = S_OK;
4136
4137 bool online = mpVM && autoVMCaller.isOk() && mVMMDev->isShFlActive();
4138
4139 if (aGlobal)
4140 {
4141 /// @todo grab & process global folders when they are done
4142 }
4143 else
4144 {
4145 SharedFolderDataMap oldFolders;
4146 if (online)
4147 oldFolders = mMachineSharedFolders;
4148
4149 mMachineSharedFolders.clear();
4150
4151 ComPtr <ISharedFolderCollection> coll;
4152 rc = mMachine->COMGETTER(SharedFolders) (coll.asOutParam());
4153 AssertComRCReturnRC (rc);
4154
4155 ComPtr <ISharedFolderEnumerator> en;
4156 rc = coll->Enumerate (en.asOutParam());
4157 AssertComRCReturnRC (rc);
4158
4159 BOOL hasMore = FALSE;
4160 while (SUCCEEDED (rc = en->HasMore (&hasMore)) && hasMore)
4161 {
4162 ComPtr <ISharedFolder> folder;
4163 rc = en->GetNext (folder.asOutParam());
4164 CheckComRCBreakRC (rc);
4165
4166 Bstr name;
4167 Bstr hostPath;
4168
4169 rc = folder->COMGETTER(Name) (name.asOutParam());
4170 CheckComRCBreakRC (rc);
4171 rc = folder->COMGETTER(HostPath) (hostPath.asOutParam());
4172 CheckComRCBreakRC (rc);
4173
4174 mMachineSharedFolders.insert (std::make_pair (name, hostPath));
4175
4176 /* send changes to HGCM if the VM is running */
4177 /// @todo report errors as runtime warnings through VMSetError
4178 if (online)
4179 {
4180 SharedFolderDataMap::iterator it = oldFolders.find (name);
4181 if (it == oldFolders.end() || it->second != hostPath)
4182 {
4183 /* a new machine folder is added or
4184 * the existing machine folder is changed */
4185 if (mSharedFolders.find (name) != mSharedFolders.end())
4186 ; /* the console folder exists, nothing to do */
4187 else
4188 {
4189 /* remove the old machhine folder (when changed)
4190 * or the global folder if any (when new) */
4191 if (it != oldFolders.end() ||
4192 mGlobalSharedFolders.find (name) !=
4193 mGlobalSharedFolders.end())
4194 rc = removeSharedFolder (name);
4195 /* create the new machine folder */
4196 rc = createSharedFolder (name, hostPath);
4197 }
4198 }
4199 /* forget the processed (or identical) folder */
4200 if (it != oldFolders.end())
4201 oldFolders.erase (it);
4202
4203 rc = S_OK;
4204 }
4205 }
4206
4207 AssertComRCReturnRC (rc);
4208
4209 /* process outdated (removed) folders */
4210 /// @todo report errors as runtime warnings through VMSetError
4211 if (online)
4212 {
4213 for (SharedFolderDataMap::const_iterator it = oldFolders.begin();
4214 it != oldFolders.end(); ++ it)
4215 {
4216 if (mSharedFolders.find (it->first) != mSharedFolders.end())
4217 ; /* the console folder exists, nothing to do */
4218 else
4219 {
4220 /* remove the outdated machine folder */
4221 rc = removeSharedFolder (it->first);
4222 /* create the global folder if there is any */
4223 SharedFolderDataMap::const_iterator git =
4224 mGlobalSharedFolders.find (it->first);
4225 if (git != mGlobalSharedFolders.end())
4226 rc = createSharedFolder (git->first, git->second);
4227 }
4228 }
4229
4230 rc = S_OK;
4231 }
4232 }
4233
4234 return rc;
4235}
4236
4237/**
4238 * Searches for a shared folder with the given name in the list of machine
4239 * shared folders and then in the list of the global shared folders.
4240 *
4241 * @param aName Name of the folder to search for.
4242 * @param aIt Where to store the pointer to the found folder.
4243 * @return @c true if the folder was found and @c false otherwise.
4244 *
4245 * @note The caller must lock this object for reading.
4246 */
4247bool Console::findOtherSharedFolder (INPTR BSTR aName,
4248 SharedFolderDataMap::const_iterator &aIt)
4249{
4250 /* sanity check */
4251 AssertReturn (isLockedOnCurrentThread(), false);
4252
4253 /* first, search machine folders */
4254 aIt = mMachineSharedFolders.find (aName);
4255 if (aIt != mMachineSharedFolders.end())
4256 return true;
4257
4258 /* second, search machine folders */
4259 aIt = mGlobalSharedFolders.find (aName);
4260 if (aIt != mGlobalSharedFolders.end())
4261 return true;
4262
4263 return false;
4264}
4265
4266/**
4267 * Calls the HGCM service to add a shared folder definition.
4268 *
4269 * @param aName Shared folder name.
4270 * @param aHostPath Shared folder path.
4271 *
4272 * @note Must be called from under AutoVMCaller and when mpVM != NULL!
4273 * @note Doesn't lock anything.
4274 */
4275HRESULT Console::createSharedFolder (INPTR BSTR aName, INPTR BSTR aHostPath)
4276{
4277 ComAssertRet (aName && *aName, E_FAIL);
4278 ComAssertRet (aHostPath && *aHostPath, E_FAIL);
4279
4280 /* sanity checks */
4281 AssertReturn (mpVM, E_FAIL);
4282 AssertReturn (mVMMDev->isShFlActive(), E_FAIL);
4283
4284 VBOXHGCMSVCPARM parms[2];
4285 SHFLSTRING *pFolderName, *pMapName;
4286 int cbString;
4287
4288 Log (("Adding shared folder '%ls' -> '%ls'\n", aName, aHostPath));
4289
4290 cbString = (RTStrUcs2Len (aHostPath) + 1) * sizeof (RTUCS2);
4291 pFolderName = (SHFLSTRING *) RTMemAllocZ (sizeof (SHFLSTRING) + cbString);
4292 Assert (pFolderName);
4293 memcpy (pFolderName->String.ucs2, aHostPath, cbString);
4294
4295 pFolderName->u16Size = cbString;
4296 pFolderName->u16Length = cbString - sizeof(RTUCS2);
4297
4298 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
4299 parms[0].u.pointer.addr = pFolderName;
4300 parms[0].u.pointer.size = sizeof (SHFLSTRING) + cbString;
4301
4302 cbString = (RTStrUcs2Len (aName) + 1) * sizeof (RTUCS2);
4303 pMapName = (SHFLSTRING *) RTMemAllocZ (sizeof(SHFLSTRING) + cbString);
4304 Assert (pMapName);
4305 memcpy (pMapName->String.ucs2, aName, cbString);
4306
4307 pMapName->u16Size = cbString;
4308 pMapName->u16Length = cbString - sizeof (RTUCS2);
4309
4310 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
4311 parms[1].u.pointer.addr = pMapName;
4312 parms[1].u.pointer.size = sizeof (SHFLSTRING) + cbString;
4313
4314 int vrc = mVMMDev->hgcmHostCall ("VBoxSharedFolders",
4315 SHFL_FN_ADD_MAPPING,
4316 2, &parms[0]);
4317 RTMemFree (pFolderName);
4318 RTMemFree (pMapName);
4319
4320 if (VBOX_FAILURE (vrc))
4321 return setError (E_FAIL,
4322 tr ("Could not create a shared folder '%ls' "
4323 "mapped to '%ls' (%Vrc)"),
4324 aName, aHostPath, vrc);
4325
4326 return S_OK;
4327}
4328
4329/**
4330 * Calls the HGCM service to remove the shared folder definition.
4331 *
4332 * @param aName Shared folder name.
4333 *
4334 * @note Must be called from under AutoVMCaller and when mpVM != NULL!
4335 * @note Doesn't lock anything.
4336 */
4337HRESULT Console::removeSharedFolder (INPTR BSTR aName)
4338{
4339 ComAssertRet (aName && *aName, E_FAIL);
4340
4341 /* sanity checks */
4342 AssertReturn (mpVM, E_FAIL);
4343 AssertReturn (mVMMDev->isShFlActive(), E_FAIL);
4344
4345 VBOXHGCMSVCPARM parms;
4346 SHFLSTRING *pMapName;
4347 int cbString;
4348
4349 Log (("Removing shared folder '%ls'\n", aName));
4350
4351 cbString = (RTStrUcs2Len (aName) + 1) * sizeof (RTUCS2);
4352 pMapName = (SHFLSTRING *) RTMemAllocZ (sizeof (SHFLSTRING) + cbString);
4353 Assert (pMapName);
4354 memcpy (pMapName->String.ucs2, aName, cbString);
4355
4356 pMapName->u16Size = cbString;
4357 pMapName->u16Length = cbString - sizeof (RTUCS2);
4358
4359 parms.type = VBOX_HGCM_SVC_PARM_PTR;
4360 parms.u.pointer.addr = pMapName;
4361 parms.u.pointer.size = sizeof (SHFLSTRING) + cbString;
4362
4363 int vrc = mVMMDev->hgcmHostCall ("VBoxSharedFolders",
4364 SHFL_FN_REMOVE_MAPPING,
4365 1, &parms);
4366 RTMemFree(pMapName);
4367 if (VBOX_FAILURE (vrc))
4368 return setError (E_FAIL,
4369 tr ("Could not remove the shared folder '%ls' (%Vrc)"),
4370 aName, vrc);
4371
4372 return S_OK;
4373}
4374
4375/**
4376 * VM state callback function. Called by the VMM
4377 * using its state machine states.
4378 *
4379 * Primarily used to handle VM initiated power off, suspend and state saving,
4380 * but also for doing termination completed work (VMSTATE_TERMINATE).
4381 *
4382 * In general this function is called in the context of the EMT.
4383 *
4384 * @param aVM The VM handle.
4385 * @param aState The new state.
4386 * @param aOldState The old state.
4387 * @param aUser The user argument (pointer to the Console object).
4388 *
4389 * @note Locks the Console object for writing.
4390 */
4391DECLCALLBACK(void)
4392Console::vmstateChangeCallback (PVM aVM, VMSTATE aState, VMSTATE aOldState,
4393 void *aUser)
4394{
4395 LogFlowFunc (("Changing state from %d to %d (aVM=%p)\n",
4396 aOldState, aState, aVM));
4397
4398 Console *that = static_cast <Console *> (aUser);
4399 AssertReturnVoid (that);
4400
4401 AutoCaller autoCaller (that);
4402 /*
4403 * Note that we must let this method proceed even if Console::uninit() has
4404 * been already called. In such case this VMSTATE change is a result of:
4405 * 1) powerDown() called from uninit() itself, or
4406 * 2) VM-(guest-)initiated power off.
4407 */
4408 AssertReturnVoid (autoCaller.isOk() ||
4409 autoCaller.state() == InUninit);
4410
4411 switch (aState)
4412 {
4413 /*
4414 * The VM has terminated
4415 */
4416 case VMSTATE_OFF:
4417 {
4418 AutoLock alock (that);
4419
4420 if (that->mVMStateChangeCallbackDisabled)
4421 break;
4422
4423 /*
4424 * Do we still think that it is running? It may happen if this is
4425 * a VM-(guest-)initiated shutdown/poweroff.
4426 */
4427 if (that->mMachineState != MachineState_Stopping &&
4428 that->mMachineState != MachineState_Saving &&
4429 that->mMachineState != MachineState_Restoring)
4430 {
4431 LogFlowFunc (("VM has powered itself off but Console still "
4432 "thinks it is running. Notifying.\n"));
4433
4434 /* prevent powerDown() from calling VMR3PowerOff() again */
4435 that->setMachineState (MachineState_Stopping);
4436
4437 /*
4438 * Setup task object and thread to carry out the operation
4439 * asynchronously (if we call powerDown() right here but there
4440 * is one or more mpVM callers (added with addVMCaller()) we'll
4441 * deadlock.
4442 */
4443 std::auto_ptr <VMTask> task (new VMTask (that, true /* aUsesVMPtr */));
4444 /*
4445 * If creating a task is falied, this can currently mean one
4446 * of two: either Console::uninit() has been called just a ms
4447 * before (so a powerDown() call is already on the way), or
4448 * powerDown() itself is being already executed. Just do
4449 * nothing .
4450 */
4451 if (!task->isOk())
4452 {
4453 LogFlowFunc (("Console is already being uninitialized.\n"));
4454 break;
4455 }
4456
4457 int vrc = RTThreadCreate (NULL, Console::powerDownThread,
4458 (void *) task.get(), 0,
4459 RTTHREADTYPE_MAIN_WORKER, 0,
4460 "VMPowerDowm");
4461
4462 AssertMsgRC (vrc, ("Could not create VMPowerUp thread (%Vrc)\n", vrc));
4463 if (VBOX_FAILURE (vrc))
4464 break;
4465
4466 /* task is now owned by powerDownThread(), so release it */
4467 task.release();
4468 }
4469 break;
4470 }
4471
4472 /*
4473 * The VM has been completely destroyed.
4474 *
4475 * Note: This state change can happen at two points:
4476 * 1) At the end of VMR3Destroy() if it was not called from EMT.
4477 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
4478 * called by EMT.
4479 */
4480 case VMSTATE_TERMINATED:
4481 {
4482 AutoLock alock (that);
4483
4484 if (that->mVMStateChangeCallbackDisabled)
4485 break;
4486
4487 /*
4488 * Terminate host interface networking. If aVM is NULL, we've been
4489 * manually called from powerUpThread() either before calling
4490 * VMR3Create() or after VMR3Create() failed, so no need to touch
4491 * networking.
4492 */
4493 if (aVM)
4494 that->powerDownHostInterfaces();
4495
4496 /*
4497 * From now on the machine is officially powered down or
4498 * remains in the Saved state.
4499 */
4500 switch (that->mMachineState)
4501 {
4502 default:
4503 AssertFailed();
4504 /* fall through */
4505 case MachineState_Stopping:
4506 /* successfully powered down */
4507 that->setMachineState (MachineState_PoweredOff);
4508 break;
4509 case MachineState_Saving:
4510 /*
4511 * successfully saved (note that the machine is already
4512 * in the Saved state on the server due to EndSavingState()
4513 * called from saveStateThread(), so only change the local
4514 * state)
4515 */
4516 that->setMachineStateLocally (MachineState_Saved);
4517 break;
4518 case MachineState_Starting:
4519 /*
4520 * failed to start, but be patient: set back to PoweredOff
4521 * (for similarity with the below)
4522 */
4523 that->setMachineState (MachineState_PoweredOff);
4524 break;
4525 case MachineState_Restoring:
4526 /*
4527 * failed to load the saved state file, but be patient:
4528 * set back to Saved (to preserve the saved state file)
4529 */
4530 that->setMachineState (MachineState_Saved);
4531 break;
4532 }
4533
4534 break;
4535 }
4536
4537 case VMSTATE_SUSPENDED:
4538 {
4539 if (aOldState == VMSTATE_RUNNING)
4540 {
4541 AutoLock alock (that);
4542
4543 if (that->mVMStateChangeCallbackDisabled)
4544 break;
4545
4546 /* Change the machine state from Running to Paused */
4547 Assert (that->mMachineState == MachineState_Running);
4548 that->setMachineState (MachineState_Paused);
4549 }
4550 }
4551
4552 case VMSTATE_RUNNING:
4553 {
4554 if (aOldState == VMSTATE_CREATED ||
4555 aOldState == VMSTATE_SUSPENDED)
4556 {
4557 AutoLock alock (that);
4558
4559 if (that->mVMStateChangeCallbackDisabled)
4560 break;
4561
4562 /*
4563 * Change the machine state from Starting, Restoring or Paused
4564 * to Running
4565 */
4566 Assert ((that->mMachineState == MachineState_Starting &&
4567 aOldState == VMSTATE_CREATED) ||
4568 ((that->mMachineState == MachineState_Restoring ||
4569 that->mMachineState == MachineState_Paused) &&
4570 aOldState == VMSTATE_SUSPENDED));
4571
4572 that->setMachineState (MachineState_Running);
4573 }
4574 }
4575
4576 default: /* shut up gcc */
4577 break;
4578 }
4579}
4580
4581/**
4582 * Sends a request to VMM to attach the given host device.
4583 * After this method succeeds, the attached device will appear in the
4584 * mUSBDevices collection.
4585 *
4586 * @param aHostDevice device to attach
4587 *
4588 * @note Synchronously calls EMT.
4589 * @note Must be called from under this object's lock.
4590 */
4591#if 1
4592HRESULT Console::attachUSBDevice (IUSBDevice *aHostDevice, PVUSBIRHCONFIG aConfig)
4593{
4594 AssertReturn (aHostDevice && aConfig, E_FAIL);
4595#else /* PDMUsb */
4596HRESULT Console::attachUSBDevice (IUSBDevice *aHostDevice)
4597{
4598 AssertReturn (aHostDevice, E_FAIL);
4599#endif
4600
4601 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
4602
4603 /* still want a lock object because we need to leave it */
4604 AutoLock alock (this);
4605
4606 HRESULT hrc;
4607
4608 /*
4609 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
4610 * method in EMT (using usbAttachCallback()).
4611 */
4612 Bstr BstrAddress;
4613 hrc = aHostDevice->COMGETTER (Address) (BstrAddress.asOutParam());
4614 ComAssertComRCRetRC (hrc);
4615
4616 Utf8Str Address (BstrAddress);
4617
4618 Guid Uuid;
4619 hrc = aHostDevice->COMGETTER (Id) (Uuid.asOutParam());
4620 ComAssertComRCRetRC (hrc);
4621
4622 BOOL fRemote = FALSE;
4623 void *pvRemote = NULL;
4624
4625 hrc = aHostDevice->COMGETTER (Remote) (&fRemote);
4626 ComAssertComRCRetRC (hrc);
4627
4628 /* protect mpVM */
4629 AutoVMCaller autoVMCaller (this);
4630 CheckComRCReturnRC (autoVMCaller.rc());
4631
4632 LogFlowThisFunc (("Proxying USB device '%s' {%Vuuid}...\n",
4633 Address.raw(), Uuid.ptr()));
4634
4635 /* leave the lock before a VMR3* call (EMT will call us back)! */
4636 alock.leave();
4637
4638#if 1
4639 PVMREQ pReq = NULL;
4640 int vrc = VMR3ReqCall (mpVM, &pReq, RT_INDEFINITE_WAIT,
4641 (PFNRT) usbAttachCallback, 7,
4642 this, aHostDevice,
4643 aConfig, Uuid.ptr(), fRemote, Address.raw(), pvRemote);
4644#else /* PDMUsb */
4645 PVMREQ pReq = NULL;
4646 int vrc = VMR3ReqCall (mpVM, &pReq, RT_INDEFINITE_WAIT,
4647 (PFNRT) usbAttachCallback, 5, this, aHostDevice, aConfig, Uuid.ptr(), fRemote, Address.raw());
4648#endif /* PDMUsb */
4649 if (VBOX_SUCCESS (vrc))
4650 vrc = pReq->iStatus;
4651 VMR3ReqFree (pReq);
4652
4653 /* restore the lock */
4654 alock.enter();
4655
4656 /* hrc is S_OK here */
4657
4658 if (VBOX_FAILURE (vrc))
4659 {
4660 LogWarningThisFunc (("Failed to create proxy device for '%s' {%Vuuid} (%Vrc)\n",
4661 Address.raw(), Uuid.ptr(), vrc));
4662
4663 switch (vrc)
4664 {
4665 case VERR_VUSB_NO_PORTS:
4666 hrc = setError (E_FAIL,
4667 tr ("Failed to attach the USB device. (No available ports on the USB controller)."));
4668 break;
4669 case VERR_VUSB_USBFS_PERMISSION:
4670 hrc = setError (E_FAIL,
4671 tr ("Not permitted to open the USB device, check usbfs options"));
4672 break;
4673 default:
4674 hrc = setError (E_FAIL,
4675 tr ("Failed to create a proxy device for the USB device. (Error: %Vrc)"), vrc);
4676 break;
4677 }
4678 }
4679
4680 return hrc;
4681}
4682
4683/**
4684 * USB device attach callback used by AttachUSBDevice().
4685 * Note that AttachUSBDevice() doesn't return until this callback is executed,
4686 * so we don't use AutoCaller and don't care about reference counters of
4687 * interface pointers passed in.
4688 *
4689 * @thread EMT
4690 * @note Locks the console object for writing.
4691 */
4692#if 1
4693DECLCALLBACK(int)
4694Console::usbAttachCallback (Console *that, IUSBDevice *aHostDevice,
4695 PVUSBIRHCONFIG aConfig, PCRTUUID aUuid, bool aRemote,
4696 const char *aAddress, void *aRemoteBackend)
4697{
4698 LogFlowFuncEnter();
4699 LogFlowFunc (("that={%p}\n", that));
4700
4701 AssertReturn (that && aConfig && aUuid, VERR_INVALID_PARAMETER);
4702
4703 if (aRemote)
4704 {
4705 /* @todo aRemoteBackend input parameter is not needed. */
4706 Assert (aRemoteBackend == NULL);
4707
4708 RemoteUSBDevice *pRemoteUSBDevice = static_cast <RemoteUSBDevice *> (aHostDevice);
4709
4710 Guid guid (*aUuid);
4711
4712 aRemoteBackend = that->consoleVRDPServer ()->USBBackendRequestPointer (pRemoteUSBDevice->clientId (), &guid);
4713
4714 if (aRemoteBackend == NULL)
4715 {
4716 /* The clientId is invalid then. */
4717 return VERR_INVALID_PARAMETER;
4718 }
4719 }
4720
4721 int vrc = aConfig->pfnCreateProxyDevice (aConfig, aUuid, aRemote, aAddress,
4722 aRemoteBackend);
4723
4724 if (VBOX_SUCCESS (vrc))
4725 {
4726 /* Create a OUSBDevice and add it to the device list */
4727 ComObjPtr <OUSBDevice> device;
4728 device.createObject();
4729 HRESULT hrc = device->init (aHostDevice);
4730 AssertComRC (hrc);
4731
4732 AutoLock alock (that);
4733 that->mUSBDevices.push_back (device);
4734 LogFlowFunc (("Attached device {%Vuuid}\n", device->id().raw()));
4735
4736 /* notify callbacks */
4737 that->onUSBDeviceStateChange (device, true /* aAttached */, NULL);
4738 }
4739
4740 LogFlowFunc (("vrc=%Vrc\n", vrc));
4741 LogFlowFuncLeave();
4742 return vrc;
4743}
4744#else /* PDMUsb */
4745//static
4746DECLCALLBACK(int)
4747Console::usbAttachCallback (Console *that, IUSBDevice *aHostDevice, PCRTUUID aUuid, bool aRemote, const char *aAddress)
4748{
4749 LogFlowFuncEnter();
4750 LogFlowFunc (("that={%p}\n", that));
4751
4752 AssertReturn (that && aConfig && aUuid, VERR_INVALID_PARAMETER);
4753
4754 if (aRemote)
4755 {
4756 RemoteUSBDevice *pRemoteUSBDevice = static_cast <RemoteUSBDevice *> (aHostDevice);
4757 Guid guid (*aUuid);
4758
4759 aRemoteBackend = that->consoleVRDPServer ()->USBBackendRequestPointer (pRemoteUSBDevice->clientId (), &guid);
4760 if (!aRemoteBackend)
4761 return VERR_INVALID_PARAMETER; /* The clientId is invalid then. */
4762 }
4763
4764 int vrc = PDMR3USBCreateProxyDevice (mVM, aUuid, aRemote, aAddress, aRemoteBackend);
4765 if (VBOX_SUCCESS (vrc))
4766 {
4767 /* Create a OUSBDevice and add it to the device list */
4768 ComObjPtr <OUSBDevice> device;
4769 device.createObject();
4770 HRESULT hrc = device->init (aHostDevice);
4771 AssertComRC (hrc);
4772
4773 AutoLock alock (that);
4774 that->mUSBDevices.push_back (device);
4775 LogFlowFunc (("Attached device {%Vuuid}\n", device->id().raw()));
4776
4777 /* notify callbacks */
4778 that->onUSBDeviceStateChange (device, true /* aAttached */, NULL);
4779 }
4780
4781 LogFlowFunc (("vrc=%Vrc\n", vrc));
4782 LogFlowFuncLeave();
4783 return vrc;
4784}
4785#endif /* PDMUsb */
4786
4787/**
4788 * Sends a request to VMM to detach the given host device. After this method
4789 * succeeds, the detached device will disappear from the mUSBDevices
4790 * collection.
4791 *
4792 * @param aIt Iterator pointing to the device to detach.
4793 *
4794 * @note Synchronously calls EMT.
4795 * @note Must be called from under this object's lock.
4796 */
4797HRESULT Console::detachUSBDevice (USBDeviceList::iterator &aIt)
4798{
4799 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
4800
4801 /* still want a lock object because we need to leave it */
4802 AutoLock alock (this);
4803
4804 /* protect mpVM */
4805 AutoVMCaller autoVMCaller (this);
4806 CheckComRCReturnRC (autoVMCaller.rc());
4807
4808 PPDMIBASE pBase = NULL;
4809 int vrc = PDMR3QueryLun (mpVM, "usb-ohci", 0, 0, &pBase);
4810
4811 /* if the device is attached, then there must be a USB controller */
4812 AssertRCReturn (vrc, E_FAIL);
4813
4814 PVUSBIRHCONFIG pRhConfig = (PVUSBIRHCONFIG) pBase->
4815 pfnQueryInterface (pBase, PDMINTERFACE_VUSB_RH_CONFIG);
4816 AssertReturn (pRhConfig, E_FAIL);
4817
4818 LogFlowThisFunc (("Detaching USB proxy device {%Vuuid}...\n",
4819 (*aIt)->id().raw()));
4820
4821 /* leave the lock before a VMR3* call (EMT will call us back)! */
4822 alock.leave();
4823
4824 PVMREQ pReq;
4825 vrc = VMR3ReqCall (mpVM, &pReq, RT_INDEFINITE_WAIT,
4826 (PFNRT) usbDetachCallback, 5,
4827 this, &aIt, pRhConfig, (*aIt)->id().raw());
4828 if (VBOX_SUCCESS (vrc))
4829 vrc = pReq->iStatus;
4830 VMR3ReqFree (pReq);
4831
4832 ComAssertRCRet (vrc, E_FAIL);
4833
4834 return S_OK;
4835}
4836
4837/**
4838 * USB device detach callback used by DetachUSBDevice().
4839 * Note that DetachUSBDevice() doesn't return until this callback is executed,
4840 * so we don't use AutoCaller and don't care about reference counters of
4841 * interface pointers passed in.
4842 *
4843 * @thread EMT
4844 * @note Locks the console object for writing.
4845 */
4846//static
4847DECLCALLBACK(int)
4848Console::usbDetachCallback (Console *that, USBDeviceList::iterator *aIt,
4849 PVUSBIRHCONFIG aConfig, PCRTUUID aUuid)
4850{
4851 LogFlowFuncEnter();
4852 LogFlowFunc (("that={%p}\n", that));
4853
4854 AssertReturn (that && aConfig && aUuid, VERR_INVALID_PARAMETER);
4855
4856 /*
4857 * If that was a remote device, release the backend pointer.
4858 * The pointer was requested in usbAttachCallback.
4859 */
4860 BOOL fRemote = FALSE;
4861
4862 HRESULT hrc2 = (**aIt)->COMGETTER (Remote) (&fRemote);
4863 ComAssertComRC (hrc2);
4864
4865 if (fRemote)
4866 {
4867 Guid guid (*aUuid);
4868 that->consoleVRDPServer ()->USBBackendReleasePointer (&guid);
4869 }
4870
4871 int vrc = aConfig->pfnDestroyProxyDevice (aConfig, aUuid);
4872
4873 if (VBOX_SUCCESS (vrc))
4874 {
4875 AutoLock alock (that);
4876
4877 /* Remove the device from the collection */
4878 that->mUSBDevices.erase (*aIt);
4879 LogFlowFunc (("Detached device {%Vuuid}\n", (**aIt)->id().raw()));
4880
4881 /* notify callbacks */
4882 that->onUSBDeviceStateChange (**aIt, false /* aAttached */, NULL);
4883 }
4884
4885 LogFlowFunc (("vrc=%Vrc\n", vrc));
4886 LogFlowFuncLeave();
4887 return vrc;
4888}
4889
4890/**
4891 * Construct the VM configuration tree (CFGM).
4892 *
4893 * This is a callback for VMR3Create() call. It is called from CFGMR3Init()
4894 * in the emulation thread (EMT). Any per thread COM/XPCOM initialization
4895 * is done here.
4896 *
4897 * @param pVM VM handle.
4898 * @param pvTask Pointer to the VMPowerUpTask object.
4899 * @return VBox status code.
4900 *
4901 * @note Locks the Console object for writing.
4902 */
4903DECLCALLBACK(int) Console::configConstructor(PVM pVM, void *pvTask)
4904{
4905 LogFlowFuncEnter();
4906
4907 /* Note: the task pointer is owned by powerUpThread() */
4908 VMPowerUpTask *task = static_cast <VMPowerUpTask *> (pvTask);
4909 AssertReturn (task, VERR_GENERAL_FAILURE);
4910
4911#if defined(RT_OS_WINDOWS)
4912 {
4913 /* initialize COM */
4914 HRESULT hrc = CoInitializeEx(NULL,
4915 COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE |
4916 COINIT_SPEED_OVER_MEMORY);
4917 LogFlow (("Console::configConstructor(): CoInitializeEx()=%08X\n", hrc));
4918 AssertComRCReturn (hrc, VERR_GENERAL_FAILURE);
4919 }
4920#endif
4921
4922 ComObjPtr <Console> pConsole = task->mConsole;
4923
4924 AutoCaller autoCaller (pConsole);
4925 AssertComRCReturn (autoCaller.rc(), VERR_ACCESS_DENIED);
4926
4927 /* lock the console because we widely use internal fields and methods */
4928 AutoLock alock (pConsole);
4929
4930 ComPtr <IMachine> pMachine = pConsole->machine();
4931
4932 int rc;
4933 HRESULT hrc;
4934 char *psz = NULL;
4935 BSTR str = NULL;
4936 ULONG cRamMBs;
4937 unsigned i;
4938
4939#define STR_CONV() do { rc = RTStrUcs2ToUtf8(&psz, str); RC_CHECK(); } while (0)
4940#define STR_FREE() do { if (str) { SysFreeString(str); str = NULL; } if (psz) { RTStrFree(psz); psz = NULL; } } while (0)
4941#define RC_CHECK() do { if (VBOX_FAILURE(rc)) { AssertMsgFailed(("rc=%Vrc\n", rc)); STR_FREE(); return rc; } } while (0)
4942#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%#x\n", hrc)); STR_FREE(); return VERR_GENERAL_FAILURE; } } while (0)
4943
4944 /* Get necessary objects */
4945
4946 ComPtr<IVirtualBox> virtualBox;
4947 hrc = pMachine->COMGETTER(Parent)(virtualBox.asOutParam()); H();
4948
4949 ComPtr<IHost> host;
4950 hrc = virtualBox->COMGETTER(Host)(host.asOutParam()); H();
4951
4952 ComPtr <ISystemProperties> systemProperties;
4953 hrc = virtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam()); H();
4954
4955 ComPtr<IBIOSSettings> biosSettings;
4956 hrc = pMachine->COMGETTER(BIOSSettings)(biosSettings.asOutParam()); H();
4957
4958
4959 /*
4960 * Get root node first.
4961 * This is the only node in the tree.
4962 */
4963 PCFGMNODE pRoot = CFGMR3GetRoot(pVM);
4964 Assert(pRoot);
4965
4966 /*
4967 * Set the root level values.
4968 */
4969 hrc = pMachine->COMGETTER(Name)(&str); H();
4970 STR_CONV();
4971 rc = CFGMR3InsertString(pRoot, "Name", psz); RC_CHECK();
4972 STR_FREE();
4973 hrc = pMachine->COMGETTER(MemorySize)(&cRamMBs); H();
4974 rc = CFGMR3InsertInteger(pRoot, "RamSize", cRamMBs * _1M); RC_CHECK();
4975 rc = CFGMR3InsertInteger(pRoot, "TimerMillies", 10); RC_CHECK();
4976 rc = CFGMR3InsertInteger(pRoot, "RawR3Enabled", 1); /* boolean */ RC_CHECK();
4977 rc = CFGMR3InsertInteger(pRoot, "RawR0Enabled", 1); /* boolean */ RC_CHECK();
4978 /** @todo Config: RawR0, PATMEnabled and CASMEnabled needs attention later. */
4979 rc = CFGMR3InsertInteger(pRoot, "PATMEnabled", 1); /* boolean */ RC_CHECK();
4980 rc = CFGMR3InsertInteger(pRoot, "CSAMEnabled", 1); /* boolean */ RC_CHECK();
4981
4982 /* hardware virtualization extensions */
4983 TriStateBool_T hwVirtExEnabled;
4984 BOOL fHWVirtExEnabled;
4985 hrc = pMachine->COMGETTER(HWVirtExEnabled)(&hwVirtExEnabled); H();
4986 if (hwVirtExEnabled == TriStateBool_Default)
4987 {
4988 /* check the default value */
4989 hrc = systemProperties->COMGETTER(HWVirtExEnabled)(&fHWVirtExEnabled); H();
4990 }
4991 else
4992 fHWVirtExEnabled = (hwVirtExEnabled == TriStateBool_True);
4993#ifndef RT_OS_DARWIN /** @todo Implement HWVirtExt on darwin. See #1865. */
4994 if (fHWVirtExEnabled)
4995 {
4996 PCFGMNODE pHWVirtExt;
4997 rc = CFGMR3InsertNode(pRoot, "HWVirtExt", &pHWVirtExt); RC_CHECK();
4998 rc = CFGMR3InsertInteger(pHWVirtExt, "Enabled", 1); RC_CHECK();
4999 }
5000#endif
5001
5002 BOOL fIOAPIC;
5003 hrc = biosSettings->COMGETTER(IOAPICEnabled)(&fIOAPIC); H();
5004
5005 /*
5006 * PDM config.
5007 * Load drivers in VBoxC.[so|dll]
5008 */
5009 PCFGMNODE pPDM;
5010 PCFGMNODE pDrivers;
5011 PCFGMNODE pMod;
5012 rc = CFGMR3InsertNode(pRoot, "PDM", &pPDM); RC_CHECK();
5013 rc = CFGMR3InsertNode(pPDM, "Drivers", &pDrivers); RC_CHECK();
5014 rc = CFGMR3InsertNode(pDrivers, "VBoxC", &pMod); RC_CHECK();
5015#ifdef VBOX_WITH_XPCOM
5016 // VBoxC is located in the components subdirectory
5017 char szPathVBoxC[RTPATH_MAX];
5018 rc = RTPathAppPrivateArch(szPathVBoxC, RTPATH_MAX - sizeof("/components/VBoxC")); AssertRC(rc);
5019 strcat(szPathVBoxC, "/components/VBoxC");
5020 rc = CFGMR3InsertString(pMod, "Path", szPathVBoxC); RC_CHECK();
5021#else
5022 rc = CFGMR3InsertString(pMod, "Path", "VBoxC"); RC_CHECK();
5023#endif
5024
5025 /*
5026 * Devices
5027 */
5028 PCFGMNODE pDevices = NULL; /* /Devices */
5029 PCFGMNODE pDev = NULL; /* /Devices/Dev/ */
5030 PCFGMNODE pInst = NULL; /* /Devices/Dev/0/ */
5031 PCFGMNODE pCfg = NULL; /* /Devices/Dev/.../Config/ */
5032 PCFGMNODE pLunL0 = NULL; /* /Devices/Dev/0/LUN#0/ */
5033 PCFGMNODE pLunL1 = NULL; /* /Devices/Dev/0/LUN#0/AttachedDriver/ */
5034 PCFGMNODE pLunL2 = NULL; /* /Devices/Dev/0/LUN#0/AttachedDriver/Config/ */
5035
5036 rc = CFGMR3InsertNode(pRoot, "Devices", &pDevices); RC_CHECK();
5037
5038 /*
5039 * PC Arch.
5040 */
5041 rc = CFGMR3InsertNode(pDevices, "pcarch", &pDev); RC_CHECK();
5042 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5043 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5044 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5045
5046 /*
5047 * PC Bios.
5048 */
5049 rc = CFGMR3InsertNode(pDevices, "pcbios", &pDev); RC_CHECK();
5050 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5051 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5052 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5053 rc = CFGMR3InsertInteger(pCfg, "RamSize", cRamMBs * _1M); RC_CHECK();
5054 rc = CFGMR3InsertString(pCfg, "HardDiskDevice", "piix3ide"); RC_CHECK();
5055 rc = CFGMR3InsertString(pCfg, "FloppyDevice", "i82078"); RC_CHECK();
5056 rc = CFGMR3InsertInteger(pCfg, "IOAPIC", fIOAPIC); RC_CHECK();
5057
5058 DeviceType_T bootDevice;
5059 if (SchemaDefs::MaxBootPosition > 9)
5060 {
5061 AssertMsgFailed (("Too many boot devices %d\n",
5062 SchemaDefs::MaxBootPosition));
5063 return VERR_INVALID_PARAMETER;
5064 }
5065
5066 for (ULONG pos = 1; pos <= SchemaDefs::MaxBootPosition; pos ++)
5067 {
5068 hrc = pMachine->GetBootOrder(pos, &bootDevice); H();
5069
5070 char szParamName[] = "BootDeviceX";
5071 szParamName[sizeof (szParamName) - 2] = ((char (pos - 1)) + '0');
5072
5073 const char *pszBootDevice;
5074 switch (bootDevice)
5075 {
5076 case DeviceType_NoDevice:
5077 pszBootDevice = "NONE";
5078 break;
5079 case DeviceType_HardDiskDevice:
5080 pszBootDevice = "IDE";
5081 break;
5082 case DeviceType_DVDDevice:
5083 pszBootDevice = "DVD";
5084 break;
5085 case DeviceType_FloppyDevice:
5086 pszBootDevice = "FLOPPY";
5087 break;
5088 case DeviceType_NetworkDevice:
5089 pszBootDevice = "LAN";
5090 break;
5091 default:
5092 AssertMsgFailed(("Invalid bootDevice=%d\n", bootDevice));
5093 return VERR_INVALID_PARAMETER;
5094 }
5095 rc = CFGMR3InsertString(pCfg, szParamName, pszBootDevice); RC_CHECK();
5096 }
5097
5098 /*
5099 * BIOS logo
5100 */
5101 BOOL fFadeIn;
5102 hrc = biosSettings->COMGETTER(LogoFadeIn)(&fFadeIn); H();
5103 rc = CFGMR3InsertInteger(pCfg, "FadeIn", fFadeIn ? 1 : 0); RC_CHECK();
5104 BOOL fFadeOut;
5105 hrc = biosSettings->COMGETTER(LogoFadeOut)(&fFadeOut); H();
5106 rc = CFGMR3InsertInteger(pCfg, "FadeOut", fFadeOut ? 1: 0); RC_CHECK();
5107 ULONG logoDisplayTime;
5108 hrc = biosSettings->COMGETTER(LogoDisplayTime)(&logoDisplayTime); H();
5109 rc = CFGMR3InsertInteger(pCfg, "LogoTime", logoDisplayTime); RC_CHECK();
5110 Bstr logoImagePath;
5111 hrc = biosSettings->COMGETTER(LogoImagePath)(logoImagePath.asOutParam()); H();
5112 rc = CFGMR3InsertString(pCfg, "LogoFile", logoImagePath ? Utf8Str(logoImagePath) : ""); RC_CHECK();
5113
5114 /*
5115 * Boot menu
5116 */
5117 BIOSBootMenuMode_T bootMenuMode;
5118 int value;
5119 biosSettings->COMGETTER(BootMenuMode)(&bootMenuMode);
5120 switch (bootMenuMode)
5121 {
5122 case BIOSBootMenuMode_Disabled:
5123 value = 0;
5124 break;
5125 case BIOSBootMenuMode_MenuOnly:
5126 value = 1;
5127 break;
5128 default:
5129 value = 2;
5130 }
5131 rc = CFGMR3InsertInteger(pCfg, "ShowBootMenu", value); RC_CHECK();
5132
5133 /*
5134 * The time offset
5135 */
5136 LONG64 timeOffset;
5137 hrc = biosSettings->COMGETTER(TimeOffset)(&timeOffset); H();
5138 PCFGMNODE pTMNode;
5139 rc = CFGMR3InsertNode(pRoot, "TM", &pTMNode); RC_CHECK();
5140 rc = CFGMR3InsertInteger(pTMNode, "UTCOffset", timeOffset * 1000000); RC_CHECK();
5141
5142 /*
5143 * ACPI
5144 */
5145 BOOL fACPI;
5146 hrc = biosSettings->COMGETTER(ACPIEnabled)(&fACPI); H();
5147 if (fACPI)
5148 {
5149 rc = CFGMR3InsertNode(pDevices, "acpi", &pDev); RC_CHECK();
5150 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5151 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5152 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5153 rc = CFGMR3InsertInteger(pCfg, "RamSize", cRamMBs * _1M); RC_CHECK();
5154 rc = CFGMR3InsertInteger(pCfg, "IOAPIC", fIOAPIC); RC_CHECK();
5155 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 7); RC_CHECK();
5156 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
5157
5158 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5159 rc = CFGMR3InsertString(pLunL0, "Driver", "ACPIHost"); RC_CHECK();
5160 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5161 }
5162
5163 /*
5164 * DMA
5165 */
5166 rc = CFGMR3InsertNode(pDevices, "8237A", &pDev); RC_CHECK();
5167 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5168 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5169
5170 /*
5171 * PCI bus.
5172 */
5173 rc = CFGMR3InsertNode(pDevices, "pci", &pDev); /* piix3 */ RC_CHECK();
5174 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5175 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5176 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5177 rc = CFGMR3InsertInteger(pCfg, "IOAPIC", fIOAPIC); RC_CHECK();
5178
5179 /*
5180 * PS/2 keyboard & mouse.
5181 */
5182 rc = CFGMR3InsertNode(pDevices, "pckbd", &pDev); RC_CHECK();
5183 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5184 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5185 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5186
5187 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5188 rc = CFGMR3InsertString(pLunL0, "Driver", "KeyboardQueue"); RC_CHECK();
5189 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5190 rc = CFGMR3InsertInteger(pCfg, "QueueSize", 64); RC_CHECK();
5191
5192 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
5193 rc = CFGMR3InsertString(pLunL1, "Driver", "MainKeyboard"); RC_CHECK();
5194 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
5195 Keyboard *pKeyboard = pConsole->mKeyboard;
5196 rc = CFGMR3InsertInteger(pCfg, "Object", (uintptr_t)pKeyboard); RC_CHECK();
5197
5198 rc = CFGMR3InsertNode(pInst, "LUN#1", &pLunL0); RC_CHECK();
5199 rc = CFGMR3InsertString(pLunL0, "Driver", "MouseQueue"); RC_CHECK();
5200 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5201 rc = CFGMR3InsertInteger(pCfg, "QueueSize", 128); RC_CHECK();
5202
5203 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
5204 rc = CFGMR3InsertString(pLunL1, "Driver", "MainMouse"); RC_CHECK();
5205 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
5206 Mouse *pMouse = pConsole->mMouse;
5207 rc = CFGMR3InsertInteger(pCfg, "Object", (uintptr_t)pMouse); RC_CHECK();
5208
5209 /*
5210 * i82078 Floppy drive controller
5211 */
5212 ComPtr<IFloppyDrive> floppyDrive;
5213 hrc = pMachine->COMGETTER(FloppyDrive)(floppyDrive.asOutParam()); H();
5214 BOOL fFloppyEnabled;
5215 hrc = floppyDrive->COMGETTER(Enabled)(&fFloppyEnabled); H();
5216 if (fFloppyEnabled)
5217 {
5218 rc = CFGMR3InsertNode(pDevices, "i82078", &pDev); RC_CHECK();
5219 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5220 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); RC_CHECK();
5221 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5222 rc = CFGMR3InsertInteger(pCfg, "IRQ", 6); RC_CHECK();
5223 rc = CFGMR3InsertInteger(pCfg, "DMA", 2); RC_CHECK();
5224 rc = CFGMR3InsertInteger(pCfg, "MemMapped", 0 ); RC_CHECK();
5225 rc = CFGMR3InsertInteger(pCfg, "IOBase", 0x3f0); RC_CHECK();
5226
5227 /* Attach the status driver */
5228 rc = CFGMR3InsertNode(pInst, "LUN#999", &pLunL0); RC_CHECK();
5229 rc = CFGMR3InsertString(pLunL0, "Driver", "MainStatus"); RC_CHECK();
5230 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5231 rc = CFGMR3InsertInteger(pCfg, "papLeds", (uintptr_t)&pConsole->mapFDLeds[0]); RC_CHECK();
5232 rc = CFGMR3InsertInteger(pCfg, "First", 0); RC_CHECK();
5233 rc = CFGMR3InsertInteger(pCfg, "Last", 0); RC_CHECK();
5234
5235 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5236
5237 ComPtr<IFloppyImage> floppyImage;
5238 hrc = floppyDrive->GetImage(floppyImage.asOutParam()); H();
5239 if (floppyImage)
5240 {
5241 pConsole->meFloppyState = DriveState_ImageMounted;
5242 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
5243 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5244 rc = CFGMR3InsertString(pCfg, "Type", "Floppy 1.44"); RC_CHECK();
5245 rc = CFGMR3InsertInteger(pCfg, "Mountable", 1); RC_CHECK();
5246
5247 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
5248 rc = CFGMR3InsertString(pLunL1, "Driver", "RawImage"); RC_CHECK();
5249 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
5250 hrc = floppyImage->COMGETTER(FilePath)(&str); H();
5251 STR_CONV();
5252 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
5253 STR_FREE();
5254 }
5255 else
5256 {
5257 ComPtr<IHostFloppyDrive> hostFloppyDrive;
5258 hrc = floppyDrive->GetHostDrive(hostFloppyDrive.asOutParam()); H();
5259 if (hostFloppyDrive)
5260 {
5261 pConsole->meFloppyState = DriveState_HostDriveCaptured;
5262 rc = CFGMR3InsertString(pLunL0, "Driver", "HostFloppy"); RC_CHECK();
5263 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5264 hrc = hostFloppyDrive->COMGETTER(Name)(&str); H();
5265 STR_CONV();
5266 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
5267 STR_FREE();
5268 }
5269 else
5270 {
5271 pConsole->meFloppyState = DriveState_NotMounted;
5272 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
5273 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5274 rc = CFGMR3InsertString(pCfg, "Type", "Floppy 1.44"); RC_CHECK();
5275 rc = CFGMR3InsertInteger(pCfg, "Mountable", 1); RC_CHECK();
5276 }
5277 }
5278 }
5279
5280 /*
5281 * i8254 Programmable Interval Timer And Dummy Speaker
5282 */
5283 rc = CFGMR3InsertNode(pDevices, "i8254", &pDev); RC_CHECK();
5284 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5285 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5286#ifdef DEBUG
5287 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5288#endif
5289
5290 /*
5291 * i8259 Programmable Interrupt Controller.
5292 */
5293 rc = CFGMR3InsertNode(pDevices, "i8259", &pDev); RC_CHECK();
5294 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5295 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5296 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5297
5298 /*
5299 * Advanced Programmable Interrupt Controller.
5300 */
5301 rc = CFGMR3InsertNode(pDevices, "apic", &pDev); RC_CHECK();
5302 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5303 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5304 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5305 rc = CFGMR3InsertInteger(pCfg, "IOAPIC", fIOAPIC); RC_CHECK();
5306
5307 if (fIOAPIC)
5308 {
5309 /*
5310 * I/O Advanced Programmable Interrupt Controller.
5311 */
5312 rc = CFGMR3InsertNode(pDevices, "ioapic", &pDev); RC_CHECK();
5313 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5314 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5315 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5316 }
5317
5318 /*
5319 * RTC MC146818.
5320 */
5321 rc = CFGMR3InsertNode(pDevices, "mc146818", &pDev); RC_CHECK();
5322 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5323 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5324
5325 /*
5326 * VGA.
5327 */
5328 rc = CFGMR3InsertNode(pDevices, "vga", &pDev); RC_CHECK();
5329 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5330 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5331 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 2); RC_CHECK();
5332 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
5333 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5334 hrc = pMachine->COMGETTER(VRAMSize)(&cRamMBs); H();
5335 rc = CFGMR3InsertInteger(pCfg, "VRamSize", cRamMBs * _1M); RC_CHECK();
5336
5337 /* Custom VESA mode list */
5338 unsigned cModes = 0;
5339 for (unsigned iMode = 1; iMode <= 16; iMode++)
5340 {
5341 char szExtraDataKey[sizeof("CustomVideoModeXX")];
5342 RTStrPrintf(szExtraDataKey, sizeof(szExtraDataKey), "CustomVideoMode%d", iMode);
5343 hrc = pMachine->GetExtraData(Bstr(szExtraDataKey), &str); H();
5344 if (!str || !*str)
5345 break;
5346 STR_CONV();
5347 rc = CFGMR3InsertString(pCfg, szExtraDataKey, psz);
5348 STR_FREE();
5349 cModes++;
5350 }
5351 rc = CFGMR3InsertInteger(pCfg, "CustomVideoModes", cModes);
5352
5353 /* VESA height reduction */
5354 ULONG ulHeightReduction;
5355 IFramebuffer *pFramebuffer = pConsole->getDisplay()->getFramebuffer();
5356 if (pFramebuffer)
5357 {
5358 hrc = pFramebuffer->COMGETTER(HeightReduction)(&ulHeightReduction); H();
5359 }
5360 else
5361 {
5362 /* If framebuffer is not available, there is no height reduction. */
5363 ulHeightReduction = 0;
5364 }
5365 rc = CFGMR3InsertInteger(pCfg, "HeightReduction", ulHeightReduction); RC_CHECK();
5366
5367 /* Attach the display. */
5368 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5369 rc = CFGMR3InsertString(pLunL0, "Driver", "MainDisplay"); RC_CHECK();
5370 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5371 Display *pDisplay = pConsole->mDisplay;
5372 rc = CFGMR3InsertInteger(pCfg, "Object", (uintptr_t)pDisplay); RC_CHECK();
5373
5374 /*
5375 * IDE (update this when the main interface changes)
5376 */
5377 rc = CFGMR3InsertNode(pDevices, "piix3ide", &pDev); /* piix3 */ RC_CHECK();
5378 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5379 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5380 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 1); RC_CHECK();
5381 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 1); RC_CHECK();
5382 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5383
5384 /* Attach the status driver */
5385 rc = CFGMR3InsertNode(pInst, "LUN#999", &pLunL0); RC_CHECK();
5386 rc = CFGMR3InsertString(pLunL0, "Driver", "MainStatus"); RC_CHECK();
5387 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5388 rc = CFGMR3InsertInteger(pCfg, "papLeds", (uintptr_t)&pConsole->mapIDELeds[0]);RC_CHECK();
5389 rc = CFGMR3InsertInteger(pCfg, "First", 0); RC_CHECK();
5390 rc = CFGMR3InsertInteger(pCfg, "Last", 3); RC_CHECK();
5391
5392 /* Attach the harddisks */
5393 ComPtr<IHardDiskAttachmentCollection> hdaColl;
5394 hrc = pMachine->COMGETTER(HardDiskAttachments)(hdaColl.asOutParam()); H();
5395 ComPtr<IHardDiskAttachmentEnumerator> hdaEnum;
5396 hrc = hdaColl->Enumerate(hdaEnum.asOutParam()); H();
5397
5398 BOOL fMore = FALSE;
5399 while ( SUCCEEDED(hrc = hdaEnum->HasMore(&fMore))
5400 && fMore)
5401 {
5402 ComPtr<IHardDiskAttachment> hda;
5403 hrc = hdaEnum->GetNext(hda.asOutParam()); H();
5404 ComPtr<IHardDisk> hardDisk;
5405 hrc = hda->COMGETTER(HardDisk)(hardDisk.asOutParam()); H();
5406 DiskControllerType_T enmCtl;
5407 hrc = hda->COMGETTER(Controller)(&enmCtl); H();
5408 LONG lDev;
5409 hrc = hda->COMGETTER(DeviceNumber)(&lDev); H();
5410
5411 switch (enmCtl)
5412 {
5413 case DiskControllerType_IDE0Controller:
5414 i = 0;
5415 break;
5416 case DiskControllerType_IDE1Controller:
5417 i = 2;
5418 break;
5419 default:
5420 AssertMsgFailed(("invalid disk controller type: %d\n", enmCtl));
5421 return VERR_GENERAL_FAILURE;
5422 }
5423
5424 if (lDev < 0 || lDev >= 2)
5425 {
5426 AssertMsgFailed(("invalid controller device number: %d\n", lDev));
5427 return VERR_GENERAL_FAILURE;
5428 }
5429
5430 i = i + lDev;
5431
5432 char szLUN[16];
5433 RTStrPrintf(szLUN, sizeof(szLUN), "LUN#%d", i);
5434 rc = CFGMR3InsertNode(pInst, szLUN, &pLunL0); RC_CHECK();
5435 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
5436 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5437 rc = CFGMR3InsertString(pCfg, "Type", "HardDisk"); RC_CHECK();
5438 rc = CFGMR3InsertInteger(pCfg, "Mountable", 0); RC_CHECK();
5439
5440 HardDiskStorageType_T hddType;
5441 hardDisk->COMGETTER(StorageType)(&hddType);
5442 if (hddType == HardDiskStorageType_VirtualDiskImage)
5443 {
5444 ComPtr<IVirtualDiskImage> vdiDisk = hardDisk;
5445 AssertBreak (!vdiDisk.isNull(), hrc = E_FAIL);
5446
5447 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
5448 rc = CFGMR3InsertString(pLunL1, "Driver", "VBoxHDD"); RC_CHECK();
5449 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
5450 hrc = vdiDisk->COMGETTER(FilePath)(&str); H();
5451 STR_CONV();
5452 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
5453 STR_FREE();
5454
5455 /* Create an inversed tree of parents. */
5456 ComPtr<IHardDisk> parentHardDisk = hardDisk;
5457 for (PCFGMNODE pParent = pCfg;;)
5458 {
5459 ComPtr<IHardDisk> curHardDisk;
5460 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
5461 if (!curHardDisk)
5462 break;
5463
5464 vdiDisk = curHardDisk;
5465 AssertBreak (!vdiDisk.isNull(), hrc = E_FAIL);
5466
5467 PCFGMNODE pCur;
5468 rc = CFGMR3InsertNode(pParent, "Parent", &pCur); RC_CHECK();
5469 hrc = vdiDisk->COMGETTER(FilePath)(&str); H();
5470 STR_CONV();
5471 rc = CFGMR3InsertString(pCur, "Path", psz); RC_CHECK();
5472 STR_FREE();
5473 rc = CFGMR3InsertInteger(pCur, "ReadOnly", 1); RC_CHECK();
5474
5475 /* next */
5476 pParent = pCur;
5477 parentHardDisk = curHardDisk;
5478 }
5479 }
5480 else if (hddType == HardDiskStorageType_ISCSIHardDisk)
5481 {
5482 ComPtr<IISCSIHardDisk> iSCSIDisk = hardDisk;
5483 AssertBreak (!iSCSIDisk.isNull(), hrc = E_FAIL);
5484
5485 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
5486 rc = CFGMR3InsertString(pLunL1, "Driver", "iSCSI"); RC_CHECK();
5487 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
5488
5489 /* Set up the iSCSI initiator driver configuration. */
5490 hrc = iSCSIDisk->COMGETTER(Target)(&str); H();
5491 STR_CONV();
5492 rc = CFGMR3InsertString(pCfg, "TargetName", psz); RC_CHECK();
5493 STR_FREE();
5494
5495 // @todo currently there is no Initiator name config.
5496 rc = CFGMR3InsertString(pCfg, "InitiatorName", "iqn.2006-02.de.innotek.initiator"); RC_CHECK();
5497
5498 ULONG64 lun;
5499 hrc = iSCSIDisk->COMGETTER(Lun)(&lun); H();
5500 rc = CFGMR3InsertInteger(pCfg, "LUN", lun); RC_CHECK();
5501
5502 hrc = iSCSIDisk->COMGETTER(Server)(&str); H();
5503 STR_CONV();
5504 USHORT port;
5505 hrc = iSCSIDisk->COMGETTER(Port)(&port); H();
5506 if (port != 0)
5507 {
5508 char *pszTN;
5509 RTStrAPrintf(&pszTN, "%s:%u", psz, port);
5510 rc = CFGMR3InsertString(pCfg, "TargetAddress", pszTN); RC_CHECK();
5511 RTStrFree(pszTN);
5512 }
5513 else
5514 {
5515 rc = CFGMR3InsertString(pCfg, "TargetAddress", psz); RC_CHECK();
5516 }
5517 STR_FREE();
5518
5519 hrc = iSCSIDisk->COMGETTER(UserName)(&str); H();
5520 if (str)
5521 {
5522 STR_CONV();
5523 rc = CFGMR3InsertString(pCfg, "InitiatorUsername", psz); RC_CHECK();
5524 STR_FREE();
5525 }
5526
5527 hrc = iSCSIDisk->COMGETTER(Password)(&str); H();
5528 if (str)
5529 {
5530 STR_CONV();
5531 rc = CFGMR3InsertString(pCfg, "InitiatorSecret", psz); RC_CHECK();
5532 STR_FREE();
5533 }
5534
5535 // @todo currently there is no target username config.
5536 //rc = CFGMR3InsertString(pCfg, "TargetUsername", ""); RC_CHECK();
5537
5538 // @todo currently there is no target password config.
5539 //rc = CFGMR3InsertString(pCfg, "TargetSecret", ""); RC_CHECK();
5540
5541 /* The iSCSI initiator needs an attached iSCSI transport driver. */
5542 rc = CFGMR3InsertNode(pLunL1, "AttachedDriver", &pLunL2); RC_CHECK();
5543 rc = CFGMR3InsertString(pLunL2, "Driver", "iSCSITCP"); RC_CHECK();
5544 /* Currently the transport driver has no config options. */
5545 }
5546 else if (hddType == HardDiskStorageType_VMDKImage)
5547 {
5548 ComPtr<IVMDKImage> vmdkDisk = hardDisk;
5549 AssertBreak (!vmdkDisk.isNull(), hrc = E_FAIL);
5550
5551 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
5552#if 1 /* Enable new VD container code (and new VMDK), as the bugs are fixed. */
5553 rc = CFGMR3InsertString(pLunL1, "Driver", "VD"); RC_CHECK();
5554#else
5555 rc = CFGMR3InsertString(pLunL1, "Driver", "VmdkHDD"); RC_CHECK();
5556#endif
5557 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
5558 hrc = vmdkDisk->COMGETTER(FilePath)(&str); H();
5559 STR_CONV();
5560 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
5561 STR_FREE();
5562 }
5563 else
5564 AssertFailed();
5565 }
5566 H();
5567
5568 ComPtr<IDVDDrive> dvdDrive;
5569 hrc = pMachine->COMGETTER(DVDDrive)(dvdDrive.asOutParam()); H();
5570 if (dvdDrive)
5571 {
5572 // ASSUME: DVD drive is always attached to LUN#2 (i.e. secondary IDE master)
5573 rc = CFGMR3InsertNode(pInst, "LUN#2", &pLunL0); RC_CHECK();
5574 ComPtr<IHostDVDDrive> hostDvdDrive;
5575 hrc = dvdDrive->GetHostDrive(hostDvdDrive.asOutParam()); H();
5576 if (hostDvdDrive)
5577 {
5578 pConsole->meDVDState = DriveState_HostDriveCaptured;
5579 rc = CFGMR3InsertString(pLunL0, "Driver", "HostDVD"); RC_CHECK();
5580 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5581 hrc = hostDvdDrive->COMGETTER(Name)(&str); H();
5582 STR_CONV();
5583 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
5584 STR_FREE();
5585 BOOL fPassthrough;
5586 hrc = dvdDrive->COMGETTER(Passthrough)(&fPassthrough); H();
5587 rc = CFGMR3InsertInteger(pCfg, "Passthrough", !!fPassthrough); RC_CHECK();
5588 }
5589 else
5590 {
5591 pConsole->meDVDState = DriveState_NotMounted;
5592 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
5593 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5594 rc = CFGMR3InsertString(pCfg, "Type", "DVD"); RC_CHECK();
5595 rc = CFGMR3InsertInteger(pCfg, "Mountable", 1); RC_CHECK();
5596
5597 ComPtr<IDVDImage> dvdImage;
5598 hrc = dvdDrive->GetImage(dvdImage.asOutParam()); H();
5599 if (dvdImage)
5600 {
5601 pConsole->meDVDState = DriveState_ImageMounted;
5602 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
5603 rc = CFGMR3InsertString(pLunL1, "Driver", "MediaISO"); RC_CHECK();
5604 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
5605 hrc = dvdImage->COMGETTER(FilePath)(&str); H();
5606 STR_CONV();
5607 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
5608 STR_FREE();
5609 }
5610 }
5611 }
5612
5613 /*
5614 * Network adapters
5615 */
5616 rc = CFGMR3InsertNode(pDevices, "pcnet", &pDev); RC_CHECK();
5617 //rc = CFGMR3InsertNode(pDevices, "ne2000", &pDev); RC_CHECK();
5618 for (ULONG ulInstance = 0; ulInstance < SchemaDefs::NetworkAdapterCount; ulInstance++)
5619 {
5620 ComPtr<INetworkAdapter> networkAdapter;
5621 hrc = pMachine->GetNetworkAdapter(ulInstance, networkAdapter.asOutParam()); H();
5622 BOOL fEnabled = FALSE;
5623 hrc = networkAdapter->COMGETTER(Enabled)(&fEnabled); H();
5624 if (!fEnabled)
5625 continue;
5626
5627 char szInstance[4]; Assert(ulInstance <= 999);
5628 RTStrPrintf(szInstance, sizeof(szInstance), "%lu", ulInstance);
5629 rc = CFGMR3InsertNode(pDev, szInstance, &pInst); RC_CHECK();
5630 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5631 /* the first network card gets the PCI ID 3, the followings starting from 8 */
5632 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", !ulInstance ? 3 : ulInstance - 1 + 8); RC_CHECK();
5633 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
5634 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5635
5636 /*
5637 * The virtual hardware type.
5638 */
5639 NetworkAdapterType_T adapterType;
5640 hrc = networkAdapter->COMGETTER(AdapterType)(&adapterType); H();
5641 switch (adapterType)
5642 {
5643 case NetworkAdapterType_NetworkAdapterAm79C970A:
5644 rc = CFGMR3InsertInteger(pCfg, "Am79C973", 0); RC_CHECK();
5645 break;
5646 case NetworkAdapterType_NetworkAdapterAm79C973:
5647 rc = CFGMR3InsertInteger(pCfg, "Am79C973", 1); RC_CHECK();
5648 break;
5649 default:
5650 AssertMsgFailed(("Invalid network adapter type '%d' for slot '%d'",
5651 adapterType, ulInstance));
5652 return VERR_GENERAL_FAILURE;
5653 }
5654
5655 /*
5656 * Get the MAC address and convert it to binary representation
5657 */
5658 Bstr macAddr;
5659 hrc = networkAdapter->COMGETTER(MACAddress)(macAddr.asOutParam()); H();
5660 Assert(macAddr);
5661 Utf8Str macAddrUtf8 = macAddr;
5662 char *macStr = (char*)macAddrUtf8.raw();
5663 Assert(strlen(macStr) == 12);
5664 PDMMAC Mac;
5665 memset(&Mac, 0, sizeof(Mac));
5666 char *pMac = (char*)&Mac;
5667 for (uint32_t i = 0; i < 6; i++)
5668 {
5669 char c1 = *macStr++ - '0';
5670 if (c1 > 9)
5671 c1 -= 7;
5672 char c2 = *macStr++ - '0';
5673 if (c2 > 9)
5674 c2 -= 7;
5675 *pMac++ = ((c1 & 0x0f) << 4) | (c2 & 0x0f);
5676 }
5677 rc = CFGMR3InsertBytes(pCfg, "MAC", &Mac, sizeof(Mac)); RC_CHECK();
5678
5679 /*
5680 * Check if the cable is supposed to be unplugged
5681 */
5682 BOOL fCableConnected;
5683 hrc = networkAdapter->COMGETTER(CableConnected)(&fCableConnected); H();
5684 rc = CFGMR3InsertInteger(pCfg, "CableConnected", fCableConnected ? 1 : 0); RC_CHECK();
5685
5686 /*
5687 * Attach the status driver.
5688 */
5689 rc = CFGMR3InsertNode(pInst, "LUN#999", &pLunL0); RC_CHECK();
5690 rc = CFGMR3InsertString(pLunL0, "Driver", "MainStatus"); RC_CHECK();
5691 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5692 rc = CFGMR3InsertInteger(pCfg, "papLeds", (uintptr_t)&pConsole->mapNetworkLeds[ulInstance]); RC_CHECK();
5693
5694 /*
5695 * Enable the packet sniffer if requested.
5696 */
5697 BOOL fSniffer;
5698 hrc = networkAdapter->COMGETTER(TraceEnabled)(&fSniffer); H();
5699 if (fSniffer)
5700 {
5701 /* insert the sniffer filter driver. */
5702 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5703 rc = CFGMR3InsertString(pLunL0, "Driver", "NetSniffer"); RC_CHECK();
5704 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5705 hrc = networkAdapter->COMGETTER(TraceFile)(&str); H();
5706 if (str) /* check convention for indicating default file. */
5707 {
5708 STR_CONV();
5709 rc = CFGMR3InsertString(pCfg, "File", psz); RC_CHECK();
5710 STR_FREE();
5711 }
5712 }
5713
5714 NetworkAttachmentType_T networkAttachment;
5715 hrc = networkAdapter->COMGETTER(AttachmentType)(&networkAttachment); H();
5716 switch (networkAttachment)
5717 {
5718 case NetworkAttachmentType_NoNetworkAttachment:
5719 break;
5720
5721 case NetworkAttachmentType_NATNetworkAttachment:
5722 {
5723 if (fSniffer)
5724 {
5725 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0); RC_CHECK();
5726 }
5727 else
5728 {
5729 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5730 }
5731 rc = CFGMR3InsertString(pLunL0, "Driver", "NAT"); RC_CHECK();
5732 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5733 /* (Port forwarding goes here.) */
5734 break;
5735 }
5736
5737 case NetworkAttachmentType_HostInterfaceNetworkAttachment:
5738 {
5739 /*
5740 * Perform the attachment if required (don't return on error!)
5741 */
5742 hrc = pConsole->attachToHostInterface(networkAdapter);
5743 if (SUCCEEDED(hrc))
5744 {
5745#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
5746 Assert (pConsole->maTapFD[ulInstance] >= 0);
5747 if (pConsole->maTapFD[ulInstance] >= 0)
5748 {
5749 if (fSniffer)
5750 {
5751 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0); RC_CHECK();
5752 }
5753 else
5754 {
5755 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5756 }
5757 rc = CFGMR3InsertString(pLunL0, "Driver", "HostInterface"); RC_CHECK();
5758 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5759 rc = CFGMR3InsertInteger(pCfg, "FileHandle", pConsole->maTapFD[ulInstance]); RC_CHECK();
5760 }
5761#elif defined(RT_OS_WINDOWS)
5762 if (fSniffer)
5763 {
5764 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0); RC_CHECK();
5765 }
5766 else
5767 {
5768 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5769 }
5770 Bstr hostInterfaceName;
5771 hrc = networkAdapter->COMGETTER(HostInterface)(hostInterfaceName.asOutParam()); H();
5772 ComPtr<IHostNetworkInterfaceCollection> coll;
5773 hrc = host->COMGETTER(NetworkInterfaces)(coll.asOutParam()); H();
5774 ComPtr<IHostNetworkInterface> hostInterface;
5775 rc = coll->FindByName(hostInterfaceName, hostInterface.asOutParam());
5776 if (!SUCCEEDED(rc))
5777 {
5778 AssertMsgFailed(("Cannot get GUID for host interface '%ls'\n", hostInterfaceName));
5779 hrc = networkAdapter->Detach(); H();
5780 }
5781 else
5782 {
5783 rc = CFGMR3InsertString(pLunL0, "Driver", "HostInterface"); RC_CHECK();
5784 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5785 rc = CFGMR3InsertString(pCfg, "HostInterfaceName", Utf8Str(hostInterfaceName)); RC_CHECK();
5786 Guid hostIFGuid;
5787 hrc = hostInterface->COMGETTER(Id)(hostIFGuid.asOutParam()); H();
5788 char szDriverGUID[256] = {0};
5789 /* add curly brackets */
5790 szDriverGUID[0] = '{';
5791 strcpy(szDriverGUID + 1, hostIFGuid.toString().raw());
5792 strcat(szDriverGUID, "}");
5793 rc = CFGMR3InsertBytes(pCfg, "GUID", szDriverGUID, sizeof(szDriverGUID)); RC_CHECK();
5794 }
5795#else
5796# error "Port me"
5797#endif
5798 }
5799 else
5800 {
5801 switch (hrc)
5802 {
5803#ifdef RT_OS_LINUX
5804 case VERR_ACCESS_DENIED:
5805 return VMSetError(pVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
5806 "Failed to open '/dev/net/tun' for read/write access. Please check the "
5807 "permissions of that node. Either do 'chmod 0666 /dev/net/tun' or "
5808 "change the group of that node and get member of that group. Make "
5809 "sure that these changes are permanently in particular if you are "
5810 "using udev"));
5811#endif /* RT_OS_LINUX */
5812 default:
5813 AssertMsgFailed(("Could not attach to host interface! Bad!\n"));
5814 return VMSetError(pVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
5815 "Failed to initialize Host Interface Networking"));
5816 }
5817 }
5818 break;
5819 }
5820
5821 case NetworkAttachmentType_InternalNetworkAttachment:
5822 {
5823 hrc = networkAdapter->COMGETTER(InternalNetwork)(&str); H();
5824 STR_CONV();
5825 if (psz && *psz)
5826 {
5827 if (fSniffer)
5828 {
5829 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0); RC_CHECK();
5830 }
5831 else
5832 {
5833 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5834 }
5835 rc = CFGMR3InsertString(pLunL0, "Driver", "IntNet"); RC_CHECK();
5836 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5837 rc = CFGMR3InsertString(pCfg, "Network", psz); RC_CHECK();
5838 }
5839 STR_FREE();
5840 break;
5841 }
5842
5843 default:
5844 AssertMsgFailed(("should not get here!\n"));
5845 break;
5846 }
5847 }
5848
5849 /*
5850 * Serial (UART) Ports
5851 */
5852 rc = CFGMR3InsertNode(pDevices, "serial", &pDev); RC_CHECK();
5853 for (ULONG ulInstance = 0; ulInstance < SchemaDefs::SerialPortCount; ulInstance++)
5854 {
5855 ComPtr<ISerialPort> serialPort;
5856 hrc = pMachine->GetSerialPort (ulInstance, serialPort.asOutParam()); H();
5857 BOOL fEnabled = FALSE;
5858 if (serialPort)
5859 hrc = serialPort->COMGETTER(Enabled)(&fEnabled); H();
5860 if (!fEnabled)
5861 continue;
5862
5863 char szInstance[4]; Assert(ulInstance <= 999);
5864 RTStrPrintf(szInstance, sizeof(szInstance), "%lu", ulInstance);
5865
5866 rc = CFGMR3InsertNode(pDev, szInstance, &pInst); RC_CHECK();
5867 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5868
5869 ULONG uIRQ, uIOBase;
5870 Bstr pipe;
5871 BOOL fServer;
5872 hrc = serialPort->COMGETTER(IRQ)(&uIRQ); H();
5873 hrc = serialPort->COMGETTER(IOBase)(&uIOBase); H();
5874 hrc = serialPort->COMGETTER(Pipe)(pipe.asOutParam()); H();
5875 hrc = serialPort->COMGETTER(Server)(&fServer); H();
5876 rc = CFGMR3InsertInteger(pCfg, "IRQ", uIRQ); RC_CHECK();
5877 rc = CFGMR3InsertInteger(pCfg, "IOBase", uIOBase); RC_CHECK();
5878 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5879 rc = CFGMR3InsertString(pLunL0, "Driver", "Char"); RC_CHECK();
5880 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
5881 rc = CFGMR3InsertString(pLunL1, "Driver", "NamedPipe"); RC_CHECK();
5882 rc = CFGMR3InsertNode(pLunL1, "Config", &pLunL2); RC_CHECK();
5883 rc = CFGMR3InsertString(pLunL2, "Location", Utf8Str(pipe)); RC_CHECK();
5884 rc = CFGMR3InsertInteger(pLunL2, "IsServer", fServer); RC_CHECK();
5885 }
5886
5887 /*
5888 * Parallel (LPT) Ports
5889 */
5890 rc = CFGMR3InsertNode(pDevices, "parallel", &pDev); RC_CHECK();
5891 for (ULONG ulInstance = 0; ulInstance < SchemaDefs::ParallelPortCount; ulInstance++)
5892 {
5893 ComPtr<IParallelPort> parallelPort;
5894 hrc = pMachine->GetParallelPort (ulInstance, parallelPort.asOutParam()); H();
5895 BOOL fEnabled = FALSE;
5896 if (parallelPort)
5897 hrc = parallelPort->COMGETTER(Enabled)(&fEnabled); H();
5898 if (!fEnabled)
5899 continue;
5900
5901 char szInstance[4]; Assert(ulInstance <= 999);
5902 RTStrPrintf(szInstance, sizeof(szInstance), "%lu", ulInstance);
5903
5904 rc = CFGMR3InsertNode(pDev, szInstance, &pInst); RC_CHECK();
5905 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5906
5907 ULONG uIRQ, uIOBase;
5908 Bstr DevicePath;
5909 hrc = parallelPort->COMGETTER(IRQ)(&uIRQ); H();
5910 hrc = parallelPort->COMGETTER(IOBase)(&uIOBase); H();
5911 hrc = parallelPort->COMGETTER(DevicePath)(DevicePath.asOutParam()); H();
5912 rc = CFGMR3InsertInteger(pCfg, "IRQ", uIRQ); RC_CHECK();
5913 rc = CFGMR3InsertInteger(pCfg, "IOBase", uIOBase); RC_CHECK();
5914 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5915 rc = CFGMR3InsertString(pLunL0, "Driver", "HostParallel"); RC_CHECK();
5916 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
5917 rc = CFGMR3InsertString(pLunL1, "DevicePath", Utf8Str(DevicePath)); RC_CHECK();
5918 }
5919
5920 /*
5921 * VMM Device
5922 */
5923 rc = CFGMR3InsertNode(pDevices, "VMMDev", &pDev); RC_CHECK();
5924 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5925 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5926 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5927 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 4); RC_CHECK();
5928 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
5929
5930 /* the VMM device's Main driver */
5931 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5932 rc = CFGMR3InsertString(pLunL0, "Driver", "MainVMMDev"); RC_CHECK();
5933 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5934 VMMDev *pVMMDev = pConsole->mVMMDev;
5935 rc = CFGMR3InsertInteger(pCfg, "Object", (uintptr_t)pVMMDev); RC_CHECK();
5936
5937 /*
5938 * Attach the status driver.
5939 */
5940 rc = CFGMR3InsertNode(pInst, "LUN#999", &pLunL0); RC_CHECK();
5941 rc = CFGMR3InsertString(pLunL0, "Driver", "MainStatus"); RC_CHECK();
5942 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5943 rc = CFGMR3InsertInteger(pCfg, "papLeds", (uintptr_t)&pConsole->mapSharedFolderLed); RC_CHECK();
5944 rc = CFGMR3InsertInteger(pCfg, "First", 0); RC_CHECK();
5945 rc = CFGMR3InsertInteger(pCfg, "Last", 0); RC_CHECK();
5946
5947 /*
5948 * Audio Sniffer Device
5949 */
5950 rc = CFGMR3InsertNode(pDevices, "AudioSniffer", &pDev); RC_CHECK();
5951 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
5952 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
5953
5954 /* the Audio Sniffer device's Main driver */
5955 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5956 rc = CFGMR3InsertString(pLunL0, "Driver", "MainAudioSniffer"); RC_CHECK();
5957 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5958 AudioSniffer *pAudioSniffer = pConsole->mAudioSniffer;
5959 rc = CFGMR3InsertInteger(pCfg, "Object", (uintptr_t)pAudioSniffer); RC_CHECK();
5960
5961 /*
5962 * AC'97 ICH audio
5963 */
5964 ComPtr<IAudioAdapter> audioAdapter;
5965 hrc = pMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam()); H();
5966 BOOL enabled = FALSE;
5967 if (audioAdapter)
5968 {
5969 hrc = audioAdapter->COMGETTER(Enabled)(&enabled); H();
5970 }
5971 if (enabled)
5972 {
5973 rc = CFGMR3InsertNode(pDevices, "ichac97", &pDev); /* ichac97 */
5974 rc = CFGMR3InsertNode(pDev, "0", &pInst);
5975 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
5976 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 5); RC_CHECK();
5977 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
5978 rc = CFGMR3InsertNode(pInst, "Config", &pCfg);
5979
5980 /* the Audio driver */
5981 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
5982 rc = CFGMR3InsertString(pLunL0, "Driver", "AUDIO"); RC_CHECK();
5983 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
5984 AudioDriverType_T audioDriver;
5985 hrc = audioAdapter->COMGETTER(AudioDriver)(&audioDriver); H();
5986 switch (audioDriver)
5987 {
5988 case AudioDriverType_NullAudioDriver:
5989 {
5990 rc = CFGMR3InsertString(pCfg, "AudioDriver", "null"); RC_CHECK();
5991 break;
5992 }
5993#ifdef RT_OS_WINDOWS
5994#ifdef VBOX_WITH_WINMM
5995 case AudioDriverType_WINMMAudioDriver:
5996 {
5997 rc = CFGMR3InsertString(pCfg, "AudioDriver", "winmm"); RC_CHECK();
5998 break;
5999 }
6000#endif
6001 case AudioDriverType_DSOUNDAudioDriver:
6002 {
6003 rc = CFGMR3InsertString(pCfg, "AudioDriver", "dsound"); RC_CHECK();
6004 break;
6005 }
6006#endif /* RT_OS_WINDOWS */
6007#ifdef RT_OS_LINUX
6008 case AudioDriverType_OSSAudioDriver:
6009 {
6010 rc = CFGMR3InsertString(pCfg, "AudioDriver", "oss"); RC_CHECK();
6011 break;
6012 }
6013# ifdef VBOX_WITH_ALSA
6014 case AudioDriverType_ALSAAudioDriver:
6015 {
6016 rc = CFGMR3InsertString(pCfg, "AudioDriver", "alsa"); RC_CHECK();
6017 break;
6018 }
6019# endif
6020#endif /* RT_OS_LINUX */
6021#ifdef RT_OS_DARWIN
6022 case AudioDriverType_CoreAudioDriver:
6023 {
6024 rc = CFGMR3InsertString(pCfg, "AudioDriver", "coreaudio"); RC_CHECK();
6025 break;
6026 }
6027#endif
6028 }
6029 }
6030
6031 /*
6032 * The USB Controller.
6033 */
6034 ComPtr<IUSBController> USBCtlPtr;
6035 hrc = pMachine->COMGETTER(USBController)(USBCtlPtr.asOutParam());
6036 if (USBCtlPtr)
6037 {
6038 BOOL fEnabled;
6039 hrc = USBCtlPtr->COMGETTER(Enabled)(&fEnabled); H();
6040 if (fEnabled)
6041 {
6042 rc = CFGMR3InsertNode(pDevices, "usb-ohci", &pDev); RC_CHECK();
6043 rc = CFGMR3InsertNode(pDev, "0", &pInst); RC_CHECK();
6044 rc = CFGMR3InsertNode(pInst, "Config", &pCfg); RC_CHECK();
6045 rc = CFGMR3InsertInteger(pInst, "Trusted", 1); /* boolean */ RC_CHECK();
6046 rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", 6); RC_CHECK();
6047 rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo", 0); RC_CHECK();
6048
6049 rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0); RC_CHECK();
6050 rc = CFGMR3InsertString(pLunL0, "Driver", "VUSBRootHub"); RC_CHECK();
6051 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
6052
6053 /*
6054 * Attach the status driver.
6055 */
6056 rc = CFGMR3InsertNode(pInst, "LUN#999", &pLunL0); RC_CHECK();
6057 rc = CFGMR3InsertString(pLunL0, "Driver", "MainStatus"); RC_CHECK();
6058 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
6059 rc = CFGMR3InsertInteger(pCfg, "papLeds", (uintptr_t)&pConsole->mapUSBLed);RC_CHECK();
6060 rc = CFGMR3InsertInteger(pCfg, "First", 0); RC_CHECK();
6061 rc = CFGMR3InsertInteger(pCfg, "Last", 0); RC_CHECK();
6062 }
6063 }
6064
6065 /*
6066 * Clipboard
6067 */
6068 {
6069 ClipboardMode_T mode = ClipboardMode_ClipDisabled;
6070 hrc = pMachine->COMGETTER(ClipboardMode) (&mode); H();
6071
6072 if (mode != ClipboardMode_ClipDisabled)
6073 {
6074 /* Load the service */
6075 rc = pConsole->mVMMDev->hgcmLoadService ("VBoxSharedClipboard", "VBoxSharedClipboard");
6076
6077 if (VBOX_FAILURE (rc))
6078 {
6079 LogRel(("VBoxSharedClipboard is not available. rc = %Vrc\n", rc));
6080 /* That is not a fatal failure. */
6081 rc = VINF_SUCCESS;
6082 }
6083 else
6084 {
6085 /* Setup the service. */
6086 VBOXHGCMSVCPARM parm;
6087
6088 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
6089
6090 switch (mode)
6091 {
6092 default:
6093 case ClipboardMode_ClipDisabled:
6094 {
6095 LogRel(("VBoxSharedClipboard mode: Off\n"));
6096 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_OFF;
6097 break;
6098 }
6099 case ClipboardMode_ClipGuestToHost:
6100 {
6101 LogRel(("VBoxSharedClipboard mode: Guest to Host\n"));
6102 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_GUEST_TO_HOST;
6103 break;
6104 }
6105 case ClipboardMode_ClipHostToGuest:
6106 {
6107 LogRel(("VBoxSharedClipboard mode: Host to Guest\n"));
6108 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_HOST_TO_GUEST;
6109 break;
6110 }
6111 case ClipboardMode_ClipBidirectional:
6112 {
6113 LogRel(("VBoxSharedClipboard mode: Bidirectional\n"));
6114 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_BIDIRECTIONAL;
6115 break;
6116 }
6117 }
6118
6119 pConsole->mVMMDev->hgcmHostCall ("VBoxSharedClipboard", VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE, 1, &parm);
6120
6121 Log(("Set VBoxSharedClipboard mode\n"));
6122 }
6123 }
6124 }
6125
6126 /*
6127 * CFGM overlay handling.
6128 *
6129 * Here we check the extra data entries for CFGM values
6130 * and create the nodes and insert the values on the fly. Existing
6131 * values will be removed and reinserted. If a value is a valid number,
6132 * it will be inserted as a number, otherwise as a string.
6133 *
6134 * We first perform a run on global extra data, then on the machine
6135 * extra data to support global settings with local overrides.
6136 *
6137 */
6138 Bstr strExtraDataKey;
6139 bool fGlobalExtraData = true;
6140 for (;;)
6141 {
6142 Bstr strNextExtraDataKey;
6143 Bstr strExtraDataValue;
6144
6145 /* get the next key */
6146 if (fGlobalExtraData)
6147 hrc = virtualBox->GetNextExtraDataKey(strExtraDataKey, strNextExtraDataKey.asOutParam(),
6148 strExtraDataValue.asOutParam());
6149 else
6150 hrc = pMachine->GetNextExtraDataKey(strExtraDataKey, strNextExtraDataKey.asOutParam(),
6151 strExtraDataValue.asOutParam());
6152
6153 /* stop if for some reason there's nothing more to request */
6154 if (FAILED(hrc) || !strNextExtraDataKey)
6155 {
6156 /* if we're out of global keys, continue with machine, otherwise we're done */
6157 if (fGlobalExtraData)
6158 {
6159 fGlobalExtraData = false;
6160 strExtraDataKey.setNull();
6161 continue;
6162 }
6163 break;
6164 }
6165
6166 strExtraDataKey = strNextExtraDataKey;
6167 Utf8Str strExtraDataKeyUtf8 = Utf8Str(strExtraDataKey);
6168
6169 /* we only care about keys starting with "VBoxInternal/" */
6170 if (strncmp(strExtraDataKeyUtf8.raw(), "VBoxInternal/", 13) != 0)
6171 continue;
6172 char *pszExtraDataKey = (char*)strExtraDataKeyUtf8.raw() + 13;
6173
6174 /* the key will be in the format "Node1/Node2/Value" or simply "Value". */
6175 PCFGMNODE pNode;
6176 char *pszCFGMValueName = strrchr(pszExtraDataKey, '/');
6177 if (pszCFGMValueName)
6178 {
6179 /* terminate the node and advance to the value */
6180 *pszCFGMValueName = '\0';
6181 pszCFGMValueName++;
6182
6183 /* does the node already exist? */
6184 pNode = CFGMR3GetChild(pRoot, pszExtraDataKey);
6185 if (pNode)
6186 {
6187 /* the value might already exist, remove it to be safe */
6188 CFGMR3RemoveValue(pNode, pszCFGMValueName);
6189 }
6190 else
6191 {
6192 /* create the node */
6193 rc = CFGMR3InsertNode(pRoot, pszExtraDataKey, &pNode);
6194 AssertMsgRC(rc, ("failed to insert node '%s'\n", pszExtraDataKey));
6195 if (VBOX_FAILURE(rc) || !pNode)
6196 continue;
6197 }
6198 }
6199 else
6200 {
6201 pNode = pRoot;
6202 pszCFGMValueName = pszExtraDataKey;
6203 pszExtraDataKey--;
6204
6205 /* the value might already exist, remove it to be safe */
6206 CFGMR3RemoveValue(pNode, pszCFGMValueName);
6207 }
6208
6209 /* now let's have a look at the value */
6210 Utf8Str strCFGMValueUtf8 = Utf8Str(strExtraDataValue);
6211 const char *pszCFGMValue = strCFGMValueUtf8.raw();
6212 /* empty value means remove value which we've already done */
6213 if (pszCFGMValue && *pszCFGMValue)
6214 {
6215 /* if it's a valid number, we'll insert it as such, otherwise string */
6216 uint64_t u64Value;
6217 if (RTStrToUInt64Ex(pszCFGMValue, NULL, 0, &u64Value) == VINF_SUCCESS)
6218 {
6219 rc = CFGMR3InsertInteger(pNode, pszCFGMValueName, u64Value);
6220 }
6221 else
6222 {
6223 rc = CFGMR3InsertString(pNode, pszCFGMValueName, pszCFGMValue);
6224 }
6225 AssertMsgRC(rc, ("failed to insert CFGM value '%s' to key '%s'\n", pszCFGMValue, pszExtraDataKey));
6226 }
6227 }
6228
6229#undef H
6230#undef RC_CHECK
6231#undef STR_FREE
6232#undef STR_CONV
6233
6234 /* Register VM state change handler */
6235 int rc2 = VMR3AtStateRegister (pVM, Console::vmstateChangeCallback, pConsole);
6236 AssertRC (rc2);
6237 if (VBOX_SUCCESS (rc))
6238 rc = rc2;
6239
6240 /* Register VM runtime error handler */
6241 rc2 = VMR3AtRuntimeErrorRegister (pVM, Console::setVMRuntimeErrorCallback, pConsole);
6242 AssertRC (rc2);
6243 if (VBOX_SUCCESS (rc))
6244 rc = rc2;
6245
6246 /* Save the VM pointer in the machine object */
6247 pConsole->mpVM = pVM;
6248
6249 LogFlowFunc (("vrc = %Vrc\n", rc));
6250 LogFlowFuncLeave();
6251
6252 return rc;
6253}
6254
6255/**
6256 * Call the initialisation script for a dynamic TAP interface.
6257 *
6258 * The initialisation script should create a TAP interface, set it up and write its name to
6259 * standard output followed by a carriage return. Anything further written to standard
6260 * output will be ignored. If it returns a non-zero exit code, or does not write an
6261 * intelligable interface name to standard output, it will be treated as having failed.
6262 * For now, this method only works on Linux.
6263 *
6264 * @returns COM status code
6265 * @param tapDevice string to store the name of the tap device created to
6266 * @param tapSetupApplication the name of the setup script
6267 */
6268HRESULT Console::callTapSetupApplication(bool isStatic, RTFILE tapFD, Bstr &tapDevice,
6269 Bstr &tapSetupApplication)
6270{
6271 LogFlowThisFunc(("\n"));
6272#ifdef RT_OS_LINUX
6273 /* Command line to start the script with. */
6274 char szCommand[4096];
6275 /* Result code */
6276 int rc;
6277
6278 /* Get the script name. */
6279 Utf8Str tapSetupAppUtf8(tapSetupApplication), tapDeviceUtf8(tapDevice);
6280 RTStrPrintf(szCommand, sizeof(szCommand), "%s %d %s", tapSetupAppUtf8.raw(),
6281 isStatic ? tapFD : 0, isStatic ? tapDeviceUtf8.raw() : "");
6282 /*
6283 * Create the process and read its output.
6284 */
6285 Log2(("About to start the TAP setup script with the following command line: %s\n",
6286 szCommand));
6287 FILE *pfScriptHandle = popen(szCommand, "r");
6288 if (pfScriptHandle == 0)
6289 {
6290 int iErr = errno;
6291 LogRel(("Failed to start the TAP interface setup script %s, error text: %s\n",
6292 szCommand, strerror(iErr)));
6293 LogFlowThisFunc(("rc=E_FAIL\n"));
6294 return setError(E_FAIL, tr ("Failed to run the host networking set up command %s: %s"),
6295 szCommand, strerror(iErr));
6296 }
6297 /* If we are using a dynamic TAP interface, we need to get the interface name. */
6298 if (!isStatic)
6299 {
6300 /* Buffer to read the application output to. It doesn't have to be long, as we are only
6301 interested in the first few (normally 5 or 6) bytes. */
6302 char acBuffer[64];
6303 /* The length of the string returned by the application. We only accept strings of 63
6304 characters or less. */
6305 size_t cBufSize;
6306
6307 /* Read the name of the device from the application. */
6308 fgets(acBuffer, sizeof(acBuffer), pfScriptHandle);
6309 cBufSize = strlen(acBuffer);
6310 /* The script must return the name of the interface followed by a carriage return as the
6311 first line of its output. We need a null-terminated string. */
6312 if ((cBufSize < 2) || (acBuffer[cBufSize - 1] != '\n'))
6313 {
6314 pclose(pfScriptHandle);
6315 LogRel(("The TAP interface setup script did not return the name of a TAP device.\n"));
6316 LogFlowThisFunc(("rc=E_FAIL\n"));
6317 return setError(E_FAIL, tr ("The host networking set up command did not supply an interface name"));
6318 }
6319 /* Overwrite the terminating newline character. */
6320 acBuffer[cBufSize - 1] = 0;
6321 tapDevice = acBuffer;
6322 }
6323 rc = pclose(pfScriptHandle);
6324 if (!WIFEXITED(rc))
6325 {
6326 LogRel(("The TAP interface setup script terminated abnormally.\n"));
6327 LogFlowThisFunc(("rc=E_FAIL\n"));
6328 return setError(E_FAIL, tr ("The host networking set up command did not run correctly"));
6329 }
6330 if (WEXITSTATUS(rc) != 0)
6331 {
6332 LogRel(("The TAP interface setup script returned a non-zero exit code.\n"));
6333 LogFlowThisFunc(("rc=E_FAIL\n"));
6334 return setError(E_FAIL, tr ("The host networking set up command returned a non-zero exit code"));
6335 }
6336 LogFlowThisFunc(("rc=S_OK\n"));
6337 return S_OK;
6338#else /* RT_OS_LINUX not defined */
6339 LogFlowThisFunc(("rc=E_NOTIMPL\n"));
6340 return E_NOTIMPL; /* not yet supported */
6341#endif
6342}
6343
6344/**
6345 * Helper function to handle host interface device creation and attachment.
6346 *
6347 * @param networkAdapter the network adapter which attachment should be reset
6348 * @return COM status code
6349 *
6350 * @note The caller must lock this object for writing.
6351 */
6352HRESULT Console::attachToHostInterface(INetworkAdapter *networkAdapter)
6353{
6354 LogFlowThisFunc(("\n"));
6355 /* sanity check */
6356 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
6357
6358#ifdef DEBUG
6359 /* paranoia */
6360 NetworkAttachmentType_T attachment;
6361 networkAdapter->COMGETTER(AttachmentType)(&attachment);
6362 Assert(attachment == NetworkAttachmentType_HostInterfaceNetworkAttachment);
6363#endif /* DEBUG */
6364
6365 HRESULT rc = S_OK;
6366
6367#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
6368 ULONG slot = 0;
6369 rc = networkAdapter->COMGETTER(Slot)(&slot);
6370 AssertComRC(rc);
6371
6372 /*
6373 * Try get the FD.
6374 */
6375 LONG ltapFD;
6376 rc = networkAdapter->COMGETTER(TAPFileDescriptor)(&ltapFD);
6377 if (SUCCEEDED(rc))
6378 maTapFD[slot] = (RTFILE)ltapFD;
6379 else
6380 maTapFD[slot] = NIL_RTFILE;
6381
6382 /*
6383 * Are we supposed to use an existing TAP interface?
6384 */
6385 if (maTapFD[slot] != NIL_RTFILE)
6386 {
6387 /* nothing to do */
6388 Assert(ltapFD >= 0);
6389 Assert((LONG)maTapFD[slot] == ltapFD);
6390 rc = S_OK;
6391 }
6392 else
6393#endif /* VBOX_WITH_UNIXY_TAP_NETWORKING */
6394 {
6395 /*
6396 * Allocate a host interface device
6397 */
6398#ifdef RT_OS_WINDOWS
6399 /* nothing to do */
6400 int rcVBox = VINF_SUCCESS;
6401#elif defined(RT_OS_LINUX)
6402 int rcVBox = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
6403 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
6404 if (VBOX_SUCCESS(rcVBox))
6405 {
6406 /*
6407 * Set/obtain the tap interface.
6408 */
6409 bool isStatic = false;
6410 struct ifreq IfReq;
6411 memset(&IfReq, 0, sizeof(IfReq));
6412 /* The name of the TAP interface we are using and the TAP setup script resp. */
6413 Bstr tapDeviceName, tapSetupApplication;
6414 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
6415 if (FAILED(rc))
6416 {
6417 tapDeviceName.setNull(); /* Is this necessary? */
6418 }
6419 else if (!tapDeviceName.isEmpty())
6420 {
6421 isStatic = true;
6422 /* If we are using a static TAP device then try to open it. */
6423 Utf8Str str(tapDeviceName);
6424 if (str.length() <= sizeof(IfReq.ifr_name))
6425 strcpy(IfReq.ifr_name, str.raw());
6426 else
6427 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
6428 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
6429 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
6430 if (rcVBox != 0)
6431 {
6432 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
6433 rc = setError(E_FAIL, tr ("Failed to open the host network interface %ls"),
6434 tapDeviceName.raw());
6435 }
6436 }
6437 if (SUCCEEDED(rc))
6438 {
6439 networkAdapter->COMGETTER(TAPSetupApplication)(tapSetupApplication.asOutParam());
6440 if (tapSetupApplication.isEmpty())
6441 {
6442 if (tapDeviceName.isEmpty())
6443 {
6444 LogRel(("No setup application was supplied for the TAP interface.\n"));
6445 rc = setError(E_FAIL, tr ("No setup application was supplied for the host networking interface"));
6446 }
6447 }
6448 else
6449 {
6450 rc = callTapSetupApplication(isStatic, maTapFD[slot], tapDeviceName,
6451 tapSetupApplication);
6452 }
6453 }
6454 if (SUCCEEDED(rc))
6455 {
6456 if (!isStatic)
6457 {
6458 Utf8Str str(tapDeviceName);
6459 if (str.length() <= sizeof(IfReq.ifr_name))
6460 strcpy(IfReq.ifr_name, str.raw());
6461 else
6462 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
6463 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
6464 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
6465 if (rcVBox != 0)
6466 {
6467 LogRel(("Failed to open the host network interface %ls returned by the setup script", tapDeviceName.raw()));
6468 rc = setError(E_FAIL, tr ("Failed to open the host network interface %ls returned by the setup script"), tapDeviceName.raw());
6469 }
6470 }
6471 if (SUCCEEDED(rc))
6472 {
6473 /*
6474 * Make it pollable.
6475 */
6476 if (fcntl(maTapFD[slot], F_SETFL, O_NONBLOCK) != -1)
6477 {
6478 Log(("attachToHostInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
6479
6480 /*
6481 * Here is the right place to communicate the TAP file descriptor and
6482 * the host interface name to the server if/when it becomes really
6483 * necessary.
6484 */
6485 maTAPDeviceName[slot] = tapDeviceName;
6486 rcVBox = VINF_SUCCESS;
6487 }
6488 else
6489 {
6490 int iErr = errno;
6491
6492 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
6493 rcVBox = VERR_HOSTIF_BLOCKING;
6494 rc = setError(E_FAIL, tr ("could not set up the host networking device for non blocking access: %s"),
6495 strerror(errno));
6496 }
6497 }
6498 }
6499 }
6500 else
6501 {
6502 LogRel(("Configuration error: Failed to open /dev/net/tun rc=%Vrc\n", rcVBox));
6503 switch (rcVBox)
6504 {
6505 case VERR_ACCESS_DENIED:
6506 /* will be handled by our caller */
6507 rc = rcVBox;
6508 break;
6509 default:
6510 rc = setError(E_FAIL, tr ("Could not set up the host networking device: %Vrc"), rcVBox);
6511 break;
6512 }
6513 }
6514#elif defined(RT_OS_DARWIN)
6515 /** @todo Implement tap networking for Darwin. */
6516 int rcVBox = VERR_NOT_IMPLEMENTED;
6517#elif defined(RT_OS_OS2)
6518 /** @todo Implement tap networking for OS/2. */
6519 int rcVBox = VERR_NOT_IMPLEMENTED;
6520#elif defined(VBOX_WITH_UNIXY_TAP_NETWORKING)
6521# error "PORTME: Implement OS specific TAP interface open/creation."
6522#else
6523# error "Unknown host OS"
6524#endif
6525 /* in case of failure, cleanup. */
6526 if (VBOX_FAILURE(rcVBox) && SUCCEEDED(rc))
6527 {
6528 LogRel(("General failure attaching to host interface\n"));
6529 rc = setError(E_FAIL, tr ("General failure attaching to host interface"));
6530 }
6531 }
6532 LogFlowThisFunc(("rc=%d\n", rc));
6533 return rc;
6534}
6535
6536/**
6537 * Helper function to handle detachment from a host interface
6538 *
6539 * @param networkAdapter the network adapter which attachment should be reset
6540 * @return COM status code
6541 *
6542 * @note The caller must lock this object for writing.
6543 */
6544HRESULT Console::detachFromHostInterface(INetworkAdapter *networkAdapter)
6545{
6546 /* sanity check */
6547 LogFlowThisFunc(("\n"));
6548 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
6549
6550 HRESULT rc = S_OK;
6551#ifdef DEBUG
6552 /* paranoia */
6553 NetworkAttachmentType_T attachment;
6554 networkAdapter->COMGETTER(AttachmentType)(&attachment);
6555 Assert(attachment == NetworkAttachmentType_HostInterfaceNetworkAttachment);
6556#endif /* DEBUG */
6557
6558#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
6559
6560 ULONG slot = 0;
6561 rc = networkAdapter->COMGETTER(Slot)(&slot);
6562 AssertComRC(rc);
6563
6564 /* is there an open TAP device? */
6565 if (maTapFD[slot] != NIL_RTFILE)
6566 {
6567 /*
6568 * Close the file handle.
6569 */
6570 Bstr tapDeviceName, tapTerminateApplication;
6571 bool isStatic = true;
6572 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
6573 if (FAILED(rc) || tapDeviceName.isEmpty())
6574 {
6575 /* If the name is not empty, this is a dynamic TAP device, so close it now,
6576 so that the termination script can remove the interface. Otherwise we still
6577 need the FD to pass to the termination script. */
6578 isStatic = false;
6579 int rcVBox = RTFileClose(maTapFD[slot]);
6580 AssertRC(rcVBox);
6581 maTapFD[slot] = NIL_RTFILE;
6582 }
6583 /*
6584 * Execute the termination command.
6585 */
6586 networkAdapter->COMGETTER(TAPTerminateApplication)(tapTerminateApplication.asOutParam());
6587 if (tapTerminateApplication)
6588 {
6589 /* Get the program name. */
6590 Utf8Str tapTermAppUtf8(tapTerminateApplication);
6591
6592 /* Build the command line. */
6593 char szCommand[4096];
6594 RTStrPrintf(szCommand, sizeof(szCommand), "%s %d %s", tapTermAppUtf8.raw(),
6595 isStatic ? maTapFD[slot] : 0, maTAPDeviceName[slot].raw());
6596
6597 /*
6598 * Create the process and wait for it to complete.
6599 */
6600 Log(("Calling the termination command: %s\n", szCommand));
6601 int rcCommand = system(szCommand);
6602 if (rcCommand == -1)
6603 {
6604 LogRel(("Failed to execute the clean up script for the TAP interface"));
6605 rc = setError(E_FAIL, tr ("Failed to execute the clean up script for the TAP interface"));
6606 }
6607 if (!WIFEXITED(rc))
6608 {
6609 LogRel(("The TAP interface clean up script terminated abnormally.\n"));
6610 rc = setError(E_FAIL, tr ("The TAP interface clean up script terminated abnormally"));
6611 }
6612 if (WEXITSTATUS(rc) != 0)
6613 {
6614 LogRel(("The TAP interface clean up script returned a non-zero exit code.\n"));
6615 rc = setError(E_FAIL, tr ("The TAP interface clean up script returned a non-zero exit code"));
6616 }
6617 }
6618
6619 if (isStatic)
6620 {
6621 /* If we are using a static TAP device, we close it now, after having called the
6622 termination script. */
6623 int rcVBox = RTFileClose(maTapFD[slot]);
6624 AssertRC(rcVBox);
6625 }
6626 /* the TAP device name and handle are no longer valid */
6627 maTapFD[slot] = NIL_RTFILE;
6628 maTAPDeviceName[slot] = "";
6629 }
6630#endif
6631 LogFlowThisFunc(("returning %d\n", rc));
6632 return rc;
6633}
6634
6635
6636/**
6637 * Called at power down to terminate host interface networking.
6638 *
6639 * @note The caller must lock this object for writing.
6640 */
6641HRESULT Console::powerDownHostInterfaces()
6642{
6643 LogFlowThisFunc (("\n"));
6644
6645 /* sanity check */
6646 AssertReturn (isLockedOnCurrentThread(), E_FAIL);
6647
6648 /*
6649 * host interface termination handling
6650 */
6651 HRESULT rc;
6652 for (ULONG slot = 0; slot < SchemaDefs::NetworkAdapterCount; slot ++)
6653 {
6654 ComPtr<INetworkAdapter> networkAdapter;
6655 rc = mMachine->GetNetworkAdapter(slot, networkAdapter.asOutParam());
6656 CheckComRCBreakRC (rc);
6657
6658 BOOL enabled = FALSE;
6659 networkAdapter->COMGETTER(Enabled) (&enabled);
6660 if (!enabled)
6661 continue;
6662
6663 NetworkAttachmentType_T attachment;
6664 networkAdapter->COMGETTER(AttachmentType)(&attachment);
6665 if (attachment == NetworkAttachmentType_HostInterfaceNetworkAttachment)
6666 {
6667 HRESULT rc2 = detachFromHostInterface(networkAdapter);
6668 if (FAILED(rc2) && SUCCEEDED(rc))
6669 rc = rc2;
6670 }
6671 }
6672
6673 return rc;
6674}
6675
6676
6677/**
6678 * Process callback handler for VMR3Load and VMR3Save.
6679 *
6680 * @param pVM The VM handle.
6681 * @param uPercent Completetion precentage (0-100).
6682 * @param pvUser Pointer to the VMProgressTask structure.
6683 * @return VINF_SUCCESS.
6684 */
6685/*static*/ DECLCALLBACK (int)
6686Console::stateProgressCallback (PVM pVM, unsigned uPercent, void *pvUser)
6687{
6688 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
6689 AssertReturn (task, VERR_INVALID_PARAMETER);
6690
6691 /* update the progress object */
6692 if (task->mProgress)
6693 task->mProgress->notifyProgress (uPercent);
6694
6695 return VINF_SUCCESS;
6696}
6697
6698/**
6699 * VM error callback function. Called by the various VM components.
6700 *
6701 * @param pVM The VM handle. Can be NULL if an error occurred before
6702 * successfully creating a VM.
6703 * @param pvUser Pointer to the VMProgressTask structure.
6704 * @param rc VBox status code.
6705 * @param pszFormat The error message.
6706 * @thread EMT.
6707 */
6708/* static */ DECLCALLBACK (void)
6709Console::setVMErrorCallback (PVM pVM, void *pvUser, int rc, RT_SRC_POS_DECL,
6710 const char *pszFormat, va_list args)
6711{
6712 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
6713 AssertReturnVoid (task);
6714
6715 /* we ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users */
6716 HRESULT hrc = setError (E_FAIL, tr ("%N.\n"
6717 "VBox status code: %d (%Vrc)"),
6718 tr (pszFormat), &args,
6719 rc, rc);
6720 task->mProgress->notifyComplete (hrc);
6721}
6722
6723/**
6724 * VM runtime error callback function.
6725 * See VMSetRuntimeError for the detailed description of parameters.
6726 *
6727 * @param pVM The VM handle.
6728 * @param pvUser The user argument.
6729 * @param fFatal Whether it is a fatal error or not.
6730 * @param pszErrorID Error ID string.
6731 * @param pszFormat Error message format string.
6732 * @param args Error message arguments.
6733 * @thread EMT.
6734 */
6735/* static */ DECLCALLBACK(void)
6736Console::setVMRuntimeErrorCallback (PVM pVM, void *pvUser, bool fFatal,
6737 const char *pszErrorID,
6738 const char *pszFormat, va_list args)
6739{
6740 LogFlowFuncEnter();
6741
6742 Console *that = static_cast <Console *> (pvUser);
6743 AssertReturnVoid (that);
6744
6745 Utf8Str message = Utf8StrFmtVA (pszFormat, args);
6746
6747 LogRel (("Console: VM runtime error: fatal=%RTbool, "
6748 "errorID=%s message=\"%s\"\n",
6749 fFatal, pszErrorID, message.raw()));
6750
6751 that->onRuntimeError (BOOL (fFatal), Bstr (pszErrorID), Bstr (message));
6752
6753 LogFlowFuncLeave();
6754}
6755
6756/**
6757 * Captures USB devices that match filters of the VM.
6758 * Called at VM startup.
6759 *
6760 * @param pVM The VM handle.
6761 *
6762 * @note The caller must lock this object for writing.
6763 */
6764HRESULT Console::captureUSBDevices (PVM pVM)
6765{
6766 LogFlowThisFunc (("\n"));
6767
6768 /* sanity check */
6769 ComAssertRet (isLockedOnCurrentThread(), E_FAIL);
6770
6771 /* If the machine has an USB controller, ask the USB proxy service to
6772 * capture devices */
6773 PPDMIBASE pBase;
6774 int vrc = PDMR3QueryLun (pVM, "usb-ohci", 0, 0, &pBase);
6775 if (VBOX_SUCCESS (vrc))
6776 {
6777 /* leave the lock before calling Host in VBoxSVC since Host may call
6778 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
6779 * produce an inter-process dead-lock otherwise. */
6780 AutoLock alock (this);
6781 alock.leave();
6782
6783 HRESULT hrc = mControl->AutoCaptureUSBDevices();
6784 ComAssertComRCRetRC (hrc);
6785 }
6786 else if ( vrc == VERR_PDM_DEVICE_NOT_FOUND
6787 || vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND)
6788 vrc = VINF_SUCCESS;
6789 else
6790 AssertRC (vrc);
6791
6792 return VBOX_SUCCESS (vrc) ? S_OK : E_FAIL;
6793}
6794
6795
6796/**
6797 * Detach all USB device which are attached to the VM for the
6798 * purpose of clean up and such like.
6799 *
6800 * @note The caller must lock this object for writing.
6801 */
6802void Console::detachAllUSBDevices (bool aDone)
6803{
6804 LogFlowThisFunc (("\n"));
6805
6806 /* sanity check */
6807 AssertReturnVoid (isLockedOnCurrentThread());
6808
6809 mUSBDevices.clear();
6810
6811 /* leave the lock before calling Host in VBoxSVC since Host may call
6812 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
6813 * produce an inter-process dead-lock otherwise. */
6814 AutoLock alock (this);
6815 alock.leave();
6816
6817 mControl->DetachAllUSBDevices (aDone);
6818}
6819
6820/**
6821 * @note Locks this object for writing.
6822 */
6823void Console::processRemoteUSBDevices (uint32_t u32ClientId, VRDPUSBDEVICEDESC *pDevList, uint32_t cbDevList)
6824{
6825 LogFlowThisFuncEnter();
6826 LogFlowThisFunc (("u32ClientId = %d, pDevList=%p, cbDevList = %d\n", u32ClientId, pDevList, cbDevList));
6827
6828 AutoCaller autoCaller (this);
6829 if (!autoCaller.isOk())
6830 {
6831 /* Console has been already uninitialized, deny request */
6832 AssertMsgFailed (("Temporary assertion to prove that it happens, "
6833 "please report to dmik\n"));
6834 LogFlowThisFunc (("Console is already uninitialized\n"));
6835 LogFlowThisFuncLeave();
6836 return;
6837 }
6838
6839 AutoLock alock (this);
6840
6841 /*
6842 * Mark all existing remote USB devices as dirty.
6843 */
6844 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
6845 while (it != mRemoteUSBDevices.end())
6846 {
6847 (*it)->dirty (true);
6848 ++ it;
6849 }
6850
6851 /*
6852 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
6853 */
6854 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
6855 VRDPUSBDEVICEDESC *e = pDevList;
6856
6857 /* The cbDevList condition must be checked first, because the function can
6858 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
6859 */
6860 while (cbDevList >= 2 && e->oNext)
6861 {
6862 LogFlowThisFunc (("vendor %04X, product %04X, name = %s\n",
6863 e->idVendor, e->idProduct,
6864 e->oProduct? (char *)e + e->oProduct: ""));
6865
6866 bool fNewDevice = true;
6867
6868 it = mRemoteUSBDevices.begin();
6869 while (it != mRemoteUSBDevices.end())
6870 {
6871 if ((*it)->devId () == e->id
6872 && (*it)->clientId () == u32ClientId)
6873 {
6874 /* The device is already in the list. */
6875 (*it)->dirty (false);
6876 fNewDevice = false;
6877 break;
6878 }
6879
6880 ++ it;
6881 }
6882
6883 if (fNewDevice)
6884 {
6885 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
6886 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""
6887 ));
6888
6889 /* Create the device object and add the new device to list. */
6890 ComObjPtr <RemoteUSBDevice> device;
6891 device.createObject();
6892 device->init (u32ClientId, e);
6893
6894 mRemoteUSBDevices.push_back (device);
6895
6896 /* Check if the device is ok for current USB filters. */
6897 BOOL fMatched = FALSE;
6898
6899 HRESULT hrc = mControl->RunUSBDeviceFilters(device, &fMatched);
6900
6901 AssertComRC (hrc);
6902
6903 LogFlowThisFunc (("USB filters return %d\n", fMatched));
6904
6905 if (fMatched)
6906 {
6907 hrc = onUSBDeviceAttach (device, NULL);
6908
6909 /// @todo (r=dmik) warning reporting subsystem
6910
6911 if (hrc == S_OK)
6912 {
6913 LogFlowThisFunc (("Device attached\n"));
6914 device->captured (true);
6915 }
6916 }
6917 }
6918
6919 if (cbDevList < e->oNext)
6920 {
6921 LogWarningThisFunc (("cbDevList %d > oNext %d\n",
6922 cbDevList, e->oNext));
6923 break;
6924 }
6925
6926 cbDevList -= e->oNext;
6927
6928 e = (VRDPUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
6929 }
6930
6931 /*
6932 * Remove dirty devices, that is those which are not reported by the server anymore.
6933 */
6934 for (;;)
6935 {
6936 ComObjPtr <RemoteUSBDevice> device;
6937
6938 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
6939 while (it != mRemoteUSBDevices.end())
6940 {
6941 if ((*it)->dirty ())
6942 {
6943 device = *it;
6944 break;
6945 }
6946
6947 ++ it;
6948 }
6949
6950 if (!device)
6951 {
6952 break;
6953 }
6954
6955 USHORT vendorId = 0;
6956 device->COMGETTER(VendorId) (&vendorId);
6957
6958 USHORT productId = 0;
6959 device->COMGETTER(ProductId) (&productId);
6960
6961 Bstr product;
6962 device->COMGETTER(Product) (product.asOutParam());
6963
6964 LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
6965 vendorId, productId, product.raw ()
6966 ));
6967
6968 /* Detach the device from VM. */
6969 if (device->captured ())
6970 {
6971 Guid uuid;
6972 device->COMGETTER (Id) (uuid.asOutParam());
6973 onUSBDeviceDetach (uuid, NULL);
6974 }
6975
6976 /* And remove it from the list. */
6977 mRemoteUSBDevices.erase (it);
6978 }
6979
6980 LogFlowThisFuncLeave();
6981}
6982
6983
6984
6985/**
6986 * Thread function which starts the VM (also from saved state) and
6987 * track progress.
6988 *
6989 * @param Thread The thread id.
6990 * @param pvUser Pointer to a VMPowerUpTask structure.
6991 * @return VINF_SUCCESS (ignored).
6992 *
6993 * @note Locks the Console object for writing.
6994 */
6995/*static*/
6996DECLCALLBACK (int) Console::powerUpThread (RTTHREAD Thread, void *pvUser)
6997{
6998 LogFlowFuncEnter();
6999
7000 std::auto_ptr <VMPowerUpTask> task (static_cast <VMPowerUpTask *> (pvUser));
7001 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
7002
7003 AssertReturn (!task->mConsole.isNull(), VERR_INVALID_PARAMETER);
7004 AssertReturn (!task->mProgress.isNull(), VERR_INVALID_PARAMETER);
7005
7006#if defined(RT_OS_WINDOWS)
7007 {
7008 /* initialize COM */
7009 HRESULT hrc = CoInitializeEx (NULL,
7010 COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE |
7011 COINIT_SPEED_OVER_MEMORY);
7012 LogFlowFunc (("CoInitializeEx()=%08X\n", hrc));
7013 }
7014#endif
7015
7016 HRESULT hrc = S_OK;
7017 int vrc = VINF_SUCCESS;
7018
7019 /* Set up a build identifier so that it can be seen from core dumps what
7020 * exact build was used to produce the core. */
7021 static char saBuildID[40];
7022 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%d %s%s%s%s",
7023 "BU", "IL", "DI", "D", VBOX_VERSION_STRING, VBOX_SVN_REV, "BU", "IL", "DI", "D");
7024
7025 ComObjPtr <Console> console = task->mConsole;
7026
7027 /* Note: no need to use addCaller() because VMPowerUpTask does that */
7028
7029 AutoLock alock (console);
7030
7031 /* sanity */
7032 Assert (console->mpVM == NULL);
7033
7034 do
7035 {
7036 /*
7037 * Initialize the release logging facility. In case something
7038 * goes wrong, there will be no release logging. Maybe in the future
7039 * we can add some logic to use different file names in this case.
7040 * Note that the logic must be in sync with Machine::DeleteSettings().
7041 */
7042
7043 Bstr logFolder;
7044 hrc = console->mMachine->COMGETTER(LogFolder) (logFolder.asOutParam());
7045 CheckComRCBreakRC (hrc);
7046
7047 Utf8Str logDir = logFolder;
7048
7049 /* make sure the Logs folder exists */
7050 Assert (!logDir.isEmpty());
7051 if (!RTDirExists (logDir))
7052 RTDirCreateFullPath (logDir, 0777);
7053
7054 Utf8Str logFile = Utf8StrFmt ("%s%cVBox.log",
7055 logDir.raw(), RTPATH_DELIMITER);
7056
7057 /*
7058 * Age the old log files
7059 * Rename .2 to .3, .1 to .2 and the last log file to .1
7060 * Overwrite target files in case they exist;
7061 */
7062 for (int i = 2; i >= 0; i--)
7063 {
7064 Utf8Str oldName;
7065 if (i > 0)
7066 oldName = Utf8StrFmt ("%s.%d", logFile.raw(), i);
7067 else
7068 oldName = logFile;
7069 Utf8Str newName = Utf8StrFmt ("%s.%d", logFile.raw(), i + 1);
7070 RTFileRename(oldName.raw(), newName.raw(), RTFILEMOVE_FLAGS_REPLACE);
7071 }
7072
7073 PRTLOGGER loggerRelease;
7074 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
7075 RTUINT fFlags = RTLOGFLAGS_PREFIX_TIME_PROG;
7076#if defined (RT_OS_WINDOWS) || defined (RT_OS_OS2)
7077 fFlags |= RTLOGFLAGS_USECRLF;
7078#endif
7079 char szError[RTPATH_MAX + 128] = "";
7080 vrc = RTLogCreateEx(&loggerRelease, fFlags, "all",
7081 "VBOX_RELEASE_LOG", ELEMENTS(s_apszGroups), s_apszGroups,
7082 RTLOGDEST_FILE, szError, sizeof(szError), logFile.raw());
7083 if (VBOX_SUCCESS(vrc))
7084 {
7085 /* some introductory information */
7086 RTTIMESPEC timeSpec;
7087 char nowUct[64];
7088 RTTimeSpecToString(RTTimeNow(&timeSpec), nowUct, sizeof(nowUct));
7089 RTLogRelLogger(loggerRelease, 0, ~0U,
7090 "VirtualBox %s r%d (%s %s) release log\n"
7091 "Log opened %s\n",
7092 VBOX_VERSION_STRING, VBOX_SVN_REV, __DATE__, __TIME__,
7093 nowUct);
7094
7095 /* register this logger as the release logger */
7096 RTLogRelSetDefaultInstance(loggerRelease);
7097 }
7098 else
7099 {
7100 hrc = setError (E_FAIL,
7101 tr ("Failed to open release log (%s, %Vrc)"), szError, vrc);
7102 break;
7103 }
7104
7105#ifdef VBOX_VRDP
7106 if (VBOX_SUCCESS (vrc))
7107 {
7108 /* Create the VRDP server. In case of headless operation, this will
7109 * also create the framebuffer, required at VM creation.
7110 */
7111 ConsoleVRDPServer *server = console->consoleVRDPServer();
7112 Assert (server);
7113 /// @todo (dmik)
7114 // does VRDP server call Console from the other thread?
7115 // Not sure, so leave the lock just in case
7116 alock.leave();
7117 vrc = server->Launch();
7118 alock.enter();
7119 if (VBOX_FAILURE (vrc))
7120 {
7121 Utf8Str errMsg;
7122 switch (vrc)
7123 {
7124 case VERR_NET_ADDRESS_IN_USE:
7125 {
7126 ULONG port = 0;
7127 console->mVRDPServer->COMGETTER(Port) (&port);
7128 errMsg = Utf8StrFmt (tr ("VRDP server port %d is already in use"),
7129 port);
7130 break;
7131 }
7132 default:
7133 errMsg = Utf8StrFmt (tr ("Failed to launch VRDP server (%Vrc)"),
7134 vrc);
7135 }
7136 LogRel (("Failed to launch VRDP server (%Vrc), error message: '%s'\n",
7137 vrc, errMsg.raw()));
7138 hrc = setError (E_FAIL, errMsg);
7139 break;
7140 }
7141 }
7142#endif /* VBOX_VRDP */
7143
7144 /*
7145 * Create the VM
7146 */
7147 PVM pVM;
7148 /*
7149 * leave the lock since EMT will call Console. It's safe because
7150 * mMachineState is either Starting or Restoring state here.
7151 */
7152 alock.leave();
7153
7154 vrc = VMR3Create (task->mSetVMErrorCallback, task.get(),
7155 task->mConfigConstructor, task.get(),
7156 &pVM);
7157
7158 alock.enter();
7159
7160#ifdef VBOX_VRDP
7161 {
7162 /* Enable client connections to the server. */
7163 ConsoleVRDPServer *server = console->consoleVRDPServer();
7164#ifdef VRDP_NO_COM
7165 server->EnableConnections ();
7166#else
7167 server->SetCallback ();
7168#endif /* VRDP_NO_COM */
7169 }
7170#endif /* VBOX_VRDP */
7171
7172 if (VBOX_SUCCESS (vrc))
7173 {
7174 do
7175 {
7176 /*
7177 * Register our load/save state file handlers
7178 */
7179 vrc = SSMR3RegisterExternal (pVM,
7180 sSSMConsoleUnit, 0 /* iInstance */, sSSMConsoleVer,
7181 0 /* cbGuess */,
7182 NULL, saveStateFileExec, NULL, NULL, loadStateFileExec, NULL,
7183 static_cast <Console *> (console));
7184 AssertRC (vrc);
7185 if (VBOX_FAILURE (vrc))
7186 break;
7187
7188 /*
7189 * Synchronize debugger settings
7190 */
7191 MachineDebugger *machineDebugger = console->getMachineDebugger();
7192 if (machineDebugger)
7193 {
7194 machineDebugger->flushQueuedSettings();
7195 }
7196
7197 /*
7198 * Shared Folders
7199 */
7200 if (console->getVMMDev()->isShFlActive())
7201 {
7202 /// @todo (dmik)
7203 // does the code below call Console from the other thread?
7204 // Not sure, so leave the lock just in case
7205 alock.leave();
7206
7207 for (SharedFolderDataMap::const_iterator
7208 it = task->mSharedFolders.begin();
7209 it != task->mSharedFolders.end();
7210 ++ it)
7211 {
7212 hrc = console->createSharedFolder ((*it).first, (*it).second);
7213 CheckComRCBreakRC (hrc);
7214 }
7215
7216 /* enter the lock again */
7217 alock.enter();
7218
7219 CheckComRCBreakRC (hrc);
7220 }
7221
7222 /*
7223 * Capture USB devices.
7224 */
7225 hrc = console->captureUSBDevices (pVM);
7226 CheckComRCBreakRC (hrc);
7227
7228 /* leave the lock before a lengthy operation */
7229 alock.leave();
7230
7231 /* Load saved state? */
7232 if (!!task->mSavedStateFile)
7233 {
7234 LogFlowFunc (("Restoring saved state from '%s'...\n",
7235 task->mSavedStateFile.raw()));
7236
7237 vrc = VMR3Load (pVM, task->mSavedStateFile,
7238 Console::stateProgressCallback,
7239 static_cast <VMProgressTask *> (task.get()));
7240
7241 /* Start/Resume the VM execution */
7242 if (VBOX_SUCCESS (vrc))
7243 {
7244 vrc = VMR3Resume (pVM);
7245 AssertRC (vrc);
7246 }
7247
7248 /* Power off in case we failed loading or resuming the VM */
7249 if (VBOX_FAILURE (vrc))
7250 {
7251 int vrc2 = VMR3PowerOff (pVM);
7252 AssertRC (vrc2);
7253 }
7254 }
7255 else
7256 {
7257 /* Power on the VM (i.e. start executing) */
7258 vrc = VMR3PowerOn(pVM);
7259 AssertRC (vrc);
7260 }
7261
7262 /* enter the lock again */
7263 alock.enter();
7264 }
7265 while (0);
7266
7267 /* On failure, destroy the VM */
7268 if (FAILED (hrc) || VBOX_FAILURE (vrc))
7269 {
7270 /* preserve existing error info */
7271 ErrorInfoKeeper eik;
7272
7273 /*
7274 * powerDown() will call VMR3Destroy() and do all necessary
7275 * cleanup (VRDP, USB devices)
7276 */
7277 HRESULT hrc2 = console->powerDown();
7278 AssertComRC (hrc2);
7279 }
7280 }
7281 else
7282 {
7283 /*
7284 * If VMR3Create() failed it has released the VM memory.
7285 */
7286 console->mpVM = NULL;
7287 }
7288
7289 if (SUCCEEDED (hrc) && VBOX_FAILURE (vrc))
7290 {
7291 /*
7292 * If VMR3Create() or one of the other calls in this function fail,
7293 * an appropriate error message has been already set. However since
7294 * that happens via a callback, the status code in this function is
7295 * not updated.
7296 */
7297 if (!task->mProgress->completed())
7298 {
7299 /*
7300 * If the COM error info is not yet set but we've got a
7301 * failure, convert the VBox status code into a meaningful
7302 * error message. This becomes unused once all the sources of
7303 * errors set the appropriate error message themselves.
7304 * Note that we don't use VMSetError() below because pVM is
7305 * either invalid or NULL here.
7306 */
7307 AssertMsgFailed (("Missing error message during powerup for "
7308 "status code %Vrc\n", vrc));
7309 hrc = setError (E_FAIL,
7310 tr ("Failed to start VM execution (%Vrc)"), vrc);
7311 }
7312 else
7313 hrc = task->mProgress->resultCode();
7314
7315 Assert (FAILED (hrc));
7316 break;
7317 }
7318 }
7319 while (0);
7320
7321 if (console->mMachineState == MachineState_Starting ||
7322 console->mMachineState == MachineState_Restoring)
7323 {
7324 /*
7325 * We are still in the Starting/Restoring state. This means one of:
7326 * 1) we failed before VMR3Create() was called;
7327 * 2) VMR3Create() failed.
7328 * In both cases, there is no need to call powerDown(), but we still
7329 * need to go back to the PoweredOff/Saved state. Reuse
7330 * vmstateChangeCallback() for that purpose.
7331 */
7332
7333 /* preserve existing error info */
7334 ErrorInfoKeeper eik;
7335
7336 Assert (console->mpVM == NULL);
7337 vmstateChangeCallback (NULL, VMSTATE_TERMINATED, VMSTATE_CREATING,
7338 console);
7339 }
7340
7341 /*
7342 * Evaluate the final result.
7343 * Note that the appropriate mMachineState value is already set by
7344 * vmstateChangeCallback() in all cases.
7345 */
7346
7347 /* leave the lock, don't need it any more */
7348 alock.leave();
7349
7350 if (SUCCEEDED (hrc))
7351 {
7352 /* Notify the progress object of the success */
7353 task->mProgress->notifyComplete (S_OK);
7354 }
7355 else
7356 {
7357 if (!task->mProgress->completed())
7358 {
7359 /* The progress object will fetch the current error info. This
7360 * gets the errors signalled by using setError(). The ones
7361 * signalled via VMSetError() immediately notify the progress
7362 * object that the operation is completed. */
7363 task->mProgress->notifyComplete (hrc);
7364 }
7365
7366 LogRel (("Power up failed (vrc=%Vrc, hrc=0x%08X)\n", vrc, hrc));
7367 }
7368
7369#if defined(RT_OS_WINDOWS)
7370 /* uninitialize COM */
7371 CoUninitialize();
7372#endif
7373
7374 LogFlowFuncLeave();
7375
7376 return VINF_SUCCESS;
7377}
7378
7379
7380/**
7381 * Reconfigures a VDI.
7382 *
7383 * @param pVM The VM handle.
7384 * @param hda The harddisk attachment.
7385 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
7386 * @return VBox status code.
7387 */
7388static DECLCALLBACK(int) reconfigureVDI(PVM pVM, IHardDiskAttachment *hda, HRESULT *phrc)
7389{
7390 LogFlowFunc (("pVM=%p hda=%p phrc=%p\n", pVM, hda, phrc));
7391
7392 int rc;
7393 HRESULT hrc;
7394 char *psz = NULL;
7395 BSTR str = NULL;
7396 *phrc = S_OK;
7397#define STR_CONV() do { rc = RTStrUcs2ToUtf8(&psz, str); RC_CHECK(); } while (0)
7398#define STR_FREE() do { if (str) { SysFreeString(str); str = NULL; } if (psz) { RTStrFree(psz); psz = NULL; } } while (0)
7399#define RC_CHECK() do { if (VBOX_FAILURE(rc)) { AssertMsgFailed(("rc=%Vrc\n", rc)); STR_FREE(); return rc; } } while (0)
7400#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%#x\n", hrc)); STR_FREE(); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
7401
7402 /*
7403 * Figure out which IDE device this is.
7404 */
7405 ComPtr<IHardDisk> hardDisk;
7406 hrc = hda->COMGETTER(HardDisk)(hardDisk.asOutParam()); H();
7407 DiskControllerType_T enmCtl;
7408 hrc = hda->COMGETTER(Controller)(&enmCtl); H();
7409 LONG lDev;
7410 hrc = hda->COMGETTER(DeviceNumber)(&lDev); H();
7411
7412 int i;
7413 switch (enmCtl)
7414 {
7415 case DiskControllerType_IDE0Controller:
7416 i = 0;
7417 break;
7418 case DiskControllerType_IDE1Controller:
7419 i = 2;
7420 break;
7421 default:
7422 AssertMsgFailed(("invalid disk controller type: %d\n", enmCtl));
7423 return VERR_GENERAL_FAILURE;
7424 }
7425
7426 if (lDev < 0 || lDev >= 2)
7427 {
7428 AssertMsgFailed(("invalid controller device number: %d\n", lDev));
7429 return VERR_GENERAL_FAILURE;
7430 }
7431
7432 i = i + lDev;
7433
7434 /*
7435 * Is there an existing LUN? If not create it.
7436 * We ASSUME that this will NEVER collide with the DVD.
7437 */
7438 PCFGMNODE pCfg;
7439 PCFGMNODE pLunL1 = CFGMR3GetChildF(CFGMR3GetRoot(pVM), "Devices/piix3ide/0/LUN#%d/AttachedDriver/", i);
7440 if (!pLunL1)
7441 {
7442 PCFGMNODE pInst = CFGMR3GetChild(CFGMR3GetRoot(pVM), "Devices/piix3ide/0/");
7443 AssertReturn(pInst, VERR_INTERNAL_ERROR);
7444
7445 PCFGMNODE pLunL0;
7446 rc = CFGMR3InsertNodeF(pInst, &pLunL0, "LUN#%d", i); RC_CHECK();
7447 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
7448 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
7449 rc = CFGMR3InsertString(pCfg, "Type", "HardDisk"); RC_CHECK();
7450 rc = CFGMR3InsertInteger(pCfg, "Mountable", 0); RC_CHECK();
7451
7452 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
7453 rc = CFGMR3InsertString(pLunL1, "Driver", "VBoxHDD"); RC_CHECK();
7454 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
7455 }
7456 else
7457 {
7458#ifdef VBOX_STRICT
7459 char *pszDriver;
7460 rc = CFGMR3QueryStringAlloc(pLunL1, "Driver", &pszDriver); RC_CHECK();
7461 Assert(!strcmp(pszDriver, "VBoxHDD"));
7462 MMR3HeapFree(pszDriver);
7463#endif
7464
7465 /*
7466 * Check if things has changed.
7467 */
7468 pCfg = CFGMR3GetChild(pLunL1, "Config");
7469 AssertReturn(pCfg, VERR_INTERNAL_ERROR);
7470
7471 /* the image */
7472 /// @todo (dmik) we temporarily use the location property to
7473 // determine the image file name. This is subject to change
7474 // when iSCSI disks are here (we should either query a
7475 // storage-specific interface from IHardDisk, or "standardize"
7476 // the location property)
7477 hrc = hardDisk->COMGETTER(Location)(&str); H();
7478 STR_CONV();
7479 char *pszPath;
7480 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
7481 if (!strcmp(psz, pszPath))
7482 {
7483 /* parent images. */
7484 ComPtr<IHardDisk> parentHardDisk = hardDisk;
7485 for (PCFGMNODE pParent = pCfg;;)
7486 {
7487 MMR3HeapFree(pszPath);
7488 pszPath = NULL;
7489 STR_FREE();
7490
7491 /* get parent */
7492 ComPtr<IHardDisk> curHardDisk;
7493 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
7494 PCFGMNODE pCur;
7495 pCur = CFGMR3GetChild(pParent, "Parent");
7496 if (!pCur && !curHardDisk)
7497 {
7498 /* no change */
7499 LogFlowFunc (("No change!\n"));
7500 return VINF_SUCCESS;
7501 }
7502 if (!pCur || !curHardDisk)
7503 break;
7504
7505 /* compare paths. */
7506 /// @todo (dmik) we temporarily use the location property to
7507 // determine the image file name. This is subject to change
7508 // when iSCSI disks are here (we should either query a
7509 // storage-specific interface from IHardDisk, or "standardize"
7510 // the location property)
7511 hrc = curHardDisk->COMGETTER(Location)(&str); H();
7512 STR_CONV();
7513 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
7514 if (strcmp(psz, pszPath))
7515 break;
7516
7517 /* next */
7518 pParent = pCur;
7519 parentHardDisk = curHardDisk;
7520 }
7521
7522 }
7523 else
7524 LogFlowFunc (("LUN#%d: old leaf image '%s'\n", i, pszPath));
7525
7526 MMR3HeapFree(pszPath);
7527 STR_FREE();
7528
7529 /*
7530 * Detach the driver and replace the config node.
7531 */
7532 rc = PDMR3DeviceDetach(pVM, "piix3ide", 0, i); RC_CHECK();
7533 CFGMR3RemoveNode(pCfg);
7534 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
7535 }
7536
7537 /*
7538 * Create the driver configuration.
7539 */
7540 /// @todo (dmik) we temporarily use the location property to
7541 // determine the image file name. This is subject to change
7542 // when iSCSI disks are here (we should either query a
7543 // storage-specific interface from IHardDisk, or "standardize"
7544 // the location property)
7545 hrc = hardDisk->COMGETTER(Location)(&str); H();
7546 STR_CONV();
7547 LogFlowFunc (("LUN#%d: leaf image '%s'\n", i, psz));
7548 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
7549 STR_FREE();
7550 /* Create an inversed tree of parents. */
7551 ComPtr<IHardDisk> parentHardDisk = hardDisk;
7552 for (PCFGMNODE pParent = pCfg;;)
7553 {
7554 ComPtr<IHardDisk> curHardDisk;
7555 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
7556 if (!curHardDisk)
7557 break;
7558
7559 PCFGMNODE pCur;
7560 rc = CFGMR3InsertNode(pParent, "Parent", &pCur); RC_CHECK();
7561 /// @todo (dmik) we temporarily use the location property to
7562 // determine the image file name. This is subject to change
7563 // when iSCSI disks are here (we should either query a
7564 // storage-specific interface from IHardDisk, or "standardize"
7565 // the location property)
7566 hrc = curHardDisk->COMGETTER(Location)(&str); H();
7567 STR_CONV();
7568 rc = CFGMR3InsertString(pCur, "Path", psz); RC_CHECK();
7569 STR_FREE();
7570
7571 /* next */
7572 pParent = pCur;
7573 parentHardDisk = curHardDisk;
7574 }
7575
7576 /*
7577 * Attach the new driver.
7578 */
7579 rc = PDMR3DeviceAttach(pVM, "piix3ide", 0, i, NULL); RC_CHECK();
7580
7581 LogFlowFunc (("Returns success\n"));
7582 return rc;
7583}
7584
7585
7586/**
7587 * Thread for executing the saved state operation.
7588 *
7589 * @param Thread The thread handle.
7590 * @param pvUser Pointer to a VMSaveTask structure.
7591 * @return VINF_SUCCESS (ignored).
7592 *
7593 * @note Locks the Console object for writing.
7594 */
7595/*static*/
7596DECLCALLBACK (int) Console::saveStateThread (RTTHREAD Thread, void *pvUser)
7597{
7598 LogFlowFuncEnter();
7599
7600 std::auto_ptr <VMSaveTask> task (static_cast <VMSaveTask *> (pvUser));
7601 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
7602
7603 Assert (!task->mSavedStateFile.isNull());
7604 Assert (!task->mProgress.isNull());
7605
7606 const ComObjPtr <Console> &that = task->mConsole;
7607
7608 /*
7609 * Note: no need to use addCaller() to protect Console or addVMCaller() to
7610 * protect mpVM because VMSaveTask does that
7611 */
7612
7613 Utf8Str errMsg;
7614 HRESULT rc = S_OK;
7615
7616 if (task->mIsSnapshot)
7617 {
7618 Assert (!task->mServerProgress.isNull());
7619 LogFlowFunc (("Waiting until the server creates differencing VDIs...\n"));
7620
7621 rc = task->mServerProgress->WaitForCompletion (-1);
7622 if (SUCCEEDED (rc))
7623 {
7624 HRESULT result = S_OK;
7625 rc = task->mServerProgress->COMGETTER(ResultCode) (&result);
7626 if (SUCCEEDED (rc))
7627 rc = result;
7628 }
7629 }
7630
7631 if (SUCCEEDED (rc))
7632 {
7633 LogFlowFunc (("Saving the state to '%s'...\n", task->mSavedStateFile.raw()));
7634
7635 int vrc = VMR3Save (that->mpVM, task->mSavedStateFile,
7636 Console::stateProgressCallback,
7637 static_cast <VMProgressTask *> (task.get()));
7638 if (VBOX_FAILURE (vrc))
7639 {
7640 errMsg = Utf8StrFmt (
7641 Console::tr ("Failed to save the machine state to '%s' (%Vrc)"),
7642 task->mSavedStateFile.raw(), vrc);
7643 rc = E_FAIL;
7644 }
7645 }
7646
7647 /* lock the console sonce we're going to access it */
7648 AutoLock thatLock (that);
7649
7650 if (SUCCEEDED (rc))
7651 {
7652 if (task->mIsSnapshot)
7653 do
7654 {
7655 LogFlowFunc (("Reattaching new differencing VDIs...\n"));
7656
7657 ComPtr <IHardDiskAttachmentCollection> hdaColl;
7658 rc = that->mMachine->COMGETTER(HardDiskAttachments) (hdaColl.asOutParam());
7659 if (FAILED (rc))
7660 break;
7661 ComPtr <IHardDiskAttachmentEnumerator> hdaEn;
7662 rc = hdaColl->Enumerate (hdaEn.asOutParam());
7663 if (FAILED (rc))
7664 break;
7665 BOOL more = FALSE;
7666 while (SUCCEEDED (rc = hdaEn->HasMore (&more)) && more)
7667 {
7668 ComPtr <IHardDiskAttachment> hda;
7669 rc = hdaEn->GetNext (hda.asOutParam());
7670 if (FAILED (rc))
7671 break;
7672
7673 PVMREQ pReq;
7674 IHardDiskAttachment *pHda = hda;
7675 /*
7676 * don't leave the lock since reconfigureVDI isn't going to
7677 * access Console.
7678 */
7679 int vrc = VMR3ReqCall (that->mpVM, &pReq, RT_INDEFINITE_WAIT,
7680 (PFNRT)reconfigureVDI, 3, that->mpVM,
7681 pHda, &rc);
7682 if (VBOX_SUCCESS (rc))
7683 rc = pReq->iStatus;
7684 VMR3ReqFree (pReq);
7685 if (FAILED (rc))
7686 break;
7687 if (VBOX_FAILURE (vrc))
7688 {
7689 errMsg = Utf8StrFmt (Console::tr ("%Vrc"), vrc);
7690 rc = E_FAIL;
7691 break;
7692 }
7693 }
7694 }
7695 while (0);
7696 }
7697
7698 /* finalize the procedure regardless of the result */
7699 if (task->mIsSnapshot)
7700 {
7701 /*
7702 * finalize the requested snapshot object.
7703 * This will reset the machine state to the state it had right
7704 * before calling mControl->BeginTakingSnapshot().
7705 */
7706 that->mControl->EndTakingSnapshot (SUCCEEDED (rc));
7707 }
7708 else
7709 {
7710 /*
7711 * finalize the requested save state procedure.
7712 * In case of success, the server will set the machine state to Saved;
7713 * in case of failure it will reset the it to the state it had right
7714 * before calling mControl->BeginSavingState().
7715 */
7716 that->mControl->EndSavingState (SUCCEEDED (rc));
7717 }
7718
7719 /* synchronize the state with the server */
7720 if (task->mIsSnapshot || FAILED (rc))
7721 {
7722 if (task->mLastMachineState == MachineState_Running)
7723 {
7724 /* restore the paused state if appropriate */
7725 that->setMachineStateLocally (MachineState_Paused);
7726 /* restore the running state if appropriate */
7727 that->Resume();
7728 }
7729 else
7730 that->setMachineStateLocally (task->mLastMachineState);
7731 }
7732 else
7733 {
7734 /*
7735 * The machine has been successfully saved, so power it down
7736 * (vmstateChangeCallback() will set state to Saved on success).
7737 * Note: we release the task's VM caller, otherwise it will
7738 * deadlock.
7739 */
7740 task->releaseVMCaller();
7741
7742 rc = that->powerDown();
7743 }
7744
7745 /* notify the progress object about operation completion */
7746 if (SUCCEEDED (rc))
7747 task->mProgress->notifyComplete (S_OK);
7748 else
7749 {
7750 if (!errMsg.isNull())
7751 task->mProgress->notifyComplete (rc,
7752 COM_IIDOF(IConsole), Console::getComponentName(), errMsg);
7753 else
7754 task->mProgress->notifyComplete (rc);
7755 }
7756
7757 LogFlowFuncLeave();
7758 return VINF_SUCCESS;
7759}
7760
7761/**
7762 * Thread for powering down the Console.
7763 *
7764 * @param Thread The thread handle.
7765 * @param pvUser Pointer to the VMTask structure.
7766 * @return VINF_SUCCESS (ignored).
7767 *
7768 * @note Locks the Console object for writing.
7769 */
7770/*static*/
7771DECLCALLBACK (int) Console::powerDownThread (RTTHREAD Thread, void *pvUser)
7772{
7773 LogFlowFuncEnter();
7774
7775 std::auto_ptr <VMTask> task (static_cast <VMTask *> (pvUser));
7776 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
7777
7778 AssertReturn (task->isOk(), VERR_GENERAL_FAILURE);
7779
7780 const ComObjPtr <Console> &that = task->mConsole;
7781
7782 /*
7783 * Note: no need to use addCaller() to protect Console
7784 * because VMTask does that
7785 */
7786
7787 /* release VM caller to let powerDown() proceed */
7788 task->releaseVMCaller();
7789
7790 HRESULT rc = that->powerDown();
7791 AssertComRC (rc);
7792
7793 LogFlowFuncLeave();
7794 return VINF_SUCCESS;
7795}
7796
7797/**
7798 * The Main status driver instance data.
7799 */
7800typedef struct DRVMAINSTATUS
7801{
7802 /** The LED connectors. */
7803 PDMILEDCONNECTORS ILedConnectors;
7804 /** Pointer to the LED ports interface above us. */
7805 PPDMILEDPORTS pLedPorts;
7806 /** Pointer to the array of LED pointers. */
7807 PPDMLED *papLeds;
7808 /** The unit number corresponding to the first entry in the LED array. */
7809 RTUINT iFirstLUN;
7810 /** The unit number corresponding to the last entry in the LED array.
7811 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
7812 RTUINT iLastLUN;
7813} DRVMAINSTATUS, *PDRVMAINSTATUS;
7814
7815
7816/**
7817 * Notification about a unit which have been changed.
7818 *
7819 * The driver must discard any pointers to data owned by
7820 * the unit and requery it.
7821 *
7822 * @param pInterface Pointer to the interface structure containing the called function pointer.
7823 * @param iLUN The unit number.
7824 */
7825DECLCALLBACK(void) Console::drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
7826{
7827 PDRVMAINSTATUS pData = (PDRVMAINSTATUS)(void *)pInterface;
7828 if (iLUN >= pData->iFirstLUN && iLUN <= pData->iLastLUN)
7829 {
7830 PPDMLED pLed;
7831 int rc = pData->pLedPorts->pfnQueryStatusLed(pData->pLedPorts, iLUN, &pLed);
7832 if (VBOX_FAILURE(rc))
7833 pLed = NULL;
7834 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLUN - pData->iFirstLUN], pLed);
7835 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
7836 }
7837}
7838
7839
7840/**
7841 * Queries an interface to the driver.
7842 *
7843 * @returns Pointer to interface.
7844 * @returns NULL if the interface was not supported by the driver.
7845 * @param pInterface Pointer to this interface structure.
7846 * @param enmInterface The requested interface identification.
7847 */
7848DECLCALLBACK(void *) Console::drvStatus_QueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
7849{
7850 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
7851 PDRVMAINSTATUS pDrv = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
7852 switch (enmInterface)
7853 {
7854 case PDMINTERFACE_BASE:
7855 return &pDrvIns->IBase;
7856 case PDMINTERFACE_LED_CONNECTORS:
7857 return &pDrv->ILedConnectors;
7858 default:
7859 return NULL;
7860 }
7861}
7862
7863
7864/**
7865 * Destruct a status driver instance.
7866 *
7867 * @returns VBox status.
7868 * @param pDrvIns The driver instance data.
7869 */
7870DECLCALLBACK(void) Console::drvStatus_Destruct(PPDMDRVINS pDrvIns)
7871{
7872 PDRVMAINSTATUS pData = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
7873 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
7874 if (pData->papLeds)
7875 {
7876 unsigned iLed = pData->iLastLUN - pData->iFirstLUN + 1;
7877 while (iLed-- > 0)
7878 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLed], NULL);
7879 }
7880}
7881
7882
7883/**
7884 * Construct a status driver instance.
7885 *
7886 * @returns VBox status.
7887 * @param pDrvIns The driver instance data.
7888 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
7889 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
7890 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
7891 * iInstance it's expected to be used a bit in this function.
7892 */
7893DECLCALLBACK(int) Console::drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
7894{
7895 PDRVMAINSTATUS pData = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
7896 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
7897
7898 /*
7899 * Validate configuration.
7900 */
7901 if (!CFGMR3AreValuesValid(pCfgHandle, "papLeds\0First\0Last\0"))
7902 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
7903 PPDMIBASE pBaseIgnore;
7904 int rc = pDrvIns->pDrvHlp->pfnAttach(pDrvIns, &pBaseIgnore);
7905 if (rc != VERR_PDM_NO_ATTACHED_DRIVER)
7906 {
7907 AssertMsgFailed(("Configuration error: Not possible to attach anything to this driver!\n"));
7908 return VERR_PDM_DRVINS_NO_ATTACH;
7909 }
7910
7911 /*
7912 * Data.
7913 */
7914 pDrvIns->IBase.pfnQueryInterface = Console::drvStatus_QueryInterface;
7915 pData->ILedConnectors.pfnUnitChanged = Console::drvStatus_UnitChanged;
7916
7917 /*
7918 * Read config.
7919 */
7920 rc = CFGMR3QueryPtr(pCfgHandle, "papLeds", (void **)&pData->papLeds);
7921 if (VBOX_FAILURE(rc))
7922 {
7923 AssertMsgFailed(("Configuration error: Failed to query the \"papLeds\" value! rc=%Vrc\n", rc));
7924 return rc;
7925 }
7926
7927 rc = CFGMR3QueryU32(pCfgHandle, "First", &pData->iFirstLUN);
7928 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
7929 pData->iFirstLUN = 0;
7930 else if (VBOX_FAILURE(rc))
7931 {
7932 AssertMsgFailed(("Configuration error: Failed to query the \"First\" value! rc=%Vrc\n", rc));
7933 return rc;
7934 }
7935
7936 rc = CFGMR3QueryU32(pCfgHandle, "Last", &pData->iLastLUN);
7937 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
7938 pData->iLastLUN = 0;
7939 else if (VBOX_FAILURE(rc))
7940 {
7941 AssertMsgFailed(("Configuration error: Failed to query the \"Last\" value! rc=%Vrc\n", rc));
7942 return rc;
7943 }
7944 if (pData->iFirstLUN > pData->iLastLUN)
7945 {
7946 AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pData->iFirstLUN, pData->iLastLUN));
7947 return VERR_GENERAL_FAILURE;
7948 }
7949
7950 /*
7951 * Get the ILedPorts interface of the above driver/device and
7952 * query the LEDs we want.
7953 */
7954 pData->pLedPorts = (PPDMILEDPORTS)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_LED_PORTS);
7955 if (!pData->pLedPorts)
7956 {
7957 AssertMsgFailed(("Configuration error: No led ports interface above!\n"));
7958 return VERR_PDM_MISSING_INTERFACE_ABOVE;
7959 }
7960
7961 for (unsigned i = pData->iFirstLUN; i <= pData->iLastLUN; i++)
7962 Console::drvStatus_UnitChanged(&pData->ILedConnectors, i);
7963
7964 return VINF_SUCCESS;
7965}
7966
7967
7968/**
7969 * Keyboard driver registration record.
7970 */
7971const PDMDRVREG Console::DrvStatusReg =
7972{
7973 /* u32Version */
7974 PDM_DRVREG_VERSION,
7975 /* szDriverName */
7976 "MainStatus",
7977 /* pszDescription */
7978 "Main status driver (Main as in the API).",
7979 /* fFlags */
7980 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
7981 /* fClass. */
7982 PDM_DRVREG_CLASS_STATUS,
7983 /* cMaxInstances */
7984 ~0,
7985 /* cbInstance */
7986 sizeof(DRVMAINSTATUS),
7987 /* pfnConstruct */
7988 Console::drvStatus_Construct,
7989 /* pfnDestruct */
7990 Console::drvStatus_Destruct,
7991 /* pfnIOCtl */
7992 NULL,
7993 /* pfnPowerOn */
7994 NULL,
7995 /* pfnReset */
7996 NULL,
7997 /* pfnSuspend */
7998 NULL,
7999 /* pfnResume */
8000 NULL,
8001 /* pfnDetach */
8002 NULL
8003};
8004
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