VirtualBox

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

Last change on this file since 67954 was 67793, checked in by vboxsync, 7 years ago

a few 'const com::Utf8Str &'

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