VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/ApplianceImplImport.cpp@ 49047

Last change on this file since 49047 was 49039, checked in by vboxsync, 11 years ago

IPRT: Filename extension versus suffix cleanup, long overdue.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 156.8 KB
Line 
1/* $Id: ApplianceImplImport.cpp 49039 2013-10-10 18:27:32Z vboxsync $ */
2/** @file
3 *
4 * IAppliance and IVirtualSystem COM class implementations.
5 */
6
7/*
8 * Copyright (C) 2008-2013 Oracle Corporation
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
19#include <iprt/path.h>
20#include <iprt/dir.h>
21#include <iprt/file.h>
22#include <iprt/s3.h>
23#include <iprt/sha.h>
24#include <iprt/manifest.h>
25#include <iprt/tar.h>
26#include <iprt/stream.h>
27
28#include <VBox/vd.h>
29#include <VBox/com/array.h>
30
31#include "ApplianceImpl.h"
32#include "VirtualBoxImpl.h"
33#include "GuestOSTypeImpl.h"
34#include "ProgressImpl.h"
35#include "MachineImpl.h"
36#include "MediumImpl.h"
37#include "MediumFormatImpl.h"
38#include "SystemPropertiesImpl.h"
39#include "HostImpl.h"
40
41#include "AutoCaller.h"
42#include "Logging.h"
43
44#include "ApplianceImplPrivate.h"
45
46#include <VBox/param.h>
47#include <VBox/version.h>
48#include <VBox/settings.h>
49
50#include <set>
51
52using namespace std;
53
54////////////////////////////////////////////////////////////////////////////////
55//
56// IAppliance public methods
57//
58////////////////////////////////////////////////////////////////////////////////
59
60/**
61 * Public method implementation. This opens the OVF with ovfreader.cpp.
62 * Thread implementation is in Appliance::readImpl().
63 *
64 * @param path
65 * @return
66 */
67STDMETHODIMP Appliance::Read(IN_BSTR path, IProgress **aProgress)
68{
69 if (!path) return E_POINTER;
70 CheckComArgOutPointerValid(aProgress);
71
72 AutoCaller autoCaller(this);
73 if (FAILED(autoCaller.rc())) return autoCaller.rc();
74
75 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
76
77 if (!isApplianceIdle())
78 return E_ACCESSDENIED;
79
80 if (m->pReader)
81 {
82 delete m->pReader;
83 m->pReader = NULL;
84 }
85
86 // see if we can handle this file; for now we insist it has an ovf/ova extension
87 Utf8Str strPath (path);
88 if (!( strPath.endsWith(".ovf", Utf8Str::CaseInsensitive)
89 || strPath.endsWith(".ova", Utf8Str::CaseInsensitive)))
90 return setError(VBOX_E_FILE_ERROR,
91 tr("Appliance file must have .ovf extension"));
92
93 ComObjPtr<Progress> progress;
94 HRESULT rc = S_OK;
95 try
96 {
97 /* Parse all necessary info out of the URI */
98 parseURI(strPath, m->locInfo);
99 rc = readImpl(m->locInfo, progress);
100 }
101 catch (HRESULT aRC)
102 {
103 rc = aRC;
104 }
105
106 if (SUCCEEDED(rc))
107 /* Return progress to the caller */
108 progress.queryInterfaceTo(aProgress);
109
110 return S_OK;
111}
112
113/**
114 * Public method implementation. This looks at the output of ovfreader.cpp and creates
115 * VirtualSystemDescription instances.
116 * @return
117 */
118STDMETHODIMP Appliance::Interpret()
119{
120 // @todo:
121 // - don't use COM methods but the methods directly (faster, but needs appropriate
122 // locking of that objects itself (s. HardDisk))
123 // - Appropriate handle errors like not supported file formats
124 AutoCaller autoCaller(this);
125 if (FAILED(autoCaller.rc())) return autoCaller.rc();
126
127 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
128
129 if (!isApplianceIdle())
130 return E_ACCESSDENIED;
131
132 HRESULT rc = S_OK;
133
134 /* Clear any previous virtual system descriptions */
135 m->virtualSystemDescriptions.clear();
136
137 if (!m->pReader)
138 return setError(E_FAIL,
139 tr("Cannot interpret appliance without reading it first (call read() before interpret())"));
140
141 // Change the appliance state so we can safely leave the lock while doing time-consuming
142 // disk imports; also the below method calls do all kinds of locking which conflicts with
143 // the appliance object lock
144 m->state = Data::ApplianceImporting;
145 alock.release();
146
147 /* Try/catch so we can clean up on error */
148 try
149 {
150 list<ovf::VirtualSystem>::const_iterator it;
151 /* Iterate through all virtual systems */
152 for (it = m->pReader->m_llVirtualSystems.begin();
153 it != m->pReader->m_llVirtualSystems.end();
154 ++it)
155 {
156 const ovf::VirtualSystem &vsysThis = *it;
157
158 ComObjPtr<VirtualSystemDescription> pNewDesc;
159 rc = pNewDesc.createObject();
160 if (FAILED(rc)) throw rc;
161 rc = pNewDesc->init();
162 if (FAILED(rc)) throw rc;
163
164 // if the virtual system in OVF had a <vbox:Machine> element, have the
165 // VirtualBox settings code parse that XML now
166 if (vsysThis.pelmVboxMachine)
167 pNewDesc->importVboxMachineXML(*vsysThis.pelmVboxMachine);
168
169 // Guest OS type
170 // This is taken from one of three places, in this order:
171 Utf8Str strOsTypeVBox;
172 Utf8StrFmt strCIMOSType("%RU32", (uint32_t)vsysThis.cimos);
173 // 1) If there is a <vbox:Machine>, then use the type from there.
174 if ( vsysThis.pelmVboxMachine
175 && pNewDesc->m->pConfig->machineUserData.strOsType.isNotEmpty()
176 )
177 strOsTypeVBox = pNewDesc->m->pConfig->machineUserData.strOsType;
178 // 2) Otherwise, if there is OperatingSystemSection/vbox:OSType, use that one.
179 else if (vsysThis.strTypeVbox.isNotEmpty()) // OVFReader has found vbox:OSType
180 strOsTypeVBox = vsysThis.strTypeVbox;
181 // 3) Otherwise, make a best guess what the vbox type is from the OVF (CIM) OS type.
182 else
183 convertCIMOSType2VBoxOSType(strOsTypeVBox, vsysThis.cimos, vsysThis.strCimosDesc);
184 pNewDesc->addEntry(VirtualSystemDescriptionType_OS,
185 "",
186 strCIMOSType,
187 strOsTypeVBox);
188
189 /* VM name */
190 Utf8Str nameVBox;
191 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
192 if ( vsysThis.pelmVboxMachine
193 && pNewDesc->m->pConfig->machineUserData.strName.isNotEmpty())
194 nameVBox = pNewDesc->m->pConfig->machineUserData.strName;
195 else
196 nameVBox = vsysThis.strName;
197 /* If there isn't any name specified create a default one out
198 * of the OS type */
199 if (nameVBox.isEmpty())
200 nameVBox = strOsTypeVBox;
201 searchUniqueVMName(nameVBox);
202 pNewDesc->addEntry(VirtualSystemDescriptionType_Name,
203 "",
204 vsysThis.strName,
205 nameVBox);
206
207 /* Based on the VM name, create a target machine path. */
208 Bstr bstrMachineFilename;
209 rc = mVirtualBox->ComposeMachineFilename(Bstr(nameVBox).raw(),
210 NULL /* aGroup */,
211 NULL /* aCreateFlags */,
212 NULL /* aBaseFolder */,
213 bstrMachineFilename.asOutParam());
214 if (FAILED(rc)) throw rc;
215 /* Determine the machine folder from that */
216 Utf8Str strMachineFolder = Utf8Str(bstrMachineFilename).stripFilename();
217
218 /* VM Product */
219 if (!vsysThis.strProduct.isEmpty())
220 pNewDesc->addEntry(VirtualSystemDescriptionType_Product,
221 "",
222 vsysThis.strProduct,
223 vsysThis.strProduct);
224
225 /* VM Vendor */
226 if (!vsysThis.strVendor.isEmpty())
227 pNewDesc->addEntry(VirtualSystemDescriptionType_Vendor,
228 "",
229 vsysThis.strVendor,
230 vsysThis.strVendor);
231
232 /* VM Version */
233 if (!vsysThis.strVersion.isEmpty())
234 pNewDesc->addEntry(VirtualSystemDescriptionType_Version,
235 "",
236 vsysThis.strVersion,
237 vsysThis.strVersion);
238
239 /* VM ProductUrl */
240 if (!vsysThis.strProductUrl.isEmpty())
241 pNewDesc->addEntry(VirtualSystemDescriptionType_ProductUrl,
242 "",
243 vsysThis.strProductUrl,
244 vsysThis.strProductUrl);
245
246 /* VM VendorUrl */
247 if (!vsysThis.strVendorUrl.isEmpty())
248 pNewDesc->addEntry(VirtualSystemDescriptionType_VendorUrl,
249 "",
250 vsysThis.strVendorUrl,
251 vsysThis.strVendorUrl);
252
253 /* VM description */
254 if (!vsysThis.strDescription.isEmpty())
255 pNewDesc->addEntry(VirtualSystemDescriptionType_Description,
256 "",
257 vsysThis.strDescription,
258 vsysThis.strDescription);
259
260 /* VM license */
261 if (!vsysThis.strLicenseText.isEmpty())
262 pNewDesc->addEntry(VirtualSystemDescriptionType_License,
263 "",
264 vsysThis.strLicenseText,
265 vsysThis.strLicenseText);
266
267 /* Now that we know the OS type, get our internal defaults based on that. */
268 ComPtr<IGuestOSType> pGuestOSType;
269 rc = mVirtualBox->GetGuestOSType(Bstr(strOsTypeVBox).raw(), pGuestOSType.asOutParam());
270 if (FAILED(rc)) throw rc;
271
272 /* CPU count */
273 ULONG cpuCountVBox;
274 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
275 if ( vsysThis.pelmVboxMachine
276 && pNewDesc->m->pConfig->hardwareMachine.cCPUs)
277 cpuCountVBox = pNewDesc->m->pConfig->hardwareMachine.cCPUs;
278 else
279 cpuCountVBox = vsysThis.cCPUs;
280 /* Check for the constraints */
281 if (cpuCountVBox > SchemaDefs::MaxCPUCount)
282 {
283 addWarning(tr("The virtual system \"%s\" claims support for %u CPU's, but VirtualBox has support for "
284 "max %u CPU's only."),
285 vsysThis.strName.c_str(), cpuCountVBox, SchemaDefs::MaxCPUCount);
286 cpuCountVBox = SchemaDefs::MaxCPUCount;
287 }
288 if (vsysThis.cCPUs == 0)
289 cpuCountVBox = 1;
290 pNewDesc->addEntry(VirtualSystemDescriptionType_CPU,
291 "",
292 Utf8StrFmt("%RU32", (uint32_t)vsysThis.cCPUs),
293 Utf8StrFmt("%RU32", (uint32_t)cpuCountVBox));
294
295 /* RAM */
296 uint64_t ullMemSizeVBox;
297 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
298 if ( vsysThis.pelmVboxMachine
299 && pNewDesc->m->pConfig->hardwareMachine.ulMemorySizeMB)
300 ullMemSizeVBox = pNewDesc->m->pConfig->hardwareMachine.ulMemorySizeMB;
301 else
302 ullMemSizeVBox = vsysThis.ullMemorySize / _1M;
303 /* Check for the constraints */
304 if ( ullMemSizeVBox != 0
305 && ( ullMemSizeVBox < MM_RAM_MIN_IN_MB
306 || ullMemSizeVBox > MM_RAM_MAX_IN_MB
307 )
308 )
309 {
310 addWarning(tr("The virtual system \"%s\" claims support for %llu MB RAM size, but VirtualBox has "
311 "support for min %u & max %u MB RAM size only."),
312 vsysThis.strName.c_str(), ullMemSizeVBox, MM_RAM_MIN_IN_MB, MM_RAM_MAX_IN_MB);
313 ullMemSizeVBox = RT_MIN(RT_MAX(ullMemSizeVBox, MM_RAM_MIN_IN_MB), MM_RAM_MAX_IN_MB);
314 }
315 if (vsysThis.ullMemorySize == 0)
316 {
317 /* If the RAM of the OVF is zero, use our predefined values */
318 ULONG memSizeVBox2;
319 rc = pGuestOSType->COMGETTER(RecommendedRAM)(&memSizeVBox2);
320 if (FAILED(rc)) throw rc;
321 /* VBox stores that in MByte */
322 ullMemSizeVBox = (uint64_t)memSizeVBox2;
323 }
324 pNewDesc->addEntry(VirtualSystemDescriptionType_Memory,
325 "",
326 Utf8StrFmt("%RU64", (uint64_t)vsysThis.ullMemorySize),
327 Utf8StrFmt("%RU64", (uint64_t)ullMemSizeVBox));
328
329 /* Audio */
330 Utf8Str strSoundCard;
331 Utf8Str strSoundCardOrig;
332 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
333 if ( vsysThis.pelmVboxMachine
334 && pNewDesc->m->pConfig->hardwareMachine.audioAdapter.fEnabled)
335 {
336 strSoundCard = Utf8StrFmt("%RU32",
337 (uint32_t)pNewDesc->m->pConfig->hardwareMachine.audioAdapter.controllerType);
338 }
339 else if (vsysThis.strSoundCardType.isNotEmpty())
340 {
341 /* Set the AC97 always for the simple OVF case.
342 * @todo: figure out the hardware which could be possible */
343 strSoundCard = Utf8StrFmt("%RU32", (uint32_t)AudioControllerType_AC97);
344 strSoundCardOrig = vsysThis.strSoundCardType;
345 }
346 if (strSoundCard.isNotEmpty())
347 pNewDesc->addEntry(VirtualSystemDescriptionType_SoundCard,
348 "",
349 strSoundCardOrig,
350 strSoundCard);
351
352#ifdef VBOX_WITH_USB
353 /* USB Controller */
354 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
355 if ( ( vsysThis.pelmVboxMachine
356 && pNewDesc->m->pConfig->hardwareMachine.usbSettings.llUSBControllers.size() > 0)
357 || vsysThis.fHasUsbController)
358 pNewDesc->addEntry(VirtualSystemDescriptionType_USBController, "", "", "");
359#endif /* VBOX_WITH_USB */
360
361 /* Network Controller */
362 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
363 if (vsysThis.pelmVboxMachine)
364 {
365 uint32_t maxNetworkAdapters = Global::getMaxNetworkAdapters(pNewDesc->m->pConfig->hardwareMachine.chipsetType);
366
367 const settings::NetworkAdaptersList &llNetworkAdapters = pNewDesc->m->pConfig->hardwareMachine.llNetworkAdapters;
368 /* Check for the constrains */
369 if (llNetworkAdapters.size() > maxNetworkAdapters)
370 addWarning(tr("The virtual system \"%s\" claims support for %zu network adapters, but VirtualBox "
371 "has support for max %u network adapter only."),
372 vsysThis.strName.c_str(), llNetworkAdapters.size(), maxNetworkAdapters);
373 /* Iterate through all network adapters. */
374 settings::NetworkAdaptersList::const_iterator it1;
375 size_t a = 0;
376 for (it1 = llNetworkAdapters.begin();
377 it1 != llNetworkAdapters.end() && a < maxNetworkAdapters;
378 ++it1, ++a)
379 {
380 if (it1->fEnabled)
381 {
382 Utf8Str strMode = convertNetworkAttachmentTypeToString(it1->mode);
383 pNewDesc->addEntry(VirtualSystemDescriptionType_NetworkAdapter,
384 "", // ref
385 strMode, // orig
386 Utf8StrFmt("%RU32", (uint32_t)it1->type), // conf
387 0,
388 Utf8StrFmt("slot=%RU32;type=%s", it1->ulSlot, strMode.c_str())); // extra conf
389 }
390 }
391 }
392 /* else we use the ovf configuration. */
393 else if (size_t cEthernetAdapters = vsysThis.llEthernetAdapters.size() > 0)
394 {
395 uint32_t maxNetworkAdapters = Global::getMaxNetworkAdapters(ChipsetType_PIIX3);
396
397 /* Check for the constrains */
398 if (cEthernetAdapters > maxNetworkAdapters)
399 addWarning(tr("The virtual system \"%s\" claims support for %zu network adapters, but VirtualBox "
400 "has support for max %u network adapter only."),
401 vsysThis.strName.c_str(), cEthernetAdapters, maxNetworkAdapters);
402
403 /* Get the default network adapter type for the selected guest OS */
404 NetworkAdapterType_T defaultAdapterVBox = NetworkAdapterType_Am79C970A;
405 rc = pGuestOSType->COMGETTER(AdapterType)(&defaultAdapterVBox);
406 if (FAILED(rc)) throw rc;
407
408 ovf::EthernetAdaptersList::const_iterator itEA;
409 /* Iterate through all abstract networks. Ignore network cards
410 * which exceed the limit of VirtualBox. */
411 size_t a = 0;
412 for (itEA = vsysThis.llEthernetAdapters.begin();
413 itEA != vsysThis.llEthernetAdapters.end() && a < maxNetworkAdapters;
414 ++itEA, ++a)
415 {
416 const ovf::EthernetAdapter &ea = *itEA; // logical network to connect to
417 Utf8Str strNetwork = ea.strNetworkName;
418 // make sure it's one of these two
419 if ( (strNetwork.compare("Null", Utf8Str::CaseInsensitive))
420 && (strNetwork.compare("NAT", Utf8Str::CaseInsensitive))
421 && (strNetwork.compare("Bridged", Utf8Str::CaseInsensitive))
422 && (strNetwork.compare("Internal", Utf8Str::CaseInsensitive))
423 && (strNetwork.compare("HostOnly", Utf8Str::CaseInsensitive))
424 && (strNetwork.compare("Generic", Utf8Str::CaseInsensitive))
425 )
426 strNetwork = "Bridged"; // VMware assumes this is the default apparently
427
428 /* Figure out the hardware type */
429 NetworkAdapterType_T nwAdapterVBox = defaultAdapterVBox;
430 if (!ea.strAdapterType.compare("PCNet32", Utf8Str::CaseInsensitive))
431 {
432 /* If the default adapter is already one of the two
433 * PCNet adapters use the default one. If not use the
434 * Am79C970A as fallback. */
435 if (!(defaultAdapterVBox == NetworkAdapterType_Am79C970A ||
436 defaultAdapterVBox == NetworkAdapterType_Am79C973))
437 nwAdapterVBox = NetworkAdapterType_Am79C970A;
438 }
439#ifdef VBOX_WITH_E1000
440 /* VMWare accidentally write this with VirtualCenter 3.5,
441 so make sure in this case always to use the VMWare one */
442 else if (!ea.strAdapterType.compare("E10000", Utf8Str::CaseInsensitive))
443 nwAdapterVBox = NetworkAdapterType_I82545EM;
444 else if (!ea.strAdapterType.compare("E1000", Utf8Str::CaseInsensitive))
445 {
446 /* Check if this OVF was written by VirtualBox */
447 if (Utf8Str(vsysThis.strVirtualSystemType).contains("virtualbox", Utf8Str::CaseInsensitive))
448 {
449 /* If the default adapter is already one of the three
450 * E1000 adapters use the default one. If not use the
451 * I82545EM as fallback. */
452 if (!(defaultAdapterVBox == NetworkAdapterType_I82540EM ||
453 defaultAdapterVBox == NetworkAdapterType_I82543GC ||
454 defaultAdapterVBox == NetworkAdapterType_I82545EM))
455 nwAdapterVBox = NetworkAdapterType_I82540EM;
456 }
457 else
458 /* Always use this one since it's what VMware uses */
459 nwAdapterVBox = NetworkAdapterType_I82545EM;
460 }
461#endif /* VBOX_WITH_E1000 */
462
463 pNewDesc->addEntry(VirtualSystemDescriptionType_NetworkAdapter,
464 "", // ref
465 ea.strNetworkName, // orig
466 Utf8StrFmt("%RU32", (uint32_t)nwAdapterVBox), // conf
467 0,
468 Utf8StrFmt("type=%s", strNetwork.c_str())); // extra conf
469 }
470 }
471
472 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
473 bool fFloppy = false;
474 bool fDVD = false;
475 if (vsysThis.pelmVboxMachine)
476 {
477 settings::StorageControllersList &llControllers = pNewDesc->m->pConfig->storageMachine.llStorageControllers;
478 settings::StorageControllersList::iterator it3;
479 for (it3 = llControllers.begin();
480 it3 != llControllers.end();
481 ++it3)
482 {
483 settings::AttachedDevicesList &llAttachments = it3->llAttachedDevices;
484 settings::AttachedDevicesList::iterator it4;
485 for (it4 = llAttachments.begin();
486 it4 != llAttachments.end();
487 ++it4)
488 {
489 fDVD |= it4->deviceType == DeviceType_DVD;
490 fFloppy |= it4->deviceType == DeviceType_Floppy;
491 if (fFloppy && fDVD)
492 break;
493 }
494 if (fFloppy && fDVD)
495 break;
496 }
497 }
498 else
499 {
500 fFloppy = vsysThis.fHasFloppyDrive;
501 fDVD = vsysThis.fHasCdromDrive;
502 }
503 /* Floppy Drive */
504 if (fFloppy)
505 pNewDesc->addEntry(VirtualSystemDescriptionType_Floppy, "", "", "");
506 /* CD Drive */
507 if (fDVD)
508 pNewDesc->addEntry(VirtualSystemDescriptionType_CDROM, "", "", "");
509
510 /* Hard disk Controller */
511 uint16_t cIDEused = 0;
512 uint16_t cSATAused = 0; NOREF(cSATAused);
513 uint16_t cSCSIused = 0; NOREF(cSCSIused);
514 ovf::ControllersMap::const_iterator hdcIt;
515 /* Iterate through all hard disk controllers */
516 for (hdcIt = vsysThis.mapControllers.begin();
517 hdcIt != vsysThis.mapControllers.end();
518 ++hdcIt)
519 {
520 const ovf::HardDiskController &hdc = hdcIt->second;
521 Utf8Str strControllerID = Utf8StrFmt("%RI32", (uint32_t)hdc.idController);
522
523 switch (hdc.system)
524 {
525 case ovf::HardDiskController::IDE:
526 /* Check for the constrains */
527 if (cIDEused < 4)
528 {
529 // @todo: figure out the IDE types
530 /* Use PIIX4 as default */
531 Utf8Str strType = "PIIX4";
532 if (!hdc.strControllerType.compare("PIIX3", Utf8Str::CaseInsensitive))
533 strType = "PIIX3";
534 else if (!hdc.strControllerType.compare("ICH6", Utf8Str::CaseInsensitive))
535 strType = "ICH6";
536 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
537 strControllerID, // strRef
538 hdc.strControllerType, // aOvfValue
539 strType); // aVboxValue
540 }
541 else
542 /* Warn only once */
543 if (cIDEused == 2)
544 addWarning(tr("The virtual \"%s\" system requests support for more than two "
545 "IDE controller channels, but VirtualBox supports only two."),
546 vsysThis.strName.c_str());
547
548 ++cIDEused;
549 break;
550
551 case ovf::HardDiskController::SATA:
552 /* Check for the constrains */
553 if (cSATAused < 1)
554 {
555 // @todo: figure out the SATA types
556 /* We only support a plain AHCI controller, so use them always */
557 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerSATA,
558 strControllerID,
559 hdc.strControllerType,
560 "AHCI");
561 }
562 else
563 {
564 /* Warn only once */
565 if (cSATAused == 1)
566 addWarning(tr("The virtual system \"%s\" requests support for more than one "
567 "SATA controller, but VirtualBox has support for only one"),
568 vsysThis.strName.c_str());
569
570 }
571 ++cSATAused;
572 break;
573
574 case ovf::HardDiskController::SCSI:
575 /* Check for the constrains */
576 if (cSCSIused < 1)
577 {
578 VirtualSystemDescriptionType_T vsdet = VirtualSystemDescriptionType_HardDiskControllerSCSI;
579 Utf8Str hdcController = "LsiLogic";
580 if (!hdc.strControllerType.compare("lsilogicsas", Utf8Str::CaseInsensitive))
581 {
582 // OVF considers SAS a variant of SCSI but VirtualBox considers it a class of its own
583 vsdet = VirtualSystemDescriptionType_HardDiskControllerSAS;
584 hdcController = "LsiLogicSas";
585 }
586 else if (!hdc.strControllerType.compare("BusLogic", Utf8Str::CaseInsensitive))
587 hdcController = "BusLogic";
588 pNewDesc->addEntry(vsdet,
589 strControllerID,
590 hdc.strControllerType,
591 hdcController);
592 }
593 else
594 addWarning(tr("The virtual system \"%s\" requests support for an additional "
595 "SCSI controller of type \"%s\" with ID %s, but VirtualBox presently "
596 "supports only one SCSI controller."),
597 vsysThis.strName.c_str(),
598 hdc.strControllerType.c_str(),
599 strControllerID.c_str());
600 ++cSCSIused;
601 break;
602 }
603 }
604
605 /* Hard disks */
606 if (vsysThis.mapVirtualDisks.size() > 0)
607 {
608 ovf::VirtualDisksMap::const_iterator itVD;
609 /* Iterate through all hard disks ()*/
610 for (itVD = vsysThis.mapVirtualDisks.begin();
611 itVD != vsysThis.mapVirtualDisks.end();
612 ++itVD)
613 {
614 const ovf::VirtualDisk &hd = itVD->second;
615 /* Get the associated disk image */
616 ovf::DiskImage di;
617 std::map<RTCString, ovf::DiskImage>::iterator foundDisk;
618
619 foundDisk = m->pReader->m_mapDisks.find(hd.strDiskId);
620 if (foundDisk == m->pReader->m_mapDisks.end())
621 continue;
622 else
623 {
624 di = foundDisk->second;
625 }
626
627 /*
628 * Figure out from URI which format the image of disk has.
629 * URI must have inside section <Disk> .
630 * But there aren't strong requirements about correspondence one URI for one disk virtual format.
631 * So possibly, we aren't able to recognize some URIs.
632 */
633 Utf8Str vdf = typeOfVirtualDiskFormatFromURI(di.strFormat);
634
635 /*
636 * fallback, if we can't determine virtual disk format using URI from the attribute ovf:format
637 * in the corresponding section <Disk> in the OVF file.
638 */
639 if (vdf.isEmpty())
640 {
641 /* Figure out from extension which format the image of disk has. */
642 {
643 char *pszExt = RTPathSuffix(di.strHref.c_str());
644 if (pszExt)
645 pszExt++;
646 /* Get the system properties. */
647 SystemProperties *pSysProps = mVirtualBox->getSystemProperties();
648 ComObjPtr<MediumFormat> trgFormat = pSysProps->mediumFormatFromExtension(pszExt);
649 if (trgFormat.isNull())
650 {
651 throw setError(E_FAIL,
652 tr("Internal inconsistency looking up medium format for the disk image '%s'"),
653 di.strHref.c_str());
654 }
655
656 Bstr bstrFormatName;
657 rc = trgFormat->COMGETTER(Name)(bstrFormatName.asOutParam());
658 if (FAILED(rc))
659 throw rc;
660
661 vdf = Utf8Str(bstrFormatName);
662 }
663 }
664
665 // @todo:
666 // - figure out all possible vmdk formats we also support
667 // - figure out if there is a url specifier for vhd already
668 // - we need a url specifier for the vdi format
669
670 if (vdf.compare("VMDK", Utf8Str::CaseInsensitive) == 0)
671 {
672 /* If the href is empty use the VM name as filename */
673 Utf8Str strFilename = di.strHref;
674 if (!strFilename.length())
675 strFilename = Utf8StrFmt("%s.vmdk", hd.strDiskId.c_str());
676
677 Utf8Str strTargetPath = Utf8Str(strMachineFolder);
678 strTargetPath.append(RTPATH_DELIMITER).append(di.strHref);
679 searchUniqueDiskImageFilePath(strTargetPath);
680
681 /* find the description for the hard disk controller
682 * that has the same ID as hd.idController */
683 const VirtualSystemDescriptionEntry *pController;
684 if (!(pController = pNewDesc->findControllerFromID(hd.idController)))
685 throw setError(E_FAIL,
686 tr("Cannot find hard disk controller with OVF instance ID %RI32 "
687 "to which disk \"%s\" should be attached"),
688 hd.idController,
689 di.strHref.c_str());
690
691 /* controller to attach to, and the bus within that controller */
692 Utf8StrFmt strExtraConfig("controller=%RI16;channel=%RI16",
693 pController->ulIndex,
694 hd.ulAddressOnParent);
695 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskImage,
696 hd.strDiskId,
697 di.strHref,
698 strTargetPath,
699 di.ulSuggestedSizeMB,
700 strExtraConfig);
701 }
702 else if (vdf.compare("RAW", Utf8Str::CaseInsensitive) == 0)
703 {
704 /* If the href is empty use the VM name as filename */
705 Utf8Str strFilename = di.strHref;
706 if (!strFilename.length())
707 strFilename = Utf8StrFmt("%s.iso", hd.strDiskId.c_str());
708
709 Utf8Str strTargetPath = Utf8Str(strMachineFolder)
710 .append(RTPATH_DELIMITER)
711 .append(di.strHref);
712 searchUniqueDiskImageFilePath(strTargetPath);
713
714 /* find the description for the hard disk controller
715 * that has the same ID as hd.idController */
716 const VirtualSystemDescriptionEntry *pController;
717 if (!(pController = pNewDesc->findControllerFromID(hd.idController)))
718 throw setError(E_FAIL,
719 tr("Cannot find disk controller with OVF instance ID %RI32 "
720 "to which disk \"%s\" should be attached"),
721 hd.idController,
722 di.strHref.c_str());
723
724 /* controller to attach to, and the bus within that controller */
725 Utf8StrFmt strExtraConfig("controller=%RI16;channel=%RI16",
726 pController->ulIndex,
727 hd.ulAddressOnParent);
728 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskImage,
729 hd.strDiskId,
730 di.strHref,
731 strTargetPath,
732 di.ulSuggestedSizeMB,
733 strExtraConfig);
734 }
735 else
736 throw setError(VBOX_E_FILE_ERROR,
737 tr("Unsupported format for virtual disk image %s in OVF: \"%s\""),
738 di.strHref.c_str(),
739 di.strFormat.c_str());
740 }
741 }
742
743 m->virtualSystemDescriptions.push_back(pNewDesc);
744 }
745 }
746 catch (HRESULT aRC)
747 {
748 /* On error we clear the list & return */
749 m->virtualSystemDescriptions.clear();
750 rc = aRC;
751 }
752
753 // reset the appliance state
754 alock.acquire();
755 m->state = Data::ApplianceIdle;
756
757 return rc;
758}
759
760/**
761 * Public method implementation. This creates one or more new machines according to the
762 * VirtualSystemScription instances created by Appliance::Interpret().
763 * Thread implementation is in Appliance::importImpl().
764 * @param aProgress
765 * @return
766 */
767STDMETHODIMP Appliance::ImportMachines(ComSafeArrayIn(ImportOptions_T, options), IProgress **aProgress)
768{
769 CheckComArgOutPointerValid(aProgress);
770
771 AutoCaller autoCaller(this);
772 if (FAILED(autoCaller.rc())) return autoCaller.rc();
773
774 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
775
776 if (options != NULL)
777 m->optListImport = com::SafeArray<ImportOptions_T>(ComSafeArrayInArg(options)).toList();
778
779 AssertReturn(!(m->optListImport.contains(ImportOptions_KeepAllMACs) && m->optListImport.contains(ImportOptions_KeepNATMACs)), E_INVALIDARG);
780
781 // do not allow entering this method if the appliance is busy reading or writing
782 if (!isApplianceIdle())
783 return E_ACCESSDENIED;
784
785 if (!m->pReader)
786 return setError(E_FAIL,
787 tr("Cannot import machines without reading it first (call read() before importMachines())"));
788
789 ComObjPtr<Progress> progress;
790 HRESULT rc = S_OK;
791 try
792 {
793 rc = importImpl(m->locInfo, progress);
794 }
795 catch (HRESULT aRC)
796 {
797 rc = aRC;
798 }
799
800 if (SUCCEEDED(rc))
801 /* Return progress to the caller */
802 progress.queryInterfaceTo(aProgress);
803
804 return rc;
805}
806
807////////////////////////////////////////////////////////////////////////////////
808//
809// Appliance private methods
810//
811////////////////////////////////////////////////////////////////////////////////
812
813HRESULT Appliance::preCheckImageAvailability(PSHASTORAGE pSHAStorage,
814 RTCString &availableImage)
815{
816 HRESULT rc = S_OK;
817 RTTAR tar = (RTTAR)pSHAStorage->pVDImageIfaces->pvUser;
818 char *pszFilename = 0;
819
820 int vrc = RTTarCurrentFile(tar, &pszFilename);
821
822 if (RT_FAILURE(vrc))
823 {
824 throw setError(VBOX_E_FILE_ERROR,
825 tr("Could not open the current file in the OVA package (%Rrc)"), vrc);
826 }
827 else
828 {
829 if (vrc == VINF_TAR_DIR_PATH)
830 {
831 throw setError(VBOX_E_FILE_ERROR,
832 tr("Empty directory folder (%s) isn't allowed in the OVA package (%Rrc)"),
833 pszFilename,
834 vrc);
835 }
836 }
837
838 availableImage = pszFilename;
839
840 return rc;
841}
842
843/*******************************************************************************
844 * Read stuff
845 ******************************************************************************/
846
847/**
848 * Implementation for reading an OVF. This starts a new thread which will call
849 * Appliance::taskThreadImportOrExport() which will then call readFS() or readS3().
850 * This will then open the OVF with ovfreader.cpp.
851 *
852 * This is in a separate private method because it is used from three locations:
853 *
854 * 1) from the public Appliance::Read().
855 *
856 * 2) in a second worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl(), which
857 * called Appliance::readFSOVA(), which called Appliance::importImpl(), which then called this again.
858 *
859 * 3) from Appliance::readS3(), which got called from a previous instance of Appliance::taskThreadImportOrExport().
860 *
861 * @param aLocInfo
862 * @param aProgress
863 * @return
864 */
865HRESULT Appliance::readImpl(const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
866{
867 BstrFmt bstrDesc = BstrFmt(tr("Reading appliance '%s'"),
868 aLocInfo.strPath.c_str());
869 HRESULT rc;
870 /* Create the progress object */
871 aProgress.createObject();
872 if (aLocInfo.storageType == VFSType_File)
873 /* 1 operation only */
874 rc = aProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
875 bstrDesc.raw(),
876 TRUE /* aCancelable */);
877 else
878 /* 4/5 is downloading, 1/5 is reading */
879 rc = aProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
880 bstrDesc.raw(),
881 TRUE /* aCancelable */,
882 2, // ULONG cOperations,
883 5, // ULONG ulTotalOperationsWeight,
884 BstrFmt(tr("Download appliance '%s'"),
885 aLocInfo.strPath.c_str()).raw(), // CBSTR bstrFirstOperationDescription,
886 4); // ULONG ulFirstOperationWeight,
887 if (FAILED(rc)) throw rc;
888
889 /* Initialize our worker task */
890 std::auto_ptr<TaskOVF> task(new TaskOVF(this, TaskOVF::Read, aLocInfo, aProgress));
891
892 rc = task->startThread();
893 if (FAILED(rc)) throw rc;
894
895 /* Don't destruct on success */
896 task.release();
897
898 return rc;
899}
900
901/**
902 * Actual worker code for reading an OVF from disk. This is called from Appliance::taskThreadImportOrExport()
903 * and therefore runs on the OVF read worker thread. This opens the OVF with ovfreader.cpp.
904 *
905 * This runs in two contexts:
906 *
907 * 1) in a first worker thread; in that case, Appliance::Read() called Appliance::readImpl();
908 *
909 * 2) in a second worker thread; in that case, Appliance::Read() called Appliance::readImpl(), which
910 * called Appliance::readS3(), which called Appliance::readImpl(), which then called this.
911 *
912 * @param pTask
913 * @return
914 */
915HRESULT Appliance::readFS(TaskOVF *pTask)
916{
917 LogFlowFuncEnter();
918 LogFlowFunc(("Appliance %p\n", this));
919
920 AutoCaller autoCaller(this);
921 if (FAILED(autoCaller.rc())) return autoCaller.rc();
922
923 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
924
925 HRESULT rc = S_OK;
926
927 if (pTask->locInfo.strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
928 rc = readFSOVF(pTask);
929 else
930 rc = readFSOVA(pTask);
931
932 LogFlowFunc(("rc=%Rhrc\n", rc));
933 LogFlowFuncLeave();
934
935 return rc;
936}
937
938HRESULT Appliance::readFSOVF(TaskOVF *pTask)
939{
940 LogFlowFuncEnter();
941
942 HRESULT rc = S_OK;
943 int vrc = VINF_SUCCESS;
944
945 PVDINTERFACEIO pShaIo = 0;
946 PVDINTERFACEIO pFileIo = 0;
947 do
948 {
949 try
950 {
951 /* Create the necessary file access interfaces. */
952 pFileIo = FileCreateInterface();
953 if (!pFileIo)
954 {
955 rc = E_OUTOFMEMORY;
956 break;
957 }
958
959 Utf8Str strMfFile = Utf8Str(pTask->locInfo.strPath).stripSuffix().append(".mf");
960
961 SHASTORAGE storage;
962 RT_ZERO(storage);
963
964 if (RTFileExists(strMfFile.c_str()))
965 {
966 pShaIo = ShaCreateInterface();
967 if (!pShaIo)
968 {
969 rc = E_OUTOFMEMORY;
970 break;
971 }
972
973 //read the manifest file and find a type of used digest
974 RTFILE pFile = NULL;
975 vrc = RTFileOpen(&pFile, strMfFile.c_str(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
976 if (RT_SUCCESS(vrc) && pFile != NULL)
977 {
978 uint64_t cbFile = 0;
979 uint64_t maxFileSize = _1M;
980 size_t cbRead = 0;
981 void *pBuf; /** @todo r=bird: You leak this buffer! throwing stuff is evil. */
982
983 vrc = RTFileGetSize(pFile, &cbFile);
984 if (cbFile > maxFileSize)
985 throw setError(VBOX_E_FILE_ERROR,
986 tr("Size of the manifest file '%s' is bigger than 1Mb. Check it, please."),
987 RTPathFilename(strMfFile.c_str()));
988
989 if (RT_SUCCESS(vrc))
990 pBuf = RTMemAllocZ(cbFile);
991 else
992 throw setError(VBOX_E_FILE_ERROR,
993 tr("Could not get size of the manifest file '%s' "),
994 RTPathFilename(strMfFile.c_str()));
995
996 vrc = RTFileRead(pFile, pBuf, cbFile, &cbRead);
997
998 if (RT_FAILURE(vrc))
999 {
1000 if (pBuf)
1001 RTMemFree(pBuf);
1002 throw setError(VBOX_E_FILE_ERROR,
1003 tr("Could not read the manifest file '%s' (%Rrc)"),
1004 RTPathFilename(strMfFile.c_str()), vrc);
1005 }
1006
1007 RTFileClose(pFile);
1008
1009 RTDIGESTTYPE digestType;
1010 vrc = RTManifestVerifyDigestType(pBuf, cbRead, &digestType);
1011
1012 if (pBuf)
1013 RTMemFree(pBuf);
1014
1015 if (RT_FAILURE(vrc))
1016 {
1017 throw setError(VBOX_E_FILE_ERROR,
1018 tr("Could not verify supported digest types in the manifest file '%s' (%Rrc)"),
1019 RTPathFilename(strMfFile.c_str()), vrc);
1020 }
1021
1022 storage.fCreateDigest = true;
1023
1024 if (digestType == RTDIGESTTYPE_SHA256)
1025 {
1026 storage.fSha256 = true;
1027 }
1028
1029 Utf8Str name = applianceIOName(applianceIOFile);
1030
1031 vrc = VDInterfaceAdd(&pFileIo->Core, name.c_str(),
1032 VDINTERFACETYPE_IO, 0, sizeof(VDINTERFACEIO),
1033 &storage.pVDImageIfaces);
1034 if (RT_FAILURE(vrc))
1035 throw setError(VBOX_E_IPRT_ERROR, "Creation of the VD interface failed (%Rrc)", vrc);
1036
1037 rc = readFSImpl(pTask, pTask->locInfo.strPath, pShaIo, &storage);
1038 if (FAILED(rc))
1039 break;
1040 }
1041 else
1042 {
1043 throw setError(VBOX_E_FILE_ERROR,
1044 tr("Could not open the manifest file '%s' (%Rrc)"),
1045 RTPathFilename(strMfFile.c_str()), vrc);
1046 }
1047 }
1048 else
1049 {
1050 storage.fCreateDigest = false;
1051 rc = readFSImpl(pTask, pTask->locInfo.strPath, pFileIo, &storage);
1052 if (FAILED(rc))
1053 break;
1054 }
1055 }
1056 catch (HRESULT rc2)
1057 {
1058 rc = rc2;
1059 }
1060
1061 }while (0);
1062
1063 /* Cleanup */
1064 if (pShaIo)
1065 RTMemFree(pShaIo);
1066 if (pFileIo)
1067 RTMemFree(pFileIo);
1068
1069 LogFlowFunc(("rc=%Rhrc\n", rc));
1070 LogFlowFuncLeave();
1071
1072 return rc;
1073}
1074
1075HRESULT Appliance::readFSOVA(TaskOVF *pTask)
1076{
1077 LogFlowFuncEnter();
1078
1079 RTTAR tar;
1080 HRESULT rc = S_OK;
1081 int vrc = 0;
1082 PVDINTERFACEIO pShaIo = 0;
1083 PVDINTERFACEIO pTarIo = 0;
1084 char *pszFilename = 0;
1085 SHASTORAGE storage;
1086
1087 RT_ZERO(storage);
1088
1089 vrc = RTTarOpen(&tar, pTask->locInfo.strPath.c_str(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE, true);
1090 if (RT_FAILURE(vrc))
1091 rc = setError(VBOX_E_FILE_ERROR,
1092 tr("Could not open the OVA file '%s' (%Rrc)"),
1093 pTask->locInfo.strPath.c_str(), vrc);
1094 else
1095 {
1096 do
1097 {
1098 vrc = RTTarCurrentFile(tar, &pszFilename);
1099 if (RT_FAILURE(vrc))
1100 {
1101 rc = VBOX_E_FILE_ERROR;
1102 break;
1103 }
1104
1105 Utf8Str suffix(RTPathSuffix(pszFilename));
1106
1107 if (!suffix.endsWith(".ovf",Utf8Str::CaseInsensitive))
1108 {
1109 vrc = VERR_FILE_NOT_FOUND;
1110 rc = setError(VBOX_E_FILE_ERROR,
1111 tr("First file in the OVA package must have the extension 'ovf'. "
1112 "But the file '%s' has the different extension (%Rrc)"),
1113 pszFilename,
1114 vrc);
1115 break;
1116 }
1117
1118 pTarIo = TarCreateInterface();
1119 if (!pTarIo)
1120 {
1121 rc = E_OUTOFMEMORY;
1122 break;
1123 }
1124
1125 pShaIo = ShaCreateInterface();
1126 if (!pShaIo)
1127 {
1128 rc = E_OUTOFMEMORY;
1129 break ;
1130 }
1131
1132 Utf8Str name = applianceIOName(applianceIOTar);
1133
1134 vrc = VDInterfaceAdd(&pTarIo->Core, name.c_str(),
1135 VDINTERFACETYPE_IO, tar, sizeof(VDINTERFACEIO),
1136 &storage.pVDImageIfaces);
1137 if (RT_FAILURE(vrc))
1138 {
1139 rc = setError(VBOX_E_IPRT_ERROR, "Creation of the VD interface failed (%Rrc)", vrc);
1140 break;
1141 }
1142
1143 rc = readFSImpl(pTask, pszFilename, pShaIo, &storage);
1144 if (FAILED(rc))
1145 break;
1146
1147 } while (0);
1148
1149 RTTarClose(tar);
1150 }
1151
1152
1153
1154 /* Cleanup */
1155 if (pszFilename)
1156 RTMemFree(pszFilename);
1157 if (pShaIo)
1158 RTMemFree(pShaIo);
1159 if (pTarIo)
1160 RTMemFree(pTarIo);
1161
1162 LogFlowFunc(("rc=%Rhrc\n", rc));
1163 LogFlowFuncLeave();
1164
1165 return rc;
1166}
1167
1168HRESULT Appliance::readFSImpl(TaskOVF *pTask, const RTCString &strFilename, PVDINTERFACEIO pIfIo, PSHASTORAGE pStorage)
1169{
1170 LogFlowFuncEnter();
1171
1172 HRESULT rc = S_OK;
1173
1174 pStorage->fCreateDigest = true;
1175
1176 void *pvTmpBuf = 0;
1177 try
1178 {
1179 /* Read the OVF into a memory buffer */
1180 size_t cbSize = 0;
1181 int vrc = ShaReadBuf(strFilename.c_str(), &pvTmpBuf, &cbSize, pIfIo, pStorage);
1182 if (RT_FAILURE(vrc)
1183 || !pvTmpBuf)
1184 throw setError(VBOX_E_FILE_ERROR,
1185 tr("Could not read OVF file '%s' (%Rrc)"),
1186 RTPathFilename(strFilename.c_str()), vrc);
1187
1188 /* Read & parse the XML structure of the OVF file */
1189 m->pReader = new ovf::OVFReader(pvTmpBuf, cbSize, pTask->locInfo.strPath);
1190
1191 if (m->pReader->m_envelopeData.getOVFVersion() == ovf::OVFVersion_2_0)
1192 {
1193 m->fSha256 = true;
1194
1195 uint8_t digest[RTSHA256_HASH_SIZE];
1196 size_t cbDigest = RTSHA256_DIGEST_LEN;
1197 char *pszDigest;
1198
1199 RTSha256(pvTmpBuf, cbSize, &digest[0]);
1200
1201 vrc = RTStrAllocEx(&pszDigest, cbDigest + 1);
1202 if (RT_SUCCESS(vrc))
1203 vrc = RTSha256ToString(digest, pszDigest, cbDigest + 1);
1204 else
1205 throw setError(VBOX_E_FILE_ERROR,
1206 tr("Could not allocate string for SHA256 digest (%Rrc)"), vrc);
1207
1208 if (RT_SUCCESS(vrc))
1209 /* Copy the SHA256 sum of the OVF file for later validation */
1210 m->strOVFSHADigest = pszDigest;
1211 else
1212 throw setError(VBOX_E_FILE_ERROR,
1213 tr("Converting SHA256 digest to a string was failed (%Rrc)"), vrc);
1214
1215 RTStrFree(pszDigest);
1216
1217 }
1218 else
1219 {
1220 m->fSha256 = false;
1221 /* Copy the SHA1 sum of the OVF file for later validation */
1222 m->strOVFSHADigest = pStorage->strDigest;
1223 }
1224
1225 }
1226 catch (RTCError &x) // includes all XML exceptions
1227 {
1228 rc = setError(VBOX_E_FILE_ERROR,
1229 x.what());
1230 }
1231 catch (HRESULT aRC)
1232 {
1233 rc = aRC;
1234 }
1235
1236 /* Cleanup */
1237 if (pvTmpBuf)
1238 RTMemFree(pvTmpBuf);
1239
1240 LogFlowFunc(("rc=%Rhrc\n", rc));
1241 LogFlowFuncLeave();
1242
1243 return rc;
1244}
1245
1246#ifdef VBOX_WITH_S3
1247/**
1248 * Worker code for reading OVF from the cloud. This is called from Appliance::taskThreadImportOrExport()
1249 * in S3 mode and therefore runs on the OVF read worker thread. This then starts a second worker
1250 * thread to create temporary files (see Appliance::readFS()).
1251 *
1252 * @param pTask
1253 * @return
1254 */
1255HRESULT Appliance::readS3(TaskOVF *pTask)
1256{
1257 LogFlowFuncEnter();
1258 LogFlowFunc(("Appliance %p\n", this));
1259
1260 AutoCaller autoCaller(this);
1261 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1262
1263 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
1264
1265 HRESULT rc = S_OK;
1266 int vrc = VINF_SUCCESS;
1267 RTS3 hS3 = NIL_RTS3;
1268 char szOSTmpDir[RTPATH_MAX];
1269 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
1270 /* The template for the temporary directory created below */
1271 char *pszTmpDir = RTPathJoinA(szOSTmpDir, "vbox-ovf-XXXXXX");
1272 list< pair<Utf8Str, ULONG> > filesList;
1273 Utf8Str strTmpOvf;
1274
1275 try
1276 {
1277 /* Extract the bucket */
1278 Utf8Str tmpPath = pTask->locInfo.strPath;
1279 Utf8Str bucket;
1280 parseBucket(tmpPath, bucket);
1281
1282 /* We need a temporary directory which we can put the OVF file & all
1283 * disk images in */
1284 vrc = RTDirCreateTemp(pszTmpDir, 0700);
1285 if (RT_FAILURE(vrc))
1286 throw setError(VBOX_E_FILE_ERROR,
1287 tr("Cannot create temporary directory '%s'"), pszTmpDir);
1288
1289 /* The temporary name of the target OVF file */
1290 strTmpOvf = Utf8StrFmt("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
1291
1292 /* Next we have to download the OVF */
1293 vrc = RTS3Create(&hS3,
1294 pTask->locInfo.strUsername.c_str(),
1295 pTask->locInfo.strPassword.c_str(),
1296 pTask->locInfo.strHostname.c_str(),
1297 "virtualbox-agent/"VBOX_VERSION_STRING);
1298 if (RT_FAILURE(vrc))
1299 throw setError(VBOX_E_IPRT_ERROR,
1300 tr("Cannot create S3 service handler"));
1301 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
1302
1303 /* Get it */
1304 char *pszFilename = RTPathFilename(strTmpOvf.c_str());
1305 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strTmpOvf.c_str());
1306 if (RT_FAILURE(vrc))
1307 {
1308 if (vrc == VERR_S3_CANCELED)
1309 throw S_OK; /* todo: !!!!!!!!!!!!! */
1310 else if (vrc == VERR_S3_ACCESS_DENIED)
1311 throw setError(E_ACCESSDENIED,
1312 tr("Cannot download file '%s' from S3 storage server (Access denied). Make sure that "
1313 "your credentials are right. "
1314 "Also check that your host clock is properly synced"),
1315 pszFilename);
1316 else if (vrc == VERR_S3_NOT_FOUND)
1317 throw setError(VBOX_E_FILE_ERROR,
1318 tr("Cannot download file '%s' from S3 storage server (File not found)"), pszFilename);
1319 else
1320 throw setError(VBOX_E_IPRT_ERROR,
1321 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
1322 }
1323
1324 /* Close the connection early */
1325 RTS3Destroy(hS3);
1326 hS3 = NIL_RTS3;
1327
1328 pTask->pProgress->SetNextOperation(Bstr(tr("Reading")).raw(), 1);
1329
1330 /* Prepare the temporary reading of the OVF */
1331 ComObjPtr<Progress> progress;
1332 LocationInfo li;
1333 li.strPath = strTmpOvf;
1334 /* Start the reading from the fs */
1335 rc = readImpl(li, progress);
1336 if (FAILED(rc)) throw rc;
1337
1338 /* Unlock the appliance for the reading thread */
1339 appLock.release();
1340 /* Wait until the reading is done, but report the progress back to the
1341 caller */
1342 ComPtr<IProgress> progressInt(progress);
1343 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
1344
1345 /* Again lock the appliance for the next steps */
1346 appLock.acquire();
1347 }
1348 catch(HRESULT aRC)
1349 {
1350 rc = aRC;
1351 }
1352 /* Cleanup */
1353 RTS3Destroy(hS3);
1354 /* Delete all files which where temporary created */
1355 if (RTPathExists(strTmpOvf.c_str()))
1356 {
1357 vrc = RTFileDelete(strTmpOvf.c_str());
1358 if (RT_FAILURE(vrc))
1359 rc = setError(VBOX_E_FILE_ERROR,
1360 tr("Cannot delete file '%s' (%Rrc)"), strTmpOvf.c_str(), vrc);
1361 }
1362 /* Delete the temporary directory */
1363 if (RTPathExists(pszTmpDir))
1364 {
1365 vrc = RTDirRemove(pszTmpDir);
1366 if (RT_FAILURE(vrc))
1367 rc = setError(VBOX_E_FILE_ERROR,
1368 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
1369 }
1370 if (pszTmpDir)
1371 RTStrFree(pszTmpDir);
1372
1373 LogFlowFunc(("rc=%Rhrc\n", rc));
1374 LogFlowFuncLeave();
1375
1376 return rc;
1377}
1378#endif /* VBOX_WITH_S3 */
1379
1380/*******************************************************************************
1381 * Import stuff
1382 ******************************************************************************/
1383
1384/**
1385 * Implementation for importing OVF data into VirtualBox. This starts a new thread which will call
1386 * Appliance::taskThreadImportOrExport().
1387 *
1388 * This creates one or more new machines according to the VirtualSystemScription instances created by
1389 * Appliance::Interpret().
1390 *
1391 * This is in a separate private method because it is used from two locations:
1392 *
1393 * 1) from the public Appliance::ImportMachines().
1394 * 2) from Appliance::importS3(), which got called from a previous instance of Appliance::taskThreadImportOrExport().
1395 *
1396 * @param aLocInfo
1397 * @param aProgress
1398 * @return
1399 */
1400HRESULT Appliance::importImpl(const LocationInfo &locInfo,
1401 ComObjPtr<Progress> &progress)
1402{
1403 HRESULT rc = S_OK;
1404
1405 SetUpProgressMode mode;
1406 if (locInfo.storageType == VFSType_File)
1407 mode = ImportFile;
1408 else
1409 mode = ImportS3;
1410
1411 rc = setUpProgress(progress,
1412 BstrFmt(tr("Importing appliance '%s'"), locInfo.strPath.c_str()),
1413 mode);
1414 if (FAILED(rc)) throw rc;
1415
1416 /* Initialize our worker task */
1417 std::auto_ptr<TaskOVF> task(new TaskOVF(this, TaskOVF::Import, locInfo, progress));
1418
1419 rc = task->startThread();
1420 if (FAILED(rc)) throw rc;
1421
1422 /* Don't destruct on success */
1423 task.release();
1424
1425 return rc;
1426}
1427
1428/**
1429 * Actual worker code for importing OVF data into VirtualBox. This is called from Appliance::taskThreadImportOrExport()
1430 * and therefore runs on the OVF import worker thread. This creates one or more new machines according to the
1431 * VirtualSystemScription instances created by Appliance::Interpret().
1432 *
1433 * This runs in three contexts:
1434 *
1435 * 1) in a first worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl();
1436 *
1437 * 2) in a second worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl(), which
1438 * called Appliance::importFSOVA(), which called Appliance::importImpl(), which then called this again.
1439 *
1440 * 3) in a second worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl(), which
1441 * called Appliance::importS3(), which called Appliance::importImpl(), which then called this again.
1442 *
1443 * @param pTask
1444 * @return
1445 */
1446HRESULT Appliance::importFS(TaskOVF *pTask)
1447{
1448
1449 LogFlowFuncEnter();
1450 LogFlowFunc(("Appliance %p\n", this));
1451
1452 AutoCaller autoCaller(this);
1453 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1454
1455 /* Change the appliance state so we can safely leave the lock while doing
1456 * time-consuming disk imports; also the below method calls do all kinds of
1457 * locking which conflicts with the appliance object lock. */
1458 AutoWriteLock writeLock(this COMMA_LOCKVAL_SRC_POS);
1459 /* Check if the appliance is currently busy. */
1460 if (!isApplianceIdle())
1461 return E_ACCESSDENIED;
1462 /* Set the internal state to importing. */
1463 m->state = Data::ApplianceImporting;
1464
1465 HRESULT rc = S_OK;
1466
1467 /* Clear the list of imported machines, if any */
1468 m->llGuidsMachinesCreated.clear();
1469
1470 if (pTask->locInfo.strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
1471 rc = importFSOVF(pTask, writeLock);
1472 else
1473 rc = importFSOVA(pTask, writeLock);
1474
1475 if (FAILED(rc))
1476 {
1477 /* With _whatever_ error we've had, do a complete roll-back of
1478 * machines and disks we've created */
1479 writeLock.release();
1480 for (list<Guid>::iterator itID = m->llGuidsMachinesCreated.begin();
1481 itID != m->llGuidsMachinesCreated.end();
1482 ++itID)
1483 {
1484 Guid guid = *itID;
1485 Bstr bstrGuid = guid.toUtf16();
1486 ComPtr<IMachine> failedMachine;
1487 HRESULT rc2 = mVirtualBox->FindMachine(bstrGuid.raw(), failedMachine.asOutParam());
1488 if (SUCCEEDED(rc2))
1489 {
1490 SafeIfaceArray<IMedium> aMedia;
1491 rc2 = failedMachine->Unregister(CleanupMode_DetachAllReturnHardDisksOnly, ComSafeArrayAsOutParam(aMedia));
1492 ComPtr<IProgress> pProgress2;
1493 rc2 = failedMachine->DeleteConfig(ComSafeArrayAsInParam(aMedia), pProgress2.asOutParam());
1494 pProgress2->WaitForCompletion(-1);
1495 }
1496 }
1497 writeLock.acquire();
1498 }
1499
1500 /* Reset the state so others can call methods again */
1501 m->state = Data::ApplianceIdle;
1502
1503 LogFlowFunc(("rc=%Rhrc\n", rc));
1504 LogFlowFuncLeave();
1505
1506 return rc;
1507}
1508
1509HRESULT Appliance::importFSOVF(TaskOVF *pTask, AutoWriteLockBase& writeLock)
1510{
1511 LogFlowFuncEnter();
1512
1513 HRESULT rc = S_OK;
1514
1515 PVDINTERFACEIO pShaIo = NULL;
1516 PVDINTERFACEIO pFileIo = NULL;
1517 void *pvMfBuf = NULL;
1518 void *pvCertBuf = NULL;
1519 writeLock.release();
1520 try
1521 {
1522 /* Create the necessary file access interfaces. */
1523 pFileIo = FileCreateInterface();
1524 if (!pFileIo)
1525 throw setError(E_OUTOFMEMORY);
1526
1527 Utf8Str strMfFile = Utf8Str(pTask->locInfo.strPath).stripSuffix().append(".mf");
1528
1529 SHASTORAGE storage;
1530 RT_ZERO(storage);
1531
1532 Utf8Str name = applianceIOName(applianceIOFile);
1533
1534 int vrc = VDInterfaceAdd(&pFileIo->Core, name.c_str(),
1535 VDINTERFACETYPE_IO, 0, sizeof(VDINTERFACEIO),
1536 &storage.pVDImageIfaces);
1537 if (RT_FAILURE(vrc))
1538 throw setError(VBOX_E_IPRT_ERROR, "Creation of the VD interface failed (%Rrc)", vrc);
1539
1540 /* Create the import stack for the rollback on errors. */
1541 ImportStack stack(pTask->locInfo, m->pReader->m_mapDisks, pTask->pProgress);
1542
1543 if (RTFileExists(strMfFile.c_str()))
1544 {
1545 pShaIo = ShaCreateInterface();
1546 if (!pShaIo)
1547 throw setError(E_OUTOFMEMORY);
1548
1549 Utf8Str nameSha = applianceIOName(applianceIOSha);
1550 /* Fill out interface descriptor. */
1551 pShaIo->Core.u32Magic = VDINTERFACE_MAGIC;
1552 pShaIo->Core.cbSize = sizeof(VDINTERFACEIO);
1553 pShaIo->Core.pszInterfaceName = nameSha.c_str();
1554 pShaIo->Core.enmInterface = VDINTERFACETYPE_IO;
1555 pShaIo->Core.pvUser = &storage;
1556 pShaIo->Core.pNext = NULL;
1557
1558 storage.fCreateDigest = true;
1559
1560 size_t cbMfSize = 0;
1561
1562 /* Now import the appliance. */
1563 importMachines(stack, pShaIo, &storage);
1564 /* Read & verify the manifest file. */
1565 /* Add the ovf file to the digest list. */
1566 stack.llSrcDisksDigest.push_front(STRPAIR(pTask->locInfo.strPath, m->strOVFSHADigest));
1567 rc = readFileToBuf(strMfFile, &pvMfBuf, &cbMfSize, true, pShaIo, &storage);
1568 if (FAILED(rc)) throw rc;
1569 rc = verifyManifestFile(strMfFile, stack, pvMfBuf, cbMfSize);
1570 if (FAILED(rc)) throw rc;
1571
1572 size_t cbCertSize = 0;
1573
1574 /* Save the SHA digest of the manifest file for the next validation */
1575 Utf8Str manifestShaDigest = storage.strDigest;
1576
1577 Utf8Str strCertFile = Utf8Str(pTask->locInfo.strPath).stripSuffix().append(".cert");
1578 if (RTFileExists(strCertFile.c_str()))
1579 {
1580 rc = readFileToBuf(strCertFile, &pvCertBuf, &cbCertSize, false, pShaIo, &storage);
1581 if (FAILED(rc)) throw rc;
1582
1583 /* verify Certificate */
1584 }
1585 }
1586 else
1587 {
1588 storage.fCreateDigest = false;
1589 importMachines(stack, pFileIo, &storage);
1590 }
1591 }
1592 catch (HRESULT rc2)
1593 {
1594 rc = rc2;
1595 }
1596 writeLock.acquire();
1597
1598 /* Cleanup */
1599 if (pvMfBuf)
1600 RTMemFree(pvMfBuf);
1601 if (pvCertBuf)
1602 RTMemFree(pvCertBuf);
1603 if (pShaIo)
1604 RTMemFree(pShaIo);
1605 if (pFileIo)
1606 RTMemFree(pFileIo);
1607
1608 LogFlowFunc(("rc=%Rhrc\n", rc));
1609 LogFlowFuncLeave();
1610
1611 return rc;
1612}
1613
1614HRESULT Appliance::importFSOVA(TaskOVF *pTask, AutoWriteLockBase& writeLock)
1615{
1616 LogFlowFuncEnter();
1617
1618 RTTAR tar;
1619 int vrc = RTTarOpen(&tar,
1620 pTask->locInfo.strPath.c_str(),
1621 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE, true);
1622 if (RT_FAILURE(vrc))
1623 return setError(VBOX_E_FILE_ERROR,
1624 tr("Could not open OVA file '%s' (%Rrc)"),
1625 pTask->locInfo.strPath.c_str(), vrc);
1626
1627 HRESULT rc = S_OK;
1628
1629 PVDINTERFACEIO pShaIo = 0;
1630 PVDINTERFACEIO pTarIo = 0;
1631 char *pszFilename = 0;
1632 void *pvMfBuf = 0;
1633 void *pvCertBuf = 0;
1634 Utf8Str OVFfilename;
1635
1636 writeLock.release();
1637 try
1638 {
1639 /* Create the necessary file access interfaces. */
1640 pShaIo = ShaCreateInterface();
1641 if (!pShaIo)
1642 throw setError(E_OUTOFMEMORY);
1643 pTarIo = TarCreateInterface();
1644 if (!pTarIo)
1645 throw setError(E_OUTOFMEMORY);
1646
1647 SHASTORAGE storage;
1648 RT_ZERO(storage);
1649
1650 Utf8Str nameTar = applianceIOName(applianceIOTar);
1651
1652 vrc = VDInterfaceAdd(&pTarIo->Core, nameTar.c_str(),
1653 VDINTERFACETYPE_IO, tar, sizeof(VDINTERFACEIO),
1654 &storage.pVDImageIfaces);
1655 if (RT_FAILURE(vrc))
1656 throw setError(VBOX_E_IPRT_ERROR,
1657 tr("Creation of the VD interface failed (%Rrc)"), vrc);
1658
1659 Utf8Str nameSha = applianceIOName(applianceIOSha);
1660 /* Fill out interface descriptor. */
1661 pShaIo->Core.u32Magic = VDINTERFACE_MAGIC;
1662 pShaIo->Core.cbSize = sizeof(VDINTERFACEIO);
1663 pShaIo->Core.pszInterfaceName = nameSha.c_str();
1664 pShaIo->Core.enmInterface = VDINTERFACETYPE_IO;
1665 pShaIo->Core.pvUser = &storage;
1666 pShaIo->Core.pNext = NULL;
1667
1668 /* Read the file name of the first file (need to be the ovf file). This
1669 * is how all internal files are named. */
1670 vrc = RTTarCurrentFile(tar, &pszFilename);
1671 if (RT_FAILURE(vrc))
1672 throw setError(VBOX_E_IPRT_ERROR,
1673 tr("Getting the OVF file within the archive failed (%Rrc)"), vrc);
1674 else
1675 {
1676 if (vrc == VINF_TAR_DIR_PATH)
1677 {
1678 throw setError(VBOX_E_FILE_ERROR,
1679 tr("Empty directory folder (%s) isn't allowed in the OVA package (%Rrc)"),
1680 pszFilename,
1681 vrc);
1682 }
1683 }
1684
1685 /* save original OVF filename */
1686 OVFfilename = pszFilename;
1687 size_t cbMfSize = 0;
1688 size_t cbCertSize = 0;
1689 Utf8Str strMfFile = (Utf8Str(pszFilename)).stripSuffix().append(".mf");
1690 Utf8Str strCertFile = (Utf8Str(pszFilename)).stripSuffix().append(".cert");
1691
1692 /* Skip the OVF file, cause this was read in IAppliance::Read already. */
1693 vrc = RTTarSeekNextFile(tar);
1694 if ( RT_FAILURE(vrc)
1695 && vrc != VERR_TAR_END_OF_FILE)
1696 throw setError(VBOX_E_IPRT_ERROR,
1697 tr("Seeking within the archive failed (%Rrc)"), vrc);
1698 else
1699 {
1700 RTTarCurrentFile(tar, &pszFilename);
1701 if (vrc == VINF_TAR_DIR_PATH)
1702 {
1703 throw setError(VBOX_E_FILE_ERROR,
1704 tr("Empty directory folder (%s) isn't allowed in the OVA package (%Rrc)"),
1705 pszFilename,
1706 vrc);
1707 }
1708 }
1709
1710 PVDINTERFACEIO pCallbacks = pShaIo;
1711 PSHASTORAGE pStorage = &storage;
1712
1713 /* We always need to create the digest, cause we didn't know if there
1714 * is a manifest file in the stream. */
1715 pStorage->fCreateDigest = true;
1716
1717 /* Create the import stack for the rollback on errors. */
1718 ImportStack stack(pTask->locInfo, m->pReader->m_mapDisks, pTask->pProgress);
1719 /*
1720 * Try to read the manifest file. First try.
1721 *
1722 * Note: This isn't fatal if the file is not found. The standard
1723 * defines 3 cases.
1724 * 1. no manifest file
1725 * 2. manifest file after the OVF file
1726 * 3. manifest file after all disk files
1727 * If we want streaming capabilities, we can't check if it is there by
1728 * searching for it. We have to try to open it on all possible places.
1729 * If it fails here, we will try it again after all disks where read.
1730 */
1731 rc = readTarFileToBuf(tar, strMfFile, &pvMfBuf, &cbMfSize, true, pCallbacks, pStorage);
1732 if (FAILED(rc)) throw rc;
1733
1734 /*
1735 * Try to read the certificate file. First try.
1736 * Logic is the same as with manifest file
1737 * Only if the manifest file had been read successfully before
1738 */
1739 vrc = RTTarCurrentFile(tar, &pszFilename);
1740 if (RT_SUCCESS(vrc))
1741 {
1742 if (pvMfBuf)
1743 {
1744 if (strCertFile.compare(pszFilename) == 0)
1745 {
1746 rc = readTarFileToBuf(tar, strCertFile, &pvCertBuf, &cbCertSize, false, pCallbacks, pStorage);
1747 if (FAILED(rc)) throw rc;
1748
1749 if (pvCertBuf)
1750 {
1751 /* verify the certificate */
1752 }
1753 }
1754 }
1755 }
1756
1757 /* Now import the appliance. */
1758 importMachines(stack, pCallbacks, pStorage);
1759 /* Try to read the manifest file. Second try. */
1760 if (!pvMfBuf)
1761 {
1762 rc = readTarFileToBuf(tar, strMfFile, &pvMfBuf, &cbMfSize, true, pCallbacks, pStorage);
1763 if (FAILED(rc)) throw rc;
1764
1765 /* If we were able to read a manifest file we can check it now. */
1766 if (pvMfBuf)
1767 {
1768 /* Add the ovf file to the digest list. */
1769 stack.llSrcDisksDigest.push_front(STRPAIR(OVFfilename, m->strOVFSHADigest));
1770 rc = verifyManifestFile(strMfFile, stack, pvMfBuf, cbMfSize);
1771 if (FAILED(rc)) throw rc;
1772
1773 /*
1774 * Try to read the certificate file. Second try.
1775 * Only if the manifest file had been read successfully before
1776 */
1777
1778 vrc = RTTarCurrentFile(tar, &pszFilename);
1779 if (RT_SUCCESS(vrc))
1780 {
1781 if (strCertFile.compare(pszFilename) == 0)
1782 {
1783 rc = readTarFileToBuf(tar, strCertFile, &pvCertBuf, &cbCertSize, false, pCallbacks, pStorage);
1784 if (FAILED(rc)) throw rc;
1785
1786 if (pvCertBuf)
1787 {
1788 /* verify the certificate */
1789 }
1790 }
1791 }
1792 }
1793 }
1794 }
1795 catch (HRESULT rc2)
1796 {
1797 rc = rc2;
1798 }
1799 writeLock.acquire();
1800
1801 RTTarClose(tar);
1802
1803 /* Cleanup */
1804 if (pszFilename)
1805 RTMemFree(pszFilename);
1806 if (pvMfBuf)
1807 RTMemFree(pvMfBuf);
1808 if (pShaIo)
1809 RTMemFree(pShaIo);
1810 if (pTarIo)
1811 RTMemFree(pTarIo);
1812 if (pvCertBuf)
1813 RTMemFree(pvCertBuf);
1814
1815 LogFlowFunc(("rc=%Rhrc\n", rc));
1816 LogFlowFuncLeave();
1817
1818 return rc;
1819}
1820
1821#ifdef VBOX_WITH_S3
1822/**
1823 * Worker code for importing OVF from the cloud. This is called from Appliance::taskThreadImportOrExport()
1824 * in S3 mode and therefore runs on the OVF import worker thread. This then starts a second worker
1825 * thread to import from temporary files (see Appliance::importFS()).
1826 * @param pTask
1827 * @return
1828 */
1829HRESULT Appliance::importS3(TaskOVF *pTask)
1830{
1831 LogFlowFuncEnter();
1832 LogFlowFunc(("Appliance %p\n", this));
1833
1834 AutoCaller autoCaller(this);
1835 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1836
1837 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
1838
1839 int vrc = VINF_SUCCESS;
1840 RTS3 hS3 = NIL_RTS3;
1841 char szOSTmpDir[RTPATH_MAX];
1842 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
1843 /* The template for the temporary directory created below */
1844 char *pszTmpDir = RTPathJoinA(szOSTmpDir, "vbox-ovf-XXXXXX");
1845 list< pair<Utf8Str, ULONG> > filesList;
1846
1847 HRESULT rc = S_OK;
1848 try
1849 {
1850 /* Extract the bucket */
1851 Utf8Str tmpPath = pTask->locInfo.strPath;
1852 Utf8Str bucket;
1853 parseBucket(tmpPath, bucket);
1854
1855 /* We need a temporary directory which we can put the all disk images
1856 * in */
1857 vrc = RTDirCreateTemp(pszTmpDir, 0700);
1858 if (RT_FAILURE(vrc))
1859 throw setError(VBOX_E_FILE_ERROR,
1860 tr("Cannot create temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
1861
1862 /* Add every disks of every virtual system to an internal list */
1863 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
1864 for (it = m->virtualSystemDescriptions.begin();
1865 it != m->virtualSystemDescriptions.end();
1866 ++it)
1867 {
1868 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
1869 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1870 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
1871 for (itH = avsdeHDs.begin();
1872 itH != avsdeHDs.end();
1873 ++itH)
1874 {
1875 const Utf8Str &strTargetFile = (*itH)->strOvf;
1876 if (!strTargetFile.isEmpty())
1877 {
1878 /* The temporary name of the target disk file */
1879 Utf8StrFmt strTmpDisk("%s/%s", pszTmpDir, RTPathFilename(strTargetFile.c_str()));
1880 filesList.push_back(pair<Utf8Str, ULONG>(strTmpDisk, (*itH)->ulSizeMB));
1881 }
1882 }
1883 }
1884
1885 /* Next we have to download the disk images */
1886 vrc = RTS3Create(&hS3,
1887 pTask->locInfo.strUsername.c_str(),
1888 pTask->locInfo.strPassword.c_str(),
1889 pTask->locInfo.strHostname.c_str(),
1890 "virtualbox-agent/"VBOX_VERSION_STRING);
1891 if (RT_FAILURE(vrc))
1892 throw setError(VBOX_E_IPRT_ERROR,
1893 tr("Cannot create S3 service handler"));
1894 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
1895
1896 /* Download all files */
1897 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
1898 {
1899 const pair<Utf8Str, ULONG> &s = (*it1);
1900 const Utf8Str &strSrcFile = s.first;
1901 /* Construct the source file name */
1902 char *pszFilename = RTPathFilename(strSrcFile.c_str());
1903 /* Advance to the next operation */
1904 if (!pTask->pProgress.isNull())
1905 pTask->pProgress->SetNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename).raw(), s.second);
1906
1907 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strSrcFile.c_str());
1908 if (RT_FAILURE(vrc))
1909 {
1910 if (vrc == VERR_S3_CANCELED)
1911 throw S_OK; /* todo: !!!!!!!!!!!!! */
1912 else if (vrc == VERR_S3_ACCESS_DENIED)
1913 throw setError(E_ACCESSDENIED,
1914 tr("Cannot download file '%s' from S3 storage server (Access denied). "
1915 "Make sure that your credentials are right. Also check that your host clock is "
1916 "properly synced"),
1917 pszFilename);
1918 else if (vrc == VERR_S3_NOT_FOUND)
1919 throw setError(VBOX_E_FILE_ERROR,
1920 tr("Cannot download file '%s' from S3 storage server (File not found)"),
1921 pszFilename);
1922 else
1923 throw setError(VBOX_E_IPRT_ERROR,
1924 tr("Cannot download file '%s' from S3 storage server (%Rrc)"),
1925 pszFilename, vrc);
1926 }
1927 }
1928
1929 /* Provide a OVF file (haven't to exist) so the import routine can
1930 * figure out where the disk images/manifest file are located. */
1931 Utf8StrFmt strTmpOvf("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
1932 /* Now check if there is an manifest file. This is optional. */
1933 Utf8Str strManifestFile; //= queryManifestFileName(strTmpOvf);
1934// Utf8Str strManifestFile = queryManifestFileName(strTmpOvf);
1935 char *pszFilename = RTPathFilename(strManifestFile.c_str());
1936 if (!pTask->pProgress.isNull())
1937 pTask->pProgress->SetNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename).raw(), 1);
1938
1939 /* Try to download it. If the error is VERR_S3_NOT_FOUND, it isn't fatal. */
1940 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strManifestFile.c_str());
1941 if (RT_SUCCESS(vrc))
1942 filesList.push_back(pair<Utf8Str, ULONG>(strManifestFile, 0));
1943 else if (RT_FAILURE(vrc))
1944 {
1945 if (vrc == VERR_S3_CANCELED)
1946 throw S_OK; /* todo: !!!!!!!!!!!!! */
1947 else if (vrc == VERR_S3_NOT_FOUND)
1948 vrc = VINF_SUCCESS; /* Not found is ok */
1949 else if (vrc == VERR_S3_ACCESS_DENIED)
1950 throw setError(E_ACCESSDENIED,
1951 tr("Cannot download file '%s' from S3 storage server (Access denied)."
1952 "Make sure that your credentials are right. "
1953 "Also check that your host clock is properly synced"),
1954 pszFilename);
1955 else
1956 throw setError(VBOX_E_IPRT_ERROR,
1957 tr("Cannot download file '%s' from S3 storage server (%Rrc)"),
1958 pszFilename, vrc);
1959 }
1960
1961 /* Close the connection early */
1962 RTS3Destroy(hS3);
1963 hS3 = NIL_RTS3;
1964
1965 pTask->pProgress->SetNextOperation(BstrFmt(tr("Importing appliance")).raw(), m->ulWeightForXmlOperation);
1966
1967 ComObjPtr<Progress> progress;
1968 /* Import the whole temporary OVF & the disk images */
1969 LocationInfo li;
1970 li.strPath = strTmpOvf;
1971 rc = importImpl(li, progress);
1972 if (FAILED(rc)) throw rc;
1973
1974 /* Unlock the appliance for the fs import thread */
1975 appLock.release();
1976 /* Wait until the import is done, but report the progress back to the
1977 caller */
1978 ComPtr<IProgress> progressInt(progress);
1979 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
1980
1981 /* Again lock the appliance for the next steps */
1982 appLock.acquire();
1983 }
1984 catch(HRESULT aRC)
1985 {
1986 rc = aRC;
1987 }
1988 /* Cleanup */
1989 RTS3Destroy(hS3);
1990 /* Delete all files which where temporary created */
1991 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
1992 {
1993 const char *pszFilePath = (*it1).first.c_str();
1994 if (RTPathExists(pszFilePath))
1995 {
1996 vrc = RTFileDelete(pszFilePath);
1997 if (RT_FAILURE(vrc))
1998 rc = setError(VBOX_E_FILE_ERROR,
1999 tr("Cannot delete file '%s' (%Rrc)"), pszFilePath, vrc);
2000 }
2001 }
2002 /* Delete the temporary directory */
2003 if (RTPathExists(pszTmpDir))
2004 {
2005 vrc = RTDirRemove(pszTmpDir);
2006 if (RT_FAILURE(vrc))
2007 rc = setError(VBOX_E_FILE_ERROR,
2008 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
2009 }
2010 if (pszTmpDir)
2011 RTStrFree(pszTmpDir);
2012
2013 LogFlowFunc(("rc=%Rhrc\n", rc));
2014 LogFlowFuncLeave();
2015
2016 return rc;
2017}
2018#endif /* VBOX_WITH_S3 */
2019
2020HRESULT Appliance::readFileToBuf(const Utf8Str &strFile,
2021 void **ppvBuf,
2022 size_t *pcbSize,
2023 bool fCreateDigest,
2024 PVDINTERFACEIO pCallbacks,
2025 PSHASTORAGE pStorage)
2026{
2027 HRESULT rc = S_OK;
2028
2029 bool fOldDigest = pStorage->fCreateDigest;/* Save the old digest property */
2030 pStorage->fCreateDigest = fCreateDigest;
2031 int vrc = ShaReadBuf(strFile.c_str(), ppvBuf, pcbSize, pCallbacks, pStorage);
2032 if ( RT_FAILURE(vrc)
2033 && vrc != VERR_FILE_NOT_FOUND)
2034 rc = setError(VBOX_E_FILE_ERROR,
2035 tr("Could not read file '%s' (%Rrc)"),
2036 RTPathFilename(strFile.c_str()), vrc);
2037 pStorage->fCreateDigest = fOldDigest; /* Restore the old digest creation behavior again. */
2038
2039 return rc;
2040}
2041
2042HRESULT Appliance::readTarFileToBuf(RTTAR tar,
2043 const Utf8Str &strFile,
2044 void **ppvBuf,
2045 size_t *pcbSize,
2046 bool fCreateDigest,
2047 PVDINTERFACEIO pCallbacks,
2048 PSHASTORAGE pStorage)
2049{
2050 HRESULT rc = S_OK;
2051
2052 char *pszCurFile;
2053 int vrc = RTTarCurrentFile(tar, &pszCurFile);
2054 if (RT_SUCCESS(vrc))
2055 {
2056 if (vrc == VINF_TAR_DIR_PATH)
2057 {
2058 rc = setError(VBOX_E_FILE_ERROR,
2059 tr("Empty directory folder (%s) isn't allowed in the OVA package (%Rrc)"),
2060 pszCurFile,
2061 vrc);
2062 }
2063 else
2064 {
2065 if (!strcmp(pszCurFile, RTPathFilename(strFile.c_str())))
2066 rc = readFileToBuf(strFile, ppvBuf, pcbSize, fCreateDigest, pCallbacks, pStorage);
2067 RTStrFree(pszCurFile);
2068 }
2069 }
2070 else if (vrc != VERR_TAR_END_OF_FILE)
2071 rc = setError(VBOX_E_IPRT_ERROR, "Seeking within the archive failed (%Rrc)", vrc);
2072
2073 return rc;
2074}
2075
2076HRESULT Appliance::verifyManifestFile(const Utf8Str &strFile, ImportStack &stack, void *pvBuf, size_t cbSize)
2077{
2078 HRESULT rc = S_OK;
2079
2080 PRTMANIFESTTEST paTests = (PRTMANIFESTTEST)RTMemAlloc(sizeof(RTMANIFESTTEST) * stack.llSrcDisksDigest.size());
2081 if (!paTests)
2082 return E_OUTOFMEMORY;
2083
2084 size_t i = 0;
2085 list<STRPAIR>::const_iterator it1;
2086 for (it1 = stack.llSrcDisksDigest.begin();
2087 it1 != stack.llSrcDisksDigest.end();
2088 ++it1, ++i)
2089 {
2090 paTests[i].pszTestFile = (*it1).first.c_str();
2091 paTests[i].pszTestDigest = (*it1).second.c_str();
2092 }
2093 size_t iFailed;
2094 int vrc = RTManifestVerifyFilesBuf(pvBuf, cbSize, paTests, stack.llSrcDisksDigest.size(), &iFailed);
2095 if (RT_UNLIKELY(vrc == VERR_MANIFEST_DIGEST_MISMATCH))
2096 rc = setError(VBOX_E_FILE_ERROR,
2097 tr("The SHA digest of '%s' does not match the one in '%s' (%Rrc)"),
2098 RTPathFilename(paTests[iFailed].pszTestFile), RTPathFilename(strFile.c_str()), vrc);
2099 else if (RT_FAILURE(vrc))
2100 rc = setError(VBOX_E_FILE_ERROR,
2101 tr("Could not verify the content of '%s' against the available files (%Rrc)"),
2102 RTPathFilename(strFile.c_str()), vrc);
2103
2104 RTMemFree(paTests);
2105
2106 return rc;
2107}
2108
2109
2110/**
2111 * Helper that converts VirtualSystem attachment values into VirtualBox attachment values.
2112 * Throws HRESULT values on errors!
2113 *
2114 * @param hdc in: the HardDiskController structure to attach to.
2115 * @param ulAddressOnParent in: the AddressOnParent parameter from OVF.
2116 * @param controllerType out: the name of the hard disk controller to attach to (e.g. "IDE Controller").
2117 * @param lControllerPort out: the channel (controller port) of the controller to attach to.
2118 * @param lDevice out: the device number to attach to.
2119 */
2120void Appliance::convertDiskAttachmentValues(const ovf::HardDiskController &hdc,
2121 uint32_t ulAddressOnParent,
2122 Bstr &controllerType,
2123 int32_t &lControllerPort,
2124 int32_t &lDevice)
2125{
2126 Log(("Appliance::convertDiskAttachmentValues: hdc.system=%d, hdc.fPrimary=%d, ulAddressOnParent=%d\n",
2127 hdc.system,
2128 hdc.fPrimary,
2129 ulAddressOnParent));
2130
2131 switch (hdc.system)
2132 {
2133 case ovf::HardDiskController::IDE:
2134 // For the IDE bus, the port parameter can be either 0 or 1, to specify the primary
2135 // or secondary IDE controller, respectively. For the primary controller of the IDE bus,
2136 // the device number can be either 0 or 1, to specify the master or the slave device,
2137 // respectively. For the secondary IDE controller, the device number is always 1 because
2138 // the master device is reserved for the CD-ROM drive.
2139 controllerType = Bstr("IDE Controller");
2140 switch (ulAddressOnParent)
2141 {
2142 case 0: // master
2143 if (!hdc.fPrimary)
2144 {
2145 // secondary master
2146 lControllerPort = (long)1;
2147 lDevice = (long)0;
2148 }
2149 else // primary master
2150 {
2151 lControllerPort = (long)0;
2152 lDevice = (long)0;
2153 }
2154 break;
2155
2156 case 1: // slave
2157 if (!hdc.fPrimary)
2158 {
2159 // secondary slave
2160 lControllerPort = (long)1;
2161 lDevice = (long)1;
2162 }
2163 else // primary slave
2164 {
2165 lControllerPort = (long)0;
2166 lDevice = (long)1;
2167 }
2168 break;
2169
2170 // used by older VBox exports
2171 case 2: // interpret this as secondary master
2172 lControllerPort = (long)1;
2173 lDevice = (long)0;
2174 break;
2175
2176 // used by older VBox exports
2177 case 3: // interpret this as secondary slave
2178 lControllerPort = (long)1;
2179 lDevice = (long)1;
2180 break;
2181
2182 default:
2183 throw setError(VBOX_E_NOT_SUPPORTED,
2184 tr("Invalid channel %RI16 specified; IDE controllers support only 0, 1 or 2"),
2185 ulAddressOnParent);
2186 break;
2187 }
2188 break;
2189
2190 case ovf::HardDiskController::SATA:
2191 controllerType = Bstr("SATA Controller");
2192 lControllerPort = (long)ulAddressOnParent;
2193 lDevice = (long)0;
2194 break;
2195
2196 case ovf::HardDiskController::SCSI:
2197 controllerType = Bstr("SCSI Controller");
2198 lControllerPort = (long)ulAddressOnParent;
2199 lDevice = (long)0;
2200 break;
2201
2202 default: break;
2203 }
2204
2205 Log(("=> lControllerPort=%d, lDevice=%d\n", lControllerPort, lDevice));
2206}
2207
2208/**
2209 * Imports one disk image. This is common code shared between
2210 * -- importMachineGeneric() for the OVF case; in that case the information comes from
2211 * the OVF virtual systems;
2212 * -- importVBoxMachine(); in that case, the information comes from the <vbox:Machine>
2213 * tag.
2214 *
2215 * Both ways of describing machines use the OVF disk references section, so in both cases
2216 * the caller needs to pass in the ovf::DiskImage structure from ovfreader.cpp.
2217 *
2218 * As a result, in both cases, if di.strHref is empty, we create a new disk as per the OVF
2219 * spec, even though this cannot really happen in the vbox:Machine case since such data
2220 * would never have been exported.
2221 *
2222 * This advances stack.pProgress by one operation with the disk's weight.
2223 *
2224 * @param di ovfreader.cpp structure describing the disk image from the OVF that is to be imported
2225 * @param strTargetPath Where to create the target image.
2226 * @param pTargetHD out: The newly created target disk. This also gets pushed on stack.llHardDisksCreated for cleanup.
2227 * @param stack
2228 */
2229void Appliance::importOneDiskImage(const ovf::DiskImage &di,
2230 Utf8Str *strTargetPath,
2231 ComObjPtr<Medium> &pTargetHD,
2232 ImportStack &stack,
2233 PVDINTERFACEIO pCallbacks,
2234 PSHASTORAGE pStorage)
2235{
2236 SHASTORAGE finalStorage;
2237 PSHASTORAGE pRealUsedStorage = pStorage;/* may be changed later to finalStorage */
2238 PVDINTERFACEIO pFileIo = NULL;/* used in GZIP case*/
2239 ComObjPtr<Progress> pProgress;
2240 pProgress.createObject();
2241 HRESULT rc = pProgress->init(mVirtualBox,
2242 static_cast<IAppliance*>(this),
2243 BstrFmt(tr("Creating medium '%s'"),
2244 strTargetPath->c_str()).raw(),
2245 TRUE);
2246 if (FAILED(rc)) throw rc;
2247
2248 /* Get the system properties. */
2249 SystemProperties *pSysProps = mVirtualBox->getSystemProperties();
2250
2251 /*
2252 * we put strSourceOVF into the stack.llSrcDisksDigest in the end of this
2253 * function like a key for a later validation of the SHA digests
2254 */
2255 const Utf8Str &strSourceOVF = di.strHref;
2256
2257 Utf8Str strSrcFilePath(stack.strSourceDir);
2258 Utf8Str strTargetDir(*strTargetPath);
2259
2260 /* Construct source file path */
2261 Utf8Str name = applianceIOName(applianceIOTar);
2262
2263 if (RTStrNICmp(pStorage->pVDImageIfaces->pszInterfaceName, name.c_str(), name.length()) == 0)
2264 strSrcFilePath = strSourceOVF;
2265 else
2266 {
2267 strSrcFilePath.append(RTPATH_SLASH_STR);
2268 strSrcFilePath.append(strSourceOVF);
2269 }
2270
2271 /* First of all check if the path is an UUID. If so, the user like to
2272 * import the disk into an existing path. This is useful for iSCSI for
2273 * example. */
2274 RTUUID uuid;
2275 int vrc = RTUuidFromStr(&uuid, strTargetPath->c_str());
2276 if (vrc == VINF_SUCCESS)
2277 {
2278 rc = mVirtualBox->findHardDiskById(Guid(uuid), true, &pTargetHD);
2279 if (FAILED(rc)) throw rc;
2280 }
2281 else
2282 {
2283 bool fGzipUsed = !(di.strCompression.compare("gzip",Utf8Str::CaseInsensitive));
2284 /* check read file to GZIP compression */
2285 try
2286 {
2287 if (fGzipUsed == true)
2288 {
2289 /*
2290 * Create the necessary file access interfaces.
2291 * For the next step:
2292 * We need to replace the previously created chain of SHA-TAR or SHA-FILE interfaces
2293 * with simple FILE interface because we don't need SHA or TAR interfaces here anymore.
2294 * But we mustn't delete the chain of SHA-TAR or SHA-FILE interfaces.
2295 */
2296
2297 /* Decompress the GZIP file and save a new file in the target path */
2298 strTargetDir = strTargetDir.stripFilename();
2299 strTargetDir.append("/temp_");
2300
2301 Utf8Str strTempTargetFilename(*strTargetPath);
2302 strTempTargetFilename = strTempTargetFilename.stripPath();
2303 strTempTargetFilename = strTempTargetFilename.stripSuffix();
2304 Utf8Str vdf = typeOfVirtualDiskFormatFromURI(di.strFormat);
2305
2306 strTargetDir.append(strTempTargetFilename);
2307
2308 vrc = decompressImageAndSave(strSrcFilePath.c_str(), strTargetDir.c_str(), pCallbacks, pStorage);
2309
2310 if (RT_FAILURE(vrc))
2311 throw setError(VBOX_E_FILE_ERROR,
2312 tr("Could not read the file '%s' (%Rrc)"),
2313 RTPathFilename(strSrcFilePath.c_str()), vrc);
2314
2315 /* Create the necessary file access interfaces. */
2316 pFileIo = FileCreateInterface();
2317 if (!pFileIo)
2318 throw setError(E_OUTOFMEMORY);
2319
2320 name = applianceIOName(applianceIOFile);
2321
2322 vrc = VDInterfaceAdd(&pFileIo->Core, name.c_str(),
2323 VDINTERFACETYPE_IO, NULL, sizeof(VDINTERFACEIO),
2324 &finalStorage.pVDImageIfaces);
2325 if (RT_FAILURE(vrc))
2326 throw setError(VBOX_E_IPRT_ERROR,
2327 tr("Creation of the VD interface failed (%Rrc)"), vrc);
2328
2329 /* Correct the source and the target with the actual values */
2330 strSrcFilePath = strTargetDir;
2331 strTargetDir = strTargetDir.stripFilename();
2332 strTargetDir.append(RTPATH_SLASH_STR);
2333 strTargetDir.append(strTempTargetFilename.c_str());
2334 *strTargetPath = strTargetDir.c_str();
2335
2336 pRealUsedStorage = &finalStorage;
2337 }
2338
2339 Utf8Str strTrgFormat = "VMDK";
2340 ULONG lCabs = 0;
2341
2342 if (RTPathHasSuffix(strTargetPath->c_str()))
2343 {
2344 const char *pszSuff = RTPathSuffix(strTargetPath->c_str());
2345 /* Figure out which format the user like to have. Default is VMDK. */
2346 ComObjPtr<MediumFormat> trgFormat = pSysProps->mediumFormatFromExtension(&pszSuff[1]);
2347 if (trgFormat.isNull())
2348 throw setError(VBOX_E_NOT_SUPPORTED,
2349 tr("Could not find a valid medium format for the target disk '%s'"),
2350 strTargetPath->c_str());
2351 /* Check the capabilities. We need create capabilities. */
2352 lCabs = 0;
2353 com::SafeArray <MediumFormatCapabilities_T> mediumFormatCap;
2354 rc = trgFormat->COMGETTER(Capabilities)(ComSafeArrayAsOutParam(mediumFormatCap));
2355
2356 if (FAILED(rc))
2357 throw rc;
2358 else
2359 {
2360 for (ULONG j = 0; j < mediumFormatCap.size(); j++)
2361 lCabs |= mediumFormatCap[j];
2362 }
2363
2364 if (!( ((lCabs & MediumFormatCapabilities_CreateFixed) == MediumFormatCapabilities_CreateFixed)
2365 || ((lCabs & MediumFormatCapabilities_CreateDynamic) == MediumFormatCapabilities_CreateDynamic)))
2366 throw setError(VBOX_E_NOT_SUPPORTED,
2367 tr("Could not find a valid medium format for the target disk '%s'"),
2368 strTargetPath->c_str());
2369 Bstr bstrFormatName;
2370 rc = trgFormat->COMGETTER(Name)(bstrFormatName.asOutParam());
2371 if (FAILED(rc)) throw rc;
2372 strTrgFormat = Utf8Str(bstrFormatName);
2373 }
2374 else
2375 {
2376 throw setError(VBOX_E_FILE_ERROR,
2377 tr("The target disk '%s' has no extension "),
2378 strTargetPath->c_str(), VERR_INVALID_NAME);
2379 }
2380
2381 /* Create an IMedium object. */
2382 pTargetHD.createObject();
2383
2384 /*CD/DVD case*/
2385 if (strTrgFormat.compare("RAW", Utf8Str::CaseInsensitive) == 0)
2386 {
2387 try
2388 {
2389 if (fGzipUsed == true)
2390 {
2391 /*
2392 * The source and target pathes are the same.
2393 * It means that we have the needed file already.
2394 * For example, in GZIP case, we decompress the file and save it in the target path,
2395 * but with some prefix like "temp_". See part "check read file to GZIP compression" earlier
2396 * in this function.
2397 * Just rename the file by deleting "temp_" from it's name
2398 */
2399 vrc = RTFileRename(strSrcFilePath.c_str(), strTargetPath->c_str(), RTPATHRENAME_FLAGS_NO_REPLACE);
2400 if (RT_FAILURE(vrc))
2401 throw setError(VBOX_E_FILE_ERROR,
2402 tr("Could not rename the file '%s' (%Rrc)"),
2403 RTPathFilename(strSourceOVF.c_str()), vrc);
2404 }
2405 else
2406 {
2407 /* Calculating SHA digest for ISO file while copying one */
2408 vrc = copyFileAndCalcShaDigest(strSrcFilePath.c_str(),
2409 strTargetPath->c_str(),
2410 pCallbacks,
2411 pRealUsedStorage);
2412
2413 if (RT_FAILURE(vrc))
2414 throw setError(VBOX_E_FILE_ERROR,
2415 tr("Could not copy ISO file '%s' listed in the OVF file (%Rrc)"),
2416 RTPathFilename(strSourceOVF.c_str()), vrc);
2417 }
2418 }
2419 catch (HRESULT arc)
2420 {
2421 throw;
2422 }
2423
2424 /* Advance to the next operation. */
2425 /* operation's weight, as set up with the IProgress originally */
2426 stack.pProgress->SetNextOperation(BstrFmt(tr("Importing virtual disk image '%s'"),
2427 RTPathFilename(strSourceOVF.c_str())).raw(),
2428 di.ulSuggestedSizeMB);
2429 }
2430 else/* HDD case*/
2431 {
2432 rc = pTargetHD->init(mVirtualBox,
2433 strTrgFormat,
2434 *strTargetPath,
2435 Guid::Empty /* media registry: none yet */);
2436 if (FAILED(rc)) throw rc;
2437
2438 /* Now create an empty hard disk. */
2439 rc = mVirtualBox->CreateHardDisk(Bstr(strTrgFormat).raw(),
2440 Bstr(*strTargetPath).raw(),
2441 ComPtr<IMedium>(pTargetHD).asOutParam());
2442 if (FAILED(rc)) throw rc;
2443
2444 /* If strHref is empty we have to create a new file. */
2445 if (strSourceOVF.isEmpty())
2446 {
2447 com::SafeArray<MediumVariant_T> mediumVariant;
2448 mediumVariant.push_back(MediumVariant_Standard);
2449 /* Create a dynamic growing disk image with the given capacity. */
2450 rc = pTargetHD->CreateBaseStorage(di.iCapacity / _1M,
2451 ComSafeArrayAsInParam(mediumVariant),
2452 ComPtr<IProgress>(pProgress).asOutParam());
2453 if (FAILED(rc)) throw rc;
2454
2455 /* Advance to the next operation. */
2456 /* operation's weight, as set up with the IProgress originally */
2457 stack.pProgress->SetNextOperation(BstrFmt(tr("Creating disk image '%s'"),
2458 strTargetPath->c_str()).raw(),
2459 di.ulSuggestedSizeMB);
2460 }
2461 else
2462 {
2463 /* We need a proper source format description */
2464 ComObjPtr<MediumFormat> srcFormat;
2465 /* Which format to use? */
2466 Utf8Str strSrcFormat = "VDI";
2467
2468 std::set<Utf8Str> listURIs = Appliance::URIFromTypeOfVirtualDiskFormat("VMDK");
2469 std::set<Utf8Str>::const_iterator itr = listURIs.find(di.strFormat);
2470
2471 if (itr != listURIs.end())
2472 {
2473 strSrcFormat = "VMDK";
2474 }
2475
2476 srcFormat = pSysProps->mediumFormat(strSrcFormat);
2477 if (srcFormat.isNull())
2478 throw setError(VBOX_E_NOT_SUPPORTED,
2479 tr("Could not find a valid medium format for the source disk '%s'"),
2480 RTPathFilename(strSourceOVF.c_str()));
2481
2482 /* Clone the source disk image */
2483 ComObjPtr<Medium> nullParent;
2484 rc = pTargetHD->importFile(strSrcFilePath.c_str(),
2485 srcFormat,
2486 MediumVariant_Standard,
2487 pCallbacks, pRealUsedStorage,
2488 nullParent,
2489 pProgress);
2490 if (FAILED(rc)) throw rc;
2491
2492
2493
2494 /* Advance to the next operation. */
2495 /* operation's weight, as set up with the IProgress originally */
2496 stack.pProgress->SetNextOperation(BstrFmt(tr("Importing virtual disk image '%s'"),
2497 RTPathFilename(strSourceOVF.c_str())).raw(),
2498 di.ulSuggestedSizeMB);
2499 }
2500
2501 /* Now wait for the background disk operation to complete; this throws
2502 * HRESULTs on error. */
2503 ComPtr<IProgress> pp(pProgress);
2504 waitForAsyncProgress(stack.pProgress, pp);
2505
2506 if (fGzipUsed == true)
2507 {
2508 /*
2509 * Just delete the temporary file
2510 */
2511 vrc = RTFileDelete(strSrcFilePath.c_str());
2512 if (RT_FAILURE(vrc))
2513 setWarning(VBOX_E_FILE_ERROR,
2514 tr("Could not delete the file '%s' (%Rrc)"),
2515 RTPathFilename(strSrcFilePath.c_str()), vrc);
2516 }
2517 }
2518 }
2519 catch (...)
2520 {
2521 if (pFileIo)
2522 RTMemFree(pFileIo);
2523
2524 throw;
2525 }
2526 }
2527
2528 if (pFileIo)
2529 RTMemFree(pFileIo);
2530
2531 /* Add the newly create disk path + a corresponding digest the our list for
2532 * later manifest verification. */
2533 stack.llSrcDisksDigest.push_back(STRPAIR(strSourceOVF, pStorage ? pStorage->strDigest : ""));
2534}
2535
2536/**
2537 * Imports one OVF virtual system (described by the given ovf::VirtualSystem and VirtualSystemDescription)
2538 * into VirtualBox by creating an IMachine instance, which is returned.
2539 *
2540 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
2541 * up any leftovers from this function. For this, the given ImportStack instance has received information
2542 * about what needs cleaning up (to support rollback).
2543 *
2544 * @param vsysThis OVF virtual system (machine) to import.
2545 * @param vsdescThis Matching virtual system description (machine) to import.
2546 * @param pNewMachine out: Newly created machine.
2547 * @param stack Cleanup stack for when this throws.
2548 */
2549void Appliance::importMachineGeneric(const ovf::VirtualSystem &vsysThis,
2550 ComObjPtr<VirtualSystemDescription> &vsdescThis,
2551 ComPtr<IMachine> &pNewMachine,
2552 ImportStack &stack,
2553 PVDINTERFACEIO pCallbacks,
2554 PSHASTORAGE pStorage)
2555{
2556 HRESULT rc;
2557
2558 // Get the instance of IGuestOSType which matches our string guest OS type so we
2559 // can use recommended defaults for the new machine where OVF doesn't provide any
2560 ComPtr<IGuestOSType> osType;
2561 rc = mVirtualBox->GetGuestOSType(Bstr(stack.strOsTypeVBox).raw(), osType.asOutParam());
2562 if (FAILED(rc)) throw rc;
2563
2564 /* Create the machine */
2565 SafeArray<BSTR> groups; /* no groups */
2566 rc = mVirtualBox->CreateMachine(NULL, /* machine name: use default */
2567 Bstr(stack.strNameVBox).raw(),
2568 ComSafeArrayAsInParam(groups),
2569 Bstr(stack.strOsTypeVBox).raw(),
2570 NULL, /* aCreateFlags */
2571 pNewMachine.asOutParam());
2572 if (FAILED(rc)) throw rc;
2573
2574 // set the description
2575 if (!stack.strDescription.isEmpty())
2576 {
2577 rc = pNewMachine->COMSETTER(Description)(Bstr(stack.strDescription).raw());
2578 if (FAILED(rc)) throw rc;
2579 }
2580
2581 // CPU count
2582 rc = pNewMachine->COMSETTER(CPUCount)(stack.cCPUs);
2583 if (FAILED(rc)) throw rc;
2584
2585 if (stack.fForceHWVirt)
2586 {
2587 rc = pNewMachine->SetHWVirtExProperty(HWVirtExPropertyType_Enabled, TRUE);
2588 if (FAILED(rc)) throw rc;
2589 }
2590
2591 // RAM
2592 rc = pNewMachine->COMSETTER(MemorySize)(stack.ulMemorySizeMB);
2593 if (FAILED(rc)) throw rc;
2594
2595 /* VRAM */
2596 /* Get the recommended VRAM for this guest OS type */
2597 ULONG vramVBox;
2598 rc = osType->COMGETTER(RecommendedVRAM)(&vramVBox);
2599 if (FAILED(rc)) throw rc;
2600
2601 /* Set the VRAM */
2602 rc = pNewMachine->COMSETTER(VRAMSize)(vramVBox);
2603 if (FAILED(rc)) throw rc;
2604
2605 // I/O APIC: Generic OVF has no setting for this. Enable it if we
2606 // import a Windows VM because if if Windows was installed without IOAPIC,
2607 // it will not mind finding an one later on, but if Windows was installed
2608 // _with_ an IOAPIC, it will bluescreen if it's not found
2609 if (!stack.fForceIOAPIC)
2610 {
2611 Bstr bstrFamilyId;
2612 rc = osType->COMGETTER(FamilyId)(bstrFamilyId.asOutParam());
2613 if (FAILED(rc)) throw rc;
2614 if (bstrFamilyId == "Windows")
2615 stack.fForceIOAPIC = true;
2616 }
2617
2618 if (stack.fForceIOAPIC)
2619 {
2620 ComPtr<IBIOSSettings> pBIOSSettings;
2621 rc = pNewMachine->COMGETTER(BIOSSettings)(pBIOSSettings.asOutParam());
2622 if (FAILED(rc)) throw rc;
2623
2624 rc = pBIOSSettings->COMSETTER(IOAPICEnabled)(TRUE);
2625 if (FAILED(rc)) throw rc;
2626 }
2627
2628 if (!stack.strAudioAdapter.isEmpty())
2629 if (stack.strAudioAdapter.compare("null", Utf8Str::CaseInsensitive) != 0)
2630 {
2631 uint32_t audio = RTStrToUInt32(stack.strAudioAdapter.c_str()); // should be 0 for AC97
2632 ComPtr<IAudioAdapter> audioAdapter;
2633 rc = pNewMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam());
2634 if (FAILED(rc)) throw rc;
2635 rc = audioAdapter->COMSETTER(Enabled)(true);
2636 if (FAILED(rc)) throw rc;
2637 rc = audioAdapter->COMSETTER(AudioController)(static_cast<AudioControllerType_T>(audio));
2638 if (FAILED(rc)) throw rc;
2639 }
2640
2641#ifdef VBOX_WITH_USB
2642 /* USB Controller */
2643 if (stack.fUSBEnabled)
2644 {
2645 ComPtr<IUSBController> usbController;
2646 rc = pNewMachine->AddUSBController(Bstr("OHCI").raw(), USBControllerType_OHCI, usbController.asOutParam());
2647 if (FAILED(rc)) throw rc;
2648 }
2649#endif /* VBOX_WITH_USB */
2650
2651 /* Change the network adapters */
2652 uint32_t maxNetworkAdapters = Global::getMaxNetworkAdapters(ChipsetType_PIIX3);
2653
2654 std::list<VirtualSystemDescriptionEntry*> vsdeNW = vsdescThis->findByType(VirtualSystemDescriptionType_NetworkAdapter);
2655 if (vsdeNW.size() == 0)
2656 {
2657 /* No network adapters, so we have to disable our default one */
2658 ComPtr<INetworkAdapter> nwVBox;
2659 rc = pNewMachine->GetNetworkAdapter(0, nwVBox.asOutParam());
2660 if (FAILED(rc)) throw rc;
2661 rc = nwVBox->COMSETTER(Enabled)(false);
2662 if (FAILED(rc)) throw rc;
2663 }
2664 else if (vsdeNW.size() > maxNetworkAdapters)
2665 throw setError(VBOX_E_FILE_ERROR,
2666 tr("Too many network adapters: OVF requests %d network adapters, "
2667 "but VirtualBox only supports %d"),
2668 vsdeNW.size(), maxNetworkAdapters);
2669 else
2670 {
2671 list<VirtualSystemDescriptionEntry*>::const_iterator nwIt;
2672 size_t a = 0;
2673 for (nwIt = vsdeNW.begin();
2674 nwIt != vsdeNW.end();
2675 ++nwIt, ++a)
2676 {
2677 const VirtualSystemDescriptionEntry* pvsys = *nwIt;
2678
2679 const Utf8Str &nwTypeVBox = pvsys->strVboxCurrent;
2680 uint32_t tt1 = RTStrToUInt32(nwTypeVBox.c_str());
2681 ComPtr<INetworkAdapter> pNetworkAdapter;
2682 rc = pNewMachine->GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
2683 if (FAILED(rc)) throw rc;
2684 /* Enable the network card & set the adapter type */
2685 rc = pNetworkAdapter->COMSETTER(Enabled)(true);
2686 if (FAILED(rc)) throw rc;
2687 rc = pNetworkAdapter->COMSETTER(AdapterType)(static_cast<NetworkAdapterType_T>(tt1));
2688 if (FAILED(rc)) throw rc;
2689
2690 // default is NAT; change to "bridged" if extra conf says so
2691 if (pvsys->strExtraConfigCurrent.endsWith("type=Bridged", Utf8Str::CaseInsensitive))
2692 {
2693 /* Attach to the right interface */
2694 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_Bridged);
2695 if (FAILED(rc)) throw rc;
2696 ComPtr<IHost> host;
2697 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
2698 if (FAILED(rc)) throw rc;
2699 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
2700 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
2701 if (FAILED(rc)) throw rc;
2702 // We search for the first host network interface which
2703 // is usable for bridged networking
2704 for (size_t j = 0;
2705 j < nwInterfaces.size();
2706 ++j)
2707 {
2708 HostNetworkInterfaceType_T itype;
2709 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
2710 if (FAILED(rc)) throw rc;
2711 if (itype == HostNetworkInterfaceType_Bridged)
2712 {
2713 Bstr name;
2714 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
2715 if (FAILED(rc)) throw rc;
2716 /* Set the interface name to attach to */
2717 rc = pNetworkAdapter->COMSETTER(BridgedInterface)(name.raw());
2718 if (FAILED(rc)) throw rc;
2719 break;
2720 }
2721 }
2722 }
2723 /* Next test for host only interfaces */
2724 else if (pvsys->strExtraConfigCurrent.endsWith("type=HostOnly", Utf8Str::CaseInsensitive))
2725 {
2726 /* Attach to the right interface */
2727 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_HostOnly);
2728 if (FAILED(rc)) throw rc;
2729 ComPtr<IHost> host;
2730 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
2731 if (FAILED(rc)) throw rc;
2732 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
2733 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
2734 if (FAILED(rc)) throw rc;
2735 // We search for the first host network interface which
2736 // is usable for host only networking
2737 for (size_t j = 0;
2738 j < nwInterfaces.size();
2739 ++j)
2740 {
2741 HostNetworkInterfaceType_T itype;
2742 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
2743 if (FAILED(rc)) throw rc;
2744 if (itype == HostNetworkInterfaceType_HostOnly)
2745 {
2746 Bstr name;
2747 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
2748 if (FAILED(rc)) throw rc;
2749 /* Set the interface name to attach to */
2750 rc = pNetworkAdapter->COMSETTER(HostOnlyInterface)(name.raw());
2751 if (FAILED(rc)) throw rc;
2752 break;
2753 }
2754 }
2755 }
2756 /* Next test for internal interfaces */
2757 else if (pvsys->strExtraConfigCurrent.endsWith("type=Internal", Utf8Str::CaseInsensitive))
2758 {
2759 /* Attach to the right interface */
2760 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_Internal);
2761 if (FAILED(rc)) throw rc;
2762 }
2763 /* Next test for Generic interfaces */
2764 else if (pvsys->strExtraConfigCurrent.endsWith("type=Generic", Utf8Str::CaseInsensitive))
2765 {
2766 /* Attach to the right interface */
2767 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_Generic);
2768 if (FAILED(rc)) throw rc;
2769 }
2770 /* Next test for NAT network interfaces */
2771 else if (pvsys->strExtraConfigCurrent.endsWith("type=NATNetwork", Utf8Str::CaseInsensitive))
2772 {
2773 /* Attach to the right interface */
2774 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_NATNetwork);
2775 if (FAILED(rc)) throw rc;
2776 com::SafeIfaceArray<INATNetwork> nwNATNetworks;
2777 rc = mVirtualBox->COMGETTER(NATNetworks)(ComSafeArrayAsOutParam(nwNATNetworks));
2778 if (FAILED(rc)) throw rc;
2779 // Pick the first NAT network (if there is any)
2780 if (nwNATNetworks.size())
2781 {
2782 Bstr name;
2783 rc = nwNATNetworks[0]->COMGETTER(NetworkName)(name.asOutParam());
2784 if (FAILED(rc)) throw rc;
2785 /* Set the NAT network name to attach to */
2786 rc = pNetworkAdapter->COMSETTER(NATNetwork)(name.raw());
2787 if (FAILED(rc)) throw rc;
2788 break;
2789 }
2790 }
2791 }
2792 }
2793
2794 // IDE Hard disk controller
2795 std::list<VirtualSystemDescriptionEntry*> vsdeHDCIDE = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerIDE);
2796 /*
2797 * In OVF (at least VMware's version of it), an IDE controller has two ports,
2798 * so VirtualBox's single IDE controller with two channels and two ports each counts as
2799 * two OVF IDE controllers -- so we accept one or two such IDE controllers
2800 */
2801 size_t cIDEControllers = vsdeHDCIDE.size();
2802 if (cIDEControllers > 2)
2803 throw setError(VBOX_E_FILE_ERROR,
2804 tr("Too many IDE controllers in OVF; import facility only supports two"));
2805 if (vsdeHDCIDE.size() > 0)
2806 {
2807 // one or two IDE controllers present in OVF: add one VirtualBox controller
2808 ComPtr<IStorageController> pController;
2809 rc = pNewMachine->AddStorageController(Bstr("IDE Controller").raw(), StorageBus_IDE, pController.asOutParam());
2810 if (FAILED(rc)) throw rc;
2811
2812 const char *pcszIDEType = vsdeHDCIDE.front()->strVboxCurrent.c_str();
2813 if (!strcmp(pcszIDEType, "PIIX3"))
2814 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX3);
2815 else if (!strcmp(pcszIDEType, "PIIX4"))
2816 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX4);
2817 else if (!strcmp(pcszIDEType, "ICH6"))
2818 rc = pController->COMSETTER(ControllerType)(StorageControllerType_ICH6);
2819 else
2820 throw setError(VBOX_E_FILE_ERROR,
2821 tr("Invalid IDE controller type \"%s\""),
2822 pcszIDEType);
2823 if (FAILED(rc)) throw rc;
2824 }
2825
2826 /* Hard disk controller SATA */
2827 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSATA = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSATA);
2828 if (vsdeHDCSATA.size() > 1)
2829 throw setError(VBOX_E_FILE_ERROR,
2830 tr("Too many SATA controllers in OVF; import facility only supports one"));
2831 if (vsdeHDCSATA.size() > 0)
2832 {
2833 ComPtr<IStorageController> pController;
2834 const Utf8Str &hdcVBox = vsdeHDCSATA.front()->strVboxCurrent;
2835 if (hdcVBox == "AHCI")
2836 {
2837 rc = pNewMachine->AddStorageController(Bstr("SATA Controller").raw(),
2838 StorageBus_SATA,
2839 pController.asOutParam());
2840 if (FAILED(rc)) throw rc;
2841 }
2842 else
2843 throw setError(VBOX_E_FILE_ERROR,
2844 tr("Invalid SATA controller type \"%s\""),
2845 hdcVBox.c_str());
2846 }
2847
2848 /* Hard disk controller SCSI */
2849 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSCSI = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSCSI);
2850 if (vsdeHDCSCSI.size() > 1)
2851 throw setError(VBOX_E_FILE_ERROR,
2852 tr("Too many SCSI controllers in OVF; import facility only supports one"));
2853 if (vsdeHDCSCSI.size() > 0)
2854 {
2855 ComPtr<IStorageController> pController;
2856 Bstr bstrName(L"SCSI Controller");
2857 StorageBus_T busType = StorageBus_SCSI;
2858 StorageControllerType_T controllerType;
2859 const Utf8Str &hdcVBox = vsdeHDCSCSI.front()->strVboxCurrent;
2860 if (hdcVBox == "LsiLogic")
2861 controllerType = StorageControllerType_LsiLogic;
2862 else if (hdcVBox == "LsiLogicSas")
2863 {
2864 // OVF treats LsiLogicSas as a SCSI controller but VBox considers it a class of its own
2865 bstrName = L"SAS Controller";
2866 busType = StorageBus_SAS;
2867 controllerType = StorageControllerType_LsiLogicSas;
2868 }
2869 else if (hdcVBox == "BusLogic")
2870 controllerType = StorageControllerType_BusLogic;
2871 else
2872 throw setError(VBOX_E_FILE_ERROR,
2873 tr("Invalid SCSI controller type \"%s\""),
2874 hdcVBox.c_str());
2875
2876 rc = pNewMachine->AddStorageController(bstrName.raw(), busType, pController.asOutParam());
2877 if (FAILED(rc)) throw rc;
2878 rc = pController->COMSETTER(ControllerType)(controllerType);
2879 if (FAILED(rc)) throw rc;
2880 }
2881
2882 /* Hard disk controller SAS */
2883 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSAS = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSAS);
2884 if (vsdeHDCSAS.size() > 1)
2885 throw setError(VBOX_E_FILE_ERROR,
2886 tr("Too many SAS controllers in OVF; import facility only supports one"));
2887 if (vsdeHDCSAS.size() > 0)
2888 {
2889 ComPtr<IStorageController> pController;
2890 rc = pNewMachine->AddStorageController(Bstr(L"SAS Controller").raw(),
2891 StorageBus_SAS,
2892 pController.asOutParam());
2893 if (FAILED(rc)) throw rc;
2894 rc = pController->COMSETTER(ControllerType)(StorageControllerType_LsiLogicSas);
2895 if (FAILED(rc)) throw rc;
2896 }
2897
2898 /* Now its time to register the machine before we add any hard disks */
2899 rc = mVirtualBox->RegisterMachine(pNewMachine);
2900 if (FAILED(rc)) throw rc;
2901
2902 // store new machine for roll-back in case of errors
2903 Bstr bstrNewMachineId;
2904 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
2905 if (FAILED(rc)) throw rc;
2906 Guid uuidNewMachine(bstrNewMachineId);
2907 m->llGuidsMachinesCreated.push_back(uuidNewMachine);
2908
2909 // Add floppies and CD-ROMs to the appropriate controllers.
2910 std::list<VirtualSystemDescriptionEntry*> vsdeFloppy = vsdescThis->findByType(VirtualSystemDescriptionType_Floppy);
2911 if (vsdeFloppy.size() > 1)
2912 throw setError(VBOX_E_FILE_ERROR,
2913 tr("Too many floppy controllers in OVF; import facility only supports one"));
2914 std::list<VirtualSystemDescriptionEntry*> vsdeCDROM = vsdescThis->findByType(VirtualSystemDescriptionType_CDROM);
2915 if ( (vsdeFloppy.size() > 0)
2916 || (vsdeCDROM.size() > 0)
2917 )
2918 {
2919 // If there's an error here we need to close the session, so
2920 // we need another try/catch block.
2921
2922 try
2923 {
2924 // to attach things we need to open a session for the new machine
2925 rc = pNewMachine->LockMachine(stack.pSession, LockType_Write);
2926 if (FAILED(rc)) throw rc;
2927 stack.fSessionOpen = true;
2928
2929 ComPtr<IMachine> sMachine;
2930 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
2931 if (FAILED(rc)) throw rc;
2932
2933 // floppy first
2934 if (vsdeFloppy.size() == 1)
2935 {
2936 ComPtr<IStorageController> pController;
2937 rc = sMachine->AddStorageController(Bstr("Floppy Controller").raw(),
2938 StorageBus_Floppy,
2939 pController.asOutParam());
2940 if (FAILED(rc)) throw rc;
2941
2942 Bstr bstrName;
2943 rc = pController->COMGETTER(Name)(bstrName.asOutParam());
2944 if (FAILED(rc)) throw rc;
2945
2946 // this is for rollback later
2947 MyHardDiskAttachment mhda;
2948 mhda.pMachine = pNewMachine;
2949 mhda.controllerType = bstrName;
2950 mhda.lControllerPort = 0;
2951 mhda.lDevice = 0;
2952
2953 Log(("Attaching floppy\n"));
2954
2955 rc = sMachine->AttachDevice(mhda.controllerType.raw(),
2956 mhda.lControllerPort,
2957 mhda.lDevice,
2958 DeviceType_Floppy,
2959 NULL);
2960 if (FAILED(rc)) throw rc;
2961
2962 stack.llHardDiskAttachments.push_back(mhda);
2963 }
2964
2965 rc = sMachine->SaveSettings();
2966 if (FAILED(rc)) throw rc;
2967
2968 // only now that we're done with all disks, close the session
2969 rc = stack.pSession->UnlockMachine();
2970 if (FAILED(rc)) throw rc;
2971 stack.fSessionOpen = false;
2972 }
2973 catch(HRESULT /* aRC */)
2974 {
2975 if (stack.fSessionOpen)
2976 stack.pSession->UnlockMachine();
2977
2978 throw;
2979 }
2980 }
2981
2982 // create the hard disks & connect them to the appropriate controllers
2983 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
2984 if (avsdeHDs.size() > 0)
2985 {
2986 // If there's an error here we need to close the session, so
2987 // we need another try/catch block.
2988 try
2989 {
2990 // to attach things we need to open a session for the new machine
2991 rc = pNewMachine->LockMachine(stack.pSession, LockType_Write);
2992 if (FAILED(rc)) throw rc;
2993 stack.fSessionOpen = true;
2994
2995 ovf::DiskImagesMap::const_iterator oit = stack.mapDisks.begin();
2996 std::set<RTCString> disksResolvedNames;
2997
2998 while(oit != stack.mapDisks.end())
2999 {
3000 ovf::DiskImage diCurrent = oit->second;
3001 ovf::VirtualDisksMap::const_iterator itVDisk = vsysThis.mapVirtualDisks.begin();
3002
3003 VirtualSystemDescriptionEntry *vsdeTargetHD = 0;
3004
3005 /*
3006 *
3007 * Iterate over all given disk images of the virtual system
3008 * disks description. We need to find the target disk path,
3009 * which could be changed by the user.
3010 *
3011 */
3012 {
3013 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
3014 for (itHD = avsdeHDs.begin();
3015 itHD != avsdeHDs.end();
3016 ++itHD)
3017 {
3018 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
3019 if (vsdeHD->strRef == diCurrent.strDiskId)
3020 {
3021 vsdeTargetHD = vsdeHD;
3022 break;
3023 }
3024 }
3025 if (!vsdeTargetHD)
3026 throw setError(E_FAIL,
3027 tr("Internal inconsistency looking up disk image '%s'"),
3028 diCurrent.strHref.c_str());
3029
3030 //diCurrent.strDiskId contains the disk identifier (e.g. "vmdisk1"), which should exist
3031 //in the virtual system's disks map under that ID and also in the global images map
3032 itVDisk = vsysThis.mapVirtualDisks.find(diCurrent.strDiskId);
3033 if (itVDisk == vsysThis.mapVirtualDisks.end())
3034 throw setError(E_FAIL,
3035 tr("Internal inconsistency looking up disk image '%s'"),
3036 diCurrent.strHref.c_str());
3037 }
3038
3039 /*
3040 * preliminary check availability of the image
3041 * This step is useful if image is placed in the OVA (TAR) package
3042 */
3043
3044 Utf8Str name = applianceIOName(applianceIOTar);
3045
3046 if (strncmp(pStorage->pVDImageIfaces->pszInterfaceName, name.c_str(), name.length()) == 0)
3047 {
3048 /* It means that we possibly have imported the storage earlier on the previous loop steps*/
3049 std::set<RTCString>::const_iterator h = disksResolvedNames.find(diCurrent.strHref);
3050 if (h != disksResolvedNames.end())
3051 {
3052 /* Yes, disk name was found, we can skip it*/
3053 ++oit;
3054 continue;
3055 }
3056
3057 RTCString availableImage(diCurrent.strHref);
3058
3059 rc = preCheckImageAvailability(pStorage,
3060 availableImage
3061 );
3062
3063 if (SUCCEEDED(rc))
3064 {
3065 /* current opened file isn't the same as passed one */
3066 if(availableImage.compare(diCurrent.strHref, Utf8Str::CaseInsensitive) != 0)
3067 {
3068 /*
3069 * availableImage contains the disk file reference (e.g. "disk1.vmdk"), which should exist
3070 * in the global images map.
3071 * And find the disk from the OVF's disk list
3072 *
3073 */
3074 {
3075 ovf::DiskImagesMap::const_iterator itDiskImage = stack.mapDisks.begin();
3076 while (++itDiskImage != stack.mapDisks.end())
3077 {
3078 if (itDiskImage->second.strHref.compare(availableImage, Utf8Str::CaseInsensitive) == 0)
3079 break;
3080 }
3081 if (itDiskImage == stack.mapDisks.end())
3082 {
3083 throw setError(E_FAIL,
3084 tr("Internal inconsistency looking up disk image '%s'. "
3085 "Check compliance OVA package structure and file names "
3086 "references in the section <References> in the OVF file."),
3087 availableImage.c_str());
3088 }
3089
3090 /* replace with a new found disk image */
3091 diCurrent = *(&itDiskImage->second);
3092 }
3093
3094 /*
3095 * Again iterate over all given disk images of the virtual system
3096 * disks description using the found disk image
3097 */
3098 {
3099 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
3100 for (itHD = avsdeHDs.begin();
3101 itHD != avsdeHDs.end();
3102 ++itHD)
3103 {
3104 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
3105 if (vsdeHD->strRef == diCurrent.strDiskId)
3106 {
3107 vsdeTargetHD = vsdeHD;
3108 break;
3109 }
3110 }
3111 if (!vsdeTargetHD)
3112 throw setError(E_FAIL,
3113 tr("Internal inconsistency looking up disk image '%s'"),
3114 diCurrent.strHref.c_str());
3115
3116 itVDisk = vsysThis.mapVirtualDisks.find(diCurrent.strDiskId);
3117 if (itVDisk == vsysThis.mapVirtualDisks.end())
3118 throw setError(E_FAIL,
3119 tr("Internal inconsistency looking up disk image '%s'"),
3120 diCurrent.strHref.c_str());
3121 }
3122 }
3123 else
3124 {
3125 ++oit;
3126 }
3127 }
3128 else
3129 {
3130 ++oit;
3131 continue;
3132 }
3133 }
3134 else
3135 {
3136 /* just continue with normal files*/
3137 ++oit;
3138 }
3139
3140 const ovf::VirtualDisk &ovfVdisk = itVDisk->second;
3141
3142 /* very important to store disk name for the next checks */
3143 disksResolvedNames.insert(diCurrent.strHref);
3144
3145 ComObjPtr<Medium> pTargetHD;
3146
3147 Utf8Str savedVboxCurrent = vsdeTargetHD->strVboxCurrent;
3148
3149 importOneDiskImage(diCurrent,
3150 &vsdeTargetHD->strVboxCurrent,
3151 pTargetHD,
3152 stack,
3153 pCallbacks,
3154 pStorage);
3155
3156 // now use the new uuid to attach the disk image to our new machine
3157 ComPtr<IMachine> sMachine;
3158 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
3159 if (FAILED(rc)) throw rc;
3160
3161 // find the hard disk controller to which we should attach
3162 ovf::HardDiskController hdc = (*vsysThis.mapControllers.find(ovfVdisk.idController)).second;
3163
3164 // this is for rollback later
3165 MyHardDiskAttachment mhda;
3166 mhda.pMachine = pNewMachine;
3167
3168 convertDiskAttachmentValues(hdc,
3169 ovfVdisk.ulAddressOnParent,
3170 mhda.controllerType, // Bstr
3171 mhda.lControllerPort,
3172 mhda.lDevice);
3173
3174 Log(("Attaching disk %s to port %d on device %d\n",
3175 vsdeTargetHD->strVboxCurrent.c_str(), mhda.lControllerPort, mhda.lDevice));
3176
3177 Utf8Str vdf = typeOfVirtualDiskFormatFromURI(diCurrent.strFormat);
3178
3179 if (vdf.compare("RAW", Utf8Str::CaseInsensitive) == 0)
3180 {
3181 ComPtr<IMedium> dvdImage(pTargetHD);
3182
3183 rc = mVirtualBox->OpenMedium(Bstr(vsdeTargetHD->strVboxCurrent).raw(),
3184 DeviceType_DVD,
3185 AccessMode_ReadWrite,
3186 false,
3187 dvdImage.asOutParam());
3188
3189 if (FAILED(rc)) throw rc;
3190
3191 rc = sMachine->AttachDevice(mhda.controllerType.raw(),// wstring name
3192 mhda.lControllerPort, // long controllerPort
3193 mhda.lDevice, // long device
3194 DeviceType_DVD, // DeviceType_T type
3195 dvdImage);
3196 if (FAILED(rc)) throw rc;
3197 }
3198 else
3199 {
3200 rc = sMachine->AttachDevice(mhda.controllerType.raw(),// wstring name
3201 mhda.lControllerPort, // long controllerPort
3202 mhda.lDevice, // long device
3203 DeviceType_HardDisk, // DeviceType_T type
3204 pTargetHD);
3205
3206 if (FAILED(rc)) throw rc;
3207 }
3208
3209 stack.llHardDiskAttachments.push_back(mhda);
3210
3211 rc = sMachine->SaveSettings();
3212 if (FAILED(rc)) throw rc;
3213
3214 /* restore */
3215 vsdeTargetHD->strVboxCurrent = savedVboxCurrent;
3216
3217 } // end while(oit != stack.mapDisks.end())
3218
3219 // only now that we're done with all disks, close the session
3220 rc = stack.pSession->UnlockMachine();
3221 if (FAILED(rc)) throw rc;
3222 stack.fSessionOpen = false;
3223 }
3224 catch(HRESULT /* aRC */)
3225 {
3226 if (stack.fSessionOpen)
3227 stack.pSession->UnlockMachine();
3228
3229 throw;
3230 }
3231 }
3232}
3233
3234/**
3235 * Imports one OVF virtual system (described by a vbox:Machine tag represented by the given config
3236 * structure) into VirtualBox by creating an IMachine instance, which is returned.
3237 *
3238 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
3239 * up any leftovers from this function. For this, the given ImportStack instance has received information
3240 * about what needs cleaning up (to support rollback).
3241 *
3242 * The machine config stored in the settings::MachineConfigFile structure contains the UUIDs of
3243 * the disk attachments used by the machine when it was exported. We also add vbox:uuid attributes
3244 * to the OVF disks sections so we can look them up. While importing these UUIDs into a second host
3245 * will most probably work, reimporting them into the same host will cause conflicts, so we always
3246 * generate new ones on import. This involves the following:
3247 *
3248 * 1) Scan the machine config for disk attachments.
3249 *
3250 * 2) For each disk attachment found, look up the OVF disk image from the disk references section
3251 * and import the disk into VirtualBox, which creates a new UUID for it. In the machine config,
3252 * replace the old UUID with the new one.
3253 *
3254 * 3) Change the machine config according to the OVF virtual system descriptions, in case the
3255 * caller has modified them using setFinalValues().
3256 *
3257 * 4) Create the VirtualBox machine with the modfified machine config.
3258 *
3259 * @param config
3260 * @param pNewMachine
3261 * @param stack
3262 */
3263void Appliance::importVBoxMachine(ComObjPtr<VirtualSystemDescription> &vsdescThis,
3264 ComPtr<IMachine> &pReturnNewMachine,
3265 ImportStack &stack,
3266 PVDINTERFACEIO pCallbacks,
3267 PSHASTORAGE pStorage)
3268{
3269 Assert(vsdescThis->m->pConfig);
3270
3271 HRESULT rc = S_OK;
3272
3273 settings::MachineConfigFile &config = *vsdescThis->m->pConfig;
3274
3275 /*
3276 * step 1): modify machine config according to OVF config, in case the user
3277 * has modified them using setFinalValues()
3278 */
3279
3280 /* OS Type */
3281 config.machineUserData.strOsType = stack.strOsTypeVBox;
3282 /* Description */
3283 config.machineUserData.strDescription = stack.strDescription;
3284 /* CPU count & extented attributes */
3285 config.hardwareMachine.cCPUs = stack.cCPUs;
3286 if (stack.fForceIOAPIC)
3287 config.hardwareMachine.fHardwareVirt = true;
3288 if (stack.fForceIOAPIC)
3289 config.hardwareMachine.biosSettings.fIOAPICEnabled = true;
3290 /* RAM size */
3291 config.hardwareMachine.ulMemorySizeMB = stack.ulMemorySizeMB;
3292
3293/*
3294 <const name="HardDiskControllerIDE" value="14" />
3295 <const name="HardDiskControllerSATA" value="15" />
3296 <const name="HardDiskControllerSCSI" value="16" />
3297 <const name="HardDiskControllerSAS" value="17" />
3298*/
3299
3300#ifdef VBOX_WITH_USB
3301 /* USB controller */
3302 if (stack.fUSBEnabled)
3303 {
3304 /** @todo r=klaus add support for arbitrary USB controller types, this can't handle multiple controllers due to its design anyway */
3305
3306 /* usually the OHCI controller is enabled already, need to check */
3307 bool fOHCIEnabled = false;
3308 settings::USBControllerList &llUSBControllers = config.hardwareMachine.usbSettings.llUSBControllers;
3309 settings::USBControllerList::iterator it;
3310 for (it = llUSBControllers.begin(); it != llUSBControllers.end(); ++it)
3311 {
3312 if (it->enmType == USBControllerType_OHCI)
3313 {
3314 fOHCIEnabled = true;
3315 break;
3316 }
3317 }
3318
3319 if (!fOHCIEnabled)
3320 {
3321 settings::USBController ctrl;
3322 ctrl.strName = "OHCI";
3323 ctrl.enmType = USBControllerType_OHCI;
3324
3325 llUSBControllers.push_back(ctrl);
3326 }
3327 }
3328 else
3329 config.hardwareMachine.usbSettings.llUSBControllers.clear();
3330#endif
3331 /* Audio adapter */
3332 if (stack.strAudioAdapter.isNotEmpty())
3333 {
3334 config.hardwareMachine.audioAdapter.fEnabled = true;
3335 config.hardwareMachine.audioAdapter.controllerType = (AudioControllerType_T)stack.strAudioAdapter.toUInt32();
3336 }
3337 else
3338 config.hardwareMachine.audioAdapter.fEnabled = false;
3339 /* Network adapter */
3340 settings::NetworkAdaptersList &llNetworkAdapters = config.hardwareMachine.llNetworkAdapters;
3341 /* First disable all network cards, they will be enabled below again. */
3342 settings::NetworkAdaptersList::iterator it1;
3343 bool fKeepAllMACs = m->optListImport.contains(ImportOptions_KeepAllMACs);
3344 bool fKeepNATMACs = m->optListImport.contains(ImportOptions_KeepNATMACs);
3345 for (it1 = llNetworkAdapters.begin(); it1 != llNetworkAdapters.end(); ++it1)
3346 {
3347 it1->fEnabled = false;
3348 if (!( fKeepAllMACs
3349 || (fKeepNATMACs && it1->mode == NetworkAttachmentType_NAT)
3350 || (fKeepNATMACs && it1->mode == NetworkAttachmentType_NATNetwork)))
3351 Host::generateMACAddress(it1->strMACAddress);
3352 }
3353 /* Now iterate over all network entries. */
3354 std::list<VirtualSystemDescriptionEntry*> avsdeNWs = vsdescThis->findByType(VirtualSystemDescriptionType_NetworkAdapter);
3355 if (avsdeNWs.size() > 0)
3356 {
3357 /* Iterate through all network adapter entries and search for the
3358 * corresponding one in the machine config. If one is found, configure
3359 * it based on the user settings. */
3360 list<VirtualSystemDescriptionEntry*>::const_iterator itNW;
3361 for (itNW = avsdeNWs.begin();
3362 itNW != avsdeNWs.end();
3363 ++itNW)
3364 {
3365 VirtualSystemDescriptionEntry *vsdeNW = *itNW;
3366 if ( vsdeNW->strExtraConfigCurrent.startsWith("slot=", Utf8Str::CaseInsensitive)
3367 && vsdeNW->strExtraConfigCurrent.length() > 6)
3368 {
3369 uint32_t iSlot = vsdeNW->strExtraConfigCurrent.substr(5, 1).toUInt32();
3370 /* Iterate through all network adapters in the machine config. */
3371 for (it1 = llNetworkAdapters.begin();
3372 it1 != llNetworkAdapters.end();
3373 ++it1)
3374 {
3375 /* Compare the slots. */
3376 if (it1->ulSlot == iSlot)
3377 {
3378 it1->fEnabled = true;
3379 it1->type = (NetworkAdapterType_T)vsdeNW->strVboxCurrent.toUInt32();
3380 break;
3381 }
3382 }
3383 }
3384 }
3385 }
3386
3387 /* Floppy controller */
3388 bool fFloppy = vsdescThis->findByType(VirtualSystemDescriptionType_Floppy).size() > 0;
3389 /* DVD controller */
3390 bool fDVD = vsdescThis->findByType(VirtualSystemDescriptionType_CDROM).size() > 0;
3391 /* Iterate over all storage controller check the attachments and remove
3392 * them when necessary. Also detect broken configs with more than one
3393 * attachment. Old VirtualBox versions (prior to 3.2.10) had all disk
3394 * attachments pointing to the last hard disk image, which causes import
3395 * failures. A long fixed bug, however the OVF files are long lived. */
3396 settings::StorageControllersList &llControllers = config.storageMachine.llStorageControllers;
3397 Guid hdUuid;
3398 uint32_t cHardDisks = 0;
3399 bool fInconsistent = false;
3400 bool fRepairDuplicate = false;
3401 settings::StorageControllersList::iterator it3;
3402 for (it3 = llControllers.begin();
3403 it3 != llControllers.end();
3404 ++it3)
3405 {
3406 settings::AttachedDevicesList &llAttachments = it3->llAttachedDevices;
3407 settings::AttachedDevicesList::iterator it4 = llAttachments.begin();
3408 while (it4 != llAttachments.end())
3409 {
3410 if ( ( !fDVD
3411 && it4->deviceType == DeviceType_DVD)
3412 ||
3413 ( !fFloppy
3414 && it4->deviceType == DeviceType_Floppy))
3415 {
3416 it4 = llAttachments.erase(it4);
3417 continue;
3418 }
3419 else if (it4->deviceType == DeviceType_HardDisk)
3420 {
3421 const Guid &thisUuid = it4->uuid;
3422 cHardDisks++;
3423 if (cHardDisks == 1)
3424 {
3425 if (hdUuid.isZero())
3426 hdUuid = thisUuid;
3427 else
3428 fInconsistent = true;
3429 }
3430 else
3431 {
3432 if (thisUuid.isZero())
3433 fInconsistent = true;
3434 else if (thisUuid == hdUuid)
3435 fRepairDuplicate = true;
3436 }
3437 }
3438 ++it4;
3439 }
3440 }
3441 /* paranoia... */
3442 if (fInconsistent || cHardDisks == 1)
3443 fRepairDuplicate = false;
3444
3445 /*
3446 * step 2: scan the machine config for media attachments
3447 */
3448
3449 /* Get all hard disk descriptions. */
3450 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
3451 std::list<VirtualSystemDescriptionEntry*>::iterator avsdeHDsIt = avsdeHDs.begin();
3452 /* paranoia - if there is no 1:1 match do not try to repair. */
3453 if (cHardDisks != avsdeHDs.size())
3454 fRepairDuplicate = false;
3455
3456 // there must be an image in the OVF disk structs with the same UUID
3457
3458 ovf::DiskImagesMap::const_iterator oit = stack.mapDisks.begin();
3459 std::set<RTCString> disksResolvedNames;
3460
3461 while(oit != stack.mapDisks.end())
3462 {
3463 ovf::DiskImage diCurrent = oit->second;
3464
3465 VirtualSystemDescriptionEntry *vsdeTargetHD = 0;
3466
3467 {
3468 /* Iterate over all given disk images of the virtual system
3469 * disks description. We need to find the target disk path,
3470 * which could be changed by the user. */
3471 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
3472 for (itHD = avsdeHDs.begin();
3473 itHD != avsdeHDs.end();
3474 ++itHD)
3475 {
3476 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
3477 if (vsdeHD->strRef == oit->first)
3478 {
3479 vsdeTargetHD = vsdeHD;
3480 break;
3481 }
3482 }
3483 if (!vsdeTargetHD)
3484 throw setError(E_FAIL,
3485 tr("Internal inconsistency looking up disk image '%s'"),
3486 oit->first.c_str());
3487 }
3488
3489 /*
3490 * preliminary check availability of the image
3491 * This step is useful if image is placed in the OVA (TAR) package
3492 */
3493
3494 Utf8Str name = applianceIOName(applianceIOTar);
3495
3496 if (strncmp(pStorage->pVDImageIfaces->pszInterfaceName, name.c_str(), name.length()) == 0)
3497 {
3498 /* It means that we possibly have imported the storage earlier on the previous loop steps*/
3499 std::set<RTCString>::const_iterator h = disksResolvedNames.find(diCurrent.strHref);
3500 if (h != disksResolvedNames.end())
3501 {
3502 /* Yes, disk name was found, we can skip it*/
3503 ++oit;
3504 continue;
3505 }
3506
3507 RTCString availableImage(diCurrent.strHref);
3508
3509 rc = preCheckImageAvailability(pStorage,
3510 availableImage
3511 );
3512
3513 if (SUCCEEDED(rc))
3514 {
3515 /* current opened file isn't the same as passed one */
3516 if(availableImage.compare(diCurrent.strHref, Utf8Str::CaseInsensitive) != 0)
3517 {
3518 // availableImage contains the disk identifier (e.g. "vmdisk1"), which should exist
3519 // in the virtual system's disks map under that ID and also in the global images map
3520 // and find the disk from the OVF's disk list
3521 ovf::DiskImagesMap::const_iterator itDiskImage = stack.mapDisks.begin();
3522 while (++itDiskImage != stack.mapDisks.end())
3523 {
3524 if(itDiskImage->second.strHref.compare(availableImage, Utf8Str::CaseInsensitive) == 0 )
3525 break;
3526 }
3527 if (itDiskImage == stack.mapDisks.end())
3528 {
3529 throw setError(E_FAIL,
3530 tr("Internal inconsistency looking up disk image '%s'. "
3531 "Check compliance OVA package structure and file names "
3532 "references in the section <References> in the OVF file."),
3533 availableImage.c_str());
3534 }
3535
3536 /* replace with a new found disk image */
3537 diCurrent = *(&itDiskImage->second);
3538
3539 /*
3540 * Again iterate over all given disk images of the virtual system
3541 * disks description using the found disk image
3542 */
3543 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
3544 for (itHD = avsdeHDs.begin();
3545 itHD != avsdeHDs.end();
3546 ++itHD)
3547 {
3548 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
3549 if (vsdeHD->strRef == diCurrent.strDiskId)
3550 {
3551 vsdeTargetHD = vsdeHD;
3552 break;
3553 }
3554 }
3555 if (!vsdeTargetHD)
3556 throw setError(E_FAIL,
3557 tr("Internal inconsistency looking up disk image '%s'"),
3558 diCurrent.strHref.c_str());
3559 }
3560 else
3561 {
3562 ++oit;
3563 }
3564 }
3565 else
3566 {
3567 ++oit;
3568 continue;
3569 }
3570 }
3571 else
3572 {
3573 /* just continue with normal files*/
3574 ++oit;
3575 }
3576
3577 /* Important! to store disk name for the next checks */
3578 disksResolvedNames.insert(diCurrent.strHref);
3579
3580 // there must be an image in the OVF disk structs with the same UUID
3581 bool fFound = false;
3582 Utf8Str strUuid;
3583
3584 // for each storage controller...
3585 for (settings::StorageControllersList::iterator sit = config.storageMachine.llStorageControllers.begin();
3586 sit != config.storageMachine.llStorageControllers.end();
3587 ++sit)
3588 {
3589 settings::StorageController &sc = *sit;
3590
3591 // find the OVF virtual system description entry for this storage controller
3592 switch (sc.storageBus)
3593 {
3594 case StorageBus_SATA:
3595 break;
3596 case StorageBus_SCSI:
3597 break;
3598 case StorageBus_IDE:
3599 break;
3600 case StorageBus_SAS:
3601 break;
3602 }
3603
3604 // for each medium attachment to this controller...
3605 for (settings::AttachedDevicesList::iterator dit = sc.llAttachedDevices.begin();
3606 dit != sc.llAttachedDevices.end();
3607 ++dit)
3608 {
3609 settings::AttachedDevice &d = *dit;
3610
3611 if (d.uuid.isZero())
3612 // empty DVD and floppy media
3613 continue;
3614
3615 // When repairing a broken VirtualBox xml config section (written
3616 // by VirtualBox versions earlier than 3.2.10) assume the disks
3617 // show up in the same order as in the OVF description.
3618 if (fRepairDuplicate)
3619 {
3620 VirtualSystemDescriptionEntry *vsdeHD = *avsdeHDsIt;
3621 ovf::DiskImagesMap::const_iterator itDiskImage = stack.mapDisks.find(vsdeHD->strRef);
3622 if (itDiskImage != stack.mapDisks.end())
3623 {
3624 const ovf::DiskImage &di = itDiskImage->second;
3625 d.uuid = Guid(di.uuidVbox);
3626 }
3627 ++avsdeHDsIt;
3628 }
3629
3630 // convert the Guid to string
3631 strUuid = d.uuid.toString();
3632
3633 if (diCurrent.uuidVbox != strUuid)
3634 {
3635 continue;
3636 }
3637
3638 /*
3639 * step 3: import disk
3640 */
3641 Utf8Str savedVboxCurrent = vsdeTargetHD->strVboxCurrent;
3642 ComObjPtr<Medium> pTargetHD;
3643 importOneDiskImage(diCurrent,
3644 &vsdeTargetHD->strVboxCurrent,
3645 pTargetHD,
3646 stack,
3647 pCallbacks,
3648 pStorage);
3649
3650 Bstr hdId;
3651
3652 Utf8Str vdf = typeOfVirtualDiskFormatFromURI(diCurrent.strFormat);
3653
3654 if (vdf.compare("RAW", Utf8Str::CaseInsensitive) == 0)
3655 {
3656 ComPtr<IMedium> dvdImage(pTargetHD);
3657
3658 rc = mVirtualBox->OpenMedium(Bstr(vsdeTargetHD->strVboxCurrent).raw(),
3659 DeviceType_DVD,
3660 AccessMode_ReadWrite,
3661 false,
3662 dvdImage.asOutParam());
3663
3664 if (FAILED(rc)) throw rc;
3665
3666 // ... and replace the old UUID in the machine config with the one of
3667 // the imported disk that was just created
3668 rc = dvdImage->COMGETTER(Id)(hdId.asOutParam());
3669 if (FAILED(rc)) throw rc;
3670 }
3671 else
3672 {
3673 // ... and replace the old UUID in the machine config with the one of
3674 // the imported disk that was just created
3675 rc = pTargetHD->COMGETTER(Id)(hdId.asOutParam());
3676 if (FAILED(rc)) throw rc;
3677 }
3678
3679 /* restore */
3680 vsdeTargetHD->strVboxCurrent = savedVboxCurrent;
3681
3682 d.uuid = hdId;
3683 fFound = true;
3684 break;
3685 } // for (settings::AttachedDevicesList::const_iterator dit = sc.llAttachedDevices.begin();
3686 } // for (settings::StorageControllersList::const_iterator sit = config.storageMachine.llStorageControllers.begin();
3687
3688 // no disk with such a UUID found:
3689 if (!fFound)
3690 throw setError(E_FAIL,
3691 tr("<vbox:Machine> element in OVF contains a medium attachment for the disk image %s "
3692 "but the OVF describes no such image"),
3693 strUuid.c_str());
3694
3695 }// while(oit != stack.mapDisks.end())
3696
3697 /*
3698 * step 4): create the machine and have it import the config
3699 */
3700
3701 ComObjPtr<Machine> pNewMachine;
3702 rc = pNewMachine.createObject();
3703 if (FAILED(rc)) throw rc;
3704
3705 // this magic constructor fills the new machine object with the MachineConfig
3706 // instance that we created from the vbox:Machine
3707 rc = pNewMachine->init(mVirtualBox,
3708 stack.strNameVBox,// name from OVF preparations; can be suffixed to avoid duplicates
3709 config); // the whole machine config
3710 if (FAILED(rc)) throw rc;
3711
3712 pReturnNewMachine = ComPtr<IMachine>(pNewMachine);
3713
3714 // and register it
3715 rc = mVirtualBox->RegisterMachine(pNewMachine);
3716 if (FAILED(rc)) throw rc;
3717
3718 // store new machine for roll-back in case of errors
3719 Bstr bstrNewMachineId;
3720 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
3721 if (FAILED(rc)) throw rc;
3722 m->llGuidsMachinesCreated.push_back(Guid(bstrNewMachineId));
3723}
3724
3725void Appliance::importMachines(ImportStack &stack,
3726 PVDINTERFACEIO pCallbacks,
3727 PSHASTORAGE pStorage)
3728{
3729 HRESULT rc = S_OK;
3730
3731 // this is safe to access because this thread only gets started
3732 const ovf::OVFReader &reader = *m->pReader;
3733
3734 /*
3735 * get the SHA digest version that was set in accordance with the value of attribute "xmlns:ovf"
3736 * of the element <Envelope> in the OVF file during reading operation. See readFSImpl().
3737 */
3738 pStorage->fSha256 = m->fSha256;
3739
3740 // create a session for the machine + disks we manipulate below
3741 rc = stack.pSession.createInprocObject(CLSID_Session);
3742 if (FAILED(rc)) throw rc;
3743
3744 list<ovf::VirtualSystem>::const_iterator it;
3745 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it1;
3746 /* Iterate through all virtual systems of that appliance */
3747 size_t i = 0;
3748 for (it = reader.m_llVirtualSystems.begin(),
3749 it1 = m->virtualSystemDescriptions.begin();
3750 it != reader.m_llVirtualSystems.end(),
3751 it1 != m->virtualSystemDescriptions.end();
3752 ++it, ++it1, ++i)
3753 {
3754 const ovf::VirtualSystem &vsysThis = *it;
3755 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it1);
3756
3757 ComPtr<IMachine> pNewMachine;
3758
3759 // there are two ways in which we can create a vbox machine from OVF:
3760 // -- either this OVF was written by vbox 3.2 or later, in which case there is a <vbox:Machine> element
3761 // in the <VirtualSystem>; then the VirtualSystemDescription::Data has a settings::MachineConfigFile
3762 // with all the machine config pretty-parsed;
3763 // -- or this is an OVF from an older vbox or an external source, and then we need to translate the
3764 // VirtualSystemDescriptionEntry and do import work
3765
3766 // Even for the vbox:Machine case, there are a number of configuration items that will be taken from
3767 // the OVF because otherwise the "override import parameters" mechanism in the GUI won't work.
3768
3769 // VM name
3770 std::list<VirtualSystemDescriptionEntry*> vsdeName = vsdescThis->findByType(VirtualSystemDescriptionType_Name);
3771 if (vsdeName.size() < 1)
3772 throw setError(VBOX_E_FILE_ERROR,
3773 tr("Missing VM name"));
3774 stack.strNameVBox = vsdeName.front()->strVboxCurrent;
3775
3776 // have VirtualBox suggest where the filename would be placed so we can
3777 // put the disk images in the same directory
3778 Bstr bstrMachineFilename;
3779 rc = mVirtualBox->ComposeMachineFilename(Bstr(stack.strNameVBox).raw(),
3780 NULL /* aGroup */,
3781 NULL /* aCreateFlags */,
3782 NULL /* aBaseFolder */,
3783 bstrMachineFilename.asOutParam());
3784 if (FAILED(rc)) throw rc;
3785 // and determine the machine folder from that
3786 stack.strMachineFolder = bstrMachineFilename;
3787 stack.strMachineFolder.stripFilename();
3788
3789 // guest OS type
3790 std::list<VirtualSystemDescriptionEntry*> vsdeOS;
3791 vsdeOS = vsdescThis->findByType(VirtualSystemDescriptionType_OS);
3792 if (vsdeOS.size() < 1)
3793 throw setError(VBOX_E_FILE_ERROR,
3794 tr("Missing guest OS type"));
3795 stack.strOsTypeVBox = vsdeOS.front()->strVboxCurrent;
3796
3797 // CPU count
3798 std::list<VirtualSystemDescriptionEntry*> vsdeCPU = vsdescThis->findByType(VirtualSystemDescriptionType_CPU);
3799 if (vsdeCPU.size() != 1)
3800 throw setError(VBOX_E_FILE_ERROR, tr("CPU count missing"));
3801
3802 stack.cCPUs = vsdeCPU.front()->strVboxCurrent.toUInt32();
3803 // We need HWVirt & IO-APIC if more than one CPU is requested
3804 if (stack.cCPUs > 1)
3805 {
3806 stack.fForceHWVirt = true;
3807 stack.fForceIOAPIC = true;
3808 }
3809
3810 // RAM
3811 std::list<VirtualSystemDescriptionEntry*> vsdeRAM = vsdescThis->findByType(VirtualSystemDescriptionType_Memory);
3812 if (vsdeRAM.size() != 1)
3813 throw setError(VBOX_E_FILE_ERROR, tr("RAM size missing"));
3814 stack.ulMemorySizeMB = (ULONG)vsdeRAM.front()->strVboxCurrent.toUInt64();
3815
3816#ifdef VBOX_WITH_USB
3817 // USB controller
3818 std::list<VirtualSystemDescriptionEntry*> vsdeUSBController = vsdescThis->findByType(VirtualSystemDescriptionType_USBController);
3819 // USB support is enabled if there's at least one such entry; to disable USB support,
3820 // the type of the USB item would have been changed to "ignore"
3821 stack.fUSBEnabled = vsdeUSBController.size() > 0;
3822#endif
3823 // audio adapter
3824 std::list<VirtualSystemDescriptionEntry*> vsdeAudioAdapter = vsdescThis->findByType(VirtualSystemDescriptionType_SoundCard);
3825 /* @todo: we support one audio adapter only */
3826 if (vsdeAudioAdapter.size() > 0)
3827 stack.strAudioAdapter = vsdeAudioAdapter.front()->strVboxCurrent;
3828
3829 // for the description of the new machine, always use the OVF entry, the user may have changed it in the import config
3830 std::list<VirtualSystemDescriptionEntry*> vsdeDescription = vsdescThis->findByType(VirtualSystemDescriptionType_Description);
3831 if (vsdeDescription.size())
3832 stack.strDescription = vsdeDescription.front()->strVboxCurrent;
3833
3834 // import vbox:machine or OVF now
3835 if (vsdescThis->m->pConfig)
3836 // vbox:Machine config
3837 importVBoxMachine(vsdescThis, pNewMachine, stack, pCallbacks, pStorage);
3838 else
3839 // generic OVF config
3840 importMachineGeneric(vsysThis, vsdescThis, pNewMachine, stack, pCallbacks, pStorage);
3841
3842 } // for (it = pAppliance->m->llVirtualSystems.begin() ...
3843}
3844
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