VirtualBox

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

Last change on this file since 15091 was 15051, checked in by vboxsync, 16 years ago

Main: Cleaned up the long standing const BSTR = const (OLECHAR *) on WIn32 vs (const PRunichar) * on XPCOM clash. Cleaned up BSTR/GUID macros (IN_BSTR replaces INPTR BSTR, IN_GUID replaces INPTR GUIDPARAM, OUT_GUID replaces GUIDPARAMOUT).

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