VirtualBox

source: vbox/trunk/src/VBox/Main/VirtualBoxImpl.cpp@ 2397

Last change on this file since 2397 was 2358, checked in by vboxsync, 18 years ago

New VMDK code.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 138.0 KB
Line 
1/** @file
2 *
3 * VirtualBox COM class implementation
4 */
5
6/*
7 * Copyright (C) 2006 InnoTek Systemberatung GmbH
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 as published by the Free Software Foundation,
13 * in version 2 as it comes in the "COPYING" file of the VirtualBox OSE
14 * distribution. VirtualBox OSE is distributed in the hope that it will
15 * be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * If you received this file as part of a commercial VirtualBox
18 * distribution, then only the terms of your commercial VirtualBox
19 * license agreement apply instead of the previous paragraph.
20 */
21
22#include "VirtualBoxImpl.h"
23#include "MachineImpl.h"
24#include "HardDiskImpl.h"
25#include "DVDImageImpl.h"
26#include "FloppyImageImpl.h"
27#include "SharedFolderImpl.h"
28#include "ProgressImpl.h"
29#include "HostImpl.h"
30#include "USBControllerImpl.h"
31#include "SystemPropertiesImpl.h"
32#include "Logging.h"
33
34#include "GuestOSTypeImpl.h"
35
36#ifdef __WIN__
37#include "win32/svchlp.h"
38#endif
39
40#include <stdio.h>
41#include <stdlib.h>
42#include <VBox/err.h>
43#include <iprt/path.h>
44#include <iprt/dir.h>
45#include <iprt/file.h>
46#include <iprt/string.h>
47#include <iprt/uuid.h>
48#include <iprt/thread.h>
49#include <iprt/process.h>
50#include <VBox/param.h>
51#include <VBox/VBoxHDD.h>
52#include <VBox/VBoxHDD-new.h>
53#include <VBox/ostypes.h>
54#include <VBox/version.h>
55
56#include <algorithm>
57#include <set>
58#include <memory> // for auto_ptr
59
60// defines
61/////////////////////////////////////////////////////////////////////////////
62
63#ifdef __DARWIN__
64#define VBOXCONFIGDIR "Library/VirtualBox"
65#else
66#define VBOXCONFIGDIR ".VirtualBox"
67#endif
68#define VBOXCONFIGGLOBALFILE "VirtualBox.xml"
69
70// globals
71/////////////////////////////////////////////////////////////////////////////
72
73static const char DefaultGlobalConfig [] =
74{
75 "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" RTFILE_LINEFEED
76 "<!-- InnoTek VirtualBox Global Configuration -->" RTFILE_LINEFEED
77 "<VirtualBox xmlns=\"" VBOX_XML_NAMESPACE "\" "
78 "version=\"" VBOX_XML_VERSION "-" VBOX_XML_PLATFORM "\">" RTFILE_LINEFEED
79 " <Global>"RTFILE_LINEFEED
80 " <MachineRegistry/>"RTFILE_LINEFEED
81 " <DiskRegistry/>"RTFILE_LINEFEED
82 " <USBDeviceFilters/>"RTFILE_LINEFEED
83 " <SystemProperties/>"RTFILE_LINEFEED
84 " </Global>"RTFILE_LINEFEED
85 "</VirtualBox>"RTFILE_LINEFEED
86};
87
88// static
89Bstr VirtualBox::sVersion;
90
91// constructor / destructor
92/////////////////////////////////////////////////////////////////////////////
93
94VirtualBox::VirtualBox()
95 : mAsyncEventThread (NIL_RTTHREAD)
96 , mAsyncEventQ (NULL)
97{}
98
99VirtualBox::~VirtualBox() {}
100
101HRESULT VirtualBox::FinalConstruct()
102{
103 LogFlowThisFunc (("\n"));
104
105 return init();
106}
107
108void VirtualBox::FinalRelease()
109{
110 LogFlowThisFunc (("\n"));
111
112 uninit();
113}
114
115VirtualBox::Data::Data()
116{
117}
118
119// public initializer/uninitializer for internal purposes only
120/////////////////////////////////////////////////////////////////////////////
121
122/**
123 * Initializes the VirtualBox object.
124 *
125 * @return COM result code
126 */
127HRESULT VirtualBox::init()
128{
129 /* Enclose the state transition NotReady->InInit->Ready */
130 AutoInitSpan autoInitSpan (this);
131 AssertReturn (autoInitSpan.isOk(), E_UNEXPECTED);
132
133 LogFlow (("===========================================================\n"));
134 LogFlowThisFuncEnter();
135
136 if (sVersion.isNull())
137 sVersion = VBOX_VERSION_STRING;
138 LogFlowThisFunc (("Version: %ls\n", sVersion.raw()));
139
140 int vrc = VINF_SUCCESS;
141 char buf [RTPATH_MAX];
142
143 /*
144 * Detect the VirtualBox home directory. Note that the code below must
145 * be in sync with the appropriate code in Logging.cpp
146 * (MainReleaseLoggerInit()).
147 */
148 {
149 /* check if an alternative VBox Home directory is set */
150 const char *vboxUserHome = getenv ("VBOX_USER_HOME");
151 if (vboxUserHome)
152 {
153 /* get the full path name */
154 vrc = RTPathAbs (vboxUserHome, buf, sizeof (buf));
155 if (VBOX_FAILURE (vrc))
156 return setError (E_FAIL,
157 tr ("Invalid home directory file path '%s' (%Vrc)"),
158 vboxUserHome, vrc);
159 unconst (mData.mHomeDir) = buf;
160 }
161 else
162 {
163 /* compose the config directory (full path) */
164 RTPathUserHome (buf, sizeof (buf));
165 unconst (mData.mHomeDir) = Utf8StrFmt ("%s%c%s", buf,
166 RTPATH_DELIMITER,
167 VBOXCONFIGDIR);
168 }
169
170 /* ensure the home directory exists */
171 if (!RTDirExists (mData.mHomeDir))
172 {
173 vrc = RTDirCreateFullPath (mData.mHomeDir, 0777);
174 if (VBOX_FAILURE (vrc))
175 {
176 return setError (E_FAIL,
177 tr ("Could not create the VirtualBox home directory '%s'"
178 "(%Vrc)"),
179 mData.mHomeDir.raw(), vrc);
180 }
181 }
182 }
183
184 /* compose the global config file name (always full path) */
185 Utf8StrFmt vboxConfigFile ("%s%c%s", mData.mHomeDir.raw(),
186 RTPATH_DELIMITER, VBOXCONFIGGLOBALFILE);
187
188 /* store the config file name */
189 unconst (mData.mCfgFile.mName) = vboxConfigFile;
190
191 /* lock the config file */
192 HRESULT rc = lockConfig();
193 if (SUCCEEDED (rc))
194 {
195 if (!isConfigLocked())
196 {
197 /*
198 * This means the config file not found. This is not fatal --
199 * we just create an empty one.
200 */
201 RTFILE handle = NIL_RTFILE;
202 int vrc = RTFileOpen (&handle, vboxConfigFile,
203 RTFILE_O_READWRITE | RTFILE_O_CREATE |
204 RTFILE_O_DENY_WRITE | RTFILE_O_WRITE_THROUGH);
205 if (VBOX_SUCCESS (vrc))
206 vrc = RTFileWrite (handle,
207 (void *) DefaultGlobalConfig,
208 sizeof (DefaultGlobalConfig), NULL);
209 if (VBOX_FAILURE (vrc))
210 {
211 rc = setError (E_FAIL, tr ("Could not create the default settings file "
212 "'%s' (%Vrc)"),
213 vboxConfigFile.raw(), vrc);
214 }
215 else
216 {
217 mData.mCfgFile.mHandle = handle;
218 /* we do not close the file to simulate lockConfig() */
219 }
220 }
221 }
222
223 /* initialize our Xerces XML subsystem */
224 if (SUCCEEDED (rc))
225 {
226 int vrc = CFGLDRInitialize();
227 if (VBOX_FAILURE (vrc))
228 rc = setError (E_FAIL, tr ("Could not initialize the XML parser (%Vrc)"),
229 vrc);
230 }
231
232 if (SUCCEEDED (rc))
233 {
234 CFGHANDLE configLoader = NULL;
235 char *loaderError = NULL;
236
237 /* load the config file */
238 int vrc = CFGLDRLoad (&configLoader, vboxConfigFile, mData.mCfgFile.mHandle,
239 XmlSchemaNS, true, cfgLdrEntityResolver,
240 &loaderError);
241 if (VBOX_SUCCESS (vrc))
242 {
243 CFGNODE global = NULL;
244 CFGLDRGetNode (configLoader, "VirtualBox/Global", 0, &global);
245 Assert (global);
246
247 do
248 {
249 /* create the host object early, machines will need it */
250 unconst (mData.mHost).createObject();
251 rc = mData.mHost->init (this);
252 ComAssertComRCBreak (rc, rc = rc);
253
254 unconst (mData.mSystemProperties).createObject();
255 rc = mData.mSystemProperties->init (this);
256 ComAssertComRCBreak (rc, rc = rc);
257
258 rc = loadDisks (global);
259 CheckComRCBreakRC ((rc));
260
261 /* guest OS type objects, needed by the machines */
262 rc = registerGuestOSTypes();
263 ComAssertComRCBreak (rc, rc = rc);
264
265 /* machines */
266 rc = loadMachines (global);
267 CheckComRCBreakRC ((rc));
268
269 /* host data (USB filters) */
270 rc = mData.mHost->loadSettings (global);
271 CheckComRCBreakRC ((rc));
272
273 rc = mData.mSystemProperties->loadSettings (global);
274 CheckComRCBreakRC ((rc));
275
276 /* check hard disk consistency */
277/// @todo (r=dmik) add IVirtualBox::cleanupHardDisks() instead or similar
278// for (HardDiskList::const_iterator it = mData.mHardDisks.begin();
279// it != mData.mHardDisks.end() && SUCCEEDED (rc);
280// ++ it)
281// {
282// rc = (*it)->checkConsistency();
283// }
284// CheckComRCBreakRC ((rc));
285 }
286 while (0);
287
288 /// @todo (dmik) if successful, check for orphan (unused) diffs
289 // that might be left because of the server crash, and remove them.
290
291 CFGLDRReleaseNode (global);
292 CFGLDRFree(configLoader);
293 }
294 else
295 {
296 rc = setError (E_FAIL,
297 tr ("Could not load the settings file '%ls' (%Vrc)%s%s"),
298 mData.mCfgFile.mName.raw(), vrc,
299 loaderError ? ".\n" : "", loaderError ? loaderError : "");
300 }
301
302 if (loaderError)
303 RTMemTmpFree (loaderError);
304 }
305
306 if (SUCCEEDED (rc))
307 {
308 /* start the client watcher thread */
309#if defined(__WIN__)
310 unconst (mWatcherData.mUpdateReq) = ::CreateEvent (NULL, FALSE, FALSE, NULL);
311#else
312 RTSemEventCreate (&unconst (mWatcherData.mUpdateReq));
313#endif
314 int vrc = RTThreadCreate (&unconst (mWatcherData.mThread),
315 clientWatcher, (void *) this,
316 0, RTTHREADTYPE_MAIN_WORKER,
317 RTTHREADFLAGS_WAITABLE, "Watcher");
318 ComAssertRC (vrc);
319 if (VBOX_FAILURE (vrc))
320 rc = E_FAIL;
321 }
322
323 if (SUCCEEDED (rc)) do
324 {
325 /* start the async event handler thread */
326 int vrc = RTThreadCreate (&unconst (mAsyncEventThread), asyncEventHandler,
327 &unconst (mAsyncEventQ),
328 0, RTTHREADTYPE_MAIN_WORKER,
329 RTTHREADFLAGS_WAITABLE, "EventHandler");
330 ComAssertRCBreak (vrc, rc = E_FAIL);
331
332 /* wait until the thread sets mAsyncEventQ */
333 RTThreadUserWait (mAsyncEventThread, RT_INDEFINITE_WAIT);
334 ComAssertBreak (mAsyncEventQ, rc = E_FAIL);
335 }
336 while (0);
337
338 /* Confirm a successful initialization when it's the case */
339 if (SUCCEEDED (rc))
340 autoInitSpan.setSucceeded();
341
342 LogFlowThisFunc (("rc=%08X\n", rc));
343 LogFlowThisFuncLeave();
344 LogFlow (("===========================================================\n"));
345 return rc;
346}
347
348void VirtualBox::uninit()
349{
350 /* Enclose the state transition Ready->InUninit->NotReady */
351 AutoUninitSpan autoUninitSpan (this);
352 if (autoUninitSpan.uninitDone())
353 return;
354
355 LogFlow (("===========================================================\n"));
356 LogFlowThisFuncEnter();
357 LogFlowThisFunc (("initFailed()=%d\n", autoUninitSpan.initFailed()));
358
359 /* tell all our child objects we've been uninitialized */
360
361 LogFlowThisFunc (("Uninitializing machines (%d)...\n", mData.mMachines.size()));
362 if (mData.mMachines.size())
363 {
364 MachineList::iterator it = mData.mMachines.begin();
365 while (it != mData.mMachines.end())
366 (*it++)->uninit();
367 mData.mMachines.clear();
368 }
369
370 if (mData.mSystemProperties)
371 {
372 mData.mSystemProperties->uninit();
373 unconst (mData.mSystemProperties).setNull();
374 }
375
376 if (mData.mHost)
377 {
378 mData.mHost->uninit();
379 unconst (mData.mHost).setNull();
380 }
381
382 /*
383 * Uninit all other children still referenced by clients
384 * (unregistered machines, hard disks, DVD/floppy images,
385 * server-side progress operations).
386 */
387 uninitDependentChildren();
388
389 mData.mFloppyImages.clear();
390 mData.mDVDImages.clear();
391 mData.mHardDisks.clear();
392
393 mData.mHardDiskMap.clear();
394
395 mData.mProgressOperations.clear();
396
397 mData.mGuestOSTypes.clear();
398
399 /* unlock the config file */
400 unlockConfig();
401
402 LogFlowThisFunc (("Releasing callbacks...\n"));
403 if (mData.mCallbacks.size())
404 {
405 /* release all callbacks */
406 LogWarningFunc (("%d unregistered callbacks!\n",
407 mData.mCallbacks.size()));
408 mData.mCallbacks.clear();
409 }
410
411 LogFlowThisFunc (("Terminating the async event handler...\n"));
412 if (mAsyncEventThread != NIL_RTTHREAD)
413 {
414 /* signal to exit the event loop */
415 if (mAsyncEventQ->postEvent (NULL))
416 {
417 /*
418 * Wait for thread termination (only if we've successfully posted
419 * a NULL event!)
420 */
421 int vrc = RTThreadWait (mAsyncEventThread, 60000, NULL);
422 if (VBOX_FAILURE (vrc))
423 LogWarningFunc (("RTThreadWait(%RTthrd) -> %Vrc\n",
424 mAsyncEventThread, vrc));
425 }
426 else
427 {
428 AssertMsgFailed (("postEvent(NULL) failed\n"));
429 RTThreadWait (mAsyncEventThread, 0, NULL);
430 }
431
432 unconst (mAsyncEventThread) = NIL_RTTHREAD;
433 unconst (mAsyncEventQ) = NULL;
434 }
435
436 LogFlowThisFunc (("Terminating the client watcher...\n"));
437 if (mWatcherData.mThread != NIL_RTTHREAD)
438 {
439 /* signal the client watcher thread */
440 updateClientWatcher();
441 /* wait for the termination */
442 RTThreadWait (mWatcherData.mThread, RT_INDEFINITE_WAIT, NULL);
443 unconst (mWatcherData.mThread) = NIL_RTTHREAD;
444 }
445 mWatcherData.mProcesses.clear();
446#if defined(__WIN__)
447 if (mWatcherData.mUpdateReq != NULL)
448 {
449 ::CloseHandle (mWatcherData.mUpdateReq);
450 unconst (mWatcherData.mUpdateReq) = NULL;
451 }
452#else
453 if (mWatcherData.mUpdateReq != NIL_RTSEMEVENT)
454 {
455 RTSemEventDestroy (mWatcherData.mUpdateReq);
456 unconst (mWatcherData.mUpdateReq) = NIL_RTSEMEVENT;
457 }
458#endif
459
460 /* uninitialize the Xerces XML subsystem */
461 CFGLDRShutdown();
462
463 LogFlowThisFuncLeave();
464 LogFlow (("===========================================================\n"));
465}
466
467// IVirtualBox properties
468/////////////////////////////////////////////////////////////////////////////
469
470STDMETHODIMP VirtualBox::COMGETTER(Version) (BSTR *aVersion)
471{
472 if (!aVersion)
473 return E_INVALIDARG;
474
475 AutoCaller autoCaller (this);
476 CheckComRCReturnRC (autoCaller.rc());
477
478 sVersion.cloneTo (aVersion);
479 return S_OK;
480}
481
482STDMETHODIMP VirtualBox::COMGETTER(HomeFolder) (BSTR *aHomeFolder)
483{
484 if (!aHomeFolder)
485 return E_POINTER;
486
487 AutoCaller autoCaller (this);
488 CheckComRCReturnRC (autoCaller.rc());
489
490 mData.mHomeDir.cloneTo (aHomeFolder);
491 return S_OK;
492}
493
494STDMETHODIMP VirtualBox::COMGETTER(Host) (IHost **aHost)
495{
496 if (!aHost)
497 return E_POINTER;
498
499 AutoCaller autoCaller (this);
500 CheckComRCReturnRC (autoCaller.rc());
501
502 mData.mHost.queryInterfaceTo (aHost);
503 return S_OK;
504}
505
506STDMETHODIMP VirtualBox::COMGETTER(SystemProperties) (ISystemProperties **aSystemProperties)
507{
508 if (!aSystemProperties)
509 return E_POINTER;
510
511 AutoCaller autoCaller (this);
512 CheckComRCReturnRC (autoCaller.rc());
513
514 mData.mSystemProperties.queryInterfaceTo (aSystemProperties);
515 return S_OK;
516}
517
518/** @note Locks this object for reading. */
519STDMETHODIMP VirtualBox::COMGETTER(Machines) (IMachineCollection **aMachines)
520{
521 if (!aMachines)
522 return E_POINTER;
523
524 AutoCaller autoCaller (this);
525 CheckComRCReturnRC (autoCaller.rc());
526
527 ComObjPtr <MachineCollection> collection;
528 collection.createObject();
529
530 AutoReaderLock alock (this);
531 collection->init (mData.mMachines);
532 collection.queryInterfaceTo (aMachines);
533
534 return S_OK;
535}
536
537/** @note Locks this object for reading. */
538STDMETHODIMP VirtualBox::COMGETTER(HardDisks) (IHardDiskCollection **aHardDisks)
539{
540 if (!aHardDisks)
541 return E_POINTER;
542
543 AutoCaller autoCaller (this);
544 CheckComRCReturnRC (autoCaller.rc());
545
546 ComObjPtr <HardDiskCollection> collection;
547 collection.createObject();
548
549 AutoReaderLock alock (this);
550 collection->init (mData.mHardDisks);
551 collection.queryInterfaceTo (aHardDisks);
552
553 return S_OK;
554}
555
556/** @note Locks this object for reading. */
557STDMETHODIMP VirtualBox::COMGETTER(DVDImages) (IDVDImageCollection **aDVDImages)
558{
559 if (!aDVDImages)
560 return E_POINTER;
561
562 AutoCaller autoCaller (this);
563 CheckComRCReturnRC (autoCaller.rc());
564
565 ComObjPtr <DVDImageCollection> collection;
566 collection.createObject();
567
568 AutoReaderLock alock (this);
569 collection->init (mData.mDVDImages);
570 collection.queryInterfaceTo (aDVDImages);
571
572 return S_OK;
573}
574
575/** @note Locks this object for reading. */
576STDMETHODIMP VirtualBox::COMGETTER(FloppyImages) (IFloppyImageCollection **aFloppyImages)
577{
578 if (!aFloppyImages)
579 return E_POINTER;
580
581 AutoCaller autoCaller (this);
582 CheckComRCReturnRC (autoCaller.rc());
583
584 ComObjPtr <FloppyImageCollection> collection;
585 collection.createObject();
586
587 AutoReaderLock alock (this);
588 collection->init (mData.mFloppyImages);
589 collection.queryInterfaceTo (aFloppyImages);
590
591 return S_OK;
592}
593
594/** @note Locks this object for reading. */
595STDMETHODIMP VirtualBox::COMGETTER(ProgressOperations) (IProgressCollection **aOperations)
596{
597 if (!aOperations)
598 return E_POINTER;
599
600 AutoCaller autoCaller (this);
601 CheckComRCReturnRC (autoCaller.rc());
602
603 ComObjPtr <ProgressCollection> collection;
604 collection.createObject();
605
606 AutoReaderLock alock (this);
607 collection->init (mData.mProgressOperations);
608 collection.queryInterfaceTo (aOperations);
609
610 return S_OK;
611}
612
613/** @note Locks this object for reading. */
614STDMETHODIMP VirtualBox::COMGETTER(GuestOSTypes) (IGuestOSTypeCollection **aGuestOSTypes)
615{
616 if (!aGuestOSTypes)
617 return E_POINTER;
618
619 AutoCaller autoCaller (this);
620 CheckComRCReturnRC (autoCaller.rc());
621
622 ComObjPtr <GuestOSTypeCollection> collection;
623 collection.createObject();
624
625 AutoReaderLock alock (this);
626 collection->init (mData.mGuestOSTypes);
627 collection.queryInterfaceTo (aGuestOSTypes);
628
629 return S_OK;
630}
631
632STDMETHODIMP
633VirtualBox::COMGETTER(SharedFolders) (ISharedFolderCollection **aSharedFolders)
634{
635 if (!aSharedFolders)
636 return E_POINTER;
637
638 AutoCaller autoCaller (this);
639 CheckComRCReturnRC (autoCaller.rc());
640
641 return setError (E_NOTIMPL, "Not yet implemented");
642}
643
644// IVirtualBox methods
645/////////////////////////////////////////////////////////////////////////////
646
647/** @note Locks mSystemProperties object for reading. */
648STDMETHODIMP VirtualBox::CreateMachine (INPTR BSTR aBaseFolder,
649 INPTR BSTR aName,
650 IMachine **aMachine)
651{
652 LogFlowThisFuncEnter();
653 LogFlowThisFunc (("aBaseFolder='%ls', aName='%ls' aMachine={%p}\n",
654 aBaseFolder, aName, aMachine));
655
656 if (!aName)
657 return E_INVALIDARG;
658 if (!aMachine)
659 return E_POINTER;
660
661 if (!*aName)
662 return setError (E_INVALIDARG,
663 tr ("Machine name cannot be empty"));
664
665 AutoCaller autoCaller (this);
666 CheckComRCReturnRC (autoCaller.rc());
667
668 /* Compose the settings file name using the following scheme:
669 *
670 * <base_folder>/<machine_name>/<machine_name>.xml
671 *
672 * If a non-null and non-empty base folder is specified, the default
673 * machine folder will be used as a base folder.
674 */
675 Bstr settingsFile = aBaseFolder;
676 if (settingsFile.isEmpty())
677 {
678 AutoReaderLock propsLock (systemProperties());
679 /* we use the non-full folder value below to keep the path relative */
680 settingsFile = systemProperties()->defaultMachineFolder();
681 }
682 settingsFile = Utf8StrFmt ("%ls%c%ls%c%ls.xml",
683 settingsFile.raw(), RTPATH_DELIMITER,
684 aName, RTPATH_DELIMITER, aName);
685
686 HRESULT rc = E_FAIL;
687
688 /* create a new object */
689 ComObjPtr <Machine> machine;
690 rc = machine.createObject();
691 if (SUCCEEDED (rc))
692 {
693 /* initialize the machine object */
694 rc = machine->init (this, settingsFile, Machine::Init_New, aName);
695 if (SUCCEEDED (rc))
696 {
697 /* set the return value */
698 rc = machine.queryInterfaceTo (aMachine);
699 ComAssertComRC (rc);
700 }
701 }
702
703 LogFlowThisFunc (("rc=%08X\n", rc));
704 LogFlowThisFuncLeave();
705
706 return rc;
707}
708
709STDMETHODIMP VirtualBox::CreateLegacyMachine (INPTR BSTR aSettingsFile,
710 INPTR BSTR aName,
711 IMachine **aMachine)
712{
713 /* null and empty strings are not allowed as path names */
714 if (!aSettingsFile || !(*aSettingsFile))
715 return E_INVALIDARG;
716
717 if (!aName)
718 return E_INVALIDARG;
719 if (!aMachine)
720 return E_POINTER;
721
722 if (!*aName)
723 return setError (E_INVALIDARG,
724 tr ("Machine name cannot be empty"));
725
726 AutoCaller autoCaller (this);
727 CheckComRCReturnRC (autoCaller.rc());
728
729 HRESULT rc = E_FAIL;
730
731 Utf8Str settingsFile = aSettingsFile;
732 /* append the default extension if none */
733 if (!RTPathHaveExt (settingsFile))
734 settingsFile = Utf8StrFmt ("%s.xml", settingsFile.raw());
735
736 /* create a new object */
737 ComObjPtr<Machine> machine;
738 rc = machine.createObject();
739 if (SUCCEEDED (rc))
740 {
741 /* initialize the machine object */
742 rc = machine->init (this, Bstr (settingsFile), Machine::Init_New,
743 aName, FALSE /* aNameSync */);
744 if (SUCCEEDED (rc))
745 {
746 /* set the return value */
747 rc = machine.queryInterfaceTo (aMachine);
748 ComAssertComRC (rc);
749 }
750 }
751 return rc;
752}
753
754STDMETHODIMP VirtualBox::OpenMachine (INPTR BSTR aSettingsFile,
755 IMachine **aMachine)
756{
757 /* null and empty strings are not allowed as path names */
758 if (!aSettingsFile || !(*aSettingsFile))
759 return E_INVALIDARG;
760
761 if (!aMachine)
762 return E_POINTER;
763
764 AutoCaller autoCaller (this);
765 CheckComRCReturnRC (autoCaller.rc());
766
767 HRESULT rc = E_FAIL;
768
769 /* create a new object */
770 ComObjPtr<Machine> machine;
771 rc = machine.createObject();
772 if (SUCCEEDED (rc))
773 {
774 /* initialize the machine object */
775 rc = machine->init (this, aSettingsFile, Machine::Init_Existing);
776 if (SUCCEEDED (rc))
777 {
778 /* set the return value */
779 rc = machine.queryInterfaceTo (aMachine);
780 ComAssertComRC (rc);
781 }
782 }
783
784 return rc;
785}
786
787/** @note Locks objects! */
788STDMETHODIMP VirtualBox::RegisterMachine (IMachine *aMachine)
789{
790 if (!aMachine)
791 return E_INVALIDARG;
792
793 AutoCaller autoCaller (this);
794 CheckComRCReturnRC (autoCaller.rc());
795
796 HRESULT rc;
797
798 Bstr name;
799 rc = aMachine->COMGETTER(Name) (name.asOutParam());
800 CheckComRCReturnRC (rc);
801
802 /*
803 * we can safely cast child to Machine * here because only Machine
804 * implementations of IMachine can be among our children
805 */
806 Machine *machine = static_cast <Machine *> (getDependentChild (aMachine));
807 if (!machine)
808 {
809 /*
810 * this machine was not created by CreateMachine()
811 * or opened by OpenMachine() or loaded during startup
812 */
813 return setError (E_FAIL,
814 tr ("The machine named '%ls' is not created within this "
815 "VirtualBox instance"), name.raw());
816 }
817
818 /*
819 * Machine::trySetRegistered() will commit and save machine settings, and
820 * will also call #registerMachine() on success.
821 */
822 rc = registerMachine (machine);
823
824 /* fire an event */
825 if (SUCCEEDED (rc))
826 onMachineRegistered (machine->data()->mUuid, TRUE);
827
828 return rc;
829}
830
831/** @note Locks objects! */
832STDMETHODIMP VirtualBox::GetMachine (INPTR GUIDPARAM aId, IMachine **aMachine)
833{
834 if (!aMachine)
835 return E_POINTER;
836
837 AutoCaller autoCaller (this);
838 CheckComRCReturnRC (autoCaller.rc());
839
840 ComObjPtr <Machine> machine;
841 HRESULT rc = findMachine (Guid (aId), true /* setError */, &machine);
842
843 /* the below will set *aMachine to NULL if machine is null */
844 machine.queryInterfaceTo (aMachine);
845
846 return rc;
847}
848
849/** @note Locks this object for reading, then some machine objects for reading. */
850STDMETHODIMP VirtualBox::FindMachine (INPTR BSTR aName, IMachine **aMachine)
851{
852 LogFlowThisFuncEnter();
853 LogFlowThisFunc (("aName=\"%ls\", aMachine={%p}\n", aName, aMachine));
854
855 if (!aName)
856 return E_INVALIDARG;
857 if (!aMachine)
858 return E_POINTER;
859
860 AutoCaller autoCaller (this);
861 CheckComRCReturnRC (autoCaller.rc());
862
863 /* start with not found */
864 ComObjPtr <Machine> machine;
865 MachineList machines;
866 {
867 /* take a copy for safe iteration outside the lock */
868 AutoReaderLock alock (this);
869 machines = mData.mMachines;
870 }
871
872 for (MachineList::iterator it = machines.begin();
873 !machine && it != machines.end();
874 ++ it)
875 {
876 AutoReaderLock machineLock (*it);
877 if ((*it)->userData()->mName == aName)
878 machine = *it;
879 }
880
881 /* this will set (*machine) to NULL if machineObj is null */
882 machine.queryInterfaceTo (aMachine);
883
884 HRESULT rc = machine
885 ? S_OK
886 : setError (E_INVALIDARG,
887 tr ("Could not find a registered machine named '%ls'"), aName);
888
889 LogFlowThisFunc (("rc=%08X\n", rc));
890 LogFlowThisFuncLeave();
891
892 return rc;
893}
894
895/** @note Locks objects! */
896STDMETHODIMP VirtualBox::UnregisterMachine (INPTR GUIDPARAM aId,
897 IMachine **aMachine)
898{
899 Guid id = aId;
900 if (id.isEmpty())
901 return E_INVALIDARG;
902
903 AutoCaller autoCaller (this);
904 CheckComRCReturnRC (autoCaller.rc());
905
906 AutoLock alock (this);
907
908 ComObjPtr <Machine> machine;
909
910 HRESULT rc = findMachine (id, true /* setError */, &machine);
911 CheckComRCReturnRC (rc);
912
913 rc = machine->trySetRegistered (FALSE);
914 CheckComRCReturnRC (rc);
915
916 /* remove from the collection of registered machines */
917 mData.mMachines.remove (machine);
918
919 /* save the global registry */
920 rc = saveConfig();
921
922 /* return the unregistered machine to the caller */
923 machine.queryInterfaceTo (aMachine);
924
925 /* fire an event */
926 onMachineRegistered (id, FALSE);
927
928 return rc;
929}
930
931STDMETHODIMP VirtualBox::CreateHardDisk (HardDiskStorageType_T aStorageType,
932 IHardDisk **aHardDisk)
933{
934 if (!aHardDisk)
935 return E_POINTER;
936
937 AutoCaller autoCaller (this);
938 CheckComRCReturnRC (autoCaller.rc());
939
940 HRESULT rc = E_FAIL;
941
942 ComObjPtr <HardDisk> hardDisk;
943
944 switch (aStorageType)
945 {
946 case HardDiskStorageType_VirtualDiskImage:
947 {
948 ComObjPtr <HVirtualDiskImage> vdi;
949 vdi.createObject();
950 rc = vdi->init (this, NULL, NULL);
951 hardDisk = vdi;
952 break;
953 }
954
955 case HardDiskStorageType_ISCSIHardDisk:
956 {
957 ComObjPtr <HISCSIHardDisk> iscsi;
958 iscsi.createObject();
959 rc = iscsi->init (this);
960 hardDisk = iscsi;
961 break;
962 }
963
964 case HardDiskStorageType_VMDKImage:
965 {
966 ComObjPtr <HVMDKImage> vmdk;
967 vmdk.createObject();
968 rc = vmdk->init (this, NULL, NULL);
969 hardDisk = vmdk;
970 break;
971 }
972 default:
973 AssertFailed();
974 };
975
976 if (SUCCEEDED (rc))
977 hardDisk.queryInterfaceTo (aHardDisk);
978
979 return rc;
980}
981
982/** @note Locks mSystemProperties object for reading. */
983STDMETHODIMP VirtualBox::OpenHardDisk (INPTR BSTR aLocation, IHardDisk **aHardDisk)
984{
985 /* null and empty strings are not allowed locations */
986 if (!aLocation || !(*aLocation))
987 return E_INVALIDARG;
988
989 if (!aHardDisk)
990 return E_POINTER;
991
992 AutoCaller autoCaller (this);
993 CheckComRCReturnRC (autoCaller.rc());
994
995 /* Currently, the location is always a path. So, append the
996 * default path if only a name is given. */
997 Bstr location = aLocation;
998 {
999 Utf8Str loc = aLocation;
1000 if (!RTPathHavePath (loc))
1001 {
1002 AutoLock propsLock (mData.mSystemProperties);
1003 location = Utf8StrFmt ("%ls%c%s",
1004 mData.mSystemProperties->defaultVDIFolder().raw(),
1005 RTPATH_DELIMITER,
1006 loc.raw());
1007 }
1008 }
1009
1010 ComObjPtr <HardDisk> hardDisk;
1011 HRESULT rc = HardDisk::openHardDisk (this, location, hardDisk);
1012 if (SUCCEEDED (rc))
1013 hardDisk.queryInterfaceTo (aHardDisk);
1014
1015 return rc;
1016}
1017
1018/** @note Locks mSystemProperties object for reading. */
1019STDMETHODIMP VirtualBox::OpenVirtualDiskImage (INPTR BSTR aFilePath,
1020 IVirtualDiskImage **aImage)
1021{
1022 /* null and empty strings are not allowed as path names here */
1023 if (!aFilePath || !(*aFilePath))
1024 return E_INVALIDARG;
1025
1026 if (!aImage)
1027 return E_POINTER;
1028
1029 AutoCaller autoCaller (this);
1030 CheckComRCReturnRC (autoCaller.rc());
1031
1032 /* append the default path if only a name is given */
1033 Bstr path = aFilePath;
1034 {
1035 Utf8Str fp = aFilePath;
1036 if (!RTPathHavePath (fp))
1037 {
1038 AutoLock propsLock (mData.mSystemProperties);
1039 path = Utf8StrFmt ("%ls%c%s",
1040 mData.mSystemProperties->defaultVDIFolder().raw(),
1041 RTPATH_DELIMITER,
1042 fp.raw());
1043 }
1044 }
1045
1046 ComObjPtr <HVirtualDiskImage> vdi;
1047 vdi.createObject();
1048 HRESULT rc = vdi->init (this, NULL, path);
1049
1050 if (SUCCEEDED (rc))
1051 vdi.queryInterfaceTo (aImage);
1052
1053 return rc;
1054}
1055
1056/** @note Locks objects! */
1057STDMETHODIMP VirtualBox::RegisterHardDisk (IHardDisk *aHardDisk)
1058{
1059 if (!aHardDisk)
1060 return E_POINTER;
1061
1062 AutoCaller autoCaller (this);
1063 CheckComRCReturnRC (autoCaller.rc());
1064
1065 VirtualBoxBase *child = getDependentChild (aHardDisk);
1066 if (!child)
1067 return setError (E_FAIL, tr ("The given hard disk is not created within "
1068 "this VirtualBox instance"));
1069
1070 /*
1071 * we can safely cast child to HardDisk * here because only HardDisk
1072 * implementations of IHardDisk can be among our children
1073 */
1074
1075 return registerHardDisk (static_cast <HardDisk *> (child), RHD_External);
1076}
1077
1078/** @note Locks objects! */
1079STDMETHODIMP VirtualBox::GetHardDisk (INPTR GUIDPARAM aId, IHardDisk **aHardDisk)
1080{
1081 if (!aHardDisk)
1082 return E_POINTER;
1083
1084 AutoCaller autoCaller (this);
1085 CheckComRCReturnRC (autoCaller.rc());
1086
1087 Guid id = aId;
1088 ComObjPtr <HardDisk> hd;
1089 HRESULT rc = findHardDisk (&id, NULL, true /* setError */, &hd);
1090
1091 /* the below will set *aHardDisk to NULL if hd is null */
1092 hd.queryInterfaceTo (aHardDisk);
1093
1094 return rc;
1095}
1096
1097/** @note Locks objects! */
1098STDMETHODIMP VirtualBox::FindHardDisk (INPTR BSTR aLocation,
1099 IHardDisk **aHardDisk)
1100{
1101 if (!aLocation)
1102 return E_INVALIDARG;
1103 if (!aHardDisk)
1104 return E_POINTER;
1105
1106 AutoCaller autoCaller (this);
1107 CheckComRCReturnRC (autoCaller.rc());
1108
1109 Utf8Str location = aLocation;
1110 if (strncmp (location, "iscsi:", 6) == 0)
1111 {
1112 /* nothing special */
1113 }
1114 else
1115 {
1116 /* For locations represented by file paths, append the default path if
1117 * only a name is given, and then get the full path. */
1118 if (!RTPathHavePath (location))
1119 {
1120 AutoLock propsLock (mData.mSystemProperties);
1121 location = Utf8StrFmt ("%ls%c%s",
1122 mData.mSystemProperties->defaultVDIFolder().raw(),
1123 RTPATH_DELIMITER,
1124 location.raw());
1125 }
1126
1127 /* get the full file name */
1128 char buf [RTPATH_MAX];
1129 int vrc = RTPathAbsEx (mData.mHomeDir, location, buf, sizeof (buf));
1130 if (VBOX_FAILURE (vrc))
1131 return setError (E_FAIL, tr ("Invalid hard disk location '%ls' (%Vrc)"),
1132 aLocation, vrc);
1133 location = buf;
1134 }
1135
1136 ComObjPtr <HardDisk> hardDisk;
1137 HRESULT rc = findHardDisk (NULL, Bstr (location), true /* setError */,
1138 &hardDisk);
1139
1140 /* the below will set *aHardDisk to NULL if hardDisk is null */
1141 hardDisk.queryInterfaceTo (aHardDisk);
1142
1143 return rc;
1144}
1145
1146/** @note Locks objects! */
1147STDMETHODIMP VirtualBox::FindVirtualDiskImage (INPTR BSTR aFilePath,
1148 IVirtualDiskImage **aImage)
1149{
1150 if (!aFilePath)
1151 return E_INVALIDARG;
1152 if (!aImage)
1153 return E_POINTER;
1154
1155 AutoCaller autoCaller (this);
1156 CheckComRCReturnRC (autoCaller.rc());
1157
1158 /* append the default path if only a name is given */
1159 Utf8Str path = aFilePath;
1160 {
1161 Utf8Str fp = path;
1162 if (!RTPathHavePath (fp))
1163 {
1164 AutoLock propsLock (mData.mSystemProperties);
1165 path = Utf8StrFmt ("%ls%c%s",
1166 mData.mSystemProperties->defaultVDIFolder().raw(),
1167 RTPATH_DELIMITER,
1168 fp.raw());
1169 }
1170 }
1171
1172 /* get the full file name */
1173 char buf [RTPATH_MAX];
1174 int vrc = RTPathAbsEx (mData.mHomeDir, path, buf, sizeof (buf));
1175 if (VBOX_FAILURE (vrc))
1176 return setError (E_FAIL, tr ("Invalid image file path '%ls' (%Vrc)"),
1177 aFilePath, vrc);
1178
1179 ComObjPtr <HVirtualDiskImage> vdi;
1180 HRESULT rc = findVirtualDiskImage (NULL, Bstr (buf), true /* setError */,
1181 &vdi);
1182
1183 /* the below will set *aImage to NULL if vdi is null */
1184 vdi.queryInterfaceTo (aImage);
1185
1186 return rc;
1187}
1188
1189/** @note Locks objects! */
1190STDMETHODIMP VirtualBox::UnregisterHardDisk (INPTR GUIDPARAM aId, IHardDisk **aHardDisk)
1191{
1192 if (!aHardDisk)
1193 return E_POINTER;
1194
1195 AutoCaller autoCaller (this);
1196 CheckComRCReturnRC (autoCaller.rc());
1197
1198 *aHardDisk = NULL;
1199
1200 Guid id = aId;
1201 ComObjPtr <HardDisk> hd;
1202 HRESULT rc = findHardDisk (&id, NULL, true /* setError */, &hd);
1203 CheckComRCReturnRC (rc);
1204
1205 rc = unregisterHardDisk (hd);
1206 if (SUCCEEDED (rc))
1207 hd.queryInterfaceTo (aHardDisk);
1208
1209 return rc;
1210}
1211
1212/** @note Doesn't lock anything. */
1213STDMETHODIMP VirtualBox::OpenDVDImage (INPTR BSTR aFilePath, INPTR GUIDPARAM aId,
1214 IDVDImage **aDVDImage)
1215{
1216 /* null and empty strings are not allowed as path names */
1217 if (!aFilePath || !(*aFilePath))
1218 return E_INVALIDARG;
1219
1220 if (!aDVDImage)
1221 return E_POINTER;
1222
1223 AutoCaller autoCaller (this);
1224 CheckComRCReturnRC (autoCaller.rc());
1225
1226 HRESULT rc = E_FAIL;
1227
1228 Guid uuid = aId;
1229 /* generate an UUID if not specified */
1230 if (uuid.isEmpty())
1231 uuid.create();
1232
1233 ComObjPtr <DVDImage> dvdImage;
1234 dvdImage.createObject();
1235 rc = dvdImage->init (this, aFilePath, FALSE /* !isRegistered */, uuid);
1236 if (SUCCEEDED (rc))
1237 dvdImage.queryInterfaceTo (aDVDImage);
1238
1239 return rc;
1240}
1241
1242/** @note Locks objects! */
1243STDMETHODIMP VirtualBox::RegisterDVDImage (IDVDImage *aDVDImage)
1244{
1245 if (!aDVDImage)
1246 return E_POINTER;
1247
1248 AutoCaller autoCaller (this);
1249 CheckComRCReturnRC (autoCaller.rc());
1250
1251 VirtualBoxBase *child = getDependentChild (aDVDImage);
1252 if (!child)
1253 return setError (E_FAIL, tr ("The given CD/DVD image is not created within "
1254 "this VirtualBox instance"));
1255
1256 /*
1257 * we can safely cast child to DVDImage * here because only DVDImage
1258 * implementations of IDVDImage can be among our children
1259 */
1260
1261 return registerDVDImage (static_cast <DVDImage *> (child),
1262 FALSE /* aOnStartUp */);
1263}
1264
1265/** @note Locks objects! */
1266STDMETHODIMP VirtualBox::GetDVDImage (INPTR GUIDPARAM aId, IDVDImage **aDVDImage)
1267{
1268 if (!aDVDImage)
1269 return E_POINTER;
1270
1271 AutoCaller autoCaller (this);
1272 CheckComRCReturnRC (autoCaller.rc());
1273
1274 Guid uuid = aId;
1275 ComObjPtr <DVDImage> dvd;
1276 HRESULT rc = findDVDImage (&uuid, NULL, true /* setError */, &dvd);
1277
1278 /* the below will set *aDVDImage to NULL if dvd is null */
1279 dvd.queryInterfaceTo (aDVDImage);
1280
1281 return rc;
1282}
1283
1284/** @note Locks objects! */
1285STDMETHODIMP VirtualBox::FindDVDImage (INPTR BSTR aFilePath, IDVDImage **aDVDImage)
1286{
1287 if (!aFilePath)
1288 return E_INVALIDARG;
1289 if (!aDVDImage)
1290 return E_POINTER;
1291
1292 AutoCaller autoCaller (this);
1293 CheckComRCReturnRC (autoCaller.rc());
1294
1295 /* get the full file name */
1296 char buf [RTPATH_MAX];
1297 int vrc = RTPathAbsEx (mData.mHomeDir, Utf8Str (aFilePath), buf, sizeof (buf));
1298 if (VBOX_FAILURE (vrc))
1299 return setError (E_FAIL, tr ("Invalid image file path: '%ls' (%Vrc)"),
1300 aFilePath, vrc);
1301
1302 ComObjPtr <DVDImage> dvd;
1303 HRESULT rc = findDVDImage (NULL, Bstr (buf), true /* setError */, &dvd);
1304
1305 /* the below will set *dvdImage to NULL if dvd is null */
1306 dvd.queryInterfaceTo (aDVDImage);
1307
1308 return rc;
1309}
1310
1311/** @note Locks objects! */
1312STDMETHODIMP VirtualBox::GetDVDImageUsage (INPTR GUIDPARAM aId,
1313 ResourceUsage_T aUsage,
1314 BSTR *aMachineIDs)
1315{
1316 if (!aMachineIDs)
1317 return E_POINTER;
1318 if (aUsage == ResourceUsage_InvalidUsage)
1319 return E_INVALIDARG;
1320
1321 AutoCaller autoCaller (this);
1322 CheckComRCReturnRC (autoCaller.rc());
1323
1324 AutoReaderLock alock (this);
1325
1326 Guid uuid = Guid (aId);
1327 HRESULT rc = findDVDImage (&uuid, NULL, true /* setError */, NULL);
1328 if (FAILED (rc))
1329 return rc;
1330
1331 Bstr ids;
1332 getDVDImageUsage (uuid, aUsage, &ids);
1333 ids.cloneTo (aMachineIDs);
1334
1335 return S_OK;
1336}
1337
1338/** @note Locks objects! */
1339STDMETHODIMP VirtualBox::UnregisterDVDImage (INPTR GUIDPARAM aId,
1340 IDVDImage **aDVDImage)
1341{
1342 if (!aDVDImage)
1343 return E_POINTER;
1344
1345 AutoCaller autoCaller (this);
1346 CheckComRCReturnRC (autoCaller.rc());
1347
1348 AutoLock alock (this);
1349
1350 *aDVDImage = NULL;
1351
1352 Guid uuid = aId;
1353 ComObjPtr <DVDImage> dvd;
1354 HRESULT rc = findDVDImage (&uuid, NULL, true /* setError */, &dvd);
1355 CheckComRCReturnRC (rc);
1356
1357 if (!getDVDImageUsage (aId, ResourceUsage_AllUsage))
1358 {
1359 /* remove from the collection */
1360 mData.mDVDImages.remove (dvd);
1361
1362 /* save the global config file */
1363 rc = saveConfig();
1364
1365 if (SUCCEEDED (rc))
1366 {
1367 rc = dvd.queryInterfaceTo (aDVDImage);
1368 ComAssertComRC (rc);
1369 }
1370 }
1371 else
1372 rc = setError(E_FAIL,
1373 tr ("The CD/DVD image with the UUID {%s} is currently in use"),
1374 uuid.toString().raw());
1375
1376 return rc;
1377}
1378
1379/** @note Doesn't lock anything. */
1380STDMETHODIMP VirtualBox::OpenFloppyImage (INPTR BSTR aFilePath, INPTR GUIDPARAM aId,
1381 IFloppyImage **aFloppyImage)
1382{
1383 /* null and empty strings are not allowed as path names */
1384 if (!aFilePath || !(*aFilePath))
1385 return E_INVALIDARG;
1386
1387 if (!aFloppyImage)
1388 return E_POINTER;
1389
1390 AutoCaller autoCaller (this);
1391 CheckComRCReturnRC (autoCaller.rc());
1392
1393 HRESULT rc = E_FAIL;
1394
1395 Guid uuid = aId;
1396 /* generate an UUID if not specified */
1397 if (Guid::isEmpty (aId))
1398 uuid.create();
1399
1400 ComObjPtr <FloppyImage> floppyImage;
1401 floppyImage.createObject();
1402 rc = floppyImage->init (this, aFilePath, FALSE /* !isRegistered */, uuid);
1403 if (SUCCEEDED (rc))
1404 floppyImage.queryInterfaceTo (aFloppyImage);
1405
1406 return rc;
1407}
1408
1409/** @note Locks objects! */
1410STDMETHODIMP VirtualBox::RegisterFloppyImage (IFloppyImage *aFloppyImage)
1411{
1412 if (!aFloppyImage)
1413 return E_POINTER;
1414
1415 AutoCaller autoCaller (this);
1416 CheckComRCReturnRC (autoCaller.rc());
1417
1418 VirtualBoxBase *child = getDependentChild (aFloppyImage);
1419 if (!child)
1420 return setError (E_FAIL, tr ("The given floppy image is not created within "
1421 "this VirtualBox instance"));
1422
1423 /*
1424 * we can safely cast child to FloppyImage * here because only FloppyImage
1425 * implementations of IFloppyImage can be among our children
1426 */
1427
1428 return registerFloppyImage (static_cast <FloppyImage *> (child),
1429 FALSE /* aOnStartUp */);
1430}
1431
1432/** @note Locks objects! */
1433STDMETHODIMP VirtualBox::GetFloppyImage (INPTR GUIDPARAM aId,
1434 IFloppyImage **aFloppyImage)
1435{
1436 if (!aFloppyImage)
1437 return E_POINTER;
1438
1439 AutoCaller autoCaller (this);
1440 CheckComRCReturnRC (autoCaller.rc());
1441
1442 Guid uuid = aId;
1443 ComObjPtr <FloppyImage> floppy;
1444 HRESULT rc = findFloppyImage (&uuid, NULL, true /* setError */, &floppy);
1445
1446 /* the below will set *aFloppyImage to NULL if dvd is null */
1447 floppy.queryInterfaceTo (aFloppyImage);
1448
1449 return rc;
1450}
1451
1452/** @note Locks objects! */
1453STDMETHODIMP VirtualBox::FindFloppyImage (INPTR BSTR aFilePath,
1454 IFloppyImage **aFloppyImage)
1455{
1456 if (!aFilePath)
1457 return E_INVALIDARG;
1458 if (!aFloppyImage)
1459 return E_POINTER;
1460
1461 AutoCaller autoCaller (this);
1462 CheckComRCReturnRC (autoCaller.rc());
1463
1464 /* get the full file name */
1465 char buf [RTPATH_MAX];
1466 int vrc = RTPathAbsEx (mData.mHomeDir, Utf8Str (aFilePath), buf, sizeof (buf));
1467 if (VBOX_FAILURE (vrc))
1468 return setError (E_FAIL, tr ("Invalid image file path: '%ls' (%Vrc)"),
1469 aFilePath, vrc);
1470
1471 ComObjPtr <FloppyImage> floppy;
1472 HRESULT rc = findFloppyImage (NULL, Bstr (buf), true /* setError */, &floppy);
1473
1474 /* the below will set *image to NULL if img is null */
1475 floppy.queryInterfaceTo (aFloppyImage);
1476
1477 return rc;
1478}
1479
1480/** @note Locks objects! */
1481STDMETHODIMP VirtualBox::GetFloppyImageUsage (INPTR GUIDPARAM aId,
1482 ResourceUsage_T aUsage,
1483 BSTR *aMachineIDs)
1484{
1485 if (!aMachineIDs)
1486 return E_POINTER;
1487 if (aUsage == ResourceUsage_InvalidUsage)
1488 return E_INVALIDARG;
1489
1490 AutoCaller autoCaller (this);
1491 CheckComRCReturnRC (autoCaller.rc());
1492
1493 AutoReaderLock alock (this);
1494
1495 Guid uuid = Guid (aId);
1496 HRESULT rc = findFloppyImage (&uuid, NULL, true /* setError */, NULL);
1497 if (FAILED (rc))
1498 return rc;
1499
1500 Bstr ids;
1501 getFloppyImageUsage (uuid, aUsage, &ids);
1502 ids.cloneTo (aMachineIDs);
1503
1504 return S_OK;
1505}
1506
1507/** @note Locks objects! */
1508STDMETHODIMP VirtualBox::UnregisterFloppyImage (INPTR GUIDPARAM aId,
1509 IFloppyImage **aFloppyImage)
1510{
1511 if (!aFloppyImage)
1512 return E_INVALIDARG;
1513
1514 AutoCaller autoCaller (this);
1515 CheckComRCReturnRC (autoCaller.rc());
1516
1517 AutoLock alock (this);
1518
1519 *aFloppyImage = NULL;
1520
1521 Guid uuid = aId;
1522 ComObjPtr <FloppyImage> floppy;
1523 HRESULT rc = findFloppyImage (&uuid, NULL, true /* setError */, &floppy);
1524 CheckComRCReturnRC (rc);
1525
1526 if (!getFloppyImageUsage (aId, ResourceUsage_AllUsage))
1527 {
1528 /* remove from the collection */
1529 mData.mFloppyImages.remove (floppy);
1530
1531 /* save the global config file */
1532 rc = saveConfig();
1533 if (SUCCEEDED (rc))
1534 {
1535 rc = floppy.queryInterfaceTo (aFloppyImage);
1536 ComAssertComRC (rc);
1537 }
1538 }
1539 else
1540 rc = setError(E_FAIL,
1541 tr ("A floppy image with UUID {%s} is currently in use"),
1542 uuid.toString().raw());
1543
1544 return rc;
1545}
1546
1547/** @note Locks this object for reading. */
1548STDMETHODIMP VirtualBox::FindGuestOSType (INPTR BSTR aId, IGuestOSType **aType)
1549{
1550 if (!aType)
1551 return E_INVALIDARG;
1552
1553 AutoCaller autoCaller (this);
1554 CheckComRCReturnRC (autoCaller.rc());
1555
1556 *aType = NULL;
1557
1558 AutoReaderLock alock (this);
1559
1560 for (GuestOSTypeList::iterator it = mData.mGuestOSTypes.begin();
1561 it != mData.mGuestOSTypes.end();
1562 ++ it)
1563 {
1564 const Bstr &typeId = (*it)->id();
1565 AssertMsg (!!typeId, ("ID must not be NULL"));
1566 if (typeId == aId)
1567 {
1568 (*it).queryInterfaceTo (aType);
1569 break;
1570 }
1571 }
1572
1573 return (*aType) ? S_OK : E_INVALIDARG;
1574}
1575
1576STDMETHODIMP
1577VirtualBox::CreateSharedFolder (INPTR BSTR aName, INPTR BSTR aHostPath)
1578{
1579 if (!aName || !aHostPath)
1580 return E_INVALIDARG;
1581
1582 AutoCaller autoCaller (this);
1583 CheckComRCReturnRC (autoCaller.rc());
1584
1585 return setError (E_NOTIMPL, "Not yet implemented");
1586}
1587
1588STDMETHODIMP VirtualBox::RemoveSharedFolder (INPTR BSTR aName)
1589{
1590 if (!aName)
1591 return E_INVALIDARG;
1592
1593 AutoCaller autoCaller (this);
1594 CheckComRCReturnRC (autoCaller.rc());
1595
1596 return setError (E_NOTIMPL, "Not yet implemented");
1597}
1598
1599/** @note Locks this object for reading. */
1600STDMETHODIMP VirtualBox::
1601GetNextExtraDataKey (INPTR BSTR aKey, BSTR *aNextKey, BSTR *aNextValue)
1602{
1603 if (!aNextKey)
1604 return E_POINTER;
1605
1606 AutoCaller autoCaller (this);
1607 CheckComRCReturnRC (autoCaller.rc());
1608
1609 /* start with nothing found */
1610 *aNextKey = NULL;
1611
1612 HRESULT rc = S_OK;
1613
1614 /* serialize file access */
1615 AutoReaderLock alock (this);
1616
1617 CFGHANDLE configLoader;
1618
1619 /* load the config file */
1620 int vrc = CFGLDRLoad (&configLoader, Utf8Str (mData.mCfgFile.mName),
1621 mData.mCfgFile.mHandle,
1622 XmlSchemaNS, true, cfgLdrEntityResolver, NULL);
1623 ComAssertRCRet (vrc, E_FAIL);
1624
1625 CFGNODE extraDataNode;
1626
1627 /* navigate to the right position */
1628 if (VBOX_SUCCESS (CFGLDRGetNode (configLoader,
1629 "VirtualBox/Global/ExtraData", 0,
1630 &extraDataNode)))
1631 {
1632 /* check if it exists */
1633 bool found = false;
1634 unsigned count;
1635 CFGNODE extraDataItemNode;
1636 CFGLDRCountChildren (extraDataNode, "ExtraDataItem", &count);
1637 for (unsigned i = 0; (i < count) && (found == false); i++)
1638 {
1639 Bstr name;
1640 CFGLDRGetChildNode (extraDataNode, "ExtraDataItem", i, &extraDataItemNode);
1641 CFGLDRQueryBSTR (extraDataItemNode, "name", name.asOutParam());
1642
1643 /* if we're supposed to return the first one */
1644 if (aKey == NULL)
1645 {
1646 name.cloneTo (aNextKey);
1647 if (aNextValue)
1648 CFGLDRQueryBSTR (extraDataItemNode, "value", aNextValue);
1649 found = true;
1650 }
1651 /* did we find the key we're looking for? */
1652 else if (name == aKey)
1653 {
1654 found = true;
1655 /* is there another item? */
1656 if (i + 1 < count)
1657 {
1658 CFGLDRGetChildNode (extraDataNode, "ExtraDataItem", i + 1,
1659 &extraDataItemNode);
1660 CFGLDRQueryBSTR (extraDataItemNode, "name", name.asOutParam());
1661 name.cloneTo (aNextKey);
1662 if (aNextValue)
1663 CFGLDRQueryBSTR (extraDataItemNode, "value", aNextValue);
1664 found = true;
1665 }
1666 else
1667 {
1668 /* it's the last one */
1669 *aNextKey = NULL;
1670 }
1671 }
1672 CFGLDRReleaseNode (extraDataItemNode);
1673 }
1674
1675 /* if we haven't found the key, it's an error */
1676 if (!found)
1677 rc = setError (E_FAIL,
1678 tr ("Could not find extra data key '%ls'"), aKey);
1679
1680 CFGLDRReleaseNode (extraDataNode);
1681 }
1682
1683 CFGLDRFree (configLoader);
1684
1685 return rc;
1686}
1687
1688/** @note Locks this object for reading. */
1689STDMETHODIMP VirtualBox::GetExtraData (INPTR BSTR aKey, BSTR *aValue)
1690{
1691 if (!aKey || !(*aKey))
1692 return E_INVALIDARG;
1693 if (!aValue)
1694 return E_POINTER;
1695
1696 AutoCaller autoCaller (this);
1697 CheckComRCReturnRC (autoCaller.rc());
1698
1699 /* start with nothing found */
1700 *aValue = NULL;
1701
1702 HRESULT rc = S_OK;
1703
1704 /* serialize file access */
1705 AutoReaderLock alock (this);
1706
1707 CFGHANDLE configLoader;
1708
1709 /* load the config file */
1710 int vrc = CFGLDRLoad (&configLoader, Utf8Str (mData.mCfgFile.mName),
1711 mData.mCfgFile.mHandle,
1712 XmlSchemaNS, true, cfgLdrEntityResolver, NULL);
1713 ComAssertRCRet (vrc, E_FAIL);
1714
1715 CFGNODE extraDataNode;
1716
1717 /* navigate to the right position */
1718 if (VBOX_SUCCESS (CFGLDRGetNode (configLoader,
1719 "VirtualBox/Global/ExtraData", 0,
1720 &extraDataNode)))
1721 {
1722 /* check if it exists */
1723 bool found = false;
1724 unsigned count;
1725 CFGNODE extraDataItemNode;
1726 CFGLDRCountChildren (extraDataNode, "ExtraDataItem", &count);
1727 for (unsigned i = 0; (i < count) && (found == false); i++)
1728 {
1729 Bstr name;
1730 CFGLDRGetChildNode (extraDataNode, "ExtraDataItem", i, &extraDataItemNode);
1731 CFGLDRQueryBSTR (extraDataItemNode, "name", name.asOutParam());
1732 if (name == aKey)
1733 {
1734 found = true;
1735 CFGLDRQueryBSTR (extraDataItemNode, "value", aValue);
1736 }
1737 CFGLDRReleaseNode (extraDataItemNode);
1738 }
1739
1740 CFGLDRReleaseNode (extraDataNode);
1741 }
1742
1743 CFGLDRFree (configLoader);
1744
1745 return rc;
1746}
1747
1748/** @note Locks this object for writing. */
1749STDMETHODIMP VirtualBox::SetExtraData(INPTR BSTR aKey, INPTR BSTR aValue)
1750{
1751 if (!aKey)
1752 return E_POINTER;
1753
1754 AutoCaller autoCaller (this);
1755 CheckComRCReturnRC (autoCaller.rc());
1756
1757 Guid emptyGuid;
1758
1759 bool changed = false;
1760 HRESULT rc = S_OK;
1761
1762 /* serialize file access */
1763 AutoLock alock (this);
1764
1765 CFGHANDLE configLoader;
1766
1767 /* load the config file */
1768 int vrc = CFGLDRLoad (&configLoader, Utf8Str (mData.mCfgFile.mName),
1769 mData.mCfgFile.mHandle,
1770 XmlSchemaNS, true, cfgLdrEntityResolver, NULL);
1771 ComAssertRCRet (vrc, E_FAIL);
1772
1773 CFGNODE extraDataNode = 0;
1774
1775 vrc = CFGLDRGetNode (configLoader, "VirtualBox/Global/ExtraData", 0,
1776 &extraDataNode);
1777 if (VBOX_FAILURE (vrc) && aValue)
1778 vrc = CFGLDRCreateNode (configLoader, "VirtualBox/Global/ExtraData",
1779 &extraDataNode);
1780
1781 if (extraDataNode)
1782 {
1783 CFGNODE extraDataItemNode = 0;
1784 Bstr oldVal;
1785
1786 unsigned count;
1787 CFGLDRCountChildren (extraDataNode, "ExtraDataItem", &count);
1788
1789 for (unsigned i = 0; i < count; i++)
1790 {
1791 CFGLDRGetChildNode (extraDataNode, "ExtraDataItem", i, &extraDataItemNode);
1792 Bstr name;
1793 CFGLDRQueryBSTR (extraDataItemNode, "name", name.asOutParam());
1794 if (name == aKey)
1795 {
1796 CFGLDRQueryBSTR (extraDataItemNode, "value", oldVal.asOutParam());
1797 break;
1798 }
1799 CFGLDRReleaseNode (extraDataItemNode);
1800 extraDataItemNode = 0;
1801 }
1802
1803 /*
1804 * When no key is found, oldVal is null. Note:
1805 * 1. when oldVal is null, |oldVal == (BSTR) NULL| is true
1806 * 2. we cannot do |oldVal != value| because it will compare
1807 * BSTR pointers instead of strings (due to type conversion ops)
1808 */
1809 changed = !(oldVal == aValue);
1810
1811 if (changed)
1812 {
1813 /* ask for permission from all listeners */
1814 if (!onExtraDataCanChange (emptyGuid, aKey, aValue))
1815 {
1816 Log (("VirtualBox::SetExtraData(): Someone vetoed! Change refused\n"));
1817 rc = setError (E_ACCESSDENIED,
1818 tr ("Could not set extra data because someone refused "
1819 "the requested change of '%ls' to '%ls'"), aKey, aValue);
1820 }
1821 else
1822 {
1823 if (aValue)
1824 {
1825 if (!extraDataItemNode)
1826 {
1827 /* create a new item */
1828 CFGLDRAppendChildNode (extraDataNode, "ExtraDataItem",
1829 &extraDataItemNode);
1830 CFGLDRSetBSTR (extraDataItemNode, "name", aKey);
1831 }
1832 CFGLDRSetBSTR (extraDataItemNode, "value", aValue);
1833 }
1834 else
1835 {
1836 /* an old value does for sure exist here */
1837 CFGLDRDeleteNode (extraDataItemNode);
1838 extraDataItemNode = 0;
1839 }
1840 }
1841 }
1842
1843 if (extraDataItemNode)
1844 CFGLDRReleaseNode (extraDataItemNode);
1845
1846 CFGLDRReleaseNode (extraDataNode);
1847
1848 if (SUCCEEDED (rc) && changed)
1849 {
1850 char *loaderError = NULL;
1851 vrc = CFGLDRSave (configLoader, &loaderError);
1852 if (VBOX_FAILURE (vrc))
1853 {
1854 rc = setError (E_FAIL,
1855 tr ("Could not save the settings file '%ls' (%Vrc)%s%s"),
1856 mData.mCfgFile.mName.raw(), vrc,
1857 loaderError ? ".\n" : "", loaderError ? loaderError : "");
1858 if (loaderError)
1859 RTMemTmpFree (loaderError);
1860 }
1861 }
1862 }
1863
1864 CFGLDRFree (configLoader);
1865
1866 /* notification handling */
1867 if (SUCCEEDED (rc) && changed)
1868 onExtraDataChange (emptyGuid, aKey, aValue);
1869
1870 return rc;
1871}
1872
1873/**
1874 * @note Locks objects!
1875 */
1876STDMETHODIMP VirtualBox::OpenSession (ISession *aSession, INPTR GUIDPARAM aMachineId)
1877{
1878 if (!aSession)
1879 return E_INVALIDARG;
1880
1881 AutoCaller autoCaller (this);
1882 CheckComRCReturnRC (autoCaller.rc());
1883
1884 Guid id = aMachineId;
1885 ComObjPtr <Machine> machine;
1886
1887 HRESULT rc = findMachine (id, true /* setError */, &machine);
1888 CheckComRCReturnRC (rc);
1889
1890 /* check the session state */
1891 SessionState_T state;
1892 rc = aSession->COMGETTER(State) (&state);
1893 CheckComRCReturnRC (rc);
1894
1895 if (state != SessionState_SessionClosed)
1896 return setError (E_INVALIDARG,
1897 tr ("The given session is already open or being opened"));
1898
1899 /* get the IInternalSessionControl interface */
1900 ComPtr <IInternalSessionControl> control = aSession;
1901 ComAssertMsgRet (!!control, ("No IInternalSessionControl interface"),
1902 E_INVALIDARG);
1903
1904 rc = machine->openSession (control);
1905
1906 if (SUCCEEDED (rc))
1907 {
1908 /*
1909 * tell the client watcher thread to update the set of
1910 * machines that have open sessions
1911 */
1912 updateClientWatcher();
1913
1914 /* fire an event */
1915 onSessionStateChange (aMachineId, SessionState_SessionOpen);
1916 }
1917
1918 return rc;
1919}
1920
1921/**
1922 * @note Locks objects!
1923 */
1924STDMETHODIMP VirtualBox::OpenRemoteSession (ISession *aSession,
1925 INPTR GUIDPARAM aMachineId,
1926 INPTR BSTR aType,
1927 IProgress **aProgress)
1928{
1929 if (!aSession || !aType)
1930 return E_INVALIDARG;
1931 if (!aProgress)
1932 return E_POINTER;
1933
1934 AutoCaller autoCaller (this);
1935 CheckComRCReturnRC (autoCaller.rc());
1936
1937 Guid id = aMachineId;
1938 ComObjPtr <Machine> machine;
1939
1940 HRESULT rc = findMachine (id, true /* setError */, &machine);
1941 CheckComRCReturnRC (rc);
1942
1943 /* check the session state */
1944 SessionState_T state;
1945 rc = aSession->COMGETTER(State) (&state);
1946 CheckComRCReturnRC (rc);
1947
1948 if (state != SessionState_SessionClosed)
1949 return setError (E_INVALIDARG,
1950 tr ("The given session is already open or being opened"));
1951
1952 /* get the IInternalSessionControl interface */
1953 ComPtr <IInternalSessionControl> control = aSession;
1954 ComAssertMsgRet (!!control, ("No IInternalSessionControl interface"),
1955 E_INVALIDARG);
1956
1957 /* create a progress object */
1958 ComObjPtr <Progress> progress;
1959 progress.createObject();
1960 progress->init (this, (IMachine *) machine,
1961 Bstr (tr ("Spawning session")),
1962 FALSE /* aCancelable */);
1963
1964 rc = machine->openRemoteSession (control, aType, progress);
1965
1966 if (SUCCEEDED (rc))
1967 {
1968 progress.queryInterfaceTo (aProgress);
1969
1970 /* fire an event */
1971 onSessionStateChange (aMachineId, SessionState_SessionSpawning);
1972 }
1973
1974 return rc;
1975}
1976
1977/**
1978 * @note Locks objects!
1979 */
1980STDMETHODIMP VirtualBox::OpenExistingSession (ISession *aSession,
1981 INPTR GUIDPARAM aMachineId)
1982{
1983 if (!aSession)
1984 return E_POINTER;
1985
1986 AutoCaller autoCaller (this);
1987 CheckComRCReturnRC (autoCaller.rc());
1988
1989 Guid id = aMachineId;
1990 ComObjPtr <Machine> machine;
1991
1992 HRESULT rc = findMachine (id, true /* setError */, &machine);
1993 CheckComRCReturnRC (rc);
1994
1995 /* check the session state */
1996 SessionState_T state;
1997 rc = aSession->COMGETTER(State) (&state);
1998 CheckComRCReturnRC (rc);
1999
2000 if (state != SessionState_SessionClosed)
2001 return setError (E_INVALIDARG,
2002 tr ("The given session is already open or being opened"));
2003
2004 /* get the IInternalSessionControl interface */
2005 ComPtr <IInternalSessionControl> control = aSession;
2006 ComAssertMsgRet (!!control, ("No IInternalSessionControl interface"),
2007 E_INVALIDARG);
2008
2009 rc = machine->openExistingSession (control);
2010
2011 return rc;
2012}
2013
2014/**
2015 * Registers a new client callback on this instance. The methods of the
2016 * callback interface will be called by this instance when the appropriate
2017 * event occurs.
2018 *
2019 * @note Locks this object for writing.
2020 */
2021STDMETHODIMP VirtualBox::RegisterCallback (IVirtualBoxCallback *callback)
2022{
2023 LogFlowMember (("VirtualBox::RegisterCallback(): callback=%p\n", callback));
2024
2025 if (!callback)
2026 return E_INVALIDARG;
2027
2028 AutoCaller autoCaller (this);
2029 CheckComRCReturnRC (autoCaller.rc());
2030
2031 AutoLock alock (this);
2032 mData.mCallbacks.push_back (CallbackList::value_type (callback));
2033
2034 return S_OK;
2035}
2036
2037/**
2038 * Unregisters the previously registered client callback.
2039 *
2040 * @note Locks this object for writing.
2041 */
2042STDMETHODIMP VirtualBox::UnregisterCallback (IVirtualBoxCallback *callback)
2043{
2044 if (!callback)
2045 return E_INVALIDARG;
2046
2047 AutoCaller autoCaller (this);
2048 CheckComRCReturnRC (autoCaller.rc());
2049
2050 HRESULT rc = S_OK;
2051
2052 AutoLock alock (this);
2053
2054 CallbackList::iterator it;
2055 it = std::find (mData.mCallbacks.begin(),
2056 mData.mCallbacks.end(),
2057 CallbackList::value_type (callback));
2058 if (it == mData.mCallbacks.end())
2059 rc = E_INVALIDARG;
2060 else
2061 mData.mCallbacks.erase (it);
2062
2063 LogFlowMember (("VirtualBox::UnregisterCallback(): callback=%p, rc=%08X\n",
2064 callback, rc));
2065 return rc;
2066}
2067
2068// public methods only for internal purposes
2069/////////////////////////////////////////////////////////////////////////////
2070
2071/**
2072 * Posts an event to the event queue that is processed asynchronously
2073 * on a dedicated thread.
2074 *
2075 * Posting events to the dedicated event queue is useful to perform secondary
2076 * actions outside any object locks -- for example, to iterate over a list
2077 * of callbacks and inform them about some change caused by some object's
2078 * method call.
2079 *
2080 * @param event event to post
2081 * (must be allocated using |new|, will be deleted automatically
2082 * by the event thread after processing)
2083 *
2084 * @note Doesn't lock any object.
2085 */
2086HRESULT VirtualBox::postEvent (Event *event)
2087{
2088 AutoCaller autoCaller (this);
2089 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
2090
2091 if (autoCaller.state() != Ready)
2092 {
2093 LogWarningFunc (("VirtualBox has been uninitialized (state=%d), "
2094 "the event is discarded!\n",
2095 autoCaller.state()));
2096 return S_OK;
2097 }
2098
2099 AssertReturn (event, E_FAIL);
2100 AssertReturn (mAsyncEventQ, E_FAIL);
2101
2102 AutoLock alock (mAsyncEventQLock);
2103 if (mAsyncEventQ->postEvent (event))
2104 return S_OK;
2105
2106 return E_FAIL;
2107}
2108
2109/**
2110 * Helper method to add a progress to the global collection of pending
2111 * operations.
2112 *
2113 * @param aProgress operation to add to the collection
2114 * @return COM status code
2115 *
2116 * @note Locks this object for writing.
2117 */
2118HRESULT VirtualBox::addProgress (IProgress *aProgress)
2119{
2120 if (!aProgress)
2121 return E_INVALIDARG;
2122
2123 AutoCaller autoCaller (this);
2124 CheckComRCReturnRC (autoCaller.rc());
2125
2126 AutoLock alock (this);
2127 mData.mProgressOperations.push_back (aProgress);
2128 return S_OK;
2129}
2130
2131/**
2132 * Helper method to remove the progress from the global collection of pending
2133 * operations. Usualy gets called upon progress completion.
2134 *
2135 * @param aId UUID of the progress operation to remove
2136 * @return COM status code
2137 *
2138 * @note Locks this object for writing.
2139 */
2140HRESULT VirtualBox::removeProgress (INPTR GUIDPARAM aId)
2141{
2142 AutoCaller autoCaller (this);
2143 CheckComRCReturnRC (autoCaller.rc());
2144
2145 ComPtr <IProgress> progress;
2146
2147 AutoLock alock (this);
2148
2149 for (ProgressList::iterator it = mData.mProgressOperations.begin();
2150 it != mData.mProgressOperations.end();
2151 ++ it)
2152 {
2153 Guid id;
2154 (*it)->COMGETTER(Id) (id.asOutParam());
2155 if (id == aId)
2156 {
2157 mData.mProgressOperations.erase (it);
2158 return S_OK;
2159 }
2160 }
2161
2162 AssertFailed(); /* should never happen */
2163
2164 return E_FAIL;
2165}
2166
2167#ifdef __WIN__
2168
2169struct StartSVCHelperClientData
2170{
2171 ComObjPtr <VirtualBox> that;
2172 ComObjPtr <Progress> progress;
2173 bool privileged;
2174 VirtualBox::SVCHelperClientFunc func;
2175 void *user;
2176};
2177
2178/**
2179 * Helper method to that starts a worker thread that:
2180 * - creates a pipe communication channel using SVCHlpClient;
2181 * - starts a SVC Helper process that will inherit this channel;
2182 * - executes the supplied function by passing it the created SVCHlpClient
2183 * and opened instance to communicate to the Helper process and the given
2184 * Progress object.
2185 *
2186 * The user function is supposed to communicate to the helper process
2187 * using the \a aClient argument to do the requested job and optionally expose
2188 * the prgress through the \a aProgress object. The user function should never
2189 * call notifyComplete() on it: this will be done authomatically using the
2190 * result code returned by the function.
2191 *
2192 * Before the user function is stared, the communication channel passed to in
2193 * the \a aClient argument, is fully set up, the function should start using
2194 * it's write() and read() methods directly.
2195 *
2196 * The \a aVrc parameter of the user function may be used to return an error
2197 * code if it is related to communication errors (for example, returned by
2198 * the SVCHlpClient members when they fail). In this case, the correct error
2199 * message using this value will be reported to the caller. Note that the
2200 * value of \a aVrc is inspected only if the user function itself returns
2201 * a success.
2202 *
2203 * If a failure happens anywhere before the user function would be normally
2204 * called, it will be called anyway in special "cleanup only" mode indicated
2205 * by \a aClient, \a aProgress and \aVrc arguments set to NULL. In this mode,
2206 * all the function is supposed to do is to cleanup its aUser argument if
2207 * necessary (it's assumed that the ownership of this argument is passed to
2208 * the user function once #startSVCHelperClient() returns a success, thus
2209 * making it responsible for the cleanup).
2210 *
2211 * After the user function returns, the thread will send the SVCHlpMsg::Null
2212 * message to indicate a process termination.
2213 *
2214 * @param aPrivileged |true| to start the SVC Hepler process as a privlieged
2215 * user that can perform administrative tasks
2216 * @param aFunc user function to run
2217 * @param aUser argument to the user function
2218 * @param aProgress progress object that will track operation completion
2219 *
2220 * @note aPrivileged is currently ignored (due to some unsolved problems in
2221 * Vista) and the process will be started as a normal (unprivileged)
2222 * process.
2223 *
2224 * @note Doesn't lock anything.
2225 */
2226HRESULT VirtualBox::startSVCHelperClient (bool aPrivileged,
2227 SVCHelperClientFunc aFunc,
2228 void *aUser, Progress *aProgress)
2229{
2230 AssertReturn (aFunc, E_POINTER);
2231 AssertReturn (aProgress, E_POINTER);
2232
2233 AutoCaller autoCaller (this);
2234 CheckComRCReturnRC (autoCaller.rc());
2235
2236 /* create the SVCHelperClientThread() argument */
2237 std::auto_ptr <StartSVCHelperClientData>
2238 d (new StartSVCHelperClientData());
2239 AssertReturn (d.get(), E_OUTOFMEMORY);
2240
2241 d->that = this;
2242 d->progress = aProgress;
2243 d->privileged = aPrivileged;
2244 d->func = aFunc;
2245 d->user = aUser;
2246
2247 RTTHREAD tid = NIL_RTTHREAD;
2248 int vrc = RTThreadCreate (&tid, SVCHelperClientThread,
2249 static_cast <void *> (d.get()),
2250 0, RTTHREADTYPE_MAIN_WORKER,
2251 RTTHREADFLAGS_WAITABLE, "SVCHelper");
2252
2253 ComAssertMsgRCRet (vrc, ("Could not create SVCHelper thread (%Vrc)\n", vrc),
2254 E_FAIL);
2255
2256 /* d is now owned by SVCHelperClientThread(), so release it */
2257 d.release();
2258
2259 return S_OK;
2260}
2261
2262/**
2263 * Worker thread for startSVCHelperClient().
2264 */
2265/* static */
2266DECLCALLBACK(int)
2267VirtualBox::SVCHelperClientThread (RTTHREAD aThread, void *aUser)
2268{
2269 LogFlowFuncEnter();
2270
2271 std::auto_ptr <StartSVCHelperClientData>
2272 d (static_cast <StartSVCHelperClientData *> (aUser));
2273
2274 HRESULT rc = S_OK;
2275 bool userFuncCalled = false;
2276
2277 do
2278 {
2279 AssertBreak (d.get(), rc = E_POINTER);
2280 AssertReturn (!d->progress.isNull(), E_POINTER);
2281
2282 /* protect VirtualBox from uninitialization */
2283 AutoCaller autoCaller (d->that);
2284 if (!autoCaller.isOk())
2285 {
2286 /* it's too late */
2287 rc = autoCaller.rc();
2288 break;
2289 }
2290
2291 int vrc = VINF_SUCCESS;
2292
2293 Guid id;
2294 id.create();
2295 SVCHlpClient client;
2296 vrc = client.create (Utf8StrFmt ("VirtualBox\\SVCHelper\\{%Vuuid}",
2297 id.raw()));
2298 if (VBOX_FAILURE (vrc))
2299 {
2300 rc = setError (E_FAIL,
2301 tr ("Could not create the communication channel (%Vrc)"), vrc);
2302 break;
2303 }
2304
2305 /* get the path to the executable */
2306 char exePathBuf [RTPATH_MAX];
2307 char *exePath = RTProcGetExecutableName (exePathBuf, RTPATH_MAX);
2308 ComAssertBreak (exePath, E_FAIL);
2309
2310 Utf8Str argsStr = Utf8StrFmt ("/Helper %s", client.name().raw());
2311
2312 LogFlowFunc (("Starting '\"%s\" %s'...\n", exePath, argsStr.raw()));
2313
2314 RTPROCESS pid = NIL_RTPROCESS;
2315
2316 if (d->privileged)
2317 {
2318 /* Attempt to start a privileged process using the Run As dialog */
2319
2320 Bstr file = exePath;
2321 Bstr parameters = argsStr;
2322
2323 SHELLEXECUTEINFO shExecInfo;
2324
2325 shExecInfo.cbSize = sizeof (SHELLEXECUTEINFO);
2326
2327 shExecInfo.fMask = NULL;
2328 shExecInfo.hwnd = NULL;
2329 shExecInfo.lpVerb = L"runas";
2330 shExecInfo.lpFile = file;
2331 shExecInfo.lpParameters = parameters;
2332 shExecInfo.lpDirectory = NULL;
2333 shExecInfo.nShow = SW_NORMAL;
2334 shExecInfo.hInstApp = NULL;
2335
2336 if (!ShellExecuteEx (&shExecInfo))
2337 {
2338 int vrc2 = RTErrConvertFromWin32 (GetLastError());
2339 /* hide excessive details in case of a frequent error
2340 * (pressing the Cancel button to close the Run As dialog) */
2341 if (vrc2 == VERR_CANCELLED)
2342 rc = setError (E_FAIL,
2343 tr ("Operatiion cancelled by the user"));
2344 else
2345 rc = setError (E_FAIL,
2346 tr ("Could not launch a privileged process '%s' (%Vrc)"),
2347 exePath, vrc2);
2348 break;
2349 }
2350 }
2351 else
2352 {
2353 const char *args[] = { exePath, "/Helper", client.name(), 0 };
2354 vrc = RTProcCreate (exePath, args, NULL, 0, &pid);
2355 if (VBOX_FAILURE (vrc))
2356 {
2357 rc = setError (E_FAIL,
2358 tr ("Could not launch a process '%s' (%Vrc)"), exePath, vrc);
2359 break;
2360 }
2361 }
2362
2363 /* wait for the client to connect */
2364 vrc = client.connect();
2365 if (VBOX_SUCCESS (vrc))
2366 {
2367 /* start the user supplied function */
2368 rc = d->func (&client, d->progress, d->user, &vrc);
2369 userFuncCalled = true;
2370 }
2371
2372 /* send the termination signal to the process anyway */
2373 {
2374 int vrc2 = client.write (SVCHlpMsg::Null);
2375 if (VBOX_SUCCESS (vrc))
2376 vrc = vrc2;
2377 }
2378
2379 if (SUCCEEDED (rc) && VBOX_FAILURE (vrc))
2380 {
2381 rc = setError (E_FAIL,
2382 tr ("Could not operate the communication channel (%Vrc)"), vrc);
2383 break;
2384 }
2385 }
2386 while (0);
2387
2388 if (FAILED (rc) && !userFuncCalled)
2389 {
2390 /* call the user function in the "cleanup only" mode
2391 * to let it free resources passed to in aUser */
2392 d->func (NULL, NULL, d->user, NULL);
2393 }
2394
2395 d->progress->notifyComplete (rc);
2396
2397 LogFlowFuncLeave();
2398 return 0;
2399}
2400
2401#endif /* __WIN__ */
2402
2403/**
2404 * Sends a signal to the client watcher thread to rescan the set of machines
2405 * that have open sessions.
2406 *
2407 * @note Doesn't lock anything.
2408 */
2409void VirtualBox::updateClientWatcher()
2410{
2411 AutoCaller autoCaller (this);
2412 AssertComRCReturn (autoCaller.rc(), (void) 0);
2413
2414 AssertReturn (mWatcherData.mThread != NIL_RTTHREAD, (void) 0);
2415
2416 /* sent an update request */
2417#if defined(__WIN__)
2418 ::SetEvent (mWatcherData.mUpdateReq);
2419#else
2420 RTSemEventSignal (mWatcherData.mUpdateReq);
2421#endif
2422}
2423
2424/**
2425 * Adds the given child process ID to the list of processes to be reaped.
2426 * This call should be followed by #updateClientWatcher() to take the effect.
2427 */
2428void VirtualBox::addProcessToReap (RTPROCESS pid)
2429{
2430 AutoCaller autoCaller (this);
2431 AssertComRCReturn (autoCaller.rc(), (void) 0);
2432
2433 /// @todo (dmik) Win32?
2434#ifndef __WIN__
2435 AutoLock alock (this);
2436 mWatcherData.mProcesses.push_back (pid);
2437#endif
2438}
2439
2440/** Event for onMachineStateChange(), onMachineDataChange(), onMachineRegistered() */
2441struct MachineEvent : public VirtualBox::CallbackEvent
2442{
2443 enum What { DataChanged, StateChanged, Registered };
2444
2445 MachineEvent (VirtualBox *aVB, const Guid &aId)
2446 : CallbackEvent (aVB), what (DataChanged), id (aId)
2447 {}
2448
2449 MachineEvent (VirtualBox *aVB, const Guid &aId, MachineState_T aState)
2450 : CallbackEvent (aVB), what (StateChanged), id (aId)
2451 , state (aState)
2452 {}
2453
2454 MachineEvent (VirtualBox *aVB, const Guid &aId, BOOL aRegistered)
2455 : CallbackEvent (aVB), what (Registered), id (aId)
2456 , registered (aRegistered)
2457 {}
2458
2459 void handleCallback (const ComPtr <IVirtualBoxCallback> &aCallback)
2460 {
2461 switch (what)
2462 {
2463 case DataChanged:
2464 LogFlow (("OnMachineDataChange: id={%Vuuid}\n", id.ptr()));
2465 aCallback->OnMachineDataChange (id);
2466 break;
2467
2468 case StateChanged:
2469 LogFlow (("OnMachineStateChange: id={%Vuuid}, state=%d\n",
2470 id.ptr(), state));
2471 aCallback->OnMachineStateChange (id, state);
2472 break;
2473
2474 case Registered:
2475 LogFlow (("OnMachineRegistered: id={%Vuuid}, registered=%d\n",
2476 id.ptr(), registered));
2477 aCallback->OnMachineRegistered (id, registered);
2478 break;
2479 }
2480 }
2481
2482 const What what;
2483
2484 Guid id;
2485 MachineState_T state;
2486 BOOL registered;
2487};
2488
2489/**
2490 * @note Doesn't lock any object.
2491 */
2492void VirtualBox::onMachineStateChange (const Guid &id, MachineState_T state)
2493{
2494 postEvent (new MachineEvent (this, id, state));
2495}
2496
2497/**
2498 * @note Doesn't lock any object.
2499 */
2500void VirtualBox::onMachineDataChange (const Guid &id)
2501{
2502 postEvent (new MachineEvent (this, id));
2503}
2504
2505/**
2506 * @note Locks this object for reading.
2507 */
2508BOOL VirtualBox::onExtraDataCanChange(const Guid &id, INPTR BSTR key, INPTR BSTR value)
2509{
2510 LogFlowThisFunc(("machine={%s} key={%ls} val={%ls}\n",
2511 id.toString().raw(), key, value));
2512
2513 CallbackList list;
2514 {
2515 AutoReaderLock alock (this);
2516 list = mData.mCallbacks;
2517 }
2518
2519 BOOL allowChange = true;
2520 CallbackList::iterator it = list.begin();
2521 while ((it != list.end()) && allowChange)
2522 {
2523 HRESULT rc = (*it++)->OnExtraDataCanChange(id, key, value, &allowChange);
2524 if (FAILED (rc))
2525 {
2526 /*
2527 * if a call to this method fails for some reason (for ex., because
2528 * the other side is dead), we ensure allowChange stays true
2529 * (MS COM RPC implementation seems to zero all output vars before
2530 * issuing an IPC call or after a failure, so it's essential there)
2531 */
2532 allowChange = true;
2533 }
2534 }
2535
2536 LogFlowThisFunc (("allowChange=%d\n", allowChange));
2537 return allowChange;
2538}
2539
2540/** Event for onExtraDataChange() */
2541struct ExtraDataEvent : public VirtualBox::CallbackEvent
2542{
2543 ExtraDataEvent (VirtualBox *aVB, const Guid &aMachineId,
2544 INPTR BSTR aKey, INPTR BSTR aVal)
2545 : CallbackEvent (aVB), machineId (aMachineId)
2546 , key (aKey), val (aVal)
2547 {}
2548
2549 void handleCallback (const ComPtr <IVirtualBoxCallback> &aCallback)
2550 {
2551 LogFlow (("OnExtraDataChange: machineId={%Vuuid}, key='%ls', val='%ls'\n",
2552 machineId.ptr(), key.raw(), val.raw()));
2553 aCallback->OnExtraDataChange (machineId, key, val);
2554 }
2555
2556 Guid machineId;
2557 Bstr key, val;
2558};
2559
2560/**
2561 * @note Doesn't lock any object.
2562 */
2563void VirtualBox::onExtraDataChange (const Guid &id, INPTR BSTR key, INPTR BSTR value)
2564{
2565 postEvent (new ExtraDataEvent (this, id, key, value));
2566}
2567
2568/**
2569 * @note Doesn't lock any object.
2570 */
2571void VirtualBox::onMachineRegistered (const Guid &aId, BOOL aRegistered)
2572{
2573 postEvent (new MachineEvent (this, aId, aRegistered));
2574}
2575
2576/** Event for onSessionStateChange() */
2577struct SessionEvent : public VirtualBox::CallbackEvent
2578{
2579 SessionEvent (VirtualBox *aVB, const Guid &aMachineId, SessionState_T aState)
2580 : CallbackEvent (aVB), machineId (aMachineId), sessionState (aState)
2581 {}
2582
2583 void handleCallback (const ComPtr <IVirtualBoxCallback> &aCallback)
2584 {
2585 LogFlow (("OnSessionStateChange: machineId={%Vuuid}, sessionState=%d\n",
2586 machineId.ptr(), sessionState));
2587 aCallback->OnSessionStateChange (machineId, sessionState);
2588 }
2589
2590 Guid machineId;
2591 SessionState_T sessionState;
2592};
2593
2594/**
2595 * @note Doesn't lock any object.
2596 */
2597void VirtualBox::onSessionStateChange (const Guid &id, SessionState_T state)
2598{
2599 postEvent (new SessionEvent (this, id, state));
2600}
2601
2602/** Event for onSnapshotTaken(), onSnapshotRemoved() and onSnapshotChange() */
2603struct SnapshotEvent : public VirtualBox::CallbackEvent
2604{
2605 enum What { Taken, Discarded, Changed };
2606
2607 SnapshotEvent (VirtualBox *aVB, const Guid &aMachineId, const Guid &aSnapshotId,
2608 What aWhat)
2609 : CallbackEvent (aVB)
2610 , what (aWhat)
2611 , machineId (aMachineId), snapshotId (aSnapshotId)
2612 {}
2613
2614 void handleCallback (const ComPtr <IVirtualBoxCallback> &aCallback)
2615 {
2616 switch (what)
2617 {
2618 case Taken:
2619 LogFlow (("OnSnapshotTaken: machineId={%Vuuid}, snapshotId={%Vuuid}\n",
2620 machineId.ptr(), snapshotId.ptr()));
2621 aCallback->OnSnapshotTaken (machineId, snapshotId);
2622 break;
2623
2624 case Discarded:
2625 LogFlow (("OnSnapshotDiscarded: machineId={%Vuuid}, snapshotId={%Vuuid}\n",
2626 machineId.ptr(), snapshotId.ptr()));
2627 aCallback->OnSnapshotDiscarded (machineId, snapshotId);
2628 break;
2629
2630 case Changed:
2631 LogFlow (("OnSnapshotChange: machineId={%Vuuid}, snapshotId={%Vuuid}\n",
2632 machineId.ptr(), snapshotId.ptr()));
2633 aCallback->OnSnapshotChange (machineId, snapshotId);
2634 break;
2635 }
2636 }
2637
2638 const What what;
2639
2640 Guid machineId;
2641 Guid snapshotId;
2642};
2643
2644/**
2645 * @note Doesn't lock any object.
2646 */
2647void VirtualBox::onSnapshotTaken (const Guid &aMachineId, const Guid &aSnapshotId)
2648{
2649 postEvent (new SnapshotEvent (this, aMachineId, aSnapshotId, SnapshotEvent::Taken));
2650}
2651
2652/**
2653 * @note Doesn't lock any object.
2654 */
2655void VirtualBox::onSnapshotDiscarded (const Guid &aMachineId, const Guid &aSnapshotId)
2656{
2657 postEvent (new SnapshotEvent (this, aMachineId, aSnapshotId, SnapshotEvent::Discarded));
2658}
2659
2660/**
2661 * @note Doesn't lock any object.
2662 */
2663void VirtualBox::onSnapshotChange (const Guid &aMachineId, const Guid &aSnapshotId)
2664{
2665 postEvent (new SnapshotEvent (this, aMachineId, aSnapshotId, SnapshotEvent::Changed));
2666}
2667
2668/**
2669 * @note Locks this object for reading.
2670 */
2671ComPtr <IGuestOSType> VirtualBox::getUnknownOSType()
2672{
2673 ComPtr <IGuestOSType> type;
2674
2675 AutoCaller autoCaller (this);
2676 AssertComRCReturn (autoCaller.rc(), type);
2677
2678 AutoReaderLock alock (this);
2679 ComAssertRet (mData.mGuestOSTypes.size() > 0, type);
2680
2681 type = mData.mGuestOSTypes.front();
2682 return type;
2683}
2684
2685/**
2686 * Returns the list of opened machines (i.e. machines having direct sessions
2687 * opened by client processes).
2688 *
2689 * @note the returned list contains smart pointers. So, clear it as soon as
2690 * it becomes no more necessary to release instances.
2691 * @note it can be possible that a session machine from the list has been
2692 * already uninitialized, so a) lock the instance and b) chheck for
2693 * instance->isReady() return value before manipulating the object directly
2694 * (i.e. not through COM methods).
2695 *
2696 * @note Locks objects for reading.
2697 */
2698void VirtualBox::getOpenedMachines (SessionMachineVector &aVector)
2699{
2700 AutoCaller autoCaller (this);
2701 AssertComRCReturn (autoCaller.rc(), (void) 0);
2702
2703 std::list <ComObjPtr <SessionMachine> > list;
2704
2705 {
2706 AutoReaderLock alock (this);
2707
2708 for (MachineList::iterator it = mData.mMachines.begin();
2709 it != mData.mMachines.end();
2710 ++ it)
2711 {
2712 ComObjPtr <SessionMachine> sm = (*it)->sessionMachine();
2713 /* SessionMachine is null when there are no open sessions */
2714 if (!sm.isNull())
2715 list.push_back (sm);
2716 }
2717 }
2718
2719 aVector = SessionMachineVector (list.begin(), list.end());
2720 return;
2721}
2722
2723/**
2724 * Helper to find machines that use the given DVD image.
2725 *
2726 * @param machineIDs string where to store the list (can be NULL)
2727 * @return TRUE if at least one machine found and false otherwise
2728 *
2729 * @note For now, we just scan all the machines. We can optimize this later
2730 * if required by adding the corresponding field to DVDImage and requiring all
2731 * IDVDImage instances to be DVDImage objects.
2732 *
2733 * @note Locks objects for reading.
2734 */
2735BOOL VirtualBox::getDVDImageUsage (const Guid &id,
2736 ResourceUsage_T usage,
2737 Bstr *machineIDs)
2738{
2739 AutoCaller autoCaller (this);
2740 AssertComRCReturn (autoCaller.rc(), FALSE);
2741
2742 typedef std::set <Guid> Set;
2743 Set idSet;
2744
2745 {
2746 AutoReaderLock alock (this);
2747
2748 for (MachineList::const_iterator mit = mData.mMachines.begin();
2749 mit != mData.mMachines.end();
2750 ++ mit)
2751 {
2752 /// @todo (dmik) move this part to Machine for better incapsulation
2753
2754 ComObjPtr <Machine> m = *mit;
2755 AutoReaderLock malock (m);
2756
2757 /* take the session machine when appropriate */
2758 if (!m->data()->mSession.mMachine.isNull())
2759 m = m->data()->mSession.mMachine;
2760
2761 const ComObjPtr <DVDDrive> &dvd = m->dvdDrive();
2762 AutoReaderLock dalock (dvd);
2763
2764 /* loop over the backed up (permanent) and current (temporary) dvd data */
2765 DVDDrive::Data *dvdData [2];
2766 if (dvd->data().isBackedUp())
2767 {
2768 dvdData [0] = dvd->data().backedUpData();
2769 dvdData [1] = dvd->data().data();
2770 }
2771 else
2772 {
2773 dvdData [0] = dvd->data().data();
2774 dvdData [1] = NULL;
2775 }
2776
2777 if (!(usage & ResourceUsage_PermanentUsage))
2778 dvdData [0] = NULL;
2779 if (!(usage & ResourceUsage_TemporaryUsage))
2780 dvdData [1] = NULL;
2781
2782 for (unsigned i = 0; i < ELEMENTS (dvdData); i++)
2783 {
2784 if (dvdData [i])
2785 {
2786 if (dvdData [i]->mDriveState == DriveState_ImageMounted)
2787 {
2788 Guid iid;
2789 dvdData [i]->mDVDImage->COMGETTER(Id) (iid.asOutParam());
2790 if (iid == id)
2791 idSet.insert (m->data()->mUuid);
2792 }
2793 }
2794 }
2795 }
2796 }
2797
2798 if (machineIDs)
2799 {
2800 if (!idSet.empty())
2801 {
2802 /* convert to a string of UUIDs */
2803 char *idList = (char *) RTMemTmpAllocZ (RTUUID_STR_LENGTH * idSet.size());
2804 char *idListPtr = idList;
2805 for (Set::iterator it = idSet.begin(); it != idSet.end(); ++ it)
2806 {
2807 RTUuidToStr (*it, idListPtr, RTUUID_STR_LENGTH);
2808 idListPtr += RTUUID_STR_LENGTH - 1;
2809 /* replace EOS with a space char */
2810 *(idListPtr ++) = ' ';
2811 }
2812 Assert (int (idListPtr - idList) == int (RTUUID_STR_LENGTH * idSet.size()));
2813 /* remove the trailing space */
2814 *(-- idListPtr) = 0;
2815 /* copy the string */
2816 *machineIDs = idList;
2817 RTMemTmpFree (idList);
2818 }
2819 else
2820 {
2821 (*machineIDs).setNull();
2822 }
2823 }
2824
2825 return !idSet.empty();
2826}
2827
2828/**
2829 * Helper to find machines that use the given floppy image.
2830 *
2831 * @param machineIDs string where to store the list (can be NULL)
2832 * @return TRUE if at least one machine found and false otherwise
2833 *
2834 * @note For now, we just scan all the machines. We can optimize this later
2835 * if required by adding the corresponding field to FloppyImage and requiring all
2836 * IFloppyImage instances to be FloppyImage objects.
2837 *
2838 * @note Locks objects for reading.
2839 */
2840BOOL VirtualBox::getFloppyImageUsage (const Guid &id,
2841 ResourceUsage_T usage,
2842 Bstr *machineIDs)
2843{
2844 AutoCaller autoCaller (this);
2845 AssertComRCReturn (autoCaller.rc(), FALSE);
2846
2847 typedef std::set <Guid> Set;
2848 Set idSet;
2849
2850 {
2851 AutoReaderLock alock (this);
2852
2853 for (MachineList::const_iterator mit = mData.mMachines.begin();
2854 mit != mData.mMachines.end();
2855 ++ mit)
2856 {
2857 /// @todo (dmik) move this part to Machine for better incapsulation
2858
2859 ComObjPtr <Machine> m = *mit;
2860 AutoReaderLock malock (m);
2861
2862 /* take the session machine when appropriate */
2863 if (!m->data()->mSession.mMachine.isNull())
2864 m = m->data()->mSession.mMachine;
2865
2866 const ComObjPtr <FloppyDrive> &drv = m->floppyDrive();
2867 AutoReaderLock dalock (drv);
2868
2869 /* loop over the backed up (permanent) and current (temporary) floppy data */
2870 FloppyDrive::Data *data [2];
2871 if (drv->data().isBackedUp())
2872 {
2873 data [0] = drv->data().backedUpData();
2874 data [1] = drv->data().data();
2875 }
2876 else
2877 {
2878 data [0] = drv->data().data();
2879 data [1] = NULL;
2880 }
2881
2882 if (!(usage & ResourceUsage_PermanentUsage))
2883 data [0] = NULL;
2884 if (!(usage & ResourceUsage_TemporaryUsage))
2885 data [1] = NULL;
2886
2887 for (unsigned i = 0; i < ELEMENTS (data); i++)
2888 {
2889 if (data [i])
2890 {
2891 if (data [i]->mDriveState == DriveState_ImageMounted)
2892 {
2893 Guid iid;
2894 data [i]->mFloppyImage->COMGETTER(Id) (iid.asOutParam());
2895 if (iid == id)
2896 idSet.insert (m->data()->mUuid);
2897 }
2898 }
2899 }
2900 }
2901 }
2902
2903 if (machineIDs)
2904 {
2905 if (!idSet.empty())
2906 {
2907 /* convert to a string of UUIDs */
2908 char *idList = (char *) RTMemTmpAllocZ (RTUUID_STR_LENGTH * idSet.size());
2909 char *idListPtr = idList;
2910 for (Set::iterator it = idSet.begin(); it != idSet.end(); ++ it)
2911 {
2912 RTUuidToStr (*it, idListPtr, RTUUID_STR_LENGTH);
2913 idListPtr += RTUUID_STR_LENGTH - 1;
2914 /* replace EOS with a space char */
2915 *(idListPtr ++) = ' ';
2916 }
2917 Assert (int (idListPtr - idList) == int (RTUUID_STR_LENGTH * idSet.size()));
2918 /* remove the trailing space */
2919 *(-- idListPtr) = 0;
2920 /* copy the string */
2921 *machineIDs = idList;
2922 RTMemTmpFree (idList);
2923 }
2924 else
2925 {
2926 (*machineIDs).setNull();
2927 }
2928 }
2929
2930 return !idSet.empty();
2931}
2932
2933/**
2934 * Tries to calculate the relative path of the given absolute path using the
2935 * directory of the VirtualBox settings file as the base directory.
2936 *
2937 * @param aPath absolute path to calculate the relative path for
2938 * @param aResult where to put the result (used only when it's possible to
2939 * make a relative path from the given absolute path;
2940 * otherwise left untouched)
2941 *
2942 * @note Doesn't lock any object.
2943 */
2944void VirtualBox::calculateRelativePath (const char *aPath, Utf8Str &aResult)
2945{
2946 AutoCaller autoCaller (this);
2947 AssertComRCReturn (autoCaller.rc(), (void) 0);
2948
2949 /* no need to lock since mHomeDir is const */
2950
2951 Utf8Str settingsDir = mData.mHomeDir;
2952
2953 if (RTPathStartsWith (aPath, settingsDir))
2954 {
2955 /* when assigning, we create a separate Utf8Str instance because both
2956 * aPath and aResult can point to the same memory location when this
2957 * func is called (if we just do aResult = aPath, aResult will be freed
2958 * first, and since its the same as aPath, an attempt to copy garbage
2959 * will be made. */
2960 aResult = Utf8Str (aPath + settingsDir.length() + 1);
2961 }
2962}
2963
2964// private methods
2965/////////////////////////////////////////////////////////////////////////////
2966
2967/**
2968 * Searches for a Machine object with the given ID in the collection
2969 * of registered machines.
2970 *
2971 * @param id
2972 * ID of the machine
2973 * @param doSetError
2974 * if TRUE, the appropriate error info is set in case when the machine
2975 * is not found
2976 * @param machine
2977 * where to store the found machine object (can be NULL)
2978 *
2979 * @return
2980 * S_OK when found or E_INVALIDARG when not found
2981 *
2982 * @note Locks this object for reading.
2983 */
2984HRESULT VirtualBox::findMachine (const Guid &aId, bool aSetError,
2985 ComObjPtr <Machine> *aMachine /* = NULL */)
2986{
2987 AutoCaller autoCaller (this);
2988 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
2989
2990 bool found = false;
2991
2992 {
2993 AutoReaderLock alock (this);
2994
2995 for (MachineList::iterator it = mData.mMachines.begin();
2996 !found && it != mData.mMachines.end();
2997 ++ it)
2998 {
2999 /* mUuid is constant, no need to lock */
3000 found = (*it)->data()->mUuid == aId;
3001 if (found && aMachine)
3002 *aMachine = *it;
3003 }
3004 }
3005
3006 HRESULT rc = found ? S_OK : E_INVALIDARG;
3007
3008 if (aSetError && !found)
3009 {
3010 setError (E_INVALIDARG,
3011 tr ("Could not find a registered machine with UUID {%Vuuid}"),
3012 aId.raw());
3013 }
3014
3015 return rc;
3016}
3017
3018/**
3019 * Searches for a HardDisk object with the given ID or location specification
3020 * in the collection of registered hard disks. If both ID and location are
3021 * specified, the first object that matches either of them (not necessarily
3022 * both) is returned.
3023 *
3024 * @param aId ID of the hard disk (NULL when unused)
3025 * @param aLocation full location specification (NULL when unused)
3026 * @param aSetError if TRUE, the appropriate error info is set in case when
3027 * the disk is not found and only one search criteria (ID
3028 * or file name) is specified.
3029 * @param aHardDisk where to store the found hard disk object (can be NULL)
3030 *
3031 * @return
3032 * S_OK when found or E_INVALIDARG when not found
3033 *
3034 * @note Locks objects for reading!
3035 */
3036HRESULT VirtualBox::
3037findHardDisk (const Guid *aId, const BSTR aLocation,
3038 bool aSetError, ComObjPtr <HardDisk> *aHardDisk /* = NULL */)
3039{
3040 ComAssertRet (aId || aLocation, E_INVALIDARG);
3041
3042 AutoReaderLock alock (this);
3043
3044 /* first lookup the map by UUID if UUID is provided */
3045 if (aId)
3046 {
3047 HardDiskMap::const_iterator it = mData.mHardDiskMap.find (*aId);
3048 if (it != mData.mHardDiskMap.end())
3049 {
3050 if (aHardDisk)
3051 *aHardDisk = (*it).second;
3052 return S_OK;
3053 }
3054 }
3055
3056 /* then iterate and find by location */
3057 bool found = false;
3058 if (aLocation)
3059 {
3060 Utf8Str location = aLocation;
3061
3062 for (HardDiskMap::const_iterator it = mData.mHardDiskMap.begin();
3063 !found && it != mData.mHardDiskMap.end();
3064 ++ it)
3065 {
3066 const ComObjPtr <HardDisk> &hd = (*it).second;
3067 AutoReaderLock hdLock (hd);
3068
3069 if (hd->storageType() == HardDiskStorageType_VirtualDiskImage ||
3070 hd->storageType() == HardDiskStorageType_VMDKImage)
3071 {
3072 /* locations of VDI and VMDK hard disks for now are just
3073 * file paths */
3074 found = RTPathCompare (location,
3075 Utf8Str (hd->toString
3076 (false /* aShort */))) == 0;
3077 }
3078 else
3079 {
3080 found = aLocation == hd->toString (false /* aShort */);
3081 }
3082
3083 if (found && aHardDisk)
3084 *aHardDisk = hd;
3085 }
3086 }
3087
3088 HRESULT rc = found ? S_OK : E_INVALIDARG;
3089
3090 if (aSetError && !found)
3091 {
3092 if (aId && !aLocation)
3093 setError (rc, tr ("Could not find a registered hard disk "
3094 "with UUID {%Vuuid}"), aId->raw());
3095 else if (aLocation && !aId)
3096 setError (rc, tr ("Could not find a registered hard disk "
3097 "with location '%ls'"), aLocation);
3098 }
3099
3100 return rc;
3101}
3102
3103/**
3104 * @deprecated Use #findHardDisk() instead.
3105 *
3106 * Searches for a HVirtualDiskImage object with the given ID or file path in the
3107 * collection of registered hard disks. If both ID and file path are specified,
3108 * the first object that matches either of them (not necessarily both)
3109 * is returned.
3110 *
3111 * @param aId ID of the hard disk (NULL when unused)
3112 * @param filePathFull full path to the image file (NULL when unused)
3113 * @param aSetError if TRUE, the appropriate error info is set in case when
3114 * the disk is not found and only one search criteria (ID
3115 * or file name) is specified.
3116 * @param aHardDisk where to store the found hard disk object (can be NULL)
3117 *
3118 * @return
3119 * S_OK when found or E_INVALIDARG when not found
3120 *
3121 * @note Locks objects for reading!
3122 */
3123HRESULT VirtualBox::
3124findVirtualDiskImage (const Guid *aId, const BSTR aFilePathFull,
3125 bool aSetError, ComObjPtr <HVirtualDiskImage> *aImage /* = NULL */)
3126{
3127 ComAssertRet (aId || aFilePathFull, E_INVALIDARG);
3128
3129 AutoReaderLock alock (this);
3130
3131 /* first lookup the map by UUID if UUID is provided */
3132 if (aId)
3133 {
3134 HardDiskMap::const_iterator it = mData.mHardDiskMap.find (*aId);
3135 if (it != mData.mHardDiskMap.end())
3136 {
3137 AutoReaderLock hdLock ((*it).second);
3138 if ((*it).second->storageType() == HardDiskStorageType_VirtualDiskImage)
3139 {
3140 if (aImage)
3141 *aImage = (*it).second->asVDI();
3142 return S_OK;
3143 }
3144 }
3145 }
3146
3147 /* then iterate and find by name */
3148 bool found = false;
3149 if (aFilePathFull)
3150 {
3151 for (HardDiskMap::const_iterator it = mData.mHardDiskMap.begin();
3152 !found && it != mData.mHardDiskMap.end();
3153 ++ it)
3154 {
3155 const ComObjPtr <HardDisk> &hd = (*it).second;
3156 AutoReaderLock hdLock (hd);
3157 if (hd->storageType() != HardDiskStorageType_VirtualDiskImage)
3158 continue;
3159
3160 found = RTPathCompare (Utf8Str (aFilePathFull),
3161 Utf8Str (hd->asVDI()->filePathFull())) == 0;
3162 if (found && aImage)
3163 *aImage = hd->asVDI();
3164 }
3165 }
3166
3167 HRESULT rc = found ? S_OK : E_INVALIDARG;
3168
3169 if (aSetError && !found)
3170 {
3171 if (aId && !aFilePathFull)
3172 setError (rc, tr ("Could not find a registered VDI hard disk "
3173 "with UUID {%Vuuid}"), aId->raw());
3174 else if (aFilePathFull && !aId)
3175 setError (rc, tr ("Could not find a registered VDI hard disk "
3176 "with the file path '%ls'"), aFilePathFull);
3177 }
3178
3179 return rc;
3180}
3181
3182/**
3183 * Searches for a DVDImage object with the given ID or file path in the
3184 * collection of registered DVD images. If both ID and file path are specified,
3185 * the first object that matches either of them (not necessarily both)
3186 * is returned.
3187 *
3188 * @param id
3189 * ID of the DVD image (unused when NULL)
3190 * @param filePathFull
3191 * full path to the image file (unused when NULL)
3192 * @param aSetError
3193 * if TRUE, the appropriate error info is set in case when the image is not
3194 * found and only one search criteria (ID or file name) is specified.
3195 * @param dvdImage
3196 * where to store the found DVD image object (can be NULL)
3197 *
3198 * @return
3199 * S_OK when found or E_INVALIDARG when not found
3200 *
3201 * @note Locks this object for reading.
3202 */
3203HRESULT VirtualBox::findDVDImage (const Guid *aId, const BSTR aFilePathFull,
3204 bool aSetError,
3205 ComObjPtr <DVDImage> *aImage /* = NULL */)
3206{
3207 ComAssertRet (aId || aFilePathFull, E_INVALIDARG);
3208
3209 bool found = false;
3210
3211 {
3212 AutoReaderLock alock (this);
3213
3214 for (DVDImageList::const_iterator it = mData.mDVDImages.begin();
3215 !found && it != mData.mDVDImages.end();
3216 ++ it)
3217 {
3218 /* DVDImage fields are constant, so no need to lock */
3219 found = (aId && (*it)->id() == *aId) ||
3220 (aFilePathFull &&
3221 RTPathCompare (Utf8Str (aFilePathFull),
3222 Utf8Str ((*it)->filePathFull())) == 0);
3223 if (found && aImage)
3224 *aImage = *it;
3225 }
3226 }
3227
3228 HRESULT rc = found ? S_OK : E_INVALIDARG;
3229
3230 if (aSetError && !found)
3231 {
3232 if (aId && !aFilePathFull)
3233 setError (rc, tr ("Could not find a registered CD/DVD image "
3234 "with UUID {%s}"), aId->toString().raw());
3235 else if (aFilePathFull && !aId)
3236 setError (rc, tr ("Could not find a registered CD/DVD image "
3237 "with the file path '%ls'"), aFilePathFull);
3238 }
3239
3240 return rc;
3241}
3242
3243/**
3244 * Searches for a FloppyImage object with the given ID or file path in the
3245 * collection of registered floppy images. If both ID and file path are specified,
3246 * the first object that matches either of them (not necessarily both)
3247 * is returned.
3248 *
3249 * @param aId
3250 * ID of the floppy image (unused when NULL)
3251 * @param aFilePathFull
3252 * full path to the image file (unused when NULL)
3253 * @param aSetError
3254 * if TRUE, the appropriate error info is set in case when the image is not
3255 * found and only one search criteria (ID or file name) is specified.
3256 * @param aImage
3257 * where to store the found floppy image object (can be NULL)
3258 *
3259 * @return
3260 * S_OK when found or E_INVALIDARG when not found
3261 *
3262 * @note Locks this object for reading.
3263 */
3264HRESULT VirtualBox::findFloppyImage (const Guid *aId, const BSTR aFilePathFull,
3265 bool aSetError,
3266 ComObjPtr <FloppyImage> *aImage /* = NULL */)
3267{
3268 ComAssertRet (aId || aFilePathFull, E_INVALIDARG);
3269
3270 bool found = false;
3271
3272 {
3273 AutoReaderLock alock (this);
3274
3275 for (FloppyImageList::iterator it = mData.mFloppyImages.begin();
3276 !found && it != mData.mFloppyImages.end();
3277 ++ it)
3278 {
3279 /* FloppyImage fields are constant, so no need to lock */
3280 found = (aId && (*it)->id() == *aId) ||
3281 (aFilePathFull &&
3282 RTPathCompare (Utf8Str (aFilePathFull),
3283 Utf8Str ((*it)->filePathFull())) == 0);
3284 if (found && aImage)
3285 *aImage = *it;
3286 }
3287 }
3288
3289 HRESULT rc = found ? S_OK : E_INVALIDARG;
3290
3291 if (aSetError && !found)
3292 {
3293 if (aId && !aFilePathFull)
3294 setError (rc, tr ("Could not find a registered floppy image "
3295 "with UUID {%s}"), aId->toString().raw());
3296 else if (aFilePathFull && !aId)
3297 setError (rc, tr ("Could not find a registered floppy image "
3298 "with the file path '%ls'"), aFilePathFull);
3299 }
3300
3301 return rc;
3302}
3303
3304/**
3305 * When \a aHardDisk is not NULL, searches for an object equal to the given
3306 * hard disk in the collection of registered hard disks, or, if the given hard
3307 * disk is HVirtualDiskImage, for an object with the given file path in the
3308 * collection of all registered non-hard disk images (DVDs and floppies).
3309 * Other parameters are unused.
3310 *
3311 * When \a aHardDisk is NULL, searches for an object with the given ID or file
3312 * path in the collection of all registered images (VDIs, DVDs and floppies).
3313 * If both ID and file path are specified, matching either of them will satisfy
3314 * the search.
3315 *
3316 * If a matching object is found, this method returns E_INVALIDARG and sets the
3317 * appropriate error info. Otherwise, S_OK is returned.
3318 *
3319 * @param aHardDisk hard disk object to check against registered media
3320 * (NULL when unused)
3321 * @param aId UUID of the media to check (NULL when unused)
3322 * @param aFilePathFull full path to the image file (NULL when unused)
3323 *
3324 * @note Locks objects!
3325 */
3326HRESULT VirtualBox::checkMediaForConflicts (HardDisk *aHardDisk,
3327 const Guid *aId,
3328 const BSTR aFilePathFull)
3329{
3330 AssertReturn (aHardDisk || aId || aFilePathFull, E_FAIL);
3331
3332 HRESULT rc = S_OK;
3333
3334 AutoReaderLock alock (this);
3335
3336 if (aHardDisk)
3337 {
3338 for (HardDiskMap::const_iterator it = mData.mHardDiskMap.begin();
3339 it != mData.mHardDiskMap.end();
3340 ++ it)
3341 {
3342 const ComObjPtr <HardDisk> &hd = (*it).second;
3343 if (hd->sameAs (aHardDisk))
3344 return setError (E_INVALIDARG,
3345 tr ("A hard disk with UUID {%Vuuid} or with the same properties "
3346 "('%ls') is already registered"),
3347 aHardDisk->id().raw(), aHardDisk->toString().raw());
3348 }
3349
3350 aId = &aHardDisk->id();
3351 if (aHardDisk->storageType() == HardDiskStorageType_VirtualDiskImage)
3352#if defined(__WIN__)
3353 /// @todo (dmik) stupid BSTR declaration lacks the BCSTR counterpart
3354 const_cast <BSTR> (aFilePathFull) = aHardDisk->asVDI()->filePathFull();
3355#else
3356 aFilePathFull = aHardDisk->asVDI()->filePathFull();
3357#endif
3358 }
3359
3360 bool found = false;
3361
3362 if (aId || aFilePathFull) do
3363 {
3364 if (!aHardDisk)
3365 {
3366 rc = findHardDisk (aId, aFilePathFull, false /* aSetError */);
3367 found = SUCCEEDED (rc);
3368 if (found)
3369 break;
3370 }
3371
3372 rc = findDVDImage (aId, aFilePathFull, false /* aSetError */);
3373 found = SUCCEEDED (rc);
3374 if (found)
3375 break;
3376
3377 rc = findFloppyImage (aId, aFilePathFull, false /* aSetError */);
3378 found = SUCCEEDED (rc);
3379 if (found)
3380 break;
3381 }
3382 while (0);
3383
3384 if (found)
3385 {
3386 if (aId && !aFilePathFull)
3387 rc = setError (E_INVALIDARG,
3388 tr ("A disk image with UUID {%Vuuid} is already registered"),
3389 aId->raw());
3390 else if (aFilePathFull && !aId)
3391 rc = setError (E_INVALIDARG,
3392 tr ("A disk image with file path '%ls' is already registered"),
3393 aFilePathFull);
3394 else
3395 rc = setError (E_INVALIDARG,
3396 tr ("A disk image with UUID {%Vuuid} or file path '%ls' "
3397 "is already registered"), aId->raw(), aFilePathFull);
3398 }
3399 else
3400 rc = S_OK;
3401
3402 return rc;
3403}
3404
3405/**
3406 * Reads in the machine definitions from the configuration loader
3407 * and creates the relevant objects.
3408 *
3409 * @note Can be called only from #init().
3410 * @note Doesn't lock anything.
3411 */
3412HRESULT VirtualBox::loadMachines (CFGNODE aGlobal)
3413{
3414 AutoCaller autoCaller (this);
3415 AssertReturn (autoCaller.state() == InInit, E_FAIL);
3416
3417 HRESULT rc = S_OK;
3418 CFGNODE machineRegistry = 0;
3419 unsigned count = 0;
3420
3421 CFGLDRGetChildNode (aGlobal, "MachineRegistry", 0, &machineRegistry);
3422 Assert (machineRegistry);
3423
3424 CFGLDRCountChildren(machineRegistry, "MachineEntry", &count);
3425 for (unsigned i = 0; i < count && SUCCEEDED (rc); i++)
3426 {
3427 CFGNODE vm = 0;
3428 CFGLDRGetChildNode(machineRegistry, "MachineEntry", i, &vm);
3429 /* get the UUID */
3430 Guid uuid;
3431 CFGLDRQueryUUID(vm, "uuid", uuid.ptr());
3432 /* get the machine configuration file name */
3433 Bstr src;
3434 CFGLDRQueryBSTR(vm, "src", src.asOutParam());
3435
3436 /* create a new object */
3437 ComObjPtr <Machine> machine;
3438 rc = machine.createObject();
3439 if (SUCCEEDED (rc))
3440 {
3441 /* initialize the machine object and register it */
3442 rc = machine->init (this, src, Machine::Init_Registered,
3443 NULL, FALSE, &uuid);
3444 if (SUCCEEDED (rc))
3445 rc = registerMachine (machine);
3446 }
3447
3448 CFGLDRReleaseNode(vm);
3449 }
3450
3451 CFGLDRReleaseNode(machineRegistry);
3452
3453 return rc;
3454}
3455
3456/**
3457 * Reads in the disk registration entries from the global settings file
3458 * and creates the relevant objects
3459 *
3460 * @param aGlobal <Global> node
3461 *
3462 * @note Can be called only from #init().
3463 * @note Doesn't lock anything.
3464 */
3465HRESULT VirtualBox::loadDisks (CFGNODE aGlobal)
3466{
3467 AutoCaller autoCaller (this);
3468 AssertReturn (autoCaller.state() == InInit, E_FAIL);
3469
3470 HRESULT rc = S_OK;
3471 CFGNODE registryNode = 0;
3472
3473 CFGLDRGetChildNode (aGlobal, "DiskRegistry", 0, &registryNode);
3474 ComAssertRet (registryNode, E_FAIL);
3475
3476 const char *ImagesNodes[] = { "HardDisks", "DVDImages", "FloppyImages" };
3477
3478 for (size_t node = 0; node < ELEMENTS (ImagesNodes) && SUCCEEDED (rc); node ++)
3479 {
3480 CFGNODE imagesNode = 0;
3481 CFGLDRGetChildNode (registryNode, ImagesNodes [node], 0, &imagesNode);
3482
3483 // all three nodes are optional
3484 if (!imagesNode)
3485 continue;
3486
3487 if (node == 0) // HardDisks node
3488 rc = loadHardDisks (imagesNode);
3489 else
3490 {
3491 unsigned count = 0;
3492 CFGLDRCountChildren (imagesNode, "Image", &count);
3493 for (unsigned i = 0; i < count && SUCCEEDED (rc); ++ i)
3494 {
3495 CFGNODE imageNode = 0;
3496 CFGLDRGetChildNode (imagesNode, "Image", i, &imageNode);
3497 ComAssertBreak (imageNode, rc = E_FAIL);
3498
3499 Guid uuid; // uuid (required)
3500 CFGLDRQueryUUID (imageNode, "uuid", uuid.ptr());
3501 Bstr src; // source (required)
3502 CFGLDRQueryBSTR (imageNode, "src", src.asOutParam());
3503
3504 switch (node)
3505 {
3506 case 1: // DVDImages
3507 {
3508 ComObjPtr <DVDImage> dvdImage;
3509 dvdImage.createObject();
3510 rc = dvdImage->init (this, src, TRUE /* isRegistered */, uuid);
3511 if (SUCCEEDED (rc))
3512 rc = registerDVDImage (dvdImage, TRUE /* aOnStartUp */);
3513
3514 break;
3515 }
3516 case 2: // FloppyImages
3517 {
3518 ComObjPtr <FloppyImage> floppyImage;
3519 floppyImage.createObject();
3520 rc = floppyImage->init (this, src, TRUE /* isRegistered */, uuid);
3521 if (SUCCEEDED (rc))
3522 rc = registerFloppyImage (floppyImage, TRUE /* aOnStartUp */);
3523
3524 break;
3525 }
3526 default:
3527 AssertFailed();
3528 }
3529
3530 CFGLDRReleaseNode (imageNode);
3531 }
3532 }
3533
3534 CFGLDRReleaseNode (imagesNode);
3535 }
3536
3537 CFGLDRReleaseNode (registryNode);
3538
3539 return rc;
3540}
3541
3542/**
3543 * Loads all hard disks from the given <HardDisks> node.
3544 * Note that all loaded hard disks register themselves within this VirtualBox.
3545 *
3546 * @param aNode <HardDisks> node
3547 *
3548 * @note Can be called only from #init().
3549 * @note Doesn't lock anything.
3550 */
3551HRESULT VirtualBox::loadHardDisks (CFGNODE aNode)
3552{
3553 AutoCaller autoCaller (this);
3554 AssertReturn (autoCaller.state() == InInit, E_FAIL);
3555
3556 AssertReturn (aNode, E_INVALIDARG);
3557
3558 HRESULT rc = S_OK;
3559
3560 unsigned count = 0;
3561 CFGLDRCountChildren (aNode, "HardDisk", &count);
3562 for (unsigned i = 0; i < count && SUCCEEDED (rc); ++ i)
3563 {
3564 CFGNODE hdNode = 0;
3565
3566 CFGLDRGetChildNode (aNode, "HardDisk", i, &hdNode);
3567 ComAssertBreak (hdNode, rc = E_FAIL);
3568
3569 {
3570 CFGNODE storageNode = 0;
3571
3572 // detect the type of the hard disk
3573 // (either one of HVirtualDiskImage, HISCSIHardDisk or HPhysicalVolume
3574 do
3575 {
3576 CFGLDRGetChildNode (hdNode, "VirtualDiskImage", 0, &storageNode);
3577 if (storageNode)
3578 {
3579 ComObjPtr <HVirtualDiskImage> vdi;
3580 vdi.createObject();
3581 rc = vdi->init (this, NULL, hdNode, storageNode);
3582 break;
3583 }
3584
3585 CFGLDRGetChildNode (hdNode, "ISCSIHardDisk", 0, &storageNode);
3586 if (storageNode)
3587 {
3588 ComObjPtr <HISCSIHardDisk> iscsi;
3589 iscsi.createObject();
3590 rc = iscsi->init (this, hdNode, storageNode);
3591 break;
3592 }
3593
3594 CFGLDRGetChildNode (hdNode, "VMDKImage", 0, &storageNode);
3595 if (storageNode)
3596 {
3597 ComObjPtr <HVMDKImage> vmdk;
3598 vmdk.createObject();
3599 rc = vmdk->init (this, NULL, hdNode, storageNode);
3600 break;
3601 }
3602
3603 /// @todo (dmik) later
3604// CFGLDRGetChildNode (hdNode, "PhysicalVolume", 0, &storageNode);
3605// if (storageNode)
3606// {
3607// break;
3608// }
3609
3610 ComAssertMsgFailedBreak (("No valid hard disk storage node!\n"),
3611 rc = E_FAIL);
3612 }
3613 while (0);
3614
3615 if (storageNode)
3616 CFGLDRReleaseNode (storageNode);
3617 }
3618
3619 CFGLDRReleaseNode (hdNode);
3620 }
3621
3622 return rc;
3623}
3624
3625/**
3626 * Helper function to write out the configuration to XML.
3627 *
3628 * @note Locks objects!
3629 */
3630HRESULT VirtualBox::saveConfig()
3631{
3632 AutoCaller autoCaller (this);
3633 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
3634
3635 ComAssertRet (!!mData.mCfgFile.mName, E_FAIL);
3636
3637 HRESULT rc = S_OK;
3638
3639 AutoLock alock (this);
3640
3641 CFGHANDLE configLoader;
3642
3643 /* load the config file */
3644 int vrc = CFGLDRLoad (&configLoader, Utf8Str (mData.mCfgFile.mName),
3645 mData.mCfgFile.mHandle,
3646 XmlSchemaNS, true, cfgLdrEntityResolver, NULL);
3647 ComAssertRCRet (vrc, E_FAIL);
3648
3649 const char * Global = "VirtualBox/Global";
3650 CFGNODE global;
3651
3652 vrc = CFGLDRGetNode(configLoader, Global, 0, &global);
3653 if (VBOX_FAILURE (vrc))
3654 CFGLDRCreateNode (configLoader, Global, &global);
3655
3656 do
3657 {
3658 ComAssertBreak (global, rc = E_FAIL);
3659
3660 /* machines */
3661 do
3662 {
3663 const char *Registry = "MachineRegistry";
3664 const char *Entry = "MachineEntry";
3665 CFGNODE registryNode = NULL;
3666
3667 /* first, delete the entire machine registry */
3668 if (VBOX_SUCCESS (CFGLDRGetChildNode (global, Registry, 0, &registryNode)))
3669 CFGLDRDeleteNode (registryNode);
3670
3671 /* then, recreate it */
3672 CFGLDRCreateChildNode (global, Registry, &registryNode);
3673
3674 /* write out the machines */
3675 for (MachineList::iterator it = mData.mMachines.begin();
3676 it != mData.mMachines.end();
3677 ++ it)
3678 {
3679 /// @todo (dmik) move this part to Machine for better incapsulation
3680
3681 ComObjPtr <Machine> m = *it;
3682 AutoReaderLock machineLock (m);
3683
3684 AssertMsg (m->data(), ("Machine data must not be NULL"));
3685 CFGNODE entryNode;
3686 CFGLDRAppendChildNode (registryNode, Entry, &entryNode);
3687 /* UUID + curly brackets */
3688 CFGLDRSetUUID (entryNode, "uuid", unconst (m->data()->mUuid).ptr());
3689 /* source */
3690 CFGLDRSetBSTR (entryNode, "src", m->data()->mConfigFile);
3691 /* done */
3692 CFGLDRReleaseNode (entryNode);
3693 }
3694
3695 CFGLDRReleaseNode (registryNode);
3696 }
3697 while (0);
3698 if (FAILED (rc))
3699 break;
3700
3701 /* disk images */
3702 do
3703 {
3704 CFGNODE registryNode = 0;
3705 CFGLDRGetChildNode (global, "DiskRegistry", 0, &registryNode);
3706 /* first, delete the entire disk image registr */
3707 if (registryNode)
3708 CFGLDRDeleteNode (registryNode);
3709 /* then, recreate it */
3710 CFGLDRCreateChildNode (global, "DiskRegistry", &registryNode);
3711 ComAssertBreak (registryNode, rc = E_FAIL);
3712
3713 /* write out the hard disks */
3714 {
3715 CFGNODE imagesNode = 0;
3716 CFGLDRCreateChildNode (registryNode, "HardDisks", &imagesNode);
3717 rc = saveHardDisks (imagesNode);
3718 CFGLDRReleaseNode (imagesNode);
3719 if (FAILED (rc))
3720 break;
3721 }
3722
3723 /* write out the CD/DVD images */
3724 {
3725 CFGNODE imagesNode = 0;
3726 CFGLDRCreateChildNode (registryNode, "DVDImages", &imagesNode);
3727
3728 for (DVDImageList::iterator it = mData.mDVDImages.begin();
3729 it != mData.mDVDImages.end();
3730 ++ it)
3731 {
3732 ComObjPtr <DVDImage> dvd = *it;
3733 /* no need to lock: fields are constant */
3734 CFGNODE imageNode = 0;
3735 CFGLDRAppendChildNode (imagesNode, "Image", &imageNode);
3736 CFGLDRSetUUID (imageNode, "uuid", dvd->id());
3737 CFGLDRSetBSTR (imageNode, "src", dvd->filePath());
3738 CFGLDRReleaseNode (imageNode);
3739 }
3740
3741 CFGLDRReleaseNode (imagesNode);
3742 }
3743
3744 /* write out the floppy images */
3745 {
3746 CFGNODE imagesNode = 0;
3747 CFGLDRCreateChildNode (registryNode, "FloppyImages", &imagesNode);
3748
3749 for (FloppyImageList::iterator it = mData.mFloppyImages.begin();
3750 it != mData.mFloppyImages.end();
3751 ++ it)
3752 {
3753 ComObjPtr <FloppyImage> fd = *it;
3754 /* no need to lock: fields are constant */
3755 CFGNODE imageNode = 0;
3756 CFGLDRAppendChildNode (imagesNode, "Image", &imageNode);
3757 CFGLDRSetUUID (imageNode, "uuid", fd->id());
3758 CFGLDRSetBSTR (imageNode, "src", fd->filePath());
3759 CFGLDRReleaseNode (imageNode);
3760 }
3761
3762 CFGLDRReleaseNode (imagesNode);
3763 }
3764
3765 CFGLDRReleaseNode (registryNode);
3766 }
3767 while (0);
3768 if (FAILED (rc))
3769 break;
3770
3771 do
3772 {
3773 /* host data (USB filters) */
3774 rc = mData.mHost->saveSettings (global);
3775 if (FAILED (rc))
3776 break;
3777
3778 rc = mData.mSystemProperties->saveSettings (global);
3779 if (FAILED (rc))
3780 break;
3781 }
3782 while (0);
3783 }
3784 while (0);
3785
3786 if (global)
3787 CFGLDRReleaseNode (global);
3788
3789 if (SUCCEEDED (rc))
3790 {
3791 char *loaderError = NULL;
3792 vrc = CFGLDRSave (configLoader, &loaderError);
3793 if (VBOX_FAILURE (vrc))
3794 {
3795 rc = setError (E_FAIL,
3796 tr ("Could not save the settings file '%ls' (%Vrc)%s%s"),
3797 mData.mCfgFile.mName.raw(), vrc,
3798 loaderError ? ".\n" : "", loaderError ? loaderError : "");
3799 if (loaderError)
3800 RTMemTmpFree (loaderError);
3801 }
3802 }
3803
3804 CFGLDRFree(configLoader);
3805
3806 return rc;
3807}
3808
3809/**
3810 * Saves all hard disks to the given <HardDisks> node.
3811 *
3812 * @param aNode <HardDisks> node
3813 *
3814 * @note Locks this object for reding.
3815 */
3816HRESULT VirtualBox::saveHardDisks (CFGNODE aNode)
3817{
3818 AssertReturn (aNode, E_INVALIDARG);
3819
3820 HRESULT rc = S_OK;
3821
3822 AutoReaderLock alock (this);
3823
3824 for (HardDiskList::const_iterator it = mData.mHardDisks.begin();
3825 it != mData.mHardDisks.end() && SUCCEEDED (rc);
3826 ++ it)
3827 {
3828 ComObjPtr <HardDisk> hd = *it;
3829 AutoReaderLock hdLock (hd);
3830
3831 CFGNODE hdNode = 0;
3832 CFGLDRAppendChildNode (aNode, "HardDisk", &hdNode);
3833 ComAssertBreak (hdNode, rc = E_FAIL);
3834
3835 CFGNODE storageNode = 0;
3836
3837 switch (hd->storageType())
3838 {
3839 case HardDiskStorageType_VirtualDiskImage:
3840 {
3841 CFGLDRAppendChildNode (hdNode, "VirtualDiskImage", &storageNode);
3842 ComAssertBreak (storageNode, rc = E_FAIL);
3843 rc = hd->saveSettings (hdNode, storageNode);
3844 break;
3845 }
3846
3847 case HardDiskStorageType_ISCSIHardDisk:
3848 {
3849 CFGLDRAppendChildNode (hdNode, "ISCSIHardDisk", &storageNode);
3850 ComAssertBreak (storageNode, rc = E_FAIL);
3851 rc = hd->saveSettings (hdNode, storageNode);
3852 break;
3853 }
3854
3855 case HardDiskStorageType_VMDKImage:
3856 {
3857 CFGLDRAppendChildNode (hdNode, "VMDKImage", &storageNode);
3858 ComAssertBreak (storageNode, rc = E_FAIL);
3859 rc = hd->saveSettings (hdNode, storageNode);
3860 break;
3861 }
3862
3863 /// @todo (dmik) later
3864// case HardDiskStorageType_PhysicalVolume:
3865// {
3866// break;
3867// }
3868 }
3869
3870 if (storageNode)
3871 CFGLDRReleaseNode (storageNode);
3872
3873 CFGLDRReleaseNode (hdNode);
3874 }
3875
3876 return rc;
3877}
3878
3879/**
3880 * Helper to register the machine.
3881 *
3882 * When called during VirtualBox startup, adds the given machine to the
3883 * collection of registered machines. Otherwise tries to mark the machine
3884 * as registered, and, if succeeded, adds it to the collection and
3885 * saves global settings.
3886 *
3887 * @param aMachine machine to register
3888 *
3889 * @note Locks objects!
3890 */
3891HRESULT VirtualBox::registerMachine (Machine *aMachine)
3892{
3893 ComAssertRet (aMachine, E_INVALIDARG);
3894
3895 AutoCaller autoCaller (this);
3896 CheckComRCReturnRC (autoCaller.rc());
3897
3898 AutoLock alock (this);
3899
3900 ComAssertRet (findMachine (aMachine->data()->mUuid,
3901 false /* aDoSetError */, NULL) == E_INVALIDARG,
3902 E_FAIL);
3903
3904 HRESULT rc = S_OK;
3905
3906 if (autoCaller.state() != InInit)
3907 {
3908 /* Machine::trySetRegistered() will commit and save machine settings */
3909 rc = aMachine->trySetRegistered (TRUE);
3910 CheckComRCReturnRC (rc);
3911 }
3912
3913 /* add to the collection of registered machines */
3914 mData.mMachines.push_back (aMachine);
3915
3916 if (autoCaller.state() != InInit)
3917 rc = saveConfig();
3918
3919 return rc;
3920}
3921
3922/**
3923 * Helper to register the hard disk.
3924 *
3925 * @param aHardDisk object to register
3926 * @param aFlags one of RHD_* values
3927 *
3928 * @note Locks objects!
3929 */
3930HRESULT VirtualBox::registerHardDisk (HardDisk *aHardDisk, RHD_Flags aFlags)
3931{
3932 ComAssertRet (aHardDisk, E_INVALIDARG);
3933
3934 AutoCaller autoCaller (this);
3935 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
3936
3937 AutoLock alock (this);
3938
3939 HRESULT rc = checkMediaForConflicts (aHardDisk, NULL, NULL);
3940 CheckComRCReturnRC (rc);
3941
3942 /* mark the hard disk as registered only when registration is external */
3943 if (aFlags == RHD_External)
3944 {
3945 rc = aHardDisk->trySetRegistered (TRUE);
3946 CheckComRCReturnRC (rc);
3947 }
3948
3949 if (!aHardDisk->parent())
3950 {
3951 /* add to the collection of top-level images */
3952 mData.mHardDisks.push_back (aHardDisk);
3953 }
3954
3955 /* insert to the map of hard disks */
3956 mData.mHardDiskMap
3957 .insert (HardDiskMap::value_type (aHardDisk->id(), aHardDisk));
3958
3959 /* save global config file if not on startup */
3960 /// @todo (dmik) optimize later to save only the <HardDisks> node
3961 if (aFlags != RHD_OnStartUp)
3962 rc = saveConfig();
3963
3964 return rc;
3965}
3966
3967/**
3968 * Helper to unregister the hard disk.
3969 *
3970 * If the hard disk is a differencing hard disk and if the unregistration
3971 * succeeds, the hard disk image is deleted and the object is uninitialized.
3972 *
3973 * @param aHardDisk hard disk to unregister
3974 *
3975 * @note Locks objects!
3976 */
3977HRESULT VirtualBox::unregisterHardDisk (HardDisk *aHardDisk)
3978{
3979 AssertReturn (aHardDisk, E_INVALIDARG);
3980
3981 AutoCaller autoCaller (this);
3982 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
3983
3984 LogFlowThisFunc (("image='%ls'\n", aHardDisk->toString().raw()));
3985
3986 AutoLock alock (this);
3987
3988 /* Lock the hard disk to ensure nobody registers it again before we delete
3989 * the differencing image (sanity check actually -- should never happen). */
3990 AutoLock hdLock (aHardDisk);
3991
3992 /* try to unregister */
3993 HRESULT rc = aHardDisk->trySetRegistered (FALSE);
3994 CheckComRCReturnRC (rc);
3995
3996 /* remove from the map of hard disks */
3997 mData.mHardDiskMap.erase (aHardDisk->id());
3998
3999 if (!aHardDisk->parent())
4000 {
4001 /* non-differencing hard disk:
4002 * remove from the collection of top-level hard disks */
4003 mData.mHardDisks.remove (aHardDisk);
4004 }
4005 else
4006 {
4007 Assert (aHardDisk->isDifferencing());
4008
4009 /* differencing hard disk: delete (only if the last access check
4010 * succeeded) and uninitialize */
4011 if (aHardDisk->asVDI()->lastAccessError().isNull())
4012 rc = aHardDisk->asVDI()->DeleteImage();
4013 aHardDisk->uninit();
4014 }
4015
4016 /* save the global config file anyway (already unregistered) */
4017 /// @todo (dmik) optimize later to save only the <HardDisks> node
4018 HRESULT rc2 = saveConfig();
4019 if (SUCCEEDED (rc))
4020 rc = rc2;
4021
4022 return rc;
4023}
4024
4025/**
4026 * Helper to unregister the differencing hard disk image.
4027 * Resets machine ID of the hard disk (to let the unregistration succeed)
4028 * and then calls #unregisterHardDisk().
4029 *
4030 * @param aHardDisk differencing hard disk image to unregister
4031 *
4032 * @note Locks objects!
4033 */
4034HRESULT VirtualBox::unregisterDiffHardDisk (HardDisk *aHardDisk)
4035{
4036 AssertReturn (aHardDisk, E_INVALIDARG);
4037
4038 AutoCaller autoCaller (this);
4039 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
4040
4041 AutoLock alock (this);
4042
4043 /*
4044 * Note: it's safe to lock aHardDisk here because the same object
4045 * will be locked by #unregisterHardDisk().
4046 */
4047 AutoLock hdLock (aHardDisk);
4048
4049 AssertReturn (aHardDisk->isDifferencing(), E_INVALIDARG);
4050
4051 /*
4052 * deassociate the machine from the hard disk
4053 * (otherwise trySetRegistered() will definitely fail)
4054 */
4055 aHardDisk->setMachineId (Guid());
4056
4057 return unregisterHardDisk (aHardDisk);
4058}
4059
4060
4061/**
4062 * Helper to update the global settings file when the name of some machine
4063 * changes so that file and directory renaming occurs. This method ensures
4064 * that all affected paths in the disk registry are properly updated.
4065 *
4066 * @param aOldPath old path (full)
4067 * @param aNewPath new path (full)
4068 *
4069 * @note Locks this object + DVD, Floppy and HardDisk children for writing.
4070 */
4071HRESULT VirtualBox::updateSettings (const char *aOldPath, const char *aNewPath)
4072{
4073 LogFlowThisFunc (("aOldPath={%s} aNewPath={%s}\n", aOldPath, aNewPath));
4074
4075 AssertReturn (aOldPath, E_INVALIDARG);
4076 AssertReturn (aNewPath, E_INVALIDARG);
4077
4078 AutoCaller autoCaller (this);
4079 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
4080
4081 AutoLock alock (this);
4082
4083 size_t oldPathLen = strlen (aOldPath);
4084
4085 /* check DVD paths */
4086 for (DVDImageList::iterator it = mData.mDVDImages.begin();
4087 it != mData.mDVDImages.end();
4088 ++ it)
4089 {
4090 ComObjPtr <DVDImage> image = *it;
4091
4092 /* no need to lock: fields are constant */
4093 Utf8Str path = image->filePathFull();
4094 LogFlowThisFunc (("DVD.fullPath={%s}\n", path.raw()));
4095
4096 if (RTPathStartsWith (path, aOldPath))
4097 {
4098 Utf8Str newPath = Utf8StrFmt ("%s%s", aNewPath,
4099 path.raw() + oldPathLen);
4100 path = newPath;
4101 calculateRelativePath (path, path);
4102 image->updatePath (newPath, path);
4103
4104 LogFlowThisFunc (("-> updated: full={%s} rel={%s}\n",
4105 newPath.raw(), path.raw()));
4106 }
4107 }
4108
4109 /* check Floppy paths */
4110 for (FloppyImageList::iterator it = mData.mFloppyImages.begin();
4111 it != mData.mFloppyImages.end();
4112 ++ it)
4113 {
4114 ComObjPtr <FloppyImage> image = *it;
4115
4116 /* no need to lock: fields are constant */
4117 Utf8Str path = image->filePathFull();
4118 LogFlowThisFunc (("Floppy.fullPath={%s}\n", path.raw()));
4119
4120 if (RTPathStartsWith (path, aOldPath))
4121 {
4122 Utf8Str newPath = Utf8StrFmt ("%s%s", aNewPath,
4123 path.raw() + oldPathLen);
4124 path = newPath;
4125 calculateRelativePath (path, path);
4126 image->updatePath (newPath, path);
4127
4128 LogFlowThisFunc (("-> updated: full={%s} rel={%s}\n",
4129 newPath.raw(), path.raw()));
4130 }
4131 }
4132
4133 /* check HardDisk paths */
4134 for (HardDiskList::const_iterator it = mData.mHardDisks.begin();
4135 it != mData.mHardDisks.end();
4136 ++ it)
4137 {
4138 (*it)->updatePaths (aOldPath, aNewPath);
4139 }
4140
4141 HRESULT rc = saveConfig();
4142
4143 return rc;
4144}
4145
4146/**
4147 * Helper to register the DVD image.
4148 *
4149 * @param aImage object to register
4150 * @param aOnStartUp whether this method called during VirtualBox init or not
4151 *
4152 * @return COM status code
4153 *
4154 * @note Locks objects!
4155 */
4156HRESULT VirtualBox::registerDVDImage (DVDImage *aImage, bool aOnStartUp)
4157{
4158 AssertReturn (aImage, E_INVALIDARG);
4159
4160 AutoCaller autoCaller (this);
4161 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
4162
4163 AutoLock alock (this);
4164
4165 HRESULT rc = checkMediaForConflicts (NULL, &aImage->id(),
4166 aImage->filePathFull());
4167 CheckComRCReturnRC (rc);
4168
4169 /* add to the collection */
4170 mData.mDVDImages.push_back (aImage);
4171
4172 /* save global config file if we're supposed to */
4173 if (!aOnStartUp)
4174 rc = saveConfig();
4175
4176 return rc;
4177}
4178
4179/**
4180 * Helper to register the floppy image.
4181 *
4182 * @param aImage object to register
4183 * @param aOnStartUp whether this method called during VirtualBox init or not
4184 *
4185 * @return COM status code
4186 *
4187 * @note Locks objects!
4188 */
4189HRESULT VirtualBox::registerFloppyImage (FloppyImage *aImage, bool aOnStartUp)
4190{
4191 AssertReturn (aImage, E_INVALIDARG);
4192
4193 AutoCaller autoCaller (this);
4194 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
4195
4196 AutoLock alock (this);
4197
4198 HRESULT rc = checkMediaForConflicts (NULL, &aImage->id(),
4199 aImage->filePathFull());
4200 CheckComRCReturnRC (rc);
4201
4202 /* add to the collection */
4203 mData.mFloppyImages.push_back (aImage);
4204
4205 /* save global config file if we're supposed to */
4206 if (!aOnStartUp)
4207 rc = saveConfig();
4208
4209 return rc;
4210}
4211
4212/**
4213 * Helper function to create the guest OS type objects and our collection
4214 *
4215 * @returns COM status code
4216 */
4217HRESULT VirtualBox::registerGuestOSTypes()
4218{
4219 AutoCaller autoCaller (this);
4220 AssertComRCReturn (autoCaller.rc(), E_FAIL);
4221 AssertReturn (autoCaller.state() == InInit, E_FAIL);
4222
4223 HRESULT rc = S_OK;
4224
4225 // this table represents our os type / string mapping
4226 static struct
4227 {
4228 const char *id; // utf-8
4229 const char *description; // utf-8
4230 const OSType osType;
4231 const uint32_t recommendedRAM;
4232 const uint32_t recommendedVRAM;
4233 const uint32_t recommendedHDD;
4234 } OSTypes[] =
4235 {
4236 /// @todo (dmik) get the list of OS types from the XML schema
4237 // NOTE: we assume that unknown is always the first entry!
4238 { "unknown", "Other/Unknown", OSTypeUnknown, 64, 4, 2000 },
4239 { "dos", "DOS", OSTypeDOS, 32, 4, 500 },
4240 { "win31", "Windows 3.1", OSTypeWin31, 32, 4, 1000 },
4241 { "win95", "Windows 95", OSTypeWin95, 64, 4, 2000 },
4242 { "win98", "Windows 98", OSTypeWin98, 64, 4, 2000 },
4243 { "winme", "Windows Me", OSTypeWinMe, 64, 4, 4000 },
4244 { "winnt4", "Windows NT 4", OSTypeWinNT4, 128, 4, 2000 },
4245 { "win2k", "Windows 2000", OSTypeWin2k, 168, 4, 4000 },
4246 { "winxp", "Windows XP", OSTypeWinXP, 192, 4, 10000 },
4247 { "win2k3", "Windows Server 2003", OSTypeWin2k3, 256, 4, 20000 },
4248 { "winvista", "Windows Vista", OSTypeWinVista, 512, 4, 20000 },
4249 { "os2warp3", "OS/2 Warp 3", OSTypeOS2Warp3, 48, 4, 1000 },
4250 { "os2warp4", "OS/2 Warp 4", OSTypeOS2Warp4, 64, 4, 2000 },
4251 { "os2warp45", "OS/2 Warp 4.5", OSTypeOS2Warp45, 96, 4, 2000 },
4252 { "linux22", "Linux 2.2", OSTypeLinux22, 64, 4, 2000 },
4253 { "linux24", "Linux 2.4", OSTypeLinux24, 128, 4, 4000 },
4254 { "linux26", "Linux 2.6", OSTypeLinux26, 128, 4, 8000 },
4255 { "freebsd", "FreeBSD", OSTypeFreeBSD, 64, 4, 2000 },
4256 { "openbsd", "OpenBSD", OSTypeOpenBSD, 64, 4, 2000 },
4257 { "netbsd", "NetBSD", OSTypeNetBSD, 64, 4, 2000 },
4258 { "netware", "Netware", OSTypeNetware, 128, 4, 4000 },
4259 { "solaris", "Solaris", OSTypeSolaris, 128, 4, 4000 },
4260 { "l4", "L4", OSTypeL4, 64, 4, 2000 }
4261 };
4262
4263 for (uint32_t i = 0; i < ELEMENTS (OSTypes) && SUCCEEDED (rc); i++)
4264 {
4265 ComObjPtr <GuestOSType> guestOSTypeObj;
4266 rc = guestOSTypeObj.createObject();
4267 if (SUCCEEDED (rc))
4268 {
4269 rc = guestOSTypeObj->init (OSTypes[i].id,
4270 OSTypes[i].description,
4271 OSTypes[i].osType,
4272 OSTypes[i].recommendedRAM,
4273 OSTypes[i].recommendedVRAM,
4274 OSTypes[i].recommendedHDD);
4275 if (SUCCEEDED (rc))
4276 mData.mGuestOSTypes.push_back (guestOSTypeObj);
4277 }
4278 }
4279
4280 return rc;
4281}
4282
4283/**
4284 * Helper to lock the VirtualBox configuration for write access.
4285 *
4286 * @note This method is not thread safe (must be called only from #init()
4287 * or #uninit()).
4288 *
4289 * @note If the configuration file is not found, the method returns
4290 * S_OK, but subsequent #isConfigLocked() will return FALSE. This is used
4291 * in some places to determine the (valid) situation when no config file
4292 * exists yet, and therefore a new one should be created from scatch.
4293 */
4294HRESULT VirtualBox::lockConfig()
4295{
4296 AutoCaller autoCaller (this);
4297 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
4298 AssertReturn (autoCaller.state() == InInit, E_FAIL);
4299
4300 HRESULT rc = S_OK;
4301
4302 Assert (!isConfigLocked());
4303 if (!isConfigLocked())
4304 {
4305 /* open the associated config file */
4306 int vrc = RTFileOpen (&mData.mCfgFile.mHandle,
4307 Utf8Str (mData.mCfgFile.mName),
4308 RTFILE_O_READWRITE | RTFILE_O_OPEN |
4309 RTFILE_O_DENY_WRITE | RTFILE_O_WRITE_THROUGH);
4310 if (VBOX_FAILURE (vrc))
4311 {
4312 mData.mCfgFile.mHandle = NIL_RTFILE;
4313
4314 /*
4315 * It is ok if the file is not found, it will be created by
4316 * init(). Otherwise return an error.
4317 */
4318 if (vrc != VERR_FILE_NOT_FOUND)
4319 rc = setError (E_FAIL,
4320 tr ("Could not lock the settings file '%ls' (%Vrc)"),
4321 mData.mCfgFile.mName.raw(), vrc);
4322 }
4323
4324 LogFlowThisFunc (("mCfgFile.mName='%ls', mCfgFile.mHandle=%d, rc=%08X\n",
4325 mData.mCfgFile.mName.raw(), mData.mCfgFile.mHandle, rc));
4326 }
4327
4328 return rc;
4329}
4330
4331/**
4332 * Helper to unlock the VirtualBox configuration from write access.
4333 *
4334 * @note This method is not thread safe (must be called only from #init()
4335 * or #uninit()).
4336 */
4337HRESULT VirtualBox::unlockConfig()
4338{
4339 AutoCaller autoCaller (this);
4340 AssertComRCReturn (autoCaller.rc(), E_FAIL);
4341 AssertReturn (autoCaller.state() == InUninit, E_FAIL);
4342
4343 HRESULT rc = S_OK;
4344
4345 if (isConfigLocked())
4346 {
4347 RTFileFlush (mData.mCfgFile.mHandle);
4348 RTFileClose (mData.mCfgFile.mHandle);
4349 /** @todo flush the directory too. */
4350 mData.mCfgFile.mHandle = NIL_RTFILE;
4351 LogFlowThisFunc (("\n"));
4352 }
4353
4354 return rc;
4355}
4356
4357/**
4358 * Thread function that watches the termination of all client processes
4359 * that have opened sessions using IVirtualBox::OpenSession()
4360 */
4361// static
4362DECLCALLBACK(int) VirtualBox::clientWatcher (RTTHREAD thread, void *pvUser)
4363{
4364 LogFlowFuncEnter();
4365
4366 VirtualBox *that = (VirtualBox *) pvUser;
4367 Assert (that);
4368
4369 SessionMachineVector machines;
4370 int cnt = 0;
4371
4372#if defined(__WIN__)
4373
4374 HRESULT hrc = CoInitializeEx (NULL,
4375 COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE |
4376 COINIT_SPEED_OVER_MEMORY);
4377 AssertComRC (hrc);
4378
4379 /// @todo (dmik) processes reaping!
4380
4381 HANDLE *handles = new HANDLE [1];
4382 handles [0] = that->mWatcherData.mUpdateReq;
4383
4384 do
4385 {
4386 AutoCaller autoCaller (that);
4387 /* VirtualBox has been early uninitialized, terminate */
4388 if (!autoCaller.isOk())
4389 break;
4390
4391 do
4392 {
4393 /* release the caller to let uninit() ever proceed */
4394 autoCaller.release();
4395
4396 DWORD rc = ::WaitForMultipleObjects (cnt + 1, handles, FALSE, INFINITE);
4397
4398 /*
4399 * Restore the caller before using VirtualBox. If it fails, this
4400 * means VirtualBox is being uninitialized and we must terminate.
4401 */
4402 autoCaller.add();
4403 if (!autoCaller.isOk())
4404 break;
4405
4406 bool update = false;
4407 if (rc == WAIT_OBJECT_0)
4408 {
4409 /* update event is signaled */
4410 update = true;
4411 }
4412 else if (rc > WAIT_OBJECT_0 && rc <= (WAIT_OBJECT_0 + cnt))
4413 {
4414 /* machine mutex is released */
4415 (machines [rc - WAIT_OBJECT_0 - 1])->checkForDeath();
4416 update = true;
4417 }
4418 else if (rc > WAIT_ABANDONED_0 && rc <= (WAIT_ABANDONED_0 + cnt))
4419 {
4420 /* machine mutex is abandoned due to client process termination */
4421 (machines [rc - WAIT_ABANDONED_0 - 1])->checkForDeath();
4422 update = true;
4423 }
4424 if (update)
4425 {
4426 /* obtain a new set of opened machines */
4427 that->getOpenedMachines (machines);
4428 cnt = machines.size();
4429 LogFlowFunc (("UPDATE: direct session count = %d\n", cnt));
4430 AssertMsg ((cnt + 1) <= MAXIMUM_WAIT_OBJECTS,
4431 ("MAXIMUM_WAIT_OBJECTS reached"));
4432 /* renew the set of event handles */
4433 delete [] handles;
4434 handles = new HANDLE [cnt + 1];
4435 handles [0] = that->mWatcherData.mUpdateReq;
4436 for (int i = 0; i < cnt; i++)
4437 handles [i + 1] = (machines [i])->ipcSem();
4438 }
4439 }
4440 while (true);
4441 }
4442 while (0);
4443
4444 /* delete the set of event handles */
4445 delete [] handles;
4446
4447 /* delete the set of opened machines if any */
4448 machines.clear();
4449
4450 ::CoUninitialize();
4451
4452#else
4453
4454 bool need_update = false;
4455
4456 do
4457 {
4458 AutoCaller autoCaller (that);
4459 if (!autoCaller.isOk())
4460 break;
4461
4462 do
4463 {
4464 /* release the caller to let uninit() ever proceed */
4465 autoCaller.release();
4466
4467 int rc = RTSemEventWait (that->mWatcherData.mUpdateReq, 500);
4468
4469 /*
4470 * Restore the caller before using VirtualBox. If it fails, this
4471 * means VirtualBox is being uninitialized and we must terminate.
4472 */
4473 autoCaller.add();
4474 if (!autoCaller.isOk())
4475 break;
4476
4477 if (VBOX_SUCCESS (rc) || need_update)
4478 {
4479 /* VBOX_SUCCESS (rc) means an update event is signaled */
4480
4481 /* obtain a new set of opened machines */
4482 that->getOpenedMachines (machines);
4483 cnt = machines.size();
4484 LogFlowFunc (("UPDATE: direct session count = %d\n", cnt));
4485 }
4486
4487 need_update = false;
4488 for (int i = 0; i < cnt; i++)
4489 need_update |= (machines [i])->checkForDeath();
4490
4491 /* reap child processes */
4492 {
4493 AutoLock alock (that);
4494 if (that->mWatcherData.mProcesses.size())
4495 {
4496 LogFlowFunc (("UPDATE: child process count = %d\n",
4497 that->mWatcherData.mProcesses.size()));
4498 ClientWatcherData::ProcessList::iterator it =
4499 that->mWatcherData.mProcesses.begin();
4500 while (it != that->mWatcherData.mProcesses.end())
4501 {
4502 RTPROCESS pid = *it;
4503 RTPROCSTATUS status;
4504 int vrc = ::RTProcWait (pid, RTPROCWAIT_FLAGS_NOBLOCK,
4505 &status);
4506 if (vrc == VINF_SUCCESS)
4507 {
4508 LogFlowFunc (("pid %d (%x) was reaped, "
4509 "status=%d, reason=%d\n",
4510 pid, pid, status.iStatus,
4511 status.enmReason));
4512 it = that->mWatcherData.mProcesses.erase (it);
4513 }
4514 else
4515 {
4516 LogFlowFunc (("pid %d (%x) was NOT reaped, vrc=%Vrc\n",
4517 pid, pid, vrc));
4518 if (vrc != VERR_PROCESS_RUNNING)
4519 {
4520 /* remove the process if it is not already running */
4521 it = that->mWatcherData.mProcesses.erase (it);
4522 }
4523 else
4524 ++ it;
4525 }
4526 }
4527 }
4528 }
4529 }
4530 while (true);
4531 }
4532 while (0);
4533
4534 /* delete the set of opened machines if any */
4535 machines.clear();
4536
4537#endif
4538
4539 LogFlowFuncLeave();
4540 return 0;
4541}
4542
4543/**
4544 * Thread function that handles custom events posted using #postEvent().
4545 */
4546// static
4547DECLCALLBACK(int) VirtualBox::asyncEventHandler (RTTHREAD thread, void *pvUser)
4548{
4549 LogFlowFuncEnter();
4550
4551 AssertReturn (pvUser, VERR_INVALID_POINTER);
4552
4553 // create an event queue for the current thread
4554 EventQueue *eventQ = new EventQueue();
4555 AssertReturn (eventQ, VERR_NO_MEMORY);
4556
4557 // return the queue to the one who created this thread
4558 *(static_cast <EventQueue **> (pvUser)) = eventQ;
4559 // signal that we're ready
4560 RTThreadUserSignal (thread);
4561
4562 BOOL ok = TRUE;
4563 Event *event = NULL;
4564
4565 while ((ok = eventQ->waitForEvent (&event)) && event)
4566 eventQ->handleEvent (event);
4567
4568 AssertReturn (ok, VERR_GENERAL_FAILURE);
4569
4570 delete eventQ;
4571
4572 LogFlowFuncLeave();
4573
4574 return 0;
4575}
4576
4577////////////////////////////////////////////////////////////////////////////////
4578
4579/**
4580 * Takes the current list of registered callbacks of the managed VirtualBox
4581 * instance, and calls #handleCallback() for every callback item from the
4582 * list, passing the item as an argument.
4583 *
4584 * @note Locks the managed VirtualBox object for reading but leaves the lock
4585 * before iterating over callbacks and calling their methods.
4586 */
4587void *VirtualBox::CallbackEvent::handler()
4588{
4589 if (mVirtualBox.isNull())
4590 return NULL;
4591
4592 AutoCaller autoCaller (mVirtualBox);
4593 if (!autoCaller.isOk())
4594 {
4595 LogWarningFunc (("VirtualBox has been uninitialized (state=%d), "
4596 "the callback event is discarded!\n",
4597 autoCaller.state()));
4598 /* We don't need mVirtualBox any more, so release it */
4599 mVirtualBox.setNull();
4600 return NULL;
4601 }
4602
4603 CallbackVector callbacks;
4604 {
4605 /* Make a copy to release the lock before iterating */
4606 AutoReaderLock alock (mVirtualBox);
4607 callbacks = CallbackVector (mVirtualBox->mData.mCallbacks.begin(),
4608 mVirtualBox->mData.mCallbacks.end());
4609 /* We don't need mVirtualBox any more, so release it */
4610 mVirtualBox.setNull();
4611 }
4612
4613 for (VirtualBox::CallbackVector::const_iterator it = callbacks.begin();
4614 it != callbacks.end(); ++ it)
4615 handleCallback (*it);
4616
4617 return NULL;
4618}
4619
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