VirtualBox

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

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

Main: PDMINS2DATA -> PDMINS_2_DATA.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 223.1 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 aName, BSTR *aValue,
3540 ULONG64 *aTimestamp, BSTR *aFlags)
3541{
3542#if !defined (VBOX_WITH_GUEST_PROPS)
3543 return E_NOTIMPL;
3544#else
3545 if (!VALID_PTR (aName))
3546 return E_INVALIDARG;
3547 if (!VALID_PTR (aValue))
3548 return E_POINTER;
3549 if ((aTimestamp != NULL) && !VALID_PTR (aTimestamp))
3550 return E_POINTER;
3551 if ((aFlags != NULL) && !VALID_PTR (aFlags))
3552 return E_POINTER;
3553
3554 AutoCaller autoCaller (this);
3555 AssertComRCReturnRC (autoCaller.rc());
3556
3557 /* protect mpVM (if not NULL) */
3558 AutoVMCallerWeak autoVMCaller (this);
3559 CheckComRCReturnRC (autoVMCaller.rc());
3560
3561 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
3562 * autoVMCaller, so there is no need to hold a lock of this */
3563
3564 HRESULT rc = E_UNEXPECTED;
3565 using namespace guestProp;
3566
3567 VBOXHGCMSVCPARM parm[4];
3568 Utf8Str Utf8Name = aName;
3569 AssertReturn(!Utf8Name.isNull(), E_OUTOFMEMORY);
3570 char pszBuffer[MAX_VALUE_LEN + MAX_FLAGS_LEN + 2];
3571
3572 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
3573 /* To save doing a const cast, we use the mutableRaw() member. */
3574 parm[0].u.pointer.addr = Utf8Name.mutableRaw();
3575 /* The + 1 is the null terminator */
3576 parm[0].u.pointer.size = Utf8Name.length() + 1;
3577 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
3578 parm[1].u.pointer.addr = pszBuffer;
3579 parm[1].u.pointer.size = sizeof(pszBuffer);
3580 int vrc = mVMMDev->hgcmHostCall ("VBoxGuestPropSvc", GET_PROP_HOST,
3581 4, &parm[0]);
3582 /* The returned string should never be able to be greater than our buffer */
3583 AssertLogRel (vrc != VERR_BUFFER_OVERFLOW);
3584 AssertLogRel (!RT_SUCCESS(vrc) || VBOX_HGCM_SVC_PARM_64BIT == parm[2].type);
3585 if (RT_SUCCESS (vrc) || (VERR_NOT_FOUND == vrc))
3586 {
3587 rc = S_OK;
3588 if (vrc != VERR_NOT_FOUND)
3589 {
3590 size_t iFlags = strlen(pszBuffer) + 1;
3591 Utf8Str(pszBuffer).cloneTo (aValue);
3592 *aTimestamp = parm[2].u.uint32;
3593 Utf8Str(pszBuffer + iFlags).cloneTo (aFlags);
3594 }
3595 else
3596 aValue = NULL;
3597 }
3598 else
3599 rc = setError (E_UNEXPECTED,
3600 tr ("Failed to call the VBoxGuestPropSvc service (%Rrc)"), vrc);
3601 return rc;
3602#endif /* else !defined (VBOX_WITH_GUEST_PROPS) */
3603}
3604
3605/**
3606 * @note Temporarily locks this object for writing.
3607 */
3608HRESULT Console::setGuestProperty (INPTR BSTR aName, INPTR BSTR aValue, INPTR BSTR aFlags)
3609{
3610#if !defined (VBOX_WITH_GUEST_PROPS)
3611 return E_NOTIMPL;
3612#else
3613 if (!VALID_PTR (aName))
3614 return E_INVALIDARG;
3615 if ((aValue != NULL) && !VALID_PTR (aValue))
3616 return E_INVALIDARG;
3617 if ((aFlags != NULL) && !VALID_PTR (aFlags))
3618 return E_INVALIDARG;
3619
3620 AutoCaller autoCaller (this);
3621 AssertComRCReturnRC (autoCaller.rc());
3622
3623 /* protect mpVM (if not NULL) */
3624 AutoVMCallerWeak autoVMCaller (this);
3625 CheckComRCReturnRC (autoVMCaller.rc());
3626
3627 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
3628 * autoVMCaller, so there is no need to hold a lock of this */
3629
3630 HRESULT rc = E_UNEXPECTED;
3631 using namespace guestProp;
3632
3633 VBOXHGCMSVCPARM parm[3];
3634 Utf8Str Utf8Name = aName;
3635 int vrc = VINF_SUCCESS;
3636
3637 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
3638 /* To save doing a const cast, we use the mutableRaw() member. */
3639 parm[0].u.pointer.addr = Utf8Name.mutableRaw();
3640 /* The + 1 is the null terminator */
3641 parm[0].u.pointer.size = Utf8Name.length() + 1;
3642 Utf8Str Utf8Value = aValue;
3643 if (aValue != NULL)
3644 {
3645 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
3646 /* To save doing a const cast, we use the mutableRaw() member. */
3647 parm[1].u.pointer.addr = Utf8Value.mutableRaw();
3648 /* The + 1 is the null terminator */
3649 parm[1].u.pointer.size = Utf8Value.length() + 1;
3650 }
3651 Utf8Str Utf8Flags = aFlags;
3652 if (aFlags != NULL)
3653 {
3654 parm[2].type = VBOX_HGCM_SVC_PARM_PTR;
3655 /* To save doing a const cast, we use the mutableRaw() member. */
3656 parm[2].u.pointer.addr = Utf8Flags.mutableRaw();
3657 /* The + 1 is the null terminator */
3658 parm[2].u.pointer.size = Utf8Flags.length() + 1;
3659 }
3660 if ((aValue != NULL) && (aFlags != NULL))
3661 vrc = mVMMDev->hgcmHostCall ("VBoxGuestPropSvc", SET_PROP_HOST,
3662 3, &parm[0]);
3663 else if (aValue != NULL)
3664 vrc = mVMMDev->hgcmHostCall ("VBoxGuestPropSvc", SET_PROP_VALUE_HOST,
3665 2, &parm[0]);
3666 else
3667 vrc = mVMMDev->hgcmHostCall ("VBoxGuestPropSvc", DEL_PROP_HOST,
3668 1, &parm[0]);
3669 if (RT_SUCCESS (vrc))
3670 rc = S_OK;
3671 else
3672 rc = setError (E_UNEXPECTED,
3673 tr ("Failed to call the VBoxGuestPropSvc service (%Rrc)"), vrc);
3674 return rc;
3675#endif /* else !defined (VBOX_WITH_GUEST_PROPS) */
3676}
3677
3678
3679/**
3680 * @note Temporarily locks this object for writing.
3681 */
3682HRESULT Console::enumerateGuestProperties (INPTR BSTR aPatterns,
3683 ComSafeArrayOut(BSTR, aNames),
3684 ComSafeArrayOut(BSTR, aValues),
3685 ComSafeArrayOut(ULONG64, aTimestamps),
3686 ComSafeArrayOut(BSTR, aFlags))
3687{
3688#if !defined (VBOX_WITH_GUEST_PROPS)
3689 return E_NOTIMPL;
3690#else
3691 if (!VALID_PTR (aPatterns) && (aPatterns != NULL))
3692 return E_POINTER;
3693 if (ComSafeArrayOutIsNull (aNames))
3694 return E_POINTER;
3695 if (ComSafeArrayOutIsNull (aValues))
3696 return E_POINTER;
3697 if (ComSafeArrayOutIsNull (aTimestamps))
3698 return E_POINTER;
3699 if (ComSafeArrayOutIsNull (aFlags))
3700 return E_POINTER;
3701
3702 AutoCaller autoCaller (this);
3703 AssertComRCReturnRC (autoCaller.rc());
3704
3705 /* protect mpVM (if not NULL) */
3706 AutoVMCallerWeak autoVMCaller (this);
3707 CheckComRCReturnRC (autoVMCaller.rc());
3708
3709 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
3710 * autoVMCaller, so there is no need to hold a lock of this */
3711
3712 using namespace guestProp;
3713
3714 VBOXHGCMSVCPARM parm[3];
3715
3716/*
3717 * Set up the pattern parameter, translating the comma-separated list to a
3718 * double-terminated zero-separated one.
3719 */
3720 Utf8Str Utf8PatternsIn = aPatterns;
3721 if ((aPatterns != NULL) && Utf8PatternsIn.isNull())
3722 return E_OUTOFMEMORY;
3723 size_t cchPatterns = Utf8PatternsIn.length();
3724 Utf8Str Utf8Patterns(cchPatterns + 2); /* Double terminator */
3725 if (Utf8Patterns.isNull())
3726 return E_OUTOFMEMORY;
3727 char *pszPatterns = Utf8Patterns.mutableRaw();
3728 unsigned iPatterns = 0;
3729 for (unsigned i = 0; i < cchPatterns; ++i)
3730 {
3731 char cIn = Utf8PatternsIn.raw()[i];
3732 if ((cIn != ',') && (cIn != ' '))
3733 pszPatterns[iPatterns] = cIn;
3734 else if (cIn != ' ')
3735 pszPatterns[iPatterns] = '\0';
3736 if (cIn != ' ')
3737 ++iPatterns;
3738 }
3739 pszPatterns[iPatterns] = '\0';
3740 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
3741 parm[0].u.pointer.addr = pszPatterns;
3742 parm[0].u.pointer.size = iPatterns + 1;
3743
3744/*
3745 * Now things get slightly complicated. Due to a race with the guest adding
3746 * properties, there is no good way to know how much large a buffer to provide
3747 * the service to enumerate into. We choose a decent starting size and loop a
3748 * few times, each time retrying with the size suggested by the service plus
3749 * one Kb.
3750 */
3751 size_t cchBuf = 4096;
3752 Utf8Str Utf8Buf;
3753 int vrc = VERR_BUFFER_OVERFLOW;
3754 for (unsigned i = 0; i < 10 && (VERR_BUFFER_OVERFLOW == vrc); ++i)
3755 {
3756 Utf8Buf.alloc(cchBuf + 1024);
3757 if (Utf8Buf.isNull())
3758 return E_OUTOFMEMORY;
3759 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
3760 parm[1].u.pointer.addr = Utf8Buf.mutableRaw();
3761 parm[1].u.pointer.size = cchBuf + 1024;
3762 vrc = mVMMDev->hgcmHostCall ("VBoxGuestPropSvc", ENUM_PROPS_HOST, 3,
3763 &parm[0]);
3764 if (parm[2].type != VBOX_HGCM_SVC_PARM_32BIT)
3765 return setError (E_FAIL, tr ("Internal application error"));
3766 cchBuf = parm[2].u.uint32;
3767 }
3768 if (VERR_BUFFER_OVERFLOW == vrc)
3769 return setError (E_UNEXPECTED, tr ("Temporary failure due to guest activity, please retry"));
3770
3771/*
3772 * Finally we have to unpack the data returned by the service into the safe
3773 * arrays supplied by the caller. We start by counting the number of entries.
3774 */
3775 const char *pszBuf
3776 = reinterpret_cast<const char *>(parm[1].u.pointer.addr);
3777 unsigned cEntries = 0;
3778 /* The list is terminated by a zero-length string at the end of a set
3779 * of four strings. */
3780 for (size_t i = 0; strlen(pszBuf + i) != 0; )
3781 {
3782 /* We are counting sets of four strings. */
3783 for (unsigned j = 0; j < 4; ++j)
3784 i += strlen(pszBuf + i) + 1;
3785 ++cEntries;
3786 }
3787
3788/*
3789 * And now we create the COM safe arrays and fill them in.
3790 */
3791 com::SafeArray <BSTR> names(cEntries);
3792 com::SafeArray <BSTR> values(cEntries);
3793 com::SafeArray <ULONG64> timestamps(cEntries);
3794 com::SafeArray <BSTR> flags(cEntries);
3795 size_t iBuf = 0;
3796 /* Rely on the service to have formated the data correctly. */
3797 for (unsigned i = 0; i < cEntries; ++i)
3798 {
3799 size_t cchName = strlen(pszBuf + iBuf);
3800 Bstr(pszBuf + iBuf).detachTo(&names[i]);
3801 iBuf += cchName + 1;
3802 size_t cchValue = strlen(pszBuf + iBuf);
3803 Bstr(pszBuf + iBuf).detachTo(&values[i]);
3804 iBuf += cchValue + 1;
3805 size_t cchTimestamp = strlen(pszBuf + iBuf);
3806 timestamps[i] = RTStrToUInt64(pszBuf + iBuf);
3807 iBuf += cchTimestamp + 1;
3808 size_t cchFlags = strlen(pszBuf + iBuf);
3809 Bstr(pszBuf + iBuf).detachTo(&flags[i]);
3810 iBuf += cchFlags + 1;
3811 }
3812 names.detachTo(ComSafeArrayOutArg (aNames));
3813 values.detachTo(ComSafeArrayOutArg (aValues));
3814 timestamps.detachTo(ComSafeArrayOutArg (aTimestamps));
3815 flags.detachTo(ComSafeArrayOutArg (aFlags));
3816 return S_OK;
3817#endif /* else !defined (VBOX_WITH_GUEST_PROPS) */
3818}
3819
3820/**
3821 * Gets called by Session::UpdateMachineState()
3822 * (IInternalSessionControl::updateMachineState()).
3823 *
3824 * Must be called only in certain cases (see the implementation).
3825 *
3826 * @note Locks this object for writing.
3827 */
3828HRESULT Console::updateMachineState (MachineState_T aMachineState)
3829{
3830 AutoCaller autoCaller (this);
3831 AssertComRCReturnRC (autoCaller.rc());
3832
3833 AutoWriteLock alock (this);
3834
3835 AssertReturn (mMachineState == MachineState_Saving ||
3836 mMachineState == MachineState_Discarding,
3837 E_FAIL);
3838
3839 return setMachineStateLocally (aMachineState);
3840}
3841
3842/**
3843 * @note Locks this object for writing.
3844 */
3845void Console::onMousePointerShapeChange(bool fVisible, bool fAlpha,
3846 uint32_t xHot, uint32_t yHot,
3847 uint32_t width, uint32_t height,
3848 void *pShape)
3849{
3850#if 0
3851 LogFlowThisFuncEnter();
3852 LogFlowThisFunc (("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, "
3853 "height=%d, shape=%p\n",
3854 fVisible, fAlpha, xHot, yHot, width, height, pShape));
3855#endif
3856
3857 AutoCaller autoCaller (this);
3858 AssertComRCReturnVoid (autoCaller.rc());
3859
3860 /* We need a write lock because we alter the cached callback data */
3861 AutoWriteLock alock (this);
3862
3863 /* Save the callback arguments */
3864 mCallbackData.mpsc.visible = fVisible;
3865 mCallbackData.mpsc.alpha = fAlpha;
3866 mCallbackData.mpsc.xHot = xHot;
3867 mCallbackData.mpsc.yHot = yHot;
3868 mCallbackData.mpsc.width = width;
3869 mCallbackData.mpsc.height = height;
3870
3871 /* start with not valid */
3872 bool wasValid = mCallbackData.mpsc.valid;
3873 mCallbackData.mpsc.valid = false;
3874
3875 if (pShape != NULL)
3876 {
3877 size_t cb = (width + 7) / 8 * height; /* size of the AND mask */
3878 cb = ((cb + 3) & ~3) + width * 4 * height; /* + gap + size of the XOR mask */
3879 /* try to reuse the old shape buffer if the size is the same */
3880 if (!wasValid)
3881 mCallbackData.mpsc.shape = NULL;
3882 else
3883 if (mCallbackData.mpsc.shape != NULL && mCallbackData.mpsc.shapeSize != cb)
3884 {
3885 RTMemFree (mCallbackData.mpsc.shape);
3886 mCallbackData.mpsc.shape = NULL;
3887 }
3888 if (mCallbackData.mpsc.shape == NULL)
3889 {
3890 mCallbackData.mpsc.shape = (BYTE *) RTMemAllocZ (cb);
3891 AssertReturnVoid (mCallbackData.mpsc.shape);
3892 }
3893 mCallbackData.mpsc.shapeSize = cb;
3894 memcpy (mCallbackData.mpsc.shape, pShape, cb);
3895 }
3896 else
3897 {
3898 if (wasValid && mCallbackData.mpsc.shape != NULL)
3899 RTMemFree (mCallbackData.mpsc.shape);
3900 mCallbackData.mpsc.shape = NULL;
3901 mCallbackData.mpsc.shapeSize = 0;
3902 }
3903
3904 mCallbackData.mpsc.valid = true;
3905
3906 CallbackList::iterator it = mCallbacks.begin();
3907 while (it != mCallbacks.end())
3908 (*it++)->OnMousePointerShapeChange (fVisible, fAlpha, xHot, yHot,
3909 width, height, (BYTE *) pShape);
3910
3911#if 0
3912 LogFlowThisFuncLeave();
3913#endif
3914}
3915
3916/**
3917 * @note Locks this object for writing.
3918 */
3919void Console::onMouseCapabilityChange (BOOL supportsAbsolute, BOOL needsHostCursor)
3920{
3921 LogFlowThisFunc (("supportsAbsolute=%d needsHostCursor=%d\n",
3922 supportsAbsolute, needsHostCursor));
3923
3924 AutoCaller autoCaller (this);
3925 AssertComRCReturnVoid (autoCaller.rc());
3926
3927 /* We need a write lock because we alter the cached callback data */
3928 AutoWriteLock alock (this);
3929
3930 /* save the callback arguments */
3931 mCallbackData.mcc.supportsAbsolute = supportsAbsolute;
3932 mCallbackData.mcc.needsHostCursor = needsHostCursor;
3933 mCallbackData.mcc.valid = true;
3934
3935 CallbackList::iterator it = mCallbacks.begin();
3936 while (it != mCallbacks.end())
3937 {
3938 Log2(("Console::onMouseCapabilityChange: calling %p\n", (void*)*it));
3939 (*it++)->OnMouseCapabilityChange (supportsAbsolute, needsHostCursor);
3940 }
3941}
3942
3943/**
3944 * @note Locks this object for reading.
3945 */
3946void Console::onStateChange (MachineState_T machineState)
3947{
3948 AutoCaller autoCaller (this);
3949 AssertComRCReturnVoid (autoCaller.rc());
3950
3951 AutoReadLock alock (this);
3952
3953 CallbackList::iterator it = mCallbacks.begin();
3954 while (it != mCallbacks.end())
3955 (*it++)->OnStateChange (machineState);
3956}
3957
3958/**
3959 * @note Locks this object for reading.
3960 */
3961void Console::onAdditionsStateChange()
3962{
3963 AutoCaller autoCaller (this);
3964 AssertComRCReturnVoid (autoCaller.rc());
3965
3966 AutoReadLock alock (this);
3967
3968 CallbackList::iterator it = mCallbacks.begin();
3969 while (it != mCallbacks.end())
3970 (*it++)->OnAdditionsStateChange();
3971}
3972
3973/**
3974 * @note Locks this object for reading.
3975 */
3976void Console::onAdditionsOutdated()
3977{
3978 AutoCaller autoCaller (this);
3979 AssertComRCReturnVoid (autoCaller.rc());
3980
3981 AutoReadLock alock (this);
3982
3983 /** @todo Use the On-Screen Display feature to report the fact.
3984 * The user should be told to install additions that are
3985 * provided with the current VBox build:
3986 * VBOX_VERSION_MAJOR.VBOX_VERSION_MINOR.VBOX_VERSION_BUILD
3987 */
3988}
3989
3990/**
3991 * @note Locks this object for writing.
3992 */
3993void Console::onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
3994{
3995 AutoCaller autoCaller (this);
3996 AssertComRCReturnVoid (autoCaller.rc());
3997
3998 /* We need a write lock because we alter the cached callback data */
3999 AutoWriteLock alock (this);
4000
4001 /* save the callback arguments */
4002 mCallbackData.klc.numLock = fNumLock;
4003 mCallbackData.klc.capsLock = fCapsLock;
4004 mCallbackData.klc.scrollLock = fScrollLock;
4005 mCallbackData.klc.valid = true;
4006
4007 CallbackList::iterator it = mCallbacks.begin();
4008 while (it != mCallbacks.end())
4009 (*it++)->OnKeyboardLedsChange(fNumLock, fCapsLock, fScrollLock);
4010}
4011
4012/**
4013 * @note Locks this object for reading.
4014 */
4015void Console::onUSBDeviceStateChange (IUSBDevice *aDevice, bool aAttached,
4016 IVirtualBoxErrorInfo *aError)
4017{
4018 AutoCaller autoCaller (this);
4019 AssertComRCReturnVoid (autoCaller.rc());
4020
4021 AutoReadLock alock (this);
4022
4023 CallbackList::iterator it = mCallbacks.begin();
4024 while (it != mCallbacks.end())
4025 (*it++)->OnUSBDeviceStateChange (aDevice, aAttached, aError);
4026}
4027
4028/**
4029 * @note Locks this object for reading.
4030 */
4031void Console::onRuntimeError (BOOL aFatal, INPTR BSTR aErrorID, INPTR BSTR aMessage)
4032{
4033 AutoCaller autoCaller (this);
4034 AssertComRCReturnVoid (autoCaller.rc());
4035
4036 AutoReadLock alock (this);
4037
4038 CallbackList::iterator it = mCallbacks.begin();
4039 while (it != mCallbacks.end())
4040 (*it++)->OnRuntimeError (aFatal, aErrorID, aMessage);
4041}
4042
4043/**
4044 * @note Locks this object for reading.
4045 */
4046HRESULT Console::onShowWindow (BOOL aCheck, BOOL *aCanShow, ULONG64 *aWinId)
4047{
4048 AssertReturn (aCanShow, E_POINTER);
4049 AssertReturn (aWinId, E_POINTER);
4050
4051 *aCanShow = FALSE;
4052 *aWinId = 0;
4053
4054 AutoCaller autoCaller (this);
4055 AssertComRCReturnRC (autoCaller.rc());
4056
4057 AutoReadLock alock (this);
4058
4059 HRESULT rc = S_OK;
4060 CallbackList::iterator it = mCallbacks.begin();
4061
4062 if (aCheck)
4063 {
4064 while (it != mCallbacks.end())
4065 {
4066 BOOL canShow = FALSE;
4067 rc = (*it++)->OnCanShowWindow (&canShow);
4068 AssertComRC (rc);
4069 if (FAILED (rc) || !canShow)
4070 return rc;
4071 }
4072 *aCanShow = TRUE;
4073 }
4074 else
4075 {
4076 while (it != mCallbacks.end())
4077 {
4078 ULONG64 winId = 0;
4079 rc = (*it++)->OnShowWindow (&winId);
4080 AssertComRC (rc);
4081 if (FAILED (rc))
4082 return rc;
4083 /* only one callback may return non-null winId */
4084 Assert (*aWinId == 0 || winId == 0);
4085 if (*aWinId == 0)
4086 *aWinId = winId;
4087 }
4088 }
4089
4090 return S_OK;
4091}
4092
4093// private methods
4094////////////////////////////////////////////////////////////////////////////////
4095
4096/**
4097 * Increases the usage counter of the mpVM pointer. Guarantees that
4098 * VMR3Destroy() will not be called on it at least until releaseVMCaller()
4099 * is called.
4100 *
4101 * If this method returns a failure, the caller is not allowed to use mpVM
4102 * and may return the failed result code to the upper level. This method sets
4103 * the extended error info on failure if \a aQuiet is false.
4104 *
4105 * Setting \a aQuiet to true is useful for methods that don't want to return
4106 * the failed result code to the caller when this method fails (e.g. need to
4107 * silently check for the mpVM avaliability).
4108 *
4109 * When mpVM is NULL but \a aAllowNullVM is true, a corresponding error will be
4110 * returned instead of asserting. Having it false is intended as a sanity check
4111 * for methods that have checked mMachineState and expect mpVM *NOT* to be NULL.
4112 *
4113 * @param aQuiet true to suppress setting error info
4114 * @param aAllowNullVM true to accept mpVM being NULL and return a failure
4115 * (otherwise this method will assert if mpVM is NULL)
4116 *
4117 * @note Locks this object for writing.
4118 */
4119HRESULT Console::addVMCaller (bool aQuiet /* = false */,
4120 bool aAllowNullVM /* = false */)
4121{
4122 AutoCaller autoCaller (this);
4123 AssertComRCReturnRC (autoCaller.rc());
4124
4125 AutoWriteLock alock (this);
4126
4127 if (mVMDestroying)
4128 {
4129 /* powerDown() is waiting for all callers to finish */
4130 return aQuiet ? E_ACCESSDENIED : setError (E_ACCESSDENIED,
4131 tr ("Virtual machine is being powered down"));
4132 }
4133
4134 if (mpVM == NULL)
4135 {
4136 Assert (aAllowNullVM == true);
4137
4138 /* The machine is not powered up */
4139 return aQuiet ? E_ACCESSDENIED : setError (E_ACCESSDENIED,
4140 tr ("Virtual machine is not powered up"));
4141 }
4142
4143 ++ mVMCallers;
4144
4145 return S_OK;
4146}
4147
4148/**
4149 * Decreases the usage counter of the mpVM pointer. Must always complete
4150 * the addVMCaller() call after the mpVM pointer is no more necessary.
4151 *
4152 * @note Locks this object for writing.
4153 */
4154void Console::releaseVMCaller()
4155{
4156 AutoCaller autoCaller (this);
4157 AssertComRCReturnVoid (autoCaller.rc());
4158
4159 AutoWriteLock alock (this);
4160
4161 AssertReturnVoid (mpVM != NULL);
4162
4163 Assert (mVMCallers > 0);
4164 -- mVMCallers;
4165
4166 if (mVMCallers == 0 && mVMDestroying)
4167 {
4168 /* inform powerDown() there are no more callers */
4169 RTSemEventSignal (mVMZeroCallersSem);
4170 }
4171}
4172
4173/**
4174 * Initialize the release logging facility. In case something
4175 * goes wrong, there will be no release logging. Maybe in the future
4176 * we can add some logic to use different file names in this case.
4177 * Note that the logic must be in sync with Machine::DeleteSettings().
4178 */
4179HRESULT Console::consoleInitReleaseLog (const ComPtr <IMachine> aMachine)
4180{
4181 HRESULT hrc = S_OK;
4182
4183 Bstr logFolder;
4184 hrc = aMachine->COMGETTER(LogFolder) (logFolder.asOutParam());
4185 CheckComRCReturnRC (hrc);
4186
4187 Utf8Str logDir = logFolder;
4188
4189 /* make sure the Logs folder exists */
4190 Assert (!logDir.isEmpty());
4191 if (!RTDirExists (logDir))
4192 RTDirCreateFullPath (logDir, 0777);
4193
4194 Utf8Str logFile = Utf8StrFmt ("%s%cVBox.log",
4195 logDir.raw(), RTPATH_DELIMITER);
4196 Utf8Str pngFile = Utf8StrFmt ("%s%cVBox.png",
4197 logDir.raw(), RTPATH_DELIMITER);
4198
4199 /*
4200 * Age the old log files
4201 * Rename .(n-1) to .(n), .(n-2) to .(n-1), ..., and the last log file to .1
4202 * Overwrite target files in case they exist.
4203 */
4204 ComPtr<IVirtualBox> virtualBox;
4205 aMachine->COMGETTER(Parent)(virtualBox.asOutParam());
4206 ComPtr <ISystemProperties> systemProperties;
4207 virtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam());
4208 ULONG uLogHistoryCount = 3;
4209 systemProperties->COMGETTER(LogHistoryCount)(&uLogHistoryCount);
4210 if (uLogHistoryCount)
4211 {
4212 for (int i = uLogHistoryCount-1; i >= 0; i--)
4213 {
4214 Utf8Str *files[] = { &logFile, &pngFile };
4215 Utf8Str oldName, newName;
4216
4217 for (unsigned int j = 0; j < ELEMENTS (files); ++ j)
4218 {
4219 if (i > 0)
4220 oldName = Utf8StrFmt ("%s.%d", files [j]->raw(), i);
4221 else
4222 oldName = *files [j];
4223 newName = Utf8StrFmt ("%s.%d", files [j]->raw(), i + 1);
4224 /* If the old file doesn't exist, delete the new file (if it
4225 * exists) to provide correct rotation even if the sequence is
4226 * broken */
4227 if ( RTFileRename (oldName, newName, RTFILEMOVE_FLAGS_REPLACE)
4228 == VERR_FILE_NOT_FOUND)
4229 RTFileDelete (newName);
4230 }
4231 }
4232 }
4233
4234 PRTLOGGER loggerRelease;
4235 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
4236 RTUINT fFlags = RTLOGFLAGS_PREFIX_TIME_PROG;
4237#if defined (RT_OS_WINDOWS) || defined (RT_OS_OS2)
4238 fFlags |= RTLOGFLAGS_USECRLF;
4239#endif
4240 char szError[RTPATH_MAX + 128] = "";
4241 int vrc = RTLogCreateEx(&loggerRelease, fFlags, "all",
4242 "VBOX_RELEASE_LOG", RT_ELEMENTS(s_apszGroups), s_apszGroups,
4243 RTLOGDEST_FILE, szError, sizeof(szError), logFile.raw());
4244 if (RT_SUCCESS(vrc))
4245 {
4246 /* some introductory information */
4247 RTTIMESPEC timeSpec;
4248 char nowUct[64];
4249 RTTimeSpecToString(RTTimeNow(&timeSpec), nowUct, sizeof(nowUct));
4250 RTLogRelLogger(loggerRelease, 0, ~0U,
4251 "VirtualBox %s r%d %s (%s %s) release log\n"
4252 "Log opened %s\n",
4253 VBOX_VERSION_STRING, VBoxSVNRev (), VBOX_BUILD_TARGET,
4254 __DATE__, __TIME__, nowUct);
4255
4256 /* register this logger as the release logger */
4257 RTLogRelSetDefaultInstance(loggerRelease);
4258 hrc = S_OK;
4259 }
4260 else
4261 hrc = setError (E_FAIL,
4262 tr ("Failed to open release log (%s, %Rrc)"), szError, vrc);
4263
4264 return hrc;
4265}
4266
4267
4268/**
4269 * Internal power off worker routine.
4270 *
4271 * This method may be called only at certain places with the folliwing meaning
4272 * as shown below:
4273 *
4274 * - if the machine state is either Running or Paused, a normal
4275 * Console-initiated powerdown takes place (e.g. PowerDown());
4276 * - if the machine state is Saving, saveStateThread() has successfully
4277 * done its job;
4278 * - if the machine state is Starting or Restoring, powerUpThread() has
4279 * failed to start/load the VM;
4280 * - if the machine state is Stopping, the VM has powered itself off
4281 * (i.e. not as a result of the powerDown() call).
4282 *
4283 * Calling it in situations other than the above will cause unexpected
4284 * behavior.
4285 *
4286 * Note that this method should be the only one that destroys mpVM and sets
4287 * it to NULL.
4288 *
4289 * @note Locks this object for writing.
4290 *
4291 * @note Never call this method from a thread that called addVMCaller() or
4292 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
4293 * release(). Otherwise it will deadlock.
4294 */
4295HRESULT Console::powerDown()
4296{
4297 LogFlowThisFuncEnter();
4298
4299 AutoCaller autoCaller (this);
4300 AssertComRCReturnRC (autoCaller.rc());
4301
4302 AutoWriteLock alock (this);
4303 int vrc = VINF_SUCCESS;
4304
4305 /* sanity */
4306 AssertReturn (mVMDestroying == false, E_FAIL);
4307
4308 LogRel (("Console::powerDown(): a request to power off the VM has been issued "
4309 "(mMachineState=%d, InUninit=%d)\n",
4310 mMachineState, autoCaller.state() == InUninit));
4311
4312 /*
4313 * Stop the VRDP server to prevent new clients connection while VM is being powered off.
4314 */
4315 if (mConsoleVRDPServer)
4316 {
4317 LogFlowThisFunc (("Stopping VRDP server...\n"));
4318
4319 /* Leave the lock since EMT will call us back as addVMCaller in updateDisplayData(). */
4320 alock.leave();
4321
4322 mConsoleVRDPServer->Stop();
4323
4324 alock.enter();
4325 }
4326
4327
4328#ifdef VBOX_HGCM
4329 /*
4330 * Shutdown HGCM services before stopping the guest, because they might need a cleanup.
4331 */
4332 if (mVMMDev)
4333 {
4334 LogFlowThisFunc (("Shutdown HGCM...\n"));
4335
4336 /* Leave the lock. */
4337 alock.leave();
4338
4339 mVMMDev->hgcmShutdown ();
4340
4341 alock.enter();
4342 }
4343# ifdef VBOX_WITH_GUEST_PROPS
4344 /* Save all guest property store entries to the machine XML file */
4345 PCFGMNODE pValues = CFGMR3GetChild (CFGMR3GetRoot (mpVM), "GuestProps/Values/");
4346 PCFGMNODE pTimestamps = CFGMR3GetChild (CFGMR3GetRoot (mpVM), "GuestProps/Timestamps/");
4347 PCFGMNODE pFlags = CFGMR3GetChild (CFGMR3GetRoot (mpVM), "GuestProps/Flags/");
4348 /* Count the number of entries we have */
4349 unsigned cValues = 0;
4350 for (PCFGMLEAF pValue = CFGMR3GetFirstValue (pValues); pValue != NULL;
4351 pValue = CFGMR3GetNextValue (pValue))
4352 ++cValues;
4353 /* And pack them into safe arrays */
4354 com::SafeArray <BSTR> names(cValues);
4355 com::SafeArray <BSTR> values(cValues);
4356 com::SafeArray <ULONG64> timestamps(cValues);
4357 com::SafeArray <BSTR> flags(cValues);
4358 PCFGMLEAF pValue = CFGMR3GetFirstValue (pValues);
4359 vrc = VINF_SUCCESS;
4360 unsigned iProp = 0;
4361 while (pValue != NULL && RT_SUCCESS(vrc))
4362 {
4363 using namespace guestProp;
4364
4365 char szPropName[MAX_NAME_LEN + 1];
4366 char szPropValue[MAX_VALUE_LEN + 1];
4367 char szPropFlags[MAX_FLAGS_LEN + 1];
4368 ULONG64 u64Timestamp = 0; /* default */
4369 szPropFlags[0] = '\0'; /* default */
4370 vrc = CFGMR3GetValueName (pValue, szPropName, sizeof(szPropName));
4371 if (RT_SUCCESS(vrc))
4372 vrc = CFGMR3QueryString (pValues, szPropName, szPropValue, sizeof(szPropValue));
4373 if (RT_SUCCESS(vrc))
4374 {
4375 CFGMR3QueryString (pFlags, szPropName, szPropFlags, sizeof(szPropFlags));
4376 CFGMR3QueryU64 (pTimestamps, szPropName, &u64Timestamp);
4377 Bstr(szPropName).cloneTo(&names[iProp]);
4378 Bstr(szPropValue).cloneTo(&values[iProp]);
4379 timestamps[iProp] = u64Timestamp;
4380 Bstr(szPropFlags).cloneTo(&flags[iProp]);
4381 pValue = CFGMR3GetNextValue (pValue);
4382 ++iProp;
4383 if (iProp >= cValues)
4384 vrc = VERR_TOO_MUCH_DATA;
4385 }
4386 }
4387 if (RT_SUCCESS(vrc) || (VERR_TOO_MUCH_DATA == vrc))
4388 mControl->PushGuestProperties(ComSafeArrayAsInParam (names),
4389 ComSafeArrayAsInParam (values),
4390 ComSafeArrayAsInParam (timestamps),
4391 ComSafeArrayAsInParam (flags));
4392# endif /* VBOX_WITH_GUEST_PROPS defined */
4393#endif /* VBOX_HGCM */
4394
4395 /* First, wait for all mpVM callers to finish their work if necessary */
4396 if (mVMCallers > 0)
4397 {
4398 /* go to the destroying state to prevent from adding new callers */
4399 mVMDestroying = true;
4400
4401 /* lazy creation */
4402 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
4403 RTSemEventCreate (&mVMZeroCallersSem);
4404
4405 LogFlowThisFunc (("Waiting for mpVM callers (%d) to drop to zero...\n",
4406 mVMCallers));
4407
4408 alock.leave();
4409
4410 RTSemEventWait (mVMZeroCallersSem, RT_INDEFINITE_WAIT);
4411
4412 alock.enter();
4413 }
4414
4415 AssertReturn (mpVM, E_FAIL);
4416
4417 AssertMsg (mMachineState == MachineState_Running ||
4418 mMachineState == MachineState_Paused ||
4419 mMachineState == MachineState_Stuck ||
4420 mMachineState == MachineState_Saving ||
4421 mMachineState == MachineState_Starting ||
4422 mMachineState == MachineState_Restoring ||
4423 mMachineState == MachineState_Stopping,
4424 ("Invalid machine state: %d\n", mMachineState));
4425
4426 HRESULT rc = S_OK;
4427 vrc = VINF_SUCCESS;
4428
4429 /*
4430 * Power off the VM if not already done that. In case of Stopping, the VM
4431 * has powered itself off and notified Console in vmstateChangeCallback().
4432 * In case of Starting or Restoring, powerUpThread() is calling us on
4433 * failure, so the VM is already off at that point.
4434 */
4435 if (mMachineState != MachineState_Stopping &&
4436 mMachineState != MachineState_Starting &&
4437 mMachineState != MachineState_Restoring)
4438 {
4439 /*
4440 * don't go from Saving to Stopping, vmstateChangeCallback needs it
4441 * to set the state to Saved on VMSTATE_TERMINATED.
4442 */
4443 if (mMachineState != MachineState_Saving)
4444 setMachineState (MachineState_Stopping);
4445
4446 LogFlowThisFunc (("Powering off the VM...\n"));
4447
4448 /* Leave the lock since EMT will call us back on VMR3PowerOff() */
4449 alock.leave();
4450
4451 vrc = VMR3PowerOff (mpVM);
4452 /*
4453 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
4454 * VM-(guest-)initiated power off happened in parallel a ms before
4455 * this call. So far, we let this error pop up on the user's side.
4456 */
4457
4458 alock.enter();
4459 }
4460
4461 LogFlowThisFunc (("Ready for VM destruction\n"));
4462
4463 /*
4464 * If we are called from Console::uninit(), then try to destroy the VM
4465 * even on failure (this will most likely fail too, but what to do?..)
4466 */
4467 if (VBOX_SUCCESS (vrc) || autoCaller.state() == InUninit)
4468 {
4469 /* If the machine has an USB comtroller, release all USB devices
4470 * (symmetric to the code in captureUSBDevices()) */
4471 bool fHasUSBController = false;
4472 {
4473 PPDMIBASE pBase;
4474 int vrc = PDMR3QueryLun (mpVM, "usb-ohci", 0, 0, &pBase);
4475 if (VBOX_SUCCESS (vrc))
4476 {
4477 fHasUSBController = true;
4478 detachAllUSBDevices (false /* aDone */);
4479 }
4480 }
4481
4482 /*
4483 * Now we've got to destroy the VM as well. (mpVM is not valid
4484 * beyond this point). We leave the lock before calling VMR3Destroy()
4485 * because it will result into calling destructors of drivers
4486 * associated with Console children which may in turn try to lock
4487 * Console (e.g. by instantiating SafeVMPtr to access mpVM). It's safe
4488 * here because mVMDestroying is set which should prevent any activity.
4489 */
4490
4491 /*
4492 * Set mpVM to NULL early just in case if some old code is not using
4493 * addVMCaller()/releaseVMCaller().
4494 */
4495 PVM pVM = mpVM;
4496 mpVM = NULL;
4497
4498 LogFlowThisFunc (("Destroying the VM...\n"));
4499
4500 alock.leave();
4501
4502 vrc = VMR3Destroy (pVM);
4503
4504 /* take the lock again */
4505 alock.enter();
4506
4507 if (VBOX_SUCCESS (vrc))
4508 {
4509 LogFlowThisFunc (("Machine has been destroyed (mMachineState=%d)\n",
4510 mMachineState));
4511 /*
4512 * Note: the Console-level machine state change happens on the
4513 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
4514 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
4515 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
4516 * occured yet. This is okay, because mMachineState is already
4517 * Stopping in this case, so any other attempt to call PowerDown()
4518 * will be rejected.
4519 */
4520 }
4521 else
4522 {
4523 /* bad bad bad, but what to do? */
4524 mpVM = pVM;
4525 rc = setError (E_FAIL,
4526 tr ("Could not destroy the machine. (Error: %Vrc)"), vrc);
4527 }
4528
4529 /*
4530 * Complete the detaching of the USB devices.
4531 */
4532 if (fHasUSBController)
4533 detachAllUSBDevices (true /* aDone */);
4534 }
4535 else
4536 {
4537 rc = setError (E_FAIL,
4538 tr ("Could not power off the machine. (Error: %Vrc)"), vrc);
4539 }
4540
4541 /*
4542 * Finished with destruction. Note that if something impossible happened
4543 * and we've failed to destroy the VM, mVMDestroying will remain false and
4544 * mMachineState will be something like Stopping, so most Console methods
4545 * will return an error to the caller.
4546 */
4547 if (mpVM == NULL)
4548 mVMDestroying = false;
4549
4550 if (SUCCEEDED (rc))
4551 {
4552 /* uninit dynamically allocated members of mCallbackData */
4553 if (mCallbackData.mpsc.valid)
4554 {
4555 if (mCallbackData.mpsc.shape != NULL)
4556 RTMemFree (mCallbackData.mpsc.shape);
4557 }
4558 memset (&mCallbackData, 0, sizeof (mCallbackData));
4559 }
4560
4561 LogFlowThisFuncLeave();
4562 return rc;
4563}
4564
4565/**
4566 * @note Locks this object for writing.
4567 */
4568HRESULT Console::setMachineState (MachineState_T aMachineState,
4569 bool aUpdateServer /* = true */)
4570{
4571 AutoCaller autoCaller (this);
4572 AssertComRCReturnRC (autoCaller.rc());
4573
4574 AutoWriteLock alock (this);
4575
4576 HRESULT rc = S_OK;
4577
4578 if (mMachineState != aMachineState)
4579 {
4580 LogFlowThisFunc (("machineState=%d\n", aMachineState));
4581 mMachineState = aMachineState;
4582
4583 /// @todo (dmik)
4584 // possibly, we need to redo onStateChange() using the dedicated
4585 // Event thread, like it is done in VirtualBox. This will make it
4586 // much safer (no deadlocks possible if someone tries to use the
4587 // console from the callback), however, listeners will lose the
4588 // ability to synchronously react to state changes (is it really
4589 // necessary??)
4590 LogFlowThisFunc (("Doing onStateChange()...\n"));
4591 onStateChange (aMachineState);
4592 LogFlowThisFunc (("Done onStateChange()\n"));
4593
4594 if (aUpdateServer)
4595 {
4596 /*
4597 * Server notification MUST be done from under the lock; otherwise
4598 * the machine state here and on the server might go out of sync, that
4599 * can lead to various unexpected results (like the machine state being
4600 * >= MachineState_Running on the server, while the session state is
4601 * already SessionState_Closed at the same time there).
4602 *
4603 * Cross-lock conditions should be carefully watched out: calling
4604 * UpdateState we will require Machine and SessionMachine locks
4605 * (remember that here we're holding the Console lock here, and
4606 * also all locks that have been entered by the thread before calling
4607 * this method).
4608 */
4609 LogFlowThisFunc (("Doing mControl->UpdateState()...\n"));
4610 rc = mControl->UpdateState (aMachineState);
4611 LogFlowThisFunc (("mControl->UpdateState()=%08X\n", rc));
4612 }
4613 }
4614
4615 return rc;
4616}
4617
4618/**
4619 * Searches for a shared folder with the given logical name
4620 * in the collection of shared folders.
4621 *
4622 * @param aName logical name of the shared folder
4623 * @param aSharedFolder where to return the found object
4624 * @param aSetError whether to set the error info if the folder is
4625 * not found
4626 * @return
4627 * S_OK when found or E_INVALIDARG when not found
4628 *
4629 * @note The caller must lock this object for writing.
4630 */
4631HRESULT Console::findSharedFolder (const BSTR aName,
4632 ComObjPtr <SharedFolder> &aSharedFolder,
4633 bool aSetError /* = false */)
4634{
4635 /* sanity check */
4636 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
4637
4638 SharedFolderMap::const_iterator it = mSharedFolders.find (aName);
4639 if (it != mSharedFolders.end())
4640 {
4641 aSharedFolder = it->second;
4642 return S_OK;
4643 }
4644
4645 if (aSetError)
4646 setError (E_INVALIDARG,
4647 tr ("Could not find a shared folder named '%ls'."), aName);
4648
4649 return E_INVALIDARG;
4650}
4651
4652/**
4653 * Fetches the list of global or machine shared folders from the server.
4654 *
4655 * @param aGlobal true to fetch global folders.
4656 *
4657 * @note The caller must lock this object for writing.
4658 */
4659HRESULT Console::fetchSharedFolders (BOOL aGlobal)
4660{
4661 /* sanity check */
4662 AssertReturn (AutoCaller (this).state() == InInit ||
4663 isWriteLockOnCurrentThread(), E_FAIL);
4664
4665 /* protect mpVM (if not NULL) */
4666 AutoVMCallerQuietWeak autoVMCaller (this);
4667
4668 HRESULT rc = S_OK;
4669
4670 bool online = mpVM && autoVMCaller.isOk() && mVMMDev->isShFlActive();
4671
4672 if (aGlobal)
4673 {
4674 /// @todo grab & process global folders when they are done
4675 }
4676 else
4677 {
4678 SharedFolderDataMap oldFolders;
4679 if (online)
4680 oldFolders = mMachineSharedFolders;
4681
4682 mMachineSharedFolders.clear();
4683
4684 ComPtr <ISharedFolderCollection> coll;
4685 rc = mMachine->COMGETTER(SharedFolders) (coll.asOutParam());
4686 AssertComRCReturnRC (rc);
4687
4688 ComPtr <ISharedFolderEnumerator> en;
4689 rc = coll->Enumerate (en.asOutParam());
4690 AssertComRCReturnRC (rc);
4691
4692 BOOL hasMore = FALSE;
4693 while (SUCCEEDED (rc = en->HasMore (&hasMore)) && hasMore)
4694 {
4695 ComPtr <ISharedFolder> folder;
4696 rc = en->GetNext (folder.asOutParam());
4697 CheckComRCBreakRC (rc);
4698
4699 Bstr name;
4700 Bstr hostPath;
4701 BOOL writable;
4702
4703 rc = folder->COMGETTER(Name) (name.asOutParam());
4704 CheckComRCBreakRC (rc);
4705 rc = folder->COMGETTER(HostPath) (hostPath.asOutParam());
4706 CheckComRCBreakRC (rc);
4707 rc = folder->COMGETTER(Writable) (&writable);
4708
4709 mMachineSharedFolders.insert (std::make_pair (name, SharedFolderData (hostPath, writable)));
4710
4711 /* send changes to HGCM if the VM is running */
4712 /// @todo report errors as runtime warnings through VMSetError
4713 if (online)
4714 {
4715 SharedFolderDataMap::iterator it = oldFolders.find (name);
4716 if (it == oldFolders.end() || it->second.mHostPath != hostPath)
4717 {
4718 /* a new machine folder is added or
4719 * the existing machine folder is changed */
4720 if (mSharedFolders.find (name) != mSharedFolders.end())
4721 ; /* the console folder exists, nothing to do */
4722 else
4723 {
4724 /* remove the old machhine folder (when changed)
4725 * or the global folder if any (when new) */
4726 if (it != oldFolders.end() ||
4727 mGlobalSharedFolders.find (name) !=
4728 mGlobalSharedFolders.end())
4729 rc = removeSharedFolder (name);
4730 /* create the new machine folder */
4731 rc = createSharedFolder (name, SharedFolderData (hostPath, writable));
4732 }
4733 }
4734 /* forget the processed (or identical) folder */
4735 if (it != oldFolders.end())
4736 oldFolders.erase (it);
4737
4738 rc = S_OK;
4739 }
4740 }
4741
4742 AssertComRCReturnRC (rc);
4743
4744 /* process outdated (removed) folders */
4745 /// @todo report errors as runtime warnings through VMSetError
4746 if (online)
4747 {
4748 for (SharedFolderDataMap::const_iterator it = oldFolders.begin();
4749 it != oldFolders.end(); ++ it)
4750 {
4751 if (mSharedFolders.find (it->first) != mSharedFolders.end())
4752 ; /* the console folder exists, nothing to do */
4753 else
4754 {
4755 /* remove the outdated machine folder */
4756 rc = removeSharedFolder (it->first);
4757 /* create the global folder if there is any */
4758 SharedFolderDataMap::const_iterator git =
4759 mGlobalSharedFolders.find (it->first);
4760 if (git != mGlobalSharedFolders.end())
4761 rc = createSharedFolder (git->first, git->second);
4762 }
4763 }
4764
4765 rc = S_OK;
4766 }
4767 }
4768
4769 return rc;
4770}
4771
4772/**
4773 * Searches for a shared folder with the given name in the list of machine
4774 * shared folders and then in the list of the global shared folders.
4775 *
4776 * @param aName Name of the folder to search for.
4777 * @param aIt Where to store the pointer to the found folder.
4778 * @return @c true if the folder was found and @c false otherwise.
4779 *
4780 * @note The caller must lock this object for reading.
4781 */
4782bool Console::findOtherSharedFolder (INPTR BSTR aName,
4783 SharedFolderDataMap::const_iterator &aIt)
4784{
4785 /* sanity check */
4786 AssertReturn (isWriteLockOnCurrentThread(), false);
4787
4788 /* first, search machine folders */
4789 aIt = mMachineSharedFolders.find (aName);
4790 if (aIt != mMachineSharedFolders.end())
4791 return true;
4792
4793 /* second, search machine folders */
4794 aIt = mGlobalSharedFolders.find (aName);
4795 if (aIt != mGlobalSharedFolders.end())
4796 return true;
4797
4798 return false;
4799}
4800
4801/**
4802 * Calls the HGCM service to add a shared folder definition.
4803 *
4804 * @param aName Shared folder name.
4805 * @param aHostPath Shared folder path.
4806 *
4807 * @note Must be called from under AutoVMCaller and when mpVM != NULL!
4808 * @note Doesn't lock anything.
4809 */
4810HRESULT Console::createSharedFolder (INPTR BSTR aName, SharedFolderData aData)
4811{
4812 ComAssertRet (aName && *aName, E_FAIL);
4813 ComAssertRet (aData.mHostPath, E_FAIL);
4814
4815 /* sanity checks */
4816 AssertReturn (mpVM, E_FAIL);
4817 AssertReturn (mVMMDev->isShFlActive(), E_FAIL);
4818
4819 VBOXHGCMSVCPARM parms[SHFL_CPARMS_ADD_MAPPING];
4820 SHFLSTRING *pFolderName, *pMapName;
4821 size_t cbString;
4822
4823 Log (("Adding shared folder '%ls' -> '%ls'\n", aName, aData.mHostPath.raw()));
4824
4825 cbString = (RTUtf16Len (aData.mHostPath) + 1) * sizeof (RTUTF16);
4826 if (cbString >= UINT16_MAX)
4827 return setError (E_INVALIDARG, tr ("The name is too long"));
4828 pFolderName = (SHFLSTRING *) RTMemAllocZ (sizeof (SHFLSTRING) + cbString);
4829 Assert (pFolderName);
4830 memcpy (pFolderName->String.ucs2, aData.mHostPath, cbString);
4831
4832 pFolderName->u16Size = (uint16_t)cbString;
4833 pFolderName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
4834
4835 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
4836 parms[0].u.pointer.addr = pFolderName;
4837 parms[0].u.pointer.size = sizeof (SHFLSTRING) + (uint16_t)cbString;
4838
4839 cbString = (RTUtf16Len (aName) + 1) * sizeof (RTUTF16);
4840 if (cbString >= UINT16_MAX)
4841 {
4842 RTMemFree (pFolderName);
4843 return setError (E_INVALIDARG, tr ("The host path is too long"));
4844 }
4845 pMapName = (SHFLSTRING *) RTMemAllocZ (sizeof(SHFLSTRING) + cbString);
4846 Assert (pMapName);
4847 memcpy (pMapName->String.ucs2, aName, cbString);
4848
4849 pMapName->u16Size = (uint16_t)cbString;
4850 pMapName->u16Length = (uint16_t)cbString - sizeof (RTUTF16);
4851
4852 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
4853 parms[1].u.pointer.addr = pMapName;
4854 parms[1].u.pointer.size = sizeof (SHFLSTRING) + (uint16_t)cbString;
4855
4856 parms[2].type = VBOX_HGCM_SVC_PARM_32BIT;
4857 parms[2].u.uint32 = aData.mWritable;
4858
4859 int vrc = mVMMDev->hgcmHostCall ("VBoxSharedFolders",
4860 SHFL_FN_ADD_MAPPING,
4861 SHFL_CPARMS_ADD_MAPPING, &parms[0]);
4862 RTMemFree (pFolderName);
4863 RTMemFree (pMapName);
4864
4865 if (VBOX_FAILURE (vrc))
4866 return setError (E_FAIL,
4867 tr ("Could not create a shared folder '%ls' "
4868 "mapped to '%ls' (%Vrc)"),
4869 aName, aData.mHostPath.raw(), vrc);
4870
4871 return S_OK;
4872}
4873
4874/**
4875 * Calls the HGCM service to remove the shared folder definition.
4876 *
4877 * @param aName Shared folder name.
4878 *
4879 * @note Must be called from under AutoVMCaller and when mpVM != NULL!
4880 * @note Doesn't lock anything.
4881 */
4882HRESULT Console::removeSharedFolder (INPTR BSTR aName)
4883{
4884 ComAssertRet (aName && *aName, E_FAIL);
4885
4886 /* sanity checks */
4887 AssertReturn (mpVM, E_FAIL);
4888 AssertReturn (mVMMDev->isShFlActive(), E_FAIL);
4889
4890 VBOXHGCMSVCPARM parms;
4891 SHFLSTRING *pMapName;
4892 size_t cbString;
4893
4894 Log (("Removing shared folder '%ls'\n", aName));
4895
4896 cbString = (RTUtf16Len (aName) + 1) * sizeof (RTUTF16);
4897 if (cbString >= UINT16_MAX)
4898 return setError (E_INVALIDARG, tr ("The name is too long"));
4899 pMapName = (SHFLSTRING *) RTMemAllocZ (sizeof (SHFLSTRING) + cbString);
4900 Assert (pMapName);
4901 memcpy (pMapName->String.ucs2, aName, cbString);
4902
4903 pMapName->u16Size = (uint16_t)cbString;
4904 pMapName->u16Length = (uint16_t)cbString - sizeof (RTUTF16);
4905
4906 parms.type = VBOX_HGCM_SVC_PARM_PTR;
4907 parms.u.pointer.addr = pMapName;
4908 parms.u.pointer.size = sizeof (SHFLSTRING) + (uint16_t)cbString;
4909
4910 int vrc = mVMMDev->hgcmHostCall ("VBoxSharedFolders",
4911 SHFL_FN_REMOVE_MAPPING,
4912 1, &parms);
4913 RTMemFree(pMapName);
4914 if (VBOX_FAILURE (vrc))
4915 return setError (E_FAIL,
4916 tr ("Could not remove the shared folder '%ls' (%Vrc)"),
4917 aName, vrc);
4918
4919 return S_OK;
4920}
4921
4922/**
4923 * VM state callback function. Called by the VMM
4924 * using its state machine states.
4925 *
4926 * Primarily used to handle VM initiated power off, suspend and state saving,
4927 * but also for doing termination completed work (VMSTATE_TERMINATE).
4928 *
4929 * In general this function is called in the context of the EMT.
4930 *
4931 * @param aVM The VM handle.
4932 * @param aState The new state.
4933 * @param aOldState The old state.
4934 * @param aUser The user argument (pointer to the Console object).
4935 *
4936 * @note Locks the Console object for writing.
4937 */
4938DECLCALLBACK(void)
4939Console::vmstateChangeCallback (PVM aVM, VMSTATE aState, VMSTATE aOldState,
4940 void *aUser)
4941{
4942 LogFlowFunc (("Changing state from %d to %d (aVM=%p)\n",
4943 aOldState, aState, aVM));
4944
4945 Console *that = static_cast <Console *> (aUser);
4946 AssertReturnVoid (that);
4947
4948 AutoCaller autoCaller (that);
4949 /*
4950 * Note that we must let this method proceed even if Console::uninit() has
4951 * been already called. In such case this VMSTATE change is a result of:
4952 * 1) powerDown() called from uninit() itself, or
4953 * 2) VM-(guest-)initiated power off.
4954 */
4955 AssertReturnVoid (autoCaller.isOk() ||
4956 autoCaller.state() == InUninit);
4957
4958 switch (aState)
4959 {
4960 /*
4961 * The VM has terminated
4962 */
4963 case VMSTATE_OFF:
4964 {
4965 AutoWriteLock alock (that);
4966
4967 if (that->mVMStateChangeCallbackDisabled)
4968 break;
4969
4970 /*
4971 * Do we still think that it is running? It may happen if this is
4972 * a VM-(guest-)initiated shutdown/poweroff.
4973 */
4974 if (that->mMachineState != MachineState_Stopping &&
4975 that->mMachineState != MachineState_Saving &&
4976 that->mMachineState != MachineState_Restoring)
4977 {
4978 LogFlowFunc (("VM has powered itself off but Console still "
4979 "thinks it is running. Notifying.\n"));
4980
4981 /* prevent powerDown() from calling VMR3PowerOff() again */
4982 that->setMachineState (MachineState_Stopping);
4983
4984 /*
4985 * Setup task object and thread to carry out the operation
4986 * asynchronously (if we call powerDown() right here but there
4987 * is one or more mpVM callers (added with addVMCaller()) we'll
4988 * deadlock.
4989 */
4990 std::auto_ptr <VMTask> task (new VMTask (that, true /* aUsesVMPtr */));
4991 /*
4992 * If creating a task is falied, this can currently mean one
4993 * of two: either Console::uninit() has been called just a ms
4994 * before (so a powerDown() call is already on the way), or
4995 * powerDown() itself is being already executed. Just do
4996 * nothing .
4997 */
4998 if (!task->isOk())
4999 {
5000 LogFlowFunc (("Console is already being uninitialized.\n"));
5001 break;
5002 }
5003
5004 int vrc = RTThreadCreate (NULL, Console::powerDownThread,
5005 (void *) task.get(), 0,
5006 RTTHREADTYPE_MAIN_WORKER, 0,
5007 "VMPowerDowm");
5008
5009 AssertMsgRC (vrc, ("Could not create VMPowerUp thread (%Vrc)\n", vrc));
5010 if (VBOX_FAILURE (vrc))
5011 break;
5012
5013 /* task is now owned by powerDownThread(), so release it */
5014 task.release();
5015 }
5016 break;
5017 }
5018
5019 /*
5020 * The VM has been completely destroyed.
5021 *
5022 * Note: This state change can happen at two points:
5023 * 1) At the end of VMR3Destroy() if it was not called from EMT.
5024 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
5025 * called by EMT.
5026 */
5027 case VMSTATE_TERMINATED:
5028 {
5029 AutoWriteLock alock (that);
5030
5031 if (that->mVMStateChangeCallbackDisabled)
5032 break;
5033
5034 /*
5035 * Terminate host interface networking. If aVM is NULL, we've been
5036 * manually called from powerUpThread() either before calling
5037 * VMR3Create() or after VMR3Create() failed, so no need to touch
5038 * networking.
5039 */
5040 if (aVM)
5041 that->powerDownHostInterfaces();
5042
5043 /*
5044 * From now on the machine is officially powered down or
5045 * remains in the Saved state.
5046 */
5047 switch (that->mMachineState)
5048 {
5049 default:
5050 AssertFailed();
5051 /* fall through */
5052 case MachineState_Stopping:
5053 /* successfully powered down */
5054 that->setMachineState (MachineState_PoweredOff);
5055 break;
5056 case MachineState_Saving:
5057 /*
5058 * successfully saved (note that the machine is already
5059 * in the Saved state on the server due to EndSavingState()
5060 * called from saveStateThread(), so only change the local
5061 * state)
5062 */
5063 that->setMachineStateLocally (MachineState_Saved);
5064 break;
5065 case MachineState_Starting:
5066 /*
5067 * failed to start, but be patient: set back to PoweredOff
5068 * (for similarity with the below)
5069 */
5070 that->setMachineState (MachineState_PoweredOff);
5071 break;
5072 case MachineState_Restoring:
5073 /*
5074 * failed to load the saved state file, but be patient:
5075 * set back to Saved (to preserve the saved state file)
5076 */
5077 that->setMachineState (MachineState_Saved);
5078 break;
5079 }
5080
5081 break;
5082 }
5083
5084 case VMSTATE_SUSPENDED:
5085 {
5086 if (aOldState == VMSTATE_RUNNING)
5087 {
5088 AutoWriteLock alock (that);
5089
5090 if (that->mVMStateChangeCallbackDisabled)
5091 break;
5092
5093 /* Change the machine state from Running to Paused */
5094 Assert (that->mMachineState == MachineState_Running);
5095 that->setMachineState (MachineState_Paused);
5096 }
5097
5098 break;
5099 }
5100
5101 case VMSTATE_RUNNING:
5102 {
5103 if (aOldState == VMSTATE_CREATED ||
5104 aOldState == VMSTATE_SUSPENDED)
5105 {
5106 AutoWriteLock alock (that);
5107
5108 if (that->mVMStateChangeCallbackDisabled)
5109 break;
5110
5111 /*
5112 * Change the machine state from Starting, Restoring or Paused
5113 * to Running
5114 */
5115 Assert ((that->mMachineState == MachineState_Starting &&
5116 aOldState == VMSTATE_CREATED) ||
5117 ((that->mMachineState == MachineState_Restoring ||
5118 that->mMachineState == MachineState_Paused) &&
5119 aOldState == VMSTATE_SUSPENDED));
5120
5121 that->setMachineState (MachineState_Running);
5122 }
5123
5124 break;
5125 }
5126
5127 case VMSTATE_GURU_MEDITATION:
5128 {
5129 AutoWriteLock alock (that);
5130
5131 if (that->mVMStateChangeCallbackDisabled)
5132 break;
5133
5134 /* Guru respects only running VMs */
5135 Assert ((that->mMachineState >= MachineState_Running));
5136
5137 that->setMachineState (MachineState_Stuck);
5138
5139 break;
5140 }
5141
5142 default: /* shut up gcc */
5143 break;
5144 }
5145}
5146
5147#ifdef VBOX_WITH_USB
5148
5149/**
5150 * Sends a request to VMM to attach the given host device.
5151 * After this method succeeds, the attached device will appear in the
5152 * mUSBDevices collection.
5153 *
5154 * @param aHostDevice device to attach
5155 *
5156 * @note Synchronously calls EMT.
5157 * @note Must be called from under this object's lock.
5158 */
5159HRESULT Console::attachUSBDevice (IUSBDevice *aHostDevice, ULONG aMaskedIfs)
5160{
5161 AssertReturn (aHostDevice, E_FAIL);
5162 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5163
5164 /* still want a lock object because we need to leave it */
5165 AutoWriteLock alock (this);
5166
5167 HRESULT hrc;
5168
5169 /*
5170 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
5171 * method in EMT (using usbAttachCallback()).
5172 */
5173 Bstr BstrAddress;
5174 hrc = aHostDevice->COMGETTER (Address) (BstrAddress.asOutParam());
5175 ComAssertComRCRetRC (hrc);
5176
5177 Utf8Str Address (BstrAddress);
5178
5179 Guid Uuid;
5180 hrc = aHostDevice->COMGETTER (Id) (Uuid.asOutParam());
5181 ComAssertComRCRetRC (hrc);
5182
5183 BOOL fRemote = FALSE;
5184 hrc = aHostDevice->COMGETTER (Remote) (&fRemote);
5185 ComAssertComRCRetRC (hrc);
5186
5187 /* protect mpVM */
5188 AutoVMCaller autoVMCaller (this);
5189 CheckComRCReturnRC (autoVMCaller.rc());
5190
5191 LogFlowThisFunc (("Proxying USB device '%s' {%Vuuid}...\n",
5192 Address.raw(), Uuid.ptr()));
5193
5194 /* leave the lock before a VMR3* call (EMT will call us back)! */
5195 alock.leave();
5196
5197/** @todo just do everything here and only wrap the PDMR3Usb call. That'll offload some notification stuff from the EMT thread. */
5198 PVMREQ pReq = NULL;
5199 int vrc = VMR3ReqCall (mpVM, &pReq, RT_INDEFINITE_WAIT,
5200 (PFNRT) usbAttachCallback, 6, this, aHostDevice, Uuid.ptr(), fRemote, Address.raw(), aMaskedIfs);
5201 if (VBOX_SUCCESS (vrc))
5202 vrc = pReq->iStatus;
5203 VMR3ReqFree (pReq);
5204
5205 /* restore the lock */
5206 alock.enter();
5207
5208 /* hrc is S_OK here */
5209
5210 if (VBOX_FAILURE (vrc))
5211 {
5212 LogWarningThisFunc (("Failed to create proxy device for '%s' {%Vuuid} (%Vrc)\n",
5213 Address.raw(), Uuid.ptr(), vrc));
5214
5215 switch (vrc)
5216 {
5217 case VERR_VUSB_NO_PORTS:
5218 hrc = setError (E_FAIL,
5219 tr ("Failed to attach the USB device. (No available ports on the USB controller)."));
5220 break;
5221 case VERR_VUSB_USBFS_PERMISSION:
5222 hrc = setError (E_FAIL,
5223 tr ("Not permitted to open the USB device, check usbfs options"));
5224 break;
5225 default:
5226 hrc = setError (E_FAIL,
5227 tr ("Failed to create a proxy device for the USB device. (Error: %Vrc)"), vrc);
5228 break;
5229 }
5230 }
5231
5232 return hrc;
5233}
5234
5235/**
5236 * USB device attach callback used by AttachUSBDevice().
5237 * Note that AttachUSBDevice() doesn't return until this callback is executed,
5238 * so we don't use AutoCaller and don't care about reference counters of
5239 * interface pointers passed in.
5240 *
5241 * @thread EMT
5242 * @note Locks the console object for writing.
5243 */
5244//static
5245DECLCALLBACK(int)
5246Console::usbAttachCallback (Console *that, IUSBDevice *aHostDevice, PCRTUUID aUuid, bool aRemote, const char *aAddress, ULONG aMaskedIfs)
5247{
5248 LogFlowFuncEnter();
5249 LogFlowFunc (("that={%p}\n", that));
5250
5251 AssertReturn (that && aUuid, VERR_INVALID_PARAMETER);
5252
5253 void *pvRemoteBackend = NULL;
5254 if (aRemote)
5255 {
5256 RemoteUSBDevice *pRemoteUSBDevice = static_cast <RemoteUSBDevice *> (aHostDevice);
5257 Guid guid (*aUuid);
5258
5259 pvRemoteBackend = that->consoleVRDPServer ()->USBBackendRequestPointer (pRemoteUSBDevice->clientId (), &guid);
5260 if (!pvRemoteBackend)
5261 return VERR_INVALID_PARAMETER; /* The clientId is invalid then. */
5262 }
5263
5264 USHORT portVersion = 1;
5265 HRESULT hrc = aHostDevice->COMGETTER(PortVersion)(&portVersion);
5266 AssertComRCReturn(hrc, VERR_GENERAL_FAILURE);
5267 Assert(portVersion == 1 || portVersion == 2);
5268
5269 int vrc = PDMR3USBCreateProxyDevice (that->mpVM, aUuid, aRemote, aAddress, pvRemoteBackend,
5270 portVersion == 1 ? VUSB_STDVER_11 : VUSB_STDVER_20, aMaskedIfs);
5271 if (VBOX_SUCCESS (vrc))
5272 {
5273 /* Create a OUSBDevice and add it to the device list */
5274 ComObjPtr <OUSBDevice> device;
5275 device.createObject();
5276 HRESULT hrc = device->init (aHostDevice);
5277 AssertComRC (hrc);
5278
5279 AutoWriteLock alock (that);
5280 that->mUSBDevices.push_back (device);
5281 LogFlowFunc (("Attached device {%Vuuid}\n", device->id().raw()));
5282
5283 /* notify callbacks */
5284 that->onUSBDeviceStateChange (device, true /* aAttached */, NULL);
5285 }
5286
5287 LogFlowFunc (("vrc=%Vrc\n", vrc));
5288 LogFlowFuncLeave();
5289 return vrc;
5290}
5291
5292/**
5293 * Sends a request to VMM to detach the given host device. After this method
5294 * succeeds, the detached device will disappear from the mUSBDevices
5295 * collection.
5296 *
5297 * @param aIt Iterator pointing to the device to detach.
5298 *
5299 * @note Synchronously calls EMT.
5300 * @note Must be called from under this object's lock.
5301 */
5302HRESULT Console::detachUSBDevice (USBDeviceList::iterator &aIt)
5303{
5304 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5305
5306 /* still want a lock object because we need to leave it */
5307 AutoWriteLock alock (this);
5308
5309 /* protect mpVM */
5310 AutoVMCaller autoVMCaller (this);
5311 CheckComRCReturnRC (autoVMCaller.rc());
5312
5313 /* if the device is attached, then there must at least one USB hub. */
5314 AssertReturn (PDMR3USBHasHub (mpVM), E_FAIL);
5315
5316 LogFlowThisFunc (("Detaching USB proxy device {%Vuuid}...\n",
5317 (*aIt)->id().raw()));
5318
5319 /* leave the lock before a VMR3* call (EMT will call us back)! */
5320 alock.leave();
5321
5322 PVMREQ pReq;
5323/** @todo just do everything here and only wrap the PDMR3Usb call. That'll offload some notification stuff from the EMT thread. */
5324 int vrc = VMR3ReqCall (mpVM, &pReq, RT_INDEFINITE_WAIT,
5325 (PFNRT) usbDetachCallback, 4,
5326 this, &aIt, (*aIt)->id().raw());
5327 if (VBOX_SUCCESS (vrc))
5328 vrc = pReq->iStatus;
5329 VMR3ReqFree (pReq);
5330
5331 ComAssertRCRet (vrc, E_FAIL);
5332
5333 return S_OK;
5334}
5335
5336/**
5337 * USB device detach callback used by DetachUSBDevice().
5338 * Note that DetachUSBDevice() doesn't return until this callback is executed,
5339 * so we don't use AutoCaller and don't care about reference counters of
5340 * interface pointers passed in.
5341 *
5342 * @thread EMT
5343 * @note Locks the console object for writing.
5344 */
5345//static
5346DECLCALLBACK(int)
5347Console::usbDetachCallback (Console *that, USBDeviceList::iterator *aIt, PCRTUUID aUuid)
5348{
5349 LogFlowFuncEnter();
5350 LogFlowFunc (("that={%p}\n", that));
5351
5352 AssertReturn (that && aUuid, VERR_INVALID_PARAMETER);
5353 ComObjPtr <OUSBDevice> device = **aIt;
5354
5355 /*
5356 * If that was a remote device, release the backend pointer.
5357 * The pointer was requested in usbAttachCallback.
5358 */
5359 BOOL fRemote = FALSE;
5360
5361 HRESULT hrc2 = (**aIt)->COMGETTER (Remote) (&fRemote);
5362 ComAssertComRC (hrc2);
5363
5364 if (fRemote)
5365 {
5366 Guid guid (*aUuid);
5367 that->consoleVRDPServer ()->USBBackendReleasePointer (&guid);
5368 }
5369
5370 int vrc = PDMR3USBDetachDevice (that->mpVM, aUuid);
5371
5372 if (VBOX_SUCCESS (vrc))
5373 {
5374 AutoWriteLock alock (that);
5375
5376 /* Remove the device from the collection */
5377 that->mUSBDevices.erase (*aIt);
5378 LogFlowFunc (("Detached device {%Vuuid}\n", device->id().raw()));
5379
5380 /* notify callbacks */
5381 that->onUSBDeviceStateChange (device, false /* aAttached */, NULL);
5382 }
5383
5384 LogFlowFunc (("vrc=%Vrc\n", vrc));
5385 LogFlowFuncLeave();
5386 return vrc;
5387}
5388
5389#endif /* VBOX_WITH_USB */
5390
5391/**
5392 * Call the initialisation script for a dynamic TAP interface.
5393 *
5394 * The initialisation script should create a TAP interface, set it up and write its name to
5395 * standard output followed by a carriage return. Anything further written to standard
5396 * output will be ignored. If it returns a non-zero exit code, or does not write an
5397 * intelligable interface name to standard output, it will be treated as having failed.
5398 * For now, this method only works on Linux.
5399 *
5400 * @returns COM status code
5401 * @param tapDevice string to store the name of the tap device created to
5402 * @param tapSetupApplication the name of the setup script
5403 */
5404HRESULT Console::callTapSetupApplication(bool isStatic, RTFILE tapFD, Bstr &tapDevice,
5405 Bstr &tapSetupApplication)
5406{
5407 LogFlowThisFunc(("\n"));
5408#ifdef RT_OS_LINUX
5409 /* Command line to start the script with. */
5410 char szCommand[4096];
5411 /* Result code */
5412 int rc;
5413
5414 /* Get the script name. */
5415 Utf8Str tapSetupAppUtf8(tapSetupApplication), tapDeviceUtf8(tapDevice);
5416 RTStrPrintf(szCommand, sizeof(szCommand), "%s %d %s", tapSetupAppUtf8.raw(),
5417 isStatic ? tapFD : 0, isStatic ? tapDeviceUtf8.raw() : "");
5418 /*
5419 * Create the process and read its output.
5420 */
5421 Log2(("About to start the TAP setup script with the following command line: %s\n",
5422 szCommand));
5423 FILE *pfScriptHandle = popen(szCommand, "r");
5424 if (pfScriptHandle == 0)
5425 {
5426 int iErr = errno;
5427 LogRel(("Failed to start the TAP interface setup script %s, error text: %s\n",
5428 szCommand, strerror(iErr)));
5429 LogFlowThisFunc(("rc=E_FAIL\n"));
5430 return setError(E_FAIL, tr ("Failed to run the host networking set up command %s: %s"),
5431 szCommand, strerror(iErr));
5432 }
5433 /* If we are using a dynamic TAP interface, we need to get the interface name. */
5434 if (!isStatic)
5435 {
5436 /* Buffer to read the application output to. It doesn't have to be long, as we are only
5437 interested in the first few (normally 5 or 6) bytes. */
5438 char acBuffer[64];
5439 /* The length of the string returned by the application. We only accept strings of 63
5440 characters or less. */
5441 size_t cBufSize;
5442
5443 /* Read the name of the device from the application. */
5444 fgets(acBuffer, sizeof(acBuffer), pfScriptHandle);
5445 cBufSize = strlen(acBuffer);
5446 /* The script must return the name of the interface followed by a carriage return as the
5447 first line of its output. We need a null-terminated string. */
5448 if ((cBufSize < 2) || (acBuffer[cBufSize - 1] != '\n'))
5449 {
5450 pclose(pfScriptHandle);
5451 LogRel(("The TAP interface setup script did not return the name of a TAP device.\n"));
5452 LogFlowThisFunc(("rc=E_FAIL\n"));
5453 return setError(E_FAIL, tr ("The host networking set up command did not supply an interface name"));
5454 }
5455 /* Overwrite the terminating newline character. */
5456 acBuffer[cBufSize - 1] = 0;
5457 tapDevice = acBuffer;
5458 }
5459 rc = pclose(pfScriptHandle);
5460 if (!WIFEXITED(rc))
5461 {
5462 LogRel(("The TAP interface setup script terminated abnormally.\n"));
5463 LogFlowThisFunc(("rc=E_FAIL\n"));
5464 return setError(E_FAIL, tr ("The host networking set up command did not run correctly"));
5465 }
5466 if (WEXITSTATUS(rc) != 0)
5467 {
5468 LogRel(("The TAP interface setup script returned a non-zero exit code.\n"));
5469 LogFlowThisFunc(("rc=E_FAIL\n"));
5470 return setError(E_FAIL, tr ("The host networking set up command returned a non-zero exit code"));
5471 }
5472 LogFlowThisFunc(("rc=S_OK\n"));
5473 return S_OK;
5474#else /* RT_OS_LINUX not defined */
5475 LogFlowThisFunc(("rc=E_NOTIMPL\n"));
5476 return E_NOTIMPL; /* not yet supported */
5477#endif
5478}
5479
5480/**
5481 * Helper function to handle host interface device creation and attachment.
5482 *
5483 * @param networkAdapter the network adapter which attachment should be reset
5484 * @return COM status code
5485 *
5486 * @note The caller must lock this object for writing.
5487 */
5488HRESULT Console::attachToHostInterface(INetworkAdapter *networkAdapter)
5489{
5490#if !defined(RT_OS_LINUX)
5491 /*
5492 * Nothing to do here.
5493 *
5494 * Note, the reason for this method in the first place a memory / fork
5495 * bug on linux. All this code belongs in DrvTAP and similar places.
5496 */
5497 NOREF(networkAdapter);
5498 return S_OK;
5499
5500#else /* RT_OS_LINUX */
5501 LogFlowThisFunc(("\n"));
5502 /* sanity check */
5503 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5504
5505# ifdef VBOX_STRICT
5506 /* paranoia */
5507 NetworkAttachmentType_T attachment;
5508 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5509 Assert(attachment == NetworkAttachmentType_HostInterface);
5510# endif /* VBOX_STRICT */
5511
5512 HRESULT rc = S_OK;
5513
5514 ULONG slot = 0;
5515 rc = networkAdapter->COMGETTER(Slot)(&slot);
5516 AssertComRC(rc);
5517
5518 /*
5519 * Try get the FD.
5520 */
5521 LONG ltapFD;
5522 rc = networkAdapter->COMGETTER(TAPFileDescriptor)(&ltapFD);
5523 if (SUCCEEDED(rc))
5524 maTapFD[slot] = (RTFILE)ltapFD;
5525 else
5526 maTapFD[slot] = NIL_RTFILE;
5527
5528 /*
5529 * Are we supposed to use an existing TAP interface?
5530 */
5531 if (maTapFD[slot] != NIL_RTFILE)
5532 {
5533 /* nothing to do */
5534 Assert(ltapFD >= 0);
5535 Assert((LONG)maTapFD[slot] == ltapFD);
5536 rc = S_OK;
5537 }
5538 else
5539 {
5540 /*
5541 * Allocate a host interface device
5542 */
5543 int rcVBox = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
5544 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
5545 if (VBOX_SUCCESS(rcVBox))
5546 {
5547 /*
5548 * Set/obtain the tap interface.
5549 */
5550 bool isStatic = false;
5551 struct ifreq IfReq;
5552 memset(&IfReq, 0, sizeof(IfReq));
5553 /* The name of the TAP interface we are using and the TAP setup script resp. */
5554 Bstr tapDeviceName, tapSetupApplication;
5555 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
5556 if (FAILED(rc))
5557 {
5558 tapDeviceName.setNull(); /* Is this necessary? */
5559 }
5560 else if (!tapDeviceName.isEmpty())
5561 {
5562 isStatic = true;
5563 /* If we are using a static TAP device then try to open it. */
5564 Utf8Str str(tapDeviceName);
5565 if (str.length() <= sizeof(IfReq.ifr_name))
5566 strcpy(IfReq.ifr_name, str.raw());
5567 else
5568 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
5569 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
5570 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
5571 if (rcVBox != 0)
5572 {
5573 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
5574 rc = setError(E_FAIL, tr ("Failed to open the host network interface %ls"),
5575 tapDeviceName.raw());
5576 }
5577 }
5578 if (SUCCEEDED(rc))
5579 {
5580 networkAdapter->COMGETTER(TAPSetupApplication)(tapSetupApplication.asOutParam());
5581 if (tapSetupApplication.isEmpty())
5582 {
5583 if (tapDeviceName.isEmpty())
5584 {
5585 LogRel(("No setup application was supplied for the TAP interface.\n"));
5586 rc = setError(E_FAIL, tr ("No setup application was supplied for the host networking interface"));
5587 }
5588 }
5589 else
5590 {
5591 rc = callTapSetupApplication(isStatic, maTapFD[slot], tapDeviceName,
5592 tapSetupApplication);
5593 }
5594 }
5595 if (SUCCEEDED(rc))
5596 {
5597 if (!isStatic)
5598 {
5599 Utf8Str str(tapDeviceName);
5600 if (str.length() <= sizeof(IfReq.ifr_name))
5601 strcpy(IfReq.ifr_name, str.raw());
5602 else
5603 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
5604 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
5605 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
5606 if (rcVBox != 0)
5607 {
5608 LogRel(("Failed to open the host network interface %ls returned by the setup script", tapDeviceName.raw()));
5609 rc = setError(E_FAIL, tr ("Failed to open the host network interface %ls returned by the setup script"), tapDeviceName.raw());
5610 }
5611 }
5612 if (SUCCEEDED(rc))
5613 {
5614 /*
5615 * Make it pollable.
5616 */
5617 if (fcntl(maTapFD[slot], F_SETFL, O_NONBLOCK) != -1)
5618 {
5619 Log(("attachToHostInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
5620
5621 /*
5622 * Here is the right place to communicate the TAP file descriptor and
5623 * the host interface name to the server if/when it becomes really
5624 * necessary.
5625 */
5626 maTAPDeviceName[slot] = tapDeviceName;
5627 rcVBox = VINF_SUCCESS;
5628 }
5629 else
5630 {
5631 int iErr = errno;
5632
5633 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
5634 rcVBox = VERR_HOSTIF_BLOCKING;
5635 rc = setError(E_FAIL, tr ("could not set up the host networking device for non blocking access: %s"),
5636 strerror(errno));
5637 }
5638 }
5639 }
5640 }
5641 else
5642 {
5643 LogRel(("Configuration error: Failed to open /dev/net/tun rc=%Vrc\n", rcVBox));
5644 switch (rcVBox)
5645 {
5646 case VERR_ACCESS_DENIED:
5647 /* will be handled by our caller */
5648 rc = rcVBox;
5649 break;
5650 default:
5651 rc = setError(E_FAIL, tr ("Could not set up the host networking device: %Vrc"), rcVBox);
5652 break;
5653 }
5654 }
5655 /* in case of failure, cleanup. */
5656 if (VBOX_FAILURE(rcVBox) && SUCCEEDED(rc))
5657 {
5658 LogRel(("General failure attaching to host interface\n"));
5659 rc = setError(E_FAIL, tr ("General failure attaching to host interface"));
5660 }
5661 }
5662 LogFlowThisFunc(("rc=%d\n", rc));
5663 return rc;
5664#endif /* RT_OS_LINUX */
5665}
5666
5667/**
5668 * Helper function to handle detachment from a host interface
5669 *
5670 * @param networkAdapter the network adapter which attachment should be reset
5671 * @return COM status code
5672 *
5673 * @note The caller must lock this object for writing.
5674 */
5675HRESULT Console::detachFromHostInterface(INetworkAdapter *networkAdapter)
5676{
5677#if !defined(RT_OS_LINUX) && !defined(RT_OS_SOLARIS)
5678 /*
5679 * Nothing to do here.
5680 */
5681 NOREF(networkAdapter);
5682 return S_OK;
5683
5684#else /* RT_LINUX || RT_OS_SOLARIS */
5685
5686 /* sanity check */
5687 LogFlowThisFunc(("\n"));
5688 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5689
5690 HRESULT rc = S_OK;
5691# ifdef VBOX_STRICT
5692 /* paranoia */
5693 NetworkAttachmentType_T attachment;
5694 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5695 Assert(attachment == NetworkAttachmentType_HostInterface);
5696# endif /* VBOX_STRICT */
5697
5698/** @todo # ifdef VBOX_WITH_UNIXY_TAP_NETWORKING: why wasn't this !defined(RT_OS_SOLARIS)? */
5699
5700 ULONG slot = 0;
5701 rc = networkAdapter->COMGETTER(Slot)(&slot);
5702 AssertComRC(rc);
5703
5704 /* is there an open TAP device? */
5705 if (maTapFD[slot] != NIL_RTFILE)
5706 {
5707 /*
5708 * Close the file handle.
5709 */
5710 Bstr tapDeviceName, tapTerminateApplication;
5711 bool isStatic = true;
5712 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
5713 if (FAILED(rc) || tapDeviceName.isEmpty())
5714 {
5715 /* If the name is empty, this is a dynamic TAP device, so close it now,
5716 so that the termination script can remove the interface. Otherwise we still
5717 need the FD to pass to the termination script. */
5718 isStatic = false;
5719 int rcVBox = RTFileClose(maTapFD[slot]);
5720 AssertRC(rcVBox);
5721 maTapFD[slot] = NIL_RTFILE;
5722 }
5723 /*
5724 * Execute the termination command.
5725 */
5726 networkAdapter->COMGETTER(TAPTerminateApplication)(tapTerminateApplication.asOutParam());
5727 if (tapTerminateApplication)
5728 {
5729 /* Get the program name. */
5730 Utf8Str tapTermAppUtf8(tapTerminateApplication);
5731
5732 /* Build the command line. */
5733 char szCommand[4096];
5734 RTStrPrintf(szCommand, sizeof(szCommand), "%s %d %s", tapTermAppUtf8.raw(),
5735 isStatic ? maTapFD[slot] : 0, maTAPDeviceName[slot].raw());
5736 /** @todo check for overflow or use RTStrAPrintf! */
5737
5738 /*
5739 * Create the process and wait for it to complete.
5740 */
5741 Log(("Calling the termination command: %s\n", szCommand));
5742 int rcCommand = system(szCommand);
5743 if (rcCommand == -1)
5744 {
5745 LogRel(("Failed to execute the clean up script for the TAP interface"));
5746 rc = setError(E_FAIL, tr ("Failed to execute the clean up script for the TAP interface"));
5747 }
5748 if (!WIFEXITED(rc))
5749 {
5750 LogRel(("The TAP interface clean up script terminated abnormally.\n"));
5751 rc = setError(E_FAIL, tr ("The TAP interface clean up script terminated abnormally"));
5752 }
5753 if (WEXITSTATUS(rc) != 0)
5754 {
5755 LogRel(("The TAP interface clean up script returned a non-zero exit code.\n"));
5756 rc = setError(E_FAIL, tr ("The TAP interface clean up script returned a non-zero exit code"));
5757 }
5758 }
5759
5760 if (isStatic)
5761 {
5762 /* If we are using a static TAP device, we close it now, after having called the
5763 termination script. */
5764 int rcVBox = RTFileClose(maTapFD[slot]);
5765 AssertRC(rcVBox);
5766 }
5767 /* the TAP device name and handle are no longer valid */
5768 maTapFD[slot] = NIL_RTFILE;
5769 maTAPDeviceName[slot] = "";
5770 }
5771 LogFlowThisFunc(("returning %d\n", rc));
5772 return rc;
5773#endif /* RT_OS_LINUX || RT_OS_SOLARIS */
5774}
5775
5776
5777/**
5778 * Called at power down to terminate host interface networking.
5779 *
5780 * @note The caller must lock this object for writing.
5781 */
5782HRESULT Console::powerDownHostInterfaces()
5783{
5784 LogFlowThisFunc (("\n"));
5785
5786 /* sanity check */
5787 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5788
5789 /*
5790 * host interface termination handling
5791 */
5792 HRESULT rc;
5793 for (ULONG slot = 0; slot < SchemaDefs::NetworkAdapterCount; slot ++)
5794 {
5795 ComPtr<INetworkAdapter> networkAdapter;
5796 rc = mMachine->GetNetworkAdapter(slot, networkAdapter.asOutParam());
5797 CheckComRCBreakRC (rc);
5798
5799 BOOL enabled = FALSE;
5800 networkAdapter->COMGETTER(Enabled) (&enabled);
5801 if (!enabled)
5802 continue;
5803
5804 NetworkAttachmentType_T attachment;
5805 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5806 if (attachment == NetworkAttachmentType_HostInterface)
5807 {
5808 HRESULT rc2 = detachFromHostInterface(networkAdapter);
5809 if (FAILED(rc2) && SUCCEEDED(rc))
5810 rc = rc2;
5811 }
5812 }
5813
5814 return rc;
5815}
5816
5817
5818/**
5819 * Process callback handler for VMR3Load and VMR3Save.
5820 *
5821 * @param pVM The VM handle.
5822 * @param uPercent Completetion precentage (0-100).
5823 * @param pvUser Pointer to the VMProgressTask structure.
5824 * @return VINF_SUCCESS.
5825 */
5826/*static*/ DECLCALLBACK (int)
5827Console::stateProgressCallback (PVM pVM, unsigned uPercent, void *pvUser)
5828{
5829 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
5830 AssertReturn (task, VERR_INVALID_PARAMETER);
5831
5832 /* update the progress object */
5833 if (task->mProgress)
5834 task->mProgress->notifyProgress (uPercent);
5835
5836 return VINF_SUCCESS;
5837}
5838
5839/**
5840 * VM error callback function. Called by the various VM components.
5841 *
5842 * @param pVM VM handle. Can be NULL if an error occurred before
5843 * successfully creating a VM.
5844 * @param pvUser Pointer to the VMProgressTask structure.
5845 * @param rc VBox status code.
5846 * @param pszFormat Printf-like error message.
5847 * @param args Various number of argumens for the error message.
5848 *
5849 * @thread EMT, VMPowerUp...
5850 *
5851 * @note The VMProgressTask structure modified by this callback is not thread
5852 * safe.
5853 */
5854/* static */ DECLCALLBACK (void)
5855Console::setVMErrorCallback (PVM pVM, void *pvUser, int rc, RT_SRC_POS_DECL,
5856 const char *pszFormat, va_list args)
5857{
5858 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
5859 AssertReturnVoid (task);
5860
5861 /* we ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users */
5862 va_list va2;
5863 va_copy(va2, args); /* Have to make a copy here or GCC will break. */
5864 Utf8Str errorMsg = Utf8StrFmt (tr ("%N.\n"
5865 "VBox status code: %d (%Vrc)"),
5866 pszFormat, &va2, rc, rc);
5867 va_end(va2);
5868
5869 /* For now, this may be called only once. Ignore subsequent calls. */
5870 if (!task->mErrorMsg.isNull())
5871 {
5872#if !defined(DEBUG_bird)
5873 AssertMsgFailed (("Cannot set error to '%s': it is already set to '%s'",
5874 errorMsg.raw(), task->mErrorMsg.raw()));
5875#endif
5876 return;
5877 }
5878
5879 task->mErrorMsg = errorMsg;
5880}
5881
5882/**
5883 * VM runtime error callback function.
5884 * See VMSetRuntimeError for the detailed description of parameters.
5885 *
5886 * @param pVM The VM handle.
5887 * @param pvUser The user argument.
5888 * @param fFatal Whether it is a fatal error or not.
5889 * @param pszErrorID Error ID string.
5890 * @param pszFormat Error message format string.
5891 * @param args Error message arguments.
5892 * @thread EMT.
5893 */
5894/* static */ DECLCALLBACK(void)
5895Console::setVMRuntimeErrorCallback (PVM pVM, void *pvUser, bool fFatal,
5896 const char *pszErrorID,
5897 const char *pszFormat, va_list args)
5898{
5899 LogFlowFuncEnter();
5900
5901 Console *that = static_cast <Console *> (pvUser);
5902 AssertReturnVoid (that);
5903
5904 Utf8Str message = Utf8StrFmtVA (pszFormat, args);
5905
5906 LogRel (("Console: VM runtime error: fatal=%RTbool, "
5907 "errorID=%s message=\"%s\"\n",
5908 fFatal, pszErrorID, message.raw()));
5909
5910 that->onRuntimeError (BOOL (fFatal), Bstr (pszErrorID), Bstr (message));
5911
5912 LogFlowFuncLeave();
5913}
5914
5915/**
5916 * Captures USB devices that match filters of the VM.
5917 * Called at VM startup.
5918 *
5919 * @param pVM The VM handle.
5920 *
5921 * @note The caller must lock this object for writing.
5922 */
5923HRESULT Console::captureUSBDevices (PVM pVM)
5924{
5925 LogFlowThisFunc (("\n"));
5926
5927 /* sanity check */
5928 ComAssertRet (isWriteLockOnCurrentThread(), E_FAIL);
5929
5930 /* If the machine has an USB controller, ask the USB proxy service to
5931 * capture devices */
5932 PPDMIBASE pBase;
5933 int vrc = PDMR3QueryLun (pVM, "usb-ohci", 0, 0, &pBase);
5934 if (VBOX_SUCCESS (vrc))
5935 {
5936 /* leave the lock before calling Host in VBoxSVC since Host may call
5937 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
5938 * produce an inter-process dead-lock otherwise. */
5939 AutoWriteLock alock (this);
5940 alock.leave();
5941
5942 HRESULT hrc = mControl->AutoCaptureUSBDevices();
5943 ComAssertComRCRetRC (hrc);
5944 }
5945 else if ( vrc == VERR_PDM_DEVICE_NOT_FOUND
5946 || vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND)
5947 vrc = VINF_SUCCESS;
5948 else
5949 AssertRC (vrc);
5950
5951 return VBOX_SUCCESS (vrc) ? S_OK : E_FAIL;
5952}
5953
5954
5955/**
5956 * Detach all USB device which are attached to the VM for the
5957 * purpose of clean up and such like.
5958 *
5959 * @note The caller must lock this object for writing.
5960 */
5961void Console::detachAllUSBDevices (bool aDone)
5962{
5963 LogFlowThisFunc (("aDone=%RTbool\n", aDone));
5964
5965 /* sanity check */
5966 AssertReturnVoid (isWriteLockOnCurrentThread());
5967
5968 mUSBDevices.clear();
5969
5970 /* leave the lock before calling Host in VBoxSVC since Host may call
5971 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
5972 * produce an inter-process dead-lock otherwise. */
5973 AutoWriteLock alock (this);
5974 alock.leave();
5975
5976 mControl->DetachAllUSBDevices (aDone);
5977}
5978
5979/**
5980 * @note Locks this object for writing.
5981 */
5982void Console::processRemoteUSBDevices (uint32_t u32ClientId, VRDPUSBDEVICEDESC *pDevList, uint32_t cbDevList)
5983{
5984 LogFlowThisFuncEnter();
5985 LogFlowThisFunc (("u32ClientId = %d, pDevList=%p, cbDevList = %d\n", u32ClientId, pDevList, cbDevList));
5986
5987 AutoCaller autoCaller (this);
5988 if (!autoCaller.isOk())
5989 {
5990 /* Console has been already uninitialized, deny request */
5991 AssertMsgFailed (("Temporary assertion to prove that it happens, "
5992 "please report to dmik\n"));
5993 LogFlowThisFunc (("Console is already uninitialized\n"));
5994 LogFlowThisFuncLeave();
5995 return;
5996 }
5997
5998 AutoWriteLock alock (this);
5999
6000 /*
6001 * Mark all existing remote USB devices as dirty.
6002 */
6003 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
6004 while (it != mRemoteUSBDevices.end())
6005 {
6006 (*it)->dirty (true);
6007 ++ it;
6008 }
6009
6010 /*
6011 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
6012 */
6013 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
6014 VRDPUSBDEVICEDESC *e = pDevList;
6015
6016 /* The cbDevList condition must be checked first, because the function can
6017 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
6018 */
6019 while (cbDevList >= 2 && e->oNext)
6020 {
6021 LogFlowThisFunc (("vendor %04X, product %04X, name = %s\n",
6022 e->idVendor, e->idProduct,
6023 e->oProduct? (char *)e + e->oProduct: ""));
6024
6025 bool fNewDevice = true;
6026
6027 it = mRemoteUSBDevices.begin();
6028 while (it != mRemoteUSBDevices.end())
6029 {
6030 if ((*it)->devId () == e->id
6031 && (*it)->clientId () == u32ClientId)
6032 {
6033 /* The device is already in the list. */
6034 (*it)->dirty (false);
6035 fNewDevice = false;
6036 break;
6037 }
6038
6039 ++ it;
6040 }
6041
6042 if (fNewDevice)
6043 {
6044 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
6045 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""
6046 ));
6047
6048 /* Create the device object and add the new device to list. */
6049 ComObjPtr <RemoteUSBDevice> device;
6050 device.createObject();
6051 device->init (u32ClientId, e);
6052
6053 mRemoteUSBDevices.push_back (device);
6054
6055 /* Check if the device is ok for current USB filters. */
6056 BOOL fMatched = FALSE;
6057 ULONG fMaskedIfs = 0;
6058
6059 HRESULT hrc = mControl->RunUSBDeviceFilters(device, &fMatched, &fMaskedIfs);
6060
6061 AssertComRC (hrc);
6062
6063 LogFlowThisFunc (("USB filters return %d %#x\n", fMatched, fMaskedIfs));
6064
6065 if (fMatched)
6066 {
6067 hrc = onUSBDeviceAttach (device, NULL, fMaskedIfs);
6068
6069 /// @todo (r=dmik) warning reporting subsystem
6070
6071 if (hrc == S_OK)
6072 {
6073 LogFlowThisFunc (("Device attached\n"));
6074 device->captured (true);
6075 }
6076 }
6077 }
6078
6079 if (cbDevList < e->oNext)
6080 {
6081 LogWarningThisFunc (("cbDevList %d > oNext %d\n",
6082 cbDevList, e->oNext));
6083 break;
6084 }
6085
6086 cbDevList -= e->oNext;
6087
6088 e = (VRDPUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
6089 }
6090
6091 /*
6092 * Remove dirty devices, that is those which are not reported by the server anymore.
6093 */
6094 for (;;)
6095 {
6096 ComObjPtr <RemoteUSBDevice> device;
6097
6098 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
6099 while (it != mRemoteUSBDevices.end())
6100 {
6101 if ((*it)->dirty ())
6102 {
6103 device = *it;
6104 break;
6105 }
6106
6107 ++ it;
6108 }
6109
6110 if (!device)
6111 {
6112 break;
6113 }
6114
6115 USHORT vendorId = 0;
6116 device->COMGETTER(VendorId) (&vendorId);
6117
6118 USHORT productId = 0;
6119 device->COMGETTER(ProductId) (&productId);
6120
6121 Bstr product;
6122 device->COMGETTER(Product) (product.asOutParam());
6123
6124 LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
6125 vendorId, productId, product.raw ()
6126 ));
6127
6128 /* Detach the device from VM. */
6129 if (device->captured ())
6130 {
6131 Guid uuid;
6132 device->COMGETTER (Id) (uuid.asOutParam());
6133 onUSBDeviceDetach (uuid, NULL);
6134 }
6135
6136 /* And remove it from the list. */
6137 mRemoteUSBDevices.erase (it);
6138 }
6139
6140 LogFlowThisFuncLeave();
6141}
6142
6143
6144
6145/**
6146 * Thread function which starts the VM (also from saved state) and
6147 * track progress.
6148 *
6149 * @param Thread The thread id.
6150 * @param pvUser Pointer to a VMPowerUpTask structure.
6151 * @return VINF_SUCCESS (ignored).
6152 *
6153 * @note Locks the Console object for writing.
6154 */
6155/*static*/
6156DECLCALLBACK (int) Console::powerUpThread (RTTHREAD Thread, void *pvUser)
6157{
6158 LogFlowFuncEnter();
6159
6160 std::auto_ptr <VMPowerUpTask> task (static_cast <VMPowerUpTask *> (pvUser));
6161 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
6162
6163 AssertReturn (!task->mConsole.isNull(), VERR_INVALID_PARAMETER);
6164 AssertReturn (!task->mProgress.isNull(), VERR_INVALID_PARAMETER);
6165
6166#if defined(RT_OS_WINDOWS)
6167 {
6168 /* initialize COM */
6169 HRESULT hrc = CoInitializeEx (NULL,
6170 COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE |
6171 COINIT_SPEED_OVER_MEMORY);
6172 LogFlowFunc (("CoInitializeEx()=%08X\n", hrc));
6173 }
6174#endif
6175
6176 HRESULT hrc = S_OK;
6177 int vrc = VINF_SUCCESS;
6178
6179 /* Set up a build identifier so that it can be seen from core dumps what
6180 * exact build was used to produce the core. */
6181 static char saBuildID[40];
6182 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%d %s%s%s%s",
6183 "BU", "IL", "DI", "D", VBOX_VERSION_STRING, VBoxSVNRev (), "BU", "IL", "DI", "D");
6184
6185 ComObjPtr <Console> console = task->mConsole;
6186
6187 /* Note: no need to use addCaller() because VMPowerUpTask does that */
6188
6189 AutoWriteLock alock (console);
6190
6191 /* sanity */
6192 Assert (console->mpVM == NULL);
6193
6194 do
6195 {
6196#ifdef VBOX_VRDP
6197 /* Create the VRDP server. In case of headless operation, this will
6198 * also create the framebuffer, required at VM creation.
6199 */
6200 ConsoleVRDPServer *server = console->consoleVRDPServer();
6201 Assert (server);
6202 /// @todo (dmik)
6203 // does VRDP server call Console from the other thread?
6204 // Not sure, so leave the lock just in case
6205 alock.leave();
6206 vrc = server->Launch();
6207 alock.enter();
6208 if (VBOX_FAILURE (vrc))
6209 {
6210 Utf8Str errMsg;
6211 switch (vrc)
6212 {
6213 case VERR_NET_ADDRESS_IN_USE:
6214 {
6215 ULONG port = 0;
6216 console->mVRDPServer->COMGETTER(Port) (&port);
6217 errMsg = Utf8StrFmt (tr ("VRDP server port %d is already in use"),
6218 port);
6219 break;
6220 }
6221 case VERR_FILE_NOT_FOUND:
6222 {
6223 errMsg = Utf8StrFmt (tr ("Could not load the VRDP library"));
6224 break;
6225 }
6226 default:
6227 errMsg = Utf8StrFmt (tr ("Failed to launch VRDP server (%Vrc)"),
6228 vrc);
6229 }
6230 LogRel (("Failed to launch VRDP server (%Vrc), error message: '%s'\n",
6231 vrc, errMsg.raw()));
6232 hrc = setError (E_FAIL, errMsg);
6233 break;
6234 }
6235#endif /* VBOX_VRDP */
6236
6237 /*
6238 * Create the VM
6239 */
6240 PVM pVM;
6241 /*
6242 * leave the lock since EMT will call Console. It's safe because
6243 * mMachineState is either Starting or Restoring state here.
6244 */
6245 alock.leave();
6246
6247 vrc = VMR3Create (task->mSetVMErrorCallback, task.get(),
6248 task->mConfigConstructor, static_cast <Console *> (console),
6249 &pVM);
6250
6251 alock.enter();
6252
6253#ifdef VBOX_VRDP
6254 /* Enable client connections to the server. */
6255 console->consoleVRDPServer()->EnableConnections ();
6256#endif /* VBOX_VRDP */
6257
6258 if (VBOX_SUCCESS (vrc))
6259 {
6260 do
6261 {
6262 /*
6263 * Register our load/save state file handlers
6264 */
6265 vrc = SSMR3RegisterExternal (pVM,
6266 sSSMConsoleUnit, 0 /* iInstance */, sSSMConsoleVer,
6267 0 /* cbGuess */,
6268 NULL, saveStateFileExec, NULL, NULL, loadStateFileExec, NULL,
6269 static_cast <Console *> (console));
6270 AssertRC (vrc);
6271 if (VBOX_FAILURE (vrc))
6272 break;
6273
6274 /*
6275 * Synchronize debugger settings
6276 */
6277 MachineDebugger *machineDebugger = console->getMachineDebugger();
6278 if (machineDebugger)
6279 {
6280 machineDebugger->flushQueuedSettings();
6281 }
6282
6283 /*
6284 * Shared Folders
6285 */
6286 if (console->getVMMDev()->isShFlActive())
6287 {
6288 /// @todo (dmik)
6289 // does the code below call Console from the other thread?
6290 // Not sure, so leave the lock just in case
6291 alock.leave();
6292
6293 for (SharedFolderDataMap::const_iterator
6294 it = task->mSharedFolders.begin();
6295 it != task->mSharedFolders.end();
6296 ++ it)
6297 {
6298 hrc = console->createSharedFolder ((*it).first, (*it).second);
6299 CheckComRCBreakRC (hrc);
6300 }
6301
6302 /* enter the lock again */
6303 alock.enter();
6304
6305 CheckComRCBreakRC (hrc);
6306 }
6307
6308 /*
6309 * Capture USB devices.
6310 */
6311 hrc = console->captureUSBDevices (pVM);
6312 CheckComRCBreakRC (hrc);
6313
6314 /* leave the lock before a lengthy operation */
6315 alock.leave();
6316
6317 /* Load saved state? */
6318 if (!!task->mSavedStateFile)
6319 {
6320 LogFlowFunc (("Restoring saved state from '%s'...\n",
6321 task->mSavedStateFile.raw()));
6322
6323 vrc = VMR3Load (pVM, task->mSavedStateFile,
6324 Console::stateProgressCallback,
6325 static_cast <VMProgressTask *> (task.get()));
6326
6327 /* Start/Resume the VM execution */
6328 if (VBOX_SUCCESS (vrc))
6329 {
6330 vrc = VMR3Resume (pVM);
6331 AssertRC (vrc);
6332 }
6333
6334 /* Power off in case we failed loading or resuming the VM */
6335 if (VBOX_FAILURE (vrc))
6336 {
6337 int vrc2 = VMR3PowerOff (pVM);
6338 AssertRC (vrc2);
6339 }
6340 }
6341 else
6342 {
6343 /* Power on the VM (i.e. start executing) */
6344 vrc = VMR3PowerOn(pVM);
6345 AssertRC (vrc);
6346 }
6347
6348 /* enter the lock again */
6349 alock.enter();
6350 }
6351 while (0);
6352
6353 /* On failure, destroy the VM */
6354 if (FAILED (hrc) || VBOX_FAILURE (vrc))
6355 {
6356 /* preserve existing error info */
6357 ErrorInfoKeeper eik;
6358
6359 /* powerDown() will call VMR3Destroy() and do all necessary
6360 * cleanup (VRDP, USB devices) */
6361 HRESULT hrc2 = console->powerDown();
6362 AssertComRC (hrc2);
6363 }
6364 }
6365 else
6366 {
6367 /*
6368 * If VMR3Create() failed it has released the VM memory.
6369 */
6370 console->mpVM = NULL;
6371 }
6372
6373 if (SUCCEEDED (hrc) && VBOX_FAILURE (vrc))
6374 {
6375 /* If VMR3Create() or one of the other calls in this function fail,
6376 * an appropriate error message has been set in task->mErrorMsg.
6377 * However since that happens via a callback, the hrc status code in
6378 * this function is not updated.
6379 */
6380 if (task->mErrorMsg.isNull())
6381 {
6382 /* If the error message is not set but we've got a failure,
6383 * convert the VBox status code into a meaningfulerror message.
6384 * This becomes unused once all the sources of errors set the
6385 * appropriate error message themselves.
6386 */
6387 AssertMsgFailed (("Missing error message during powerup for "
6388 "status code %Vrc\n", vrc));
6389 task->mErrorMsg = Utf8StrFmt (
6390 tr ("Failed to start VM execution (%Vrc)"), vrc);
6391 }
6392
6393 /* Set the error message as the COM error.
6394 * Progress::notifyComplete() will pick it up later. */
6395 hrc = setError (E_FAIL, task->mErrorMsg);
6396 break;
6397 }
6398 }
6399 while (0);
6400
6401 if (console->mMachineState == MachineState_Starting ||
6402 console->mMachineState == MachineState_Restoring)
6403 {
6404 /* We are still in the Starting/Restoring state. This means one of:
6405 *
6406 * 1) we failed before VMR3Create() was called;
6407 * 2) VMR3Create() failed.
6408 *
6409 * In both cases, there is no need to call powerDown(), but we still
6410 * need to go back to the PoweredOff/Saved state. Reuse
6411 * vmstateChangeCallback() for that purpose.
6412 */
6413
6414 /* preserve existing error info */
6415 ErrorInfoKeeper eik;
6416
6417 Assert (console->mpVM == NULL);
6418 vmstateChangeCallback (NULL, VMSTATE_TERMINATED, VMSTATE_CREATING,
6419 console);
6420 }
6421
6422 /*
6423 * Evaluate the final result. Note that the appropriate mMachineState value
6424 * is already set by vmstateChangeCallback() in all cases.
6425 */
6426
6427 /* leave the lock, don't need it any more */
6428 alock.leave();
6429
6430 if (SUCCEEDED (hrc))
6431 {
6432 /* Notify the progress object of the success */
6433 task->mProgress->notifyComplete (S_OK);
6434 }
6435 else
6436 {
6437 /* The progress object will fetch the current error info */
6438 task->mProgress->notifyComplete (hrc);
6439
6440 LogRel (("Power up failed (vrc=%Vrc, hrc=%Rhrc (%#08X))\n", vrc, hrc, hrc));
6441 }
6442
6443#if defined(RT_OS_WINDOWS)
6444 /* uninitialize COM */
6445 CoUninitialize();
6446#endif
6447
6448 LogFlowFuncLeave();
6449
6450 return VINF_SUCCESS;
6451}
6452
6453
6454/**
6455 * Reconfigures a VDI.
6456 *
6457 * @param pVM The VM handle.
6458 * @param hda The harddisk attachment.
6459 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
6460 * @return VBox status code.
6461 */
6462static DECLCALLBACK(int) reconfigureVDI(PVM pVM, IHardDiskAttachment *hda, HRESULT *phrc)
6463{
6464 LogFlowFunc (("pVM=%p hda=%p phrc=%p\n", pVM, hda, phrc));
6465
6466 int rc;
6467 HRESULT hrc;
6468 char *psz = NULL;
6469 BSTR str = NULL;
6470 *phrc = S_OK;
6471#define STR_CONV() do { rc = RTUtf16ToUtf8(str, &psz); RC_CHECK(); } while (0)
6472#define STR_FREE() do { if (str) { SysFreeString(str); str = NULL; } if (psz) { RTStrFree(psz); psz = NULL; } } while (0)
6473#define RC_CHECK() do { if (VBOX_FAILURE(rc)) { AssertMsgFailed(("rc=%Vrc\n", rc)); STR_FREE(); return rc; } } while (0)
6474#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%Rhrc (%#x)\n", hrc, hrc)); STR_FREE(); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
6475
6476 /*
6477 * Figure out which IDE device this is.
6478 */
6479 ComPtr<IHardDisk> hardDisk;
6480 hrc = hda->COMGETTER(HardDisk)(hardDisk.asOutParam()); H();
6481 StorageBus_T enmBus;
6482 hrc = hda->COMGETTER(Bus)(&enmBus); H();
6483 LONG lDev;
6484 hrc = hda->COMGETTER(Device)(&lDev); H();
6485 LONG lChannel;
6486 hrc = hda->COMGETTER(Channel)(&lChannel); H();
6487
6488 int iLUN;
6489 switch (enmBus)
6490 {
6491 case StorageBus_IDE:
6492 {
6493 if (lChannel >= 2)
6494 {
6495 AssertMsgFailed(("invalid controller channel number: %d\n", lChannel));
6496 return VERR_GENERAL_FAILURE;
6497 }
6498
6499 if (lDev >= 2)
6500 {
6501 AssertMsgFailed(("invalid controller device number: %d\n", lDev));
6502 return VERR_GENERAL_FAILURE;
6503 }
6504 iLUN = 2*lChannel + lDev;
6505 }
6506 break;
6507 case StorageBus_SATA:
6508 iLUN = lChannel;
6509 break;
6510 default:
6511 AssertMsgFailed(("invalid disk controller type: %d\n", enmBus));
6512 return VERR_GENERAL_FAILURE;
6513 }
6514
6515 /*
6516 * Is there an existing LUN? If not create it.
6517 * We ASSUME that this will NEVER collide with the DVD.
6518 */
6519 PCFGMNODE pCfg;
6520 PCFGMNODE pLunL1 = CFGMR3GetChildF(CFGMR3GetRoot(pVM), "Devices/piix3ide/0/LUN#%d/AttachedDriver/", iLUN);
6521 if (!pLunL1)
6522 {
6523 PCFGMNODE pInst = CFGMR3GetChild(CFGMR3GetRoot(pVM), "Devices/piix3ide/0/");
6524 AssertReturn(pInst, VERR_INTERNAL_ERROR);
6525
6526 PCFGMNODE pLunL0;
6527 rc = CFGMR3InsertNodeF(pInst, &pLunL0, "LUN#%d", iLUN); RC_CHECK();
6528 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
6529 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
6530 rc = CFGMR3InsertString(pCfg, "Type", "HardDisk"); RC_CHECK();
6531 rc = CFGMR3InsertInteger(pCfg, "Mountable", 0); RC_CHECK();
6532
6533 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
6534 rc = CFGMR3InsertString(pLunL1, "Driver", "VBoxHDD"); RC_CHECK();
6535 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
6536 }
6537 else
6538 {
6539#ifdef VBOX_STRICT
6540 char *pszDriver;
6541 rc = CFGMR3QueryStringAlloc(pLunL1, "Driver", &pszDriver); RC_CHECK();
6542 Assert(!strcmp(pszDriver, "VBoxHDD"));
6543 MMR3HeapFree(pszDriver);
6544#endif
6545
6546 /*
6547 * Check if things has changed.
6548 */
6549 pCfg = CFGMR3GetChild(pLunL1, "Config");
6550 AssertReturn(pCfg, VERR_INTERNAL_ERROR);
6551
6552 /* the image */
6553 /// @todo (dmik) we temporarily use the location property to
6554 // determine the image file name. This is subject to change
6555 // when iSCSI disks are here (we should either query a
6556 // storage-specific interface from IHardDisk, or "standardize"
6557 // the location property)
6558 hrc = hardDisk->COMGETTER(Location)(&str); H();
6559 STR_CONV();
6560 char *pszPath;
6561 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
6562 if (!strcmp(psz, pszPath))
6563 {
6564 /* parent images. */
6565 ComPtr<IHardDisk> parentHardDisk = hardDisk;
6566 for (PCFGMNODE pParent = pCfg;;)
6567 {
6568 MMR3HeapFree(pszPath);
6569 pszPath = NULL;
6570 STR_FREE();
6571
6572 /* get parent */
6573 ComPtr<IHardDisk> curHardDisk;
6574 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
6575 PCFGMNODE pCur;
6576 pCur = CFGMR3GetChild(pParent, "Parent");
6577 if (!pCur && !curHardDisk)
6578 {
6579 /* no change */
6580 LogFlowFunc (("No change!\n"));
6581 return VINF_SUCCESS;
6582 }
6583 if (!pCur || !curHardDisk)
6584 break;
6585
6586 /* compare paths. */
6587 /// @todo (dmik) we temporarily use the location property to
6588 // determine the image file name. This is subject to change
6589 // when iSCSI disks are here (we should either query a
6590 // storage-specific interface from IHardDisk, or "standardize"
6591 // the location property)
6592 hrc = curHardDisk->COMGETTER(Location)(&str); H();
6593 STR_CONV();
6594 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
6595 if (strcmp(psz, pszPath))
6596 break;
6597
6598 /* next */
6599 pParent = pCur;
6600 parentHardDisk = curHardDisk;
6601 }
6602
6603 }
6604 else
6605 LogFlowFunc (("LUN#%d: old leaf image '%s'\n", iLUN, pszPath));
6606
6607 MMR3HeapFree(pszPath);
6608 STR_FREE();
6609
6610 /*
6611 * Detach the driver and replace the config node.
6612 */
6613 rc = PDMR3DeviceDetach(pVM, "piix3ide", 0, iLUN); RC_CHECK();
6614 CFGMR3RemoveNode(pCfg);
6615 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
6616 }
6617
6618 /*
6619 * Create the driver configuration.
6620 */
6621 /// @todo (dmik) we temporarily use the location property to
6622 // determine the image file name. This is subject to change
6623 // when iSCSI disks are here (we should either query a
6624 // storage-specific interface from IHardDisk, or "standardize"
6625 // the location property)
6626 hrc = hardDisk->COMGETTER(Location)(&str); H();
6627 STR_CONV();
6628 LogFlowFunc (("LUN#%d: leaf image '%s'\n", iLUN, psz));
6629 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
6630 STR_FREE();
6631 /* Create an inversed tree of parents. */
6632 ComPtr<IHardDisk> parentHardDisk = hardDisk;
6633 for (PCFGMNODE pParent = pCfg;;)
6634 {
6635 ComPtr<IHardDisk> curHardDisk;
6636 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
6637 if (!curHardDisk)
6638 break;
6639
6640 PCFGMNODE pCur;
6641 rc = CFGMR3InsertNode(pParent, "Parent", &pCur); RC_CHECK();
6642 /// @todo (dmik) we temporarily use the location property to
6643 // determine the image file name. This is subject to change
6644 // when iSCSI disks are here (we should either query a
6645 // storage-specific interface from IHardDisk, or "standardize"
6646 // the location property)
6647 hrc = curHardDisk->COMGETTER(Location)(&str); H();
6648 STR_CONV();
6649 rc = CFGMR3InsertString(pCur, "Path", psz); RC_CHECK();
6650 STR_FREE();
6651
6652 /* next */
6653 pParent = pCur;
6654 parentHardDisk = curHardDisk;
6655 }
6656
6657 /*
6658 * Attach the new driver.
6659 */
6660 rc = PDMR3DeviceAttach(pVM, "piix3ide", 0, iLUN, NULL); RC_CHECK();
6661
6662 LogFlowFunc (("Returns success\n"));
6663 return rc;
6664}
6665
6666
6667/**
6668 * Thread for executing the saved state operation.
6669 *
6670 * @param Thread The thread handle.
6671 * @param pvUser Pointer to a VMSaveTask structure.
6672 * @return VINF_SUCCESS (ignored).
6673 *
6674 * @note Locks the Console object for writing.
6675 */
6676/*static*/
6677DECLCALLBACK (int) Console::saveStateThread (RTTHREAD Thread, void *pvUser)
6678{
6679 LogFlowFuncEnter();
6680
6681 std::auto_ptr <VMSaveTask> task (static_cast <VMSaveTask *> (pvUser));
6682 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
6683
6684 Assert (!task->mSavedStateFile.isNull());
6685 Assert (!task->mProgress.isNull());
6686
6687 const ComObjPtr <Console> &that = task->mConsole;
6688
6689 /*
6690 * Note: no need to use addCaller() to protect Console or addVMCaller() to
6691 * protect mpVM because VMSaveTask does that
6692 */
6693
6694 Utf8Str errMsg;
6695 HRESULT rc = S_OK;
6696
6697 if (task->mIsSnapshot)
6698 {
6699 Assert (!task->mServerProgress.isNull());
6700 LogFlowFunc (("Waiting until the server creates differencing VDIs...\n"));
6701
6702 rc = task->mServerProgress->WaitForCompletion (-1);
6703 if (SUCCEEDED (rc))
6704 {
6705 HRESULT result = S_OK;
6706 rc = task->mServerProgress->COMGETTER(ResultCode) (&result);
6707 if (SUCCEEDED (rc))
6708 rc = result;
6709 }
6710 }
6711
6712 if (SUCCEEDED (rc))
6713 {
6714 LogFlowFunc (("Saving the state to '%s'...\n", task->mSavedStateFile.raw()));
6715
6716 int vrc = VMR3Save (that->mpVM, task->mSavedStateFile,
6717 Console::stateProgressCallback,
6718 static_cast <VMProgressTask *> (task.get()));
6719 if (VBOX_FAILURE (vrc))
6720 {
6721 errMsg = Utf8StrFmt (
6722 Console::tr ("Failed to save the machine state to '%s' (%Vrc)"),
6723 task->mSavedStateFile.raw(), vrc);
6724 rc = E_FAIL;
6725 }
6726 }
6727
6728 /* lock the console sonce we're going to access it */
6729 AutoWriteLock thatLock (that);
6730
6731 if (SUCCEEDED (rc))
6732 {
6733 if (task->mIsSnapshot)
6734 do
6735 {
6736 LogFlowFunc (("Reattaching new differencing VDIs...\n"));
6737
6738 ComPtr <IHardDiskAttachmentCollection> hdaColl;
6739 rc = that->mMachine->COMGETTER(HardDiskAttachments) (hdaColl.asOutParam());
6740 if (FAILED (rc))
6741 break;
6742 ComPtr <IHardDiskAttachmentEnumerator> hdaEn;
6743 rc = hdaColl->Enumerate (hdaEn.asOutParam());
6744 if (FAILED (rc))
6745 break;
6746 BOOL more = FALSE;
6747 while (SUCCEEDED (rc = hdaEn->HasMore (&more)) && more)
6748 {
6749 ComPtr <IHardDiskAttachment> hda;
6750 rc = hdaEn->GetNext (hda.asOutParam());
6751 if (FAILED (rc))
6752 break;
6753
6754 PVMREQ pReq;
6755 IHardDiskAttachment *pHda = hda;
6756 /*
6757 * don't leave the lock since reconfigureVDI isn't going to
6758 * access Console.
6759 */
6760 int vrc = VMR3ReqCall (that->mpVM, &pReq, RT_INDEFINITE_WAIT,
6761 (PFNRT)reconfigureVDI, 3, that->mpVM,
6762 pHda, &rc);
6763 if (VBOX_SUCCESS (rc))
6764 rc = pReq->iStatus;
6765 VMR3ReqFree (pReq);
6766 if (FAILED (rc))
6767 break;
6768 if (VBOX_FAILURE (vrc))
6769 {
6770 errMsg = Utf8StrFmt (Console::tr ("%Vrc"), vrc);
6771 rc = E_FAIL;
6772 break;
6773 }
6774 }
6775 }
6776 while (0);
6777 }
6778
6779 /* finalize the procedure regardless of the result */
6780 if (task->mIsSnapshot)
6781 {
6782 /*
6783 * finalize the requested snapshot object.
6784 * This will reset the machine state to the state it had right
6785 * before calling mControl->BeginTakingSnapshot().
6786 */
6787 that->mControl->EndTakingSnapshot (SUCCEEDED (rc));
6788 }
6789 else
6790 {
6791 /*
6792 * finalize the requested save state procedure.
6793 * In case of success, the server will set the machine state to Saved;
6794 * in case of failure it will reset the it to the state it had right
6795 * before calling mControl->BeginSavingState().
6796 */
6797 that->mControl->EndSavingState (SUCCEEDED (rc));
6798 }
6799
6800 /* synchronize the state with the server */
6801 if (task->mIsSnapshot || FAILED (rc))
6802 {
6803 if (task->mLastMachineState == MachineState_Running)
6804 {
6805 /* restore the paused state if appropriate */
6806 that->setMachineStateLocally (MachineState_Paused);
6807 /* restore the running state if appropriate */
6808 that->Resume();
6809 }
6810 else
6811 that->setMachineStateLocally (task->mLastMachineState);
6812 }
6813 else
6814 {
6815 /*
6816 * The machine has been successfully saved, so power it down
6817 * (vmstateChangeCallback() will set state to Saved on success).
6818 * Note: we release the task's VM caller, otherwise it will
6819 * deadlock.
6820 */
6821 task->releaseVMCaller();
6822
6823 rc = that->powerDown();
6824 }
6825
6826 /* notify the progress object about operation completion */
6827 if (SUCCEEDED (rc))
6828 task->mProgress->notifyComplete (S_OK);
6829 else
6830 {
6831 if (!errMsg.isNull())
6832 task->mProgress->notifyComplete (rc,
6833 COM_IIDOF(IConsole), Console::getComponentName(), errMsg);
6834 else
6835 task->mProgress->notifyComplete (rc);
6836 }
6837
6838 LogFlowFuncLeave();
6839 return VINF_SUCCESS;
6840}
6841
6842/**
6843 * Thread for powering down the Console.
6844 *
6845 * @param Thread The thread handle.
6846 * @param pvUser Pointer to the VMTask structure.
6847 * @return VINF_SUCCESS (ignored).
6848 *
6849 * @note Locks the Console object for writing.
6850 */
6851/*static*/
6852DECLCALLBACK (int) Console::powerDownThread (RTTHREAD Thread, void *pvUser)
6853{
6854 LogFlowFuncEnter();
6855
6856 std::auto_ptr <VMTask> task (static_cast <VMTask *> (pvUser));
6857 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
6858
6859 AssertReturn (task->isOk(), VERR_GENERAL_FAILURE);
6860
6861 const ComObjPtr <Console> &that = task->mConsole;
6862
6863 /*
6864 * Note: no need to use addCaller() to protect Console
6865 * because VMTask does that
6866 */
6867
6868 /* release VM caller to let powerDown() proceed */
6869 task->releaseVMCaller();
6870
6871 HRESULT rc = that->powerDown();
6872 AssertComRC (rc);
6873
6874 LogFlowFuncLeave();
6875 return VINF_SUCCESS;
6876}
6877
6878/**
6879 * The Main status driver instance data.
6880 */
6881typedef struct DRVMAINSTATUS
6882{
6883 /** The LED connectors. */
6884 PDMILEDCONNECTORS ILedConnectors;
6885 /** Pointer to the LED ports interface above us. */
6886 PPDMILEDPORTS pLedPorts;
6887 /** Pointer to the array of LED pointers. */
6888 PPDMLED *papLeds;
6889 /** The unit number corresponding to the first entry in the LED array. */
6890 RTUINT iFirstLUN;
6891 /** The unit number corresponding to the last entry in the LED array.
6892 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
6893 RTUINT iLastLUN;
6894} DRVMAINSTATUS, *PDRVMAINSTATUS;
6895
6896
6897/**
6898 * Notification about a unit which have been changed.
6899 *
6900 * The driver must discard any pointers to data owned by
6901 * the unit and requery it.
6902 *
6903 * @param pInterface Pointer to the interface structure containing the called function pointer.
6904 * @param iLUN The unit number.
6905 */
6906DECLCALLBACK(void) Console::drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
6907{
6908 PDRVMAINSTATUS pData = (PDRVMAINSTATUS)(void *)pInterface;
6909 if (iLUN >= pData->iFirstLUN && iLUN <= pData->iLastLUN)
6910 {
6911 PPDMLED pLed;
6912 int rc = pData->pLedPorts->pfnQueryStatusLed(pData->pLedPorts, iLUN, &pLed);
6913 if (VBOX_FAILURE(rc))
6914 pLed = NULL;
6915 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLUN - pData->iFirstLUN], pLed);
6916 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
6917 }
6918}
6919
6920
6921/**
6922 * Queries an interface to the driver.
6923 *
6924 * @returns Pointer to interface.
6925 * @returns NULL if the interface was not supported by the driver.
6926 * @param pInterface Pointer to this interface structure.
6927 * @param enmInterface The requested interface identification.
6928 */
6929DECLCALLBACK(void *) Console::drvStatus_QueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
6930{
6931 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
6932 PDRVMAINSTATUS pDrv = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
6933 switch (enmInterface)
6934 {
6935 case PDMINTERFACE_BASE:
6936 return &pDrvIns->IBase;
6937 case PDMINTERFACE_LED_CONNECTORS:
6938 return &pDrv->ILedConnectors;
6939 default:
6940 return NULL;
6941 }
6942}
6943
6944
6945/**
6946 * Destruct a status driver instance.
6947 *
6948 * @returns VBox status.
6949 * @param pDrvIns The driver instance data.
6950 */
6951DECLCALLBACK(void) Console::drvStatus_Destruct(PPDMDRVINS pDrvIns)
6952{
6953 PDRVMAINSTATUS pData = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
6954 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
6955 if (pData->papLeds)
6956 {
6957 unsigned iLed = pData->iLastLUN - pData->iFirstLUN + 1;
6958 while (iLed-- > 0)
6959 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLed], NULL);
6960 }
6961}
6962
6963
6964/**
6965 * Construct a status driver instance.
6966 *
6967 * @returns VBox status.
6968 * @param pDrvIns The driver instance data.
6969 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
6970 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
6971 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
6972 * iInstance it's expected to be used a bit in this function.
6973 */
6974DECLCALLBACK(int) Console::drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
6975{
6976 PDRVMAINSTATUS pData = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
6977 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
6978
6979 /*
6980 * Validate configuration.
6981 */
6982 if (!CFGMR3AreValuesValid(pCfgHandle, "papLeds\0First\0Last\0"))
6983 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
6984 PPDMIBASE pBaseIgnore;
6985 int rc = pDrvIns->pDrvHlp->pfnAttach(pDrvIns, &pBaseIgnore);
6986 if (rc != VERR_PDM_NO_ATTACHED_DRIVER)
6987 {
6988 AssertMsgFailed(("Configuration error: Not possible to attach anything to this driver!\n"));
6989 return VERR_PDM_DRVINS_NO_ATTACH;
6990 }
6991
6992 /*
6993 * Data.
6994 */
6995 pDrvIns->IBase.pfnQueryInterface = Console::drvStatus_QueryInterface;
6996 pData->ILedConnectors.pfnUnitChanged = Console::drvStatus_UnitChanged;
6997
6998 /*
6999 * Read config.
7000 */
7001 rc = CFGMR3QueryPtr(pCfgHandle, "papLeds", (void **)&pData->papLeds);
7002 if (VBOX_FAILURE(rc))
7003 {
7004 AssertMsgFailed(("Configuration error: Failed to query the \"papLeds\" value! rc=%Vrc\n", rc));
7005 return rc;
7006 }
7007
7008 rc = CFGMR3QueryU32(pCfgHandle, "First", &pData->iFirstLUN);
7009 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
7010 pData->iFirstLUN = 0;
7011 else if (VBOX_FAILURE(rc))
7012 {
7013 AssertMsgFailed(("Configuration error: Failed to query the \"First\" value! rc=%Vrc\n", rc));
7014 return rc;
7015 }
7016
7017 rc = CFGMR3QueryU32(pCfgHandle, "Last", &pData->iLastLUN);
7018 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
7019 pData->iLastLUN = 0;
7020 else if (VBOX_FAILURE(rc))
7021 {
7022 AssertMsgFailed(("Configuration error: Failed to query the \"Last\" value! rc=%Vrc\n", rc));
7023 return rc;
7024 }
7025 if (pData->iFirstLUN > pData->iLastLUN)
7026 {
7027 AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pData->iFirstLUN, pData->iLastLUN));
7028 return VERR_GENERAL_FAILURE;
7029 }
7030
7031 /*
7032 * Get the ILedPorts interface of the above driver/device and
7033 * query the LEDs we want.
7034 */
7035 pData->pLedPorts = (PPDMILEDPORTS)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_LED_PORTS);
7036 if (!pData->pLedPorts)
7037 {
7038 AssertMsgFailed(("Configuration error: No led ports interface above!\n"));
7039 return VERR_PDM_MISSING_INTERFACE_ABOVE;
7040 }
7041
7042 for (unsigned i = pData->iFirstLUN; i <= pData->iLastLUN; i++)
7043 Console::drvStatus_UnitChanged(&pData->ILedConnectors, i);
7044
7045 return VINF_SUCCESS;
7046}
7047
7048
7049/**
7050 * Keyboard driver registration record.
7051 */
7052const PDMDRVREG Console::DrvStatusReg =
7053{
7054 /* u32Version */
7055 PDM_DRVREG_VERSION,
7056 /* szDriverName */
7057 "MainStatus",
7058 /* pszDescription */
7059 "Main status driver (Main as in the API).",
7060 /* fFlags */
7061 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
7062 /* fClass. */
7063 PDM_DRVREG_CLASS_STATUS,
7064 /* cMaxInstances */
7065 ~0,
7066 /* cbInstance */
7067 sizeof(DRVMAINSTATUS),
7068 /* pfnConstruct */
7069 Console::drvStatus_Construct,
7070 /* pfnDestruct */
7071 Console::drvStatus_Destruct,
7072 /* pfnIOCtl */
7073 NULL,
7074 /* pfnPowerOn */
7075 NULL,
7076 /* pfnReset */
7077 NULL,
7078 /* pfnSuspend */
7079 NULL,
7080 /* pfnResume */
7081 NULL,
7082 /* pfnDetach */
7083 NULL
7084};
7085
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