VirtualBox

source: vbox/trunk/src/VBox/Main/ApplianceImpl.cpp@ 16702

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

OVF: updated testcase

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 102.0 KB
Line 
1/* $Id: ApplianceImpl.cpp 16702 2009-02-12 10:20:52Z vboxsync $ */
2/** @file
3 *
4 * IAppliance and IVirtualSystem COM class implementations
5 */
6
7/*
8 * Copyright (C) 2008-2009 Sun Microsystems, Inc.
9 *
10 * This file is part of VirtualBox Open Source Edition (OSE), as
11 * available from http://www.virtualbox.org. This file is free software;
12 * you can redistribute it and/or modify it under the terms of the GNU
13 * General Public License (GPL) as published by the Free Software
14 * Foundation, in version 2 as it comes in the "COPYING" file of the
15 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
16 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
17 *
18 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
19 * Clara, CA 95054 USA or visit http://www.sun.com if you need
20 * additional information or have any questions.
21 */
22
23#include <iprt/stream.h>
24#include <iprt/path.h>
25#include <iprt/dir.h>
26#include <iprt/file.h>
27
28#include "ApplianceImpl.h"
29#include "VirtualBoxImpl.h"
30#include "GuestOSTypeImpl.h"
31#include "ProgressImpl.h"
32
33#include "Logging.h"
34
35#include "VBox/xml.h"
36
37#include <iostream>
38#include <sstream>
39
40using namespace std;
41
42// defines
43////////////////////////////////////////////////////////////////////////////////
44
45struct DiskImage
46{
47 Utf8Str strDiskId; // value from DiskSection/Disk/@diskId
48 int64_t iCapacity; // value from DiskSection/Disk/@capacity;
49 // (maximum size for dynamic images, I guess; we always translate this to bytes)
50 int64_t iPopulatedSize; // value from DiskSection/Disk/@populatedSize
51 // (actual used size of disk, always in bytes; can be an estimate of used disk
52 // space, but cannot be larger than iCapacity)
53 Utf8Str strFormat; // value from DiskSection/Disk/@format
54 // typically http://www.vmware.com/specifications/vmdk.html#sparse
55
56 // fields from /References/File; the spec says the file reference from disk can be empty,
57 // so in that case, strFilename will be empty, then a new disk should be created
58 Utf8Str strHref; // value from /References/File/@href (filename); if empty, then the remaining fields are ignored
59 int64_t iSize; // value from /References/File/@size (optional according to spec; then we set -1 here)
60 int64_t iChunkSize; // value from /References/File/@chunkSize (optional, unsupported)
61 Utf8Str strCompression; // value from /References/File/@compression (optional, can be "gzip" according to spec)
62};
63
64struct Network
65{
66 Utf8Str strNetworkName; // value from NetworkSection/Network/@name
67 // unfortunately the OVF spec is unspecific about how networks should be specified further
68};
69
70struct VirtualHardwareItem
71{
72 Utf8Str strDescription;
73 Utf8Str strCaption;
74 Utf8Str strElementName;
75
76 uint32_t ulInstanceID;
77 uint32_t ulParent;
78
79 OVFResourceType_T resourceType;
80 Utf8Str strOtherResourceType;
81 Utf8Str strResourceSubType;
82
83 Utf8Str strHostResource; // "Abstractly specifies how a device shall connect to a resource on the deployment platform.
84 // Not all devices need a backing." Used with disk items, for which this references a virtual
85 // disk from the Disks section.
86 bool fAutomaticAllocation;
87 bool fAutomaticDeallocation;
88 Utf8Str strConnection; // "All Ethernet adapters that specify the same abstract network connection name within an OVF
89 // package shall be deployed on the same network. The abstract network connection name shall be
90 // listed in the NetworkSection at the outermost envelope level."
91 Utf8Str strAddress; // "Device-specific. For an Ethernet adapter, this specifies the MAC address."
92 Utf8Str strAddressOnParent; // "For a device, this specifies its location on the controller."
93 Utf8Str strAllocationUnits; // "Specifies the units of allocation used. For example, “byte * 2^20”."
94 uint64_t ullVirtualQuantity; // "Specifies the quantity of resources presented. For example, “256”."
95 uint64_t ullReservation; // "Specifies the minimum quantity of resources guaranteed to be available."
96 uint64_t ullLimit; // "Specifies the maximum quantity of resources that will be granted."
97 uint64_t ullWeight; // "Specifies a relative priority for this allocation in relation to other allocations."
98
99 Utf8Str strConsumerVisibility;
100 Utf8Str strMappingBehavior;
101 Utf8Str strPoolID;
102 uint32_t ulBusNumber; // seen with IDE controllers, but not listed in OVF spec
103
104 uint32_t ulLineNumber; // line number of <Item> element in XML source; cached for error messages
105
106 VirtualHardwareItem()
107 : ulInstanceID(0), fAutomaticAllocation(false), fAutomaticDeallocation(false), ullVirtualQuantity(0), ullReservation(0), ullLimit(0), ullWeight(0), ulBusNumber(0), ulLineNumber(0)
108 {};
109};
110
111typedef map<Utf8Str, DiskImage> DiskImagesMap;
112typedef map<Utf8Str, Network> NetworksMap;
113
114struct VirtualSystem;
115
116// opaque private instance data of Appliance class
117struct Appliance::Data
118{
119 Bstr bstrPath;
120
121 DiskImagesMap mapDisks; // map of DiskImage structs, sorted by DiskImage.strDiskId
122
123 NetworksMap mapNetworks; // map of Network structs, sorted by Network.strNetworkName
124
125 list<VirtualSystem> llVirtualSystems;
126
127 list< ComObjPtr<VirtualSystemDescription> > virtualSystemDescriptions;
128};
129
130typedef map<uint32_t, VirtualHardwareItem> HardwareItemsMap;
131
132struct HardDiskController
133{
134 uint32_t idController; // instance ID (Item/InstanceId); this gets referenced from HardDisk
135 enum ControllerSystemType { IDE, SATA, SCSI };
136 ControllerSystemType system; // one of IDE, SATA, SCSI
137 Utf8Str strControllerType; // controller subtype (Item/ResourceSubType); e.g. "LsiLogic"; can be empty (esp. for IDE)
138 Utf8Str strAddress; // for IDE
139 uint32_t ulBusNumber; // for IDE
140
141 HardDiskController()
142 : idController(0),
143 ulBusNumber(0)
144 {
145 }
146};
147
148typedef map<uint32_t, HardDiskController> ControllersMap;
149
150struct VirtualDisk
151{
152 uint32_t idController; // SCSI (or IDE) controller this disk is connected to;
153 // points into VirtualSystem.mapControllers
154 Utf8Str strDiskId; // if the hard disk has an ovf:/disk/<id> reference,
155 // this receives the <id> component; points to one of the
156 // references in Appliance::Data.mapDisks
157};
158
159typedef map<Utf8Str, VirtualDisk> VirtualDisksMap;
160
161struct VirtualSystem
162{
163 Utf8Str strName; // copy of VirtualSystem/@id
164
165 CIMOSType_T cimos;
166 Utf8Str strVirtualSystemType; // generic hardware description; OVF says this can be something like "vmx-4" or "xen";
167 // VMware Workstation 6.5 is "vmx-07"
168
169 HardwareItemsMap mapHardwareItems; // map of virtual hardware items, sorted by unique instance ID
170
171 uint64_t ullMemorySize; // always in bytes, copied from llHardwareItems; default = 0 (unspecified)
172 uint16_t cCPUs; // no. of CPUs, copied from llHardwareItems; default = 1
173
174 list<Utf8Str> llNetworkNames;
175 // list of strings referring to network names
176 // (one for each VirtualSystem/Item[@ResourceType=10]/Connection element)
177
178 ControllersMap mapControllers;
179 // list of hard disk controllers
180 // (one for each VirtualSystem/Item[@ResourceType=6] element with accumulated data from children)
181
182 VirtualDisksMap mapVirtualDisks;
183 // (one for each VirtualSystem/Item[@ResourceType=17] element with accumulated data from children)
184
185 bool fHasFloppyDrive; // true if there's a floppy item in mapHardwareItems
186 bool fHasCdromDrive; // true if there's a CD-ROM item in mapHardwareItems; ISO images are not yet supported by OVFtool
187 bool fHasUsbController; // true if there's a USB controller item in mapHardwareItems
188
189 Utf8Str strSoundCardType; // if not empty, then the system wants a soundcard; this then specifies the hardware;
190 // VMware Workstation 6.5 uses "ensoniq1371" for example
191
192 Utf8Str strLicenceInfo; // license info if any; receives contents of VirtualSystem/EulaSection/Info
193 Utf8Str strLicenceText; // license info if any; receives contents of VirtualSystem/EulaSection/License
194
195 VirtualSystem()
196 : ullMemorySize(0), cCPUs(1), fHasFloppyDrive(false), fHasCdromDrive(false), fHasUsbController(false)
197 {
198 }
199};
200
201struct Appliance::Task
202{
203 Task(Appliance *aThat, Progress *aProgress)
204 : that(aThat)
205 , progress(aProgress)
206 , rc(S_OK)
207 {}
208 ~Task() {}
209
210 HRESULT startThread();
211
212 Appliance *that;
213 ComObjPtr<Progress> progress;
214 HRESULT rc;
215};
216
217// globals
218////////////////////////////////////////////////////////////////////////////////
219
220template <class T>
221inline
222com::Utf8Str toString(const T& val)
223{
224 // @todo optimize
225 std::ostringstream ss;
226 ss << val;
227 return Utf8Str(ss.str().c_str());
228}
229
230static Utf8Str stripFilename(const Utf8Str &strFile)
231{
232 Utf8Str str2(strFile);
233 RTPathStripFilename(str2.mutableRaw());
234 return str2;
235}
236
237// IVirtualBox public methods
238////////////////////////////////////////////////////////////////////////////////
239
240/**
241 * Implementation for IVirtualBox::createAppliance.
242 *
243 * @param anAppliance IAppliance object created if S_OK is returned.
244 * @return S_OK or error.
245 */
246STDMETHODIMP VirtualBox::CreateAppliance(IAppliance** anAppliance)
247{
248 HRESULT rc;
249
250 ComObjPtr<Appliance> appliance;
251 appliance.createObject();
252 rc = appliance->init(this);
253// ComAssertComRCThrowRC(rc);
254
255 if (SUCCEEDED(rc))
256 appliance.queryInterfaceTo(anAppliance);
257
258 return rc;
259}
260
261// Appliance::task methods
262////////////////////////////////////////////////////////////////////////////////
263
264HRESULT Appliance::Task::startThread()
265{
266 int vrc = RTThreadCreate(NULL, Appliance::taskThread, this,
267 0, RTTHREADTYPE_MAIN_HEAVY_WORKER, 0,
268 "Appliance::Task");
269 ComAssertMsgRCRet(vrc,
270 ("Could not create Appliance::Task thread (%Rrc)\n", vrc), E_FAIL);
271
272 return S_OK;
273}
274
275// IAppliance constructor / destructor
276////////////////////////////////////////////////////////////////////////////////
277
278DEFINE_EMPTY_CTOR_DTOR(Appliance)
279struct shutup {};
280
281// IAppliance private methods
282////////////////////////////////////////////////////////////////////////////////
283
284/**
285 * Private helper method that goes thru the elements of the given "current" element in the OVF XML
286 * and handles the contained child elements (which can be "Section" or "Content" elements).
287 *
288 * @param pcszPath Path spec of the XML file, for error messages.
289 * @param pReferencesElement "References" element from OVF, for looking up file specifications; can be NULL if no such element is present.
290 * @param pCurElem Element whose children are to be analyzed here.
291 * @return
292 */
293HRESULT Appliance::LoopThruSections(const char *pcszPath,
294 const xml::Node *pReferencesElem,
295 const xml::Node *pCurElem)
296{
297 HRESULT rc;
298
299 xml::NodesLoop loopChildren(*pCurElem);
300 const xml::Node *pElem;
301 while ((pElem = loopChildren.forAllNodes()))
302 {
303 const char *pcszElemName = pElem->getName();
304 const char *pcszTypeAttr = "";
305 const xml::Node *pTypeAttr;
306 if ((pTypeAttr = pElem->findAttribute("type")))
307 pcszTypeAttr = pTypeAttr->getValue();
308
309 if ( (!strcmp(pcszElemName, "DiskSection"))
310 || ( (!strcmp(pcszElemName, "Section"))
311 && (!strcmp(pcszTypeAttr, "ovf:DiskSection_Type"))
312 )
313 )
314 {
315 if (!(SUCCEEDED((rc = HandleDiskSection(pcszPath, pReferencesElem, pElem)))))
316 return rc;
317 }
318 else if ( (!strcmp(pcszElemName, "NetworkSection"))
319 || ( (!strcmp(pcszElemName, "Section"))
320 && (!strcmp(pcszTypeAttr, "ovf:NetworkSection_Type"))
321 )
322 )
323 {
324 if (!(SUCCEEDED((rc = HandleNetworkSection(pcszPath, pElem)))))
325 return rc;
326 }
327 else if ( (!strcmp(pcszElemName, "DeploymentOptionSection>")))
328 {
329 // TODO
330 }
331 else if ( (!strcmp(pcszElemName, "Info")))
332 {
333 // child of VirtualSystemCollection -- TODO
334 }
335 else if ( (!strcmp(pcszElemName, "ResourceAllocationSection")))
336 {
337 // child of VirtualSystemCollection -- TODO
338 }
339 else if ( (!strcmp(pcszElemName, "StartupSection")))
340 {
341 // child of VirtualSystemCollection -- TODO
342 }
343 else if ( (!strcmp(pcszElemName, "VirtualSystem"))
344 || ( (!strcmp(pcszElemName, "Content"))
345 && (!strcmp(pcszTypeAttr, "ovf:VirtualSystem_Type"))
346 )
347 )
348 {
349 if (!(SUCCEEDED((rc = HandleVirtualSystemContent(pcszPath, pElem)))))
350 return rc;
351 }
352 else if ( (!strcmp(pcszElemName, "VirtualSystemCollection"))
353 || ( (!strcmp(pcszElemName, "Content"))
354 && (!strcmp(pcszTypeAttr, "ovf:VirtualSystemCollection_Type"))
355 )
356 )
357 {
358 // TODO ResourceAllocationSection
359
360 // recurse for this, since it has VirtualSystem elements as children
361 if (!(SUCCEEDED((rc = LoopThruSections(pcszPath, pReferencesElem, pElem)))))
362 return rc;
363 }
364 }
365
366 return S_OK;
367}
368
369/**
370 * Private helper method that handles disk sections in the OVF XML.
371 * @param pcszPath Path spec of the XML file, for error messages.
372 * @param pReferencesElement "References" element from OVF, for looking up file specifications; can be NULL if no such element is present.
373 * @param pSectionElem Section element for which this helper is getting called.
374 * @return
375 */
376HRESULT Appliance::HandleDiskSection(const char *pcszPath,
377 const xml::Node *pReferencesElem,
378 const xml::Node *pSectionElem)
379{
380 // contains "Disk" child elements
381 xml::NodesLoop loopDisks(*pSectionElem, "Disk");
382 const xml::Node *pelmDisk;
383 while ((pelmDisk = loopDisks.forAllNodes()))
384 {
385 DiskImage d;
386 const char *pcszBad = NULL;
387 if (!(pelmDisk->getAttributeValue("diskId", d.strDiskId)))
388 pcszBad = "diskId";
389 else if (!(pelmDisk->getAttributeValue("format", d.strFormat)))
390 pcszBad = "format";
391 else if (!(pelmDisk->getAttributeValue("capacity", d.iCapacity)))
392 pcszBad = "capacity";
393 else
394 {
395 if (!(pelmDisk->getAttributeValue("populatedSize", d.iPopulatedSize)))
396 // optional
397 d.iPopulatedSize = -1;
398
399 Utf8Str strFileRef;
400 if (pelmDisk->getAttributeValue("fileRef", strFileRef)) // optional
401 {
402 // look up corresponding /References/File nodes (list built above)
403 const xml::Node *pFileElem;
404 if ( pReferencesElem
405 && ((pFileElem = pReferencesElem->findChildElementFromId(strFileRef.c_str())))
406 )
407 {
408 // copy remaining values from file node then
409 const char *pcszBadInFile = NULL;
410 if (!(pFileElem->getAttributeValue("href", d.strHref)))
411 pcszBadInFile = "href";
412 else if (!(pFileElem->getAttributeValue("size", d.iSize)))
413 d.iSize = -1; // optional
414 // if (!(pFileElem->getAttributeValue("size", d.iChunkSize))) TODO
415 d.iChunkSize = -1; // optional
416 pFileElem->getAttributeValue("compression", d.strCompression);
417
418 if (pcszBadInFile)
419 return setError(VBOX_E_FILE_ERROR,
420 tr("Error reading \"%s\": missing or invalid attribute '%s' in 'File' element, line %d"),
421 pcszPath,
422 pcszBadInFile,
423 pFileElem->getLineNumber());
424 }
425 else
426 return setError(VBOX_E_FILE_ERROR,
427 tr("Error reading \"%s\": cannot find References/File element for ID '%s' referenced by 'Disk' element, line %d"),
428 pcszPath,
429 strFileRef.c_str(),
430 pelmDisk->getLineNumber());
431 }
432 }
433
434 if (pcszBad)
435 return setError(VBOX_E_FILE_ERROR,
436 tr("Error reading \"%s\": missing or invalid attribute '%s' in 'DiskSection' element, line %d"),
437 pcszPath,
438 pcszBad,
439 pelmDisk->getLineNumber());
440
441 m->mapDisks[d.strDiskId] = d;
442 }
443
444 return S_OK;
445}
446
447/**
448 * Private helper method that handles network sections in the OVF XML.
449 * @param pcszPath Path spec of the XML file, for error messages.
450 * @param pSectionElem Section element for which this helper is getting called.
451 * @return
452 */
453HRESULT Appliance::HandleNetworkSection(const char *pcszPath,
454 const xml::Node *pSectionElem)
455{
456 // contains "Disk" child elements
457 xml::NodesLoop loopNetworks(*pSectionElem, "Network");
458 const xml::Node *pelmNetwork;
459 while ((pelmNetwork = loopNetworks.forAllNodes()))
460 {
461 Network n;
462 if (!(pelmNetwork->getAttributeValue("name", n.strNetworkName)))
463 return setError(VBOX_E_FILE_ERROR,
464 tr("Error reading \"%s\": missing 'name' attribute in 'Network', line %d"),
465 pcszPath,
466 pelmNetwork->getLineNumber());
467
468 m->mapNetworks[n.strNetworkName] = n;
469 }
470
471 return S_OK;
472}
473
474/**
475 * Private helper method that handles a "VirtualSystem" element in the OVF XML.
476 *
477 * @param pcszPath
478 * @param pContentElem
479 * @return
480 */
481HRESULT Appliance::HandleVirtualSystemContent(const char *pcszPath,
482 const xml::Node *pelmVirtualSystem)
483{
484 VirtualSystem vsys;
485
486 const xml::Node *pIdAttr = pelmVirtualSystem->findAttribute("id");
487 if (pIdAttr)
488 vsys.strName = pIdAttr->getValue();
489
490 xml::NodesLoop loop(*pelmVirtualSystem); // all child elements
491 const xml::Node *pelmThis;
492 while ((pelmThis = loop.forAllNodes()))
493 {
494 const char *pcszElemName = pelmThis->getName();
495 const xml::Node *pTypeAttr = pelmThis->findAttribute("type");
496 const char *pcszTypeAttr = (pTypeAttr) ? pTypeAttr->getValue() : "";
497
498 if (!strcmp(pcszElemName, "EulaSection"))
499 {
500 /* <EulaSection>
501 <Info ovf:msgid="6">License agreement for the Virtual System.</Info>
502 <License ovf:msgid="1">License terms can go in here.</License>
503 </EulaSection> */
504
505 const xml::Node *pelmInfo, *pelmLicense;
506 if ( ((pelmInfo = pelmThis->findChildElement("Info")))
507 && ((pelmLicense = pelmThis->findChildElement("License")))
508 )
509 {
510 vsys.strLicenceInfo = pelmInfo->getValue();
511 vsys.strLicenceText = pelmLicense->getValue();
512 }
513 }
514 else if ( (!strcmp(pcszElemName, "VirtualHardwareSection"))
515 || (!strcmp(pcszTypeAttr, "ovf:VirtualHardwareSection_Type"))
516 )
517 {
518 const xml::Node *pelmSystem, *pelmVirtualSystemType;
519 if ((pelmSystem = pelmThis->findChildElement("System")))
520 {
521 /* <System>
522 <vssd:Description>Description of the virtual hardware section.</vssd:Description>
523 <vssd:ElementName>vmware</vssd:ElementName>
524 <vssd:InstanceID>1</vssd:InstanceID>
525 <vssd:VirtualSystemIdentifier>MyLampService</vssd:VirtualSystemIdentifier>
526 <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
527 </System>*/
528 if ((pelmVirtualSystemType = pelmSystem->findChildElement("VirtualSystemType")))
529 vsys.strVirtualSystemType = pelmVirtualSystemType->getValue();
530 }
531
532 xml::NodesLoop loopVirtualHardwareItems(*pelmThis, "Item"); // all "Item" child elements
533 const xml::Node *pelmItem;
534 while ((pelmItem = loopVirtualHardwareItems.forAllNodes()))
535 {
536 VirtualHardwareItem i;
537
538 i.ulLineNumber = pelmItem->getLineNumber();
539
540 xml::NodesLoop loopItemChildren(*pelmItem); // all child elements
541 const xml::Node *pelmItemChild;
542 while ((pelmItemChild = loopItemChildren.forAllNodes()))
543 {
544 const char *pcszItemChildName = pelmItemChild->getName();
545 if (!strcmp(pcszItemChildName, "Description"))
546 i.strDescription = pelmItemChild->getValue();
547 else if (!strcmp(pcszItemChildName, "Caption"))
548 i.strCaption = pelmItemChild->getValue();
549 else if (!strcmp(pcszItemChildName, "ElementName"))
550 i.strElementName = pelmItemChild->getValue();
551 else if ( (!strcmp(pcszItemChildName, "InstanceID"))
552 || (!strcmp(pcszItemChildName, "InstanceId"))
553 )
554 pelmItemChild->copyValue(i.ulInstanceID);
555 else if (!strcmp(pcszItemChildName, "HostResource"))
556 i.strHostResource = pelmItemChild->getValue();
557 else if (!strcmp(pcszItemChildName, "ResourceType"))
558 {
559 int32_t iType; /** @todo how to fix correctly? (enum fun.) */
560 pelmItemChild->copyValue(iType);
561 i.resourceType = (OVFResourceType_T)iType;
562 }
563 else if (!strcmp(pcszItemChildName, "OtherResourceType"))
564 i.strOtherResourceType = pelmItemChild->getValue();
565 else if (!strcmp(pcszItemChildName, "ResourceSubType"))
566 i.strResourceSubType = pelmItemChild->getValue();
567 else if (!strcmp(pcszItemChildName, "AutomaticAllocation"))
568 i.fAutomaticAllocation = (!strcmp(pelmItemChild->getValue(), "true")) ? true : false;
569 else if (!strcmp(pcszItemChildName, "AutomaticDeallocation"))
570 i.fAutomaticDeallocation = (!strcmp(pelmItemChild->getValue(), "true")) ? true : false;
571 else if (!strcmp(pcszItemChildName, "Parent"))
572 pelmItemChild->copyValue(i.ulParent);
573 else if (!strcmp(pcszItemChildName, "Connection"))
574 i.strConnection = pelmItemChild->getValue();
575 else if (!strcmp(pcszItemChildName, "Address"))
576 i.strAddress = pelmItemChild->getValue();
577 else if (!strcmp(pcszItemChildName, "AddressOnParent"))
578 i.strAddressOnParent = pelmItemChild->getValue();
579 else if (!strcmp(pcszItemChildName, "AllocationUnits"))
580 i.strAllocationUnits = pelmItemChild->getValue();
581 else if (!strcmp(pcszItemChildName, "VirtualQuantity"))
582 pelmItemChild->copyValue(i.ullVirtualQuantity);
583 else if (!strcmp(pcszItemChildName, "Reservation"))
584 pelmItemChild->copyValue(i.ullReservation);
585 else if (!strcmp(pcszItemChildName, "Limit"))
586 pelmItemChild->copyValue(i.ullLimit);
587 else if (!strcmp(pcszItemChildName, "Weight"))
588 pelmItemChild->copyValue(i.ullWeight);
589 else if (!strcmp(pcszItemChildName, "ConsumerVisibility"))
590 i.strConsumerVisibility = pelmItemChild->getValue();
591 else if (!strcmp(pcszItemChildName, "MappingBehavior"))
592 i.strMappingBehavior = pelmItemChild->getValue();
593 else if (!strcmp(pcszItemChildName, "PoolID"))
594 i.strPoolID = pelmItemChild->getValue();
595 else if (!strcmp(pcszItemChildName, "BusNumber"))
596 pelmItemChild->copyValue(i.ulBusNumber);
597 else
598 return setError(VBOX_E_FILE_ERROR,
599 tr("Error reading \"%s\": unknown element \"%s\" under Item element, line %d"),
600 pcszPath,
601 pcszItemChildName,
602 i.ulLineNumber);
603 }
604
605 // store!
606 vsys.mapHardwareItems[i.ulInstanceID] = i;
607 }
608
609 HardwareItemsMap::const_iterator itH;
610
611 for (itH = vsys.mapHardwareItems.begin();
612 itH != vsys.mapHardwareItems.end();
613 ++itH)
614 {
615 const VirtualHardwareItem &i = itH->second;
616
617 // do some analysis
618 switch (i.resourceType)
619 {
620 case OVFResourceType_Processor: // 3
621 /* <rasd:Caption>1 virtual CPU</rasd:Caption>
622 <rasd:Description>Number of virtual CPUs</rasd:Description>
623 <rasd:ElementName>virtual CPU</rasd:ElementName>
624 <rasd:InstanceID>1</rasd:InstanceID>
625 <rasd:ResourceType>3</rasd:ResourceType>
626 <rasd:VirtualQuantity>1</rasd:VirtualQuantity>*/
627 if (i.ullVirtualQuantity < UINT16_MAX)
628 vsys.cCPUs = (uint16_t)i.ullVirtualQuantity;
629 else
630 return setError(VBOX_E_FILE_ERROR,
631 tr("Error reading \"%s\": CPU count %RI64 is larger than %d, line %d"),
632 pcszPath,
633 i.ullVirtualQuantity,
634 UINT16_MAX,
635 i.ulLineNumber);
636 break;
637
638 case OVFResourceType_Memory: // 4
639 if ( (i.strAllocationUnits == "MegaBytes") // found in OVF created by OVF toolkit
640 || (i.strAllocationUnits == "MB") // found in MS docs
641 || (i.strAllocationUnits == "byte * 2^20") // suggested by OVF spec DSP0243 page 21
642 )
643 vsys.ullMemorySize = i.ullVirtualQuantity * 1024 * 1024;
644 else
645 return setError(VBOX_E_FILE_ERROR,
646 tr("Error reading \"%s\": Invalid allocation unit \"%s\" specified with memory size item, line %d"),
647 pcszPath,
648 i.strAllocationUnits.c_str(),
649 i.ulLineNumber);
650 break;
651
652 case OVFResourceType_IdeController: // 5 IdeController
653 {
654 /* <Item>
655 <rasd:Caption>ideController0</rasd:Caption>
656 <rasd:Description>IDE Controller</rasd:Description>
657 <rasd:InstanceId>5</rasd:InstanceId>
658 <rasd:ResourceType>5</rasd:ResourceType>
659 <rasd:Address>0</rasd:Address>
660 <rasd:BusNumber>0</rasd:BusNumber>
661 </Item> */
662 HardDiskController hdc;
663 hdc.system = HardDiskController::IDE;
664 hdc.idController = i.ulInstanceID;
665 hdc.strAddress = i.strAddress;
666 hdc.ulBusNumber = i.ulBusNumber;
667
668 vsys.mapControllers[i.ulInstanceID] = hdc;
669 }
670 break;
671
672 case OVFResourceType_ParallelScsiHba: // 6 SCSI controller
673 {
674 /* <Item>
675 <rasd:Caption>SCSI Controller 0 - LSI Logic</rasd:Caption>
676 <rasd:Description>SCI Controller</rasd:Description>
677 <rasd:ElementName>SCSI controller</rasd:ElementName>
678 <rasd:InstanceID>4</rasd:InstanceID>
679 <rasd:ResourceSubType>LsiLogic</rasd:ResourceSubType>
680 <rasd:ResourceType>6</rasd:ResourceType>
681 </Item> */
682 HardDiskController hdc;
683 hdc.system = HardDiskController::SCSI;
684 hdc.idController = i.ulInstanceID;
685 hdc.strControllerType = i.strResourceSubType;
686
687 vsys.mapControllers[i.ulInstanceID] = hdc;
688 }
689 break;
690
691 case OVFResourceType_EthernetAdapter: // 10
692 {
693 /* <Item>
694 <rasd:AutomaticAllocation>true</rasd:AutomaticAllocation>
695 <rasd:Caption>Ethernet adapter on 'VM Network'</rasd:Caption>
696 <rasd:Connection>VM Network</rasd:Connection>
697 <rasd:Description>VM Network?</rasd:Description>
698 <rasd:ElementName>Ethernet adapter</rasd:ElementName>
699 <rasd:InstanceID>3</rasd:InstanceID>
700 <rasd:ResourceType>10</rasd:ResourceType>
701 </Item>
702
703 OVF spec DSP 0243 page 21:
704 "For an Ethernet adapter, this specifies the abstract network connection name
705 for the virtual machine. All Ethernet adapters that specify the same abstract
706 network connection name within an OVF package shall be deployed on the same
707 network. The abstract network connection name shall be listed in the NetworkSection
708 at the outermost envelope level." */
709
710 // make sure we have a matching NetworkSection/Network
711 NetworksMap::iterator it = m->mapNetworks.find(i.strConnection);
712 if (it == m->mapNetworks.end())
713 return setError(VBOX_E_FILE_ERROR,
714 tr("Error reading \"%s\": Invalid connection \"%s\"; cannot find matching NetworkSection/Network element, line %d"),
715 pcszPath,
716 i.strConnection.c_str(),
717 i.ulLineNumber);
718
719 vsys.llNetworkNames.push_back(i.strConnection);
720 }
721 break;
722
723 case OVFResourceType_FloppyDrive: // 14
724 vsys.fHasFloppyDrive = true; // we have no additional information
725 break;
726
727 case OVFResourceType_CdDrive: // 15
728 /* <Item ovf:required="false">
729 <rasd:Caption>cdrom1</rasd:Caption>
730 <rasd:InstanceId>7</rasd:InstanceId>
731 <rasd:ResourceType>15</rasd:ResourceType>
732 <rasd:AutomaticAllocation>true</rasd:AutomaticAllocation>
733 <rasd:Parent>5</rasd:Parent>
734 <rasd:AddressOnParent>0</rasd:AddressOnParent>
735 </Item> */
736 // I tried to see what happens if I set an ISO for the CD-ROM in VMware Workstation,
737 // but then the ovftool dies with "Device backing not supported". So I guess if
738 // VMware can't export ISOs, then we don't need to be able to import them right now.
739 vsys.fHasCdromDrive = true; // we have no additional information
740 break;
741
742 case OVFResourceType_HardDisk: // 17
743 {
744 /* <Item>
745 <rasd:Caption>Harddisk 1</rasd:Caption>
746 <rasd:Description>HD</rasd:Description>
747 <rasd:ElementName>Hard Disk</rasd:ElementName>
748 <rasd:HostResource>ovf://disk/lamp</rasd:HostResource>
749 <rasd:InstanceID>5</rasd:InstanceID>
750 <rasd:Parent>4</rasd:Parent>
751 <rasd:ResourceType>17</rasd:ResourceType>
752 </Item> */
753
754 // look up the hard disk controller element whose InstanceID equals our Parent;
755 // this is how the connection is specified in OVF
756 ControllersMap::const_iterator it = vsys.mapControllers.find(i.ulParent);
757 if (it == vsys.mapControllers.end())
758 return setError(VBOX_E_FILE_ERROR,
759 tr("Error reading \"%s\": Hard disk item with instance ID %d specifies invalid parent %d, line %d"),
760 pcszPath,
761 i.ulInstanceID,
762 i.ulParent,
763 i.ulLineNumber);
764 const HardDiskController &hdc = it->second;
765
766 VirtualDisk vd;
767 vd.idController = i.ulParent;
768 bool fFound = false;
769 // ovf://disk/lamp
770 // 12345678901234
771 if (i.strHostResource.substr(0, 11) == "ovf://disk/")
772 vd.strDiskId = i.strHostResource.substr(11);
773 else if (i.strHostResource.substr(0, 6) == "/disk/")
774 vd.strDiskId = i.strHostResource.substr(6);
775
776 if ( !(vd.strDiskId.length())
777 || (m->mapDisks.find(vd.strDiskId) == m->mapDisks.end())
778 )
779 return setError(VBOX_E_FILE_ERROR,
780 tr("Error reading \"%s\": Hard disk item with instance ID %d specifies invalid host resource \"%s\", line %d"),
781 pcszPath,
782 i.ulInstanceID,
783 i.strHostResource.c_str(),
784 i.ulLineNumber);
785
786 vsys.mapVirtualDisks[vd.strDiskId] = vd;
787 }
788 break;
789
790 case OVFResourceType_UsbController: // 23
791 /* <Item ovf:required="false">
792 <rasd:Caption>usb</rasd:Caption>
793 <rasd:Description>USB Controller</rasd:Description>
794 <rasd:InstanceId>3</rasd:InstanceId>
795 <rasd:ResourceType>23</rasd:ResourceType>
796 <rasd:Address>0</rasd:Address>
797 <rasd:BusNumber>0</rasd:BusNumber>
798 </Item> */
799 vsys.fHasUsbController = true; // we have no additional information
800 break;
801
802 case OVFResourceType_SoundCard: // 35
803 /* <Item ovf:required="false">
804 <rasd:Caption>sound</rasd:Caption>
805 <rasd:Description>Sound Card</rasd:Description>
806 <rasd:InstanceId>10</rasd:InstanceId>
807 <rasd:ResourceType>35</rasd:ResourceType>
808 <rasd:ResourceSubType>ensoniq1371</rasd:ResourceSubType>
809 <rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
810 <rasd:AddressOnParent>3</rasd:AddressOnParent>
811 </Item> */
812 vsys.strSoundCardType = i.strResourceSubType;
813 break;
814
815 default:
816 return setError(VBOX_E_FILE_ERROR,
817 tr("Error reading \"%s\": Unknown resource type %d in hardware item, line %d"),
818 pcszPath,
819 i.resourceType,
820 i.ulLineNumber);
821 }
822 }
823 }
824 else if ( (!strcmp(pcszElemName, "OperatingSystemSection"))
825 || (!strcmp(pcszTypeAttr, "ovf:OperatingSystemSection_Type"))
826 )
827 {
828 uint64_t cimos64;
829 if (!(pelmThis->getAttributeValue("id", cimos64)))
830 return setError(VBOX_E_FILE_ERROR,
831 tr("Error reading \"%s\": missing or invalid 'ovf:id' attribute in operating system section element, line %d"),
832 pcszPath,
833 pelmThis->getLineNumber());
834
835 vsys.cimos = (CIMOSType_T)cimos64;
836 }
837 }
838
839 // now create the virtual system
840 m->llVirtualSystems.push_back(vsys);
841
842 return S_OK;
843}
844
845// IAppliance public methods
846////////////////////////////////////////////////////////////////////////////////
847
848/**
849 * Appliance initializer.
850 *
851 * This loads the given appliance.
852 * @param
853 * @return
854 */
855
856HRESULT Appliance::init(VirtualBox *aVirtualBox)
857{
858 HRESULT rc;
859
860 /* Enclose the state transition NotReady->InInit->Ready */
861 AutoInitSpan autoInitSpan(this);
862 AssertReturn(autoInitSpan.isOk(), E_FAIL);
863
864 /* Weak reference to a VirtualBox object */
865 unconst(mVirtualBox) = aVirtualBox;
866
867 // initialize data
868 m = new Data;
869
870 /* Confirm a successful initialization */
871 autoInitSpan.setSucceeded();
872
873 return S_OK;
874}
875
876void Appliance::uninit()
877{
878 delete m;
879 m = NULL;
880}
881
882STDMETHODIMP Appliance::COMGETTER(Path)(BSTR *aPath)
883{
884 if (!aPath)
885 return E_POINTER;
886
887 AutoCaller autoCaller(this);
888 CheckComRCReturnRC(autoCaller.rc());
889
890 AutoReadLock alock(this);
891
892 m->bstrPath.cloneTo(aPath);
893
894 return S_OK;
895}
896
897STDMETHODIMP Appliance::COMGETTER(Disks)(ComSafeArrayOut(BSTR, aDisks))
898{
899 CheckComArgOutSafeArrayPointerValid(aDisks);
900
901 AutoCaller autoCaller(this);
902 CheckComRCReturnRC(autoCaller.rc());
903
904 AutoReadLock alock(this);
905
906 size_t c = m->mapDisks.size();
907 com::SafeArray<BSTR> sfaDisks(c);
908
909 DiskImagesMap::const_iterator it;
910 size_t i = 0;
911 for (it = m->mapDisks.begin();
912 it != m->mapDisks.end();
913 ++it, ++i)
914 {
915 // create a string representing this disk
916 const DiskImage &d = it->second;
917 char *psz = NULL;
918 RTStrAPrintf(&psz,
919 "%s\t"
920 "%RI64\t"
921 "%RI64\t"
922 "%s\t"
923 "%s\t"
924 "%RI64\t"
925 "%RI64\t"
926 "%s",
927 d.strDiskId.c_str(),
928 d.iCapacity,
929 d.iPopulatedSize,
930 d.strFormat.c_str(),
931 d.strHref.c_str(),
932 d.iSize,
933 d.iChunkSize,
934 d.strCompression.c_str());
935 Utf8Str utf(psz);
936 Bstr bstr(utf);
937 // push to safearray
938 bstr.cloneTo(&sfaDisks[i]);
939 RTStrFree(psz);
940 }
941
942 sfaDisks.detachTo(ComSafeArrayOutArg(aDisks));
943
944 return S_OK;
945}
946
947STDMETHODIMP Appliance::COMGETTER(VirtualSystemDescriptions)(ComSafeArrayOut(IVirtualSystemDescription*, aVirtualSystemDescriptions))
948{
949 CheckComArgOutSafeArrayPointerValid(aVirtualSystemDescriptions);
950
951 AutoCaller autoCaller(this);
952 CheckComRCReturnRC(autoCaller.rc());
953
954 AutoReadLock alock(this);
955
956 SafeIfaceArray<IVirtualSystemDescription> sfaVSD(m->virtualSystemDescriptions);
957 sfaVSD.detachTo(ComSafeArrayOutArg(aVirtualSystemDescriptions));
958
959 return S_OK;
960}
961
962void convertCIMOSType2VBoxOSType(Utf8Str &osTypeVBox, CIMOSType_T c)
963{
964 switch (c)
965 {
966 case CIMOSType_CIMOS_Unknown: // 0 - Unknown
967 osTypeVBox = SchemaDefs_OSTypeId_Other;
968 break;
969
970 case CIMOSType_CIMOS_OS2: // 12 - OS/2
971 osTypeVBox = SchemaDefs_OSTypeId_OS2;
972 break;
973
974 case CIMOSType_CIMOS_MSDOS: // 14 - MSDOS
975 osTypeVBox = SchemaDefs_OSTypeId_DOS;
976 break;
977
978 case CIMOSType_CIMOS_WIN3x: // 15 - WIN3x
979 osTypeVBox = SchemaDefs_OSTypeId_Windows31;
980 break;
981
982 case CIMOSType_CIMOS_WIN95: // 16 - WIN95
983 osTypeVBox = SchemaDefs_OSTypeId_Windows95;
984 break;
985
986 case CIMOSType_CIMOS_WIN98: // 17 - WIN98
987 osTypeVBox = SchemaDefs_OSTypeId_Windows98;
988 break;
989
990 case CIMOSType_CIMOS_WINNT: // 18 - WINNT
991 osTypeVBox = SchemaDefs_OSTypeId_WindowsNT4;
992 break;
993
994 case CIMOSType_CIMOS_NetWare: // 21 - NetWare
995 case CIMOSType_CIMOS_NovellOES: // 86 - Novell OES
996 osTypeVBox = SchemaDefs_OSTypeId_Netware;
997 break;
998
999 case CIMOSType_CIMOS_Solaris: // 29 - Solaris
1000 case CIMOSType_CIMOS_SunOS: // 30 - SunOS
1001 osTypeVBox = SchemaDefs_OSTypeId_Solaris;
1002 break;
1003
1004 case CIMOSType_CIMOS_FreeBSD: // 42 - FreeBSD
1005 osTypeVBox = SchemaDefs_OSTypeId_FreeBSD;
1006 break;
1007
1008 case CIMOSType_CIMOS_NetBSD: // 43 - NetBSD
1009 osTypeVBox = SchemaDefs_OSTypeId_NetBSD;
1010 break;
1011
1012 case CIMOSType_CIMOS_QNX: // 48 - QNX
1013 osTypeVBox = SchemaDefs_OSTypeId_QNX;
1014 break;
1015
1016 case CIMOSType_CIMOS_Windows2000: // 58 - Windows 2000
1017 osTypeVBox = SchemaDefs_OSTypeId_Windows2000;
1018 break;
1019
1020 case CIMOSType_CIMOS_WindowsMe: // 63 - Windows (R) Me
1021 osTypeVBox = SchemaDefs_OSTypeId_WindowsMe;
1022 break;
1023
1024 case CIMOSType_CIMOS_OpenBSD: // 65 - OpenBSD
1025 osTypeVBox = SchemaDefs_OSTypeId_OpenBSD;
1026 break;
1027
1028 case CIMOSType_CIMOS_WindowsXP: // 67 - Windows XP
1029 case CIMOSType_CIMOS_WindowsXPEmbedded: // 72 - Windows XP Embedded
1030 case CIMOSType_CIMOS_WindowsEmbeddedforPointofService: // 75 - Windows Embedded for Point of Service
1031 osTypeVBox = SchemaDefs_OSTypeId_WindowsXP;
1032 break;
1033
1034 case CIMOSType_CIMOS_MicrosoftWindowsServer2003: // 69 - Microsoft Windows Server 2003
1035 osTypeVBox = SchemaDefs_OSTypeId_Windows2003;
1036 break;
1037
1038 case CIMOSType_CIMOS_MicrosoftWindowsServer2003_64: // 70 - Microsoft Windows Server 2003 64-Bit
1039 osTypeVBox = SchemaDefs_OSTypeId_Windows2003_64;
1040 break;
1041
1042 case CIMOSType_CIMOS_WindowsXP_64: // 71 - Windows XP 64-Bit
1043 osTypeVBox = SchemaDefs_OSTypeId_WindowsXP_64;
1044 break;
1045
1046 case CIMOSType_CIMOS_WindowsVista: // 73 - Windows Vista
1047 osTypeVBox = SchemaDefs_OSTypeId_WindowsVista;
1048 break;
1049
1050 case CIMOSType_CIMOS_WindowsVista_64: // 74 - Windows Vista 64-Bit
1051 osTypeVBox = SchemaDefs_OSTypeId_WindowsVista_64;
1052 break;
1053
1054 case CIMOSType_CIMOS_MicrosoftWindowsServer2008: // 76 - Microsoft Windows Server 2008
1055 osTypeVBox = SchemaDefs_OSTypeId_Windows2008;
1056 break;
1057
1058 case CIMOSType_CIMOS_MicrosoftWindowsServer2008_64: // 77 - Microsoft Windows Server 2008 64-Bit
1059 osTypeVBox = SchemaDefs_OSTypeId_Windows2008_64;
1060 break;
1061
1062 case CIMOSType_CIMOS_FreeBSD_64: // 78 - FreeBSD 64-Bit
1063 osTypeVBox = SchemaDefs_OSTypeId_FreeBSD_64;
1064 break;
1065
1066 case CIMOSType_CIMOS_RedHatEnterpriseLinux: // 79 - RedHat Enterprise Linux
1067 osTypeVBox = SchemaDefs_OSTypeId_RedHat;
1068 break;
1069
1070 case CIMOSType_CIMOS_RedHatEnterpriseLinux_64: // 80 - RedHat Enterprise Linux 64-Bit
1071 osTypeVBox = SchemaDefs_OSTypeId_RedHat_64;
1072 break;
1073
1074 case CIMOSType_CIMOS_Solaris_64: // 81 - Solaris 64-Bit
1075 osTypeVBox = SchemaDefs_OSTypeId_Solaris_64;
1076 break;
1077
1078 case CIMOSType_CIMOS_SUSE: // 82 - SUSE
1079 case CIMOSType_CIMOS_SLES: // 84 - SLES
1080 case CIMOSType_CIMOS_NovellLinuxDesktop: // 87 - Novell Linux Desktop
1081 osTypeVBox = SchemaDefs_OSTypeId_OpenSUSE;
1082 break;
1083
1084 case CIMOSType_CIMOS_SUSE_64: // 83 - SUSE 64-Bit
1085 case CIMOSType_CIMOS_SLES_64: // 85 - SLES 64-Bit
1086 osTypeVBox = SchemaDefs_OSTypeId_OpenSUSE_64;
1087 break;
1088
1089 case CIMOSType_CIMOS_LINUX: // 36 - LINUX
1090 case CIMOSType_CIMOS_SunJavaDesktopSystem: // 88 - Sun Java Desktop System
1091 case CIMOSType_CIMOS_TurboLinux: // 91 - TurboLinux
1092 osTypeVBox = SchemaDefs_OSTypeId_Linux;
1093 break;
1094
1095 // case CIMOSType_CIMOS_TurboLinux_64: // 92 - TurboLinux 64-Bit
1096 // case CIMOSType_CIMOS_Linux_64: // 101 - Linux 64-Bit
1097 // osTypeVBox = VBOXOSTYPE_Linux_x64;
1098 // break;
1099
1100 case CIMOSType_CIMOS_Mandriva: // 89 - Mandriva
1101 osTypeVBox = SchemaDefs_OSTypeId_Mandriva;
1102 break;
1103
1104 case CIMOSType_CIMOS_Mandriva_64: // 90 - Mandriva 64-Bit
1105 osTypeVBox = SchemaDefs_OSTypeId_Mandriva_64;
1106 break;
1107
1108 case CIMOSType_CIMOS_Ubuntu: // 93 - Ubuntu
1109 osTypeVBox = SchemaDefs_OSTypeId_Ubuntu;
1110 break;
1111
1112 case CIMOSType_CIMOS_Ubuntu_64: // 94 - Ubuntu 64-Bit
1113 osTypeVBox = SchemaDefs_OSTypeId_Ubuntu_64;
1114 break;
1115
1116 case CIMOSType_CIMOS_Debian: // 95 - Debian
1117 osTypeVBox = SchemaDefs_OSTypeId_Debian;
1118 break;
1119
1120 case CIMOSType_CIMOS_Debian_64: // 96 - Debian 64-Bit
1121 osTypeVBox = SchemaDefs_OSTypeId_Debian_64;
1122 break;
1123
1124 case CIMOSType_CIMOS_Linux_2_4_x: // 97 - Linux 2.4.x
1125 osTypeVBox = SchemaDefs_OSTypeId_Linux24;
1126 break;
1127
1128 case CIMOSType_CIMOS_Linux_2_4_x_64: // 98 - Linux 2.4.x 64-Bit
1129 osTypeVBox = SchemaDefs_OSTypeId_Linux24_64;
1130 break;
1131
1132 case CIMOSType_CIMOS_Linux_2_6_x: // 99 - Linux 2.6.x
1133 osTypeVBox = SchemaDefs_OSTypeId_Linux26;
1134 break;
1135
1136 case CIMOSType_CIMOS_Linux_2_6_x_64: // 100 - Linux 2.6.x 64-Bit
1137 osTypeVBox = SchemaDefs_OSTypeId_Linux26_64;
1138 break;
1139 default:
1140 {
1141 /* If we are here we have no clue what OS this should be. Set
1142 to other type as default. */
1143 osTypeVBox = SchemaDefs_OSTypeId_Other;
1144 }
1145 }
1146}
1147
1148STDMETHODIMP Appliance::Read(IN_BSTR path)
1149{
1150 HRESULT rc = S_OK;
1151
1152 if (!path)
1153 return E_POINTER;
1154
1155 AutoCaller autoCaller(this);
1156 CheckComRCReturnRC(autoCaller.rc());
1157
1158 AutoWriteLock alock(this);
1159 m->bstrPath = path;
1160
1161 // see if we can handle this file; for now we insist it has an ".ovf" extension
1162 Utf8Str utf8Path(path);
1163 const char *pcszLastDot = strrchr(utf8Path, '.');
1164 if ( (!pcszLastDot)
1165 || ( strcmp(pcszLastDot, ".ovf")
1166 && strcmp(pcszLastDot, ".OVF")
1167 )
1168 )
1169 return setError(VBOX_E_FILE_ERROR,
1170 tr("Appliance file must have .ovf extension"));
1171
1172 try
1173 {
1174 xml::XmlFileParser parser;
1175 xml::Document doc;
1176 parser.read(utf8Path.raw(),
1177 doc);
1178
1179 const xml::Node *pRootElem = doc.getRootElement();
1180 if (strcmp(pRootElem->getName(), "Envelope"))
1181 return setError(VBOX_E_FILE_ERROR,
1182 tr("Root element in OVF file must be \"Envelope\"."));
1183
1184 // OVF has the following rough layout:
1185 /*
1186 -- <References> .... files referenced from other parts of the file, such as VMDK images
1187 -- Metadata, comprised of several section commands
1188 -- virtual machines, either a single <VirtualSystem>, or a <VirtualSystemCollection>
1189 -- optionally <Strings> for localization
1190 */
1191
1192 // get all "File" child elements of "References" section so we can look up files easily;
1193 // first find the "References" sections so we can look up files
1194 xml::NodesList listFileElements; // receives all /Envelope/References/File nodes
1195 const xml::Node *pReferencesElem;
1196 if ((pReferencesElem = pRootElem->findChildElement("References")))
1197 pReferencesElem->getChildElements(listFileElements, "File");
1198
1199 // now go though the sections
1200 if (!(SUCCEEDED(rc = LoopThruSections(utf8Path.raw(), pReferencesElem, pRootElem))))
1201 return rc;
1202 }
1203 catch(xml::Error &x)
1204 {
1205 return setError(VBOX_E_FILE_ERROR,
1206 x.what());
1207 }
1208
1209 return S_OK;
1210}
1211
1212STDMETHODIMP Appliance::Interpret()
1213{
1214 // @todo:
1215 // - don't use COM methods but the methods directly (faster, but needs appropriate locking of that objects itself (s. HardDisk2))
1216 // - Appropriate handle errors like not supported file formats
1217 AutoCaller autoCaller(this);
1218 CheckComRCReturnRC(autoCaller.rc());
1219
1220 AutoWriteLock(this);
1221
1222 HRESULT rc = S_OK;
1223
1224 /* Clear any previous virtual system descriptions */
1225 // @todo: have the entries deleted also?
1226 m->virtualSystemDescriptions.clear();
1227
1228 /* We need the default path for storing disk images */
1229 ComPtr<ISystemProperties> systemProps;
1230 rc = mVirtualBox->COMGETTER(SystemProperties)(systemProps.asOutParam());
1231 CheckComRCReturnRC(rc);
1232 Bstr bstrDefaultHardDiskLocation;
1233 rc = systemProps->COMGETTER(DefaultHardDiskFolder)(bstrDefaultHardDiskLocation.asOutParam());
1234 CheckComRCReturnRC(rc);
1235
1236 /* Try/catch so we can clean up on error */
1237 try
1238 {
1239 list<VirtualSystem>::const_iterator it;
1240 /* Iterate through all appliances */
1241 for (it = m->llVirtualSystems.begin();
1242 it != m->llVirtualSystems.end();
1243 ++it)
1244 {
1245 const VirtualSystem &vsysThis = *it;
1246
1247 ComObjPtr<VirtualSystemDescription> pNewDesc;
1248 rc = pNewDesc.createObject();
1249 CheckComRCThrowRC(rc);
1250 rc = pNewDesc->init();
1251 CheckComRCThrowRC(rc);
1252
1253 /* Guest OS type */
1254 Utf8Str strOsTypeVBox,
1255 strCIMOSType = toString<ULONG>(vsysThis.cimos);
1256 convertCIMOSType2VBoxOSType(strOsTypeVBox, vsysThis.cimos);
1257 pNewDesc->addEntry(VirtualSystemDescriptionType_OS,
1258 "",
1259 strCIMOSType,
1260 strOsTypeVBox);
1261
1262 /* VM name */
1263 /* If the there isn't any name specified create a default one out of
1264 * the OS type */
1265 Utf8Str nameVBox = vsysThis.strName;
1266 if (nameVBox == "")
1267 nameVBox = strOsTypeVBox;
1268 searchUniqueVMName(nameVBox);
1269 pNewDesc->addEntry(VirtualSystemDescriptionType_Name,
1270 "",
1271 vsysThis.strName,
1272 nameVBox);
1273
1274 /* Now that we know the OS type, get our internal defaults based on that. */
1275 ComPtr<IGuestOSType> pGuestOSType;
1276 rc = mVirtualBox->GetGuestOSType(Bstr(strOsTypeVBox), pGuestOSType.asOutParam());
1277 CheckComRCThrowRC(rc);
1278
1279 /* CPU count */
1280 ULONG cpuCountVBox = vsysThis.cCPUs;
1281 /* Check for the constrains */
1282 if (cpuCountVBox > 1) //SchemaDefs::MaxCPUCount)
1283 {
1284 pNewDesc->addWarning(tr("The virtual system claims support for %u CPU's, but VirtualBox has support for max %u CPU's only."),
1285 cpuCountVBox, 1); //SchemaDefs::MaxCPUCount);
1286 cpuCountVBox = 1; //SchemaDefs::MaxCPUCount;
1287 }
1288 if (vsysThis.cCPUs == 0)
1289 cpuCountVBox = 1;
1290 pNewDesc->addEntry(VirtualSystemDescriptionType_CPU,
1291 "",
1292 toString<ULONG>(vsysThis.cCPUs),
1293 toString<ULONG>(cpuCountVBox));
1294
1295 /* RAM */
1296 uint64_t ullMemSizeVBox = vsysThis.ullMemorySize / _1M;
1297 /* Check for the constrains */
1298 if (ullMemSizeVBox != 0 &&
1299 (ullMemSizeVBox < static_cast<uint64_t>(SchemaDefs::MinGuestRAM) ||
1300 ullMemSizeVBox > static_cast<uint64_t>(SchemaDefs::MaxGuestRAM)))
1301 {
1302 pNewDesc->addWarning(tr("The virtual system claims support for %llu MB RAM size, but VirtualBox has support for min %u & max %u MB RAM size only."),
1303 ullMemSizeVBox, SchemaDefs::MinGuestRAM, SchemaDefs::MaxGuestRAM);
1304 ullMemSizeVBox = RT_MIN(RT_MAX(ullMemSizeVBox, static_cast<uint64_t>(SchemaDefs::MinGuestRAM)), static_cast<uint64_t>(SchemaDefs::MaxGuestRAM));
1305 }
1306 if (vsysThis.ullMemorySize == 0)
1307 {
1308 /* If the RAM of the OVF is zero, use our predefined values */
1309 ULONG memSizeVBox2;
1310 rc = pGuestOSType->COMGETTER(RecommendedRAM)(&memSizeVBox2);
1311 CheckComRCThrowRC(rc);
1312 /* VBox stores that in MByte */
1313 ullMemSizeVBox = (uint64_t)memSizeVBox2;
1314 }
1315 pNewDesc->addEntry(VirtualSystemDescriptionType_Memory,
1316 "",
1317 toString<uint64_t>(vsysThis.ullMemorySize),
1318 toString<uint64_t>(ullMemSizeVBox));
1319
1320 /* Audio */
1321 if (!vsysThis.strSoundCardType.isNull())
1322 /* Currently we set the AC97 always.
1323 @todo: figure out the hardware which could be possible */
1324 pNewDesc->addEntry(VirtualSystemDescriptionType_SoundCard,
1325 "",
1326 vsysThis.strSoundCardType,
1327 toString<ULONG>(AudioControllerType_AC97));
1328
1329 /* USB Controller */
1330 if (vsysThis.fHasUsbController)
1331 pNewDesc->addEntry(VirtualSystemDescriptionType_USBController, "", "", "");
1332
1333 NetworksMap::const_iterator itN;
1334 for (itN = m->mapNetworks.begin();
1335 itN != m->mapNetworks.end();
1336 ++itN)
1337 {
1338 const Network &nw = itN->second;
1339 pNewDesc->addEntry(VirtualSystemDescriptionType_LogicalNetwork,
1340 "",
1341 nw.strNetworkName,
1342 nw.strNetworkName);
1343 }
1344
1345 /* Network Controller */
1346 // @todo: there is no hardware specification in the OVF file; supposedly the
1347 // hardware will then be determined by the VirtualSystemType element (e.g. "vmx-07")
1348 if (vsysThis.llNetworkNames.size() > 0)
1349 {
1350 /* Check for the constrains */
1351 if (vsysThis.llNetworkNames.size() > SchemaDefs::NetworkAdapterCount)
1352 {
1353 pNewDesc->addWarning(tr("The virtual system claims support for %u network adapters, but VirtualBox has support for max %u network adapter only."),
1354 vsysThis.llNetworkNames.size(), SchemaDefs::NetworkAdapterCount);
1355
1356 }
1357 /* Get the default network adapter type for the selected guest OS */
1358 NetworkAdapterType_T nwAdapterVBox = NetworkAdapterType_Am79C970A;
1359 rc = pGuestOSType->COMGETTER(AdapterType)(&nwAdapterVBox);
1360 CheckComRCThrowRC(rc);
1361 list<Utf8Str>::const_iterator nwIt;
1362 /* Iterate through all abstract networks. We support 8 network
1363 * adapters at the maximum, so the first 8 will be added only. */
1364 size_t a = 0;
1365 for (nwIt = vsysThis.llNetworkNames.begin();
1366 nwIt != vsysThis.llNetworkNames.end() && a < SchemaDefs::NetworkAdapterCount;
1367 ++nwIt, ++a)
1368 {
1369 Utf8Str strNetwork = *nwIt; // logical network to connect to
1370 pNewDesc->addEntry(VirtualSystemDescriptionType_NetworkAdapter,
1371 "", // ref
1372 strNetwork, // orig
1373 toString<ULONG>(nwAdapterVBox), // conf
1374 Utf8StrFmt("network=%s", strNetwork.c_str())); // extra conf
1375 }
1376 }
1377
1378 /* Floppy Drive */
1379 if (vsysThis.fHasFloppyDrive)
1380 pNewDesc->addEntry(VirtualSystemDescriptionType_Floppy, "", "", "");
1381
1382 /* CD Drive */
1383 /* @todo: I can't disable the CDROM. So nothing to do for now */
1384 /*
1385 if (vsysThis.fHasCdromDrive)
1386 pNewDesc->addEntry(VirtualSystemDescriptionType_CDROM, "", "", "");*/
1387
1388 /* Hard disk Controller */
1389 uint16_t cIDEused = 0;
1390 uint16_t cSATAused = 0;
1391 uint16_t cSCSIused = 0;
1392 ControllersMap::const_iterator hdcIt;
1393 /* Iterate through all hard disk controllers */
1394 for (hdcIt = vsysThis.mapControllers.begin();
1395 hdcIt != vsysThis.mapControllers.end();
1396 ++hdcIt)
1397 {
1398 const HardDiskController &hdc = hdcIt->second;
1399 Utf8Str strControllerID = toString<uint32_t>(hdc.idController);
1400
1401 switch (hdc.system)
1402 {
1403 case HardDiskController::IDE:
1404 {
1405 /* Check for the constrains */
1406 /* @todo: I'm very confused! Are these bits *one* controller or
1407 is every port/bus declared as an extra controller. */
1408 if (cIDEused < 4)
1409 {
1410 // @todo: figure out the IDE types
1411 /* Use PIIX4 as default */
1412 // IDEControllerType_T hdcController = IDEControllerType_PIIX4;
1413 Utf8Str strType = "PIIX4";
1414 if (!RTStrICmp(hdc.strControllerType.c_str(), "PIIX3"))
1415 strType = "PIIX3";
1416 // else // if (!RTStrICmp(hdc.strControllerType.c_str(), "PIIX4"))
1417 // hdcController = IDEControllerType_PIIX4;
1418 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
1419 strControllerID,
1420 hdc.strControllerType,
1421 strType);
1422 }
1423 else
1424 {
1425 /* Warn only once */
1426 if (cIDEused == 1)
1427 pNewDesc->addWarning(tr("The virtual system claims support for more than one IDE controller, but VirtualBox has support for only one."));
1428
1429 }
1430 ++cIDEused;
1431 break;
1432 }
1433
1434#ifdef VBOX_WITH_AHCI
1435 case HardDiskController::SATA:
1436 {
1437 /* Check for the constrains */
1438 if (cSATAused < 1)
1439 {
1440 // @todo: figure out the SATA types
1441 /* We only support a plain AHCI controller, so use them always */
1442 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerSATA,
1443 strControllerID,
1444 hdc.strControllerType,
1445 "AHCI");
1446 }
1447 else
1448 {
1449 /* Warn only once */
1450 if (cSATAused == 1)
1451 pNewDesc->addWarning(tr("The virtual system claims support for more than one SATA controller, but VirtualBox has support for only one."));
1452
1453 }
1454 ++cSATAused;
1455 break;
1456 }
1457#endif /* VBOX_WITH_AHCI */
1458
1459 case HardDiskController::SCSI:
1460 {
1461 /* Check for the constrains */
1462 if (cSCSIused < 1)
1463 {
1464 // @todo: figure out the SCSI types
1465 Utf8Str hdcController = "LsiLogic";
1466 /* if (!RTStrICmp(hdc.strControllerType.c_str(), "LsiLogic"))
1467 hdcController = "LsiLogic";
1468 else*/
1469 if (!RTStrICmp(hdc.strControllerType.c_str(), "BusLogic"))
1470 hdcController = "BusLogic";
1471 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerSCSI,
1472 strControllerID,
1473 hdc.strControllerType,
1474 hdcController);
1475 }
1476 else
1477 {
1478 /* Warn only once */
1479 if (cSCSIused == 1)
1480 pNewDesc->addWarning(tr("The virtual system claims support for more than one SCSI controller, but VirtualBox has support for only one."));
1481
1482 }
1483 ++cSCSIused;
1484 break;
1485 }
1486 default:
1487 {
1488 /* @todo: should we stop? */
1489 }
1490 }
1491 }
1492
1493 /* Hard disks */
1494 if (vsysThis.mapVirtualDisks.size() > 0)
1495 {
1496 VirtualDisksMap::const_iterator itVD;
1497 /* Iterate through all hard disks ()*/
1498 for (itVD = vsysThis.mapVirtualDisks.begin();
1499 itVD != vsysThis.mapVirtualDisks.end();
1500 ++itVD)
1501 {
1502 const VirtualDisk &hd = itVD->second;
1503 /* Get the associated disk image */
1504 const DiskImage &di = m->mapDisks[hd.strDiskId];
1505
1506 // @todo:
1507 // - figure out all possible vmdk formats we also support
1508 // - figure out if there is a url specifier for vhd already
1509 // - we need a url specifier for the vdi format
1510 if ( (!RTStrICmp(di.strFormat.c_str(), "http://www.vmware.com/specifications/vmdk.html#sparse"))
1511 || (!RTStrICmp(di.strFormat.c_str(), "http://www.vmware.com/specifications/vmdk.html#compressed"))
1512 )
1513 {
1514 /* If the href is empty use the VM name as filename */
1515 Utf8Str strFilename = di.strHref.c_str();
1516 if (di.strHref.c_str()[0] == 0)
1517 strFilename = Utf8StrFmt("%s.vmdk", nameVBox.c_str());
1518 /* Construct a unique target path */
1519 Utf8StrFmt strPath("%ls%c%s",
1520 bstrDefaultHardDiskLocation.raw(),
1521 RTPATH_DELIMITER,
1522 strFilename.c_str());
1523 searchUniqueDiskImageFilePath(strPath);
1524
1525 /* find the description for the hard disk controller
1526 * that has the same ID as hd.idController */
1527 const VirtualSystemDescriptionEntry *pController;
1528 if (!(pController = pNewDesc->findControllerFromID(hd.idController)))
1529 throw setError(E_FAIL,
1530 tr("Internal inconsistency looking up hard disk controller."));
1531
1532 /* controller to attach to @todo bus? */
1533 Utf8StrFmt strExtraConfig("controller=%RI16",
1534 pController->ulIndex);
1535 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskImage,
1536 hd.strDiskId,
1537 di.strHref,
1538 strPath,
1539 strExtraConfig);
1540 }
1541 else
1542 {
1543 /* @todo: should we stop here? */
1544 pNewDesc->addWarning(tr("The virtual system claims support for the following virtual disk image format which VirtualBox not support: %s"),
1545 di.strFormat.c_str());
1546 }
1547 }
1548 }
1549
1550 m->virtualSystemDescriptions.push_back(pNewDesc);
1551 }
1552 }
1553 catch (HRESULT aRC)
1554 {
1555 /* On error we clear the list & return */
1556 m->virtualSystemDescriptions.clear();
1557 rc = aRC;
1558 }
1559
1560 return rc;
1561}
1562
1563STDMETHODIMP Appliance::ImportMachines(IProgress **aProgress)
1564{
1565 CheckComArgOutPointerValid(aProgress);
1566
1567 AutoCaller autoCaller(this);
1568 CheckComRCReturnRC(autoCaller.rc());
1569
1570 AutoReadLock(this);
1571
1572 HRESULT rc = S_OK;
1573
1574 ComObjPtr<Progress> progress;
1575 try
1576 {
1577 /* Figure out how many sub operation the import will need */
1578 /* One for the appliance */
1579 int opCount = 1;
1580 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
1581 for (it = m->virtualSystemDescriptions.begin();
1582 it != m->virtualSystemDescriptions.end();
1583 ++it)
1584 {
1585 /* One for every Virtual System */
1586 ++opCount;
1587 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
1588 /* One for every hard disk of the Virtual System */
1589 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1590 opCount += avsdeHDs.size();
1591 }
1592 Bstr progressDesc = BstrFmt(tr("Import appliance '%ls'"),
1593 m->bstrPath.raw());
1594 /* Create the progress object */
1595 progress.createObject();
1596 rc = progress->init(mVirtualBox, static_cast<IAppliance *>(this),
1597 progressDesc,
1598 FALSE /* aCancelable */,
1599 opCount,
1600 progressDesc);
1601 CheckComRCThrowRC(rc);
1602
1603 /* Initialize our worker task */
1604 std::auto_ptr<Task> task(new Task(this, progress));
1605 //AssertComRCThrowRC (task->autoCaller.rc());
1606
1607 rc = task->startThread();
1608 CheckComRCThrowRC(rc);
1609
1610 task.release();
1611 }
1612 catch (HRESULT aRC)
1613 {
1614 rc = aRC;
1615 }
1616
1617 if (SUCCEEDED(rc))
1618 /* Return progress to the caller */
1619 progress.queryInterfaceTo(aProgress);
1620
1621 return rc;
1622}
1623
1624HRESULT Appliance::searchUniqueVMName(Utf8Str& aName) const
1625{
1626 IMachine *machine = NULL;
1627 char *tmpName = RTStrDup(aName.c_str());
1628 int i = 1;
1629 /* @todo: Maybe too cost-intensive; try to find a lighter way */
1630 while (mVirtualBox->FindMachine(Bstr(tmpName), &machine) != VBOX_E_OBJECT_NOT_FOUND)
1631 {
1632 RTStrFree(tmpName);
1633 RTStrAPrintf(&tmpName, "%s_%d", aName.c_str(), i);
1634 ++i;
1635 }
1636 aName = tmpName;
1637 RTStrFree(tmpName);
1638
1639 return S_OK;
1640}
1641
1642HRESULT Appliance::searchUniqueDiskImageFilePath(Utf8Str& aName) const
1643{
1644 IHardDisk2 *harddisk = NULL;
1645 char *tmpName = RTStrDup(aName.c_str());
1646 int i = 1;
1647 /* Check if the file exists or if a file with this path is registered
1648 * already */
1649 /* @todo: Maybe too cost-intensive; try to find a lighter way */
1650 while (RTPathExists(tmpName) ||
1651 mVirtualBox->FindHardDisk2(Bstr(tmpName), &harddisk) != VBOX_E_OBJECT_NOT_FOUND)
1652 {
1653 RTStrFree(tmpName);
1654 char *tmpDir = RTStrDup(aName.c_str());
1655 RTPathStripFilename(tmpDir);;
1656 char *tmpFile = RTStrDup(RTPathFilename(aName.c_str()));
1657 RTPathStripExt(tmpFile);
1658 const char *tmpExt = RTPathExt(aName.c_str());
1659 RTStrAPrintf(&tmpName, "%s%c%s_%d%s", tmpDir, RTPATH_DELIMITER, tmpFile, i, tmpExt);
1660 RTStrFree(tmpFile);
1661 RTStrFree(tmpDir);
1662 ++i;
1663 }
1664 aName = tmpName;
1665 RTStrFree(tmpName);
1666
1667 return S_OK;
1668}
1669
1670/* static */
1671DECLCALLBACK(int) Appliance::taskThread(RTTHREAD aThread, void *pvUser)
1672{
1673 std::auto_ptr <Task> task(static_cast<Task *>(pvUser));
1674 AssertReturn(task.get(), VERR_GENERAL_FAILURE);
1675
1676 Appliance *app = task->that;
1677
1678 /// @todo ugly hack, fix ComAssert... (same as in HardDisk2::taskThread)
1679 #define setError app->setError
1680
1681 LogFlowFuncEnter();
1682 LogFlowFunc(("Appliance %p\n", app));
1683
1684 AutoCaller autoCaller(app);
1685 CheckComRCReturnRC(autoCaller.rc());
1686
1687 AutoWriteLock appLock(app);
1688
1689 HRESULT rc = S_OK;
1690
1691 list<VirtualSystem>::const_iterator it;
1692 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it1;
1693 /* Iterate through all virtual systems of that appliance */
1694 size_t i = 0;
1695 for (it = app->m->llVirtualSystems.begin(),
1696 it1 = app->m->virtualSystemDescriptions.begin();
1697 it != app->m->llVirtualSystems.end();
1698 ++it, ++it1, ++i)
1699 {
1700 const VirtualSystem &vsysThis = *it;
1701 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it1);
1702
1703 /* Catch possible errors */
1704 try
1705 {
1706 if (!task->progress.isNull())
1707 {
1708 rc = task->progress->advanceOperation (BstrFmt(tr("Importing Virtual System %d"), i + 1));
1709 CheckComRCThrowRC(rc);
1710 }
1711
1712 /* How many sub notifications are necessary? */
1713 const float opCountMax = 100.0/5;
1714 uint32_t opCount = 0;
1715
1716 /* Guest OS type */
1717 std::list<VirtualSystemDescriptionEntry*> vsdeOS = vsdescThis->findByType(VirtualSystemDescriptionType_OS);
1718 ComAssertMsgThrow(vsdeOS.size() == 1, ("Guest OS Type missing"), E_FAIL);
1719 const Utf8Str &strOsTypeVBox = vsdeOS.front()->strConfig;
1720
1721 /* Now that we know the base system get our internal defaults based on that. */
1722 ComPtr<IGuestOSType> osType;
1723 rc = app->mVirtualBox->GetGuestOSType(Bstr(strOsTypeVBox), osType.asOutParam());
1724 CheckComRCThrowRC(rc);
1725
1726 /* Create the machine */
1727 /* First get the name */
1728 std::list<VirtualSystemDescriptionEntry*> vsdeName = vsdescThis->findByType(VirtualSystemDescriptionType_Name);
1729 ComAssertMsgThrow(vsdeName.size() == 1, ("Guest OS name missing"), E_FAIL);
1730 const Utf8Str &strNameVBox = vsdeName.front()->strConfig;
1731 ComPtr<IMachine> pNewMachine;
1732 rc = app->mVirtualBox->CreateMachine(Bstr(strNameVBox), Bstr(strOsTypeVBox),
1733 Bstr(), Guid(),
1734 pNewMachine.asOutParam());
1735 CheckComRCThrowRC(rc);
1736
1737 if (!task->progress.isNull())
1738 {
1739 rc = task->progress->notifyProgress((uint32_t)(opCountMax * opCount++));
1740 CheckComRCThrowRC(rc);
1741 }
1742
1743 /* CPU count (ignored for now) */
1744 // EntriesList vsdeCPU = vsd->findByType (VirtualSystemDescriptionType_CPU);
1745
1746 /* RAM */
1747 std::list<VirtualSystemDescriptionEntry*> vsdeRAM = vsdescThis->findByType(VirtualSystemDescriptionType_Memory);
1748 ComAssertMsgThrow(vsdeRAM.size() == 1, ("RAM size missing"), E_FAIL);
1749 const Utf8Str &memoryVBox = vsdeRAM.front()->strConfig;
1750 ULONG tt = (ULONG)RTStrToUInt64(memoryVBox.c_str());
1751 rc = pNewMachine->COMSETTER(MemorySize)(tt);
1752 CheckComRCThrowRC(rc);
1753
1754 /* VRAM */
1755 /* Get the recommended VRAM for this guest OS type */
1756 ULONG vramVBox;
1757 rc = osType->COMGETTER(RecommendedVRAM)(&vramVBox);
1758 CheckComRCThrowRC(rc);
1759 /* Set the VRAM */
1760 rc = pNewMachine->COMSETTER(VRAMSize)(vramVBox);
1761 CheckComRCThrowRC(rc);
1762
1763 if (!task->progress.isNull())
1764 {
1765 rc = task->progress->notifyProgress((uint32_t)(opCountMax * opCount++));
1766 CheckComRCThrowRC(rc);
1767 }
1768
1769 /* Audio Adapter */
1770 std::list<VirtualSystemDescriptionEntry*> vsdeAudioAdapter = vsdescThis->findByType(VirtualSystemDescriptionType_SoundCard);
1771 /* @todo: we support one audio adapter only */
1772 if (vsdeAudioAdapter.size() > 0)
1773 {
1774 const Utf8Str& audioAdapterVBox = vsdeAudioAdapter.front()->strConfig;
1775 if (RTStrICmp(audioAdapterVBox, "null") != 0)
1776 {
1777 uint32_t audio = RTStrToUInt32(audioAdapterVBox.c_str());
1778 ComPtr<IAudioAdapter> audioAdapter;
1779 rc = pNewMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam());
1780 CheckComRCThrowRC(rc);
1781 rc = audioAdapter->COMSETTER(Enabled)(true);
1782 CheckComRCThrowRC(rc);
1783 rc = audioAdapter->COMSETTER(AudioController)(static_cast<AudioControllerType_T>(audio));
1784 CheckComRCThrowRC(rc);
1785 }
1786 }
1787
1788 /* USB Controller */
1789 std::list<VirtualSystemDescriptionEntry*> vsdeUSBController = vsdescThis->findByType(VirtualSystemDescriptionType_USBController);
1790 // USB support is enabled if there's at least one such entry; to disable USB support,
1791 // the type of the USB item would have been changed to "ignore"
1792 bool fUSBEnabled = vsdeUSBController.size() > 0;
1793
1794 ComPtr<IUSBController> usbController;
1795 rc = pNewMachine->COMGETTER(USBController)(usbController.asOutParam());
1796 CheckComRCThrowRC(rc);
1797 rc = usbController->COMSETTER(Enabled)(fUSBEnabled);
1798 CheckComRCThrowRC(rc);
1799
1800 if (!task->progress.isNull())
1801 {
1802 rc = task->progress->notifyProgress((uint32_t)(opCountMax * opCount++));
1803 CheckComRCThrowRC(rc);
1804 }
1805
1806 /* Change the network adapters */
1807 std::list<VirtualSystemDescriptionEntry*> vsdeNW = vsdescThis->findByType(VirtualSystemDescriptionType_NetworkAdapter);
1808 if (vsdeNW.size() == 0)
1809 {
1810 /* No network adapters, so we have to disable our default one */
1811 ComPtr<INetworkAdapter> nwVBox;
1812 rc = pNewMachine->GetNetworkAdapter(0, nwVBox.asOutParam());
1813 CheckComRCThrowRC(rc);
1814 rc = nwVBox->COMSETTER(Enabled)(false);
1815 CheckComRCThrowRC(rc);
1816 }
1817 else
1818 {
1819 list<VirtualSystemDescriptionEntry*>::const_iterator nwIt;
1820 /* Iterate through all network cards. We support 8 network adapters
1821 * at the maximum. (@todo: warn if there are more!) */
1822 size_t a = 0;
1823 for (nwIt = vsdeNW.begin();
1824 (nwIt != vsdeNW.end() && a < SchemaDefs::NetworkAdapterCount);
1825 ++nwIt, ++a)
1826 {
1827 const Utf8Str &nwTypeVBox = (*nwIt)->strConfig;
1828 uint32_t tt1 = RTStrToUInt32(nwTypeVBox.c_str());
1829 ComPtr<INetworkAdapter> nwVBox;
1830 rc = pNewMachine->GetNetworkAdapter((ULONG)a, nwVBox.asOutParam());
1831 CheckComRCThrowRC(rc);
1832 /* Enable the network card & set the adapter type */
1833 /* NAT is set as default */
1834 rc = nwVBox->COMSETTER(Enabled)(true);
1835 CheckComRCThrowRC(rc);
1836 rc = nwVBox->COMSETTER(AdapterType)(static_cast<NetworkAdapterType_T>(tt1));
1837 CheckComRCThrowRC(rc);
1838 }
1839 }
1840
1841 /* Floppy drive */
1842 std::list<VirtualSystemDescriptionEntry*> vsdeFloppy = vsdescThis->findByType(VirtualSystemDescriptionType_Floppy);
1843 // Floppy support is enabled if there's at least one such entry; to disable floppy support,
1844 // the type of the floppy item would have been changed to "ignore"
1845 bool fFloppyEnabled = vsdeFloppy.size() > 0;
1846 ComPtr<IFloppyDrive> floppyDrive;
1847 rc = pNewMachine->COMGETTER(FloppyDrive)(floppyDrive.asOutParam());
1848 CheckComRCThrowRC(rc);
1849 rc = floppyDrive->COMSETTER(Enabled)(fFloppyEnabled);
1850 CheckComRCThrowRC(rc);
1851
1852 if (!task->progress.isNull())
1853 {
1854 rc = task->progress->notifyProgress((uint32_t)(opCountMax * opCount++));
1855 CheckComRCThrowRC(rc);
1856 }
1857
1858 /* CDROM drive */
1859 /* @todo: I can't disable the CDROM. So nothing to do for now */
1860 // std::list<VirtualSystemDescriptionEntry*> vsdeFloppy = vsd->findByType(VirtualSystemDescriptionType_CDROM);
1861
1862 /* Hard disk controller IDE */
1863 std::list<VirtualSystemDescriptionEntry*> vsdeHDCIDE = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerIDE);
1864 /* @todo: we support one IDE controller only */
1865 if (vsdeHDCIDE.size() > 0)
1866 {
1867 /* Set the appropriate IDE controller in the virtual BIOS of the VM */
1868 ComPtr<IBIOSSettings> biosSettings;
1869 rc = pNewMachine->COMGETTER(BIOSSettings)(biosSettings.asOutParam());
1870 CheckComRCThrowRC(rc);
1871 const char *pcszIDEType = vsdeHDCIDE.front()->strConfig.c_str();
1872 if (!strcmp(pcszIDEType, "PIIX3"))
1873 rc = biosSettings->COMSETTER(IDEControllerType)(IDEControllerType_PIIX3);
1874 else if (!strcmp(pcszIDEType, "PIIX4"))
1875 rc = biosSettings->COMSETTER(IDEControllerType)(IDEControllerType_PIIX4);
1876 else
1877 throw setError(VBOX_E_FILE_ERROR,
1878 tr("Invalid IDE controller type \"%s\""),
1879 pcszIDEType);
1880 CheckComRCThrowRC(rc);
1881 }
1882#ifdef VBOX_WITH_AHCI
1883 /* Hard disk controller SATA */
1884 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSATA = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSATA);
1885 /* @todo: we support one SATA controller only */
1886 if (vsdeHDCSATA.size() > 0)
1887 {
1888 const Utf8Str &hdcVBox = vsdeHDCIDE.front()->strConfig;
1889 if (hdcVBox == "AHCI")
1890 {
1891 /* For now we have just to enable the AHCI controller. */
1892 ComPtr<ISATAController> hdcSATAVBox;
1893 rc = pNewMachine->COMGETTER(SATAController)(hdcSATAVBox.asOutParam());
1894 CheckComRCThrowRC(rc);
1895 rc = hdcSATAVBox->COMSETTER(Enabled)(true);
1896 CheckComRCThrowRC(rc);
1897 }
1898 else
1899 {
1900 throw setError(VBOX_E_FILE_ERROR,
1901 tr("Invalid SATA controller type \"%s\""),
1902 hdcVBox.c_str());
1903 }
1904 }
1905#endif /* VBOX_WITH_AHCI */
1906
1907 /* Hard disk controller SCSI */
1908 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSCSI = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSCSI);
1909 /* @todo: do we support more than one SCSI controller? */
1910 if (vsdeHDCSCSI.size() > 0)
1911 {
1912 /* @todo: revisit when Main support for SCSI is ready */
1913 }
1914
1915 /* Now its time to register the machine before we add any hard disks */
1916 rc = app->mVirtualBox->RegisterMachine(pNewMachine);
1917 CheckComRCThrowRC(rc);
1918
1919 if (!task->progress.isNull())
1920 {
1921 rc = task->progress->notifyProgress((uint32_t)(opCountMax * opCount++));
1922 CheckComRCThrowRC(rc);
1923 }
1924
1925 /* Create the hard disks & connect them to the appropriate controllers. */
1926 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1927 if (avsdeHDs.size() > 0)
1928 {
1929 Guid newMachineId;
1930 rc = pNewMachine->COMGETTER(Id)(newMachineId.asOutParam());
1931 CheckComRCThrowRC(rc);
1932 /* If in the next block an error occur we have to deregister
1933 the machine, so make an extra try/catch block. */
1934 ComPtr<ISession> session;
1935 ComPtr<IHardDisk2> srcHdVBox;
1936 try
1937 {
1938 /* In order to attach hard disks we need to open a session
1939 * for the new machine */
1940 rc = session.createInprocObject(CLSID_Session);
1941 CheckComRCThrowRC(rc);
1942 rc = app->mVirtualBox->OpenSession(session, newMachineId);
1943 CheckComRCThrowRC(rc);
1944
1945 int result;
1946 /* The disk image has to be on the same place as the OVF file. So
1947 * strip the filename out of the full file path. */
1948 Utf8Str strSrcDir = stripFilename(Utf8Str(app->m->bstrPath).raw());
1949
1950 /* Iterate over all given disk images */
1951 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
1952 for (itHD = avsdeHDs.begin();
1953 itHD != avsdeHDs.end();
1954 ++itHD)
1955 {
1956 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
1957
1958 const char *pcszDstFilePath = vsdeHD->strConfig.c_str();
1959 /* Check if the destination file exists already or the
1960 * destination path is empty. */
1961 if ( !(*pcszDstFilePath)
1962 || RTPathExists(pcszDstFilePath)
1963 )
1964 /* This isn't allowed */
1965 throw setError(VBOX_E_FILE_ERROR,
1966 tr("Destination file '%s' exists",
1967 pcszDstFilePath));
1968
1969 /* Find the disk from the OVF's disk list */
1970 DiskImagesMap::const_iterator itDiskImage = app->m->mapDisks.find(vsdeHD->strRef);
1971 /* vsdeHD->strRef contains the disk identifier (e.g. "vmdisk1"), which should exist
1972 in the virtual system's disks map under that ID and also in the global images map. */
1973 VirtualDisksMap::const_iterator itVirtualDisk = vsysThis.mapVirtualDisks.find(vsdeHD->strRef);
1974
1975 if ( itDiskImage == app->m->mapDisks.end()
1976 || itVirtualDisk == vsysThis.mapVirtualDisks.end()
1977 )
1978 throw setError(E_FAIL,
1979 tr("Internal inconsistency looking up disk images."));
1980
1981 const DiskImage &di = itDiskImage->second;
1982 const VirtualDisk &vd = itVirtualDisk->second;
1983
1984 /* Make sure all target directories exists */
1985 rc = VirtualBox::ensureFilePathExists(pcszDstFilePath);
1986 CheckComRCThrowRC(rc);
1987 ComPtr<IHardDisk2> dstHdVBox;
1988 /* If strHref is empty we have to create a new file */
1989 if (di.strHref.c_str()[0] == 0)
1990 {
1991 /* Which format to use? */
1992 Bstr srcFormat = L"VDI";
1993 if ( (!RTStrICmp(di.strFormat.c_str(), "http://www.vmware.com/specifications/vmdk.html#sparse"))
1994 || (!RTStrICmp(di.strFormat.c_str(), "http://www.vmware.com/specifications/vmdk.html#compressed")))
1995 srcFormat = L"VMDK";
1996 /* Create an empty hard disk */
1997 rc = app->mVirtualBox->CreateHardDisk2(srcFormat, Bstr(pcszDstFilePath), dstHdVBox.asOutParam());
1998 CheckComRCThrowRC(rc);
1999 /* Create a dynamic growing disk image with the given capacity */
2000 ComPtr<IProgress> progress;
2001 dstHdVBox->CreateDynamicStorage(di.iCapacity / _1M, progress.asOutParam());
2002 CheckComRCThrowRC(rc);
2003 /* Advance to the next operation */
2004 if (!task->progress.isNull())
2005 {
2006 rc = task->progress->advanceOperation (BstrFmt(tr("Creating virtual disk image '%s'"), pcszDstFilePath));
2007 CheckComRCThrowRC(rc);
2008 }
2009 /* Manually check the progress to inform the user */
2010 BOOL fCompleted;
2011 LONG currentPercent;
2012 while (SUCCEEDED(progress->COMGETTER(Completed(&fCompleted))))
2013 {
2014 rc = progress->COMGETTER(Percent(&currentPercent));
2015 CheckComRCThrowRC(rc);
2016 if (!task->progress.isNull())
2017 {
2018 rc = task->progress->notifyProgress(currentPercent);
2019 CheckComRCThrowRC(rc);
2020 }
2021 if (fCompleted)
2022 break;
2023 /* Make sure the loop is not too tight */
2024 rc = progress->WaitForCompletion(100);
2025 CheckComRCThrowRC(rc);
2026 }
2027 /* Check the real return code of the asynchrony operation */
2028 HRESULT vrc;
2029 rc = progress->COMGETTER(ResultCode)(&vrc);
2030 CheckComRCThrowRC(rc);
2031 CheckComRCThrowRC(vrc);
2032 }
2033 else
2034 {
2035 /* Construct the source file path */
2036 Utf8StrFmt strSrcFilePath("%s%c%s", strSrcDir.c_str(), RTPATH_DELIMITER, di.strHref.c_str());
2037 /* Check if the source file exists */
2038 if (!RTPathExists(strSrcFilePath.c_str()))
2039 /* This isn't allowed */
2040 throw setError(VBOX_E_FILE_ERROR,
2041 tr("Source virtual disk image file '%s' doesn't exists",
2042 strSrcFilePath.c_str()));
2043 /* Clone the disk image (this is necessary cause the id has
2044 * to be recreated for the case the same hard disk is
2045 * attached already from a previous import) */
2046 /* First open the existing disk image */
2047 rc = app->mVirtualBox->OpenHardDisk2(Bstr(strSrcFilePath), srcHdVBox.asOutParam());
2048 CheckComRCThrowRC(rc);
2049 /* We need the format description of the source disk image */
2050 Bstr srcFormat;
2051 rc = srcHdVBox->COMGETTER(Format)(srcFormat.asOutParam());
2052 CheckComRCThrowRC(rc);
2053 /* Create a new hard disk interface for the destination disk image */
2054 rc = app->mVirtualBox->CreateHardDisk2(srcFormat, Bstr(pcszDstFilePath), dstHdVBox.asOutParam());
2055 CheckComRCThrowRC(rc);
2056 /* Clone the source disk image */
2057 ComPtr<IProgress> progress;
2058 rc = srcHdVBox->CloneTo(dstHdVBox, progress.asOutParam());
2059 CheckComRCThrowRC(rc);
2060 /* Advance to the next operation */
2061 if (!task->progress.isNull())
2062 {
2063 rc = task->progress->advanceOperation (BstrFmt(tr("Importing virtual disk image '%s'"), strSrcFilePath.c_str()));
2064 CheckComRCThrowRC(rc);
2065 }
2066 /* Manually check the progress to inform the user */
2067 BOOL fCompleted;
2068 LONG currentPercent;
2069 while (SUCCEEDED(progress->COMGETTER(Completed(&fCompleted))))
2070 {
2071 rc = progress->COMGETTER(Percent(&currentPercent));
2072 CheckComRCThrowRC(rc);
2073 if (!task->progress.isNull())
2074 {
2075 rc = task->progress->notifyProgress (currentPercent);
2076 CheckComRCThrowRC(rc);
2077 }
2078 if (fCompleted)
2079 break;
2080 /* Make sure the loop is not too tight */
2081 rc = progress->WaitForCompletion(100);
2082 CheckComRCThrowRC(rc);
2083 }
2084 /* Check the real return code of the asynchrony operation */
2085 HRESULT vrc;
2086 rc = progress->COMGETTER(ResultCode)(&vrc);
2087 CheckComRCThrowRC(rc);
2088 CheckComRCThrowRC(vrc);
2089 /* We *must* close the source disk image in order to deregister it */
2090 rc = srcHdVBox->Close();
2091 CheckComRCThrowRC(rc);
2092 }
2093 /* Now use the new uuid to attach the disk image to our new machine */
2094 ComPtr<IMachine> sMachine;
2095 rc = session->COMGETTER(Machine)(sMachine.asOutParam());
2096 CheckComRCThrowRC(rc);
2097 Guid hdId;
2098 rc = dstHdVBox->COMGETTER(Id)(hdId.asOutParam());;
2099 CheckComRCThrowRC(rc);
2100 /* For now we assume we have one controller of every type only */
2101 HardDiskController hdc = (*vsysThis.mapControllers.find(vd.idController)).second;
2102 StorageBus_T sbt = StorageBus_IDE;
2103 switch (hdc.system)
2104 {
2105 case HardDiskController::IDE: sbt = StorageBus_IDE; break;
2106 case HardDiskController::SATA: sbt = StorageBus_SATA; break;
2107 //case HardDiskController::SCSI: sbt = StorageBus_SCSI; break; // @todo: not available yet
2108 default: break;
2109 }
2110 rc = sMachine->AttachHardDisk2(hdId, sbt, hdc.ulBusNumber, 0);
2111 CheckComRCThrowRC(rc);
2112 rc = sMachine->SaveSettings();
2113 CheckComRCThrowRC(rc);
2114 rc = session->Close();
2115 CheckComRCThrowRC(rc);
2116 }
2117 }
2118 catch(HRESULT aRC)
2119 {
2120 /* @todo: Not sure what to do when there are successfully
2121 added disk images. Delete them also? For now we leave
2122 them. */
2123 if (!srcHdVBox.isNull())
2124 {
2125 /* Close any open src disks */
2126 rc = srcHdVBox->Close();
2127 CheckComRCThrowRC(rc);
2128 }
2129 if (!session.isNull())
2130 {
2131 /* If there is an open session, close them before doing
2132 anything further. */
2133 rc = session->Close();
2134 CheckComRCThrowRC(rc);
2135 }
2136 /* Unregister/Delete the failed machine */
2137 ComPtr<IMachine> failedMachine;
2138 rc = app->mVirtualBox->UnregisterMachine(newMachineId, failedMachine.asOutParam());
2139 CheckComRCThrowRC(rc);
2140 rc = failedMachine->DeleteSettings();
2141 CheckComRCThrowRC(rc);
2142 /* Throw the original error */
2143 throw;
2144 }
2145 }
2146 }
2147 catch(HRESULT aRC)
2148 {
2149 /* @todo: If we are here an error on importing of *one* virtual
2150 system has occurred. We didn't break now, but try to import the
2151 other virtual systems. This needs some further discussion. */
2152 rc = aRC;
2153 }
2154 }
2155
2156 task->rc = rc;
2157
2158 if (!task->progress.isNull())
2159 task->progress->notifyComplete (rc);
2160
2161 LogFlowFunc(("rc=%Rhrc\n", rc));
2162 LogFlowFuncLeave();
2163
2164 /// @todo ugly hack, fix ComAssert... (same as in HardDisk2::taskThread)
2165 #undef setError
2166
2167 return VINF_SUCCESS;
2168}
2169
2170// IVirtualSystemDescription constructor / destructor
2171////////////////////////////////////////////////////////////////////////////////
2172
2173DEFINE_EMPTY_CTOR_DTOR(VirtualSystemDescription)
2174struct shutup3 {};
2175
2176struct VirtualSystemDescription::Data
2177{
2178 list<VirtualSystemDescriptionEntry> descriptions;
2179 list<Utf8Str> warnings;
2180};
2181
2182HRESULT VirtualSystemDescription::init()
2183{
2184 /* Enclose the state transition NotReady->InInit->Ready */
2185 AutoInitSpan autoInitSpan(this);
2186 AssertReturn(autoInitSpan.isOk(), E_FAIL);
2187
2188 /* Initialize data */
2189 m = new Data();
2190
2191 /* Confirm a successful initialization */
2192 autoInitSpan.setSucceeded();
2193
2194 return S_OK;
2195}
2196
2197void VirtualSystemDescription::uninit()
2198{
2199 delete m;
2200 m = NULL;
2201}
2202
2203STDMETHODIMP VirtualSystemDescription::COMGETTER(Count)(ULONG *aCount)
2204{
2205 if (!aCount)
2206 return E_POINTER;
2207
2208 AutoCaller autoCaller(this);
2209 CheckComRCReturnRC(autoCaller.rc());
2210
2211 AutoReadLock alock(this);
2212
2213 *aCount = (ULONG)m->descriptions.size();
2214
2215 return S_OK;
2216}
2217
2218STDMETHODIMP VirtualSystemDescription::GetDescription(ComSafeArrayOut(VirtualSystemDescriptionType_T, aTypes),
2219 ComSafeArrayOut(BSTR, aRefs),
2220 ComSafeArrayOut(BSTR, aOrigValues),
2221 ComSafeArrayOut(BSTR, aConfigValues),
2222 ComSafeArrayOut(BSTR, aExtraConfigValues))
2223{
2224 if (ComSafeArrayOutIsNull(aTypes) ||
2225 ComSafeArrayOutIsNull(aRefs) ||
2226 ComSafeArrayOutIsNull(aOrigValues) ||
2227 ComSafeArrayOutIsNull(aConfigValues) ||
2228 ComSafeArrayOutIsNull(aExtraConfigValues))
2229 return E_POINTER;
2230
2231 AutoCaller autoCaller(this);
2232 CheckComRCReturnRC(autoCaller.rc());
2233
2234 AutoReadLock alock(this);
2235
2236 ULONG c = (ULONG)m->descriptions.size();
2237 com::SafeArray<VirtualSystemDescriptionType_T> sfaTypes(c);
2238 com::SafeArray<BSTR> sfaRefs(c);
2239 com::SafeArray<BSTR> sfaOrigValues(c);
2240 com::SafeArray<BSTR> sfaConfigValues(c);
2241 com::SafeArray<BSTR> sfaExtraConfigValues(c);
2242
2243 list<VirtualSystemDescriptionEntry>::const_iterator it;
2244 size_t i = 0;
2245 for (it = m->descriptions.begin();
2246 it != m->descriptions.end();
2247 ++it, ++i)
2248 {
2249 const VirtualSystemDescriptionEntry &vsde = (*it);
2250
2251 sfaTypes[i] = vsde.type;
2252
2253 Bstr bstr = vsde.strRef;
2254 bstr.cloneTo(&sfaRefs[i]);
2255
2256 bstr = vsde.strOrig;
2257 bstr.cloneTo(&sfaOrigValues[i]);
2258
2259 bstr = vsde.strConfig;
2260 bstr.cloneTo(&sfaConfigValues[i]);
2261
2262 bstr = vsde.strExtraConfig;
2263 bstr.cloneTo(&sfaExtraConfigValues[i]);
2264 }
2265
2266 sfaTypes.detachTo(ComSafeArrayOutArg(aTypes));
2267 sfaRefs.detachTo(ComSafeArrayOutArg(aRefs));
2268 sfaOrigValues.detachTo(ComSafeArrayOutArg(aOrigValues));
2269 sfaConfigValues.detachTo(ComSafeArrayOutArg(aConfigValues));
2270 sfaExtraConfigValues.detachTo(ComSafeArrayOutArg(aExtraConfigValues));
2271
2272 return S_OK;
2273}
2274
2275STDMETHODIMP VirtualSystemDescription::SetFinalValues(ComSafeArrayIn(BOOL, aEnabled),
2276 ComSafeArrayIn(IN_BSTR, argConfigValues),
2277 ComSafeArrayIn(IN_BSTR, argExtraConfigValues))
2278{
2279 CheckComArgSafeArrayNotNull(argConfigValues);
2280 CheckComArgSafeArrayNotNull(argExtraConfigValues);
2281
2282 AutoCaller autoCaller(this);
2283 CheckComRCReturnRC(autoCaller.rc());
2284
2285 AutoWriteLock alock(this);
2286
2287 com::SafeArray<IN_BSTR> aConfigValues(ComSafeArrayInArg(argConfigValues));
2288 com::SafeArray<IN_BSTR> aExtraConfigValues(ComSafeArrayInArg(argExtraConfigValues));
2289
2290 if ( (aConfigValues.size() != m->descriptions.size())
2291 || (aExtraConfigValues.size() != m->descriptions.size())
2292 )
2293 return E_INVALIDARG;
2294
2295 list<VirtualSystemDescriptionEntry>::iterator it;
2296 size_t i = 0;
2297 for (it = m->descriptions.begin();
2298 it != m->descriptions.end();
2299 ++it, ++i)
2300 {
2301 VirtualSystemDescriptionEntry& vsde = *it;
2302
2303 if (aEnabled[i])
2304 {
2305 vsde.strConfig = aConfigValues[i];
2306 vsde.strExtraConfig = aExtraConfigValues[i];
2307 }
2308 else
2309 vsde.type = VirtualSystemDescriptionType_Ignore;
2310 }
2311
2312 return S_OK;
2313}
2314
2315STDMETHODIMP VirtualSystemDescription::GetWarnings(ComSafeArrayOut(BSTR, aWarnings))
2316{
2317 if (ComSafeArrayOutIsNull(aWarnings))
2318 return E_POINTER;
2319
2320 AutoCaller autoCaller(this);
2321 CheckComRCReturnRC(autoCaller.rc());
2322
2323 AutoReadLock alock(this);
2324
2325 com::SafeArray<BSTR> sfaWarnings(m->warnings.size());
2326
2327 list<Utf8Str>::const_iterator it;
2328 size_t i = 0;
2329 for (it = m->warnings.begin();
2330 it != m->warnings.end();
2331 ++it, ++i)
2332 {
2333 Bstr bstr = *it;
2334 bstr.cloneTo(&sfaWarnings[i]);
2335 }
2336
2337 sfaWarnings.detachTo(ComSafeArrayOutArg(aWarnings));
2338
2339 return S_OK;
2340}
2341
2342void VirtualSystemDescription::addEntry(VirtualSystemDescriptionType_T aType,
2343 const Utf8Str &strRef,
2344 const Utf8Str &aOrigValue,
2345 const Utf8Str &aAutoValue,
2346 const Utf8Str &strExtraConfig /*= ""*/)
2347{
2348 VirtualSystemDescriptionEntry vsde;
2349 vsde.ulIndex = m->descriptions.size(); // each entry gets an index so the client side can reference them
2350 vsde.type = aType;
2351 vsde.strRef = strRef;
2352 vsde.strOrig = aOrigValue;
2353 vsde.strConfig = aAutoValue;
2354 vsde.strExtraConfig = strExtraConfig;
2355
2356 m->descriptions.push_back(vsde);
2357}
2358
2359void VirtualSystemDescription::addWarning(const char* aWarning, ...)
2360{
2361 va_list args;
2362 va_start(args, aWarning);
2363 Utf8StrFmtVA str(aWarning, args);
2364 va_end(args);
2365 m->warnings.push_back(str);
2366}
2367
2368std::list<VirtualSystemDescriptionEntry*> VirtualSystemDescription::findByType(VirtualSystemDescriptionType_T aType)
2369{
2370 std::list<VirtualSystemDescriptionEntry*> vsd;
2371 list<VirtualSystemDescriptionEntry>::iterator it;
2372 for (it = m->descriptions.begin();
2373 it != m->descriptions.end();
2374 ++it)
2375 if (it->type == aType)
2376 vsd.push_back(&(*it));
2377
2378 return vsd;
2379}
2380
2381const VirtualSystemDescriptionEntry* VirtualSystemDescription::findControllerFromID(uint32_t id)
2382{
2383 Utf8Str strRef = toString<uint32_t>(id);
2384 list<VirtualSystemDescriptionEntry>::const_iterator it;
2385 for (it = m->descriptions.begin();
2386 it != m->descriptions.end();
2387 ++it)
2388 {
2389 switch (it->type)
2390 {
2391 case VirtualSystemDescriptionType_HardDiskControllerIDE:
2392 case VirtualSystemDescriptionType_HardDiskControllerSATA:
2393 case VirtualSystemDescriptionType_HardDiskControllerSCSI:
2394 if (it->strRef == strRef)
2395 return &(*it);
2396 break;
2397 }
2398 }
2399
2400 return NULL;
2401}
2402
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