VirtualBox

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

Last change on this file since 15256 was 15166, checked in by vboxsync, 16 years ago

Main and HostServices/GuestProps: additional logging

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