VirtualBox

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

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

Main & DrvVD: fix a whole bunch of incorrect CFGM key updates, required to get iSCSI snapshots working.

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