VirtualBox

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

Last change on this file since 6022 was 5999, checked in by vboxsync, 17 years ago

The Giant CDDL Dual-License Header Change.

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

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