VirtualBox

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

Last change on this file since 4753 was 4540, checked in by vboxsync, 17 years ago

Implemented notification for guest about an active VRDP connection.

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

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