VirtualBox

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

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

Main: Fixed illegal cast of HardDisk * to IVirtualDiskImage * in attempt to fix #2622.

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

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