VirtualBox

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

Last change on this file since 15741 was 15708, checked in by vboxsync, 16 years ago

Main: #3424: Bumped XML format version to 1.6 and so that the auto-converter will delete old <HostInterface> nodes containing TAPSetup/TAPTerminate attributes. Removed all (obsolete) sections of code in #ifdef VBOX_WITH_UNIXY_TAP_NETWORKING (that uses these attributes); removed the define itself.

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