VirtualBox

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

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

Main: add the Main part of the guest/host configuration registry

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