VirtualBox

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

Last change on this file since 59571 was 59567, checked in by vboxsync, 9 years ago

RTManifestSetAttr,RTManifestEntrySetAttr: Allow the attribute name to be NULL when there is a distinctive fType value given.

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette