VirtualBox

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

Last change on this file since 15941 was 15762, checked in by vboxsync, 16 years ago

Main: Exmplicit machine state comparisons replaced with bool "IsMetastate"-like methods.

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

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