VirtualBox

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

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

HostServices/GuestProperties and Main: add timestamps and flags (currently stub code with no actual values accepted) to the guest properties

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