VirtualBox

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

Last change on this file since 62468 was 62363, checked in by vboxsync, 9 years ago

Main/VBoxSVC: enable -Wconversion plus a couple of fixes (all harmless)

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

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