VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/ApplianceImplExport.cpp@ 67184

Last change on this file since 67184 was 67184, checked in by vboxsync, 8 years ago

Main: Reworking IAppliance export to use new TAR creator. Changes protected by VBOX_WITH_NEW_TAR_CREATOR define (currently not defined).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 114.7 KB
Line 
1/* $Id: ApplianceImplExport.cpp 67184 2017-05-31 20:32:04Z vboxsync $ */
2/** @file
3 * IAppliance and IVirtualSystem COM class implementations.
4 */
5
6/*
7 * Copyright (C) 2008-2017 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.215389.xyz. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#include <iprt/path.h>
19#include <iprt/dir.h>
20#include <iprt/param.h>
21#include <iprt/s3.h>
22#include <iprt/manifest.h>
23#include <iprt/stream.h>
24#ifndef VBOX_WITH_NEW_TAR_CREATOR
25# include <iprt/tar.h>
26#else
27# include <iprt/zip.h>
28#endif
29
30#include <VBox/version.h>
31
32#include "ApplianceImpl.h"
33#include "VirtualBoxImpl.h"
34#include "ProgressImpl.h"
35#include "MachineImpl.h"
36#include "MediumImpl.h"
37#include "MediumFormatImpl.h"
38#include "Global.h"
39#include "SystemPropertiesImpl.h"
40
41#include "AutoCaller.h"
42#include "Logging.h"
43
44#include "ApplianceImplPrivate.h"
45
46using namespace std;
47
48////////////////////////////////////////////////////////////////////////////////
49//
50// IMachine public methods
51//
52////////////////////////////////////////////////////////////////////////////////
53
54// This code is here so we won't have to include the appliance headers in the
55// IMachine implementation, and we also need to access private appliance data.
56
57/**
58* Public method implementation.
59* @param aAppliance Appliance object.
60* @param aLocation Where to store the appliance.
61* @param aDescription Appliance description.
62* @return
63*/
64HRESULT Machine::exportTo(const ComPtr<IAppliance> &aAppliance, const com::Utf8Str &aLocation,
65 ComPtr<IVirtualSystemDescription> &aDescription)
66{
67 HRESULT rc = S_OK;
68
69 if (!aAppliance)
70 return E_POINTER;
71
72 ComObjPtr<VirtualSystemDescription> pNewDesc;
73
74 try
75 {
76 IAppliance *iAppliance = aAppliance;
77 Appliance *pAppliance = static_cast<Appliance*>(iAppliance);
78
79 LocationInfo locInfo;
80 i_parseURI(aLocation, locInfo);
81 // create a new virtual system to store in the appliance
82 rc = pNewDesc.createObject();
83 if (FAILED(rc)) throw rc;
84 rc = pNewDesc->init();
85 if (FAILED(rc)) throw rc;
86
87 // store the machine object so we can dump the XML in Appliance::Write()
88 pNewDesc->m->pMachine = this;
89
90 // first, call the COM methods, as they request locks
91 BOOL fUSBEnabled = FALSE;
92 com::SafeIfaceArray<IUSBController> usbControllers;
93 rc = COMGETTER(USBControllers)(ComSafeArrayAsOutParam(usbControllers));
94 if (SUCCEEDED(rc))
95 {
96 for (unsigned i = 0; i < usbControllers.size(); ++i)
97 {
98 USBControllerType_T enmType;
99
100 rc = usbControllers[i]->COMGETTER(Type)(&enmType);
101 if (FAILED(rc)) throw rc;
102
103 if (enmType == USBControllerType_OHCI)
104 fUSBEnabled = TRUE;
105 }
106 }
107
108 // request the machine lock while accessing internal members
109 AutoReadLock alock1(this COMMA_LOCKVAL_SRC_POS);
110
111 ComPtr<IAudioAdapter> pAudioAdapter = mAudioAdapter;
112 BOOL fAudioEnabled;
113 rc = pAudioAdapter->COMGETTER(Enabled)(&fAudioEnabled);
114 if (FAILED(rc)) throw rc;
115 AudioControllerType_T audioController;
116 rc = pAudioAdapter->COMGETTER(AudioController)(&audioController);
117 if (FAILED(rc)) throw rc;
118
119 // get name
120 Utf8Str strVMName = mUserData->s.strName;
121 // get description
122 Utf8Str strDescription = mUserData->s.strDescription;
123 // get guest OS
124 Utf8Str strOsTypeVBox = mUserData->s.strOsType;
125 // CPU count
126 uint32_t cCPUs = mHWData->mCPUCount;
127 // memory size in MB
128 uint32_t ulMemSizeMB = mHWData->mMemorySize;
129 // VRAM size?
130 // BIOS settings?
131 // 3D acceleration enabled?
132 // hardware virtualization enabled?
133 // nested paging enabled?
134 // HWVirtExVPIDEnabled?
135 // PAEEnabled?
136 // Long mode enabled?
137 BOOL fLongMode;
138 rc = GetCPUProperty(CPUPropertyType_LongMode, &fLongMode);
139 if (FAILED(rc)) throw rc;
140
141 // snapshotFolder?
142 // VRDPServer?
143
144 /* Guest OS type */
145 ovf::CIMOSType_T cim = convertVBoxOSType2CIMOSType(strOsTypeVBox.c_str(), fLongMode);
146 pNewDesc->i_addEntry(VirtualSystemDescriptionType_OS,
147 "",
148 Utf8StrFmt("%RI32", cim),
149 strOsTypeVBox);
150
151 /* VM name */
152 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Name,
153 "",
154 strVMName,
155 strVMName);
156
157 // description
158 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Description,
159 "",
160 strDescription,
161 strDescription);
162
163 /* CPU count*/
164 Utf8Str strCpuCount = Utf8StrFmt("%RI32", cCPUs);
165 pNewDesc->i_addEntry(VirtualSystemDescriptionType_CPU,
166 "",
167 strCpuCount,
168 strCpuCount);
169
170 /* Memory */
171 Utf8Str strMemory = Utf8StrFmt("%RI64", (uint64_t)ulMemSizeMB * _1M);
172 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Memory,
173 "",
174 strMemory,
175 strMemory);
176
177 // the one VirtualBox IDE controller has two channels with two ports each, which is
178 // considered two IDE controllers with two ports each by OVF, so export it as two
179 int32_t lIDEControllerPrimaryIndex = 0;
180 int32_t lIDEControllerSecondaryIndex = 0;
181 int32_t lSATAControllerIndex = 0;
182 int32_t lSCSIControllerIndex = 0;
183
184 /* Fetch all available storage controllers */
185 com::SafeIfaceArray<IStorageController> nwControllers;
186 rc = COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(nwControllers));
187 if (FAILED(rc)) throw rc;
188
189 ComPtr<IStorageController> pIDEController;
190 ComPtr<IStorageController> pSATAController;
191 ComPtr<IStorageController> pSCSIController;
192 ComPtr<IStorageController> pSASController;
193 for (size_t j = 0; j < nwControllers.size(); ++j)
194 {
195 StorageBus_T eType;
196 rc = nwControllers[j]->COMGETTER(Bus)(&eType);
197 if (FAILED(rc)) throw rc;
198 if ( eType == StorageBus_IDE
199 && pIDEController.isNull())
200 pIDEController = nwControllers[j];
201 else if ( eType == StorageBus_SATA
202 && pSATAController.isNull())
203 pSATAController = nwControllers[j];
204 else if ( eType == StorageBus_SCSI
205 && pSATAController.isNull())
206 pSCSIController = nwControllers[j];
207 else if ( eType == StorageBus_SAS
208 && pSASController.isNull())
209 pSASController = nwControllers[j];
210 }
211
212// <const name="HardDiskControllerIDE" value="6" />
213 if (!pIDEController.isNull())
214 {
215 StorageControllerType_T ctlr;
216 rc = pIDEController->COMGETTER(ControllerType)(&ctlr);
217 if (FAILED(rc)) throw rc;
218
219 Utf8Str strVBox;
220 switch (ctlr)
221 {
222 case StorageControllerType_PIIX3: strVBox = "PIIX3"; break;
223 case StorageControllerType_PIIX4: strVBox = "PIIX4"; break;
224 case StorageControllerType_ICH6: strVBox = "ICH6"; break;
225 default: break; /* Shut up MSC. */
226 }
227
228 if (strVBox.length())
229 {
230 lIDEControllerPrimaryIndex = (int32_t)pNewDesc->m->maDescriptions.size();
231 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
232 Utf8StrFmt("%d", lIDEControllerPrimaryIndex), // strRef
233 strVBox, // aOvfValue
234 strVBox); // aVBoxValue
235 lIDEControllerSecondaryIndex = lIDEControllerPrimaryIndex + 1;
236 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
237 Utf8StrFmt("%d", lIDEControllerSecondaryIndex),
238 strVBox,
239 strVBox);
240 }
241 }
242
243// <const name="HardDiskControllerSATA" value="7" />
244 if (!pSATAController.isNull())
245 {
246 Utf8Str strVBox = "AHCI";
247 lSATAControllerIndex = (int32_t)pNewDesc->m->maDescriptions.size();
248 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerSATA,
249 Utf8StrFmt("%d", lSATAControllerIndex),
250 strVBox,
251 strVBox);
252 }
253
254// <const name="HardDiskControllerSCSI" value="8" />
255 if (!pSCSIController.isNull())
256 {
257 StorageControllerType_T ctlr;
258 rc = pSCSIController->COMGETTER(ControllerType)(&ctlr);
259 if (SUCCEEDED(rc))
260 {
261 Utf8Str strVBox = "LsiLogic"; // the default in VBox
262 switch (ctlr)
263 {
264 case StorageControllerType_LsiLogic: strVBox = "LsiLogic"; break;
265 case StorageControllerType_BusLogic: strVBox = "BusLogic"; break;
266 default: break; /* Shut up MSC. */
267 }
268 lSCSIControllerIndex = (int32_t)pNewDesc->m->maDescriptions.size();
269 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerSCSI,
270 Utf8StrFmt("%d", lSCSIControllerIndex),
271 strVBox,
272 strVBox);
273 }
274 else
275 throw rc;
276 }
277
278 if (!pSASController.isNull())
279 {
280 // VirtualBox considers the SAS controller a class of its own but in OVF
281 // it should be a SCSI controller
282 Utf8Str strVBox = "LsiLogicSas";
283 lSCSIControllerIndex = (int32_t)pNewDesc->m->maDescriptions.size();
284 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerSAS,
285 Utf8StrFmt("%d", lSCSIControllerIndex),
286 strVBox,
287 strVBox);
288 }
289
290// <const name="HardDiskImage" value="9" />
291// <const name="Floppy" value="18" />
292// <const name="CDROM" value="19" />
293
294 for (MediumAttachmentList::const_iterator
295 it = mMediumAttachments->begin();
296 it != mMediumAttachments->end();
297 ++it)
298 {
299 ComObjPtr<MediumAttachment> pHDA = *it;
300
301 // the attachment's data
302 ComPtr<IMedium> pMedium;
303 ComPtr<IStorageController> ctl;
304 Bstr controllerName;
305
306 rc = pHDA->COMGETTER(Controller)(controllerName.asOutParam());
307 if (FAILED(rc)) throw rc;
308
309 rc = GetStorageControllerByName(controllerName.raw(), ctl.asOutParam());
310 if (FAILED(rc)) throw rc;
311
312 StorageBus_T storageBus;
313 DeviceType_T deviceType;
314 LONG lChannel;
315 LONG lDevice;
316
317 rc = ctl->COMGETTER(Bus)(&storageBus);
318 if (FAILED(rc)) throw rc;
319
320 rc = pHDA->COMGETTER(Type)(&deviceType);
321 if (FAILED(rc)) throw rc;
322
323 rc = pHDA->COMGETTER(Medium)(pMedium.asOutParam());
324 if (FAILED(rc)) throw rc;
325
326 rc = pHDA->COMGETTER(Port)(&lChannel);
327 if (FAILED(rc)) throw rc;
328
329 rc = pHDA->COMGETTER(Device)(&lDevice);
330 if (FAILED(rc)) throw rc;
331
332 Utf8Str strTargetImageName;
333 Utf8Str strLocation;
334 LONG64 llSize = 0;
335
336 if ( deviceType == DeviceType_HardDisk
337 && pMedium)
338 {
339 Bstr bstrLocation;
340
341 rc = pMedium->COMGETTER(Location)(bstrLocation.asOutParam());
342 if (FAILED(rc)) throw rc;
343 strLocation = bstrLocation;
344
345 // find the source's base medium for two things:
346 // 1) we'll use its name to determine the name of the target disk, which is readable,
347 // as opposed to the UUID filename of a differencing image, if pMedium is one
348 // 2) we need the size of the base image so we can give it to addEntry(), and later
349 // on export, the progress will be based on that (and not the diff image)
350 ComPtr<IMedium> pBaseMedium;
351 rc = pMedium->COMGETTER(Base)(pBaseMedium.asOutParam());
352 // returns pMedium if there are no diff images
353 if (FAILED(rc)) throw rc;
354
355 Utf8Str strName = Utf8Str(locInfo.strPath).stripPath().stripSuffix();
356 strTargetImageName = Utf8StrFmt("%s-disk%.3d.vmdk", strName.c_str(), ++pAppliance->m->cDisks);
357 if (strTargetImageName.length() > RTTAR_NAME_MAX)
358 throw setError(VBOX_E_NOT_SUPPORTED,
359 tr("Cannot attach disk '%s' -- file name too long"), strTargetImageName.c_str());
360
361 // force reading state, or else size will be returned as 0
362 MediumState_T ms;
363 rc = pBaseMedium->RefreshState(&ms);
364 if (FAILED(rc)) throw rc;
365
366 rc = pBaseMedium->COMGETTER(Size)(&llSize);
367 if (FAILED(rc)) throw rc;
368
369 /* If the medium is encrypted add the key identifier to the list. */
370 IMedium *iBaseMedium = pBaseMedium;
371 Medium *pBase = static_cast<Medium*>(iBaseMedium);
372 const com::Utf8Str strKeyId = pBase->i_getKeyId();
373 if (!strKeyId.isEmpty())
374 {
375 IMedium *iMedium = pMedium;
376 Medium *pMed = static_cast<Medium*>(iMedium);
377 com::Guid mediumUuid = pMed->i_getId();
378 bool fKnown = false;
379
380 /* Check whether the ID is already in our sequence, add it otherwise. */
381 for (unsigned i = 0; i < pAppliance->m->m_vecPasswordIdentifiers.size(); i++)
382 {
383 if (strKeyId.equals(pAppliance->m->m_vecPasswordIdentifiers[i]))
384 {
385 fKnown = true;
386 break;
387 }
388 }
389
390 if (!fKnown)
391 {
392 GUIDVEC vecMediumIds;
393
394 vecMediumIds.push_back(mediumUuid);
395 pAppliance->m->m_vecPasswordIdentifiers.push_back(strKeyId);
396 pAppliance->m->m_mapPwIdToMediumIds.insert(std::pair<com::Utf8Str, GUIDVEC>(strKeyId, vecMediumIds));
397 }
398 else
399 {
400 std::map<com::Utf8Str, GUIDVEC>::iterator itMap = pAppliance->m->m_mapPwIdToMediumIds.find(strKeyId);
401 if (itMap == pAppliance->m->m_mapPwIdToMediumIds.end())
402 throw setError(E_FAIL, tr("Internal error adding a medium UUID to the map"));
403 itMap->second.push_back(mediumUuid);
404 }
405 }
406 }
407 else if ( deviceType == DeviceType_DVD
408 && pMedium)
409 {
410 /*
411 * check the minimal rules to grant access to export an image
412 * 1. no host drive CD/DVD image
413 * 2. the image must be accessible and readable
414 * 3. only ISO image is exported
415 */
416
417 //1. no host drive CD/DVD image
418 BOOL fHostDrive = false;
419 rc = pMedium->COMGETTER(HostDrive)(&fHostDrive);
420 if (FAILED(rc)) throw rc;
421
422 if(fHostDrive)
423 continue;
424
425 //2. the image must be accessible and readable
426 MediumState_T ms;
427 rc = pMedium->RefreshState(&ms);
428 if (FAILED(rc)) throw rc;
429
430 if (ms != MediumState_Created)
431 continue;
432
433 //3. only ISO image is exported
434 Bstr bstrLocation;
435 rc = pMedium->COMGETTER(Location)(bstrLocation.asOutParam());
436 if (FAILED(rc)) throw rc;
437
438 strLocation = bstrLocation;
439
440 Utf8Str ext = strLocation;
441 ext.assignEx(RTPathSuffix(ext.c_str()));//returns extension with dot (".iso")
442
443 int eq = ext.compare(".iso", Utf8Str::CaseInsensitive);
444 if (eq != 0)
445 continue;
446
447 Utf8Str strName = Utf8Str(locInfo.strPath).stripPath().stripSuffix();
448 strTargetImageName = Utf8StrFmt("%s-disk%.3d.iso", strName.c_str(), ++pAppliance->m->cDisks);
449 if (strTargetImageName.length() > RTTAR_NAME_MAX)
450 throw setError(VBOX_E_NOT_SUPPORTED,
451 tr("Cannot attach image '%s' -- file name too long"), strTargetImageName.c_str());
452
453 rc = pMedium->COMGETTER(Size)(&llSize);
454 if (FAILED(rc)) throw rc;
455 }
456 // and how this translates to the virtual system
457 int32_t lControllerVsys = 0;
458 LONG lChannelVsys;
459
460 switch (storageBus)
461 {
462 case StorageBus_IDE:
463 // this is the exact reverse to what we're doing in Appliance::taskThreadImportMachines,
464 // and it must be updated when that is changed!
465 // Before 3.2 we exported one IDE controller with channel 0-3, but we now maintain
466 // compatibility with what VMware does and export two IDE controllers with two channels each
467
468 if (lChannel == 0 && lDevice == 0) // primary master
469 {
470 lControllerVsys = lIDEControllerPrimaryIndex;
471 lChannelVsys = 0;
472 }
473 else if (lChannel == 0 && lDevice == 1) // primary slave
474 {
475 lControllerVsys = lIDEControllerPrimaryIndex;
476 lChannelVsys = 1;
477 }
478 else if (lChannel == 1 && lDevice == 0) // secondary master; by default this is the CD-ROM but
479 // as of VirtualBox 3.1 that can change
480 {
481 lControllerVsys = lIDEControllerSecondaryIndex;
482 lChannelVsys = 0;
483 }
484 else if (lChannel == 1 && lDevice == 1) // secondary slave
485 {
486 lControllerVsys = lIDEControllerSecondaryIndex;
487 lChannelVsys = 1;
488 }
489 else
490 throw setError(VBOX_E_NOT_SUPPORTED,
491 tr("Cannot handle medium attachment: channel is %d, device is %d"), lChannel, lDevice);
492 break;
493
494 case StorageBus_SATA:
495 lChannelVsys = lChannel; // should be between 0 and 29
496 lControllerVsys = lSATAControllerIndex;
497 break;
498
499 case StorageBus_SCSI:
500 case StorageBus_SAS:
501 lChannelVsys = lChannel; // should be between 0 and 15
502 lControllerVsys = lSCSIControllerIndex;
503 break;
504
505 case StorageBus_Floppy:
506 lChannelVsys = 0;
507 lControllerVsys = 0;
508 break;
509
510 default:
511 throw setError(VBOX_E_NOT_SUPPORTED,
512 tr("Cannot handle medium attachment: storageBus is %d, channel is %d, device is %d"),
513 storageBus, lChannel, lDevice);
514 break;
515 }
516
517 Utf8StrFmt strExtra("controller=%RI32;channel=%RI32", lControllerVsys, lChannelVsys);
518 Utf8Str strEmpty;
519
520 switch (deviceType)
521 {
522 case DeviceType_HardDisk:
523 Log(("Adding VirtualSystemDescriptionType_HardDiskImage, disk size: %RI64\n", llSize));
524 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskImage,
525 strTargetImageName, // disk ID: let's use the name
526 strTargetImageName, // OVF value:
527 strLocation, // vbox value: media path
528 (uint32_t)(llSize / _1M),
529 strExtra);
530 break;
531
532 case DeviceType_DVD:
533 Log(("Adding VirtualSystemDescriptionType_CDROM, disk size: %RI64\n", llSize));
534 pNewDesc->i_addEntry(VirtualSystemDescriptionType_CDROM,
535 strTargetImageName, // disk ID
536 strTargetImageName, // OVF value
537 strLocation, // vbox value
538 (uint32_t)(llSize / _1M),// ulSize
539 strExtra);
540 break;
541
542 case DeviceType_Floppy:
543 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Floppy,
544 strEmpty, // disk ID
545 strEmpty, // OVF value
546 strEmpty, // vbox value
547 1, // ulSize
548 strExtra);
549 break;
550
551 default: break; /* Shut up MSC. */
552 }
553 }
554
555// <const name="NetworkAdapter" />
556 uint32_t maxNetworkAdapters = Global::getMaxNetworkAdapters(i_getChipsetType());
557 size_t a;
558 for (a = 0; a < maxNetworkAdapters; ++a)
559 {
560 ComPtr<INetworkAdapter> pNetworkAdapter;
561 BOOL fEnabled;
562 NetworkAdapterType_T adapterType;
563 NetworkAttachmentType_T attachmentType;
564
565 rc = GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
566 if (FAILED(rc)) throw rc;
567 /* Enable the network card & set the adapter type */
568 rc = pNetworkAdapter->COMGETTER(Enabled)(&fEnabled);
569 if (FAILED(rc)) throw rc;
570
571 if (fEnabled)
572 {
573 rc = pNetworkAdapter->COMGETTER(AdapterType)(&adapterType);
574 if (FAILED(rc)) throw rc;
575
576 rc = pNetworkAdapter->COMGETTER(AttachmentType)(&attachmentType);
577 if (FAILED(rc)) throw rc;
578
579 Utf8Str strAttachmentType = convertNetworkAttachmentTypeToString(attachmentType);
580 pNewDesc->i_addEntry(VirtualSystemDescriptionType_NetworkAdapter,
581 "", // ref
582 strAttachmentType, // orig
583 Utf8StrFmt("%RI32", (uint32_t)adapterType), // conf
584 0,
585 Utf8StrFmt("type=%s", strAttachmentType.c_str())); // extra conf
586 }
587 }
588
589// <const name="USBController" />
590#ifdef VBOX_WITH_USB
591 if (fUSBEnabled)
592 pNewDesc->i_addEntry(VirtualSystemDescriptionType_USBController, "", "", "");
593#endif /* VBOX_WITH_USB */
594
595// <const name="SoundCard" />
596 if (fAudioEnabled)
597 pNewDesc->i_addEntry(VirtualSystemDescriptionType_SoundCard,
598 "",
599 "ensoniq1371", // this is what OVFTool writes and VMware supports
600 Utf8StrFmt("%RI32", audioController));
601
602 /* We return the new description to the caller */
603 ComPtr<IVirtualSystemDescription> copy(pNewDesc);
604 copy.queryInterfaceTo(aDescription.asOutParam());
605
606 AutoWriteLock alock(pAppliance COMMA_LOCKVAL_SRC_POS);
607 // finally, add the virtual system to the appliance
608 pAppliance->m->virtualSystemDescriptions.push_back(pNewDesc);
609 }
610 catch(HRESULT arc)
611 {
612 rc = arc;
613 }
614
615 return rc;
616}
617
618////////////////////////////////////////////////////////////////////////////////
619//
620// IAppliance public methods
621//
622////////////////////////////////////////////////////////////////////////////////
623
624/**
625 * Public method implementation.
626 * @param aFormat Appliance format.
627 * @param aOptions Export options.
628 * @param aPath Path to write the appliance to.
629 * @param aProgress Progress object.
630 * @return
631 */
632HRESULT Appliance::write(const com::Utf8Str &aFormat,
633 const std::vector<ExportOptions_T> &aOptions,
634 const com::Utf8Str &aPath,
635 ComPtr<IProgress> &aProgress)
636{
637 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
638
639 m->optListExport.clear();
640 if (aOptions.size())
641 {
642 for (size_t i = 0; i < aOptions.size(); ++i)
643 {
644 m->optListExport.insert(i, aOptions[i]);
645 }
646 }
647
648// AssertReturn(!(m->optListExport.contains(ExportOptions_CreateManifest)
649// && m->optListExport.contains(ExportOptions_ExportDVDImages)), E_INVALIDARG);
650
651 m->fExportISOImages = m->optListExport.contains(ExportOptions_ExportDVDImages);
652
653 if (!m->fExportISOImages)/* remove all ISO images from VirtualSystemDescription */
654 {
655 for (list<ComObjPtr<VirtualSystemDescription> >::const_iterator
656 it = m->virtualSystemDescriptions.begin();
657 it != m->virtualSystemDescriptions.end();
658 ++it)
659 {
660 ComObjPtr<VirtualSystemDescription> vsdescThis = *it;
661 std::list<VirtualSystemDescriptionEntry*> skipped = vsdescThis->i_findByType(VirtualSystemDescriptionType_CDROM);
662 std::list<VirtualSystemDescriptionEntry*>::const_iterator itSkipped = skipped.begin();
663 while (itSkipped != skipped.end())
664 {
665 (*itSkipped)->skipIt = true;
666 ++itSkipped;
667 }
668 }
669 }
670
671 // do not allow entering this method if the appliance is busy reading or writing
672 if (!i_isApplianceIdle())
673 return E_ACCESSDENIED;
674
675 // see if we can handle this file; for now we insist it has an ".ovf" extension
676 if (!( aPath.endsWith(".ovf", Utf8Str::CaseInsensitive)
677 || aPath.endsWith(".ova", Utf8Str::CaseInsensitive)))
678 return setError(VBOX_E_FILE_ERROR,
679 tr("Appliance file must have .ovf or .ova extension"));
680
681 ovf::OVFVersion_T ovfF;
682 if (aFormat == "ovf-0.9")
683 ovfF = ovf::OVFVersion_0_9;
684 else if (aFormat == "ovf-1.0")
685 ovfF = ovf::OVFVersion_1_0;
686 else if (aFormat == "ovf-2.0")
687 ovfF = ovf::OVFVersion_2_0;
688 else
689 return setError(VBOX_E_FILE_ERROR,
690 tr("Invalid format \"%s\" specified"), aFormat.c_str());
691
692 /* As of OVF 2.0 we have to use SHA-256 in the manifest. */
693 m->fManifest = m->optListExport.contains(ExportOptions_CreateManifest);
694 if (m->fManifest)
695 m->fDigestTypes = ovfF >= ovf::OVFVersion_2_0 ? RTMANIFEST_ATTR_SHA256 : RTMANIFEST_ATTR_SHA1;
696#ifndef VBOX_WITH_NEW_TAR_CREATOR
697 m->fSha256 = ovfF >= ovf::OVFVersion_2_0;
698#endif
699 Assert(m->hOurManifest == NIL_RTMANIFEST);
700
701 /* Check whether all passwords are supplied or error out. */
702 if (m->m_cPwProvided < m->m_vecPasswordIdentifiers.size())
703 return setError(VBOX_E_INVALID_OBJECT_STATE,
704 tr("Appliance export failed because not all passwords were provided for all encrypted media"));
705
706 ComObjPtr<Progress> progress;
707 HRESULT rc = S_OK;
708 try
709 {
710 /* Parse all necessary info out of the URI */
711 i_parseURI(aPath, m->locInfo);
712 rc = i_writeImpl(ovfF, m->locInfo, progress);
713 }
714 catch (HRESULT aRC)
715 {
716 rc = aRC;
717 }
718
719 if (SUCCEEDED(rc))
720 /* Return progress to the caller */
721 progress.queryInterfaceTo(aProgress.asOutParam());
722
723 return rc;
724}
725
726////////////////////////////////////////////////////////////////////////////////
727//
728// Appliance private methods
729//
730////////////////////////////////////////////////////////////////////////////////
731
732/*******************************************************************************
733 * Export stuff
734 ******************************************************************************/
735
736/**
737 * Implementation for writing out the OVF to disk. This starts a new thread which will call
738 * Appliance::taskThreadWriteOVF().
739 *
740 * This is in a separate private method because it is used from two locations:
741 *
742 * 1) from the public Appliance::Write().
743 *
744 * 2) in a second worker thread; in that case, Appliance::Write() called Appliance::i_writeImpl(), which
745 * called Appliance::i_writeFSOVA(), which called Appliance::i_writeImpl(), which then called this again.
746 *
747 * @param aFormat
748 * @param aLocInfo
749 * @param aProgress
750 * @return
751 */
752HRESULT Appliance::i_writeImpl(ovf::OVFVersion_T aFormat, const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
753{
754 HRESULT rc;
755 try
756 {
757 rc = i_setUpProgress(aProgress,
758 BstrFmt(tr("Export appliance '%s'"), aLocInfo.strPath.c_str()),
759 (aLocInfo.storageType == VFSType_File) ? WriteFile : WriteS3);
760
761 /* Initialize our worker task */
762 TaskOVF* task = NULL;
763 try
764 {
765 task = new TaskOVF(this, TaskOVF::Write, aLocInfo, aProgress);
766 }
767 catch(...)
768 {
769 delete task;
770 throw rc = setError(VBOX_E_OBJECT_NOT_FOUND,
771 tr("Could not create TaskOVF object for for writing out the OVF to disk"));
772 }
773
774 /* The OVF version to write */
775 task->enFormat = aFormat;
776
777 rc = task->createThread();
778 if (FAILED(rc)) throw rc;
779
780 }
781 catch (HRESULT aRC)
782 {
783 rc = aRC;
784 }
785
786 return rc;
787}
788
789/**
790 * Called from Appliance::i_writeFS() for creating a XML document for this
791 * Appliance.
792 *
793 * @param writeLock The current write lock.
794 * @param doc The xml document to fill.
795 * @param stack Structure for temporary private
796 * data shared with caller.
797 * @param strPath Path to the target OVF.
798 * instance for which to write XML.
799 * @param enFormat OVF format (0.9 or 1.0).
800 */
801void Appliance::i_buildXML(AutoWriteLockBase& writeLock,
802 xml::Document &doc,
803 XMLStack &stack,
804 const Utf8Str &strPath,
805 ovf::OVFVersion_T enFormat)
806{
807 xml::ElementNode *pelmRoot = doc.createRootElement("Envelope");
808
809 pelmRoot->setAttribute("ovf:version", enFormat == ovf::OVFVersion_2_0 ? "2.0"
810 : enFormat == ovf::OVFVersion_1_0 ? "1.0"
811 : "0.9");
812 pelmRoot->setAttribute("xml:lang", "en-US");
813
814 Utf8Str strNamespace;
815
816 if (enFormat == ovf::OVFVersion_0_9)
817 {
818 strNamespace = ovf::OVF09_URI_string;
819 }
820 else if (enFormat == ovf::OVFVersion_1_0)
821 {
822 strNamespace = ovf::OVF10_URI_string;
823 }
824 else
825 {
826 strNamespace = ovf::OVF20_URI_string;
827 }
828
829 pelmRoot->setAttribute("xmlns", strNamespace);
830 pelmRoot->setAttribute("xmlns:ovf", strNamespace);
831
832 // pelmRoot->setAttribute("xmlns:ovfstr", "http://schema.dmtf.org/ovf/strings/1");
833 pelmRoot->setAttribute("xmlns:rasd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData");
834 pelmRoot->setAttribute("xmlns:vssd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData");
835 pelmRoot->setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
836 pelmRoot->setAttribute("xmlns:vbox", "http://www.215389.xyz/ovf/machine");
837 // pelmRoot->setAttribute("xsi:schemaLocation", "http://schemas.dmtf.org/ovf/envelope/1 ../ovf-envelope.xsd");
838
839 if (enFormat == ovf::OVFVersion_2_0)
840 {
841 pelmRoot->setAttribute("xmlns:epasd",
842 "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_EthernetPortAllocationSettingData.xsd");
843 pelmRoot->setAttribute("xmlns:sasd",
844 "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_StorageAllocationSettingData.xsd");
845 }
846
847 // <Envelope>/<References>
848 xml::ElementNode *pelmReferences = pelmRoot->createChild("References"); // 0.9 and 1.0
849
850 /* <Envelope>/<DiskSection>:
851 <DiskSection>
852 <Info>List of the virtual disks used in the package</Info>
853 <Disk ovf:capacity="4294967296" ovf:diskId="lamp" ovf:format="..." ovf:populatedSize="1924967692"/>
854 </DiskSection> */
855 xml::ElementNode *pelmDiskSection;
856 if (enFormat == ovf::OVFVersion_0_9)
857 {
858 // <Section xsi:type="ovf:DiskSection_Type">
859 pelmDiskSection = pelmRoot->createChild("Section");
860 pelmDiskSection->setAttribute("xsi:type", "ovf:DiskSection_Type");
861 }
862 else
863 pelmDiskSection = pelmRoot->createChild("DiskSection");
864
865 xml::ElementNode *pelmDiskSectionInfo = pelmDiskSection->createChild("Info");
866 pelmDiskSectionInfo->addContent("List of the virtual disks used in the package");
867
868 /* <Envelope>/<NetworkSection>:
869 <NetworkSection>
870 <Info>Logical networks used in the package</Info>
871 <Network ovf:name="VM Network">
872 <Description>The network that the LAMP Service will be available on</Description>
873 </Network>
874 </NetworkSection> */
875 xml::ElementNode *pelmNetworkSection;
876 if (enFormat == ovf::OVFVersion_0_9)
877 {
878 // <Section xsi:type="ovf:NetworkSection_Type">
879 pelmNetworkSection = pelmRoot->createChild("Section");
880 pelmNetworkSection->setAttribute("xsi:type", "ovf:NetworkSection_Type");
881 }
882 else
883 pelmNetworkSection = pelmRoot->createChild("NetworkSection");
884
885 xml::ElementNode *pelmNetworkSectionInfo = pelmNetworkSection->createChild("Info");
886 pelmNetworkSectionInfo->addContent("Logical networks used in the package");
887
888 // and here come the virtual systems:
889
890 // write a collection if we have more than one virtual system _and_ we're
891 // writing OVF 1.0; otherwise fail since ovftool can't import more than
892 // one machine, it seems
893 xml::ElementNode *pelmToAddVirtualSystemsTo;
894 if (m->virtualSystemDescriptions.size() > 1)
895 {
896 if (enFormat == ovf::OVFVersion_0_9)
897 throw setError(VBOX_E_FILE_ERROR,
898 tr("Cannot export more than one virtual system with OVF 0.9, use OVF 1.0"));
899
900 pelmToAddVirtualSystemsTo = pelmRoot->createChild("VirtualSystemCollection");
901 pelmToAddVirtualSystemsTo->setAttribute("ovf:name", "ExportedVirtualBoxMachines"); // whatever
902 }
903 else
904 pelmToAddVirtualSystemsTo = pelmRoot; // add virtual system directly under root element
905
906 // this list receives pointers to the XML elements in the machine XML which
907 // might have UUIDs that need fixing after we know the UUIDs of the exported images
908 std::list<xml::ElementNode*> llElementsWithUuidAttributes;
909 uint32_t ulFile = 1;
910 /* Iterate through all virtual systems of that appliance */
911 for (list<ComObjPtr<VirtualSystemDescription> >::const_iterator
912 itV = m->virtualSystemDescriptions.begin();
913 itV != m->virtualSystemDescriptions.end();
914 ++itV)
915 {
916 ComObjPtr<VirtualSystemDescription> vsdescThis = *itV;
917 i_buildXMLForOneVirtualSystem(writeLock,
918 *pelmToAddVirtualSystemsTo,
919 &llElementsWithUuidAttributes,
920 vsdescThis,
921 enFormat,
922 stack); // disks and networks stack
923
924 list<Utf8Str> diskList;
925
926 for (list<Utf8Str>::const_iterator
927 itDisk = stack.mapDiskSequenceForOneVM.begin();
928 itDisk != stack.mapDiskSequenceForOneVM.end();
929 ++itDisk)
930 {
931 const Utf8Str &strDiskID = *itDisk;
932 const VirtualSystemDescriptionEntry *pDiskEntry = stack.mapDisks[strDiskID];
933
934 // source path: where the VBox image is
935 const Utf8Str &strSrcFilePath = pDiskEntry->strVBoxCurrent;
936 Bstr bstrSrcFilePath(strSrcFilePath);
937
938 //skip empty Medium. There are no information to add into section <References> or <DiskSection>
939 if (strSrcFilePath.isEmpty() ||
940 pDiskEntry->skipIt == true)
941 continue;
942
943 // Do NOT check here whether the file exists. FindMedium will figure
944 // that out, and filesystem-based tests are simply wrong in the
945 // general case (think of iSCSI).
946
947 // We need some info from the source disks
948 ComPtr<IMedium> pSourceDisk;
949 //DeviceType_T deviceType = DeviceType_HardDisk;// by default
950
951 Log(("Finding source disk \"%ls\"\n", bstrSrcFilePath.raw()));
952
953 HRESULT rc;
954
955 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
956 {
957 rc = mVirtualBox->OpenMedium(bstrSrcFilePath.raw(),
958 DeviceType_HardDisk,
959 AccessMode_ReadWrite,
960 FALSE /* fForceNewUuid */,
961 pSourceDisk.asOutParam());
962 if (FAILED(rc))
963 throw rc;
964 }
965 else if (pDiskEntry->type == VirtualSystemDescriptionType_CDROM)//may be, this is CD/DVD
966 {
967 rc = mVirtualBox->OpenMedium(bstrSrcFilePath.raw(),
968 DeviceType_DVD,
969 AccessMode_ReadOnly,
970 FALSE,
971 pSourceDisk.asOutParam());
972 if (FAILED(rc))
973 throw rc;
974 }
975
976 Bstr uuidSource;
977 rc = pSourceDisk->COMGETTER(Id)(uuidSource.asOutParam());
978 if (FAILED(rc)) throw rc;
979 Guid guidSource(uuidSource);
980
981 // output filename
982 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
983 // target path needs to be composed from where the output OVF is
984 Utf8Str strTargetFilePath(strPath);
985 strTargetFilePath.stripFilename();
986 strTargetFilePath.append("/");
987 strTargetFilePath.append(strTargetFileNameOnly);
988
989 // We are always exporting to VMDK stream optimized for now
990 //Bstr bstrSrcFormat = L"VMDK";//not used
991
992 diskList.push_back(strTargetFilePath);
993
994 LONG64 cbCapacity = 0; // size reported to guest
995 rc = pSourceDisk->COMGETTER(LogicalSize)(&cbCapacity);
996 if (FAILED(rc)) throw rc;
997 /// @todo r=poetzsch: wrong it is reported in bytes ...
998 // capacity is reported in megabytes, so...
999 //cbCapacity *= _1M;
1000
1001 Guid guidTarget; /* Creates a new uniq number for the target disk. */
1002 guidTarget.create();
1003
1004 // now handle the XML for the disk:
1005 Utf8StrFmt strFileRef("file%RI32", ulFile++);
1006 // <File ovf:href="WindowsXpProfessional-disk1.vmdk" ovf:id="file1" ovf:size="1710381056"/>
1007 xml::ElementNode *pelmFile = pelmReferences->createChild("File");
1008 pelmFile->setAttribute("ovf:id", strFileRef);
1009 pelmFile->setAttribute("ovf:href", strTargetFileNameOnly);
1010 /// @todo the actual size is not available at this point of time,
1011 // cause the disk will be compressed. The 1.0 standard says this is
1012 // optional! 1.1 isn't fully clear if the "gzip" format is used.
1013 // Need to be checked. */
1014 // pelmFile->setAttribute("ovf:size", Utf8StrFmt("%RI64", cbFile).c_str());
1015
1016 // add disk to XML Disks section
1017 // <Disk ovf:capacity="8589934592" ovf:diskId="vmdisk1" ovf:fileRef="file1" ovf:format="..."/>
1018 xml::ElementNode *pelmDisk = pelmDiskSection->createChild("Disk");
1019 pelmDisk->setAttribute("ovf:capacity", Utf8StrFmt("%RI64", cbCapacity).c_str());
1020 pelmDisk->setAttribute("ovf:diskId", strDiskID);
1021 pelmDisk->setAttribute("ovf:fileRef", strFileRef);
1022
1023 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)//deviceType == DeviceType_HardDisk
1024 {
1025 pelmDisk->setAttribute("ovf:format",
1026 (enFormat == ovf::OVFVersion_0_9)
1027 ? "http://www.vmware.com/specifications/vmdk.html#sparse" // must be sparse or ovftoo
1028 : "http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized"
1029 // correct string as communicated to us by VMware (public bug #6612)
1030 );
1031 }
1032 else //pDiskEntry->type == VirtualSystemDescriptionType_CDROM, deviceType == DeviceType_DVD
1033 {
1034 pelmDisk->setAttribute("ovf:format",
1035 "http://www.ecma-international.org/publications/standards/Ecma-119.htm"
1036 );
1037 }
1038
1039 // add the UUID of the newly target image to the OVF disk element, but in the
1040 // vbox: namespace since it's not part of the standard
1041 pelmDisk->setAttribute("vbox:uuid", Utf8StrFmt("%RTuuid", guidTarget.raw()).c_str());
1042
1043 // now, we might have other XML elements from vbox:Machine pointing to this image,
1044 // but those would refer to the UUID of the _source_ image (which we created the
1045 // export image from); those UUIDs need to be fixed to the export image
1046 Utf8Str strGuidSourceCurly = guidSource.toStringCurly();
1047 for (std::list<xml::ElementNode*>::const_iterator
1048 it = llElementsWithUuidAttributes.begin();
1049 it != llElementsWithUuidAttributes.end();
1050 ++it)
1051 {
1052 xml::ElementNode *pelmImage = *it;
1053 Utf8Str strUUID;
1054 pelmImage->getAttributeValue("uuid", strUUID);
1055 if (strUUID == strGuidSourceCurly)
1056 // overwrite existing uuid attribute
1057 pelmImage->setAttribute("uuid", guidTarget.toStringCurly());
1058 }
1059 }
1060 llElementsWithUuidAttributes.clear();
1061 stack.mapDiskSequenceForOneVM.clear();
1062 }
1063
1064 // now, fill in the network section we set up empty above according
1065 // to the networks we found with the hardware items
1066 for (map<Utf8Str, bool>::const_iterator
1067 it = stack.mapNetworks.begin();
1068 it != stack.mapNetworks.end();
1069 ++it)
1070 {
1071 const Utf8Str &strNetwork = it->first;
1072 xml::ElementNode *pelmNetwork = pelmNetworkSection->createChild("Network");
1073 pelmNetwork->setAttribute("ovf:name", strNetwork.c_str());
1074 pelmNetwork->createChild("Description")->addContent("Logical network used by this appliance.");
1075 }
1076
1077}
1078
1079/**
1080 * Called from Appliance::i_buildXML() for each virtual system (machine) that
1081 * needs XML written out.
1082 *
1083 * @param writeLock The current write lock.
1084 * @param elmToAddVirtualSystemsTo XML element to append elements to.
1085 * @param pllElementsWithUuidAttributes out: list of XML elements produced here
1086 * with UUID attributes for quick
1087 * fixing by caller later
1088 * @param vsdescThis The IVirtualSystemDescription
1089 * instance for which to write XML.
1090 * @param enFormat OVF format (0.9 or 1.0).
1091 * @param stack Structure for temporary private
1092 * data shared with caller.
1093 */
1094void Appliance::i_buildXMLForOneVirtualSystem(AutoWriteLockBase& writeLock,
1095 xml::ElementNode &elmToAddVirtualSystemsTo,
1096 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes,
1097 ComObjPtr<VirtualSystemDescription> &vsdescThis,
1098 ovf::OVFVersion_T enFormat,
1099 XMLStack &stack)
1100{
1101 LogFlowFunc(("ENTER appliance %p\n", this));
1102
1103 xml::ElementNode *pelmVirtualSystem;
1104 if (enFormat == ovf::OVFVersion_0_9)
1105 {
1106 // <Section xsi:type="ovf:NetworkSection_Type">
1107 pelmVirtualSystem = elmToAddVirtualSystemsTo.createChild("Content");
1108 pelmVirtualSystem->setAttribute("xsi:type", "ovf:VirtualSystem_Type");
1109 }
1110 else
1111 pelmVirtualSystem = elmToAddVirtualSystemsTo.createChild("VirtualSystem");
1112
1113 /*xml::ElementNode *pelmVirtualSystemInfo =*/ pelmVirtualSystem->createChild("Info")->addContent("A virtual machine");
1114
1115 std::list<VirtualSystemDescriptionEntry*> llName = vsdescThis->i_findByType(VirtualSystemDescriptionType_Name);
1116 if (llName.empty())
1117 throw setError(VBOX_E_NOT_SUPPORTED, tr("Missing VM name"));
1118 Utf8Str &strVMName = llName.back()->strVBoxCurrent;
1119 pelmVirtualSystem->setAttribute("ovf:id", strVMName);
1120
1121 // product info
1122 std::list<VirtualSystemDescriptionEntry*> llProduct = vsdescThis->i_findByType(VirtualSystemDescriptionType_Product);
1123 std::list<VirtualSystemDescriptionEntry*> llProductUrl = vsdescThis->i_findByType(VirtualSystemDescriptionType_ProductUrl);
1124 std::list<VirtualSystemDescriptionEntry*> llVendor = vsdescThis->i_findByType(VirtualSystemDescriptionType_Vendor);
1125 std::list<VirtualSystemDescriptionEntry*> llVendorUrl = vsdescThis->i_findByType(VirtualSystemDescriptionType_VendorUrl);
1126 std::list<VirtualSystemDescriptionEntry*> llVersion = vsdescThis->i_findByType(VirtualSystemDescriptionType_Version);
1127 bool fProduct = llProduct.size() && !llProduct.back()->strVBoxCurrent.isEmpty();
1128 bool fProductUrl = llProductUrl.size() && !llProductUrl.back()->strVBoxCurrent.isEmpty();
1129 bool fVendor = llVendor.size() && !llVendor.back()->strVBoxCurrent.isEmpty();
1130 bool fVendorUrl = llVendorUrl.size() && !llVendorUrl.back()->strVBoxCurrent.isEmpty();
1131 bool fVersion = llVersion.size() && !llVersion.back()->strVBoxCurrent.isEmpty();
1132 if (fProduct || fProductUrl || fVendor || fVendorUrl || fVersion)
1133 {
1134 /* <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
1135 <Info>Meta-information about the installed software</Info>
1136 <Product>VAtest</Product>
1137 <Vendor>SUN Microsystems</Vendor>
1138 <Version>10.0</Version>
1139 <ProductUrl>http://blogs.sun.com/VirtualGuru</ProductUrl>
1140 <VendorUrl>http://www.sun.com</VendorUrl>
1141 </Section> */
1142 xml::ElementNode *pelmAnnotationSection;
1143 if (enFormat == ovf::OVFVersion_0_9)
1144 {
1145 // <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
1146 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
1147 pelmAnnotationSection->setAttribute("xsi:type", "ovf:ProductSection_Type");
1148 }
1149 else
1150 pelmAnnotationSection = pelmVirtualSystem->createChild("ProductSection");
1151
1152 pelmAnnotationSection->createChild("Info")->addContent("Meta-information about the installed software");
1153 if (fProduct)
1154 pelmAnnotationSection->createChild("Product")->addContent(llProduct.back()->strVBoxCurrent);
1155 if (fVendor)
1156 pelmAnnotationSection->createChild("Vendor")->addContent(llVendor.back()->strVBoxCurrent);
1157 if (fVersion)
1158 pelmAnnotationSection->createChild("Version")->addContent(llVersion.back()->strVBoxCurrent);
1159 if (fProductUrl)
1160 pelmAnnotationSection->createChild("ProductUrl")->addContent(llProductUrl.back()->strVBoxCurrent);
1161 if (fVendorUrl)
1162 pelmAnnotationSection->createChild("VendorUrl")->addContent(llVendorUrl.back()->strVBoxCurrent);
1163 }
1164
1165 // description
1166 std::list<VirtualSystemDescriptionEntry*> llDescription = vsdescThis->i_findByType(VirtualSystemDescriptionType_Description);
1167 if (llDescription.size() &&
1168 !llDescription.back()->strVBoxCurrent.isEmpty())
1169 {
1170 /* <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
1171 <Info>A human-readable annotation</Info>
1172 <Annotation>Plan 9</Annotation>
1173 </Section> */
1174 xml::ElementNode *pelmAnnotationSection;
1175 if (enFormat == ovf::OVFVersion_0_9)
1176 {
1177 // <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
1178 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
1179 pelmAnnotationSection->setAttribute("xsi:type", "ovf:AnnotationSection_Type");
1180 }
1181 else
1182 pelmAnnotationSection = pelmVirtualSystem->createChild("AnnotationSection");
1183
1184 pelmAnnotationSection->createChild("Info")->addContent("A human-readable annotation");
1185 pelmAnnotationSection->createChild("Annotation")->addContent(llDescription.back()->strVBoxCurrent);
1186 }
1187
1188 // license
1189 std::list<VirtualSystemDescriptionEntry*> llLicense = vsdescThis->i_findByType(VirtualSystemDescriptionType_License);
1190 if (llLicense.size() &&
1191 !llLicense.back()->strVBoxCurrent.isEmpty())
1192 {
1193 /* <EulaSection>
1194 <Info ovf:msgid="6">License agreement for the Virtual System.</Info>
1195 <License ovf:msgid="1">License terms can go in here.</License>
1196 </EulaSection> */
1197 xml::ElementNode *pelmEulaSection;
1198 if (enFormat == ovf::OVFVersion_0_9)
1199 {
1200 pelmEulaSection = pelmVirtualSystem->createChild("Section");
1201 pelmEulaSection->setAttribute("xsi:type", "ovf:EulaSection_Type");
1202 }
1203 else
1204 pelmEulaSection = pelmVirtualSystem->createChild("EulaSection");
1205
1206 pelmEulaSection->createChild("Info")->addContent("License agreement for the virtual system");
1207 pelmEulaSection->createChild("License")->addContent(llLicense.back()->strVBoxCurrent);
1208 }
1209
1210 // operating system
1211 std::list<VirtualSystemDescriptionEntry*> llOS = vsdescThis->i_findByType(VirtualSystemDescriptionType_OS);
1212 if (llOS.empty())
1213 throw setError(VBOX_E_NOT_SUPPORTED, tr("Missing OS type"));
1214 /* <OperatingSystemSection ovf:id="82">
1215 <Info>Guest Operating System</Info>
1216 <Description>Linux 2.6.x</Description>
1217 </OperatingSystemSection> */
1218 VirtualSystemDescriptionEntry *pvsdeOS = llOS.back();
1219 xml::ElementNode *pelmOperatingSystemSection;
1220 if (enFormat == ovf::OVFVersion_0_9)
1221 {
1222 pelmOperatingSystemSection = pelmVirtualSystem->createChild("Section");
1223 pelmOperatingSystemSection->setAttribute("xsi:type", "ovf:OperatingSystemSection_Type");
1224 }
1225 else
1226 pelmOperatingSystemSection = pelmVirtualSystem->createChild("OperatingSystemSection");
1227
1228 pelmOperatingSystemSection->setAttribute("ovf:id", pvsdeOS->strOvf);
1229 pelmOperatingSystemSection->createChild("Info")->addContent("The kind of installed guest operating system");
1230 Utf8Str strOSDesc;
1231 convertCIMOSType2VBoxOSType(strOSDesc, (ovf::CIMOSType_T)pvsdeOS->strOvf.toInt32(), "");
1232 pelmOperatingSystemSection->createChild("Description")->addContent(strOSDesc);
1233 // add the VirtualBox ostype in a custom tag in a different namespace
1234 xml::ElementNode *pelmVBoxOSType = pelmOperatingSystemSection->createChild("vbox:OSType");
1235 pelmVBoxOSType->setAttribute("ovf:required", "false");
1236 pelmVBoxOSType->addContent(pvsdeOS->strVBoxCurrent);
1237
1238 // <VirtualHardwareSection ovf:id="hw1" ovf:transport="iso">
1239 xml::ElementNode *pelmVirtualHardwareSection;
1240 if (enFormat == ovf::OVFVersion_0_9)
1241 {
1242 // <Section xsi:type="ovf:VirtualHardwareSection_Type">
1243 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("Section");
1244 pelmVirtualHardwareSection->setAttribute("xsi:type", "ovf:VirtualHardwareSection_Type");
1245 }
1246 else
1247 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("VirtualHardwareSection");
1248
1249 pelmVirtualHardwareSection->createChild("Info")->addContent("Virtual hardware requirements for a virtual machine");
1250
1251 /* <System>
1252 <vssd:Description>Description of the virtual hardware section.</vssd:Description>
1253 <vssd:ElementName>vmware</vssd:ElementName>
1254 <vssd:InstanceID>1</vssd:InstanceID>
1255 <vssd:VirtualSystemIdentifier>MyLampService</vssd:VirtualSystemIdentifier>
1256 <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
1257 </System> */
1258 xml::ElementNode *pelmSystem = pelmVirtualHardwareSection->createChild("System");
1259
1260 pelmSystem->createChild("vssd:ElementName")->addContent("Virtual Hardware Family"); // required OVF 1.0
1261
1262 // <vssd:InstanceId>0</vssd:InstanceId>
1263 if (enFormat == ovf::OVFVersion_0_9)
1264 pelmSystem->createChild("vssd:InstanceId")->addContent("0");
1265 else // capitalization changed...
1266 pelmSystem->createChild("vssd:InstanceID")->addContent("0");
1267
1268 // <vssd:VirtualSystemIdentifier>VAtest</vssd:VirtualSystemIdentifier>
1269 pelmSystem->createChild("vssd:VirtualSystemIdentifier")->addContent(strVMName);
1270 // <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
1271 const char *pcszHardware = "virtualbox-2.2";
1272 if (enFormat == ovf::OVFVersion_0_9)
1273 // pretend to be vmware compatible then
1274 pcszHardware = "vmx-6";
1275 pelmSystem->createChild("vssd:VirtualSystemType")->addContent(pcszHardware);
1276
1277 // loop thru all description entries twice; once to write out all
1278 // devices _except_ disk images, and a second time to assign the
1279 // disk images; this is because disk images need to reference
1280 // IDE controllers, and we can't know their instance IDs without
1281 // assigning them first
1282
1283 uint32_t idIDEPrimaryController = 0;
1284 int32_t lIDEPrimaryControllerIndex = 0;
1285 uint32_t idIDESecondaryController = 0;
1286 int32_t lIDESecondaryControllerIndex = 0;
1287 uint32_t idSATAController = 0;
1288 int32_t lSATAControllerIndex = 0;
1289 uint32_t idSCSIController = 0;
1290 int32_t lSCSIControllerIndex = 0;
1291
1292 uint32_t ulInstanceID = 1;
1293
1294 uint32_t cDVDs = 0;
1295
1296 for (size_t uLoop = 1; uLoop <= 2; ++uLoop)
1297 {
1298 int32_t lIndexThis = 0;
1299 for (vector<VirtualSystemDescriptionEntry>::const_iterator
1300 it = vsdescThis->m->maDescriptions.begin();
1301 it != vsdescThis->m->maDescriptions.end();
1302 ++it, ++lIndexThis)
1303 {
1304 const VirtualSystemDescriptionEntry &desc = *it;
1305
1306 LogFlowFunc(("Loop %u: handling description entry ulIndex=%u, type=%s, strRef=%s, strOvf=%s, strVBox=%s, strExtraConfig=%s\n",
1307 uLoop,
1308 desc.ulIndex,
1309 ( desc.type == VirtualSystemDescriptionType_HardDiskControllerIDE ? "HardDiskControllerIDE"
1310 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSATA ? "HardDiskControllerSATA"
1311 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSCSI ? "HardDiskControllerSCSI"
1312 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSAS ? "HardDiskControllerSAS"
1313 : desc.type == VirtualSystemDescriptionType_HardDiskImage ? "HardDiskImage"
1314 : Utf8StrFmt("%d", desc.type).c_str()),
1315 desc.strRef.c_str(),
1316 desc.strOvf.c_str(),
1317 desc.strVBoxCurrent.c_str(),
1318 desc.strExtraConfigCurrent.c_str()));
1319
1320 ovf::ResourceType_T type = (ovf::ResourceType_T)0; // if this becomes != 0 then we do stuff
1321 Utf8Str strResourceSubType;
1322
1323 Utf8Str strDescription; // results in <rasd:Description>...</rasd:Description> block
1324 Utf8Str strCaption; // results in <rasd:Caption>...</rasd:Caption> block
1325
1326 uint32_t ulParent = 0;
1327
1328 int32_t lVirtualQuantity = -1;
1329 Utf8Str strAllocationUnits;
1330
1331 int32_t lAddress = -1;
1332 int32_t lBusNumber = -1;
1333 int32_t lAddressOnParent = -1;
1334
1335 int32_t lAutomaticAllocation = -1; // 0 means "false", 1 means "true"
1336 Utf8Str strConnection; // results in <rasd:Connection>...</rasd:Connection> block
1337 Utf8Str strHostResource;
1338
1339 uint64_t uTemp;
1340
1341 ovf::VirtualHardwareItem vhi;
1342 ovf::StorageItem si;
1343 ovf::EthernetPortItem epi;
1344
1345 switch (desc.type)
1346 {
1347 case VirtualSystemDescriptionType_CPU:
1348 /* <Item>
1349 <rasd:Caption>1 virtual CPU</rasd:Caption>
1350 <rasd:Description>Number of virtual CPUs</rasd:Description>
1351 <rasd:ElementName>virtual CPU</rasd:ElementName>
1352 <rasd:InstanceID>1</rasd:InstanceID>
1353 <rasd:ResourceType>3</rasd:ResourceType>
1354 <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
1355 </Item> */
1356 if (uLoop == 1)
1357 {
1358 strDescription = "Number of virtual CPUs";
1359 type = ovf::ResourceType_Processor; // 3
1360 desc.strVBoxCurrent.toInt(uTemp);
1361 lVirtualQuantity = (int32_t)uTemp;
1362 strCaption = Utf8StrFmt("%d virtual CPU", lVirtualQuantity); // without this ovftool
1363 // won't eat the item
1364 }
1365 break;
1366
1367 case VirtualSystemDescriptionType_Memory:
1368 /* <Item>
1369 <rasd:AllocationUnits>MegaBytes</rasd:AllocationUnits>
1370 <rasd:Caption>256 MB of memory</rasd:Caption>
1371 <rasd:Description>Memory Size</rasd:Description>
1372 <rasd:ElementName>Memory</rasd:ElementName>
1373 <rasd:InstanceID>2</rasd:InstanceID>
1374 <rasd:ResourceType>4</rasd:ResourceType>
1375 <rasd:VirtualQuantity>256</rasd:VirtualQuantity>
1376 </Item> */
1377 if (uLoop == 1)
1378 {
1379 strDescription = "Memory Size";
1380 type = ovf::ResourceType_Memory; // 4
1381 desc.strVBoxCurrent.toInt(uTemp);
1382 lVirtualQuantity = (int32_t)(uTemp / _1M);
1383 strAllocationUnits = "MegaBytes";
1384 strCaption = Utf8StrFmt("%d MB of memory", lVirtualQuantity); // without this ovftool
1385 // won't eat the item
1386 }
1387 break;
1388
1389 case VirtualSystemDescriptionType_HardDiskControllerIDE:
1390 /* <Item>
1391 <rasd:Caption>ideController1</rasd:Caption>
1392 <rasd:Description>IDE Controller</rasd:Description>
1393 <rasd:InstanceId>5</rasd:InstanceId>
1394 <rasd:ResourceType>5</rasd:ResourceType>
1395 <rasd:Address>1</rasd:Address>
1396 <rasd:BusNumber>1</rasd:BusNumber>
1397 </Item> */
1398 if (uLoop == 1)
1399 {
1400 strDescription = "IDE Controller";
1401 type = ovf::ResourceType_IDEController; // 5
1402 strResourceSubType = desc.strVBoxCurrent;
1403
1404 if (!lIDEPrimaryControllerIndex)
1405 {
1406 // first IDE controller:
1407 strCaption = "ideController0";
1408 lAddress = 0;
1409 lBusNumber = 0;
1410 // remember this ID
1411 idIDEPrimaryController = ulInstanceID;
1412 lIDEPrimaryControllerIndex = lIndexThis;
1413 }
1414 else
1415 {
1416 // second IDE controller:
1417 strCaption = "ideController1";
1418 lAddress = 1;
1419 lBusNumber = 1;
1420 // remember this ID
1421 idIDESecondaryController = ulInstanceID;
1422 lIDESecondaryControllerIndex = lIndexThis;
1423 }
1424 }
1425 break;
1426
1427 case VirtualSystemDescriptionType_HardDiskControllerSATA:
1428 /* <Item>
1429 <rasd:Caption>sataController0</rasd:Caption>
1430 <rasd:Description>SATA Controller</rasd:Description>
1431 <rasd:InstanceId>4</rasd:InstanceId>
1432 <rasd:ResourceType>20</rasd:ResourceType>
1433 <rasd:ResourceSubType>ahci</rasd:ResourceSubType>
1434 <rasd:Address>0</rasd:Address>
1435 <rasd:BusNumber>0</rasd:BusNumber>
1436 </Item>
1437 */
1438 if (uLoop == 1)
1439 {
1440 strDescription = "SATA Controller";
1441 strCaption = "sataController0";
1442 type = ovf::ResourceType_OtherStorageDevice; // 20
1443 // it seems that OVFTool always writes these two, and since we can only
1444 // have one SATA controller, we'll use this as well
1445 lAddress = 0;
1446 lBusNumber = 0;
1447
1448 if ( desc.strVBoxCurrent.isEmpty() // AHCI is the default in VirtualBox
1449 || (!desc.strVBoxCurrent.compare("ahci", Utf8Str::CaseInsensitive))
1450 )
1451 strResourceSubType = "AHCI";
1452 else
1453 throw setError(VBOX_E_NOT_SUPPORTED,
1454 tr("Invalid config string \"%s\" in SATA controller"), desc.strVBoxCurrent.c_str());
1455
1456 // remember this ID
1457 idSATAController = ulInstanceID;
1458 lSATAControllerIndex = lIndexThis;
1459 }
1460 break;
1461
1462 case VirtualSystemDescriptionType_HardDiskControllerSCSI:
1463 case VirtualSystemDescriptionType_HardDiskControllerSAS:
1464 /* <Item>
1465 <rasd:Caption>scsiController0</rasd:Caption>
1466 <rasd:Description>SCSI Controller</rasd:Description>
1467 <rasd:InstanceId>4</rasd:InstanceId>
1468 <rasd:ResourceType>6</rasd:ResourceType>
1469 <rasd:ResourceSubType>buslogic</rasd:ResourceSubType>
1470 <rasd:Address>0</rasd:Address>
1471 <rasd:BusNumber>0</rasd:BusNumber>
1472 </Item>
1473 */
1474 if (uLoop == 1)
1475 {
1476 strDescription = "SCSI Controller";
1477 strCaption = "scsiController0";
1478 type = ovf::ResourceType_ParallelSCSIHBA; // 6
1479 // it seems that OVFTool always writes these two, and since we can only
1480 // have one SATA controller, we'll use this as well
1481 lAddress = 0;
1482 lBusNumber = 0;
1483
1484 if ( desc.strVBoxCurrent.isEmpty() // LsiLogic is the default in VirtualBox
1485 || (!desc.strVBoxCurrent.compare("lsilogic", Utf8Str::CaseInsensitive))
1486 )
1487 strResourceSubType = "lsilogic";
1488 else if (!desc.strVBoxCurrent.compare("buslogic", Utf8Str::CaseInsensitive))
1489 strResourceSubType = "buslogic";
1490 else if (!desc.strVBoxCurrent.compare("lsilogicsas", Utf8Str::CaseInsensitive))
1491 strResourceSubType = "lsilogicsas";
1492 else
1493 throw setError(VBOX_E_NOT_SUPPORTED,
1494 tr("Invalid config string \"%s\" in SCSI/SAS controller"),
1495 desc.strVBoxCurrent.c_str());
1496
1497 // remember this ID
1498 idSCSIController = ulInstanceID;
1499 lSCSIControllerIndex = lIndexThis;
1500 }
1501 break;
1502
1503 case VirtualSystemDescriptionType_HardDiskImage:
1504 /* <Item>
1505 <rasd:Caption>disk1</rasd:Caption>
1506 <rasd:InstanceId>8</rasd:InstanceId>
1507 <rasd:ResourceType>17</rasd:ResourceType>
1508 <rasd:HostResource>/disk/vmdisk1</rasd:HostResource>
1509 <rasd:Parent>4</rasd:Parent>
1510 <rasd:AddressOnParent>0</rasd:AddressOnParent>
1511 </Item> */
1512 if (uLoop == 2)
1513 {
1514 uint32_t cDisks = (uint32_t)stack.mapDisks.size();
1515 Utf8Str strDiskID = Utf8StrFmt("vmdisk%RI32", ++cDisks);
1516
1517 strDescription = "Disk Image";
1518 strCaption = Utf8StrFmt("disk%RI32", cDisks); // this is not used for anything else
1519 type = ovf::ResourceType_HardDisk; // 17
1520
1521 // the following references the "<Disks>" XML block
1522 strHostResource = Utf8StrFmt("/disk/%s", strDiskID.c_str());
1523
1524 // controller=<index>;channel=<c>
1525 size_t pos1 = desc.strExtraConfigCurrent.find("controller=");
1526 size_t pos2 = desc.strExtraConfigCurrent.find("channel=");
1527 int32_t lControllerIndex = -1;
1528 if (pos1 != Utf8Str::npos)
1529 {
1530 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
1531 if (lControllerIndex == lIDEPrimaryControllerIndex)
1532 ulParent = idIDEPrimaryController;
1533 else if (lControllerIndex == lIDESecondaryControllerIndex)
1534 ulParent = idIDESecondaryController;
1535 else if (lControllerIndex == lSCSIControllerIndex)
1536 ulParent = idSCSIController;
1537 else if (lControllerIndex == lSATAControllerIndex)
1538 ulParent = idSATAController;
1539 }
1540 if (pos2 != Utf8Str::npos)
1541 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
1542
1543 LogFlowFunc(("HardDiskImage details: pos1=%d, pos2=%d, lControllerIndex=%d, lIDEPrimaryControllerIndex=%d, lIDESecondaryControllerIndex=%d, ulParent=%d, lAddressOnParent=%d\n",
1544 pos1, pos2, lControllerIndex, lIDEPrimaryControllerIndex, lIDESecondaryControllerIndex,
1545 ulParent, lAddressOnParent));
1546
1547 if ( !ulParent
1548 || lAddressOnParent == -1
1549 )
1550 throw setError(VBOX_E_NOT_SUPPORTED,
1551 tr("Missing or bad extra config string in hard disk image: \"%s\""),
1552 desc.strExtraConfigCurrent.c_str());
1553
1554 stack.mapDisks[strDiskID] = &desc;
1555
1556 //use the list stack.mapDiskSequence where the disks go as the "VirtualSystem" should be placed
1557 //in the OVF description file.
1558 stack.mapDiskSequence.push_back(strDiskID);
1559 stack.mapDiskSequenceForOneVM.push_back(strDiskID);
1560 }
1561 break;
1562
1563 case VirtualSystemDescriptionType_Floppy:
1564 if (uLoop == 1)
1565 {
1566 strDescription = "Floppy Drive";
1567 strCaption = "floppy0"; // this is what OVFTool writes
1568 type = ovf::ResourceType_FloppyDrive; // 14
1569 lAutomaticAllocation = 0;
1570 lAddressOnParent = 0; // this is what OVFTool writes
1571 }
1572 break;
1573
1574 case VirtualSystemDescriptionType_CDROM:
1575 /* <Item>
1576 <rasd:Caption>cdrom1</rasd:Caption>
1577 <rasd:InstanceId>8</rasd:InstanceId>
1578 <rasd:ResourceType>15</rasd:ResourceType>
1579 <rasd:HostResource>/disk/cdrom1</rasd:HostResource>
1580 <rasd:Parent>4</rasd:Parent>
1581 <rasd:AddressOnParent>0</rasd:AddressOnParent>
1582 </Item> */
1583 if (uLoop == 2)
1584 {
1585 uint32_t cDisks = (uint32_t)stack.mapDisks.size();
1586 Utf8Str strDiskID = Utf8StrFmt("iso%RI32", ++cDisks);
1587 ++cDVDs;
1588 strDescription = "CD-ROM Drive";
1589 strCaption = Utf8StrFmt("cdrom%RI32", cDVDs); // OVFTool starts with 1
1590 type = ovf::ResourceType_CDDrive; // 15
1591 lAutomaticAllocation = 1;
1592
1593 //skip empty Medium. There are no information to add into section <References> or <DiskSection>
1594 if (desc.strVBoxCurrent.isNotEmpty() &&
1595 desc.skipIt == false)
1596 {
1597 // the following references the "<Disks>" XML block
1598 strHostResource = Utf8StrFmt("/disk/%s", strDiskID.c_str());
1599 }
1600
1601 // controller=<index>;channel=<c>
1602 size_t pos1 = desc.strExtraConfigCurrent.find("controller=");
1603 size_t pos2 = desc.strExtraConfigCurrent.find("channel=");
1604 int32_t lControllerIndex = -1;
1605 if (pos1 != Utf8Str::npos)
1606 {
1607 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
1608 if (lControllerIndex == lIDEPrimaryControllerIndex)
1609 ulParent = idIDEPrimaryController;
1610 else if (lControllerIndex == lIDESecondaryControllerIndex)
1611 ulParent = idIDESecondaryController;
1612 else if (lControllerIndex == lSCSIControllerIndex)
1613 ulParent = idSCSIController;
1614 else if (lControllerIndex == lSATAControllerIndex)
1615 ulParent = idSATAController;
1616 }
1617 if (pos2 != Utf8Str::npos)
1618 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
1619
1620 LogFlowFunc(("DVD drive details: pos1=%d, pos2=%d, lControllerIndex=%d, lIDEPrimaryControllerIndex=%d, lIDESecondaryControllerIndex=%d, ulParent=%d, lAddressOnParent=%d\n",
1621 pos1, pos2, lControllerIndex, lIDEPrimaryControllerIndex,
1622 lIDESecondaryControllerIndex, ulParent, lAddressOnParent));
1623
1624 if ( !ulParent
1625 || lAddressOnParent == -1
1626 )
1627 throw setError(VBOX_E_NOT_SUPPORTED,
1628 tr("Missing or bad extra config string in DVD drive medium: \"%s\""),
1629 desc.strExtraConfigCurrent.c_str());
1630
1631 stack.mapDisks[strDiskID] = &desc;
1632
1633 //use the list stack.mapDiskSequence where the disks go as the "VirtualSystem" should be placed
1634 //in the OVF description file.
1635 stack.mapDiskSequence.push_back(strDiskID);
1636 stack.mapDiskSequenceForOneVM.push_back(strDiskID);
1637 // there is no DVD drive map to update because it is
1638 // handled completely with this entry.
1639 }
1640 break;
1641
1642 case VirtualSystemDescriptionType_NetworkAdapter:
1643 /* <Item>
1644 <rasd:AutomaticAllocation>true</rasd:AutomaticAllocation>
1645 <rasd:Caption>Ethernet adapter on 'VM Network'</rasd:Caption>
1646 <rasd:Connection>VM Network</rasd:Connection>
1647 <rasd:ElementName>VM network</rasd:ElementName>
1648 <rasd:InstanceID>3</rasd:InstanceID>
1649 <rasd:ResourceType>10</rasd:ResourceType>
1650 </Item> */
1651 if (uLoop == 2)
1652 {
1653 lAutomaticAllocation = 1;
1654 strCaption = Utf8StrFmt("Ethernet adapter on '%s'", desc.strOvf.c_str());
1655 type = ovf::ResourceType_EthernetAdapter; // 10
1656 /* Set the hardware type to something useful.
1657 * To be compatible with vmware & others we set
1658 * PCNet32 for our PCNet types & E1000 for the
1659 * E1000 cards. */
1660 switch (desc.strVBoxCurrent.toInt32())
1661 {
1662 case NetworkAdapterType_Am79C970A:
1663 case NetworkAdapterType_Am79C973: strResourceSubType = "PCNet32"; break;
1664#ifdef VBOX_WITH_E1000
1665 case NetworkAdapterType_I82540EM:
1666 case NetworkAdapterType_I82545EM:
1667 case NetworkAdapterType_I82543GC: strResourceSubType = "E1000"; break;
1668#endif /* VBOX_WITH_E1000 */
1669 }
1670 strConnection = desc.strOvf;
1671
1672 stack.mapNetworks[desc.strOvf] = true;
1673 }
1674 break;
1675
1676 case VirtualSystemDescriptionType_USBController:
1677 /* <Item ovf:required="false">
1678 <rasd:Caption>usb</rasd:Caption>
1679 <rasd:Description>USB Controller</rasd:Description>
1680 <rasd:InstanceId>3</rasd:InstanceId>
1681 <rasd:ResourceType>23</rasd:ResourceType>
1682 <rasd:Address>0</rasd:Address>
1683 <rasd:BusNumber>0</rasd:BusNumber>
1684 </Item> */
1685 if (uLoop == 1)
1686 {
1687 strDescription = "USB Controller";
1688 strCaption = "usb";
1689 type = ovf::ResourceType_USBController; // 23
1690 lAddress = 0; // this is what OVFTool writes
1691 lBusNumber = 0; // this is what OVFTool writes
1692 }
1693 break;
1694
1695 case VirtualSystemDescriptionType_SoundCard:
1696 /* <Item ovf:required="false">
1697 <rasd:Caption>sound</rasd:Caption>
1698 <rasd:Description>Sound Card</rasd:Description>
1699 <rasd:InstanceId>10</rasd:InstanceId>
1700 <rasd:ResourceType>35</rasd:ResourceType>
1701 <rasd:ResourceSubType>ensoniq1371</rasd:ResourceSubType>
1702 <rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
1703 <rasd:AddressOnParent>3</rasd:AddressOnParent>
1704 </Item> */
1705 if (uLoop == 1)
1706 {
1707 strDescription = "Sound Card";
1708 strCaption = "sound";
1709 type = ovf::ResourceType_SoundCard; // 35
1710 strResourceSubType = desc.strOvf; // e.g. ensoniq1371
1711 lAutomaticAllocation = 0;
1712 lAddressOnParent = 3; // what gives? this is what OVFTool writes
1713 }
1714 break;
1715
1716 default: break; /* Shut up MSC. */
1717 }
1718
1719 if (type)
1720 {
1721 xml::ElementNode *pItem;
1722 xml::ElementNode *pItemHelper;
1723 RTCString itemElement;
1724 RTCString itemElementHelper;
1725
1726 if (enFormat == ovf::OVFVersion_2_0)
1727 {
1728 if(uLoop == 2)
1729 {
1730 if (desc.type == VirtualSystemDescriptionType_NetworkAdapter)
1731 {
1732 itemElement = "epasd:";
1733 pItem = pelmVirtualHardwareSection->createChild("EthernetPortItem");
1734 }
1735 else if (desc.type == VirtualSystemDescriptionType_CDROM ||
1736 desc.type == VirtualSystemDescriptionType_HardDiskImage)
1737 {
1738 itemElement = "sasd:";
1739 pItem = pelmVirtualHardwareSection->createChild("StorageItem");
1740 }
1741 else
1742 pItem = NULL;
1743 }
1744 else
1745 {
1746 itemElement = "rasd:";
1747 pItem = pelmVirtualHardwareSection->createChild("Item");
1748 }
1749 }
1750 else
1751 {
1752 itemElement = "rasd:";
1753 pItem = pelmVirtualHardwareSection->createChild("Item");
1754 }
1755
1756 // NOTE: DO NOT CHANGE THE ORDER of these items! The OVF standards prescribes that
1757 // the elements from the rasd: namespace must be sorted by letter, and VMware
1758 // actually requires this as well (see public bug #6612)
1759
1760 if (lAddress != -1)
1761 {
1762 //pItem->createChild("rasd:Address")->addContent(Utf8StrFmt("%d", lAddress));
1763 itemElementHelper = itemElement;
1764 pItemHelper = pItem->createChild(itemElementHelper.append("Address").c_str());
1765 pItemHelper->addContent(Utf8StrFmt("%d", lAddress));
1766 }
1767
1768 if (lAddressOnParent != -1)
1769 {
1770 //pItem->createChild("rasd:AddressOnParent")->addContent(Utf8StrFmt("%d", lAddressOnParent));
1771 itemElementHelper = itemElement;
1772 pItemHelper = pItem->createChild(itemElementHelper.append("AddressOnParent").c_str());
1773 pItemHelper->addContent(Utf8StrFmt("%d", lAddressOnParent));
1774 }
1775
1776 if (!strAllocationUnits.isEmpty())
1777 {
1778 //pItem->createChild("rasd:AllocationUnits")->addContent(strAllocationUnits);
1779 itemElementHelper = itemElement;
1780 pItemHelper = pItem->createChild(itemElementHelper.append("AllocationUnits").c_str());
1781 pItemHelper->addContent(strAllocationUnits);
1782 }
1783
1784 if (lAutomaticAllocation != -1)
1785 {
1786 //pItem->createChild("rasd:AutomaticAllocation")->addContent( (lAutomaticAllocation) ? "true" : "false" );
1787 itemElementHelper = itemElement;
1788 pItemHelper = pItem->createChild(itemElementHelper.append("AutomaticAllocation").c_str());
1789 pItemHelper->addContent((lAutomaticAllocation) ? "true" : "false" );
1790 }
1791
1792 if (lBusNumber != -1)
1793 {
1794 if (enFormat == ovf::OVFVersion_0_9)
1795 {
1796 // BusNumber is invalid OVF 1.0 so only write it in 0.9 mode for OVFTool
1797 //pItem->createChild("rasd:BusNumber")->addContent(Utf8StrFmt("%d", lBusNumber));
1798 itemElementHelper = itemElement;
1799 pItemHelper = pItem->createChild(itemElementHelper.append("BusNumber").c_str());
1800 pItemHelper->addContent(Utf8StrFmt("%d", lBusNumber));
1801 }
1802 }
1803
1804 if (!strCaption.isEmpty())
1805 {
1806 //pItem->createChild("rasd:Caption")->addContent(strCaption);
1807 itemElementHelper = itemElement;
1808 pItemHelper = pItem->createChild(itemElementHelper.append("Caption").c_str());
1809 pItemHelper->addContent(strCaption);
1810 }
1811
1812 if (!strConnection.isEmpty())
1813 {
1814 //pItem->createChild("rasd:Connection")->addContent(strConnection);
1815 itemElementHelper = itemElement;
1816 pItemHelper = pItem->createChild(itemElementHelper.append("Connection").c_str());
1817 pItemHelper->addContent(strConnection);
1818 }
1819
1820 if (!strDescription.isEmpty())
1821 {
1822 //pItem->createChild("rasd:Description")->addContent(strDescription);
1823 itemElementHelper = itemElement;
1824 pItemHelper = pItem->createChild(itemElementHelper.append("Description").c_str());
1825 pItemHelper->addContent(strDescription);
1826 }
1827
1828 if (!strCaption.isEmpty())
1829 {
1830 if (enFormat == ovf::OVFVersion_1_0)
1831 {
1832 //pItem->createChild("rasd:ElementName")->addContent(strCaption);
1833 itemElementHelper = itemElement;
1834 pItemHelper = pItem->createChild(itemElementHelper.append("ElementName").c_str());
1835 pItemHelper->addContent(strCaption);
1836 }
1837 }
1838
1839 if (!strHostResource.isEmpty())
1840 {
1841 //pItem->createChild("rasd:HostResource")->addContent(strHostResource);
1842 itemElementHelper = itemElement;
1843 pItemHelper = pItem->createChild(itemElementHelper.append("HostResource").c_str());
1844 pItemHelper->addContent(strHostResource);
1845 }
1846
1847 {
1848 // <rasd:InstanceID>1</rasd:InstanceID>
1849 itemElementHelper = itemElement;
1850 if (enFormat == ovf::OVFVersion_0_9)
1851 //pelmInstanceID = pItem->createChild("rasd:InstanceId");
1852 pItemHelper = pItem->createChild(itemElementHelper.append("InstanceId").c_str());
1853 else
1854 //pelmInstanceID = pItem->createChild("rasd:InstanceID"); // capitalization changed...
1855 pItemHelper = pItem->createChild(itemElementHelper.append("InstanceID").c_str());
1856
1857 pItemHelper->addContent(Utf8StrFmt("%d", ulInstanceID++));
1858 }
1859
1860 if (ulParent)
1861 {
1862 //pItem->createChild("rasd:Parent")->addContent(Utf8StrFmt("%d", ulParent));
1863 itemElementHelper = itemElement;
1864 pItemHelper = pItem->createChild(itemElementHelper.append("Parent").c_str());
1865 pItemHelper->addContent(Utf8StrFmt("%d", ulParent));
1866 }
1867
1868 if (!strResourceSubType.isEmpty())
1869 {
1870 //pItem->createChild("rasd:ResourceSubType")->addContent(strResourceSubType);
1871 itemElementHelper = itemElement;
1872 pItemHelper = pItem->createChild(itemElementHelper.append("ResourceSubType").c_str());
1873 pItemHelper->addContent(strResourceSubType);
1874 }
1875
1876 {
1877 // <rasd:ResourceType>3</rasd:ResourceType>
1878 //pItem->createChild("rasd:ResourceType")->addContent(Utf8StrFmt("%d", type));
1879 itemElementHelper = itemElement;
1880 pItemHelper = pItem->createChild(itemElementHelper.append("ResourceType").c_str());
1881 pItemHelper->addContent(Utf8StrFmt("%d", type));
1882 }
1883
1884 // <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
1885 if (lVirtualQuantity != -1)
1886 {
1887 //pItem->createChild("rasd:VirtualQuantity")->addContent(Utf8StrFmt("%d", lVirtualQuantity));
1888 itemElementHelper = itemElement;
1889 pItemHelper = pItem->createChild(itemElementHelper.append("VirtualQuantity").c_str());
1890 pItemHelper->addContent(Utf8StrFmt("%d", lVirtualQuantity));
1891 }
1892 }
1893 }
1894 } // for (size_t uLoop = 1; uLoop <= 2; ++uLoop)
1895
1896 // now that we're done with the official OVF <Item> tags under <VirtualSystem>, write out VirtualBox XML
1897 // under the vbox: namespace
1898 xml::ElementNode *pelmVBoxMachine = pelmVirtualSystem->createChild("vbox:Machine");
1899 // ovf:required="false" tells other OVF parsers that they can ignore this thing
1900 pelmVBoxMachine->setAttribute("ovf:required", "false");
1901 // ovf:Info element is required or VMware will bail out on the vbox:Machine element
1902 pelmVBoxMachine->createChild("ovf:Info")->addContent("Complete VirtualBox machine configuration in VirtualBox format");
1903
1904 // create an empty machine config
1905 // use the same settings version as the current VM settings file
1906 settings::MachineConfigFile *pConfig = new settings::MachineConfigFile(&vsdescThis->m->pMachine->i_getSettingsFileFull());
1907
1908 writeLock.release();
1909 try
1910 {
1911 AutoWriteLock machineLock(vsdescThis->m->pMachine COMMA_LOCKVAL_SRC_POS);
1912 // fill the machine config
1913 vsdescThis->m->pMachine->i_copyMachineDataToSettings(*pConfig);
1914
1915 // Apply export tweaks to machine settings
1916 bool fStripAllMACs = m->optListExport.contains(ExportOptions_StripAllMACs);
1917 bool fStripAllNonNATMACs = m->optListExport.contains(ExportOptions_StripAllNonNATMACs);
1918 if (fStripAllMACs || fStripAllNonNATMACs)
1919 {
1920 for (settings::NetworkAdaptersList::iterator
1921 it = pConfig->hardwareMachine.llNetworkAdapters.begin();
1922 it != pConfig->hardwareMachine.llNetworkAdapters.end();
1923 ++it)
1924 {
1925 settings::NetworkAdapter &nic = *it;
1926 if (fStripAllMACs || (fStripAllNonNATMACs && nic.mode != NetworkAttachmentType_NAT))
1927 nic.strMACAddress.setNull();
1928 }
1929 }
1930
1931 // write the machine config to the vbox:Machine element
1932 pConfig->buildMachineXML(*pelmVBoxMachine,
1933 settings::MachineConfigFile::BuildMachineXML_WriteVBoxVersionAttribute
1934 /*| settings::MachineConfigFile::BuildMachineXML_SkipRemovableMedia*/
1935 | settings::MachineConfigFile::BuildMachineXML_SuppressSavedState,
1936 // but not BuildMachineXML_IncludeSnapshots nor BuildMachineXML_MediaRegistry
1937 pllElementsWithUuidAttributes);
1938 delete pConfig;
1939 }
1940 catch (...)
1941 {
1942 writeLock.acquire();
1943 delete pConfig;
1944 throw;
1945 }
1946 writeLock.acquire();
1947}
1948
1949/**
1950 * Actual worker code for writing out OVF/OVA to disk. This is called from Appliance::taskThreadWriteOVF()
1951 * and therefore runs on the OVF/OVA write worker thread.
1952 *
1953 * This runs in one context:
1954 *
1955 * 1) in a first worker thread; in that case, Appliance::Write() called Appliance::i_writeImpl();
1956 *
1957 * @param pTask
1958 * @return
1959 */
1960HRESULT Appliance::i_writeFS(TaskOVF *pTask)
1961{
1962 LogFlowFuncEnter();
1963 LogFlowFunc(("ENTER appliance %p\n", this));
1964
1965 AutoCaller autoCaller(this);
1966 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1967
1968 HRESULT rc = S_OK;
1969
1970 // Lock the media tree early to make sure nobody else tries to make changes
1971 // to the tree. Also lock the IAppliance object for writing.
1972 AutoMultiWriteLock2 multiLock(&mVirtualBox->i_getMediaTreeLockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
1973 // Additional protect the IAppliance object, cause we leave the lock
1974 // when starting the disk export and we don't won't block other
1975 // callers on this lengthy operations.
1976 m->state = Data::ApplianceExporting;
1977
1978 if (pTask->locInfo.strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
1979 rc = i_writeFSOVF(pTask, multiLock);
1980 else
1981 rc = i_writeFSOVA(pTask, multiLock);
1982
1983 // reset the state so others can call methods again
1984 m->state = Data::ApplianceIdle;
1985
1986 LogFlowFunc(("rc=%Rhrc\n", rc));
1987 LogFlowFuncLeave();
1988 return rc;
1989}
1990
1991HRESULT Appliance::i_writeFSOVF(TaskOVF *pTask, AutoWriteLockBase& writeLock)
1992{
1993 LogFlowFuncEnter();
1994
1995#ifdef VBOX_WITH_NEW_TAR_CREATOR
1996 HRESULT hrc = E_NOTIMPL;
1997 AssertFailed();
1998 RT_NOREF(pTask, writeLock);
1999
2000 /** @todo need a FSS creator wrapper around a directory here. */
2001
2002 LogFlowFuncLeave();
2003 return hrc;
2004
2005#else /* VBOX_WITH_NEW_TAR_CREATOR */
2006 HRESULT rc = S_OK;
2007
2008 PVDINTERFACEIO pShaIo = 0;
2009 PVDINTERFACEIO pFileIo = 0;
2010 do
2011 {
2012 pShaIo = ShaCreateInterface();
2013 if (!pShaIo)
2014 {
2015 rc = E_OUTOFMEMORY;
2016 break;
2017 }
2018 pFileIo = FileCreateInterface();
2019 if (!pFileIo)
2020 {
2021 rc = E_OUTOFMEMORY;
2022 break;
2023 }
2024
2025 SHASTORAGE storage;
2026 RT_ZERO(storage);
2027 storage.fCreateDigest = m->fManifest;
2028 storage.fSha256 = m->fSha256;
2029
2030
2031 Utf8Str name = i_applianceIOName(applianceIOFile);
2032
2033 int vrc = VDInterfaceAdd(&pFileIo->Core, name.c_str(),
2034 VDINTERFACETYPE_IO, 0, sizeof(VDINTERFACEIO),
2035 &storage.pVDImageIfaces);
2036 if (RT_FAILURE(vrc))
2037 {
2038 rc = E_FAIL;
2039 break;
2040 }
2041 rc = i_writeFSImpl(pTask, writeLock, pShaIo, &storage);
2042 } while (0);
2043
2044 /* Cleanup */
2045 if (pShaIo)
2046 RTMemFree(pShaIo);
2047 if (pFileIo)
2048 RTMemFree(pFileIo);
2049
2050 LogFlowFuncLeave();
2051 return rc;
2052#endif
2053}
2054
2055HRESULT Appliance::i_writeFSOVA(TaskOVF *pTask, AutoWriteLockBase &writeLock)
2056{
2057 LogFlowFuncEnter();
2058
2059#ifdef VBOX_WITH_NEW_TAR_CREATOR
2060 /*
2061 * Open the output file and attach a TAR creator to it.
2062 */
2063 HRESULT hrc;
2064 RTVFSIOSTREAM hVfsIosTar;
2065 int vrc = RTVfsIoStrmOpenNormal(pTask->locInfo.strPath.c_str(),
2066 RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_WRITE,
2067 &hVfsIosTar);
2068 if (RT_SUCCESS(vrc))
2069 {
2070 /** @todo which format does the standard dicate here actually?
2071 * GNU or USTAR/POSIX? */
2072 RTVFSFSSTREAM hVfsFssTar;
2073 vrc = RTZipTarFsStreamToIoStream(hVfsIosTar, RTZIPTARFORMAT_GNU, 0 /*fFlags*/, &hVfsFssTar);
2074 RTVfsIoStrmRelease(hVfsIosTar);
2075 if (RT_SUCCESS(vrc))
2076 {
2077 hrc = i_writeFSImpl(pTask, writeLock, hVfsFssTar);
2078 RTVfsFsStrmRelease(hVfsFssTar);
2079 }
2080 else
2081 hrc = setErrorVrc(vrc, tr("Failed create TAR creator for '%s' (%Rrc)"), pTask->locInfo.strPath.c_str(), vrc);
2082
2083 /* Delete the OVA on failure. */
2084 if (FAILED(hrc))
2085 RTFileDelete(pTask->locInfo.strPath.c_str());
2086 }
2087 else
2088 hrc = setErrorVrc(vrc, tr("Failed to open '%s' for writing (%Rrc)"), pTask->locInfo.strPath.c_str(), vrc);
2089
2090 LogFlowFuncLeave();
2091 return hrc;
2092
2093#else /* VBOX_WITH_NEW_TAR_CREATOR */
2094
2095 RTTAR tar;
2096 int vrc = RTTarOpen(&tar, pTask->locInfo.strPath.c_str(), RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_ALL);
2097 if (RT_FAILURE(vrc))
2098 return setError(VBOX_E_FILE_ERROR,
2099 tr("Could not create OVA file '%s' (%Rrc)"),
2100 pTask->locInfo.strPath.c_str(), vrc);
2101
2102 HRESULT rc = S_OK;
2103
2104 PVDINTERFACEIO pShaIo = 0;
2105 PVDINTERFACEIO pTarIo = 0;
2106 do
2107 {
2108 pShaIo = ShaCreateInterface();
2109 if (!pShaIo)
2110 {
2111 rc = E_OUTOFMEMORY;
2112 break;
2113 }
2114 pTarIo = tarWriterCreateInterface();
2115 if (!pTarIo)
2116 {
2117 rc = E_OUTOFMEMORY;
2118 break;
2119 }
2120 SHASTORAGE storage;
2121 RT_ZERO(storage);
2122 storage.fCreateDigest = m->fManifest;
2123 storage.fSha256 = m->fSha256;
2124
2125 Utf8Str name = i_applianceIOName(applianceIOTar);
2126
2127 vrc = VDInterfaceAdd(&pTarIo->Core, name.c_str(),
2128 VDINTERFACETYPE_IO, tar, sizeof(VDINTERFACEIO),
2129 &storage.pVDImageIfaces);
2130
2131 if (RT_FAILURE(vrc))
2132 {
2133 rc = E_FAIL;
2134 break;
2135 }
2136 rc = i_writeFSImpl(pTask, writeLock, pShaIo, &storage);
2137 } while (0);
2138
2139 RTTarClose(tar);
2140
2141 /* Cleanup */
2142 if (pShaIo)
2143 RTMemFree(pShaIo);
2144 if (pTarIo)
2145 RTMemFree(pTarIo);
2146
2147 /* Delete ova file on error */
2148 if (FAILED(rc))
2149 RTFileDelete(pTask->locInfo.strPath.c_str());
2150
2151 LogFlowFuncLeave();
2152 return rc;
2153#endif
2154}
2155
2156#ifdef VBOX_WITH_NEW_TAR_CREATOR
2157HRESULT Appliance::i_writeFSImpl(TaskOVF *pTask, AutoWriteLockBase &writeLock, RTVFSFSSTREAM hVfsFssDst)
2158#else
2159HRESULT Appliance::i_writeFSImpl(TaskOVF *pTask, AutoWriteLockBase& writeLock, PVDINTERFACEIO pIfIo, PSHASTORAGE pStorage)
2160#endif
2161{
2162 LogFlowFuncEnter();
2163
2164 HRESULT rc = S_OK;
2165#ifdef VBOX_WITH_NEW_TAR_CREATOR
2166 RTMANIFEST hManifest;
2167 int vrc = RTManifestCreate(0 /*fFlags*/, &hManifest);
2168
2169#else
2170 int vrc;
2171 list<STRPAIR> fileList;
2172#endif
2173 try
2174 {
2175 // the XML stack contains two maps for disks and networks, which allows us to
2176 // a) have a list of unique disk names (to make sure the same disk name is only added once)
2177 // and b) keep a list of all networks
2178 XMLStack stack;
2179 // Scope this to free the memory as soon as this is finished
2180 {
2181 /* Construct the OVF name. */
2182 Utf8Str strOvfFile(pTask->locInfo.strPath);
2183 strOvfFile.stripSuffix().append(".ovf");
2184
2185 /* Render a valid ovf document into a memory buffer. */
2186 xml::Document doc;
2187 i_buildXML(writeLock, doc, stack, pTask->locInfo.strPath, pTask->enFormat);
2188
2189 void *pvBuf = NULL;
2190 size_t cbSize = 0;
2191 xml::XmlMemWriter writer;
2192 writer.write(doc, &pvBuf, &cbSize);
2193 if (RT_UNLIKELY(!pvBuf))
2194 throw setError(VBOX_E_FILE_ERROR,
2195 tr("Could not create OVF file '%s'"),
2196 strOvfFile.c_str());
2197
2198 /* Write the ovf file to "disk". */
2199#ifdef VBOX_WITH_NEW_TAR_CREATOR
2200 rc = i_writeBufferToFile(hVfsFssDst, strOvfFile.c_str(), pvBuf, cbSize);
2201 if (FAILED(rc))
2202 throw rc;
2203#else
2204 vrc = writeBufferToFile(strOvfFile.c_str(), pvBuf, cbSize, pIfIo, pStorage);
2205 if (RT_FAILURE(vrc))
2206 throw setErrorVrc(vrc, tr("Could not create OVF file '%s' (%Rrc)"), strOvfFile.c_str(), vrc);
2207#endif
2208
2209#ifndef VBOX_WITH_NEW_TAR_CREATOR
2210 fileList.push_back(STRPAIR(strOvfFile, pStorage->strDigest));
2211#endif
2212 }
2213
2214 // We need a proper format description
2215 ComObjPtr<MediumFormat> formatTemp;
2216
2217 ComObjPtr<MediumFormat> format;
2218 // Scope for the AutoReadLock
2219 {
2220 SystemProperties *pSysProps = mVirtualBox->i_getSystemProperties();
2221 AutoReadLock propsLock(pSysProps COMMA_LOCKVAL_SRC_POS);
2222 // We are always exporting to VMDK stream optimized for now
2223 formatTemp = pSysProps->i_mediumFormatFromExtension("iso");
2224
2225 format = pSysProps->i_mediumFormat("VMDK");
2226 if (format.isNull())
2227 throw setError(VBOX_E_NOT_SUPPORTED,
2228 tr("Invalid medium storage format"));
2229 }
2230
2231 // Finally, write out the disks!
2232 //use the list stack.mapDiskSequence where the disks were put as the "VirtualSystem"s had been placed
2233 //in the OVF description file. I.e. we have one "VirtualSystem" in the OVF file, we extract all disks
2234 //attached to it. And these disks are stored in the stack.mapDiskSequence. Next we shift to the next
2235 //"VirtualSystem" and repeat the operation.
2236 //And here we go through the list and extract all disks in the same sequence
2237 for (list<Utf8Str>::const_iterator
2238 it = stack.mapDiskSequence.begin();
2239 it != stack.mapDiskSequence.end();
2240 ++it)
2241 {
2242 const Utf8Str &strDiskID = *it;
2243 const VirtualSystemDescriptionEntry *pDiskEntry = stack.mapDisks[strDiskID];
2244
2245 // source path: where the VBox image is
2246 const Utf8Str &strSrcFilePath = pDiskEntry->strVBoxCurrent;
2247
2248 //skip empty Medium. In common, It's may be empty CD/DVD
2249 if (strSrcFilePath.isEmpty() ||
2250 pDiskEntry->skipIt == true)
2251 continue;
2252
2253 // Do NOT check here whether the file exists. findHardDisk will
2254 // figure that out, and filesystem-based tests are simply wrong
2255 // in the general case (think of iSCSI).
2256
2257 // clone the disk:
2258 ComObjPtr<Medium> pSourceDisk;
2259
2260 Log(("Finding source disk \"%s\"\n", strSrcFilePath.c_str()));
2261
2262 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
2263 {
2264 rc = mVirtualBox->i_findHardDiskByLocation(strSrcFilePath, true, &pSourceDisk);
2265 if (FAILED(rc)) throw rc;
2266 }
2267 else//may be CD or DVD
2268 {
2269 rc = mVirtualBox->i_findDVDOrFloppyImage(DeviceType_DVD,
2270 NULL,
2271 strSrcFilePath,
2272 true,
2273 &pSourceDisk);
2274 if (FAILED(rc)) throw rc;
2275 }
2276
2277 Bstr uuidSource;
2278 rc = pSourceDisk->COMGETTER(Id)(uuidSource.asOutParam());
2279 if (FAILED(rc)) throw rc;
2280 Guid guidSource(uuidSource);
2281
2282 // output filename
2283 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
2284 // target path needs to be composed from where the output OVF is
2285 Utf8Str strTargetFilePath(pTask->locInfo.strPath);
2286 strTargetFilePath.stripFilename()
2287 .append("/")
2288 .append(strTargetFileNameOnly);
2289
2290 // The exporting requests a lock on the media tree. So leave our lock temporary.
2291 writeLock.release();
2292 try
2293 {
2294 // advance to the next operation
2295 pTask->pProgress->SetNextOperation(BstrFmt(tr("Exporting to disk image '%s'"),
2296 RTPathFilename(strTargetFilePath.c_str())).raw(),
2297 pDiskEntry->ulSizeMB); // operation's weight, as set up
2298 // with the IProgress originally
2299
2300 // create a flat copy of the source disk image
2301 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
2302 {
2303 /*
2304 * Export a disk image.
2305 */
2306 ComObjPtr<Progress> pProgress2;
2307 pProgress2.createObject();
2308 rc = pProgress2->init(mVirtualBox, static_cast<IAppliance*>(this),
2309 BstrFmt(tr("Creating medium '%s'"),
2310 strTargetFilePath.c_str()).raw(), TRUE);
2311 if (FAILED(rc)) throw rc;
2312
2313#ifdef VBOX_WITH_NEW_TAR_CREATOR
2314 /* For compressed VMDK fun, we let i_exportFile produce the image bytes. */
2315 if (true)
2316 {
2317 RTVFSIOSTREAM hVfsIosDst;
2318 vrc = RTVfsFsStrmPushFile(hVfsFssDst, strTargetFilePath.c_str(), UINT64_MAX,
2319 NULL /*paObjInfo*/, 0 /*cObjInfo*/, RTVFSFSSTRM_PUSH_F_STREAM, &hVfsIosDst);
2320 if (RT_FAILURE(vrc))
2321 throw setErrorVrc(vrc, tr("RTVfsFsStrmPushFile failed for '%s' (%Rrc)"), strTargetFilePath.c_str(), vrc);
2322 hVfsIosDst = i_manifestSetupDigestCalculationForGivenIoStream(hVfsIosDst, strTargetFilePath.c_str(),
2323 false /*fRead*/);
2324 if (hVfsIosDst == NIL_RTVFSIOSTREAM)
2325 throw setError(E_FAIL, "i_manifestSetupDigestCalculationForGivenIoStream(%s)", strTargetFilePath.c_str());
2326
2327 rc = pSourceDisk->i_exportFile(strTargetFilePath.c_str(),
2328 format,
2329 MediumVariant_VmdkStreamOptimized,
2330 m->m_pSecretKeyStore,
2331 hVfsIosDst,
2332 pProgress2);
2333 RTVfsIoStrmRelease(hVfsIosDst);
2334 if (FAILED(rc)) throw rc;
2335 }
2336 /* When creating sparse raw images, the tar creator stream pulls the data
2337 out of the disk image. It will scan for empty space first, then copy
2338 the non-empty segments into the tar stream. */
2339 else
2340 {
2341 throw E_NOTIMPL;
2342 }
2343#else
2344 rc = pSourceDisk->i_exportFile(strTargetFilePath.c_str(),
2345 format,
2346 MediumVariant_VmdkStreamOptimized,
2347 m->m_pSecretKeyStore,
2348 pIfIo,
2349 pStorage,
2350 pProgress2);
2351 if (FAILED(rc)) throw rc;
2352#endif
2353
2354 ComPtr<IProgress> pProgress3(pProgress2);
2355 // now wait for the background disk operation to complete; this throws HRESULTs on error
2356 i_waitForAsyncProgress(pTask->pProgress, pProgress3);
2357 }
2358 else
2359 {
2360 /*
2361 * Copy CD/DVD/floppy image.
2362 */
2363 Assert(pDiskEntry->type == VirtualSystemDescriptionType_CDROM);
2364
2365#ifdef VBOX_WITH_NEW_TAR_CREATOR
2366 /* Open the source image and cast it to a VFS base object. */
2367 RTVFSFILE hVfsSrcFile;
2368 vrc = RTVfsFileOpenNormal(strSrcFilePath.c_str(),
2369 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE,
2370 &hVfsSrcFile);
2371 if (RT_FAILURE(vrc))
2372 throw setErrorBoth(VBOX_E_FILE_ERROR, vrc,
2373 tr("Could not create or open file '%s' (%Rrc)"), strSrcFilePath.c_str(), vrc);
2374
2375 RTVFSOBJ hVfsSrc = RTVfsObjFromFile(hVfsSrcFile);
2376 RTVfsFileRelease(hVfsSrcFile);
2377 AssertStmt(hVfsSrc != NIL_RTVFSOBJ, throw VERR_INTERNAL_ERROR);
2378
2379 /* Add it to the output stream. This will pull in all the data from the object. */
2380 vrc = RTVfsFsStrmAdd(hVfsFssDst, strTargetFilePath.c_str(), hVfsSrc, 0 /*fFlags*/);
2381 RTVfsObjRelease(hVfsSrc);
2382 if (RT_FAILURE(vrc))
2383 throw setErrorBoth(VBOX_E_FILE_ERROR, vrc, tr("Error during copy CD/DVD image '%s' (%Rrc)"),
2384 strSrcFilePath.c_str(), vrc);
2385#else
2386 /* Read the ISO file and add one to OVA/OVF package */
2387 void *pvStorage;
2388 RTFILE pFile = NULL;
2389 void *pvUser = pStorage;
2390
2391 vrc = pIfIo->pfnOpen(pvUser, strTargetFilePath.c_str(),
2392 RTFILE_O_OPEN_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_NONE,
2393 0,
2394 &pvStorage);
2395 if (RT_FAILURE(vrc))
2396 throw setError(VBOX_E_FILE_ERROR,
2397 tr("Could not create or open file '%s' (%Rrc)"),
2398 strTargetFilePath.c_str(), vrc);
2399
2400 vrc = RTFileOpen(&pFile,
2401 strSrcFilePath.c_str(),
2402 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
2403
2404 if (RT_FAILURE(vrc) || pFile == NULL)
2405 {
2406 pIfIo->pfnClose(pvUser, pvStorage);
2407 throw setError(VBOX_E_FILE_ERROR,
2408 tr("Could not create or open file '%s' (%Rrc)"),
2409 strSrcFilePath.c_str(), vrc);
2410 }
2411
2412 uint64_t cbFile = 0;
2413 vrc = RTFileGetSize(pFile, &cbFile);
2414 if (RT_SUCCESS(vrc))
2415 {
2416 size_t const cbTmpSize = _1M;
2417 void *pvTmpBuf = RTMemAlloc(cbTmpSize);
2418 if (pvTmpBuf)
2419 {
2420 /* The copy loop. */
2421 uint64_t offDstFile = 0;
2422 for (;;)
2423 {
2424 size_t cbChunk = 0;
2425 vrc = RTFileRead(pFile, pvTmpBuf, cbTmpSize, &cbChunk);
2426 if (RT_FAILURE(vrc) || cbChunk == 0)
2427 break;
2428
2429 size_t cbWritten = 0;
2430 vrc = pIfIo->pfnWriteSync(pvUser,
2431 pvStorage,
2432 offDstFile,
2433 pvTmpBuf,
2434 cbChunk,
2435 &cbWritten);
2436 if (RT_FAILURE(vrc))
2437 break;
2438 Assert(cbWritten == cbChunk);
2439
2440 offDstFile += cbWritten;
2441 }
2442
2443 RTMemFree(pvTmpBuf);
2444 }
2445 else
2446 vrc = VERR_NO_MEMORY;
2447 }
2448
2449 pIfIo->pfnClose(pvUser, pvStorage);
2450 RTFileClose(pFile);
2451
2452 if (RT_FAILURE(vrc))
2453 {
2454 if (vrc == VERR_EOF)
2455 vrc = VINF_SUCCESS;
2456 else
2457 throw setError(VBOX_E_FILE_ERROR,
2458 tr("Error during copy CD/DVD image '%s' (%Rrc)"),
2459 strSrcFilePath.c_str(), vrc);
2460 }
2461#endif
2462 }
2463 }
2464 catch (HRESULT rc3)
2465 {
2466 writeLock.acquire();
2467 /// @todo file deletion on error? If not, we can remove that whole try/catch block.
2468 throw rc3;
2469 }
2470 // Finished, lock again (so nobody mess around with the medium tree
2471 // in the meantime)
2472 writeLock.acquire();
2473#ifndef VBOX_WITH_NEW_TAR_CREATOR
2474 fileList.push_back(STRPAIR(strTargetFilePath, pStorage->strDigest));
2475#endif
2476 }
2477
2478 if (m->fManifest)
2479 {
2480 // Create & write the manifest file
2481 Utf8Str strMfFilePath = Utf8Str(pTask->locInfo.strPath).stripSuffix().append(".mf");
2482 Utf8Str strMfFileName = Utf8Str(strMfFilePath).stripPath();
2483 pTask->pProgress->SetNextOperation(BstrFmt(tr("Creating manifest file '%s'"), strMfFileName.c_str()).raw(),
2484 m->ulWeightForManifestOperation); // operation's weight, as set up
2485 // with the IProgress originally);
2486#ifdef VBOX_WITH_NEW_TAR_CREATOR
2487 /* Create a memory I/O stream and write the manifest to it. */
2488 RTVFSIOSTREAM hVfsIosManifest;
2489 vrc = RTVfsMemIoStrmCreate(NIL_RTVFSIOSTREAM, _1K, &hVfsIosManifest);
2490 if (RT_FAILURE(vrc))
2491 throw setErrorVrc(vrc, tr("RTVfsMemIoStrmCreate failed (%Rrc)"), vrc);
2492 if (m->hOurManifest != NIL_RTMANIFEST) /* In case it's empty. */
2493 vrc = RTManifestWriteStandard(m->hOurManifest, hVfsIosManifest);
2494 if (RT_SUCCESS(vrc))
2495 {
2496 /* Rewind the stream and add it to the output. */
2497 size_t cbIgnored;
2498 vrc = RTVfsIoStrmReadAt(hVfsIosManifest, 0 /*offset*/, &cbIgnored, 0, true /*fBlocking*/, &cbIgnored);
2499 if (RT_SUCCESS(vrc))
2500 {
2501 RTVFSOBJ hVfsObjManifest = RTVfsObjFromIoStream(hVfsIosManifest);
2502 vrc = RTVfsFsStrmAdd(hVfsFssDst, strMfFilePath.c_str(), hVfsObjManifest, 0 /*fFlags*/);
2503 if (RT_SUCCESS(vrc))
2504 rc = S_OK;
2505 else
2506 rc = setErrorVrc(vrc, tr("RTVfsFsStrmAdd failed for the manifest (%Rrc)"), vrc);
2507 }
2508 else
2509 rc = setErrorVrc(vrc, tr("RTManifestWriteStandard failed (%Rrc)"), vrc);
2510 }
2511 else
2512 rc = setErrorVrc(vrc, tr("RTManifestWriteStandard failed (%Rrc)"), vrc);
2513 RTVfsIoStrmRelease(hVfsIosManifest);
2514 if (FAILED(rc))
2515 throw rc;
2516#else
2517 PRTMANIFESTTEST paManifestFiles = (PRTMANIFESTTEST)RTMemAlloc(sizeof(RTMANIFESTTEST) * fileList.size());
2518 size_t i = 0;
2519 for (list<STRPAIR>::const_iterator
2520 it = fileList.begin();
2521 it != fileList.end();
2522 ++it, ++i)
2523 {
2524 paManifestFiles[i].pszTestFile = (*it).first.c_str();
2525 paManifestFiles[i].pszTestDigest = (*it).second.c_str();
2526 }
2527 void *pvBuf;
2528 size_t cbSize;
2529 vrc = RTManifestWriteFilesBuf(&pvBuf, &cbSize, m->fSha256 ? RTDIGESTTYPE_SHA256 : RTDIGESTTYPE_SHA1,
2530 paManifestFiles, fileList.size());
2531 RTMemFree(paManifestFiles);
2532 if (RT_FAILURE(vrc))
2533 throw setError(VBOX_E_FILE_ERROR,
2534 tr("Could not create manifest file '%s' (%Rrc)"),
2535 strMfFileName.c_str(), vrc);
2536 /* Disable digest creation for the manifest file. */
2537 pStorage->fCreateDigest = false;
2538 /* Write the manifest file to disk. */
2539 vrc = writeBufferToFile(strMfFilePath.c_str(), pvBuf, cbSize, pIfIo, pStorage);
2540 RTMemFree(pvBuf);
2541 if (RT_FAILURE(vrc))
2542 throw setError(VBOX_E_FILE_ERROR,
2543 tr("Could not create manifest file '%s' (%Rrc)"),
2544 strMfFilePath.c_str(), vrc);
2545#endif
2546 }
2547 }
2548 catch (RTCError &x) // includes all XML exceptions
2549 {
2550 rc = setError(VBOX_E_FILE_ERROR,
2551 x.what());
2552 }
2553 catch (HRESULT aRC)
2554 {
2555 rc = aRC;
2556 }
2557
2558#ifndef VBOX_WITH_NEW_TAR_CREATOR /* done in caller now */
2559 /* Cleanup on error */
2560 if (FAILED(rc))
2561 {
2562 for (list<STRPAIR>::const_iterator
2563 it = fileList.begin();
2564 it != fileList.end();
2565 ++it)
2566 pIfIo->pfnDelete(pStorage, (*it).first.c_str());
2567 }
2568#endif
2569
2570 LogFlowFunc(("rc=%Rhrc\n", rc));
2571 LogFlowFuncLeave();
2572
2573 return rc;
2574}
2575
2576
2577#ifdef VBOX_WITH_NEW_TAR_CREATOR
2578/**
2579 * Writes a memory buffer to a file in the output file system stream.
2580 *
2581 * @returns COM status code.
2582 * @param hVfsFssDst The file system stream to add the file to.
2583 * @param pszFilename The file name (w/ path if desired).
2584 * @param pvContent Pointer to buffer containing the file content.
2585 * @param cbContent Size of the content.
2586 */
2587HRESULT Appliance::i_writeBufferToFile(RTVFSFSSTREAM hVfsFssDst, const char *pszFilename, const void *pvContent, size_t cbContent)
2588{
2589 /*
2590 * Create a VFS file around the memory, converting it to a base VFS object handle.
2591 */
2592 HRESULT hrc;
2593 RTVFSIOSTREAM hVfsIosSrc;
2594 int vrc = RTVfsIoStrmFromBuffer(RTFILE_O_READ, pvContent, cbContent, &hVfsIosSrc);
2595 if (RT_SUCCESS(vrc))
2596 {
2597 hVfsIosSrc = i_manifestSetupDigestCalculationForGivenIoStream(hVfsIosSrc, pszFilename);
2598 AssertReturn(hVfsIosSrc != NIL_RTVFSIOSTREAM,
2599 setErrorVrc(vrc, "i_manifestSetupDigestCalculationForGivenIoStream"));
2600
2601 RTVFSOBJ hVfsObj = RTVfsObjFromIoStream(hVfsIosSrc);
2602 RTVfsIoStrmRelease(hVfsIosSrc);
2603 AssertReturn(hVfsObj != NIL_RTVFSOBJ, E_FAIL);
2604
2605 /*
2606 * Add it to the stream.
2607 */
2608 vrc = RTVfsFsStrmAdd(hVfsFssDst, pszFilename, hVfsObj, 0);
2609 RTVfsObjRelease(hVfsObj);
2610 if (RT_SUCCESS(vrc))
2611 hrc = S_OK;
2612 else
2613 hrc = setErrorVrc(vrc, tr("RTVfsFsStrmAdd failed for '%s' (%Rrc)"), pszFilename, vrc);
2614 }
2615 else
2616 hrc = setErrorVrc(vrc, "RTVfsIoStrmFromBuffer");
2617 return hrc;
2618}
2619#endif
2620
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