VirtualBox

source: vbox/trunk/src/VBox/Main/xml/Settings.cpp@ 37624

最後變更 在這個檔案從37624是 37606,由 vboxsync 提交於 14 年 前

Settings: read the aborted flag

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Date Revision Author Id
檔案大小: 201.7 KB
 
1/* $Id: Settings.cpp 37606 2011-06-23 09:59:04Z vboxsync $ */
2/** @file
3 * Settings File Manipulation API.
4 *
5 * Two classes, MainConfigFile and MachineConfigFile, represent the VirtualBox.xml and
6 * machine XML files. They share a common ancestor class, ConfigFileBase, which shares
7 * functionality such as talking to the XML back-end classes and settings version management.
8 *
9 * The code can read all VirtualBox settings files version 1.3 and higher. That version was
10 * written by VirtualBox 2.0. It can write settings version 1.7 (used by VirtualBox 2.2 and
11 * 3.0) and 1.9 (used by VirtualBox 3.1) and newer ones obviously.
12 *
13 * The settings versions enum is defined in src/VBox/Main/idl/VirtualBox.xidl. To introduce
14 * a new settings version (should be necessary at most once per VirtualBox major release,
15 * if at all), add a new SettingsVersion value to that enum and grep for the previously
16 * highest value to see which code in here needs adjusting.
17 *
18 * Certainly ConfigFileBase::ConfigFileBase() will. Change VBOX_XML_VERSION below as well.
19 *
20 * Once a new settings version has been added, these are the rules for introducing a new
21 * setting: If an XML element or attribute or value is introduced that was not present in
22 * previous versions, then settings version checks need to be introduced. See the
23 * SettingsVersion enumeration in src/VBox/Main/idl/VirtualBox.xidl for details about which
24 * version was used when.
25 *
26 * The settings versions checks are necessary because since version 3.1, VirtualBox no longer
27 * automatically converts XML settings files but only if necessary, that is, if settings are
28 * present that the old format does not support. If we write an element or attribute to a
29 * settings file of an older version, then an old VirtualBox (before 3.1) will attempt to
30 * validate it with XML schema, and that will certainly fail.
31 *
32 * So, to introduce a new setting:
33 *
34 * 1) Make sure the constructor of corresponding settings structure has a proper default.
35 *
36 * 2) In the settings reader method, try to read the setting; if it's there, great, if not,
37 * the default value will have been set by the constructor. The rule is to be tolerant
38 * here.
39 *
40 * 3) In MachineConfigFile::bumpSettingsVersionIfNeeded(), check if the new setting has
41 * a non-default value (i.e. that differs from the constructor). If so, bump the
42 * settings version to the current version so the settings writer (4) can write out
43 * the non-default value properly.
44 *
45 * So far a corresponding method for MainConfigFile has not been necessary since there
46 * have been no incompatible changes yet.
47 *
48 * 4) In the settings writer method, write the setting _only_ if the current settings
49 * version (stored in m->sv) is high enough. That is, for VirtualBox 4.0, write it
50 * only if (m->sv >= SettingsVersion_v1_11).
51 */
52
53/*
54 * Copyright (C) 2007-2011 Oracle Corporation
55 *
56 * This file is part of VirtualBox Open Source Edition (OSE), as
57 * available from http://www.alldomusa.eu.org. This file is free software;
58 * you can redistribute it and/or modify it under the terms of the GNU
59 * General Public License (GPL) as published by the Free Software
60 * Foundation, in version 2 as it comes in the "COPYING" file of the
61 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
62 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
63 */
64
65#include "VBox/com/string.h"
66#include "VBox/settings.h"
67#include <iprt/cpp/xml.h>
68#include <iprt/stream.h>
69#include <iprt/ctype.h>
70#include <iprt/file.h>
71#include <iprt/process.h>
72#include <iprt/ldr.h>
73#include <iprt/cpp/lock.h>
74
75// generated header
76#include "SchemaDefs.h"
77
78#include "Logging.h"
79
80using namespace com;
81using namespace settings;
82
83////////////////////////////////////////////////////////////////////////////////
84//
85// Defines
86//
87////////////////////////////////////////////////////////////////////////////////
88
89/** VirtualBox XML settings namespace */
90#define VBOX_XML_NAMESPACE "http://www.innotek.de/VirtualBox-settings"
91
92/** VirtualBox XML settings version number substring ("x.y") */
93#define VBOX_XML_VERSION "1.12"
94
95/** VirtualBox XML settings version platform substring */
96#if defined (RT_OS_DARWIN)
97# define VBOX_XML_PLATFORM "macosx"
98#elif defined (RT_OS_FREEBSD)
99# define VBOX_XML_PLATFORM "freebsd"
100#elif defined (RT_OS_LINUX)
101# define VBOX_XML_PLATFORM "linux"
102#elif defined (RT_OS_NETBSD)
103# define VBOX_XML_PLATFORM "netbsd"
104#elif defined (RT_OS_OPENBSD)
105# define VBOX_XML_PLATFORM "openbsd"
106#elif defined (RT_OS_OS2)
107# define VBOX_XML_PLATFORM "os2"
108#elif defined (RT_OS_SOLARIS)
109# define VBOX_XML_PLATFORM "solaris"
110#elif defined (RT_OS_WINDOWS)
111# define VBOX_XML_PLATFORM "windows"
112#else
113# error Unsupported platform!
114#endif
115
116/** VirtualBox XML settings full version string ("x.y-platform") */
117#define VBOX_XML_VERSION_FULL VBOX_XML_VERSION "-" VBOX_XML_PLATFORM
118
119////////////////////////////////////////////////////////////////////////////////
120//
121// Internal data
122//
123////////////////////////////////////////////////////////////////////////////////
124
125/**
126 * Opaque data structore for ConfigFileBase (only declared
127 * in header, defined only here).
128 */
129
130struct ConfigFileBase::Data
131{
132 Data()
133 : pDoc(NULL),
134 pelmRoot(NULL),
135 sv(SettingsVersion_Null),
136 svRead(SettingsVersion_Null)
137 {}
138
139 ~Data()
140 {
141 cleanup();
142 }
143
144 RTCString strFilename;
145 bool fFileExists;
146
147 xml::Document *pDoc;
148 xml::ElementNode *pelmRoot;
149
150 com::Utf8Str strSettingsVersionFull; // e.g. "1.7-linux"
151 SettingsVersion_T sv; // e.g. SettingsVersion_v1_7
152
153 SettingsVersion_T svRead; // settings version that the original file had when it was read,
154 // or SettingsVersion_Null if none
155
156 void copyFrom(const Data &d)
157 {
158 strFilename = d.strFilename;
159 fFileExists = d.fFileExists;
160 strSettingsVersionFull = d.strSettingsVersionFull;
161 sv = d.sv;
162 svRead = d.svRead;
163 }
164
165 void cleanup()
166 {
167 if (pDoc)
168 {
169 delete pDoc;
170 pDoc = NULL;
171 pelmRoot = NULL;
172 }
173 }
174};
175
176/**
177 * Private exception class (not in the header file) that makes
178 * throwing xml::LogicError instances easier. That class is public
179 * and should be caught by client code.
180 */
181class settings::ConfigFileError : public xml::LogicError
182{
183public:
184 ConfigFileError(const ConfigFileBase *file,
185 const xml::Node *pNode,
186 const char *pcszFormat, ...)
187 : xml::LogicError()
188 {
189 va_list args;
190 va_start(args, pcszFormat);
191 Utf8Str strWhat(pcszFormat, args);
192 va_end(args);
193
194 Utf8Str strLine;
195 if (pNode)
196 strLine = Utf8StrFmt(" (line %RU32)", pNode->getLineNumber());
197
198 const char *pcsz = strLine.c_str();
199 Utf8StrFmt str(N_("Error in %s%s -- %s"),
200 file->m->strFilename.c_str(),
201 (pcsz) ? pcsz : "",
202 strWhat.c_str());
203
204 setWhat(str.c_str());
205 }
206};
207
208////////////////////////////////////////////////////////////////////////////////
209//
210// MediaRegistry
211//
212////////////////////////////////////////////////////////////////////////////////
213
214bool Medium::operator==(const Medium &m) const
215{
216 return (uuid == m.uuid)
217 && (strLocation == m.strLocation)
218 && (strDescription == m.strDescription)
219 && (strFormat == m.strFormat)
220 && (fAutoReset == m.fAutoReset)
221 && (properties == m.properties)
222 && (hdType == m.hdType)
223 && (llChildren== m.llChildren); // this is deep and recurses
224}
225
226bool MediaRegistry::operator==(const MediaRegistry &m) const
227{
228 return llHardDisks == m.llHardDisks
229 && llDvdImages == m.llDvdImages
230 && llFloppyImages == m.llFloppyImages;
231}
232
233////////////////////////////////////////////////////////////////////////////////
234//
235// ConfigFileBase
236//
237////////////////////////////////////////////////////////////////////////////////
238
239/**
240 * Constructor. Allocates the XML internals, parses the XML file if
241 * pstrFilename is != NULL and reads the settings version from it.
242 * @param strFilename
243 */
244ConfigFileBase::ConfigFileBase(const com::Utf8Str *pstrFilename)
245 : m(new Data)
246{
247 Utf8Str strMajor;
248 Utf8Str strMinor;
249
250 m->fFileExists = false;
251
252 if (pstrFilename)
253 {
254 // reading existing settings file:
255 m->strFilename = *pstrFilename;
256
257 xml::XmlFileParser parser;
258 m->pDoc = new xml::Document;
259 parser.read(*pstrFilename,
260 *m->pDoc);
261
262 m->fFileExists = true;
263
264 m->pelmRoot = m->pDoc->getRootElement();
265 if (!m->pelmRoot || !m->pelmRoot->nameEquals("VirtualBox"))
266 throw ConfigFileError(this, NULL, N_("Root element in VirtualBox settings files must be \"VirtualBox\"."));
267
268 if (!(m->pelmRoot->getAttributeValue("version", m->strSettingsVersionFull)))
269 throw ConfigFileError(this, m->pelmRoot, N_("Required VirtualBox/@version attribute is missing"));
270
271 LogRel(("Loading settings file \"%s\" with version \"%s\"\n", m->strFilename.c_str(), m->strSettingsVersionFull.c_str()));
272
273 // parse settings version; allow future versions but fail if file is older than 1.6
274 m->sv = SettingsVersion_Null;
275 if (m->strSettingsVersionFull.length() > 3)
276 {
277 const char *pcsz = m->strSettingsVersionFull.c_str();
278 char c;
279
280 while ( (c = *pcsz)
281 && RT_C_IS_DIGIT(c)
282 )
283 {
284 strMajor.append(c);
285 ++pcsz;
286 }
287
288 if (*pcsz++ == '.')
289 {
290 while ( (c = *pcsz)
291 && RT_C_IS_DIGIT(c)
292 )
293 {
294 strMinor.append(c);
295 ++pcsz;
296 }
297 }
298
299 uint32_t ulMajor = RTStrToUInt32(strMajor.c_str());
300 uint32_t ulMinor = RTStrToUInt32(strMinor.c_str());
301
302 if (ulMajor == 1)
303 {
304 if (ulMinor == 3)
305 m->sv = SettingsVersion_v1_3;
306 else if (ulMinor == 4)
307 m->sv = SettingsVersion_v1_4;
308 else if (ulMinor == 5)
309 m->sv = SettingsVersion_v1_5;
310 else if (ulMinor == 6)
311 m->sv = SettingsVersion_v1_6;
312 else if (ulMinor == 7)
313 m->sv = SettingsVersion_v1_7;
314 else if (ulMinor == 8)
315 m->sv = SettingsVersion_v1_8;
316 else if (ulMinor == 9)
317 m->sv = SettingsVersion_v1_9;
318 else if (ulMinor == 10)
319 m->sv = SettingsVersion_v1_10;
320 else if (ulMinor == 11)
321 m->sv = SettingsVersion_v1_11;
322 else if (ulMinor == 12)
323 m->sv = SettingsVersion_v1_12;
324 else if (ulMinor > 12)
325 m->sv = SettingsVersion_Future;
326 }
327 else if (ulMajor > 1)
328 m->sv = SettingsVersion_Future;
329
330 LogRel(("Parsed settings version %d.%d to enum value %d\n", ulMajor, ulMinor, m->sv));
331 }
332
333 if (m->sv == SettingsVersion_Null)
334 throw ConfigFileError(this, m->pelmRoot, N_("Cannot handle settings version '%s'"), m->strSettingsVersionFull.c_str());
335
336 // remember the settings version we read in case it gets upgraded later,
337 // so we know when to make backups
338 m->svRead = m->sv;
339 }
340 else
341 {
342 // creating new settings file:
343 m->strSettingsVersionFull = VBOX_XML_VERSION_FULL;
344 m->sv = SettingsVersion_v1_12;
345 }
346}
347
348ConfigFileBase::ConfigFileBase(const ConfigFileBase &other)
349 : m(new Data)
350{
351 copyBaseFrom(other);
352 m->strFilename = "";
353 m->fFileExists = false;
354}
355
356/**
357 * Clean up.
358 */
359ConfigFileBase::~ConfigFileBase()
360{
361 if (m)
362 {
363 delete m;
364 m = NULL;
365 }
366}
367
368/**
369 * Helper function that parses a UUID in string form into
370 * a com::Guid item. Accepts UUIDs both with and without
371 * "{}" brackets. Throws on errors.
372 * @param guid
373 * @param strUUID
374 */
375void ConfigFileBase::parseUUID(Guid &guid,
376 const Utf8Str &strUUID) const
377{
378 guid = strUUID.c_str();
379 if (guid.isEmpty())
380 throw ConfigFileError(this, NULL, N_("UUID \"%s\" has invalid format"), strUUID.c_str());
381}
382
383/**
384 * Parses the given string in str and attempts to treat it as an ISO
385 * date/time stamp to put into timestamp. Throws on errors.
386 * @param timestamp
387 * @param str
388 */
389void ConfigFileBase::parseTimestamp(RTTIMESPEC &timestamp,
390 const com::Utf8Str &str) const
391{
392 const char *pcsz = str.c_str();
393 // yyyy-mm-ddThh:mm:ss
394 // "2009-07-10T11:54:03Z"
395 // 01234567890123456789
396 // 1
397 if (str.length() > 19)
398 {
399 // timezone must either be unspecified or 'Z' for UTC
400 if ( (pcsz[19])
401 && (pcsz[19] != 'Z')
402 )
403 throw ConfigFileError(this, NULL, N_("Cannot handle ISO timestamp '%s': is not UTC date"), str.c_str());
404
405 int32_t yyyy;
406 uint32_t mm, dd, hh, min, secs;
407 if ( (pcsz[4] == '-')
408 && (pcsz[7] == '-')
409 && (pcsz[10] == 'T')
410 && (pcsz[13] == ':')
411 && (pcsz[16] == ':')
412 )
413 {
414 int rc;
415 if ( (RT_SUCCESS(rc = RTStrToInt32Ex(pcsz, NULL, 0, &yyyy)))
416 // could theoretically be negative but let's assume that nobody
417 // created virtual machines before the Christian era
418 && (RT_SUCCESS(rc = RTStrToUInt32Ex(pcsz + 5, NULL, 0, &mm)))
419 && (RT_SUCCESS(rc = RTStrToUInt32Ex(pcsz + 8, NULL, 0, &dd)))
420 && (RT_SUCCESS(rc = RTStrToUInt32Ex(pcsz + 11, NULL, 0, &hh)))
421 && (RT_SUCCESS(rc = RTStrToUInt32Ex(pcsz + 14, NULL, 0, &min)))
422 && (RT_SUCCESS(rc = RTStrToUInt32Ex(pcsz + 17, NULL, 0, &secs)))
423 )
424 {
425 RTTIME time =
426 {
427 yyyy,
428 (uint8_t)mm,
429 0,
430 0,
431 (uint8_t)dd,
432 (uint8_t)hh,
433 (uint8_t)min,
434 (uint8_t)secs,
435 0,
436 RTTIME_FLAGS_TYPE_UTC,
437 0
438 };
439 if (RTTimeNormalize(&time))
440 if (RTTimeImplode(&timestamp, &time))
441 return;
442 }
443
444 throw ConfigFileError(this, NULL, N_("Cannot parse ISO timestamp '%s': runtime error, %Rra"), str.c_str(), rc);
445 }
446
447 throw ConfigFileError(this, NULL, N_("Cannot parse ISO timestamp '%s': invalid format"), str.c_str());
448 }
449}
450
451/**
452 * Helper to create a string for a RTTIMESPEC for writing out ISO timestamps.
453 * @param stamp
454 * @return
455 */
456com::Utf8Str ConfigFileBase::makeString(const RTTIMESPEC &stamp)
457{
458 RTTIME time;
459 if (!RTTimeExplode(&time, &stamp))
460 throw ConfigFileError(this, NULL, N_("Timespec %lld ms is invalid"), RTTimeSpecGetMilli(&stamp));
461
462 return Utf8StrFmt("%04u-%02u-%02uT%02u:%02u:%02uZ",
463 time.i32Year, time.u8Month, time.u8MonthDay,
464 time.u8Hour, time.u8Minute, time.u8Second);
465}
466
467/**
468 * Helper method to read in an ExtraData subtree and stores its contents
469 * in the given map of extradata items. Used for both main and machine
470 * extradata (MainConfigFile and MachineConfigFile).
471 * @param elmExtraData
472 * @param map
473 */
474void ConfigFileBase::readExtraData(const xml::ElementNode &elmExtraData,
475 StringsMap &map)
476{
477 xml::NodesLoop nlLevel4(elmExtraData);
478 const xml::ElementNode *pelmExtraDataItem;
479 while ((pelmExtraDataItem = nlLevel4.forAllNodes()))
480 {
481 if (pelmExtraDataItem->nameEquals("ExtraDataItem"))
482 {
483 // <ExtraDataItem name="GUI/LastWindowPostion" value="97,88,981,858"/>
484 Utf8Str strName, strValue;
485 if ( ((pelmExtraDataItem->getAttributeValue("name", strName)))
486 && ((pelmExtraDataItem->getAttributeValue("value", strValue)))
487 )
488 map[strName] = strValue;
489 else
490 throw ConfigFileError(this, pelmExtraDataItem, N_("Required ExtraDataItem/@name or @value attribute is missing"));
491 }
492 }
493}
494
495/**
496 * Reads <USBDeviceFilter> entries from under the given elmDeviceFilters node and
497 * stores them in the given linklist. This is in ConfigFileBase because it's used
498 * from both MainConfigFile (for host filters) and MachineConfigFile (for machine
499 * filters).
500 * @param elmDeviceFilters
501 * @param ll
502 */
503void ConfigFileBase::readUSBDeviceFilters(const xml::ElementNode &elmDeviceFilters,
504 USBDeviceFiltersList &ll)
505{
506 xml::NodesLoop nl1(elmDeviceFilters, "DeviceFilter");
507 const xml::ElementNode *pelmLevel4Child;
508 while ((pelmLevel4Child = nl1.forAllNodes()))
509 {
510 USBDeviceFilter flt;
511 flt.action = USBDeviceFilterAction_Ignore;
512 Utf8Str strAction;
513 if ( (pelmLevel4Child->getAttributeValue("name", flt.strName))
514 && (pelmLevel4Child->getAttributeValue("active", flt.fActive))
515 )
516 {
517 if (!pelmLevel4Child->getAttributeValue("vendorId", flt.strVendorId))
518 pelmLevel4Child->getAttributeValue("vendorid", flt.strVendorId); // used before 1.3
519 if (!pelmLevel4Child->getAttributeValue("productId", flt.strProductId))
520 pelmLevel4Child->getAttributeValue("productid", flt.strProductId); // used before 1.3
521 pelmLevel4Child->getAttributeValue("revision", flt.strRevision);
522 pelmLevel4Child->getAttributeValue("manufacturer", flt.strManufacturer);
523 pelmLevel4Child->getAttributeValue("product", flt.strProduct);
524 if (!pelmLevel4Child->getAttributeValue("serialNumber", flt.strSerialNumber))
525 pelmLevel4Child->getAttributeValue("serialnumber", flt.strSerialNumber); // used before 1.3
526 pelmLevel4Child->getAttributeValue("port", flt.strPort);
527
528 // the next 2 are irrelevant for host USB objects
529 pelmLevel4Child->getAttributeValue("remote", flt.strRemote);
530 pelmLevel4Child->getAttributeValue("maskedInterfaces", flt.ulMaskedInterfaces);
531
532 // action is only used with host USB objects
533 if (pelmLevel4Child->getAttributeValue("action", strAction))
534 {
535 if (strAction == "Ignore")
536 flt.action = USBDeviceFilterAction_Ignore;
537 else if (strAction == "Hold")
538 flt.action = USBDeviceFilterAction_Hold;
539 else
540 throw ConfigFileError(this, pelmLevel4Child, N_("Invalid value '%s' in DeviceFilter/@action attribute"), strAction.c_str());
541 }
542
543 ll.push_back(flt);
544 }
545 }
546}
547
548/**
549 * Reads a media registry entry from the main VirtualBox.xml file.
550 *
551 * Whereas the current media registry code is fairly straightforward, it was quite a mess
552 * with settings format before 1.4 (VirtualBox 2.0 used settings format 1.3). The elements
553 * in the media registry were much more inconsistent, and different elements were used
554 * depending on the type of device and image.
555 *
556 * @param t
557 * @param elmMedium
558 * @param llMedia
559 */
560void ConfigFileBase::readMedium(MediaType t,
561 const xml::ElementNode &elmMedium, // HardDisk node if root; if recursing,
562 // child HardDisk node or DiffHardDisk node for pre-1.4
563 MediaList &llMedia) // list to append medium to (root disk or child list)
564{
565 // <HardDisk uuid="{5471ecdb-1ddb-4012-a801-6d98e226868b}" location="/mnt/innotek-unix/vdis/Windows XP.vdi" format="VDI" type="Normal">
566 settings::Medium med;
567 Utf8Str strUUID;
568 if (!(elmMedium.getAttributeValue("uuid", strUUID)))
569 throw ConfigFileError(this, &elmMedium, N_("Required %s/@uuid attribute is missing"), elmMedium.getName());
570
571 parseUUID(med.uuid, strUUID);
572
573 bool fNeedsLocation = true;
574
575 if (t == HardDisk)
576 {
577 if (m->sv < SettingsVersion_v1_4)
578 {
579 // here the system is:
580 // <HardDisk uuid="{....}" type="normal">
581 // <VirtualDiskImage filePath="/path/to/xxx.vdi"/>
582 // </HardDisk>
583
584 fNeedsLocation = false;
585 bool fNeedsFilePath = true;
586 const xml::ElementNode *pelmImage;
587 if ((pelmImage = elmMedium.findChildElement("VirtualDiskImage")))
588 med.strFormat = "VDI";
589 else if ((pelmImage = elmMedium.findChildElement("VMDKImage")))
590 med.strFormat = "VMDK";
591 else if ((pelmImage = elmMedium.findChildElement("VHDImage")))
592 med.strFormat = "VHD";
593 else if ((pelmImage = elmMedium.findChildElement("ISCSIHardDisk")))
594 {
595 med.strFormat = "iSCSI";
596
597 fNeedsFilePath = false;
598 // location is special here: current settings specify an "iscsi://user@server:port/target/lun"
599 // string for the location and also have several disk properties for these, whereas this used
600 // to be hidden in several sub-elements before 1.4, so compose a location string and set up
601 // the properties:
602 med.strLocation = "iscsi://";
603 Utf8Str strUser, strServer, strPort, strTarget, strLun;
604 if (pelmImage->getAttributeValue("userName", strUser))
605 {
606 med.strLocation.append(strUser);
607 med.strLocation.append("@");
608 }
609 Utf8Str strServerAndPort;
610 if (pelmImage->getAttributeValue("server", strServer))
611 {
612 strServerAndPort = strServer;
613 }
614 if (pelmImage->getAttributeValue("port", strPort))
615 {
616 if (strServerAndPort.length())
617 strServerAndPort.append(":");
618 strServerAndPort.append(strPort);
619 }
620 med.strLocation.append(strServerAndPort);
621 if (pelmImage->getAttributeValue("target", strTarget))
622 {
623 med.strLocation.append("/");
624 med.strLocation.append(strTarget);
625 }
626 if (pelmImage->getAttributeValue("lun", strLun))
627 {
628 med.strLocation.append("/");
629 med.strLocation.append(strLun);
630 }
631
632 if (strServer.length() && strPort.length())
633 med.properties["TargetAddress"] = strServerAndPort;
634 if (strTarget.length())
635 med.properties["TargetName"] = strTarget;
636 if (strUser.length())
637 med.properties["InitiatorUsername"] = strUser;
638 Utf8Str strPassword;
639 if (pelmImage->getAttributeValue("password", strPassword))
640 med.properties["InitiatorSecret"] = strPassword;
641 if (strLun.length())
642 med.properties["LUN"] = strLun;
643 }
644 else if ((pelmImage = elmMedium.findChildElement("CustomHardDisk")))
645 {
646 fNeedsFilePath = false;
647 fNeedsLocation = true;
648 // also requires @format attribute, which will be queried below
649 }
650 else
651 throw ConfigFileError(this, &elmMedium, N_("Required %s/VirtualDiskImage element is missing"), elmMedium.getName());
652
653 if (fNeedsFilePath)
654 {
655 if (!(pelmImage->getAttributeValuePath("filePath", med.strLocation)))
656 throw ConfigFileError(this, &elmMedium, N_("Required %s/@filePath attribute is missing"), elmMedium.getName());
657 }
658 }
659
660 if (med.strFormat.isEmpty()) // not set with 1.4 format above, or 1.4 Custom format?
661 if (!(elmMedium.getAttributeValue("format", med.strFormat)))
662 throw ConfigFileError(this, &elmMedium, N_("Required %s/@format attribute is missing"), elmMedium.getName());
663
664 if (!(elmMedium.getAttributeValue("autoReset", med.fAutoReset)))
665 med.fAutoReset = false;
666
667 Utf8Str strType;
668 if ((elmMedium.getAttributeValue("type", strType)))
669 {
670 // pre-1.4 used lower case, so make this case-insensitive
671 strType.toUpper();
672 if (strType == "NORMAL")
673 med.hdType = MediumType_Normal;
674 else if (strType == "IMMUTABLE")
675 med.hdType = MediumType_Immutable;
676 else if (strType == "WRITETHROUGH")
677 med.hdType = MediumType_Writethrough;
678 else if (strType == "SHAREABLE")
679 med.hdType = MediumType_Shareable;
680 else if (strType == "READONLY")
681 med.hdType = MediumType_Readonly;
682 else if (strType == "MULTIATTACH")
683 med.hdType = MediumType_MultiAttach;
684 else
685 throw ConfigFileError(this, &elmMedium, N_("HardDisk/@type attribute must be one of Normal, Immutable, Writethrough, Shareable, Readonly or MultiAttach"));
686 }
687 }
688 else
689 {
690 if (m->sv < SettingsVersion_v1_4)
691 {
692 // DVD and floppy images before 1.4 had "src" attribute instead of "location"
693 if (!(elmMedium.getAttributeValue("src", med.strLocation)))
694 throw ConfigFileError(this, &elmMedium, N_("Required %s/@src attribute is missing"), elmMedium.getName());
695
696 fNeedsLocation = false;
697 }
698
699 if (!(elmMedium.getAttributeValue("format", med.strFormat)))
700 {
701 // DVD and floppy images before 1.11 had no format attribute. assign the default.
702 med.strFormat = "RAW";
703 }
704
705 if (t == DVDImage)
706 med.hdType = MediumType_Readonly;
707 else if (t == FloppyImage)
708 med.hdType = MediumType_Writethrough;
709 }
710
711 if (fNeedsLocation)
712 // current files and 1.4 CustomHardDisk elements must have a location attribute
713 if (!(elmMedium.getAttributeValue("location", med.strLocation)))
714 throw ConfigFileError(this, &elmMedium, N_("Required %s/@location attribute is missing"), elmMedium.getName());
715
716 elmMedium.getAttributeValue("Description", med.strDescription); // optional
717
718 // recurse to handle children
719 xml::NodesLoop nl2(elmMedium);
720 const xml::ElementNode *pelmHDChild;
721 while ((pelmHDChild = nl2.forAllNodes()))
722 {
723 if ( t == HardDisk
724 && ( pelmHDChild->nameEquals("HardDisk")
725 || ( (m->sv < SettingsVersion_v1_4)
726 && (pelmHDChild->nameEquals("DiffHardDisk"))
727 )
728 )
729 )
730 // recurse with this element and push the child onto our current children list
731 readMedium(t,
732 *pelmHDChild,
733 med.llChildren);
734 else if (pelmHDChild->nameEquals("Property"))
735 {
736 Utf8Str strPropName, strPropValue;
737 if ( (pelmHDChild->getAttributeValue("name", strPropName))
738 && (pelmHDChild->getAttributeValue("value", strPropValue))
739 )
740 med.properties[strPropName] = strPropValue;
741 else
742 throw ConfigFileError(this, pelmHDChild, N_("Required HardDisk/Property/@name or @value attribute is missing"));
743 }
744 }
745
746 llMedia.push_back(med);
747}
748
749/**
750 * Reads in the entire <MediaRegistry> chunk and stores its media in the lists
751 * of the given MediaRegistry structure.
752 *
753 * This is used in both MainConfigFile and MachineConfigFile since starting with
754 * VirtualBox 4.0, we can have media registries in both.
755 *
756 * For pre-1.4 files, this gets called with the <DiskRegistry> chunk instead.
757 *
758 * @param elmMediaRegistry
759 */
760void ConfigFileBase::readMediaRegistry(const xml::ElementNode &elmMediaRegistry,
761 MediaRegistry &mr)
762{
763 xml::NodesLoop nl1(elmMediaRegistry);
764 const xml::ElementNode *pelmChild1;
765 while ((pelmChild1 = nl1.forAllNodes()))
766 {
767 MediaType t = Error;
768 if (pelmChild1->nameEquals("HardDisks"))
769 t = HardDisk;
770 else if (pelmChild1->nameEquals("DVDImages"))
771 t = DVDImage;
772 else if (pelmChild1->nameEquals("FloppyImages"))
773 t = FloppyImage;
774 else
775 continue;
776
777 xml::NodesLoop nl2(*pelmChild1);
778 const xml::ElementNode *pelmMedium;
779 while ((pelmMedium = nl2.forAllNodes()))
780 {
781 if ( t == HardDisk
782 && (pelmMedium->nameEquals("HardDisk"))
783 )
784 readMedium(t,
785 *pelmMedium,
786 mr.llHardDisks); // list to append hard disk data to: the root list
787 else if ( t == DVDImage
788 && (pelmMedium->nameEquals("Image"))
789 )
790 readMedium(t,
791 *pelmMedium,
792 mr.llDvdImages); // list to append dvd images to: the root list
793 else if ( t == FloppyImage
794 && (pelmMedium->nameEquals("Image"))
795 )
796 readMedium(t,
797 *pelmMedium,
798 mr.llFloppyImages); // list to append floppy images to: the root list
799 }
800 }
801}
802
803/**
804 * Adds a "version" attribute to the given XML element with the
805 * VirtualBox settings version (e.g. "1.10-linux"). Used by
806 * the XML format for the root element and by the OVF export
807 * for the vbox:Machine element.
808 * @param elm
809 */
810void ConfigFileBase::setVersionAttribute(xml::ElementNode &elm)
811{
812 const char *pcszVersion = NULL;
813 switch (m->sv)
814 {
815 case SettingsVersion_v1_8:
816 pcszVersion = "1.8";
817 break;
818
819 case SettingsVersion_v1_9:
820 pcszVersion = "1.9";
821 break;
822
823 case SettingsVersion_v1_10:
824 pcszVersion = "1.10";
825 break;
826
827 case SettingsVersion_v1_11:
828 pcszVersion = "1.11";
829 break;
830
831 case SettingsVersion_v1_12:
832 pcszVersion = "1.12";
833 break;
834
835 case SettingsVersion_Future:
836 // can be set if this code runs on XML files that were created by a future version of VBox;
837 // in that case, downgrade to current version when writing since we can't write future versions...
838 pcszVersion = "1.12";
839 m->sv = SettingsVersion_v1_12;
840 break;
841
842 default:
843 // silently upgrade if this is less than 1.7 because that's the oldest we can write
844 pcszVersion = "1.7";
845 m->sv = SettingsVersion_v1_7;
846 break;
847 }
848
849 elm.setAttribute("version", Utf8StrFmt("%s-%s",
850 pcszVersion,
851 VBOX_XML_PLATFORM)); // e.g. "linux"
852}
853
854/**
855 * Creates a new stub xml::Document in the m->pDoc member with the
856 * root "VirtualBox" element set up. This is used by both
857 * MainConfigFile and MachineConfigFile at the beginning of writing
858 * out their XML.
859 *
860 * Before calling this, it is the responsibility of the caller to
861 * set the "sv" member to the required settings version that is to
862 * be written. For newly created files, the settings version will be
863 * the latest (1.12); for files read in from disk earlier, it will be
864 * the settings version indicated in the file. However, this method
865 * will silently make sure that the settings version is always
866 * at least 1.7 and change it if necessary, since there is no write
867 * support for earlier settings versions.
868 */
869void ConfigFileBase::createStubDocument()
870{
871 Assert(m->pDoc == NULL);
872 m->pDoc = new xml::Document;
873
874 m->pelmRoot = m->pDoc->createRootElement("VirtualBox",
875 "\n"
876 "** DO NOT EDIT THIS FILE.\n"
877 "** If you make changes to this file while any VirtualBox related application\n"
878 "** is running, your changes will be overwritten later, without taking effect.\n"
879 "** Use VBoxManage or the VirtualBox Manager GUI to make changes.\n"
880);
881 m->pelmRoot->setAttribute("xmlns", VBOX_XML_NAMESPACE);
882
883 // add settings version attribute to root element
884 setVersionAttribute(*m->pelmRoot);
885
886 // since this gets called before the XML document is actually written out,
887 // this is where we must check whether we're upgrading the settings version
888 // and need to make a backup, so the user can go back to an earlier
889 // VirtualBox version and recover his old settings files.
890 if ( (m->svRead != SettingsVersion_Null) // old file exists?
891 && (m->svRead < m->sv) // we're upgrading?
892 )
893 {
894 // compose new filename: strip off trailing ".xml"/".vbox"
895 Utf8Str strFilenameNew;
896 Utf8Str strExt = ".xml";
897 if (m->strFilename.endsWith(".xml"))
898 strFilenameNew = m->strFilename.substr(0, m->strFilename.length() - 4);
899 else if (m->strFilename.endsWith(".vbox"))
900 {
901 strFilenameNew = m->strFilename.substr(0, m->strFilename.length() - 5);
902 strExt = ".vbox";
903 }
904
905 // and append something like "-1.3-linux.xml"
906 strFilenameNew.append("-");
907 strFilenameNew.append(m->strSettingsVersionFull); // e.g. "1.3-linux"
908 strFilenameNew.append(strExt); // .xml for main config, .vbox for machine config
909
910 RTFileMove(m->strFilename.c_str(),
911 strFilenameNew.c_str(),
912 0); // no RTFILEMOVE_FLAGS_REPLACE
913
914 // do this only once
915 m->svRead = SettingsVersion_Null;
916 }
917}
918
919/**
920 * Creates an <ExtraData> node under the given parent element with
921 * <ExtraDataItem> childern according to the contents of the given
922 * map.
923 *
924 * This is in ConfigFileBase because it's used in both MainConfigFile
925 * and MachineConfigFile, which both can have extradata.
926 *
927 * @param elmParent
928 * @param me
929 */
930void ConfigFileBase::buildExtraData(xml::ElementNode &elmParent,
931 const StringsMap &me)
932{
933 if (me.size())
934 {
935 xml::ElementNode *pelmExtraData = elmParent.createChild("ExtraData");
936 for (StringsMap::const_iterator it = me.begin();
937 it != me.end();
938 ++it)
939 {
940 const Utf8Str &strName = it->first;
941 const Utf8Str &strValue = it->second;
942 xml::ElementNode *pelmThis = pelmExtraData->createChild("ExtraDataItem");
943 pelmThis->setAttribute("name", strName);
944 pelmThis->setAttribute("value", strValue);
945 }
946 }
947}
948
949/**
950 * Creates <DeviceFilter> nodes under the given parent element according to
951 * the contents of the given USBDeviceFiltersList. This is in ConfigFileBase
952 * because it's used in both MainConfigFile (for host filters) and
953 * MachineConfigFile (for machine filters).
954 *
955 * If fHostMode is true, this means that we're supposed to write filters
956 * for the IHost interface (respect "action", omit "strRemote" and
957 * "ulMaskedInterfaces" in struct USBDeviceFilter).
958 *
959 * @param elmParent
960 * @param ll
961 * @param fHostMode
962 */
963void ConfigFileBase::buildUSBDeviceFilters(xml::ElementNode &elmParent,
964 const USBDeviceFiltersList &ll,
965 bool fHostMode)
966{
967 for (USBDeviceFiltersList::const_iterator it = ll.begin();
968 it != ll.end();
969 ++it)
970 {
971 const USBDeviceFilter &flt = *it;
972 xml::ElementNode *pelmFilter = elmParent.createChild("DeviceFilter");
973 pelmFilter->setAttribute("name", flt.strName);
974 pelmFilter->setAttribute("active", flt.fActive);
975 if (flt.strVendorId.length())
976 pelmFilter->setAttribute("vendorId", flt.strVendorId);
977 if (flt.strProductId.length())
978 pelmFilter->setAttribute("productId", flt.strProductId);
979 if (flt.strRevision.length())
980 pelmFilter->setAttribute("revision", flt.strRevision);
981 if (flt.strManufacturer.length())
982 pelmFilter->setAttribute("manufacturer", flt.strManufacturer);
983 if (flt.strProduct.length())
984 pelmFilter->setAttribute("product", flt.strProduct);
985 if (flt.strSerialNumber.length())
986 pelmFilter->setAttribute("serialNumber", flt.strSerialNumber);
987 if (flt.strPort.length())
988 pelmFilter->setAttribute("port", flt.strPort);
989
990 if (fHostMode)
991 {
992 const char *pcsz =
993 (flt.action == USBDeviceFilterAction_Ignore) ? "Ignore"
994 : /*(flt.action == USBDeviceFilterAction_Hold) ?*/ "Hold";
995 pelmFilter->setAttribute("action", pcsz);
996 }
997 else
998 {
999 if (flt.strRemote.length())
1000 pelmFilter->setAttribute("remote", flt.strRemote);
1001 if (flt.ulMaskedInterfaces)
1002 pelmFilter->setAttribute("maskedInterfaces", flt.ulMaskedInterfaces);
1003 }
1004 }
1005}
1006
1007/**
1008 * Creates a single <HardDisk> element for the given Medium structure
1009 * and recurses to write the child hard disks underneath. Called from
1010 * MainConfigFile::write().
1011 *
1012 * @param elmMedium
1013 * @param m
1014 * @param level
1015 */
1016void ConfigFileBase::buildMedium(xml::ElementNode &elmMedium,
1017 DeviceType_T devType,
1018 const Medium &mdm,
1019 uint32_t level) // 0 for "root" call, incremented with each recursion
1020{
1021 xml::ElementNode *pelmMedium;
1022
1023 if (devType == DeviceType_HardDisk)
1024 pelmMedium = elmMedium.createChild("HardDisk");
1025 else
1026 pelmMedium = elmMedium.createChild("Image");
1027
1028 pelmMedium->setAttribute("uuid", mdm.uuid.toStringCurly());
1029
1030 pelmMedium->setAttributePath("location", mdm.strLocation);
1031
1032 if (devType == DeviceType_HardDisk || RTStrICmp(mdm.strFormat.c_str(), "RAW"))
1033 pelmMedium->setAttribute("format", mdm.strFormat);
1034 if ( devType == DeviceType_HardDisk
1035 && mdm.fAutoReset)
1036 pelmMedium->setAttribute("autoReset", mdm.fAutoReset);
1037 if (mdm.strDescription.length())
1038 pelmMedium->setAttribute("Description", mdm.strDescription);
1039
1040 for (StringsMap::const_iterator it = mdm.properties.begin();
1041 it != mdm.properties.end();
1042 ++it)
1043 {
1044 xml::ElementNode *pelmProp = pelmMedium->createChild("Property");
1045 pelmProp->setAttribute("name", it->first);
1046 pelmProp->setAttribute("value", it->second);
1047 }
1048
1049 // only for base hard disks, save the type
1050 if (level == 0)
1051 {
1052 // no need to save the usual DVD/floppy medium types
1053 if ( ( devType != DeviceType_DVD
1054 || ( mdm.hdType != MediumType_Writethrough // shouldn't happen
1055 && mdm.hdType != MediumType_Readonly))
1056 && ( devType != DeviceType_Floppy
1057 || mdm.hdType != MediumType_Writethrough))
1058 {
1059 const char *pcszType =
1060 mdm.hdType == MediumType_Normal ? "Normal" :
1061 mdm.hdType == MediumType_Immutable ? "Immutable" :
1062 mdm.hdType == MediumType_Writethrough ? "Writethrough" :
1063 mdm.hdType == MediumType_Shareable ? "Shareable" :
1064 mdm.hdType == MediumType_Readonly ? "Readonly" :
1065 mdm.hdType == MediumType_MultiAttach ? "MultiAttach" :
1066 "INVALID";
1067 pelmMedium->setAttribute("type", pcszType);
1068 }
1069 }
1070
1071 for (MediaList::const_iterator it = mdm.llChildren.begin();
1072 it != mdm.llChildren.end();
1073 ++it)
1074 {
1075 // recurse for children
1076 buildMedium(*pelmMedium, // parent
1077 devType, // device type
1078 *it, // settings::Medium
1079 ++level); // recursion level
1080 }
1081}
1082
1083/**
1084 * Creates a <MediaRegistry> node under the given parent and writes out all
1085 * hard disks and DVD and floppy images from the lists in the given MediaRegistry
1086 * structure under it.
1087 *
1088 * This is used in both MainConfigFile and MachineConfigFile since starting with
1089 * VirtualBox 4.0, we can have media registries in both.
1090 *
1091 * @param elmParent
1092 * @param mr
1093 */
1094void ConfigFileBase::buildMediaRegistry(xml::ElementNode &elmParent,
1095 const MediaRegistry &mr)
1096{
1097 xml::ElementNode *pelmMediaRegistry = elmParent.createChild("MediaRegistry");
1098
1099 xml::ElementNode *pelmHardDisks = pelmMediaRegistry->createChild("HardDisks");
1100 for (MediaList::const_iterator it = mr.llHardDisks.begin();
1101 it != mr.llHardDisks.end();
1102 ++it)
1103 {
1104 buildMedium(*pelmHardDisks, DeviceType_HardDisk, *it, 0);
1105 }
1106
1107 xml::ElementNode *pelmDVDImages = pelmMediaRegistry->createChild("DVDImages");
1108 for (MediaList::const_iterator it = mr.llDvdImages.begin();
1109 it != mr.llDvdImages.end();
1110 ++it)
1111 {
1112 buildMedium(*pelmDVDImages, DeviceType_DVD, *it, 0);
1113 }
1114
1115 xml::ElementNode *pelmFloppyImages = pelmMediaRegistry->createChild("FloppyImages");
1116 for (MediaList::const_iterator it = mr.llFloppyImages.begin();
1117 it != mr.llFloppyImages.end();
1118 ++it)
1119 {
1120 buildMedium(*pelmFloppyImages, DeviceType_Floppy, *it, 0);
1121 }
1122}
1123
1124/**
1125 * Cleans up memory allocated by the internal XML parser. To be called by
1126 * descendant classes when they're done analyzing the DOM tree to discard it.
1127 */
1128void ConfigFileBase::clearDocument()
1129{
1130 m->cleanup();
1131}
1132
1133/**
1134 * Returns true only if the underlying config file exists on disk;
1135 * either because the file has been loaded from disk, or it's been written
1136 * to disk, or both.
1137 * @return
1138 */
1139bool ConfigFileBase::fileExists()
1140{
1141 return m->fFileExists;
1142}
1143
1144/**
1145 * Copies the base variables from another instance. Used by Machine::saveSettings
1146 * so that the settings version does not get lost when a copy of the Machine settings
1147 * file is made to see if settings have actually changed.
1148 * @param b
1149 */
1150void ConfigFileBase::copyBaseFrom(const ConfigFileBase &b)
1151{
1152 m->copyFrom(*b.m);
1153}
1154
1155////////////////////////////////////////////////////////////////////////////////
1156//
1157// Structures shared between Machine XML and VirtualBox.xml
1158//
1159////////////////////////////////////////////////////////////////////////////////
1160
1161/**
1162 * Comparison operator. This gets called from MachineConfigFile::operator==,
1163 * which in turn gets called from Machine::saveSettings to figure out whether
1164 * machine settings have really changed and thus need to be written out to disk.
1165 */
1166bool USBDeviceFilter::operator==(const USBDeviceFilter &u) const
1167{
1168 return ( (this == &u)
1169 || ( (strName == u.strName)
1170 && (fActive == u.fActive)
1171 && (strVendorId == u.strVendorId)
1172 && (strProductId == u.strProductId)
1173 && (strRevision == u.strRevision)
1174 && (strManufacturer == u.strManufacturer)
1175 && (strProduct == u.strProduct)
1176 && (strSerialNumber == u.strSerialNumber)
1177 && (strPort == u.strPort)
1178 && (action == u.action)
1179 && (strRemote == u.strRemote)
1180 && (ulMaskedInterfaces == u.ulMaskedInterfaces)
1181 )
1182 );
1183}
1184
1185////////////////////////////////////////////////////////////////////////////////
1186//
1187// MainConfigFile
1188//
1189////////////////////////////////////////////////////////////////////////////////
1190
1191/**
1192 * Reads one <MachineEntry> from the main VirtualBox.xml file.
1193 * @param elmMachineRegistry
1194 */
1195void MainConfigFile::readMachineRegistry(const xml::ElementNode &elmMachineRegistry)
1196{
1197 // <MachineEntry uuid="{ xxx }" src=" xxx "/>
1198 xml::NodesLoop nl1(elmMachineRegistry);
1199 const xml::ElementNode *pelmChild1;
1200 while ((pelmChild1 = nl1.forAllNodes()))
1201 {
1202 if (pelmChild1->nameEquals("MachineEntry"))
1203 {
1204 MachineRegistryEntry mre;
1205 Utf8Str strUUID;
1206 if ( ((pelmChild1->getAttributeValue("uuid", strUUID)))
1207 && ((pelmChild1->getAttributeValue("src", mre.strSettingsFile)))
1208 )
1209 {
1210 parseUUID(mre.uuid, strUUID);
1211 llMachines.push_back(mre);
1212 }
1213 else
1214 throw ConfigFileError(this, pelmChild1, N_("Required MachineEntry/@uuid or @src attribute is missing"));
1215 }
1216 }
1217}
1218
1219/**
1220 * Reads in the <DHCPServers> chunk.
1221 * @param elmDHCPServers
1222 */
1223void MainConfigFile::readDHCPServers(const xml::ElementNode &elmDHCPServers)
1224{
1225 xml::NodesLoop nl1(elmDHCPServers);
1226 const xml::ElementNode *pelmServer;
1227 while ((pelmServer = nl1.forAllNodes()))
1228 {
1229 if (pelmServer->nameEquals("DHCPServer"))
1230 {
1231 DHCPServer srv;
1232 if ( (pelmServer->getAttributeValue("networkName", srv.strNetworkName))
1233 && (pelmServer->getAttributeValue("IPAddress", srv.strIPAddress))
1234 && (pelmServer->getAttributeValue("networkMask", srv.strIPNetworkMask))
1235 && (pelmServer->getAttributeValue("lowerIP", srv.strIPLower))
1236 && (pelmServer->getAttributeValue("upperIP", srv.strIPUpper))
1237 && (pelmServer->getAttributeValue("enabled", srv.fEnabled))
1238 )
1239 llDhcpServers.push_back(srv);
1240 else
1241 throw ConfigFileError(this, pelmServer, N_("Required DHCPServer/@networkName, @IPAddress, @networkMask, @lowerIP, @upperIP or @enabled attribute is missing"));
1242 }
1243 }
1244}
1245
1246/**
1247 * Constructor.
1248 *
1249 * If pstrFilename is != NULL, this reads the given settings file into the member
1250 * variables and various substructures and lists. Otherwise, the member variables
1251 * are initialized with default values.
1252 *
1253 * Throws variants of xml::Error for I/O, XML and logical content errors, which
1254 * the caller should catch; if this constructor does not throw, then the member
1255 * variables contain meaningful values (either from the file or defaults).
1256 *
1257 * @param strFilename
1258 */
1259MainConfigFile::MainConfigFile(const Utf8Str *pstrFilename)
1260 : ConfigFileBase(pstrFilename)
1261{
1262 if (pstrFilename)
1263 {
1264 // the ConfigFileBase constructor has loaded the XML file, so now
1265 // we need only analyze what is in there
1266 xml::NodesLoop nlRootChildren(*m->pelmRoot);
1267 const xml::ElementNode *pelmRootChild;
1268 while ((pelmRootChild = nlRootChildren.forAllNodes()))
1269 {
1270 if (pelmRootChild->nameEquals("Global"))
1271 {
1272 xml::NodesLoop nlGlobalChildren(*pelmRootChild);
1273 const xml::ElementNode *pelmGlobalChild;
1274 while ((pelmGlobalChild = nlGlobalChildren.forAllNodes()))
1275 {
1276 if (pelmGlobalChild->nameEquals("SystemProperties"))
1277 {
1278 pelmGlobalChild->getAttributeValue("defaultMachineFolder", systemProperties.strDefaultMachineFolder);
1279 pelmGlobalChild->getAttributeValue("defaultHardDiskFormat", systemProperties.strDefaultHardDiskFormat);
1280 if (!pelmGlobalChild->getAttributeValue("VRDEAuthLibrary", systemProperties.strVRDEAuthLibrary))
1281 // pre-1.11 used @remoteDisplayAuthLibrary instead
1282 pelmGlobalChild->getAttributeValue("remoteDisplayAuthLibrary", systemProperties.strVRDEAuthLibrary);
1283 pelmGlobalChild->getAttributeValue("webServiceAuthLibrary", systemProperties.strWebServiceAuthLibrary);
1284 pelmGlobalChild->getAttributeValue("defaultVRDEExtPack", systemProperties.strDefaultVRDEExtPack);
1285 pelmGlobalChild->getAttributeValue("LogHistoryCount", systemProperties.ulLogHistoryCount);
1286 }
1287 else if (pelmGlobalChild->nameEquals("ExtraData"))
1288 readExtraData(*pelmGlobalChild, mapExtraDataItems);
1289 else if (pelmGlobalChild->nameEquals("MachineRegistry"))
1290 readMachineRegistry(*pelmGlobalChild);
1291 else if ( (pelmGlobalChild->nameEquals("MediaRegistry"))
1292 || ( (m->sv < SettingsVersion_v1_4)
1293 && (pelmGlobalChild->nameEquals("DiskRegistry"))
1294 )
1295 )
1296 readMediaRegistry(*pelmGlobalChild, mediaRegistry);
1297 else if (pelmGlobalChild->nameEquals("NetserviceRegistry"))
1298 {
1299 xml::NodesLoop nlLevel4(*pelmGlobalChild);
1300 const xml::ElementNode *pelmLevel4Child;
1301 while ((pelmLevel4Child = nlLevel4.forAllNodes()))
1302 {
1303 if (pelmLevel4Child->nameEquals("DHCPServers"))
1304 readDHCPServers(*pelmLevel4Child);
1305 }
1306 }
1307 else if (pelmGlobalChild->nameEquals("USBDeviceFilters"))
1308 readUSBDeviceFilters(*pelmGlobalChild, host.llUSBDeviceFilters);
1309 }
1310 } // end if (pelmRootChild->nameEquals("Global"))
1311 }
1312
1313 clearDocument();
1314 }
1315
1316 // DHCP servers were introduced with settings version 1.7; if we're loading
1317 // from an older version OR this is a fresh install, then add one DHCP server
1318 // with default settings
1319 if ( (!llDhcpServers.size())
1320 && ( (!pstrFilename) // empty VirtualBox.xml file
1321 || (m->sv < SettingsVersion_v1_7) // upgrading from before 1.7
1322 )
1323 )
1324 {
1325 DHCPServer srv;
1326 srv.strNetworkName =
1327#ifdef RT_OS_WINDOWS
1328 "HostInterfaceNetworking-VirtualBox Host-Only Ethernet Adapter";
1329#else
1330 "HostInterfaceNetworking-vboxnet0";
1331#endif
1332 srv.strIPAddress = "192.168.56.100";
1333 srv.strIPNetworkMask = "255.255.255.0";
1334 srv.strIPLower = "192.168.56.101";
1335 srv.strIPUpper = "192.168.56.254";
1336 srv.fEnabled = true;
1337 llDhcpServers.push_back(srv);
1338 }
1339}
1340
1341/**
1342 * Called from the IVirtualBox interface to write out VirtualBox.xml. This
1343 * builds an XML DOM tree and writes it out to disk.
1344 */
1345void MainConfigFile::write(const com::Utf8Str strFilename)
1346{
1347 m->strFilename = strFilename;
1348 createStubDocument();
1349
1350 xml::ElementNode *pelmGlobal = m->pelmRoot->createChild("Global");
1351
1352 buildExtraData(*pelmGlobal, mapExtraDataItems);
1353
1354 xml::ElementNode *pelmMachineRegistry = pelmGlobal->createChild("MachineRegistry");
1355 for (MachinesRegistry::const_iterator it = llMachines.begin();
1356 it != llMachines.end();
1357 ++it)
1358 {
1359 // <MachineEntry uuid="{5f102a55-a51b-48e3-b45a-b28d33469488}" src="/mnt/innotek-unix/vbox-machines/Windows 5.1 XP 1 (Office 2003)/Windows 5.1 XP 1 (Office 2003).xml"/>
1360 const MachineRegistryEntry &mre = *it;
1361 xml::ElementNode *pelmMachineEntry = pelmMachineRegistry->createChild("MachineEntry");
1362 pelmMachineEntry->setAttribute("uuid", mre.uuid.toStringCurly());
1363 pelmMachineEntry->setAttribute("src", mre.strSettingsFile);
1364 }
1365
1366 buildMediaRegistry(*pelmGlobal, mediaRegistry);
1367
1368 xml::ElementNode *pelmNetserviceRegistry = pelmGlobal->createChild("NetserviceRegistry");
1369 xml::ElementNode *pelmDHCPServers = pelmNetserviceRegistry->createChild("DHCPServers");
1370 for (DHCPServersList::const_iterator it = llDhcpServers.begin();
1371 it != llDhcpServers.end();
1372 ++it)
1373 {
1374 const DHCPServer &d = *it;
1375 xml::ElementNode *pelmThis = pelmDHCPServers->createChild("DHCPServer");
1376 pelmThis->setAttribute("networkName", d.strNetworkName);
1377 pelmThis->setAttribute("IPAddress", d.strIPAddress);
1378 pelmThis->setAttribute("networkMask", d.strIPNetworkMask);
1379 pelmThis->setAttribute("lowerIP", d.strIPLower);
1380 pelmThis->setAttribute("upperIP", d.strIPUpper);
1381 pelmThis->setAttribute("enabled", (d.fEnabled) ? 1 : 0); // too bad we chose 1 vs. 0 here
1382 }
1383
1384 xml::ElementNode *pelmSysProps = pelmGlobal->createChild("SystemProperties");
1385 if (systemProperties.strDefaultMachineFolder.length())
1386 pelmSysProps->setAttribute("defaultMachineFolder", systemProperties.strDefaultMachineFolder);
1387 if (systemProperties.strDefaultHardDiskFormat.length())
1388 pelmSysProps->setAttribute("defaultHardDiskFormat", systemProperties.strDefaultHardDiskFormat);
1389 if (systemProperties.strVRDEAuthLibrary.length())
1390 pelmSysProps->setAttribute("VRDEAuthLibrary", systemProperties.strVRDEAuthLibrary);
1391 if (systemProperties.strWebServiceAuthLibrary.length())
1392 pelmSysProps->setAttribute("webServiceAuthLibrary", systemProperties.strWebServiceAuthLibrary);
1393 if (systemProperties.strDefaultVRDEExtPack.length())
1394 pelmSysProps->setAttribute("defaultVRDEExtPack", systemProperties.strDefaultVRDEExtPack);
1395 pelmSysProps->setAttribute("LogHistoryCount", systemProperties.ulLogHistoryCount);
1396
1397 buildUSBDeviceFilters(*pelmGlobal->createChild("USBDeviceFilters"),
1398 host.llUSBDeviceFilters,
1399 true); // fHostMode
1400
1401 // now go write the XML
1402 xml::XmlFileWriter writer(*m->pDoc);
1403 writer.write(m->strFilename.c_str(), true /*fSafe*/);
1404
1405 m->fFileExists = true;
1406
1407 clearDocument();
1408}
1409
1410////////////////////////////////////////////////////////////////////////////////
1411//
1412// Machine XML structures
1413//
1414////////////////////////////////////////////////////////////////////////////////
1415
1416/**
1417 * Comparison operator. This gets called from MachineConfigFile::operator==,
1418 * which in turn gets called from Machine::saveSettings to figure out whether
1419 * machine settings have really changed and thus need to be written out to disk.
1420 */
1421bool VRDESettings::operator==(const VRDESettings& v) const
1422{
1423 return ( (this == &v)
1424 || ( (fEnabled == v.fEnabled)
1425 && (authType == v.authType)
1426 && (ulAuthTimeout == v.ulAuthTimeout)
1427 && (strAuthLibrary == v.strAuthLibrary)
1428 && (fAllowMultiConnection == v.fAllowMultiConnection)
1429 && (fReuseSingleConnection == v.fReuseSingleConnection)
1430 && (strVrdeExtPack == v.strVrdeExtPack)
1431 && (mapProperties == v.mapProperties)
1432 )
1433 );
1434}
1435
1436/**
1437 * Comparison operator. This gets called from MachineConfigFile::operator==,
1438 * which in turn gets called from Machine::saveSettings to figure out whether
1439 * machine settings have really changed and thus need to be written out to disk.
1440 */
1441bool BIOSSettings::operator==(const BIOSSettings &d) const
1442{
1443 return ( (this == &d)
1444 || ( fACPIEnabled == d.fACPIEnabled
1445 && fIOAPICEnabled == d.fIOAPICEnabled
1446 && fLogoFadeIn == d.fLogoFadeIn
1447 && fLogoFadeOut == d.fLogoFadeOut
1448 && ulLogoDisplayTime == d.ulLogoDisplayTime
1449 && strLogoImagePath == d.strLogoImagePath
1450 && biosBootMenuMode == d.biosBootMenuMode
1451 && fPXEDebugEnabled == d.fPXEDebugEnabled
1452 && llTimeOffset == d.llTimeOffset)
1453 );
1454}
1455
1456/**
1457 * Comparison operator. This gets called from MachineConfigFile::operator==,
1458 * which in turn gets called from Machine::saveSettings to figure out whether
1459 * machine settings have really changed and thus need to be written out to disk.
1460 */
1461bool USBController::operator==(const USBController &u) const
1462{
1463 return ( (this == &u)
1464 || ( (fEnabled == u.fEnabled)
1465 && (fEnabledEHCI == u.fEnabledEHCI)
1466 && (llDeviceFilters == u.llDeviceFilters)
1467 )
1468 );
1469}
1470
1471/**
1472 * Comparison operator. This gets called from MachineConfigFile::operator==,
1473 * which in turn gets called from Machine::saveSettings to figure out whether
1474 * machine settings have really changed and thus need to be written out to disk.
1475 */
1476bool NetworkAdapter::operator==(const NetworkAdapter &n) const
1477{
1478 return ( (this == &n)
1479 || ( (ulSlot == n.ulSlot)
1480 && (type == n.type)
1481 && (fEnabled == n.fEnabled)
1482 && (strMACAddress == n.strMACAddress)
1483 && (fCableConnected == n.fCableConnected)
1484 && (ulLineSpeed == n.ulLineSpeed)
1485 && (enmPromiscModePolicy == n.enmPromiscModePolicy)
1486 && (fTraceEnabled == n.fTraceEnabled)
1487 && (strTraceFile == n.strTraceFile)
1488 && (mode == n.mode)
1489 && (nat == n.nat)
1490 && (strBridgedName == n.strBridgedName)
1491 && (strHostOnlyName == n.strHostOnlyName)
1492 && (strInternalNetworkName == n.strInternalNetworkName)
1493 && (strGenericDriver == n.strGenericDriver)
1494 && (genericProperties == n.genericProperties)
1495 && (ulBootPriority == n.ulBootPriority)
1496 )
1497 );
1498}
1499
1500/**
1501 * Comparison operator. This gets called from MachineConfigFile::operator==,
1502 * which in turn gets called from Machine::saveSettings to figure out whether
1503 * machine settings have really changed and thus need to be written out to disk.
1504 */
1505bool SerialPort::operator==(const SerialPort &s) const
1506{
1507 return ( (this == &s)
1508 || ( (ulSlot == s.ulSlot)
1509 && (fEnabled == s.fEnabled)
1510 && (ulIOBase == s.ulIOBase)
1511 && (ulIRQ == s.ulIRQ)
1512 && (portMode == s.portMode)
1513 && (strPath == s.strPath)
1514 && (fServer == s.fServer)
1515 )
1516 );
1517}
1518
1519/**
1520 * Comparison operator. This gets called from MachineConfigFile::operator==,
1521 * which in turn gets called from Machine::saveSettings to figure out whether
1522 * machine settings have really changed and thus need to be written out to disk.
1523 */
1524bool ParallelPort::operator==(const ParallelPort &s) const
1525{
1526 return ( (this == &s)
1527 || ( (ulSlot == s.ulSlot)
1528 && (fEnabled == s.fEnabled)
1529 && (ulIOBase == s.ulIOBase)
1530 && (ulIRQ == s.ulIRQ)
1531 && (strPath == s.strPath)
1532 )
1533 );
1534}
1535
1536/**
1537 * Comparison operator. This gets called from MachineConfigFile::operator==,
1538 * which in turn gets called from Machine::saveSettings to figure out whether
1539 * machine settings have really changed and thus need to be written out to disk.
1540 */
1541bool SharedFolder::operator==(const SharedFolder &g) const
1542{
1543 return ( (this == &g)
1544 || ( (strName == g.strName)
1545 && (strHostPath == g.strHostPath)
1546 && (fWritable == g.fWritable)
1547 && (fAutoMount == g.fAutoMount)
1548 )
1549 );
1550}
1551
1552/**
1553 * Comparison operator. This gets called from MachineConfigFile::operator==,
1554 * which in turn gets called from Machine::saveSettings to figure out whether
1555 * machine settings have really changed and thus need to be written out to disk.
1556 */
1557bool GuestProperty::operator==(const GuestProperty &g) const
1558{
1559 return ( (this == &g)
1560 || ( (strName == g.strName)
1561 && (strValue == g.strValue)
1562 && (timestamp == g.timestamp)
1563 && (strFlags == g.strFlags)
1564 )
1565 );
1566}
1567
1568// use a define for the platform-dependent default value of
1569// hwvirt exclusivity, since we'll need to check that value
1570// in bumpSettingsVersionIfNeeded()
1571#if defined(RT_OS_DARWIN) || defined(RT_OS_WINDOWS)
1572 #define HWVIRTEXCLUSIVEDEFAULT false
1573#else
1574 #define HWVIRTEXCLUSIVEDEFAULT true
1575#endif
1576
1577/**
1578 * Hardware struct constructor.
1579 */
1580Hardware::Hardware()
1581 : strVersion("1"),
1582 fHardwareVirt(true),
1583 fHardwareVirtExclusive(HWVIRTEXCLUSIVEDEFAULT),
1584 fNestedPaging(true),
1585 fVPID(true),
1586 fHardwareVirtForce(false),
1587 fSyntheticCpu(false),
1588 fPAE(false),
1589 cCPUs(1),
1590 fCpuHotPlug(false),
1591 fHpetEnabled(false),
1592 ulCpuExecutionCap(100),
1593 ulMemorySizeMB((uint32_t)-1),
1594 ulVRAMSizeMB(8),
1595 cMonitors(1),
1596 fAccelerate3D(false),
1597 fAccelerate2DVideo(false),
1598 firmwareType(FirmwareType_BIOS),
1599 pointingHidType(PointingHidType_PS2Mouse),
1600 keyboardHidType(KeyboardHidType_PS2Keyboard),
1601 chipsetType(ChipsetType_PIIX3),
1602 clipboardMode(ClipboardMode_Bidirectional),
1603 ulMemoryBalloonSize(0),
1604 fPageFusionEnabled(false)
1605{
1606 mapBootOrder[0] = DeviceType_Floppy;
1607 mapBootOrder[1] = DeviceType_DVD;
1608 mapBootOrder[2] = DeviceType_HardDisk;
1609
1610 /* The default value for PAE depends on the host:
1611 * - 64 bits host -> always true
1612 * - 32 bits host -> true for Windows & Darwin (masked off if the host cpu doesn't support it anyway)
1613 */
1614#if HC_ARCH_BITS == 64 || defined(RT_OS_WINDOWS) || defined(RT_OS_DARWIN)
1615 fPAE = true;
1616#endif
1617
1618 /* The default value of large page supports depends on the host:
1619 * - 64 bits host -> true, unless it's Linux (pending further prediction work due to excessively expensive large page allocations)
1620 * - 32 bits host -> false
1621 */
1622#if HC_ARCH_BITS == 64 && !defined(RT_OS_LINUX)
1623 fLargePages = true;
1624#else
1625 /* Not supported on 32 bits hosts. */
1626 fLargePages = false;
1627#endif
1628}
1629
1630/**
1631 * Comparison operator. This gets called from MachineConfigFile::operator==,
1632 * which in turn gets called from Machine::saveSettings to figure out whether
1633 * machine settings have really changed and thus need to be written out to disk.
1634 */
1635bool Hardware::operator==(const Hardware& h) const
1636{
1637 return ( (this == &h)
1638 || ( (strVersion == h.strVersion)
1639 && (uuid == h.uuid)
1640 && (fHardwareVirt == h.fHardwareVirt)
1641 && (fHardwareVirtExclusive == h.fHardwareVirtExclusive)
1642 && (fNestedPaging == h.fNestedPaging)
1643 && (fLargePages == h.fLargePages)
1644 && (fVPID == h.fVPID)
1645 && (fHardwareVirtForce == h.fHardwareVirtForce)
1646 && (fSyntheticCpu == h.fSyntheticCpu)
1647 && (fPAE == h.fPAE)
1648 && (cCPUs == h.cCPUs)
1649 && (fCpuHotPlug == h.fCpuHotPlug)
1650 && (ulCpuExecutionCap == h.ulCpuExecutionCap)
1651 && (fHpetEnabled == h.fHpetEnabled)
1652 && (llCpus == h.llCpus)
1653 && (llCpuIdLeafs == h.llCpuIdLeafs)
1654 && (ulMemorySizeMB == h.ulMemorySizeMB)
1655 && (mapBootOrder == h.mapBootOrder)
1656 && (ulVRAMSizeMB == h.ulVRAMSizeMB)
1657 && (cMonitors == h.cMonitors)
1658 && (fAccelerate3D == h.fAccelerate3D)
1659 && (fAccelerate2DVideo == h.fAccelerate2DVideo)
1660 && (firmwareType == h.firmwareType)
1661 && (pointingHidType == h.pointingHidType)
1662 && (keyboardHidType == h.keyboardHidType)
1663 && (chipsetType == h.chipsetType)
1664 && (vrdeSettings == h.vrdeSettings)
1665 && (biosSettings == h.biosSettings)
1666 && (usbController == h.usbController)
1667 && (llNetworkAdapters == h.llNetworkAdapters)
1668 && (llSerialPorts == h.llSerialPorts)
1669 && (llParallelPorts == h.llParallelPorts)
1670 && (audioAdapter == h.audioAdapter)
1671 && (llSharedFolders == h.llSharedFolders)
1672 && (clipboardMode == h.clipboardMode)
1673 && (ulMemoryBalloonSize == h.ulMemoryBalloonSize)
1674 && (fPageFusionEnabled == h.fPageFusionEnabled)
1675 && (llGuestProperties == h.llGuestProperties)
1676 && (strNotificationPatterns == h.strNotificationPatterns)
1677 && (ioSettings == h.ioSettings)
1678 && (pciAttachments == h.pciAttachments)
1679 )
1680 );
1681}
1682
1683/**
1684 * Comparison operator. This gets called from MachineConfigFile::operator==,
1685 * which in turn gets called from Machine::saveSettings to figure out whether
1686 * machine settings have really changed and thus need to be written out to disk.
1687 */
1688bool AttachedDevice::operator==(const AttachedDevice &a) const
1689{
1690 return ( (this == &a)
1691 || ( (deviceType == a.deviceType)
1692 && (fPassThrough == a.fPassThrough)
1693 && (lPort == a.lPort)
1694 && (lDevice == a.lDevice)
1695 && (uuid == a.uuid)
1696 && (strHostDriveSrc == a.strHostDriveSrc)
1697 && (strBwGroup == a.strBwGroup)
1698 )
1699 );
1700}
1701
1702/**
1703 * Comparison operator. This gets called from MachineConfigFile::operator==,
1704 * which in turn gets called from Machine::saveSettings to figure out whether
1705 * machine settings have really changed and thus need to be written out to disk.
1706 */
1707bool StorageController::operator==(const StorageController &s) const
1708{
1709 return ( (this == &s)
1710 || ( (strName == s.strName)
1711 && (storageBus == s.storageBus)
1712 && (controllerType == s.controllerType)
1713 && (ulPortCount == s.ulPortCount)
1714 && (ulInstance == s.ulInstance)
1715 && (fUseHostIOCache == s.fUseHostIOCache)
1716 && (lIDE0MasterEmulationPort == s.lIDE0MasterEmulationPort)
1717 && (lIDE0SlaveEmulationPort == s.lIDE0SlaveEmulationPort)
1718 && (lIDE1MasterEmulationPort == s.lIDE1MasterEmulationPort)
1719 && (lIDE1SlaveEmulationPort == s.lIDE1SlaveEmulationPort)
1720 && (llAttachedDevices == s.llAttachedDevices)
1721 )
1722 );
1723}
1724
1725/**
1726 * Comparison operator. This gets called from MachineConfigFile::operator==,
1727 * which in turn gets called from Machine::saveSettings to figure out whether
1728 * machine settings have really changed and thus need to be written out to disk.
1729 */
1730bool Storage::operator==(const Storage &s) const
1731{
1732 return ( (this == &s)
1733 || (llStorageControllers == s.llStorageControllers) // deep compare
1734 );
1735}
1736
1737/**
1738 * Comparison operator. This gets called from MachineConfigFile::operator==,
1739 * which in turn gets called from Machine::saveSettings to figure out whether
1740 * machine settings have really changed and thus need to be written out to disk.
1741 */
1742bool Snapshot::operator==(const Snapshot &s) const
1743{
1744 return ( (this == &s)
1745 || ( (uuid == s.uuid)
1746 && (strName == s.strName)
1747 && (strDescription == s.strDescription)
1748 && (RTTimeSpecIsEqual(&timestamp, &s.timestamp))
1749 && (strStateFile == s.strStateFile)
1750 && (hardware == s.hardware) // deep compare
1751 && (storage == s.storage) // deep compare
1752 && (llChildSnapshots == s.llChildSnapshots) // deep compare
1753 )
1754 );
1755}
1756
1757/**
1758 * IoSettings constructor.
1759 */
1760IoSettings::IoSettings()
1761{
1762 fIoCacheEnabled = true;
1763 ulIoCacheSize = 5;
1764}
1765
1766////////////////////////////////////////////////////////////////////////////////
1767//
1768// MachineConfigFile
1769//
1770////////////////////////////////////////////////////////////////////////////////
1771
1772/**
1773 * Constructor.
1774 *
1775 * If pstrFilename is != NULL, this reads the given settings file into the member
1776 * variables and various substructures and lists. Otherwise, the member variables
1777 * are initialized with default values.
1778 *
1779 * Throws variants of xml::Error for I/O, XML and logical content errors, which
1780 * the caller should catch; if this constructor does not throw, then the member
1781 * variables contain meaningful values (either from the file or defaults).
1782 *
1783 * @param strFilename
1784 */
1785MachineConfigFile::MachineConfigFile(const Utf8Str *pstrFilename)
1786 : ConfigFileBase(pstrFilename),
1787 fCurrentStateModified(true),
1788 fAborted(false)
1789{
1790 RTTimeNow(&timeLastStateChange);
1791
1792 if (pstrFilename)
1793 {
1794 // the ConfigFileBase constructor has loaded the XML file, so now
1795 // we need only analyze what is in there
1796
1797 xml::NodesLoop nlRootChildren(*m->pelmRoot);
1798 const xml::ElementNode *pelmRootChild;
1799 while ((pelmRootChild = nlRootChildren.forAllNodes()))
1800 {
1801 if (pelmRootChild->nameEquals("Machine"))
1802 readMachine(*pelmRootChild);
1803 }
1804
1805 // clean up memory allocated by XML engine
1806 clearDocument();
1807 }
1808}
1809
1810/**
1811 * Public routine which returns true if this machine config file can have its
1812 * own media registry (which is true for settings version v1.11 and higher,
1813 * i.e. files created by VirtualBox 4.0 and higher).
1814 * @return
1815 */
1816bool MachineConfigFile::canHaveOwnMediaRegistry() const
1817{
1818 return (m->sv >= SettingsVersion_v1_11);
1819}
1820
1821/**
1822 * Public routine which allows for importing machine XML from an external DOM tree.
1823 * Use this after having called the constructor with a NULL argument.
1824 *
1825 * This is used by the OVF code if a <vbox:Machine> element has been encountered
1826 * in an OVF VirtualSystem element.
1827 *
1828 * @param elmMachine
1829 */
1830void MachineConfigFile::importMachineXML(const xml::ElementNode &elmMachine)
1831{
1832 readMachine(elmMachine);
1833}
1834
1835/**
1836 * Comparison operator. This gets called from Machine::saveSettings to figure out
1837 * whether machine settings have really changed and thus need to be written out to disk.
1838 *
1839 * Even though this is called operator==, this does NOT compare all fields; the "equals"
1840 * should be understood as "has the same machine config as". The following fields are
1841 * NOT compared:
1842 * -- settings versions and file names inherited from ConfigFileBase;
1843 * -- fCurrentStateModified because that is considered separately in Machine::saveSettings!!
1844 *
1845 * The "deep" comparisons marked below will invoke the operator== functions of the
1846 * structs defined in this file, which may in turn go into comparing lists of
1847 * other structures. As a result, invoking this can be expensive, but it's
1848 * less expensive than writing out XML to disk.
1849 */
1850bool MachineConfigFile::operator==(const MachineConfigFile &c) const
1851{
1852 return ( (this == &c)
1853 || ( (uuid == c.uuid)
1854 && (machineUserData == c.machineUserData)
1855 && (strStateFile == c.strStateFile)
1856 && (uuidCurrentSnapshot == c.uuidCurrentSnapshot)
1857 // skip fCurrentStateModified!
1858 && (RTTimeSpecIsEqual(&timeLastStateChange, &c.timeLastStateChange))
1859 && (fAborted == c.fAborted)
1860 && (hardwareMachine == c.hardwareMachine) // this one's deep
1861 && (storageMachine == c.storageMachine) // this one's deep
1862 && (mediaRegistry == c.mediaRegistry) // this one's deep
1863 && (mapExtraDataItems == c.mapExtraDataItems) // this one's deep
1864 && (llFirstSnapshot == c.llFirstSnapshot) // this one's deep
1865 )
1866 );
1867}
1868
1869/**
1870 * Called from MachineConfigFile::readHardware() to read cpu information.
1871 * @param elmCpuid
1872 * @param ll
1873 */
1874void MachineConfigFile::readCpuTree(const xml::ElementNode &elmCpu,
1875 CpuList &ll)
1876{
1877 xml::NodesLoop nl1(elmCpu, "Cpu");
1878 const xml::ElementNode *pelmCpu;
1879 while ((pelmCpu = nl1.forAllNodes()))
1880 {
1881 Cpu cpu;
1882
1883 if (!pelmCpu->getAttributeValue("id", cpu.ulId))
1884 throw ConfigFileError(this, pelmCpu, N_("Required Cpu/@id attribute is missing"));
1885
1886 ll.push_back(cpu);
1887 }
1888}
1889
1890/**
1891 * Called from MachineConfigFile::readHardware() to cpuid information.
1892 * @param elmCpuid
1893 * @param ll
1894 */
1895void MachineConfigFile::readCpuIdTree(const xml::ElementNode &elmCpuid,
1896 CpuIdLeafsList &ll)
1897{
1898 xml::NodesLoop nl1(elmCpuid, "CpuIdLeaf");
1899 const xml::ElementNode *pelmCpuIdLeaf;
1900 while ((pelmCpuIdLeaf = nl1.forAllNodes()))
1901 {
1902 CpuIdLeaf leaf;
1903
1904 if (!pelmCpuIdLeaf->getAttributeValue("id", leaf.ulId))
1905 throw ConfigFileError(this, pelmCpuIdLeaf, N_("Required CpuId/@id attribute is missing"));
1906
1907 pelmCpuIdLeaf->getAttributeValue("eax", leaf.ulEax);
1908 pelmCpuIdLeaf->getAttributeValue("ebx", leaf.ulEbx);
1909 pelmCpuIdLeaf->getAttributeValue("ecx", leaf.ulEcx);
1910 pelmCpuIdLeaf->getAttributeValue("edx", leaf.ulEdx);
1911
1912 ll.push_back(leaf);
1913 }
1914}
1915
1916/**
1917 * Called from MachineConfigFile::readHardware() to network information.
1918 * @param elmNetwork
1919 * @param ll
1920 */
1921void MachineConfigFile::readNetworkAdapters(const xml::ElementNode &elmNetwork,
1922 NetworkAdaptersList &ll)
1923{
1924 xml::NodesLoop nl1(elmNetwork, "Adapter");
1925 const xml::ElementNode *pelmAdapter;
1926 while ((pelmAdapter = nl1.forAllNodes()))
1927 {
1928 NetworkAdapter nic;
1929
1930 if (!pelmAdapter->getAttributeValue("slot", nic.ulSlot))
1931 throw ConfigFileError(this, pelmAdapter, N_("Required Adapter/@slot attribute is missing"));
1932
1933 Utf8Str strTemp;
1934 if (pelmAdapter->getAttributeValue("type", strTemp))
1935 {
1936 if (strTemp == "Am79C970A")
1937 nic.type = NetworkAdapterType_Am79C970A;
1938 else if (strTemp == "Am79C973")
1939 nic.type = NetworkAdapterType_Am79C973;
1940 else if (strTemp == "82540EM")
1941 nic.type = NetworkAdapterType_I82540EM;
1942 else if (strTemp == "82543GC")
1943 nic.type = NetworkAdapterType_I82543GC;
1944 else if (strTemp == "82545EM")
1945 nic.type = NetworkAdapterType_I82545EM;
1946 else if (strTemp == "virtio")
1947 nic.type = NetworkAdapterType_Virtio;
1948 else
1949 throw ConfigFileError(this, pelmAdapter, N_("Invalid value '%s' in Adapter/@type attribute"), strTemp.c_str());
1950 }
1951
1952 pelmAdapter->getAttributeValue("enabled", nic.fEnabled);
1953 pelmAdapter->getAttributeValue("MACAddress", nic.strMACAddress);
1954 pelmAdapter->getAttributeValue("cable", nic.fCableConnected);
1955 pelmAdapter->getAttributeValue("speed", nic.ulLineSpeed);
1956
1957 if (pelmAdapter->getAttributeValue("promiscuousModePolicy", strTemp))
1958 {
1959 if (strTemp == "Deny")
1960 nic.enmPromiscModePolicy = NetworkAdapterPromiscModePolicy_Deny;
1961 else if (strTemp == "AllowNetwork")
1962 nic.enmPromiscModePolicy = NetworkAdapterPromiscModePolicy_AllowNetwork;
1963 else if (strTemp == "AllowAll")
1964 nic.enmPromiscModePolicy = NetworkAdapterPromiscModePolicy_AllowAll;
1965 else
1966 throw ConfigFileError(this, pelmAdapter,
1967 N_("Invalid value '%s' in Adapter/@promiscuousModePolicy attribute"), strTemp.c_str());
1968 }
1969
1970 pelmAdapter->getAttributeValue("trace", nic.fTraceEnabled);
1971 pelmAdapter->getAttributeValue("tracefile", nic.strTraceFile);
1972 pelmAdapter->getAttributeValue("bootPriority", nic.ulBootPriority);
1973 pelmAdapter->getAttributeValue("bandwidthGroup", nic.strBandwidthGroup);
1974
1975 xml::ElementNodesList llNetworkModes;
1976 pelmAdapter->getChildElements(llNetworkModes);
1977 xml::ElementNodesList::iterator it;
1978 /* We should have only active mode descriptor and disabled modes set */
1979 if (llNetworkModes.size() > 2)
1980 {
1981 throw ConfigFileError(this, pelmAdapter, N_("Invalid number of modes ('%d') attached to Adapter attribute"), llNetworkModes.size());
1982 }
1983 for (it = llNetworkModes.begin(); it != llNetworkModes.end(); ++it)
1984 {
1985 const xml::ElementNode *pelmNode = *it;
1986 if (pelmNode->nameEquals("DisabledModes"))
1987 {
1988 xml::ElementNodesList llDisabledNetworkModes;
1989 xml::ElementNodesList::iterator itDisabled;
1990 pelmNode->getChildElements(llDisabledNetworkModes);
1991 /* run over disabled list and load settings */
1992 for (itDisabled = llDisabledNetworkModes.begin();
1993 itDisabled != llDisabledNetworkModes.end(); ++itDisabled)
1994 {
1995 const xml::ElementNode *pelmDisabledNode = *itDisabled;
1996 readAttachedNetworkMode(*pelmDisabledNode, false, nic);
1997 }
1998 }
1999 else
2000 readAttachedNetworkMode(*pelmNode, true, nic);
2001 }
2002 // else: default is NetworkAttachmentType_Null
2003
2004 ll.push_back(nic);
2005 }
2006}
2007
2008void MachineConfigFile::readAttachedNetworkMode(const xml::ElementNode &elmMode, bool fEnabled, NetworkAdapter &nic)
2009{
2010 NetworkAttachmentType_T enmAttachmentType = NetworkAttachmentType_Null;
2011
2012 if (elmMode.nameEquals("NAT"))
2013 {
2014 enmAttachmentType = NetworkAttachmentType_NAT;
2015
2016 elmMode.getAttributeValue("hostip", nic.nat.strBindIP);
2017 elmMode.getAttributeValue("mtu", nic.nat.u32Mtu);
2018 elmMode.getAttributeValue("sockrcv", nic.nat.u32SockRcv);
2019 elmMode.getAttributeValue("socksnd", nic.nat.u32SockSnd);
2020 elmMode.getAttributeValue("tcprcv", nic.nat.u32TcpRcv);
2021 elmMode.getAttributeValue("tcpsnd", nic.nat.u32TcpSnd);
2022 const xml::ElementNode *pelmDNS;
2023 if ((pelmDNS = elmMode.findChildElement("DNS")))
2024 {
2025 pelmDNS->getAttributeValue("pass-domain", nic.nat.fDnsPassDomain);
2026 pelmDNS->getAttributeValue("use-proxy", nic.nat.fDnsProxy);
2027 pelmDNS->getAttributeValue("use-host-resolver", nic.nat.fDnsUseHostResolver);
2028 }
2029 const xml::ElementNode *pelmAlias;
2030 if ((pelmAlias = elmMode.findChildElement("Alias")))
2031 {
2032 pelmAlias->getAttributeValue("logging", nic.nat.fAliasLog);
2033 pelmAlias->getAttributeValue("proxy-only", nic.nat.fAliasProxyOnly);
2034 pelmAlias->getAttributeValue("use-same-ports", nic.nat.fAliasUseSamePorts);
2035 }
2036 const xml::ElementNode *pelmTFTP;
2037 if ((pelmTFTP = elmMode.findChildElement("TFTP")))
2038 {
2039 pelmTFTP->getAttributeValue("prefix", nic.nat.strTftpPrefix);
2040 pelmTFTP->getAttributeValue("boot-file", nic.nat.strTftpBootFile);
2041 pelmTFTP->getAttributeValue("next-server", nic.nat.strTftpNextServer);
2042 }
2043 xml::ElementNodesList plstNatPF;
2044 elmMode.getChildElements(plstNatPF, "Forwarding");
2045 for (xml::ElementNodesList::iterator pf = plstNatPF.begin(); pf != plstNatPF.end(); ++pf)
2046 {
2047 NATRule rule;
2048 uint32_t port = 0;
2049 (*pf)->getAttributeValue("name", rule.strName);
2050 (*pf)->getAttributeValue("proto", (uint32_t&)rule.proto);
2051 (*pf)->getAttributeValue("hostip", rule.strHostIP);
2052 (*pf)->getAttributeValue("hostport", port);
2053 rule.u16HostPort = port;
2054 (*pf)->getAttributeValue("guestip", rule.strGuestIP);
2055 (*pf)->getAttributeValue("guestport", port);
2056 rule.u16GuestPort = port;
2057 nic.nat.llRules.push_back(rule);
2058 }
2059 }
2060 else if ( (elmMode.nameEquals("HostInterface"))
2061 || (elmMode.nameEquals("BridgedInterface")))
2062 {
2063 enmAttachmentType = NetworkAttachmentType_Bridged;
2064
2065 elmMode.getAttributeValue("name", nic.strBridgedName); // optional bridged interface name
2066 }
2067 else if (elmMode.nameEquals("InternalNetwork"))
2068 {
2069 enmAttachmentType = NetworkAttachmentType_Internal;
2070
2071 if (!elmMode.getAttributeValue("name", nic.strInternalNetworkName)) // required network name
2072 throw ConfigFileError(this, &elmMode, N_("Required InternalNetwork/@name element is missing"));
2073 }
2074 else if (elmMode.nameEquals("HostOnlyInterface"))
2075 {
2076 enmAttachmentType = NetworkAttachmentType_HostOnly;
2077
2078 if (!elmMode.getAttributeValue("name", nic.strHostOnlyName)) // required network name
2079 throw ConfigFileError(this, &elmMode, N_("Required HostOnlyInterface/@name element is missing"));
2080 }
2081 else if (elmMode.nameEquals("GenericInterface"))
2082 {
2083 enmAttachmentType = NetworkAttachmentType_Generic;
2084
2085 elmMode.getAttributeValue("driver", nic.strGenericDriver); // optional network attachment driver
2086
2087 // get all properties
2088 xml::NodesLoop nl(elmMode);
2089 const xml::ElementNode *pelmModeChild;
2090 while ((pelmModeChild = nl.forAllNodes()))
2091 {
2092 if (pelmModeChild->nameEquals("Property"))
2093 {
2094 Utf8Str strPropName, strPropValue;
2095 if ( (pelmModeChild->getAttributeValue("name", strPropName))
2096 && (pelmModeChild->getAttributeValue("value", strPropValue))
2097 )
2098 nic.genericProperties[strPropName] = strPropValue;
2099 else
2100 throw ConfigFileError(this, pelmModeChild, N_("Required GenericInterface/Property/@name or @value attribute is missing"));
2101 }
2102 }
2103 }
2104 else if (elmMode.nameEquals("VDE"))
2105 {
2106 enmAttachmentType = NetworkAttachmentType_Generic;
2107
2108 com::Utf8Str strVDEName;
2109 elmMode.getAttributeValue("network", strVDEName); // optional network name
2110 nic.strGenericDriver = "VDE";
2111 nic.genericProperties["network"] = strVDEName;
2112 }
2113
2114 if (fEnabled && enmAttachmentType != NetworkAttachmentType_Null)
2115 nic.mode = enmAttachmentType;
2116}
2117
2118/**
2119 * Called from MachineConfigFile::readHardware() to read serial port information.
2120 * @param elmUART
2121 * @param ll
2122 */
2123void MachineConfigFile::readSerialPorts(const xml::ElementNode &elmUART,
2124 SerialPortsList &ll)
2125{
2126 xml::NodesLoop nl1(elmUART, "Port");
2127 const xml::ElementNode *pelmPort;
2128 while ((pelmPort = nl1.forAllNodes()))
2129 {
2130 SerialPort port;
2131 if (!pelmPort->getAttributeValue("slot", port.ulSlot))
2132 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@slot attribute is missing"));
2133
2134 // slot must be unique
2135 for (SerialPortsList::const_iterator it = ll.begin();
2136 it != ll.end();
2137 ++it)
2138 if ((*it).ulSlot == port.ulSlot)
2139 throw ConfigFileError(this, pelmPort, N_("Invalid value %RU32 in UART/Port/@slot attribute: value is not unique"), port.ulSlot);
2140
2141 if (!pelmPort->getAttributeValue("enabled", port.fEnabled))
2142 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@enabled attribute is missing"));
2143 if (!pelmPort->getAttributeValue("IOBase", port.ulIOBase))
2144 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@IOBase attribute is missing"));
2145 if (!pelmPort->getAttributeValue("IRQ", port.ulIRQ))
2146 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@IRQ attribute is missing"));
2147
2148 Utf8Str strPortMode;
2149 if (!pelmPort->getAttributeValue("hostMode", strPortMode))
2150 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@hostMode attribute is missing"));
2151 if (strPortMode == "RawFile")
2152 port.portMode = PortMode_RawFile;
2153 else if (strPortMode == "HostPipe")
2154 port.portMode = PortMode_HostPipe;
2155 else if (strPortMode == "HostDevice")
2156 port.portMode = PortMode_HostDevice;
2157 else if (strPortMode == "Disconnected")
2158 port.portMode = PortMode_Disconnected;
2159 else
2160 throw ConfigFileError(this, pelmPort, N_("Invalid value '%s' in UART/Port/@hostMode attribute"), strPortMode.c_str());
2161
2162 pelmPort->getAttributeValue("path", port.strPath);
2163 pelmPort->getAttributeValue("server", port.fServer);
2164
2165 ll.push_back(port);
2166 }
2167}
2168
2169/**
2170 * Called from MachineConfigFile::readHardware() to read parallel port information.
2171 * @param elmLPT
2172 * @param ll
2173 */
2174void MachineConfigFile::readParallelPorts(const xml::ElementNode &elmLPT,
2175 ParallelPortsList &ll)
2176{
2177 xml::NodesLoop nl1(elmLPT, "Port");
2178 const xml::ElementNode *pelmPort;
2179 while ((pelmPort = nl1.forAllNodes()))
2180 {
2181 ParallelPort port;
2182 if (!pelmPort->getAttributeValue("slot", port.ulSlot))
2183 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@slot attribute is missing"));
2184
2185 // slot must be unique
2186 for (ParallelPortsList::const_iterator it = ll.begin();
2187 it != ll.end();
2188 ++it)
2189 if ((*it).ulSlot == port.ulSlot)
2190 throw ConfigFileError(this, pelmPort, N_("Invalid value %RU32 in LPT/Port/@slot attribute: value is not unique"), port.ulSlot);
2191
2192 if (!pelmPort->getAttributeValue("enabled", port.fEnabled))
2193 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@enabled attribute is missing"));
2194 if (!pelmPort->getAttributeValue("IOBase", port.ulIOBase))
2195 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@IOBase attribute is missing"));
2196 if (!pelmPort->getAttributeValue("IRQ", port.ulIRQ))
2197 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@IRQ attribute is missing"));
2198
2199 pelmPort->getAttributeValue("path", port.strPath);
2200
2201 ll.push_back(port);
2202 }
2203}
2204
2205/**
2206 * Called from MachineConfigFile::readHardware() to read audio adapter information
2207 * and maybe fix driver information depending on the current host hardware.
2208 *
2209 * @param elmAudioAdapter "AudioAdapter" XML element.
2210 * @param hw
2211 */
2212void MachineConfigFile::readAudioAdapter(const xml::ElementNode &elmAudioAdapter,
2213 AudioAdapter &aa)
2214{
2215 elmAudioAdapter.getAttributeValue("enabled", aa.fEnabled);
2216
2217 Utf8Str strTemp;
2218 if (elmAudioAdapter.getAttributeValue("controller", strTemp))
2219 {
2220 if (strTemp == "SB16")
2221 aa.controllerType = AudioControllerType_SB16;
2222 else if (strTemp == "AC97")
2223 aa.controllerType = AudioControllerType_AC97;
2224 else if (strTemp == "HDA")
2225 aa.controllerType = AudioControllerType_HDA;
2226 else
2227 throw ConfigFileError(this, &elmAudioAdapter, N_("Invalid value '%s' in AudioAdapter/@controller attribute"), strTemp.c_str());
2228 }
2229
2230 if (elmAudioAdapter.getAttributeValue("driver", strTemp))
2231 {
2232 // settings before 1.3 used lower case so make sure this is case-insensitive
2233 strTemp.toUpper();
2234 if (strTemp == "NULL")
2235 aa.driverType = AudioDriverType_Null;
2236 else if (strTemp == "WINMM")
2237 aa.driverType = AudioDriverType_WinMM;
2238 else if ( (strTemp == "DIRECTSOUND") || (strTemp == "DSOUND") )
2239 aa.driverType = AudioDriverType_DirectSound;
2240 else if (strTemp == "SOLAUDIO")
2241 aa.driverType = AudioDriverType_SolAudio;
2242 else if (strTemp == "ALSA")
2243 aa.driverType = AudioDriverType_ALSA;
2244 else if (strTemp == "PULSE")
2245 aa.driverType = AudioDriverType_Pulse;
2246 else if (strTemp == "OSS")
2247 aa.driverType = AudioDriverType_OSS;
2248 else if (strTemp == "COREAUDIO")
2249 aa.driverType = AudioDriverType_CoreAudio;
2250 else if (strTemp == "MMPM")
2251 aa.driverType = AudioDriverType_MMPM;
2252 else
2253 throw ConfigFileError(this, &elmAudioAdapter, N_("Invalid value '%s' in AudioAdapter/@driver attribute"), strTemp.c_str());
2254
2255 // now check if this is actually supported on the current host platform;
2256 // people might be opening a file created on a Windows host, and that
2257 // VM should still start on a Linux host
2258 if (!isAudioDriverAllowedOnThisHost(aa.driverType))
2259 aa.driverType = getHostDefaultAudioDriver();
2260 }
2261}
2262
2263/**
2264 * Called from MachineConfigFile::readHardware() to read guest property information.
2265 * @param elmGuestProperties
2266 * @param hw
2267 */
2268void MachineConfigFile::readGuestProperties(const xml::ElementNode &elmGuestProperties,
2269 Hardware &hw)
2270{
2271 xml::NodesLoop nl1(elmGuestProperties, "GuestProperty");
2272 const xml::ElementNode *pelmProp;
2273 while ((pelmProp = nl1.forAllNodes()))
2274 {
2275 GuestProperty prop;
2276 pelmProp->getAttributeValue("name", prop.strName);
2277 pelmProp->getAttributeValue("value", prop.strValue);
2278
2279 pelmProp->getAttributeValue("timestamp", prop.timestamp);
2280 pelmProp->getAttributeValue("flags", prop.strFlags);
2281 hw.llGuestProperties.push_back(prop);
2282 }
2283
2284 elmGuestProperties.getAttributeValue("notificationPatterns", hw.strNotificationPatterns);
2285}
2286
2287/**
2288 * Helper function to read attributes that are common to <SATAController> (pre-1.7)
2289 * and <StorageController>.
2290 * @param elmStorageController
2291 * @param strg
2292 */
2293void MachineConfigFile::readStorageControllerAttributes(const xml::ElementNode &elmStorageController,
2294 StorageController &sctl)
2295{
2296 elmStorageController.getAttributeValue("PortCount", sctl.ulPortCount);
2297 elmStorageController.getAttributeValue("IDE0MasterEmulationPort", sctl.lIDE0MasterEmulationPort);
2298 elmStorageController.getAttributeValue("IDE0SlaveEmulationPort", sctl.lIDE0SlaveEmulationPort);
2299 elmStorageController.getAttributeValue("IDE1MasterEmulationPort", sctl.lIDE1MasterEmulationPort);
2300 elmStorageController.getAttributeValue("IDE1SlaveEmulationPort", sctl.lIDE1SlaveEmulationPort);
2301
2302 elmStorageController.getAttributeValue("useHostIOCache", sctl.fUseHostIOCache);
2303}
2304
2305/**
2306 * Reads in a <Hardware> block and stores it in the given structure. Used
2307 * both directly from readMachine and from readSnapshot, since snapshots
2308 * have their own hardware sections.
2309 *
2310 * For legacy pre-1.7 settings we also need a storage structure because
2311 * the IDE and SATA controllers used to be defined under <Hardware>.
2312 *
2313 * @param elmHardware
2314 * @param hw
2315 */
2316void MachineConfigFile::readHardware(const xml::ElementNode &elmHardware,
2317 Hardware &hw,
2318 Storage &strg)
2319{
2320 if (!elmHardware.getAttributeValue("version", hw.strVersion))
2321 {
2322 /* KLUDGE ALERT! For a while during the 3.1 development this was not
2323 written because it was thought to have a default value of "2". For
2324 sv <= 1.3 it defaults to "1" because the attribute didn't exist,
2325 while for 1.4+ it is sort of mandatory. Now, the buggy XML writer
2326 code only wrote 1.7 and later. So, if it's a 1.7+ XML file and it's
2327 missing the hardware version, then it probably should be "2" instead
2328 of "1". */
2329 if (m->sv < SettingsVersion_v1_7)
2330 hw.strVersion = "1";
2331 else
2332 hw.strVersion = "2";
2333 }
2334 Utf8Str strUUID;
2335 if (elmHardware.getAttributeValue("uuid", strUUID))
2336 parseUUID(hw.uuid, strUUID);
2337
2338 xml::NodesLoop nl1(elmHardware);
2339 const xml::ElementNode *pelmHwChild;
2340 while ((pelmHwChild = nl1.forAllNodes()))
2341 {
2342 if (pelmHwChild->nameEquals("CPU"))
2343 {
2344 if (!pelmHwChild->getAttributeValue("count", hw.cCPUs))
2345 {
2346 // pre-1.5 variant; not sure if this actually exists in the wild anywhere
2347 const xml::ElementNode *pelmCPUChild;
2348 if ((pelmCPUChild = pelmHwChild->findChildElement("CPUCount")))
2349 pelmCPUChild->getAttributeValue("count", hw.cCPUs);
2350 }
2351
2352 pelmHwChild->getAttributeValue("hotplug", hw.fCpuHotPlug);
2353 pelmHwChild->getAttributeValue("executionCap", hw.ulCpuExecutionCap);
2354
2355 const xml::ElementNode *pelmCPUChild;
2356 if (hw.fCpuHotPlug)
2357 {
2358 if ((pelmCPUChild = pelmHwChild->findChildElement("CpuTree")))
2359 readCpuTree(*pelmCPUChild, hw.llCpus);
2360 }
2361
2362 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtEx")))
2363 {
2364 pelmCPUChild->getAttributeValue("enabled", hw.fHardwareVirt);
2365 pelmCPUChild->getAttributeValue("exclusive", hw.fHardwareVirtExclusive); // settings version 1.9
2366 }
2367 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExNestedPaging")))
2368 pelmCPUChild->getAttributeValue("enabled", hw.fNestedPaging);
2369 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExLargePages")))
2370 pelmCPUChild->getAttributeValue("enabled", hw.fLargePages);
2371 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExVPID")))
2372 pelmCPUChild->getAttributeValue("enabled", hw.fVPID);
2373 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtForce")))
2374 pelmCPUChild->getAttributeValue("enabled", hw.fHardwareVirtForce);
2375
2376 if (!(pelmCPUChild = pelmHwChild->findChildElement("PAE")))
2377 {
2378 /* The default for pre 3.1 was false, so we must respect that. */
2379 if (m->sv < SettingsVersion_v1_9)
2380 hw.fPAE = false;
2381 }
2382 else
2383 pelmCPUChild->getAttributeValue("enabled", hw.fPAE);
2384
2385 if ((pelmCPUChild = pelmHwChild->findChildElement("SyntheticCpu")))
2386 pelmCPUChild->getAttributeValue("enabled", hw.fSyntheticCpu);
2387 if ((pelmCPUChild = pelmHwChild->findChildElement("CpuIdTree")))
2388 readCpuIdTree(*pelmCPUChild, hw.llCpuIdLeafs);
2389 }
2390 else if (pelmHwChild->nameEquals("Memory"))
2391 {
2392 pelmHwChild->getAttributeValue("RAMSize", hw.ulMemorySizeMB);
2393 pelmHwChild->getAttributeValue("PageFusion", hw.fPageFusionEnabled);
2394 }
2395 else if (pelmHwChild->nameEquals("Firmware"))
2396 {
2397 Utf8Str strFirmwareType;
2398 if (pelmHwChild->getAttributeValue("type", strFirmwareType))
2399 {
2400 if ( (strFirmwareType == "BIOS")
2401 || (strFirmwareType == "1") // some trunk builds used the number here
2402 )
2403 hw.firmwareType = FirmwareType_BIOS;
2404 else if ( (strFirmwareType == "EFI")
2405 || (strFirmwareType == "2") // some trunk builds used the number here
2406 )
2407 hw.firmwareType = FirmwareType_EFI;
2408 else if ( strFirmwareType == "EFI32")
2409 hw.firmwareType = FirmwareType_EFI32;
2410 else if ( strFirmwareType == "EFI64")
2411 hw.firmwareType = FirmwareType_EFI64;
2412 else if ( strFirmwareType == "EFIDUAL")
2413 hw.firmwareType = FirmwareType_EFIDUAL;
2414 else
2415 throw ConfigFileError(this,
2416 pelmHwChild,
2417 N_("Invalid value '%s' in Firmware/@type"),
2418 strFirmwareType.c_str());
2419 }
2420 }
2421 else if (pelmHwChild->nameEquals("HID"))
2422 {
2423 Utf8Str strHidType;
2424 if (pelmHwChild->getAttributeValue("Keyboard", strHidType))
2425 {
2426 if (strHidType == "None")
2427 hw.keyboardHidType = KeyboardHidType_None;
2428 else if (strHidType == "USBKeyboard")
2429 hw.keyboardHidType = KeyboardHidType_USBKeyboard;
2430 else if (strHidType == "PS2Keyboard")
2431 hw.keyboardHidType = KeyboardHidType_PS2Keyboard;
2432 else if (strHidType == "ComboKeyboard")
2433 hw.keyboardHidType = KeyboardHidType_ComboKeyboard;
2434 else
2435 throw ConfigFileError(this,
2436 pelmHwChild,
2437 N_("Invalid value '%s' in HID/Keyboard/@type"),
2438 strHidType.c_str());
2439 }
2440 if (pelmHwChild->getAttributeValue("Pointing", strHidType))
2441 {
2442 if (strHidType == "None")
2443 hw.pointingHidType = PointingHidType_None;
2444 else if (strHidType == "USBMouse")
2445 hw.pointingHidType = PointingHidType_USBMouse;
2446 else if (strHidType == "USBTablet")
2447 hw.pointingHidType = PointingHidType_USBTablet;
2448 else if (strHidType == "PS2Mouse")
2449 hw.pointingHidType = PointingHidType_PS2Mouse;
2450 else if (strHidType == "ComboMouse")
2451 hw.pointingHidType = PointingHidType_ComboMouse;
2452 else
2453 throw ConfigFileError(this,
2454 pelmHwChild,
2455 N_("Invalid value '%s' in HID/Pointing/@type"),
2456 strHidType.c_str());
2457 }
2458 }
2459 else if (pelmHwChild->nameEquals("Chipset"))
2460 {
2461 Utf8Str strChipsetType;
2462 if (pelmHwChild->getAttributeValue("type", strChipsetType))
2463 {
2464 if (strChipsetType == "PIIX3")
2465 hw.chipsetType = ChipsetType_PIIX3;
2466 else if (strChipsetType == "ICH9")
2467 hw.chipsetType = ChipsetType_ICH9;
2468 else
2469 throw ConfigFileError(this,
2470 pelmHwChild,
2471 N_("Invalid value '%s' in Chipset/@type"),
2472 strChipsetType.c_str());
2473 }
2474 }
2475 else if (pelmHwChild->nameEquals("HPET"))
2476 {
2477 pelmHwChild->getAttributeValue("enabled", hw.fHpetEnabled);
2478 }
2479 else if (pelmHwChild->nameEquals("Boot"))
2480 {
2481 hw.mapBootOrder.clear();
2482
2483 xml::NodesLoop nl2(*pelmHwChild, "Order");
2484 const xml::ElementNode *pelmOrder;
2485 while ((pelmOrder = nl2.forAllNodes()))
2486 {
2487 uint32_t ulPos;
2488 Utf8Str strDevice;
2489 if (!pelmOrder->getAttributeValue("position", ulPos))
2490 throw ConfigFileError(this, pelmOrder, N_("Required Boot/Order/@position attribute is missing"));
2491
2492 if ( ulPos < 1
2493 || ulPos > SchemaDefs::MaxBootPosition
2494 )
2495 throw ConfigFileError(this,
2496 pelmOrder,
2497 N_("Invalid value '%RU32' in Boot/Order/@position: must be greater than 0 and less than %RU32"),
2498 ulPos,
2499 SchemaDefs::MaxBootPosition + 1);
2500 // XML is 1-based but internal data is 0-based
2501 --ulPos;
2502
2503 if (hw.mapBootOrder.find(ulPos) != hw.mapBootOrder.end())
2504 throw ConfigFileError(this, pelmOrder, N_("Invalid value '%RU32' in Boot/Order/@position: value is not unique"), ulPos);
2505
2506 if (!pelmOrder->getAttributeValue("device", strDevice))
2507 throw ConfigFileError(this, pelmOrder, N_("Required Boot/Order/@device attribute is missing"));
2508
2509 DeviceType_T type;
2510 if (strDevice == "None")
2511 type = DeviceType_Null;
2512 else if (strDevice == "Floppy")
2513 type = DeviceType_Floppy;
2514 else if (strDevice == "DVD")
2515 type = DeviceType_DVD;
2516 else if (strDevice == "HardDisk")
2517 type = DeviceType_HardDisk;
2518 else if (strDevice == "Network")
2519 type = DeviceType_Network;
2520 else
2521 throw ConfigFileError(this, pelmOrder, N_("Invalid value '%s' in Boot/Order/@device attribute"), strDevice.c_str());
2522 hw.mapBootOrder[ulPos] = type;
2523 }
2524 }
2525 else if (pelmHwChild->nameEquals("Display"))
2526 {
2527 pelmHwChild->getAttributeValue("VRAMSize", hw.ulVRAMSizeMB);
2528 if (!pelmHwChild->getAttributeValue("monitorCount", hw.cMonitors))
2529 pelmHwChild->getAttributeValue("MonitorCount", hw.cMonitors); // pre-v1.5 variant
2530 if (!pelmHwChild->getAttributeValue("accelerate3D", hw.fAccelerate3D))
2531 pelmHwChild->getAttributeValue("Accelerate3D", hw.fAccelerate3D); // pre-v1.5 variant
2532 pelmHwChild->getAttributeValue("accelerate2DVideo", hw.fAccelerate2DVideo);
2533 }
2534 else if (pelmHwChild->nameEquals("RemoteDisplay"))
2535 {
2536 pelmHwChild->getAttributeValue("enabled", hw.vrdeSettings.fEnabled);
2537
2538 Utf8Str str;
2539 if (pelmHwChild->getAttributeValue("port", str))
2540 hw.vrdeSettings.mapProperties["TCP/Ports"] = str;
2541 if (pelmHwChild->getAttributeValue("netAddress", str))
2542 hw.vrdeSettings.mapProperties["TCP/Address"] = str;
2543
2544 Utf8Str strAuthType;
2545 if (pelmHwChild->getAttributeValue("authType", strAuthType))
2546 {
2547 // settings before 1.3 used lower case so make sure this is case-insensitive
2548 strAuthType.toUpper();
2549 if (strAuthType == "NULL")
2550 hw.vrdeSettings.authType = AuthType_Null;
2551 else if (strAuthType == "GUEST")
2552 hw.vrdeSettings.authType = AuthType_Guest;
2553 else if (strAuthType == "EXTERNAL")
2554 hw.vrdeSettings.authType = AuthType_External;
2555 else
2556 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in RemoteDisplay/@authType attribute"), strAuthType.c_str());
2557 }
2558
2559 pelmHwChild->getAttributeValue("authLibrary", hw.vrdeSettings.strAuthLibrary);
2560 pelmHwChild->getAttributeValue("authTimeout", hw.vrdeSettings.ulAuthTimeout);
2561 pelmHwChild->getAttributeValue("allowMultiConnection", hw.vrdeSettings.fAllowMultiConnection);
2562 pelmHwChild->getAttributeValue("reuseSingleConnection", hw.vrdeSettings.fReuseSingleConnection);
2563
2564 /* 3.2 and 4.0 betas, 4.0 has this information in VRDEProperties. */
2565 const xml::ElementNode *pelmVideoChannel;
2566 if ((pelmVideoChannel = pelmHwChild->findChildElement("VideoChannel")))
2567 {
2568 bool fVideoChannel = false;
2569 pelmVideoChannel->getAttributeValue("enabled", fVideoChannel);
2570 hw.vrdeSettings.mapProperties["VideoChannel/Enabled"] = fVideoChannel? "true": "false";
2571
2572 uint32_t ulVideoChannelQuality = 75;
2573 pelmVideoChannel->getAttributeValue("quality", ulVideoChannelQuality);
2574 ulVideoChannelQuality = RT_CLAMP(ulVideoChannelQuality, 10, 100);
2575 char *pszBuffer = NULL;
2576 if (RTStrAPrintf(&pszBuffer, "%d", ulVideoChannelQuality) >= 0)
2577 {
2578 hw.vrdeSettings.mapProperties["VideoChannel/Quality"] = pszBuffer;
2579 RTStrFree(pszBuffer);
2580 }
2581 else
2582 hw.vrdeSettings.mapProperties["VideoChannel/Quality"] = "75";
2583 }
2584 pelmHwChild->getAttributeValue("VRDEExtPack", hw.vrdeSettings.strVrdeExtPack);
2585
2586 const xml::ElementNode *pelmProperties = pelmHwChild->findChildElement("VRDEProperties");
2587 if (pelmProperties != NULL)
2588 {
2589 xml::NodesLoop nl(*pelmProperties);
2590 const xml::ElementNode *pelmProperty;
2591 while ((pelmProperty = nl.forAllNodes()))
2592 {
2593 if (pelmProperty->nameEquals("Property"))
2594 {
2595 /* <Property name="TCP/Ports" value="3000-3002"/> */
2596 Utf8Str strName, strValue;
2597 if ( ((pelmProperty->getAttributeValue("name", strName)))
2598 && ((pelmProperty->getAttributeValue("value", strValue)))
2599 )
2600 hw.vrdeSettings.mapProperties[strName] = strValue;
2601 else
2602 throw ConfigFileError(this, pelmProperty, N_("Required VRDE Property/@name or @value attribute is missing"));
2603 }
2604 }
2605 }
2606 }
2607 else if (pelmHwChild->nameEquals("BIOS"))
2608 {
2609 const xml::ElementNode *pelmBIOSChild;
2610 if ((pelmBIOSChild = pelmHwChild->findChildElement("ACPI")))
2611 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fACPIEnabled);
2612 if ((pelmBIOSChild = pelmHwChild->findChildElement("IOAPIC")))
2613 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fIOAPICEnabled);
2614 if ((pelmBIOSChild = pelmHwChild->findChildElement("Logo")))
2615 {
2616 pelmBIOSChild->getAttributeValue("fadeIn", hw.biosSettings.fLogoFadeIn);
2617 pelmBIOSChild->getAttributeValue("fadeOut", hw.biosSettings.fLogoFadeOut);
2618 pelmBIOSChild->getAttributeValue("displayTime", hw.biosSettings.ulLogoDisplayTime);
2619 pelmBIOSChild->getAttributeValue("imagePath", hw.biosSettings.strLogoImagePath);
2620 }
2621 if ((pelmBIOSChild = pelmHwChild->findChildElement("BootMenu")))
2622 {
2623 Utf8Str strBootMenuMode;
2624 if (pelmBIOSChild->getAttributeValue("mode", strBootMenuMode))
2625 {
2626 // settings before 1.3 used lower case so make sure this is case-insensitive
2627 strBootMenuMode.toUpper();
2628 if (strBootMenuMode == "DISABLED")
2629 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_Disabled;
2630 else if (strBootMenuMode == "MENUONLY")
2631 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_MenuOnly;
2632 else if (strBootMenuMode == "MESSAGEANDMENU")
2633 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_MessageAndMenu;
2634 else
2635 throw ConfigFileError(this, pelmBIOSChild, N_("Invalid value '%s' in BootMenu/@mode attribute"), strBootMenuMode.c_str());
2636 }
2637 }
2638 if ((pelmBIOSChild = pelmHwChild->findChildElement("PXEDebug")))
2639 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fPXEDebugEnabled);
2640 if ((pelmBIOSChild = pelmHwChild->findChildElement("TimeOffset")))
2641 pelmBIOSChild->getAttributeValue("value", hw.biosSettings.llTimeOffset);
2642
2643 // legacy BIOS/IDEController (pre 1.7)
2644 if ( (m->sv < SettingsVersion_v1_7)
2645 && ((pelmBIOSChild = pelmHwChild->findChildElement("IDEController")))
2646 )
2647 {
2648 StorageController sctl;
2649 sctl.strName = "IDE Controller";
2650 sctl.storageBus = StorageBus_IDE;
2651
2652 Utf8Str strType;
2653 if (pelmBIOSChild->getAttributeValue("type", strType))
2654 {
2655 if (strType == "PIIX3")
2656 sctl.controllerType = StorageControllerType_PIIX3;
2657 else if (strType == "PIIX4")
2658 sctl.controllerType = StorageControllerType_PIIX4;
2659 else if (strType == "ICH6")
2660 sctl.controllerType = StorageControllerType_ICH6;
2661 else
2662 throw ConfigFileError(this, pelmBIOSChild, N_("Invalid value '%s' for IDEController/@type attribute"), strType.c_str());
2663 }
2664 sctl.ulPortCount = 2;
2665 strg.llStorageControllers.push_back(sctl);
2666 }
2667 }
2668 else if (pelmHwChild->nameEquals("USBController"))
2669 {
2670 pelmHwChild->getAttributeValue("enabled", hw.usbController.fEnabled);
2671 pelmHwChild->getAttributeValue("enabledEhci", hw.usbController.fEnabledEHCI);
2672
2673 readUSBDeviceFilters(*pelmHwChild,
2674 hw.usbController.llDeviceFilters);
2675 }
2676 else if ( (m->sv < SettingsVersion_v1_7)
2677 && (pelmHwChild->nameEquals("SATAController"))
2678 )
2679 {
2680 bool f;
2681 if ( (pelmHwChild->getAttributeValue("enabled", f))
2682 && (f)
2683 )
2684 {
2685 StorageController sctl;
2686 sctl.strName = "SATA Controller";
2687 sctl.storageBus = StorageBus_SATA;
2688 sctl.controllerType = StorageControllerType_IntelAhci;
2689
2690 readStorageControllerAttributes(*pelmHwChild, sctl);
2691
2692 strg.llStorageControllers.push_back(sctl);
2693 }
2694 }
2695 else if (pelmHwChild->nameEquals("Network"))
2696 readNetworkAdapters(*pelmHwChild, hw.llNetworkAdapters);
2697 else if (pelmHwChild->nameEquals("RTC"))
2698 {
2699 Utf8Str strLocalOrUTC;
2700 machineUserData.fRTCUseUTC = pelmHwChild->getAttributeValue("localOrUTC", strLocalOrUTC)
2701 && strLocalOrUTC == "UTC";
2702 }
2703 else if ( (pelmHwChild->nameEquals("UART"))
2704 || (pelmHwChild->nameEquals("Uart")) // used before 1.3
2705 )
2706 readSerialPorts(*pelmHwChild, hw.llSerialPorts);
2707 else if ( (pelmHwChild->nameEquals("LPT"))
2708 || (pelmHwChild->nameEquals("Lpt")) // used before 1.3
2709 )
2710 readParallelPorts(*pelmHwChild, hw.llParallelPorts);
2711 else if (pelmHwChild->nameEquals("AudioAdapter"))
2712 readAudioAdapter(*pelmHwChild, hw.audioAdapter);
2713 else if (pelmHwChild->nameEquals("SharedFolders"))
2714 {
2715 xml::NodesLoop nl2(*pelmHwChild, "SharedFolder");
2716 const xml::ElementNode *pelmFolder;
2717 while ((pelmFolder = nl2.forAllNodes()))
2718 {
2719 SharedFolder sf;
2720 pelmFolder->getAttributeValue("name", sf.strName);
2721 pelmFolder->getAttributeValue("hostPath", sf.strHostPath);
2722 pelmFolder->getAttributeValue("writable", sf.fWritable);
2723 pelmFolder->getAttributeValue("autoMount", sf.fAutoMount);
2724 hw.llSharedFolders.push_back(sf);
2725 }
2726 }
2727 else if (pelmHwChild->nameEquals("Clipboard"))
2728 {
2729 Utf8Str strTemp;
2730 if (pelmHwChild->getAttributeValue("mode", strTemp))
2731 {
2732 if (strTemp == "Disabled")
2733 hw.clipboardMode = ClipboardMode_Disabled;
2734 else if (strTemp == "HostToGuest")
2735 hw.clipboardMode = ClipboardMode_HostToGuest;
2736 else if (strTemp == "GuestToHost")
2737 hw.clipboardMode = ClipboardMode_GuestToHost;
2738 else if (strTemp == "Bidirectional")
2739 hw.clipboardMode = ClipboardMode_Bidirectional;
2740 else
2741 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in Clipboard/@mode attribute"), strTemp.c_str());
2742 }
2743 }
2744 else if (pelmHwChild->nameEquals("Guest"))
2745 {
2746 if (!pelmHwChild->getAttributeValue("memoryBalloonSize", hw.ulMemoryBalloonSize))
2747 pelmHwChild->getAttributeValue("MemoryBalloonSize", hw.ulMemoryBalloonSize); // used before 1.3
2748 }
2749 else if (pelmHwChild->nameEquals("GuestProperties"))
2750 readGuestProperties(*pelmHwChild, hw);
2751 else if (pelmHwChild->nameEquals("IO"))
2752 {
2753 const xml::ElementNode *pelmBwGroups;
2754 const xml::ElementNode *pelmIoChild;
2755
2756 if ((pelmIoChild = pelmHwChild->findChildElement("IoCache")))
2757 {
2758 pelmIoChild->getAttributeValue("enabled", hw.ioSettings.fIoCacheEnabled);
2759 pelmIoChild->getAttributeValue("size", hw.ioSettings.ulIoCacheSize);
2760 }
2761
2762 if ((pelmBwGroups = pelmHwChild->findChildElement("BandwidthGroups")))
2763 {
2764 xml::NodesLoop nl2(*pelmBwGroups, "BandwidthGroup");
2765 const xml::ElementNode *pelmBandwidthGroup;
2766 while ((pelmBandwidthGroup = nl2.forAllNodes()))
2767 {
2768 BandwidthGroup gr;
2769 Utf8Str strTemp;
2770
2771 pelmBandwidthGroup->getAttributeValue("name", gr.strName);
2772
2773 if (pelmBandwidthGroup->getAttributeValue("type", strTemp))
2774 {
2775 if (strTemp == "Disk")
2776 gr.enmType = BandwidthGroupType_Disk;
2777 else if (strTemp == "Network")
2778 gr.enmType = BandwidthGroupType_Network;
2779 else
2780 throw ConfigFileError(this, pelmBandwidthGroup, N_("Invalid value '%s' in BandwidthGroup/@type attribute"), strTemp.c_str());
2781 }
2782 else
2783 throw ConfigFileError(this, pelmBandwidthGroup, N_("Missing BandwidthGroup/@type attribute"));
2784
2785 pelmBandwidthGroup->getAttributeValue("maxMbPerSec", gr.cMaxMbPerSec);
2786 hw.ioSettings.llBandwidthGroups.push_back(gr);
2787 }
2788 }
2789 } else if (pelmHwChild->nameEquals("HostPci")) {
2790 const xml::ElementNode *pelmDevices;
2791
2792 if ((pelmDevices = pelmHwChild->findChildElement("Devices")))
2793 {
2794 xml::NodesLoop nl2(*pelmDevices, "Device");
2795 const xml::ElementNode *pelmDevice;
2796 while ((pelmDevice = nl2.forAllNodes()))
2797 {
2798 HostPciDeviceAttachment hpda;
2799
2800 if (!pelmDevice->getAttributeValue("host", hpda.uHostAddress))
2801 throw ConfigFileError(this, pelmDevice, N_("Missing Device/@host attribute"));
2802
2803 if (!pelmDevice->getAttributeValue("guest", hpda.uGuestAddress))
2804 throw ConfigFileError(this, pelmDevice, N_("Missing Device/@guest attribute"));
2805
2806 /* name is optional */
2807 pelmDevice->getAttributeValue("name", hpda.strDeviceName);
2808
2809 hw.pciAttachments.push_back(hpda);
2810 }
2811 }
2812 }
2813 }
2814
2815 if (hw.ulMemorySizeMB == (uint32_t)-1)
2816 throw ConfigFileError(this, &elmHardware, N_("Required Memory/@RAMSize element/attribute is missing"));
2817}
2818
2819/**
2820 * This gets called instead of readStorageControllers() for legacy pre-1.7 settings
2821 * files which have a <HardDiskAttachments> node and storage controller settings
2822 * hidden in the <Hardware> settings. We set the StorageControllers fields just the
2823 * same, just from different sources.
2824 * @param elmHardware <Hardware> XML node.
2825 * @param elmHardDiskAttachments <HardDiskAttachments> XML node.
2826 * @param strg
2827 */
2828void MachineConfigFile::readHardDiskAttachments_pre1_7(const xml::ElementNode &elmHardDiskAttachments,
2829 Storage &strg)
2830{
2831 StorageController *pIDEController = NULL;
2832 StorageController *pSATAController = NULL;
2833
2834 for (StorageControllersList::iterator it = strg.llStorageControllers.begin();
2835 it != strg.llStorageControllers.end();
2836 ++it)
2837 {
2838 StorageController &s = *it;
2839 if (s.storageBus == StorageBus_IDE)
2840 pIDEController = &s;
2841 else if (s.storageBus == StorageBus_SATA)
2842 pSATAController = &s;
2843 }
2844
2845 xml::NodesLoop nl1(elmHardDiskAttachments, "HardDiskAttachment");
2846 const xml::ElementNode *pelmAttachment;
2847 while ((pelmAttachment = nl1.forAllNodes()))
2848 {
2849 AttachedDevice att;
2850 Utf8Str strUUID, strBus;
2851
2852 if (!pelmAttachment->getAttributeValue("hardDisk", strUUID))
2853 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@hardDisk attribute is missing"));
2854 parseUUID(att.uuid, strUUID);
2855
2856 if (!pelmAttachment->getAttributeValue("bus", strBus))
2857 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@bus attribute is missing"));
2858 // pre-1.7 'channel' is now port
2859 if (!pelmAttachment->getAttributeValue("channel", att.lPort))
2860 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@channel attribute is missing"));
2861 // pre-1.7 'device' is still device
2862 if (!pelmAttachment->getAttributeValue("device", att.lDevice))
2863 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@device attribute is missing"));
2864
2865 att.deviceType = DeviceType_HardDisk;
2866
2867 if (strBus == "IDE")
2868 {
2869 if (!pIDEController)
2870 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus is 'IDE' but cannot find IDE controller"));
2871 pIDEController->llAttachedDevices.push_back(att);
2872 }
2873 else if (strBus == "SATA")
2874 {
2875 if (!pSATAController)
2876 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus is 'SATA' but cannot find SATA controller"));
2877 pSATAController->llAttachedDevices.push_back(att);
2878 }
2879 else
2880 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus attribute has illegal value '%s'"), strBus.c_str());
2881 }
2882}
2883
2884/**
2885 * Reads in a <StorageControllers> block and stores it in the given Storage structure.
2886 * Used both directly from readMachine and from readSnapshot, since snapshots
2887 * have their own storage controllers sections.
2888 *
2889 * This is only called for settings version 1.7 and above; see readHardDiskAttachments_pre1_7()
2890 * for earlier versions.
2891 *
2892 * @param elmStorageControllers
2893 */
2894void MachineConfigFile::readStorageControllers(const xml::ElementNode &elmStorageControllers,
2895 Storage &strg)
2896{
2897 xml::NodesLoop nlStorageControllers(elmStorageControllers, "StorageController");
2898 const xml::ElementNode *pelmController;
2899 while ((pelmController = nlStorageControllers.forAllNodes()))
2900 {
2901 StorageController sctl;
2902
2903 if (!pelmController->getAttributeValue("name", sctl.strName))
2904 throw ConfigFileError(this, pelmController, N_("Required StorageController/@name attribute is missing"));
2905 // canonicalize storage controller names for configs in the switchover
2906 // period.
2907 if (m->sv < SettingsVersion_v1_9)
2908 {
2909 if (sctl.strName == "IDE")
2910 sctl.strName = "IDE Controller";
2911 else if (sctl.strName == "SATA")
2912 sctl.strName = "SATA Controller";
2913 else if (sctl.strName == "SCSI")
2914 sctl.strName = "SCSI Controller";
2915 }
2916
2917 pelmController->getAttributeValue("Instance", sctl.ulInstance);
2918 // default from constructor is 0
2919
2920 pelmController->getAttributeValue("Bootable", sctl.fBootable);
2921 // default from constructor is true which is true
2922 // for settings below version 1.11 because they allowed only
2923 // one controller per type.
2924
2925 Utf8Str strType;
2926 if (!pelmController->getAttributeValue("type", strType))
2927 throw ConfigFileError(this, pelmController, N_("Required StorageController/@type attribute is missing"));
2928
2929 if (strType == "AHCI")
2930 {
2931 sctl.storageBus = StorageBus_SATA;
2932 sctl.controllerType = StorageControllerType_IntelAhci;
2933 }
2934 else if (strType == "LsiLogic")
2935 {
2936 sctl.storageBus = StorageBus_SCSI;
2937 sctl.controllerType = StorageControllerType_LsiLogic;
2938 }
2939 else if (strType == "BusLogic")
2940 {
2941 sctl.storageBus = StorageBus_SCSI;
2942 sctl.controllerType = StorageControllerType_BusLogic;
2943 }
2944 else if (strType == "PIIX3")
2945 {
2946 sctl.storageBus = StorageBus_IDE;
2947 sctl.controllerType = StorageControllerType_PIIX3;
2948 }
2949 else if (strType == "PIIX4")
2950 {
2951 sctl.storageBus = StorageBus_IDE;
2952 sctl.controllerType = StorageControllerType_PIIX4;
2953 }
2954 else if (strType == "ICH6")
2955 {
2956 sctl.storageBus = StorageBus_IDE;
2957 sctl.controllerType = StorageControllerType_ICH6;
2958 }
2959 else if ( (m->sv >= SettingsVersion_v1_9)
2960 && (strType == "I82078")
2961 )
2962 {
2963 sctl.storageBus = StorageBus_Floppy;
2964 sctl.controllerType = StorageControllerType_I82078;
2965 }
2966 else if (strType == "LsiLogicSas")
2967 {
2968 sctl.storageBus = StorageBus_SAS;
2969 sctl.controllerType = StorageControllerType_LsiLogicSas;
2970 }
2971 else
2972 throw ConfigFileError(this, pelmController, N_("Invalid value '%s' for StorageController/@type attribute"), strType.c_str());
2973
2974 readStorageControllerAttributes(*pelmController, sctl);
2975
2976 xml::NodesLoop nlAttached(*pelmController, "AttachedDevice");
2977 const xml::ElementNode *pelmAttached;
2978 while ((pelmAttached = nlAttached.forAllNodes()))
2979 {
2980 AttachedDevice att;
2981 Utf8Str strTemp;
2982 pelmAttached->getAttributeValue("type", strTemp);
2983
2984 if (strTemp == "HardDisk")
2985 att.deviceType = DeviceType_HardDisk;
2986 else if (m->sv >= SettingsVersion_v1_9)
2987 {
2988 // starting with 1.9 we list DVD and floppy drive info + attachments under <StorageControllers>
2989 if (strTemp == "DVD")
2990 {
2991 att.deviceType = DeviceType_DVD;
2992 pelmAttached->getAttributeValue("passthrough", att.fPassThrough);
2993 }
2994 else if (strTemp == "Floppy")
2995 att.deviceType = DeviceType_Floppy;
2996 }
2997
2998 if (att.deviceType != DeviceType_Null)
2999 {
3000 const xml::ElementNode *pelmImage;
3001 // all types can have images attached, but for HardDisk it's required
3002 if (!(pelmImage = pelmAttached->findChildElement("Image")))
3003 {
3004 if (att.deviceType == DeviceType_HardDisk)
3005 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/Image element is missing"));
3006 else
3007 {
3008 // DVDs and floppies can also have <HostDrive> instead of <Image>
3009 const xml::ElementNode *pelmHostDrive;
3010 if ((pelmHostDrive = pelmAttached->findChildElement("HostDrive")))
3011 if (!pelmHostDrive->getAttributeValue("src", att.strHostDriveSrc))
3012 throw ConfigFileError(this, pelmHostDrive, N_("Required AttachedDevice/HostDrive/@src attribute is missing"));
3013 }
3014 }
3015 else
3016 {
3017 if (!pelmImage->getAttributeValue("uuid", strTemp))
3018 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/Image/@uuid attribute is missing"));
3019 parseUUID(att.uuid, strTemp);
3020 }
3021
3022 if (!pelmAttached->getAttributeValue("port", att.lPort))
3023 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/@port attribute is missing"));
3024 if (!pelmAttached->getAttributeValue("device", att.lDevice))
3025 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/@device attribute is missing"));
3026
3027 pelmAttached->getAttributeValue("bandwidthGroup", att.strBwGroup);
3028 sctl.llAttachedDevices.push_back(att);
3029 }
3030 }
3031
3032 strg.llStorageControllers.push_back(sctl);
3033 }
3034}
3035
3036/**
3037 * This gets called for legacy pre-1.9 settings files after having parsed the
3038 * <Hardware> and <StorageControllers> sections to parse <Hardware> once more
3039 * for the <DVDDrive> and <FloppyDrive> sections.
3040 *
3041 * Before settings version 1.9, DVD and floppy drives were specified separately
3042 * under <Hardware>; we then need this extra loop to make sure the storage
3043 * controller structs are already set up so we can add stuff to them.
3044 *
3045 * @param elmHardware
3046 * @param strg
3047 */
3048void MachineConfigFile::readDVDAndFloppies_pre1_9(const xml::ElementNode &elmHardware,
3049 Storage &strg)
3050{
3051 xml::NodesLoop nl1(elmHardware);
3052 const xml::ElementNode *pelmHwChild;
3053 while ((pelmHwChild = nl1.forAllNodes()))
3054 {
3055 if (pelmHwChild->nameEquals("DVDDrive"))
3056 {
3057 // create a DVD "attached device" and attach it to the existing IDE controller
3058 AttachedDevice att;
3059 att.deviceType = DeviceType_DVD;
3060 // legacy DVD drive is always secondary master (port 1, device 0)
3061 att.lPort = 1;
3062 att.lDevice = 0;
3063 pelmHwChild->getAttributeValue("passthrough", att.fPassThrough);
3064
3065 const xml::ElementNode *pDriveChild;
3066 Utf8Str strTmp;
3067 if ( ((pDriveChild = pelmHwChild->findChildElement("Image")))
3068 && (pDriveChild->getAttributeValue("uuid", strTmp))
3069 )
3070 parseUUID(att.uuid, strTmp);
3071 else if ((pDriveChild = pelmHwChild->findChildElement("HostDrive")))
3072 pDriveChild->getAttributeValue("src", att.strHostDriveSrc);
3073
3074 // find the IDE controller and attach the DVD drive
3075 bool fFound = false;
3076 for (StorageControllersList::iterator it = strg.llStorageControllers.begin();
3077 it != strg.llStorageControllers.end();
3078 ++it)
3079 {
3080 StorageController &sctl = *it;
3081 if (sctl.storageBus == StorageBus_IDE)
3082 {
3083 sctl.llAttachedDevices.push_back(att);
3084 fFound = true;
3085 break;
3086 }
3087 }
3088
3089 if (!fFound)
3090 throw ConfigFileError(this, pelmHwChild, N_("Internal error: found DVD drive but IDE controller does not exist"));
3091 // shouldn't happen because pre-1.9 settings files always had at least one IDE controller in the settings
3092 // which should have gotten parsed in <StorageControllers> before this got called
3093 }
3094 else if (pelmHwChild->nameEquals("FloppyDrive"))
3095 {
3096 bool fEnabled;
3097 if ( (pelmHwChild->getAttributeValue("enabled", fEnabled))
3098 && (fEnabled)
3099 )
3100 {
3101 // create a new floppy controller and attach a floppy "attached device"
3102 StorageController sctl;
3103 sctl.strName = "Floppy Controller";
3104 sctl.storageBus = StorageBus_Floppy;
3105 sctl.controllerType = StorageControllerType_I82078;
3106 sctl.ulPortCount = 1;
3107
3108 AttachedDevice att;
3109 att.deviceType = DeviceType_Floppy;
3110 att.lPort = 0;
3111 att.lDevice = 0;
3112
3113 const xml::ElementNode *pDriveChild;
3114 Utf8Str strTmp;
3115 if ( ((pDriveChild = pelmHwChild->findChildElement("Image")))
3116 && (pDriveChild->getAttributeValue("uuid", strTmp))
3117 )
3118 parseUUID(att.uuid, strTmp);
3119 else if ((pDriveChild = pelmHwChild->findChildElement("HostDrive")))
3120 pDriveChild->getAttributeValue("src", att.strHostDriveSrc);
3121
3122 // store attachment with controller
3123 sctl.llAttachedDevices.push_back(att);
3124 // store controller with storage
3125 strg.llStorageControllers.push_back(sctl);
3126 }
3127 }
3128 }
3129}
3130
3131/**
3132 * Called initially for the <Snapshot> element under <Machine>, if present,
3133 * to store the snapshot's data into the given Snapshot structure (which is
3134 * then the one in the Machine struct). This might then recurse if
3135 * a <Snapshots> (plural) element is found in the snapshot, which should
3136 * contain a list of child snapshots; such lists are maintained in the
3137 * Snapshot structure.
3138 *
3139 * @param elmSnapshot
3140 * @param snap
3141 */
3142void MachineConfigFile::readSnapshot(const xml::ElementNode &elmSnapshot,
3143 Snapshot &snap)
3144{
3145 Utf8Str strTemp;
3146
3147 if (!elmSnapshot.getAttributeValue("uuid", strTemp))
3148 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@uuid attribute is missing"));
3149 parseUUID(snap.uuid, strTemp);
3150
3151 if (!elmSnapshot.getAttributeValue("name", snap.strName))
3152 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@name attribute is missing"));
3153
3154 // earlier 3.1 trunk builds had a bug and added Description as an attribute, read it silently and write it back as an element
3155 elmSnapshot.getAttributeValue("Description", snap.strDescription);
3156
3157 if (!elmSnapshot.getAttributeValue("timeStamp", strTemp))
3158 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@timeStamp attribute is missing"));
3159 parseTimestamp(snap.timestamp, strTemp);
3160
3161 elmSnapshot.getAttributeValuePath("stateFile", snap.strStateFile); // online snapshots only
3162
3163 // parse Hardware before the other elements because other things depend on it
3164 const xml::ElementNode *pelmHardware;
3165 if (!(pelmHardware = elmSnapshot.findChildElement("Hardware")))
3166 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@Hardware element is missing"));
3167 readHardware(*pelmHardware, snap.hardware, snap.storage);
3168
3169 xml::NodesLoop nlSnapshotChildren(elmSnapshot);
3170 const xml::ElementNode *pelmSnapshotChild;
3171 while ((pelmSnapshotChild = nlSnapshotChildren.forAllNodes()))
3172 {
3173 if (pelmSnapshotChild->nameEquals("Description"))
3174 snap.strDescription = pelmSnapshotChild->getValue();
3175 else if ( (m->sv < SettingsVersion_v1_7)
3176 && (pelmSnapshotChild->nameEquals("HardDiskAttachments"))
3177 )
3178 readHardDiskAttachments_pre1_7(*pelmSnapshotChild, snap.storage);
3179 else if ( (m->sv >= SettingsVersion_v1_7)
3180 && (pelmSnapshotChild->nameEquals("StorageControllers"))
3181 )
3182 readStorageControllers(*pelmSnapshotChild, snap.storage);
3183 else if (pelmSnapshotChild->nameEquals("Snapshots"))
3184 {
3185 xml::NodesLoop nlChildSnapshots(*pelmSnapshotChild);
3186 const xml::ElementNode *pelmChildSnapshot;
3187 while ((pelmChildSnapshot = nlChildSnapshots.forAllNodes()))
3188 {
3189 if (pelmChildSnapshot->nameEquals("Snapshot"))
3190 {
3191 Snapshot child;
3192 readSnapshot(*pelmChildSnapshot, child);
3193 snap.llChildSnapshots.push_back(child);
3194 }
3195 }
3196 }
3197 }
3198
3199 if (m->sv < SettingsVersion_v1_9)
3200 // go through Hardware once more to repair the settings controller structures
3201 // with data from old DVDDrive and FloppyDrive elements
3202 readDVDAndFloppies_pre1_9(*pelmHardware, snap.storage);
3203}
3204
3205const struct {
3206 const char *pcszOld;
3207 const char *pcszNew;
3208} aConvertOSTypes[] =
3209{
3210 { "unknown", "Other" },
3211 { "dos", "DOS" },
3212 { "win31", "Windows31" },
3213 { "win95", "Windows95" },
3214 { "win98", "Windows98" },
3215 { "winme", "WindowsMe" },
3216 { "winnt4", "WindowsNT4" },
3217 { "win2k", "Windows2000" },
3218 { "winxp", "WindowsXP" },
3219 { "win2k3", "Windows2003" },
3220 { "winvista", "WindowsVista" },
3221 { "win2k8", "Windows2008" },
3222 { "os2warp3", "OS2Warp3" },
3223 { "os2warp4", "OS2Warp4" },
3224 { "os2warp45", "OS2Warp45" },
3225 { "ecs", "OS2eCS" },
3226 { "linux22", "Linux22" },
3227 { "linux24", "Linux24" },
3228 { "linux26", "Linux26" },
3229 { "archlinux", "ArchLinux" },
3230 { "debian", "Debian" },
3231 { "opensuse", "OpenSUSE" },
3232 { "fedoracore", "Fedora" },
3233 { "gentoo", "Gentoo" },
3234 { "mandriva", "Mandriva" },
3235 { "redhat", "RedHat" },
3236 { "ubuntu", "Ubuntu" },
3237 { "xandros", "Xandros" },
3238 { "freebsd", "FreeBSD" },
3239 { "openbsd", "OpenBSD" },
3240 { "netbsd", "NetBSD" },
3241 { "netware", "Netware" },
3242 { "solaris", "Solaris" },
3243 { "opensolaris", "OpenSolaris" },
3244 { "l4", "L4" }
3245};
3246
3247void MachineConfigFile::convertOldOSType_pre1_5(Utf8Str &str)
3248{
3249 for (unsigned u = 0;
3250 u < RT_ELEMENTS(aConvertOSTypes);
3251 ++u)
3252 {
3253 if (str == aConvertOSTypes[u].pcszOld)
3254 {
3255 str = aConvertOSTypes[u].pcszNew;
3256 break;
3257 }
3258 }
3259}
3260
3261/**
3262 * Called from the constructor to actually read in the <Machine> element
3263 * of a machine config file.
3264 * @param elmMachine
3265 */
3266void MachineConfigFile::readMachine(const xml::ElementNode &elmMachine)
3267{
3268 Utf8Str strUUID;
3269 if ( (elmMachine.getAttributeValue("uuid", strUUID))
3270 && (elmMachine.getAttributeValue("name", machineUserData.strName))
3271 )
3272 {
3273 parseUUID(uuid, strUUID);
3274
3275 elmMachine.getAttributeValue("nameSync", machineUserData.fNameSync);
3276
3277 Utf8Str str;
3278 elmMachine.getAttributeValue("Description", machineUserData.strDescription);
3279
3280 elmMachine.getAttributeValue("OSType", machineUserData.strOsType);
3281 if (m->sv < SettingsVersion_v1_5)
3282 convertOldOSType_pre1_5(machineUserData.strOsType);
3283
3284 elmMachine.getAttributeValuePath("stateFile", strStateFile);
3285
3286 if (elmMachine.getAttributeValue("currentSnapshot", str))
3287 parseUUID(uuidCurrentSnapshot, str);
3288
3289 elmMachine.getAttributeValuePath("snapshotFolder", machineUserData.strSnapshotFolder);
3290
3291 if (!elmMachine.getAttributeValue("currentStateModified", fCurrentStateModified))
3292 fCurrentStateModified = true;
3293 if (elmMachine.getAttributeValue("lastStateChange", str))
3294 parseTimestamp(timeLastStateChange, str);
3295 // constructor has called RTTimeNow(&timeLastStateChange) before
3296 if (elmMachine.getAttributeValue("aborted", fAborted))
3297 fAborted = true;
3298
3299 // parse Hardware before the other elements because other things depend on it
3300 const xml::ElementNode *pelmHardware;
3301 if (!(pelmHardware = elmMachine.findChildElement("Hardware")))
3302 throw ConfigFileError(this, &elmMachine, N_("Required Machine/Hardware element is missing"));
3303 readHardware(*pelmHardware, hardwareMachine, storageMachine);
3304
3305 xml::NodesLoop nlRootChildren(elmMachine);
3306 const xml::ElementNode *pelmMachineChild;
3307 while ((pelmMachineChild = nlRootChildren.forAllNodes()))
3308 {
3309 if (pelmMachineChild->nameEquals("ExtraData"))
3310 readExtraData(*pelmMachineChild,
3311 mapExtraDataItems);
3312 else if ( (m->sv < SettingsVersion_v1_7)
3313 && (pelmMachineChild->nameEquals("HardDiskAttachments"))
3314 )
3315 readHardDiskAttachments_pre1_7(*pelmMachineChild, storageMachine);
3316 else if ( (m->sv >= SettingsVersion_v1_7)
3317 && (pelmMachineChild->nameEquals("StorageControllers"))
3318 )
3319 readStorageControllers(*pelmMachineChild, storageMachine);
3320 else if (pelmMachineChild->nameEquals("Snapshot"))
3321 {
3322 Snapshot snap;
3323 // this will recurse into child snapshots, if necessary
3324 readSnapshot(*pelmMachineChild, snap);
3325 llFirstSnapshot.push_back(snap);
3326 }
3327 else if (pelmMachineChild->nameEquals("Description"))
3328 machineUserData.strDescription = pelmMachineChild->getValue();
3329 else if (pelmMachineChild->nameEquals("Teleporter"))
3330 {
3331 pelmMachineChild->getAttributeValue("enabled", machineUserData.fTeleporterEnabled);
3332 pelmMachineChild->getAttributeValue("port", machineUserData.uTeleporterPort);
3333 pelmMachineChild->getAttributeValue("address", machineUserData.strTeleporterAddress);
3334 pelmMachineChild->getAttributeValue("password", machineUserData.strTeleporterPassword);
3335 }
3336 else if (pelmMachineChild->nameEquals("FaultTolerance"))
3337 {
3338 Utf8Str strFaultToleranceSate;
3339 if (pelmMachineChild->getAttributeValue("state", strFaultToleranceSate))
3340 {
3341 if (strFaultToleranceSate == "master")
3342 machineUserData.enmFaultToleranceState = FaultToleranceState_Master;
3343 else
3344 if (strFaultToleranceSate == "standby")
3345 machineUserData.enmFaultToleranceState = FaultToleranceState_Standby;
3346 else
3347 machineUserData.enmFaultToleranceState = FaultToleranceState_Inactive;
3348 }
3349 pelmMachineChild->getAttributeValue("port", machineUserData.uFaultTolerancePort);
3350 pelmMachineChild->getAttributeValue("address", machineUserData.strFaultToleranceAddress);
3351 pelmMachineChild->getAttributeValue("interval", machineUserData.uFaultToleranceInterval);
3352 pelmMachineChild->getAttributeValue("password", machineUserData.strFaultTolerancePassword);
3353 }
3354 else if (pelmMachineChild->nameEquals("MediaRegistry"))
3355 readMediaRegistry(*pelmMachineChild, mediaRegistry);
3356 }
3357
3358 if (m->sv < SettingsVersion_v1_9)
3359 // go through Hardware once more to repair the settings controller structures
3360 // with data from old DVDDrive and FloppyDrive elements
3361 readDVDAndFloppies_pre1_9(*pelmHardware, storageMachine);
3362 }
3363 else
3364 throw ConfigFileError(this, &elmMachine, N_("Required Machine/@uuid or @name attributes is missing"));
3365}
3366
3367/**
3368 * Creates a <Hardware> node under elmParent and then writes out the XML
3369 * keys under that. Called for both the <Machine> node and for snapshots.
3370 * @param elmParent
3371 * @param st
3372 */
3373void MachineConfigFile::buildHardwareXML(xml::ElementNode &elmParent,
3374 const Hardware &hw,
3375 const Storage &strg)
3376{
3377 xml::ElementNode *pelmHardware = elmParent.createChild("Hardware");
3378
3379 if (m->sv >= SettingsVersion_v1_4)
3380 pelmHardware->setAttribute("version", hw.strVersion);
3381 if ( (m->sv >= SettingsVersion_v1_9)
3382 && (!hw.uuid.isEmpty())
3383 )
3384 pelmHardware->setAttribute("uuid", hw.uuid.toStringCurly());
3385
3386 xml::ElementNode *pelmCPU = pelmHardware->createChild("CPU");
3387
3388 xml::ElementNode *pelmHwVirtEx = pelmCPU->createChild("HardwareVirtEx");
3389 pelmHwVirtEx->setAttribute("enabled", hw.fHardwareVirt);
3390 if (m->sv >= SettingsVersion_v1_9)
3391 pelmHwVirtEx->setAttribute("exclusive", hw.fHardwareVirtExclusive);
3392
3393 pelmCPU->createChild("HardwareVirtExNestedPaging")->setAttribute("enabled", hw.fNestedPaging);
3394 pelmCPU->createChild("HardwareVirtExVPID")->setAttribute("enabled", hw.fVPID);
3395 pelmCPU->createChild("PAE")->setAttribute("enabled", hw.fPAE);
3396
3397 if (hw.fSyntheticCpu)
3398 pelmCPU->createChild("SyntheticCpu")->setAttribute("enabled", hw.fSyntheticCpu);
3399 pelmCPU->setAttribute("count", hw.cCPUs);
3400 if (hw.ulCpuExecutionCap != 100)
3401 pelmCPU->setAttribute("executionCap", hw.ulCpuExecutionCap);
3402
3403 /* Always save this setting as we have changed the default in 4.0 (on for large memory 64-bit systems). */
3404 pelmCPU->createChild("HardwareVirtExLargePages")->setAttribute("enabled", hw.fLargePages);
3405
3406 if (m->sv >= SettingsVersion_v1_9)
3407 pelmCPU->createChild("HardwareVirtForce")->setAttribute("enabled", hw.fHardwareVirtForce);
3408
3409 if (m->sv >= SettingsVersion_v1_10)
3410 {
3411 pelmCPU->setAttribute("hotplug", hw.fCpuHotPlug);
3412
3413 xml::ElementNode *pelmCpuTree = NULL;
3414 for (CpuList::const_iterator it = hw.llCpus.begin();
3415 it != hw.llCpus.end();
3416 ++it)
3417 {
3418 const Cpu &cpu = *it;
3419
3420 if (pelmCpuTree == NULL)
3421 pelmCpuTree = pelmCPU->createChild("CpuTree");
3422
3423 xml::ElementNode *pelmCpu = pelmCpuTree->createChild("Cpu");
3424 pelmCpu->setAttribute("id", cpu.ulId);
3425 }
3426 }
3427
3428 xml::ElementNode *pelmCpuIdTree = NULL;
3429 for (CpuIdLeafsList::const_iterator it = hw.llCpuIdLeafs.begin();
3430 it != hw.llCpuIdLeafs.end();
3431 ++it)
3432 {
3433 const CpuIdLeaf &leaf = *it;
3434
3435 if (pelmCpuIdTree == NULL)
3436 pelmCpuIdTree = pelmCPU->createChild("CpuIdTree");
3437
3438 xml::ElementNode *pelmCpuIdLeaf = pelmCpuIdTree->createChild("CpuIdLeaf");
3439 pelmCpuIdLeaf->setAttribute("id", leaf.ulId);
3440 pelmCpuIdLeaf->setAttribute("eax", leaf.ulEax);
3441 pelmCpuIdLeaf->setAttribute("ebx", leaf.ulEbx);
3442 pelmCpuIdLeaf->setAttribute("ecx", leaf.ulEcx);
3443 pelmCpuIdLeaf->setAttribute("edx", leaf.ulEdx);
3444 }
3445
3446 xml::ElementNode *pelmMemory = pelmHardware->createChild("Memory");
3447 pelmMemory->setAttribute("RAMSize", hw.ulMemorySizeMB);
3448 if (m->sv >= SettingsVersion_v1_10)
3449 {
3450 pelmMemory->setAttribute("PageFusion", hw.fPageFusionEnabled);
3451 }
3452
3453 if ( (m->sv >= SettingsVersion_v1_9)
3454 && (hw.firmwareType >= FirmwareType_EFI)
3455 )
3456 {
3457 xml::ElementNode *pelmFirmware = pelmHardware->createChild("Firmware");
3458 const char *pcszFirmware;
3459
3460 switch (hw.firmwareType)
3461 {
3462 case FirmwareType_EFI: pcszFirmware = "EFI"; break;
3463 case FirmwareType_EFI32: pcszFirmware = "EFI32"; break;
3464 case FirmwareType_EFI64: pcszFirmware = "EFI64"; break;
3465 case FirmwareType_EFIDUAL: pcszFirmware = "EFIDUAL"; break;
3466 default: pcszFirmware = "None"; break;
3467 }
3468 pelmFirmware->setAttribute("type", pcszFirmware);
3469 }
3470
3471 if ( (m->sv >= SettingsVersion_v1_10)
3472 )
3473 {
3474 xml::ElementNode *pelmHid = pelmHardware->createChild("HID");
3475 const char *pcszHid;
3476
3477 switch (hw.pointingHidType)
3478 {
3479 case PointingHidType_USBMouse: pcszHid = "USBMouse"; break;
3480 case PointingHidType_USBTablet: pcszHid = "USBTablet"; break;
3481 case PointingHidType_PS2Mouse: pcszHid = "PS2Mouse"; break;
3482 case PointingHidType_ComboMouse: pcszHid = "ComboMouse"; break;
3483 case PointingHidType_None: pcszHid = "None"; break;
3484 default: Assert(false); pcszHid = "PS2Mouse"; break;
3485 }
3486 pelmHid->setAttribute("Pointing", pcszHid);
3487
3488 switch (hw.keyboardHidType)
3489 {
3490 case KeyboardHidType_USBKeyboard: pcszHid = "USBKeyboard"; break;
3491 case KeyboardHidType_PS2Keyboard: pcszHid = "PS2Keyboard"; break;
3492 case KeyboardHidType_ComboKeyboard: pcszHid = "ComboKeyboard"; break;
3493 case KeyboardHidType_None: pcszHid = "None"; break;
3494 default: Assert(false); pcszHid = "PS2Keyboard"; break;
3495 }
3496 pelmHid->setAttribute("Keyboard", pcszHid);
3497 }
3498
3499 if ( (m->sv >= SettingsVersion_v1_10)
3500 )
3501 {
3502 xml::ElementNode *pelmHpet = pelmHardware->createChild("HPET");
3503 pelmHpet->setAttribute("enabled", hw.fHpetEnabled);
3504 }
3505
3506 if ( (m->sv >= SettingsVersion_v1_11)
3507 )
3508 {
3509 xml::ElementNode *pelmChipset = pelmHardware->createChild("Chipset");
3510 const char *pcszChipset;
3511
3512 switch (hw.chipsetType)
3513 {
3514 case ChipsetType_PIIX3: pcszChipset = "PIIX3"; break;
3515 case ChipsetType_ICH9: pcszChipset = "ICH9"; break;
3516 default: Assert(false); pcszChipset = "PIIX3"; break;
3517 }
3518 pelmChipset->setAttribute("type", pcszChipset);
3519 }
3520
3521 xml::ElementNode *pelmBoot = pelmHardware->createChild("Boot");
3522 for (BootOrderMap::const_iterator it = hw.mapBootOrder.begin();
3523 it != hw.mapBootOrder.end();
3524 ++it)
3525 {
3526 uint32_t i = it->first;
3527 DeviceType_T type = it->second;
3528 const char *pcszDevice;
3529
3530 switch (type)
3531 {
3532 case DeviceType_Floppy: pcszDevice = "Floppy"; break;
3533 case DeviceType_DVD: pcszDevice = "DVD"; break;
3534 case DeviceType_HardDisk: pcszDevice = "HardDisk"; break;
3535 case DeviceType_Network: pcszDevice = "Network"; break;
3536 default: /*case DeviceType_Null:*/ pcszDevice = "None"; break;
3537 }
3538
3539 xml::ElementNode *pelmOrder = pelmBoot->createChild("Order");
3540 pelmOrder->setAttribute("position",
3541 i + 1); // XML is 1-based but internal data is 0-based
3542 pelmOrder->setAttribute("device", pcszDevice);
3543 }
3544
3545 xml::ElementNode *pelmDisplay = pelmHardware->createChild("Display");
3546 pelmDisplay->setAttribute("VRAMSize", hw.ulVRAMSizeMB);
3547 pelmDisplay->setAttribute("monitorCount", hw.cMonitors);
3548 pelmDisplay->setAttribute("accelerate3D", hw.fAccelerate3D);
3549
3550 if (m->sv >= SettingsVersion_v1_8)
3551 pelmDisplay->setAttribute("accelerate2DVideo", hw.fAccelerate2DVideo);
3552
3553 xml::ElementNode *pelmVRDE = pelmHardware->createChild("RemoteDisplay");
3554 pelmVRDE->setAttribute("enabled", hw.vrdeSettings.fEnabled);
3555 if (m->sv < SettingsVersion_v1_11)
3556 {
3557 /* In VBox 4.0 these attributes are replaced with "Properties". */
3558 Utf8Str strPort;
3559 StringsMap::const_iterator it = hw.vrdeSettings.mapProperties.find("TCP/Ports");
3560 if (it != hw.vrdeSettings.mapProperties.end())
3561 strPort = it->second;
3562 if (!strPort.length())
3563 strPort = "3389";
3564 pelmVRDE->setAttribute("port", strPort);
3565
3566 Utf8Str strAddress;
3567 it = hw.vrdeSettings.mapProperties.find("TCP/Address");
3568 if (it != hw.vrdeSettings.mapProperties.end())
3569 strAddress = it->second;
3570 if (strAddress.length())
3571 pelmVRDE->setAttribute("netAddress", strAddress);
3572 }
3573 const char *pcszAuthType;
3574 switch (hw.vrdeSettings.authType)
3575 {
3576 case AuthType_Guest: pcszAuthType = "Guest"; break;
3577 case AuthType_External: pcszAuthType = "External"; break;
3578 default: /*case AuthType_Null:*/ pcszAuthType = "Null"; break;
3579 }
3580 pelmVRDE->setAttribute("authType", pcszAuthType);
3581
3582 if (hw.vrdeSettings.ulAuthTimeout != 0)
3583 pelmVRDE->setAttribute("authTimeout", hw.vrdeSettings.ulAuthTimeout);
3584 if (hw.vrdeSettings.fAllowMultiConnection)
3585 pelmVRDE->setAttribute("allowMultiConnection", hw.vrdeSettings.fAllowMultiConnection);
3586 if (hw.vrdeSettings.fReuseSingleConnection)
3587 pelmVRDE->setAttribute("reuseSingleConnection", hw.vrdeSettings.fReuseSingleConnection);
3588
3589 if (m->sv == SettingsVersion_v1_10)
3590 {
3591 xml::ElementNode *pelmVideoChannel = pelmVRDE->createChild("VideoChannel");
3592
3593 /* In 4.0 videochannel settings were replaced with properties, so look at properties. */
3594 Utf8Str str;
3595 StringsMap::const_iterator it = hw.vrdeSettings.mapProperties.find("VideoChannel/Enabled");
3596 if (it != hw.vrdeSettings.mapProperties.end())
3597 str = it->second;
3598 bool fVideoChannel = RTStrICmp(str.c_str(), "true") == 0
3599 || RTStrCmp(str.c_str(), "1") == 0;
3600 pelmVideoChannel->setAttribute("enabled", fVideoChannel);
3601
3602 it = hw.vrdeSettings.mapProperties.find("VideoChannel/Quality");
3603 if (it != hw.vrdeSettings.mapProperties.end())
3604 str = it->second;
3605 uint32_t ulVideoChannelQuality = RTStrToUInt32(str.c_str()); /* This returns 0 on invalid string which is ok. */
3606 if (ulVideoChannelQuality == 0)
3607 ulVideoChannelQuality = 75;
3608 else
3609 ulVideoChannelQuality = RT_CLAMP(ulVideoChannelQuality, 10, 100);
3610 pelmVideoChannel->setAttribute("quality", ulVideoChannelQuality);
3611 }
3612 if (m->sv >= SettingsVersion_v1_11)
3613 {
3614 if (hw.vrdeSettings.strAuthLibrary.length())
3615 pelmVRDE->setAttribute("authLibrary", hw.vrdeSettings.strAuthLibrary);
3616 if (hw.vrdeSettings.strVrdeExtPack.isNotEmpty())
3617 pelmVRDE->setAttribute("VRDEExtPack", hw.vrdeSettings.strVrdeExtPack);
3618 if (hw.vrdeSettings.mapProperties.size() > 0)
3619 {
3620 xml::ElementNode *pelmProperties = pelmVRDE->createChild("VRDEProperties");
3621 for (StringsMap::const_iterator it = hw.vrdeSettings.mapProperties.begin();
3622 it != hw.vrdeSettings.mapProperties.end();
3623 ++it)
3624 {
3625 const Utf8Str &strName = it->first;
3626 const Utf8Str &strValue = it->second;
3627 xml::ElementNode *pelm = pelmProperties->createChild("Property");
3628 pelm->setAttribute("name", strName);
3629 pelm->setAttribute("value", strValue);
3630 }
3631 }
3632 }
3633
3634 xml::ElementNode *pelmBIOS = pelmHardware->createChild("BIOS");
3635 pelmBIOS->createChild("ACPI")->setAttribute("enabled", hw.biosSettings.fACPIEnabled);
3636 pelmBIOS->createChild("IOAPIC")->setAttribute("enabled", hw.biosSettings.fIOAPICEnabled);
3637
3638 xml::ElementNode *pelmLogo = pelmBIOS->createChild("Logo");
3639 pelmLogo->setAttribute("fadeIn", hw.biosSettings.fLogoFadeIn);
3640 pelmLogo->setAttribute("fadeOut", hw.biosSettings.fLogoFadeOut);
3641 pelmLogo->setAttribute("displayTime", hw.biosSettings.ulLogoDisplayTime);
3642 if (hw.biosSettings.strLogoImagePath.length())
3643 pelmLogo->setAttribute("imagePath", hw.biosSettings.strLogoImagePath);
3644
3645 const char *pcszBootMenu;
3646 switch (hw.biosSettings.biosBootMenuMode)
3647 {
3648 case BIOSBootMenuMode_Disabled: pcszBootMenu = "Disabled"; break;
3649 case BIOSBootMenuMode_MenuOnly: pcszBootMenu = "MenuOnly"; break;
3650 default: /*BIOSBootMenuMode_MessageAndMenu*/ pcszBootMenu = "MessageAndMenu"; break;
3651 }
3652 pelmBIOS->createChild("BootMenu")->setAttribute("mode", pcszBootMenu);
3653 pelmBIOS->createChild("TimeOffset")->setAttribute("value", hw.biosSettings.llTimeOffset);
3654 pelmBIOS->createChild("PXEDebug")->setAttribute("enabled", hw.biosSettings.fPXEDebugEnabled);
3655
3656 if (m->sv < SettingsVersion_v1_9)
3657 {
3658 // settings formats before 1.9 had separate DVDDrive and FloppyDrive items under Hardware;
3659 // run thru the storage controllers to see if we have a DVD or floppy drives
3660 size_t cDVDs = 0;
3661 size_t cFloppies = 0;
3662
3663 xml::ElementNode *pelmDVD = pelmHardware->createChild("DVDDrive");
3664 xml::ElementNode *pelmFloppy = pelmHardware->createChild("FloppyDrive");
3665
3666 for (StorageControllersList::const_iterator it = strg.llStorageControllers.begin();
3667 it != strg.llStorageControllers.end();
3668 ++it)
3669 {
3670 const StorageController &sctl = *it;
3671 // in old settings format, the DVD drive could only have been under the IDE controller
3672 if (sctl.storageBus == StorageBus_IDE)
3673 {
3674 for (AttachedDevicesList::const_iterator it2 = sctl.llAttachedDevices.begin();
3675 it2 != sctl.llAttachedDevices.end();
3676 ++it2)
3677 {
3678 const AttachedDevice &att = *it2;
3679 if (att.deviceType == DeviceType_DVD)
3680 {
3681 if (cDVDs > 0)
3682 throw ConfigFileError(this, NULL, N_("Internal error: cannot save more than one DVD drive with old settings format"));
3683
3684 ++cDVDs;
3685
3686 pelmDVD->setAttribute("passthrough", att.fPassThrough);
3687 if (!att.uuid.isEmpty())
3688 pelmDVD->createChild("Image")->setAttribute("uuid", att.uuid.toStringCurly());
3689 else if (att.strHostDriveSrc.length())
3690 pelmDVD->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
3691 }
3692 }
3693 }
3694 else if (sctl.storageBus == StorageBus_Floppy)
3695 {
3696 size_t cFloppiesHere = sctl.llAttachedDevices.size();
3697 if (cFloppiesHere > 1)
3698 throw ConfigFileError(this, NULL, N_("Internal error: floppy controller cannot have more than one device attachment"));
3699 if (cFloppiesHere)
3700 {
3701 const AttachedDevice &att = sctl.llAttachedDevices.front();
3702 pelmFloppy->setAttribute("enabled", true);
3703 if (!att.uuid.isEmpty())
3704 pelmFloppy->createChild("Image")->setAttribute("uuid", att.uuid.toStringCurly());
3705 else if (att.strHostDriveSrc.length())
3706 pelmFloppy->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
3707 }
3708
3709 cFloppies += cFloppiesHere;
3710 }
3711 }
3712
3713 if (cFloppies == 0)
3714 pelmFloppy->setAttribute("enabled", false);
3715 else if (cFloppies > 1)
3716 throw ConfigFileError(this, NULL, N_("Internal error: cannot save more than one floppy drive with old settings format"));
3717 }
3718
3719 xml::ElementNode *pelmUSB = pelmHardware->createChild("USBController");
3720 pelmUSB->setAttribute("enabled", hw.usbController.fEnabled);
3721 pelmUSB->setAttribute("enabledEhci", hw.usbController.fEnabledEHCI);
3722
3723 buildUSBDeviceFilters(*pelmUSB,
3724 hw.usbController.llDeviceFilters,
3725 false); // fHostMode
3726
3727 xml::ElementNode *pelmNetwork = pelmHardware->createChild("Network");
3728 for (NetworkAdaptersList::const_iterator it = hw.llNetworkAdapters.begin();
3729 it != hw.llNetworkAdapters.end();
3730 ++it)
3731 {
3732 const NetworkAdapter &nic = *it;
3733
3734 xml::ElementNode *pelmAdapter = pelmNetwork->createChild("Adapter");
3735 pelmAdapter->setAttribute("slot", nic.ulSlot);
3736 pelmAdapter->setAttribute("enabled", nic.fEnabled);
3737 pelmAdapter->setAttribute("MACAddress", nic.strMACAddress);
3738 pelmAdapter->setAttribute("cable", nic.fCableConnected);
3739 pelmAdapter->setAttribute("speed", nic.ulLineSpeed);
3740 if (nic.ulBootPriority != 0)
3741 {
3742 pelmAdapter->setAttribute("bootPriority", nic.ulBootPriority);
3743 }
3744 if (nic.fTraceEnabled)
3745 {
3746 pelmAdapter->setAttribute("trace", nic.fTraceEnabled);
3747 pelmAdapter->setAttribute("tracefile", nic.strTraceFile);
3748 }
3749 if (nic.strBandwidthGroup.isNotEmpty())
3750 pelmAdapter->setAttribute("bandwidthGroup", nic.strBandwidthGroup);
3751
3752 const char *pszPolicy;
3753 switch (nic.enmPromiscModePolicy)
3754 {
3755 case NetworkAdapterPromiscModePolicy_Deny: pszPolicy = NULL; break;
3756 case NetworkAdapterPromiscModePolicy_AllowNetwork: pszPolicy = "AllowNetwork"; break;
3757 case NetworkAdapterPromiscModePolicy_AllowAll: pszPolicy = "AllowAll"; break;
3758 default: pszPolicy = NULL; AssertFailed(); break;
3759 }
3760 if (pszPolicy)
3761 pelmAdapter->setAttribute("promiscuousModePolicy", pszPolicy);
3762
3763 const char *pcszType;
3764 switch (nic.type)
3765 {
3766 case NetworkAdapterType_Am79C973: pcszType = "Am79C973"; break;
3767 case NetworkAdapterType_I82540EM: pcszType = "82540EM"; break;
3768 case NetworkAdapterType_I82543GC: pcszType = "82543GC"; break;
3769 case NetworkAdapterType_I82545EM: pcszType = "82545EM"; break;
3770 case NetworkAdapterType_Virtio: pcszType = "virtio"; break;
3771 default: /*case NetworkAdapterType_Am79C970A:*/ pcszType = "Am79C970A"; break;
3772 }
3773 pelmAdapter->setAttribute("type", pcszType);
3774
3775 xml::ElementNode *pelmNAT;
3776 if (m->sv < SettingsVersion_v1_10)
3777 {
3778 switch (nic.mode)
3779 {
3780 case NetworkAttachmentType_NAT:
3781 pelmNAT = pelmAdapter->createChild("NAT");
3782 if (nic.nat.strNetwork.length())
3783 pelmNAT->setAttribute("network", nic.nat.strNetwork);
3784 break;
3785
3786 case NetworkAttachmentType_Bridged:
3787 pelmAdapter->createChild("BridgedInterface")->setAttribute("name", nic.strBridgedName);
3788 break;
3789
3790 case NetworkAttachmentType_Internal:
3791 pelmAdapter->createChild("InternalNetwork")->setAttribute("name", nic.strInternalNetworkName);
3792 break;
3793
3794 case NetworkAttachmentType_HostOnly:
3795 pelmAdapter->createChild("HostOnlyInterface")->setAttribute("name", nic.strHostOnlyName);
3796 break;
3797
3798 default: /*case NetworkAttachmentType_Null:*/
3799 break;
3800 }
3801 }
3802 else
3803 {
3804 /* m->sv >= SettingsVersion_v1_10 */
3805 xml::ElementNode *pelmDisabledNode = NULL;
3806 pelmDisabledNode = pelmAdapter->createChild("DisabledModes");
3807 if (nic.mode != NetworkAttachmentType_NAT)
3808 buildNetworkXML(NetworkAttachmentType_NAT, *pelmDisabledNode, false, nic);
3809 if (nic.mode != NetworkAttachmentType_Bridged)
3810 buildNetworkXML(NetworkAttachmentType_Bridged, *pelmDisabledNode, false, nic);
3811 if (nic.mode != NetworkAttachmentType_Internal)
3812 buildNetworkXML(NetworkAttachmentType_HostOnly, *pelmDisabledNode, false, nic);
3813 if (nic.mode != NetworkAttachmentType_HostOnly)
3814 buildNetworkXML(NetworkAttachmentType_HostOnly, *pelmDisabledNode, false, nic);
3815 if (nic.mode != NetworkAttachmentType_Generic)
3816 buildNetworkXML(NetworkAttachmentType_Generic, *pelmDisabledNode, false, nic);
3817 buildNetworkXML(nic.mode, *pelmAdapter, true, nic);
3818 }
3819 }
3820
3821 xml::ElementNode *pelmPorts = pelmHardware->createChild("UART");
3822 for (SerialPortsList::const_iterator it = hw.llSerialPorts.begin();
3823 it != hw.llSerialPorts.end();
3824 ++it)
3825 {
3826 const SerialPort &port = *it;
3827 xml::ElementNode *pelmPort = pelmPorts->createChild("Port");
3828 pelmPort->setAttribute("slot", port.ulSlot);
3829 pelmPort->setAttribute("enabled", port.fEnabled);
3830 pelmPort->setAttributeHex("IOBase", port.ulIOBase);
3831 pelmPort->setAttribute("IRQ", port.ulIRQ);
3832
3833 const char *pcszHostMode;
3834 switch (port.portMode)
3835 {
3836 case PortMode_HostPipe: pcszHostMode = "HostPipe"; break;
3837 case PortMode_HostDevice: pcszHostMode = "HostDevice"; break;
3838 case PortMode_RawFile: pcszHostMode = "RawFile"; break;
3839 default: /*case PortMode_Disconnected:*/ pcszHostMode = "Disconnected"; break;
3840 }
3841 switch (port.portMode)
3842 {
3843 case PortMode_HostPipe:
3844 pelmPort->setAttribute("server", port.fServer);
3845 /* no break */
3846 case PortMode_HostDevice:
3847 case PortMode_RawFile:
3848 pelmPort->setAttribute("path", port.strPath);
3849 break;
3850
3851 default:
3852 break;
3853 }
3854 pelmPort->setAttribute("hostMode", pcszHostMode);
3855 }
3856
3857 pelmPorts = pelmHardware->createChild("LPT");
3858 for (ParallelPortsList::const_iterator it = hw.llParallelPorts.begin();
3859 it != hw.llParallelPorts.end();
3860 ++it)
3861 {
3862 const ParallelPort &port = *it;
3863 xml::ElementNode *pelmPort = pelmPorts->createChild("Port");
3864 pelmPort->setAttribute("slot", port.ulSlot);
3865 pelmPort->setAttribute("enabled", port.fEnabled);
3866 pelmPort->setAttributeHex("IOBase", port.ulIOBase);
3867 pelmPort->setAttribute("IRQ", port.ulIRQ);
3868 if (port.strPath.length())
3869 pelmPort->setAttribute("path", port.strPath);
3870 }
3871
3872 xml::ElementNode *pelmAudio = pelmHardware->createChild("AudioAdapter");
3873 const char *pcszController;
3874 switch (hw.audioAdapter.controllerType)
3875 {
3876 case AudioControllerType_SB16:
3877 pcszController = "SB16";
3878 break;
3879 case AudioControllerType_HDA:
3880 if (m->sv >= SettingsVersion_v1_11)
3881 {
3882 pcszController = "HDA";
3883 break;
3884 }
3885 /* fall through */
3886 case AudioControllerType_AC97:
3887 default:
3888 pcszController = "AC97"; break;
3889 }
3890 pelmAudio->setAttribute("controller", pcszController);
3891
3892 if (m->sv >= SettingsVersion_v1_10)
3893 {
3894 xml::ElementNode *pelmRTC = pelmHardware->createChild("RTC");
3895 pelmRTC->setAttribute("localOrUTC", machineUserData.fRTCUseUTC ? "UTC" : "local");
3896 }
3897
3898 const char *pcszDriver;
3899 switch (hw.audioAdapter.driverType)
3900 {
3901 case AudioDriverType_WinMM: pcszDriver = "WinMM"; break;
3902 case AudioDriverType_DirectSound: pcszDriver = "DirectSound"; break;
3903 case AudioDriverType_SolAudio: pcszDriver = "SolAudio"; break;
3904 case AudioDriverType_ALSA: pcszDriver = "ALSA"; break;
3905 case AudioDriverType_Pulse: pcszDriver = "Pulse"; break;
3906 case AudioDriverType_OSS: pcszDriver = "OSS"; break;
3907 case AudioDriverType_CoreAudio: pcszDriver = "CoreAudio"; break;
3908 case AudioDriverType_MMPM: pcszDriver = "MMPM"; break;
3909 default: /*case AudioDriverType_Null:*/ pcszDriver = "Null"; break;
3910 }
3911 pelmAudio->setAttribute("driver", pcszDriver);
3912
3913 pelmAudio->setAttribute("enabled", hw.audioAdapter.fEnabled);
3914
3915 xml::ElementNode *pelmSharedFolders = pelmHardware->createChild("SharedFolders");
3916 for (SharedFoldersList::const_iterator it = hw.llSharedFolders.begin();
3917 it != hw.llSharedFolders.end();
3918 ++it)
3919 {
3920 const SharedFolder &sf = *it;
3921 xml::ElementNode *pelmThis = pelmSharedFolders->createChild("SharedFolder");
3922 pelmThis->setAttribute("name", sf.strName);
3923 pelmThis->setAttribute("hostPath", sf.strHostPath);
3924 pelmThis->setAttribute("writable", sf.fWritable);
3925 pelmThis->setAttribute("autoMount", sf.fAutoMount);
3926 }
3927
3928 xml::ElementNode *pelmClip = pelmHardware->createChild("Clipboard");
3929 const char *pcszClip;
3930 switch (hw.clipboardMode)
3931 {
3932 case ClipboardMode_Disabled: pcszClip = "Disabled"; break;
3933 case ClipboardMode_HostToGuest: pcszClip = "HostToGuest"; break;
3934 case ClipboardMode_GuestToHost: pcszClip = "GuestToHost"; break;
3935 default: /*case ClipboardMode_Bidirectional:*/ pcszClip = "Bidirectional"; break;
3936 }
3937 pelmClip->setAttribute("mode", pcszClip);
3938
3939 if (m->sv >= SettingsVersion_v1_10)
3940 {
3941 xml::ElementNode *pelmIo = pelmHardware->createChild("IO");
3942 xml::ElementNode *pelmIoCache;
3943
3944 pelmIoCache = pelmIo->createChild("IoCache");
3945 pelmIoCache->setAttribute("enabled", hw.ioSettings.fIoCacheEnabled);
3946 pelmIoCache->setAttribute("size", hw.ioSettings.ulIoCacheSize);
3947
3948 if (m->sv >= SettingsVersion_v1_11)
3949 {
3950 xml::ElementNode *pelmBandwidthGroups = pelmIo->createChild("BandwidthGroups");
3951 for (BandwidthGroupList::const_iterator it = hw.ioSettings.llBandwidthGroups.begin();
3952 it != hw.ioSettings.llBandwidthGroups.end();
3953 ++it)
3954 {
3955 const BandwidthGroup &gr = *it;
3956 const char *pcszType;
3957 xml::ElementNode *pelmThis = pelmBandwidthGroups->createChild("BandwidthGroup");
3958 pelmThis->setAttribute("name", gr.strName);
3959 switch (gr.enmType)
3960 {
3961 case BandwidthGroupType_Network: pcszType = "Network"; break;
3962 default: /* BandwidthGrouptype_Disk */ pcszType = "Disk"; break;
3963 }
3964 pelmThis->setAttribute("type", pcszType);
3965 pelmThis->setAttribute("maxMbPerSec", gr.cMaxMbPerSec);
3966 }
3967 }
3968 }
3969
3970 if (m->sv >= SettingsVersion_v1_12)
3971 {
3972 xml::ElementNode *pelmPci = pelmHardware->createChild("HostPci");
3973 xml::ElementNode *pelmPciDevices = pelmPci->createChild("Devices");
3974
3975 for (HostPciDeviceAttachmentList::const_iterator it = hw.pciAttachments.begin();
3976 it != hw.pciAttachments.end();
3977 ++it)
3978 {
3979 const HostPciDeviceAttachment &hpda = *it;
3980
3981 xml::ElementNode *pelmThis = pelmPciDevices->createChild("Device");
3982
3983 pelmThis->setAttribute("host", hpda.uHostAddress);
3984 pelmThis->setAttribute("guest", hpda.uGuestAddress);
3985 pelmThis->setAttribute("name", hpda.strDeviceName);
3986 }
3987 }
3988
3989 xml::ElementNode *pelmGuest = pelmHardware->createChild("Guest");
3990 pelmGuest->setAttribute("memoryBalloonSize", hw.ulMemoryBalloonSize);
3991
3992 xml::ElementNode *pelmGuestProps = pelmHardware->createChild("GuestProperties");
3993 for (GuestPropertiesList::const_iterator it = hw.llGuestProperties.begin();
3994 it != hw.llGuestProperties.end();
3995 ++it)
3996 {
3997 const GuestProperty &prop = *it;
3998 xml::ElementNode *pelmProp = pelmGuestProps->createChild("GuestProperty");
3999 pelmProp->setAttribute("name", prop.strName);
4000 pelmProp->setAttribute("value", prop.strValue);
4001 pelmProp->setAttribute("timestamp", prop.timestamp);
4002 pelmProp->setAttribute("flags", prop.strFlags);
4003 }
4004
4005 if (hw.strNotificationPatterns.length())
4006 pelmGuestProps->setAttribute("notificationPatterns", hw.strNotificationPatterns);
4007}
4008
4009/**
4010 * Fill a <Network> node. Only relevant for XML version >= v1_10.
4011 * @param mode
4012 * @param elmParent
4013 * @param fEnabled
4014 * @param nic
4015 */
4016void MachineConfigFile::buildNetworkXML(NetworkAttachmentType_T mode,
4017 xml::ElementNode &elmParent,
4018 bool fEnabled,
4019 const NetworkAdapter &nic)
4020{
4021 switch (mode)
4022 {
4023 case NetworkAttachmentType_NAT:
4024 xml::ElementNode *pelmNAT;
4025 pelmNAT = elmParent.createChild("NAT");
4026
4027 if (nic.nat.strNetwork.length())
4028 pelmNAT->setAttribute("network", nic.nat.strNetwork);
4029 if (nic.nat.strBindIP.length())
4030 pelmNAT->setAttribute("hostip", nic.nat.strBindIP);
4031 if (nic.nat.u32Mtu)
4032 pelmNAT->setAttribute("mtu", nic.nat.u32Mtu);
4033 if (nic.nat.u32SockRcv)
4034 pelmNAT->setAttribute("sockrcv", nic.nat.u32SockRcv);
4035 if (nic.nat.u32SockSnd)
4036 pelmNAT->setAttribute("socksnd", nic.nat.u32SockSnd);
4037 if (nic.nat.u32TcpRcv)
4038 pelmNAT->setAttribute("tcprcv", nic.nat.u32TcpRcv);
4039 if (nic.nat.u32TcpSnd)
4040 pelmNAT->setAttribute("tcpsnd", nic.nat.u32TcpSnd);
4041 xml::ElementNode *pelmDNS;
4042 pelmDNS = pelmNAT->createChild("DNS");
4043 pelmDNS->setAttribute("pass-domain", nic.nat.fDnsPassDomain);
4044 pelmDNS->setAttribute("use-proxy", nic.nat.fDnsProxy);
4045 pelmDNS->setAttribute("use-host-resolver", nic.nat.fDnsUseHostResolver);
4046
4047 xml::ElementNode *pelmAlias;
4048 pelmAlias = pelmNAT->createChild("Alias");
4049 pelmAlias->setAttribute("logging", nic.nat.fAliasLog);
4050 pelmAlias->setAttribute("proxy-only", nic.nat.fAliasProxyOnly);
4051 pelmAlias->setAttribute("use-same-ports", nic.nat.fAliasUseSamePorts);
4052
4053 if ( nic.nat.strTftpPrefix.length()
4054 || nic.nat.strTftpBootFile.length()
4055 || nic.nat.strTftpNextServer.length())
4056 {
4057 xml::ElementNode *pelmTFTP;
4058 pelmTFTP = pelmNAT->createChild("TFTP");
4059 if (nic.nat.strTftpPrefix.length())
4060 pelmTFTP->setAttribute("prefix", nic.nat.strTftpPrefix);
4061 if (nic.nat.strTftpBootFile.length())
4062 pelmTFTP->setAttribute("boot-file", nic.nat.strTftpBootFile);
4063 if (nic.nat.strTftpNextServer.length())
4064 pelmTFTP->setAttribute("next-server", nic.nat.strTftpNextServer);
4065 }
4066 for (NATRuleList::const_iterator rule = nic.nat.llRules.begin();
4067 rule != nic.nat.llRules.end(); ++rule)
4068 {
4069 xml::ElementNode *pelmPF;
4070 pelmPF = pelmNAT->createChild("Forwarding");
4071 if ((*rule).strName.length())
4072 pelmPF->setAttribute("name", (*rule).strName);
4073 pelmPF->setAttribute("proto", (*rule).proto);
4074 if ((*rule).strHostIP.length())
4075 pelmPF->setAttribute("hostip", (*rule).strHostIP);
4076 if ((*rule).u16HostPort)
4077 pelmPF->setAttribute("hostport", (*rule).u16HostPort);
4078 if ((*rule).strGuestIP.length())
4079 pelmPF->setAttribute("guestip", (*rule).strGuestIP);
4080 if ((*rule).u16GuestPort)
4081 pelmPF->setAttribute("guestport", (*rule).u16GuestPort);
4082 }
4083 break;
4084
4085 case NetworkAttachmentType_Bridged:
4086 if (fEnabled || !nic.strBridgedName.isEmpty())
4087 elmParent.createChild("BridgedInterface")->setAttribute("name", nic.strBridgedName);
4088 break;
4089
4090 case NetworkAttachmentType_Internal:
4091 if (fEnabled || !nic.strInternalNetworkName.isEmpty())
4092 elmParent.createChild("InternalNetwork")->setAttribute("name", nic.strInternalNetworkName);
4093 break;
4094
4095 case NetworkAttachmentType_HostOnly:
4096 if (fEnabled || !nic.strHostOnlyName.isEmpty())
4097 elmParent.createChild("HostOnlyInterface")->setAttribute("name", nic.strHostOnlyName);
4098 break;
4099
4100 case NetworkAttachmentType_Generic:
4101 if (fEnabled || !nic.strGenericDriver.isEmpty() || nic.genericProperties.size())
4102 {
4103 xml::ElementNode *pelmMode = elmParent.createChild("GenericInterface");
4104 pelmMode->setAttribute("driver", nic.strGenericDriver);
4105 for (StringsMap::const_iterator it = nic.genericProperties.begin();
4106 it != nic.genericProperties.end();
4107 ++it)
4108 {
4109 xml::ElementNode *pelmProp = pelmMode->createChild("Property");
4110 pelmProp->setAttribute("name", it->first);
4111 pelmProp->setAttribute("value", it->second);
4112 }
4113 }
4114 break;
4115
4116 default: /*case NetworkAttachmentType_Null:*/
4117 break;
4118 }
4119}
4120
4121/**
4122 * Creates a <StorageControllers> node under elmParent and then writes out the XML
4123 * keys under that. Called for both the <Machine> node and for snapshots.
4124 * @param elmParent
4125 * @param st
4126 * @param fSkipRemovableMedia If true, DVD and floppy attachments are skipped and
4127 * an empty drive is always written instead. This is for the OVF export case.
4128 * This parameter is ignored unless the settings version is at least v1.9, which
4129 * is always the case when this gets called for OVF export.
4130 * @param pllElementsWithUuidAttributes If not NULL, must point to a list of element node
4131 * pointers to which we will append all elements that we created here that contain
4132 * UUID attributes. This allows the OVF export code to quickly replace the internal
4133 * media UUIDs with the UUIDs of the media that were exported.
4134 */
4135void MachineConfigFile::buildStorageControllersXML(xml::ElementNode &elmParent,
4136 const Storage &st,
4137 bool fSkipRemovableMedia,
4138 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes)
4139{
4140 xml::ElementNode *pelmStorageControllers = elmParent.createChild("StorageControllers");
4141
4142 for (StorageControllersList::const_iterator it = st.llStorageControllers.begin();
4143 it != st.llStorageControllers.end();
4144 ++it)
4145 {
4146 const StorageController &sc = *it;
4147
4148 if ( (m->sv < SettingsVersion_v1_9)
4149 && (sc.controllerType == StorageControllerType_I82078)
4150 )
4151 // floppy controller already got written into <Hardware>/<FloppyController> in writeHardware()
4152 // for pre-1.9 settings
4153 continue;
4154
4155 xml::ElementNode *pelmController = pelmStorageControllers->createChild("StorageController");
4156 com::Utf8Str name = sc.strName;
4157 if (m->sv < SettingsVersion_v1_8)
4158 {
4159 // pre-1.8 settings use shorter controller names, they are
4160 // expanded when reading the settings
4161 if (name == "IDE Controller")
4162 name = "IDE";
4163 else if (name == "SATA Controller")
4164 name = "SATA";
4165 else if (name == "SCSI Controller")
4166 name = "SCSI";
4167 }
4168 pelmController->setAttribute("name", sc.strName);
4169
4170 const char *pcszType;
4171 switch (sc.controllerType)
4172 {
4173 case StorageControllerType_IntelAhci: pcszType = "AHCI"; break;
4174 case StorageControllerType_LsiLogic: pcszType = "LsiLogic"; break;
4175 case StorageControllerType_BusLogic: pcszType = "BusLogic"; break;
4176 case StorageControllerType_PIIX4: pcszType = "PIIX4"; break;
4177 case StorageControllerType_ICH6: pcszType = "ICH6"; break;
4178 case StorageControllerType_I82078: pcszType = "I82078"; break;
4179 case StorageControllerType_LsiLogicSas: pcszType = "LsiLogicSas"; break;
4180 default: /*case StorageControllerType_PIIX3:*/ pcszType = "PIIX3"; break;
4181 }
4182 pelmController->setAttribute("type", pcszType);
4183
4184 pelmController->setAttribute("PortCount", sc.ulPortCount);
4185
4186 if (m->sv >= SettingsVersion_v1_9)
4187 if (sc.ulInstance)
4188 pelmController->setAttribute("Instance", sc.ulInstance);
4189
4190 if (m->sv >= SettingsVersion_v1_10)
4191 pelmController->setAttribute("useHostIOCache", sc.fUseHostIOCache);
4192
4193 if (m->sv >= SettingsVersion_v1_11)
4194 pelmController->setAttribute("Bootable", sc.fBootable);
4195
4196 if (sc.controllerType == StorageControllerType_IntelAhci)
4197 {
4198 pelmController->setAttribute("IDE0MasterEmulationPort", sc.lIDE0MasterEmulationPort);
4199 pelmController->setAttribute("IDE0SlaveEmulationPort", sc.lIDE0SlaveEmulationPort);
4200 pelmController->setAttribute("IDE1MasterEmulationPort", sc.lIDE1MasterEmulationPort);
4201 pelmController->setAttribute("IDE1SlaveEmulationPort", sc.lIDE1SlaveEmulationPort);
4202 }
4203
4204 for (AttachedDevicesList::const_iterator it2 = sc.llAttachedDevices.begin();
4205 it2 != sc.llAttachedDevices.end();
4206 ++it2)
4207 {
4208 const AttachedDevice &att = *it2;
4209
4210 // For settings version before 1.9, DVDs and floppies are in hardware, not storage controllers,
4211 // so we shouldn't write them here; we only get here for DVDs though because we ruled out
4212 // the floppy controller at the top of the loop
4213 if ( att.deviceType == DeviceType_DVD
4214 && m->sv < SettingsVersion_v1_9
4215 )
4216 continue;
4217
4218 xml::ElementNode *pelmDevice = pelmController->createChild("AttachedDevice");
4219
4220 pcszType = NULL;
4221
4222 switch (att.deviceType)
4223 {
4224 case DeviceType_HardDisk:
4225 pcszType = "HardDisk";
4226 break;
4227
4228 case DeviceType_DVD:
4229 pcszType = "DVD";
4230 pelmDevice->setAttribute("passthrough", att.fPassThrough);
4231 break;
4232
4233 case DeviceType_Floppy:
4234 pcszType = "Floppy";
4235 break;
4236 }
4237
4238 pelmDevice->setAttribute("type", pcszType);
4239
4240 pelmDevice->setAttribute("port", att.lPort);
4241 pelmDevice->setAttribute("device", att.lDevice);
4242
4243 if (att.strBwGroup.length())
4244 pelmDevice->setAttribute("bandwidthGroup", att.strBwGroup);
4245
4246 // attached image, if any
4247 if ( !att.uuid.isEmpty()
4248 && ( att.deviceType == DeviceType_HardDisk
4249 || !fSkipRemovableMedia
4250 )
4251 )
4252 {
4253 xml::ElementNode *pelmImage = pelmDevice->createChild("Image");
4254 pelmImage->setAttribute("uuid", att.uuid.toStringCurly());
4255
4256 // if caller wants a list of UUID elements, give it to them
4257 if (pllElementsWithUuidAttributes)
4258 pllElementsWithUuidAttributes->push_back(pelmImage);
4259 }
4260 else if ( (m->sv >= SettingsVersion_v1_9)
4261 && (att.strHostDriveSrc.length())
4262 )
4263 pelmDevice->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
4264 }
4265 }
4266}
4267
4268/**
4269 * Writes a single snapshot into the DOM tree. Initially this gets called from MachineConfigFile::write()
4270 * for the root snapshot of a machine, if present; elmParent then points to the <Snapshots> node under the
4271 * <Machine> node to which <Snapshot> must be added. This may then recurse for child snapshots.
4272 * @param elmParent
4273 * @param snap
4274 */
4275void MachineConfigFile::buildSnapshotXML(xml::ElementNode &elmParent,
4276 const Snapshot &snap)
4277{
4278 xml::ElementNode *pelmSnapshot = elmParent.createChild("Snapshot");
4279
4280 pelmSnapshot->setAttribute("uuid", snap.uuid.toStringCurly());
4281 pelmSnapshot->setAttribute("name", snap.strName);
4282 pelmSnapshot->setAttribute("timeStamp", makeString(snap.timestamp));
4283
4284 if (snap.strStateFile.length())
4285 pelmSnapshot->setAttributePath("stateFile", snap.strStateFile);
4286
4287 if (snap.strDescription.length())
4288 pelmSnapshot->createChild("Description")->addContent(snap.strDescription);
4289
4290 buildHardwareXML(*pelmSnapshot, snap.hardware, snap.storage);
4291 buildStorageControllersXML(*pelmSnapshot,
4292 snap.storage,
4293 false /* fSkipRemovableMedia */,
4294 NULL); /* pllElementsWithUuidAttributes */
4295 // we only skip removable media for OVF, but we never get here for OVF
4296 // since snapshots never get written then
4297
4298 if (snap.llChildSnapshots.size())
4299 {
4300 xml::ElementNode *pelmChildren = pelmSnapshot->createChild("Snapshots");
4301 for (SnapshotsList::const_iterator it = snap.llChildSnapshots.begin();
4302 it != snap.llChildSnapshots.end();
4303 ++it)
4304 {
4305 const Snapshot &child = *it;
4306 buildSnapshotXML(*pelmChildren, child);
4307 }
4308 }
4309}
4310
4311/**
4312 * Builds the XML DOM tree for the machine config under the given XML element.
4313 *
4314 * This has been separated out from write() so it can be called from elsewhere,
4315 * such as the OVF code, to build machine XML in an existing XML tree.
4316 *
4317 * As a result, this gets called from two locations:
4318 *
4319 * -- MachineConfigFile::write();
4320 *
4321 * -- Appliance::buildXMLForOneVirtualSystem()
4322 *
4323 * In fl, the following flag bits are recognized:
4324 *
4325 * -- BuildMachineXML_MediaRegistry: If set, the machine's media registry will
4326 * be written, if present. This is not set when called from OVF because OVF
4327 * has its own variant of a media registry. This flag is ignored unless the
4328 * settings version is at least v1.11 (VirtualBox 4.0).
4329 *
4330 * -- BuildMachineXML_IncludeSnapshots: If set, descend into the snapshots tree
4331 * of the machine and write out <Snapshot> and possibly more snapshots under
4332 * that, if snapshots are present. Otherwise all snapshots are suppressed
4333 * (when called from OVF).
4334 *
4335 * -- BuildMachineXML_WriteVboxVersionAttribute: If set, add a settingsVersion
4336 * attribute to the machine tag with the vbox settings version. This is for
4337 * the OVF export case in which we don't have the settings version set in
4338 * the root element.
4339 *
4340 * -- BuildMachineXML_SkipRemovableMedia: If set, removable media attachments
4341 * (DVDs, floppies) are silently skipped. This is for the OVF export case
4342 * until we support copying ISO and RAW media as well. This flag is ignored
4343 * unless the settings version is at least v1.9, which is always the case
4344 * when this gets called for OVF export.
4345 *
4346 * -- BuildMachineXML_SuppressSavedState: If set, the Machine/@stateFile
4347 * attribute is never set. This is also for the OVF export case because we
4348 * cannot save states with OVF.
4349 *
4350 * @param elmMachine XML <Machine> element to add attributes and elements to.
4351 * @param fl Flags.
4352 * @param pllElementsWithUuidAttributes pointer to list that should receive UUID elements or NULL;
4353 * see buildStorageControllersXML() for details.
4354 */
4355void MachineConfigFile::buildMachineXML(xml::ElementNode &elmMachine,
4356 uint32_t fl,
4357 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes)
4358{
4359 if (fl & BuildMachineXML_WriteVboxVersionAttribute)
4360 // add settings version attribute to machine element
4361 setVersionAttribute(elmMachine);
4362
4363 elmMachine.setAttribute("uuid", uuid.toStringCurly());
4364 elmMachine.setAttribute("name", machineUserData.strName);
4365 if (!machineUserData.fNameSync)
4366 elmMachine.setAttribute("nameSync", machineUserData.fNameSync);
4367 if (machineUserData.strDescription.length())
4368 elmMachine.createChild("Description")->addContent(machineUserData.strDescription);
4369 elmMachine.setAttribute("OSType", machineUserData.strOsType);
4370 if ( strStateFile.length()
4371 && !(fl & BuildMachineXML_SuppressSavedState)
4372 )
4373 elmMachine.setAttributePath("stateFile", strStateFile);
4374 if ( (fl & BuildMachineXML_IncludeSnapshots)
4375 && !uuidCurrentSnapshot.isEmpty())
4376 elmMachine.setAttribute("currentSnapshot", uuidCurrentSnapshot.toStringCurly());
4377
4378 if (machineUserData.strSnapshotFolder.length())
4379 elmMachine.setAttributePath("snapshotFolder", machineUserData.strSnapshotFolder);
4380 if (!fCurrentStateModified)
4381 elmMachine.setAttribute("currentStateModified", fCurrentStateModified);
4382 elmMachine.setAttribute("lastStateChange", makeString(timeLastStateChange));
4383 if (fAborted)
4384 elmMachine.setAttribute("aborted", fAborted);
4385 if ( m->sv >= SettingsVersion_v1_9
4386 && ( machineUserData.fTeleporterEnabled
4387 || machineUserData.uTeleporterPort
4388 || !machineUserData.strTeleporterAddress.isEmpty()
4389 || !machineUserData.strTeleporterPassword.isEmpty()
4390 )
4391 )
4392 {
4393 xml::ElementNode *pelmTeleporter = elmMachine.createChild("Teleporter");
4394 pelmTeleporter->setAttribute("enabled", machineUserData.fTeleporterEnabled);
4395 pelmTeleporter->setAttribute("port", machineUserData.uTeleporterPort);
4396 pelmTeleporter->setAttribute("address", machineUserData.strTeleporterAddress);
4397 pelmTeleporter->setAttribute("password", machineUserData.strTeleporterPassword);
4398 }
4399
4400 if ( m->sv >= SettingsVersion_v1_11
4401 && ( machineUserData.enmFaultToleranceState != FaultToleranceState_Inactive
4402 || machineUserData.uFaultTolerancePort
4403 || machineUserData.uFaultToleranceInterval
4404 || !machineUserData.strFaultToleranceAddress.isEmpty()
4405 )
4406 )
4407 {
4408 xml::ElementNode *pelmFaultTolerance = elmMachine.createChild("FaultTolerance");
4409 switch (machineUserData.enmFaultToleranceState)
4410 {
4411 case FaultToleranceState_Inactive:
4412 pelmFaultTolerance->setAttribute("state", "inactive");
4413 break;
4414 case FaultToleranceState_Master:
4415 pelmFaultTolerance->setAttribute("state", "master");
4416 break;
4417 case FaultToleranceState_Standby:
4418 pelmFaultTolerance->setAttribute("state", "standby");
4419 break;
4420 }
4421
4422 pelmFaultTolerance->setAttribute("port", machineUserData.uFaultTolerancePort);
4423 pelmFaultTolerance->setAttribute("address", machineUserData.strFaultToleranceAddress);
4424 pelmFaultTolerance->setAttribute("interval", machineUserData.uFaultToleranceInterval);
4425 pelmFaultTolerance->setAttribute("password", machineUserData.strFaultTolerancePassword);
4426 }
4427
4428 if ( (fl & BuildMachineXML_MediaRegistry)
4429 && (m->sv >= SettingsVersion_v1_11)
4430 )
4431 buildMediaRegistry(elmMachine, mediaRegistry);
4432
4433 buildExtraData(elmMachine, mapExtraDataItems);
4434
4435 if ( (fl & BuildMachineXML_IncludeSnapshots)
4436 && llFirstSnapshot.size())
4437 buildSnapshotXML(elmMachine, llFirstSnapshot.front());
4438
4439 buildHardwareXML(elmMachine, hardwareMachine, storageMachine);
4440 buildStorageControllersXML(elmMachine,
4441 storageMachine,
4442 !!(fl & BuildMachineXML_SkipRemovableMedia),
4443 pllElementsWithUuidAttributes);
4444}
4445
4446/**
4447 * Returns true only if the given AudioDriverType is supported on
4448 * the current host platform. For example, this would return false
4449 * for AudioDriverType_DirectSound when compiled on a Linux host.
4450 * @param drv AudioDriverType_* enum to test.
4451 * @return true only if the current host supports that driver.
4452 */
4453/*static*/
4454bool MachineConfigFile::isAudioDriverAllowedOnThisHost(AudioDriverType_T drv)
4455{
4456 switch (drv)
4457 {
4458 case AudioDriverType_Null:
4459#ifdef RT_OS_WINDOWS
4460# ifdef VBOX_WITH_WINMM
4461 case AudioDriverType_WinMM:
4462# endif
4463 case AudioDriverType_DirectSound:
4464#endif /* RT_OS_WINDOWS */
4465#ifdef RT_OS_SOLARIS
4466 case AudioDriverType_SolAudio:
4467#endif
4468#ifdef RT_OS_LINUX
4469# ifdef VBOX_WITH_ALSA
4470 case AudioDriverType_ALSA:
4471# endif
4472# ifdef VBOX_WITH_PULSE
4473 case AudioDriverType_Pulse:
4474# endif
4475#endif /* RT_OS_LINUX */
4476#if defined (RT_OS_LINUX) || defined (RT_OS_FREEBSD) || defined(VBOX_WITH_SOLARIS_OSS)
4477 case AudioDriverType_OSS:
4478#endif
4479#ifdef RT_OS_FREEBSD
4480# ifdef VBOX_WITH_PULSE
4481 case AudioDriverType_Pulse:
4482# endif
4483#endif
4484#ifdef RT_OS_DARWIN
4485 case AudioDriverType_CoreAudio:
4486#endif
4487#ifdef RT_OS_OS2
4488 case AudioDriverType_MMPM:
4489#endif
4490 return true;
4491 }
4492
4493 return false;
4494}
4495
4496/**
4497 * Returns the AudioDriverType_* which should be used by default on this
4498 * host platform. On Linux, this will check at runtime whether PulseAudio
4499 * or ALSA are actually supported on the first call.
4500 * @return
4501 */
4502/*static*/
4503AudioDriverType_T MachineConfigFile::getHostDefaultAudioDriver()
4504{
4505#if defined(RT_OS_WINDOWS)
4506# ifdef VBOX_WITH_WINMM
4507 return AudioDriverType_WinMM;
4508# else /* VBOX_WITH_WINMM */
4509 return AudioDriverType_DirectSound;
4510# endif /* !VBOX_WITH_WINMM */
4511#elif defined(RT_OS_SOLARIS)
4512 return AudioDriverType_SolAudio;
4513#elif defined(RT_OS_LINUX)
4514 // on Linux, we need to check at runtime what's actually supported...
4515 static RTCLockMtx s_mtx;
4516 static AudioDriverType_T s_linuxDriver = -1;
4517 RTCLock lock(s_mtx);
4518 if (s_linuxDriver == (AudioDriverType_T)-1)
4519 {
4520# if defined(VBOX_WITH_PULSE)
4521 /* Check for the pulse library & that the pulse audio daemon is running. */
4522 if (RTProcIsRunningByName("pulseaudio") &&
4523 RTLdrIsLoadable("libpulse.so.0"))
4524 s_linuxDriver = AudioDriverType_Pulse;
4525 else
4526# endif /* VBOX_WITH_PULSE */
4527# if defined(VBOX_WITH_ALSA)
4528 /* Check if we can load the ALSA library */
4529 if (RTLdrIsLoadable("libasound.so.2"))
4530 s_linuxDriver = AudioDriverType_ALSA;
4531 else
4532# endif /* VBOX_WITH_ALSA */
4533 s_linuxDriver = AudioDriverType_OSS;
4534 }
4535 return s_linuxDriver;
4536// end elif defined(RT_OS_LINUX)
4537#elif defined(RT_OS_DARWIN)
4538 return AudioDriverType_CoreAudio;
4539#elif defined(RT_OS_OS2)
4540 return AudioDriverType_MMPM;
4541#elif defined(RT_OS_FREEBSD)
4542 return AudioDriverType_OSS;
4543#else
4544 return AudioDriverType_Null;
4545#endif
4546}
4547
4548/**
4549 * Called from write() before calling ConfigFileBase::createStubDocument().
4550 * This adjusts the settings version in m->sv if incompatible settings require
4551 * a settings bump, whereas otherwise we try to preserve the settings version
4552 * to avoid breaking compatibility with older versions.
4553 *
4554 * We do the checks in here in reverse order: newest first, oldest last, so
4555 * that we avoid unnecessary checks since some of these are expensive.
4556 */
4557void MachineConfigFile::bumpSettingsVersionIfNeeded()
4558{
4559 if (m->sv < SettingsVersion_v1_12)
4560 {
4561 // VirtualBox 4.1 adds PCI passthrough.
4562 if (hardwareMachine.pciAttachments.size())
4563 m->sv = SettingsVersion_v1_12;
4564 }
4565
4566 if (m->sv < SettingsVersion_v1_12)
4567 {
4568 // VirtualBox 4.1 adds a promiscuous mode policy to the network
4569 // adapters and a generic network driver transport.
4570 NetworkAdaptersList::const_iterator netit;
4571 for (netit = hardwareMachine.llNetworkAdapters.begin();
4572 netit != hardwareMachine.llNetworkAdapters.end();
4573 ++netit)
4574 {
4575 if ( netit->enmPromiscModePolicy != NetworkAdapterPromiscModePolicy_Deny
4576 || netit->mode == NetworkAttachmentType_Generic
4577 || !netit->strGenericDriver.isEmpty()
4578 || netit->genericProperties.size()
4579 )
4580 {
4581 m->sv = SettingsVersion_v1_12;
4582 break;
4583 }
4584 }
4585 }
4586
4587 if (m->sv < SettingsVersion_v1_11)
4588 {
4589 // VirtualBox 4.0 adds HD audio, CPU priorities, fault tolerance,
4590 // per-machine media registries, VRDE, JRockitVE, bandwidth gorups,
4591 // ICH9 chipset
4592 if ( hardwareMachine.audioAdapter.controllerType == AudioControllerType_HDA
4593 || hardwareMachine.ulCpuExecutionCap != 100
4594 || machineUserData.enmFaultToleranceState != FaultToleranceState_Inactive
4595 || machineUserData.uFaultTolerancePort
4596 || machineUserData.uFaultToleranceInterval
4597 || !machineUserData.strFaultToleranceAddress.isEmpty()
4598 || mediaRegistry.llHardDisks.size()
4599 || mediaRegistry.llDvdImages.size()
4600 || mediaRegistry.llFloppyImages.size()
4601 || !hardwareMachine.vrdeSettings.strVrdeExtPack.isEmpty()
4602 || !hardwareMachine.vrdeSettings.strAuthLibrary.isEmpty()
4603 || machineUserData.strOsType == "JRockitVE"
4604 || hardwareMachine.ioSettings.llBandwidthGroups.size()
4605 || hardwareMachine.chipsetType == ChipsetType_ICH9
4606 )
4607 m->sv = SettingsVersion_v1_11;
4608 }
4609
4610 if (m->sv < SettingsVersion_v1_10)
4611 {
4612 /* If the properties contain elements other than "TCP/Ports" and "TCP/Address",
4613 * then increase the version to at least VBox 3.2, which can have video channel properties.
4614 */
4615 unsigned cOldProperties = 0;
4616
4617 StringsMap::const_iterator it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Ports");
4618 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4619 cOldProperties++;
4620 it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Address");
4621 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4622 cOldProperties++;
4623
4624 if (hardwareMachine.vrdeSettings.mapProperties.size() != cOldProperties)
4625 m->sv = SettingsVersion_v1_10;
4626 }
4627
4628 if (m->sv < SettingsVersion_v1_11)
4629 {
4630 /* If the properties contain elements other than "TCP/Ports", "TCP/Address",
4631 * "VideoChannel/Enabled" and "VideoChannel/Quality" then increase the version to VBox 4.0.
4632 */
4633 unsigned cOldProperties = 0;
4634
4635 StringsMap::const_iterator it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Ports");
4636 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4637 cOldProperties++;
4638 it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Address");
4639 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4640 cOldProperties++;
4641 it = hardwareMachine.vrdeSettings.mapProperties.find("VideoChannel/Enabled");
4642 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4643 cOldProperties++;
4644 it = hardwareMachine.vrdeSettings.mapProperties.find("VideoChannel/Quality");
4645 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4646 cOldProperties++;
4647
4648 if (hardwareMachine.vrdeSettings.mapProperties.size() != cOldProperties)
4649 m->sv = SettingsVersion_v1_11;
4650 }
4651
4652 // settings version 1.9 is required if there is not exactly one DVD
4653 // or more than one floppy drive present or the DVD is not at the secondary
4654 // master; this check is a bit more complicated
4655 //
4656 // settings version 1.10 is required if the host cache should be disabled
4657 //
4658 // settings version 1.11 is required for bandwidth limits and if more than
4659 // one controller of each type is present.
4660 if (m->sv < SettingsVersion_v1_11)
4661 {
4662 // count attached DVDs and floppies (only if < v1.9)
4663 size_t cDVDs = 0;
4664 size_t cFloppies = 0;
4665
4666 // count storage controllers (if < v1.11)
4667 size_t cSata = 0;
4668 size_t cScsiLsi = 0;
4669 size_t cScsiBuslogic = 0;
4670 size_t cSas = 0;
4671 size_t cIde = 0;
4672 size_t cFloppy = 0;
4673
4674 // need to run thru all the storage controllers and attached devices to figure this out
4675 for (StorageControllersList::const_iterator it = storageMachine.llStorageControllers.begin();
4676 it != storageMachine.llStorageControllers.end();
4677 ++it)
4678 {
4679 const StorageController &sctl = *it;
4680
4681 // count storage controllers of each type; 1.11 is required if more than one
4682 // controller of one type is present
4683 switch (sctl.storageBus)
4684 {
4685 case StorageBus_IDE:
4686 cIde++;
4687 break;
4688 case StorageBus_SATA:
4689 cSata++;
4690 break;
4691 case StorageBus_SAS:
4692 cSas++;
4693 break;
4694 case StorageBus_SCSI:
4695 if (sctl.controllerType == StorageControllerType_LsiLogic)
4696 cScsiLsi++;
4697 else
4698 cScsiBuslogic++;
4699 break;
4700 case StorageBus_Floppy:
4701 cFloppy++;
4702 break;
4703 default:
4704 // Do nothing
4705 break;
4706 }
4707
4708 if ( cSata > 1
4709 || cScsiLsi > 1
4710 || cScsiBuslogic > 1
4711 || cSas > 1
4712 || cIde > 1
4713 || cFloppy > 1)
4714 {
4715 m->sv = SettingsVersion_v1_11;
4716 break; // abort the loop -- we will not raise the version further
4717 }
4718
4719 for (AttachedDevicesList::const_iterator it2 = sctl.llAttachedDevices.begin();
4720 it2 != sctl.llAttachedDevices.end();
4721 ++it2)
4722 {
4723 const AttachedDevice &att = *it2;
4724
4725 // Bandwidth limitations are new in VirtualBox 4.0 (1.11)
4726 if (m->sv < SettingsVersion_v1_11)
4727 {
4728 if (att.strBwGroup.length() != 0)
4729 {
4730 m->sv = SettingsVersion_v1_11;
4731 break; // abort the loop -- we will not raise the version further
4732 }
4733 }
4734
4735 // disabling the host IO cache requires settings version 1.10
4736 if ( (m->sv < SettingsVersion_v1_10)
4737 && (!sctl.fUseHostIOCache)
4738 )
4739 m->sv = SettingsVersion_v1_10;
4740
4741 // we can only write the StorageController/@Instance attribute with v1.9
4742 if ( (m->sv < SettingsVersion_v1_9)
4743 && (sctl.ulInstance != 0)
4744 )
4745 m->sv = SettingsVersion_v1_9;
4746
4747 if (m->sv < SettingsVersion_v1_9)
4748 {
4749 if (att.deviceType == DeviceType_DVD)
4750 {
4751 if ( (sctl.storageBus != StorageBus_IDE) // DVD at bus other than DVD?
4752 || (att.lPort != 1) // DVDs not at secondary master?
4753 || (att.lDevice != 0)
4754 )
4755 m->sv = SettingsVersion_v1_9;
4756
4757 ++cDVDs;
4758 }
4759 else if (att.deviceType == DeviceType_Floppy)
4760 ++cFloppies;
4761 }
4762 }
4763
4764 if (m->sv >= SettingsVersion_v1_11)
4765 break; // abort the loop -- we will not raise the version further
4766 }
4767
4768 // VirtualBox before 3.1 had zero or one floppy and exactly one DVD,
4769 // so any deviation from that will require settings version 1.9
4770 if ( (m->sv < SettingsVersion_v1_9)
4771 && ( (cDVDs != 1)
4772 || (cFloppies > 1)
4773 )
4774 )
4775 m->sv = SettingsVersion_v1_9;
4776 }
4777
4778 // VirtualBox 3.2: Check for non default I/O settings
4779 if (m->sv < SettingsVersion_v1_10)
4780 {
4781 if ( (hardwareMachine.ioSettings.fIoCacheEnabled != true)
4782 || (hardwareMachine.ioSettings.ulIoCacheSize != 5)
4783 // and page fusion
4784 || (hardwareMachine.fPageFusionEnabled)
4785 // and CPU hotplug, RTC timezone control, HID type and HPET
4786 || machineUserData.fRTCUseUTC
4787 || hardwareMachine.fCpuHotPlug
4788 || hardwareMachine.pointingHidType != PointingHidType_PS2Mouse
4789 || hardwareMachine.keyboardHidType != KeyboardHidType_PS2Keyboard
4790 || hardwareMachine.fHpetEnabled
4791 )
4792 m->sv = SettingsVersion_v1_10;
4793 }
4794
4795 // VirtualBox 3.2 adds NAT and boot priority to the NIC config in Main
4796 // VirtualBox 4.0 adds network bandwitdth
4797 if (m->sv < SettingsVersion_v1_11)
4798 {
4799 NetworkAdaptersList::const_iterator netit;
4800 for (netit = hardwareMachine.llNetworkAdapters.begin();
4801 netit != hardwareMachine.llNetworkAdapters.end();
4802 ++netit)
4803 {
4804 if ( (m->sv < SettingsVersion_v1_12)
4805 && (netit->strBandwidthGroup.isNotEmpty())
4806 )
4807 {
4808 /* New in VirtualBox 4.1 */
4809 m->sv = SettingsVersion_v1_12;
4810 break;
4811 }
4812 else if ( (m->sv < SettingsVersion_v1_10)
4813 && (netit->fEnabled)
4814 && (netit->mode == NetworkAttachmentType_NAT)
4815 && ( netit->nat.u32Mtu != 0
4816 || netit->nat.u32SockRcv != 0
4817 || netit->nat.u32SockSnd != 0
4818 || netit->nat.u32TcpRcv != 0
4819 || netit->nat.u32TcpSnd != 0
4820 || !netit->nat.fDnsPassDomain
4821 || netit->nat.fDnsProxy
4822 || netit->nat.fDnsUseHostResolver
4823 || netit->nat.fAliasLog
4824 || netit->nat.fAliasProxyOnly
4825 || netit->nat.fAliasUseSamePorts
4826 || netit->nat.strTftpPrefix.length()
4827 || netit->nat.strTftpBootFile.length()
4828 || netit->nat.strTftpNextServer.length()
4829 || netit->nat.llRules.size()
4830 )
4831 )
4832 {
4833 m->sv = SettingsVersion_v1_10;
4834 // no break because we still might need v1.11 above
4835 }
4836 else if ( (m->sv < SettingsVersion_v1_10)
4837 && (netit->fEnabled)
4838 && (netit->ulBootPriority != 0)
4839 )
4840 {
4841 m->sv = SettingsVersion_v1_10;
4842 // no break because we still might need v1.11 above
4843 }
4844 }
4845 }
4846
4847 // all the following require settings version 1.9
4848 if ( (m->sv < SettingsVersion_v1_9)
4849 && ( (hardwareMachine.firmwareType >= FirmwareType_EFI)
4850 || (hardwareMachine.fHardwareVirtExclusive != HWVIRTEXCLUSIVEDEFAULT)
4851 || machineUserData.fTeleporterEnabled
4852 || machineUserData.uTeleporterPort
4853 || !machineUserData.strTeleporterAddress.isEmpty()
4854 || !machineUserData.strTeleporterPassword.isEmpty()
4855 || !hardwareMachine.uuid.isEmpty()
4856 )
4857 )
4858 m->sv = SettingsVersion_v1_9;
4859
4860 // "accelerate 2d video" requires settings version 1.8
4861 if ( (m->sv < SettingsVersion_v1_8)
4862 && (hardwareMachine.fAccelerate2DVideo)
4863 )
4864 m->sv = SettingsVersion_v1_8;
4865
4866 // The hardware versions other than "1" requires settings version 1.4 (2.1+).
4867 if ( m->sv < SettingsVersion_v1_4
4868 && hardwareMachine.strVersion != "1"
4869 )
4870 m->sv = SettingsVersion_v1_4;
4871}
4872
4873/**
4874 * Called from Main code to write a machine config file to disk. This builds a DOM tree from
4875 * the member variables and then writes the XML file; it throws xml::Error instances on errors,
4876 * in particular if the file cannot be written.
4877 */
4878void MachineConfigFile::write(const com::Utf8Str &strFilename)
4879{
4880 try
4881 {
4882 // createStubDocument() sets the settings version to at least 1.7; however,
4883 // we might need to enfore a later settings version if incompatible settings
4884 // are present:
4885 bumpSettingsVersionIfNeeded();
4886
4887 m->strFilename = strFilename;
4888 createStubDocument();
4889
4890 xml::ElementNode *pelmMachine = m->pelmRoot->createChild("Machine");
4891 buildMachineXML(*pelmMachine,
4892 MachineConfigFile::BuildMachineXML_IncludeSnapshots
4893 | MachineConfigFile::BuildMachineXML_MediaRegistry,
4894 // but not BuildMachineXML_WriteVboxVersionAttribute
4895 NULL); /* pllElementsWithUuidAttributes */
4896
4897 // now go write the XML
4898 xml::XmlFileWriter writer(*m->pDoc);
4899 writer.write(m->strFilename.c_str(), true /*fSafe*/);
4900
4901 m->fFileExists = true;
4902 clearDocument();
4903 }
4904 catch (...)
4905 {
4906 clearDocument();
4907 throw;
4908 }
4909}
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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