VirtualBox

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

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

6813 stage 2 - Use the server side API wrapper code..

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