VirtualBox

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

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

Main/Settings: prepare for 5.2 settings, without anything actually needing it

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Revision Author Id
File size: 295.2 KB
Line 
1/* $Id: Settings.cpp 67608 2017-06-26 13:33:35Z 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 * VBOX_XML_VERSION does not have to be changed if the settings for a default VM do not
20 * touch newly introduced attributes or tags. It has the benefit that older VirtualBox
21 * versions do not trigger their "newer" code path.
22 *
23 * Once a new settings version has been added, these are the rules for introducing a new
24 * setting: If an XML element or attribute or value is introduced that was not present in
25 * previous versions, then settings version checks need to be introduced. See the
26 * SettingsVersion enumeration in src/VBox/Main/idl/VirtualBox.xidl for details about which
27 * version was used when.
28 *
29 * The settings versions checks are necessary because since version 3.1, VirtualBox no longer
30 * automatically converts XML settings files but only if necessary, that is, if settings are
31 * present that the old format does not support. If we write an element or attribute to a
32 * settings file of an older version, then an old VirtualBox (before 3.1) will attempt to
33 * validate it with XML schema, and that will certainly fail.
34 *
35 * So, to introduce a new setting:
36 *
37 * 1) Make sure the constructor of corresponding settings structure has a proper default.
38 *
39 * 2) In the settings reader method, try to read the setting; if it's there, great, if not,
40 * the default value will have been set by the constructor. The rule is to be tolerant
41 * here.
42 *
43 * 3) In MachineConfigFile::bumpSettingsVersionIfNeeded(), check if the new setting has
44 * a non-default value (i.e. that differs from the constructor). If so, bump the
45 * settings version to the current version so the settings writer (4) can write out
46 * the non-default value properly.
47 *
48 * So far a corresponding method for MainConfigFile has not been necessary since there
49 * have been no incompatible changes yet.
50 *
51 * 4) In the settings writer method, write the setting _only_ if the current settings
52 * version (stored in m->sv) is high enough. That is, for VirtualBox 4.0, write it
53 * only if (m->sv >= SettingsVersion_v1_11).
54 *
55 * 5) You _must_ update xml/VirtalBox-settings.xsd to contain the new tags and attributes.
56 * Check that settings file from before and after your change are validating properly.
57 * Use "kmk testvalidsettings", it should not find any files which don't validate.
58 */
59
60/*
61 * Copyright (C) 2007-2016 Oracle Corporation
62 *
63 * This file is part of VirtualBox Open Source Edition (OSE), as
64 * available from http://www.virtualbox.org. This file is free software;
65 * you can redistribute it and/or modify it under the terms of the GNU
66 * General Public License (GPL) as published by the Free Software
67 * Foundation, in version 2 as it comes in the "COPYING" file of the
68 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
69 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
70 */
71
72#include "VBox/com/string.h"
73#include "VBox/settings.h"
74#include <iprt/cpp/xml.h>
75#include <iprt/stream.h>
76#include <iprt/ctype.h>
77#include <iprt/file.h>
78#include <iprt/process.h>
79#include <iprt/ldr.h>
80#include <iprt/base64.h>
81#include <iprt/cpp/lock.h>
82
83// generated header
84#include "SchemaDefs.h"
85
86#include "Logging.h"
87#include "HashedPw.h"
88
89using namespace com;
90using namespace settings;
91
92////////////////////////////////////////////////////////////////////////////////
93//
94// Defines
95//
96////////////////////////////////////////////////////////////////////////////////
97
98/** VirtualBox XML settings namespace */
99#define VBOX_XML_NAMESPACE "http://www.virtualbox.org/"
100
101/** VirtualBox XML schema location (relative URI) */
102#define VBOX_XML_SCHEMA "VirtualBox-settings.xsd"
103
104/** VirtualBox XML settings version number substring ("x.y") */
105#define VBOX_XML_VERSION "1.12"
106
107/** VirtualBox OVF settings import default version number substring ("x.y").
108 *
109 * Think twice before changing this, as all VirtualBox versions before 5.1
110 * wrote the settings version when exporting, but totally ignored it on
111 * importing (while it should have been a mandatory attribute), so 3rd party
112 * software out there creates OVF files with the VirtualBox specific settings
113 * but lacking the version attribute. This shouldn't happen any more, but
114 * breaking existing OVF files isn't nice. */
115#define VBOX_XML_IMPORT_VERSION "1.15"
116
117/** VirtualBox XML settings version platform substring */
118#if defined (RT_OS_DARWIN)
119# define VBOX_XML_PLATFORM "macosx"
120#elif defined (RT_OS_FREEBSD)
121# define VBOX_XML_PLATFORM "freebsd"
122#elif defined (RT_OS_LINUX)
123# define VBOX_XML_PLATFORM "linux"
124#elif defined (RT_OS_NETBSD)
125# define VBOX_XML_PLATFORM "netbsd"
126#elif defined (RT_OS_OPENBSD)
127# define VBOX_XML_PLATFORM "openbsd"
128#elif defined (RT_OS_OS2)
129# define VBOX_XML_PLATFORM "os2"
130#elif defined (RT_OS_SOLARIS)
131# define VBOX_XML_PLATFORM "solaris"
132#elif defined (RT_OS_WINDOWS)
133# define VBOX_XML_PLATFORM "windows"
134#else
135# error Unsupported platform!
136#endif
137
138/** VirtualBox XML settings full version string ("x.y-platform") */
139#define VBOX_XML_VERSION_FULL VBOX_XML_VERSION "-" VBOX_XML_PLATFORM
140
141/** VirtualBox OVF import default settings full version string ("x.y-platform") */
142#define VBOX_XML_IMPORT_VERSION_FULL VBOX_XML_IMPORT_VERSION "-" VBOX_XML_PLATFORM
143
144////////////////////////////////////////////////////////////////////////////////
145//
146// Internal data
147//
148////////////////////////////////////////////////////////////////////////////////
149
150/**
151 * Opaque data structore for ConfigFileBase (only declared
152 * in header, defined only here).
153 */
154
155struct ConfigFileBase::Data
156{
157 Data()
158 : pDoc(NULL),
159 pelmRoot(NULL),
160 sv(SettingsVersion_Null),
161 svRead(SettingsVersion_Null)
162 {}
163
164 ~Data()
165 {
166 cleanup();
167 }
168
169 RTCString strFilename;
170 bool fFileExists;
171
172 xml::Document *pDoc;
173 xml::ElementNode *pelmRoot;
174
175 com::Utf8Str strSettingsVersionFull; // e.g. "1.7-linux"
176 SettingsVersion_T sv; // e.g. SettingsVersion_v1_7
177
178 SettingsVersion_T svRead; // settings version that the original file had when it was read,
179 // or SettingsVersion_Null if none
180
181 void copyFrom(const Data &d)
182 {
183 strFilename = d.strFilename;
184 fFileExists = d.fFileExists;
185 strSettingsVersionFull = d.strSettingsVersionFull;
186 sv = d.sv;
187 svRead = d.svRead;
188 }
189
190 void cleanup()
191 {
192 if (pDoc)
193 {
194 delete pDoc;
195 pDoc = NULL;
196 pelmRoot = NULL;
197 }
198 }
199};
200
201/**
202 * Private exception class (not in the header file) that makes
203 * throwing xml::LogicError instances easier. That class is public
204 * and should be caught by client code.
205 */
206class settings::ConfigFileError : public xml::LogicError
207{
208public:
209 ConfigFileError(const ConfigFileBase *file,
210 const xml::Node *pNode,
211 const char *pcszFormat, ...)
212 : xml::LogicError()
213 {
214 va_list args;
215 va_start(args, pcszFormat);
216 Utf8Str strWhat(pcszFormat, args);
217 va_end(args);
218
219 Utf8Str strLine;
220 if (pNode)
221 strLine = Utf8StrFmt(" (line %RU32)", pNode->getLineNumber());
222
223 const char *pcsz = strLine.c_str();
224 Utf8StrFmt str(N_("Error in %s%s -- %s"),
225 file->m->strFilename.c_str(),
226 (pcsz) ? pcsz : "",
227 strWhat.c_str());
228
229 setWhat(str.c_str());
230 }
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 pstrFilename
243 */
244ConfigFileBase::ConfigFileBase(const com::Utf8Str *pstrFilename)
245 : m(new Data)
246{
247 m->fFileExists = false;
248
249 if (pstrFilename)
250 {
251 // reading existing settings file:
252 m->strFilename = *pstrFilename;
253
254 xml::XmlFileParser parser;
255 m->pDoc = new xml::Document;
256 parser.read(*pstrFilename,
257 *m->pDoc);
258
259 m->fFileExists = true;
260
261 m->pelmRoot = m->pDoc->getRootElement();
262 if (!m->pelmRoot || !m->pelmRoot->nameEquals("VirtualBox"))
263 throw ConfigFileError(this, m->pelmRoot, N_("Root element in VirtualBox settings files must be \"VirtualBox\""));
264
265 if (!(m->pelmRoot->getAttributeValue("version", m->strSettingsVersionFull)))
266 throw ConfigFileError(this, m->pelmRoot, N_("Required VirtualBox/@version attribute is missing"));
267
268 LogRel(("Loading settings file \"%s\" with version \"%s\"\n", m->strFilename.c_str(), m->strSettingsVersionFull.c_str()));
269
270 m->sv = parseVersion(m->strSettingsVersionFull, m->pelmRoot);
271
272 // remember the settings version we read in case it gets upgraded later,
273 // so we know when to make backups
274 m->svRead = m->sv;
275 }
276 else
277 {
278 // creating new settings file:
279 m->strSettingsVersionFull = VBOX_XML_VERSION_FULL;
280 m->sv = SettingsVersion_v1_12;
281 }
282}
283
284ConfigFileBase::ConfigFileBase(const ConfigFileBase &other)
285 : m(new Data)
286{
287 copyBaseFrom(other);
288 m->strFilename = "";
289 m->fFileExists = false;
290}
291
292/**
293 * Clean up.
294 */
295ConfigFileBase::~ConfigFileBase()
296{
297 if (m)
298 {
299 delete m;
300 m = NULL;
301 }
302}
303
304/**
305 * Helper function to convert a MediaType enum value into string from.
306 * @param t
307 */
308/*static*/
309const char *ConfigFileBase::stringifyMediaType(MediaType t)
310{
311 switch (t)
312 {
313 case HardDisk:
314 return "hard disk";
315 case DVDImage:
316 return "DVD";
317 case FloppyImage:
318 return "floppy";
319 default:
320 AssertMsgFailed(("media type %d\n", t));
321 return "UNKNOWN";
322 }
323}
324
325/**
326 * Helper function that parses a full version number.
327 *
328 * Allow future versions but fail if file is older than 1.6. Throws on errors.
329 * @returns settings version
330 * @param strVersion
331 * @param pElm
332 */
333SettingsVersion_T ConfigFileBase::parseVersion(const Utf8Str &strVersion, const xml::ElementNode *pElm)
334{
335 SettingsVersion_T sv = SettingsVersion_Null;
336 if (strVersion.length() > 3)
337 {
338 uint32_t ulMajor = 0;
339 uint32_t ulMinor = 0;
340
341 const char *pcsz = strVersion.c_str();
342 char c;
343
344 while ( (c = *pcsz)
345 && RT_C_IS_DIGIT(c)
346 )
347 {
348 ulMajor *= 10;
349 ulMajor += c - '0';
350 ++pcsz;
351 }
352
353 if (*pcsz++ == '.')
354 {
355 while ( (c = *pcsz)
356 && RT_C_IS_DIGIT(c)
357 )
358 {
359 ulMinor *= 10;
360 ulMinor += c - '0';
361 ++pcsz;
362 }
363 }
364
365 if (ulMajor == 1)
366 {
367 if (ulMinor == 3)
368 sv = SettingsVersion_v1_3;
369 else if (ulMinor == 4)
370 sv = SettingsVersion_v1_4;
371 else if (ulMinor == 5)
372 sv = SettingsVersion_v1_5;
373 else if (ulMinor == 6)
374 sv = SettingsVersion_v1_6;
375 else if (ulMinor == 7)
376 sv = SettingsVersion_v1_7;
377 else if (ulMinor == 8)
378 sv = SettingsVersion_v1_8;
379 else if (ulMinor == 9)
380 sv = SettingsVersion_v1_9;
381 else if (ulMinor == 10)
382 sv = SettingsVersion_v1_10;
383 else if (ulMinor == 11)
384 sv = SettingsVersion_v1_11;
385 else if (ulMinor == 12)
386 sv = SettingsVersion_v1_12;
387 else if (ulMinor == 13)
388 sv = SettingsVersion_v1_13;
389 else if (ulMinor == 14)
390 sv = SettingsVersion_v1_14;
391 else if (ulMinor == 15)
392 sv = SettingsVersion_v1_15;
393 else if (ulMinor == 16)
394 sv = SettingsVersion_v1_16;
395 else if (ulMinor == 17)
396 sv = SettingsVersion_v1_17;
397 else if (ulMinor > 17)
398 sv = SettingsVersion_Future;
399 }
400 else if (ulMajor > 1)
401 sv = SettingsVersion_Future;
402
403 Log(("Parsed settings version %d.%d to enum value %d\n", ulMajor, ulMinor, sv));
404 }
405
406 if (sv == SettingsVersion_Null)
407 throw ConfigFileError(this, pElm, N_("Cannot handle settings version '%s'"), strVersion.c_str());
408
409 return sv;
410}
411
412/**
413 * Helper function that parses a UUID in string form into
414 * a com::Guid item. Accepts UUIDs both with and without
415 * "{}" brackets. Throws on errors.
416 * @param guid
417 * @param strUUID
418 * @param pElm
419 */
420void ConfigFileBase::parseUUID(Guid &guid,
421 const Utf8Str &strUUID,
422 const xml::ElementNode *pElm) const
423{
424 guid = strUUID.c_str();
425 if (guid.isZero())
426 throw ConfigFileError(this, pElm, N_("UUID \"%s\" has zero format"), strUUID.c_str());
427 else if (!guid.isValid())
428 throw ConfigFileError(this, pElm, N_("UUID \"%s\" has invalid format"), strUUID.c_str());
429}
430
431/**
432 * Parses the given string in str and attempts to treat it as an ISO
433 * date/time stamp to put into timestamp. Throws on errors.
434 * @param timestamp
435 * @param str
436 * @param pElm
437 */
438void ConfigFileBase::parseTimestamp(RTTIMESPEC &timestamp,
439 const com::Utf8Str &str,
440 const xml::ElementNode *pElm) const
441{
442 const char *pcsz = str.c_str();
443 // yyyy-mm-ddThh:mm:ss
444 // "2009-07-10T11:54:03Z"
445 // 01234567890123456789
446 // 1
447 if (str.length() > 19)
448 {
449 // timezone must either be unspecified or 'Z' for UTC
450 if ( (pcsz[19])
451 && (pcsz[19] != 'Z')
452 )
453 throw ConfigFileError(this, pElm, N_("Cannot handle ISO timestamp '%s': is not UTC date"), str.c_str());
454
455 int32_t yyyy;
456 uint32_t mm, dd, hh, min, secs;
457 if ( (pcsz[4] == '-')
458 && (pcsz[7] == '-')
459 && (pcsz[10] == 'T')
460 && (pcsz[13] == ':')
461 && (pcsz[16] == ':')
462 )
463 {
464 int rc;
465 if ( (RT_SUCCESS(rc = RTStrToInt32Ex(pcsz, NULL, 0, &yyyy)))
466 // could theoretically be negative but let's assume that nobody
467 // created virtual machines before the Christian era
468 && (RT_SUCCESS(rc = RTStrToUInt32Ex(pcsz + 5, NULL, 0, &mm)))
469 && (RT_SUCCESS(rc = RTStrToUInt32Ex(pcsz + 8, NULL, 0, &dd)))
470 && (RT_SUCCESS(rc = RTStrToUInt32Ex(pcsz + 11, NULL, 0, &hh)))
471 && (RT_SUCCESS(rc = RTStrToUInt32Ex(pcsz + 14, NULL, 0, &min)))
472 && (RT_SUCCESS(rc = RTStrToUInt32Ex(pcsz + 17, NULL, 0, &secs)))
473 )
474 {
475 RTTIME time =
476 {
477 yyyy,
478 (uint8_t)mm,
479 0,
480 0,
481 (uint8_t)dd,
482 (uint8_t)hh,
483 (uint8_t)min,
484 (uint8_t)secs,
485 0,
486 RTTIME_FLAGS_TYPE_UTC,
487 0
488 };
489 if (RTTimeNormalize(&time))
490 if (RTTimeImplode(&timestamp, &time))
491 return;
492 }
493
494 throw ConfigFileError(this, pElm, N_("Cannot parse ISO timestamp '%s': runtime error, %Rra"), str.c_str(), rc);
495 }
496
497 throw ConfigFileError(this, pElm, N_("Cannot parse ISO timestamp '%s': invalid format"), str.c_str());
498 }
499}
500
501/**
502 * Helper function that parses a Base64 formatted string into a binary blob.
503 * @param binary
504 * @param str
505 * @param pElm
506 */
507void ConfigFileBase::parseBase64(IconBlob &binary,
508 const Utf8Str &str,
509 const xml::ElementNode *pElm) const
510{
511#define DECODE_STR_MAX _1M
512 const char* psz = str.c_str();
513 ssize_t cbOut = RTBase64DecodedSize(psz, NULL);
514 if (cbOut > DECODE_STR_MAX)
515 throw ConfigFileError(this, pElm, N_("Base64 encoded data too long (%d > %d)"), cbOut, DECODE_STR_MAX);
516 else if (cbOut < 0)
517 throw ConfigFileError(this, pElm, N_("Base64 encoded data '%s' invalid"), psz);
518 binary.resize(cbOut);
519 int vrc = VINF_SUCCESS;
520 if (cbOut)
521 vrc = RTBase64Decode(psz, &binary.front(), cbOut, NULL, NULL);
522 if (RT_FAILURE(vrc))
523 {
524 binary.resize(0);
525 throw ConfigFileError(this, pElm, N_("Base64 encoded data could not be decoded (%Rrc)"), vrc);
526 }
527}
528
529/**
530 * Helper to create a string for a RTTIMESPEC for writing out ISO timestamps.
531 * @param stamp
532 * @return
533 */
534com::Utf8Str ConfigFileBase::stringifyTimestamp(const RTTIMESPEC &stamp) const
535{
536 RTTIME time;
537 if (!RTTimeExplode(&time, &stamp))
538 throw ConfigFileError(this, NULL, N_("Timespec %lld ms is invalid"), RTTimeSpecGetMilli(&stamp));
539
540 return Utf8StrFmt("%04u-%02u-%02uT%02u:%02u:%02uZ",
541 time.i32Year, time.u8Month, time.u8MonthDay,
542 time.u8Hour, time.u8Minute, time.u8Second);
543}
544
545/**
546 * Helper to create a base64 encoded string out of a binary blob.
547 * @param str
548 * @param binary
549 */
550void ConfigFileBase::toBase64(com::Utf8Str &str, const IconBlob &binary) const
551{
552 ssize_t cb = binary.size();
553 if (cb > 0)
554 {
555 ssize_t cchOut = RTBase64EncodedLength(cb);
556 str.reserve(cchOut+1);
557 int vrc = RTBase64Encode(&binary.front(), cb,
558 str.mutableRaw(), str.capacity(),
559 NULL);
560 if (RT_FAILURE(vrc))
561 throw ConfigFileError(this, NULL, N_("Failed to convert binary data to base64 format (%Rrc)"), vrc);
562 str.jolt();
563 }
564}
565
566/**
567 * Helper method to read in an ExtraData subtree and stores its contents
568 * in the given map of extradata items. Used for both main and machine
569 * extradata (MainConfigFile and MachineConfigFile).
570 * @param elmExtraData
571 * @param map
572 */
573void ConfigFileBase::readExtraData(const xml::ElementNode &elmExtraData,
574 StringsMap &map)
575{
576 xml::NodesLoop nlLevel4(elmExtraData);
577 const xml::ElementNode *pelmExtraDataItem;
578 while ((pelmExtraDataItem = nlLevel4.forAllNodes()))
579 {
580 if (pelmExtraDataItem->nameEquals("ExtraDataItem"))
581 {
582 // <ExtraDataItem name="GUI/LastWindowPostion" value="97,88,981,858"/>
583 Utf8Str strName, strValue;
584 if ( pelmExtraDataItem->getAttributeValue("name", strName)
585 && pelmExtraDataItem->getAttributeValue("value", strValue) )
586 map[strName] = strValue;
587 else
588 throw ConfigFileError(this, pelmExtraDataItem, N_("Required ExtraDataItem/@name or @value attribute is missing"));
589 }
590 }
591}
592
593/**
594 * Reads \<USBDeviceFilter\> entries from under the given elmDeviceFilters node and
595 * stores them in the given linklist. This is in ConfigFileBase because it's used
596 * from both MainConfigFile (for host filters) and MachineConfigFile (for machine
597 * filters).
598 * @param elmDeviceFilters
599 * @param ll
600 */
601void ConfigFileBase::readUSBDeviceFilters(const xml::ElementNode &elmDeviceFilters,
602 USBDeviceFiltersList &ll)
603{
604 xml::NodesLoop nl1(elmDeviceFilters, "DeviceFilter");
605 const xml::ElementNode *pelmLevel4Child;
606 while ((pelmLevel4Child = nl1.forAllNodes()))
607 {
608 USBDeviceFilter flt;
609 flt.action = USBDeviceFilterAction_Ignore;
610 Utf8Str strAction;
611 if ( pelmLevel4Child->getAttributeValue("name", flt.strName)
612 && pelmLevel4Child->getAttributeValue("active", flt.fActive))
613 {
614 if (!pelmLevel4Child->getAttributeValue("vendorId", flt.strVendorId))
615 pelmLevel4Child->getAttributeValue("vendorid", flt.strVendorId); // used before 1.3
616 if (!pelmLevel4Child->getAttributeValue("productId", flt.strProductId))
617 pelmLevel4Child->getAttributeValue("productid", flt.strProductId); // used before 1.3
618 pelmLevel4Child->getAttributeValue("revision", flt.strRevision);
619 pelmLevel4Child->getAttributeValue("manufacturer", flt.strManufacturer);
620 pelmLevel4Child->getAttributeValue("product", flt.strProduct);
621 if (!pelmLevel4Child->getAttributeValue("serialNumber", flt.strSerialNumber))
622 pelmLevel4Child->getAttributeValue("serialnumber", flt.strSerialNumber); // used before 1.3
623 pelmLevel4Child->getAttributeValue("port", flt.strPort);
624
625 // the next 2 are irrelevant for host USB objects
626 pelmLevel4Child->getAttributeValue("remote", flt.strRemote);
627 pelmLevel4Child->getAttributeValue("maskedInterfaces", flt.ulMaskedInterfaces);
628
629 // action is only used with host USB objects
630 if (pelmLevel4Child->getAttributeValue("action", strAction))
631 {
632 if (strAction == "Ignore")
633 flt.action = USBDeviceFilterAction_Ignore;
634 else if (strAction == "Hold")
635 flt.action = USBDeviceFilterAction_Hold;
636 else
637 throw ConfigFileError(this, pelmLevel4Child, N_("Invalid value '%s' in DeviceFilter/@action attribute"), strAction.c_str());
638 }
639
640 ll.push_back(flt);
641 }
642 }
643}
644
645/**
646 * Reads a media registry entry from the main VirtualBox.xml file.
647 *
648 * Whereas the current media registry code is fairly straightforward, it was quite a mess
649 * with settings format before 1.4 (VirtualBox 2.0 used settings format 1.3). The elements
650 * in the media registry were much more inconsistent, and different elements were used
651 * depending on the type of device and image.
652 *
653 * @param t
654 * @param elmMedium
655 * @param med
656 */
657void ConfigFileBase::readMediumOne(MediaType t,
658 const xml::ElementNode &elmMedium,
659 Medium &med)
660{
661 // <HardDisk uuid="{5471ecdb-1ddb-4012-a801-6d98e226868b}" location="/mnt/innotek-unix/vdis/Windows XP.vdi" format="VDI" type="Normal">
662
663 Utf8Str strUUID;
664 if (!elmMedium.getAttributeValue("uuid", strUUID))
665 throw ConfigFileError(this, &elmMedium, N_("Required %s/@uuid attribute is missing"), elmMedium.getName());
666
667 parseUUID(med.uuid, strUUID, &elmMedium);
668
669 bool fNeedsLocation = true;
670
671 if (t == HardDisk)
672 {
673 if (m->sv < SettingsVersion_v1_4)
674 {
675 // here the system is:
676 // <HardDisk uuid="{....}" type="normal">
677 // <VirtualDiskImage filePath="/path/to/xxx.vdi"/>
678 // </HardDisk>
679
680 fNeedsLocation = false;
681 bool fNeedsFilePath = true;
682 const xml::ElementNode *pelmImage;
683 if ((pelmImage = elmMedium.findChildElement("VirtualDiskImage")))
684 med.strFormat = "VDI";
685 else if ((pelmImage = elmMedium.findChildElement("VMDKImage")))
686 med.strFormat = "VMDK";
687 else if ((pelmImage = elmMedium.findChildElement("VHDImage")))
688 med.strFormat = "VHD";
689 else if ((pelmImage = elmMedium.findChildElement("ISCSIHardDisk")))
690 {
691 med.strFormat = "iSCSI";
692
693 fNeedsFilePath = false;
694 // location is special here: current settings specify an "iscsi://user@server:port/target/lun"
695 // string for the location and also have several disk properties for these, whereas this used
696 // to be hidden in several sub-elements before 1.4, so compose a location string and set up
697 // the properties:
698 med.strLocation = "iscsi://";
699 Utf8Str strUser, strServer, strPort, strTarget, strLun;
700 if (pelmImage->getAttributeValue("userName", strUser))
701 {
702 med.strLocation.append(strUser);
703 med.strLocation.append("@");
704 }
705 Utf8Str strServerAndPort;
706 if (pelmImage->getAttributeValue("server", strServer))
707 {
708 strServerAndPort = strServer;
709 }
710 if (pelmImage->getAttributeValue("port", strPort))
711 {
712 if (strServerAndPort.length())
713 strServerAndPort.append(":");
714 strServerAndPort.append(strPort);
715 }
716 med.strLocation.append(strServerAndPort);
717 if (pelmImage->getAttributeValue("target", strTarget))
718 {
719 med.strLocation.append("/");
720 med.strLocation.append(strTarget);
721 }
722 if (pelmImage->getAttributeValue("lun", strLun))
723 {
724 med.strLocation.append("/");
725 med.strLocation.append(strLun);
726 }
727
728 if (strServer.length() && strPort.length())
729 med.properties["TargetAddress"] = strServerAndPort;
730 if (strTarget.length())
731 med.properties["TargetName"] = strTarget;
732 if (strUser.length())
733 med.properties["InitiatorUsername"] = strUser;
734 Utf8Str strPassword;
735 if (pelmImage->getAttributeValue("password", strPassword))
736 med.properties["InitiatorSecret"] = strPassword;
737 if (strLun.length())
738 med.properties["LUN"] = strLun;
739 }
740 else if ((pelmImage = elmMedium.findChildElement("CustomHardDisk")))
741 {
742 fNeedsFilePath = false;
743 fNeedsLocation = true;
744 // also requires @format attribute, which will be queried below
745 }
746 else
747 throw ConfigFileError(this, &elmMedium, N_("Required %s/VirtualDiskImage element is missing"), elmMedium.getName());
748
749 if (fNeedsFilePath)
750 {
751 if (!(pelmImage->getAttributeValuePath("filePath", med.strLocation)))
752 throw ConfigFileError(this, &elmMedium, N_("Required %s/@filePath attribute is missing"), elmMedium.getName());
753 }
754 }
755
756 if (med.strFormat.isEmpty()) // not set with 1.4 format above, or 1.4 Custom format?
757 if (!elmMedium.getAttributeValue("format", med.strFormat))
758 throw ConfigFileError(this, &elmMedium, N_("Required %s/@format attribute is missing"), elmMedium.getName());
759
760 if (!elmMedium.getAttributeValue("autoReset", med.fAutoReset))
761 med.fAutoReset = false;
762
763 Utf8Str strType;
764 if (elmMedium.getAttributeValue("type", strType))
765 {
766 // pre-1.4 used lower case, so make this case-insensitive
767 strType.toUpper();
768 if (strType == "NORMAL")
769 med.hdType = MediumType_Normal;
770 else if (strType == "IMMUTABLE")
771 med.hdType = MediumType_Immutable;
772 else if (strType == "WRITETHROUGH")
773 med.hdType = MediumType_Writethrough;
774 else if (strType == "SHAREABLE")
775 med.hdType = MediumType_Shareable;
776 else if (strType == "READONLY")
777 med.hdType = MediumType_Readonly;
778 else if (strType == "MULTIATTACH")
779 med.hdType = MediumType_MultiAttach;
780 else
781 throw ConfigFileError(this, &elmMedium, N_("HardDisk/@type attribute must be one of Normal, Immutable, Writethrough, Shareable, Readonly or MultiAttach"));
782 }
783 }
784 else
785 {
786 if (m->sv < SettingsVersion_v1_4)
787 {
788 // DVD and floppy images before 1.4 had "src" attribute instead of "location"
789 if (!elmMedium.getAttributeValue("src", med.strLocation))
790 throw ConfigFileError(this, &elmMedium, N_("Required %s/@src attribute is missing"), elmMedium.getName());
791
792 fNeedsLocation = false;
793 }
794
795 if (!elmMedium.getAttributeValue("format", med.strFormat))
796 {
797 // DVD and floppy images before 1.11 had no format attribute. assign the default.
798 med.strFormat = "RAW";
799 }
800
801 if (t == DVDImage)
802 med.hdType = MediumType_Readonly;
803 else if (t == FloppyImage)
804 med.hdType = MediumType_Writethrough;
805 }
806
807 if (fNeedsLocation)
808 // current files and 1.4 CustomHardDisk elements must have a location attribute
809 if (!elmMedium.getAttributeValue("location", med.strLocation))
810 throw ConfigFileError(this, &elmMedium, N_("Required %s/@location attribute is missing"), elmMedium.getName());
811
812 elmMedium.getAttributeValue("Description", med.strDescription); // optional
813
814 // handle medium properties
815 xml::NodesLoop nl2(elmMedium, "Property");
816 const xml::ElementNode *pelmHDChild;
817 while ((pelmHDChild = nl2.forAllNodes()))
818 {
819 Utf8Str strPropName, strPropValue;
820 if ( pelmHDChild->getAttributeValue("name", strPropName)
821 && pelmHDChild->getAttributeValue("value", strPropValue) )
822 med.properties[strPropName] = strPropValue;
823 else
824 throw ConfigFileError(this, pelmHDChild, N_("Required HardDisk/Property/@name or @value attribute is missing"));
825 }
826}
827
828/**
829 * Reads a media registry entry from the main VirtualBox.xml file and recurses
830 * into children where applicable.
831 *
832 * @param t
833 * @param depth
834 * @param elmMedium
835 * @param med
836 */
837void ConfigFileBase::readMedium(MediaType t,
838 uint32_t depth,
839 const xml::ElementNode &elmMedium, // HardDisk node if root; if recursing,
840 // child HardDisk node or DiffHardDisk node for pre-1.4
841 Medium &med) // medium settings to fill out
842{
843 if (depth > SETTINGS_MEDIUM_DEPTH_MAX)
844 throw ConfigFileError(this, &elmMedium, N_("Maximum medium tree depth of %u exceeded"), SETTINGS_MEDIUM_DEPTH_MAX);
845
846 // Do not inline this method call, as the purpose of having this separate
847 // is to save on stack size. Less local variables are the key for reaching
848 // deep recursion levels with small stack (XPCOM/g++ without optimization).
849 readMediumOne(t, elmMedium, med);
850
851 if (t != HardDisk)
852 return;
853
854 // recurse to handle children
855 MediaList &llSettingsChildren = med.llChildren;
856 xml::NodesLoop nl2(elmMedium, m->sv >= SettingsVersion_v1_4 ? "HardDisk" : "DiffHardDisk");
857 const xml::ElementNode *pelmHDChild;
858 while ((pelmHDChild = nl2.forAllNodes()))
859 {
860 // recurse with this element and put the child at the end of the list.
861 // XPCOM has very small stack, avoid big local variables and use the
862 // list element.
863 llSettingsChildren.push_back(Medium::Empty);
864 readMedium(t,
865 depth + 1,
866 *pelmHDChild,
867 llSettingsChildren.back());
868 }
869}
870
871/**
872 * Reads in the entire \<MediaRegistry\> chunk and stores its media in the lists
873 * of the given MediaRegistry structure.
874 *
875 * This is used in both MainConfigFile and MachineConfigFile since starting with
876 * VirtualBox 4.0, we can have media registries in both.
877 *
878 * For pre-1.4 files, this gets called with the \<DiskRegistry\> chunk instead.
879 *
880 * @param elmMediaRegistry
881 * @param mr
882 */
883void ConfigFileBase::readMediaRegistry(const xml::ElementNode &elmMediaRegistry,
884 MediaRegistry &mr)
885{
886 xml::NodesLoop nl1(elmMediaRegistry);
887 const xml::ElementNode *pelmChild1;
888 while ((pelmChild1 = nl1.forAllNodes()))
889 {
890 MediaType t = Error;
891 if (pelmChild1->nameEquals("HardDisks"))
892 t = HardDisk;
893 else if (pelmChild1->nameEquals("DVDImages"))
894 t = DVDImage;
895 else if (pelmChild1->nameEquals("FloppyImages"))
896 t = FloppyImage;
897 else
898 continue;
899
900 xml::NodesLoop nl2(*pelmChild1);
901 const xml::ElementNode *pelmMedium;
902 while ((pelmMedium = nl2.forAllNodes()))
903 {
904 if ( t == HardDisk
905 && (pelmMedium->nameEquals("HardDisk")))
906 {
907 mr.llHardDisks.push_back(Medium::Empty);
908 readMedium(t, 1, *pelmMedium, mr.llHardDisks.back());
909 }
910 else if ( t == DVDImage
911 && (pelmMedium->nameEquals("Image")))
912 {
913 mr.llDvdImages.push_back(Medium::Empty);
914 readMedium(t, 1, *pelmMedium, mr.llDvdImages.back());
915 }
916 else if ( t == FloppyImage
917 && (pelmMedium->nameEquals("Image")))
918 {
919 mr.llFloppyImages.push_back(Medium::Empty);
920 readMedium(t, 1, *pelmMedium, mr.llFloppyImages.back());
921 }
922 }
923 }
924}
925
926/**
927 * This is common version for reading NAT port forward rule in per-_machine's_adapter_ and
928 * per-network approaches.
929 * Note: this function doesn't in fill given list from xml::ElementNodesList, because there is conflicting
930 * declaration in ovmfreader.h.
931 */
932void ConfigFileBase::readNATForwardRulesMap(const xml::ElementNode &elmParent, NATRulesMap &mapRules)
933{
934 xml::ElementNodesList plstRules;
935 elmParent.getChildElements(plstRules, "Forwarding");
936 for (xml::ElementNodesList::iterator pf = plstRules.begin(); pf != plstRules.end(); ++pf)
937 {
938 NATRule rule;
939 uint32_t port = 0;
940 (*pf)->getAttributeValue("name", rule.strName);
941 (*pf)->getAttributeValue("proto", (uint32_t&)rule.proto);
942 (*pf)->getAttributeValue("hostip", rule.strHostIP);
943 (*pf)->getAttributeValue("hostport", port);
944 rule.u16HostPort = (uint16_t)port;
945 (*pf)->getAttributeValue("guestip", rule.strGuestIP);
946 (*pf)->getAttributeValue("guestport", port);
947 rule.u16GuestPort = (uint16_t)port;
948 mapRules.insert(std::make_pair(rule.strName, rule));
949 }
950}
951
952void ConfigFileBase::readNATLoopbacks(const xml::ElementNode &elmParent, NATLoopbackOffsetList &llLoopbacks)
953{
954 xml::ElementNodesList plstLoopbacks;
955 elmParent.getChildElements(plstLoopbacks, "Loopback4");
956 for (xml::ElementNodesList::iterator lo = plstLoopbacks.begin();
957 lo != plstLoopbacks.end(); ++lo)
958 {
959 NATHostLoopbackOffset loopback;
960 (*lo)->getAttributeValue("address", loopback.strLoopbackHostAddress);
961 (*lo)->getAttributeValue("offset", (uint32_t&)loopback.u32Offset);
962 llLoopbacks.push_back(loopback);
963 }
964}
965
966
967/**
968 * Adds a "version" attribute to the given XML element with the
969 * VirtualBox settings version (e.g. "1.10-linux"). Used by
970 * the XML format for the root element and by the OVF export
971 * for the vbox:Machine element.
972 * @param elm
973 */
974void ConfigFileBase::setVersionAttribute(xml::ElementNode &elm)
975{
976 const char *pcszVersion = NULL;
977 switch (m->sv)
978 {
979 case SettingsVersion_v1_8:
980 pcszVersion = "1.8";
981 break;
982
983 case SettingsVersion_v1_9:
984 pcszVersion = "1.9";
985 break;
986
987 case SettingsVersion_v1_10:
988 pcszVersion = "1.10";
989 break;
990
991 case SettingsVersion_v1_11:
992 pcszVersion = "1.11";
993 break;
994
995 case SettingsVersion_v1_12:
996 pcszVersion = "1.12";
997 break;
998
999 case SettingsVersion_v1_13:
1000 pcszVersion = "1.13";
1001 break;
1002
1003 case SettingsVersion_v1_14:
1004 pcszVersion = "1.14";
1005 break;
1006
1007 case SettingsVersion_v1_15:
1008 pcszVersion = "1.15";
1009 break;
1010
1011 case SettingsVersion_v1_16:
1012 pcszVersion = "1.16";
1013 break;
1014
1015 case SettingsVersion_v1_17:
1016 pcszVersion = "1.17";
1017 break;
1018
1019 default:
1020 // catch human error: the assertion below will trigger in debug
1021 // or dbgopt builds, so hopefully this will get noticed sooner in
1022 // the future, because it's easy to forget top update something.
1023 AssertMsg(m->sv <= SettingsVersion_v1_7, ("Settings.cpp: unexpected settings version %d, unhandled future version?\n", m->sv));
1024 // silently upgrade if this is less than 1.7 because that's the oldest we can write
1025 if (m->sv <= SettingsVersion_v1_7)
1026 {
1027 pcszVersion = "1.7";
1028 m->sv = SettingsVersion_v1_7;
1029 }
1030 else
1031 {
1032 // This is reached for SettingsVersion_Future and forgotten
1033 // settings version after SettingsVersion_v1_7, which should
1034 // not happen (see assertion above). Set the version to the
1035 // latest known version, to minimize loss of information, but
1036 // as we can't predict the future we have to use some format
1037 // we know, and latest should be the best choice. Note that
1038 // for "forgotten settings" this may not be the best choice,
1039 // but as it's an omission of someone who changed this file
1040 // it's the only generic possibility.
1041 pcszVersion = "1.17";
1042 m->sv = SettingsVersion_v1_17;
1043 }
1044 break;
1045 }
1046
1047 m->strSettingsVersionFull = Utf8StrFmt("%s-%s",
1048 pcszVersion,
1049 VBOX_XML_PLATFORM); // e.g. "linux"
1050 elm.setAttribute("version", m->strSettingsVersionFull);
1051}
1052
1053
1054/**
1055 * Creates a special backup file in case there is a version
1056 * bump, so that it is possible to go back to the previous
1057 * state. This is done only once (not for every settings
1058 * version bump), when the settings version is newer than
1059 * the version read from the config file. Must be called
1060 * before ConfigFileBase::createStubDocument, because that
1061 * method may alter information which this method needs.
1062 */
1063void ConfigFileBase::specialBackupIfFirstBump()
1064{
1065 // Since this gets called before the XML document is actually written out,
1066 // this is where we must check whether we're upgrading the settings version
1067 // and need to make a backup, so the user can go back to an earlier
1068 // VirtualBox version and recover his old settings files.
1069 if ( (m->svRead != SettingsVersion_Null) // old file exists?
1070 && (m->svRead < m->sv) // we're upgrading?
1071 )
1072 {
1073 // compose new filename: strip off trailing ".xml"/".vbox"
1074 Utf8Str strFilenameNew;
1075 Utf8Str strExt = ".xml";
1076 if (m->strFilename.endsWith(".xml"))
1077 strFilenameNew = m->strFilename.substr(0, m->strFilename.length() - 4);
1078 else if (m->strFilename.endsWith(".vbox"))
1079 {
1080 strFilenameNew = m->strFilename.substr(0, m->strFilename.length() - 5);
1081 strExt = ".vbox";
1082 }
1083
1084 // and append something like "-1.3-linux.xml"
1085 strFilenameNew.append("-");
1086 strFilenameNew.append(m->strSettingsVersionFull); // e.g. "1.3-linux"
1087 strFilenameNew.append(strExt); // .xml for main config, .vbox for machine config
1088
1089 // Copying the file cannot be avoided, as doing tricks with renaming
1090 // causes trouble on OS X with aliases (which follow the rename), and
1091 // on all platforms there is a risk of "losing" the VM config when
1092 // running out of space, as a rename here couldn't be rolled back.
1093 // Ignoring all errors besides running out of space is intentional, as
1094 // we don't want to do anything if the file already exists.
1095 int vrc = RTFileCopy(m->strFilename.c_str(), strFilenameNew.c_str());
1096 if (RT_UNLIKELY(vrc == VERR_DISK_FULL))
1097 throw ConfigFileError(this, NULL, N_("Cannot create settings backup file when upgrading to a newer settings format"));
1098
1099 // do this only once
1100 m->svRead = SettingsVersion_Null;
1101 }
1102}
1103
1104/**
1105 * Creates a new stub xml::Document in the m->pDoc member with the
1106 * root "VirtualBox" element set up. This is used by both
1107 * MainConfigFile and MachineConfigFile at the beginning of writing
1108 * out their XML.
1109 *
1110 * Before calling this, it is the responsibility of the caller to
1111 * set the "sv" member to the required settings version that is to
1112 * be written. For newly created files, the settings version will be
1113 * recent (1.12 or later if necessary); for files read in from disk
1114 * earlier, it will be the settings version indicated in the file.
1115 * However, this method will silently make sure that the settings
1116 * version is always at least 1.7 and change it if necessary, since
1117 * there is no write support for earlier settings versions.
1118 */
1119void ConfigFileBase::createStubDocument()
1120{
1121 Assert(m->pDoc == NULL);
1122 m->pDoc = new xml::Document;
1123
1124 m->pelmRoot = m->pDoc->createRootElement("VirtualBox",
1125 "\n"
1126 "** DO NOT EDIT THIS FILE.\n"
1127 "** If you make changes to this file while any VirtualBox related application\n"
1128 "** is running, your changes will be overwritten later, without taking effect.\n"
1129 "** Use VBoxManage or the VirtualBox Manager GUI to make changes.\n"
1130);
1131 m->pelmRoot->setAttribute("xmlns", VBOX_XML_NAMESPACE);
1132 // Have the code for producing a proper schema reference. Not used by most
1133 // tools, so don't bother doing it. The schema is not on the server anyway.
1134#ifdef VBOX_WITH_SETTINGS_SCHEMA
1135 m->pelmRoot->setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
1136 m->pelmRoot->setAttribute("xsi:schemaLocation", VBOX_XML_NAMESPACE " " VBOX_XML_SCHEMA);
1137#endif
1138
1139 // add settings version attribute to root element, update m->strSettingsVersionFull
1140 setVersionAttribute(*m->pelmRoot);
1141
1142 LogRel(("Saving settings file \"%s\" with version \"%s\"\n", m->strFilename.c_str(), m->strSettingsVersionFull.c_str()));
1143}
1144
1145/**
1146 * Creates an \<ExtraData\> node under the given parent element with
1147 * \<ExtraDataItem\> childern according to the contents of the given
1148 * map.
1149 *
1150 * This is in ConfigFileBase because it's used in both MainConfigFile
1151 * and MachineConfigFile, which both can have extradata.
1152 *
1153 * @param elmParent
1154 * @param me
1155 */
1156void ConfigFileBase::buildExtraData(xml::ElementNode &elmParent,
1157 const StringsMap &me)
1158{
1159 if (me.size())
1160 {
1161 xml::ElementNode *pelmExtraData = elmParent.createChild("ExtraData");
1162 for (StringsMap::const_iterator it = me.begin();
1163 it != me.end();
1164 ++it)
1165 {
1166 const Utf8Str &strName = it->first;
1167 const Utf8Str &strValue = it->second;
1168 xml::ElementNode *pelmThis = pelmExtraData->createChild("ExtraDataItem");
1169 pelmThis->setAttribute("name", strName);
1170 pelmThis->setAttribute("value", strValue);
1171 }
1172 }
1173}
1174
1175/**
1176 * Creates \<DeviceFilter\> nodes under the given parent element according to
1177 * the contents of the given USBDeviceFiltersList. This is in ConfigFileBase
1178 * because it's used in both MainConfigFile (for host filters) and
1179 * MachineConfigFile (for machine filters).
1180 *
1181 * If fHostMode is true, this means that we're supposed to write filters
1182 * for the IHost interface (respect "action", omit "strRemote" and
1183 * "ulMaskedInterfaces" in struct USBDeviceFilter).
1184 *
1185 * @param elmParent
1186 * @param ll
1187 * @param fHostMode
1188 */
1189void ConfigFileBase::buildUSBDeviceFilters(xml::ElementNode &elmParent,
1190 const USBDeviceFiltersList &ll,
1191 bool fHostMode)
1192{
1193 for (USBDeviceFiltersList::const_iterator it = ll.begin();
1194 it != ll.end();
1195 ++it)
1196 {
1197 const USBDeviceFilter &flt = *it;
1198 xml::ElementNode *pelmFilter = elmParent.createChild("DeviceFilter");
1199 pelmFilter->setAttribute("name", flt.strName);
1200 pelmFilter->setAttribute("active", flt.fActive);
1201 if (flt.strVendorId.length())
1202 pelmFilter->setAttribute("vendorId", flt.strVendorId);
1203 if (flt.strProductId.length())
1204 pelmFilter->setAttribute("productId", flt.strProductId);
1205 if (flt.strRevision.length())
1206 pelmFilter->setAttribute("revision", flt.strRevision);
1207 if (flt.strManufacturer.length())
1208 pelmFilter->setAttribute("manufacturer", flt.strManufacturer);
1209 if (flt.strProduct.length())
1210 pelmFilter->setAttribute("product", flt.strProduct);
1211 if (flt.strSerialNumber.length())
1212 pelmFilter->setAttribute("serialNumber", flt.strSerialNumber);
1213 if (flt.strPort.length())
1214 pelmFilter->setAttribute("port", flt.strPort);
1215
1216 if (fHostMode)
1217 {
1218 const char *pcsz =
1219 (flt.action == USBDeviceFilterAction_Ignore) ? "Ignore"
1220 : /*(flt.action == USBDeviceFilterAction_Hold) ?*/ "Hold";
1221 pelmFilter->setAttribute("action", pcsz);
1222 }
1223 else
1224 {
1225 if (flt.strRemote.length())
1226 pelmFilter->setAttribute("remote", flt.strRemote);
1227 if (flt.ulMaskedInterfaces)
1228 pelmFilter->setAttribute("maskedInterfaces", flt.ulMaskedInterfaces);
1229 }
1230 }
1231}
1232
1233/**
1234 * Creates a single \<HardDisk\> element for the given Medium structure
1235 * and recurses to write the child hard disks underneath. Called from
1236 * MainConfigFile::write().
1237 *
1238 * @param t
1239 * @param depth
1240 * @param elmMedium
1241 * @param mdm
1242 */
1243void ConfigFileBase::buildMedium(MediaType t,
1244 uint32_t depth,
1245 xml::ElementNode &elmMedium,
1246 const Medium &mdm)
1247{
1248 if (depth > SETTINGS_MEDIUM_DEPTH_MAX)
1249 throw ConfigFileError(this, &elmMedium, N_("Maximum medium tree depth of %u exceeded"), SETTINGS_MEDIUM_DEPTH_MAX);
1250
1251 xml::ElementNode *pelmMedium;
1252
1253 if (t == HardDisk)
1254 pelmMedium = elmMedium.createChild("HardDisk");
1255 else
1256 pelmMedium = elmMedium.createChild("Image");
1257
1258 pelmMedium->setAttribute("uuid", mdm.uuid.toStringCurly());
1259
1260 pelmMedium->setAttributePath("location", mdm.strLocation);
1261
1262 if (t == HardDisk || RTStrICmp(mdm.strFormat.c_str(), "RAW"))
1263 pelmMedium->setAttribute("format", mdm.strFormat);
1264 if ( t == HardDisk
1265 && mdm.fAutoReset)
1266 pelmMedium->setAttribute("autoReset", mdm.fAutoReset);
1267 if (mdm.strDescription.length())
1268 pelmMedium->setAttribute("Description", mdm.strDescription);
1269
1270 for (StringsMap::const_iterator it = mdm.properties.begin();
1271 it != mdm.properties.end();
1272 ++it)
1273 {
1274 xml::ElementNode *pelmProp = pelmMedium->createChild("Property");
1275 pelmProp->setAttribute("name", it->first);
1276 pelmProp->setAttribute("value", it->second);
1277 }
1278
1279 // only for base hard disks, save the type
1280 if (depth == 1)
1281 {
1282 // no need to save the usual DVD/floppy medium types
1283 if ( ( t != DVDImage
1284 || ( mdm.hdType != MediumType_Writethrough // shouldn't happen
1285 && mdm.hdType != MediumType_Readonly))
1286 && ( t != FloppyImage
1287 || mdm.hdType != MediumType_Writethrough))
1288 {
1289 const char *pcszType =
1290 mdm.hdType == MediumType_Normal ? "Normal" :
1291 mdm.hdType == MediumType_Immutable ? "Immutable" :
1292 mdm.hdType == MediumType_Writethrough ? "Writethrough" :
1293 mdm.hdType == MediumType_Shareable ? "Shareable" :
1294 mdm.hdType == MediumType_Readonly ? "Readonly" :
1295 mdm.hdType == MediumType_MultiAttach ? "MultiAttach" :
1296 "INVALID";
1297 pelmMedium->setAttribute("type", pcszType);
1298 }
1299 }
1300
1301 for (MediaList::const_iterator it = mdm.llChildren.begin();
1302 it != mdm.llChildren.end();
1303 ++it)
1304 {
1305 // recurse for children
1306 buildMedium(t, // device type
1307 depth + 1, // depth
1308 *pelmMedium, // parent
1309 *it); // settings::Medium
1310 }
1311}
1312
1313/**
1314 * Creates a \<MediaRegistry\> node under the given parent and writes out all
1315 * hard disks and DVD and floppy images from the lists in the given MediaRegistry
1316 * structure under it.
1317 *
1318 * This is used in both MainConfigFile and MachineConfigFile since starting with
1319 * VirtualBox 4.0, we can have media registries in both.
1320 *
1321 * @param elmParent
1322 * @param mr
1323 */
1324void ConfigFileBase::buildMediaRegistry(xml::ElementNode &elmParent,
1325 const MediaRegistry &mr)
1326{
1327 if (mr.llHardDisks.size() == 0 && mr.llDvdImages.size() == 0 && mr.llFloppyImages.size() == 0)
1328 return;
1329
1330 xml::ElementNode *pelmMediaRegistry = elmParent.createChild("MediaRegistry");
1331
1332 if (mr.llHardDisks.size())
1333 {
1334 xml::ElementNode *pelmHardDisks = pelmMediaRegistry->createChild("HardDisks");
1335 for (MediaList::const_iterator it = mr.llHardDisks.begin();
1336 it != mr.llHardDisks.end();
1337 ++it)
1338 {
1339 buildMedium(HardDisk, 1, *pelmHardDisks, *it);
1340 }
1341 }
1342
1343 if (mr.llDvdImages.size())
1344 {
1345 xml::ElementNode *pelmDVDImages = pelmMediaRegistry->createChild("DVDImages");
1346 for (MediaList::const_iterator it = mr.llDvdImages.begin();
1347 it != mr.llDvdImages.end();
1348 ++it)
1349 {
1350 buildMedium(DVDImage, 1, *pelmDVDImages, *it);
1351 }
1352 }
1353
1354 if (mr.llFloppyImages.size())
1355 {
1356 xml::ElementNode *pelmFloppyImages = pelmMediaRegistry->createChild("FloppyImages");
1357 for (MediaList::const_iterator it = mr.llFloppyImages.begin();
1358 it != mr.llFloppyImages.end();
1359 ++it)
1360 {
1361 buildMedium(FloppyImage, 1, *pelmFloppyImages, *it);
1362 }
1363 }
1364}
1365
1366/**
1367 * Serialize NAT port-forwarding rules in parent container.
1368 * Note: it's responsibility of caller to create parent of the list tag.
1369 * because this method used for serializing per-_mahine's_adapter_ and per-network approaches.
1370 */
1371void ConfigFileBase::buildNATForwardRulesMap(xml::ElementNode &elmParent, const NATRulesMap &mapRules)
1372{
1373 for (NATRulesMap::const_iterator r = mapRules.begin();
1374 r != mapRules.end(); ++r)
1375 {
1376 xml::ElementNode *pelmPF;
1377 pelmPF = elmParent.createChild("Forwarding");
1378 const NATRule &nr = r->second;
1379 if (nr.strName.length())
1380 pelmPF->setAttribute("name", nr.strName);
1381 pelmPF->setAttribute("proto", nr.proto);
1382 if (nr.strHostIP.length())
1383 pelmPF->setAttribute("hostip", nr.strHostIP);
1384 if (nr.u16HostPort)
1385 pelmPF->setAttribute("hostport", nr.u16HostPort);
1386 if (nr.strGuestIP.length())
1387 pelmPF->setAttribute("guestip", nr.strGuestIP);
1388 if (nr.u16GuestPort)
1389 pelmPF->setAttribute("guestport", nr.u16GuestPort);
1390 }
1391}
1392
1393
1394void ConfigFileBase::buildNATLoopbacks(xml::ElementNode &elmParent, const NATLoopbackOffsetList &natLoopbackOffsetList)
1395{
1396 for (NATLoopbackOffsetList::const_iterator lo = natLoopbackOffsetList.begin();
1397 lo != natLoopbackOffsetList.end(); ++lo)
1398 {
1399 xml::ElementNode *pelmLo;
1400 pelmLo = elmParent.createChild("Loopback4");
1401 pelmLo->setAttribute("address", (*lo).strLoopbackHostAddress);
1402 pelmLo->setAttribute("offset", (*lo).u32Offset);
1403 }
1404}
1405
1406/**
1407 * Cleans up memory allocated by the internal XML parser. To be called by
1408 * descendant classes when they're done analyzing the DOM tree to discard it.
1409 */
1410void ConfigFileBase::clearDocument()
1411{
1412 m->cleanup();
1413}
1414
1415/**
1416 * Returns true only if the underlying config file exists on disk;
1417 * either because the file has been loaded from disk, or it's been written
1418 * to disk, or both.
1419 * @return
1420 */
1421bool ConfigFileBase::fileExists()
1422{
1423 return m->fFileExists;
1424}
1425
1426/**
1427 * Copies the base variables from another instance. Used by Machine::saveSettings
1428 * so that the settings version does not get lost when a copy of the Machine settings
1429 * file is made to see if settings have actually changed.
1430 * @param b
1431 */
1432void ConfigFileBase::copyBaseFrom(const ConfigFileBase &b)
1433{
1434 m->copyFrom(*b.m);
1435}
1436
1437////////////////////////////////////////////////////////////////////////////////
1438//
1439// Structures shared between Machine XML and VirtualBox.xml
1440//
1441////////////////////////////////////////////////////////////////////////////////
1442
1443
1444/**
1445 * Constructor. Needs to set sane defaults which stand the test of time.
1446 */
1447USBDeviceFilter::USBDeviceFilter() :
1448 fActive(false),
1449 action(USBDeviceFilterAction_Null),
1450 ulMaskedInterfaces(0)
1451{
1452}
1453
1454/**
1455 * Comparison operator. This gets called from MachineConfigFile::operator==,
1456 * which in turn gets called from Machine::saveSettings to figure out whether
1457 * machine settings have really changed and thus need to be written out to disk.
1458 */
1459bool USBDeviceFilter::operator==(const USBDeviceFilter &u) const
1460{
1461 return (this == &u)
1462 || ( strName == u.strName
1463 && fActive == u.fActive
1464 && strVendorId == u.strVendorId
1465 && strProductId == u.strProductId
1466 && strRevision == u.strRevision
1467 && strManufacturer == u.strManufacturer
1468 && strProduct == u.strProduct
1469 && strSerialNumber == u.strSerialNumber
1470 && strPort == u.strPort
1471 && action == u.action
1472 && strRemote == u.strRemote
1473 && ulMaskedInterfaces == u.ulMaskedInterfaces);
1474}
1475
1476/**
1477 * Constructor. Needs to set sane defaults which stand the test of time.
1478 */
1479Medium::Medium() :
1480 fAutoReset(false),
1481 hdType(MediumType_Normal)
1482{
1483}
1484
1485/**
1486 * Comparison operator. This gets called from MachineConfigFile::operator==,
1487 * which in turn gets called from Machine::saveSettings to figure out whether
1488 * machine settings have really changed and thus need to be written out to disk.
1489 */
1490bool Medium::operator==(const Medium &m) const
1491{
1492 return (this == &m)
1493 || ( uuid == m.uuid
1494 && strLocation == m.strLocation
1495 && strDescription == m.strDescription
1496 && strFormat == m.strFormat
1497 && fAutoReset == m.fAutoReset
1498 && properties == m.properties
1499 && hdType == m.hdType
1500 && llChildren == m.llChildren); // this is deep and recurses
1501}
1502
1503const struct Medium Medium::Empty; /* default ctor is OK */
1504
1505/**
1506 * Comparison operator. This gets called from MachineConfigFile::operator==,
1507 * which in turn gets called from Machine::saveSettings to figure out whether
1508 * machine settings have really changed and thus need to be written out to disk.
1509 */
1510bool MediaRegistry::operator==(const MediaRegistry &m) const
1511{
1512 return (this == &m)
1513 || ( llHardDisks == m.llHardDisks
1514 && llDvdImages == m.llDvdImages
1515 && llFloppyImages == m.llFloppyImages);
1516}
1517
1518/**
1519 * Constructor. Needs to set sane defaults which stand the test of time.
1520 */
1521NATRule::NATRule() :
1522 proto(NATProtocol_TCP),
1523 u16HostPort(0),
1524 u16GuestPort(0)
1525{
1526}
1527
1528/**
1529 * Comparison operator. This gets called from MachineConfigFile::operator==,
1530 * which in turn gets called from Machine::saveSettings to figure out whether
1531 * machine settings have really changed and thus need to be written out to disk.
1532 */
1533bool NATRule::operator==(const NATRule &r) const
1534{
1535 return (this == &r)
1536 || ( strName == r.strName
1537 && proto == r.proto
1538 && u16HostPort == r.u16HostPort
1539 && strHostIP == r.strHostIP
1540 && u16GuestPort == r.u16GuestPort
1541 && strGuestIP == r.strGuestIP);
1542}
1543
1544/**
1545 * Constructor. Needs to set sane defaults which stand the test of time.
1546 */
1547NATHostLoopbackOffset::NATHostLoopbackOffset() :
1548 u32Offset(0)
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 NATHostLoopbackOffset::operator==(const NATHostLoopbackOffset &o) const
1558{
1559 return (this == &o)
1560 || ( strLoopbackHostAddress == o.strLoopbackHostAddress
1561 && u32Offset == o.u32Offset);
1562}
1563
1564
1565////////////////////////////////////////////////////////////////////////////////
1566//
1567// VirtualBox.xml structures
1568//
1569////////////////////////////////////////////////////////////////////////////////
1570
1571/**
1572 * Constructor. Needs to set sane defaults which stand the test of time.
1573 */
1574SystemProperties::SystemProperties() :
1575 ulLogHistoryCount(3),
1576 fExclusiveHwVirt(true)
1577{
1578#if defined(RT_OS_DARWIN) || defined(RT_OS_WINDOWS) || defined(RT_OS_SOLARIS)
1579 fExclusiveHwVirt = false;
1580#endif
1581}
1582
1583/**
1584 * Constructor. Needs to set sane defaults which stand the test of time.
1585 */
1586DhcpOptValue::DhcpOptValue() :
1587 text(),
1588 encoding(DhcpOptEncoding_Legacy)
1589{
1590}
1591
1592/**
1593 * Non-standard constructor.
1594 */
1595DhcpOptValue::DhcpOptValue(const com::Utf8Str &aText, DhcpOptEncoding_T aEncoding) :
1596 text(aText),
1597 encoding(aEncoding)
1598{
1599}
1600
1601/**
1602 * Non-standard constructor.
1603 */
1604VmNameSlotKey::VmNameSlotKey(const com::Utf8Str& aVmName, LONG aSlot) :
1605 VmName(aVmName),
1606 Slot(aSlot)
1607{
1608}
1609
1610/**
1611 * Non-standard comparison operator.
1612 */
1613bool VmNameSlotKey::operator< (const VmNameSlotKey& that) const
1614{
1615 if (VmName == that.VmName)
1616 return Slot < that.Slot;
1617 else
1618 return VmName < that.VmName;
1619}
1620
1621/**
1622 * Constructor. Needs to set sane defaults which stand the test of time.
1623 */
1624DHCPServer::DHCPServer() :
1625 fEnabled(false)
1626{
1627}
1628
1629/**
1630 * Constructor. Needs to set sane defaults which stand the test of time.
1631 */
1632NATNetwork::NATNetwork() :
1633 fEnabled(true),
1634 fIPv6Enabled(false),
1635 fAdvertiseDefaultIPv6Route(false),
1636 fNeedDhcpServer(true),
1637 u32HostLoopback6Offset(0)
1638{
1639}
1640
1641
1642
1643////////////////////////////////////////////////////////////////////////////////
1644//
1645// MainConfigFile
1646//
1647////////////////////////////////////////////////////////////////////////////////
1648
1649/**
1650 * Reads one \<MachineEntry\> from the main VirtualBox.xml file.
1651 * @param elmMachineRegistry
1652 */
1653void MainConfigFile::readMachineRegistry(const xml::ElementNode &elmMachineRegistry)
1654{
1655 // <MachineEntry uuid="{ xxx }" src=" xxx "/>
1656 xml::NodesLoop nl1(elmMachineRegistry);
1657 const xml::ElementNode *pelmChild1;
1658 while ((pelmChild1 = nl1.forAllNodes()))
1659 {
1660 if (pelmChild1->nameEquals("MachineEntry"))
1661 {
1662 MachineRegistryEntry mre;
1663 Utf8Str strUUID;
1664 if ( pelmChild1->getAttributeValue("uuid", strUUID)
1665 && pelmChild1->getAttributeValue("src", mre.strSettingsFile) )
1666 {
1667 parseUUID(mre.uuid, strUUID, pelmChild1);
1668 llMachines.push_back(mre);
1669 }
1670 else
1671 throw ConfigFileError(this, pelmChild1, N_("Required MachineEntry/@uuid or @src attribute is missing"));
1672 }
1673 }
1674}
1675
1676/**
1677 * Reads in the \<DHCPServers\> chunk.
1678 * @param elmDHCPServers
1679 */
1680void MainConfigFile::readDHCPServers(const xml::ElementNode &elmDHCPServers)
1681{
1682 xml::NodesLoop nl1(elmDHCPServers);
1683 const xml::ElementNode *pelmServer;
1684 while ((pelmServer = nl1.forAllNodes()))
1685 {
1686 if (pelmServer->nameEquals("DHCPServer"))
1687 {
1688 DHCPServer srv;
1689 if ( pelmServer->getAttributeValue("networkName", srv.strNetworkName)
1690 && pelmServer->getAttributeValue("IPAddress", srv.strIPAddress)
1691 && pelmServer->getAttributeValue("networkMask", srv.GlobalDhcpOptions[DhcpOpt_SubnetMask].text)
1692 && pelmServer->getAttributeValue("lowerIP", srv.strIPLower)
1693 && pelmServer->getAttributeValue("upperIP", srv.strIPUpper)
1694 && pelmServer->getAttributeValue("enabled", srv.fEnabled) )
1695 {
1696 xml::NodesLoop nlOptions(*pelmServer, "Options");
1697 const xml::ElementNode *options;
1698 /* XXX: Options are in 1:1 relation to DHCPServer */
1699
1700 while ((options = nlOptions.forAllNodes()))
1701 {
1702 readDhcpOptions(srv.GlobalDhcpOptions, *options);
1703 } /* end of forall("Options") */
1704 xml::NodesLoop nlConfig(*pelmServer, "Config");
1705 const xml::ElementNode *cfg;
1706 while ((cfg = nlConfig.forAllNodes()))
1707 {
1708 com::Utf8Str strVmName;
1709 uint32_t u32Slot;
1710 cfg->getAttributeValue("vm-name", strVmName);
1711 cfg->getAttributeValue("slot", u32Slot);
1712 readDhcpOptions(srv.VmSlot2OptionsM[VmNameSlotKey(strVmName, u32Slot)], *cfg);
1713 }
1714 llDhcpServers.push_back(srv);
1715 }
1716 else
1717 throw ConfigFileError(this, pelmServer, N_("Required DHCPServer/@networkName, @IPAddress, @networkMask, @lowerIP, @upperIP or @enabled attribute is missing"));
1718 }
1719 }
1720}
1721
1722void MainConfigFile::readDhcpOptions(DhcpOptionMap& map,
1723 const xml::ElementNode& options)
1724{
1725 xml::NodesLoop nl2(options, "Option");
1726 const xml::ElementNode *opt;
1727 while ((opt = nl2.forAllNodes()))
1728 {
1729 DhcpOpt_T OptName;
1730 com::Utf8Str OptText;
1731 int32_t OptEnc = DhcpOptEncoding_Legacy;
1732
1733 opt->getAttributeValue("name", (uint32_t&)OptName);
1734
1735 if (OptName == DhcpOpt_SubnetMask)
1736 continue;
1737
1738 opt->getAttributeValue("value", OptText);
1739 opt->getAttributeValue("encoding", OptEnc);
1740
1741 map[OptName] = DhcpOptValue(OptText, (DhcpOptEncoding_T)OptEnc);
1742 } /* end of forall("Option") */
1743
1744}
1745
1746/**
1747 * Reads in the \<NATNetworks\> chunk.
1748 * @param elmNATNetworks
1749 */
1750void MainConfigFile::readNATNetworks(const xml::ElementNode &elmNATNetworks)
1751{
1752 xml::NodesLoop nl1(elmNATNetworks);
1753 const xml::ElementNode *pelmNet;
1754 while ((pelmNet = nl1.forAllNodes()))
1755 {
1756 if (pelmNet->nameEquals("NATNetwork"))
1757 {
1758 NATNetwork net;
1759 if ( pelmNet->getAttributeValue("networkName", net.strNetworkName)
1760 && pelmNet->getAttributeValue("enabled", net.fEnabled)
1761 && pelmNet->getAttributeValue("network", net.strIPv4NetworkCidr)
1762 && pelmNet->getAttributeValue("ipv6", net.fIPv6Enabled)
1763 && pelmNet->getAttributeValue("ipv6prefix", net.strIPv6Prefix)
1764 && pelmNet->getAttributeValue("advertiseDefaultIPv6Route", net.fAdvertiseDefaultIPv6Route)
1765 && pelmNet->getAttributeValue("needDhcp", net.fNeedDhcpServer) )
1766 {
1767 pelmNet->getAttributeValue("loopback6", net.u32HostLoopback6Offset);
1768 const xml::ElementNode *pelmMappings;
1769 if ((pelmMappings = pelmNet->findChildElement("Mappings")))
1770 readNATLoopbacks(*pelmMappings, net.llHostLoopbackOffsetList);
1771
1772 const xml::ElementNode *pelmPortForwardRules4;
1773 if ((pelmPortForwardRules4 = pelmNet->findChildElement("PortForwarding4")))
1774 readNATForwardRulesMap(*pelmPortForwardRules4,
1775 net.mapPortForwardRules4);
1776
1777 const xml::ElementNode *pelmPortForwardRules6;
1778 if ((pelmPortForwardRules6 = pelmNet->findChildElement("PortForwarding6")))
1779 readNATForwardRulesMap(*pelmPortForwardRules6,
1780 net.mapPortForwardRules6);
1781
1782 llNATNetworks.push_back(net);
1783 }
1784 else
1785 throw ConfigFileError(this, pelmNet, N_("Required NATNetwork/@networkName, @gateway, @network,@advertiseDefaultIpv6Route , @needDhcp or @enabled attribute is missing"));
1786 }
1787 }
1788}
1789
1790/**
1791 * Creates \<USBDeviceSource\> nodes under the given parent element according to
1792 * the contents of the given USBDeviceSourcesList.
1793 *
1794 * @param elmParent
1795 * @param ll
1796 */
1797void MainConfigFile::buildUSBDeviceSources(xml::ElementNode &elmParent,
1798 const USBDeviceSourcesList &ll)
1799{
1800 for (USBDeviceSourcesList::const_iterator it = ll.begin();
1801 it != ll.end();
1802 ++it)
1803 {
1804 const USBDeviceSource &src = *it;
1805 xml::ElementNode *pelmSource = elmParent.createChild("USBDeviceSource");
1806 pelmSource->setAttribute("name", src.strName);
1807 pelmSource->setAttribute("backend", src.strBackend);
1808 pelmSource->setAttribute("address", src.strAddress);
1809
1810 /* Write the properties. */
1811 for (StringsMap::const_iterator itProp = src.properties.begin();
1812 itProp != src.properties.end();
1813 ++itProp)
1814 {
1815 xml::ElementNode *pelmProp = pelmSource->createChild("Property");
1816 pelmProp->setAttribute("name", itProp->first);
1817 pelmProp->setAttribute("value", itProp->second);
1818 }
1819 }
1820}
1821
1822/**
1823 * Reads \<USBDeviceFilter\> entries from under the given elmDeviceFilters node and
1824 * stores them in the given linklist. This is in ConfigFileBase because it's used
1825 * from both MainConfigFile (for host filters) and MachineConfigFile (for machine
1826 * filters).
1827 * @param elmDeviceSources
1828 * @param ll
1829 */
1830void MainConfigFile::readUSBDeviceSources(const xml::ElementNode &elmDeviceSources,
1831 USBDeviceSourcesList &ll)
1832{
1833 xml::NodesLoop nl1(elmDeviceSources, "USBDeviceSource");
1834 const xml::ElementNode *pelmChild;
1835 while ((pelmChild = nl1.forAllNodes()))
1836 {
1837 USBDeviceSource src;
1838
1839 if ( pelmChild->getAttributeValue("name", src.strName)
1840 && pelmChild->getAttributeValue("backend", src.strBackend)
1841 && pelmChild->getAttributeValue("address", src.strAddress))
1842 {
1843 // handle medium properties
1844 xml::NodesLoop nl2(*pelmChild, "Property");
1845 const xml::ElementNode *pelmSrcChild;
1846 while ((pelmSrcChild = nl2.forAllNodes()))
1847 {
1848 Utf8Str strPropName, strPropValue;
1849 if ( pelmSrcChild->getAttributeValue("name", strPropName)
1850 && pelmSrcChild->getAttributeValue("value", strPropValue) )
1851 src.properties[strPropName] = strPropValue;
1852 else
1853 throw ConfigFileError(this, pelmSrcChild, N_("Required USBDeviceSource/Property/@name or @value attribute is missing"));
1854 }
1855
1856 ll.push_back(src);
1857 }
1858 }
1859}
1860
1861/**
1862 * Constructor.
1863 *
1864 * If pstrFilename is != NULL, this reads the given settings file into the member
1865 * variables and various substructures and lists. Otherwise, the member variables
1866 * are initialized with default values.
1867 *
1868 * Throws variants of xml::Error for I/O, XML and logical content errors, which
1869 * the caller should catch; if this constructor does not throw, then the member
1870 * variables contain meaningful values (either from the file or defaults).
1871 *
1872 * @param pstrFilename
1873 */
1874MainConfigFile::MainConfigFile(const Utf8Str *pstrFilename)
1875 : ConfigFileBase(pstrFilename)
1876{
1877 if (pstrFilename)
1878 {
1879 // the ConfigFileBase constructor has loaded the XML file, so now
1880 // we need only analyze what is in there
1881 xml::NodesLoop nlRootChildren(*m->pelmRoot);
1882 const xml::ElementNode *pelmRootChild;
1883 while ((pelmRootChild = nlRootChildren.forAllNodes()))
1884 {
1885 if (pelmRootChild->nameEquals("Global"))
1886 {
1887 xml::NodesLoop nlGlobalChildren(*pelmRootChild);
1888 const xml::ElementNode *pelmGlobalChild;
1889 while ((pelmGlobalChild = nlGlobalChildren.forAllNodes()))
1890 {
1891 if (pelmGlobalChild->nameEquals("SystemProperties"))
1892 {
1893 pelmGlobalChild->getAttributeValue("defaultMachineFolder", systemProperties.strDefaultMachineFolder);
1894 pelmGlobalChild->getAttributeValue("LoggingLevel", systemProperties.strLoggingLevel);
1895 pelmGlobalChild->getAttributeValue("defaultHardDiskFormat", systemProperties.strDefaultHardDiskFormat);
1896 if (!pelmGlobalChild->getAttributeValue("VRDEAuthLibrary", systemProperties.strVRDEAuthLibrary))
1897 // pre-1.11 used @remoteDisplayAuthLibrary instead
1898 pelmGlobalChild->getAttributeValue("remoteDisplayAuthLibrary", systemProperties.strVRDEAuthLibrary);
1899 pelmGlobalChild->getAttributeValue("webServiceAuthLibrary", systemProperties.strWebServiceAuthLibrary);
1900 pelmGlobalChild->getAttributeValue("defaultVRDEExtPack", systemProperties.strDefaultVRDEExtPack);
1901 pelmGlobalChild->getAttributeValue("LogHistoryCount", systemProperties.ulLogHistoryCount);
1902 pelmGlobalChild->getAttributeValue("autostartDatabasePath", systemProperties.strAutostartDatabasePath);
1903 pelmGlobalChild->getAttributeValue("defaultFrontend", systemProperties.strDefaultFrontend);
1904 pelmGlobalChild->getAttributeValue("exclusiveHwVirt", systemProperties.fExclusiveHwVirt);
1905 }
1906 else if (pelmGlobalChild->nameEquals("ExtraData"))
1907 readExtraData(*pelmGlobalChild, mapExtraDataItems);
1908 else if (pelmGlobalChild->nameEquals("MachineRegistry"))
1909 readMachineRegistry(*pelmGlobalChild);
1910 else if ( (pelmGlobalChild->nameEquals("MediaRegistry"))
1911 || ( (m->sv < SettingsVersion_v1_4)
1912 && (pelmGlobalChild->nameEquals("DiskRegistry"))
1913 )
1914 )
1915 readMediaRegistry(*pelmGlobalChild, mediaRegistry);
1916 else if (pelmGlobalChild->nameEquals("NetserviceRegistry"))
1917 {
1918 xml::NodesLoop nlLevel4(*pelmGlobalChild);
1919 const xml::ElementNode *pelmLevel4Child;
1920 while ((pelmLevel4Child = nlLevel4.forAllNodes()))
1921 {
1922 if (pelmLevel4Child->nameEquals("DHCPServers"))
1923 readDHCPServers(*pelmLevel4Child);
1924 if (pelmLevel4Child->nameEquals("NATNetworks"))
1925 readNATNetworks(*pelmLevel4Child);
1926 }
1927 }
1928 else if (pelmGlobalChild->nameEquals("USBDeviceFilters"))
1929 readUSBDeviceFilters(*pelmGlobalChild, host.llUSBDeviceFilters);
1930 else if (pelmGlobalChild->nameEquals("USBDeviceSources"))
1931 readUSBDeviceSources(*pelmGlobalChild, host.llUSBDeviceSources);
1932 }
1933 } // end if (pelmRootChild->nameEquals("Global"))
1934 }
1935
1936 clearDocument();
1937 }
1938
1939 // DHCP servers were introduced with settings version 1.7; if we're loading
1940 // from an older version OR this is a fresh install, then add one DHCP server
1941 // with default settings
1942 if ( (!llDhcpServers.size())
1943 && ( (!pstrFilename) // empty VirtualBox.xml file
1944 || (m->sv < SettingsVersion_v1_7) // upgrading from before 1.7
1945 )
1946 )
1947 {
1948 DHCPServer srv;
1949 srv.strNetworkName =
1950#ifdef RT_OS_WINDOWS
1951 "HostInterfaceNetworking-VirtualBox Host-Only Ethernet Adapter";
1952#else
1953 "HostInterfaceNetworking-vboxnet0";
1954#endif
1955 srv.strIPAddress = "192.168.56.100";
1956 srv.GlobalDhcpOptions[DhcpOpt_SubnetMask] = DhcpOptValue("255.255.255.0");
1957 srv.strIPLower = "192.168.56.101";
1958 srv.strIPUpper = "192.168.56.254";
1959 srv.fEnabled = true;
1960 llDhcpServers.push_back(srv);
1961 }
1962}
1963
1964void MainConfigFile::bumpSettingsVersionIfNeeded()
1965{
1966 if (m->sv < SettingsVersion_v1_16)
1967 {
1968 // VirtualBox 5.1 add support for additional USB device sources.
1969 if (!host.llUSBDeviceSources.empty())
1970 m->sv = SettingsVersion_v1_16;
1971 }
1972
1973 if (m->sv < SettingsVersion_v1_14)
1974 {
1975 // VirtualBox 4.3 adds NAT networks.
1976 if ( !llNATNetworks.empty())
1977 m->sv = SettingsVersion_v1_14;
1978 }
1979}
1980
1981
1982/**
1983 * Called from the IVirtualBox interface to write out VirtualBox.xml. This
1984 * builds an XML DOM tree and writes it out to disk.
1985 */
1986void MainConfigFile::write(const com::Utf8Str strFilename)
1987{
1988 bumpSettingsVersionIfNeeded();
1989
1990 m->strFilename = strFilename;
1991 specialBackupIfFirstBump();
1992 createStubDocument();
1993
1994 xml::ElementNode *pelmGlobal = m->pelmRoot->createChild("Global");
1995
1996 buildExtraData(*pelmGlobal, mapExtraDataItems);
1997
1998 xml::ElementNode *pelmMachineRegistry = pelmGlobal->createChild("MachineRegistry");
1999 for (MachinesRegistry::const_iterator it = llMachines.begin();
2000 it != llMachines.end();
2001 ++it)
2002 {
2003 // <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"/>
2004 const MachineRegistryEntry &mre = *it;
2005 xml::ElementNode *pelmMachineEntry = pelmMachineRegistry->createChild("MachineEntry");
2006 pelmMachineEntry->setAttribute("uuid", mre.uuid.toStringCurly());
2007 pelmMachineEntry->setAttribute("src", mre.strSettingsFile);
2008 }
2009
2010 buildMediaRegistry(*pelmGlobal, mediaRegistry);
2011
2012 xml::ElementNode *pelmNetserviceRegistry = pelmGlobal->createChild("NetserviceRegistry");
2013 xml::ElementNode *pelmDHCPServers = pelmNetserviceRegistry->createChild("DHCPServers");
2014 for (DHCPServersList::const_iterator it = llDhcpServers.begin();
2015 it != llDhcpServers.end();
2016 ++it)
2017 {
2018 const DHCPServer &d = *it;
2019 xml::ElementNode *pelmThis = pelmDHCPServers->createChild("DHCPServer");
2020 DhcpOptConstIterator itOpt;
2021 itOpt = d.GlobalDhcpOptions.find(DhcpOpt_SubnetMask);
2022
2023 pelmThis->setAttribute("networkName", d.strNetworkName);
2024 pelmThis->setAttribute("IPAddress", d.strIPAddress);
2025 if (itOpt != d.GlobalDhcpOptions.end())
2026 pelmThis->setAttribute("networkMask", itOpt->second.text);
2027 pelmThis->setAttribute("lowerIP", d.strIPLower);
2028 pelmThis->setAttribute("upperIP", d.strIPUpper);
2029 pelmThis->setAttribute("enabled", (d.fEnabled) ? 1 : 0); // too bad we chose 1 vs. 0 here
2030 /* We assume that if there're only 1 element it means that */
2031 size_t cOpt = d.GlobalDhcpOptions.size();
2032 /* We don't want duplicate validation check of networkMask here*/
2033 if ( ( itOpt == d.GlobalDhcpOptions.end()
2034 && cOpt > 0)
2035 || cOpt > 1)
2036 {
2037 xml::ElementNode *pelmOptions = pelmThis->createChild("Options");
2038 for (itOpt = d.GlobalDhcpOptions.begin();
2039 itOpt != d.GlobalDhcpOptions.end();
2040 ++itOpt)
2041 {
2042 if (itOpt->first == DhcpOpt_SubnetMask)
2043 continue;
2044
2045 xml::ElementNode *pelmOpt = pelmOptions->createChild("Option");
2046
2047 if (!pelmOpt)
2048 break;
2049
2050 pelmOpt->setAttribute("name", itOpt->first);
2051 pelmOpt->setAttribute("value", itOpt->second.text);
2052 if (itOpt->second.encoding != DhcpOptEncoding_Legacy)
2053 pelmOpt->setAttribute("encoding", (int)itOpt->second.encoding);
2054 }
2055 } /* end of if */
2056
2057 if (d.VmSlot2OptionsM.size() > 0)
2058 {
2059 VmSlot2OptionsConstIterator itVmSlot;
2060 DhcpOptConstIterator itOpt1;
2061 for(itVmSlot = d.VmSlot2OptionsM.begin();
2062 itVmSlot != d.VmSlot2OptionsM.end();
2063 ++itVmSlot)
2064 {
2065 xml::ElementNode *pelmCfg = pelmThis->createChild("Config");
2066 pelmCfg->setAttribute("vm-name", itVmSlot->first.VmName);
2067 pelmCfg->setAttribute("slot", (int32_t)itVmSlot->first.Slot);
2068
2069 for (itOpt1 = itVmSlot->second.begin();
2070 itOpt1 != itVmSlot->second.end();
2071 ++itOpt1)
2072 {
2073 xml::ElementNode *pelmOpt = pelmCfg->createChild("Option");
2074 pelmOpt->setAttribute("name", itOpt1->first);
2075 pelmOpt->setAttribute("value", itOpt1->second.text);
2076 if (itOpt1->second.encoding != DhcpOptEncoding_Legacy)
2077 pelmOpt->setAttribute("encoding", (int)itOpt1->second.encoding);
2078 }
2079 }
2080 } /* and of if */
2081
2082 }
2083
2084 xml::ElementNode *pelmNATNetworks;
2085 /* don't create entry if no NAT networks are registered. */
2086 if (!llNATNetworks.empty())
2087 {
2088 pelmNATNetworks = pelmNetserviceRegistry->createChild("NATNetworks");
2089 for (NATNetworksList::const_iterator it = llNATNetworks.begin();
2090 it != llNATNetworks.end();
2091 ++it)
2092 {
2093 const NATNetwork &n = *it;
2094 xml::ElementNode *pelmThis = pelmNATNetworks->createChild("NATNetwork");
2095 pelmThis->setAttribute("networkName", n.strNetworkName);
2096 pelmThis->setAttribute("network", n.strIPv4NetworkCidr);
2097 pelmThis->setAttribute("ipv6", n.fIPv6Enabled ? 1 : 0);
2098 pelmThis->setAttribute("ipv6prefix", n.strIPv6Prefix);
2099 pelmThis->setAttribute("advertiseDefaultIPv6Route", (n.fAdvertiseDefaultIPv6Route)? 1 : 0);
2100 pelmThis->setAttribute("needDhcp", (n.fNeedDhcpServer) ? 1 : 0);
2101 pelmThis->setAttribute("enabled", (n.fEnabled) ? 1 : 0); // too bad we chose 1 vs. 0 here
2102 if (n.mapPortForwardRules4.size())
2103 {
2104 xml::ElementNode *pelmPf4 = pelmThis->createChild("PortForwarding4");
2105 buildNATForwardRulesMap(*pelmPf4, n.mapPortForwardRules4);
2106 }
2107 if (n.mapPortForwardRules6.size())
2108 {
2109 xml::ElementNode *pelmPf6 = pelmThis->createChild("PortForwarding6");
2110 buildNATForwardRulesMap(*pelmPf6, n.mapPortForwardRules6);
2111 }
2112
2113 if (n.llHostLoopbackOffsetList.size())
2114 {
2115 xml::ElementNode *pelmMappings = pelmThis->createChild("Mappings");
2116 buildNATLoopbacks(*pelmMappings, n.llHostLoopbackOffsetList);
2117
2118 }
2119 }
2120 }
2121
2122
2123 xml::ElementNode *pelmSysProps = pelmGlobal->createChild("SystemProperties");
2124 if (systemProperties.strDefaultMachineFolder.length())
2125 pelmSysProps->setAttribute("defaultMachineFolder", systemProperties.strDefaultMachineFolder);
2126 if (systemProperties.strLoggingLevel.length())
2127 pelmSysProps->setAttribute("LoggingLevel", systemProperties.strLoggingLevel);
2128 if (systemProperties.strDefaultHardDiskFormat.length())
2129 pelmSysProps->setAttribute("defaultHardDiskFormat", systemProperties.strDefaultHardDiskFormat);
2130 if (systemProperties.strVRDEAuthLibrary.length())
2131 pelmSysProps->setAttribute("VRDEAuthLibrary", systemProperties.strVRDEAuthLibrary);
2132 if (systemProperties.strWebServiceAuthLibrary.length())
2133 pelmSysProps->setAttribute("webServiceAuthLibrary", systemProperties.strWebServiceAuthLibrary);
2134 if (systemProperties.strDefaultVRDEExtPack.length())
2135 pelmSysProps->setAttribute("defaultVRDEExtPack", systemProperties.strDefaultVRDEExtPack);
2136 pelmSysProps->setAttribute("LogHistoryCount", systemProperties.ulLogHistoryCount);
2137 if (systemProperties.strAutostartDatabasePath.length())
2138 pelmSysProps->setAttribute("autostartDatabasePath", systemProperties.strAutostartDatabasePath);
2139 if (systemProperties.strDefaultFrontend.length())
2140 pelmSysProps->setAttribute("defaultFrontend", systemProperties.strDefaultFrontend);
2141 pelmSysProps->setAttribute("exclusiveHwVirt", systemProperties.fExclusiveHwVirt);
2142
2143 buildUSBDeviceFilters(*pelmGlobal->createChild("USBDeviceFilters"),
2144 host.llUSBDeviceFilters,
2145 true); // fHostMode
2146
2147 if (!host.llUSBDeviceSources.empty())
2148 buildUSBDeviceSources(*pelmGlobal->createChild("USBDeviceSources"),
2149 host.llUSBDeviceSources);
2150
2151 // now go write the XML
2152 xml::XmlFileWriter writer(*m->pDoc);
2153 writer.write(m->strFilename.c_str(), true /*fSafe*/);
2154
2155 m->fFileExists = true;
2156
2157 clearDocument();
2158}
2159
2160////////////////////////////////////////////////////////////////////////////////
2161//
2162// Machine XML structures
2163//
2164////////////////////////////////////////////////////////////////////////////////
2165
2166/**
2167 * Constructor. Needs to set sane defaults which stand the test of time.
2168 */
2169VRDESettings::VRDESettings() :
2170 fEnabled(true), // default for old VMs, for new ones it's false
2171 authType(AuthType_Null),
2172 ulAuthTimeout(5000),
2173 fAllowMultiConnection(false),
2174 fReuseSingleConnection(false)
2175{
2176}
2177
2178/**
2179 * Check if all settings have default values.
2180 */
2181bool VRDESettings::areDefaultSettings(SettingsVersion_T sv) const
2182{
2183 return (sv < SettingsVersion_v1_16 ? fEnabled : !fEnabled)
2184 && authType == AuthType_Null
2185 && (ulAuthTimeout == 5000 || ulAuthTimeout == 0)
2186 && strAuthLibrary.isEmpty()
2187 && !fAllowMultiConnection
2188 && !fReuseSingleConnection
2189 && strVrdeExtPack.isEmpty()
2190 && mapProperties.size() == 0;
2191}
2192
2193/**
2194 * Comparison operator. This gets called from MachineConfigFile::operator==,
2195 * which in turn gets called from Machine::saveSettings to figure out whether
2196 * machine settings have really changed and thus need to be written out to disk.
2197 */
2198bool VRDESettings::operator==(const VRDESettings& v) const
2199{
2200 return (this == &v)
2201 || ( fEnabled == v.fEnabled
2202 && authType == v.authType
2203 && ulAuthTimeout == v.ulAuthTimeout
2204 && strAuthLibrary == v.strAuthLibrary
2205 && fAllowMultiConnection == v.fAllowMultiConnection
2206 && fReuseSingleConnection == v.fReuseSingleConnection
2207 && strVrdeExtPack == v.strVrdeExtPack
2208 && mapProperties == v.mapProperties);
2209}
2210
2211/**
2212 * Constructor. Needs to set sane defaults which stand the test of time.
2213 */
2214BIOSSettings::BIOSSettings() :
2215 fACPIEnabled(true),
2216 fIOAPICEnabled(false),
2217 fLogoFadeIn(true),
2218 fLogoFadeOut(true),
2219 fPXEDebugEnabled(false),
2220 ulLogoDisplayTime(0),
2221 biosBootMenuMode(BIOSBootMenuMode_MessageAndMenu),
2222 apicMode(APICMode_APIC),
2223 llTimeOffset(0)
2224{
2225}
2226
2227/**
2228 * Check if all settings have default values.
2229 */
2230bool BIOSSettings::areDefaultSettings() const
2231{
2232 return fACPIEnabled
2233 && !fIOAPICEnabled
2234 && fLogoFadeIn
2235 && fLogoFadeOut
2236 && !fPXEDebugEnabled
2237 && ulLogoDisplayTime == 0
2238 && biosBootMenuMode == BIOSBootMenuMode_MessageAndMenu
2239 && apicMode == APICMode_APIC
2240 && llTimeOffset == 0
2241 && strLogoImagePath.isEmpty();
2242}
2243
2244/**
2245 * Comparison operator. This gets called from MachineConfigFile::operator==,
2246 * which in turn gets called from Machine::saveSettings to figure out whether
2247 * machine settings have really changed and thus need to be written out to disk.
2248 */
2249bool BIOSSettings::operator==(const BIOSSettings &d) const
2250{
2251 return (this == &d)
2252 || ( fACPIEnabled == d.fACPIEnabled
2253 && fIOAPICEnabled == d.fIOAPICEnabled
2254 && fLogoFadeIn == d.fLogoFadeIn
2255 && fLogoFadeOut == d.fLogoFadeOut
2256 && fPXEDebugEnabled == d.fPXEDebugEnabled
2257 && ulLogoDisplayTime == d.ulLogoDisplayTime
2258 && biosBootMenuMode == d.biosBootMenuMode
2259 && apicMode == d.apicMode
2260 && llTimeOffset == d.llTimeOffset
2261 && strLogoImagePath == d.strLogoImagePath);
2262}
2263
2264/**
2265 * Constructor. Needs to set sane defaults which stand the test of time.
2266 */
2267USBController::USBController() :
2268 enmType(USBControllerType_Null)
2269{
2270}
2271
2272/**
2273 * Comparison operator. This gets called from MachineConfigFile::operator==,
2274 * which in turn gets called from Machine::saveSettings to figure out whether
2275 * machine settings have really changed and thus need to be written out to disk.
2276 */
2277bool USBController::operator==(const USBController &u) const
2278{
2279 return (this == &u)
2280 || ( strName == u.strName
2281 && enmType == u.enmType);
2282}
2283
2284/**
2285 * Constructor. Needs to set sane defaults which stand the test of time.
2286 */
2287USB::USB()
2288{
2289}
2290
2291/**
2292 * Comparison operator. This gets called from MachineConfigFile::operator==,
2293 * which in turn gets called from Machine::saveSettings to figure out whether
2294 * machine settings have really changed and thus need to be written out to disk.
2295 */
2296bool USB::operator==(const USB &u) const
2297{
2298 return (this == &u)
2299 || ( llUSBControllers == u.llUSBControllers
2300 && llDeviceFilters == u.llDeviceFilters);
2301}
2302
2303/**
2304 * Constructor. Needs to set sane defaults which stand the test of time.
2305 */
2306NAT::NAT() :
2307 u32Mtu(0),
2308 u32SockRcv(0),
2309 u32SockSnd(0),
2310 u32TcpRcv(0),
2311 u32TcpSnd(0),
2312 fDNSPassDomain(true), /* historically this value is true */
2313 fDNSProxy(false),
2314 fDNSUseHostResolver(false),
2315 fAliasLog(false),
2316 fAliasProxyOnly(false),
2317 fAliasUseSamePorts(false)
2318{
2319}
2320
2321/**
2322 * Check if all DNS settings have default values.
2323 */
2324bool NAT::areDNSDefaultSettings() const
2325{
2326 return fDNSPassDomain && !fDNSProxy && !fDNSUseHostResolver;
2327}
2328
2329/**
2330 * Check if all Alias settings have default values.
2331 */
2332bool NAT::areAliasDefaultSettings() const
2333{
2334 return !fAliasLog && !fAliasProxyOnly && !fAliasUseSamePorts;
2335}
2336
2337/**
2338 * Check if all TFTP settings have default values.
2339 */
2340bool NAT::areTFTPDefaultSettings() const
2341{
2342 return strTFTPPrefix.isEmpty()
2343 && strTFTPBootFile.isEmpty()
2344 && strTFTPNextServer.isEmpty();
2345}
2346
2347/**
2348 * Check if all settings have default values.
2349 */
2350bool NAT::areDefaultSettings() const
2351{
2352 return strNetwork.isEmpty()
2353 && strBindIP.isEmpty()
2354 && u32Mtu == 0
2355 && u32SockRcv == 0
2356 && u32SockSnd == 0
2357 && u32TcpRcv == 0
2358 && u32TcpSnd == 0
2359 && areDNSDefaultSettings()
2360 && areAliasDefaultSettings()
2361 && areTFTPDefaultSettings()
2362 && mapRules.size() == 0;
2363}
2364
2365/**
2366 * Comparison operator. This gets called from MachineConfigFile::operator==,
2367 * which in turn gets called from Machine::saveSettings to figure out whether
2368 * machine settings have really changed and thus need to be written out to disk.
2369 */
2370bool NAT::operator==(const NAT &n) const
2371{
2372 return (this == &n)
2373 || ( strNetwork == n.strNetwork
2374 && strBindIP == n.strBindIP
2375 && u32Mtu == n.u32Mtu
2376 && u32SockRcv == n.u32SockRcv
2377 && u32SockSnd == n.u32SockSnd
2378 && u32TcpSnd == n.u32TcpSnd
2379 && u32TcpRcv == n.u32TcpRcv
2380 && strTFTPPrefix == n.strTFTPPrefix
2381 && strTFTPBootFile == n.strTFTPBootFile
2382 && strTFTPNextServer == n.strTFTPNextServer
2383 && fDNSPassDomain == n.fDNSPassDomain
2384 && fDNSProxy == n.fDNSProxy
2385 && fDNSUseHostResolver == n.fDNSUseHostResolver
2386 && fAliasLog == n.fAliasLog
2387 && fAliasProxyOnly == n.fAliasProxyOnly
2388 && fAliasUseSamePorts == n.fAliasUseSamePorts
2389 && mapRules == n.mapRules);
2390}
2391
2392/**
2393 * Constructor. Needs to set sane defaults which stand the test of time.
2394 */
2395NetworkAdapter::NetworkAdapter() :
2396 ulSlot(0),
2397 type(NetworkAdapterType_Am79C970A), // default for old VMs, for new ones it's Am79C973
2398 fEnabled(false),
2399 fCableConnected(false), // default for old VMs, for new ones it's true
2400 ulLineSpeed(0),
2401 enmPromiscModePolicy(NetworkAdapterPromiscModePolicy_Deny),
2402 fTraceEnabled(false),
2403 mode(NetworkAttachmentType_Null),
2404 ulBootPriority(0)
2405{
2406}
2407
2408/**
2409 * Check if all Generic Driver settings have default values.
2410 */
2411bool NetworkAdapter::areGenericDriverDefaultSettings() const
2412{
2413 return strGenericDriver.isEmpty()
2414 && genericProperties.size() == 0;
2415}
2416
2417/**
2418 * Check if all settings have default values.
2419 */
2420bool NetworkAdapter::areDefaultSettings(SettingsVersion_T sv) const
2421{
2422 // 5.0 and earlier had a default of fCableConnected=false, which doesn't
2423 // make a lot of sense (but it's a fact). Later versions don't save the
2424 // setting if it's at the default value and thus must get it right.
2425 return !fEnabled
2426 && strMACAddress.isEmpty()
2427 && ( (sv >= SettingsVersion_v1_16 && fCableConnected && type == NetworkAdapterType_Am79C973)
2428 || (sv < SettingsVersion_v1_16 && !fCableConnected && type == NetworkAdapterType_Am79C970A))
2429 && ulLineSpeed == 0
2430 && enmPromiscModePolicy == NetworkAdapterPromiscModePolicy_Deny
2431 && mode == NetworkAttachmentType_Null
2432 && nat.areDefaultSettings()
2433 && strBridgedName.isEmpty()
2434 && strInternalNetworkName.isEmpty()
2435 && strHostOnlyName.isEmpty()
2436 && areGenericDriverDefaultSettings()
2437 && strNATNetworkName.isEmpty();
2438}
2439
2440/**
2441 * Special check if settings of the non-current attachment type have default values.
2442 */
2443bool NetworkAdapter::areDisabledDefaultSettings() const
2444{
2445 return (mode != NetworkAttachmentType_NAT ? nat.areDefaultSettings() : true)
2446 && (mode != NetworkAttachmentType_Bridged ? strBridgedName.isEmpty() : true)
2447 && (mode != NetworkAttachmentType_Internal ? strInternalNetworkName.isEmpty() : true)
2448 && (mode != NetworkAttachmentType_HostOnly ? strHostOnlyName.isEmpty() : true)
2449 && (mode != NetworkAttachmentType_Generic ? areGenericDriverDefaultSettings() : true)
2450 && (mode != NetworkAttachmentType_NATNetwork ? strNATNetworkName.isEmpty() : true);
2451}
2452
2453/**
2454 * Comparison operator. This gets called from MachineConfigFile::operator==,
2455 * which in turn gets called from Machine::saveSettings to figure out whether
2456 * machine settings have really changed and thus need to be written out to disk.
2457 */
2458bool NetworkAdapter::operator==(const NetworkAdapter &n) const
2459{
2460 return (this == &n)
2461 || ( ulSlot == n.ulSlot
2462 && type == n.type
2463 && fEnabled == n.fEnabled
2464 && strMACAddress == n.strMACAddress
2465 && fCableConnected == n.fCableConnected
2466 && ulLineSpeed == n.ulLineSpeed
2467 && enmPromiscModePolicy == n.enmPromiscModePolicy
2468 && fTraceEnabled == n.fTraceEnabled
2469 && strTraceFile == n.strTraceFile
2470 && mode == n.mode
2471 && nat == n.nat
2472 && strBridgedName == n.strBridgedName
2473 && strHostOnlyName == n.strHostOnlyName
2474 && strInternalNetworkName == n.strInternalNetworkName
2475 && strGenericDriver == n.strGenericDriver
2476 && genericProperties == n.genericProperties
2477 && ulBootPriority == n.ulBootPriority
2478 && strBandwidthGroup == n.strBandwidthGroup);
2479}
2480
2481/**
2482 * Constructor. Needs to set sane defaults which stand the test of time.
2483 */
2484SerialPort::SerialPort() :
2485 ulSlot(0),
2486 fEnabled(false),
2487 ulIOBase(0x3f8),
2488 ulIRQ(4),
2489 portMode(PortMode_Disconnected),
2490 fServer(false)
2491{
2492}
2493
2494/**
2495 * Comparison operator. This gets called from MachineConfigFile::operator==,
2496 * which in turn gets called from Machine::saveSettings to figure out whether
2497 * machine settings have really changed and thus need to be written out to disk.
2498 */
2499bool SerialPort::operator==(const SerialPort &s) const
2500{
2501 return (this == &s)
2502 || ( ulSlot == s.ulSlot
2503 && fEnabled == s.fEnabled
2504 && ulIOBase == s.ulIOBase
2505 && ulIRQ == s.ulIRQ
2506 && portMode == s.portMode
2507 && strPath == s.strPath
2508 && fServer == s.fServer);
2509}
2510
2511/**
2512 * Constructor. Needs to set sane defaults which stand the test of time.
2513 */
2514ParallelPort::ParallelPort() :
2515 ulSlot(0),
2516 fEnabled(false),
2517 ulIOBase(0x378),
2518 ulIRQ(7)
2519{
2520}
2521
2522/**
2523 * Comparison operator. This gets called from MachineConfigFile::operator==,
2524 * which in turn gets called from Machine::saveSettings to figure out whether
2525 * machine settings have really changed and thus need to be written out to disk.
2526 */
2527bool ParallelPort::operator==(const ParallelPort &s) const
2528{
2529 return (this == &s)
2530 || ( ulSlot == s.ulSlot
2531 && fEnabled == s.fEnabled
2532 && ulIOBase == s.ulIOBase
2533 && ulIRQ == s.ulIRQ
2534 && strPath == s.strPath);
2535}
2536
2537/**
2538 * Constructor. Needs to set sane defaults which stand the test of time.
2539 */
2540AudioAdapter::AudioAdapter() :
2541 fEnabled(true), // default for old VMs, for new ones it's false
2542 controllerType(AudioControllerType_AC97),
2543 codecType(AudioCodecType_STAC9700),
2544 driverType(AudioDriverType_Null)
2545{
2546}
2547
2548/**
2549 * Check if all settings have default values.
2550 */
2551bool AudioAdapter::areDefaultSettings(SettingsVersion_T sv) const
2552{
2553 return (sv < SettingsVersion_v1_16 ? false : !fEnabled)
2554 && controllerType == AudioControllerType_AC97
2555 && codecType == AudioCodecType_STAC9700
2556 && properties.size() == 0;
2557}
2558
2559/**
2560 * Comparison operator. This gets called from MachineConfigFile::operator==,
2561 * which in turn gets called from Machine::saveSettings to figure out whether
2562 * machine settings have really changed and thus need to be written out to disk.
2563 */
2564bool AudioAdapter::operator==(const AudioAdapter &a) const
2565{
2566 return (this == &a)
2567 || ( fEnabled == a.fEnabled
2568 && controllerType == a.controllerType
2569 && codecType == a.codecType
2570 && driverType == a.driverType
2571 && properties == a.properties);
2572}
2573
2574/**
2575 * Constructor. Needs to set sane defaults which stand the test of time.
2576 */
2577SharedFolder::SharedFolder() :
2578 fWritable(false),
2579 fAutoMount(false)
2580{
2581}
2582
2583/**
2584 * Comparison operator. This gets called from MachineConfigFile::operator==,
2585 * which in turn gets called from Machine::saveSettings to figure out whether
2586 * machine settings have really changed and thus need to be written out to disk.
2587 */
2588bool SharedFolder::operator==(const SharedFolder &g) const
2589{
2590 return (this == &g)
2591 || ( strName == g.strName
2592 && strHostPath == g.strHostPath
2593 && fWritable == g.fWritable
2594 && fAutoMount == g.fAutoMount);
2595}
2596
2597/**
2598 * Constructor. Needs to set sane defaults which stand the test of time.
2599 */
2600GuestProperty::GuestProperty() :
2601 timestamp(0)
2602{
2603}
2604
2605/**
2606 * Comparison operator. This gets called from MachineConfigFile::operator==,
2607 * which in turn gets called from Machine::saveSettings to figure out whether
2608 * machine settings have really changed and thus need to be written out to disk.
2609 */
2610bool GuestProperty::operator==(const GuestProperty &g) const
2611{
2612 return (this == &g)
2613 || ( strName == g.strName
2614 && strValue == g.strValue
2615 && timestamp == g.timestamp
2616 && strFlags == g.strFlags);
2617}
2618
2619/**
2620 * Constructor. Needs to set sane defaults which stand the test of time.
2621 */
2622CpuIdLeaf::CpuIdLeaf() :
2623 ulId(UINT32_MAX),
2624 ulEax(0),
2625 ulEbx(0),
2626 ulEcx(0),
2627 ulEdx(0)
2628{
2629}
2630
2631/**
2632 * Comparison operator. This gets called from MachineConfigFile::operator==,
2633 * which in turn gets called from Machine::saveSettings to figure out whether
2634 * machine settings have really changed and thus need to be written out to disk.
2635 */
2636bool CpuIdLeaf::operator==(const CpuIdLeaf &c) const
2637{
2638 return (this == &c)
2639 || ( ulId == c.ulId
2640 && ulEax == c.ulEax
2641 && ulEbx == c.ulEbx
2642 && ulEcx == c.ulEcx
2643 && ulEdx == c.ulEdx);
2644}
2645
2646/**
2647 * Constructor. Needs to set sane defaults which stand the test of time.
2648 */
2649Cpu::Cpu() :
2650 ulId(UINT32_MAX)
2651{
2652}
2653
2654/**
2655 * Comparison operator. This gets called from MachineConfigFile::operator==,
2656 * which in turn gets called from Machine::saveSettings to figure out whether
2657 * machine settings have really changed and thus need to be written out to disk.
2658 */
2659bool Cpu::operator==(const Cpu &c) const
2660{
2661 return (this == &c)
2662 || (ulId == c.ulId);
2663}
2664
2665/**
2666 * Constructor. Needs to set sane defaults which stand the test of time.
2667 */
2668BandwidthGroup::BandwidthGroup() :
2669 cMaxBytesPerSec(0),
2670 enmType(BandwidthGroupType_Null)
2671{
2672}
2673
2674/**
2675 * Comparison operator. This gets called from MachineConfigFile::operator==,
2676 * which in turn gets called from Machine::saveSettings to figure out whether
2677 * machine settings have really changed and thus need to be written out to disk.
2678 */
2679bool BandwidthGroup::operator==(const BandwidthGroup &i) const
2680{
2681 return (this == &i)
2682 || ( strName == i.strName
2683 && cMaxBytesPerSec == i.cMaxBytesPerSec
2684 && enmType == i.enmType);
2685}
2686
2687/**
2688 * IOSettings constructor.
2689 */
2690IOSettings::IOSettings() :
2691 fIOCacheEnabled(true),
2692 ulIOCacheSize(5)
2693{
2694}
2695
2696/**
2697 * Check if all IO Cache settings have default values.
2698 */
2699bool IOSettings::areIOCacheDefaultSettings() const
2700{
2701 return fIOCacheEnabled
2702 && ulIOCacheSize == 5;
2703}
2704
2705/**
2706 * Check if all settings have default values.
2707 */
2708bool IOSettings::areDefaultSettings() const
2709{
2710 return areIOCacheDefaultSettings()
2711 && llBandwidthGroups.size() == 0;
2712}
2713
2714/**
2715 * Comparison operator. This gets called from MachineConfigFile::operator==,
2716 * which in turn gets called from Machine::saveSettings to figure out whether
2717 * machine settings have really changed and thus need to be written out to disk.
2718 */
2719bool IOSettings::operator==(const IOSettings &i) const
2720{
2721 return (this == &i)
2722 || ( fIOCacheEnabled == i.fIOCacheEnabled
2723 && ulIOCacheSize == i.ulIOCacheSize
2724 && llBandwidthGroups == i.llBandwidthGroups);
2725}
2726
2727/**
2728 * Constructor. Needs to set sane defaults which stand the test of time.
2729 */
2730HostPCIDeviceAttachment::HostPCIDeviceAttachment() :
2731 uHostAddress(0),
2732 uGuestAddress(0)
2733{
2734}
2735
2736/**
2737 * Comparison operator. This gets called from MachineConfigFile::operator==,
2738 * which in turn gets called from Machine::saveSettings to figure out whether
2739 * machine settings have really changed and thus need to be written out to disk.
2740 */
2741bool HostPCIDeviceAttachment::operator==(const HostPCIDeviceAttachment &a) const
2742{
2743 return (this == &a)
2744 || ( uHostAddress == a.uHostAddress
2745 && uGuestAddress == a.uGuestAddress
2746 && strDeviceName == a.strDeviceName);
2747}
2748
2749
2750/**
2751 * Constructor. Needs to set sane defaults which stand the test of time.
2752 */
2753Hardware::Hardware() :
2754 strVersion("1"),
2755 fHardwareVirt(true),
2756 fNestedPaging(true),
2757 fVPID(true),
2758 fUnrestrictedExecution(true),
2759 fHardwareVirtForce(false),
2760 fTripleFaultReset(false),
2761 fPAE(false),
2762 fAPIC(true),
2763 fX2APIC(false),
2764 enmLongMode(HC_ARCH_BITS == 64 ? Hardware::LongMode_Enabled : Hardware::LongMode_Disabled),
2765 cCPUs(1),
2766 fCpuHotPlug(false),
2767 fHPETEnabled(false),
2768 ulCpuExecutionCap(100),
2769 uCpuIdPortabilityLevel(0),
2770 strCpuProfile("host"),
2771 ulMemorySizeMB((uint32_t)-1),
2772 graphicsControllerType(GraphicsControllerType_VBoxVGA),
2773 ulVRAMSizeMB(8),
2774 cMonitors(1),
2775 fAccelerate3D(false),
2776 fAccelerate2DVideo(false),
2777 ulVideoCaptureHorzRes(1024),
2778 ulVideoCaptureVertRes(768),
2779 ulVideoCaptureRate(512),
2780 ulVideoCaptureFPS(25),
2781 ulVideoCaptureMaxTime(0),
2782 ulVideoCaptureMaxSize(0),
2783 fVideoCaptureEnabled(false),
2784 u64VideoCaptureScreens(UINT64_C(0xffffffffffffffff)),
2785 strVideoCaptureFile(""),
2786 firmwareType(FirmwareType_BIOS),
2787 pointingHIDType(PointingHIDType_PS2Mouse),
2788 keyboardHIDType(KeyboardHIDType_PS2Keyboard),
2789 chipsetType(ChipsetType_PIIX3),
2790 paravirtProvider(ParavirtProvider_Legacy), // default for old VMs, for new ones it's ParavirtProvider_Default
2791 strParavirtDebug(""),
2792 fEmulatedUSBCardReader(false),
2793 clipboardMode(ClipboardMode_Disabled),
2794 dndMode(DnDMode_Disabled),
2795 ulMemoryBalloonSize(0),
2796 fPageFusionEnabled(false)
2797{
2798 mapBootOrder[0] = DeviceType_Floppy;
2799 mapBootOrder[1] = DeviceType_DVD;
2800 mapBootOrder[2] = DeviceType_HardDisk;
2801
2802 /* The default value for PAE depends on the host:
2803 * - 64 bits host -> always true
2804 * - 32 bits host -> true for Windows & Darwin (masked off if the host cpu doesn't support it anyway)
2805 */
2806#if HC_ARCH_BITS == 64 || defined(RT_OS_WINDOWS) || defined(RT_OS_DARWIN)
2807 fPAE = true;
2808#endif
2809
2810 /* The default value of large page supports depends on the host:
2811 * - 64 bits host -> true, unless it's Linux (pending further prediction work due to excessively expensive large page allocations)
2812 * - 32 bits host -> false
2813 */
2814#if HC_ARCH_BITS == 64 && !defined(RT_OS_LINUX)
2815 fLargePages = true;
2816#else
2817 /* Not supported on 32 bits hosts. */
2818 fLargePages = false;
2819#endif
2820}
2821
2822/**
2823 * Check if all Paravirt settings have default values.
2824 */
2825bool Hardware::areParavirtDefaultSettings(SettingsVersion_T sv) const
2826{
2827 // 5.0 didn't save the paravirt settings if it is ParavirtProvider_Legacy,
2828 // so this default must be kept. Later versions don't save the setting if
2829 // it's at the default value.
2830 return ( (sv >= SettingsVersion_v1_16 && paravirtProvider == ParavirtProvider_Default)
2831 || (sv < SettingsVersion_v1_16 && paravirtProvider == ParavirtProvider_Legacy))
2832 && strParavirtDebug.isEmpty();
2833}
2834
2835/**
2836 * Check if all Boot Order settings have default values.
2837 */
2838bool Hardware::areBootOrderDefaultSettings() const
2839{
2840 BootOrderMap::const_iterator it0 = mapBootOrder.find(0);
2841 BootOrderMap::const_iterator it1 = mapBootOrder.find(1);
2842 BootOrderMap::const_iterator it2 = mapBootOrder.find(2);
2843 BootOrderMap::const_iterator it3 = mapBootOrder.find(3);
2844 return ( mapBootOrder.size() == 3
2845 || ( mapBootOrder.size() == 4
2846 && (it3 != mapBootOrder.end() && it3->second == DeviceType_Null)))
2847 && (it0 != mapBootOrder.end() && it0->second == DeviceType_Floppy)
2848 && (it1 != mapBootOrder.end() && it1->second == DeviceType_DVD)
2849 && (it2 != mapBootOrder.end() && it2->second == DeviceType_HardDisk);
2850}
2851
2852/**
2853 * Check if all Display settings have default values.
2854 */
2855bool Hardware::areDisplayDefaultSettings() const
2856{
2857 return graphicsControllerType == GraphicsControllerType_VBoxVGA
2858 && ulVRAMSizeMB == 8
2859 && cMonitors <= 1
2860 && !fAccelerate3D
2861 && !fAccelerate2DVideo;
2862}
2863
2864/**
2865 * Check if all Video Capture settings have default values.
2866 */
2867bool Hardware::areVideoCaptureDefaultSettings() const
2868{
2869 return !fVideoCaptureEnabled
2870 && u64VideoCaptureScreens == UINT64_C(0xffffffffffffffff)
2871 && strVideoCaptureFile.isEmpty()
2872 && ulVideoCaptureHorzRes == 1024
2873 && ulVideoCaptureVertRes == 768
2874 && ulVideoCaptureRate == 512
2875 && ulVideoCaptureFPS == 25
2876 && ulVideoCaptureMaxTime == 0
2877 && ulVideoCaptureMaxSize == 0;
2878}
2879
2880/**
2881 * Check if all Network Adapter settings have default values.
2882 */
2883bool Hardware::areAllNetworkAdaptersDefaultSettings(SettingsVersion_T sv) const
2884{
2885 for (NetworkAdaptersList::const_iterator it = llNetworkAdapters.begin();
2886 it != llNetworkAdapters.end();
2887 ++it)
2888 {
2889 if (!it->areDefaultSettings(sv))
2890 return false;
2891 }
2892 return true;
2893}
2894
2895/**
2896 * Comparison operator. This gets called from MachineConfigFile::operator==,
2897 * which in turn gets called from Machine::saveSettings to figure out whether
2898 * machine settings have really changed and thus need to be written out to disk.
2899 */
2900bool Hardware::operator==(const Hardware& h) const
2901{
2902 return (this == &h)
2903 || ( strVersion == h.strVersion
2904 && uuid == h.uuid
2905 && fHardwareVirt == h.fHardwareVirt
2906 && fNestedPaging == h.fNestedPaging
2907 && fLargePages == h.fLargePages
2908 && fVPID == h.fVPID
2909 && fUnrestrictedExecution == h.fUnrestrictedExecution
2910 && fHardwareVirtForce == h.fHardwareVirtForce
2911 && fPAE == h.fPAE
2912 && enmLongMode == h.enmLongMode
2913 && fTripleFaultReset == h.fTripleFaultReset
2914 && fAPIC == h.fAPIC
2915 && fX2APIC == h.fX2APIC
2916 && cCPUs == h.cCPUs
2917 && fCpuHotPlug == h.fCpuHotPlug
2918 && ulCpuExecutionCap == h.ulCpuExecutionCap
2919 && uCpuIdPortabilityLevel == h.uCpuIdPortabilityLevel
2920 && strCpuProfile == h.strCpuProfile
2921 && fHPETEnabled == h.fHPETEnabled
2922 && llCpus == h.llCpus
2923 && llCpuIdLeafs == h.llCpuIdLeafs
2924 && ulMemorySizeMB == h.ulMemorySizeMB
2925 && mapBootOrder == h.mapBootOrder
2926 && graphicsControllerType == h.graphicsControllerType
2927 && ulVRAMSizeMB == h.ulVRAMSizeMB
2928 && cMonitors == h.cMonitors
2929 && fAccelerate3D == h.fAccelerate3D
2930 && fAccelerate2DVideo == h.fAccelerate2DVideo
2931 && fVideoCaptureEnabled == h.fVideoCaptureEnabled
2932 && u64VideoCaptureScreens == h.u64VideoCaptureScreens
2933 && strVideoCaptureFile == h.strVideoCaptureFile
2934 && ulVideoCaptureHorzRes == h.ulVideoCaptureHorzRes
2935 && ulVideoCaptureVertRes == h.ulVideoCaptureVertRes
2936 && ulVideoCaptureRate == h.ulVideoCaptureRate
2937 && ulVideoCaptureFPS == h.ulVideoCaptureFPS
2938 && ulVideoCaptureMaxTime == h.ulVideoCaptureMaxTime
2939 && ulVideoCaptureMaxSize == h.ulVideoCaptureMaxTime
2940 && firmwareType == h.firmwareType
2941 && pointingHIDType == h.pointingHIDType
2942 && keyboardHIDType == h.keyboardHIDType
2943 && chipsetType == h.chipsetType
2944 && paravirtProvider == h.paravirtProvider
2945 && strParavirtDebug == h.strParavirtDebug
2946 && fEmulatedUSBCardReader == h.fEmulatedUSBCardReader
2947 && vrdeSettings == h.vrdeSettings
2948 && biosSettings == h.biosSettings
2949 && usbSettings == h.usbSettings
2950 && llNetworkAdapters == h.llNetworkAdapters
2951 && llSerialPorts == h.llSerialPorts
2952 && llParallelPorts == h.llParallelPorts
2953 && audioAdapter == h.audioAdapter
2954 && storage == h.storage
2955 && llSharedFolders == h.llSharedFolders
2956 && clipboardMode == h.clipboardMode
2957 && dndMode == h.dndMode
2958 && ulMemoryBalloonSize == h.ulMemoryBalloonSize
2959 && fPageFusionEnabled == h.fPageFusionEnabled
2960 && llGuestProperties == h.llGuestProperties
2961 && ioSettings == h.ioSettings
2962 && pciAttachments == h.pciAttachments
2963 && strDefaultFrontend == h.strDefaultFrontend);
2964}
2965
2966/**
2967 * Constructor. Needs to set sane defaults which stand the test of time.
2968 */
2969AttachedDevice::AttachedDevice() :
2970 deviceType(DeviceType_Null),
2971 fPassThrough(false),
2972 fTempEject(false),
2973 fNonRotational(false),
2974 fDiscard(false),
2975 fHotPluggable(false),
2976 lPort(0),
2977 lDevice(0)
2978{
2979}
2980
2981/**
2982 * Comparison operator. This gets called from MachineConfigFile::operator==,
2983 * which in turn gets called from Machine::saveSettings to figure out whether
2984 * machine settings have really changed and thus need to be written out to disk.
2985 */
2986bool AttachedDevice::operator==(const AttachedDevice &a) const
2987{
2988 return (this == &a)
2989 || ( deviceType == a.deviceType
2990 && fPassThrough == a.fPassThrough
2991 && fTempEject == a.fTempEject
2992 && fNonRotational == a.fNonRotational
2993 && fDiscard == a.fDiscard
2994 && fHotPluggable == a.fHotPluggable
2995 && lPort == a.lPort
2996 && lDevice == a.lDevice
2997 && uuid == a.uuid
2998 && strHostDriveSrc == a.strHostDriveSrc
2999 && strBwGroup == a.strBwGroup);
3000}
3001
3002/**
3003 * Constructor. Needs to set sane defaults which stand the test of time.
3004 */
3005StorageController::StorageController() :
3006 storageBus(StorageBus_IDE),
3007 controllerType(StorageControllerType_PIIX3),
3008 ulPortCount(2),
3009 ulInstance(0),
3010 fUseHostIOCache(true),
3011 fBootable(true)
3012{
3013}
3014
3015/**
3016 * Comparison operator. This gets called from MachineConfigFile::operator==,
3017 * which in turn gets called from Machine::saveSettings to figure out whether
3018 * machine settings have really changed and thus need to be written out to disk.
3019 */
3020bool StorageController::operator==(const StorageController &s) const
3021{
3022 return (this == &s)
3023 || ( strName == s.strName
3024 && storageBus == s.storageBus
3025 && controllerType == s.controllerType
3026 && ulPortCount == s.ulPortCount
3027 && ulInstance == s.ulInstance
3028 && fUseHostIOCache == s.fUseHostIOCache
3029 && llAttachedDevices == s.llAttachedDevices);
3030}
3031
3032/**
3033 * Comparison operator. This gets called from MachineConfigFile::operator==,
3034 * which in turn gets called from Machine::saveSettings to figure out whether
3035 * machine settings have really changed and thus need to be written out to disk.
3036 */
3037bool Storage::operator==(const Storage &s) const
3038{
3039 return (this == &s)
3040 || (llStorageControllers == s.llStorageControllers); // deep compare
3041}
3042
3043/**
3044 * Constructor. Needs to set sane defaults which stand the test of time.
3045 */
3046Debugging::Debugging() :
3047 fTracingEnabled(false),
3048 fAllowTracingToAccessVM(false),
3049 strTracingConfig()
3050{
3051}
3052
3053/**
3054 * Check if all settings have default values.
3055 */
3056bool Debugging::areDefaultSettings() const
3057{
3058 return !fTracingEnabled
3059 && !fAllowTracingToAccessVM
3060 && strTracingConfig.isEmpty();
3061}
3062
3063/**
3064 * Comparison operator. This gets called from MachineConfigFile::operator==,
3065 * which in turn gets called from Machine::saveSettings to figure out whether
3066 * machine settings have really changed and thus need to be written out to disk.
3067 */
3068bool Debugging::operator==(const Debugging &d) const
3069{
3070 return (this == &d)
3071 || ( fTracingEnabled == d.fTracingEnabled
3072 && fAllowTracingToAccessVM == d.fAllowTracingToAccessVM
3073 && strTracingConfig == d.strTracingConfig);
3074}
3075
3076/**
3077 * Constructor. Needs to set sane defaults which stand the test of time.
3078 */
3079Autostart::Autostart() :
3080 fAutostartEnabled(false),
3081 uAutostartDelay(0),
3082 enmAutostopType(AutostopType_Disabled)
3083{
3084}
3085
3086/**
3087 * Check if all settings have default values.
3088 */
3089bool Autostart::areDefaultSettings() const
3090{
3091 return !fAutostartEnabled
3092 && !uAutostartDelay
3093 && enmAutostopType == AutostopType_Disabled;
3094}
3095
3096/**
3097 * Comparison operator. This gets called from MachineConfigFile::operator==,
3098 * which in turn gets called from Machine::saveSettings to figure out whether
3099 * machine settings have really changed and thus need to be written out to disk.
3100 */
3101bool Autostart::operator==(const Autostart &a) const
3102{
3103 return (this == &a)
3104 || ( fAutostartEnabled == a.fAutostartEnabled
3105 && uAutostartDelay == a.uAutostartDelay
3106 && enmAutostopType == a.enmAutostopType);
3107}
3108
3109/**
3110 * Constructor. Needs to set sane defaults which stand the test of time.
3111 */
3112Snapshot::Snapshot()
3113{
3114 RTTimeSpecSetNano(&timestamp, 0);
3115}
3116
3117/**
3118 * Comparison operator. This gets called from MachineConfigFile::operator==,
3119 * which in turn gets called from Machine::saveSettings to figure out whether
3120 * machine settings have really changed and thus need to be written out to disk.
3121 */
3122bool Snapshot::operator==(const Snapshot &s) const
3123{
3124 return (this == &s)
3125 || ( uuid == s.uuid
3126 && strName == s.strName
3127 && strDescription == s.strDescription
3128 && RTTimeSpecIsEqual(&timestamp, &s.timestamp)
3129 && strStateFile == s.strStateFile
3130 && hardware == s.hardware // deep compare
3131 && llChildSnapshots == s.llChildSnapshots // deep compare
3132 && debugging == s.debugging
3133 && autostart == s.autostart);
3134}
3135
3136const struct Snapshot settings::Snapshot::Empty; /* default ctor is OK */
3137
3138/**
3139 * Constructor. Needs to set sane defaults which stand the test of time.
3140 */
3141MachineUserData::MachineUserData() :
3142 fDirectoryIncludesUUID(false),
3143 fNameSync(true),
3144 fTeleporterEnabled(false),
3145 uTeleporterPort(0),
3146 enmFaultToleranceState(FaultToleranceState_Inactive),
3147 uFaultTolerancePort(0),
3148 uFaultToleranceInterval(0),
3149 fRTCUseUTC(false),
3150 strVMPriority()
3151{
3152 llGroups.push_back("/");
3153}
3154
3155/**
3156 * Comparison operator. This gets called from MachineConfigFile::operator==,
3157 * which in turn gets called from Machine::saveSettings to figure out whether
3158 * machine settings have really changed and thus need to be written out to disk.
3159 */
3160bool MachineUserData::operator==(const MachineUserData &c) const
3161{
3162 return (this == &c)
3163 || ( strName == c.strName
3164 && fDirectoryIncludesUUID == c.fDirectoryIncludesUUID
3165 && fNameSync == c.fNameSync
3166 && strDescription == c.strDescription
3167 && llGroups == c.llGroups
3168 && strOsType == c.strOsType
3169 && strSnapshotFolder == c.strSnapshotFolder
3170 && fTeleporterEnabled == c.fTeleporterEnabled
3171 && uTeleporterPort == c.uTeleporterPort
3172 && strTeleporterAddress == c.strTeleporterAddress
3173 && strTeleporterPassword == c.strTeleporterPassword
3174 && enmFaultToleranceState == c.enmFaultToleranceState
3175 && uFaultTolerancePort == c.uFaultTolerancePort
3176 && uFaultToleranceInterval == c.uFaultToleranceInterval
3177 && strFaultToleranceAddress == c.strFaultToleranceAddress
3178 && strFaultTolerancePassword == c.strFaultTolerancePassword
3179 && fRTCUseUTC == c.fRTCUseUTC
3180 && ovIcon == c.ovIcon
3181 && strVMPriority == c.strVMPriority);
3182}
3183
3184
3185////////////////////////////////////////////////////////////////////////////////
3186//
3187// MachineConfigFile
3188//
3189////////////////////////////////////////////////////////////////////////////////
3190
3191/**
3192 * Constructor.
3193 *
3194 * If pstrFilename is != NULL, this reads the given settings file into the member
3195 * variables and various substructures and lists. Otherwise, the member variables
3196 * are initialized with default values.
3197 *
3198 * Throws variants of xml::Error for I/O, XML and logical content errors, which
3199 * the caller should catch; if this constructor does not throw, then the member
3200 * variables contain meaningful values (either from the file or defaults).
3201 *
3202 * @param pstrFilename
3203 */
3204MachineConfigFile::MachineConfigFile(const Utf8Str *pstrFilename)
3205 : ConfigFileBase(pstrFilename),
3206 fCurrentStateModified(true),
3207 fAborted(false)
3208{
3209 RTTimeNow(&timeLastStateChange);
3210
3211 if (pstrFilename)
3212 {
3213 // the ConfigFileBase constructor has loaded the XML file, so now
3214 // we need only analyze what is in there
3215
3216 xml::NodesLoop nlRootChildren(*m->pelmRoot);
3217 const xml::ElementNode *pelmRootChild;
3218 while ((pelmRootChild = nlRootChildren.forAllNodes()))
3219 {
3220 if (pelmRootChild->nameEquals("Machine"))
3221 readMachine(*pelmRootChild);
3222 }
3223
3224 // clean up memory allocated by XML engine
3225 clearDocument();
3226 }
3227}
3228
3229/**
3230 * Public routine which returns true if this machine config file can have its
3231 * own media registry (which is true for settings version v1.11 and higher,
3232 * i.e. files created by VirtualBox 4.0 and higher).
3233 * @return
3234 */
3235bool MachineConfigFile::canHaveOwnMediaRegistry() const
3236{
3237 return (m->sv >= SettingsVersion_v1_11);
3238}
3239
3240/**
3241 * Public routine which allows for importing machine XML from an external DOM tree.
3242 * Use this after having called the constructor with a NULL argument.
3243 *
3244 * This is used by the OVF code if a <vbox:Machine> element has been encountered
3245 * in an OVF VirtualSystem element.
3246 *
3247 * @param elmMachine
3248 */
3249void MachineConfigFile::importMachineXML(const xml::ElementNode &elmMachine)
3250{
3251 // Ideally the version should be mandatory, but since VirtualBox didn't
3252 // care about it until 5.1 came with different defaults, there are OVF
3253 // files created by magicians (not using VirtualBox, which always wrote it)
3254 // which lack this information. Let's hope that they learn to add the
3255 // version when they switch to the newer settings style/defaults of 5.1.
3256 if (!(elmMachine.getAttributeValue("version", m->strSettingsVersionFull)))
3257 m->strSettingsVersionFull = VBOX_XML_IMPORT_VERSION_FULL;
3258
3259 LogRel(("Import settings with version \"%s\"\n", m->strSettingsVersionFull.c_str()));
3260
3261 m->sv = parseVersion(m->strSettingsVersionFull, &elmMachine);
3262
3263 // remember the settings version we read in case it gets upgraded later,
3264 // so we know when to make backups
3265 m->svRead = m->sv;
3266
3267 readMachine(elmMachine);
3268}
3269
3270/**
3271 * Comparison operator. This gets called from Machine::saveSettings to figure out
3272 * whether machine settings have really changed and thus need to be written out to disk.
3273 *
3274 * Even though this is called operator==, this does NOT compare all fields; the "equals"
3275 * should be understood as "has the same machine config as". The following fields are
3276 * NOT compared:
3277 * -- settings versions and file names inherited from ConfigFileBase;
3278 * -- fCurrentStateModified because that is considered separately in Machine::saveSettings!!
3279 *
3280 * The "deep" comparisons marked below will invoke the operator== functions of the
3281 * structs defined in this file, which may in turn go into comparing lists of
3282 * other structures. As a result, invoking this can be expensive, but it's
3283 * less expensive than writing out XML to disk.
3284 */
3285bool MachineConfigFile::operator==(const MachineConfigFile &c) const
3286{
3287 return (this == &c)
3288 || ( uuid == c.uuid
3289 && machineUserData == c.machineUserData
3290 && strStateFile == c.strStateFile
3291 && uuidCurrentSnapshot == c.uuidCurrentSnapshot
3292 // skip fCurrentStateModified!
3293 && RTTimeSpecIsEqual(&timeLastStateChange, &c.timeLastStateChange)
3294 && fAborted == c.fAborted
3295 && hardwareMachine == c.hardwareMachine // this one's deep
3296 && mediaRegistry == c.mediaRegistry // this one's deep
3297 // skip mapExtraDataItems! there is no old state available as it's always forced
3298 && llFirstSnapshot == c.llFirstSnapshot); // this one's deep
3299}
3300
3301/**
3302 * Called from MachineConfigFile::readHardware() to read cpu information.
3303 * @param elmCpu
3304 * @param ll
3305 */
3306void MachineConfigFile::readCpuTree(const xml::ElementNode &elmCpu,
3307 CpuList &ll)
3308{
3309 xml::NodesLoop nl1(elmCpu, "Cpu");
3310 const xml::ElementNode *pelmCpu;
3311 while ((pelmCpu = nl1.forAllNodes()))
3312 {
3313 Cpu cpu;
3314
3315 if (!pelmCpu->getAttributeValue("id", cpu.ulId))
3316 throw ConfigFileError(this, pelmCpu, N_("Required Cpu/@id attribute is missing"));
3317
3318 ll.push_back(cpu);
3319 }
3320}
3321
3322/**
3323 * Called from MachineConfigFile::readHardware() to cpuid information.
3324 * @param elmCpuid
3325 * @param ll
3326 */
3327void MachineConfigFile::readCpuIdTree(const xml::ElementNode &elmCpuid,
3328 CpuIdLeafsList &ll)
3329{
3330 xml::NodesLoop nl1(elmCpuid, "CpuIdLeaf");
3331 const xml::ElementNode *pelmCpuIdLeaf;
3332 while ((pelmCpuIdLeaf = nl1.forAllNodes()))
3333 {
3334 CpuIdLeaf leaf;
3335
3336 if (!pelmCpuIdLeaf->getAttributeValue("id", leaf.ulId))
3337 throw ConfigFileError(this, pelmCpuIdLeaf, N_("Required CpuId/@id attribute is missing"));
3338
3339 pelmCpuIdLeaf->getAttributeValue("eax", leaf.ulEax);
3340 pelmCpuIdLeaf->getAttributeValue("ebx", leaf.ulEbx);
3341 pelmCpuIdLeaf->getAttributeValue("ecx", leaf.ulEcx);
3342 pelmCpuIdLeaf->getAttributeValue("edx", leaf.ulEdx);
3343
3344 ll.push_back(leaf);
3345 }
3346}
3347
3348/**
3349 * Called from MachineConfigFile::readHardware() to network information.
3350 * @param elmNetwork
3351 * @param ll
3352 */
3353void MachineConfigFile::readNetworkAdapters(const xml::ElementNode &elmNetwork,
3354 NetworkAdaptersList &ll)
3355{
3356 xml::NodesLoop nl1(elmNetwork, "Adapter");
3357 const xml::ElementNode *pelmAdapter;
3358 while ((pelmAdapter = nl1.forAllNodes()))
3359 {
3360 NetworkAdapter nic;
3361
3362 if (m->sv >= SettingsVersion_v1_16)
3363 {
3364 /* Starting with VirtualBox 5.1 the default is cable connected and
3365 * PCnet-FAST III. Needs to match NetworkAdapter.areDefaultSettings(). */
3366 nic.fCableConnected = true;
3367 nic.type = NetworkAdapterType_Am79C973;
3368 }
3369
3370 if (!pelmAdapter->getAttributeValue("slot", nic.ulSlot))
3371 throw ConfigFileError(this, pelmAdapter, N_("Required Adapter/@slot attribute is missing"));
3372
3373 Utf8Str strTemp;
3374 if (pelmAdapter->getAttributeValue("type", strTemp))
3375 {
3376 if (strTemp == "Am79C970A")
3377 nic.type = NetworkAdapterType_Am79C970A;
3378 else if (strTemp == "Am79C973")
3379 nic.type = NetworkAdapterType_Am79C973;
3380 else if (strTemp == "82540EM")
3381 nic.type = NetworkAdapterType_I82540EM;
3382 else if (strTemp == "82543GC")
3383 nic.type = NetworkAdapterType_I82543GC;
3384 else if (strTemp == "82545EM")
3385 nic.type = NetworkAdapterType_I82545EM;
3386 else if (strTemp == "virtio")
3387 nic.type = NetworkAdapterType_Virtio;
3388 else
3389 throw ConfigFileError(this, pelmAdapter, N_("Invalid value '%s' in Adapter/@type attribute"), strTemp.c_str());
3390 }
3391
3392 pelmAdapter->getAttributeValue("enabled", nic.fEnabled);
3393 pelmAdapter->getAttributeValue("MACAddress", nic.strMACAddress);
3394 pelmAdapter->getAttributeValue("cable", nic.fCableConnected);
3395 pelmAdapter->getAttributeValue("speed", nic.ulLineSpeed);
3396
3397 if (pelmAdapter->getAttributeValue("promiscuousModePolicy", strTemp))
3398 {
3399 if (strTemp == "Deny")
3400 nic.enmPromiscModePolicy = NetworkAdapterPromiscModePolicy_Deny;
3401 else if (strTemp == "AllowNetwork")
3402 nic.enmPromiscModePolicy = NetworkAdapterPromiscModePolicy_AllowNetwork;
3403 else if (strTemp == "AllowAll")
3404 nic.enmPromiscModePolicy = NetworkAdapterPromiscModePolicy_AllowAll;
3405 else
3406 throw ConfigFileError(this, pelmAdapter,
3407 N_("Invalid value '%s' in Adapter/@promiscuousModePolicy attribute"), strTemp.c_str());
3408 }
3409
3410 pelmAdapter->getAttributeValue("trace", nic.fTraceEnabled);
3411 pelmAdapter->getAttributeValue("tracefile", nic.strTraceFile);
3412 pelmAdapter->getAttributeValue("bootPriority", nic.ulBootPriority);
3413 pelmAdapter->getAttributeValue("bandwidthGroup", nic.strBandwidthGroup);
3414
3415 xml::ElementNodesList llNetworkModes;
3416 pelmAdapter->getChildElements(llNetworkModes);
3417 xml::ElementNodesList::iterator it;
3418 /* We should have only active mode descriptor and disabled modes set */
3419 if (llNetworkModes.size() > 2)
3420 {
3421 throw ConfigFileError(this, pelmAdapter, N_("Invalid number of modes ('%d') attached to Adapter attribute"), llNetworkModes.size());
3422 }
3423 for (it = llNetworkModes.begin(); it != llNetworkModes.end(); ++it)
3424 {
3425 const xml::ElementNode *pelmNode = *it;
3426 if (pelmNode->nameEquals("DisabledModes"))
3427 {
3428 xml::ElementNodesList llDisabledNetworkModes;
3429 xml::ElementNodesList::iterator itDisabled;
3430 pelmNode->getChildElements(llDisabledNetworkModes);
3431 /* run over disabled list and load settings */
3432 for (itDisabled = llDisabledNetworkModes.begin();
3433 itDisabled != llDisabledNetworkModes.end(); ++itDisabled)
3434 {
3435 const xml::ElementNode *pelmDisabledNode = *itDisabled;
3436 readAttachedNetworkMode(*pelmDisabledNode, false, nic);
3437 }
3438 }
3439 else
3440 readAttachedNetworkMode(*pelmNode, true, nic);
3441 }
3442 // else: default is NetworkAttachmentType_Null
3443
3444 ll.push_back(nic);
3445 }
3446}
3447
3448void MachineConfigFile::readAttachedNetworkMode(const xml::ElementNode &elmMode, bool fEnabled, NetworkAdapter &nic)
3449{
3450 NetworkAttachmentType_T enmAttachmentType = NetworkAttachmentType_Null;
3451
3452 if (elmMode.nameEquals("NAT"))
3453 {
3454 enmAttachmentType = NetworkAttachmentType_NAT;
3455
3456 elmMode.getAttributeValue("network", nic.nat.strNetwork);
3457 elmMode.getAttributeValue("hostip", nic.nat.strBindIP);
3458 elmMode.getAttributeValue("mtu", nic.nat.u32Mtu);
3459 elmMode.getAttributeValue("sockrcv", nic.nat.u32SockRcv);
3460 elmMode.getAttributeValue("socksnd", nic.nat.u32SockSnd);
3461 elmMode.getAttributeValue("tcprcv", nic.nat.u32TcpRcv);
3462 elmMode.getAttributeValue("tcpsnd", nic.nat.u32TcpSnd);
3463 const xml::ElementNode *pelmDNS;
3464 if ((pelmDNS = elmMode.findChildElement("DNS")))
3465 {
3466 pelmDNS->getAttributeValue("pass-domain", nic.nat.fDNSPassDomain);
3467 pelmDNS->getAttributeValue("use-proxy", nic.nat.fDNSProxy);
3468 pelmDNS->getAttributeValue("use-host-resolver", nic.nat.fDNSUseHostResolver);
3469 }
3470 const xml::ElementNode *pelmAlias;
3471 if ((pelmAlias = elmMode.findChildElement("Alias")))
3472 {
3473 pelmAlias->getAttributeValue("logging", nic.nat.fAliasLog);
3474 pelmAlias->getAttributeValue("proxy-only", nic.nat.fAliasProxyOnly);
3475 pelmAlias->getAttributeValue("use-same-ports", nic.nat.fAliasUseSamePorts);
3476 }
3477 const xml::ElementNode *pelmTFTP;
3478 if ((pelmTFTP = elmMode.findChildElement("TFTP")))
3479 {
3480 pelmTFTP->getAttributeValue("prefix", nic.nat.strTFTPPrefix);
3481 pelmTFTP->getAttributeValue("boot-file", nic.nat.strTFTPBootFile);
3482 pelmTFTP->getAttributeValue("next-server", nic.nat.strTFTPNextServer);
3483 }
3484
3485 readNATForwardRulesMap(elmMode, nic.nat.mapRules);
3486 }
3487 else if ( elmMode.nameEquals("HostInterface")
3488 || elmMode.nameEquals("BridgedInterface"))
3489 {
3490 enmAttachmentType = NetworkAttachmentType_Bridged;
3491
3492 // optional network name, cannot be required or we have trouble with
3493 // settings which are saved before configuring the network name
3494 elmMode.getAttributeValue("name", nic.strBridgedName);
3495 }
3496 else if (elmMode.nameEquals("InternalNetwork"))
3497 {
3498 enmAttachmentType = NetworkAttachmentType_Internal;
3499
3500 // optional network name, cannot be required or we have trouble with
3501 // settings which are saved before configuring the network name
3502 elmMode.getAttributeValue("name", nic.strInternalNetworkName);
3503 }
3504 else if (elmMode.nameEquals("HostOnlyInterface"))
3505 {
3506 enmAttachmentType = NetworkAttachmentType_HostOnly;
3507
3508 // optional network name, cannot be required or we have trouble with
3509 // settings which are saved before configuring the network name
3510 elmMode.getAttributeValue("name", nic.strHostOnlyName);
3511 }
3512 else if (elmMode.nameEquals("GenericInterface"))
3513 {
3514 enmAttachmentType = NetworkAttachmentType_Generic;
3515
3516 elmMode.getAttributeValue("driver", nic.strGenericDriver); // optional network attachment driver
3517
3518 // get all properties
3519 xml::NodesLoop nl(elmMode);
3520 const xml::ElementNode *pelmModeChild;
3521 while ((pelmModeChild = nl.forAllNodes()))
3522 {
3523 if (pelmModeChild->nameEquals("Property"))
3524 {
3525 Utf8Str strPropName, strPropValue;
3526 if ( pelmModeChild->getAttributeValue("name", strPropName)
3527 && pelmModeChild->getAttributeValue("value", strPropValue) )
3528 nic.genericProperties[strPropName] = strPropValue;
3529 else
3530 throw ConfigFileError(this, pelmModeChild, N_("Required GenericInterface/Property/@name or @value attribute is missing"));
3531 }
3532 }
3533 }
3534 else if (elmMode.nameEquals("NATNetwork"))
3535 {
3536 enmAttachmentType = NetworkAttachmentType_NATNetwork;
3537
3538 // optional network name, cannot be required or we have trouble with
3539 // settings which are saved before configuring the network name
3540 elmMode.getAttributeValue("name", nic.strNATNetworkName);
3541 }
3542 else if (elmMode.nameEquals("VDE"))
3543 {
3544 // inofficial hack (VDE networking was never part of the official
3545 // settings, so it's not mentioned in VirtualBox-settings.xsd)
3546 enmAttachmentType = NetworkAttachmentType_Generic;
3547
3548 com::Utf8Str strVDEName;
3549 elmMode.getAttributeValue("network", strVDEName); // optional network name
3550 nic.strGenericDriver = "VDE";
3551 nic.genericProperties["network"] = strVDEName;
3552 }
3553
3554 if (fEnabled && enmAttachmentType != NetworkAttachmentType_Null)
3555 nic.mode = enmAttachmentType;
3556}
3557
3558/**
3559 * Called from MachineConfigFile::readHardware() to read serial port information.
3560 * @param elmUART
3561 * @param ll
3562 */
3563void MachineConfigFile::readSerialPorts(const xml::ElementNode &elmUART,
3564 SerialPortsList &ll)
3565{
3566 xml::NodesLoop nl1(elmUART, "Port");
3567 const xml::ElementNode *pelmPort;
3568 while ((pelmPort = nl1.forAllNodes()))
3569 {
3570 SerialPort port;
3571 if (!pelmPort->getAttributeValue("slot", port.ulSlot))
3572 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@slot attribute is missing"));
3573
3574 // slot must be unique
3575 for (SerialPortsList::const_iterator it = ll.begin();
3576 it != ll.end();
3577 ++it)
3578 if ((*it).ulSlot == port.ulSlot)
3579 throw ConfigFileError(this, pelmPort, N_("Invalid value %RU32 in UART/Port/@slot attribute: value is not unique"), port.ulSlot);
3580
3581 if (!pelmPort->getAttributeValue("enabled", port.fEnabled))
3582 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@enabled attribute is missing"));
3583 if (!pelmPort->getAttributeValue("IOBase", port.ulIOBase))
3584 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@IOBase attribute is missing"));
3585 if (!pelmPort->getAttributeValue("IRQ", port.ulIRQ))
3586 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@IRQ attribute is missing"));
3587
3588 Utf8Str strPortMode;
3589 if (!pelmPort->getAttributeValue("hostMode", strPortMode))
3590 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@hostMode attribute is missing"));
3591 if (strPortMode == "RawFile")
3592 port.portMode = PortMode_RawFile;
3593 else if (strPortMode == "HostPipe")
3594 port.portMode = PortMode_HostPipe;
3595 else if (strPortMode == "HostDevice")
3596 port.portMode = PortMode_HostDevice;
3597 else if (strPortMode == "Disconnected")
3598 port.portMode = PortMode_Disconnected;
3599 else if (strPortMode == "TCP")
3600 port.portMode = PortMode_TCP;
3601 else
3602 throw ConfigFileError(this, pelmPort, N_("Invalid value '%s' in UART/Port/@hostMode attribute"), strPortMode.c_str());
3603
3604 pelmPort->getAttributeValue("path", port.strPath);
3605 pelmPort->getAttributeValue("server", port.fServer);
3606
3607 ll.push_back(port);
3608 }
3609}
3610
3611/**
3612 * Called from MachineConfigFile::readHardware() to read parallel port information.
3613 * @param elmLPT
3614 * @param ll
3615 */
3616void MachineConfigFile::readParallelPorts(const xml::ElementNode &elmLPT,
3617 ParallelPortsList &ll)
3618{
3619 xml::NodesLoop nl1(elmLPT, "Port");
3620 const xml::ElementNode *pelmPort;
3621 while ((pelmPort = nl1.forAllNodes()))
3622 {
3623 ParallelPort port;
3624 if (!pelmPort->getAttributeValue("slot", port.ulSlot))
3625 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@slot attribute is missing"));
3626
3627 // slot must be unique
3628 for (ParallelPortsList::const_iterator it = ll.begin();
3629 it != ll.end();
3630 ++it)
3631 if ((*it).ulSlot == port.ulSlot)
3632 throw ConfigFileError(this, pelmPort, N_("Invalid value %RU32 in LPT/Port/@slot attribute: value is not unique"), port.ulSlot);
3633
3634 if (!pelmPort->getAttributeValue("enabled", port.fEnabled))
3635 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@enabled attribute is missing"));
3636 if (!pelmPort->getAttributeValue("IOBase", port.ulIOBase))
3637 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@IOBase attribute is missing"));
3638 if (!pelmPort->getAttributeValue("IRQ", port.ulIRQ))
3639 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@IRQ attribute is missing"));
3640
3641 pelmPort->getAttributeValue("path", port.strPath);
3642
3643 ll.push_back(port);
3644 }
3645}
3646
3647/**
3648 * Called from MachineConfigFile::readHardware() to read audio adapter information
3649 * and maybe fix driver information depending on the current host hardware.
3650 *
3651 * @param elmAudioAdapter "AudioAdapter" XML element.
3652 * @param aa
3653 */
3654void MachineConfigFile::readAudioAdapter(const xml::ElementNode &elmAudioAdapter,
3655 AudioAdapter &aa)
3656{
3657 if (m->sv >= SettingsVersion_v1_15)
3658 {
3659 // get all properties
3660 xml::NodesLoop nl1(elmAudioAdapter, "Property");
3661 const xml::ElementNode *pelmModeChild;
3662 while ((pelmModeChild = nl1.forAllNodes()))
3663 {
3664 Utf8Str strPropName, strPropValue;
3665 if ( pelmModeChild->getAttributeValue("name", strPropName)
3666 && pelmModeChild->getAttributeValue("value", strPropValue) )
3667 aa.properties[strPropName] = strPropValue;
3668 else
3669 throw ConfigFileError(this, pelmModeChild, N_("Required AudioAdapter/Property/@name or @value attribute "
3670 "is missing"));
3671 }
3672 }
3673
3674 elmAudioAdapter.getAttributeValue("enabled", aa.fEnabled);
3675
3676 Utf8Str strTemp;
3677 if (elmAudioAdapter.getAttributeValue("controller", strTemp))
3678 {
3679 if (strTemp == "SB16")
3680 aa.controllerType = AudioControllerType_SB16;
3681 else if (strTemp == "AC97")
3682 aa.controllerType = AudioControllerType_AC97;
3683 else if (strTemp == "HDA")
3684 aa.controllerType = AudioControllerType_HDA;
3685 else
3686 throw ConfigFileError(this, &elmAudioAdapter, N_("Invalid value '%s' in AudioAdapter/@controller attribute"), strTemp.c_str());
3687 }
3688
3689 if (elmAudioAdapter.getAttributeValue("codec", strTemp))
3690 {
3691 if (strTemp == "SB16")
3692 aa.codecType = AudioCodecType_SB16;
3693 else if (strTemp == "STAC9700")
3694 aa.codecType = AudioCodecType_STAC9700;
3695 else if (strTemp == "AD1980")
3696 aa.codecType = AudioCodecType_AD1980;
3697 else if (strTemp == "STAC9221")
3698 aa.codecType = AudioCodecType_STAC9221;
3699 else
3700 throw ConfigFileError(this, &elmAudioAdapter, N_("Invalid value '%s' in AudioAdapter/@codec attribute"), strTemp.c_str());
3701 }
3702 else
3703 {
3704 /* No codec attribute provided; use defaults. */
3705 switch (aa.controllerType)
3706 {
3707 case AudioControllerType_AC97:
3708 aa.codecType = AudioCodecType_STAC9700;
3709 break;
3710 case AudioControllerType_SB16:
3711 aa.codecType = AudioCodecType_SB16;
3712 break;
3713 case AudioControllerType_HDA:
3714 aa.codecType = AudioCodecType_STAC9221;
3715 break;
3716 default:
3717 Assert(false); /* We just checked the controller type above. */
3718 }
3719 }
3720
3721 if (elmAudioAdapter.getAttributeValue("driver", strTemp))
3722 {
3723 // settings before 1.3 used lower case so make sure this is case-insensitive
3724 strTemp.toUpper();
3725 if (strTemp == "NULL")
3726 aa.driverType = AudioDriverType_Null;
3727 else if (strTemp == "WINMM")
3728 aa.driverType = AudioDriverType_WinMM;
3729 else if ( (strTemp == "DIRECTSOUND") || (strTemp == "DSOUND") )
3730 aa.driverType = AudioDriverType_DirectSound;
3731 else if (strTemp == "SOLAUDIO") /* Deprecated -- Solaris will use OSS by default now. */
3732 aa.driverType = AudioDriverType_SolAudio;
3733 else if (strTemp == "ALSA")
3734 aa.driverType = AudioDriverType_ALSA;
3735 else if (strTemp == "PULSE")
3736 aa.driverType = AudioDriverType_Pulse;
3737 else if (strTemp == "OSS")
3738 aa.driverType = AudioDriverType_OSS;
3739 else if (strTemp == "COREAUDIO")
3740 aa.driverType = AudioDriverType_CoreAudio;
3741 else if (strTemp == "MMPM")
3742 aa.driverType = AudioDriverType_MMPM;
3743 else
3744 throw ConfigFileError(this, &elmAudioAdapter, N_("Invalid value '%s' in AudioAdapter/@driver attribute"), strTemp.c_str());
3745
3746 // now check if this is actually supported on the current host platform;
3747 // people might be opening a file created on a Windows host, and that
3748 // VM should still start on a Linux host
3749 if (!isAudioDriverAllowedOnThisHost(aa.driverType))
3750 aa.driverType = getHostDefaultAudioDriver();
3751 }
3752}
3753
3754/**
3755 * Called from MachineConfigFile::readHardware() to read guest property information.
3756 * @param elmGuestProperties
3757 * @param hw
3758 */
3759void MachineConfigFile::readGuestProperties(const xml::ElementNode &elmGuestProperties,
3760 Hardware &hw)
3761{
3762 xml::NodesLoop nl1(elmGuestProperties, "GuestProperty");
3763 const xml::ElementNode *pelmProp;
3764 while ((pelmProp = nl1.forAllNodes()))
3765 {
3766 GuestProperty prop;
3767 pelmProp->getAttributeValue("name", prop.strName);
3768 pelmProp->getAttributeValue("value", prop.strValue);
3769
3770 pelmProp->getAttributeValue("timestamp", prop.timestamp);
3771 pelmProp->getAttributeValue("flags", prop.strFlags);
3772 hw.llGuestProperties.push_back(prop);
3773 }
3774}
3775
3776/**
3777 * Helper function to read attributes that are common to \<SATAController\> (pre-1.7)
3778 * and \<StorageController\>.
3779 * @param elmStorageController
3780 * @param sctl
3781 */
3782void MachineConfigFile::readStorageControllerAttributes(const xml::ElementNode &elmStorageController,
3783 StorageController &sctl)
3784{
3785 elmStorageController.getAttributeValue("PortCount", sctl.ulPortCount);
3786 elmStorageController.getAttributeValue("useHostIOCache", sctl.fUseHostIOCache);
3787}
3788
3789/**
3790 * Reads in a \<Hardware\> block and stores it in the given structure. Used
3791 * both directly from readMachine and from readSnapshot, since snapshots
3792 * have their own hardware sections.
3793 *
3794 * For legacy pre-1.7 settings we also need a storage structure because
3795 * the IDE and SATA controllers used to be defined under \<Hardware\>.
3796 *
3797 * @param elmHardware
3798 * @param hw
3799 */
3800void MachineConfigFile::readHardware(const xml::ElementNode &elmHardware,
3801 Hardware &hw)
3802{
3803 if (m->sv >= SettingsVersion_v1_16)
3804 {
3805 /* Starting with VirtualBox 5.1 the default is Default, before it was
3806 * Legacy. This needs to matched by areParavirtDefaultSettings(). */
3807 hw.paravirtProvider = ParavirtProvider_Default;
3808 /* The new default is disabled, before it was enabled by default. */
3809 hw.vrdeSettings.fEnabled = false;
3810 /* The new default is disabled, before it was enabled by default. */
3811 hw.audioAdapter.fEnabled = false;
3812 }
3813
3814 if (!elmHardware.getAttributeValue("version", hw.strVersion))
3815 {
3816 /* KLUDGE ALERT! For a while during the 3.1 development this was not
3817 written because it was thought to have a default value of "2". For
3818 sv <= 1.3 it defaults to "1" because the attribute didn't exist,
3819 while for 1.4+ it is sort of mandatory. Now, the buggy XML writer
3820 code only wrote 1.7 and later. So, if it's a 1.7+ XML file and it's
3821 missing the hardware version, then it probably should be "2" instead
3822 of "1". */
3823 if (m->sv < SettingsVersion_v1_7)
3824 hw.strVersion = "1";
3825 else
3826 hw.strVersion = "2";
3827 }
3828 Utf8Str strUUID;
3829 if (elmHardware.getAttributeValue("uuid", strUUID))
3830 parseUUID(hw.uuid, strUUID, &elmHardware);
3831
3832 xml::NodesLoop nl1(elmHardware);
3833 const xml::ElementNode *pelmHwChild;
3834 while ((pelmHwChild = nl1.forAllNodes()))
3835 {
3836 if (pelmHwChild->nameEquals("CPU"))
3837 {
3838 if (!pelmHwChild->getAttributeValue("count", hw.cCPUs))
3839 {
3840 // pre-1.5 variant; not sure if this actually exists in the wild anywhere
3841 const xml::ElementNode *pelmCPUChild;
3842 if ((pelmCPUChild = pelmHwChild->findChildElement("CPUCount")))
3843 pelmCPUChild->getAttributeValue("count", hw.cCPUs);
3844 }
3845
3846 pelmHwChild->getAttributeValue("hotplug", hw.fCpuHotPlug);
3847 pelmHwChild->getAttributeValue("executionCap", hw.ulCpuExecutionCap);
3848
3849 const xml::ElementNode *pelmCPUChild;
3850 if (hw.fCpuHotPlug)
3851 {
3852 if ((pelmCPUChild = pelmHwChild->findChildElement("CpuTree")))
3853 readCpuTree(*pelmCPUChild, hw.llCpus);
3854 }
3855
3856 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtEx")))
3857 {
3858 pelmCPUChild->getAttributeValue("enabled", hw.fHardwareVirt);
3859 }
3860 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExNestedPaging")))
3861 pelmCPUChild->getAttributeValue("enabled", hw.fNestedPaging);
3862 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExLargePages")))
3863 pelmCPUChild->getAttributeValue("enabled", hw.fLargePages);
3864 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExVPID")))
3865 pelmCPUChild->getAttributeValue("enabled", hw.fVPID);
3866 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExUX")))
3867 pelmCPUChild->getAttributeValue("enabled", hw.fUnrestrictedExecution);
3868 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtForce")))
3869 pelmCPUChild->getAttributeValue("enabled", hw.fHardwareVirtForce);
3870
3871 if (!(pelmCPUChild = pelmHwChild->findChildElement("PAE")))
3872 {
3873 /* The default for pre 3.1 was false, so we must respect that. */
3874 if (m->sv < SettingsVersion_v1_9)
3875 hw.fPAE = false;
3876 }
3877 else
3878 pelmCPUChild->getAttributeValue("enabled", hw.fPAE);
3879
3880 bool fLongMode;
3881 if ( (pelmCPUChild = pelmHwChild->findChildElement("LongMode"))
3882 && pelmCPUChild->getAttributeValue("enabled", fLongMode) )
3883 hw.enmLongMode = fLongMode ? Hardware::LongMode_Enabled : Hardware::LongMode_Disabled;
3884 else
3885 hw.enmLongMode = Hardware::LongMode_Legacy;
3886
3887 if ((pelmCPUChild = pelmHwChild->findChildElement("SyntheticCpu")))
3888 {
3889 bool fSyntheticCpu = false;
3890 pelmCPUChild->getAttributeValue("enabled", fSyntheticCpu);
3891 hw.uCpuIdPortabilityLevel = fSyntheticCpu ? 1 : 0;
3892 }
3893 pelmHwChild->getAttributeValue("CpuIdPortabilityLevel", hw.uCpuIdPortabilityLevel);
3894 pelmHwChild->getAttributeValue("CpuProfile", hw.strCpuProfile);
3895
3896 if ((pelmCPUChild = pelmHwChild->findChildElement("TripleFaultReset")))
3897 pelmCPUChild->getAttributeValue("enabled", hw.fTripleFaultReset);
3898
3899 if ((pelmCPUChild = pelmHwChild->findChildElement("APIC")))
3900 pelmCPUChild->getAttributeValue("enabled", hw.fAPIC);
3901 if ((pelmCPUChild = pelmHwChild->findChildElement("X2APIC")))
3902 pelmCPUChild->getAttributeValue("enabled", hw.fX2APIC);
3903 if (hw.fX2APIC)
3904 hw.fAPIC = true;
3905
3906 if ((pelmCPUChild = pelmHwChild->findChildElement("CpuIdTree")))
3907 readCpuIdTree(*pelmCPUChild, hw.llCpuIdLeafs);
3908 }
3909 else if (pelmHwChild->nameEquals("Memory"))
3910 {
3911 pelmHwChild->getAttributeValue("RAMSize", hw.ulMemorySizeMB);
3912 pelmHwChild->getAttributeValue("PageFusion", hw.fPageFusionEnabled);
3913 }
3914 else if (pelmHwChild->nameEquals("Firmware"))
3915 {
3916 Utf8Str strFirmwareType;
3917 if (pelmHwChild->getAttributeValue("type", strFirmwareType))
3918 {
3919 if ( (strFirmwareType == "BIOS")
3920 || (strFirmwareType == "1") // some trunk builds used the number here
3921 )
3922 hw.firmwareType = FirmwareType_BIOS;
3923 else if ( (strFirmwareType == "EFI")
3924 || (strFirmwareType == "2") // some trunk builds used the number here
3925 )
3926 hw.firmwareType = FirmwareType_EFI;
3927 else if ( strFirmwareType == "EFI32")
3928 hw.firmwareType = FirmwareType_EFI32;
3929 else if ( strFirmwareType == "EFI64")
3930 hw.firmwareType = FirmwareType_EFI64;
3931 else if ( strFirmwareType == "EFIDUAL")
3932 hw.firmwareType = FirmwareType_EFIDUAL;
3933 else
3934 throw ConfigFileError(this,
3935 pelmHwChild,
3936 N_("Invalid value '%s' in Firmware/@type"),
3937 strFirmwareType.c_str());
3938 }
3939 }
3940 else if (pelmHwChild->nameEquals("HID"))
3941 {
3942 Utf8Str strHIDType;
3943 if (pelmHwChild->getAttributeValue("Keyboard", strHIDType))
3944 {
3945 if (strHIDType == "None")
3946 hw.keyboardHIDType = KeyboardHIDType_None;
3947 else if (strHIDType == "USBKeyboard")
3948 hw.keyboardHIDType = KeyboardHIDType_USBKeyboard;
3949 else if (strHIDType == "PS2Keyboard")
3950 hw.keyboardHIDType = KeyboardHIDType_PS2Keyboard;
3951 else if (strHIDType == "ComboKeyboard")
3952 hw.keyboardHIDType = KeyboardHIDType_ComboKeyboard;
3953 else
3954 throw ConfigFileError(this,
3955 pelmHwChild,
3956 N_("Invalid value '%s' in HID/Keyboard/@type"),
3957 strHIDType.c_str());
3958 }
3959 if (pelmHwChild->getAttributeValue("Pointing", strHIDType))
3960 {
3961 if (strHIDType == "None")
3962 hw.pointingHIDType = PointingHIDType_None;
3963 else if (strHIDType == "USBMouse")
3964 hw.pointingHIDType = PointingHIDType_USBMouse;
3965 else if (strHIDType == "USBTablet")
3966 hw.pointingHIDType = PointingHIDType_USBTablet;
3967 else if (strHIDType == "PS2Mouse")
3968 hw.pointingHIDType = PointingHIDType_PS2Mouse;
3969 else if (strHIDType == "ComboMouse")
3970 hw.pointingHIDType = PointingHIDType_ComboMouse;
3971 else if (strHIDType == "USBMultiTouch")
3972 hw.pointingHIDType = PointingHIDType_USBMultiTouch;
3973 else
3974 throw ConfigFileError(this,
3975 pelmHwChild,
3976 N_("Invalid value '%s' in HID/Pointing/@type"),
3977 strHIDType.c_str());
3978 }
3979 }
3980 else if (pelmHwChild->nameEquals("Chipset"))
3981 {
3982 Utf8Str strChipsetType;
3983 if (pelmHwChild->getAttributeValue("type", strChipsetType))
3984 {
3985 if (strChipsetType == "PIIX3")
3986 hw.chipsetType = ChipsetType_PIIX3;
3987 else if (strChipsetType == "ICH9")
3988 hw.chipsetType = ChipsetType_ICH9;
3989 else
3990 throw ConfigFileError(this,
3991 pelmHwChild,
3992 N_("Invalid value '%s' in Chipset/@type"),
3993 strChipsetType.c_str());
3994 }
3995 }
3996 else if (pelmHwChild->nameEquals("Paravirt"))
3997 {
3998 Utf8Str strProvider;
3999 if (pelmHwChild->getAttributeValue("provider", strProvider))
4000 {
4001 if (strProvider == "None")
4002 hw.paravirtProvider = ParavirtProvider_None;
4003 else if (strProvider == "Default")
4004 hw.paravirtProvider = ParavirtProvider_Default;
4005 else if (strProvider == "Legacy")
4006 hw.paravirtProvider = ParavirtProvider_Legacy;
4007 else if (strProvider == "Minimal")
4008 hw.paravirtProvider = ParavirtProvider_Minimal;
4009 else if (strProvider == "HyperV")
4010 hw.paravirtProvider = ParavirtProvider_HyperV;
4011 else if (strProvider == "KVM")
4012 hw.paravirtProvider = ParavirtProvider_KVM;
4013 else
4014 throw ConfigFileError(this,
4015 pelmHwChild,
4016 N_("Invalid value '%s' in Paravirt/@provider attribute"),
4017 strProvider.c_str());
4018 }
4019
4020 pelmHwChild->getAttributeValue("debug", hw.strParavirtDebug);
4021 }
4022 else if (pelmHwChild->nameEquals("HPET"))
4023 {
4024 pelmHwChild->getAttributeValue("enabled", hw.fHPETEnabled);
4025 }
4026 else if (pelmHwChild->nameEquals("Boot"))
4027 {
4028 hw.mapBootOrder.clear();
4029
4030 xml::NodesLoop nl2(*pelmHwChild, "Order");
4031 const xml::ElementNode *pelmOrder;
4032 while ((pelmOrder = nl2.forAllNodes()))
4033 {
4034 uint32_t ulPos;
4035 Utf8Str strDevice;
4036 if (!pelmOrder->getAttributeValue("position", ulPos))
4037 throw ConfigFileError(this, pelmOrder, N_("Required Boot/Order/@position attribute is missing"));
4038
4039 if ( ulPos < 1
4040 || ulPos > SchemaDefs::MaxBootPosition
4041 )
4042 throw ConfigFileError(this,
4043 pelmOrder,
4044 N_("Invalid value '%RU32' in Boot/Order/@position: must be greater than 0 and less than %RU32"),
4045 ulPos,
4046 SchemaDefs::MaxBootPosition + 1);
4047 // XML is 1-based but internal data is 0-based
4048 --ulPos;
4049
4050 if (hw.mapBootOrder.find(ulPos) != hw.mapBootOrder.end())
4051 throw ConfigFileError(this, pelmOrder, N_("Invalid value '%RU32' in Boot/Order/@position: value is not unique"), ulPos);
4052
4053 if (!pelmOrder->getAttributeValue("device", strDevice))
4054 throw ConfigFileError(this, pelmOrder, N_("Required Boot/Order/@device attribute is missing"));
4055
4056 DeviceType_T type;
4057 if (strDevice == "None")
4058 type = DeviceType_Null;
4059 else if (strDevice == "Floppy")
4060 type = DeviceType_Floppy;
4061 else if (strDevice == "DVD")
4062 type = DeviceType_DVD;
4063 else if (strDevice == "HardDisk")
4064 type = DeviceType_HardDisk;
4065 else if (strDevice == "Network")
4066 type = DeviceType_Network;
4067 else
4068 throw ConfigFileError(this, pelmOrder, N_("Invalid value '%s' in Boot/Order/@device attribute"), strDevice.c_str());
4069 hw.mapBootOrder[ulPos] = type;
4070 }
4071 }
4072 else if (pelmHwChild->nameEquals("Display"))
4073 {
4074 Utf8Str strGraphicsControllerType;
4075 if (!pelmHwChild->getAttributeValue("controller", strGraphicsControllerType))
4076 hw.graphicsControllerType = GraphicsControllerType_VBoxVGA;
4077 else
4078 {
4079 strGraphicsControllerType.toUpper();
4080 GraphicsControllerType_T type;
4081 if (strGraphicsControllerType == "VBOXVGA")
4082 type = GraphicsControllerType_VBoxVGA;
4083 else if (strGraphicsControllerType == "VMSVGA")
4084 type = GraphicsControllerType_VMSVGA;
4085 else if (strGraphicsControllerType == "NONE")
4086 type = GraphicsControllerType_Null;
4087 else
4088 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in Display/@controller attribute"), strGraphicsControllerType.c_str());
4089 hw.graphicsControllerType = type;
4090 }
4091 pelmHwChild->getAttributeValue("VRAMSize", hw.ulVRAMSizeMB);
4092 if (!pelmHwChild->getAttributeValue("monitorCount", hw.cMonitors))
4093 pelmHwChild->getAttributeValue("MonitorCount", hw.cMonitors); // pre-v1.5 variant
4094 if (!pelmHwChild->getAttributeValue("accelerate3D", hw.fAccelerate3D))
4095 pelmHwChild->getAttributeValue("Accelerate3D", hw.fAccelerate3D); // pre-v1.5 variant
4096 pelmHwChild->getAttributeValue("accelerate2DVideo", hw.fAccelerate2DVideo);
4097 }
4098 else if (pelmHwChild->nameEquals("VideoCapture"))
4099 {
4100 pelmHwChild->getAttributeValue("enabled", hw.fVideoCaptureEnabled);
4101 pelmHwChild->getAttributeValue("screens", hw.u64VideoCaptureScreens);
4102 pelmHwChild->getAttributeValuePath("file", hw.strVideoCaptureFile);
4103 pelmHwChild->getAttributeValue("horzRes", hw.ulVideoCaptureHorzRes);
4104 pelmHwChild->getAttributeValue("vertRes", hw.ulVideoCaptureVertRes);
4105 pelmHwChild->getAttributeValue("rate", hw.ulVideoCaptureRate);
4106 pelmHwChild->getAttributeValue("fps", hw.ulVideoCaptureFPS);
4107 pelmHwChild->getAttributeValue("maxTime", hw.ulVideoCaptureMaxTime);
4108 pelmHwChild->getAttributeValue("maxSize", hw.ulVideoCaptureMaxSize);
4109 }
4110 else if (pelmHwChild->nameEquals("RemoteDisplay"))
4111 {
4112 pelmHwChild->getAttributeValue("enabled", hw.vrdeSettings.fEnabled);
4113
4114 Utf8Str str;
4115 if (pelmHwChild->getAttributeValue("port", str))
4116 hw.vrdeSettings.mapProperties["TCP/Ports"] = str;
4117 if (pelmHwChild->getAttributeValue("netAddress", str))
4118 hw.vrdeSettings.mapProperties["TCP/Address"] = str;
4119
4120 Utf8Str strAuthType;
4121 if (pelmHwChild->getAttributeValue("authType", strAuthType))
4122 {
4123 // settings before 1.3 used lower case so make sure this is case-insensitive
4124 strAuthType.toUpper();
4125 if (strAuthType == "NULL")
4126 hw.vrdeSettings.authType = AuthType_Null;
4127 else if (strAuthType == "GUEST")
4128 hw.vrdeSettings.authType = AuthType_Guest;
4129 else if (strAuthType == "EXTERNAL")
4130 hw.vrdeSettings.authType = AuthType_External;
4131 else
4132 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in RemoteDisplay/@authType attribute"), strAuthType.c_str());
4133 }
4134
4135 pelmHwChild->getAttributeValue("authLibrary", hw.vrdeSettings.strAuthLibrary);
4136 pelmHwChild->getAttributeValue("authTimeout", hw.vrdeSettings.ulAuthTimeout);
4137 pelmHwChild->getAttributeValue("allowMultiConnection", hw.vrdeSettings.fAllowMultiConnection);
4138 pelmHwChild->getAttributeValue("reuseSingleConnection", hw.vrdeSettings.fReuseSingleConnection);
4139
4140 /* 3.2 and 4.0 betas, 4.0 has this information in VRDEProperties. */
4141 const xml::ElementNode *pelmVideoChannel;
4142 if ((pelmVideoChannel = pelmHwChild->findChildElement("VideoChannel")))
4143 {
4144 bool fVideoChannel = false;
4145 pelmVideoChannel->getAttributeValue("enabled", fVideoChannel);
4146 hw.vrdeSettings.mapProperties["VideoChannel/Enabled"] = fVideoChannel? "true": "false";
4147
4148 uint32_t ulVideoChannelQuality = 75;
4149 pelmVideoChannel->getAttributeValue("quality", ulVideoChannelQuality);
4150 ulVideoChannelQuality = RT_CLAMP(ulVideoChannelQuality, 10, 100);
4151 char *pszBuffer = NULL;
4152 if (RTStrAPrintf(&pszBuffer, "%d", ulVideoChannelQuality) >= 0)
4153 {
4154 hw.vrdeSettings.mapProperties["VideoChannel/Quality"] = pszBuffer;
4155 RTStrFree(pszBuffer);
4156 }
4157 else
4158 hw.vrdeSettings.mapProperties["VideoChannel/Quality"] = "75";
4159 }
4160 pelmHwChild->getAttributeValue("VRDEExtPack", hw.vrdeSettings.strVrdeExtPack);
4161
4162 const xml::ElementNode *pelmProperties = pelmHwChild->findChildElement("VRDEProperties");
4163 if (pelmProperties != NULL)
4164 {
4165 xml::NodesLoop nl(*pelmProperties);
4166 const xml::ElementNode *pelmProperty;
4167 while ((pelmProperty = nl.forAllNodes()))
4168 {
4169 if (pelmProperty->nameEquals("Property"))
4170 {
4171 /* <Property name="TCP/Ports" value="3000-3002"/> */
4172 Utf8Str strName, strValue;
4173 if ( pelmProperty->getAttributeValue("name", strName)
4174 && pelmProperty->getAttributeValue("value", strValue))
4175 hw.vrdeSettings.mapProperties[strName] = strValue;
4176 else
4177 throw ConfigFileError(this, pelmProperty, N_("Required VRDE Property/@name or @value attribute is missing"));
4178 }
4179 }
4180 }
4181 }
4182 else if (pelmHwChild->nameEquals("BIOS"))
4183 {
4184 const xml::ElementNode *pelmBIOSChild;
4185 if ((pelmBIOSChild = pelmHwChild->findChildElement("ACPI")))
4186 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fACPIEnabled);
4187 if ((pelmBIOSChild = pelmHwChild->findChildElement("IOAPIC")))
4188 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fIOAPICEnabled);
4189 if ((pelmBIOSChild = pelmHwChild->findChildElement("APIC")))
4190 {
4191 Utf8Str strAPIC;
4192 if (pelmBIOSChild->getAttributeValue("mode", strAPIC))
4193 {
4194 strAPIC.toUpper();
4195 if (strAPIC == "DISABLED")
4196 hw.biosSettings.apicMode = APICMode_Disabled;
4197 else if (strAPIC == "APIC")
4198 hw.biosSettings.apicMode = APICMode_APIC;
4199 else if (strAPIC == "X2APIC")
4200 hw.biosSettings.apicMode = APICMode_X2APIC;
4201 else
4202 throw ConfigFileError(this, pelmBIOSChild, N_("Invalid value '%s' in APIC/@mode attribute"), strAPIC.c_str());
4203 }
4204 }
4205 if ((pelmBIOSChild = pelmHwChild->findChildElement("Logo")))
4206 {
4207 pelmBIOSChild->getAttributeValue("fadeIn", hw.biosSettings.fLogoFadeIn);
4208 pelmBIOSChild->getAttributeValue("fadeOut", hw.biosSettings.fLogoFadeOut);
4209 pelmBIOSChild->getAttributeValue("displayTime", hw.biosSettings.ulLogoDisplayTime);
4210 pelmBIOSChild->getAttributeValue("imagePath", hw.biosSettings.strLogoImagePath);
4211 }
4212 if ((pelmBIOSChild = pelmHwChild->findChildElement("BootMenu")))
4213 {
4214 Utf8Str strBootMenuMode;
4215 if (pelmBIOSChild->getAttributeValue("mode", strBootMenuMode))
4216 {
4217 // settings before 1.3 used lower case so make sure this is case-insensitive
4218 strBootMenuMode.toUpper();
4219 if (strBootMenuMode == "DISABLED")
4220 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_Disabled;
4221 else if (strBootMenuMode == "MENUONLY")
4222 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_MenuOnly;
4223 else if (strBootMenuMode == "MESSAGEANDMENU")
4224 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_MessageAndMenu;
4225 else
4226 throw ConfigFileError(this, pelmBIOSChild, N_("Invalid value '%s' in BootMenu/@mode attribute"), strBootMenuMode.c_str());
4227 }
4228 }
4229 if ((pelmBIOSChild = pelmHwChild->findChildElement("PXEDebug")))
4230 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fPXEDebugEnabled);
4231 if ((pelmBIOSChild = pelmHwChild->findChildElement("TimeOffset")))
4232 pelmBIOSChild->getAttributeValue("value", hw.biosSettings.llTimeOffset);
4233
4234 // legacy BIOS/IDEController (pre 1.7)
4235 if ( (m->sv < SettingsVersion_v1_7)
4236 && (pelmBIOSChild = pelmHwChild->findChildElement("IDEController"))
4237 )
4238 {
4239 StorageController sctl;
4240 sctl.strName = "IDE Controller";
4241 sctl.storageBus = StorageBus_IDE;
4242
4243 Utf8Str strType;
4244 if (pelmBIOSChild->getAttributeValue("type", strType))
4245 {
4246 if (strType == "PIIX3")
4247 sctl.controllerType = StorageControllerType_PIIX3;
4248 else if (strType == "PIIX4")
4249 sctl.controllerType = StorageControllerType_PIIX4;
4250 else if (strType == "ICH6")
4251 sctl.controllerType = StorageControllerType_ICH6;
4252 else
4253 throw ConfigFileError(this, pelmBIOSChild, N_("Invalid value '%s' for IDEController/@type attribute"), strType.c_str());
4254 }
4255 sctl.ulPortCount = 2;
4256 hw.storage.llStorageControllers.push_back(sctl);
4257 }
4258 }
4259 else if ( (m->sv <= SettingsVersion_v1_14)
4260 && pelmHwChild->nameEquals("USBController"))
4261 {
4262 bool fEnabled = false;
4263
4264 pelmHwChild->getAttributeValue("enabled", fEnabled);
4265 if (fEnabled)
4266 {
4267 /* Create OHCI controller with default name. */
4268 USBController ctrl;
4269
4270 ctrl.strName = "OHCI";
4271 ctrl.enmType = USBControllerType_OHCI;
4272 hw.usbSettings.llUSBControllers.push_back(ctrl);
4273 }
4274
4275 pelmHwChild->getAttributeValue("enabledEhci", fEnabled);
4276 if (fEnabled)
4277 {
4278 /* Create OHCI controller with default name. */
4279 USBController ctrl;
4280
4281 ctrl.strName = "EHCI";
4282 ctrl.enmType = USBControllerType_EHCI;
4283 hw.usbSettings.llUSBControllers.push_back(ctrl);
4284 }
4285
4286 readUSBDeviceFilters(*pelmHwChild,
4287 hw.usbSettings.llDeviceFilters);
4288 }
4289 else if (pelmHwChild->nameEquals("USB"))
4290 {
4291 const xml::ElementNode *pelmUSBChild;
4292
4293 if ((pelmUSBChild = pelmHwChild->findChildElement("Controllers")))
4294 {
4295 xml::NodesLoop nl2(*pelmUSBChild, "Controller");
4296 const xml::ElementNode *pelmCtrl;
4297
4298 while ((pelmCtrl = nl2.forAllNodes()))
4299 {
4300 USBController ctrl;
4301 com::Utf8Str strCtrlType;
4302
4303 pelmCtrl->getAttributeValue("name", ctrl.strName);
4304
4305 if (pelmCtrl->getAttributeValue("type", strCtrlType))
4306 {
4307 if (strCtrlType == "OHCI")
4308 ctrl.enmType = USBControllerType_OHCI;
4309 else if (strCtrlType == "EHCI")
4310 ctrl.enmType = USBControllerType_EHCI;
4311 else if (strCtrlType == "XHCI")
4312 ctrl.enmType = USBControllerType_XHCI;
4313 else
4314 throw ConfigFileError(this, pelmCtrl, N_("Invalid value '%s' for Controller/@type attribute"), strCtrlType.c_str());
4315 }
4316
4317 hw.usbSettings.llUSBControllers.push_back(ctrl);
4318 }
4319 }
4320
4321 if ((pelmUSBChild = pelmHwChild->findChildElement("DeviceFilters")))
4322 readUSBDeviceFilters(*pelmUSBChild, hw.usbSettings.llDeviceFilters);
4323 }
4324 else if ( m->sv < SettingsVersion_v1_7
4325 && pelmHwChild->nameEquals("SATAController"))
4326 {
4327 bool f;
4328 if ( pelmHwChild->getAttributeValue("enabled", f)
4329 && f)
4330 {
4331 StorageController sctl;
4332 sctl.strName = "SATA Controller";
4333 sctl.storageBus = StorageBus_SATA;
4334 sctl.controllerType = StorageControllerType_IntelAhci;
4335
4336 readStorageControllerAttributes(*pelmHwChild, sctl);
4337
4338 hw.storage.llStorageControllers.push_back(sctl);
4339 }
4340 }
4341 else if (pelmHwChild->nameEquals("Network"))
4342 readNetworkAdapters(*pelmHwChild, hw.llNetworkAdapters);
4343 else if (pelmHwChild->nameEquals("RTC"))
4344 {
4345 Utf8Str strLocalOrUTC;
4346 machineUserData.fRTCUseUTC = pelmHwChild->getAttributeValue("localOrUTC", strLocalOrUTC)
4347 && strLocalOrUTC == "UTC";
4348 }
4349 else if ( pelmHwChild->nameEquals("UART")
4350 || pelmHwChild->nameEquals("Uart") // used before 1.3
4351 )
4352 readSerialPorts(*pelmHwChild, hw.llSerialPorts);
4353 else if ( pelmHwChild->nameEquals("LPT")
4354 || pelmHwChild->nameEquals("Lpt") // used before 1.3
4355 )
4356 readParallelPorts(*pelmHwChild, hw.llParallelPorts);
4357 else if (pelmHwChild->nameEquals("AudioAdapter"))
4358 readAudioAdapter(*pelmHwChild, hw.audioAdapter);
4359 else if (pelmHwChild->nameEquals("SharedFolders"))
4360 {
4361 xml::NodesLoop nl2(*pelmHwChild, "SharedFolder");
4362 const xml::ElementNode *pelmFolder;
4363 while ((pelmFolder = nl2.forAllNodes()))
4364 {
4365 SharedFolder sf;
4366 pelmFolder->getAttributeValue("name", sf.strName);
4367 pelmFolder->getAttributeValue("hostPath", sf.strHostPath);
4368 pelmFolder->getAttributeValue("writable", sf.fWritable);
4369 pelmFolder->getAttributeValue("autoMount", sf.fAutoMount);
4370 hw.llSharedFolders.push_back(sf);
4371 }
4372 }
4373 else if (pelmHwChild->nameEquals("Clipboard"))
4374 {
4375 Utf8Str strTemp;
4376 if (pelmHwChild->getAttributeValue("mode", strTemp))
4377 {
4378 if (strTemp == "Disabled")
4379 hw.clipboardMode = ClipboardMode_Disabled;
4380 else if (strTemp == "HostToGuest")
4381 hw.clipboardMode = ClipboardMode_HostToGuest;
4382 else if (strTemp == "GuestToHost")
4383 hw.clipboardMode = ClipboardMode_GuestToHost;
4384 else if (strTemp == "Bidirectional")
4385 hw.clipboardMode = ClipboardMode_Bidirectional;
4386 else
4387 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in Clipboard/@mode attribute"), strTemp.c_str());
4388 }
4389 }
4390 else if (pelmHwChild->nameEquals("DragAndDrop"))
4391 {
4392 Utf8Str strTemp;
4393 if (pelmHwChild->getAttributeValue("mode", strTemp))
4394 {
4395 if (strTemp == "Disabled")
4396 hw.dndMode = DnDMode_Disabled;
4397 else if (strTemp == "HostToGuest")
4398 hw.dndMode = DnDMode_HostToGuest;
4399 else if (strTemp == "GuestToHost")
4400 hw.dndMode = DnDMode_GuestToHost;
4401 else if (strTemp == "Bidirectional")
4402 hw.dndMode = DnDMode_Bidirectional;
4403 else
4404 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in DragAndDrop/@mode attribute"), strTemp.c_str());
4405 }
4406 }
4407 else if (pelmHwChild->nameEquals("Guest"))
4408 {
4409 if (!pelmHwChild->getAttributeValue("memoryBalloonSize", hw.ulMemoryBalloonSize))
4410 pelmHwChild->getAttributeValue("MemoryBalloonSize", hw.ulMemoryBalloonSize); // used before 1.3
4411 }
4412 else if (pelmHwChild->nameEquals("GuestProperties"))
4413 readGuestProperties(*pelmHwChild, hw);
4414 else if (pelmHwChild->nameEquals("IO"))
4415 {
4416 const xml::ElementNode *pelmBwGroups;
4417 const xml::ElementNode *pelmIOChild;
4418
4419 if ((pelmIOChild = pelmHwChild->findChildElement("IoCache")))
4420 {
4421 pelmIOChild->getAttributeValue("enabled", hw.ioSettings.fIOCacheEnabled);
4422 pelmIOChild->getAttributeValue("size", hw.ioSettings.ulIOCacheSize);
4423 }
4424
4425 if ((pelmBwGroups = pelmHwChild->findChildElement("BandwidthGroups")))
4426 {
4427 xml::NodesLoop nl2(*pelmBwGroups, "BandwidthGroup");
4428 const xml::ElementNode *pelmBandwidthGroup;
4429 while ((pelmBandwidthGroup = nl2.forAllNodes()))
4430 {
4431 BandwidthGroup gr;
4432 Utf8Str strTemp;
4433
4434 pelmBandwidthGroup->getAttributeValue("name", gr.strName);
4435
4436 if (pelmBandwidthGroup->getAttributeValue("type", strTemp))
4437 {
4438 if (strTemp == "Disk")
4439 gr.enmType = BandwidthGroupType_Disk;
4440 else if (strTemp == "Network")
4441 gr.enmType = BandwidthGroupType_Network;
4442 else
4443 throw ConfigFileError(this, pelmBandwidthGroup, N_("Invalid value '%s' in BandwidthGroup/@type attribute"), strTemp.c_str());
4444 }
4445 else
4446 throw ConfigFileError(this, pelmBandwidthGroup, N_("Missing BandwidthGroup/@type attribute"));
4447
4448 if (!pelmBandwidthGroup->getAttributeValue("maxBytesPerSec", gr.cMaxBytesPerSec))
4449 {
4450 pelmBandwidthGroup->getAttributeValue("maxMbPerSec", gr.cMaxBytesPerSec);
4451 gr.cMaxBytesPerSec *= _1M;
4452 }
4453 hw.ioSettings.llBandwidthGroups.push_back(gr);
4454 }
4455 }
4456 }
4457 else if (pelmHwChild->nameEquals("HostPci"))
4458 {
4459 const xml::ElementNode *pelmDevices;
4460
4461 if ((pelmDevices = pelmHwChild->findChildElement("Devices")))
4462 {
4463 xml::NodesLoop nl2(*pelmDevices, "Device");
4464 const xml::ElementNode *pelmDevice;
4465 while ((pelmDevice = nl2.forAllNodes()))
4466 {
4467 HostPCIDeviceAttachment hpda;
4468
4469 if (!pelmDevice->getAttributeValue("host", hpda.uHostAddress))
4470 throw ConfigFileError(this, pelmDevice, N_("Missing Device/@host attribute"));
4471
4472 if (!pelmDevice->getAttributeValue("guest", hpda.uGuestAddress))
4473 throw ConfigFileError(this, pelmDevice, N_("Missing Device/@guest attribute"));
4474
4475 /* name is optional */
4476 pelmDevice->getAttributeValue("name", hpda.strDeviceName);
4477
4478 hw.pciAttachments.push_back(hpda);
4479 }
4480 }
4481 }
4482 else if (pelmHwChild->nameEquals("EmulatedUSB"))
4483 {
4484 const xml::ElementNode *pelmCardReader;
4485
4486 if ((pelmCardReader = pelmHwChild->findChildElement("CardReader")))
4487 {
4488 pelmCardReader->getAttributeValue("enabled", hw.fEmulatedUSBCardReader);
4489 }
4490 }
4491 else if (pelmHwChild->nameEquals("Frontend"))
4492 {
4493 const xml::ElementNode *pelmDefault;
4494
4495 if ((pelmDefault = pelmHwChild->findChildElement("Default")))
4496 {
4497 pelmDefault->getAttributeValue("type", hw.strDefaultFrontend);
4498 }
4499 }
4500 else if (pelmHwChild->nameEquals("StorageControllers"))
4501 readStorageControllers(*pelmHwChild, hw.storage);
4502 }
4503
4504 if (hw.ulMemorySizeMB == (uint32_t)-1)
4505 throw ConfigFileError(this, &elmHardware, N_("Required Memory/@RAMSize element/attribute is missing"));
4506}
4507
4508/**
4509 * This gets called instead of readStorageControllers() for legacy pre-1.7 settings
4510 * files which have a \<HardDiskAttachments\> node and storage controller settings
4511 * hidden in the \<Hardware\> settings. We set the StorageControllers fields just the
4512 * same, just from different sources.
4513 * @param elmHardDiskAttachments \<HardDiskAttachments\> XML node.
4514 * @param strg
4515 */
4516void MachineConfigFile::readHardDiskAttachments_pre1_7(const xml::ElementNode &elmHardDiskAttachments,
4517 Storage &strg)
4518{
4519 StorageController *pIDEController = NULL;
4520 StorageController *pSATAController = NULL;
4521
4522 for (StorageControllersList::iterator it = strg.llStorageControllers.begin();
4523 it != strg.llStorageControllers.end();
4524 ++it)
4525 {
4526 StorageController &s = *it;
4527 if (s.storageBus == StorageBus_IDE)
4528 pIDEController = &s;
4529 else if (s.storageBus == StorageBus_SATA)
4530 pSATAController = &s;
4531 }
4532
4533 xml::NodesLoop nl1(elmHardDiskAttachments, "HardDiskAttachment");
4534 const xml::ElementNode *pelmAttachment;
4535 while ((pelmAttachment = nl1.forAllNodes()))
4536 {
4537 AttachedDevice att;
4538 Utf8Str strUUID, strBus;
4539
4540 if (!pelmAttachment->getAttributeValue("hardDisk", strUUID))
4541 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@hardDisk attribute is missing"));
4542 parseUUID(att.uuid, strUUID, pelmAttachment);
4543
4544 if (!pelmAttachment->getAttributeValue("bus", strBus))
4545 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@bus attribute is missing"));
4546 // pre-1.7 'channel' is now port
4547 if (!pelmAttachment->getAttributeValue("channel", att.lPort))
4548 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@channel attribute is missing"));
4549 // pre-1.7 'device' is still device
4550 if (!pelmAttachment->getAttributeValue("device", att.lDevice))
4551 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@device attribute is missing"));
4552
4553 att.deviceType = DeviceType_HardDisk;
4554
4555 if (strBus == "IDE")
4556 {
4557 if (!pIDEController)
4558 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus is 'IDE' but cannot find IDE controller"));
4559 pIDEController->llAttachedDevices.push_back(att);
4560 }
4561 else if (strBus == "SATA")
4562 {
4563 if (!pSATAController)
4564 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus is 'SATA' but cannot find SATA controller"));
4565 pSATAController->llAttachedDevices.push_back(att);
4566 }
4567 else
4568 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus attribute has illegal value '%s'"), strBus.c_str());
4569 }
4570}
4571
4572/**
4573 * Reads in a \<StorageControllers\> block and stores it in the given Storage structure.
4574 * Used both directly from readMachine and from readSnapshot, since snapshots
4575 * have their own storage controllers sections.
4576 *
4577 * This is only called for settings version 1.7 and above; see readHardDiskAttachments_pre1_7()
4578 * for earlier versions.
4579 *
4580 * @param elmStorageControllers
4581 * @param strg
4582 */
4583void MachineConfigFile::readStorageControllers(const xml::ElementNode &elmStorageControllers,
4584 Storage &strg)
4585{
4586 xml::NodesLoop nlStorageControllers(elmStorageControllers, "StorageController");
4587 const xml::ElementNode *pelmController;
4588 while ((pelmController = nlStorageControllers.forAllNodes()))
4589 {
4590 StorageController sctl;
4591
4592 if (!pelmController->getAttributeValue("name", sctl.strName))
4593 throw ConfigFileError(this, pelmController, N_("Required StorageController/@name attribute is missing"));
4594 // canonicalize storage controller names for configs in the switchover
4595 // period.
4596 if (m->sv < SettingsVersion_v1_9)
4597 {
4598 if (sctl.strName == "IDE")
4599 sctl.strName = "IDE Controller";
4600 else if (sctl.strName == "SATA")
4601 sctl.strName = "SATA Controller";
4602 else if (sctl.strName == "SCSI")
4603 sctl.strName = "SCSI Controller";
4604 }
4605
4606 pelmController->getAttributeValue("Instance", sctl.ulInstance);
4607 // default from constructor is 0
4608
4609 pelmController->getAttributeValue("Bootable", sctl.fBootable);
4610 // default from constructor is true which is true
4611 // for settings below version 1.11 because they allowed only
4612 // one controller per type.
4613
4614 Utf8Str strType;
4615 if (!pelmController->getAttributeValue("type", strType))
4616 throw ConfigFileError(this, pelmController, N_("Required StorageController/@type attribute is missing"));
4617
4618 if (strType == "AHCI")
4619 {
4620 sctl.storageBus = StorageBus_SATA;
4621 sctl.controllerType = StorageControllerType_IntelAhci;
4622 }
4623 else if (strType == "LsiLogic")
4624 {
4625 sctl.storageBus = StorageBus_SCSI;
4626 sctl.controllerType = StorageControllerType_LsiLogic;
4627 }
4628 else if (strType == "BusLogic")
4629 {
4630 sctl.storageBus = StorageBus_SCSI;
4631 sctl.controllerType = StorageControllerType_BusLogic;
4632 }
4633 else if (strType == "PIIX3")
4634 {
4635 sctl.storageBus = StorageBus_IDE;
4636 sctl.controllerType = StorageControllerType_PIIX3;
4637 }
4638 else if (strType == "PIIX4")
4639 {
4640 sctl.storageBus = StorageBus_IDE;
4641 sctl.controllerType = StorageControllerType_PIIX4;
4642 }
4643 else if (strType == "ICH6")
4644 {
4645 sctl.storageBus = StorageBus_IDE;
4646 sctl.controllerType = StorageControllerType_ICH6;
4647 }
4648 else if ( (m->sv >= SettingsVersion_v1_9)
4649 && (strType == "I82078")
4650 )
4651 {
4652 sctl.storageBus = StorageBus_Floppy;
4653 sctl.controllerType = StorageControllerType_I82078;
4654 }
4655 else if (strType == "LsiLogicSas")
4656 {
4657 sctl.storageBus = StorageBus_SAS;
4658 sctl.controllerType = StorageControllerType_LsiLogicSas;
4659 }
4660 else if (strType == "USB")
4661 {
4662 sctl.storageBus = StorageBus_USB;
4663 sctl.controllerType = StorageControllerType_USB;
4664 }
4665 else if (strType == "NVMe")
4666 {
4667 sctl.storageBus = StorageBus_PCIe;
4668 sctl.controllerType = StorageControllerType_NVMe;
4669 }
4670 else
4671 throw ConfigFileError(this, pelmController, N_("Invalid value '%s' for StorageController/@type attribute"), strType.c_str());
4672
4673 readStorageControllerAttributes(*pelmController, sctl);
4674
4675 xml::NodesLoop nlAttached(*pelmController, "AttachedDevice");
4676 const xml::ElementNode *pelmAttached;
4677 while ((pelmAttached = nlAttached.forAllNodes()))
4678 {
4679 AttachedDevice att;
4680 Utf8Str strTemp;
4681 pelmAttached->getAttributeValue("type", strTemp);
4682
4683 att.fDiscard = false;
4684 att.fNonRotational = false;
4685 att.fHotPluggable = false;
4686
4687 if (strTemp == "HardDisk")
4688 {
4689 att.deviceType = DeviceType_HardDisk;
4690 pelmAttached->getAttributeValue("nonrotational", att.fNonRotational);
4691 pelmAttached->getAttributeValue("discard", att.fDiscard);
4692 }
4693 else if (m->sv >= SettingsVersion_v1_9)
4694 {
4695 // starting with 1.9 we list DVD and floppy drive info + attachments under <StorageControllers>
4696 if (strTemp == "DVD")
4697 {
4698 att.deviceType = DeviceType_DVD;
4699 pelmAttached->getAttributeValue("passthrough", att.fPassThrough);
4700 pelmAttached->getAttributeValue("tempeject", att.fTempEject);
4701 }
4702 else if (strTemp == "Floppy")
4703 att.deviceType = DeviceType_Floppy;
4704 }
4705
4706 if (att.deviceType != DeviceType_Null)
4707 {
4708 const xml::ElementNode *pelmImage;
4709 // all types can have images attached, but for HardDisk it's required
4710 if (!(pelmImage = pelmAttached->findChildElement("Image")))
4711 {
4712 if (att.deviceType == DeviceType_HardDisk)
4713 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/Image element is missing"));
4714 else
4715 {
4716 // DVDs and floppies can also have <HostDrive> instead of <Image>
4717 const xml::ElementNode *pelmHostDrive;
4718 if ((pelmHostDrive = pelmAttached->findChildElement("HostDrive")))
4719 if (!pelmHostDrive->getAttributeValue("src", att.strHostDriveSrc))
4720 throw ConfigFileError(this, pelmHostDrive, N_("Required AttachedDevice/HostDrive/@src attribute is missing"));
4721 }
4722 }
4723 else
4724 {
4725 if (!pelmImage->getAttributeValue("uuid", strTemp))
4726 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/Image/@uuid attribute is missing"));
4727 parseUUID(att.uuid, strTemp, pelmImage);
4728 }
4729
4730 if (!pelmAttached->getAttributeValue("port", att.lPort))
4731 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/@port attribute is missing"));
4732 if (!pelmAttached->getAttributeValue("device", att.lDevice))
4733 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/@device attribute is missing"));
4734
4735 /* AHCI controller ports are hotpluggable by default, keep compatibility with existing settings. */
4736 if (m->sv >= SettingsVersion_v1_15)
4737 pelmAttached->getAttributeValue("hotpluggable", att.fHotPluggable);
4738 else if (sctl.controllerType == StorageControllerType_IntelAhci)
4739 att.fHotPluggable = true;
4740
4741 pelmAttached->getAttributeValue("bandwidthGroup", att.strBwGroup);
4742 sctl.llAttachedDevices.push_back(att);
4743 }
4744 }
4745
4746 strg.llStorageControllers.push_back(sctl);
4747 }
4748}
4749
4750/**
4751 * This gets called for legacy pre-1.9 settings files after having parsed the
4752 * \<Hardware\> and \<StorageControllers\> sections to parse \<Hardware\> once more
4753 * for the \<DVDDrive\> and \<FloppyDrive\> sections.
4754 *
4755 * Before settings version 1.9, DVD and floppy drives were specified separately
4756 * under \<Hardware\>; we then need this extra loop to make sure the storage
4757 * controller structs are already set up so we can add stuff to them.
4758 *
4759 * @param elmHardware
4760 * @param strg
4761 */
4762void MachineConfigFile::readDVDAndFloppies_pre1_9(const xml::ElementNode &elmHardware,
4763 Storage &strg)
4764{
4765 xml::NodesLoop nl1(elmHardware);
4766 const xml::ElementNode *pelmHwChild;
4767 while ((pelmHwChild = nl1.forAllNodes()))
4768 {
4769 if (pelmHwChild->nameEquals("DVDDrive"))
4770 {
4771 // create a DVD "attached device" and attach it to the existing IDE controller
4772 AttachedDevice att;
4773 att.deviceType = DeviceType_DVD;
4774 // legacy DVD drive is always secondary master (port 1, device 0)
4775 att.lPort = 1;
4776 att.lDevice = 0;
4777 pelmHwChild->getAttributeValue("passthrough", att.fPassThrough);
4778 pelmHwChild->getAttributeValue("tempeject", att.fTempEject);
4779
4780 const xml::ElementNode *pDriveChild;
4781 Utf8Str strTmp;
4782 if ( (pDriveChild = pelmHwChild->findChildElement("Image")) != NULL
4783 && pDriveChild->getAttributeValue("uuid", strTmp))
4784 parseUUID(att.uuid, strTmp, pDriveChild);
4785 else if ((pDriveChild = pelmHwChild->findChildElement("HostDrive")))
4786 pDriveChild->getAttributeValue("src", att.strHostDriveSrc);
4787
4788 // find the IDE controller and attach the DVD drive
4789 bool fFound = false;
4790 for (StorageControllersList::iterator it = strg.llStorageControllers.begin();
4791 it != strg.llStorageControllers.end();
4792 ++it)
4793 {
4794 StorageController &sctl = *it;
4795 if (sctl.storageBus == StorageBus_IDE)
4796 {
4797 sctl.llAttachedDevices.push_back(att);
4798 fFound = true;
4799 break;
4800 }
4801 }
4802
4803 if (!fFound)
4804 throw ConfigFileError(this, pelmHwChild, N_("Internal error: found DVD drive but IDE controller does not exist"));
4805 // shouldn't happen because pre-1.9 settings files always had at least one IDE controller in the settings
4806 // which should have gotten parsed in <StorageControllers> before this got called
4807 }
4808 else if (pelmHwChild->nameEquals("FloppyDrive"))
4809 {
4810 bool fEnabled;
4811 if ( pelmHwChild->getAttributeValue("enabled", fEnabled)
4812 && fEnabled)
4813 {
4814 // create a new floppy controller and attach a floppy "attached device"
4815 StorageController sctl;
4816 sctl.strName = "Floppy Controller";
4817 sctl.storageBus = StorageBus_Floppy;
4818 sctl.controllerType = StorageControllerType_I82078;
4819 sctl.ulPortCount = 1;
4820
4821 AttachedDevice att;
4822 att.deviceType = DeviceType_Floppy;
4823 att.lPort = 0;
4824 att.lDevice = 0;
4825
4826 const xml::ElementNode *pDriveChild;
4827 Utf8Str strTmp;
4828 if ( (pDriveChild = pelmHwChild->findChildElement("Image"))
4829 && pDriveChild->getAttributeValue("uuid", strTmp) )
4830 parseUUID(att.uuid, strTmp, pDriveChild);
4831 else if ((pDriveChild = pelmHwChild->findChildElement("HostDrive")))
4832 pDriveChild->getAttributeValue("src", att.strHostDriveSrc);
4833
4834 // store attachment with controller
4835 sctl.llAttachedDevices.push_back(att);
4836 // store controller with storage
4837 strg.llStorageControllers.push_back(sctl);
4838 }
4839 }
4840 }
4841}
4842
4843/**
4844 * Called for reading the \<Teleporter\> element under \<Machine\>.
4845 */
4846void MachineConfigFile::readTeleporter(const xml::ElementNode *pElmTeleporter,
4847 MachineUserData *pUserData)
4848{
4849 pElmTeleporter->getAttributeValue("enabled", pUserData->fTeleporterEnabled);
4850 pElmTeleporter->getAttributeValue("port", pUserData->uTeleporterPort);
4851 pElmTeleporter->getAttributeValue("address", pUserData->strTeleporterAddress);
4852 pElmTeleporter->getAttributeValue("password", pUserData->strTeleporterPassword);
4853
4854 if ( pUserData->strTeleporterPassword.isNotEmpty()
4855 && !VBoxIsPasswordHashed(&pUserData->strTeleporterPassword))
4856 VBoxHashPassword(&pUserData->strTeleporterPassword);
4857}
4858
4859/**
4860 * Called for reading the \<Debugging\> element under \<Machine\> or \<Snapshot\>.
4861 */
4862void MachineConfigFile::readDebugging(const xml::ElementNode *pElmDebugging, Debugging *pDbg)
4863{
4864 if (!pElmDebugging || m->sv < SettingsVersion_v1_13)
4865 return;
4866
4867 const xml::ElementNode * const pelmTracing = pElmDebugging->findChildElement("Tracing");
4868 if (pelmTracing)
4869 {
4870 pelmTracing->getAttributeValue("enabled", pDbg->fTracingEnabled);
4871 pelmTracing->getAttributeValue("allowTracingToAccessVM", pDbg->fAllowTracingToAccessVM);
4872 pelmTracing->getAttributeValue("config", pDbg->strTracingConfig);
4873 }
4874}
4875
4876/**
4877 * Called for reading the \<Autostart\> element under \<Machine\> or \<Snapshot\>.
4878 */
4879void MachineConfigFile::readAutostart(const xml::ElementNode *pElmAutostart, Autostart *pAutostart)
4880{
4881 Utf8Str strAutostop;
4882
4883 if (!pElmAutostart || m->sv < SettingsVersion_v1_13)
4884 return;
4885
4886 pElmAutostart->getAttributeValue("enabled", pAutostart->fAutostartEnabled);
4887 pElmAutostart->getAttributeValue("delay", pAutostart->uAutostartDelay);
4888 pElmAutostart->getAttributeValue("autostop", strAutostop);
4889 if (strAutostop == "Disabled")
4890 pAutostart->enmAutostopType = AutostopType_Disabled;
4891 else if (strAutostop == "SaveState")
4892 pAutostart->enmAutostopType = AutostopType_SaveState;
4893 else if (strAutostop == "PowerOff")
4894 pAutostart->enmAutostopType = AutostopType_PowerOff;
4895 else if (strAutostop == "AcpiShutdown")
4896 pAutostart->enmAutostopType = AutostopType_AcpiShutdown;
4897 else
4898 throw ConfigFileError(this, pElmAutostart, N_("Invalid value '%s' for Autostart/@autostop attribute"), strAutostop.c_str());
4899}
4900
4901/**
4902 * Called for reading the \<Groups\> element under \<Machine\>.
4903 */
4904void MachineConfigFile::readGroups(const xml::ElementNode *pElmGroups, StringsList *pllGroups)
4905{
4906 pllGroups->clear();
4907 if (!pElmGroups || m->sv < SettingsVersion_v1_13)
4908 {
4909 pllGroups->push_back("/");
4910 return;
4911 }
4912
4913 xml::NodesLoop nlGroups(*pElmGroups);
4914 const xml::ElementNode *pelmGroup;
4915 while ((pelmGroup = nlGroups.forAllNodes()))
4916 {
4917 if (pelmGroup->nameEquals("Group"))
4918 {
4919 Utf8Str strGroup;
4920 if (!pelmGroup->getAttributeValue("name", strGroup))
4921 throw ConfigFileError(this, pelmGroup, N_("Required Group/@name attribute is missing"));
4922 pllGroups->push_back(strGroup);
4923 }
4924 }
4925}
4926
4927/**
4928 * Called initially for the \<Snapshot\> element under \<Machine\>, if present,
4929 * to store the snapshot's data into the given Snapshot structure (which is
4930 * then the one in the Machine struct). This might then recurse if
4931 * a \<Snapshots\> (plural) element is found in the snapshot, which should
4932 * contain a list of child snapshots; such lists are maintained in the
4933 * Snapshot structure.
4934 *
4935 * @param curSnapshotUuid
4936 * @param depth
4937 * @param elmSnapshot
4938 * @param snap
4939 * @returns true if curSnapshotUuid is in this snapshot subtree, otherwise false
4940 */
4941bool MachineConfigFile::readSnapshot(const Guid &curSnapshotUuid,
4942 uint32_t depth,
4943 const xml::ElementNode &elmSnapshot,
4944 Snapshot &snap)
4945{
4946 if (depth > SETTINGS_SNAPSHOT_DEPTH_MAX)
4947 throw ConfigFileError(this, &elmSnapshot, N_("Maximum snapshot tree depth of %u exceeded"), SETTINGS_SNAPSHOT_DEPTH_MAX);
4948
4949 Utf8Str strTemp;
4950
4951 if (!elmSnapshot.getAttributeValue("uuid", strTemp))
4952 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@uuid attribute is missing"));
4953 parseUUID(snap.uuid, strTemp, &elmSnapshot);
4954 bool foundCurrentSnapshot = (snap.uuid == curSnapshotUuid);
4955
4956 if (!elmSnapshot.getAttributeValue("name", snap.strName))
4957 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@name attribute is missing"));
4958
4959 // earlier 3.1 trunk builds had a bug and added Description as an attribute, read it silently and write it back as an element
4960 elmSnapshot.getAttributeValue("Description", snap.strDescription);
4961
4962 if (!elmSnapshot.getAttributeValue("timeStamp", strTemp))
4963 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@timeStamp attribute is missing"));
4964 parseTimestamp(snap.timestamp, strTemp, &elmSnapshot);
4965
4966 elmSnapshot.getAttributeValuePath("stateFile", snap.strStateFile); // online snapshots only
4967
4968 // parse Hardware before the other elements because other things depend on it
4969 const xml::ElementNode *pelmHardware;
4970 if (!(pelmHardware = elmSnapshot.findChildElement("Hardware")))
4971 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@Hardware element is missing"));
4972 readHardware(*pelmHardware, snap.hardware);
4973
4974 xml::NodesLoop nlSnapshotChildren(elmSnapshot);
4975 const xml::ElementNode *pelmSnapshotChild;
4976 while ((pelmSnapshotChild = nlSnapshotChildren.forAllNodes()))
4977 {
4978 if (pelmSnapshotChild->nameEquals("Description"))
4979 snap.strDescription = pelmSnapshotChild->getValue();
4980 else if ( m->sv < SettingsVersion_v1_7
4981 && pelmSnapshotChild->nameEquals("HardDiskAttachments"))
4982 readHardDiskAttachments_pre1_7(*pelmSnapshotChild, snap.hardware.storage);
4983 else if ( m->sv >= SettingsVersion_v1_7
4984 && pelmSnapshotChild->nameEquals("StorageControllers"))
4985 readStorageControllers(*pelmSnapshotChild, snap.hardware.storage);
4986 else if (pelmSnapshotChild->nameEquals("Snapshots"))
4987 {
4988 xml::NodesLoop nlChildSnapshots(*pelmSnapshotChild);
4989 const xml::ElementNode *pelmChildSnapshot;
4990 while ((pelmChildSnapshot = nlChildSnapshots.forAllNodes()))
4991 {
4992 if (pelmChildSnapshot->nameEquals("Snapshot"))
4993 {
4994 // recurse with this element and put the child at the
4995 // end of the list. XPCOM has very small stack, avoid
4996 // big local variables and use the list element.
4997 snap.llChildSnapshots.push_back(Snapshot::Empty);
4998 bool found = readSnapshot(curSnapshotUuid, depth + 1, *pelmChildSnapshot, snap.llChildSnapshots.back());
4999 foundCurrentSnapshot = foundCurrentSnapshot || found;
5000 }
5001 }
5002 }
5003 }
5004
5005 if (m->sv < SettingsVersion_v1_9)
5006 // go through Hardware once more to repair the settings controller structures
5007 // with data from old DVDDrive and FloppyDrive elements
5008 readDVDAndFloppies_pre1_9(*pelmHardware, snap.hardware.storage);
5009
5010 readDebugging(elmSnapshot.findChildElement("Debugging"), &snap.debugging);
5011 readAutostart(elmSnapshot.findChildElement("Autostart"), &snap.autostart);
5012 // note: Groups exist only for Machine, not for Snapshot
5013
5014 return foundCurrentSnapshot;
5015}
5016
5017const struct {
5018 const char *pcszOld;
5019 const char *pcszNew;
5020} aConvertOSTypes[] =
5021{
5022 { "unknown", "Other" },
5023 { "dos", "DOS" },
5024 { "win31", "Windows31" },
5025 { "win95", "Windows95" },
5026 { "win98", "Windows98" },
5027 { "winme", "WindowsMe" },
5028 { "winnt4", "WindowsNT4" },
5029 { "win2k", "Windows2000" },
5030 { "winxp", "WindowsXP" },
5031 { "win2k3", "Windows2003" },
5032 { "winvista", "WindowsVista" },
5033 { "win2k8", "Windows2008" },
5034 { "os2warp3", "OS2Warp3" },
5035 { "os2warp4", "OS2Warp4" },
5036 { "os2warp45", "OS2Warp45" },
5037 { "ecs", "OS2eCS" },
5038 { "linux22", "Linux22" },
5039 { "linux24", "Linux24" },
5040 { "linux26", "Linux26" },
5041 { "archlinux", "ArchLinux" },
5042 { "debian", "Debian" },
5043 { "opensuse", "OpenSUSE" },
5044 { "fedoracore", "Fedora" },
5045 { "gentoo", "Gentoo" },
5046 { "mandriva", "Mandriva" },
5047 { "redhat", "RedHat" },
5048 { "ubuntu", "Ubuntu" },
5049 { "xandros", "Xandros" },
5050 { "freebsd", "FreeBSD" },
5051 { "openbsd", "OpenBSD" },
5052 { "netbsd", "NetBSD" },
5053 { "netware", "Netware" },
5054 { "solaris", "Solaris" },
5055 { "opensolaris", "OpenSolaris" },
5056 { "l4", "L4" }
5057};
5058
5059void MachineConfigFile::convertOldOSType_pre1_5(Utf8Str &str)
5060{
5061 for (unsigned u = 0;
5062 u < RT_ELEMENTS(aConvertOSTypes);
5063 ++u)
5064 {
5065 if (str == aConvertOSTypes[u].pcszOld)
5066 {
5067 str = aConvertOSTypes[u].pcszNew;
5068 break;
5069 }
5070 }
5071}
5072
5073/**
5074 * Called from the constructor to actually read in the \<Machine\> element
5075 * of a machine config file.
5076 * @param elmMachine
5077 */
5078void MachineConfigFile::readMachine(const xml::ElementNode &elmMachine)
5079{
5080 Utf8Str strUUID;
5081 if ( elmMachine.getAttributeValue("uuid", strUUID)
5082 && elmMachine.getAttributeValue("name", machineUserData.strName))
5083 {
5084 parseUUID(uuid, strUUID, &elmMachine);
5085
5086 elmMachine.getAttributeValue("directoryIncludesUUID", machineUserData.fDirectoryIncludesUUID);
5087 elmMachine.getAttributeValue("nameSync", machineUserData.fNameSync);
5088
5089 Utf8Str str;
5090 elmMachine.getAttributeValue("Description", machineUserData.strDescription);
5091 elmMachine.getAttributeValue("OSType", machineUserData.strOsType);
5092 if (m->sv < SettingsVersion_v1_5)
5093 convertOldOSType_pre1_5(machineUserData.strOsType);
5094
5095 elmMachine.getAttributeValuePath("stateFile", strStateFile);
5096
5097 if (elmMachine.getAttributeValue("currentSnapshot", str))
5098 parseUUID(uuidCurrentSnapshot, str, &elmMachine);
5099
5100 elmMachine.getAttributeValuePath("snapshotFolder", machineUserData.strSnapshotFolder);
5101
5102 if (!elmMachine.getAttributeValue("currentStateModified", fCurrentStateModified))
5103 fCurrentStateModified = true;
5104 if (elmMachine.getAttributeValue("lastStateChange", str))
5105 parseTimestamp(timeLastStateChange, str, &elmMachine);
5106 // constructor has called RTTimeNow(&timeLastStateChange) before
5107 if (elmMachine.getAttributeValue("aborted", fAborted))
5108 fAborted = true;
5109
5110 elmMachine.getAttributeValue("processPriority", machineUserData.strVMPriority);
5111
5112 str.setNull();
5113 elmMachine.getAttributeValue("icon", str);
5114 parseBase64(machineUserData.ovIcon, str, &elmMachine);
5115
5116 // parse Hardware before the other elements because other things depend on it
5117 const xml::ElementNode *pelmHardware;
5118 if (!(pelmHardware = elmMachine.findChildElement("Hardware")))
5119 throw ConfigFileError(this, &elmMachine, N_("Required Machine/Hardware element is missing"));
5120 readHardware(*pelmHardware, hardwareMachine);
5121
5122 xml::NodesLoop nlRootChildren(elmMachine);
5123 const xml::ElementNode *pelmMachineChild;
5124 while ((pelmMachineChild = nlRootChildren.forAllNodes()))
5125 {
5126 if (pelmMachineChild->nameEquals("ExtraData"))
5127 readExtraData(*pelmMachineChild,
5128 mapExtraDataItems);
5129 else if ( (m->sv < SettingsVersion_v1_7)
5130 && (pelmMachineChild->nameEquals("HardDiskAttachments"))
5131 )
5132 readHardDiskAttachments_pre1_7(*pelmMachineChild, hardwareMachine.storage);
5133 else if ( (m->sv >= SettingsVersion_v1_7)
5134 && (pelmMachineChild->nameEquals("StorageControllers"))
5135 )
5136 readStorageControllers(*pelmMachineChild, hardwareMachine.storage);
5137 else if (pelmMachineChild->nameEquals("Snapshot"))
5138 {
5139 if (uuidCurrentSnapshot.isZero())
5140 throw ConfigFileError(this, &elmMachine, N_("Snapshots present but required Machine/@currentSnapshot attribute is missing"));
5141 bool foundCurrentSnapshot = false;
5142 Snapshot snap;
5143 // this will recurse into child snapshots, if necessary
5144 foundCurrentSnapshot = readSnapshot(uuidCurrentSnapshot, 1, *pelmMachineChild, snap);
5145 if (!foundCurrentSnapshot)
5146 throw ConfigFileError(this, &elmMachine, N_("Snapshots present but none matches the UUID in the Machine/@currentSnapshot attribute"));
5147 llFirstSnapshot.push_back(snap);
5148 }
5149 else if (pelmMachineChild->nameEquals("Description"))
5150 machineUserData.strDescription = pelmMachineChild->getValue();
5151 else if (pelmMachineChild->nameEquals("Teleporter"))
5152 readTeleporter(pelmMachineChild, &machineUserData);
5153 else if (pelmMachineChild->nameEquals("FaultTolerance"))
5154 {
5155 Utf8Str strFaultToleranceSate;
5156 if (pelmMachineChild->getAttributeValue("state", strFaultToleranceSate))
5157 {
5158 if (strFaultToleranceSate == "master")
5159 machineUserData.enmFaultToleranceState = FaultToleranceState_Master;
5160 else
5161 if (strFaultToleranceSate == "standby")
5162 machineUserData.enmFaultToleranceState = FaultToleranceState_Standby;
5163 else
5164 machineUserData.enmFaultToleranceState = FaultToleranceState_Inactive;
5165 }
5166 pelmMachineChild->getAttributeValue("port", machineUserData.uFaultTolerancePort);
5167 pelmMachineChild->getAttributeValue("address", machineUserData.strFaultToleranceAddress);
5168 pelmMachineChild->getAttributeValue("interval", machineUserData.uFaultToleranceInterval);
5169 pelmMachineChild->getAttributeValue("password", machineUserData.strFaultTolerancePassword);
5170 }
5171 else if (pelmMachineChild->nameEquals("MediaRegistry"))
5172 readMediaRegistry(*pelmMachineChild, mediaRegistry);
5173 else if (pelmMachineChild->nameEquals("Debugging"))
5174 readDebugging(pelmMachineChild, &debugging);
5175 else if (pelmMachineChild->nameEquals("Autostart"))
5176 readAutostart(pelmMachineChild, &autostart);
5177 else if (pelmMachineChild->nameEquals("Groups"))
5178 readGroups(pelmMachineChild, &machineUserData.llGroups);
5179 }
5180
5181 if (m->sv < SettingsVersion_v1_9)
5182 // go through Hardware once more to repair the settings controller structures
5183 // with data from old DVDDrive and FloppyDrive elements
5184 readDVDAndFloppies_pre1_9(*pelmHardware, hardwareMachine.storage);
5185 }
5186 else
5187 throw ConfigFileError(this, &elmMachine, N_("Required Machine/@uuid or @name attributes is missing"));
5188}
5189
5190/**
5191 * Creates a \<Hardware\> node under elmParent and then writes out the XML
5192 * keys under that. Called for both the \<Machine\> node and for snapshots.
5193 * @param elmParent
5194 * @param hw
5195 * @param fl
5196 * @param pllElementsWithUuidAttributes
5197 */
5198void MachineConfigFile::buildHardwareXML(xml::ElementNode &elmParent,
5199 const Hardware &hw,
5200 uint32_t fl,
5201 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes)
5202{
5203 xml::ElementNode *pelmHardware = elmParent.createChild("Hardware");
5204
5205 if ( m->sv >= SettingsVersion_v1_4
5206 && (m->sv < SettingsVersion_v1_7 ? hw.strVersion != "1" : hw.strVersion != "2"))
5207 pelmHardware->setAttribute("version", hw.strVersion);
5208
5209 if ((m->sv >= SettingsVersion_v1_9)
5210 && !hw.uuid.isZero()
5211 && hw.uuid.isValid()
5212 )
5213 pelmHardware->setAttribute("uuid", hw.uuid.toStringCurly());
5214
5215 xml::ElementNode *pelmCPU = pelmHardware->createChild("CPU");
5216
5217 if (!hw.fHardwareVirt)
5218 pelmCPU->createChild("HardwareVirtEx")->setAttribute("enabled", hw.fHardwareVirt);
5219 if (!hw.fNestedPaging)
5220 pelmCPU->createChild("HardwareVirtExNestedPaging")->setAttribute("enabled", hw.fNestedPaging);
5221 if (!hw.fVPID)
5222 pelmCPU->createChild("HardwareVirtExVPID")->setAttribute("enabled", hw.fVPID);
5223 if (!hw.fUnrestrictedExecution)
5224 pelmCPU->createChild("HardwareVirtExUX")->setAttribute("enabled", hw.fUnrestrictedExecution);
5225 // PAE has too crazy default handling, must always save this setting.
5226 pelmCPU->createChild("PAE")->setAttribute("enabled", hw.fPAE);
5227 if (m->sv >= SettingsVersion_v1_16)
5228 {
5229 }
5230 if (m->sv >= SettingsVersion_v1_14 && hw.enmLongMode != Hardware::LongMode_Legacy)
5231 {
5232 // LongMode has too crazy default handling, must always save this setting.
5233 pelmCPU->createChild("LongMode")->setAttribute("enabled", hw.enmLongMode == Hardware::LongMode_Enabled);
5234 }
5235
5236 if (hw.fTripleFaultReset)
5237 pelmCPU->createChild("TripleFaultReset")->setAttribute("enabled", hw.fTripleFaultReset);
5238 if (m->sv >= SettingsVersion_v1_14)
5239 {
5240 if (hw.fX2APIC)
5241 pelmCPU->createChild("X2APIC")->setAttribute("enabled", hw.fX2APIC);
5242 else if (!hw.fAPIC)
5243 pelmCPU->createChild("APIC")->setAttribute("enabled", hw.fAPIC);
5244 }
5245 if (hw.cCPUs > 1)
5246 pelmCPU->setAttribute("count", hw.cCPUs);
5247 if (hw.ulCpuExecutionCap != 100)
5248 pelmCPU->setAttribute("executionCap", hw.ulCpuExecutionCap);
5249 if (hw.uCpuIdPortabilityLevel != 0)
5250 pelmCPU->setAttribute("CpuIdPortabilityLevel", hw.uCpuIdPortabilityLevel);
5251 if (!hw.strCpuProfile.equals("host") && hw.strCpuProfile.isNotEmpty())
5252 pelmCPU->setAttribute("CpuProfile", hw.strCpuProfile);
5253
5254 // HardwareVirtExLargePages has too crazy default handling, must always save this setting.
5255 pelmCPU->createChild("HardwareVirtExLargePages")->setAttribute("enabled", hw.fLargePages);
5256
5257 if (m->sv >= SettingsVersion_v1_9)
5258 {
5259 if (hw.fHardwareVirtForce)
5260 pelmCPU->createChild("HardwareVirtForce")->setAttribute("enabled", hw.fHardwareVirtForce);
5261 }
5262
5263 if (m->sv >= SettingsVersion_v1_10)
5264 {
5265 if (hw.fCpuHotPlug)
5266 pelmCPU->setAttribute("hotplug", hw.fCpuHotPlug);
5267
5268 xml::ElementNode *pelmCpuTree = NULL;
5269 for (CpuList::const_iterator it = hw.llCpus.begin();
5270 it != hw.llCpus.end();
5271 ++it)
5272 {
5273 const Cpu &cpu = *it;
5274
5275 if (pelmCpuTree == NULL)
5276 pelmCpuTree = pelmCPU->createChild("CpuTree");
5277
5278 xml::ElementNode *pelmCpu = pelmCpuTree->createChild("Cpu");
5279 pelmCpu->setAttribute("id", cpu.ulId);
5280 }
5281 }
5282
5283 xml::ElementNode *pelmCpuIdTree = NULL;
5284 for (CpuIdLeafsList::const_iterator it = hw.llCpuIdLeafs.begin();
5285 it != hw.llCpuIdLeafs.end();
5286 ++it)
5287 {
5288 const CpuIdLeaf &leaf = *it;
5289
5290 if (pelmCpuIdTree == NULL)
5291 pelmCpuIdTree = pelmCPU->createChild("CpuIdTree");
5292
5293 xml::ElementNode *pelmCpuIdLeaf = pelmCpuIdTree->createChild("CpuIdLeaf");
5294 pelmCpuIdLeaf->setAttribute("id", leaf.ulId);
5295 pelmCpuIdLeaf->setAttribute("eax", leaf.ulEax);
5296 pelmCpuIdLeaf->setAttribute("ebx", leaf.ulEbx);
5297 pelmCpuIdLeaf->setAttribute("ecx", leaf.ulEcx);
5298 pelmCpuIdLeaf->setAttribute("edx", leaf.ulEdx);
5299 }
5300
5301 xml::ElementNode *pelmMemory = pelmHardware->createChild("Memory");
5302 pelmMemory->setAttribute("RAMSize", hw.ulMemorySizeMB);
5303 if (m->sv >= SettingsVersion_v1_10)
5304 {
5305 if (hw.fPageFusionEnabled)
5306 pelmMemory->setAttribute("PageFusion", hw.fPageFusionEnabled);
5307 }
5308
5309 if ( (m->sv >= SettingsVersion_v1_9)
5310 && (hw.firmwareType >= FirmwareType_EFI)
5311 )
5312 {
5313 xml::ElementNode *pelmFirmware = pelmHardware->createChild("Firmware");
5314 const char *pcszFirmware;
5315
5316 switch (hw.firmwareType)
5317 {
5318 case FirmwareType_EFI: pcszFirmware = "EFI"; break;
5319 case FirmwareType_EFI32: pcszFirmware = "EFI32"; break;
5320 case FirmwareType_EFI64: pcszFirmware = "EFI64"; break;
5321 case FirmwareType_EFIDUAL: pcszFirmware = "EFIDUAL"; break;
5322 default: pcszFirmware = "None"; break;
5323 }
5324 pelmFirmware->setAttribute("type", pcszFirmware);
5325 }
5326
5327 if ( m->sv >= SettingsVersion_v1_10
5328 && ( hw.pointingHIDType != PointingHIDType_PS2Mouse
5329 || hw.keyboardHIDType != KeyboardHIDType_PS2Keyboard))
5330 {
5331 xml::ElementNode *pelmHID = pelmHardware->createChild("HID");
5332 const char *pcszHID;
5333
5334 if (hw.pointingHIDType != PointingHIDType_PS2Mouse)
5335 {
5336 switch (hw.pointingHIDType)
5337 {
5338 case PointingHIDType_USBMouse: pcszHID = "USBMouse"; break;
5339 case PointingHIDType_USBTablet: pcszHID = "USBTablet"; break;
5340 case PointingHIDType_PS2Mouse: pcszHID = "PS2Mouse"; break;
5341 case PointingHIDType_ComboMouse: pcszHID = "ComboMouse"; break;
5342 case PointingHIDType_USBMultiTouch: pcszHID = "USBMultiTouch";break;
5343 case PointingHIDType_None: pcszHID = "None"; break;
5344 default: Assert(false); pcszHID = "PS2Mouse"; break;
5345 }
5346 pelmHID->setAttribute("Pointing", pcszHID);
5347 }
5348
5349 if (hw.keyboardHIDType != KeyboardHIDType_PS2Keyboard)
5350 {
5351 switch (hw.keyboardHIDType)
5352 {
5353 case KeyboardHIDType_USBKeyboard: pcszHID = "USBKeyboard"; break;
5354 case KeyboardHIDType_PS2Keyboard: pcszHID = "PS2Keyboard"; break;
5355 case KeyboardHIDType_ComboKeyboard: pcszHID = "ComboKeyboard"; break;
5356 case KeyboardHIDType_None: pcszHID = "None"; break;
5357 default: Assert(false); pcszHID = "PS2Keyboard"; break;
5358 }
5359 pelmHID->setAttribute("Keyboard", pcszHID);
5360 }
5361 }
5362
5363 if ( (m->sv >= SettingsVersion_v1_10)
5364 && hw.fHPETEnabled
5365 )
5366 {
5367 xml::ElementNode *pelmHPET = pelmHardware->createChild("HPET");
5368 pelmHPET->setAttribute("enabled", hw.fHPETEnabled);
5369 }
5370
5371 if ( (m->sv >= SettingsVersion_v1_11)
5372 )
5373 {
5374 if (hw.chipsetType != ChipsetType_PIIX3)
5375 {
5376 xml::ElementNode *pelmChipset = pelmHardware->createChild("Chipset");
5377 const char *pcszChipset;
5378
5379 switch (hw.chipsetType)
5380 {
5381 case ChipsetType_PIIX3: pcszChipset = "PIIX3"; break;
5382 case ChipsetType_ICH9: pcszChipset = "ICH9"; break;
5383 default: Assert(false); pcszChipset = "PIIX3"; break;
5384 }
5385 pelmChipset->setAttribute("type", pcszChipset);
5386 }
5387 }
5388
5389 if ( (m->sv >= SettingsVersion_v1_15)
5390 && !hw.areParavirtDefaultSettings(m->sv)
5391 )
5392 {
5393 const char *pcszParavirtProvider;
5394 switch (hw.paravirtProvider)
5395 {
5396 case ParavirtProvider_None: pcszParavirtProvider = "None"; break;
5397 case ParavirtProvider_Default: pcszParavirtProvider = "Default"; break;
5398 case ParavirtProvider_Legacy: pcszParavirtProvider = "Legacy"; break;
5399 case ParavirtProvider_Minimal: pcszParavirtProvider = "Minimal"; break;
5400 case ParavirtProvider_HyperV: pcszParavirtProvider = "HyperV"; break;
5401 case ParavirtProvider_KVM: pcszParavirtProvider = "KVM"; break;
5402 default: Assert(false); pcszParavirtProvider = "None"; break;
5403 }
5404
5405 xml::ElementNode *pelmParavirt = pelmHardware->createChild("Paravirt");
5406 pelmParavirt->setAttribute("provider", pcszParavirtProvider);
5407
5408 if ( m->sv >= SettingsVersion_v1_16
5409 && hw.strParavirtDebug.isNotEmpty())
5410 pelmParavirt->setAttribute("debug", hw.strParavirtDebug);
5411 }
5412
5413 if (!hw.areBootOrderDefaultSettings())
5414 {
5415 xml::ElementNode *pelmBoot = pelmHardware->createChild("Boot");
5416 for (BootOrderMap::const_iterator it = hw.mapBootOrder.begin();
5417 it != hw.mapBootOrder.end();
5418 ++it)
5419 {
5420 uint32_t i = it->first;
5421 DeviceType_T type = it->second;
5422 const char *pcszDevice;
5423
5424 switch (type)
5425 {
5426 case DeviceType_Floppy: pcszDevice = "Floppy"; break;
5427 case DeviceType_DVD: pcszDevice = "DVD"; break;
5428 case DeviceType_HardDisk: pcszDevice = "HardDisk"; break;
5429 case DeviceType_Network: pcszDevice = "Network"; break;
5430 default: /*case DeviceType_Null:*/ pcszDevice = "None"; break;
5431 }
5432
5433 xml::ElementNode *pelmOrder = pelmBoot->createChild("Order");
5434 pelmOrder->setAttribute("position",
5435 i + 1); // XML is 1-based but internal data is 0-based
5436 pelmOrder->setAttribute("device", pcszDevice);
5437 }
5438 }
5439
5440 if (!hw.areDisplayDefaultSettings())
5441 {
5442 xml::ElementNode *pelmDisplay = pelmHardware->createChild("Display");
5443 if (hw.graphicsControllerType != GraphicsControllerType_VBoxVGA)
5444 {
5445 const char *pcszGraphics;
5446 switch (hw.graphicsControllerType)
5447 {
5448 case GraphicsControllerType_VBoxVGA: pcszGraphics = "VBoxVGA"; break;
5449 case GraphicsControllerType_VMSVGA: pcszGraphics = "VMSVGA"; break;
5450 default: /*case GraphicsControllerType_Null:*/ pcszGraphics = "None"; break;
5451 }
5452 pelmDisplay->setAttribute("controller", pcszGraphics);
5453 }
5454 if (hw.ulVRAMSizeMB != 8)
5455 pelmDisplay->setAttribute("VRAMSize", hw.ulVRAMSizeMB);
5456 if (hw.cMonitors > 1)
5457 pelmDisplay->setAttribute("monitorCount", hw.cMonitors);
5458 if (hw.fAccelerate3D)
5459 pelmDisplay->setAttribute("accelerate3D", hw.fAccelerate3D);
5460
5461 if (m->sv >= SettingsVersion_v1_8)
5462 {
5463 if (hw.fAccelerate2DVideo)
5464 pelmDisplay->setAttribute("accelerate2DVideo", hw.fAccelerate2DVideo);
5465 }
5466 }
5467
5468 if (m->sv >= SettingsVersion_v1_14 && !hw.areVideoCaptureDefaultSettings())
5469 {
5470 xml::ElementNode *pelmVideoCapture = pelmHardware->createChild("VideoCapture");
5471 if (hw.fVideoCaptureEnabled)
5472 pelmVideoCapture->setAttribute("enabled", hw.fVideoCaptureEnabled);
5473 if (hw.u64VideoCaptureScreens != UINT64_C(0xffffffffffffffff))
5474 pelmVideoCapture->setAttribute("screens", hw.u64VideoCaptureScreens);
5475 if (!hw.strVideoCaptureFile.isEmpty())
5476 pelmVideoCapture->setAttributePath("file", hw.strVideoCaptureFile);
5477 if (hw.ulVideoCaptureHorzRes != 1024 || hw.ulVideoCaptureVertRes != 768)
5478 {
5479 pelmVideoCapture->setAttribute("horzRes", hw.ulVideoCaptureHorzRes);
5480 pelmVideoCapture->setAttribute("vertRes", hw.ulVideoCaptureVertRes);
5481 }
5482 if (hw.ulVideoCaptureRate != 512)
5483 pelmVideoCapture->setAttribute("rate", hw.ulVideoCaptureRate);
5484 if (hw.ulVideoCaptureFPS)
5485 pelmVideoCapture->setAttribute("fps", hw.ulVideoCaptureFPS);
5486 if (hw.ulVideoCaptureMaxTime)
5487 pelmVideoCapture->setAttribute("maxTime", hw.ulVideoCaptureMaxTime);
5488 if (hw.ulVideoCaptureMaxSize)
5489 pelmVideoCapture->setAttribute("maxSize", hw.ulVideoCaptureMaxSize);
5490 }
5491
5492 if (!hw.vrdeSettings.areDefaultSettings(m->sv))
5493 {
5494 xml::ElementNode *pelmVRDE = pelmHardware->createChild("RemoteDisplay");
5495 if (m->sv < SettingsVersion_v1_16 ? !hw.vrdeSettings.fEnabled : hw.vrdeSettings.fEnabled)
5496 pelmVRDE->setAttribute("enabled", hw.vrdeSettings.fEnabled);
5497 if (m->sv < SettingsVersion_v1_11)
5498 {
5499 /* In VBox 4.0 these attributes are replaced with "Properties". */
5500 Utf8Str strPort;
5501 StringsMap::const_iterator it = hw.vrdeSettings.mapProperties.find("TCP/Ports");
5502 if (it != hw.vrdeSettings.mapProperties.end())
5503 strPort = it->second;
5504 if (!strPort.length())
5505 strPort = "3389";
5506 pelmVRDE->setAttribute("port", strPort);
5507
5508 Utf8Str strAddress;
5509 it = hw.vrdeSettings.mapProperties.find("TCP/Address");
5510 if (it != hw.vrdeSettings.mapProperties.end())
5511 strAddress = it->second;
5512 if (strAddress.length())
5513 pelmVRDE->setAttribute("netAddress", strAddress);
5514 }
5515 if (hw.vrdeSettings.authType != AuthType_Null)
5516 {
5517 const char *pcszAuthType;
5518 switch (hw.vrdeSettings.authType)
5519 {
5520 case AuthType_Guest: pcszAuthType = "Guest"; break;
5521 case AuthType_External: pcszAuthType = "External"; break;
5522 default: /*case AuthType_Null:*/ pcszAuthType = "Null"; break;
5523 }
5524 pelmVRDE->setAttribute("authType", pcszAuthType);
5525 }
5526
5527 if (hw.vrdeSettings.ulAuthTimeout != 0 && hw.vrdeSettings.ulAuthTimeout != 5000)
5528 pelmVRDE->setAttribute("authTimeout", hw.vrdeSettings.ulAuthTimeout);
5529 if (hw.vrdeSettings.fAllowMultiConnection)
5530 pelmVRDE->setAttribute("allowMultiConnection", hw.vrdeSettings.fAllowMultiConnection);
5531 if (hw.vrdeSettings.fReuseSingleConnection)
5532 pelmVRDE->setAttribute("reuseSingleConnection", hw.vrdeSettings.fReuseSingleConnection);
5533
5534 if (m->sv == SettingsVersion_v1_10)
5535 {
5536 xml::ElementNode *pelmVideoChannel = pelmVRDE->createChild("VideoChannel");
5537
5538 /* In 4.0 videochannel settings were replaced with properties, so look at properties. */
5539 Utf8Str str;
5540 StringsMap::const_iterator it = hw.vrdeSettings.mapProperties.find("VideoChannel/Enabled");
5541 if (it != hw.vrdeSettings.mapProperties.end())
5542 str = it->second;
5543 bool fVideoChannel = RTStrICmp(str.c_str(), "true") == 0
5544 || RTStrCmp(str.c_str(), "1") == 0;
5545 pelmVideoChannel->setAttribute("enabled", fVideoChannel);
5546
5547 it = hw.vrdeSettings.mapProperties.find("VideoChannel/Quality");
5548 if (it != hw.vrdeSettings.mapProperties.end())
5549 str = it->second;
5550 uint32_t ulVideoChannelQuality = RTStrToUInt32(str.c_str()); /* This returns 0 on invalid string which is ok. */
5551 if (ulVideoChannelQuality == 0)
5552 ulVideoChannelQuality = 75;
5553 else
5554 ulVideoChannelQuality = RT_CLAMP(ulVideoChannelQuality, 10, 100);
5555 pelmVideoChannel->setAttribute("quality", ulVideoChannelQuality);
5556 }
5557 if (m->sv >= SettingsVersion_v1_11)
5558 {
5559 if (hw.vrdeSettings.strAuthLibrary.length())
5560 pelmVRDE->setAttribute("authLibrary", hw.vrdeSettings.strAuthLibrary);
5561 if (hw.vrdeSettings.strVrdeExtPack.isNotEmpty())
5562 pelmVRDE->setAttribute("VRDEExtPack", hw.vrdeSettings.strVrdeExtPack);
5563 if (hw.vrdeSettings.mapProperties.size() > 0)
5564 {
5565 xml::ElementNode *pelmProperties = pelmVRDE->createChild("VRDEProperties");
5566 for (StringsMap::const_iterator it = hw.vrdeSettings.mapProperties.begin();
5567 it != hw.vrdeSettings.mapProperties.end();
5568 ++it)
5569 {
5570 const Utf8Str &strName = it->first;
5571 const Utf8Str &strValue = it->second;
5572 xml::ElementNode *pelm = pelmProperties->createChild("Property");
5573 pelm->setAttribute("name", strName);
5574 pelm->setAttribute("value", strValue);
5575 }
5576 }
5577 }
5578 }
5579
5580 if (!hw.biosSettings.areDefaultSettings())
5581 {
5582 xml::ElementNode *pelmBIOS = pelmHardware->createChild("BIOS");
5583 if (!hw.biosSettings.fACPIEnabled)
5584 pelmBIOS->createChild("ACPI")->setAttribute("enabled", hw.biosSettings.fACPIEnabled);
5585 if (hw.biosSettings.fIOAPICEnabled)
5586 pelmBIOS->createChild("IOAPIC")->setAttribute("enabled", hw.biosSettings.fIOAPICEnabled);
5587 if (hw.biosSettings.apicMode != APICMode_APIC)
5588 {
5589 const char *pcszAPIC;
5590 switch (hw.biosSettings.apicMode)
5591 {
5592 case APICMode_Disabled:
5593 pcszAPIC = "Disabled";
5594 break;
5595 case APICMode_APIC:
5596 default:
5597 pcszAPIC = "APIC";
5598 break;
5599 case APICMode_X2APIC:
5600 pcszAPIC = "X2APIC";
5601 break;
5602 }
5603 pelmBIOS->createChild("APIC")->setAttribute("mode", pcszAPIC);
5604 }
5605
5606 if ( !hw.biosSettings.fLogoFadeIn
5607 || !hw.biosSettings.fLogoFadeOut
5608 || hw.biosSettings.ulLogoDisplayTime
5609 || !hw.biosSettings.strLogoImagePath.isEmpty())
5610 {
5611 xml::ElementNode *pelmLogo = pelmBIOS->createChild("Logo");
5612 pelmLogo->setAttribute("fadeIn", hw.biosSettings.fLogoFadeIn);
5613 pelmLogo->setAttribute("fadeOut", hw.biosSettings.fLogoFadeOut);
5614 pelmLogo->setAttribute("displayTime", hw.biosSettings.ulLogoDisplayTime);
5615 if (!hw.biosSettings.strLogoImagePath.isEmpty())
5616 pelmLogo->setAttribute("imagePath", hw.biosSettings.strLogoImagePath);
5617 }
5618
5619 if (hw.biosSettings.biosBootMenuMode != BIOSBootMenuMode_MessageAndMenu)
5620 {
5621 const char *pcszBootMenu;
5622 switch (hw.biosSettings.biosBootMenuMode)
5623 {
5624 case BIOSBootMenuMode_Disabled: pcszBootMenu = "Disabled"; break;
5625 case BIOSBootMenuMode_MenuOnly: pcszBootMenu = "MenuOnly"; break;
5626 default: /*BIOSBootMenuMode_MessageAndMenu*/ pcszBootMenu = "MessageAndMenu"; break;
5627 }
5628 pelmBIOS->createChild("BootMenu")->setAttribute("mode", pcszBootMenu);
5629 }
5630 if (hw.biosSettings.llTimeOffset)
5631 pelmBIOS->createChild("TimeOffset")->setAttribute("value", hw.biosSettings.llTimeOffset);
5632 if (hw.biosSettings.fPXEDebugEnabled)
5633 pelmBIOS->createChild("PXEDebug")->setAttribute("enabled", hw.biosSettings.fPXEDebugEnabled);
5634 }
5635
5636 if (m->sv < SettingsVersion_v1_9)
5637 {
5638 // settings formats before 1.9 had separate DVDDrive and FloppyDrive items under Hardware;
5639 // run thru the storage controllers to see if we have a DVD or floppy drives
5640 size_t cDVDs = 0;
5641 size_t cFloppies = 0;
5642
5643 xml::ElementNode *pelmDVD = pelmHardware->createChild("DVDDrive");
5644 xml::ElementNode *pelmFloppy = pelmHardware->createChild("FloppyDrive");
5645
5646 for (StorageControllersList::const_iterator it = hw.storage.llStorageControllers.begin();
5647 it != hw.storage.llStorageControllers.end();
5648 ++it)
5649 {
5650 const StorageController &sctl = *it;
5651 // in old settings format, the DVD drive could only have been under the IDE controller
5652 if (sctl.storageBus == StorageBus_IDE)
5653 {
5654 for (AttachedDevicesList::const_iterator it2 = sctl.llAttachedDevices.begin();
5655 it2 != sctl.llAttachedDevices.end();
5656 ++it2)
5657 {
5658 const AttachedDevice &att = *it2;
5659 if (att.deviceType == DeviceType_DVD)
5660 {
5661 if (cDVDs > 0)
5662 throw ConfigFileError(this, NULL, N_("Internal error: cannot save more than one DVD drive with old settings format"));
5663
5664 ++cDVDs;
5665
5666 pelmDVD->setAttribute("passthrough", att.fPassThrough);
5667 if (att.fTempEject)
5668 pelmDVD->setAttribute("tempeject", att.fTempEject);
5669
5670 if (!att.uuid.isZero() && att.uuid.isValid())
5671 pelmDVD->createChild("Image")->setAttribute("uuid", att.uuid.toStringCurly());
5672 else if (att.strHostDriveSrc.length())
5673 pelmDVD->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
5674 }
5675 }
5676 }
5677 else if (sctl.storageBus == StorageBus_Floppy)
5678 {
5679 size_t cFloppiesHere = sctl.llAttachedDevices.size();
5680 if (cFloppiesHere > 1)
5681 throw ConfigFileError(this, NULL, N_("Internal error: floppy controller cannot have more than one device attachment"));
5682 if (cFloppiesHere)
5683 {
5684 const AttachedDevice &att = sctl.llAttachedDevices.front();
5685 pelmFloppy->setAttribute("enabled", true);
5686
5687 if (!att.uuid.isZero() && att.uuid.isValid())
5688 pelmFloppy->createChild("Image")->setAttribute("uuid", att.uuid.toStringCurly());
5689 else if (att.strHostDriveSrc.length())
5690 pelmFloppy->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
5691 }
5692
5693 cFloppies += cFloppiesHere;
5694 }
5695 }
5696
5697 if (cFloppies == 0)
5698 pelmFloppy->setAttribute("enabled", false);
5699 else if (cFloppies > 1)
5700 throw ConfigFileError(this, NULL, N_("Internal error: cannot save more than one floppy drive with old settings format"));
5701 }
5702
5703 if (m->sv < SettingsVersion_v1_14)
5704 {
5705 bool fOhciEnabled = false;
5706 bool fEhciEnabled = false;
5707 xml::ElementNode *pelmUSB = pelmHardware->createChild("USBController");
5708
5709 for (USBControllerList::const_iterator it = hw.usbSettings.llUSBControllers.begin();
5710 it != hw.usbSettings.llUSBControllers.end();
5711 ++it)
5712 {
5713 const USBController &ctrl = *it;
5714
5715 switch (ctrl.enmType)
5716 {
5717 case USBControllerType_OHCI:
5718 fOhciEnabled = true;
5719 break;
5720 case USBControllerType_EHCI:
5721 fEhciEnabled = true;
5722 break;
5723 default:
5724 AssertMsgFailed(("Unknown USB controller type %d\n", ctrl.enmType));
5725 }
5726 }
5727
5728 pelmUSB->setAttribute("enabled", fOhciEnabled);
5729 pelmUSB->setAttribute("enabledEhci", fEhciEnabled);
5730
5731 buildUSBDeviceFilters(*pelmUSB, hw.usbSettings.llDeviceFilters, false /* fHostMode */);
5732 }
5733 else
5734 {
5735 if ( hw.usbSettings.llUSBControllers.size()
5736 || hw.usbSettings.llDeviceFilters.size())
5737 {
5738 xml::ElementNode *pelmUSB = pelmHardware->createChild("USB");
5739 if (hw.usbSettings.llUSBControllers.size())
5740 {
5741 xml::ElementNode *pelmCtrls = pelmUSB->createChild("Controllers");
5742
5743 for (USBControllerList::const_iterator it = hw.usbSettings.llUSBControllers.begin();
5744 it != hw.usbSettings.llUSBControllers.end();
5745 ++it)
5746 {
5747 const USBController &ctrl = *it;
5748 com::Utf8Str strType;
5749 xml::ElementNode *pelmCtrl = pelmCtrls->createChild("Controller");
5750
5751 switch (ctrl.enmType)
5752 {
5753 case USBControllerType_OHCI:
5754 strType = "OHCI";
5755 break;
5756 case USBControllerType_EHCI:
5757 strType = "EHCI";
5758 break;
5759 case USBControllerType_XHCI:
5760 strType = "XHCI";
5761 break;
5762 default:
5763 AssertMsgFailed(("Unknown USB controller type %d\n", ctrl.enmType));
5764 }
5765
5766 pelmCtrl->setAttribute("name", ctrl.strName);
5767 pelmCtrl->setAttribute("type", strType);
5768 }
5769 }
5770
5771 if (hw.usbSettings.llDeviceFilters.size())
5772 {
5773 xml::ElementNode *pelmFilters = pelmUSB->createChild("DeviceFilters");
5774 buildUSBDeviceFilters(*pelmFilters, hw.usbSettings.llDeviceFilters, false /* fHostMode */);
5775 }
5776 }
5777 }
5778
5779 if ( hw.llNetworkAdapters.size()
5780 && !hw.areAllNetworkAdaptersDefaultSettings(m->sv))
5781 {
5782 xml::ElementNode *pelmNetwork = pelmHardware->createChild("Network");
5783 for (NetworkAdaptersList::const_iterator it = hw.llNetworkAdapters.begin();
5784 it != hw.llNetworkAdapters.end();
5785 ++it)
5786 {
5787 const NetworkAdapter &nic = *it;
5788
5789 if (!nic.areDefaultSettings(m->sv))
5790 {
5791 xml::ElementNode *pelmAdapter = pelmNetwork->createChild("Adapter");
5792 pelmAdapter->setAttribute("slot", nic.ulSlot);
5793 if (nic.fEnabled)
5794 pelmAdapter->setAttribute("enabled", nic.fEnabled);
5795 if (!nic.strMACAddress.isEmpty())
5796 pelmAdapter->setAttribute("MACAddress", nic.strMACAddress);
5797 if ( (m->sv >= SettingsVersion_v1_16 && !nic.fCableConnected)
5798 || (m->sv < SettingsVersion_v1_16 && nic.fCableConnected))
5799 pelmAdapter->setAttribute("cable", nic.fCableConnected);
5800 if (nic.ulLineSpeed)
5801 pelmAdapter->setAttribute("speed", nic.ulLineSpeed);
5802 if (nic.ulBootPriority != 0)
5803 pelmAdapter->setAttribute("bootPriority", nic.ulBootPriority);
5804 if (nic.fTraceEnabled)
5805 {
5806 pelmAdapter->setAttribute("trace", nic.fTraceEnabled);
5807 pelmAdapter->setAttribute("tracefile", nic.strTraceFile);
5808 }
5809 if (nic.strBandwidthGroup.isNotEmpty())
5810 pelmAdapter->setAttribute("bandwidthGroup", nic.strBandwidthGroup);
5811
5812 const char *pszPolicy;
5813 switch (nic.enmPromiscModePolicy)
5814 {
5815 case NetworkAdapterPromiscModePolicy_Deny: pszPolicy = NULL; break;
5816 case NetworkAdapterPromiscModePolicy_AllowNetwork: pszPolicy = "AllowNetwork"; break;
5817 case NetworkAdapterPromiscModePolicy_AllowAll: pszPolicy = "AllowAll"; break;
5818 default: pszPolicy = NULL; AssertFailed(); break;
5819 }
5820 if (pszPolicy)
5821 pelmAdapter->setAttribute("promiscuousModePolicy", pszPolicy);
5822
5823 if ( (m->sv >= SettingsVersion_v1_16 && nic.type != NetworkAdapterType_Am79C973)
5824 || (m->sv < SettingsVersion_v1_16 && nic.type != NetworkAdapterType_Am79C970A))
5825 {
5826 const char *pcszType;
5827 switch (nic.type)
5828 {
5829 case NetworkAdapterType_Am79C973: pcszType = "Am79C973"; break;
5830 case NetworkAdapterType_I82540EM: pcszType = "82540EM"; break;
5831 case NetworkAdapterType_I82543GC: pcszType = "82543GC"; break;
5832 case NetworkAdapterType_I82545EM: pcszType = "82545EM"; break;
5833 case NetworkAdapterType_Virtio: pcszType = "virtio"; break;
5834 default: /*case NetworkAdapterType_Am79C970A:*/ pcszType = "Am79C970A"; break;
5835 }
5836 pelmAdapter->setAttribute("type", pcszType);
5837 }
5838
5839 xml::ElementNode *pelmNAT;
5840 if (m->sv < SettingsVersion_v1_10)
5841 {
5842 switch (nic.mode)
5843 {
5844 case NetworkAttachmentType_NAT:
5845 pelmNAT = pelmAdapter->createChild("NAT");
5846 if (nic.nat.strNetwork.length())
5847 pelmNAT->setAttribute("network", nic.nat.strNetwork);
5848 break;
5849
5850 case NetworkAttachmentType_Bridged:
5851 pelmAdapter->createChild("BridgedInterface")->setAttribute("name", nic.strBridgedName);
5852 break;
5853
5854 case NetworkAttachmentType_Internal:
5855 pelmAdapter->createChild("InternalNetwork")->setAttribute("name", nic.strInternalNetworkName);
5856 break;
5857
5858 case NetworkAttachmentType_HostOnly:
5859 pelmAdapter->createChild("HostOnlyInterface")->setAttribute("name", nic.strHostOnlyName);
5860 break;
5861
5862 default: /*case NetworkAttachmentType_Null:*/
5863 break;
5864 }
5865 }
5866 else
5867 {
5868 /* m->sv >= SettingsVersion_v1_10 */
5869 if (!nic.areDisabledDefaultSettings())
5870 {
5871 xml::ElementNode *pelmDisabledNode = pelmAdapter->createChild("DisabledModes");
5872 if (nic.mode != NetworkAttachmentType_NAT)
5873 buildNetworkXML(NetworkAttachmentType_NAT, false, *pelmDisabledNode, nic);
5874 if (nic.mode != NetworkAttachmentType_Bridged)
5875 buildNetworkXML(NetworkAttachmentType_Bridged, false, *pelmDisabledNode, nic);
5876 if (nic.mode != NetworkAttachmentType_Internal)
5877 buildNetworkXML(NetworkAttachmentType_Internal, false, *pelmDisabledNode, nic);
5878 if (nic.mode != NetworkAttachmentType_HostOnly)
5879 buildNetworkXML(NetworkAttachmentType_HostOnly, false, *pelmDisabledNode, nic);
5880 if (nic.mode != NetworkAttachmentType_Generic)
5881 buildNetworkXML(NetworkAttachmentType_Generic, false, *pelmDisabledNode, nic);
5882 if (nic.mode != NetworkAttachmentType_NATNetwork)
5883 buildNetworkXML(NetworkAttachmentType_NATNetwork, false, *pelmDisabledNode, nic);
5884 }
5885 buildNetworkXML(nic.mode, true, *pelmAdapter, nic);
5886 }
5887 }
5888 }
5889 }
5890
5891 if (hw.llSerialPorts.size())
5892 {
5893 xml::ElementNode *pelmPorts = pelmHardware->createChild("UART");
5894 for (SerialPortsList::const_iterator it = hw.llSerialPorts.begin();
5895 it != hw.llSerialPorts.end();
5896 ++it)
5897 {
5898 const SerialPort &port = *it;
5899 xml::ElementNode *pelmPort = pelmPorts->createChild("Port");
5900 pelmPort->setAttribute("slot", port.ulSlot);
5901 pelmPort->setAttribute("enabled", port.fEnabled);
5902 pelmPort->setAttributeHex("IOBase", port.ulIOBase);
5903 pelmPort->setAttribute("IRQ", port.ulIRQ);
5904
5905 const char *pcszHostMode;
5906 switch (port.portMode)
5907 {
5908 case PortMode_HostPipe: pcszHostMode = "HostPipe"; break;
5909 case PortMode_HostDevice: pcszHostMode = "HostDevice"; break;
5910 case PortMode_TCP: pcszHostMode = "TCP"; break;
5911 case PortMode_RawFile: pcszHostMode = "RawFile"; break;
5912 default: /*case PortMode_Disconnected:*/ pcszHostMode = "Disconnected"; break;
5913 }
5914 switch (port.portMode)
5915 {
5916 case PortMode_TCP:
5917 case PortMode_HostPipe:
5918 pelmPort->setAttribute("server", port.fServer);
5919 /* fall thru */
5920 case PortMode_HostDevice:
5921 case PortMode_RawFile:
5922 pelmPort->setAttribute("path", port.strPath);
5923 break;
5924
5925 default:
5926 break;
5927 }
5928 pelmPort->setAttribute("hostMode", pcszHostMode);
5929 }
5930 }
5931
5932 if (hw.llParallelPorts.size())
5933 {
5934 xml::ElementNode *pelmPorts = pelmHardware->createChild("LPT");
5935 for (ParallelPortsList::const_iterator it = hw.llParallelPorts.begin();
5936 it != hw.llParallelPorts.end();
5937 ++it)
5938 {
5939 const ParallelPort &port = *it;
5940 xml::ElementNode *pelmPort = pelmPorts->createChild("Port");
5941 pelmPort->setAttribute("slot", port.ulSlot);
5942 pelmPort->setAttribute("enabled", port.fEnabled);
5943 pelmPort->setAttributeHex("IOBase", port.ulIOBase);
5944 pelmPort->setAttribute("IRQ", port.ulIRQ);
5945 if (port.strPath.length())
5946 pelmPort->setAttribute("path", port.strPath);
5947 }
5948 }
5949
5950 /* Always write the AudioAdapter config, intentionally not checking if
5951 * the settings are at the default, because that would be problematic
5952 * for the configured host driver type, which would automatically change
5953 * if the default host driver is detected differently. */
5954 {
5955 xml::ElementNode *pelmAudio = pelmHardware->createChild("AudioAdapter");
5956
5957 const char *pcszController;
5958 switch (hw.audioAdapter.controllerType)
5959 {
5960 case AudioControllerType_SB16:
5961 pcszController = "SB16";
5962 break;
5963 case AudioControllerType_HDA:
5964 if (m->sv >= SettingsVersion_v1_11)
5965 {
5966 pcszController = "HDA";
5967 break;
5968 }
5969 /* fall through */
5970 case AudioControllerType_AC97:
5971 default:
5972 pcszController = NULL;
5973 break;
5974 }
5975 if (pcszController)
5976 pelmAudio->setAttribute("controller", pcszController);
5977
5978 const char *pcszCodec;
5979 switch (hw.audioAdapter.codecType)
5980 {
5981 /* Only write out the setting for non-default AC'97 codec
5982 * and leave the rest alone.
5983 */
5984#if 0
5985 case AudioCodecType_SB16:
5986 pcszCodec = "SB16";
5987 break;
5988 case AudioCodecType_STAC9221:
5989 pcszCodec = "STAC9221";
5990 break;
5991 case AudioCodecType_STAC9700:
5992 pcszCodec = "STAC9700";
5993 break;
5994#endif
5995 case AudioCodecType_AD1980:
5996 pcszCodec = "AD1980";
5997 break;
5998 default:
5999 /* Don't write out anything if unknown. */
6000 pcszCodec = NULL;
6001 }
6002 if (pcszCodec)
6003 pelmAudio->setAttribute("codec", pcszCodec);
6004
6005 const char *pcszDriver;
6006 switch (hw.audioAdapter.driverType)
6007 {
6008 case AudioDriverType_WinMM: pcszDriver = "WinMM"; break;
6009 case AudioDriverType_DirectSound: pcszDriver = "DirectSound"; break;
6010 case AudioDriverType_SolAudio: pcszDriver = "SolAudio"; break;
6011 case AudioDriverType_ALSA: pcszDriver = "ALSA"; break;
6012 case AudioDriverType_Pulse: pcszDriver = "Pulse"; break;
6013 case AudioDriverType_OSS: pcszDriver = "OSS"; break;
6014 case AudioDriverType_CoreAudio: pcszDriver = "CoreAudio"; break;
6015 case AudioDriverType_MMPM: pcszDriver = "MMPM"; break;
6016 default: /*case AudioDriverType_Null:*/ pcszDriver = "Null"; break;
6017 }
6018 /* Deliberately have the audio driver explicitly in the config file,
6019 * otherwise an unwritten default driver triggers auto-detection. */
6020 pelmAudio->setAttribute("driver", pcszDriver);
6021
6022 if (hw.audioAdapter.fEnabled || m->sv < SettingsVersion_v1_16)
6023 pelmAudio->setAttribute("enabled", hw.audioAdapter.fEnabled);
6024
6025 if (m->sv >= SettingsVersion_v1_15 && hw.audioAdapter.properties.size() > 0)
6026 {
6027 for (StringsMap::const_iterator it = hw.audioAdapter.properties.begin();
6028 it != hw.audioAdapter.properties.end();
6029 ++it)
6030 {
6031 const Utf8Str &strName = it->first;
6032 const Utf8Str &strValue = it->second;
6033 xml::ElementNode *pelm = pelmAudio->createChild("Property");
6034 pelm->setAttribute("name", strName);
6035 pelm->setAttribute("value", strValue);
6036 }
6037 }
6038 }
6039
6040 if (m->sv >= SettingsVersion_v1_10 && machineUserData.fRTCUseUTC)
6041 {
6042 xml::ElementNode *pelmRTC = pelmHardware->createChild("RTC");
6043 pelmRTC->setAttribute("localOrUTC", machineUserData.fRTCUseUTC ? "UTC" : "local");
6044 }
6045
6046 if (hw.llSharedFolders.size())
6047 {
6048 xml::ElementNode *pelmSharedFolders = pelmHardware->createChild("SharedFolders");
6049 for (SharedFoldersList::const_iterator it = hw.llSharedFolders.begin();
6050 it != hw.llSharedFolders.end();
6051 ++it)
6052 {
6053 const SharedFolder &sf = *it;
6054 xml::ElementNode *pelmThis = pelmSharedFolders->createChild("SharedFolder");
6055 pelmThis->setAttribute("name", sf.strName);
6056 pelmThis->setAttribute("hostPath", sf.strHostPath);
6057 pelmThis->setAttribute("writable", sf.fWritable);
6058 pelmThis->setAttribute("autoMount", sf.fAutoMount);
6059 }
6060 }
6061
6062 if (hw.clipboardMode != ClipboardMode_Disabled)
6063 {
6064 xml::ElementNode *pelmClip = pelmHardware->createChild("Clipboard");
6065 const char *pcszClip;
6066 switch (hw.clipboardMode)
6067 {
6068 default: /*case ClipboardMode_Disabled:*/ pcszClip = "Disabled"; break;
6069 case ClipboardMode_HostToGuest: pcszClip = "HostToGuest"; break;
6070 case ClipboardMode_GuestToHost: pcszClip = "GuestToHost"; break;
6071 case ClipboardMode_Bidirectional: pcszClip = "Bidirectional"; break;
6072 }
6073 pelmClip->setAttribute("mode", pcszClip);
6074 }
6075
6076 if (hw.dndMode != DnDMode_Disabled)
6077 {
6078 xml::ElementNode *pelmDragAndDrop = pelmHardware->createChild("DragAndDrop");
6079 const char *pcszDragAndDrop;
6080 switch (hw.dndMode)
6081 {
6082 default: /*case DnDMode_Disabled:*/ pcszDragAndDrop = "Disabled"; break;
6083 case DnDMode_HostToGuest: pcszDragAndDrop = "HostToGuest"; break;
6084 case DnDMode_GuestToHost: pcszDragAndDrop = "GuestToHost"; break;
6085 case DnDMode_Bidirectional: pcszDragAndDrop = "Bidirectional"; break;
6086 }
6087 pelmDragAndDrop->setAttribute("mode", pcszDragAndDrop);
6088 }
6089
6090 if ( m->sv >= SettingsVersion_v1_10
6091 && !hw.ioSettings.areDefaultSettings())
6092 {
6093 xml::ElementNode *pelmIO = pelmHardware->createChild("IO");
6094 xml::ElementNode *pelmIOCache;
6095
6096 if (!hw.ioSettings.areDefaultSettings())
6097 {
6098 pelmIOCache = pelmIO->createChild("IoCache");
6099 if (!hw.ioSettings.fIOCacheEnabled)
6100 pelmIOCache->setAttribute("enabled", hw.ioSettings.fIOCacheEnabled);
6101 if (hw.ioSettings.ulIOCacheSize != 5)
6102 pelmIOCache->setAttribute("size", hw.ioSettings.ulIOCacheSize);
6103 }
6104
6105 if ( m->sv >= SettingsVersion_v1_11
6106 && hw.ioSettings.llBandwidthGroups.size())
6107 {
6108 xml::ElementNode *pelmBandwidthGroups = pelmIO->createChild("BandwidthGroups");
6109 for (BandwidthGroupList::const_iterator it = hw.ioSettings.llBandwidthGroups.begin();
6110 it != hw.ioSettings.llBandwidthGroups.end();
6111 ++it)
6112 {
6113 const BandwidthGroup &gr = *it;
6114 const char *pcszType;
6115 xml::ElementNode *pelmThis = pelmBandwidthGroups->createChild("BandwidthGroup");
6116 pelmThis->setAttribute("name", gr.strName);
6117 switch (gr.enmType)
6118 {
6119 case BandwidthGroupType_Network: pcszType = "Network"; break;
6120 default: /* BandwidthGrouptype_Disk */ pcszType = "Disk"; break;
6121 }
6122 pelmThis->setAttribute("type", pcszType);
6123 if (m->sv >= SettingsVersion_v1_13)
6124 pelmThis->setAttribute("maxBytesPerSec", gr.cMaxBytesPerSec);
6125 else
6126 pelmThis->setAttribute("maxMbPerSec", gr.cMaxBytesPerSec / _1M);
6127 }
6128 }
6129 }
6130
6131 if ( m->sv >= SettingsVersion_v1_12
6132 && hw.pciAttachments.size())
6133 {
6134 xml::ElementNode *pelmPCI = pelmHardware->createChild("HostPci");
6135 xml::ElementNode *pelmPCIDevices = pelmPCI->createChild("Devices");
6136
6137 for (HostPCIDeviceAttachmentList::const_iterator it = hw.pciAttachments.begin();
6138 it != hw.pciAttachments.end();
6139 ++it)
6140 {
6141 const HostPCIDeviceAttachment &hpda = *it;
6142
6143 xml::ElementNode *pelmThis = pelmPCIDevices->createChild("Device");
6144
6145 pelmThis->setAttribute("host", hpda.uHostAddress);
6146 pelmThis->setAttribute("guest", hpda.uGuestAddress);
6147 pelmThis->setAttribute("name", hpda.strDeviceName);
6148 }
6149 }
6150
6151 if ( m->sv >= SettingsVersion_v1_12
6152 && hw.fEmulatedUSBCardReader)
6153 {
6154 xml::ElementNode *pelmEmulatedUSB = pelmHardware->createChild("EmulatedUSB");
6155
6156 xml::ElementNode *pelmCardReader = pelmEmulatedUSB->createChild("CardReader");
6157 pelmCardReader->setAttribute("enabled", hw.fEmulatedUSBCardReader);
6158 }
6159
6160 if ( m->sv >= SettingsVersion_v1_14
6161 && !hw.strDefaultFrontend.isEmpty())
6162 {
6163 xml::ElementNode *pelmFrontend = pelmHardware->createChild("Frontend");
6164 xml::ElementNode *pelmDefault = pelmFrontend->createChild("Default");
6165 pelmDefault->setAttribute("type", hw.strDefaultFrontend);
6166 }
6167
6168 if (hw.ulMemoryBalloonSize)
6169 {
6170 xml::ElementNode *pelmGuest = pelmHardware->createChild("Guest");
6171 pelmGuest->setAttribute("memoryBalloonSize", hw.ulMemoryBalloonSize);
6172 }
6173
6174 if (hw.llGuestProperties.size())
6175 {
6176 xml::ElementNode *pelmGuestProps = pelmHardware->createChild("GuestProperties");
6177 for (GuestPropertiesList::const_iterator it = hw.llGuestProperties.begin();
6178 it != hw.llGuestProperties.end();
6179 ++it)
6180 {
6181 const GuestProperty &prop = *it;
6182 xml::ElementNode *pelmProp = pelmGuestProps->createChild("GuestProperty");
6183 pelmProp->setAttribute("name", prop.strName);
6184 pelmProp->setAttribute("value", prop.strValue);
6185 pelmProp->setAttribute("timestamp", prop.timestamp);
6186 pelmProp->setAttribute("flags", prop.strFlags);
6187 }
6188 }
6189
6190 /** @todo In the future (6.0?) place the storage controllers under \<Hardware\>, because
6191 * this is where it always should've been. What else than hardware are they? */
6192 xml::ElementNode &elmStorageParent = (m->sv > SettingsVersion_Future) ? *pelmHardware : elmParent;
6193 buildStorageControllersXML(elmStorageParent,
6194 hw.storage,
6195 !!(fl & BuildMachineXML_SkipRemovableMedia),
6196 pllElementsWithUuidAttributes);
6197}
6198
6199/**
6200 * Fill a \<Network\> node. Only relevant for XML version >= v1_10.
6201 * @param mode
6202 * @param fEnabled
6203 * @param elmParent
6204 * @param nic
6205 */
6206void MachineConfigFile::buildNetworkXML(NetworkAttachmentType_T mode,
6207 bool fEnabled,
6208 xml::ElementNode &elmParent,
6209 const NetworkAdapter &nic)
6210{
6211 switch (mode)
6212 {
6213 case NetworkAttachmentType_NAT:
6214 // For the currently active network attachment type we have to
6215 // generate the tag, otherwise the attachment type is lost.
6216 if (fEnabled || !nic.nat.areDefaultSettings())
6217 {
6218 xml::ElementNode *pelmNAT = elmParent.createChild("NAT");
6219
6220 if (!nic.nat.areDefaultSettings())
6221 {
6222 if (nic.nat.strNetwork.length())
6223 pelmNAT->setAttribute("network", nic.nat.strNetwork);
6224 if (nic.nat.strBindIP.length())
6225 pelmNAT->setAttribute("hostip", nic.nat.strBindIP);
6226 if (nic.nat.u32Mtu)
6227 pelmNAT->setAttribute("mtu", nic.nat.u32Mtu);
6228 if (nic.nat.u32SockRcv)
6229 pelmNAT->setAttribute("sockrcv", nic.nat.u32SockRcv);
6230 if (nic.nat.u32SockSnd)
6231 pelmNAT->setAttribute("socksnd", nic.nat.u32SockSnd);
6232 if (nic.nat.u32TcpRcv)
6233 pelmNAT->setAttribute("tcprcv", nic.nat.u32TcpRcv);
6234 if (nic.nat.u32TcpSnd)
6235 pelmNAT->setAttribute("tcpsnd", nic.nat.u32TcpSnd);
6236 if (!nic.nat.areDNSDefaultSettings())
6237 {
6238 xml::ElementNode *pelmDNS = pelmNAT->createChild("DNS");
6239 if (!nic.nat.fDNSPassDomain)
6240 pelmDNS->setAttribute("pass-domain", nic.nat.fDNSPassDomain);
6241 if (nic.nat.fDNSProxy)
6242 pelmDNS->setAttribute("use-proxy", nic.nat.fDNSProxy);
6243 if (nic.nat.fDNSUseHostResolver)
6244 pelmDNS->setAttribute("use-host-resolver", nic.nat.fDNSUseHostResolver);
6245 }
6246
6247 if (!nic.nat.areAliasDefaultSettings())
6248 {
6249 xml::ElementNode *pelmAlias = pelmNAT->createChild("Alias");
6250 if (nic.nat.fAliasLog)
6251 pelmAlias->setAttribute("logging", nic.nat.fAliasLog);
6252 if (nic.nat.fAliasProxyOnly)
6253 pelmAlias->setAttribute("proxy-only", nic.nat.fAliasProxyOnly);
6254 if (nic.nat.fAliasUseSamePorts)
6255 pelmAlias->setAttribute("use-same-ports", nic.nat.fAliasUseSamePorts);
6256 }
6257
6258 if (!nic.nat.areTFTPDefaultSettings())
6259 {
6260 xml::ElementNode *pelmTFTP;
6261 pelmTFTP = pelmNAT->createChild("TFTP");
6262 if (nic.nat.strTFTPPrefix.length())
6263 pelmTFTP->setAttribute("prefix", nic.nat.strTFTPPrefix);
6264 if (nic.nat.strTFTPBootFile.length())
6265 pelmTFTP->setAttribute("boot-file", nic.nat.strTFTPBootFile);
6266 if (nic.nat.strTFTPNextServer.length())
6267 pelmTFTP->setAttribute("next-server", nic.nat.strTFTPNextServer);
6268 }
6269 buildNATForwardRulesMap(*pelmNAT, nic.nat.mapRules);
6270 }
6271 }
6272 break;
6273
6274 case NetworkAttachmentType_Bridged:
6275 // For the currently active network attachment type we have to
6276 // generate the tag, otherwise the attachment type is lost.
6277 if (fEnabled || !nic.strBridgedName.isEmpty())
6278 {
6279 xml::ElementNode *pelmMode = elmParent.createChild("BridgedInterface");
6280 if (!nic.strBridgedName.isEmpty())
6281 pelmMode->setAttribute("name", nic.strBridgedName);
6282 }
6283 break;
6284
6285 case NetworkAttachmentType_Internal:
6286 // For the currently active network attachment type we have to
6287 // generate the tag, otherwise the attachment type is lost.
6288 if (fEnabled || !nic.strInternalNetworkName.isEmpty())
6289 {
6290 xml::ElementNode *pelmMode = elmParent.createChild("InternalNetwork");
6291 if (!nic.strInternalNetworkName.isEmpty())
6292 pelmMode->setAttribute("name", nic.strInternalNetworkName);
6293 }
6294 break;
6295
6296 case NetworkAttachmentType_HostOnly:
6297 // For the currently active network attachment type we have to
6298 // generate the tag, otherwise the attachment type is lost.
6299 if (fEnabled || !nic.strHostOnlyName.isEmpty())
6300 {
6301 xml::ElementNode *pelmMode = elmParent.createChild("HostOnlyInterface");
6302 if (!nic.strHostOnlyName.isEmpty())
6303 pelmMode->setAttribute("name", nic.strHostOnlyName);
6304 }
6305 break;
6306
6307 case NetworkAttachmentType_Generic:
6308 // For the currently active network attachment type we have to
6309 // generate the tag, otherwise the attachment type is lost.
6310 if (fEnabled || !nic.areGenericDriverDefaultSettings())
6311 {
6312 xml::ElementNode *pelmMode = elmParent.createChild("GenericInterface");
6313 if (!nic.areGenericDriverDefaultSettings())
6314 {
6315 pelmMode->setAttribute("driver", nic.strGenericDriver);
6316 for (StringsMap::const_iterator it = nic.genericProperties.begin();
6317 it != nic.genericProperties.end();
6318 ++it)
6319 {
6320 xml::ElementNode *pelmProp = pelmMode->createChild("Property");
6321 pelmProp->setAttribute("name", it->first);
6322 pelmProp->setAttribute("value", it->second);
6323 }
6324 }
6325 }
6326 break;
6327
6328 case NetworkAttachmentType_NATNetwork:
6329 // For the currently active network attachment type we have to
6330 // generate the tag, otherwise the attachment type is lost.
6331 if (fEnabled || !nic.strNATNetworkName.isEmpty())
6332 {
6333 xml::ElementNode *pelmMode = elmParent.createChild("NATNetwork");
6334 if (!nic.strNATNetworkName.isEmpty())
6335 pelmMode->setAttribute("name", nic.strNATNetworkName);
6336 }
6337 break;
6338
6339 default: /*case NetworkAttachmentType_Null:*/
6340 break;
6341 }
6342}
6343
6344/**
6345 * Creates a \<StorageControllers\> node under elmParent and then writes out the XML
6346 * keys under that. Called for both the \<Machine\> node and for snapshots.
6347 * @param elmParent
6348 * @param st
6349 * @param fSkipRemovableMedia If true, DVD and floppy attachments are skipped and
6350 * an empty drive is always written instead. This is for the OVF export case.
6351 * This parameter is ignored unless the settings version is at least v1.9, which
6352 * is always the case when this gets called for OVF export.
6353 * @param pllElementsWithUuidAttributes If not NULL, must point to a list of element node
6354 * pointers to which we will append all elements that we created here that contain
6355 * UUID attributes. This allows the OVF export code to quickly replace the internal
6356 * media UUIDs with the UUIDs of the media that were exported.
6357 */
6358void MachineConfigFile::buildStorageControllersXML(xml::ElementNode &elmParent,
6359 const Storage &st,
6360 bool fSkipRemovableMedia,
6361 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes)
6362{
6363 if (!st.llStorageControllers.size())
6364 return;
6365 xml::ElementNode *pelmStorageControllers = elmParent.createChild("StorageControllers");
6366
6367 for (StorageControllersList::const_iterator it = st.llStorageControllers.begin();
6368 it != st.llStorageControllers.end();
6369 ++it)
6370 {
6371 const StorageController &sc = *it;
6372
6373 if ( (m->sv < SettingsVersion_v1_9)
6374 && (sc.controllerType == StorageControllerType_I82078)
6375 )
6376 // floppy controller already got written into <Hardware>/<FloppyController> in buildHardwareXML()
6377 // for pre-1.9 settings
6378 continue;
6379
6380 xml::ElementNode *pelmController = pelmStorageControllers->createChild("StorageController");
6381 com::Utf8Str name = sc.strName;
6382 if (m->sv < SettingsVersion_v1_8)
6383 {
6384 // pre-1.8 settings use shorter controller names, they are
6385 // expanded when reading the settings
6386 if (name == "IDE Controller")
6387 name = "IDE";
6388 else if (name == "SATA Controller")
6389 name = "SATA";
6390 else if (name == "SCSI Controller")
6391 name = "SCSI";
6392 }
6393 pelmController->setAttribute("name", sc.strName);
6394
6395 const char *pcszType;
6396 switch (sc.controllerType)
6397 {
6398 case StorageControllerType_IntelAhci: pcszType = "AHCI"; break;
6399 case StorageControllerType_LsiLogic: pcszType = "LsiLogic"; break;
6400 case StorageControllerType_BusLogic: pcszType = "BusLogic"; break;
6401 case StorageControllerType_PIIX4: pcszType = "PIIX4"; break;
6402 case StorageControllerType_ICH6: pcszType = "ICH6"; break;
6403 case StorageControllerType_I82078: pcszType = "I82078"; break;
6404 case StorageControllerType_LsiLogicSas: pcszType = "LsiLogicSas"; break;
6405 case StorageControllerType_USB: pcszType = "USB"; break;
6406 case StorageControllerType_NVMe: pcszType = "NVMe"; break;
6407 default: /*case StorageControllerType_PIIX3:*/ pcszType = "PIIX3"; break;
6408 }
6409 pelmController->setAttribute("type", pcszType);
6410
6411 pelmController->setAttribute("PortCount", sc.ulPortCount);
6412
6413 if (m->sv >= SettingsVersion_v1_9)
6414 if (sc.ulInstance)
6415 pelmController->setAttribute("Instance", sc.ulInstance);
6416
6417 if (m->sv >= SettingsVersion_v1_10)
6418 pelmController->setAttribute("useHostIOCache", sc.fUseHostIOCache);
6419
6420 if (m->sv >= SettingsVersion_v1_11)
6421 pelmController->setAttribute("Bootable", sc.fBootable);
6422
6423 if (sc.controllerType == StorageControllerType_IntelAhci)
6424 {
6425 pelmController->setAttribute("IDE0MasterEmulationPort", 0);
6426 pelmController->setAttribute("IDE0SlaveEmulationPort", 1);
6427 pelmController->setAttribute("IDE1MasterEmulationPort", 2);
6428 pelmController->setAttribute("IDE1SlaveEmulationPort", 3);
6429 }
6430
6431 for (AttachedDevicesList::const_iterator it2 = sc.llAttachedDevices.begin();
6432 it2 != sc.llAttachedDevices.end();
6433 ++it2)
6434 {
6435 const AttachedDevice &att = *it2;
6436
6437 // For settings version before 1.9, DVDs and floppies are in hardware, not storage controllers,
6438 // so we shouldn't write them here; we only get here for DVDs though because we ruled out
6439 // the floppy controller at the top of the loop
6440 if ( att.deviceType == DeviceType_DVD
6441 && m->sv < SettingsVersion_v1_9
6442 )
6443 continue;
6444
6445 xml::ElementNode *pelmDevice = pelmController->createChild("AttachedDevice");
6446
6447 pcszType = NULL;
6448
6449 switch (att.deviceType)
6450 {
6451 case DeviceType_HardDisk:
6452 pcszType = "HardDisk";
6453 if (att.fNonRotational)
6454 pelmDevice->setAttribute("nonrotational", att.fNonRotational);
6455 if (att.fDiscard)
6456 pelmDevice->setAttribute("discard", att.fDiscard);
6457 break;
6458
6459 case DeviceType_DVD:
6460 pcszType = "DVD";
6461 pelmDevice->setAttribute("passthrough", att.fPassThrough);
6462 if (att.fTempEject)
6463 pelmDevice->setAttribute("tempeject", att.fTempEject);
6464 break;
6465
6466 case DeviceType_Floppy:
6467 pcszType = "Floppy";
6468 break;
6469
6470 default: break; /* Shut up MSC. */
6471 }
6472
6473 pelmDevice->setAttribute("type", pcszType);
6474
6475 if (m->sv >= SettingsVersion_v1_15)
6476 pelmDevice->setAttribute("hotpluggable", att.fHotPluggable);
6477
6478 pelmDevice->setAttribute("port", att.lPort);
6479 pelmDevice->setAttribute("device", att.lDevice);
6480
6481 if (att.strBwGroup.length())
6482 pelmDevice->setAttribute("bandwidthGroup", att.strBwGroup);
6483
6484 // attached image, if any
6485 if (!att.uuid.isZero()
6486 && att.uuid.isValid()
6487 && (att.deviceType == DeviceType_HardDisk
6488 || !fSkipRemovableMedia
6489 )
6490 )
6491 {
6492 xml::ElementNode *pelmImage = pelmDevice->createChild("Image");
6493 pelmImage->setAttribute("uuid", att.uuid.toStringCurly());
6494
6495 // if caller wants a list of UUID elements, give it to them
6496 if (pllElementsWithUuidAttributes)
6497 pllElementsWithUuidAttributes->push_back(pelmImage);
6498 }
6499 else if ( (m->sv >= SettingsVersion_v1_9)
6500 && (att.strHostDriveSrc.length())
6501 )
6502 pelmDevice->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
6503 }
6504 }
6505}
6506
6507/**
6508 * Creates a \<Debugging\> node under elmParent and then writes out the XML
6509 * keys under that. Called for both the \<Machine\> node and for snapshots.
6510 *
6511 * @param pElmParent Pointer to the parent element.
6512 * @param pDbg Pointer to the debugging settings.
6513 */
6514void MachineConfigFile::buildDebuggingXML(xml::ElementNode *pElmParent, const Debugging *pDbg)
6515{
6516 if (m->sv < SettingsVersion_v1_13 || pDbg->areDefaultSettings())
6517 return;
6518
6519 xml::ElementNode *pElmDebugging = pElmParent->createChild("Debugging");
6520 xml::ElementNode *pElmTracing = pElmDebugging->createChild("Tracing");
6521 pElmTracing->setAttribute("enabled", pDbg->fTracingEnabled);
6522 pElmTracing->setAttribute("allowTracingToAccessVM", pDbg->fAllowTracingToAccessVM);
6523 pElmTracing->setAttribute("config", pDbg->strTracingConfig);
6524}
6525
6526/**
6527 * Creates a \<Autostart\> node under elmParent and then writes out the XML
6528 * keys under that. Called for both the \<Machine\> node and for snapshots.
6529 *
6530 * @param pElmParent Pointer to the parent element.
6531 * @param pAutostart Pointer to the autostart settings.
6532 */
6533void MachineConfigFile::buildAutostartXML(xml::ElementNode *pElmParent, const Autostart *pAutostart)
6534{
6535 const char *pcszAutostop = NULL;
6536
6537 if (m->sv < SettingsVersion_v1_13 || pAutostart->areDefaultSettings())
6538 return;
6539
6540 xml::ElementNode *pElmAutostart = pElmParent->createChild("Autostart");
6541 pElmAutostart->setAttribute("enabled", pAutostart->fAutostartEnabled);
6542 pElmAutostart->setAttribute("delay", pAutostart->uAutostartDelay);
6543
6544 switch (pAutostart->enmAutostopType)
6545 {
6546 case AutostopType_Disabled: pcszAutostop = "Disabled"; break;
6547 case AutostopType_SaveState: pcszAutostop = "SaveState"; break;
6548 case AutostopType_PowerOff: pcszAutostop = "PowerOff"; break;
6549 case AutostopType_AcpiShutdown: pcszAutostop = "AcpiShutdown"; break;
6550 default: Assert(false); pcszAutostop = "Disabled"; break;
6551 }
6552 pElmAutostart->setAttribute("autostop", pcszAutostop);
6553}
6554
6555/**
6556 * Creates a \<Groups\> node under elmParent and then writes out the XML
6557 * keys under that. Called for the \<Machine\> node only.
6558 *
6559 * @param pElmParent Pointer to the parent element.
6560 * @param pllGroups Pointer to the groups list.
6561 */
6562void MachineConfigFile::buildGroupsXML(xml::ElementNode *pElmParent, const StringsList *pllGroups)
6563{
6564 if ( m->sv < SettingsVersion_v1_13 || pllGroups->size() == 0
6565 || (pllGroups->size() == 1 && pllGroups->front() == "/"))
6566 return;
6567
6568 xml::ElementNode *pElmGroups = pElmParent->createChild("Groups");
6569 for (StringsList::const_iterator it = pllGroups->begin();
6570 it != pllGroups->end();
6571 ++it)
6572 {
6573 const Utf8Str &group = *it;
6574 xml::ElementNode *pElmGroup = pElmGroups->createChild("Group");
6575 pElmGroup->setAttribute("name", group);
6576 }
6577}
6578
6579/**
6580 * Writes a single snapshot into the DOM tree. Initially this gets called from MachineConfigFile::write()
6581 * for the root snapshot of a machine, if present; elmParent then points to the \<Snapshots\> node under the
6582 * \<Machine\> node to which \<Snapshot\> must be added. This may then recurse for child snapshots.
6583 *
6584 * @param depth
6585 * @param elmParent
6586 * @param snap
6587 */
6588void MachineConfigFile::buildSnapshotXML(uint32_t depth,
6589 xml::ElementNode &elmParent,
6590 const Snapshot &snap)
6591{
6592 if (depth > SETTINGS_SNAPSHOT_DEPTH_MAX)
6593 throw ConfigFileError(this, NULL, N_("Maximum snapshot tree depth of %u exceeded"), SETTINGS_SNAPSHOT_DEPTH_MAX);
6594
6595 xml::ElementNode *pelmSnapshot = elmParent.createChild("Snapshot");
6596
6597 pelmSnapshot->setAttribute("uuid", snap.uuid.toStringCurly());
6598 pelmSnapshot->setAttribute("name", snap.strName);
6599 pelmSnapshot->setAttribute("timeStamp", stringifyTimestamp(snap.timestamp));
6600
6601 if (snap.strStateFile.length())
6602 pelmSnapshot->setAttributePath("stateFile", snap.strStateFile);
6603
6604 if (snap.strDescription.length())
6605 pelmSnapshot->createChild("Description")->addContent(snap.strDescription);
6606
6607 // We only skip removable media for OVF, but OVF never includes snapshots.
6608 buildHardwareXML(*pelmSnapshot, snap.hardware, 0 /* fl */, NULL /* pllElementsWithUuidAttributes */);
6609 buildDebuggingXML(pelmSnapshot, &snap.debugging);
6610 buildAutostartXML(pelmSnapshot, &snap.autostart);
6611 // note: Groups exist only for Machine, not for Snapshot
6612
6613 if (snap.llChildSnapshots.size())
6614 {
6615 xml::ElementNode *pelmChildren = pelmSnapshot->createChild("Snapshots");
6616 for (SnapshotsList::const_iterator it = snap.llChildSnapshots.begin();
6617 it != snap.llChildSnapshots.end();
6618 ++it)
6619 {
6620 const Snapshot &child = *it;
6621 buildSnapshotXML(depth + 1, *pelmChildren, child);
6622 }
6623 }
6624}
6625
6626/**
6627 * Builds the XML DOM tree for the machine config under the given XML element.
6628 *
6629 * This has been separated out from write() so it can be called from elsewhere,
6630 * such as the OVF code, to build machine XML in an existing XML tree.
6631 *
6632 * As a result, this gets called from two locations:
6633 *
6634 * -- MachineConfigFile::write();
6635 *
6636 * -- Appliance::buildXMLForOneVirtualSystem()
6637 *
6638 * In fl, the following flag bits are recognized:
6639 *
6640 * -- BuildMachineXML_MediaRegistry: If set, the machine's media registry will
6641 * be written, if present. This is not set when called from OVF because OVF
6642 * has its own variant of a media registry. This flag is ignored unless the
6643 * settings version is at least v1.11 (VirtualBox 4.0).
6644 *
6645 * -- BuildMachineXML_IncludeSnapshots: If set, descend into the snapshots tree
6646 * of the machine and write out \<Snapshot\> and possibly more snapshots under
6647 * that, if snapshots are present. Otherwise all snapshots are suppressed
6648 * (when called from OVF).
6649 *
6650 * -- BuildMachineXML_WriteVBoxVersionAttribute: If set, add a settingsVersion
6651 * attribute to the machine tag with the vbox settings version. This is for
6652 * the OVF export case in which we don't have the settings version set in
6653 * the root element.
6654 *
6655 * -- BuildMachineXML_SkipRemovableMedia: If set, removable media attachments
6656 * (DVDs, floppies) are silently skipped. This is for the OVF export case
6657 * until we support copying ISO and RAW media as well. This flag is ignored
6658 * unless the settings version is at least v1.9, which is always the case
6659 * when this gets called for OVF export.
6660 *
6661 * -- BuildMachineXML_SuppressSavedState: If set, the Machine/stateFile
6662 * attribute is never set. This is also for the OVF export case because we
6663 * cannot save states with OVF.
6664 *
6665 * @param elmMachine XML \<Machine\> element to add attributes and elements to.
6666 * @param fl Flags.
6667 * @param pllElementsWithUuidAttributes pointer to list that should receive UUID elements or NULL;
6668 * see buildStorageControllersXML() for details.
6669 */
6670void MachineConfigFile::buildMachineXML(xml::ElementNode &elmMachine,
6671 uint32_t fl,
6672 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes)
6673{
6674 if (fl & BuildMachineXML_WriteVBoxVersionAttribute)
6675 {
6676 // add settings version attribute to machine element
6677 setVersionAttribute(elmMachine);
6678 LogRel(("Exporting settings file \"%s\" with version \"%s\"\n", m->strFilename.c_str(), m->strSettingsVersionFull.c_str()));
6679 }
6680
6681 elmMachine.setAttribute("uuid", uuid.toStringCurly());
6682 elmMachine.setAttribute("name", machineUserData.strName);
6683 if (machineUserData.fDirectoryIncludesUUID)
6684 elmMachine.setAttribute("directoryIncludesUUID", machineUserData.fDirectoryIncludesUUID);
6685 if (!machineUserData.fNameSync)
6686 elmMachine.setAttribute("nameSync", machineUserData.fNameSync);
6687 if (machineUserData.strDescription.length())
6688 elmMachine.createChild("Description")->addContent(machineUserData.strDescription);
6689 elmMachine.setAttribute("OSType", machineUserData.strOsType);
6690 if ( strStateFile.length()
6691 && !(fl & BuildMachineXML_SuppressSavedState)
6692 )
6693 elmMachine.setAttributePath("stateFile", strStateFile);
6694
6695 if ((fl & BuildMachineXML_IncludeSnapshots)
6696 && !uuidCurrentSnapshot.isZero()
6697 && uuidCurrentSnapshot.isValid())
6698 elmMachine.setAttribute("currentSnapshot", uuidCurrentSnapshot.toStringCurly());
6699
6700 if (machineUserData.strSnapshotFolder.length())
6701 elmMachine.setAttributePath("snapshotFolder", machineUserData.strSnapshotFolder);
6702 if (!fCurrentStateModified)
6703 elmMachine.setAttribute("currentStateModified", fCurrentStateModified);
6704 elmMachine.setAttribute("lastStateChange", stringifyTimestamp(timeLastStateChange));
6705 if (fAborted)
6706 elmMachine.setAttribute("aborted", fAborted);
6707 if (machineUserData.strVMPriority.length())
6708 elmMachine.setAttribute("processPriority", machineUserData.strVMPriority);
6709 // Please keep the icon last so that one doesn't have to check if there
6710 // is anything in the line after this very long attribute in the XML.
6711 if (machineUserData.ovIcon.size())
6712 {
6713 Utf8Str strIcon;
6714 toBase64(strIcon, machineUserData.ovIcon);
6715 elmMachine.setAttribute("icon", strIcon);
6716 }
6717 if ( m->sv >= SettingsVersion_v1_9
6718 && ( machineUserData.fTeleporterEnabled
6719 || machineUserData.uTeleporterPort
6720 || !machineUserData.strTeleporterAddress.isEmpty()
6721 || !machineUserData.strTeleporterPassword.isEmpty()
6722 )
6723 )
6724 {
6725 xml::ElementNode *pelmTeleporter = elmMachine.createChild("Teleporter");
6726 pelmTeleporter->setAttribute("enabled", machineUserData.fTeleporterEnabled);
6727 pelmTeleporter->setAttribute("port", machineUserData.uTeleporterPort);
6728 pelmTeleporter->setAttribute("address", machineUserData.strTeleporterAddress);
6729 pelmTeleporter->setAttribute("password", machineUserData.strTeleporterPassword);
6730 }
6731
6732 if ( m->sv >= SettingsVersion_v1_11
6733 && ( machineUserData.enmFaultToleranceState != FaultToleranceState_Inactive
6734 || machineUserData.uFaultTolerancePort
6735 || machineUserData.uFaultToleranceInterval
6736 || !machineUserData.strFaultToleranceAddress.isEmpty()
6737 )
6738 )
6739 {
6740 xml::ElementNode *pelmFaultTolerance = elmMachine.createChild("FaultTolerance");
6741 switch (machineUserData.enmFaultToleranceState)
6742 {
6743 case FaultToleranceState_Inactive:
6744 pelmFaultTolerance->setAttribute("state", "inactive");
6745 break;
6746 case FaultToleranceState_Master:
6747 pelmFaultTolerance->setAttribute("state", "master");
6748 break;
6749 case FaultToleranceState_Standby:
6750 pelmFaultTolerance->setAttribute("state", "standby");
6751 break;
6752 }
6753
6754 pelmFaultTolerance->setAttribute("port", machineUserData.uFaultTolerancePort);
6755 pelmFaultTolerance->setAttribute("address", machineUserData.strFaultToleranceAddress);
6756 pelmFaultTolerance->setAttribute("interval", machineUserData.uFaultToleranceInterval);
6757 pelmFaultTolerance->setAttribute("password", machineUserData.strFaultTolerancePassword);
6758 }
6759
6760 if ( (fl & BuildMachineXML_MediaRegistry)
6761 && (m->sv >= SettingsVersion_v1_11)
6762 )
6763 buildMediaRegistry(elmMachine, mediaRegistry);
6764
6765 buildExtraData(elmMachine, mapExtraDataItems);
6766
6767 if ( (fl & BuildMachineXML_IncludeSnapshots)
6768 && llFirstSnapshot.size())
6769 buildSnapshotXML(1, elmMachine, llFirstSnapshot.front());
6770
6771 buildHardwareXML(elmMachine, hardwareMachine, fl, pllElementsWithUuidAttributes);
6772 buildDebuggingXML(&elmMachine, &debugging);
6773 buildAutostartXML(&elmMachine, &autostart);
6774 buildGroupsXML(&elmMachine, &machineUserData.llGroups);
6775}
6776
6777/**
6778 * Returns true only if the given AudioDriverType is supported on
6779 * the current host platform. For example, this would return false
6780 * for AudioDriverType_DirectSound when compiled on a Linux host.
6781 * @param drv AudioDriverType_* enum to test.
6782 * @return true only if the current host supports that driver.
6783 */
6784/*static*/
6785bool MachineConfigFile::isAudioDriverAllowedOnThisHost(AudioDriverType_T drv)
6786{
6787 switch (drv)
6788 {
6789 case AudioDriverType_Null:
6790#ifdef RT_OS_WINDOWS
6791 case AudioDriverType_DirectSound:
6792#endif
6793#ifdef VBOX_WITH_AUDIO_OSS
6794 case AudioDriverType_OSS:
6795#endif
6796#ifdef VBOX_WITH_AUDIO_ALSA
6797 case AudioDriverType_ALSA:
6798#endif
6799#ifdef VBOX_WITH_AUDIO_PULSE
6800 case AudioDriverType_Pulse:
6801#endif
6802#ifdef RT_OS_DARWIN
6803 case AudioDriverType_CoreAudio:
6804#endif
6805#ifdef RT_OS_OS2
6806 case AudioDriverType_MMPM:
6807#endif
6808 return true;
6809 default: break; /* Shut up MSC. */
6810 }
6811
6812 return false;
6813}
6814
6815/**
6816 * Returns the AudioDriverType_* which should be used by default on this
6817 * host platform. On Linux, this will check at runtime whether PulseAudio
6818 * or ALSA are actually supported on the first call.
6819 *
6820 * @return Default audio driver type for this host platform.
6821 */
6822/*static*/
6823AudioDriverType_T MachineConfigFile::getHostDefaultAudioDriver()
6824{
6825#if defined(RT_OS_WINDOWS)
6826 return AudioDriverType_DirectSound;
6827
6828#elif defined(RT_OS_LINUX)
6829 /* On Linux, we need to check at runtime what's actually supported. */
6830 static RTCLockMtx s_mtx;
6831 static AudioDriverType_T s_linuxDriver = -1;
6832 RTCLock lock(s_mtx);
6833 if (s_linuxDriver == (AudioDriverType_T)-1)
6834 {
6835# ifdef VBOX_WITH_AUDIO_PULSE
6836 /* Check for the pulse library & that the pulse audio daemon is running. */
6837 if (RTProcIsRunningByName("pulseaudio") &&
6838 RTLdrIsLoadable("libpulse.so.0"))
6839 s_linuxDriver = AudioDriverType_Pulse;
6840 else
6841# endif /* VBOX_WITH_AUDIO_PULSE */
6842# ifdef VBOX_WITH_AUDIO_ALSA
6843 /* Check if we can load the ALSA library */
6844 if (RTLdrIsLoadable("libasound.so.2"))
6845 s_linuxDriver = AudioDriverType_ALSA;
6846 else
6847# endif /* VBOX_WITH_AUDIO_ALSA */
6848 s_linuxDriver = AudioDriverType_OSS;
6849 }
6850 return s_linuxDriver;
6851
6852#elif defined(RT_OS_DARWIN)
6853 return AudioDriverType_CoreAudio;
6854
6855#elif defined(RT_OS_OS2)
6856 return AudioDriverType_MMPM;
6857
6858#else /* All other platforms. */
6859# ifdef VBOX_WITH_AUDIO_OSS
6860 return AudioDriverType_OSS;
6861# else
6862 /* Return NULL driver as a fallback if nothing of the above is available. */
6863 return AudioDriverType_Null;
6864# endif
6865#endif
6866}
6867
6868/**
6869 * Called from write() before calling ConfigFileBase::createStubDocument().
6870 * This adjusts the settings version in m->sv if incompatible settings require
6871 * a settings bump, whereas otherwise we try to preserve the settings version
6872 * to avoid breaking compatibility with older versions.
6873 *
6874 * We do the checks in here in reverse order: newest first, oldest last, so
6875 * that we avoid unnecessary checks since some of these are expensive.
6876 */
6877void MachineConfigFile::bumpSettingsVersionIfNeeded()
6878{
6879 if (m->sv < SettingsVersion_v1_16)
6880 {
6881 // VirtualBox 5.1 adds a NVMe storage controller, paravirt debug
6882 // options, cpu profile, APIC settings (CPU capability and BIOS).
6883
6884 if ( hardwareMachine.strParavirtDebug.isNotEmpty()
6885 || (!hardwareMachine.strCpuProfile.equals("host") && hardwareMachine.strCpuProfile.isNotEmpty())
6886 || hardwareMachine.biosSettings.apicMode != APICMode_APIC
6887 || !hardwareMachine.fAPIC
6888 || hardwareMachine.fX2APIC)
6889 {
6890 m->sv = SettingsVersion_v1_16;
6891 return;
6892 }
6893
6894 for (StorageControllersList::const_iterator it = hardwareMachine.storage.llStorageControllers.begin();
6895 it != hardwareMachine.storage.llStorageControllers.end();
6896 ++it)
6897 {
6898 const StorageController &sctl = *it;
6899
6900 if (sctl.controllerType == StorageControllerType_NVMe)
6901 {
6902 m->sv = SettingsVersion_v1_16;
6903 return;
6904 }
6905 }
6906 }
6907
6908 if (m->sv < SettingsVersion_v1_15)
6909 {
6910 // VirtualBox 5.0 adds paravirt providers, explicit AHCI port hotplug
6911 // setting, USB storage controller, xHCI, serial port TCP backend
6912 // and VM process priority.
6913
6914 /*
6915 * Check simple configuration bits first, loopy stuff afterwards.
6916 */
6917 if ( hardwareMachine.paravirtProvider != ParavirtProvider_Legacy
6918 || hardwareMachine.uCpuIdPortabilityLevel != 0
6919 || machineUserData.strVMPriority.length())
6920 {
6921 m->sv = SettingsVersion_v1_15;
6922 return;
6923 }
6924
6925 /*
6926 * Check whether the hotpluggable flag of all storage devices differs
6927 * from the default for old settings.
6928 * AHCI ports are hotpluggable by default every other device is not.
6929 * Also check if there are USB storage controllers.
6930 */
6931 for (StorageControllersList::const_iterator it = hardwareMachine.storage.llStorageControllers.begin();
6932 it != hardwareMachine.storage.llStorageControllers.end();
6933 ++it)
6934 {
6935 const StorageController &sctl = *it;
6936
6937 if (sctl.controllerType == StorageControllerType_USB)
6938 {
6939 m->sv = SettingsVersion_v1_15;
6940 return;
6941 }
6942
6943 for (AttachedDevicesList::const_iterator it2 = sctl.llAttachedDevices.begin();
6944 it2 != sctl.llAttachedDevices.end();
6945 ++it2)
6946 {
6947 const AttachedDevice &att = *it2;
6948
6949 if ( ( att.fHotPluggable
6950 && sctl.controllerType != StorageControllerType_IntelAhci)
6951 || ( !att.fHotPluggable
6952 && sctl.controllerType == StorageControllerType_IntelAhci))
6953 {
6954 m->sv = SettingsVersion_v1_15;
6955 return;
6956 }
6957 }
6958 }
6959
6960 /*
6961 * Check if there is an xHCI (USB3) USB controller.
6962 */
6963 for (USBControllerList::const_iterator it = hardwareMachine.usbSettings.llUSBControllers.begin();
6964 it != hardwareMachine.usbSettings.llUSBControllers.end();
6965 ++it)
6966 {
6967 const USBController &ctrl = *it;
6968 if (ctrl.enmType == USBControllerType_XHCI)
6969 {
6970 m->sv = SettingsVersion_v1_15;
6971 return;
6972 }
6973 }
6974
6975 /*
6976 * Check if any serial port uses the TCP backend.
6977 */
6978 for (SerialPortsList::const_iterator it = hardwareMachine.llSerialPorts.begin();
6979 it != hardwareMachine.llSerialPorts.end();
6980 ++it)
6981 {
6982 const SerialPort &port = *it;
6983 if (port.portMode == PortMode_TCP)
6984 {
6985 m->sv = SettingsVersion_v1_15;
6986 return;
6987 }
6988 }
6989 }
6990
6991 if (m->sv < SettingsVersion_v1_14)
6992 {
6993 // VirtualBox 4.3 adds default frontend setting, graphics controller
6994 // setting, explicit long mode setting, video capturing and NAT networking.
6995 if ( !hardwareMachine.strDefaultFrontend.isEmpty()
6996 || hardwareMachine.graphicsControllerType != GraphicsControllerType_VBoxVGA
6997 || hardwareMachine.enmLongMode != Hardware::LongMode_Legacy
6998 || machineUserData.ovIcon.size() > 0
6999 || hardwareMachine.fVideoCaptureEnabled)
7000 {
7001 m->sv = SettingsVersion_v1_14;
7002 return;
7003 }
7004 NetworkAdaptersList::const_iterator netit;
7005 for (netit = hardwareMachine.llNetworkAdapters.begin();
7006 netit != hardwareMachine.llNetworkAdapters.end();
7007 ++netit)
7008 {
7009 if (netit->mode == NetworkAttachmentType_NATNetwork)
7010 {
7011 m->sv = SettingsVersion_v1_14;
7012 break;
7013 }
7014 }
7015 }
7016
7017 if (m->sv < SettingsVersion_v1_14)
7018 {
7019 unsigned cOhciCtrls = 0;
7020 unsigned cEhciCtrls = 0;
7021 bool fNonStdName = false;
7022
7023 for (USBControllerList::const_iterator it = hardwareMachine.usbSettings.llUSBControllers.begin();
7024 it != hardwareMachine.usbSettings.llUSBControllers.end();
7025 ++it)
7026 {
7027 const USBController &ctrl = *it;
7028
7029 switch (ctrl.enmType)
7030 {
7031 case USBControllerType_OHCI:
7032 cOhciCtrls++;
7033 if (ctrl.strName != "OHCI")
7034 fNonStdName = true;
7035 break;
7036 case USBControllerType_EHCI:
7037 cEhciCtrls++;
7038 if (ctrl.strName != "EHCI")
7039 fNonStdName = true;
7040 break;
7041 default:
7042 /* Anything unknown forces a bump. */
7043 fNonStdName = true;
7044 }
7045
7046 /* Skip checking other controllers if the settings bump is necessary. */
7047 if (cOhciCtrls > 1 || cEhciCtrls > 1 || fNonStdName)
7048 {
7049 m->sv = SettingsVersion_v1_14;
7050 break;
7051 }
7052 }
7053 }
7054
7055 if (m->sv < SettingsVersion_v1_13)
7056 {
7057 // VirtualBox 4.2 adds tracing, autostart, UUID in directory and groups.
7058 if ( !debugging.areDefaultSettings()
7059 || !autostart.areDefaultSettings()
7060 || machineUserData.fDirectoryIncludesUUID
7061 || machineUserData.llGroups.size() > 1
7062 || machineUserData.llGroups.front() != "/")
7063 m->sv = SettingsVersion_v1_13;
7064 }
7065
7066 if (m->sv < SettingsVersion_v1_13)
7067 {
7068 // VirtualBox 4.2 changes the units for bandwidth group limits.
7069 for (BandwidthGroupList::const_iterator it = hardwareMachine.ioSettings.llBandwidthGroups.begin();
7070 it != hardwareMachine.ioSettings.llBandwidthGroups.end();
7071 ++it)
7072 {
7073 const BandwidthGroup &gr = *it;
7074 if (gr.cMaxBytesPerSec % _1M)
7075 {
7076 // Bump version if a limit cannot be expressed in megabytes
7077 m->sv = SettingsVersion_v1_13;
7078 break;
7079 }
7080 }
7081 }
7082
7083 if (m->sv < SettingsVersion_v1_12)
7084 {
7085 // VirtualBox 4.1 adds PCI passthrough and emulated USB Smart Card reader
7086 if ( hardwareMachine.pciAttachments.size()
7087 || hardwareMachine.fEmulatedUSBCardReader)
7088 m->sv = SettingsVersion_v1_12;
7089 }
7090
7091 if (m->sv < SettingsVersion_v1_12)
7092 {
7093 // VirtualBox 4.1 adds a promiscuous mode policy to the network
7094 // adapters and a generic network driver transport.
7095 NetworkAdaptersList::const_iterator netit;
7096 for (netit = hardwareMachine.llNetworkAdapters.begin();
7097 netit != hardwareMachine.llNetworkAdapters.end();
7098 ++netit)
7099 {
7100 if ( netit->enmPromiscModePolicy != NetworkAdapterPromiscModePolicy_Deny
7101 || netit->mode == NetworkAttachmentType_Generic
7102 || !netit->areGenericDriverDefaultSettings()
7103 )
7104 {
7105 m->sv = SettingsVersion_v1_12;
7106 break;
7107 }
7108 }
7109 }
7110
7111 if (m->sv < SettingsVersion_v1_11)
7112 {
7113 // VirtualBox 4.0 adds HD audio, CPU priorities, fault tolerance,
7114 // per-machine media registries, VRDE, JRockitVE, bandwidth groups,
7115 // ICH9 chipset
7116 if ( hardwareMachine.audioAdapter.controllerType == AudioControllerType_HDA
7117 || hardwareMachine.ulCpuExecutionCap != 100
7118 || machineUserData.enmFaultToleranceState != FaultToleranceState_Inactive
7119 || machineUserData.uFaultTolerancePort
7120 || machineUserData.uFaultToleranceInterval
7121 || !machineUserData.strFaultToleranceAddress.isEmpty()
7122 || mediaRegistry.llHardDisks.size()
7123 || mediaRegistry.llDvdImages.size()
7124 || mediaRegistry.llFloppyImages.size()
7125 || !hardwareMachine.vrdeSettings.strVrdeExtPack.isEmpty()
7126 || !hardwareMachine.vrdeSettings.strAuthLibrary.isEmpty()
7127 || machineUserData.strOsType == "JRockitVE"
7128 || hardwareMachine.ioSettings.llBandwidthGroups.size()
7129 || hardwareMachine.chipsetType == ChipsetType_ICH9
7130 )
7131 m->sv = SettingsVersion_v1_11;
7132 }
7133
7134 if (m->sv < SettingsVersion_v1_10)
7135 {
7136 /* If the properties contain elements other than "TCP/Ports" and "TCP/Address",
7137 * then increase the version to at least VBox 3.2, which can have video channel properties.
7138 */
7139 unsigned cOldProperties = 0;
7140
7141 StringsMap::const_iterator it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Ports");
7142 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
7143 cOldProperties++;
7144 it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Address");
7145 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
7146 cOldProperties++;
7147
7148 if (hardwareMachine.vrdeSettings.mapProperties.size() != cOldProperties)
7149 m->sv = SettingsVersion_v1_10;
7150 }
7151
7152 if (m->sv < SettingsVersion_v1_11)
7153 {
7154 /* If the properties contain elements other than "TCP/Ports", "TCP/Address",
7155 * "VideoChannel/Enabled" and "VideoChannel/Quality" then increase the version to VBox 4.0.
7156 */
7157 unsigned cOldProperties = 0;
7158
7159 StringsMap::const_iterator it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Ports");
7160 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
7161 cOldProperties++;
7162 it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Address");
7163 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
7164 cOldProperties++;
7165 it = hardwareMachine.vrdeSettings.mapProperties.find("VideoChannel/Enabled");
7166 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
7167 cOldProperties++;
7168 it = hardwareMachine.vrdeSettings.mapProperties.find("VideoChannel/Quality");
7169 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
7170 cOldProperties++;
7171
7172 if (hardwareMachine.vrdeSettings.mapProperties.size() != cOldProperties)
7173 m->sv = SettingsVersion_v1_11;
7174 }
7175
7176 // settings version 1.9 is required if there is not exactly one DVD
7177 // or more than one floppy drive present or the DVD is not at the secondary
7178 // master; this check is a bit more complicated
7179 //
7180 // settings version 1.10 is required if the host cache should be disabled
7181 //
7182 // settings version 1.11 is required for bandwidth limits and if more than
7183 // one controller of each type is present.
7184 if (m->sv < SettingsVersion_v1_11)
7185 {
7186 // count attached DVDs and floppies (only if < v1.9)
7187 size_t cDVDs = 0;
7188 size_t cFloppies = 0;
7189
7190 // count storage controllers (if < v1.11)
7191 size_t cSata = 0;
7192 size_t cScsiLsi = 0;
7193 size_t cScsiBuslogic = 0;
7194 size_t cSas = 0;
7195 size_t cIde = 0;
7196 size_t cFloppy = 0;
7197
7198 // need to run thru all the storage controllers and attached devices to figure this out
7199 for (StorageControllersList::const_iterator it = hardwareMachine.storage.llStorageControllers.begin();
7200 it != hardwareMachine.storage.llStorageControllers.end();
7201 ++it)
7202 {
7203 const StorageController &sctl = *it;
7204
7205 // count storage controllers of each type; 1.11 is required if more than one
7206 // controller of one type is present
7207 switch (sctl.storageBus)
7208 {
7209 case StorageBus_IDE:
7210 cIde++;
7211 break;
7212 case StorageBus_SATA:
7213 cSata++;
7214 break;
7215 case StorageBus_SAS:
7216 cSas++;
7217 break;
7218 case StorageBus_SCSI:
7219 if (sctl.controllerType == StorageControllerType_LsiLogic)
7220 cScsiLsi++;
7221 else
7222 cScsiBuslogic++;
7223 break;
7224 case StorageBus_Floppy:
7225 cFloppy++;
7226 break;
7227 default:
7228 // Do nothing
7229 break;
7230 }
7231
7232 if ( cSata > 1
7233 || cScsiLsi > 1
7234 || cScsiBuslogic > 1
7235 || cSas > 1
7236 || cIde > 1
7237 || cFloppy > 1)
7238 {
7239 m->sv = SettingsVersion_v1_11;
7240 break; // abort the loop -- we will not raise the version further
7241 }
7242
7243 for (AttachedDevicesList::const_iterator it2 = sctl.llAttachedDevices.begin();
7244 it2 != sctl.llAttachedDevices.end();
7245 ++it2)
7246 {
7247 const AttachedDevice &att = *it2;
7248
7249 // Bandwidth limitations are new in VirtualBox 4.0 (1.11)
7250 if (m->sv < SettingsVersion_v1_11)
7251 {
7252 if (att.strBwGroup.length() != 0)
7253 {
7254 m->sv = SettingsVersion_v1_11;
7255 break; // abort the loop -- we will not raise the version further
7256 }
7257 }
7258
7259 // disabling the host IO cache requires settings version 1.10
7260 if ( (m->sv < SettingsVersion_v1_10)
7261 && (!sctl.fUseHostIOCache)
7262 )
7263 m->sv = SettingsVersion_v1_10;
7264
7265 // we can only write the StorageController/@Instance attribute with v1.9
7266 if ( (m->sv < SettingsVersion_v1_9)
7267 && (sctl.ulInstance != 0)
7268 )
7269 m->sv = SettingsVersion_v1_9;
7270
7271 if (m->sv < SettingsVersion_v1_9)
7272 {
7273 if (att.deviceType == DeviceType_DVD)
7274 {
7275 if ( (sctl.storageBus != StorageBus_IDE) // DVD at bus other than DVD?
7276 || (att.lPort != 1) // DVDs not at secondary master?
7277 || (att.lDevice != 0)
7278 )
7279 m->sv = SettingsVersion_v1_9;
7280
7281 ++cDVDs;
7282 }
7283 else if (att.deviceType == DeviceType_Floppy)
7284 ++cFloppies;
7285 }
7286 }
7287
7288 if (m->sv >= SettingsVersion_v1_11)
7289 break; // abort the loop -- we will not raise the version further
7290 }
7291
7292 // VirtualBox before 3.1 had zero or one floppy and exactly one DVD,
7293 // so any deviation from that will require settings version 1.9
7294 if ( (m->sv < SettingsVersion_v1_9)
7295 && ( (cDVDs != 1)
7296 || (cFloppies > 1)
7297 )
7298 )
7299 m->sv = SettingsVersion_v1_9;
7300 }
7301
7302 // VirtualBox 3.2: Check for non default I/O settings
7303 if (m->sv < SettingsVersion_v1_10)
7304 {
7305 if ( (hardwareMachine.ioSettings.fIOCacheEnabled != true)
7306 || (hardwareMachine.ioSettings.ulIOCacheSize != 5)
7307 // and page fusion
7308 || (hardwareMachine.fPageFusionEnabled)
7309 // and CPU hotplug, RTC timezone control, HID type and HPET
7310 || machineUserData.fRTCUseUTC
7311 || hardwareMachine.fCpuHotPlug
7312 || hardwareMachine.pointingHIDType != PointingHIDType_PS2Mouse
7313 || hardwareMachine.keyboardHIDType != KeyboardHIDType_PS2Keyboard
7314 || hardwareMachine.fHPETEnabled
7315 )
7316 m->sv = SettingsVersion_v1_10;
7317 }
7318
7319 // VirtualBox 3.2 adds NAT and boot priority to the NIC config in Main
7320 // VirtualBox 4.0 adds network bandwitdth
7321 if (m->sv < SettingsVersion_v1_11)
7322 {
7323 NetworkAdaptersList::const_iterator netit;
7324 for (netit = hardwareMachine.llNetworkAdapters.begin();
7325 netit != hardwareMachine.llNetworkAdapters.end();
7326 ++netit)
7327 {
7328 if ( (m->sv < SettingsVersion_v1_12)
7329 && (netit->strBandwidthGroup.isNotEmpty())
7330 )
7331 {
7332 /* New in VirtualBox 4.1 */
7333 m->sv = SettingsVersion_v1_12;
7334 break;
7335 }
7336 else if ( (m->sv < SettingsVersion_v1_10)
7337 && (netit->fEnabled)
7338 && (netit->mode == NetworkAttachmentType_NAT)
7339 && ( netit->nat.u32Mtu != 0
7340 || netit->nat.u32SockRcv != 0
7341 || netit->nat.u32SockSnd != 0
7342 || netit->nat.u32TcpRcv != 0
7343 || netit->nat.u32TcpSnd != 0
7344 || !netit->nat.fDNSPassDomain
7345 || netit->nat.fDNSProxy
7346 || netit->nat.fDNSUseHostResolver
7347 || netit->nat.fAliasLog
7348 || netit->nat.fAliasProxyOnly
7349 || netit->nat.fAliasUseSamePorts
7350 || netit->nat.strTFTPPrefix.length()
7351 || netit->nat.strTFTPBootFile.length()
7352 || netit->nat.strTFTPNextServer.length()
7353 || netit->nat.mapRules.size()
7354 )
7355 )
7356 {
7357 m->sv = SettingsVersion_v1_10;
7358 // no break because we still might need v1.11 above
7359 }
7360 else if ( (m->sv < SettingsVersion_v1_10)
7361 && (netit->fEnabled)
7362 && (netit->ulBootPriority != 0)
7363 )
7364 {
7365 m->sv = SettingsVersion_v1_10;
7366 // no break because we still might need v1.11 above
7367 }
7368 }
7369 }
7370
7371 // all the following require settings version 1.9
7372 if ( (m->sv < SettingsVersion_v1_9)
7373 && ( (hardwareMachine.firmwareType >= FirmwareType_EFI)
7374 || machineUserData.fTeleporterEnabled
7375 || machineUserData.uTeleporterPort
7376 || !machineUserData.strTeleporterAddress.isEmpty()
7377 || !machineUserData.strTeleporterPassword.isEmpty()
7378 || (!hardwareMachine.uuid.isZero() && hardwareMachine.uuid.isValid())
7379 )
7380 )
7381 m->sv = SettingsVersion_v1_9;
7382
7383 // "accelerate 2d video" requires settings version 1.8
7384 if ( (m->sv < SettingsVersion_v1_8)
7385 && (hardwareMachine.fAccelerate2DVideo)
7386 )
7387 m->sv = SettingsVersion_v1_8;
7388
7389 // The hardware versions other than "1" requires settings version 1.4 (2.1+).
7390 if ( m->sv < SettingsVersion_v1_4
7391 && hardwareMachine.strVersion != "1"
7392 )
7393 m->sv = SettingsVersion_v1_4;
7394}
7395
7396/**
7397 * Called from Main code to write a machine config file to disk. This builds a DOM tree from
7398 * the member variables and then writes the XML file; it throws xml::Error instances on errors,
7399 * in particular if the file cannot be written.
7400 */
7401void MachineConfigFile::write(const com::Utf8Str &strFilename)
7402{
7403 try
7404 {
7405 // createStubDocument() sets the settings version to at least 1.7; however,
7406 // we might need to enfore a later settings version if incompatible settings
7407 // are present:
7408 bumpSettingsVersionIfNeeded();
7409
7410 m->strFilename = strFilename;
7411 specialBackupIfFirstBump();
7412 createStubDocument();
7413
7414 xml::ElementNode *pelmMachine = m->pelmRoot->createChild("Machine");
7415 buildMachineXML(*pelmMachine,
7416 MachineConfigFile::BuildMachineXML_IncludeSnapshots
7417 | MachineConfigFile::BuildMachineXML_MediaRegistry,
7418 // but not BuildMachineXML_WriteVBoxVersionAttribute
7419 NULL); /* pllElementsWithUuidAttributes */
7420
7421 // now go write the XML
7422 xml::XmlFileWriter writer(*m->pDoc);
7423 writer.write(m->strFilename.c_str(), true /*fSafe*/);
7424
7425 m->fFileExists = true;
7426 clearDocument();
7427 }
7428 catch (...)
7429 {
7430 clearDocument();
7431 throw;
7432 }
7433}
Note: See TracBrowser for help on using the repository browser.

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