VirtualBox

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

Last change on this file since 2527 was 2527, checked in by vboxsync, 18 years ago

Check VRDP multiconnection property. A new external authentication prototype for multiconnection.

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

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