VirtualBox

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

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

Main: #3314: Don't delete the saved state file if restoring the VM fails in the middle of VMR3Load() (for example due to the state file incompatibility).

  • 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 15448 2008-12-13 19:32:05Z 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/Restoring to Stopping because vmstateChangeCallback() needs it to
4601 * set the state to Saved on VMSTATE_TERMINATED. In terms of protecting from
4602 * inappropriate operations while leaving the lock below, Saving or
4603 * Restoring should be fine too */
4604 if (mMachineState != MachineState_Saving &&
4605 mMachineState != MachineState_Restoring &&
4606 mMachineState != MachineState_Stopping)
4607 setMachineState (MachineState_Stopping);
4608
4609 /* ----------------------------------------------------------------------
4610 * DONE with necessary state changes, perform the power down actions (it's
4611 * safe to leave the object lock now if needed)
4612 * ---------------------------------------------------------------------- */
4613
4614 /* Stop the VRDP server to prevent new clients connection while VM is being
4615 * powered off. */
4616 if (mConsoleVRDPServer)
4617 {
4618 LogFlowThisFunc (("Stopping VRDP server...\n"));
4619
4620 /* Leave the lock since EMT will call us back as addVMCaller()
4621 * in updateDisplayData(). */
4622 alock.leave();
4623
4624 mConsoleVRDPServer->Stop();
4625
4626 alock.enter();
4627 }
4628
4629 /* advance percent count */
4630 if (aProgress)
4631 aProgress->notifyProgress (99 * (++ step) / StepCount );
4632
4633#ifdef VBOX_WITH_HGCM
4634
4635# ifdef VBOX_WITH_GUEST_PROPS
4636
4637 /* Save all guest property store entries to the machine XML file */
4638 com::SafeArray <BSTR> namesOut;
4639 com::SafeArray <BSTR> valuesOut;
4640 com::SafeArray <ULONG64> timestampsOut;
4641 com::SafeArray <BSTR> flagsOut;
4642 Bstr pattern("");
4643 if (pattern.isNull())
4644 rc = E_OUTOFMEMORY;
4645 else
4646 rc = doEnumerateGuestProperties (Bstr (""), ComSafeArrayAsOutParam (namesOut),
4647 ComSafeArrayAsOutParam (valuesOut),
4648 ComSafeArrayAsOutParam (timestampsOut),
4649 ComSafeArrayAsOutParam (flagsOut));
4650 if (SUCCEEDED(rc))
4651 {
4652 try
4653 {
4654 std::vector <BSTR> names;
4655 std::vector <BSTR> values;
4656 std::vector <ULONG64> timestamps;
4657 std::vector <BSTR> flags;
4658 for (unsigned i = 0; i < namesOut.size(); ++i)
4659 {
4660 uint32_t fFlags;
4661 guestProp::validateFlags (Utf8Str(flagsOut[i]).raw(), &fFlags);
4662 if ( !( fFlags & guestProp::TRANSIENT)
4663 || (mMachineState == MachineState_Saving)
4664 )
4665 {
4666 names.push_back(namesOut[i]);
4667 values.push_back(valuesOut[i]);
4668 timestamps.push_back(timestampsOut[i]);
4669 flags.push_back(flagsOut[i]);
4670 }
4671 }
4672 com::SafeArray <BSTR> namesIn (names);
4673 com::SafeArray <BSTR> valuesIn (values);
4674 com::SafeArray <ULONG64> timestampsIn (timestamps);
4675 com::SafeArray <BSTR> flagsIn (flags);
4676 if ( namesIn.isNull()
4677 || valuesIn.isNull()
4678 || timestampsIn.isNull()
4679 || flagsIn.isNull()
4680 )
4681 throw std::bad_alloc();
4682 /* PushGuestProperties() calls DiscardSettings(), which calls us back */
4683 alock.leave();
4684 mControl->PushGuestProperties (ComSafeArrayAsInParam (namesIn),
4685 ComSafeArrayAsInParam (valuesIn),
4686 ComSafeArrayAsInParam (timestampsIn),
4687 ComSafeArrayAsInParam (flagsIn));
4688 alock.enter();
4689 }
4690 catch (std::bad_alloc)
4691 {
4692 rc = E_OUTOFMEMORY;
4693 }
4694 }
4695
4696 /* advance percent count */
4697 if (aProgress)
4698 aProgress->notifyProgress (99 * (++ step) / StepCount );
4699
4700# endif /* VBOX_WITH_GUEST_PROPS defined */
4701
4702 /* Shutdown HGCM services before stopping the guest, because they might
4703 * need a cleanup. */
4704 if (mVMMDev)
4705 {
4706 LogFlowThisFunc (("Shutdown HGCM...\n"));
4707
4708 /* Leave the lock since EMT will call us back as addVMCaller() */
4709 alock.leave();
4710
4711 mVMMDev->hgcmShutdown ();
4712
4713 alock.enter();
4714 }
4715
4716 /* advance percent count */
4717 if (aProgress)
4718 aProgress->notifyProgress (99 * (++ step) / StepCount );
4719
4720#endif /* VBOX_WITH_HGCM */
4721
4722 /* ----------------------------------------------------------------------
4723 * Now, wait for all mpVM callers to finish their work if there are still
4724 * some on other threads. NO methods that need mpVM (or initiate other calls
4725 * that need it) may be called after this point
4726 * ---------------------------------------------------------------------- */
4727
4728 if (mVMCallers > 0)
4729 {
4730 /* go to the destroying state to prevent from adding new callers */
4731 mVMDestroying = true;
4732
4733 /* lazy creation */
4734 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
4735 RTSemEventCreate (&mVMZeroCallersSem);
4736
4737 LogFlowThisFunc (("Waiting for mpVM callers (%d) to drop to zero...\n",
4738 mVMCallers));
4739
4740 alock.leave();
4741
4742 RTSemEventWait (mVMZeroCallersSem, RT_INDEFINITE_WAIT);
4743
4744 alock.enter();
4745 }
4746
4747 /* advance percent count */
4748 if (aProgress)
4749 aProgress->notifyProgress (99 * (++ step) / StepCount );
4750
4751 vrc = VINF_SUCCESS;
4752
4753 /* Power off the VM if not already done that */
4754 if (!mVMPoweredOff)
4755 {
4756 LogFlowThisFunc (("Powering off the VM...\n"));
4757
4758 /* Leave the lock since EMT will call us back on VMR3PowerOff() */
4759 alock.leave();
4760
4761 vrc = VMR3PowerOff (mpVM);
4762
4763 /* Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
4764 * VM-(guest-)initiated power off happened in parallel a ms before this
4765 * call. So far, we let this error pop up on the user's side. */
4766
4767 alock.enter();
4768
4769 }
4770 else
4771 {
4772 /* reset the flag for further re-use */
4773 mVMPoweredOff = false;
4774 }
4775
4776 /* advance percent count */
4777 if (aProgress)
4778 aProgress->notifyProgress (99 * (++ step) / StepCount );
4779
4780 LogFlowThisFunc (("Ready for VM destruction.\n"));
4781
4782 /* If we are called from Console::uninit(), then try to destroy the VM even
4783 * on failure (this will most likely fail too, but what to do?..) */
4784 if (VBOX_SUCCESS (vrc) || autoCaller.state() == InUninit)
4785 {
4786 /* If the machine has an USB comtroller, release all USB devices
4787 * (symmetric to the code in captureUSBDevices()) */
4788 bool fHasUSBController = false;
4789 {
4790 PPDMIBASE pBase;
4791 int vrc = PDMR3QueryLun (mpVM, "usb-ohci", 0, 0, &pBase);
4792 if (VBOX_SUCCESS (vrc))
4793 {
4794 fHasUSBController = true;
4795 detachAllUSBDevices (false /* aDone */);
4796 }
4797 }
4798
4799 /* Now we've got to destroy the VM as well. (mpVM is not valid beyond
4800 * this point). We leave the lock before calling VMR3Destroy() because
4801 * it will result into calling destructors of drivers associated with
4802 * Console children which may in turn try to lock Console (e.g. by
4803 * instantiating SafeVMPtr to access mpVM). It's safe here because
4804 * mVMDestroying is set which should prevent any activity. */
4805
4806 /* Set mpVM to NULL early just in case if some old code is not using
4807 * addVMCaller()/releaseVMCaller(). */
4808 PVM pVM = mpVM;
4809 mpVM = NULL;
4810
4811 LogFlowThisFunc (("Destroying the VM...\n"));
4812
4813 alock.leave();
4814
4815 vrc = VMR3Destroy (pVM);
4816
4817 /* take the lock again */
4818 alock.enter();
4819
4820 /* advance percent count */
4821 if (aProgress)
4822 aProgress->notifyProgress (99 * (++ step) / StepCount );
4823
4824 if (VBOX_SUCCESS (vrc))
4825 {
4826 LogFlowThisFunc (("Machine has been destroyed (mMachineState=%d)\n",
4827 mMachineState));
4828 /* Note: the Console-level machine state change happens on the
4829 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
4830 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
4831 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
4832 * occurred yet. This is okay, because mMachineState is already
4833 * Stopping in this case, so any other attempt to call PowerDown()
4834 * will be rejected. */
4835 }
4836 else
4837 {
4838 /* bad bad bad, but what to do? */
4839 mpVM = pVM;
4840 rc = setError (VBOX_E_VM_ERROR,
4841 tr ("Could not destroy the machine. (Error: %Rrc)"), vrc);
4842 }
4843
4844 /* Complete the detaching of the USB devices. */
4845 if (fHasUSBController)
4846 detachAllUSBDevices (true /* aDone */);
4847
4848 /* advance percent count */
4849 if (aProgress)
4850 aProgress->notifyProgress (99 * (++ step) / StepCount );
4851 }
4852 else
4853 {
4854 rc = setError (VBOX_E_VM_ERROR,
4855 tr ("Could not power off the machine. (Error: %Rrc)"), vrc);
4856 }
4857
4858 /* Finished with destruction. Note that if something impossible happened and
4859 * we've failed to destroy the VM, mVMDestroying will remain true and
4860 * mMachineState will be something like Stopping, so most Console methods
4861 * will return an error to the caller. */
4862 if (mpVM == NULL)
4863 mVMDestroying = false;
4864
4865 if (SUCCEEDED (rc))
4866 {
4867 /* uninit dynamically allocated members of mCallbackData */
4868 if (mCallbackData.mpsc.valid)
4869 {
4870 if (mCallbackData.mpsc.shape != NULL)
4871 RTMemFree (mCallbackData.mpsc.shape);
4872 }
4873 memset (&mCallbackData, 0, sizeof (mCallbackData));
4874 }
4875
4876 /* complete the progress */
4877 if (aProgress)
4878 aProgress->notifyComplete (rc);
4879
4880 LogFlowThisFuncLeave();
4881 return rc;
4882}
4883
4884/**
4885 * @note Locks this object for writing.
4886 */
4887HRESULT Console::setMachineState (MachineState_T aMachineState,
4888 bool aUpdateServer /* = true */)
4889{
4890 AutoCaller autoCaller (this);
4891 AssertComRCReturnRC (autoCaller.rc());
4892
4893 AutoWriteLock alock (this);
4894
4895 HRESULT rc = S_OK;
4896
4897 if (mMachineState != aMachineState)
4898 {
4899 LogFlowThisFunc (("machineState=%d\n", aMachineState));
4900 mMachineState = aMachineState;
4901
4902 /// @todo (dmik)
4903 // possibly, we need to redo onStateChange() using the dedicated
4904 // Event thread, like it is done in VirtualBox. This will make it
4905 // much safer (no deadlocks possible if someone tries to use the
4906 // console from the callback), however, listeners will lose the
4907 // ability to synchronously react to state changes (is it really
4908 // necessary??)
4909 LogFlowThisFunc (("Doing onStateChange()...\n"));
4910 onStateChange (aMachineState);
4911 LogFlowThisFunc (("Done onStateChange()\n"));
4912
4913 if (aUpdateServer)
4914 {
4915 /*
4916 * Server notification MUST be done from under the lock; otherwise
4917 * the machine state here and on the server might go out of sync, that
4918 * can lead to various unexpected results (like the machine state being
4919 * >= MachineState_Running on the server, while the session state is
4920 * already SessionState_Closed at the same time there).
4921 *
4922 * Cross-lock conditions should be carefully watched out: calling
4923 * UpdateState we will require Machine and SessionMachine locks
4924 * (remember that here we're holding the Console lock here, and
4925 * also all locks that have been entered by the thread before calling
4926 * this method).
4927 */
4928 LogFlowThisFunc (("Doing mControl->UpdateState()...\n"));
4929 rc = mControl->UpdateState (aMachineState);
4930 LogFlowThisFunc (("mControl->UpdateState()=%08X\n", rc));
4931 }
4932 }
4933
4934 return rc;
4935}
4936
4937/**
4938 * Searches for a shared folder with the given logical name
4939 * in the collection of shared folders.
4940 *
4941 * @param aName logical name of the shared folder
4942 * @param aSharedFolder where to return the found object
4943 * @param aSetError whether to set the error info if the folder is
4944 * not found
4945 * @return
4946 * S_OK when found or E_INVALIDARG when not found
4947 *
4948 * @note The caller must lock this object for writing.
4949 */
4950HRESULT Console::findSharedFolder (CBSTR aName,
4951 ComObjPtr <SharedFolder> &aSharedFolder,
4952 bool aSetError /* = false */)
4953{
4954 /* sanity check */
4955 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
4956
4957 SharedFolderMap::const_iterator it = mSharedFolders.find (aName);
4958 if (it != mSharedFolders.end())
4959 {
4960 aSharedFolder = it->second;
4961 return S_OK;
4962 }
4963
4964 if (aSetError)
4965 setError (VBOX_E_FILE_ERROR,
4966 tr ("Could not find a shared folder named '%ls'."), aName);
4967
4968 return VBOX_E_FILE_ERROR;
4969}
4970
4971/**
4972 * Fetches the list of global or machine shared folders from the server.
4973 *
4974 * @param aGlobal true to fetch global folders.
4975 *
4976 * @note The caller must lock this object for writing.
4977 */
4978HRESULT Console::fetchSharedFolders (BOOL aGlobal)
4979{
4980 /* sanity check */
4981 AssertReturn (AutoCaller (this).state() == InInit ||
4982 isWriteLockOnCurrentThread(), E_FAIL);
4983
4984 /* protect mpVM (if not NULL) */
4985 AutoVMCallerQuietWeak autoVMCaller (this);
4986
4987 HRESULT rc = S_OK;
4988
4989 bool online = mpVM && autoVMCaller.isOk() && mVMMDev->isShFlActive();
4990
4991 if (aGlobal)
4992 {
4993 /// @todo grab & process global folders when they are done
4994 }
4995 else
4996 {
4997 SharedFolderDataMap oldFolders;
4998 if (online)
4999 oldFolders = mMachineSharedFolders;
5000
5001 mMachineSharedFolders.clear();
5002
5003 ComPtr <ISharedFolderCollection> coll;
5004 rc = mMachine->COMGETTER(SharedFolders) (coll.asOutParam());
5005 AssertComRCReturnRC (rc);
5006
5007 ComPtr <ISharedFolderEnumerator> en;
5008 rc = coll->Enumerate (en.asOutParam());
5009 AssertComRCReturnRC (rc);
5010
5011 BOOL hasMore = FALSE;
5012 while (SUCCEEDED (rc = en->HasMore (&hasMore)) && hasMore)
5013 {
5014 ComPtr <ISharedFolder> folder;
5015 rc = en->GetNext (folder.asOutParam());
5016 CheckComRCBreakRC (rc);
5017
5018 Bstr name;
5019 Bstr hostPath;
5020 BOOL writable;
5021
5022 rc = folder->COMGETTER(Name) (name.asOutParam());
5023 CheckComRCBreakRC (rc);
5024 rc = folder->COMGETTER(HostPath) (hostPath.asOutParam());
5025 CheckComRCBreakRC (rc);
5026 rc = folder->COMGETTER(Writable) (&writable);
5027
5028 mMachineSharedFolders.insert (std::make_pair (name, SharedFolderData (hostPath, writable)));
5029
5030 /* send changes to HGCM if the VM is running */
5031 /// @todo report errors as runtime warnings through VMSetError
5032 if (online)
5033 {
5034 SharedFolderDataMap::iterator it = oldFolders.find (name);
5035 if (it == oldFolders.end() || it->second.mHostPath != hostPath)
5036 {
5037 /* a new machine folder is added or
5038 * the existing machine folder is changed */
5039 if (mSharedFolders.find (name) != mSharedFolders.end())
5040 ; /* the console folder exists, nothing to do */
5041 else
5042 {
5043 /* remove the old machine folder (when changed)
5044 * or the global folder if any (when new) */
5045 if (it != oldFolders.end() ||
5046 mGlobalSharedFolders.find (name) !=
5047 mGlobalSharedFolders.end())
5048 rc = removeSharedFolder (name);
5049 /* create the new machine folder */
5050 rc = createSharedFolder (name, SharedFolderData (hostPath, writable));
5051 }
5052 }
5053 /* forget the processed (or identical) folder */
5054 if (it != oldFolders.end())
5055 oldFolders.erase (it);
5056
5057 rc = S_OK;
5058 }
5059 }
5060
5061 AssertComRCReturnRC (rc);
5062
5063 /* process outdated (removed) folders */
5064 /// @todo report errors as runtime warnings through VMSetError
5065 if (online)
5066 {
5067 for (SharedFolderDataMap::const_iterator it = oldFolders.begin();
5068 it != oldFolders.end(); ++ it)
5069 {
5070 if (mSharedFolders.find (it->first) != mSharedFolders.end())
5071 ; /* the console folder exists, nothing to do */
5072 else
5073 {
5074 /* remove the outdated machine folder */
5075 rc = removeSharedFolder (it->first);
5076 /* create the global folder if there is any */
5077 SharedFolderDataMap::const_iterator git =
5078 mGlobalSharedFolders.find (it->first);
5079 if (git != mGlobalSharedFolders.end())
5080 rc = createSharedFolder (git->first, git->second);
5081 }
5082 }
5083
5084 rc = S_OK;
5085 }
5086 }
5087
5088 return rc;
5089}
5090
5091/**
5092 * Searches for a shared folder with the given name in the list of machine
5093 * shared folders and then in the list of the global shared folders.
5094 *
5095 * @param aName Name of the folder to search for.
5096 * @param aIt Where to store the pointer to the found folder.
5097 * @return @c true if the folder was found and @c false otherwise.
5098 *
5099 * @note The caller must lock this object for reading.
5100 */
5101bool Console::findOtherSharedFolder (IN_BSTR aName,
5102 SharedFolderDataMap::const_iterator &aIt)
5103{
5104 /* sanity check */
5105 AssertReturn (isWriteLockOnCurrentThread(), false);
5106
5107 /* first, search machine folders */
5108 aIt = mMachineSharedFolders.find (aName);
5109 if (aIt != mMachineSharedFolders.end())
5110 return true;
5111
5112 /* second, search machine folders */
5113 aIt = mGlobalSharedFolders.find (aName);
5114 if (aIt != mGlobalSharedFolders.end())
5115 return true;
5116
5117 return false;
5118}
5119
5120/**
5121 * Calls the HGCM service to add a shared folder definition.
5122 *
5123 * @param aName Shared folder name.
5124 * @param aHostPath Shared folder path.
5125 *
5126 * @note Must be called from under AutoVMCaller and when mpVM != NULL!
5127 * @note Doesn't lock anything.
5128 */
5129HRESULT Console::createSharedFolder (CBSTR aName, SharedFolderData aData)
5130{
5131 ComAssertRet (aName && *aName, E_FAIL);
5132 ComAssertRet (aData.mHostPath, E_FAIL);
5133
5134 /* sanity checks */
5135 AssertReturn (mpVM, E_FAIL);
5136 AssertReturn (mVMMDev->isShFlActive(), E_FAIL);
5137
5138 VBOXHGCMSVCPARM parms[SHFL_CPARMS_ADD_MAPPING];
5139 SHFLSTRING *pFolderName, *pMapName;
5140 size_t cbString;
5141
5142 Log (("Adding shared folder '%ls' -> '%ls'\n", aName, aData.mHostPath.raw()));
5143
5144 cbString = (RTUtf16Len (aData.mHostPath) + 1) * sizeof (RTUTF16);
5145 if (cbString >= UINT16_MAX)
5146 return setError (E_INVALIDARG, tr ("The name is too long"));
5147 pFolderName = (SHFLSTRING *) RTMemAllocZ (sizeof (SHFLSTRING) + cbString);
5148 Assert (pFolderName);
5149 memcpy (pFolderName->String.ucs2, aData.mHostPath, cbString);
5150
5151 pFolderName->u16Size = (uint16_t)cbString;
5152 pFolderName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
5153
5154 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
5155 parms[0].u.pointer.addr = pFolderName;
5156 parms[0].u.pointer.size = sizeof (SHFLSTRING) + (uint16_t)cbString;
5157
5158 cbString = (RTUtf16Len (aName) + 1) * sizeof (RTUTF16);
5159 if (cbString >= UINT16_MAX)
5160 {
5161 RTMemFree (pFolderName);
5162 return setError (E_INVALIDARG, tr ("The host path is too long"));
5163 }
5164 pMapName = (SHFLSTRING *) RTMemAllocZ (sizeof(SHFLSTRING) + cbString);
5165 Assert (pMapName);
5166 memcpy (pMapName->String.ucs2, aName, cbString);
5167
5168 pMapName->u16Size = (uint16_t)cbString;
5169 pMapName->u16Length = (uint16_t)cbString - sizeof (RTUTF16);
5170
5171 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
5172 parms[1].u.pointer.addr = pMapName;
5173 parms[1].u.pointer.size = sizeof (SHFLSTRING) + (uint16_t)cbString;
5174
5175 parms[2].type = VBOX_HGCM_SVC_PARM_32BIT;
5176 parms[2].u.uint32 = aData.mWritable;
5177
5178 int vrc = mVMMDev->hgcmHostCall ("VBoxSharedFolders",
5179 SHFL_FN_ADD_MAPPING,
5180 SHFL_CPARMS_ADD_MAPPING, &parms[0]);
5181 RTMemFree (pFolderName);
5182 RTMemFree (pMapName);
5183
5184 if (VBOX_FAILURE (vrc))
5185 return setError (E_FAIL,
5186 tr ("Could not create a shared folder '%ls' "
5187 "mapped to '%ls' (%Rrc)"),
5188 aName, aData.mHostPath.raw(), vrc);
5189
5190 return S_OK;
5191}
5192
5193/**
5194 * Calls the HGCM service to remove the shared folder definition.
5195 *
5196 * @param aName Shared folder name.
5197 *
5198 * @note Must be called from under AutoVMCaller and when mpVM != NULL!
5199 * @note Doesn't lock anything.
5200 */
5201HRESULT Console::removeSharedFolder (CBSTR aName)
5202{
5203 ComAssertRet (aName && *aName, E_FAIL);
5204
5205 /* sanity checks */
5206 AssertReturn (mpVM, E_FAIL);
5207 AssertReturn (mVMMDev->isShFlActive(), E_FAIL);
5208
5209 VBOXHGCMSVCPARM parms;
5210 SHFLSTRING *pMapName;
5211 size_t cbString;
5212
5213 Log (("Removing shared folder '%ls'\n", aName));
5214
5215 cbString = (RTUtf16Len (aName) + 1) * sizeof (RTUTF16);
5216 if (cbString >= UINT16_MAX)
5217 return setError (E_INVALIDARG, tr ("The name is too long"));
5218 pMapName = (SHFLSTRING *) RTMemAllocZ (sizeof (SHFLSTRING) + cbString);
5219 Assert (pMapName);
5220 memcpy (pMapName->String.ucs2, aName, cbString);
5221
5222 pMapName->u16Size = (uint16_t)cbString;
5223 pMapName->u16Length = (uint16_t)cbString - sizeof (RTUTF16);
5224
5225 parms.type = VBOX_HGCM_SVC_PARM_PTR;
5226 parms.u.pointer.addr = pMapName;
5227 parms.u.pointer.size = sizeof (SHFLSTRING) + (uint16_t)cbString;
5228
5229 int vrc = mVMMDev->hgcmHostCall ("VBoxSharedFolders",
5230 SHFL_FN_REMOVE_MAPPING,
5231 1, &parms);
5232 RTMemFree(pMapName);
5233 if (VBOX_FAILURE (vrc))
5234 return setError (E_FAIL,
5235 tr ("Could not remove the shared folder '%ls' (%Rrc)"),
5236 aName, vrc);
5237
5238 return S_OK;
5239}
5240
5241/**
5242 * VM state callback function. Called by the VMM
5243 * using its state machine states.
5244 *
5245 * Primarily used to handle VM initiated power off, suspend and state saving,
5246 * but also for doing termination completed work (VMSTATE_TERMINATE).
5247 *
5248 * In general this function is called in the context of the EMT.
5249 *
5250 * @param aVM The VM handle.
5251 * @param aState The new state.
5252 * @param aOldState The old state.
5253 * @param aUser The user argument (pointer to the Console object).
5254 *
5255 * @note Locks the Console object for writing.
5256 */
5257DECLCALLBACK(void)
5258Console::vmstateChangeCallback (PVM aVM, VMSTATE aState, VMSTATE aOldState,
5259 void *aUser)
5260{
5261 LogFlowFunc (("Changing state from %d to %d (aVM=%p)\n",
5262 aOldState, aState, aVM));
5263
5264 Console *that = static_cast <Console *> (aUser);
5265 AssertReturnVoid (that);
5266
5267 AutoCaller autoCaller (that);
5268
5269 /* Note that we must let this method proceed even if Console::uninit() has
5270 * been already called. In such case this VMSTATE change is a result of:
5271 * 1) powerDown() called from uninit() itself, or
5272 * 2) VM-(guest-)initiated power off. */
5273 AssertReturnVoid (autoCaller.isOk() ||
5274 autoCaller.state() == InUninit);
5275
5276 switch (aState)
5277 {
5278 /*
5279 * The VM has terminated
5280 */
5281 case VMSTATE_OFF:
5282 {
5283 AutoWriteLock alock (that);
5284
5285 if (that->mVMStateChangeCallbackDisabled)
5286 break;
5287
5288 /* Do we still think that it is running? It may happen if this is a
5289 * VM-(guest-)initiated shutdown/poweroff.
5290 */
5291 if (that->mMachineState != MachineState_Stopping &&
5292 that->mMachineState != MachineState_Saving &&
5293 that->mMachineState != MachineState_Restoring)
5294 {
5295 LogFlowFunc (("VM has powered itself off but Console still "
5296 "thinks it is running. Notifying.\n"));
5297
5298 /* prevent powerDown() from calling VMR3PowerOff() again */
5299 Assert (that->mVMPoweredOff == false);
5300 that->mVMPoweredOff = true;
5301
5302 /* we are stopping now */
5303 that->setMachineState (MachineState_Stopping);
5304
5305 /* Setup task object and thread to carry out the operation
5306 * asynchronously (if we call powerDown() right here but there
5307 * is one or more mpVM callers (added with addVMCaller()) we'll
5308 * deadlock).
5309 */
5310 std::auto_ptr <VMProgressTask> task (
5311 new VMProgressTask (that, NULL /* aProgress */,
5312 true /* aUsesVMPtr */));
5313
5314 /* If creating a task is falied, this can currently mean one of
5315 * two: either Console::uninit() has been called just a ms
5316 * before (so a powerDown() call is already on the way), or
5317 * powerDown() itself is being already executed. Just do
5318 * nothing.
5319 */
5320 if (!task->isOk())
5321 {
5322 LogFlowFunc (("Console is already being uninitialized.\n"));
5323 break;
5324 }
5325
5326 int vrc = RTThreadCreate (NULL, Console::powerDownThread,
5327 (void *) task.get(), 0,
5328 RTTHREADTYPE_MAIN_WORKER, 0,
5329 "VMPowerDown");
5330
5331 AssertMsgRCBreak (vrc,
5332 ("Could not create VMPowerDown thread (%Rrc)\n", vrc));
5333
5334 /* task is now owned by powerDownThread(), so release it */
5335 task.release();
5336 }
5337 break;
5338 }
5339
5340 /* The VM has been completely destroyed.
5341 *
5342 * Note: This state change can happen at two points:
5343 * 1) At the end of VMR3Destroy() if it was not called from EMT.
5344 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
5345 * called by EMT.
5346 */
5347 case VMSTATE_TERMINATED:
5348 {
5349 AutoWriteLock alock (that);
5350
5351 if (that->mVMStateChangeCallbackDisabled)
5352 break;
5353
5354 /* Terminate host interface networking. If aVM is NULL, we've been
5355 * manually called from powerUpThread() either before calling
5356 * VMR3Create() or after VMR3Create() failed, so no need to touch
5357 * networking.
5358 */
5359 if (aVM)
5360 that->powerDownHostInterfaces();
5361
5362 /* From now on the machine is officially powered down or remains in
5363 * the Saved state.
5364 */
5365 switch (that->mMachineState)
5366 {
5367 default:
5368 AssertFailed();
5369 /* fall through */
5370 case MachineState_Stopping:
5371 /* successfully powered down */
5372 that->setMachineState (MachineState_PoweredOff);
5373 break;
5374 case MachineState_Saving:
5375 /* successfully saved (note that the machine is already in
5376 * the Saved state on the server due to EndSavingState()
5377 * called from saveStateThread(), so only change the local
5378 * state) */
5379 that->setMachineStateLocally (MachineState_Saved);
5380 break;
5381 case MachineState_Starting:
5382 /* failed to start, but be patient: set back to PoweredOff
5383 * (for similarity with the below) */
5384 that->setMachineState (MachineState_PoweredOff);
5385 break;
5386 case MachineState_Restoring:
5387 /* failed to load the saved state file, but be patient: set
5388 * back to Saved (to preserve the saved state file) */
5389 that->setMachineState (MachineState_Saved);
5390 break;
5391 }
5392
5393 break;
5394 }
5395
5396 case VMSTATE_SUSPENDED:
5397 {
5398 if (aOldState == VMSTATE_RUNNING)
5399 {
5400 AutoWriteLock alock (that);
5401
5402 if (that->mVMStateChangeCallbackDisabled)
5403 break;
5404
5405 /* Change the machine state from Running to Paused */
5406 Assert (that->mMachineState == MachineState_Running);
5407 that->setMachineState (MachineState_Paused);
5408 }
5409
5410 break;
5411 }
5412
5413 case VMSTATE_RUNNING:
5414 {
5415 if (aOldState == VMSTATE_CREATED ||
5416 aOldState == VMSTATE_SUSPENDED)
5417 {
5418 AutoWriteLock alock (that);
5419
5420 if (that->mVMStateChangeCallbackDisabled)
5421 break;
5422
5423 /* Change the machine state from Starting, Restoring or Paused
5424 * to Running */
5425 Assert ( ( ( that->mMachineState == MachineState_Starting
5426 || that->mMachineState == MachineState_Paused)
5427 && aOldState == VMSTATE_CREATED)
5428 || ( ( that->mMachineState == MachineState_Restoring
5429 || that->mMachineState == MachineState_Paused)
5430 && aOldState == VMSTATE_SUSPENDED));
5431
5432 that->setMachineState (MachineState_Running);
5433 }
5434
5435 break;
5436 }
5437
5438 case VMSTATE_GURU_MEDITATION:
5439 {
5440 AutoWriteLock alock (that);
5441
5442 if (that->mVMStateChangeCallbackDisabled)
5443 break;
5444
5445 /* Guru respects only running VMs */
5446 Assert ((that->mMachineState >= MachineState_Running));
5447
5448 that->setMachineState (MachineState_Stuck);
5449
5450 break;
5451 }
5452
5453 default: /* shut up gcc */
5454 break;
5455 }
5456}
5457
5458#ifdef VBOX_WITH_USB
5459
5460/**
5461 * Sends a request to VMM to attach the given host device.
5462 * After this method succeeds, the attached device will appear in the
5463 * mUSBDevices collection.
5464 *
5465 * @param aHostDevice device to attach
5466 *
5467 * @note Synchronously calls EMT.
5468 * @note Must be called from under this object's lock.
5469 */
5470HRESULT Console::attachUSBDevice (IUSBDevice *aHostDevice, ULONG aMaskedIfs)
5471{
5472 AssertReturn (aHostDevice, E_FAIL);
5473 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5474
5475 /* still want a lock object because we need to leave it */
5476 AutoWriteLock alock (this);
5477
5478 HRESULT hrc;
5479
5480 /*
5481 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
5482 * method in EMT (using usbAttachCallback()).
5483 */
5484 Bstr BstrAddress;
5485 hrc = aHostDevice->COMGETTER (Address) (BstrAddress.asOutParam());
5486 ComAssertComRCRetRC (hrc);
5487
5488 Utf8Str Address (BstrAddress);
5489
5490 Guid Uuid;
5491 hrc = aHostDevice->COMGETTER (Id) (Uuid.asOutParam());
5492 ComAssertComRCRetRC (hrc);
5493
5494 BOOL fRemote = FALSE;
5495 hrc = aHostDevice->COMGETTER (Remote) (&fRemote);
5496 ComAssertComRCRetRC (hrc);
5497
5498 /* protect mpVM */
5499 AutoVMCaller autoVMCaller (this);
5500 CheckComRCReturnRC (autoVMCaller.rc());
5501
5502 LogFlowThisFunc (("Proxying USB device '%s' {%RTuuid}...\n",
5503 Address.raw(), Uuid.ptr()));
5504
5505 /* leave the lock before a VMR3* call (EMT will call us back)! */
5506 alock.leave();
5507
5508/** @todo just do everything here and only wrap the PDMR3Usb call. That'll offload some notification stuff from the EMT thread. */
5509 PVMREQ pReq = NULL;
5510 int vrc = VMR3ReqCall (mpVM, VMREQDEST_ANY, &pReq, RT_INDEFINITE_WAIT,
5511 (PFNRT) usbAttachCallback, 6, this, aHostDevice, Uuid.ptr(), fRemote, Address.raw(), aMaskedIfs);
5512 if (VBOX_SUCCESS (vrc))
5513 vrc = pReq->iStatus;
5514 VMR3ReqFree (pReq);
5515
5516 /* restore the lock */
5517 alock.enter();
5518
5519 /* hrc is S_OK here */
5520
5521 if (VBOX_FAILURE (vrc))
5522 {
5523 LogWarningThisFunc (("Failed to create proxy device for '%s' {%RTuuid} (%Rrc)\n",
5524 Address.raw(), Uuid.ptr(), vrc));
5525
5526 switch (vrc)
5527 {
5528 case VERR_VUSB_NO_PORTS:
5529 hrc = setError (E_FAIL,
5530 tr ("Failed to attach the USB device. (No available ports on the USB controller)."));
5531 break;
5532 case VERR_VUSB_USBFS_PERMISSION:
5533 hrc = setError (E_FAIL,
5534 tr ("Not permitted to open the USB device, check usbfs options"));
5535 break;
5536 default:
5537 hrc = setError (E_FAIL,
5538 tr ("Failed to create a proxy device for the USB device. (Error: %Rrc)"), vrc);
5539 break;
5540 }
5541 }
5542
5543 return hrc;
5544}
5545
5546/**
5547 * USB device attach callback used by AttachUSBDevice().
5548 * Note that AttachUSBDevice() doesn't return until this callback is executed,
5549 * so we don't use AutoCaller and don't care about reference counters of
5550 * interface pointers passed in.
5551 *
5552 * @thread EMT
5553 * @note Locks the console object for writing.
5554 */
5555//static
5556DECLCALLBACK(int)
5557Console::usbAttachCallback (Console *that, IUSBDevice *aHostDevice, PCRTUUID aUuid, bool aRemote, const char *aAddress, ULONG aMaskedIfs)
5558{
5559 LogFlowFuncEnter();
5560 LogFlowFunc (("that={%p}\n", that));
5561
5562 AssertReturn (that && aUuid, VERR_INVALID_PARAMETER);
5563
5564 void *pvRemoteBackend = NULL;
5565 if (aRemote)
5566 {
5567 RemoteUSBDevice *pRemoteUSBDevice = static_cast <RemoteUSBDevice *> (aHostDevice);
5568 Guid guid (*aUuid);
5569
5570 pvRemoteBackend = that->consoleVRDPServer ()->USBBackendRequestPointer (pRemoteUSBDevice->clientId (), &guid);
5571 if (!pvRemoteBackend)
5572 return VERR_INVALID_PARAMETER; /* The clientId is invalid then. */
5573 }
5574
5575 USHORT portVersion = 1;
5576 HRESULT hrc = aHostDevice->COMGETTER(PortVersion)(&portVersion);
5577 AssertComRCReturn(hrc, VERR_GENERAL_FAILURE);
5578 Assert(portVersion == 1 || portVersion == 2);
5579
5580 int vrc = PDMR3USBCreateProxyDevice (that->mpVM, aUuid, aRemote, aAddress, pvRemoteBackend,
5581 portVersion == 1 ? VUSB_STDVER_11 : VUSB_STDVER_20, aMaskedIfs);
5582 if (VBOX_SUCCESS (vrc))
5583 {
5584 /* Create a OUSBDevice and add it to the device list */
5585 ComObjPtr <OUSBDevice> device;
5586 device.createObject();
5587 HRESULT hrc = device->init (aHostDevice);
5588 AssertComRC (hrc);
5589
5590 AutoWriteLock alock (that);
5591 that->mUSBDevices.push_back (device);
5592 LogFlowFunc (("Attached device {%RTuuid}\n", device->id().raw()));
5593
5594 /* notify callbacks */
5595 that->onUSBDeviceStateChange (device, true /* aAttached */, NULL);
5596 }
5597
5598 LogFlowFunc (("vrc=%Rrc\n", vrc));
5599 LogFlowFuncLeave();
5600 return vrc;
5601}
5602
5603/**
5604 * Sends a request to VMM to detach the given host device. After this method
5605 * succeeds, the detached device will disappear from the mUSBDevices
5606 * collection.
5607 *
5608 * @param aIt Iterator pointing to the device to detach.
5609 *
5610 * @note Synchronously calls EMT.
5611 * @note Must be called from under this object's lock.
5612 */
5613HRESULT Console::detachUSBDevice (USBDeviceList::iterator &aIt)
5614{
5615 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5616
5617 /* still want a lock object because we need to leave it */
5618 AutoWriteLock alock (this);
5619
5620 /* protect mpVM */
5621 AutoVMCaller autoVMCaller (this);
5622 CheckComRCReturnRC (autoVMCaller.rc());
5623
5624 /* if the device is attached, then there must at least one USB hub. */
5625 AssertReturn (PDMR3USBHasHub (mpVM), E_FAIL);
5626
5627 LogFlowThisFunc (("Detaching USB proxy device {%RTuuid}...\n",
5628 (*aIt)->id().raw()));
5629
5630 /* leave the lock before a VMR3* call (EMT will call us back)! */
5631 alock.leave();
5632
5633 PVMREQ pReq;
5634/** @todo just do everything here and only wrap the PDMR3Usb call. That'll offload some notification stuff from the EMT thread. */
5635 int vrc = VMR3ReqCall (mpVM, VMREQDEST_ANY, &pReq, RT_INDEFINITE_WAIT,
5636 (PFNRT) usbDetachCallback, 4,
5637 this, &aIt, (*aIt)->id().raw());
5638 if (VBOX_SUCCESS (vrc))
5639 vrc = pReq->iStatus;
5640 VMR3ReqFree (pReq);
5641
5642 ComAssertRCRet (vrc, E_FAIL);
5643
5644 return S_OK;
5645}
5646
5647/**
5648 * USB device detach callback used by DetachUSBDevice().
5649 * Note that DetachUSBDevice() doesn't return until this callback is executed,
5650 * so we don't use AutoCaller and don't care about reference counters of
5651 * interface pointers passed in.
5652 *
5653 * @thread EMT
5654 * @note Locks the console object for writing.
5655 */
5656//static
5657DECLCALLBACK(int)
5658Console::usbDetachCallback (Console *that, USBDeviceList::iterator *aIt, PCRTUUID aUuid)
5659{
5660 LogFlowFuncEnter();
5661 LogFlowFunc (("that={%p}\n", that));
5662
5663 AssertReturn (that && aUuid, VERR_INVALID_PARAMETER);
5664 ComObjPtr <OUSBDevice> device = **aIt;
5665
5666 /*
5667 * If that was a remote device, release the backend pointer.
5668 * The pointer was requested in usbAttachCallback.
5669 */
5670 BOOL fRemote = FALSE;
5671
5672 HRESULT hrc2 = (**aIt)->COMGETTER (Remote) (&fRemote);
5673 ComAssertComRC (hrc2);
5674
5675 if (fRemote)
5676 {
5677 Guid guid (*aUuid);
5678 that->consoleVRDPServer ()->USBBackendReleasePointer (&guid);
5679 }
5680
5681 int vrc = PDMR3USBDetachDevice (that->mpVM, aUuid);
5682
5683 if (VBOX_SUCCESS (vrc))
5684 {
5685 AutoWriteLock alock (that);
5686
5687 /* Remove the device from the collection */
5688 that->mUSBDevices.erase (*aIt);
5689 LogFlowFunc (("Detached device {%RTuuid}\n", device->id().raw()));
5690
5691 /* notify callbacks */
5692 that->onUSBDeviceStateChange (device, false /* aAttached */, NULL);
5693 }
5694
5695 LogFlowFunc (("vrc=%Rrc\n", vrc));
5696 LogFlowFuncLeave();
5697 return vrc;
5698}
5699
5700#endif /* VBOX_WITH_USB */
5701
5702/**
5703 * Call the initialisation script for a dynamic TAP interface.
5704 *
5705 * The initialisation script should create a TAP interface, set it up and write its name to
5706 * standard output followed by a carriage return. Anything further written to standard
5707 * output will be ignored. If it returns a non-zero exit code, or does not write an
5708 * intelligible interface name to standard output, it will be treated as having failed.
5709 * For now, this method only works on Linux.
5710 *
5711 * @returns COM status code
5712 * @param tapDevice string to store the name of the tap device created to
5713 * @param tapSetupApplication the name of the setup script
5714 */
5715HRESULT Console::callTapSetupApplication(bool isStatic, RTFILE tapFD, Bstr &tapDevice,
5716 Bstr &tapSetupApplication)
5717{
5718 LogFlowThisFunc(("\n"));
5719#ifdef RT_OS_LINUX
5720 /* Command line to start the script with. */
5721 char szCommand[4096];
5722 /* Result code */
5723 int rc;
5724
5725 /* Get the script name. */
5726 Utf8Str tapSetupAppUtf8(tapSetupApplication), tapDeviceUtf8(tapDevice);
5727 RTStrPrintf(szCommand, sizeof(szCommand), "%s %d %s", tapSetupAppUtf8.raw(),
5728 isStatic ? tapFD : 0, isStatic ? tapDeviceUtf8.raw() : "");
5729 /*
5730 * Create the process and read its output.
5731 */
5732 Log2(("About to start the TAP setup script with the following command line: %s\n",
5733 szCommand));
5734 FILE *pfScriptHandle = popen(szCommand, "r");
5735 if (pfScriptHandle == 0)
5736 {
5737 int iErr = errno;
5738 LogRel(("Failed to start the TAP interface setup script %s, error text: %s\n",
5739 szCommand, strerror(iErr)));
5740 LogFlowThisFunc(("rc=E_FAIL\n"));
5741 return setError(E_FAIL, tr ("Failed to run the host networking set up command %s: %s"),
5742 szCommand, strerror(iErr));
5743 }
5744 /* If we are using a dynamic TAP interface, we need to get the interface name. */
5745 if (!isStatic)
5746 {
5747 /* Buffer to read the application output to. It doesn't have to be long, as we are only
5748 interested in the first few (normally 5 or 6) bytes. */
5749 char acBuffer[64];
5750 /* The length of the string returned by the application. We only accept strings of 63
5751 characters or less. */
5752 size_t cBufSize;
5753
5754 /* Read the name of the device from the application. */
5755 fgets(acBuffer, sizeof(acBuffer), pfScriptHandle);
5756 cBufSize = strlen(acBuffer);
5757 /* The script must return the name of the interface followed by a carriage return as the
5758 first line of its output. We need a null-terminated string. */
5759 if ((cBufSize < 2) || (acBuffer[cBufSize - 1] != '\n'))
5760 {
5761 pclose(pfScriptHandle);
5762 LogRel(("The TAP interface setup script did not return the name of a TAP device.\n"));
5763 LogFlowThisFunc(("rc=E_FAIL\n"));
5764 return setError(E_FAIL, tr ("The host networking set up command did not supply an interface name"));
5765 }
5766 /* Overwrite the terminating newline character. */
5767 acBuffer[cBufSize - 1] = 0;
5768 tapDevice = acBuffer;
5769 }
5770 rc = pclose(pfScriptHandle);
5771 if (!WIFEXITED(rc))
5772 {
5773 LogRel(("The TAP interface setup script terminated abnormally.\n"));
5774 LogFlowThisFunc(("rc=E_FAIL\n"));
5775 return setError(E_FAIL, tr ("The host networking set up command did not run correctly"));
5776 }
5777 if (WEXITSTATUS(rc) != 0)
5778 {
5779 LogRel(("The TAP interface setup script returned a non-zero exit code.\n"));
5780 LogFlowThisFunc(("rc=E_FAIL\n"));
5781 return setError(E_FAIL, tr ("The host networking set up command returned a non-zero exit code"));
5782 }
5783 LogFlowThisFunc(("rc=S_OK\n"));
5784 return S_OK;
5785#else /* RT_OS_LINUX not defined */
5786 LogFlowThisFunc(("rc=E_NOTIMPL\n"));
5787 ReturnComNotImplemented(); /* not yet supported */
5788#endif
5789}
5790
5791/**
5792 * Helper function to handle host interface device creation and attachment.
5793 *
5794 * @param networkAdapter the network adapter which attachment should be reset
5795 * @return COM status code
5796 *
5797 * @note The caller must lock this object for writing.
5798 */
5799HRESULT Console::attachToHostInterface(INetworkAdapter *networkAdapter)
5800{
5801#if !defined(RT_OS_LINUX) || defined(VBOX_WITH_NETFLT)
5802 /*
5803 * Nothing to do here.
5804 *
5805 * Note, the reason for this method in the first place a memory / fork
5806 * bug on linux. All this code belongs in DrvTAP and similar places.
5807 */
5808 NOREF(networkAdapter);
5809 return S_OK;
5810
5811#else /* RT_OS_LINUX */
5812 LogFlowThisFunc(("\n"));
5813 /* sanity check */
5814 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5815
5816# ifdef VBOX_STRICT
5817 /* paranoia */
5818 NetworkAttachmentType_T attachment;
5819 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5820 Assert(attachment == NetworkAttachmentType_HostInterface);
5821# endif /* VBOX_STRICT */
5822
5823 HRESULT rc = S_OK;
5824
5825 ULONG slot = 0;
5826 rc = networkAdapter->COMGETTER(Slot)(&slot);
5827 AssertComRC(rc);
5828
5829 /*
5830 * Try get the FD.
5831 */
5832 LONG ltapFD;
5833 rc = networkAdapter->COMGETTER(TAPFileDescriptor)(&ltapFD);
5834 if (SUCCEEDED(rc))
5835 maTapFD[slot] = (RTFILE)ltapFD;
5836 else
5837 maTapFD[slot] = NIL_RTFILE;
5838
5839 /*
5840 * Are we supposed to use an existing TAP interface?
5841 */
5842 if (maTapFD[slot] != NIL_RTFILE)
5843 {
5844 /* nothing to do */
5845 Assert(ltapFD >= 0);
5846 Assert((LONG)maTapFD[slot] == ltapFD);
5847 rc = S_OK;
5848 }
5849 else
5850 {
5851 /*
5852 * Allocate a host interface device
5853 */
5854 int rcVBox = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
5855 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
5856 if (VBOX_SUCCESS(rcVBox))
5857 {
5858 /*
5859 * Set/obtain the tap interface.
5860 */
5861 bool isStatic = false;
5862 struct ifreq IfReq;
5863 memset(&IfReq, 0, sizeof(IfReq));
5864 /* The name of the TAP interface we are using and the TAP setup script resp. */
5865 Bstr tapDeviceName, tapSetupApplication;
5866 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
5867 if (FAILED(rc))
5868 {
5869 tapDeviceName.setNull(); /* Is this necessary? */
5870 }
5871 else if (!tapDeviceName.isEmpty())
5872 {
5873 isStatic = true;
5874 /* If we are using a static TAP device then try to open it. */
5875 Utf8Str str(tapDeviceName);
5876 if (str.length() <= sizeof(IfReq.ifr_name))
5877 strcpy(IfReq.ifr_name, str.raw());
5878 else
5879 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
5880 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
5881 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
5882 if (rcVBox != 0)
5883 {
5884 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
5885 rc = setError(E_FAIL, tr ("Failed to open the host network interface %ls"),
5886 tapDeviceName.raw());
5887 }
5888 }
5889 if (SUCCEEDED(rc))
5890 {
5891 networkAdapter->COMGETTER(TAPSetupApplication)(tapSetupApplication.asOutParam());
5892 if (tapSetupApplication.isEmpty())
5893 {
5894 if (tapDeviceName.isEmpty())
5895 {
5896 LogRel(("No setup application was supplied for the TAP interface.\n"));
5897 rc = setError(E_FAIL, tr ("No setup application was supplied for the host networking interface"));
5898 }
5899 }
5900 else
5901 {
5902 rc = callTapSetupApplication(isStatic, maTapFD[slot], tapDeviceName,
5903 tapSetupApplication);
5904 }
5905 }
5906 if (SUCCEEDED(rc))
5907 {
5908 if (!isStatic)
5909 {
5910 Utf8Str str(tapDeviceName);
5911 if (str.length() <= sizeof(IfReq.ifr_name))
5912 strcpy(IfReq.ifr_name, str.raw());
5913 else
5914 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
5915 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
5916 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
5917 if (rcVBox != 0)
5918 {
5919 LogRel(("Failed to open the host network interface %ls returned by the setup script", tapDeviceName.raw()));
5920 rc = setError(E_FAIL, tr ("Failed to open the host network interface %ls returned by the setup script"), tapDeviceName.raw());
5921 }
5922 }
5923 if (SUCCEEDED(rc))
5924 {
5925 /*
5926 * Make it pollable.
5927 */
5928 if (fcntl(maTapFD[slot], F_SETFL, O_NONBLOCK) != -1)
5929 {
5930 Log(("attachToHostInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
5931
5932 /*
5933 * Here is the right place to communicate the TAP file descriptor and
5934 * the host interface name to the server if/when it becomes really
5935 * necessary.
5936 */
5937 maTAPDeviceName[slot] = tapDeviceName;
5938 rcVBox = VINF_SUCCESS;
5939 }
5940 else
5941 {
5942 int iErr = errno;
5943
5944 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
5945 rcVBox = VERR_HOSTIF_BLOCKING;
5946 rc = setError(E_FAIL, tr ("could not set up the host networking device for non blocking access: %s"),
5947 strerror(errno));
5948 }
5949 }
5950 }
5951 }
5952 else
5953 {
5954 LogRel(("Configuration error: Failed to open /dev/net/tun rc=%Rrc\n", rcVBox));
5955 switch (rcVBox)
5956 {
5957 case VERR_ACCESS_DENIED:
5958 /* will be handled by our caller */
5959 rc = rcVBox;
5960 break;
5961 default:
5962 rc = setError(E_FAIL, tr ("Could not set up the host networking device: %Rrc"), rcVBox);
5963 break;
5964 }
5965 }
5966 /* in case of failure, cleanup. */
5967 if (VBOX_FAILURE(rcVBox) && SUCCEEDED(rc))
5968 {
5969 LogRel(("General failure attaching to host interface\n"));
5970 rc = setError(E_FAIL, tr ("General failure attaching to host interface"));
5971 }
5972 }
5973 LogFlowThisFunc(("rc=%d\n", rc));
5974 return rc;
5975#endif /* RT_OS_LINUX */
5976}
5977
5978/**
5979 * Helper function to handle detachment from a host interface
5980 *
5981 * @param networkAdapter the network adapter which attachment should be reset
5982 * @return COM status code
5983 *
5984 * @note The caller must lock this object for writing.
5985 */
5986HRESULT Console::detachFromHostInterface(INetworkAdapter *networkAdapter)
5987{
5988#if !defined(RT_OS_LINUX) || defined(VBOX_WITH_NETFLT)
5989 /*
5990 * Nothing to do here.
5991 */
5992 NOREF(networkAdapter);
5993 return S_OK;
5994
5995#else /* RT_OS_LINUX */
5996
5997 /* sanity check */
5998 LogFlowThisFunc(("\n"));
5999 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
6000
6001 HRESULT rc = S_OK;
6002# ifdef VBOX_STRICT
6003 /* paranoia */
6004 NetworkAttachmentType_T attachment;
6005 networkAdapter->COMGETTER(AttachmentType)(&attachment);
6006 Assert(attachment == NetworkAttachmentType_HostInterface);
6007# endif /* VBOX_STRICT */
6008
6009 ULONG slot = 0;
6010 rc = networkAdapter->COMGETTER(Slot)(&slot);
6011 AssertComRC(rc);
6012
6013 /* is there an open TAP device? */
6014 if (maTapFD[slot] != NIL_RTFILE)
6015 {
6016 /*
6017 * Close the file handle.
6018 */
6019 Bstr tapDeviceName, tapTerminateApplication;
6020 bool isStatic = true;
6021 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
6022 if (FAILED(rc) || tapDeviceName.isEmpty())
6023 {
6024 /* If the name is empty, this is a dynamic TAP device, so close it now,
6025 so that the termination script can remove the interface. Otherwise we still
6026 need the FD to pass to the termination script. */
6027 isStatic = false;
6028 int rcVBox = RTFileClose(maTapFD[slot]);
6029 AssertRC(rcVBox);
6030 maTapFD[slot] = NIL_RTFILE;
6031 }
6032 /*
6033 * Execute the termination command.
6034 */
6035 networkAdapter->COMGETTER(TAPTerminateApplication)(tapTerminateApplication.asOutParam());
6036 if (tapTerminateApplication)
6037 {
6038 /* Get the program name. */
6039 Utf8Str tapTermAppUtf8(tapTerminateApplication);
6040
6041 /* Build the command line. */
6042 char szCommand[4096];
6043 RTStrPrintf(szCommand, sizeof(szCommand), "%s %d %s", tapTermAppUtf8.raw(),
6044 isStatic ? maTapFD[slot] : 0, maTAPDeviceName[slot].raw());
6045 /** @todo check for overflow or use RTStrAPrintf! */
6046
6047 /*
6048 * Create the process and wait for it to complete.
6049 */
6050 Log(("Calling the termination command: %s\n", szCommand));
6051 int rcCommand = system(szCommand);
6052 if (rcCommand == -1)
6053 {
6054 LogRel(("Failed to execute the clean up script for the TAP interface"));
6055 rc = setError(E_FAIL, tr ("Failed to execute the clean up script for the TAP interface"));
6056 }
6057 if (!WIFEXITED(rc))
6058 {
6059 LogRel(("The TAP interface clean up script terminated abnormally.\n"));
6060 rc = setError(E_FAIL, tr ("The TAP interface clean up script terminated abnormally"));
6061 }
6062 if (WEXITSTATUS(rc) != 0)
6063 {
6064 LogRel(("The TAP interface clean up script returned a non-zero exit code.\n"));
6065 rc = setError(E_FAIL, tr ("The TAP interface clean up script returned a non-zero exit code"));
6066 }
6067 }
6068
6069 if (isStatic)
6070 {
6071 /* If we are using a static TAP device, we close it now, after having called the
6072 termination script. */
6073 int rcVBox = RTFileClose(maTapFD[slot]);
6074 AssertRC(rcVBox);
6075 }
6076 /* the TAP device name and handle are no longer valid */
6077 maTapFD[slot] = NIL_RTFILE;
6078 maTAPDeviceName[slot] = "";
6079 }
6080 LogFlowThisFunc(("returning %d\n", rc));
6081 return rc;
6082#endif /* RT_OS_LINUX */
6083}
6084
6085
6086/**
6087 * Called at power down to terminate host interface networking.
6088 *
6089 * @note The caller must lock this object for writing.
6090 */
6091HRESULT Console::powerDownHostInterfaces()
6092{
6093 LogFlowThisFunc (("\n"));
6094
6095 /* sanity check */
6096 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
6097
6098 /*
6099 * host interface termination handling
6100 */
6101 HRESULT rc;
6102 for (ULONG slot = 0; slot < SchemaDefs::NetworkAdapterCount; slot ++)
6103 {
6104 ComPtr<INetworkAdapter> networkAdapter;
6105 rc = mMachine->GetNetworkAdapter(slot, networkAdapter.asOutParam());
6106 CheckComRCBreakRC (rc);
6107
6108 BOOL enabled = FALSE;
6109 networkAdapter->COMGETTER(Enabled) (&enabled);
6110 if (!enabled)
6111 continue;
6112
6113 NetworkAttachmentType_T attachment;
6114 networkAdapter->COMGETTER(AttachmentType)(&attachment);
6115 if (attachment == NetworkAttachmentType_HostInterface)
6116 {
6117 HRESULT rc2 = detachFromHostInterface(networkAdapter);
6118 if (FAILED(rc2) && SUCCEEDED(rc))
6119 rc = rc2;
6120 }
6121 }
6122
6123 return rc;
6124}
6125
6126
6127/**
6128 * Process callback handler for VMR3Load and VMR3Save.
6129 *
6130 * @param pVM The VM handle.
6131 * @param uPercent Completetion precentage (0-100).
6132 * @param pvUser Pointer to the VMProgressTask structure.
6133 * @return VINF_SUCCESS.
6134 */
6135/*static*/ DECLCALLBACK (int)
6136Console::stateProgressCallback (PVM pVM, unsigned uPercent, void *pvUser)
6137{
6138 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
6139 AssertReturn (task, VERR_INVALID_PARAMETER);
6140
6141 /* update the progress object */
6142 if (task->mProgress)
6143 task->mProgress->notifyProgress (uPercent);
6144
6145 return VINF_SUCCESS;
6146}
6147
6148/**
6149 * VM error callback function. Called by the various VM components.
6150 *
6151 * @param pVM VM handle. Can be NULL if an error occurred before
6152 * successfully creating a VM.
6153 * @param pvUser Pointer to the VMProgressTask structure.
6154 * @param rc VBox status code.
6155 * @param pszFormat Printf-like error message.
6156 * @param args Various number of arguments for the error message.
6157 *
6158 * @thread EMT, VMPowerUp...
6159 *
6160 * @note The VMProgressTask structure modified by this callback is not thread
6161 * safe.
6162 */
6163/* static */ DECLCALLBACK (void)
6164Console::setVMErrorCallback (PVM pVM, void *pvUser, int rc, RT_SRC_POS_DECL,
6165 const char *pszFormat, va_list args)
6166{
6167 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
6168 AssertReturnVoid (task);
6169
6170 /* we ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users */
6171 va_list va2;
6172 va_copy (va2, args); /* Have to make a copy here or GCC will break. */
6173
6174 /* append to the existing error message if any */
6175 if (!task->mErrorMsg.isEmpty())
6176 task->mErrorMsg = Utf8StrFmt ("%s.\n%N (%Rrc)", task->mErrorMsg.raw(),
6177 pszFormat, &va2, rc, rc);
6178 else
6179 task->mErrorMsg = Utf8StrFmt ("%N (%Rrc)",
6180 pszFormat, &va2, rc, rc);
6181
6182 va_end (va2);
6183}
6184
6185/**
6186 * VM runtime error callback function.
6187 * See VMSetRuntimeError for the detailed description of parameters.
6188 *
6189 * @param pVM The VM handle.
6190 * @param pvUser The user argument.
6191 * @param fFatal Whether it is a fatal error or not.
6192 * @param pszErrorID Error ID string.
6193 * @param pszFormat Error message format string.
6194 * @param args Error message arguments.
6195 * @thread EMT.
6196 */
6197/* static */ DECLCALLBACK(void)
6198Console::setVMRuntimeErrorCallback (PVM pVM, void *pvUser, bool fFatal,
6199 const char *pszErrorID,
6200 const char *pszFormat, va_list args)
6201{
6202 LogFlowFuncEnter();
6203
6204 Console *that = static_cast <Console *> (pvUser);
6205 AssertReturnVoid (that);
6206
6207 Utf8Str message = Utf8StrFmtVA (pszFormat, args);
6208
6209 LogRel (("Console: VM runtime error: fatal=%RTbool, "
6210 "errorID=%s message=\"%s\"\n",
6211 fFatal, pszErrorID, message.raw()));
6212
6213 that->onRuntimeError (BOOL (fFatal), Bstr (pszErrorID), Bstr (message));
6214
6215 LogFlowFuncLeave();
6216}
6217
6218/**
6219 * Captures USB devices that match filters of the VM.
6220 * Called at VM startup.
6221 *
6222 * @param pVM The VM handle.
6223 *
6224 * @note The caller must lock this object for writing.
6225 */
6226HRESULT Console::captureUSBDevices (PVM pVM)
6227{
6228 LogFlowThisFunc (("\n"));
6229
6230 /* sanity check */
6231 ComAssertRet (isWriteLockOnCurrentThread(), E_FAIL);
6232
6233 /* If the machine has an USB controller, ask the USB proxy service to
6234 * capture devices */
6235 PPDMIBASE pBase;
6236 int vrc = PDMR3QueryLun (pVM, "usb-ohci", 0, 0, &pBase);
6237 if (VBOX_SUCCESS (vrc))
6238 {
6239 /* leave the lock before calling Host in VBoxSVC since Host may call
6240 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
6241 * produce an inter-process dead-lock otherwise. */
6242 AutoWriteLock alock (this);
6243 alock.leave();
6244
6245 HRESULT hrc = mControl->AutoCaptureUSBDevices();
6246 ComAssertComRCRetRC (hrc);
6247 }
6248 else if ( vrc == VERR_PDM_DEVICE_NOT_FOUND
6249 || vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND)
6250 vrc = VINF_SUCCESS;
6251 else
6252 AssertRC (vrc);
6253
6254 return VBOX_SUCCESS (vrc) ? S_OK : E_FAIL;
6255}
6256
6257
6258/**
6259 * Detach all USB device which are attached to the VM for the
6260 * purpose of clean up and such like.
6261 *
6262 * @note The caller must lock this object for writing.
6263 */
6264void Console::detachAllUSBDevices (bool aDone)
6265{
6266 LogFlowThisFunc (("aDone=%RTbool\n", aDone));
6267
6268 /* sanity check */
6269 AssertReturnVoid (isWriteLockOnCurrentThread());
6270
6271 mUSBDevices.clear();
6272
6273 /* leave the lock before calling Host in VBoxSVC since Host may call
6274 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
6275 * produce an inter-process dead-lock otherwise. */
6276 AutoWriteLock alock (this);
6277 alock.leave();
6278
6279 mControl->DetachAllUSBDevices (aDone);
6280}
6281
6282/**
6283 * @note Locks this object for writing.
6284 */
6285void Console::processRemoteUSBDevices (uint32_t u32ClientId, VRDPUSBDEVICEDESC *pDevList, uint32_t cbDevList)
6286{
6287 LogFlowThisFuncEnter();
6288 LogFlowThisFunc (("u32ClientId = %d, pDevList=%p, cbDevList = %d\n", u32ClientId, pDevList, cbDevList));
6289
6290 AutoCaller autoCaller (this);
6291 if (!autoCaller.isOk())
6292 {
6293 /* Console has been already uninitialized, deny request */
6294 AssertMsgFailed (("Temporary assertion to prove that it happens, "
6295 "please report to dmik\n"));
6296 LogFlowThisFunc (("Console is already uninitialized\n"));
6297 LogFlowThisFuncLeave();
6298 return;
6299 }
6300
6301 AutoWriteLock alock (this);
6302
6303 /*
6304 * Mark all existing remote USB devices as dirty.
6305 */
6306 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
6307 while (it != mRemoteUSBDevices.end())
6308 {
6309 (*it)->dirty (true);
6310 ++ it;
6311 }
6312
6313 /*
6314 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
6315 */
6316 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
6317 VRDPUSBDEVICEDESC *e = pDevList;
6318
6319 /* The cbDevList condition must be checked first, because the function can
6320 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
6321 */
6322 while (cbDevList >= 2 && e->oNext)
6323 {
6324 LogFlowThisFunc (("vendor %04X, product %04X, name = %s\n",
6325 e->idVendor, e->idProduct,
6326 e->oProduct? (char *)e + e->oProduct: ""));
6327
6328 bool fNewDevice = true;
6329
6330 it = mRemoteUSBDevices.begin();
6331 while (it != mRemoteUSBDevices.end())
6332 {
6333 if ((*it)->devId () == e->id
6334 && (*it)->clientId () == u32ClientId)
6335 {
6336 /* The device is already in the list. */
6337 (*it)->dirty (false);
6338 fNewDevice = false;
6339 break;
6340 }
6341
6342 ++ it;
6343 }
6344
6345 if (fNewDevice)
6346 {
6347 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
6348 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""
6349 ));
6350
6351 /* Create the device object and add the new device to list. */
6352 ComObjPtr <RemoteUSBDevice> device;
6353 device.createObject();
6354 device->init (u32ClientId, e);
6355
6356 mRemoteUSBDevices.push_back (device);
6357
6358 /* Check if the device is ok for current USB filters. */
6359 BOOL fMatched = FALSE;
6360 ULONG fMaskedIfs = 0;
6361
6362 HRESULT hrc = mControl->RunUSBDeviceFilters(device, &fMatched, &fMaskedIfs);
6363
6364 AssertComRC (hrc);
6365
6366 LogFlowThisFunc (("USB filters return %d %#x\n", fMatched, fMaskedIfs));
6367
6368 if (fMatched)
6369 {
6370 hrc = onUSBDeviceAttach (device, NULL, fMaskedIfs);
6371
6372 /// @todo (r=dmik) warning reporting subsystem
6373
6374 if (hrc == S_OK)
6375 {
6376 LogFlowThisFunc (("Device attached\n"));
6377 device->captured (true);
6378 }
6379 }
6380 }
6381
6382 if (cbDevList < e->oNext)
6383 {
6384 LogWarningThisFunc (("cbDevList %d > oNext %d\n",
6385 cbDevList, e->oNext));
6386 break;
6387 }
6388
6389 cbDevList -= e->oNext;
6390
6391 e = (VRDPUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
6392 }
6393
6394 /*
6395 * Remove dirty devices, that is those which are not reported by the server anymore.
6396 */
6397 for (;;)
6398 {
6399 ComObjPtr <RemoteUSBDevice> device;
6400
6401 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
6402 while (it != mRemoteUSBDevices.end())
6403 {
6404 if ((*it)->dirty ())
6405 {
6406 device = *it;
6407 break;
6408 }
6409
6410 ++ it;
6411 }
6412
6413 if (!device)
6414 {
6415 break;
6416 }
6417
6418 USHORT vendorId = 0;
6419 device->COMGETTER(VendorId) (&vendorId);
6420
6421 USHORT productId = 0;
6422 device->COMGETTER(ProductId) (&productId);
6423
6424 Bstr product;
6425 device->COMGETTER(Product) (product.asOutParam());
6426
6427 LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
6428 vendorId, productId, product.raw ()
6429 ));
6430
6431 /* Detach the device from VM. */
6432 if (device->captured ())
6433 {
6434 Guid uuid;
6435 device->COMGETTER (Id) (uuid.asOutParam());
6436 onUSBDeviceDetach (uuid, NULL);
6437 }
6438
6439 /* And remove it from the list. */
6440 mRemoteUSBDevices.erase (it);
6441 }
6442
6443 LogFlowThisFuncLeave();
6444}
6445
6446/**
6447 * Thread function which starts the VM (also from saved state) and
6448 * track progress.
6449 *
6450 * @param Thread The thread id.
6451 * @param pvUser Pointer to a VMPowerUpTask structure.
6452 * @return VINF_SUCCESS (ignored).
6453 *
6454 * @note Locks the Console object for writing.
6455 */
6456/*static*/
6457DECLCALLBACK (int) Console::powerUpThread (RTTHREAD Thread, void *pvUser)
6458{
6459 LogFlowFuncEnter();
6460
6461 std::auto_ptr <VMPowerUpTask> task (static_cast <VMPowerUpTask *> (pvUser));
6462 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
6463
6464 AssertReturn (!task->mConsole.isNull(), VERR_INVALID_PARAMETER);
6465 AssertReturn (!task->mProgress.isNull(), VERR_INVALID_PARAMETER);
6466
6467#if defined(RT_OS_WINDOWS)
6468 {
6469 /* initialize COM */
6470 HRESULT hrc = CoInitializeEx (NULL,
6471 COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE |
6472 COINIT_SPEED_OVER_MEMORY);
6473 LogFlowFunc (("CoInitializeEx()=%08X\n", hrc));
6474 }
6475#endif
6476
6477 HRESULT rc = S_OK;
6478 int vrc = VINF_SUCCESS;
6479
6480 /* Set up a build identifier so that it can be seen from core dumps what
6481 * exact build was used to produce the core. */
6482 static char saBuildID[40];
6483 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%d %s%s%s%s",
6484 "BU", "IL", "DI", "D", VBOX_VERSION_STRING, VBoxSVNRev (), "BU", "IL", "DI", "D");
6485
6486 ComObjPtr <Console> console = task->mConsole;
6487
6488 /* Note: no need to use addCaller() because VMPowerUpTask does that */
6489
6490 /* The lock is also used as a signal from the task initiator (which
6491 * releases it only after RTThreadCreate()) that we can start the job */
6492 AutoWriteLock alock (console);
6493
6494 /* sanity */
6495 Assert (console->mpVM == NULL);
6496
6497 try
6498 {
6499 {
6500 ErrorInfoKeeper eik (true /* aIsNull */);
6501 MultiResult mrc (S_OK);
6502
6503 /* perform a check of inaccessible media deferred in PowerUp() */
6504 for (VMPowerUpTask::Media::const_iterator
6505 it = task->mediaToCheck.begin();
6506 it != task->mediaToCheck.end(); ++ it)
6507 {
6508 MediaState_T mediaState;
6509 rc = (*it)->COMGETTER(State) (&mediaState);
6510 CheckComRCThrowRC (rc);
6511
6512 Assert (mediaState == MediaState_LockedRead ||
6513 mediaState == MediaState_LockedWrite);
6514
6515 /* Note that we locked the medium already, so use the error
6516 * value to see if there was an accessibility failure */
6517
6518 Bstr error;
6519 rc = (*it)->COMGETTER(LastAccessError) (error.asOutParam());
6520 CheckComRCThrowRC (rc);
6521
6522 if (!error.isNull())
6523 {
6524 Bstr loc;
6525 rc = (*it)->COMGETTER(Location) (loc.asOutParam());
6526 CheckComRCThrowRC (rc);
6527
6528 /* collect multiple errors */
6529 eik.restore();
6530
6531 /* be in sync with MediumBase::setStateError() */
6532 Assert (!error.isEmpty());
6533 mrc = setError (E_FAIL,
6534 tr ("Medium '%ls' is not accessible. %ls"),
6535 loc.raw(), error.raw());
6536
6537 eik.fetch();
6538 }
6539 }
6540
6541 eik.restore();
6542 CheckComRCThrowRC ((HRESULT) mrc);
6543 }
6544
6545#ifdef VBOX_WITH_VRDP
6546
6547 /* Create the VRDP server. In case of headless operation, this will
6548 * also create the framebuffer, required at VM creation.
6549 */
6550 ConsoleVRDPServer *server = console->consoleVRDPServer();
6551 Assert (server);
6552
6553 /// @todo (dmik)
6554 // does VRDP server call Console from the other thread?
6555 // Not sure, so leave the lock just in case
6556 alock.leave();
6557 vrc = server->Launch();
6558 alock.enter();
6559
6560 if (VBOX_FAILURE (vrc))
6561 {
6562 Utf8Str errMsg;
6563 switch (vrc)
6564 {
6565 case VERR_NET_ADDRESS_IN_USE:
6566 {
6567 ULONG port = 0;
6568 console->mVRDPServer->COMGETTER(Port) (&port);
6569 errMsg = Utf8StrFmt (tr ("VRDP server port %d is already in use"),
6570 port);
6571 break;
6572 }
6573 case VERR_FILE_NOT_FOUND:
6574 {
6575 errMsg = Utf8StrFmt (tr ("Could not load the VRDP library"));
6576 break;
6577 }
6578 default:
6579 errMsg = Utf8StrFmt (tr ("Failed to launch VRDP server (%Rrc)"),
6580 vrc);
6581 }
6582 LogRel (("Failed to launch VRDP server (%Rrc), error message: '%s'\n",
6583 vrc, errMsg.raw()));
6584 throw setError (E_FAIL, errMsg);
6585 }
6586
6587#endif /* VBOX_WITH_VRDP */
6588
6589 ULONG cCpus = 1;
6590#ifdef VBOX_WITH_SMP_GUESTS
6591 pMachine->COMGETTER(CPUCount)(&cCpus);
6592#endif
6593
6594 /*
6595 * Create the VM
6596 */
6597 PVM pVM;
6598 /*
6599 * leave the lock since EMT will call Console. It's safe because
6600 * mMachineState is either Starting or Restoring state here.
6601 */
6602 alock.leave();
6603
6604 vrc = VMR3Create (cCpus, task->mSetVMErrorCallback, task.get(),
6605 task->mConfigConstructor, static_cast <Console *> (console),
6606 &pVM);
6607
6608 alock.enter();
6609
6610#ifdef VBOX_WITH_VRDP
6611 /* Enable client connections to the server. */
6612 console->consoleVRDPServer()->EnableConnections ();
6613#endif /* VBOX_WITH_VRDP */
6614
6615 if (VBOX_SUCCESS (vrc))
6616 {
6617 do
6618 {
6619 /*
6620 * Register our load/save state file handlers
6621 */
6622 vrc = SSMR3RegisterExternal (pVM,
6623 sSSMConsoleUnit, 0 /* iInstance */, sSSMConsoleVer,
6624 0 /* cbGuess */,
6625 NULL, saveStateFileExec, NULL, NULL, loadStateFileExec, NULL,
6626 static_cast <Console *> (console));
6627 AssertRC (vrc);
6628 if (VBOX_FAILURE (vrc))
6629 break;
6630
6631 /*
6632 * Synchronize debugger settings
6633 */
6634 MachineDebugger *machineDebugger = console->getMachineDebugger();
6635 if (machineDebugger)
6636 {
6637 machineDebugger->flushQueuedSettings();
6638 }
6639
6640 /*
6641 * Shared Folders
6642 */
6643 if (console->getVMMDev()->isShFlActive())
6644 {
6645 /// @todo (dmik)
6646 // does the code below call Console from the other thread?
6647 // Not sure, so leave the lock just in case
6648 alock.leave();
6649
6650 for (SharedFolderDataMap::const_iterator
6651 it = task->mSharedFolders.begin();
6652 it != task->mSharedFolders.end();
6653 ++ it)
6654 {
6655 rc = console->createSharedFolder ((*it).first, (*it).second);
6656 CheckComRCBreakRC (rc);
6657 }
6658
6659 /* enter the lock again */
6660 alock.enter();
6661
6662 CheckComRCBreakRC (rc);
6663 }
6664
6665 /*
6666 * Capture USB devices.
6667 */
6668 rc = console->captureUSBDevices (pVM);
6669 CheckComRCBreakRC (rc);
6670
6671 /* leave the lock before a lengthy operation */
6672 alock.leave();
6673
6674 /* Load saved state? */
6675 if (!!task->mSavedStateFile)
6676 {
6677 LogFlowFunc (("Restoring saved state from '%s'...\n",
6678 task->mSavedStateFile.raw()));
6679
6680 vrc = VMR3Load (pVM, task->mSavedStateFile,
6681 Console::stateProgressCallback,
6682 static_cast <VMProgressTask *> (task.get()));
6683
6684 if (VBOX_SUCCESS (vrc))
6685 {
6686 if (task->mStartPaused)
6687 /* done */
6688 console->setMachineState (MachineState_Paused);
6689 else
6690 {
6691 /* Start/Resume the VM execution */
6692 vrc = VMR3Resume (pVM);
6693 AssertRC (vrc);
6694 }
6695 }
6696
6697 /* Power off in case we failed loading or resuming the VM */
6698 if (VBOX_FAILURE (vrc))
6699 {
6700 int vrc2 = VMR3PowerOff (pVM);
6701 AssertRC (vrc2);
6702 }
6703 }
6704 else if (task->mStartPaused)
6705 /* done */
6706 console->setMachineState (MachineState_Paused);
6707 else
6708 {
6709 /* Power on the VM (i.e. start executing) */
6710 vrc = VMR3PowerOn(pVM);
6711 AssertRC (vrc);
6712 }
6713
6714 /* enter the lock again */
6715 alock.enter();
6716 }
6717 while (0);
6718
6719 /* On failure, destroy the VM */
6720 if (FAILED (rc) || VBOX_FAILURE (vrc))
6721 {
6722 /* preserve existing error info */
6723 ErrorInfoKeeper eik;
6724
6725 /* powerDown() will call VMR3Destroy() and do all necessary
6726 * cleanup (VRDP, USB devices) */
6727 HRESULT rc2 = console->powerDown();
6728 AssertComRC (rc2);
6729 }
6730 }
6731 else
6732 {
6733 /*
6734 * If VMR3Create() failed it has released the VM memory.
6735 */
6736 console->mpVM = NULL;
6737 }
6738
6739 if (SUCCEEDED (rc) && VBOX_FAILURE (vrc))
6740 {
6741 /* If VMR3Create() or one of the other calls in this function fail,
6742 * an appropriate error message has been set in task->mErrorMsg.
6743 * However since that happens via a callback, the rc status code in
6744 * this function is not updated.
6745 */
6746 if (task->mErrorMsg.isNull())
6747 {
6748 /* If the error message is not set but we've got a failure,
6749 * convert the VBox status code into a meaningfulerror message.
6750 * This becomes unused once all the sources of errors set the
6751 * appropriate error message themselves.
6752 */
6753 AssertMsgFailed (("Missing error message during powerup for "
6754 "status code %Rrc\n", vrc));
6755 task->mErrorMsg = Utf8StrFmt (
6756 tr ("Failed to start VM execution (%Rrc)"), vrc);
6757 }
6758
6759 /* Set the error message as the COM error.
6760 * Progress::notifyComplete() will pick it up later. */
6761 throw setError (E_FAIL, task->mErrorMsg);
6762 }
6763 }
6764 catch (HRESULT aRC) { rc = aRC; }
6765
6766 if (console->mMachineState == MachineState_Starting ||
6767 console->mMachineState == MachineState_Restoring)
6768 {
6769 /* We are still in the Starting/Restoring state. This means one of:
6770 *
6771 * 1) we failed before VMR3Create() was called;
6772 * 2) VMR3Create() failed.
6773 *
6774 * In both cases, there is no need to call powerDown(), but we still
6775 * need to go back to the PoweredOff/Saved state. Reuse
6776 * vmstateChangeCallback() for that purpose.
6777 */
6778
6779 /* preserve existing error info */
6780 ErrorInfoKeeper eik;
6781
6782 Assert (console->mpVM == NULL);
6783 vmstateChangeCallback (NULL, VMSTATE_TERMINATED, VMSTATE_CREATING,
6784 console);
6785 }
6786
6787 /*
6788 * Evaluate the final result. Note that the appropriate mMachineState value
6789 * is already set by vmstateChangeCallback() in all cases.
6790 */
6791
6792 /* leave the lock, don't need it any more */
6793 alock.leave();
6794
6795 if (SUCCEEDED (rc))
6796 {
6797 /* Notify the progress object of the success */
6798 task->mProgress->notifyComplete (S_OK);
6799 }
6800 else
6801 {
6802 /* The progress object will fetch the current error info */
6803 task->mProgress->notifyComplete (rc);
6804
6805 LogRel (("Power up failed (vrc=%Rrc, rc=%Rhrc (%#08X))\n", vrc, rc, rc));
6806 }
6807
6808#if defined(RT_OS_WINDOWS)
6809 /* uninitialize COM */
6810 CoUninitialize();
6811#endif
6812
6813 LogFlowFuncLeave();
6814
6815 return VINF_SUCCESS;
6816}
6817
6818
6819/**
6820 * Reconfigures a VDI.
6821 *
6822 * @param pVM The VM handle.
6823 * @param hda The harddisk attachment.
6824 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
6825 * @return VBox status code.
6826 */
6827static DECLCALLBACK(int) reconfigureHardDisks(PVM pVM, IHardDisk2Attachment *hda,
6828 HRESULT *phrc)
6829{
6830 LogFlowFunc (("pVM=%p hda=%p phrc=%p\n", pVM, hda, phrc));
6831
6832 int rc;
6833 HRESULT hrc;
6834 Bstr bstr;
6835 *phrc = S_OK;
6836#define RC_CHECK() do { if (VBOX_FAILURE(rc)) { AssertMsgFailed(("rc=%Rrc\n", rc)); return rc; } } while (0)
6837#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%Rhrc (%#x)\n", hrc, hrc)); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
6838
6839 /*
6840 * Figure out which IDE device this is.
6841 */
6842 ComPtr<IHardDisk2> hardDisk;
6843 hrc = hda->COMGETTER(HardDisk)(hardDisk.asOutParam()); H();
6844 StorageBus_T enmBus;
6845 hrc = hda->COMGETTER(Bus)(&enmBus); H();
6846 LONG lDev;
6847 hrc = hda->COMGETTER(Device)(&lDev); H();
6848 LONG lChannel;
6849 hrc = hda->COMGETTER(Channel)(&lChannel); H();
6850
6851 int iLUN;
6852 const char *pcszDevice = NULL;
6853
6854 switch (enmBus)
6855 {
6856 case StorageBus_IDE:
6857 {
6858 if (lChannel >= 2 || lChannel < 0)
6859 {
6860 AssertMsgFailed(("invalid controller channel number: %d\n", lChannel));
6861 return VERR_GENERAL_FAILURE;
6862 }
6863
6864 if (lDev >= 2 || lDev < 0)
6865 {
6866 AssertMsgFailed(("invalid controller device number: %d\n", lDev));
6867 return VERR_GENERAL_FAILURE;
6868 }
6869
6870 iLUN = 2*lChannel + lDev;
6871 pcszDevice = "piix3ide";
6872 break;
6873 }
6874 case StorageBus_SATA:
6875 {
6876 iLUN = lChannel;
6877 pcszDevice = "ahci";
6878 break;
6879 }
6880 default:
6881 {
6882 AssertMsgFailed(("invalid disk controller type: %d\n", enmBus));
6883 return VERR_GENERAL_FAILURE;
6884 }
6885 }
6886
6887 /*
6888 * Is there an existing LUN? If not create it.
6889 * We ASSUME that this will NEVER collide with the DVD.
6890 */
6891 PCFGMNODE pCfg;
6892 PCFGMNODE pLunL1;
6893
6894 pLunL1 = CFGMR3GetChildF(CFGMR3GetRoot(pVM), "Devices/%s/0/LUN#%d/AttachedDriver/", pcszDevice, iLUN);
6895
6896 if (!pLunL1)
6897 {
6898 PCFGMNODE pInst = CFGMR3GetChildF(CFGMR3GetRoot(pVM), "Devices/%s/0/", pcszDevice);
6899 AssertReturn(pInst, VERR_INTERNAL_ERROR);
6900
6901 PCFGMNODE pLunL0;
6902 rc = CFGMR3InsertNodeF(pInst, &pLunL0, "LUN#%d", iLUN); RC_CHECK();
6903 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
6904 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
6905 rc = CFGMR3InsertString(pCfg, "Type", "HardDisk"); RC_CHECK();
6906 rc = CFGMR3InsertInteger(pCfg, "Mountable", 0); RC_CHECK();
6907
6908 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
6909 rc = CFGMR3InsertString(pLunL1, "Driver", "VD"); RC_CHECK();
6910 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
6911 }
6912 else
6913 {
6914#ifdef VBOX_STRICT
6915 char *pszDriver;
6916 rc = CFGMR3QueryStringAlloc(pLunL1, "Driver", &pszDriver); RC_CHECK();
6917 Assert(!strcmp(pszDriver, "VD"));
6918 MMR3HeapFree(pszDriver);
6919#endif
6920
6921 /*
6922 * Check if things has changed.
6923 */
6924 pCfg = CFGMR3GetChild(pLunL1, "Config");
6925 AssertReturn(pCfg, VERR_INTERNAL_ERROR);
6926
6927 /* the format */
6928 hrc = hardDisk->COMGETTER(Format)(bstr.asOutParam()); H();
6929 char *pszFormat;
6930 rc = CFGMR3QueryStringAlloc(pCfg, "Format", &pszFormat); RC_CHECK();
6931 if (bstr == pszFormat)
6932 {
6933 /* the image */
6934 hrc = hardDisk->COMGETTER(Location)(bstr.asOutParam()); H();
6935 char *pszPath;
6936 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
6937 if (bstr == pszPath)
6938 {
6939 /* parent images. */
6940 ComPtr<IHardDisk2> parentHardDisk = hardDisk;
6941 for (PCFGMNODE pParent = pCfg;;)
6942 {
6943 MMR3HeapFree(pszPath);
6944 pszPath = NULL;
6945
6946 MMR3HeapFree(pszFormat);
6947 pszFormat = NULL;
6948
6949 /* get parent */
6950 ComPtr<IHardDisk2> curHardDisk;
6951 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
6952 PCFGMNODE pCur;
6953 pCur = CFGMR3GetChild(pParent, "Parent");
6954 if (!pCur && !curHardDisk)
6955 {
6956 /* no change */
6957 LogFlowFunc (("No change!\n"));
6958 return VINF_SUCCESS;
6959 }
6960 if (!pCur || !curHardDisk)
6961 break;
6962
6963 /* compare formats. */
6964 hrc = curHardDisk->COMGETTER(Format)(bstr.asOutParam()); H();
6965 rc = CFGMR3QueryStringAlloc(pCfg, "Format", &pszPath); RC_CHECK();
6966 if (bstr != pszFormat)
6967 break;
6968
6969 /* compare paths. */
6970 hrc = curHardDisk->COMGETTER(Location)(bstr.asOutParam()); H();
6971 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
6972 if (bstr != pszPath)
6973 break;
6974
6975 /* next */
6976 pParent = pCur;
6977 parentHardDisk = curHardDisk;
6978 }
6979
6980 }
6981 else
6982 LogFlowFunc (("LUN#%d: old leaf location '%s'\n", iLUN, pszPath));
6983
6984 MMR3HeapFree(pszPath);
6985 }
6986 else
6987 LogFlowFunc (("LUN#%d: old leaf format '%s'\n", iLUN, pszFormat));
6988
6989 MMR3HeapFree(pszFormat);
6990
6991 /*
6992 * Detach the driver and replace the config node.
6993 */
6994 rc = PDMR3DeviceDetach(pVM, pcszDevice, 0, iLUN); RC_CHECK();
6995 CFGMR3RemoveNode(pCfg);
6996 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
6997 }
6998
6999 /*
7000 * Create the driver configuration.
7001 */
7002 hrc = hardDisk->COMGETTER(Format)(bstr.asOutParam()); H();
7003 LogFlowFunc (("LUN#%d: leaf format '%ls'\n", iLUN, bstr.raw()));
7004 rc = CFGMR3InsertString(pCfg, "Format", Utf8Str(bstr)); RC_CHECK();
7005 hrc = hardDisk->COMGETTER(Location)(bstr.asOutParam()); H();
7006 LogFlowFunc (("LUN#%d: leaf location '%ls'\n", iLUN, bstr.raw()));
7007 rc = CFGMR3InsertString(pCfg, "Path", Utf8Str(bstr)); RC_CHECK();
7008 /* Create an inversed tree of parents. */
7009 ComPtr<IHardDisk2> parentHardDisk = hardDisk;
7010 for (PCFGMNODE pParent = pCfg;;)
7011 {
7012 ComPtr<IHardDisk2> curHardDisk;
7013 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
7014 if (!curHardDisk)
7015 break;
7016
7017 PCFGMNODE pCur;
7018 rc = CFGMR3InsertNode(pParent, "Parent", &pCur); RC_CHECK();
7019 hrc = curHardDisk->COMGETTER(Format)(bstr.asOutParam()); H();
7020 rc = CFGMR3InsertString(pCur, "Format", Utf8Str(bstr)); RC_CHECK();
7021 hrc = curHardDisk->COMGETTER(Location)(bstr.asOutParam()); H();
7022 rc = CFGMR3InsertString(pCur, "Path", Utf8Str(bstr)); RC_CHECK();
7023
7024 /* next */
7025 pParent = pCur;
7026 parentHardDisk = curHardDisk;
7027 }
7028
7029 /*
7030 * Attach the new driver.
7031 */
7032 rc = PDMR3DeviceAttach(pVM, pcszDevice, 0, iLUN, NULL); RC_CHECK();
7033
7034 LogFlowFunc (("Returns success\n"));
7035 return rc;
7036}
7037
7038
7039/**
7040 * Thread for executing the saved state operation.
7041 *
7042 * @param Thread The thread handle.
7043 * @param pvUser Pointer to a VMSaveTask structure.
7044 * @return VINF_SUCCESS (ignored).
7045 *
7046 * @note Locks the Console object for writing.
7047 */
7048/*static*/
7049DECLCALLBACK (int) Console::saveStateThread (RTTHREAD Thread, void *pvUser)
7050{
7051 LogFlowFuncEnter();
7052
7053 std::auto_ptr <VMSaveTask> task (static_cast <VMSaveTask *> (pvUser));
7054 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
7055
7056 Assert (!task->mSavedStateFile.isNull());
7057 Assert (!task->mProgress.isNull());
7058
7059 const ComObjPtr <Console> &that = task->mConsole;
7060
7061 /*
7062 * Note: no need to use addCaller() to protect Console or addVMCaller() to
7063 * protect mpVM because VMSaveTask does that
7064 */
7065
7066 Utf8Str errMsg;
7067 HRESULT rc = S_OK;
7068
7069 if (task->mIsSnapshot)
7070 {
7071 Assert (!task->mServerProgress.isNull());
7072 LogFlowFunc (("Waiting until the server creates differencing VDIs...\n"));
7073
7074 rc = task->mServerProgress->WaitForCompletion (-1);
7075 if (SUCCEEDED (rc))
7076 {
7077 HRESULT result = S_OK;
7078 rc = task->mServerProgress->COMGETTER(ResultCode) (&result);
7079 if (SUCCEEDED (rc))
7080 rc = result;
7081 }
7082 }
7083
7084 if (SUCCEEDED (rc))
7085 {
7086 LogFlowFunc (("Saving the state to '%s'...\n", task->mSavedStateFile.raw()));
7087
7088 int vrc = VMR3Save (that->mpVM, task->mSavedStateFile,
7089 Console::stateProgressCallback,
7090 static_cast <VMProgressTask *> (task.get()));
7091 if (VBOX_FAILURE (vrc))
7092 {
7093 errMsg = Utf8StrFmt (
7094 Console::tr ("Failed to save the machine state to '%s' (%Rrc)"),
7095 task->mSavedStateFile.raw(), vrc);
7096 rc = E_FAIL;
7097 }
7098 }
7099
7100 /* lock the console once we're going to access it */
7101 AutoWriteLock thatLock (that);
7102
7103 if (SUCCEEDED (rc))
7104 {
7105 if (task->mIsSnapshot)
7106 do
7107 {
7108 LogFlowFunc (("Reattaching new differencing hard disks...\n"));
7109
7110 com::SafeIfaceArray <IHardDisk2Attachment> atts;
7111 rc = that->mMachine->
7112 COMGETTER(HardDisk2Attachments) (ComSafeArrayAsOutParam (atts));
7113 if (FAILED (rc))
7114 break;
7115 for (size_t i = 0; i < atts.size(); ++ i)
7116 {
7117 PVMREQ pReq;
7118 /*
7119 * don't leave the lock since reconfigureHardDisks isn't going
7120 * to access Console.
7121 */
7122 int vrc = VMR3ReqCall (that->mpVM, VMREQDEST_ANY, &pReq, RT_INDEFINITE_WAIT,
7123 (PFNRT)reconfigureHardDisks, 3, that->mpVM,
7124 atts [i], &rc);
7125 if (VBOX_SUCCESS (rc))
7126 rc = pReq->iStatus;
7127 VMR3ReqFree (pReq);
7128 if (FAILED (rc))
7129 break;
7130 if (VBOX_FAILURE (vrc))
7131 {
7132 errMsg = Utf8StrFmt (Console::tr ("%Rrc"), vrc);
7133 rc = E_FAIL;
7134 break;
7135 }
7136 }
7137 }
7138 while (0);
7139 }
7140
7141 /* finalize the procedure regardless of the result */
7142 if (task->mIsSnapshot)
7143 {
7144 /*
7145 * finalize the requested snapshot object.
7146 * This will reset the machine state to the state it had right
7147 * before calling mControl->BeginTakingSnapshot().
7148 */
7149 that->mControl->EndTakingSnapshot (SUCCEEDED (rc));
7150 }
7151 else
7152 {
7153 /*
7154 * finalize the requested save state procedure.
7155 * In case of success, the server will set the machine state to Saved;
7156 * in case of failure it will reset the it to the state it had right
7157 * before calling mControl->BeginSavingState().
7158 */
7159 that->mControl->EndSavingState (SUCCEEDED (rc));
7160 }
7161
7162 /* synchronize the state with the server */
7163 if (task->mIsSnapshot || FAILED (rc))
7164 {
7165 if (task->mLastMachineState == MachineState_Running)
7166 {
7167 /* restore the paused state if appropriate */
7168 that->setMachineStateLocally (MachineState_Paused);
7169 /* restore the running state if appropriate */
7170 that->Resume();
7171 }
7172 else
7173 that->setMachineStateLocally (task->mLastMachineState);
7174 }
7175 else
7176 {
7177 /*
7178 * The machine has been successfully saved, so power it down
7179 * (vmstateChangeCallback() will set state to Saved on success).
7180 * Note: we release the task's VM caller, otherwise it will
7181 * deadlock.
7182 */
7183 task->releaseVMCaller();
7184
7185 rc = that->powerDown();
7186 }
7187
7188 /* notify the progress object about operation completion */
7189 if (SUCCEEDED (rc))
7190 task->mProgress->notifyComplete (S_OK);
7191 else
7192 {
7193 if (!errMsg.isNull())
7194 task->mProgress->notifyComplete (rc,
7195 COM_IIDOF(IConsole), Console::getComponentName(), errMsg);
7196 else
7197 task->mProgress->notifyComplete (rc);
7198 }
7199
7200 LogFlowFuncLeave();
7201 return VINF_SUCCESS;
7202}
7203
7204/**
7205 * Thread for powering down the Console.
7206 *
7207 * @param Thread The thread handle.
7208 * @param pvUser Pointer to the VMTask structure.
7209 * @return VINF_SUCCESS (ignored).
7210 *
7211 * @note Locks the Console object for writing.
7212 */
7213/*static*/
7214DECLCALLBACK (int) Console::powerDownThread (RTTHREAD Thread, void *pvUser)
7215{
7216 LogFlowFuncEnter();
7217
7218 std::auto_ptr <VMProgressTask> task (static_cast <VMProgressTask *> (pvUser));
7219 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
7220
7221 AssertReturn (task->isOk(), VERR_GENERAL_FAILURE);
7222
7223 const ComObjPtr <Console> &that = task->mConsole;
7224
7225 /* Note: no need to use addCaller() to protect Console because VMTask does
7226 * that */
7227
7228 /* wait until the method tat started us returns */
7229 AutoWriteLock thatLock (that);
7230
7231 /* release VM caller to avoid the powerDown() deadlock */
7232 task->releaseVMCaller();
7233
7234 that->powerDown (task->mProgress);
7235
7236 LogFlowFuncLeave();
7237 return VINF_SUCCESS;
7238}
7239
7240/**
7241 * The Main status driver instance data.
7242 */
7243typedef struct DRVMAINSTATUS
7244{
7245 /** The LED connectors. */
7246 PDMILEDCONNECTORS ILedConnectors;
7247 /** Pointer to the LED ports interface above us. */
7248 PPDMILEDPORTS pLedPorts;
7249 /** Pointer to the array of LED pointers. */
7250 PPDMLED *papLeds;
7251 /** The unit number corresponding to the first entry in the LED array. */
7252 RTUINT iFirstLUN;
7253 /** The unit number corresponding to the last entry in the LED array.
7254 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
7255 RTUINT iLastLUN;
7256} DRVMAINSTATUS, *PDRVMAINSTATUS;
7257
7258
7259/**
7260 * Notification about a unit which have been changed.
7261 *
7262 * The driver must discard any pointers to data owned by
7263 * the unit and requery it.
7264 *
7265 * @param pInterface Pointer to the interface structure containing the called function pointer.
7266 * @param iLUN The unit number.
7267 */
7268DECLCALLBACK(void) Console::drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
7269{
7270 PDRVMAINSTATUS pData = (PDRVMAINSTATUS)(void *)pInterface;
7271 if (iLUN >= pData->iFirstLUN && iLUN <= pData->iLastLUN)
7272 {
7273 PPDMLED pLed;
7274 int rc = pData->pLedPorts->pfnQueryStatusLed(pData->pLedPorts, iLUN, &pLed);
7275 if (VBOX_FAILURE(rc))
7276 pLed = NULL;
7277 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLUN - pData->iFirstLUN], pLed);
7278 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
7279 }
7280}
7281
7282
7283/**
7284 * Queries an interface to the driver.
7285 *
7286 * @returns Pointer to interface.
7287 * @returns NULL if the interface was not supported by the driver.
7288 * @param pInterface Pointer to this interface structure.
7289 * @param enmInterface The requested interface identification.
7290 */
7291DECLCALLBACK(void *) Console::drvStatus_QueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
7292{
7293 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
7294 PDRVMAINSTATUS pDrv = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
7295 switch (enmInterface)
7296 {
7297 case PDMINTERFACE_BASE:
7298 return &pDrvIns->IBase;
7299 case PDMINTERFACE_LED_CONNECTORS:
7300 return &pDrv->ILedConnectors;
7301 default:
7302 return NULL;
7303 }
7304}
7305
7306
7307/**
7308 * Destruct a status driver instance.
7309 *
7310 * @returns VBox status.
7311 * @param pDrvIns The driver instance data.
7312 */
7313DECLCALLBACK(void) Console::drvStatus_Destruct(PPDMDRVINS pDrvIns)
7314{
7315 PDRVMAINSTATUS pData = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
7316 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
7317 if (pData->papLeds)
7318 {
7319 unsigned iLed = pData->iLastLUN - pData->iFirstLUN + 1;
7320 while (iLed-- > 0)
7321 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLed], NULL);
7322 }
7323}
7324
7325
7326/**
7327 * Construct a status driver instance.
7328 *
7329 * @returns VBox status.
7330 * @param pDrvIns The driver instance data.
7331 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
7332 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
7333 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
7334 * iInstance it's expected to be used a bit in this function.
7335 */
7336DECLCALLBACK(int) Console::drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
7337{
7338 PDRVMAINSTATUS pData = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
7339 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
7340
7341 /*
7342 * Validate configuration.
7343 */
7344 if (!CFGMR3AreValuesValid(pCfgHandle, "papLeds\0First\0Last\0"))
7345 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
7346 PPDMIBASE pBaseIgnore;
7347 int rc = pDrvIns->pDrvHlp->pfnAttach(pDrvIns, &pBaseIgnore);
7348 if (rc != VERR_PDM_NO_ATTACHED_DRIVER)
7349 {
7350 AssertMsgFailed(("Configuration error: Not possible to attach anything to this driver!\n"));
7351 return VERR_PDM_DRVINS_NO_ATTACH;
7352 }
7353
7354 /*
7355 * Data.
7356 */
7357 pDrvIns->IBase.pfnQueryInterface = Console::drvStatus_QueryInterface;
7358 pData->ILedConnectors.pfnUnitChanged = Console::drvStatus_UnitChanged;
7359
7360 /*
7361 * Read config.
7362 */
7363 rc = CFGMR3QueryPtr(pCfgHandle, "papLeds", (void **)&pData->papLeds);
7364 if (VBOX_FAILURE(rc))
7365 {
7366 AssertMsgFailed(("Configuration error: Failed to query the \"papLeds\" value! rc=%Rrc\n", rc));
7367 return rc;
7368 }
7369
7370 rc = CFGMR3QueryU32(pCfgHandle, "First", &pData->iFirstLUN);
7371 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
7372 pData->iFirstLUN = 0;
7373 else if (VBOX_FAILURE(rc))
7374 {
7375 AssertMsgFailed(("Configuration error: Failed to query the \"First\" value! rc=%Rrc\n", rc));
7376 return rc;
7377 }
7378
7379 rc = CFGMR3QueryU32(pCfgHandle, "Last", &pData->iLastLUN);
7380 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
7381 pData->iLastLUN = 0;
7382 else if (VBOX_FAILURE(rc))
7383 {
7384 AssertMsgFailed(("Configuration error: Failed to query the \"Last\" value! rc=%Rrc\n", rc));
7385 return rc;
7386 }
7387 if (pData->iFirstLUN > pData->iLastLUN)
7388 {
7389 AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pData->iFirstLUN, pData->iLastLUN));
7390 return VERR_GENERAL_FAILURE;
7391 }
7392
7393 /*
7394 * Get the ILedPorts interface of the above driver/device and
7395 * query the LEDs we want.
7396 */
7397 pData->pLedPorts = (PPDMILEDPORTS)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_LED_PORTS);
7398 if (!pData->pLedPorts)
7399 {
7400 AssertMsgFailed(("Configuration error: No led ports interface above!\n"));
7401 return VERR_PDM_MISSING_INTERFACE_ABOVE;
7402 }
7403
7404 for (unsigned i = pData->iFirstLUN; i <= pData->iLastLUN; i++)
7405 Console::drvStatus_UnitChanged(&pData->ILedConnectors, i);
7406
7407 return VINF_SUCCESS;
7408}
7409
7410
7411/**
7412 * Keyboard driver registration record.
7413 */
7414const PDMDRVREG Console::DrvStatusReg =
7415{
7416 /* u32Version */
7417 PDM_DRVREG_VERSION,
7418 /* szDriverName */
7419 "MainStatus",
7420 /* pszDescription */
7421 "Main status driver (Main as in the API).",
7422 /* fFlags */
7423 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
7424 /* fClass. */
7425 PDM_DRVREG_CLASS_STATUS,
7426 /* cMaxInstances */
7427 ~0,
7428 /* cbInstance */
7429 sizeof(DRVMAINSTATUS),
7430 /* pfnConstruct */
7431 Console::drvStatus_Construct,
7432 /* pfnDestruct */
7433 Console::drvStatus_Destruct,
7434 /* pfnIOCtl */
7435 NULL,
7436 /* pfnPowerOn */
7437 NULL,
7438 /* pfnReset */
7439 NULL,
7440 /* pfnSuspend */
7441 NULL,
7442 /* pfnResume */
7443 NULL,
7444 /* pfnDetach */
7445 NULL
7446};
7447/* 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