VirtualBox

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

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

Main: call DiscardSettings() before saving guest properties in order to avoid saving any undesired temporary settings

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