VirtualBox

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

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

Main: ApplianceImplExport.cpp: Got VBOX_WITH_NEW_TAR_CREATOR mostly done and working.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 115.9 KB
Line 
1/* $Id: ApplianceImplExport.cpp 67190 2017-06-01 07:42:17Z 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.virtualbox.org. 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.virtualbox.org/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 /*
1997 * Create write-to-dir file system stream for the target directory.
1998 * This unifies the disk access with the TAR based OVA variant.
1999 */
2000 HRESULT hrc;
2001 int vrc;
2002 RTVFSFSSTREAM hVfsFss2Dir = NIL_RTVFSFSSTREAM;
2003 try
2004 {
2005 Utf8Str strTargetDir(pTask->locInfo.strPath);
2006 strTargetDir.stripFilename();
2007 vrc = RTVfsFsStrmToNormalDir(strTargetDir.c_str(), 0 /*fFlags*/, &hVfsFss2Dir);
2008 if (RT_SUCCESS(vrc))
2009 hrc = S_OK;
2010 else
2011 hrc = setErrorVrc(vrc, tr("Failed to open directory '%s' (%Rrc)"), strTargetDir.c_str(), vrc);
2012 }
2013 catch (std::bad_alloc)
2014 {
2015 hrc = E_OUTOFMEMORY;
2016 }
2017 if (SUCCEEDED(hrc))
2018 {
2019 /*
2020 * Join i_writeFSOVA. On failure, delete (undo) anything we might
2021 * have written to the disk before failing.
2022 */
2023 hrc = i_writeFSImpl(pTask, writeLock, hVfsFss2Dir);
2024 if (FAILED(hrc))
2025 RTVfsFsStrmToDirUndo(hVfsFss2Dir);
2026 RTVfsFsStrmRelease(hVfsFss2Dir);
2027 }
2028
2029 LogFlowFuncLeave();
2030 return hrc;
2031
2032#else /* VBOX_WITH_NEW_TAR_CREATOR */
2033 HRESULT rc = S_OK;
2034
2035 PVDINTERFACEIO pShaIo = 0;
2036 PVDINTERFACEIO pFileIo = 0;
2037 do
2038 {
2039 pShaIo = ShaCreateInterface();
2040 if (!pShaIo)
2041 {
2042 rc = E_OUTOFMEMORY;
2043 break;
2044 }
2045 pFileIo = FileCreateInterface();
2046 if (!pFileIo)
2047 {
2048 rc = E_OUTOFMEMORY;
2049 break;
2050 }
2051
2052 SHASTORAGE storage;
2053 RT_ZERO(storage);
2054 storage.fCreateDigest = m->fManifest;
2055 storage.fSha256 = m->fSha256;
2056
2057
2058 Utf8Str name = i_applianceIOName(applianceIOFile);
2059
2060 int vrc = VDInterfaceAdd(&pFileIo->Core, name.c_str(),
2061 VDINTERFACETYPE_IO, 0, sizeof(VDINTERFACEIO),
2062 &storage.pVDImageIfaces);
2063 if (RT_FAILURE(vrc))
2064 {
2065 rc = E_FAIL;
2066 break;
2067 }
2068 rc = i_writeFSImpl(pTask, writeLock, pShaIo, &storage);
2069 } while (0);
2070
2071 /* Cleanup */
2072 if (pShaIo)
2073 RTMemFree(pShaIo);
2074 if (pFileIo)
2075 RTMemFree(pFileIo);
2076
2077 LogFlowFuncLeave();
2078 return rc;
2079#endif
2080}
2081
2082HRESULT Appliance::i_writeFSOVA(TaskOVF *pTask, AutoWriteLockBase &writeLock)
2083{
2084 LogFlowFuncEnter();
2085
2086#ifdef VBOX_WITH_NEW_TAR_CREATOR
2087 /*
2088 * Open the output file and attach a TAR creator to it.
2089 */
2090 HRESULT hrc;
2091 RTVFSIOSTREAM hVfsIosTar;
2092 int vrc = RTVfsIoStrmOpenNormal(pTask->locInfo.strPath.c_str(),
2093 RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_WRITE,
2094 &hVfsIosTar);
2095 if (RT_SUCCESS(vrc))
2096 {
2097 /** @todo which format does the standard dictate here actually?
2098 * GNU or USTAR/POSIX? */
2099 RTVFSFSSTREAM hVfsFssTar;
2100 vrc = RTZipTarFsStreamToIoStream(hVfsIosTar, RTZIPTARFORMAT_GNU, 0 /*fFlags*/, &hVfsFssTar);
2101 RTVfsIoStrmRelease(hVfsIosTar);
2102 if (RT_SUCCESS(vrc))
2103 {
2104 hrc = i_writeFSImpl(pTask, writeLock, hVfsFssTar);
2105 RTVfsFsStrmRelease(hVfsFssTar);
2106 }
2107 else
2108 hrc = setErrorVrc(vrc, tr("Failed create TAR creator for '%s' (%Rrc)"), pTask->locInfo.strPath.c_str(), vrc);
2109
2110 /* Delete the OVA on failure. */
2111 if (FAILED(hrc))
2112 RTFileDelete(pTask->locInfo.strPath.c_str());
2113 }
2114 else
2115 hrc = setErrorVrc(vrc, tr("Failed to open '%s' for writing (%Rrc)"), pTask->locInfo.strPath.c_str(), vrc);
2116
2117 LogFlowFuncLeave();
2118 return hrc;
2119
2120#else /* VBOX_WITH_NEW_TAR_CREATOR */
2121
2122 RTTAR tar;
2123 int vrc = RTTarOpen(&tar, pTask->locInfo.strPath.c_str(), RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_ALL);
2124 if (RT_FAILURE(vrc))
2125 return setError(VBOX_E_FILE_ERROR,
2126 tr("Could not create OVA file '%s' (%Rrc)"),
2127 pTask->locInfo.strPath.c_str(), vrc);
2128
2129 HRESULT rc = S_OK;
2130
2131 PVDINTERFACEIO pShaIo = 0;
2132 PVDINTERFACEIO pTarIo = 0;
2133 do
2134 {
2135 pShaIo = ShaCreateInterface();
2136 if (!pShaIo)
2137 {
2138 rc = E_OUTOFMEMORY;
2139 break;
2140 }
2141 pTarIo = tarWriterCreateInterface();
2142 if (!pTarIo)
2143 {
2144 rc = E_OUTOFMEMORY;
2145 break;
2146 }
2147 SHASTORAGE storage;
2148 RT_ZERO(storage);
2149 storage.fCreateDigest = m->fManifest;
2150 storage.fSha256 = m->fSha256;
2151
2152 Utf8Str name = i_applianceIOName(applianceIOTar);
2153
2154 vrc = VDInterfaceAdd(&pTarIo->Core, name.c_str(),
2155 VDINTERFACETYPE_IO, tar, sizeof(VDINTERFACEIO),
2156 &storage.pVDImageIfaces);
2157
2158 if (RT_FAILURE(vrc))
2159 {
2160 rc = E_FAIL;
2161 break;
2162 }
2163 rc = i_writeFSImpl(pTask, writeLock, pShaIo, &storage);
2164 } while (0);
2165
2166 RTTarClose(tar);
2167
2168 /* Cleanup */
2169 if (pShaIo)
2170 RTMemFree(pShaIo);
2171 if (pTarIo)
2172 RTMemFree(pTarIo);
2173
2174 /* Delete ova file on error */
2175 if (FAILED(rc))
2176 RTFileDelete(pTask->locInfo.strPath.c_str());
2177
2178 LogFlowFuncLeave();
2179 return rc;
2180#endif
2181}
2182
2183#ifdef VBOX_WITH_NEW_TAR_CREATOR
2184HRESULT Appliance::i_writeFSImpl(TaskOVF *pTask, AutoWriteLockBase &writeLock, RTVFSFSSTREAM hVfsFssDst)
2185#else
2186HRESULT Appliance::i_writeFSImpl(TaskOVF *pTask, AutoWriteLockBase& writeLock, PVDINTERFACEIO pIfIo, PSHASTORAGE pStorage)
2187#endif
2188{
2189 LogFlowFuncEnter();
2190
2191 HRESULT rc = S_OK;
2192#ifdef VBOX_WITH_NEW_TAR_CREATOR
2193 RTMANIFEST hManifest;
2194 int vrc = RTManifestCreate(0 /*fFlags*/, &hManifest);
2195
2196#else
2197 int vrc;
2198 list<STRPAIR> fileList;
2199#endif
2200 try
2201 {
2202 // the XML stack contains two maps for disks and networks, which allows us to
2203 // a) have a list of unique disk names (to make sure the same disk name is only added once)
2204 // and b) keep a list of all networks
2205 XMLStack stack;
2206 // Scope this to free the memory as soon as this is finished
2207 {
2208 /* Construct the OVF name. */
2209 Utf8Str strOvfFile(pTask->locInfo.strPath);
2210#ifdef VBOX_WITH_NEW_TAR_CREATOR
2211 strOvfFile.stripPath().stripSuffix().append(".ovf");
2212#else
2213 strOvfFile.stripSuffix().append(".ovf");
2214#endif
2215
2216 /* Render a valid ovf document into a memory buffer. */
2217 xml::Document doc;
2218 i_buildXML(writeLock, doc, stack, pTask->locInfo.strPath, pTask->enFormat);
2219
2220 void *pvBuf = NULL;
2221 size_t cbSize = 0;
2222 xml::XmlMemWriter writer;
2223 writer.write(doc, &pvBuf, &cbSize);
2224 if (RT_UNLIKELY(!pvBuf))
2225 throw setError(VBOX_E_FILE_ERROR,
2226 tr("Could not create OVF file '%s'"),
2227 strOvfFile.c_str());
2228
2229 /* Write the ovf file to "disk". */
2230#ifdef VBOX_WITH_NEW_TAR_CREATOR
2231 rc = i_writeBufferToFile(hVfsFssDst, strOvfFile.c_str(), pvBuf, cbSize);
2232 if (FAILED(rc))
2233 throw rc;
2234#else
2235 vrc = writeBufferToFile(strOvfFile.c_str(), pvBuf, cbSize, pIfIo, pStorage);
2236 if (RT_FAILURE(vrc))
2237 throw setErrorVrc(vrc, tr("Could not create OVF file '%s' (%Rrc)"), strOvfFile.c_str(), vrc);
2238#endif
2239
2240#ifndef VBOX_WITH_NEW_TAR_CREATOR
2241 fileList.push_back(STRPAIR(strOvfFile, pStorage->strDigest));
2242#endif
2243 }
2244
2245 // We need a proper format description
2246 ComObjPtr<MediumFormat> formatTemp;
2247
2248 ComObjPtr<MediumFormat> format;
2249 // Scope for the AutoReadLock
2250 {
2251 SystemProperties *pSysProps = mVirtualBox->i_getSystemProperties();
2252 AutoReadLock propsLock(pSysProps COMMA_LOCKVAL_SRC_POS);
2253 // We are always exporting to VMDK stream optimized for now
2254 formatTemp = pSysProps->i_mediumFormatFromExtension("iso");
2255
2256 format = pSysProps->i_mediumFormat("VMDK");
2257 if (format.isNull())
2258 throw setError(VBOX_E_NOT_SUPPORTED,
2259 tr("Invalid medium storage format"));
2260 }
2261
2262 // Finally, write out the disks!
2263 //use the list stack.mapDiskSequence where the disks were put as the "VirtualSystem"s had been placed
2264 //in the OVF description file. I.e. we have one "VirtualSystem" in the OVF file, we extract all disks
2265 //attached to it. And these disks are stored in the stack.mapDiskSequence. Next we shift to the next
2266 //"VirtualSystem" and repeat the operation.
2267 //And here we go through the list and extract all disks in the same sequence
2268 for (list<Utf8Str>::const_iterator
2269 it = stack.mapDiskSequence.begin();
2270 it != stack.mapDiskSequence.end();
2271 ++it)
2272 {
2273 const Utf8Str &strDiskID = *it;
2274 const VirtualSystemDescriptionEntry *pDiskEntry = stack.mapDisks[strDiskID];
2275
2276 // source path: where the VBox image is
2277 const Utf8Str &strSrcFilePath = pDiskEntry->strVBoxCurrent;
2278
2279 //skip empty Medium. In common, It's may be empty CD/DVD
2280 if (strSrcFilePath.isEmpty() ||
2281 pDiskEntry->skipIt == true)
2282 continue;
2283
2284 // Do NOT check here whether the file exists. findHardDisk will
2285 // figure that out, and filesystem-based tests are simply wrong
2286 // in the general case (think of iSCSI).
2287
2288 // clone the disk:
2289 ComObjPtr<Medium> pSourceDisk;
2290
2291 Log(("Finding source disk \"%s\"\n", strSrcFilePath.c_str()));
2292
2293 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
2294 {
2295 rc = mVirtualBox->i_findHardDiskByLocation(strSrcFilePath, true, &pSourceDisk);
2296 if (FAILED(rc)) throw rc;
2297 }
2298 else//may be CD or DVD
2299 {
2300 rc = mVirtualBox->i_findDVDOrFloppyImage(DeviceType_DVD,
2301 NULL,
2302 strSrcFilePath,
2303 true,
2304 &pSourceDisk);
2305 if (FAILED(rc)) throw rc;
2306 }
2307
2308 Bstr uuidSource;
2309 rc = pSourceDisk->COMGETTER(Id)(uuidSource.asOutParam());
2310 if (FAILED(rc)) throw rc;
2311 Guid guidSource(uuidSource);
2312
2313 // output filename
2314 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
2315 // target path needs to be composed from where the output OVF is
2316#ifdef VBOX_WITH_NEW_TAR_CREATOR
2317 const Utf8Str &strTargetFilePath = strTargetFileNameOnly;
2318#else
2319 Utf8Str strTargetFilePath(pTask->locInfo.strPath);
2320 strTargetFilePath.stripFilename()
2321 .append("/")
2322 .append(strTargetFileNameOnly);
2323#endif
2324
2325 // The exporting requests a lock on the media tree. So leave our lock temporary.
2326 writeLock.release();
2327 try
2328 {
2329 // advance to the next operation
2330 pTask->pProgress->SetNextOperation(BstrFmt(tr("Exporting to disk image '%s'"),
2331 RTPathFilename(strTargetFilePath.c_str())).raw(),
2332 pDiskEntry->ulSizeMB); // operation's weight, as set up
2333 // with the IProgress originally
2334
2335 // create a flat copy of the source disk image
2336 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
2337 {
2338 /*
2339 * Export a disk image.
2340 */
2341 ComObjPtr<Progress> pProgress2;
2342 pProgress2.createObject();
2343 rc = pProgress2->init(mVirtualBox, static_cast<IAppliance*>(this),
2344 BstrFmt(tr("Creating medium '%s'"),
2345 strTargetFilePath.c_str()).raw(), TRUE);
2346 if (FAILED(rc)) throw rc;
2347
2348#ifdef VBOX_WITH_NEW_TAR_CREATOR
2349 /* For compressed VMDK fun, we let i_exportFile produce the image bytes. */
2350 if (true)
2351 {
2352 RTVFSIOSTREAM hVfsIosDst;
2353 vrc = RTVfsFsStrmPushFile(hVfsFssDst, strTargetFilePath.c_str(), UINT64_MAX,
2354 NULL /*paObjInfo*/, 0 /*cObjInfo*/, RTVFSFSSTRM_PUSH_F_STREAM, &hVfsIosDst);
2355 if (RT_FAILURE(vrc))
2356 throw setErrorVrc(vrc, tr("RTVfsFsStrmPushFile failed for '%s' (%Rrc)"), strTargetFilePath.c_str(), vrc);
2357 hVfsIosDst = i_manifestSetupDigestCalculationForGivenIoStream(hVfsIosDst, strTargetFilePath.c_str(),
2358 false /*fRead*/);
2359 if (hVfsIosDst == NIL_RTVFSIOSTREAM)
2360 throw setError(E_FAIL, "i_manifestSetupDigestCalculationForGivenIoStream(%s)", strTargetFilePath.c_str());
2361
2362 rc = pSourceDisk->i_exportFile(strTargetFilePath.c_str(),
2363 format,
2364 MediumVariant_VmdkStreamOptimized,
2365 m->m_pSecretKeyStore,
2366 hVfsIosDst,
2367 pProgress2);
2368 RTVfsIoStrmRelease(hVfsIosDst);
2369 if (FAILED(rc)) throw rc;
2370 }
2371 /* When creating sparse raw images, the tar creator stream pulls the data
2372 out of the disk image. It will scan for empty space first, then copy
2373 the non-empty segments into the tar stream. */
2374 else
2375 {
2376 throw E_NOTIMPL;
2377 }
2378#else
2379 rc = pSourceDisk->i_exportFile(strTargetFilePath.c_str(),
2380 format,
2381 MediumVariant_VmdkStreamOptimized,
2382 m->m_pSecretKeyStore,
2383 pIfIo,
2384 pStorage,
2385 pProgress2);
2386 if (FAILED(rc)) throw rc;
2387#endif
2388
2389 ComPtr<IProgress> pProgress3(pProgress2);
2390 // now wait for the background disk operation to complete; this throws HRESULTs on error
2391 i_waitForAsyncProgress(pTask->pProgress, pProgress3);
2392 }
2393 else
2394 {
2395 /*
2396 * Copy CD/DVD/floppy image.
2397 */
2398 Assert(pDiskEntry->type == VirtualSystemDescriptionType_CDROM);
2399
2400#ifdef VBOX_WITH_NEW_TAR_CREATOR
2401 /* Open the source image and cast it to a VFS base object. */
2402 RTVFSFILE hVfsSrcFile;
2403 vrc = RTVfsFileOpenNormal(strSrcFilePath.c_str(),
2404 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE,
2405 &hVfsSrcFile);
2406 if (RT_FAILURE(vrc))
2407 throw setErrorBoth(VBOX_E_FILE_ERROR, vrc,
2408 tr("Could not create or open file '%s' (%Rrc)"), strSrcFilePath.c_str(), vrc);
2409
2410 RTVFSOBJ hVfsSrc = RTVfsObjFromFile(hVfsSrcFile);
2411 RTVfsFileRelease(hVfsSrcFile);
2412 AssertStmt(hVfsSrc != NIL_RTVFSOBJ, throw VERR_INTERNAL_ERROR);
2413
2414 /* Add it to the output stream. This will pull in all the data from the object. */
2415 vrc = RTVfsFsStrmAdd(hVfsFssDst, strTargetFilePath.c_str(), hVfsSrc, 0 /*fFlags*/);
2416 RTVfsObjRelease(hVfsSrc);
2417 if (RT_FAILURE(vrc))
2418 throw setErrorBoth(VBOX_E_FILE_ERROR, vrc, tr("Error during copy CD/DVD image '%s' (%Rrc)"),
2419 strSrcFilePath.c_str(), vrc);
2420#else
2421 /* Read the ISO file and add one to OVA/OVF package */
2422 void *pvStorage;
2423 RTFILE pFile = NULL;
2424 void *pvUser = pStorage;
2425
2426 vrc = pIfIo->pfnOpen(pvUser, strTargetFilePath.c_str(),
2427 RTFILE_O_OPEN_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_NONE,
2428 0,
2429 &pvStorage);
2430 if (RT_FAILURE(vrc))
2431 throw setError(VBOX_E_FILE_ERROR,
2432 tr("Could not create or open file '%s' (%Rrc)"),
2433 strTargetFilePath.c_str(), vrc);
2434
2435 vrc = RTFileOpen(&pFile,
2436 strSrcFilePath.c_str(),
2437 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
2438
2439 if (RT_FAILURE(vrc) || pFile == NULL)
2440 {
2441 pIfIo->pfnClose(pvUser, pvStorage);
2442 throw setError(VBOX_E_FILE_ERROR,
2443 tr("Could not create or open file '%s' (%Rrc)"),
2444 strSrcFilePath.c_str(), vrc);
2445 }
2446
2447 uint64_t cbFile = 0;
2448 vrc = RTFileGetSize(pFile, &cbFile);
2449 if (RT_SUCCESS(vrc))
2450 {
2451 size_t const cbTmpSize = _1M;
2452 void *pvTmpBuf = RTMemAlloc(cbTmpSize);
2453 if (pvTmpBuf)
2454 {
2455 /* The copy loop. */
2456 uint64_t offDstFile = 0;
2457 for (;;)
2458 {
2459 size_t cbChunk = 0;
2460 vrc = RTFileRead(pFile, pvTmpBuf, cbTmpSize, &cbChunk);
2461 if (RT_FAILURE(vrc) || cbChunk == 0)
2462 break;
2463
2464 size_t cbWritten = 0;
2465 vrc = pIfIo->pfnWriteSync(pvUser,
2466 pvStorage,
2467 offDstFile,
2468 pvTmpBuf,
2469 cbChunk,
2470 &cbWritten);
2471 if (RT_FAILURE(vrc))
2472 break;
2473 Assert(cbWritten == cbChunk);
2474
2475 offDstFile += cbWritten;
2476 }
2477
2478 RTMemFree(pvTmpBuf);
2479 }
2480 else
2481 vrc = VERR_NO_MEMORY;
2482 }
2483
2484 pIfIo->pfnClose(pvUser, pvStorage);
2485 RTFileClose(pFile);
2486
2487 if (RT_FAILURE(vrc))
2488 {
2489 if (vrc == VERR_EOF)
2490 vrc = VINF_SUCCESS;
2491 else
2492 throw setError(VBOX_E_FILE_ERROR,
2493 tr("Error during copy CD/DVD image '%s' (%Rrc)"),
2494 strSrcFilePath.c_str(), vrc);
2495 }
2496#endif
2497 }
2498 }
2499 catch (HRESULT rc3)
2500 {
2501 writeLock.acquire();
2502 /// @todo file deletion on error? If not, we can remove that whole try/catch block.
2503 throw rc3;
2504 }
2505 // Finished, lock again (so nobody mess around with the medium tree
2506 // in the meantime)
2507 writeLock.acquire();
2508#ifndef VBOX_WITH_NEW_TAR_CREATOR
2509 fileList.push_back(STRPAIR(strTargetFilePath, pStorage->strDigest));
2510#endif
2511 }
2512
2513 if (m->fManifest)
2514 {
2515 // Create & write the manifest file
2516 Utf8Str strMfFilePath = Utf8Str(pTask->locInfo.strPath).stripSuffix().append(".mf");
2517 Utf8Str strMfFileName = Utf8Str(strMfFilePath).stripPath();
2518 pTask->pProgress->SetNextOperation(BstrFmt(tr("Creating manifest file '%s'"), strMfFileName.c_str()).raw(),
2519 m->ulWeightForManifestOperation); // operation's weight, as set up
2520 // with the IProgress originally);
2521#ifdef VBOX_WITH_NEW_TAR_CREATOR
2522 /* Create a memory I/O stream and write the manifest to it. */
2523 RTVFSIOSTREAM hVfsIosManifest;
2524 vrc = RTVfsMemIoStrmCreate(NIL_RTVFSIOSTREAM, _1K, &hVfsIosManifest);
2525 if (RT_FAILURE(vrc))
2526 throw setErrorVrc(vrc, tr("RTVfsMemIoStrmCreate failed (%Rrc)"), vrc);
2527 if (m->hOurManifest != NIL_RTMANIFEST) /* In case it's empty. */
2528 vrc = RTManifestWriteStandard(m->hOurManifest, hVfsIosManifest);
2529 if (RT_SUCCESS(vrc))
2530 {
2531 /* Rewind the stream and add it to the output. */
2532 size_t cbIgnored;
2533 vrc = RTVfsIoStrmReadAt(hVfsIosManifest, 0 /*offset*/, &cbIgnored, 0, true /*fBlocking*/, &cbIgnored);
2534 if (RT_SUCCESS(vrc))
2535 {
2536 RTVFSOBJ hVfsObjManifest = RTVfsObjFromIoStream(hVfsIosManifest);
2537 vrc = RTVfsFsStrmAdd(hVfsFssDst, strMfFileName.c_str(), hVfsObjManifest, 0 /*fFlags*/);
2538 if (RT_SUCCESS(vrc))
2539 rc = S_OK;
2540 else
2541 rc = setErrorVrc(vrc, tr("RTVfsFsStrmAdd failed for the manifest (%Rrc)"), vrc);
2542 }
2543 else
2544 rc = setErrorVrc(vrc, tr("RTManifestWriteStandard failed (%Rrc)"), vrc);
2545 }
2546 else
2547 rc = setErrorVrc(vrc, tr("RTManifestWriteStandard failed (%Rrc)"), vrc);
2548 RTVfsIoStrmRelease(hVfsIosManifest);
2549 if (FAILED(rc))
2550 throw rc;
2551#else
2552 PRTMANIFESTTEST paManifestFiles = (PRTMANIFESTTEST)RTMemAlloc(sizeof(RTMANIFESTTEST) * fileList.size());
2553 size_t i = 0;
2554 for (list<STRPAIR>::const_iterator
2555 it = fileList.begin();
2556 it != fileList.end();
2557 ++it, ++i)
2558 {
2559 paManifestFiles[i].pszTestFile = (*it).first.c_str();
2560 paManifestFiles[i].pszTestDigest = (*it).second.c_str();
2561 }
2562 void *pvBuf;
2563 size_t cbSize;
2564 vrc = RTManifestWriteFilesBuf(&pvBuf, &cbSize, m->fSha256 ? RTDIGESTTYPE_SHA256 : RTDIGESTTYPE_SHA1,
2565 paManifestFiles, fileList.size());
2566 RTMemFree(paManifestFiles);
2567 if (RT_FAILURE(vrc))
2568 throw setError(VBOX_E_FILE_ERROR,
2569 tr("Could not create manifest file '%s' (%Rrc)"),
2570 strMfFileName.c_str(), vrc);
2571 /* Disable digest creation for the manifest file. */
2572 pStorage->fCreateDigest = false;
2573 /* Write the manifest file to disk. */
2574 vrc = writeBufferToFile(strMfFilePath.c_str(), pvBuf, cbSize, pIfIo, pStorage);
2575 RTMemFree(pvBuf);
2576 if (RT_FAILURE(vrc))
2577 throw setError(VBOX_E_FILE_ERROR,
2578 tr("Could not create manifest file '%s' (%Rrc)"),
2579 strMfFilePath.c_str(), vrc);
2580#endif
2581 }
2582 }
2583 catch (RTCError &x) // includes all XML exceptions
2584 {
2585 rc = setError(VBOX_E_FILE_ERROR,
2586 x.what());
2587 }
2588 catch (HRESULT aRC)
2589 {
2590 rc = aRC;
2591 }
2592
2593#ifndef VBOX_WITH_NEW_TAR_CREATOR /* done in caller now */
2594 /* Cleanup on error */
2595 if (FAILED(rc))
2596 {
2597 for (list<STRPAIR>::const_iterator
2598 it = fileList.begin();
2599 it != fileList.end();
2600 ++it)
2601 pIfIo->pfnDelete(pStorage, (*it).first.c_str());
2602 }
2603#endif
2604
2605 LogFlowFunc(("rc=%Rhrc\n", rc));
2606 LogFlowFuncLeave();
2607
2608 return rc;
2609}
2610
2611
2612#ifdef VBOX_WITH_NEW_TAR_CREATOR
2613/**
2614 * Writes a memory buffer to a file in the output file system stream.
2615 *
2616 * @returns COM status code.
2617 * @param hVfsFssDst The file system stream to add the file to.
2618 * @param pszFilename The file name (w/ path if desired).
2619 * @param pvContent Pointer to buffer containing the file content.
2620 * @param cbContent Size of the content.
2621 */
2622HRESULT Appliance::i_writeBufferToFile(RTVFSFSSTREAM hVfsFssDst, const char *pszFilename, const void *pvContent, size_t cbContent)
2623{
2624 /*
2625 * Create a VFS file around the memory, converting it to a base VFS object handle.
2626 */
2627 HRESULT hrc;
2628 RTVFSIOSTREAM hVfsIosSrc;
2629 int vrc = RTVfsIoStrmFromBuffer(RTFILE_O_READ, pvContent, cbContent, &hVfsIosSrc);
2630 if (RT_SUCCESS(vrc))
2631 {
2632 hVfsIosSrc = i_manifestSetupDigestCalculationForGivenIoStream(hVfsIosSrc, pszFilename);
2633 AssertReturn(hVfsIosSrc != NIL_RTVFSIOSTREAM,
2634 setErrorVrc(vrc, "i_manifestSetupDigestCalculationForGivenIoStream"));
2635
2636 RTVFSOBJ hVfsObj = RTVfsObjFromIoStream(hVfsIosSrc);
2637 RTVfsIoStrmRelease(hVfsIosSrc);
2638 AssertReturn(hVfsObj != NIL_RTVFSOBJ, E_FAIL);
2639
2640 /*
2641 * Add it to the stream.
2642 */
2643 vrc = RTVfsFsStrmAdd(hVfsFssDst, pszFilename, hVfsObj, 0);
2644 RTVfsObjRelease(hVfsObj);
2645 if (RT_SUCCESS(vrc))
2646 hrc = S_OK;
2647 else
2648 hrc = setErrorVrc(vrc, tr("RTVfsFsStrmAdd failed for '%s' (%Rrc)"), pszFilename, vrc);
2649 }
2650 else
2651 hrc = setErrorVrc(vrc, "RTVfsIoStrmFromBuffer");
2652 return hrc;
2653}
2654#endif
2655
Note: See TracBrowser for help on using the repository browser.

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