VirtualBox

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

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

Made annoying assertion in setVMErrorCallback ignorable.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 217.5 KB
Line 
1/** @file
2 *
3 * VBox Console COM Class implementation
4 */
5
6/*
7 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
18 * Clara, CA 95054 USA or visit http://www.sun.com if you need
19 * additional information or have any questions.
20 */
21
22#include <iprt/types.h> /* for stdint.h constants */
23
24#if defined(RT_OS_WINDOWS)
25#elif defined(RT_OS_LINUX)
26# include <errno.h>
27# include <sys/ioctl.h>
28# include <sys/poll.h>
29# include <sys/fcntl.h>
30# include <sys/types.h>
31# include <sys/wait.h>
32# include <net/if.h>
33# include <linux/if_tun.h>
34# include <stdio.h>
35# include <stdlib.h>
36# include <string.h>
37#elif defined(VBOX_WITH_UNIXY_TAP_NETWORKING)
38# include <sys/wait.h>
39# include <sys/fcntl.h>
40#endif
41
42#include "ConsoleImpl.h"
43#include "GuestImpl.h"
44#include "KeyboardImpl.h"
45#include "MouseImpl.h"
46#include "DisplayImpl.h"
47#include "MachineDebuggerImpl.h"
48#include "USBDeviceImpl.h"
49#include "RemoteUSBDeviceImpl.h"
50#include "SharedFolderImpl.h"
51#include "AudioSnifferInterface.h"
52#include "ConsoleVRDPServer.h"
53#include "VMMDev.h"
54#include "Version.h"
55
56// generated header
57#include "SchemaDefs.h"
58
59#include "Logging.h"
60
61#include <iprt/string.h>
62#include <iprt/asm.h>
63#include <iprt/file.h>
64#include <iprt/path.h>
65#include <iprt/dir.h>
66#include <iprt/process.h>
67#include <iprt/ldr.h>
68#include <iprt/cpputils.h>
69
70#include <VBox/vmapi.h>
71#include <VBox/err.h>
72#include <VBox/param.h>
73#include <VBox/vusb.h>
74#include <VBox/mm.h>
75#include <VBox/ssm.h>
76#include <VBox/version.h>
77#ifdef VBOX_WITH_USB
78# include <VBox/pdmusb.h>
79#endif
80
81#include <VBox/VBoxDev.h>
82
83#include <VBox/HostServices/VBoxClipboardSvc.h>
84#ifdef VBOX_WITH_GUEST_PROPS
85# include <VBox/HostServices/GuestPropertySvc.h>
86#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
2489// Non-interface public methods
2490/////////////////////////////////////////////////////////////////////////////
2491
2492/**
2493 * Called by IInternalSessionControl::OnDVDDriveChange().
2494 *
2495 * @note Locks this object for writing.
2496 */
2497HRESULT Console::onDVDDriveChange()
2498{
2499 LogFlowThisFunc (("\n"));
2500
2501 AutoCaller autoCaller (this);
2502 AssertComRCReturnRC (autoCaller.rc());
2503
2504 /* doDriveChange() needs a write lock */
2505 AutoWriteLock alock (this);
2506
2507 /* Ignore callbacks when there's no VM around */
2508 if (!mpVM)
2509 return S_OK;
2510
2511 /* protect mpVM */
2512 AutoVMCaller autoVMCaller (this);
2513 CheckComRCReturnRC (autoVMCaller.rc());
2514
2515 /* Get the current DVD state */
2516 HRESULT rc;
2517 DriveState_T eState;
2518
2519 rc = mDVDDrive->COMGETTER (State) (&eState);
2520 ComAssertComRCRetRC (rc);
2521
2522 /* Paranoia */
2523 if ( eState == DriveState_NotMounted
2524 && meDVDState == DriveState_NotMounted)
2525 {
2526 LogFlowThisFunc (("Returns (NotMounted -> NotMounted)\n"));
2527 return S_OK;
2528 }
2529
2530 /* Get the path string and other relevant properties */
2531 Bstr Path;
2532 bool fPassthrough = false;
2533 switch (eState)
2534 {
2535 case DriveState_ImageMounted:
2536 {
2537 ComPtr <IDVDImage> ImagePtr;
2538 rc = mDVDDrive->GetImage (ImagePtr.asOutParam());
2539 if (SUCCEEDED (rc))
2540 rc = ImagePtr->COMGETTER(FilePath) (Path.asOutParam());
2541 break;
2542 }
2543
2544 case DriveState_HostDriveCaptured:
2545 {
2546 ComPtr <IHostDVDDrive> DrivePtr;
2547 BOOL enabled;
2548 rc = mDVDDrive->GetHostDrive (DrivePtr.asOutParam());
2549 if (SUCCEEDED (rc))
2550 rc = DrivePtr->COMGETTER (Name) (Path.asOutParam());
2551 if (SUCCEEDED (rc))
2552 rc = mDVDDrive->COMGETTER (Passthrough) (&enabled);
2553 if (SUCCEEDED (rc))
2554 fPassthrough = !!enabled;
2555 break;
2556 }
2557
2558 case DriveState_NotMounted:
2559 break;
2560
2561 default:
2562 AssertMsgFailed (("Invalid DriveState: %d\n", eState));
2563 rc = E_FAIL;
2564 break;
2565 }
2566
2567 AssertComRC (rc);
2568 if (FAILED (rc))
2569 {
2570 LogFlowThisFunc (("Returns %#x\n", rc));
2571 return rc;
2572 }
2573
2574 rc = doDriveChange ("piix3ide", 0, 2, eState, &meDVDState,
2575 Utf8Str (Path).raw(), fPassthrough);
2576
2577 /* notify console callbacks on success */
2578 if (SUCCEEDED (rc))
2579 {
2580 CallbackList::iterator it = mCallbacks.begin();
2581 while (it != mCallbacks.end())
2582 (*it++)->OnDVDDriveChange();
2583 }
2584
2585 return rc;
2586}
2587
2588
2589/**
2590 * Called by IInternalSessionControl::OnFloppyDriveChange().
2591 *
2592 * @note Locks this object for writing.
2593 */
2594HRESULT Console::onFloppyDriveChange()
2595{
2596 LogFlowThisFunc (("\n"));
2597
2598 AutoCaller autoCaller (this);
2599 AssertComRCReturnRC (autoCaller.rc());
2600
2601 /* doDriveChange() needs a write lock */
2602 AutoWriteLock alock (this);
2603
2604 /* Ignore callbacks when there's no VM around */
2605 if (!mpVM)
2606 return S_OK;
2607
2608 /* protect mpVM */
2609 AutoVMCaller autoVMCaller (this);
2610 CheckComRCReturnRC (autoVMCaller.rc());
2611
2612 /* Get the current floppy state */
2613 HRESULT rc;
2614 DriveState_T eState;
2615
2616 /* If the floppy drive is disabled, we're not interested */
2617 BOOL fEnabled;
2618 rc = mFloppyDrive->COMGETTER (Enabled) (&fEnabled);
2619 ComAssertComRCRetRC (rc);
2620
2621 if (!fEnabled)
2622 return S_OK;
2623
2624 rc = mFloppyDrive->COMGETTER (State) (&eState);
2625 ComAssertComRCRetRC (rc);
2626
2627 Log2 (("onFloppyDriveChange: eState=%d meFloppyState=%d\n", eState, meFloppyState));
2628
2629
2630 /* Paranoia */
2631 if ( eState == DriveState_NotMounted
2632 && meFloppyState == DriveState_NotMounted)
2633 {
2634 LogFlowThisFunc (("Returns (NotMounted -> NotMounted)\n"));
2635 return S_OK;
2636 }
2637
2638 /* Get the path string and other relevant properties */
2639 Bstr Path;
2640 switch (eState)
2641 {
2642 case DriveState_ImageMounted:
2643 {
2644 ComPtr <IFloppyImage> ImagePtr;
2645 rc = mFloppyDrive->GetImage (ImagePtr.asOutParam());
2646 if (SUCCEEDED (rc))
2647 rc = ImagePtr->COMGETTER(FilePath) (Path.asOutParam());
2648 break;
2649 }
2650
2651 case DriveState_HostDriveCaptured:
2652 {
2653 ComPtr <IHostFloppyDrive> DrivePtr;
2654 rc = mFloppyDrive->GetHostDrive (DrivePtr.asOutParam());
2655 if (SUCCEEDED (rc))
2656 rc = DrivePtr->COMGETTER (Name) (Path.asOutParam());
2657 break;
2658 }
2659
2660 case DriveState_NotMounted:
2661 break;
2662
2663 default:
2664 AssertMsgFailed (("Invalid DriveState: %d\n", eState));
2665 rc = E_FAIL;
2666 break;
2667 }
2668
2669 AssertComRC (rc);
2670 if (FAILED (rc))
2671 {
2672 LogFlowThisFunc (("Returns %#x\n", rc));
2673 return rc;
2674 }
2675
2676 rc = doDriveChange ("i82078", 0, 0, eState, &meFloppyState,
2677 Utf8Str (Path).raw(), false);
2678
2679 /* notify console callbacks on success */
2680 if (SUCCEEDED (rc))
2681 {
2682 CallbackList::iterator it = mCallbacks.begin();
2683 while (it != mCallbacks.end())
2684 (*it++)->OnFloppyDriveChange();
2685 }
2686
2687 return rc;
2688}
2689
2690
2691/**
2692 * Process a floppy or dvd change.
2693 *
2694 * @returns COM status code.
2695 *
2696 * @param pszDevice The PDM device name.
2697 * @param uInstance The PDM device instance.
2698 * @param uLun The PDM LUN number of the drive.
2699 * @param eState The new state.
2700 * @param peState Pointer to the variable keeping the actual state of the drive.
2701 * This will be both read and updated to eState or other appropriate state.
2702 * @param pszPath The path to the media / drive which is now being mounted / captured.
2703 * If NULL no media or drive is attached and the lun will be configured with
2704 * the default block driver with no media. This will also be the state if
2705 * mounting / capturing the specified media / drive fails.
2706 * @param fPassthrough Enables using passthrough mode of the host DVD drive if applicable.
2707 *
2708 * @note Locks this object for writing.
2709 */
2710HRESULT Console::doDriveChange (const char *pszDevice, unsigned uInstance, unsigned uLun, DriveState_T eState,
2711 DriveState_T *peState, const char *pszPath, bool fPassthrough)
2712{
2713 LogFlowThisFunc (("pszDevice=%p:{%s} uInstance=%u uLun=%u eState=%d "
2714 "peState=%p:{%d} pszPath=%p:{%s} fPassthrough=%d\n",
2715 pszDevice, pszDevice, uInstance, uLun, eState,
2716 peState, *peState, pszPath, pszPath, fPassthrough));
2717
2718 AutoCaller autoCaller (this);
2719 AssertComRCReturnRC (autoCaller.rc());
2720
2721 /* We will need to release the write lock before calling EMT */
2722 AutoWriteLock alock (this);
2723
2724 /* protect mpVM */
2725 AutoVMCaller autoVMCaller (this);
2726 CheckComRCReturnRC (autoVMCaller.rc());
2727
2728 /*
2729 * Call worker in EMT, that's faster and safer than doing everything
2730 * using VM3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
2731 * here to make requests from under the lock in order to serialize them.
2732 */
2733 PVMREQ pReq;
2734 int vrc = VMR3ReqCall (mpVM, &pReq, 0 /* no wait! */,
2735 (PFNRT) Console::changeDrive, 8,
2736 this, pszDevice, uInstance, uLun, eState, peState,
2737 pszPath, fPassthrough);
2738 /// @todo (r=dmik) bird, it would be nice to have a special VMR3Req method
2739 // for that purpose, that doesn't return useless VERR_TIMEOUT
2740 if (vrc == VERR_TIMEOUT)
2741 vrc = VINF_SUCCESS;
2742
2743 /* leave the lock before waiting for a result (EMT will call us back!) */
2744 alock.leave();
2745
2746 if (VBOX_SUCCESS (vrc))
2747 {
2748 vrc = VMR3ReqWait (pReq, RT_INDEFINITE_WAIT);
2749 AssertRC (vrc);
2750 if (VBOX_SUCCESS (vrc))
2751 vrc = pReq->iStatus;
2752 }
2753 VMR3ReqFree (pReq);
2754
2755 if (VBOX_SUCCESS (vrc))
2756 {
2757 LogFlowThisFunc (("Returns S_OK\n"));
2758 return S_OK;
2759 }
2760
2761 if (pszPath)
2762 return setError (E_FAIL,
2763 tr ("Could not mount the media/drive '%s' (%Vrc)"), pszPath, vrc);
2764
2765 return setError (E_FAIL,
2766 tr ("Could not unmount the currently mounted media/drive (%Vrc)"), vrc);
2767}
2768
2769
2770/**
2771 * Performs the Floppy/DVD change in EMT.
2772 *
2773 * @returns VBox status code.
2774 *
2775 * @param pThis Pointer to the Console object.
2776 * @param pszDevice The PDM device name.
2777 * @param uInstance The PDM device instance.
2778 * @param uLun The PDM LUN number of the drive.
2779 * @param eState The new state.
2780 * @param peState Pointer to the variable keeping the actual state of the drive.
2781 * This will be both read and updated to eState or other appropriate state.
2782 * @param pszPath The path to the media / drive which is now being mounted / captured.
2783 * If NULL no media or drive is attached and the lun will be configured with
2784 * the default block driver with no media. This will also be the state if
2785 * mounting / capturing the specified media / drive fails.
2786 * @param fPassthrough Enables using passthrough mode of the host DVD drive if applicable.
2787 *
2788 * @thread EMT
2789 * @note Locks the Console object for writing.
2790 */
2791DECLCALLBACK(int) Console::changeDrive (Console *pThis, const char *pszDevice, unsigned uInstance, unsigned uLun,
2792 DriveState_T eState, DriveState_T *peState,
2793 const char *pszPath, bool fPassthrough)
2794{
2795 LogFlowFunc (("pThis=%p pszDevice=%p:{%s} uInstance=%u uLun=%u eState=%d "
2796 "peState=%p:{%d} pszPath=%p:{%s} fPassthrough=%d\n",
2797 pThis, pszDevice, pszDevice, uInstance, uLun, eState,
2798 peState, *peState, pszPath, pszPath, fPassthrough));
2799
2800 AssertReturn (pThis, VERR_INVALID_PARAMETER);
2801
2802 AssertMsg ( (!strcmp (pszDevice, "i82078") && uLun == 0 && uInstance == 0)
2803 || (!strcmp (pszDevice, "piix3ide") && uLun == 2 && uInstance == 0),
2804 ("pszDevice=%s uLun=%d uInstance=%d\n", pszDevice, uLun, uInstance));
2805
2806 AutoCaller autoCaller (pThis);
2807 AssertComRCReturn (autoCaller.rc(), VERR_ACCESS_DENIED);
2808
2809 /*
2810 * Locking the object before doing VMR3* calls is quite safe here, since
2811 * we're on EMT. Write lock is necessary because we indirectly modify the
2812 * meDVDState/meFloppyState members (pointed to by peState).
2813 */
2814 AutoWriteLock alock (pThis);
2815
2816 /* protect mpVM */
2817 AutoVMCaller autoVMCaller (pThis);
2818 CheckComRCReturnRC (autoVMCaller.rc());
2819
2820 PVM pVM = pThis->mpVM;
2821
2822 /*
2823 * Suspend the VM first.
2824 *
2825 * The VM must not be running since it might have pending I/O to
2826 * the drive which is being changed.
2827 */
2828 bool fResume;
2829 VMSTATE enmVMState = VMR3GetState (pVM);
2830 switch (enmVMState)
2831 {
2832 case VMSTATE_RESETTING:
2833 case VMSTATE_RUNNING:
2834 {
2835 LogFlowFunc (("Suspending the VM...\n"));
2836 /* disable the callback to prevent Console-level state change */
2837 pThis->mVMStateChangeCallbackDisabled = true;
2838 int rc = VMR3Suspend (pVM);
2839 pThis->mVMStateChangeCallbackDisabled = false;
2840 AssertRCReturn (rc, rc);
2841 fResume = true;
2842 break;
2843 }
2844
2845 case VMSTATE_SUSPENDED:
2846 case VMSTATE_CREATED:
2847 case VMSTATE_OFF:
2848 fResume = false;
2849 break;
2850
2851 default:
2852 AssertMsgFailedReturn (("enmVMState=%d\n", enmVMState), VERR_ACCESS_DENIED);
2853 }
2854
2855 int rc = VINF_SUCCESS;
2856 int rcRet = VINF_SUCCESS;
2857
2858 do
2859 {
2860 /*
2861 * Unmount existing media / detach host drive.
2862 */
2863 PPDMIMOUNT pIMount = NULL;
2864 switch (*peState)
2865 {
2866
2867 case DriveState_ImageMounted:
2868 {
2869 /*
2870 * Resolve the interface.
2871 */
2872 PPDMIBASE pBase;
2873 rc = PDMR3QueryLun (pVM, pszDevice, uInstance, uLun, &pBase);
2874 if (VBOX_FAILURE (rc))
2875 {
2876 if (rc == VERR_PDM_LUN_NOT_FOUND)
2877 rc = VINF_SUCCESS;
2878 AssertRC (rc);
2879 break;
2880 }
2881
2882 pIMount = (PPDMIMOUNT) pBase->pfnQueryInterface (pBase, PDMINTERFACE_MOUNT);
2883 AssertBreakStmt (pIMount, rc = VERR_INVALID_POINTER);
2884
2885 /*
2886 * Unmount the media.
2887 */
2888 rc = pIMount->pfnUnmount (pIMount, false);
2889 if (rc == VERR_PDM_MEDIA_NOT_MOUNTED)
2890 rc = VINF_SUCCESS;
2891 break;
2892 }
2893
2894 case DriveState_HostDriveCaptured:
2895 {
2896 rc = PDMR3DeviceDetach (pVM, pszDevice, uInstance, uLun);
2897 if (rc == VINF_PDM_NO_DRIVER_ATTACHED_TO_LUN)
2898 rc = VINF_SUCCESS;
2899 AssertRC (rc);
2900 break;
2901 }
2902
2903 case DriveState_NotMounted:
2904 break;
2905
2906 default:
2907 AssertMsgFailed (("Invalid *peState: %d\n", peState));
2908 break;
2909 }
2910
2911 if (VBOX_FAILURE (rc))
2912 {
2913 rcRet = rc;
2914 break;
2915 }
2916
2917 /*
2918 * Nothing is currently mounted.
2919 */
2920 *peState = DriveState_NotMounted;
2921
2922
2923 /*
2924 * Process the HostDriveCaptured state first, as the fallback path
2925 * means mounting the normal block driver without media.
2926 */
2927 if (eState == DriveState_HostDriveCaptured)
2928 {
2929 /*
2930 * Detach existing driver chain (block).
2931 */
2932 int rc = PDMR3DeviceDetach (pVM, pszDevice, uInstance, uLun);
2933 if (VBOX_FAILURE (rc))
2934 {
2935 if (rc == VERR_PDM_LUN_NOT_FOUND)
2936 rc = VINF_SUCCESS;
2937 AssertReleaseRC (rc);
2938 break; /* we're toast */
2939 }
2940 pIMount = NULL;
2941
2942 /*
2943 * Construct a new driver configuration.
2944 */
2945 PCFGMNODE pInst = CFGMR3GetChildF (CFGMR3GetRoot (pVM), "Devices/%s/%d/", pszDevice, uInstance);
2946 AssertRelease (pInst);
2947 /* nuke anything which might have been left behind. */
2948 CFGMR3RemoveNode (CFGMR3GetChildF (pInst, "LUN#%d", uLun));
2949
2950 /* create a new block driver config */
2951 PCFGMNODE pLunL0;
2952 PCFGMNODE pCfg;
2953 if ( VBOX_SUCCESS (rc = CFGMR3InsertNodeF (pInst, &pLunL0, "LUN#%u", uLun))
2954 && VBOX_SUCCESS (rc = CFGMR3InsertString (pLunL0, "Driver", !strcmp (pszDevice, "i82078") ? "HostFloppy" : "HostDVD"))
2955 && VBOX_SUCCESS (rc = CFGMR3InsertNode (pLunL0, "Config", &pCfg))
2956 && VBOX_SUCCESS (rc = CFGMR3InsertString (pCfg, "Path", pszPath))
2957 && VBOX_SUCCESS (rc = !strcmp (pszDevice, "i82078") ? VINF_SUCCESS : CFGMR3InsertInteger(pCfg, "Passthrough", fPassthrough)))
2958 {
2959 /*
2960 * Attempt to attach the driver.
2961 */
2962 rc = PDMR3DeviceAttach (pVM, pszDevice, uInstance, uLun, NULL);
2963 AssertRC (rc);
2964 }
2965 if (VBOX_FAILURE (rc))
2966 rcRet = rc;
2967 }
2968
2969 /*
2970 * Process the ImageMounted, NotMounted and failed HostDriveCapture cases.
2971 */
2972 rc = VINF_SUCCESS;
2973 switch (eState)
2974 {
2975#define RC_CHECK() do { if (VBOX_FAILURE (rc)) { AssertReleaseRC (rc); break; } } while (0)
2976
2977 case DriveState_HostDriveCaptured:
2978 if (VBOX_SUCCESS (rcRet))
2979 break;
2980 /* fallback: umounted block driver. */
2981 pszPath = NULL;
2982 eState = DriveState_NotMounted;
2983 /* fallthru */
2984 case DriveState_ImageMounted:
2985 case DriveState_NotMounted:
2986 {
2987 /*
2988 * Resolve the drive interface / create the driver.
2989 */
2990 if (!pIMount)
2991 {
2992 PPDMIBASE pBase;
2993 rc = PDMR3QueryLun (pVM, pszDevice, uInstance, uLun, &pBase);
2994 if (rc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
2995 {
2996 /*
2997 * We have to create it, so we'll do the full config setup and everything.
2998 */
2999 PCFGMNODE pIdeInst = CFGMR3GetChildF (CFGMR3GetRoot (pVM), "Devices/%s/%d/", pszDevice, uInstance);
3000 AssertRelease (pIdeInst);
3001
3002 /* nuke anything which might have been left behind. */
3003 CFGMR3RemoveNode (CFGMR3GetChildF (pIdeInst, "LUN#%d", uLun));
3004
3005 /* create a new block driver config */
3006 PCFGMNODE pLunL0;
3007 rc = CFGMR3InsertNodeF (pIdeInst, &pLunL0, "LUN#%d", uLun); RC_CHECK();
3008 rc = CFGMR3InsertString (pLunL0, "Driver", "Block"); RC_CHECK();
3009 PCFGMNODE pCfg;
3010 rc = CFGMR3InsertNode (pLunL0, "Config", &pCfg); RC_CHECK();
3011 rc = CFGMR3InsertString (pCfg, "Type", !strcmp (pszDevice, "i82078") ? "Floppy 1.44" : "DVD");
3012 RC_CHECK();
3013 rc = CFGMR3InsertInteger (pCfg, "Mountable", 1); RC_CHECK();
3014
3015 /*
3016 * Attach the driver.
3017 */
3018 rc = PDMR3DeviceAttach (pVM, pszDevice, uInstance, uLun, &pBase);
3019 RC_CHECK();
3020 }
3021 else if (VBOX_FAILURE(rc))
3022 {
3023 AssertRC (rc);
3024 return rc;
3025 }
3026
3027 pIMount = (PPDMIMOUNT) pBase->pfnQueryInterface (pBase, PDMINTERFACE_MOUNT);
3028 if (!pIMount)
3029 {
3030 AssertFailed();
3031 return rc;
3032 }
3033 }
3034
3035 /*
3036 * If we've got an image, let's mount it.
3037 */
3038 if (pszPath && *pszPath)
3039 {
3040 rc = pIMount->pfnMount (pIMount, pszPath, strcmp (pszDevice, "i82078") ? "MediaISO" : "RawImage");
3041 if (VBOX_FAILURE (rc))
3042 eState = DriveState_NotMounted;
3043 }
3044 break;
3045 }
3046
3047 default:
3048 AssertMsgFailed (("Invalid eState: %d\n", eState));
3049 break;
3050
3051#undef RC_CHECK
3052 }
3053
3054 if (VBOX_FAILURE (rc) && VBOX_SUCCESS (rcRet))
3055 rcRet = rc;
3056
3057 *peState = eState;
3058 }
3059 while (0);
3060
3061 /*
3062 * Resume the VM if necessary.
3063 */
3064 if (fResume)
3065 {
3066 LogFlowFunc (("Resuming the VM...\n"));
3067 /* disable the callback to prevent Console-level state change */
3068 pThis->mVMStateChangeCallbackDisabled = true;
3069 rc = VMR3Resume (pVM);
3070 pThis->mVMStateChangeCallbackDisabled = false;
3071 AssertRC (rc);
3072 if (VBOX_FAILURE (rc))
3073 {
3074 /* too bad, we failed. try to sync the console state with the VMM state */
3075 vmstateChangeCallback (pVM, VMSTATE_SUSPENDED, enmVMState, pThis);
3076 }
3077 /// @todo (r=dmik) if we failed with drive mount, then the VMR3Resume
3078 // error (if any) will be hidden from the caller. For proper reporting
3079 // of such multiple errors to the caller we need to enhance the
3080 // IVurtualBoxError interface. For now, give the first error the higher
3081 // priority.
3082 if (VBOX_SUCCESS (rcRet))
3083 rcRet = rc;
3084 }
3085
3086 LogFlowFunc (("Returning %Vrc\n", rcRet));
3087 return rcRet;
3088}
3089
3090
3091/**
3092 * Called by IInternalSessionControl::OnNetworkAdapterChange().
3093 *
3094 * @note Locks this object for writing.
3095 */
3096HRESULT Console::onNetworkAdapterChange (INetworkAdapter *aNetworkAdapter)
3097{
3098 LogFlowThisFunc (("\n"));
3099
3100 AutoCaller autoCaller (this);
3101 AssertComRCReturnRC (autoCaller.rc());
3102
3103 AutoWriteLock alock (this);
3104
3105 /* Don't do anything if the VM isn't running */
3106 if (!mpVM)
3107 return S_OK;
3108
3109 /* protect mpVM */
3110 AutoVMCaller autoVMCaller (this);
3111 CheckComRCReturnRC (autoVMCaller.rc());
3112
3113 /* Get the properties we need from the adapter */
3114 BOOL fCableConnected;
3115 HRESULT rc = aNetworkAdapter->COMGETTER(CableConnected) (&fCableConnected);
3116 AssertComRC(rc);
3117 if (SUCCEEDED(rc))
3118 {
3119 ULONG ulInstance;
3120 rc = aNetworkAdapter->COMGETTER(Slot) (&ulInstance);
3121 AssertComRC (rc);
3122 if (SUCCEEDED (rc))
3123 {
3124 /*
3125 * Find the pcnet instance, get the config interface and update
3126 * the link state.
3127 */
3128 PPDMIBASE pBase;
3129 const char *cszAdapterName = "pcnet";
3130#ifdef VBOX_WITH_E1000
3131 /*
3132 * Perharps it would be much wiser to wrap both 'pcnet' and 'e1000'
3133 * into generic 'net' device.
3134 */
3135 NetworkAdapterType_T adapterType;
3136 rc = aNetworkAdapter->COMGETTER(AdapterType)(&adapterType);
3137 AssertComRC(rc);
3138 if (adapterType == NetworkAdapterType_I82540EM ||
3139 adapterType == NetworkAdapterType_I82543GC)
3140 cszAdapterName = "e1000";
3141#endif
3142 int vrc = PDMR3QueryDeviceLun (mpVM, cszAdapterName,
3143 (unsigned) ulInstance, 0, &pBase);
3144 ComAssertRC (vrc);
3145 if (VBOX_SUCCESS (vrc))
3146 {
3147 Assert(pBase);
3148 PPDMINETWORKCONFIG pINetCfg = (PPDMINETWORKCONFIG) pBase->
3149 pfnQueryInterface(pBase, PDMINTERFACE_NETWORK_CONFIG);
3150 if (pINetCfg)
3151 {
3152 Log (("Console::onNetworkAdapterChange: setting link state to %d\n",
3153 fCableConnected));
3154 vrc = pINetCfg->pfnSetLinkState (pINetCfg,
3155 fCableConnected ? PDMNETWORKLINKSTATE_UP
3156 : PDMNETWORKLINKSTATE_DOWN);
3157 ComAssertRC (vrc);
3158 }
3159 }
3160
3161 if (VBOX_FAILURE (vrc))
3162 rc = E_FAIL;
3163 }
3164 }
3165
3166 /* notify console callbacks on success */
3167 if (SUCCEEDED (rc))
3168 {
3169 CallbackList::iterator it = mCallbacks.begin();
3170 while (it != mCallbacks.end())
3171 (*it++)->OnNetworkAdapterChange (aNetworkAdapter);
3172 }
3173
3174 LogFlowThisFunc (("Leaving rc=%#x\n", rc));
3175 return rc;
3176}
3177
3178/**
3179 * Called by IInternalSessionControl::OnSerialPortChange().
3180 *
3181 * @note Locks this object for writing.
3182 */
3183HRESULT Console::onSerialPortChange (ISerialPort *aSerialPort)
3184{
3185 LogFlowThisFunc (("\n"));
3186
3187 AutoCaller autoCaller (this);
3188 AssertComRCReturnRC (autoCaller.rc());
3189
3190 AutoWriteLock alock (this);
3191
3192 /* Don't do anything if the VM isn't running */
3193 if (!mpVM)
3194 return S_OK;
3195
3196 HRESULT rc = S_OK;
3197
3198 /* protect mpVM */
3199 AutoVMCaller autoVMCaller (this);
3200 CheckComRCReturnRC (autoVMCaller.rc());
3201
3202 /* nothing to do so far */
3203
3204 /* notify console callbacks on success */
3205 if (SUCCEEDED (rc))
3206 {
3207 CallbackList::iterator it = mCallbacks.begin();
3208 while (it != mCallbacks.end())
3209 (*it++)->OnSerialPortChange (aSerialPort);
3210 }
3211
3212 LogFlowThisFunc (("Leaving rc=%#x\n", rc));
3213 return rc;
3214}
3215
3216/**
3217 * Called by IInternalSessionControl::OnParallelPortChange().
3218 *
3219 * @note Locks this object for writing.
3220 */
3221HRESULT Console::onParallelPortChange (IParallelPort *aParallelPort)
3222{
3223 LogFlowThisFunc (("\n"));
3224
3225 AutoCaller autoCaller (this);
3226 AssertComRCReturnRC (autoCaller.rc());
3227
3228 AutoWriteLock alock (this);
3229
3230 /* Don't do anything if the VM isn't running */
3231 if (!mpVM)
3232 return S_OK;
3233
3234 HRESULT rc = S_OK;
3235
3236 /* protect mpVM */
3237 AutoVMCaller autoVMCaller (this);
3238 CheckComRCReturnRC (autoVMCaller.rc());
3239
3240 /* nothing to do so far */
3241
3242 /* notify console callbacks on success */
3243 if (SUCCEEDED (rc))
3244 {
3245 CallbackList::iterator it = mCallbacks.begin();
3246 while (it != mCallbacks.end())
3247 (*it++)->OnParallelPortChange (aParallelPort);
3248 }
3249
3250 LogFlowThisFunc (("Leaving rc=%#x\n", rc));
3251 return rc;
3252}
3253
3254/**
3255 * Called by IInternalSessionControl::OnVRDPServerChange().
3256 *
3257 * @note Locks this object for writing.
3258 */
3259HRESULT Console::onVRDPServerChange()
3260{
3261 AutoCaller autoCaller (this);
3262 AssertComRCReturnRC (autoCaller.rc());
3263
3264 AutoWriteLock alock (this);
3265
3266 HRESULT rc = S_OK;
3267
3268 if (mVRDPServer && mMachineState == MachineState_Running)
3269 {
3270 BOOL vrdpEnabled = FALSE;
3271
3272 rc = mVRDPServer->COMGETTER(Enabled) (&vrdpEnabled);
3273 ComAssertComRCRetRC (rc);
3274
3275 if (vrdpEnabled)
3276 {
3277 // If there was no VRDP server started the 'stop' will do nothing.
3278 // However if a server was started and this notification was called,
3279 // we have to restart the server.
3280 mConsoleVRDPServer->Stop ();
3281
3282 if (VBOX_FAILURE(mConsoleVRDPServer->Launch ()))
3283 {
3284 rc = E_FAIL;
3285 }
3286 else
3287 {
3288 mConsoleVRDPServer->EnableConnections ();
3289 }
3290 }
3291 else
3292 {
3293 mConsoleVRDPServer->Stop ();
3294 }
3295 }
3296
3297 /* notify console callbacks on success */
3298 if (SUCCEEDED (rc))
3299 {
3300 CallbackList::iterator it = mCallbacks.begin();
3301 while (it != mCallbacks.end())
3302 (*it++)->OnVRDPServerChange();
3303 }
3304
3305 return rc;
3306}
3307
3308/**
3309 * Called by IInternalSessionControl::OnUSBControllerChange().
3310 *
3311 * @note Locks this object for writing.
3312 */
3313HRESULT Console::onUSBControllerChange()
3314{
3315 LogFlowThisFunc (("\n"));
3316
3317 AutoCaller autoCaller (this);
3318 AssertComRCReturnRC (autoCaller.rc());
3319
3320 AutoWriteLock alock (this);
3321
3322 /* Ignore if no VM is running yet. */
3323 if (!mpVM)
3324 return S_OK;
3325
3326 HRESULT rc = S_OK;
3327
3328/// @todo (dmik)
3329// check for the Enabled state and disable virtual USB controller??
3330// Anyway, if we want to query the machine's USB Controller we need to cache
3331// it to to mUSBController in #init() (as it is done with mDVDDrive).
3332//
3333// bird: While the VM supports hot-plugging, I doubt any guest can handle it at this time... :-)
3334//
3335// /* protect mpVM */
3336// AutoVMCaller autoVMCaller (this);
3337// CheckComRCReturnRC (autoVMCaller.rc());
3338
3339 /* notify console callbacks on success */
3340 if (SUCCEEDED (rc))
3341 {
3342 CallbackList::iterator it = mCallbacks.begin();
3343 while (it != mCallbacks.end())
3344 (*it++)->OnUSBControllerChange();
3345 }
3346
3347 return rc;
3348}
3349
3350/**
3351 * Called by IInternalSessionControl::OnSharedFolderChange().
3352 *
3353 * @note Locks this object for writing.
3354 */
3355HRESULT Console::onSharedFolderChange (BOOL aGlobal)
3356{
3357 LogFlowThisFunc (("aGlobal=%RTbool\n", aGlobal));
3358
3359 AutoCaller autoCaller (this);
3360 AssertComRCReturnRC (autoCaller.rc());
3361
3362 AutoWriteLock alock (this);
3363
3364 HRESULT rc = fetchSharedFolders (aGlobal);
3365
3366 /* notify console callbacks on success */
3367 if (SUCCEEDED (rc))
3368 {
3369 CallbackList::iterator it = mCallbacks.begin();
3370 while (it != mCallbacks.end())
3371 (*it++)->OnSharedFolderChange (aGlobal ? (Scope_T) Scope_Global
3372 : (Scope_T) Scope_Machine);
3373 }
3374
3375 return rc;
3376}
3377
3378/**
3379 * Called by IInternalSessionControl::OnUSBDeviceAttach() or locally by
3380 * processRemoteUSBDevices() after IInternalMachineControl::RunUSBDeviceFilters()
3381 * returns TRUE for a given remote USB device.
3382 *
3383 * @return S_OK if the device was attached to the VM.
3384 * @return failure if not attached.
3385 *
3386 * @param aDevice
3387 * The device in question.
3388 * @param aMaskedIfs
3389 * The interfaces to hide from the guest.
3390 *
3391 * @note Locks this object for writing.
3392 */
3393HRESULT Console::onUSBDeviceAttach (IUSBDevice *aDevice, IVirtualBoxErrorInfo *aError, ULONG aMaskedIfs)
3394{
3395#ifdef VBOX_WITH_USB
3396 LogFlowThisFunc (("aDevice=%p aError=%p\n", aDevice, aError));
3397
3398 AutoCaller autoCaller (this);
3399 ComAssertComRCRetRC (autoCaller.rc());
3400
3401 AutoWriteLock alock (this);
3402
3403 /* protect mpVM (we don't need error info, since it's a callback) */
3404 AutoVMCallerQuiet autoVMCaller (this);
3405 if (FAILED (autoVMCaller.rc()))
3406 {
3407 /* The VM may be no more operational when this message arrives
3408 * (e.g. it may be Saving or Stopping or just PoweredOff) --
3409 * autoVMCaller.rc() will return a failure in this case. */
3410 LogFlowThisFunc (("Attach request ignored (mMachineState=%d).\n",
3411 mMachineState));
3412 return autoVMCaller.rc();
3413 }
3414
3415 if (aError != NULL)
3416 {
3417 /* notify callbacks about the error */
3418 onUSBDeviceStateChange (aDevice, true /* aAttached */, aError);
3419 return S_OK;
3420 }
3421
3422 /* Don't proceed unless there's at least one USB hub. */
3423 if (!PDMR3USBHasHub (mpVM))
3424 {
3425 LogFlowThisFunc (("Attach request ignored (no USB controller).\n"));
3426 return E_FAIL;
3427 }
3428
3429 HRESULT rc = attachUSBDevice (aDevice, aMaskedIfs);
3430 if (FAILED (rc))
3431 {
3432 /* take the current error info */
3433 com::ErrorInfoKeeper eik;
3434 /* the error must be a VirtualBoxErrorInfo instance */
3435 ComPtr <IVirtualBoxErrorInfo> error = eik.takeError();
3436 Assert (!error.isNull());
3437 if (!error.isNull())
3438 {
3439 /* notify callbacks about the error */
3440 onUSBDeviceStateChange (aDevice, true /* aAttached */, error);
3441 }
3442 }
3443
3444 return rc;
3445
3446#else /* !VBOX_WITH_USB */
3447 return E_FAIL;
3448#endif /* !VBOX_WITH_USB */
3449}
3450
3451/**
3452 * Called by IInternalSessionControl::OnUSBDeviceDetach() and locally by
3453 * processRemoteUSBDevices().
3454 *
3455 * @note Locks this object for writing.
3456 */
3457HRESULT Console::onUSBDeviceDetach (INPTR GUIDPARAM aId,
3458 IVirtualBoxErrorInfo *aError)
3459{
3460#ifdef VBOX_WITH_USB
3461 Guid Uuid (aId);
3462 LogFlowThisFunc (("aId={%Vuuid} aError=%p\n", Uuid.raw(), aError));
3463
3464 AutoCaller autoCaller (this);
3465 AssertComRCReturnRC (autoCaller.rc());
3466
3467 AutoWriteLock alock (this);
3468
3469 /* Find the device. */
3470 ComObjPtr <OUSBDevice> device;
3471 USBDeviceList::iterator it = mUSBDevices.begin();
3472 while (it != mUSBDevices.end())
3473 {
3474 LogFlowThisFunc (("it={%Vuuid}\n", (*it)->id().raw()));
3475 if ((*it)->id() == Uuid)
3476 {
3477 device = *it;
3478 break;
3479 }
3480 ++ it;
3481 }
3482
3483
3484 if (device.isNull())
3485 {
3486 LogFlowThisFunc (("USB device not found.\n"));
3487
3488 /* The VM may be no more operational when this message arrives
3489 * (e.g. it may be Saving or Stopping or just PoweredOff). Use
3490 * AutoVMCaller to detect it -- AutoVMCaller::rc() will return a
3491 * failure in this case. */
3492
3493 AutoVMCallerQuiet autoVMCaller (this);
3494 if (FAILED (autoVMCaller.rc()))
3495 {
3496 LogFlowThisFunc (("Detach request ignored (mMachineState=%d).\n",
3497 mMachineState));
3498 return autoVMCaller.rc();
3499 }
3500
3501 /* the device must be in the list otherwise */
3502 AssertFailedReturn (E_FAIL);
3503 }
3504
3505 if (aError != NULL)
3506 {
3507 /* notify callback about an error */
3508 onUSBDeviceStateChange (device, false /* aAttached */, aError);
3509 return S_OK;
3510 }
3511
3512 HRESULT rc = detachUSBDevice (it);
3513
3514 if (FAILED (rc))
3515 {
3516 /* take the current error info */
3517 com::ErrorInfoKeeper eik;
3518 /* the error must be a VirtualBoxErrorInfo instance */
3519 ComPtr <IVirtualBoxErrorInfo> error = eik.takeError();
3520 Assert (!error.isNull());
3521 if (!error.isNull())
3522 {
3523 /* notify callbacks about the error */
3524 onUSBDeviceStateChange (device, false /* aAttached */, error);
3525 }
3526 }
3527
3528 return rc;
3529
3530#else /* !VBOX_WITH_USB */
3531 return E_FAIL;
3532#endif /* !VBOX_WITH_USB */
3533}
3534
3535/**
3536 * @note Temporarily locks this object for writing.
3537 */
3538HRESULT Console::getGuestProperty (INPTR BSTR aKey, BSTR *aValue)
3539{
3540#if !defined (VBOX_WITH_GUEST_PROPS)
3541 return E_NOTIMPL;
3542#else
3543 if (!VALID_PTR (aKey))
3544 return E_INVALIDARG;
3545 if (!VALID_PTR (aValue))
3546 return E_POINTER;
3547
3548 AutoCaller autoCaller (this);
3549 AssertComRCReturnRC (autoCaller.rc());
3550
3551 /* protect mpVM (if not NULL) */
3552 AutoVMCallerWeak autoVMCaller (this);
3553 CheckComRCReturnRC (autoVMCaller.rc());
3554
3555 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
3556 * autoVMCaller, so there is no need to hold a lock of this */
3557
3558 HRESULT rc = E_UNEXPECTED;
3559 using namespace guestProp;
3560
3561 VBOXHGCMSVCPARM parm[3];
3562 Utf8Str Utf8Key = aKey;
3563 Utf8Str Utf8Value (MAX_VALUE_LEN + 1);
3564
3565 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
3566 /* To save doing a const cast, we use the mutableRaw() member. */
3567 parm[0].u.pointer.addr = Utf8Key.mutableRaw();
3568 /* The + 1 is the null terminator */
3569 parm[0].u.pointer.size = Utf8Key.length() + 1;
3570 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
3571 parm[1].u.pointer.addr = Utf8Value.mutableRaw();
3572 parm[1].u.pointer.size = MAX_VALUE_LEN + 1;
3573 int vrc = mVMMDev->hgcmHostCall ("VBoxGuestPropSvc", GET_CONFIG_KEY_HOST,
3574 3, &parm[0]);
3575 /* The returned string should never be able to be greater than our buffer */
3576 AssertLogRel (vrc != VERR_BUFFER_OVERFLOW);
3577 if (RT_SUCCESS (vrc) || (VERR_NOT_FOUND == vrc))
3578 {
3579 rc = S_OK;
3580 if (vrc != VERR_NOT_FOUND)
3581 Utf8Value.cloneTo (aValue);
3582 else
3583 aValue = NULL;
3584 }
3585 else
3586 rc = setError (E_UNEXPECTED,
3587 tr ("Failed to call the VBoxGuestPropSvc service (%Rrc)"), vrc);
3588 return rc;
3589#endif /* else !defined (VBOX_WITH_GUEST_PROPS) */
3590}
3591
3592/**
3593 * @note Temporarily locks this object for writing.
3594 */
3595HRESULT Console::setGuestProperty (INPTR BSTR aKey, INPTR BSTR aValue)
3596{
3597#if !defined (VBOX_WITH_GUEST_PROPS)
3598 return E_NOTIMPL;
3599#else
3600 if (!VALID_PTR (aKey))
3601 return E_INVALIDARG;
3602 if ((aValue != NULL) && !VALID_PTR (aValue))
3603 return E_INVALIDARG;
3604
3605 AutoCaller autoCaller (this);
3606 AssertComRCReturnRC (autoCaller.rc());
3607
3608 /* protect mpVM (if not NULL) */
3609 AutoVMCallerWeak autoVMCaller (this);
3610 CheckComRCReturnRC (autoVMCaller.rc());
3611
3612 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
3613 * autoVMCaller, so there is no need to hold a lock of this */
3614
3615 HRESULT rc = E_UNEXPECTED;
3616 using namespace guestProp;
3617
3618 VBOXHGCMSVCPARM parm[2];
3619 Utf8Str Utf8Key = aKey;
3620 int vrc = VINF_SUCCESS;
3621
3622 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
3623 /* To save doing a const cast, we use the mutableRaw() member. */
3624 parm[0].u.pointer.addr = Utf8Key.mutableRaw();
3625 /* The + 1 is the null terminator */
3626 parm[0].u.pointer.size = Utf8Key.length() + 1;
3627 if (aValue != NULL)
3628 {
3629 Utf8Str Utf8Value = aValue;
3630 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
3631 /* To save doing a const cast, we use the mutableRaw() member. */
3632 parm[1].u.pointer.addr = Utf8Value.mutableRaw();
3633 /* The + 1 is the null terminator */
3634 parm[1].u.pointer.size = Utf8Value.length() + 1;
3635 vrc = mVMMDev->hgcmHostCall ("VBoxGuestPropSvc", SET_CONFIG_KEY_HOST,
3636 2, &parm[0]);
3637 }
3638 else
3639 vrc = mVMMDev->hgcmHostCall ("VBoxGuestPropSvc", DEL_CONFIG_KEY_HOST,
3640 1, &parm[0]);
3641 if (RT_SUCCESS (vrc))
3642 rc = S_OK;
3643 else
3644 rc = setError (E_UNEXPECTED,
3645 tr ("Failed to call the VBoxGuestPropSvc service (%Rrc)"), vrc);
3646 return rc;
3647#endif /* else !defined (VBOX_WITH_GUEST_PROPS) */
3648}
3649
3650/**
3651 * Gets called by Session::UpdateMachineState()
3652 * (IInternalSessionControl::updateMachineState()).
3653 *
3654 * Must be called only in certain cases (see the implementation).
3655 *
3656 * @note Locks this object for writing.
3657 */
3658HRESULT Console::updateMachineState (MachineState_T aMachineState)
3659{
3660 AutoCaller autoCaller (this);
3661 AssertComRCReturnRC (autoCaller.rc());
3662
3663 AutoWriteLock alock (this);
3664
3665 AssertReturn (mMachineState == MachineState_Saving ||
3666 mMachineState == MachineState_Discarding,
3667 E_FAIL);
3668
3669 return setMachineStateLocally (aMachineState);
3670}
3671
3672/**
3673 * @note Locks this object for writing.
3674 */
3675void Console::onMousePointerShapeChange(bool fVisible, bool fAlpha,
3676 uint32_t xHot, uint32_t yHot,
3677 uint32_t width, uint32_t height,
3678 void *pShape)
3679{
3680#if 0
3681 LogFlowThisFuncEnter();
3682 LogFlowThisFunc (("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, "
3683 "height=%d, shape=%p\n",
3684 fVisible, fAlpha, xHot, yHot, width, height, pShape));
3685#endif
3686
3687 AutoCaller autoCaller (this);
3688 AssertComRCReturnVoid (autoCaller.rc());
3689
3690 /* We need a write lock because we alter the cached callback data */
3691 AutoWriteLock alock (this);
3692
3693 /* Save the callback arguments */
3694 mCallbackData.mpsc.visible = fVisible;
3695 mCallbackData.mpsc.alpha = fAlpha;
3696 mCallbackData.mpsc.xHot = xHot;
3697 mCallbackData.mpsc.yHot = yHot;
3698 mCallbackData.mpsc.width = width;
3699 mCallbackData.mpsc.height = height;
3700
3701 /* start with not valid */
3702 bool wasValid = mCallbackData.mpsc.valid;
3703 mCallbackData.mpsc.valid = false;
3704
3705 if (pShape != NULL)
3706 {
3707 size_t cb = (width + 7) / 8 * height; /* size of the AND mask */
3708 cb = ((cb + 3) & ~3) + width * 4 * height; /* + gap + size of the XOR mask */
3709 /* try to reuse the old shape buffer if the size is the same */
3710 if (!wasValid)
3711 mCallbackData.mpsc.shape = NULL;
3712 else
3713 if (mCallbackData.mpsc.shape != NULL && mCallbackData.mpsc.shapeSize != cb)
3714 {
3715 RTMemFree (mCallbackData.mpsc.shape);
3716 mCallbackData.mpsc.shape = NULL;
3717 }
3718 if (mCallbackData.mpsc.shape == NULL)
3719 {
3720 mCallbackData.mpsc.shape = (BYTE *) RTMemAllocZ (cb);
3721 AssertReturnVoid (mCallbackData.mpsc.shape);
3722 }
3723 mCallbackData.mpsc.shapeSize = cb;
3724 memcpy (mCallbackData.mpsc.shape, pShape, cb);
3725 }
3726 else
3727 {
3728 if (wasValid && mCallbackData.mpsc.shape != NULL)
3729 RTMemFree (mCallbackData.mpsc.shape);
3730 mCallbackData.mpsc.shape = NULL;
3731 mCallbackData.mpsc.shapeSize = 0;
3732 }
3733
3734 mCallbackData.mpsc.valid = true;
3735
3736 CallbackList::iterator it = mCallbacks.begin();
3737 while (it != mCallbacks.end())
3738 (*it++)->OnMousePointerShapeChange (fVisible, fAlpha, xHot, yHot,
3739 width, height, (BYTE *) pShape);
3740
3741#if 0
3742 LogFlowThisFuncLeave();
3743#endif
3744}
3745
3746/**
3747 * @note Locks this object for writing.
3748 */
3749void Console::onMouseCapabilityChange (BOOL supportsAbsolute, BOOL needsHostCursor)
3750{
3751 LogFlowThisFunc (("supportsAbsolute=%d needsHostCursor=%d\n",
3752 supportsAbsolute, needsHostCursor));
3753
3754 AutoCaller autoCaller (this);
3755 AssertComRCReturnVoid (autoCaller.rc());
3756
3757 /* We need a write lock because we alter the cached callback data */
3758 AutoWriteLock alock (this);
3759
3760 /* save the callback arguments */
3761 mCallbackData.mcc.supportsAbsolute = supportsAbsolute;
3762 mCallbackData.mcc.needsHostCursor = needsHostCursor;
3763 mCallbackData.mcc.valid = true;
3764
3765 CallbackList::iterator it = mCallbacks.begin();
3766 while (it != mCallbacks.end())
3767 {
3768 Log2(("Console::onMouseCapabilityChange: calling %p\n", (void*)*it));
3769 (*it++)->OnMouseCapabilityChange (supportsAbsolute, needsHostCursor);
3770 }
3771}
3772
3773/**
3774 * @note Locks this object for reading.
3775 */
3776void Console::onStateChange (MachineState_T machineState)
3777{
3778 AutoCaller autoCaller (this);
3779 AssertComRCReturnVoid (autoCaller.rc());
3780
3781 AutoReadLock alock (this);
3782
3783 CallbackList::iterator it = mCallbacks.begin();
3784 while (it != mCallbacks.end())
3785 (*it++)->OnStateChange (machineState);
3786}
3787
3788/**
3789 * @note Locks this object for reading.
3790 */
3791void Console::onAdditionsStateChange()
3792{
3793 AutoCaller autoCaller (this);
3794 AssertComRCReturnVoid (autoCaller.rc());
3795
3796 AutoReadLock alock (this);
3797
3798 CallbackList::iterator it = mCallbacks.begin();
3799 while (it != mCallbacks.end())
3800 (*it++)->OnAdditionsStateChange();
3801}
3802
3803/**
3804 * @note Locks this object for reading.
3805 */
3806void Console::onAdditionsOutdated()
3807{
3808 AutoCaller autoCaller (this);
3809 AssertComRCReturnVoid (autoCaller.rc());
3810
3811 AutoReadLock alock (this);
3812
3813 /** @todo Use the On-Screen Display feature to report the fact.
3814 * The user should be told to install additions that are
3815 * provided with the current VBox build:
3816 * VBOX_VERSION_MAJOR.VBOX_VERSION_MINOR.VBOX_VERSION_BUILD
3817 */
3818}
3819
3820/**
3821 * @note Locks this object for writing.
3822 */
3823void Console::onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
3824{
3825 AutoCaller autoCaller (this);
3826 AssertComRCReturnVoid (autoCaller.rc());
3827
3828 /* We need a write lock because we alter the cached callback data */
3829 AutoWriteLock alock (this);
3830
3831 /* save the callback arguments */
3832 mCallbackData.klc.numLock = fNumLock;
3833 mCallbackData.klc.capsLock = fCapsLock;
3834 mCallbackData.klc.scrollLock = fScrollLock;
3835 mCallbackData.klc.valid = true;
3836
3837 CallbackList::iterator it = mCallbacks.begin();
3838 while (it != mCallbacks.end())
3839 (*it++)->OnKeyboardLedsChange(fNumLock, fCapsLock, fScrollLock);
3840}
3841
3842/**
3843 * @note Locks this object for reading.
3844 */
3845void Console::onUSBDeviceStateChange (IUSBDevice *aDevice, bool aAttached,
3846 IVirtualBoxErrorInfo *aError)
3847{
3848 AutoCaller autoCaller (this);
3849 AssertComRCReturnVoid (autoCaller.rc());
3850
3851 AutoReadLock alock (this);
3852
3853 CallbackList::iterator it = mCallbacks.begin();
3854 while (it != mCallbacks.end())
3855 (*it++)->OnUSBDeviceStateChange (aDevice, aAttached, aError);
3856}
3857
3858/**
3859 * @note Locks this object for reading.
3860 */
3861void Console::onRuntimeError (BOOL aFatal, INPTR BSTR aErrorID, INPTR BSTR aMessage)
3862{
3863 AutoCaller autoCaller (this);
3864 AssertComRCReturnVoid (autoCaller.rc());
3865
3866 AutoReadLock alock (this);
3867
3868 CallbackList::iterator it = mCallbacks.begin();
3869 while (it != mCallbacks.end())
3870 (*it++)->OnRuntimeError (aFatal, aErrorID, aMessage);
3871}
3872
3873/**
3874 * @note Locks this object for reading.
3875 */
3876HRESULT Console::onShowWindow (BOOL aCheck, BOOL *aCanShow, ULONG64 *aWinId)
3877{
3878 AssertReturn (aCanShow, E_POINTER);
3879 AssertReturn (aWinId, E_POINTER);
3880
3881 *aCanShow = FALSE;
3882 *aWinId = 0;
3883
3884 AutoCaller autoCaller (this);
3885 AssertComRCReturnRC (autoCaller.rc());
3886
3887 AutoReadLock alock (this);
3888
3889 HRESULT rc = S_OK;
3890 CallbackList::iterator it = mCallbacks.begin();
3891
3892 if (aCheck)
3893 {
3894 while (it != mCallbacks.end())
3895 {
3896 BOOL canShow = FALSE;
3897 rc = (*it++)->OnCanShowWindow (&canShow);
3898 AssertComRC (rc);
3899 if (FAILED (rc) || !canShow)
3900 return rc;
3901 }
3902 *aCanShow = TRUE;
3903 }
3904 else
3905 {
3906 while (it != mCallbacks.end())
3907 {
3908 ULONG64 winId = 0;
3909 rc = (*it++)->OnShowWindow (&winId);
3910 AssertComRC (rc);
3911 if (FAILED (rc))
3912 return rc;
3913 /* only one callback may return non-null winId */
3914 Assert (*aWinId == 0 || winId == 0);
3915 if (*aWinId == 0)
3916 *aWinId = winId;
3917 }
3918 }
3919
3920 return S_OK;
3921}
3922
3923// private methods
3924////////////////////////////////////////////////////////////////////////////////
3925
3926/**
3927 * Increases the usage counter of the mpVM pointer. Guarantees that
3928 * VMR3Destroy() will not be called on it at least until releaseVMCaller()
3929 * is called.
3930 *
3931 * If this method returns a failure, the caller is not allowed to use mpVM
3932 * and may return the failed result code to the upper level. This method sets
3933 * the extended error info on failure if \a aQuiet is false.
3934 *
3935 * Setting \a aQuiet to true is useful for methods that don't want to return
3936 * the failed result code to the caller when this method fails (e.g. need to
3937 * silently check for the mpVM avaliability).
3938 *
3939 * When mpVM is NULL but \a aAllowNullVM is true, a corresponding error will be
3940 * returned instead of asserting. Having it false is intended as a sanity check
3941 * for methods that have checked mMachineState and expect mpVM *NOT* to be NULL.
3942 *
3943 * @param aQuiet true to suppress setting error info
3944 * @param aAllowNullVM true to accept mpVM being NULL and return a failure
3945 * (otherwise this method will assert if mpVM is NULL)
3946 *
3947 * @note Locks this object for writing.
3948 */
3949HRESULT Console::addVMCaller (bool aQuiet /* = false */,
3950 bool aAllowNullVM /* = false */)
3951{
3952 AutoCaller autoCaller (this);
3953 AssertComRCReturnRC (autoCaller.rc());
3954
3955 AutoWriteLock alock (this);
3956
3957 if (mVMDestroying)
3958 {
3959 /* powerDown() is waiting for all callers to finish */
3960 return aQuiet ? E_ACCESSDENIED : setError (E_ACCESSDENIED,
3961 tr ("Virtual machine is being powered down"));
3962 }
3963
3964 if (mpVM == NULL)
3965 {
3966 Assert (aAllowNullVM == true);
3967
3968 /* The machine is not powered up */
3969 return aQuiet ? E_ACCESSDENIED : setError (E_ACCESSDENIED,
3970 tr ("Virtual machine is not powered up"));
3971 }
3972
3973 ++ mVMCallers;
3974
3975 return S_OK;
3976}
3977
3978/**
3979 * Decreases the usage counter of the mpVM pointer. Must always complete
3980 * the addVMCaller() call after the mpVM pointer is no more necessary.
3981 *
3982 * @note Locks this object for writing.
3983 */
3984void Console::releaseVMCaller()
3985{
3986 AutoCaller autoCaller (this);
3987 AssertComRCReturnVoid (autoCaller.rc());
3988
3989 AutoWriteLock alock (this);
3990
3991 AssertReturnVoid (mpVM != NULL);
3992
3993 Assert (mVMCallers > 0);
3994 -- mVMCallers;
3995
3996 if (mVMCallers == 0 && mVMDestroying)
3997 {
3998 /* inform powerDown() there are no more callers */
3999 RTSemEventSignal (mVMZeroCallersSem);
4000 }
4001}
4002
4003/**
4004 * Initialize the release logging facility. In case something
4005 * goes wrong, there will be no release logging. Maybe in the future
4006 * we can add some logic to use different file names in this case.
4007 * Note that the logic must be in sync with Machine::DeleteSettings().
4008 */
4009HRESULT Console::consoleInitReleaseLog (const ComPtr <IMachine> aMachine)
4010{
4011 HRESULT hrc = S_OK;
4012
4013 Bstr logFolder;
4014 hrc = aMachine->COMGETTER(LogFolder) (logFolder.asOutParam());
4015 CheckComRCReturnRC (hrc);
4016
4017 Utf8Str logDir = logFolder;
4018
4019 /* make sure the Logs folder exists */
4020 Assert (!logDir.isEmpty());
4021 if (!RTDirExists (logDir))
4022 RTDirCreateFullPath (logDir, 0777);
4023
4024 Utf8Str logFile = Utf8StrFmt ("%s%cVBox.log",
4025 logDir.raw(), RTPATH_DELIMITER);
4026 Utf8Str pngFile = Utf8StrFmt ("%s%cVBox.png",
4027 logDir.raw(), RTPATH_DELIMITER);
4028
4029 /*
4030 * Age the old log files
4031 * Rename .(n-1) to .(n), .(n-2) to .(n-1), ..., and the last log file to .1
4032 * Overwrite target files in case they exist.
4033 */
4034 ComPtr<IVirtualBox> virtualBox;
4035 aMachine->COMGETTER(Parent)(virtualBox.asOutParam());
4036 ComPtr <ISystemProperties> systemProperties;
4037 virtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam());
4038 ULONG uLogHistoryCount = 3;
4039 systemProperties->COMGETTER(LogHistoryCount)(&uLogHistoryCount);
4040 if (uLogHistoryCount)
4041 {
4042 for (int i = uLogHistoryCount-1; i >= 0; i--)
4043 {
4044 Utf8Str *files[] = { &logFile, &pngFile };
4045 Utf8Str oldName, newName;
4046
4047 for (unsigned int j = 0; j < ELEMENTS (files); ++ j)
4048 {
4049 if (i > 0)
4050 oldName = Utf8StrFmt ("%s.%d", files [j]->raw(), i);
4051 else
4052 oldName = *files [j];
4053 newName = Utf8StrFmt ("%s.%d", files [j]->raw(), i + 1);
4054 /* If the old file doesn't exist, delete the new file (if it
4055 * exists) to provide correct rotation even if the sequence is
4056 * broken */
4057 if ( RTFileRename (oldName, newName, RTFILEMOVE_FLAGS_REPLACE)
4058 == VERR_FILE_NOT_FOUND)
4059 RTFileDelete (newName);
4060 }
4061 }
4062 }
4063
4064 PRTLOGGER loggerRelease;
4065 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
4066 RTUINT fFlags = RTLOGFLAGS_PREFIX_TIME_PROG;
4067#if defined (RT_OS_WINDOWS) || defined (RT_OS_OS2)
4068 fFlags |= RTLOGFLAGS_USECRLF;
4069#endif
4070 char szError[RTPATH_MAX + 128] = "";
4071 int vrc = RTLogCreateEx(&loggerRelease, fFlags, "all",
4072 "VBOX_RELEASE_LOG", RT_ELEMENTS(s_apszGroups), s_apszGroups,
4073 RTLOGDEST_FILE, szError, sizeof(szError), logFile.raw());
4074 if (RT_SUCCESS(vrc))
4075 {
4076 /* some introductory information */
4077 RTTIMESPEC timeSpec;
4078 char nowUct[64];
4079 RTTimeSpecToString(RTTimeNow(&timeSpec), nowUct, sizeof(nowUct));
4080 RTLogRelLogger(loggerRelease, 0, ~0U,
4081 "VirtualBox %s r%d %s (%s %s) release log\n"
4082 "Log opened %s\n",
4083 VBOX_VERSION_STRING, VBoxSVNRev (), VBOX_BUILD_TARGET,
4084 __DATE__, __TIME__, nowUct);
4085
4086 /* register this logger as the release logger */
4087 RTLogRelSetDefaultInstance(loggerRelease);
4088 hrc = S_OK;
4089 }
4090 else
4091 hrc = setError (E_FAIL,
4092 tr ("Failed to open release log (%s, %Rrc)"), szError, vrc);
4093
4094 return hrc;
4095}
4096
4097
4098/**
4099 * Internal power off worker routine.
4100 *
4101 * This method may be called only at certain places with the folliwing meaning
4102 * as shown below:
4103 *
4104 * - if the machine state is either Running or Paused, a normal
4105 * Console-initiated powerdown takes place (e.g. PowerDown());
4106 * - if the machine state is Saving, saveStateThread() has successfully
4107 * done its job;
4108 * - if the machine state is Starting or Restoring, powerUpThread() has
4109 * failed to start/load the VM;
4110 * - if the machine state is Stopping, the VM has powered itself off
4111 * (i.e. not as a result of the powerDown() call).
4112 *
4113 * Calling it in situations other than the above will cause unexpected
4114 * behavior.
4115 *
4116 * Note that this method should be the only one that destroys mpVM and sets
4117 * it to NULL.
4118 *
4119 * @note Locks this object for writing.
4120 *
4121 * @note Never call this method from a thread that called addVMCaller() or
4122 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
4123 * release(). Otherwise it will deadlock.
4124 */
4125HRESULT Console::powerDown()
4126{
4127 LogFlowThisFuncEnter();
4128
4129 AutoCaller autoCaller (this);
4130 AssertComRCReturnRC (autoCaller.rc());
4131
4132 AutoWriteLock alock (this);
4133 int vrc = VINF_SUCCESS;
4134
4135 /* sanity */
4136 AssertReturn (mVMDestroying == false, E_FAIL);
4137
4138 LogRel (("Console::powerDown(): a request to power off the VM has been issued "
4139 "(mMachineState=%d, InUninit=%d)\n",
4140 mMachineState, autoCaller.state() == InUninit));
4141
4142 /*
4143 * Stop the VRDP server to prevent new clients connection while VM is being powered off.
4144 */
4145 if (mConsoleVRDPServer)
4146 {
4147 LogFlowThisFunc (("Stopping VRDP server...\n"));
4148
4149 /* Leave the lock since EMT will call us back as addVMCaller in updateDisplayData(). */
4150 alock.leave();
4151
4152 mConsoleVRDPServer->Stop();
4153
4154 alock.enter();
4155 }
4156
4157
4158#ifdef VBOX_HGCM
4159 /*
4160 * Shutdown HGCM services before stopping the guest, because they might need a cleanup.
4161 */
4162 if (mVMMDev)
4163 {
4164 LogFlowThisFunc (("Shutdown HGCM...\n"));
4165
4166 /* Leave the lock. */
4167 alock.leave();
4168
4169 mVMMDev->hgcmShutdown ();
4170
4171 alock.enter();
4172 }
4173# ifdef VBOX_WITH_GUEST_PROPS
4174 /* Save all guest/host property store entries to the machine XML
4175 * file as extra data. */
4176 PCFGMNODE pRegistry = CFGMR3GetChild (CFGMR3GetRoot (mpVM), "Guest/Registry/");
4177 PCFGMLEAF pValue = CFGMR3GetFirstValue (pRegistry);
4178 vrc = VINF_SUCCESS;
4179 while (pValue != NULL && RT_SUCCESS(vrc))
4180 {
4181 using namespace guestProp;
4182 char szKeyName[MAX_NAME_LEN + 1];
4183 char szKeyValue[MAX_VALUE_LEN + 1];
4184 char szExtraDataName[VBOX_SHARED_INFO_PREFIX_LEN + MAX_NAME_LEN + 1];
4185 vrc = CFGMR3GetValueName (pValue, szKeyName, sizeof(szKeyName));
4186 if (RT_SUCCESS(vrc))
4187 vrc = CFGMR3QueryString (pRegistry, szKeyName, szKeyValue, sizeof(szKeyValue));
4188 if (RT_SUCCESS(vrc))
4189 {
4190 strcpy(szExtraDataName, VBOX_SHARED_INFO_KEY_PREFIX);
4191 strncpy(szExtraDataName + VBOX_SHARED_INFO_PREFIX_LEN, szKeyName, sizeof(szKeyName));
4192 szExtraDataName[sizeof(szExtraDataName) - 1] = 0;
4193 }
4194 if (RT_SUCCESS(vrc))
4195 if (FAILED(mMachine->SetExtraData(Bstr(szExtraDataName).raw(), Bstr(szKeyValue).raw())))
4196 vrc = VERR_UNRESOLVED_ERROR; /* We only need to know that we have to stop. */
4197 if (RT_SUCCESS(vrc))
4198 pValue = CFGMR3GetNextValue (pValue);
4199 }
4200 /* In a second stage, we remove any extra data keys corresponding to
4201 * properties which aren't in the CFGM node. */
4202 Bstr strExtraDataKey;
4203 for (;;)
4204 {
4205 using namespace guestProp;
4206 Bstr strNextExtraDataKey;
4207 Bstr strExtraDataValue;
4208
4209 /* get the next key */
4210 int hrc = mMachine->GetNextExtraDataKey(strExtraDataKey, strNextExtraDataKey.asOutParam(),
4211 strExtraDataValue.asOutParam());
4212
4213 /* stop if for some reason there's nothing more to request */
4214 if (FAILED(hrc) || !strNextExtraDataKey)
4215 break;
4216
4217 strExtraDataKey = strNextExtraDataKey;
4218 Utf8Str strExtraDataKeyUtf8 = Utf8Str(strExtraDataKey);
4219
4220 /* we only care about keys starting with VBOX_SHARED_INFO_KEY_PREFIX */
4221 if (strncmp(strExtraDataKeyUtf8.raw(), VBOX_SHARED_INFO_KEY_PREFIX, VBOX_SHARED_INFO_PREFIX_LEN) != 0)
4222 continue;
4223 char *pszCFGMValueName = (char*)strExtraDataKeyUtf8.raw() + VBOX_SHARED_INFO_PREFIX_LEN;
4224
4225 /* Now see if a lookup of the name in the CFGM node succeeds. */
4226 char szKeyValue[MAX_VALUE_LEN + 1];
4227 vrc = CFGMR3QueryString (pRegistry, pszCFGMValueName, szKeyValue, sizeof(szKeyValue));
4228 /* And delete it from the extra data if it failed. */
4229 if (VERR_CFGM_VALUE_NOT_FOUND == vrc)
4230 mMachine->SetExtraData(strExtraDataKey, NULL);
4231 }
4232# endif /* VBOX_WITH_GUEST_PROPS defined */
4233#endif /* VBOX_HGCM */
4234
4235 /* First, wait for all mpVM callers to finish their work if necessary */
4236 if (mVMCallers > 0)
4237 {
4238 /* go to the destroying state to prevent from adding new callers */
4239 mVMDestroying = true;
4240
4241 /* lazy creation */
4242 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
4243 RTSemEventCreate (&mVMZeroCallersSem);
4244
4245 LogFlowThisFunc (("Waiting for mpVM callers (%d) to drop to zero...\n",
4246 mVMCallers));
4247
4248 alock.leave();
4249
4250 RTSemEventWait (mVMZeroCallersSem, RT_INDEFINITE_WAIT);
4251
4252 alock.enter();
4253 }
4254
4255 AssertReturn (mpVM, E_FAIL);
4256
4257 AssertMsg (mMachineState == MachineState_Running ||
4258 mMachineState == MachineState_Paused ||
4259 mMachineState == MachineState_Stuck ||
4260 mMachineState == MachineState_Saving ||
4261 mMachineState == MachineState_Starting ||
4262 mMachineState == MachineState_Restoring ||
4263 mMachineState == MachineState_Stopping,
4264 ("Invalid machine state: %d\n", mMachineState));
4265
4266 HRESULT rc = S_OK;
4267 vrc = VINF_SUCCESS;
4268
4269 /*
4270 * Power off the VM if not already done that. In case of Stopping, the VM
4271 * has powered itself off and notified Console in vmstateChangeCallback().
4272 * In case of Starting or Restoring, powerUpThread() is calling us on
4273 * failure, so the VM is already off at that point.
4274 */
4275 if (mMachineState != MachineState_Stopping &&
4276 mMachineState != MachineState_Starting &&
4277 mMachineState != MachineState_Restoring)
4278 {
4279 /*
4280 * don't go from Saving to Stopping, vmstateChangeCallback needs it
4281 * to set the state to Saved on VMSTATE_TERMINATED.
4282 */
4283 if (mMachineState != MachineState_Saving)
4284 setMachineState (MachineState_Stopping);
4285
4286 LogFlowThisFunc (("Powering off the VM...\n"));
4287
4288 /* Leave the lock since EMT will call us back on VMR3PowerOff() */
4289 alock.leave();
4290
4291 vrc = VMR3PowerOff (mpVM);
4292 /*
4293 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
4294 * VM-(guest-)initiated power off happened in parallel a ms before
4295 * this call. So far, we let this error pop up on the user's side.
4296 */
4297
4298 alock.enter();
4299 }
4300
4301 LogFlowThisFunc (("Ready for VM destruction\n"));
4302
4303 /*
4304 * If we are called from Console::uninit(), then try to destroy the VM
4305 * even on failure (this will most likely fail too, but what to do?..)
4306 */
4307 if (VBOX_SUCCESS (vrc) || autoCaller.state() == InUninit)
4308 {
4309 /* If the machine has an USB comtroller, release all USB devices
4310 * (symmetric to the code in captureUSBDevices()) */
4311 bool fHasUSBController = false;
4312 {
4313 PPDMIBASE pBase;
4314 int vrc = PDMR3QueryLun (mpVM, "usb-ohci", 0, 0, &pBase);
4315 if (VBOX_SUCCESS (vrc))
4316 {
4317 fHasUSBController = true;
4318 detachAllUSBDevices (false /* aDone */);
4319 }
4320 }
4321
4322 /*
4323 * Now we've got to destroy the VM as well. (mpVM is not valid
4324 * beyond this point). We leave the lock before calling VMR3Destroy()
4325 * because it will result into calling destructors of drivers
4326 * associated with Console children which may in turn try to lock
4327 * Console (e.g. by instantiating SafeVMPtr to access mpVM). It's safe
4328 * here because mVMDestroying is set which should prevent any activity.
4329 */
4330
4331 /*
4332 * Set mpVM to NULL early just in case if some old code is not using
4333 * addVMCaller()/releaseVMCaller().
4334 */
4335 PVM pVM = mpVM;
4336 mpVM = NULL;
4337
4338 LogFlowThisFunc (("Destroying the VM...\n"));
4339
4340 alock.leave();
4341
4342 vrc = VMR3Destroy (pVM);
4343
4344 /* take the lock again */
4345 alock.enter();
4346
4347 if (VBOX_SUCCESS (vrc))
4348 {
4349 LogFlowThisFunc (("Machine has been destroyed (mMachineState=%d)\n",
4350 mMachineState));
4351 /*
4352 * Note: the Console-level machine state change happens on the
4353 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
4354 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
4355 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
4356 * occured yet. This is okay, because mMachineState is already
4357 * Stopping in this case, so any other attempt to call PowerDown()
4358 * will be rejected.
4359 */
4360 }
4361 else
4362 {
4363 /* bad bad bad, but what to do? */
4364 mpVM = pVM;
4365 rc = setError (E_FAIL,
4366 tr ("Could not destroy the machine. (Error: %Vrc)"), vrc);
4367 }
4368
4369 /*
4370 * Complete the detaching of the USB devices.
4371 */
4372 if (fHasUSBController)
4373 detachAllUSBDevices (true /* aDone */);
4374 }
4375 else
4376 {
4377 rc = setError (E_FAIL,
4378 tr ("Could not power off the machine. (Error: %Vrc)"), vrc);
4379 }
4380
4381 /*
4382 * Finished with destruction. Note that if something impossible happened
4383 * and we've failed to destroy the VM, mVMDestroying will remain false and
4384 * mMachineState will be something like Stopping, so most Console methods
4385 * will return an error to the caller.
4386 */
4387 if (mpVM == NULL)
4388 mVMDestroying = false;
4389
4390 if (SUCCEEDED (rc))
4391 {
4392 /* uninit dynamically allocated members of mCallbackData */
4393 if (mCallbackData.mpsc.valid)
4394 {
4395 if (mCallbackData.mpsc.shape != NULL)
4396 RTMemFree (mCallbackData.mpsc.shape);
4397 }
4398 memset (&mCallbackData, 0, sizeof (mCallbackData));
4399 }
4400
4401 LogFlowThisFuncLeave();
4402 return rc;
4403}
4404
4405/**
4406 * @note Locks this object for writing.
4407 */
4408HRESULT Console::setMachineState (MachineState_T aMachineState,
4409 bool aUpdateServer /* = true */)
4410{
4411 AutoCaller autoCaller (this);
4412 AssertComRCReturnRC (autoCaller.rc());
4413
4414 AutoWriteLock alock (this);
4415
4416 HRESULT rc = S_OK;
4417
4418 if (mMachineState != aMachineState)
4419 {
4420 LogFlowThisFunc (("machineState=%d\n", aMachineState));
4421 mMachineState = aMachineState;
4422
4423 /// @todo (dmik)
4424 // possibly, we need to redo onStateChange() using the dedicated
4425 // Event thread, like it is done in VirtualBox. This will make it
4426 // much safer (no deadlocks possible if someone tries to use the
4427 // console from the callback), however, listeners will lose the
4428 // ability to synchronously react to state changes (is it really
4429 // necessary??)
4430 LogFlowThisFunc (("Doing onStateChange()...\n"));
4431 onStateChange (aMachineState);
4432 LogFlowThisFunc (("Done onStateChange()\n"));
4433
4434 if (aUpdateServer)
4435 {
4436 /*
4437 * Server notification MUST be done from under the lock; otherwise
4438 * the machine state here and on the server might go out of sync, that
4439 * can lead to various unexpected results (like the machine state being
4440 * >= MachineState_Running on the server, while the session state is
4441 * already SessionState_Closed at the same time there).
4442 *
4443 * Cross-lock conditions should be carefully watched out: calling
4444 * UpdateState we will require Machine and SessionMachine locks
4445 * (remember that here we're holding the Console lock here, and
4446 * also all locks that have been entered by the thread before calling
4447 * this method).
4448 */
4449 LogFlowThisFunc (("Doing mControl->UpdateState()...\n"));
4450 rc = mControl->UpdateState (aMachineState);
4451 LogFlowThisFunc (("mControl->UpdateState()=%08X\n", rc));
4452 }
4453 }
4454
4455 return rc;
4456}
4457
4458/**
4459 * Searches for a shared folder with the given logical name
4460 * in the collection of shared folders.
4461 *
4462 * @param aName logical name of the shared folder
4463 * @param aSharedFolder where to return the found object
4464 * @param aSetError whether to set the error info if the folder is
4465 * not found
4466 * @return
4467 * S_OK when found or E_INVALIDARG when not found
4468 *
4469 * @note The caller must lock this object for writing.
4470 */
4471HRESULT Console::findSharedFolder (const BSTR aName,
4472 ComObjPtr <SharedFolder> &aSharedFolder,
4473 bool aSetError /* = false */)
4474{
4475 /* sanity check */
4476 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
4477
4478 SharedFolderMap::const_iterator it = mSharedFolders.find (aName);
4479 if (it != mSharedFolders.end())
4480 {
4481 aSharedFolder = it->second;
4482 return S_OK;
4483 }
4484
4485 if (aSetError)
4486 setError (E_INVALIDARG,
4487 tr ("Could not find a shared folder named '%ls'."), aName);
4488
4489 return E_INVALIDARG;
4490}
4491
4492/**
4493 * Fetches the list of global or machine shared folders from the server.
4494 *
4495 * @param aGlobal true to fetch global folders.
4496 *
4497 * @note The caller must lock this object for writing.
4498 */
4499HRESULT Console::fetchSharedFolders (BOOL aGlobal)
4500{
4501 /* sanity check */
4502 AssertReturn (AutoCaller (this).state() == InInit ||
4503 isWriteLockOnCurrentThread(), E_FAIL);
4504
4505 /* protect mpVM (if not NULL) */
4506 AutoVMCallerQuietWeak autoVMCaller (this);
4507
4508 HRESULT rc = S_OK;
4509
4510 bool online = mpVM && autoVMCaller.isOk() && mVMMDev->isShFlActive();
4511
4512 if (aGlobal)
4513 {
4514 /// @todo grab & process global folders when they are done
4515 }
4516 else
4517 {
4518 SharedFolderDataMap oldFolders;
4519 if (online)
4520 oldFolders = mMachineSharedFolders;
4521
4522 mMachineSharedFolders.clear();
4523
4524 ComPtr <ISharedFolderCollection> coll;
4525 rc = mMachine->COMGETTER(SharedFolders) (coll.asOutParam());
4526 AssertComRCReturnRC (rc);
4527
4528 ComPtr <ISharedFolderEnumerator> en;
4529 rc = coll->Enumerate (en.asOutParam());
4530 AssertComRCReturnRC (rc);
4531
4532 BOOL hasMore = FALSE;
4533 while (SUCCEEDED (rc = en->HasMore (&hasMore)) && hasMore)
4534 {
4535 ComPtr <ISharedFolder> folder;
4536 rc = en->GetNext (folder.asOutParam());
4537 CheckComRCBreakRC (rc);
4538
4539 Bstr name;
4540 Bstr hostPath;
4541 BOOL writable;
4542
4543 rc = folder->COMGETTER(Name) (name.asOutParam());
4544 CheckComRCBreakRC (rc);
4545 rc = folder->COMGETTER(HostPath) (hostPath.asOutParam());
4546 CheckComRCBreakRC (rc);
4547 rc = folder->COMGETTER(Writable) (&writable);
4548
4549 mMachineSharedFolders.insert (std::make_pair (name, SharedFolderData (hostPath, writable)));
4550
4551 /* send changes to HGCM if the VM is running */
4552 /// @todo report errors as runtime warnings through VMSetError
4553 if (online)
4554 {
4555 SharedFolderDataMap::iterator it = oldFolders.find (name);
4556 if (it == oldFolders.end() || it->second.mHostPath != hostPath)
4557 {
4558 /* a new machine folder is added or
4559 * the existing machine folder is changed */
4560 if (mSharedFolders.find (name) != mSharedFolders.end())
4561 ; /* the console folder exists, nothing to do */
4562 else
4563 {
4564 /* remove the old machhine folder (when changed)
4565 * or the global folder if any (when new) */
4566 if (it != oldFolders.end() ||
4567 mGlobalSharedFolders.find (name) !=
4568 mGlobalSharedFolders.end())
4569 rc = removeSharedFolder (name);
4570 /* create the new machine folder */
4571 rc = createSharedFolder (name, SharedFolderData (hostPath, writable));
4572 }
4573 }
4574 /* forget the processed (or identical) folder */
4575 if (it != oldFolders.end())
4576 oldFolders.erase (it);
4577
4578 rc = S_OK;
4579 }
4580 }
4581
4582 AssertComRCReturnRC (rc);
4583
4584 /* process outdated (removed) folders */
4585 /// @todo report errors as runtime warnings through VMSetError
4586 if (online)
4587 {
4588 for (SharedFolderDataMap::const_iterator it = oldFolders.begin();
4589 it != oldFolders.end(); ++ it)
4590 {
4591 if (mSharedFolders.find (it->first) != mSharedFolders.end())
4592 ; /* the console folder exists, nothing to do */
4593 else
4594 {
4595 /* remove the outdated machine folder */
4596 rc = removeSharedFolder (it->first);
4597 /* create the global folder if there is any */
4598 SharedFolderDataMap::const_iterator git =
4599 mGlobalSharedFolders.find (it->first);
4600 if (git != mGlobalSharedFolders.end())
4601 rc = createSharedFolder (git->first, git->second);
4602 }
4603 }
4604
4605 rc = S_OK;
4606 }
4607 }
4608
4609 return rc;
4610}
4611
4612/**
4613 * Searches for a shared folder with the given name in the list of machine
4614 * shared folders and then in the list of the global shared folders.
4615 *
4616 * @param aName Name of the folder to search for.
4617 * @param aIt Where to store the pointer to the found folder.
4618 * @return @c true if the folder was found and @c false otherwise.
4619 *
4620 * @note The caller must lock this object for reading.
4621 */
4622bool Console::findOtherSharedFolder (INPTR BSTR aName,
4623 SharedFolderDataMap::const_iterator &aIt)
4624{
4625 /* sanity check */
4626 AssertReturn (isWriteLockOnCurrentThread(), false);
4627
4628 /* first, search machine folders */
4629 aIt = mMachineSharedFolders.find (aName);
4630 if (aIt != mMachineSharedFolders.end())
4631 return true;
4632
4633 /* second, search machine folders */
4634 aIt = mGlobalSharedFolders.find (aName);
4635 if (aIt != mGlobalSharedFolders.end())
4636 return true;
4637
4638 return false;
4639}
4640
4641/**
4642 * Calls the HGCM service to add a shared folder definition.
4643 *
4644 * @param aName Shared folder name.
4645 * @param aHostPath Shared folder path.
4646 *
4647 * @note Must be called from under AutoVMCaller and when mpVM != NULL!
4648 * @note Doesn't lock anything.
4649 */
4650HRESULT Console::createSharedFolder (INPTR BSTR aName, SharedFolderData aData)
4651{
4652 ComAssertRet (aName && *aName, E_FAIL);
4653 ComAssertRet (aData.mHostPath, E_FAIL);
4654
4655 /* sanity checks */
4656 AssertReturn (mpVM, E_FAIL);
4657 AssertReturn (mVMMDev->isShFlActive(), E_FAIL);
4658
4659 VBOXHGCMSVCPARM parms[SHFL_CPARMS_ADD_MAPPING];
4660 SHFLSTRING *pFolderName, *pMapName;
4661 size_t cbString;
4662
4663 Log (("Adding shared folder '%ls' -> '%ls'\n", aName, aData.mHostPath.raw()));
4664
4665 cbString = (RTUtf16Len (aData.mHostPath) + 1) * sizeof (RTUTF16);
4666 if (cbString >= UINT16_MAX)
4667 return setError (E_INVALIDARG, tr ("The name is too long"));
4668 pFolderName = (SHFLSTRING *) RTMemAllocZ (sizeof (SHFLSTRING) + cbString);
4669 Assert (pFolderName);
4670 memcpy (pFolderName->String.ucs2, aData.mHostPath, cbString);
4671
4672 pFolderName->u16Size = (uint16_t)cbString;
4673 pFolderName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
4674
4675 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
4676 parms[0].u.pointer.addr = pFolderName;
4677 parms[0].u.pointer.size = sizeof (SHFLSTRING) + (uint16_t)cbString;
4678
4679 cbString = (RTUtf16Len (aName) + 1) * sizeof (RTUTF16);
4680 if (cbString >= UINT16_MAX)
4681 {
4682 RTMemFree (pFolderName);
4683 return setError (E_INVALIDARG, tr ("The host path is too long"));
4684 }
4685 pMapName = (SHFLSTRING *) RTMemAllocZ (sizeof(SHFLSTRING) + cbString);
4686 Assert (pMapName);
4687 memcpy (pMapName->String.ucs2, aName, cbString);
4688
4689 pMapName->u16Size = (uint16_t)cbString;
4690 pMapName->u16Length = (uint16_t)cbString - sizeof (RTUTF16);
4691
4692 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
4693 parms[1].u.pointer.addr = pMapName;
4694 parms[1].u.pointer.size = sizeof (SHFLSTRING) + (uint16_t)cbString;
4695
4696 parms[2].type = VBOX_HGCM_SVC_PARM_32BIT;
4697 parms[2].u.uint32 = aData.mWritable;
4698
4699 int vrc = mVMMDev->hgcmHostCall ("VBoxSharedFolders",
4700 SHFL_FN_ADD_MAPPING,
4701 SHFL_CPARMS_ADD_MAPPING, &parms[0]);
4702 RTMemFree (pFolderName);
4703 RTMemFree (pMapName);
4704
4705 if (VBOX_FAILURE (vrc))
4706 return setError (E_FAIL,
4707 tr ("Could not create a shared folder '%ls' "
4708 "mapped to '%ls' (%Vrc)"),
4709 aName, aData.mHostPath.raw(), vrc);
4710
4711 return S_OK;
4712}
4713
4714/**
4715 * Calls the HGCM service to remove the shared folder definition.
4716 *
4717 * @param aName Shared folder name.
4718 *
4719 * @note Must be called from under AutoVMCaller and when mpVM != NULL!
4720 * @note Doesn't lock anything.
4721 */
4722HRESULT Console::removeSharedFolder (INPTR BSTR aName)
4723{
4724 ComAssertRet (aName && *aName, E_FAIL);
4725
4726 /* sanity checks */
4727 AssertReturn (mpVM, E_FAIL);
4728 AssertReturn (mVMMDev->isShFlActive(), E_FAIL);
4729
4730 VBOXHGCMSVCPARM parms;
4731 SHFLSTRING *pMapName;
4732 size_t cbString;
4733
4734 Log (("Removing shared folder '%ls'\n", aName));
4735
4736 cbString = (RTUtf16Len (aName) + 1) * sizeof (RTUTF16);
4737 if (cbString >= UINT16_MAX)
4738 return setError (E_INVALIDARG, tr ("The name is too long"));
4739 pMapName = (SHFLSTRING *) RTMemAllocZ (sizeof (SHFLSTRING) + cbString);
4740 Assert (pMapName);
4741 memcpy (pMapName->String.ucs2, aName, cbString);
4742
4743 pMapName->u16Size = (uint16_t)cbString;
4744 pMapName->u16Length = (uint16_t)cbString - sizeof (RTUTF16);
4745
4746 parms.type = VBOX_HGCM_SVC_PARM_PTR;
4747 parms.u.pointer.addr = pMapName;
4748 parms.u.pointer.size = sizeof (SHFLSTRING) + (uint16_t)cbString;
4749
4750 int vrc = mVMMDev->hgcmHostCall ("VBoxSharedFolders",
4751 SHFL_FN_REMOVE_MAPPING,
4752 1, &parms);
4753 RTMemFree(pMapName);
4754 if (VBOX_FAILURE (vrc))
4755 return setError (E_FAIL,
4756 tr ("Could not remove the shared folder '%ls' (%Vrc)"),
4757 aName, vrc);
4758
4759 return S_OK;
4760}
4761
4762/**
4763 * VM state callback function. Called by the VMM
4764 * using its state machine states.
4765 *
4766 * Primarily used to handle VM initiated power off, suspend and state saving,
4767 * but also for doing termination completed work (VMSTATE_TERMINATE).
4768 *
4769 * In general this function is called in the context of the EMT.
4770 *
4771 * @param aVM The VM handle.
4772 * @param aState The new state.
4773 * @param aOldState The old state.
4774 * @param aUser The user argument (pointer to the Console object).
4775 *
4776 * @note Locks the Console object for writing.
4777 */
4778DECLCALLBACK(void)
4779Console::vmstateChangeCallback (PVM aVM, VMSTATE aState, VMSTATE aOldState,
4780 void *aUser)
4781{
4782 LogFlowFunc (("Changing state from %d to %d (aVM=%p)\n",
4783 aOldState, aState, aVM));
4784
4785 Console *that = static_cast <Console *> (aUser);
4786 AssertReturnVoid (that);
4787
4788 AutoCaller autoCaller (that);
4789 /*
4790 * Note that we must let this method proceed even if Console::uninit() has
4791 * been already called. In such case this VMSTATE change is a result of:
4792 * 1) powerDown() called from uninit() itself, or
4793 * 2) VM-(guest-)initiated power off.
4794 */
4795 AssertReturnVoid (autoCaller.isOk() ||
4796 autoCaller.state() == InUninit);
4797
4798 switch (aState)
4799 {
4800 /*
4801 * The VM has terminated
4802 */
4803 case VMSTATE_OFF:
4804 {
4805 AutoWriteLock alock (that);
4806
4807 if (that->mVMStateChangeCallbackDisabled)
4808 break;
4809
4810 /*
4811 * Do we still think that it is running? It may happen if this is
4812 * a VM-(guest-)initiated shutdown/poweroff.
4813 */
4814 if (that->mMachineState != MachineState_Stopping &&
4815 that->mMachineState != MachineState_Saving &&
4816 that->mMachineState != MachineState_Restoring)
4817 {
4818 LogFlowFunc (("VM has powered itself off but Console still "
4819 "thinks it is running. Notifying.\n"));
4820
4821 /* prevent powerDown() from calling VMR3PowerOff() again */
4822 that->setMachineState (MachineState_Stopping);
4823
4824 /*
4825 * Setup task object and thread to carry out the operation
4826 * asynchronously (if we call powerDown() right here but there
4827 * is one or more mpVM callers (added with addVMCaller()) we'll
4828 * deadlock.
4829 */
4830 std::auto_ptr <VMTask> task (new VMTask (that, true /* aUsesVMPtr */));
4831 /*
4832 * If creating a task is falied, this can currently mean one
4833 * of two: either Console::uninit() has been called just a ms
4834 * before (so a powerDown() call is already on the way), or
4835 * powerDown() itself is being already executed. Just do
4836 * nothing .
4837 */
4838 if (!task->isOk())
4839 {
4840 LogFlowFunc (("Console is already being uninitialized.\n"));
4841 break;
4842 }
4843
4844 int vrc = RTThreadCreate (NULL, Console::powerDownThread,
4845 (void *) task.get(), 0,
4846 RTTHREADTYPE_MAIN_WORKER, 0,
4847 "VMPowerDowm");
4848
4849 AssertMsgRC (vrc, ("Could not create VMPowerUp thread (%Vrc)\n", vrc));
4850 if (VBOX_FAILURE (vrc))
4851 break;
4852
4853 /* task is now owned by powerDownThread(), so release it */
4854 task.release();
4855 }
4856 break;
4857 }
4858
4859 /*
4860 * The VM has been completely destroyed.
4861 *
4862 * Note: This state change can happen at two points:
4863 * 1) At the end of VMR3Destroy() if it was not called from EMT.
4864 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
4865 * called by EMT.
4866 */
4867 case VMSTATE_TERMINATED:
4868 {
4869 AutoWriteLock alock (that);
4870
4871 if (that->mVMStateChangeCallbackDisabled)
4872 break;
4873
4874 /*
4875 * Terminate host interface networking. If aVM is NULL, we've been
4876 * manually called from powerUpThread() either before calling
4877 * VMR3Create() or after VMR3Create() failed, so no need to touch
4878 * networking.
4879 */
4880 if (aVM)
4881 that->powerDownHostInterfaces();
4882
4883 /*
4884 * From now on the machine is officially powered down or
4885 * remains in the Saved state.
4886 */
4887 switch (that->mMachineState)
4888 {
4889 default:
4890 AssertFailed();
4891 /* fall through */
4892 case MachineState_Stopping:
4893 /* successfully powered down */
4894 that->setMachineState (MachineState_PoweredOff);
4895 break;
4896 case MachineState_Saving:
4897 /*
4898 * successfully saved (note that the machine is already
4899 * in the Saved state on the server due to EndSavingState()
4900 * called from saveStateThread(), so only change the local
4901 * state)
4902 */
4903 that->setMachineStateLocally (MachineState_Saved);
4904 break;
4905 case MachineState_Starting:
4906 /*
4907 * failed to start, but be patient: set back to PoweredOff
4908 * (for similarity with the below)
4909 */
4910 that->setMachineState (MachineState_PoweredOff);
4911 break;
4912 case MachineState_Restoring:
4913 /*
4914 * failed to load the saved state file, but be patient:
4915 * set back to Saved (to preserve the saved state file)
4916 */
4917 that->setMachineState (MachineState_Saved);
4918 break;
4919 }
4920
4921 break;
4922 }
4923
4924 case VMSTATE_SUSPENDED:
4925 {
4926 if (aOldState == VMSTATE_RUNNING)
4927 {
4928 AutoWriteLock alock (that);
4929
4930 if (that->mVMStateChangeCallbackDisabled)
4931 break;
4932
4933 /* Change the machine state from Running to Paused */
4934 Assert (that->mMachineState == MachineState_Running);
4935 that->setMachineState (MachineState_Paused);
4936 }
4937
4938 break;
4939 }
4940
4941 case VMSTATE_RUNNING:
4942 {
4943 if (aOldState == VMSTATE_CREATED ||
4944 aOldState == VMSTATE_SUSPENDED)
4945 {
4946 AutoWriteLock alock (that);
4947
4948 if (that->mVMStateChangeCallbackDisabled)
4949 break;
4950
4951 /*
4952 * Change the machine state from Starting, Restoring or Paused
4953 * to Running
4954 */
4955 Assert ((that->mMachineState == MachineState_Starting &&
4956 aOldState == VMSTATE_CREATED) ||
4957 ((that->mMachineState == MachineState_Restoring ||
4958 that->mMachineState == MachineState_Paused) &&
4959 aOldState == VMSTATE_SUSPENDED));
4960
4961 that->setMachineState (MachineState_Running);
4962 }
4963
4964 break;
4965 }
4966
4967 case VMSTATE_GURU_MEDITATION:
4968 {
4969 AutoWriteLock alock (that);
4970
4971 if (that->mVMStateChangeCallbackDisabled)
4972 break;
4973
4974 /* Guru respects only running VMs */
4975 Assert ((that->mMachineState >= MachineState_Running));
4976
4977 that->setMachineState (MachineState_Stuck);
4978
4979 break;
4980 }
4981
4982 default: /* shut up gcc */
4983 break;
4984 }
4985}
4986
4987#ifdef VBOX_WITH_USB
4988
4989/**
4990 * Sends a request to VMM to attach the given host device.
4991 * After this method succeeds, the attached device will appear in the
4992 * mUSBDevices collection.
4993 *
4994 * @param aHostDevice device to attach
4995 *
4996 * @note Synchronously calls EMT.
4997 * @note Must be called from under this object's lock.
4998 */
4999HRESULT Console::attachUSBDevice (IUSBDevice *aHostDevice, ULONG aMaskedIfs)
5000{
5001 AssertReturn (aHostDevice, E_FAIL);
5002 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5003
5004 /* still want a lock object because we need to leave it */
5005 AutoWriteLock alock (this);
5006
5007 HRESULT hrc;
5008
5009 /*
5010 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
5011 * method in EMT (using usbAttachCallback()).
5012 */
5013 Bstr BstrAddress;
5014 hrc = aHostDevice->COMGETTER (Address) (BstrAddress.asOutParam());
5015 ComAssertComRCRetRC (hrc);
5016
5017 Utf8Str Address (BstrAddress);
5018
5019 Guid Uuid;
5020 hrc = aHostDevice->COMGETTER (Id) (Uuid.asOutParam());
5021 ComAssertComRCRetRC (hrc);
5022
5023 BOOL fRemote = FALSE;
5024 hrc = aHostDevice->COMGETTER (Remote) (&fRemote);
5025 ComAssertComRCRetRC (hrc);
5026
5027 /* protect mpVM */
5028 AutoVMCaller autoVMCaller (this);
5029 CheckComRCReturnRC (autoVMCaller.rc());
5030
5031 LogFlowThisFunc (("Proxying USB device '%s' {%Vuuid}...\n",
5032 Address.raw(), Uuid.ptr()));
5033
5034 /* leave the lock before a VMR3* call (EMT will call us back)! */
5035 alock.leave();
5036
5037/** @todo just do everything here and only wrap the PDMR3Usb call. That'll offload some notification stuff from the EMT thread. */
5038 PVMREQ pReq = NULL;
5039 int vrc = VMR3ReqCall (mpVM, &pReq, RT_INDEFINITE_WAIT,
5040 (PFNRT) usbAttachCallback, 6, this, aHostDevice, Uuid.ptr(), fRemote, Address.raw(), aMaskedIfs);
5041 if (VBOX_SUCCESS (vrc))
5042 vrc = pReq->iStatus;
5043 VMR3ReqFree (pReq);
5044
5045 /* restore the lock */
5046 alock.enter();
5047
5048 /* hrc is S_OK here */
5049
5050 if (VBOX_FAILURE (vrc))
5051 {
5052 LogWarningThisFunc (("Failed to create proxy device for '%s' {%Vuuid} (%Vrc)\n",
5053 Address.raw(), Uuid.ptr(), vrc));
5054
5055 switch (vrc)
5056 {
5057 case VERR_VUSB_NO_PORTS:
5058 hrc = setError (E_FAIL,
5059 tr ("Failed to attach the USB device. (No available ports on the USB controller)."));
5060 break;
5061 case VERR_VUSB_USBFS_PERMISSION:
5062 hrc = setError (E_FAIL,
5063 tr ("Not permitted to open the USB device, check usbfs options"));
5064 break;
5065 default:
5066 hrc = setError (E_FAIL,
5067 tr ("Failed to create a proxy device for the USB device. (Error: %Vrc)"), vrc);
5068 break;
5069 }
5070 }
5071
5072 return hrc;
5073}
5074
5075/**
5076 * USB device attach callback used by AttachUSBDevice().
5077 * Note that AttachUSBDevice() doesn't return until this callback is executed,
5078 * so we don't use AutoCaller and don't care about reference counters of
5079 * interface pointers passed in.
5080 *
5081 * @thread EMT
5082 * @note Locks the console object for writing.
5083 */
5084//static
5085DECLCALLBACK(int)
5086Console::usbAttachCallback (Console *that, IUSBDevice *aHostDevice, PCRTUUID aUuid, bool aRemote, const char *aAddress, ULONG aMaskedIfs)
5087{
5088 LogFlowFuncEnter();
5089 LogFlowFunc (("that={%p}\n", that));
5090
5091 AssertReturn (that && aUuid, VERR_INVALID_PARAMETER);
5092
5093 void *pvRemoteBackend = NULL;
5094 if (aRemote)
5095 {
5096 RemoteUSBDevice *pRemoteUSBDevice = static_cast <RemoteUSBDevice *> (aHostDevice);
5097 Guid guid (*aUuid);
5098
5099 pvRemoteBackend = that->consoleVRDPServer ()->USBBackendRequestPointer (pRemoteUSBDevice->clientId (), &guid);
5100 if (!pvRemoteBackend)
5101 return VERR_INVALID_PARAMETER; /* The clientId is invalid then. */
5102 }
5103
5104 USHORT portVersion = 1;
5105 HRESULT hrc = aHostDevice->COMGETTER(PortVersion)(&portVersion);
5106 AssertComRCReturn(hrc, VERR_GENERAL_FAILURE);
5107 Assert(portVersion == 1 || portVersion == 2);
5108
5109 int vrc = PDMR3USBCreateProxyDevice (that->mpVM, aUuid, aRemote, aAddress, pvRemoteBackend,
5110 portVersion == 1 ? VUSB_STDVER_11 : VUSB_STDVER_20, aMaskedIfs);
5111 if (VBOX_SUCCESS (vrc))
5112 {
5113 /* Create a OUSBDevice and add it to the device list */
5114 ComObjPtr <OUSBDevice> device;
5115 device.createObject();
5116 HRESULT hrc = device->init (aHostDevice);
5117 AssertComRC (hrc);
5118
5119 AutoWriteLock alock (that);
5120 that->mUSBDevices.push_back (device);
5121 LogFlowFunc (("Attached device {%Vuuid}\n", device->id().raw()));
5122
5123 /* notify callbacks */
5124 that->onUSBDeviceStateChange (device, true /* aAttached */, NULL);
5125 }
5126
5127 LogFlowFunc (("vrc=%Vrc\n", vrc));
5128 LogFlowFuncLeave();
5129 return vrc;
5130}
5131
5132/**
5133 * Sends a request to VMM to detach the given host device. After this method
5134 * succeeds, the detached device will disappear from the mUSBDevices
5135 * collection.
5136 *
5137 * @param aIt Iterator pointing to the device to detach.
5138 *
5139 * @note Synchronously calls EMT.
5140 * @note Must be called from under this object's lock.
5141 */
5142HRESULT Console::detachUSBDevice (USBDeviceList::iterator &aIt)
5143{
5144 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5145
5146 /* still want a lock object because we need to leave it */
5147 AutoWriteLock alock (this);
5148
5149 /* protect mpVM */
5150 AutoVMCaller autoVMCaller (this);
5151 CheckComRCReturnRC (autoVMCaller.rc());
5152
5153 /* if the device is attached, then there must at least one USB hub. */
5154 AssertReturn (PDMR3USBHasHub (mpVM), E_FAIL);
5155
5156 LogFlowThisFunc (("Detaching USB proxy device {%Vuuid}...\n",
5157 (*aIt)->id().raw()));
5158
5159 /* leave the lock before a VMR3* call (EMT will call us back)! */
5160 alock.leave();
5161
5162 PVMREQ pReq;
5163/** @todo just do everything here and only wrap the PDMR3Usb call. That'll offload some notification stuff from the EMT thread. */
5164 int vrc = VMR3ReqCall (mpVM, &pReq, RT_INDEFINITE_WAIT,
5165 (PFNRT) usbDetachCallback, 4,
5166 this, &aIt, (*aIt)->id().raw());
5167 if (VBOX_SUCCESS (vrc))
5168 vrc = pReq->iStatus;
5169 VMR3ReqFree (pReq);
5170
5171 ComAssertRCRet (vrc, E_FAIL);
5172
5173 return S_OK;
5174}
5175
5176/**
5177 * USB device detach callback used by DetachUSBDevice().
5178 * Note that DetachUSBDevice() doesn't return until this callback is executed,
5179 * so we don't use AutoCaller and don't care about reference counters of
5180 * interface pointers passed in.
5181 *
5182 * @thread EMT
5183 * @note Locks the console object for writing.
5184 */
5185//static
5186DECLCALLBACK(int)
5187Console::usbDetachCallback (Console *that, USBDeviceList::iterator *aIt, PCRTUUID aUuid)
5188{
5189 LogFlowFuncEnter();
5190 LogFlowFunc (("that={%p}\n", that));
5191
5192 AssertReturn (that && aUuid, VERR_INVALID_PARAMETER);
5193 ComObjPtr <OUSBDevice> device = **aIt;
5194
5195 /*
5196 * If that was a remote device, release the backend pointer.
5197 * The pointer was requested in usbAttachCallback.
5198 */
5199 BOOL fRemote = FALSE;
5200
5201 HRESULT hrc2 = (**aIt)->COMGETTER (Remote) (&fRemote);
5202 ComAssertComRC (hrc2);
5203
5204 if (fRemote)
5205 {
5206 Guid guid (*aUuid);
5207 that->consoleVRDPServer ()->USBBackendReleasePointer (&guid);
5208 }
5209
5210 int vrc = PDMR3USBDetachDevice (that->mpVM, aUuid);
5211
5212 if (VBOX_SUCCESS (vrc))
5213 {
5214 AutoWriteLock alock (that);
5215
5216 /* Remove the device from the collection */
5217 that->mUSBDevices.erase (*aIt);
5218 LogFlowFunc (("Detached device {%Vuuid}\n", device->id().raw()));
5219
5220 /* notify callbacks */
5221 that->onUSBDeviceStateChange (device, false /* aAttached */, NULL);
5222 }
5223
5224 LogFlowFunc (("vrc=%Vrc\n", vrc));
5225 LogFlowFuncLeave();
5226 return vrc;
5227}
5228
5229#endif /* VBOX_WITH_USB */
5230
5231/**
5232 * Call the initialisation script for a dynamic TAP interface.
5233 *
5234 * The initialisation script should create a TAP interface, set it up and write its name to
5235 * standard output followed by a carriage return. Anything further written to standard
5236 * output will be ignored. If it returns a non-zero exit code, or does not write an
5237 * intelligable interface name to standard output, it will be treated as having failed.
5238 * For now, this method only works on Linux.
5239 *
5240 * @returns COM status code
5241 * @param tapDevice string to store the name of the tap device created to
5242 * @param tapSetupApplication the name of the setup script
5243 */
5244HRESULT Console::callTapSetupApplication(bool isStatic, RTFILE tapFD, Bstr &tapDevice,
5245 Bstr &tapSetupApplication)
5246{
5247 LogFlowThisFunc(("\n"));
5248#ifdef RT_OS_LINUX
5249 /* Command line to start the script with. */
5250 char szCommand[4096];
5251 /* Result code */
5252 int rc;
5253
5254 /* Get the script name. */
5255 Utf8Str tapSetupAppUtf8(tapSetupApplication), tapDeviceUtf8(tapDevice);
5256 RTStrPrintf(szCommand, sizeof(szCommand), "%s %d %s", tapSetupAppUtf8.raw(),
5257 isStatic ? tapFD : 0, isStatic ? tapDeviceUtf8.raw() : "");
5258 /*
5259 * Create the process and read its output.
5260 */
5261 Log2(("About to start the TAP setup script with the following command line: %s\n",
5262 szCommand));
5263 FILE *pfScriptHandle = popen(szCommand, "r");
5264 if (pfScriptHandle == 0)
5265 {
5266 int iErr = errno;
5267 LogRel(("Failed to start the TAP interface setup script %s, error text: %s\n",
5268 szCommand, strerror(iErr)));
5269 LogFlowThisFunc(("rc=E_FAIL\n"));
5270 return setError(E_FAIL, tr ("Failed to run the host networking set up command %s: %s"),
5271 szCommand, strerror(iErr));
5272 }
5273 /* If we are using a dynamic TAP interface, we need to get the interface name. */
5274 if (!isStatic)
5275 {
5276 /* Buffer to read the application output to. It doesn't have to be long, as we are only
5277 interested in the first few (normally 5 or 6) bytes. */
5278 char acBuffer[64];
5279 /* The length of the string returned by the application. We only accept strings of 63
5280 characters or less. */
5281 size_t cBufSize;
5282
5283 /* Read the name of the device from the application. */
5284 fgets(acBuffer, sizeof(acBuffer), pfScriptHandle);
5285 cBufSize = strlen(acBuffer);
5286 /* The script must return the name of the interface followed by a carriage return as the
5287 first line of its output. We need a null-terminated string. */
5288 if ((cBufSize < 2) || (acBuffer[cBufSize - 1] != '\n'))
5289 {
5290 pclose(pfScriptHandle);
5291 LogRel(("The TAP interface setup script did not return the name of a TAP device.\n"));
5292 LogFlowThisFunc(("rc=E_FAIL\n"));
5293 return setError(E_FAIL, tr ("The host networking set up command did not supply an interface name"));
5294 }
5295 /* Overwrite the terminating newline character. */
5296 acBuffer[cBufSize - 1] = 0;
5297 tapDevice = acBuffer;
5298 }
5299 rc = pclose(pfScriptHandle);
5300 if (!WIFEXITED(rc))
5301 {
5302 LogRel(("The TAP interface setup script terminated abnormally.\n"));
5303 LogFlowThisFunc(("rc=E_FAIL\n"));
5304 return setError(E_FAIL, tr ("The host networking set up command did not run correctly"));
5305 }
5306 if (WEXITSTATUS(rc) != 0)
5307 {
5308 LogRel(("The TAP interface setup script returned a non-zero exit code.\n"));
5309 LogFlowThisFunc(("rc=E_FAIL\n"));
5310 return setError(E_FAIL, tr ("The host networking set up command returned a non-zero exit code"));
5311 }
5312 LogFlowThisFunc(("rc=S_OK\n"));
5313 return S_OK;
5314#else /* RT_OS_LINUX not defined */
5315 LogFlowThisFunc(("rc=E_NOTIMPL\n"));
5316 return E_NOTIMPL; /* not yet supported */
5317#endif
5318}
5319
5320/**
5321 * Helper function to handle host interface device creation and attachment.
5322 *
5323 * @param networkAdapter the network adapter which attachment should be reset
5324 * @return COM status code
5325 *
5326 * @note The caller must lock this object for writing.
5327 */
5328HRESULT Console::attachToHostInterface(INetworkAdapter *networkAdapter)
5329{
5330 LogFlowThisFunc(("\n"));
5331 /* sanity check */
5332 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5333
5334#ifdef DEBUG
5335 /* paranoia */
5336 NetworkAttachmentType_T attachment;
5337 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5338 Assert(attachment == NetworkAttachmentType_HostInterface);
5339#endif /* DEBUG */
5340
5341 HRESULT rc = S_OK;
5342
5343#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
5344 ULONG slot = 0;
5345 rc = networkAdapter->COMGETTER(Slot)(&slot);
5346 AssertComRC(rc);
5347
5348 /*
5349 * Try get the FD.
5350 */
5351 LONG ltapFD;
5352 rc = networkAdapter->COMGETTER(TAPFileDescriptor)(&ltapFD);
5353 if (SUCCEEDED(rc))
5354 maTapFD[slot] = (RTFILE)ltapFD;
5355 else
5356 maTapFD[slot] = NIL_RTFILE;
5357
5358 /*
5359 * Are we supposed to use an existing TAP interface?
5360 */
5361 if (maTapFD[slot] != NIL_RTFILE)
5362 {
5363 /* nothing to do */
5364 Assert(ltapFD >= 0);
5365 Assert((LONG)maTapFD[slot] == ltapFD);
5366 rc = S_OK;
5367 }
5368 else
5369#endif /* VBOX_WITH_UNIXY_TAP_NETWORKING */
5370 {
5371 /*
5372 * Allocate a host interface device
5373 */
5374#ifdef RT_OS_WINDOWS
5375 /* nothing to do */
5376 int rcVBox = VINF_SUCCESS;
5377#elif defined(RT_OS_LINUX)
5378 int rcVBox = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
5379 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
5380 if (VBOX_SUCCESS(rcVBox))
5381 {
5382 /*
5383 * Set/obtain the tap interface.
5384 */
5385 bool isStatic = false;
5386 struct ifreq IfReq;
5387 memset(&IfReq, 0, sizeof(IfReq));
5388 /* The name of the TAP interface we are using and the TAP setup script resp. */
5389 Bstr tapDeviceName, tapSetupApplication;
5390 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
5391 if (FAILED(rc))
5392 {
5393 tapDeviceName.setNull(); /* Is this necessary? */
5394 }
5395 else if (!tapDeviceName.isEmpty())
5396 {
5397 isStatic = true;
5398 /* If we are using a static TAP device then try to open it. */
5399 Utf8Str str(tapDeviceName);
5400 if (str.length() <= sizeof(IfReq.ifr_name))
5401 strcpy(IfReq.ifr_name, str.raw());
5402 else
5403 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
5404 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
5405 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
5406 if (rcVBox != 0)
5407 {
5408 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
5409 rc = setError(E_FAIL, tr ("Failed to open the host network interface %ls"),
5410 tapDeviceName.raw());
5411 }
5412 }
5413 if (SUCCEEDED(rc))
5414 {
5415 networkAdapter->COMGETTER(TAPSetupApplication)(tapSetupApplication.asOutParam());
5416 if (tapSetupApplication.isEmpty())
5417 {
5418 if (tapDeviceName.isEmpty())
5419 {
5420 LogRel(("No setup application was supplied for the TAP interface.\n"));
5421 rc = setError(E_FAIL, tr ("No setup application was supplied for the host networking interface"));
5422 }
5423 }
5424 else
5425 {
5426 rc = callTapSetupApplication(isStatic, maTapFD[slot], tapDeviceName,
5427 tapSetupApplication);
5428 }
5429 }
5430 if (SUCCEEDED(rc))
5431 {
5432 if (!isStatic)
5433 {
5434 Utf8Str str(tapDeviceName);
5435 if (str.length() <= sizeof(IfReq.ifr_name))
5436 strcpy(IfReq.ifr_name, str.raw());
5437 else
5438 memcpy(IfReq.ifr_name, str.raw(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
5439 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
5440 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
5441 if (rcVBox != 0)
5442 {
5443 LogRel(("Failed to open the host network interface %ls returned by the setup script", tapDeviceName.raw()));
5444 rc = setError(E_FAIL, tr ("Failed to open the host network interface %ls returned by the setup script"), tapDeviceName.raw());
5445 }
5446 }
5447 if (SUCCEEDED(rc))
5448 {
5449 /*
5450 * Make it pollable.
5451 */
5452 if (fcntl(maTapFD[slot], F_SETFL, O_NONBLOCK) != -1)
5453 {
5454 Log(("attachToHostInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
5455
5456 /*
5457 * Here is the right place to communicate the TAP file descriptor and
5458 * the host interface name to the server if/when it becomes really
5459 * necessary.
5460 */
5461 maTAPDeviceName[slot] = tapDeviceName;
5462 rcVBox = VINF_SUCCESS;
5463 }
5464 else
5465 {
5466 int iErr = errno;
5467
5468 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
5469 rcVBox = VERR_HOSTIF_BLOCKING;
5470 rc = setError(E_FAIL, tr ("could not set up the host networking device for non blocking access: %s"),
5471 strerror(errno));
5472 }
5473 }
5474 }
5475 }
5476 else
5477 {
5478 LogRel(("Configuration error: Failed to open /dev/net/tun rc=%Vrc\n", rcVBox));
5479 switch (rcVBox)
5480 {
5481 case VERR_ACCESS_DENIED:
5482 /* will be handled by our caller */
5483 rc = rcVBox;
5484 break;
5485 default:
5486 rc = setError(E_FAIL, tr ("Could not set up the host networking device: %Vrc"), rcVBox);
5487 break;
5488 }
5489 }
5490#elif defined(RT_OS_DARWIN)
5491 /** @todo Implement tap networking for Darwin. */
5492 int rcVBox = VERR_NOT_IMPLEMENTED;
5493#elif defined(RT_OS_FREEBSD)
5494 /** @todo Implement tap networking for FreeBSD. */
5495 int rcVBox = VERR_NOT_IMPLEMENTED;
5496#elif defined(RT_OS_OS2)
5497 /** @todo Implement tap networking for OS/2. */
5498 int rcVBox = VERR_NOT_IMPLEMENTED;
5499#elif defined(RT_OS_SOLARIS)
5500 /* nothing to do */
5501 int rcVBox = VINF_SUCCESS;
5502#elif defined(VBOX_WITH_UNIXY_TAP_NETWORKING)
5503# error "PORTME: Implement OS specific TAP interface open/creation."
5504#else
5505# error "Unknown host OS"
5506#endif
5507 /* in case of failure, cleanup. */
5508 if (VBOX_FAILURE(rcVBox) && SUCCEEDED(rc))
5509 {
5510 LogRel(("General failure attaching to host interface\n"));
5511 rc = setError(E_FAIL, tr ("General failure attaching to host interface"));
5512 }
5513 }
5514 LogFlowThisFunc(("rc=%d\n", rc));
5515 return rc;
5516}
5517
5518/**
5519 * Helper function to handle detachment from a host interface
5520 *
5521 * @param networkAdapter the network adapter which attachment should be reset
5522 * @return COM status code
5523 *
5524 * @note The caller must lock this object for writing.
5525 */
5526HRESULT Console::detachFromHostInterface(INetworkAdapter *networkAdapter)
5527{
5528 /* sanity check */
5529 LogFlowThisFunc(("\n"));
5530 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5531
5532 HRESULT rc = S_OK;
5533#ifdef DEBUG
5534 /* paranoia */
5535 NetworkAttachmentType_T attachment;
5536 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5537 Assert(attachment == NetworkAttachmentType_HostInterface);
5538#endif /* DEBUG */
5539
5540#ifdef VBOX_WITH_UNIXY_TAP_NETWORKING
5541
5542 ULONG slot = 0;
5543 rc = networkAdapter->COMGETTER(Slot)(&slot);
5544 AssertComRC(rc);
5545
5546 /* is there an open TAP device? */
5547 if (maTapFD[slot] != NIL_RTFILE)
5548 {
5549 /*
5550 * Close the file handle.
5551 */
5552 Bstr tapDeviceName, tapTerminateApplication;
5553 bool isStatic = true;
5554 rc = networkAdapter->COMGETTER(HostInterface)(tapDeviceName.asOutParam());
5555 if (FAILED(rc) || tapDeviceName.isEmpty())
5556 {
5557 /* If the name is empty, this is a dynamic TAP device, so close it now,
5558 so that the termination script can remove the interface. Otherwise we still
5559 need the FD to pass to the termination script. */
5560 isStatic = false;
5561 int rcVBox = RTFileClose(maTapFD[slot]);
5562 AssertRC(rcVBox);
5563 maTapFD[slot] = NIL_RTFILE;
5564 }
5565 /*
5566 * Execute the termination command.
5567 */
5568 networkAdapter->COMGETTER(TAPTerminateApplication)(tapTerminateApplication.asOutParam());
5569 if (tapTerminateApplication)
5570 {
5571 /* Get the program name. */
5572 Utf8Str tapTermAppUtf8(tapTerminateApplication);
5573
5574 /* Build the command line. */
5575 char szCommand[4096];
5576 RTStrPrintf(szCommand, sizeof(szCommand), "%s %d %s", tapTermAppUtf8.raw(),
5577 isStatic ? maTapFD[slot] : 0, maTAPDeviceName[slot].raw());
5578
5579 /*
5580 * Create the process and wait for it to complete.
5581 */
5582 Log(("Calling the termination command: %s\n", szCommand));
5583 int rcCommand = system(szCommand);
5584 if (rcCommand == -1)
5585 {
5586 LogRel(("Failed to execute the clean up script for the TAP interface"));
5587 rc = setError(E_FAIL, tr ("Failed to execute the clean up script for the TAP interface"));
5588 }
5589 if (!WIFEXITED(rc))
5590 {
5591 LogRel(("The TAP interface clean up script terminated abnormally.\n"));
5592 rc = setError(E_FAIL, tr ("The TAP interface clean up script terminated abnormally"));
5593 }
5594 if (WEXITSTATUS(rc) != 0)
5595 {
5596 LogRel(("The TAP interface clean up script returned a non-zero exit code.\n"));
5597 rc = setError(E_FAIL, tr ("The TAP interface clean up script returned a non-zero exit code"));
5598 }
5599 }
5600
5601 if (isStatic)
5602 {
5603 /* If we are using a static TAP device, we close it now, after having called the
5604 termination script. */
5605 int rcVBox = RTFileClose(maTapFD[slot]);
5606 AssertRC(rcVBox);
5607 }
5608 /* the TAP device name and handle are no longer valid */
5609 maTapFD[slot] = NIL_RTFILE;
5610 maTAPDeviceName[slot] = "";
5611 }
5612#endif
5613 LogFlowThisFunc(("returning %d\n", rc));
5614 return rc;
5615}
5616
5617
5618/**
5619 * Called at power down to terminate host interface networking.
5620 *
5621 * @note The caller must lock this object for writing.
5622 */
5623HRESULT Console::powerDownHostInterfaces()
5624{
5625 LogFlowThisFunc (("\n"));
5626
5627 /* sanity check */
5628 AssertReturn (isWriteLockOnCurrentThread(), E_FAIL);
5629
5630 /*
5631 * host interface termination handling
5632 */
5633 HRESULT rc;
5634 for (ULONG slot = 0; slot < SchemaDefs::NetworkAdapterCount; slot ++)
5635 {
5636 ComPtr<INetworkAdapter> networkAdapter;
5637 rc = mMachine->GetNetworkAdapter(slot, networkAdapter.asOutParam());
5638 CheckComRCBreakRC (rc);
5639
5640 BOOL enabled = FALSE;
5641 networkAdapter->COMGETTER(Enabled) (&enabled);
5642 if (!enabled)
5643 continue;
5644
5645 NetworkAttachmentType_T attachment;
5646 networkAdapter->COMGETTER(AttachmentType)(&attachment);
5647 if (attachment == NetworkAttachmentType_HostInterface)
5648 {
5649 HRESULT rc2 = detachFromHostInterface(networkAdapter);
5650 if (FAILED(rc2) && SUCCEEDED(rc))
5651 rc = rc2;
5652 }
5653 }
5654
5655 return rc;
5656}
5657
5658
5659/**
5660 * Process callback handler for VMR3Load and VMR3Save.
5661 *
5662 * @param pVM The VM handle.
5663 * @param uPercent Completetion precentage (0-100).
5664 * @param pvUser Pointer to the VMProgressTask structure.
5665 * @return VINF_SUCCESS.
5666 */
5667/*static*/ DECLCALLBACK (int)
5668Console::stateProgressCallback (PVM pVM, unsigned uPercent, void *pvUser)
5669{
5670 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
5671 AssertReturn (task, VERR_INVALID_PARAMETER);
5672
5673 /* update the progress object */
5674 if (task->mProgress)
5675 task->mProgress->notifyProgress (uPercent);
5676
5677 return VINF_SUCCESS;
5678}
5679
5680/**
5681 * VM error callback function. Called by the various VM components.
5682 *
5683 * @param pVM VM handle. Can be NULL if an error occurred before
5684 * successfully creating a VM.
5685 * @param pvUser Pointer to the VMProgressTask structure.
5686 * @param rc VBox status code.
5687 * @param pszFormat Printf-like error message.
5688 * @param args Various number of argumens for the error message.
5689 *
5690 * @thread EMT, VMPowerUp...
5691 *
5692 * @note The VMProgressTask structure modified by this callback is not thread
5693 * safe.
5694 */
5695/* static */ DECLCALLBACK (void)
5696Console::setVMErrorCallback (PVM pVM, void *pvUser, int rc, RT_SRC_POS_DECL,
5697 const char *pszFormat, va_list args)
5698{
5699 VMProgressTask *task = static_cast <VMProgressTask *> (pvUser);
5700 AssertReturnVoid (task);
5701
5702 /* we ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users */
5703 va_list va2;
5704 va_copy(va2, args); /* Have to make a copy here or GCC will break. */
5705 Utf8Str errorMsg = Utf8StrFmt (tr ("%N.\n"
5706 "VBox status code: %d (%Vrc)"),
5707 pszFormat, &va2, rc, rc);
5708 va_end(va2);
5709
5710 /* For now, this may be called only once. Ignore subsequent calls. */
5711 if (!task->mErrorMsg.isNull())
5712 {
5713#if !defined(DEBUG_bird)
5714 AssertMsgFailed (("Cannot set error to '%s': it is already set to '%s'",
5715 errorMsg.raw(), task->mErrorMsg.raw()));
5716#endif
5717 return;
5718 }
5719
5720 task->mErrorMsg = errorMsg;
5721}
5722
5723/**
5724 * VM runtime error callback function.
5725 * See VMSetRuntimeError for the detailed description of parameters.
5726 *
5727 * @param pVM The VM handle.
5728 * @param pvUser The user argument.
5729 * @param fFatal Whether it is a fatal error or not.
5730 * @param pszErrorID Error ID string.
5731 * @param pszFormat Error message format string.
5732 * @param args Error message arguments.
5733 * @thread EMT.
5734 */
5735/* static */ DECLCALLBACK(void)
5736Console::setVMRuntimeErrorCallback (PVM pVM, void *pvUser, bool fFatal,
5737 const char *pszErrorID,
5738 const char *pszFormat, va_list args)
5739{
5740 LogFlowFuncEnter();
5741
5742 Console *that = static_cast <Console *> (pvUser);
5743 AssertReturnVoid (that);
5744
5745 Utf8Str message = Utf8StrFmtVA (pszFormat, args);
5746
5747 LogRel (("Console: VM runtime error: fatal=%RTbool, "
5748 "errorID=%s message=\"%s\"\n",
5749 fFatal, pszErrorID, message.raw()));
5750
5751 that->onRuntimeError (BOOL (fFatal), Bstr (pszErrorID), Bstr (message));
5752
5753 LogFlowFuncLeave();
5754}
5755
5756/**
5757 * Captures USB devices that match filters of the VM.
5758 * Called at VM startup.
5759 *
5760 * @param pVM The VM handle.
5761 *
5762 * @note The caller must lock this object for writing.
5763 */
5764HRESULT Console::captureUSBDevices (PVM pVM)
5765{
5766 LogFlowThisFunc (("\n"));
5767
5768 /* sanity check */
5769 ComAssertRet (isWriteLockOnCurrentThread(), E_FAIL);
5770
5771 /* If the machine has an USB controller, ask the USB proxy service to
5772 * capture devices */
5773 PPDMIBASE pBase;
5774 int vrc = PDMR3QueryLun (pVM, "usb-ohci", 0, 0, &pBase);
5775 if (VBOX_SUCCESS (vrc))
5776 {
5777 /* leave the lock before calling Host in VBoxSVC since Host may call
5778 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
5779 * produce an inter-process dead-lock otherwise. */
5780 AutoWriteLock alock (this);
5781 alock.leave();
5782
5783 HRESULT hrc = mControl->AutoCaptureUSBDevices();
5784 ComAssertComRCRetRC (hrc);
5785 }
5786 else if ( vrc == VERR_PDM_DEVICE_NOT_FOUND
5787 || vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND)
5788 vrc = VINF_SUCCESS;
5789 else
5790 AssertRC (vrc);
5791
5792 return VBOX_SUCCESS (vrc) ? S_OK : E_FAIL;
5793}
5794
5795
5796/**
5797 * Detach all USB device which are attached to the VM for the
5798 * purpose of clean up and such like.
5799 *
5800 * @note The caller must lock this object for writing.
5801 */
5802void Console::detachAllUSBDevices (bool aDone)
5803{
5804 LogFlowThisFunc (("aDone=%RTbool\n", aDone));
5805
5806 /* sanity check */
5807 AssertReturnVoid (isWriteLockOnCurrentThread());
5808
5809 mUSBDevices.clear();
5810
5811 /* leave the lock before calling Host in VBoxSVC since Host may call
5812 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
5813 * produce an inter-process dead-lock otherwise. */
5814 AutoWriteLock alock (this);
5815 alock.leave();
5816
5817 mControl->DetachAllUSBDevices (aDone);
5818}
5819
5820/**
5821 * @note Locks this object for writing.
5822 */
5823void Console::processRemoteUSBDevices (uint32_t u32ClientId, VRDPUSBDEVICEDESC *pDevList, uint32_t cbDevList)
5824{
5825 LogFlowThisFuncEnter();
5826 LogFlowThisFunc (("u32ClientId = %d, pDevList=%p, cbDevList = %d\n", u32ClientId, pDevList, cbDevList));
5827
5828 AutoCaller autoCaller (this);
5829 if (!autoCaller.isOk())
5830 {
5831 /* Console has been already uninitialized, deny request */
5832 AssertMsgFailed (("Temporary assertion to prove that it happens, "
5833 "please report to dmik\n"));
5834 LogFlowThisFunc (("Console is already uninitialized\n"));
5835 LogFlowThisFuncLeave();
5836 return;
5837 }
5838
5839 AutoWriteLock alock (this);
5840
5841 /*
5842 * Mark all existing remote USB devices as dirty.
5843 */
5844 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
5845 while (it != mRemoteUSBDevices.end())
5846 {
5847 (*it)->dirty (true);
5848 ++ it;
5849 }
5850
5851 /*
5852 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
5853 */
5854 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
5855 VRDPUSBDEVICEDESC *e = pDevList;
5856
5857 /* The cbDevList condition must be checked first, because the function can
5858 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
5859 */
5860 while (cbDevList >= 2 && e->oNext)
5861 {
5862 LogFlowThisFunc (("vendor %04X, product %04X, name = %s\n",
5863 e->idVendor, e->idProduct,
5864 e->oProduct? (char *)e + e->oProduct: ""));
5865
5866 bool fNewDevice = true;
5867
5868 it = mRemoteUSBDevices.begin();
5869 while (it != mRemoteUSBDevices.end())
5870 {
5871 if ((*it)->devId () == e->id
5872 && (*it)->clientId () == u32ClientId)
5873 {
5874 /* The device is already in the list. */
5875 (*it)->dirty (false);
5876 fNewDevice = false;
5877 break;
5878 }
5879
5880 ++ it;
5881 }
5882
5883 if (fNewDevice)
5884 {
5885 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
5886 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""
5887 ));
5888
5889 /* Create the device object and add the new device to list. */
5890 ComObjPtr <RemoteUSBDevice> device;
5891 device.createObject();
5892 device->init (u32ClientId, e);
5893
5894 mRemoteUSBDevices.push_back (device);
5895
5896 /* Check if the device is ok for current USB filters. */
5897 BOOL fMatched = FALSE;
5898 ULONG fMaskedIfs = 0;
5899
5900 HRESULT hrc = mControl->RunUSBDeviceFilters(device, &fMatched, &fMaskedIfs);
5901
5902 AssertComRC (hrc);
5903
5904 LogFlowThisFunc (("USB filters return %d %#x\n", fMatched, fMaskedIfs));
5905
5906 if (fMatched)
5907 {
5908 hrc = onUSBDeviceAttach (device, NULL, fMaskedIfs);
5909
5910 /// @todo (r=dmik) warning reporting subsystem
5911
5912 if (hrc == S_OK)
5913 {
5914 LogFlowThisFunc (("Device attached\n"));
5915 device->captured (true);
5916 }
5917 }
5918 }
5919
5920 if (cbDevList < e->oNext)
5921 {
5922 LogWarningThisFunc (("cbDevList %d > oNext %d\n",
5923 cbDevList, e->oNext));
5924 break;
5925 }
5926
5927 cbDevList -= e->oNext;
5928
5929 e = (VRDPUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
5930 }
5931
5932 /*
5933 * Remove dirty devices, that is those which are not reported by the server anymore.
5934 */
5935 for (;;)
5936 {
5937 ComObjPtr <RemoteUSBDevice> device;
5938
5939 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
5940 while (it != mRemoteUSBDevices.end())
5941 {
5942 if ((*it)->dirty ())
5943 {
5944 device = *it;
5945 break;
5946 }
5947
5948 ++ it;
5949 }
5950
5951 if (!device)
5952 {
5953 break;
5954 }
5955
5956 USHORT vendorId = 0;
5957 device->COMGETTER(VendorId) (&vendorId);
5958
5959 USHORT productId = 0;
5960 device->COMGETTER(ProductId) (&productId);
5961
5962 Bstr product;
5963 device->COMGETTER(Product) (product.asOutParam());
5964
5965 LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
5966 vendorId, productId, product.raw ()
5967 ));
5968
5969 /* Detach the device from VM. */
5970 if (device->captured ())
5971 {
5972 Guid uuid;
5973 device->COMGETTER (Id) (uuid.asOutParam());
5974 onUSBDeviceDetach (uuid, NULL);
5975 }
5976
5977 /* And remove it from the list. */
5978 mRemoteUSBDevices.erase (it);
5979 }
5980
5981 LogFlowThisFuncLeave();
5982}
5983
5984
5985
5986/**
5987 * Thread function which starts the VM (also from saved state) and
5988 * track progress.
5989 *
5990 * @param Thread The thread id.
5991 * @param pvUser Pointer to a VMPowerUpTask structure.
5992 * @return VINF_SUCCESS (ignored).
5993 *
5994 * @note Locks the Console object for writing.
5995 */
5996/*static*/
5997DECLCALLBACK (int) Console::powerUpThread (RTTHREAD Thread, void *pvUser)
5998{
5999 LogFlowFuncEnter();
6000
6001 std::auto_ptr <VMPowerUpTask> task (static_cast <VMPowerUpTask *> (pvUser));
6002 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
6003
6004 AssertReturn (!task->mConsole.isNull(), VERR_INVALID_PARAMETER);
6005 AssertReturn (!task->mProgress.isNull(), VERR_INVALID_PARAMETER);
6006
6007#if defined(RT_OS_WINDOWS)
6008 {
6009 /* initialize COM */
6010 HRESULT hrc = CoInitializeEx (NULL,
6011 COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE |
6012 COINIT_SPEED_OVER_MEMORY);
6013 LogFlowFunc (("CoInitializeEx()=%08X\n", hrc));
6014 }
6015#endif
6016
6017 HRESULT hrc = S_OK;
6018 int vrc = VINF_SUCCESS;
6019
6020 /* Set up a build identifier so that it can be seen from core dumps what
6021 * exact build was used to produce the core. */
6022 static char saBuildID[40];
6023 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%d %s%s%s%s",
6024 "BU", "IL", "DI", "D", VBOX_VERSION_STRING, VBoxSVNRev (), "BU", "IL", "DI", "D");
6025
6026 ComObjPtr <Console> console = task->mConsole;
6027
6028 /* Note: no need to use addCaller() because VMPowerUpTask does that */
6029
6030 AutoWriteLock alock (console);
6031
6032 /* sanity */
6033 Assert (console->mpVM == NULL);
6034
6035 do
6036 {
6037#ifdef VBOX_VRDP
6038 /* Create the VRDP server. In case of headless operation, this will
6039 * also create the framebuffer, required at VM creation.
6040 */
6041 ConsoleVRDPServer *server = console->consoleVRDPServer();
6042 Assert (server);
6043 /// @todo (dmik)
6044 // does VRDP server call Console from the other thread?
6045 // Not sure, so leave the lock just in case
6046 alock.leave();
6047 vrc = server->Launch();
6048 alock.enter();
6049 if (VBOX_FAILURE (vrc))
6050 {
6051 Utf8Str errMsg;
6052 switch (vrc)
6053 {
6054 case VERR_NET_ADDRESS_IN_USE:
6055 {
6056 ULONG port = 0;
6057 console->mVRDPServer->COMGETTER(Port) (&port);
6058 errMsg = Utf8StrFmt (tr ("VRDP server port %d is already in use"),
6059 port);
6060 break;
6061 }
6062 case VERR_FILE_NOT_FOUND:
6063 {
6064 errMsg = Utf8StrFmt (tr ("Could not load the VRDP library"));
6065 break;
6066 }
6067 default:
6068 errMsg = Utf8StrFmt (tr ("Failed to launch VRDP server (%Vrc)"),
6069 vrc);
6070 }
6071 LogRel (("Failed to launch VRDP server (%Vrc), error message: '%s'\n",
6072 vrc, errMsg.raw()));
6073 hrc = setError (E_FAIL, errMsg);
6074 break;
6075 }
6076#endif /* VBOX_VRDP */
6077
6078 /*
6079 * Create the VM
6080 */
6081 PVM pVM;
6082 /*
6083 * leave the lock since EMT will call Console. It's safe because
6084 * mMachineState is either Starting or Restoring state here.
6085 */
6086 alock.leave();
6087
6088 vrc = VMR3Create (task->mSetVMErrorCallback, task.get(),
6089 task->mConfigConstructor, static_cast <Console *> (console),
6090 &pVM);
6091
6092 alock.enter();
6093
6094#ifdef VBOX_VRDP
6095 /* Enable client connections to the server. */
6096 console->consoleVRDPServer()->EnableConnections ();
6097#endif /* VBOX_VRDP */
6098
6099 if (VBOX_SUCCESS (vrc))
6100 {
6101 do
6102 {
6103 /*
6104 * Register our load/save state file handlers
6105 */
6106 vrc = SSMR3RegisterExternal (pVM,
6107 sSSMConsoleUnit, 0 /* iInstance */, sSSMConsoleVer,
6108 0 /* cbGuess */,
6109 NULL, saveStateFileExec, NULL, NULL, loadStateFileExec, NULL,
6110 static_cast <Console *> (console));
6111 AssertRC (vrc);
6112 if (VBOX_FAILURE (vrc))
6113 break;
6114
6115 /*
6116 * Synchronize debugger settings
6117 */
6118 MachineDebugger *machineDebugger = console->getMachineDebugger();
6119 if (machineDebugger)
6120 {
6121 machineDebugger->flushQueuedSettings();
6122 }
6123
6124 /*
6125 * Shared Folders
6126 */
6127 if (console->getVMMDev()->isShFlActive())
6128 {
6129 /// @todo (dmik)
6130 // does the code below call Console from the other thread?
6131 // Not sure, so leave the lock just in case
6132 alock.leave();
6133
6134 for (SharedFolderDataMap::const_iterator
6135 it = task->mSharedFolders.begin();
6136 it != task->mSharedFolders.end();
6137 ++ it)
6138 {
6139 hrc = console->createSharedFolder ((*it).first, (*it).second);
6140 CheckComRCBreakRC (hrc);
6141 }
6142
6143 /* enter the lock again */
6144 alock.enter();
6145
6146 CheckComRCBreakRC (hrc);
6147 }
6148
6149 /*
6150 * Capture USB devices.
6151 */
6152 hrc = console->captureUSBDevices (pVM);
6153 CheckComRCBreakRC (hrc);
6154
6155 /* leave the lock before a lengthy operation */
6156 alock.leave();
6157
6158 /* Load saved state? */
6159 if (!!task->mSavedStateFile)
6160 {
6161 LogFlowFunc (("Restoring saved state from '%s'...\n",
6162 task->mSavedStateFile.raw()));
6163
6164 vrc = VMR3Load (pVM, task->mSavedStateFile,
6165 Console::stateProgressCallback,
6166 static_cast <VMProgressTask *> (task.get()));
6167
6168 /* Start/Resume the VM execution */
6169 if (VBOX_SUCCESS (vrc))
6170 {
6171 vrc = VMR3Resume (pVM);
6172 AssertRC (vrc);
6173 }
6174
6175 /* Power off in case we failed loading or resuming the VM */
6176 if (VBOX_FAILURE (vrc))
6177 {
6178 int vrc2 = VMR3PowerOff (pVM);
6179 AssertRC (vrc2);
6180 }
6181 }
6182 else
6183 {
6184 /* Power on the VM (i.e. start executing) */
6185 vrc = VMR3PowerOn(pVM);
6186 AssertRC (vrc);
6187 }
6188
6189 /* enter the lock again */
6190 alock.enter();
6191 }
6192 while (0);
6193
6194 /* On failure, destroy the VM */
6195 if (FAILED (hrc) || VBOX_FAILURE (vrc))
6196 {
6197 /* preserve existing error info */
6198 ErrorInfoKeeper eik;
6199
6200 /* powerDown() will call VMR3Destroy() and do all necessary
6201 * cleanup (VRDP, USB devices) */
6202 HRESULT hrc2 = console->powerDown();
6203 AssertComRC (hrc2);
6204 }
6205 }
6206 else
6207 {
6208 /*
6209 * If VMR3Create() failed it has released the VM memory.
6210 */
6211 console->mpVM = NULL;
6212 }
6213
6214 if (SUCCEEDED (hrc) && VBOX_FAILURE (vrc))
6215 {
6216 /* If VMR3Create() or one of the other calls in this function fail,
6217 * an appropriate error message has been set in task->mErrorMsg.
6218 * However since that happens via a callback, the hrc status code in
6219 * this function is not updated.
6220 */
6221 if (task->mErrorMsg.isNull())
6222 {
6223 /* If the error message is not set but we've got a failure,
6224 * convert the VBox status code into a meaningfulerror message.
6225 * This becomes unused once all the sources of errors set the
6226 * appropriate error message themselves.
6227 */
6228 AssertMsgFailed (("Missing error message during powerup for "
6229 "status code %Vrc\n", vrc));
6230 task->mErrorMsg = Utf8StrFmt (
6231 tr ("Failed to start VM execution (%Vrc)"), vrc);
6232 }
6233
6234 /* Set the error message as the COM error.
6235 * Progress::notifyComplete() will pick it up later. */
6236 hrc = setError (E_FAIL, task->mErrorMsg);
6237 break;
6238 }
6239 }
6240 while (0);
6241
6242 if (console->mMachineState == MachineState_Starting ||
6243 console->mMachineState == MachineState_Restoring)
6244 {
6245 /* We are still in the Starting/Restoring state. This means one of:
6246 *
6247 * 1) we failed before VMR3Create() was called;
6248 * 2) VMR3Create() failed.
6249 *
6250 * In both cases, there is no need to call powerDown(), but we still
6251 * need to go back to the PoweredOff/Saved state. Reuse
6252 * vmstateChangeCallback() for that purpose.
6253 */
6254
6255 /* preserve existing error info */
6256 ErrorInfoKeeper eik;
6257
6258 Assert (console->mpVM == NULL);
6259 vmstateChangeCallback (NULL, VMSTATE_TERMINATED, VMSTATE_CREATING,
6260 console);
6261 }
6262
6263 /*
6264 * Evaluate the final result. Note that the appropriate mMachineState value
6265 * is already set by vmstateChangeCallback() in all cases.
6266 */
6267
6268 /* leave the lock, don't need it any more */
6269 alock.leave();
6270
6271 if (SUCCEEDED (hrc))
6272 {
6273 /* Notify the progress object of the success */
6274 task->mProgress->notifyComplete (S_OK);
6275 }
6276 else
6277 {
6278 /* The progress object will fetch the current error info */
6279 task->mProgress->notifyComplete (hrc);
6280
6281 LogRel (("Power up failed (vrc=%Vrc, hrc=%Rhrc (%#08X))\n", vrc, hrc, hrc));
6282 }
6283
6284#if defined(RT_OS_WINDOWS)
6285 /* uninitialize COM */
6286 CoUninitialize();
6287#endif
6288
6289 LogFlowFuncLeave();
6290
6291 return VINF_SUCCESS;
6292}
6293
6294
6295/**
6296 * Reconfigures a VDI.
6297 *
6298 * @param pVM The VM handle.
6299 * @param hda The harddisk attachment.
6300 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
6301 * @return VBox status code.
6302 */
6303static DECLCALLBACK(int) reconfigureVDI(PVM pVM, IHardDiskAttachment *hda, HRESULT *phrc)
6304{
6305 LogFlowFunc (("pVM=%p hda=%p phrc=%p\n", pVM, hda, phrc));
6306
6307 int rc;
6308 HRESULT hrc;
6309 char *psz = NULL;
6310 BSTR str = NULL;
6311 *phrc = S_OK;
6312#define STR_CONV() do { rc = RTUtf16ToUtf8(str, &psz); RC_CHECK(); } while (0)
6313#define STR_FREE() do { if (str) { SysFreeString(str); str = NULL; } if (psz) { RTStrFree(psz); psz = NULL; } } while (0)
6314#define RC_CHECK() do { if (VBOX_FAILURE(rc)) { AssertMsgFailed(("rc=%Vrc\n", rc)); STR_FREE(); return rc; } } while (0)
6315#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%Rhrc (%#x)\n", hrc, hrc)); STR_FREE(); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
6316
6317 /*
6318 * Figure out which IDE device this is.
6319 */
6320 ComPtr<IHardDisk> hardDisk;
6321 hrc = hda->COMGETTER(HardDisk)(hardDisk.asOutParam()); H();
6322 StorageBus_T enmBus;
6323 hrc = hda->COMGETTER(Bus)(&enmBus); H();
6324 LONG lDev;
6325 hrc = hda->COMGETTER(Device)(&lDev); H();
6326 LONG lChannel;
6327 hrc = hda->COMGETTER(Channel)(&lChannel); H();
6328
6329 int iLUN;
6330 switch (enmBus)
6331 {
6332 case StorageBus_IDE:
6333 {
6334 if (lChannel >= 2)
6335 {
6336 AssertMsgFailed(("invalid controller channel number: %d\n", lChannel));
6337 return VERR_GENERAL_FAILURE;
6338 }
6339
6340 if (lDev >= 2)
6341 {
6342 AssertMsgFailed(("invalid controller device number: %d\n", lDev));
6343 return VERR_GENERAL_FAILURE;
6344 }
6345 iLUN = 2*lChannel + lDev;
6346 }
6347 break;
6348 case StorageBus_SATA:
6349 iLUN = lChannel;
6350 break;
6351 default:
6352 AssertMsgFailed(("invalid disk controller type: %d\n", enmBus));
6353 return VERR_GENERAL_FAILURE;
6354 }
6355
6356 /*
6357 * Is there an existing LUN? If not create it.
6358 * We ASSUME that this will NEVER collide with the DVD.
6359 */
6360 PCFGMNODE pCfg;
6361 PCFGMNODE pLunL1 = CFGMR3GetChildF(CFGMR3GetRoot(pVM), "Devices/piix3ide/0/LUN#%d/AttachedDriver/", iLUN);
6362 if (!pLunL1)
6363 {
6364 PCFGMNODE pInst = CFGMR3GetChild(CFGMR3GetRoot(pVM), "Devices/piix3ide/0/");
6365 AssertReturn(pInst, VERR_INTERNAL_ERROR);
6366
6367 PCFGMNODE pLunL0;
6368 rc = CFGMR3InsertNodeF(pInst, &pLunL0, "LUN#%d", iLUN); RC_CHECK();
6369 rc = CFGMR3InsertString(pLunL0, "Driver", "Block"); RC_CHECK();
6370 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
6371 rc = CFGMR3InsertString(pCfg, "Type", "HardDisk"); RC_CHECK();
6372 rc = CFGMR3InsertInteger(pCfg, "Mountable", 0); RC_CHECK();
6373
6374 rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1); RC_CHECK();
6375 rc = CFGMR3InsertString(pLunL1, "Driver", "VBoxHDD"); RC_CHECK();
6376 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
6377 }
6378 else
6379 {
6380#ifdef VBOX_STRICT
6381 char *pszDriver;
6382 rc = CFGMR3QueryStringAlloc(pLunL1, "Driver", &pszDriver); RC_CHECK();
6383 Assert(!strcmp(pszDriver, "VBoxHDD"));
6384 MMR3HeapFree(pszDriver);
6385#endif
6386
6387 /*
6388 * Check if things has changed.
6389 */
6390 pCfg = CFGMR3GetChild(pLunL1, "Config");
6391 AssertReturn(pCfg, VERR_INTERNAL_ERROR);
6392
6393 /* the image */
6394 /// @todo (dmik) we temporarily use the location property to
6395 // determine the image file name. This is subject to change
6396 // when iSCSI disks are here (we should either query a
6397 // storage-specific interface from IHardDisk, or "standardize"
6398 // the location property)
6399 hrc = hardDisk->COMGETTER(Location)(&str); H();
6400 STR_CONV();
6401 char *pszPath;
6402 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
6403 if (!strcmp(psz, pszPath))
6404 {
6405 /* parent images. */
6406 ComPtr<IHardDisk> parentHardDisk = hardDisk;
6407 for (PCFGMNODE pParent = pCfg;;)
6408 {
6409 MMR3HeapFree(pszPath);
6410 pszPath = NULL;
6411 STR_FREE();
6412
6413 /* get parent */
6414 ComPtr<IHardDisk> curHardDisk;
6415 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
6416 PCFGMNODE pCur;
6417 pCur = CFGMR3GetChild(pParent, "Parent");
6418 if (!pCur && !curHardDisk)
6419 {
6420 /* no change */
6421 LogFlowFunc (("No change!\n"));
6422 return VINF_SUCCESS;
6423 }
6424 if (!pCur || !curHardDisk)
6425 break;
6426
6427 /* compare paths. */
6428 /// @todo (dmik) we temporarily use the location property to
6429 // determine the image file name. This is subject to change
6430 // when iSCSI disks are here (we should either query a
6431 // storage-specific interface from IHardDisk, or "standardize"
6432 // the location property)
6433 hrc = curHardDisk->COMGETTER(Location)(&str); H();
6434 STR_CONV();
6435 rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pszPath); RC_CHECK();
6436 if (strcmp(psz, pszPath))
6437 break;
6438
6439 /* next */
6440 pParent = pCur;
6441 parentHardDisk = curHardDisk;
6442 }
6443
6444 }
6445 else
6446 LogFlowFunc (("LUN#%d: old leaf image '%s'\n", iLUN, pszPath));
6447
6448 MMR3HeapFree(pszPath);
6449 STR_FREE();
6450
6451 /*
6452 * Detach the driver and replace the config node.
6453 */
6454 rc = PDMR3DeviceDetach(pVM, "piix3ide", 0, iLUN); RC_CHECK();
6455 CFGMR3RemoveNode(pCfg);
6456 rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg); RC_CHECK();
6457 }
6458
6459 /*
6460 * Create the driver configuration.
6461 */
6462 /// @todo (dmik) we temporarily use the location property to
6463 // determine the image file name. This is subject to change
6464 // when iSCSI disks are here (we should either query a
6465 // storage-specific interface from IHardDisk, or "standardize"
6466 // the location property)
6467 hrc = hardDisk->COMGETTER(Location)(&str); H();
6468 STR_CONV();
6469 LogFlowFunc (("LUN#%d: leaf image '%s'\n", iLUN, psz));
6470 rc = CFGMR3InsertString(pCfg, "Path", psz); RC_CHECK();
6471 STR_FREE();
6472 /* Create an inversed tree of parents. */
6473 ComPtr<IHardDisk> parentHardDisk = hardDisk;
6474 for (PCFGMNODE pParent = pCfg;;)
6475 {
6476 ComPtr<IHardDisk> curHardDisk;
6477 hrc = parentHardDisk->COMGETTER(Parent)(curHardDisk.asOutParam()); H();
6478 if (!curHardDisk)
6479 break;
6480
6481 PCFGMNODE pCur;
6482 rc = CFGMR3InsertNode(pParent, "Parent", &pCur); RC_CHECK();
6483 /// @todo (dmik) we temporarily use the location property to
6484 // determine the image file name. This is subject to change
6485 // when iSCSI disks are here (we should either query a
6486 // storage-specific interface from IHardDisk, or "standardize"
6487 // the location property)
6488 hrc = curHardDisk->COMGETTER(Location)(&str); H();
6489 STR_CONV();
6490 rc = CFGMR3InsertString(pCur, "Path", psz); RC_CHECK();
6491 STR_FREE();
6492
6493 /* next */
6494 pParent = pCur;
6495 parentHardDisk = curHardDisk;
6496 }
6497
6498 /*
6499 * Attach the new driver.
6500 */
6501 rc = PDMR3DeviceAttach(pVM, "piix3ide", 0, iLUN, NULL); RC_CHECK();
6502
6503 LogFlowFunc (("Returns success\n"));
6504 return rc;
6505}
6506
6507
6508/**
6509 * Thread for executing the saved state operation.
6510 *
6511 * @param Thread The thread handle.
6512 * @param pvUser Pointer to a VMSaveTask structure.
6513 * @return VINF_SUCCESS (ignored).
6514 *
6515 * @note Locks the Console object for writing.
6516 */
6517/*static*/
6518DECLCALLBACK (int) Console::saveStateThread (RTTHREAD Thread, void *pvUser)
6519{
6520 LogFlowFuncEnter();
6521
6522 std::auto_ptr <VMSaveTask> task (static_cast <VMSaveTask *> (pvUser));
6523 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
6524
6525 Assert (!task->mSavedStateFile.isNull());
6526 Assert (!task->mProgress.isNull());
6527
6528 const ComObjPtr <Console> &that = task->mConsole;
6529
6530 /*
6531 * Note: no need to use addCaller() to protect Console or addVMCaller() to
6532 * protect mpVM because VMSaveTask does that
6533 */
6534
6535 Utf8Str errMsg;
6536 HRESULT rc = S_OK;
6537
6538 if (task->mIsSnapshot)
6539 {
6540 Assert (!task->mServerProgress.isNull());
6541 LogFlowFunc (("Waiting until the server creates differencing VDIs...\n"));
6542
6543 rc = task->mServerProgress->WaitForCompletion (-1);
6544 if (SUCCEEDED (rc))
6545 {
6546 HRESULT result = S_OK;
6547 rc = task->mServerProgress->COMGETTER(ResultCode) (&result);
6548 if (SUCCEEDED (rc))
6549 rc = result;
6550 }
6551 }
6552
6553 if (SUCCEEDED (rc))
6554 {
6555 LogFlowFunc (("Saving the state to '%s'...\n", task->mSavedStateFile.raw()));
6556
6557 int vrc = VMR3Save (that->mpVM, task->mSavedStateFile,
6558 Console::stateProgressCallback,
6559 static_cast <VMProgressTask *> (task.get()));
6560 if (VBOX_FAILURE (vrc))
6561 {
6562 errMsg = Utf8StrFmt (
6563 Console::tr ("Failed to save the machine state to '%s' (%Vrc)"),
6564 task->mSavedStateFile.raw(), vrc);
6565 rc = E_FAIL;
6566 }
6567 }
6568
6569 /* lock the console sonce we're going to access it */
6570 AutoWriteLock thatLock (that);
6571
6572 if (SUCCEEDED (rc))
6573 {
6574 if (task->mIsSnapshot)
6575 do
6576 {
6577 LogFlowFunc (("Reattaching new differencing VDIs...\n"));
6578
6579 ComPtr <IHardDiskAttachmentCollection> hdaColl;
6580 rc = that->mMachine->COMGETTER(HardDiskAttachments) (hdaColl.asOutParam());
6581 if (FAILED (rc))
6582 break;
6583 ComPtr <IHardDiskAttachmentEnumerator> hdaEn;
6584 rc = hdaColl->Enumerate (hdaEn.asOutParam());
6585 if (FAILED (rc))
6586 break;
6587 BOOL more = FALSE;
6588 while (SUCCEEDED (rc = hdaEn->HasMore (&more)) && more)
6589 {
6590 ComPtr <IHardDiskAttachment> hda;
6591 rc = hdaEn->GetNext (hda.asOutParam());
6592 if (FAILED (rc))
6593 break;
6594
6595 PVMREQ pReq;
6596 IHardDiskAttachment *pHda = hda;
6597 /*
6598 * don't leave the lock since reconfigureVDI isn't going to
6599 * access Console.
6600 */
6601 int vrc = VMR3ReqCall (that->mpVM, &pReq, RT_INDEFINITE_WAIT,
6602 (PFNRT)reconfigureVDI, 3, that->mpVM,
6603 pHda, &rc);
6604 if (VBOX_SUCCESS (rc))
6605 rc = pReq->iStatus;
6606 VMR3ReqFree (pReq);
6607 if (FAILED (rc))
6608 break;
6609 if (VBOX_FAILURE (vrc))
6610 {
6611 errMsg = Utf8StrFmt (Console::tr ("%Vrc"), vrc);
6612 rc = E_FAIL;
6613 break;
6614 }
6615 }
6616 }
6617 while (0);
6618 }
6619
6620 /* finalize the procedure regardless of the result */
6621 if (task->mIsSnapshot)
6622 {
6623 /*
6624 * finalize the requested snapshot object.
6625 * This will reset the machine state to the state it had right
6626 * before calling mControl->BeginTakingSnapshot().
6627 */
6628 that->mControl->EndTakingSnapshot (SUCCEEDED (rc));
6629 }
6630 else
6631 {
6632 /*
6633 * finalize the requested save state procedure.
6634 * In case of success, the server will set the machine state to Saved;
6635 * in case of failure it will reset the it to the state it had right
6636 * before calling mControl->BeginSavingState().
6637 */
6638 that->mControl->EndSavingState (SUCCEEDED (rc));
6639 }
6640
6641 /* synchronize the state with the server */
6642 if (task->mIsSnapshot || FAILED (rc))
6643 {
6644 if (task->mLastMachineState == MachineState_Running)
6645 {
6646 /* restore the paused state if appropriate */
6647 that->setMachineStateLocally (MachineState_Paused);
6648 /* restore the running state if appropriate */
6649 that->Resume();
6650 }
6651 else
6652 that->setMachineStateLocally (task->mLastMachineState);
6653 }
6654 else
6655 {
6656 /*
6657 * The machine has been successfully saved, so power it down
6658 * (vmstateChangeCallback() will set state to Saved on success).
6659 * Note: we release the task's VM caller, otherwise it will
6660 * deadlock.
6661 */
6662 task->releaseVMCaller();
6663
6664 rc = that->powerDown();
6665 }
6666
6667 /* notify the progress object about operation completion */
6668 if (SUCCEEDED (rc))
6669 task->mProgress->notifyComplete (S_OK);
6670 else
6671 {
6672 if (!errMsg.isNull())
6673 task->mProgress->notifyComplete (rc,
6674 COM_IIDOF(IConsole), Console::getComponentName(), errMsg);
6675 else
6676 task->mProgress->notifyComplete (rc);
6677 }
6678
6679 LogFlowFuncLeave();
6680 return VINF_SUCCESS;
6681}
6682
6683/**
6684 * Thread for powering down the Console.
6685 *
6686 * @param Thread The thread handle.
6687 * @param pvUser Pointer to the VMTask structure.
6688 * @return VINF_SUCCESS (ignored).
6689 *
6690 * @note Locks the Console object for writing.
6691 */
6692/*static*/
6693DECLCALLBACK (int) Console::powerDownThread (RTTHREAD Thread, void *pvUser)
6694{
6695 LogFlowFuncEnter();
6696
6697 std::auto_ptr <VMTask> task (static_cast <VMTask *> (pvUser));
6698 AssertReturn (task.get(), VERR_INVALID_PARAMETER);
6699
6700 AssertReturn (task->isOk(), VERR_GENERAL_FAILURE);
6701
6702 const ComObjPtr <Console> &that = task->mConsole;
6703
6704 /*
6705 * Note: no need to use addCaller() to protect Console
6706 * because VMTask does that
6707 */
6708
6709 /* release VM caller to let powerDown() proceed */
6710 task->releaseVMCaller();
6711
6712 HRESULT rc = that->powerDown();
6713 AssertComRC (rc);
6714
6715 LogFlowFuncLeave();
6716 return VINF_SUCCESS;
6717}
6718
6719/**
6720 * The Main status driver instance data.
6721 */
6722typedef struct DRVMAINSTATUS
6723{
6724 /** The LED connectors. */
6725 PDMILEDCONNECTORS ILedConnectors;
6726 /** Pointer to the LED ports interface above us. */
6727 PPDMILEDPORTS pLedPorts;
6728 /** Pointer to the array of LED pointers. */
6729 PPDMLED *papLeds;
6730 /** The unit number corresponding to the first entry in the LED array. */
6731 RTUINT iFirstLUN;
6732 /** The unit number corresponding to the last entry in the LED array.
6733 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
6734 RTUINT iLastLUN;
6735} DRVMAINSTATUS, *PDRVMAINSTATUS;
6736
6737
6738/**
6739 * Notification about a unit which have been changed.
6740 *
6741 * The driver must discard any pointers to data owned by
6742 * the unit and requery it.
6743 *
6744 * @param pInterface Pointer to the interface structure containing the called function pointer.
6745 * @param iLUN The unit number.
6746 */
6747DECLCALLBACK(void) Console::drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
6748{
6749 PDRVMAINSTATUS pData = (PDRVMAINSTATUS)(void *)pInterface;
6750 if (iLUN >= pData->iFirstLUN && iLUN <= pData->iLastLUN)
6751 {
6752 PPDMLED pLed;
6753 int rc = pData->pLedPorts->pfnQueryStatusLed(pData->pLedPorts, iLUN, &pLed);
6754 if (VBOX_FAILURE(rc))
6755 pLed = NULL;
6756 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLUN - pData->iFirstLUN], pLed);
6757 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
6758 }
6759}
6760
6761
6762/**
6763 * Queries an interface to the driver.
6764 *
6765 * @returns Pointer to interface.
6766 * @returns NULL if the interface was not supported by the driver.
6767 * @param pInterface Pointer to this interface structure.
6768 * @param enmInterface The requested interface identification.
6769 */
6770DECLCALLBACK(void *) Console::drvStatus_QueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
6771{
6772 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
6773 PDRVMAINSTATUS pDrv = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
6774 switch (enmInterface)
6775 {
6776 case PDMINTERFACE_BASE:
6777 return &pDrvIns->IBase;
6778 case PDMINTERFACE_LED_CONNECTORS:
6779 return &pDrv->ILedConnectors;
6780 default:
6781 return NULL;
6782 }
6783}
6784
6785
6786/**
6787 * Destruct a status driver instance.
6788 *
6789 * @returns VBox status.
6790 * @param pDrvIns The driver instance data.
6791 */
6792DECLCALLBACK(void) Console::drvStatus_Destruct(PPDMDRVINS pDrvIns)
6793{
6794 PDRVMAINSTATUS pData = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
6795 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
6796 if (pData->papLeds)
6797 {
6798 unsigned iLed = pData->iLastLUN - pData->iFirstLUN + 1;
6799 while (iLed-- > 0)
6800 ASMAtomicXchgPtr((void * volatile *)&pData->papLeds[iLed], NULL);
6801 }
6802}
6803
6804
6805/**
6806 * Construct a status driver instance.
6807 *
6808 * @returns VBox status.
6809 * @param pDrvIns The driver instance data.
6810 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
6811 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
6812 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
6813 * iInstance it's expected to be used a bit in this function.
6814 */
6815DECLCALLBACK(int) Console::drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
6816{
6817 PDRVMAINSTATUS pData = PDMINS2DATA(pDrvIns, PDRVMAINSTATUS);
6818 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
6819
6820 /*
6821 * Validate configuration.
6822 */
6823 if (!CFGMR3AreValuesValid(pCfgHandle, "papLeds\0First\0Last\0"))
6824 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
6825 PPDMIBASE pBaseIgnore;
6826 int rc = pDrvIns->pDrvHlp->pfnAttach(pDrvIns, &pBaseIgnore);
6827 if (rc != VERR_PDM_NO_ATTACHED_DRIVER)
6828 {
6829 AssertMsgFailed(("Configuration error: Not possible to attach anything to this driver!\n"));
6830 return VERR_PDM_DRVINS_NO_ATTACH;
6831 }
6832
6833 /*
6834 * Data.
6835 */
6836 pDrvIns->IBase.pfnQueryInterface = Console::drvStatus_QueryInterface;
6837 pData->ILedConnectors.pfnUnitChanged = Console::drvStatus_UnitChanged;
6838
6839 /*
6840 * Read config.
6841 */
6842 rc = CFGMR3QueryPtr(pCfgHandle, "papLeds", (void **)&pData->papLeds);
6843 if (VBOX_FAILURE(rc))
6844 {
6845 AssertMsgFailed(("Configuration error: Failed to query the \"papLeds\" value! rc=%Vrc\n", rc));
6846 return rc;
6847 }
6848
6849 rc = CFGMR3QueryU32(pCfgHandle, "First", &pData->iFirstLUN);
6850 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
6851 pData->iFirstLUN = 0;
6852 else if (VBOX_FAILURE(rc))
6853 {
6854 AssertMsgFailed(("Configuration error: Failed to query the \"First\" value! rc=%Vrc\n", rc));
6855 return rc;
6856 }
6857
6858 rc = CFGMR3QueryU32(pCfgHandle, "Last", &pData->iLastLUN);
6859 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
6860 pData->iLastLUN = 0;
6861 else if (VBOX_FAILURE(rc))
6862 {
6863 AssertMsgFailed(("Configuration error: Failed to query the \"Last\" value! rc=%Vrc\n", rc));
6864 return rc;
6865 }
6866 if (pData->iFirstLUN > pData->iLastLUN)
6867 {
6868 AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pData->iFirstLUN, pData->iLastLUN));
6869 return VERR_GENERAL_FAILURE;
6870 }
6871
6872 /*
6873 * Get the ILedPorts interface of the above driver/device and
6874 * query the LEDs we want.
6875 */
6876 pData->pLedPorts = (PPDMILEDPORTS)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_LED_PORTS);
6877 if (!pData->pLedPorts)
6878 {
6879 AssertMsgFailed(("Configuration error: No led ports interface above!\n"));
6880 return VERR_PDM_MISSING_INTERFACE_ABOVE;
6881 }
6882
6883 for (unsigned i = pData->iFirstLUN; i <= pData->iLastLUN; i++)
6884 Console::drvStatus_UnitChanged(&pData->ILedConnectors, i);
6885
6886 return VINF_SUCCESS;
6887}
6888
6889
6890/**
6891 * Keyboard driver registration record.
6892 */
6893const PDMDRVREG Console::DrvStatusReg =
6894{
6895 /* u32Version */
6896 PDM_DRVREG_VERSION,
6897 /* szDriverName */
6898 "MainStatus",
6899 /* pszDescription */
6900 "Main status driver (Main as in the API).",
6901 /* fFlags */
6902 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
6903 /* fClass. */
6904 PDM_DRVREG_CLASS_STATUS,
6905 /* cMaxInstances */
6906 ~0,
6907 /* cbInstance */
6908 sizeof(DRVMAINSTATUS),
6909 /* pfnConstruct */
6910 Console::drvStatus_Construct,
6911 /* pfnDestruct */
6912 Console::drvStatus_Destruct,
6913 /* pfnIOCtl */
6914 NULL,
6915 /* pfnPowerOn */
6916 NULL,
6917 /* pfnReset */
6918 NULL,
6919 /* pfnSuspend */
6920 NULL,
6921 /* pfnResume */
6922 NULL,
6923 /* pfnDetach */
6924 NULL
6925};
6926
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