VirtualBox

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

Last change on this file since 70215 was 69070, checked in by vboxsync, 7 years ago

Settings: restore the lost code for writing maxSize attribute for video capture

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