VirtualBox

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

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

implemented the ACPI sleep button

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

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