VirtualBox

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

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

#3282: Collection got replaced with safe array. Warning, windows builds/tests may break.

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette