VirtualBox

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

Last change on this file since 61627 was 61501, checked in by vboxsync, 9 years ago

Main/xml/Settings.cpp: fix almost complete snapshot breakage, it saved the hardware part of the current state for all snapshot instead of the right data, plus a fix for a much older bug where the same happened partially for some USB related data

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Revision Author Id
File size: 291.0 KB
Line 
1/* $Id: Settings.cpp 61501 2016-06-06 17:12:32Z 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 = port;
910 (*pf)->getAttributeValue("guestip", rule.strGuestIP);
911 (*pf)->getAttributeValue("guestport", port);
912 rule.u16GuestPort = 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(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() const
2120{
2121 return !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_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)
2366 || (sv < SettingsVersion_v1_16 && !fCableConnected))
2367 && ulLineSpeed == 0
2368 && enmPromiscModePolicy == NetworkAdapterPromiscModePolicy_Deny
2369 && type == NetworkAdapterType_Am79C973
2370 && mode == NetworkAttachmentType_Null
2371 && nat.areDefaultSettings()
2372 && strBridgedName.isEmpty()
2373 && strInternalNetworkName.isEmpty()
2374 && strHostOnlyName.isEmpty()
2375 && areGenericDriverDefaultSettings()
2376 && strNATNetworkName.isEmpty();
2377}
2378
2379/**
2380 * Special check if settings of the non-current attachment type have default values.
2381 */
2382bool NetworkAdapter::areDisabledDefaultSettings() const
2383{
2384 return (mode != NetworkAttachmentType_NAT ? nat.areDefaultSettings() : true)
2385 && (mode != NetworkAttachmentType_Bridged ? strBridgedName.isEmpty() : true)
2386 && (mode != NetworkAttachmentType_Internal ? strInternalNetworkName.isEmpty() : true)
2387 && (mode != NetworkAttachmentType_HostOnly ? strHostOnlyName.isEmpty() : true)
2388 && (mode != NetworkAttachmentType_Generic ? areGenericDriverDefaultSettings() : true)
2389 && (mode != NetworkAttachmentType_NATNetwork ? strNATNetworkName.isEmpty() : true);
2390}
2391
2392/**
2393 * Comparison operator. This gets called from MachineConfigFile::operator==,
2394 * which in turn gets called from Machine::saveSettings to figure out whether
2395 * machine settings have really changed and thus need to be written out to disk.
2396 */
2397bool NetworkAdapter::operator==(const NetworkAdapter &n) const
2398{
2399 return (this == &n)
2400 || ( ulSlot == n.ulSlot
2401 && type == n.type
2402 && fEnabled == n.fEnabled
2403 && strMACAddress == n.strMACAddress
2404 && fCableConnected == n.fCableConnected
2405 && ulLineSpeed == n.ulLineSpeed
2406 && enmPromiscModePolicy == n.enmPromiscModePolicy
2407 && fTraceEnabled == n.fTraceEnabled
2408 && strTraceFile == n.strTraceFile
2409 && mode == n.mode
2410 && nat == n.nat
2411 && strBridgedName == n.strBridgedName
2412 && strHostOnlyName == n.strHostOnlyName
2413 && strInternalNetworkName == n.strInternalNetworkName
2414 && strGenericDriver == n.strGenericDriver
2415 && genericProperties == n.genericProperties
2416 && ulBootPriority == n.ulBootPriority
2417 && strBandwidthGroup == n.strBandwidthGroup);
2418}
2419
2420/**
2421 * Constructor. Needs to set sane defaults which stand the test of time.
2422 */
2423SerialPort::SerialPort() :
2424 ulSlot(0),
2425 fEnabled(false),
2426 ulIOBase(0x3f8),
2427 ulIRQ(4),
2428 portMode(PortMode_Disconnected),
2429 fServer(false)
2430{
2431}
2432
2433/**
2434 * Comparison operator. This gets called from MachineConfigFile::operator==,
2435 * which in turn gets called from Machine::saveSettings to figure out whether
2436 * machine settings have really changed and thus need to be written out to disk.
2437 */
2438bool SerialPort::operator==(const SerialPort &s) const
2439{
2440 return (this == &s)
2441 || ( ulSlot == s.ulSlot
2442 && fEnabled == s.fEnabled
2443 && ulIOBase == s.ulIOBase
2444 && ulIRQ == s.ulIRQ
2445 && portMode == s.portMode
2446 && strPath == s.strPath
2447 && fServer == s.fServer);
2448}
2449
2450/**
2451 * Constructor. Needs to set sane defaults which stand the test of time.
2452 */
2453ParallelPort::ParallelPort() :
2454 ulSlot(0),
2455 fEnabled(false),
2456 ulIOBase(0x378),
2457 ulIRQ(7)
2458{
2459}
2460
2461/**
2462 * Comparison operator. This gets called from MachineConfigFile::operator==,
2463 * which in turn gets called from Machine::saveSettings to figure out whether
2464 * machine settings have really changed and thus need to be written out to disk.
2465 */
2466bool ParallelPort::operator==(const ParallelPort &s) const
2467{
2468 return (this == &s)
2469 || ( ulSlot == s.ulSlot
2470 && fEnabled == s.fEnabled
2471 && ulIOBase == s.ulIOBase
2472 && ulIRQ == s.ulIRQ
2473 && strPath == s.strPath);
2474}
2475
2476/**
2477 * Constructor. Needs to set sane defaults which stand the test of time.
2478 */
2479AudioAdapter::AudioAdapter() :
2480 fEnabled(false),
2481 controllerType(AudioControllerType_AC97),
2482 codecType(AudioCodecType_STAC9700),
2483 driverType(AudioDriverType_Null)
2484{
2485}
2486
2487/**
2488 * Check if all settings have default values.
2489 */
2490bool AudioAdapter::areDefaultSettings(SettingsVersion_T sv) const
2491{
2492 return (sv <= SettingsVersion_v1_14 ? fEnabled : !fEnabled)
2493 && controllerType == AudioControllerType_AC97
2494 && codecType == AudioCodecType_STAC9700
2495 && driverType == MachineConfigFile::getHostDefaultAudioDriver()
2496 && properties.size() == 0;
2497}
2498
2499/**
2500 * Comparison operator. This gets called from MachineConfigFile::operator==,
2501 * which in turn gets called from Machine::saveSettings to figure out whether
2502 * machine settings have really changed and thus need to be written out to disk.
2503 */
2504bool AudioAdapter::operator==(const AudioAdapter &a) const
2505{
2506 return (this == &a)
2507 || ( fEnabled == a.fEnabled
2508 && controllerType == a.controllerType
2509 && codecType == a.codecType
2510 && driverType == a.driverType
2511 && properties == a.properties);
2512}
2513
2514/**
2515 * Constructor. Needs to set sane defaults which stand the test of time.
2516 */
2517SharedFolder::SharedFolder() :
2518 fWritable(false),
2519 fAutoMount(false)
2520{
2521}
2522
2523/**
2524 * Comparison operator. This gets called from MachineConfigFile::operator==,
2525 * which in turn gets called from Machine::saveSettings to figure out whether
2526 * machine settings have really changed and thus need to be written out to disk.
2527 */
2528bool SharedFolder::operator==(const SharedFolder &g) const
2529{
2530 return (this == &g)
2531 || ( strName == g.strName
2532 && strHostPath == g.strHostPath
2533 && fWritable == g.fWritable
2534 && fAutoMount == g.fAutoMount);
2535}
2536
2537/**
2538 * Constructor. Needs to set sane defaults which stand the test of time.
2539 */
2540GuestProperty::GuestProperty() :
2541 timestamp(0)
2542{
2543}
2544
2545/**
2546 * Comparison operator. This gets called from MachineConfigFile::operator==,
2547 * which in turn gets called from Machine::saveSettings to figure out whether
2548 * machine settings have really changed and thus need to be written out to disk.
2549 */
2550bool GuestProperty::operator==(const GuestProperty &g) const
2551{
2552 return (this == &g)
2553 || ( strName == g.strName
2554 && strValue == g.strValue
2555 && timestamp == g.timestamp
2556 && strFlags == g.strFlags);
2557}
2558
2559/**
2560 * Constructor. Needs to set sane defaults which stand the test of time.
2561 */
2562CpuIdLeaf::CpuIdLeaf() :
2563 ulId(UINT32_MAX),
2564 ulEax(0),
2565 ulEbx(0),
2566 ulEcx(0),
2567 ulEdx(0)
2568{
2569}
2570
2571/**
2572 * Comparison operator. This gets called from MachineConfigFile::operator==,
2573 * which in turn gets called from Machine::saveSettings to figure out whether
2574 * machine settings have really changed and thus need to be written out to disk.
2575 */
2576bool CpuIdLeaf::operator==(const CpuIdLeaf &c) const
2577{
2578 return (this == &c)
2579 || ( ulId == c.ulId
2580 && ulEax == c.ulEax
2581 && ulEbx == c.ulEbx
2582 && ulEcx == c.ulEcx
2583 && ulEdx == c.ulEdx);
2584}
2585
2586/**
2587 * Constructor. Needs to set sane defaults which stand the test of time.
2588 */
2589Cpu::Cpu() :
2590 ulId(UINT32_MAX)
2591{
2592}
2593
2594/**
2595 * Comparison operator. This gets called from MachineConfigFile::operator==,
2596 * which in turn gets called from Machine::saveSettings to figure out whether
2597 * machine settings have really changed and thus need to be written out to disk.
2598 */
2599bool Cpu::operator==(const Cpu &c) const
2600{
2601 return (this == &c)
2602 || (ulId == c.ulId);
2603}
2604
2605/**
2606 * Constructor. Needs to set sane defaults which stand the test of time.
2607 */
2608BandwidthGroup::BandwidthGroup() :
2609 cMaxBytesPerSec(0),
2610 enmType(BandwidthGroupType_Null)
2611{
2612}
2613
2614/**
2615 * Comparison operator. This gets called from MachineConfigFile::operator==,
2616 * which in turn gets called from Machine::saveSettings to figure out whether
2617 * machine settings have really changed and thus need to be written out to disk.
2618 */
2619bool BandwidthGroup::operator==(const BandwidthGroup &i) const
2620{
2621 return (this == &i)
2622 || ( strName == i.strName
2623 && cMaxBytesPerSec == i.cMaxBytesPerSec
2624 && enmType == i.enmType);
2625}
2626
2627/**
2628 * IOSettings constructor.
2629 */
2630IOSettings::IOSettings() :
2631 fIOCacheEnabled(true),
2632 ulIOCacheSize(5)
2633{
2634}
2635
2636/**
2637 * Check if all IO Cache settings have default values.
2638 */
2639bool IOSettings::areIOCacheDefaultSettings() const
2640{
2641 return fIOCacheEnabled
2642 && ulIOCacheSize == 5;
2643}
2644
2645/**
2646 * Check if all settings have default values.
2647 */
2648bool IOSettings::areDefaultSettings() const
2649{
2650 return areIOCacheDefaultSettings()
2651 && llBandwidthGroups.size() == 0;
2652}
2653
2654/**
2655 * Comparison operator. This gets called from MachineConfigFile::operator==,
2656 * which in turn gets called from Machine::saveSettings to figure out whether
2657 * machine settings have really changed and thus need to be written out to disk.
2658 */
2659bool IOSettings::operator==(const IOSettings &i) const
2660{
2661 return (this == &i)
2662 || ( fIOCacheEnabled == i.fIOCacheEnabled
2663 && ulIOCacheSize == i.ulIOCacheSize
2664 && llBandwidthGroups == i.llBandwidthGroups);
2665}
2666
2667/**
2668 * Constructor. Needs to set sane defaults which stand the test of time.
2669 */
2670HostPCIDeviceAttachment::HostPCIDeviceAttachment() :
2671 uHostAddress(0),
2672 uGuestAddress(0)
2673{
2674}
2675
2676/**
2677 * Comparison operator. This gets called from MachineConfigFile::operator==,
2678 * which in turn gets called from Machine::saveSettings to figure out whether
2679 * machine settings have really changed and thus need to be written out to disk.
2680 */
2681bool HostPCIDeviceAttachment::operator==(const HostPCIDeviceAttachment &a) const
2682{
2683 return (this == &a)
2684 || ( uHostAddress == a.uHostAddress
2685 && uGuestAddress == a.uGuestAddress
2686 && strDeviceName == a.strDeviceName);
2687}
2688
2689
2690/**
2691 * Constructor. Needs to set sane defaults which stand the test of time.
2692 */
2693Hardware::Hardware() :
2694 strVersion("1"),
2695 fHardwareVirt(true),
2696 fNestedPaging(true),
2697 fVPID(true),
2698 fUnrestrictedExecution(true),
2699 fHardwareVirtForce(false),
2700 fTripleFaultReset(false),
2701 fPAE(false),
2702 fAPIC(true),
2703 fX2APIC(false),
2704 enmLongMode(HC_ARCH_BITS == 64 ? Hardware::LongMode_Enabled : Hardware::LongMode_Disabled),
2705 cCPUs(1),
2706 fCpuHotPlug(false),
2707 fHPETEnabled(false),
2708 ulCpuExecutionCap(100),
2709 uCpuIdPortabilityLevel(0),
2710 strCpuProfile("host"),
2711 ulMemorySizeMB((uint32_t)-1),
2712 graphicsControllerType(GraphicsControllerType_VBoxVGA),
2713 ulVRAMSizeMB(8),
2714 cMonitors(1),
2715 fAccelerate3D(false),
2716 fAccelerate2DVideo(false),
2717 ulVideoCaptureHorzRes(1024),
2718 ulVideoCaptureVertRes(768),
2719 ulVideoCaptureRate(512),
2720 ulVideoCaptureFPS(25),
2721 ulVideoCaptureMaxTime(0),
2722 ulVideoCaptureMaxSize(0),
2723 fVideoCaptureEnabled(false),
2724 u64VideoCaptureScreens(UINT64_C(0xffffffffffffffff)),
2725 strVideoCaptureFile(""),
2726 firmwareType(FirmwareType_BIOS),
2727 pointingHIDType(PointingHIDType_PS2Mouse),
2728 keyboardHIDType(KeyboardHIDType_PS2Keyboard),
2729 chipsetType(ChipsetType_PIIX3),
2730 paravirtProvider(ParavirtProvider_Legacy), // default for old VMs, for new ones it's ParavirtProvider_Default
2731 strParavirtDebug(""),
2732 fEmulatedUSBCardReader(false),
2733 clipboardMode(ClipboardMode_Disabled),
2734 dndMode(DnDMode_Disabled),
2735 ulMemoryBalloonSize(0),
2736 fPageFusionEnabled(false)
2737{
2738 mapBootOrder[0] = DeviceType_Floppy;
2739 mapBootOrder[1] = DeviceType_DVD;
2740 mapBootOrder[2] = DeviceType_HardDisk;
2741
2742 /* The default value for PAE depends on the host:
2743 * - 64 bits host -> always true
2744 * - 32 bits host -> true for Windows & Darwin (masked off if the host cpu doesn't support it anyway)
2745 */
2746#if HC_ARCH_BITS == 64 || defined(RT_OS_WINDOWS) || defined(RT_OS_DARWIN)
2747 fPAE = true;
2748#endif
2749
2750 /* The default value of large page supports depends on the host:
2751 * - 64 bits host -> true, unless it's Linux (pending further prediction work due to excessively expensive large page allocations)
2752 * - 32 bits host -> false
2753 */
2754#if HC_ARCH_BITS == 64 && !defined(RT_OS_LINUX)
2755 fLargePages = true;
2756#else
2757 /* Not supported on 32 bits hosts. */
2758 fLargePages = false;
2759#endif
2760}
2761
2762/**
2763 * Check if all Paravirt settings have default values.
2764 */
2765bool Hardware::areParavirtDefaultSettings(SettingsVersion_T sv) const
2766{
2767 // 5.0 didn't save the paravirt settings if it is ParavirtProvider_Legacy,
2768 // so this default must be kept. Later versions don't save the setting if
2769 // it's at the default value.
2770 return ( (sv >= SettingsVersion_v1_16 && paravirtProvider == ParavirtProvider_Default)
2771 || (sv < SettingsVersion_v1_16 && paravirtProvider == ParavirtProvider_Legacy))
2772 && strParavirtDebug.isEmpty();
2773}
2774
2775/**
2776 * Check if all Boot Order settings have default values.
2777 */
2778bool Hardware::areBootOrderDefaultSettings() const
2779{
2780 BootOrderMap::const_iterator it0 = mapBootOrder.find(0);
2781 BootOrderMap::const_iterator it1 = mapBootOrder.find(1);
2782 BootOrderMap::const_iterator it2 = mapBootOrder.find(2);
2783 BootOrderMap::const_iterator it3 = mapBootOrder.find(3);
2784 return ( mapBootOrder.size() == 3
2785 || ( mapBootOrder.size() == 4
2786 && (it3 != mapBootOrder.end() && it3->second == DeviceType_Null)))
2787 && (it0 != mapBootOrder.end() && it0->second == DeviceType_Floppy)
2788 && (it1 != mapBootOrder.end() && it1->second == DeviceType_DVD)
2789 && (it2 != mapBootOrder.end() && it2->second == DeviceType_HardDisk);
2790}
2791
2792/**
2793 * Check if all Display settings have default values.
2794 */
2795bool Hardware::areDisplayDefaultSettings() const
2796{
2797 return graphicsControllerType == GraphicsControllerType_VBoxVGA
2798 && ulVRAMSizeMB == 8
2799 && cMonitors <= 1
2800 && !fAccelerate3D
2801 && !fAccelerate2DVideo;
2802}
2803
2804/**
2805 * Check if all Video Capture settings have default values.
2806 */
2807bool Hardware::areVideoCaptureDefaultSettings() const
2808{
2809 return !fVideoCaptureEnabled
2810 && u64VideoCaptureScreens == UINT64_C(0xffffffffffffffff)
2811 && strVideoCaptureFile.isEmpty()
2812 && ulVideoCaptureHorzRes == 1024
2813 && ulVideoCaptureVertRes == 768
2814 && ulVideoCaptureRate == 512
2815 && ulVideoCaptureFPS == 25
2816 && ulVideoCaptureMaxTime == 0
2817 && ulVideoCaptureMaxSize == 0;
2818}
2819
2820/**
2821 * Check if all Network Adapter settings have default values.
2822 */
2823bool Hardware::areAllNetworkAdaptersDefaultSettings(SettingsVersion_T sv) const
2824{
2825 for (NetworkAdaptersList::const_iterator it = llNetworkAdapters.begin();
2826 it != llNetworkAdapters.end();
2827 ++it)
2828 {
2829 if (!it->areDefaultSettings(sv))
2830 return false;
2831 }
2832 return true;
2833}
2834
2835/**
2836 * Comparison operator. This gets called from MachineConfigFile::operator==,
2837 * which in turn gets called from Machine::saveSettings to figure out whether
2838 * machine settings have really changed and thus need to be written out to disk.
2839 */
2840bool Hardware::operator==(const Hardware& h) const
2841{
2842 return (this == &h)
2843 || ( strVersion == h.strVersion
2844 && uuid == h.uuid
2845 && fHardwareVirt == h.fHardwareVirt
2846 && fNestedPaging == h.fNestedPaging
2847 && fLargePages == h.fLargePages
2848 && fVPID == h.fVPID
2849 && fUnrestrictedExecution == h.fUnrestrictedExecution
2850 && fHardwareVirtForce == h.fHardwareVirtForce
2851 && fPAE == h.fPAE
2852 && enmLongMode == h.enmLongMode
2853 && fTripleFaultReset == h.fTripleFaultReset
2854 && fAPIC == h.fAPIC
2855 && fX2APIC == h.fX2APIC
2856 && cCPUs == h.cCPUs
2857 && fCpuHotPlug == h.fCpuHotPlug
2858 && ulCpuExecutionCap == h.ulCpuExecutionCap
2859 && uCpuIdPortabilityLevel == h.uCpuIdPortabilityLevel
2860 && strCpuProfile == h.strCpuProfile
2861 && fHPETEnabled == h.fHPETEnabled
2862 && llCpus == h.llCpus
2863 && llCpuIdLeafs == h.llCpuIdLeafs
2864 && ulMemorySizeMB == h.ulMemorySizeMB
2865 && mapBootOrder == h.mapBootOrder
2866 && graphicsControllerType == h.graphicsControllerType
2867 && ulVRAMSizeMB == h.ulVRAMSizeMB
2868 && cMonitors == h.cMonitors
2869 && fAccelerate3D == h.fAccelerate3D
2870 && fAccelerate2DVideo == h.fAccelerate2DVideo
2871 && fVideoCaptureEnabled == h.fVideoCaptureEnabled
2872 && u64VideoCaptureScreens == h.u64VideoCaptureScreens
2873 && strVideoCaptureFile == h.strVideoCaptureFile
2874 && ulVideoCaptureHorzRes == h.ulVideoCaptureHorzRes
2875 && ulVideoCaptureVertRes == h.ulVideoCaptureVertRes
2876 && ulVideoCaptureRate == h.ulVideoCaptureRate
2877 && ulVideoCaptureFPS == h.ulVideoCaptureFPS
2878 && ulVideoCaptureMaxTime == h.ulVideoCaptureMaxTime
2879 && ulVideoCaptureMaxSize == h.ulVideoCaptureMaxTime
2880 && firmwareType == h.firmwareType
2881 && pointingHIDType == h.pointingHIDType
2882 && keyboardHIDType == h.keyboardHIDType
2883 && chipsetType == h.chipsetType
2884 && paravirtProvider == h.paravirtProvider
2885 && strParavirtDebug == h.strParavirtDebug
2886 && fEmulatedUSBCardReader == h.fEmulatedUSBCardReader
2887 && vrdeSettings == h.vrdeSettings
2888 && biosSettings == h.biosSettings
2889 && usbSettings == h.usbSettings
2890 && llNetworkAdapters == h.llNetworkAdapters
2891 && llSerialPorts == h.llSerialPorts
2892 && llParallelPorts == h.llParallelPorts
2893 && audioAdapter == h.audioAdapter
2894 && storage == h.storage
2895 && llSharedFolders == h.llSharedFolders
2896 && clipboardMode == h.clipboardMode
2897 && dndMode == h.dndMode
2898 && ulMemoryBalloonSize == h.ulMemoryBalloonSize
2899 && fPageFusionEnabled == h.fPageFusionEnabled
2900 && llGuestProperties == h.llGuestProperties
2901 && ioSettings == h.ioSettings
2902 && pciAttachments == h.pciAttachments
2903 && strDefaultFrontend == h.strDefaultFrontend);
2904}
2905
2906/**
2907 * Constructor. Needs to set sane defaults which stand the test of time.
2908 */
2909AttachedDevice::AttachedDevice() :
2910 deviceType(DeviceType_Null),
2911 fPassThrough(false),
2912 fTempEject(false),
2913 fNonRotational(false),
2914 fDiscard(false),
2915 fHotPluggable(false),
2916 lPort(0),
2917 lDevice(0)
2918{
2919}
2920
2921/**
2922 * Comparison operator. This gets called from MachineConfigFile::operator==,
2923 * which in turn gets called from Machine::saveSettings to figure out whether
2924 * machine settings have really changed and thus need to be written out to disk.
2925 */
2926bool AttachedDevice::operator==(const AttachedDevice &a) const
2927{
2928 return (this == &a)
2929 || ( deviceType == a.deviceType
2930 && fPassThrough == a.fPassThrough
2931 && fTempEject == a.fTempEject
2932 && fNonRotational == a.fNonRotational
2933 && fDiscard == a.fDiscard
2934 && fHotPluggable == a.fHotPluggable
2935 && lPort == a.lPort
2936 && lDevice == a.lDevice
2937 && uuid == a.uuid
2938 && strHostDriveSrc == a.strHostDriveSrc
2939 && strBwGroup == a.strBwGroup);
2940}
2941
2942/**
2943 * Constructor. Needs to set sane defaults which stand the test of time.
2944 */
2945StorageController::StorageController() :
2946 storageBus(StorageBus_IDE),
2947 controllerType(StorageControllerType_PIIX3),
2948 ulPortCount(2),
2949 ulInstance(0),
2950 fUseHostIOCache(true),
2951 fBootable(true)
2952{
2953}
2954
2955/**
2956 * Comparison operator. This gets called from MachineConfigFile::operator==,
2957 * which in turn gets called from Machine::saveSettings to figure out whether
2958 * machine settings have really changed and thus need to be written out to disk.
2959 */
2960bool StorageController::operator==(const StorageController &s) const
2961{
2962 return (this == &s)
2963 || ( strName == s.strName
2964 && storageBus == s.storageBus
2965 && controllerType == s.controllerType
2966 && ulPortCount == s.ulPortCount
2967 && ulInstance == s.ulInstance
2968 && fUseHostIOCache == s.fUseHostIOCache
2969 && llAttachedDevices == s.llAttachedDevices);
2970}
2971
2972/**
2973 * Comparison operator. This gets called from MachineConfigFile::operator==,
2974 * which in turn gets called from Machine::saveSettings to figure out whether
2975 * machine settings have really changed and thus need to be written out to disk.
2976 */
2977bool Storage::operator==(const Storage &s) const
2978{
2979 return (this == &s)
2980 || (llStorageControllers == s.llStorageControllers); // deep compare
2981}
2982
2983/**
2984 * Constructor. Needs to set sane defaults which stand the test of time.
2985 */
2986Debugging::Debugging() :
2987 fTracingEnabled(false),
2988 fAllowTracingToAccessVM(false),
2989 strTracingConfig()
2990{
2991}
2992
2993/**
2994 * Check if all settings have default values.
2995 */
2996bool Debugging::areDefaultSettings() const
2997{
2998 return !fTracingEnabled
2999 && !fAllowTracingToAccessVM
3000 && strTracingConfig.isEmpty();
3001}
3002
3003/**
3004 * Comparison operator. This gets called from MachineConfigFile::operator==,
3005 * which in turn gets called from Machine::saveSettings to figure out whether
3006 * machine settings have really changed and thus need to be written out to disk.
3007 */
3008bool Debugging::operator==(const Debugging &d) const
3009{
3010 return (this == &d)
3011 || ( fTracingEnabled == d.fTracingEnabled
3012 && fAllowTracingToAccessVM == d.fAllowTracingToAccessVM
3013 && strTracingConfig == d.strTracingConfig);
3014}
3015
3016/**
3017 * Constructor. Needs to set sane defaults which stand the test of time.
3018 */
3019Autostart::Autostart() :
3020 fAutostartEnabled(false),
3021 uAutostartDelay(0),
3022 enmAutostopType(AutostopType_Disabled)
3023{
3024}
3025
3026/**
3027 * Check if all settings have default values.
3028 */
3029bool Autostart::areDefaultSettings() const
3030{
3031 return !fAutostartEnabled
3032 && !uAutostartDelay
3033 && enmAutostopType == AutostopType_Disabled;
3034}
3035
3036/**
3037 * Comparison operator. This gets called from MachineConfigFile::operator==,
3038 * which in turn gets called from Machine::saveSettings to figure out whether
3039 * machine settings have really changed and thus need to be written out to disk.
3040 */
3041bool Autostart::operator==(const Autostart &a) const
3042{
3043 return (this == &a)
3044 || ( fAutostartEnabled == a.fAutostartEnabled
3045 && uAutostartDelay == a.uAutostartDelay
3046 && enmAutostopType == a.enmAutostopType);
3047}
3048
3049/**
3050 * Constructor. Needs to set sane defaults which stand the test of time.
3051 */
3052Snapshot::Snapshot()
3053{
3054 RTTimeSpecSetNano(&timestamp, 0);
3055}
3056
3057/**
3058 * Comparison operator. This gets called from MachineConfigFile::operator==,
3059 * which in turn gets called from Machine::saveSettings to figure out whether
3060 * machine settings have really changed and thus need to be written out to disk.
3061 */
3062bool Snapshot::operator==(const Snapshot &s) const
3063{
3064 return (this == &s)
3065 || ( uuid == s.uuid
3066 && strName == s.strName
3067 && strDescription == s.strDescription
3068 && RTTimeSpecIsEqual(&timestamp, &s.timestamp)
3069 && strStateFile == s.strStateFile
3070 && hardware == s.hardware // deep compare
3071 && llChildSnapshots == s.llChildSnapshots // deep compare
3072 && debugging == s.debugging
3073 && autostart == s.autostart);
3074}
3075
3076const struct Snapshot settings::Snapshot::Empty; /* default ctor is OK */
3077
3078/**
3079 * Constructor. Needs to set sane defaults which stand the test of time.
3080 */
3081MachineUserData::MachineUserData() :
3082 fDirectoryIncludesUUID(false),
3083 fNameSync(true),
3084 fTeleporterEnabled(false),
3085 uTeleporterPort(0),
3086 enmFaultToleranceState(FaultToleranceState_Inactive),
3087 uFaultTolerancePort(0),
3088 uFaultToleranceInterval(0),
3089 fRTCUseUTC(false),
3090 strVMPriority("")
3091{
3092 llGroups.push_back("/");
3093}
3094
3095/**
3096 * Comparison operator. This gets called from MachineConfigFile::operator==,
3097 * which in turn gets called from Machine::saveSettings to figure out whether
3098 * machine settings have really changed and thus need to be written out to disk.
3099 */
3100bool MachineUserData::operator==(const MachineUserData &c) const
3101{
3102 return (this == &c)
3103 || ( strName == c.strName
3104 && fDirectoryIncludesUUID == c.fDirectoryIncludesUUID
3105 && fNameSync == c.fNameSync
3106 && strDescription == c.strDescription
3107 && llGroups == c.llGroups
3108 && strOsType == c.strOsType
3109 && strSnapshotFolder == c.strSnapshotFolder
3110 && fTeleporterEnabled == c.fTeleporterEnabled
3111 && uTeleporterPort == c.uTeleporterPort
3112 && strTeleporterAddress == c.strTeleporterAddress
3113 && strTeleporterPassword == c.strTeleporterPassword
3114 && enmFaultToleranceState == c.enmFaultToleranceState
3115 && uFaultTolerancePort == c.uFaultTolerancePort
3116 && uFaultToleranceInterval == c.uFaultToleranceInterval
3117 && strFaultToleranceAddress == c.strFaultToleranceAddress
3118 && strFaultTolerancePassword == c.strFaultTolerancePassword
3119 && fRTCUseUTC == c.fRTCUseUTC
3120 && ovIcon == c.ovIcon
3121 && strVMPriority == c.strVMPriority);
3122}
3123
3124
3125////////////////////////////////////////////////////////////////////////////////
3126//
3127// MachineConfigFile
3128//
3129////////////////////////////////////////////////////////////////////////////////
3130
3131/**
3132 * Constructor.
3133 *
3134 * If pstrFilename is != NULL, this reads the given settings file into the member
3135 * variables and various substructures and lists. Otherwise, the member variables
3136 * are initialized with default values.
3137 *
3138 * Throws variants of xml::Error for I/O, XML and logical content errors, which
3139 * the caller should catch; if this constructor does not throw, then the member
3140 * variables contain meaningful values (either from the file or defaults).
3141 *
3142 * @param strFilename
3143 */
3144MachineConfigFile::MachineConfigFile(const Utf8Str *pstrFilename)
3145 : ConfigFileBase(pstrFilename),
3146 fCurrentStateModified(true),
3147 fAborted(false)
3148{
3149 RTTimeNow(&timeLastStateChange);
3150
3151 if (pstrFilename)
3152 {
3153 // the ConfigFileBase constructor has loaded the XML file, so now
3154 // we need only analyze what is in there
3155
3156 xml::NodesLoop nlRootChildren(*m->pelmRoot);
3157 const xml::ElementNode *pelmRootChild;
3158 while ((pelmRootChild = nlRootChildren.forAllNodes()))
3159 {
3160 if (pelmRootChild->nameEquals("Machine"))
3161 readMachine(*pelmRootChild);
3162 }
3163
3164 // clean up memory allocated by XML engine
3165 clearDocument();
3166 }
3167}
3168
3169/**
3170 * Public routine which returns true if this machine config file can have its
3171 * own media registry (which is true for settings version v1.11 and higher,
3172 * i.e. files created by VirtualBox 4.0 and higher).
3173 * @return
3174 */
3175bool MachineConfigFile::canHaveOwnMediaRegistry() const
3176{
3177 return (m->sv >= SettingsVersion_v1_11);
3178}
3179
3180/**
3181 * Public routine which allows for importing machine XML from an external DOM tree.
3182 * Use this after having called the constructor with a NULL argument.
3183 *
3184 * This is used by the OVF code if a <vbox:Machine> element has been encountered
3185 * in an OVF VirtualSystem element.
3186 *
3187 * @param elmMachine
3188 */
3189void MachineConfigFile::importMachineXML(const xml::ElementNode &elmMachine)
3190{
3191 readMachine(elmMachine);
3192}
3193
3194/**
3195 * Comparison operator. This gets called from Machine::saveSettings to figure out
3196 * whether machine settings have really changed and thus need to be written out to disk.
3197 *
3198 * Even though this is called operator==, this does NOT compare all fields; the "equals"
3199 * should be understood as "has the same machine config as". The following fields are
3200 * NOT compared:
3201 * -- settings versions and file names inherited from ConfigFileBase;
3202 * -- fCurrentStateModified because that is considered separately in Machine::saveSettings!!
3203 *
3204 * The "deep" comparisons marked below will invoke the operator== functions of the
3205 * structs defined in this file, which may in turn go into comparing lists of
3206 * other structures. As a result, invoking this can be expensive, but it's
3207 * less expensive than writing out XML to disk.
3208 */
3209bool MachineConfigFile::operator==(const MachineConfigFile &c) const
3210{
3211 return (this == &c)
3212 || ( uuid == c.uuid
3213 && machineUserData == c.machineUserData
3214 && strStateFile == c.strStateFile
3215 && uuidCurrentSnapshot == c.uuidCurrentSnapshot
3216 // skip fCurrentStateModified!
3217 && RTTimeSpecIsEqual(&timeLastStateChange, &c.timeLastStateChange)
3218 && fAborted == c.fAborted
3219 && hardwareMachine == c.hardwareMachine // this one's deep
3220 && mediaRegistry == c.mediaRegistry // this one's deep
3221 // skip mapExtraDataItems! there is no old state available as it's always forced
3222 && llFirstSnapshot == c.llFirstSnapshot); // this one's deep
3223}
3224
3225/**
3226 * Called from MachineConfigFile::readHardware() to read cpu information.
3227 * @param elmCpuid
3228 * @param ll
3229 */
3230void MachineConfigFile::readCpuTree(const xml::ElementNode &elmCpu,
3231 CpuList &ll)
3232{
3233 xml::NodesLoop nl1(elmCpu, "Cpu");
3234 const xml::ElementNode *pelmCpu;
3235 while ((pelmCpu = nl1.forAllNodes()))
3236 {
3237 Cpu cpu;
3238
3239 if (!pelmCpu->getAttributeValue("id", cpu.ulId))
3240 throw ConfigFileError(this, pelmCpu, N_("Required Cpu/@id attribute is missing"));
3241
3242 ll.push_back(cpu);
3243 }
3244}
3245
3246/**
3247 * Called from MachineConfigFile::readHardware() to cpuid information.
3248 * @param elmCpuid
3249 * @param ll
3250 */
3251void MachineConfigFile::readCpuIdTree(const xml::ElementNode &elmCpuid,
3252 CpuIdLeafsList &ll)
3253{
3254 xml::NodesLoop nl1(elmCpuid, "CpuIdLeaf");
3255 const xml::ElementNode *pelmCpuIdLeaf;
3256 while ((pelmCpuIdLeaf = nl1.forAllNodes()))
3257 {
3258 CpuIdLeaf leaf;
3259
3260 if (!pelmCpuIdLeaf->getAttributeValue("id", leaf.ulId))
3261 throw ConfigFileError(this, pelmCpuIdLeaf, N_("Required CpuId/@id attribute is missing"));
3262
3263 pelmCpuIdLeaf->getAttributeValue("eax", leaf.ulEax);
3264 pelmCpuIdLeaf->getAttributeValue("ebx", leaf.ulEbx);
3265 pelmCpuIdLeaf->getAttributeValue("ecx", leaf.ulEcx);
3266 pelmCpuIdLeaf->getAttributeValue("edx", leaf.ulEdx);
3267
3268 ll.push_back(leaf);
3269 }
3270}
3271
3272/**
3273 * Called from MachineConfigFile::readHardware() to network information.
3274 * @param elmNetwork
3275 * @param ll
3276 */
3277void MachineConfigFile::readNetworkAdapters(const xml::ElementNode &elmNetwork,
3278 NetworkAdaptersList &ll)
3279{
3280 xml::NodesLoop nl1(elmNetwork, "Adapter");
3281 const xml::ElementNode *pelmAdapter;
3282 while ((pelmAdapter = nl1.forAllNodes()))
3283 {
3284 NetworkAdapter nic;
3285
3286 if (m->sv >= SettingsVersion_v1_16)
3287 {
3288 /* Starting with VirtualBox 5.1 the default is true, before it was
3289 * false. This needs to matched by NetworkAdapter.areDefaultSettings(). */
3290 nic.fCableConnected = true;
3291 }
3292
3293 if (!pelmAdapter->getAttributeValue("slot", nic.ulSlot))
3294 throw ConfigFileError(this, pelmAdapter, N_("Required Adapter/@slot attribute is missing"));
3295
3296 Utf8Str strTemp;
3297 if (pelmAdapter->getAttributeValue("type", strTemp))
3298 {
3299 if (strTemp == "Am79C970A")
3300 nic.type = NetworkAdapterType_Am79C970A;
3301 else if (strTemp == "Am79C973")
3302 nic.type = NetworkAdapterType_Am79C973;
3303 else if (strTemp == "82540EM")
3304 nic.type = NetworkAdapterType_I82540EM;
3305 else if (strTemp == "82543GC")
3306 nic.type = NetworkAdapterType_I82543GC;
3307 else if (strTemp == "82545EM")
3308 nic.type = NetworkAdapterType_I82545EM;
3309 else if (strTemp == "virtio")
3310 nic.type = NetworkAdapterType_Virtio;
3311 else
3312 throw ConfigFileError(this, pelmAdapter, N_("Invalid value '%s' in Adapter/@type attribute"), strTemp.c_str());
3313 }
3314
3315 pelmAdapter->getAttributeValue("enabled", nic.fEnabled);
3316 pelmAdapter->getAttributeValue("MACAddress", nic.strMACAddress);
3317 pelmAdapter->getAttributeValue("cable", nic.fCableConnected);
3318 pelmAdapter->getAttributeValue("speed", nic.ulLineSpeed);
3319
3320 if (pelmAdapter->getAttributeValue("promiscuousModePolicy", strTemp))
3321 {
3322 if (strTemp == "Deny")
3323 nic.enmPromiscModePolicy = NetworkAdapterPromiscModePolicy_Deny;
3324 else if (strTemp == "AllowNetwork")
3325 nic.enmPromiscModePolicy = NetworkAdapterPromiscModePolicy_AllowNetwork;
3326 else if (strTemp == "AllowAll")
3327 nic.enmPromiscModePolicy = NetworkAdapterPromiscModePolicy_AllowAll;
3328 else
3329 throw ConfigFileError(this, pelmAdapter,
3330 N_("Invalid value '%s' in Adapter/@promiscuousModePolicy attribute"), strTemp.c_str());
3331 }
3332
3333 pelmAdapter->getAttributeValue("trace", nic.fTraceEnabled);
3334 pelmAdapter->getAttributeValue("tracefile", nic.strTraceFile);
3335 pelmAdapter->getAttributeValue("bootPriority", nic.ulBootPriority);
3336 pelmAdapter->getAttributeValue("bandwidthGroup", nic.strBandwidthGroup);
3337
3338 xml::ElementNodesList llNetworkModes;
3339 pelmAdapter->getChildElements(llNetworkModes);
3340 xml::ElementNodesList::iterator it;
3341 /* We should have only active mode descriptor and disabled modes set */
3342 if (llNetworkModes.size() > 2)
3343 {
3344 throw ConfigFileError(this, pelmAdapter, N_("Invalid number of modes ('%d') attached to Adapter attribute"), llNetworkModes.size());
3345 }
3346 for (it = llNetworkModes.begin(); it != llNetworkModes.end(); ++it)
3347 {
3348 const xml::ElementNode *pelmNode = *it;
3349 if (pelmNode->nameEquals("DisabledModes"))
3350 {
3351 xml::ElementNodesList llDisabledNetworkModes;
3352 xml::ElementNodesList::iterator itDisabled;
3353 pelmNode->getChildElements(llDisabledNetworkModes);
3354 /* run over disabled list and load settings */
3355 for (itDisabled = llDisabledNetworkModes.begin();
3356 itDisabled != llDisabledNetworkModes.end(); ++itDisabled)
3357 {
3358 const xml::ElementNode *pelmDisabledNode = *itDisabled;
3359 readAttachedNetworkMode(*pelmDisabledNode, false, nic);
3360 }
3361 }
3362 else
3363 readAttachedNetworkMode(*pelmNode, true, nic);
3364 }
3365 // else: default is NetworkAttachmentType_Null
3366
3367 ll.push_back(nic);
3368 }
3369}
3370
3371void MachineConfigFile::readAttachedNetworkMode(const xml::ElementNode &elmMode, bool fEnabled, NetworkAdapter &nic)
3372{
3373 NetworkAttachmentType_T enmAttachmentType = NetworkAttachmentType_Null;
3374
3375 if (elmMode.nameEquals("NAT"))
3376 {
3377 enmAttachmentType = NetworkAttachmentType_NAT;
3378
3379 elmMode.getAttributeValue("network", nic.nat.strNetwork);
3380 elmMode.getAttributeValue("hostip", nic.nat.strBindIP);
3381 elmMode.getAttributeValue("mtu", nic.nat.u32Mtu);
3382 elmMode.getAttributeValue("sockrcv", nic.nat.u32SockRcv);
3383 elmMode.getAttributeValue("socksnd", nic.nat.u32SockSnd);
3384 elmMode.getAttributeValue("tcprcv", nic.nat.u32TcpRcv);
3385 elmMode.getAttributeValue("tcpsnd", nic.nat.u32TcpSnd);
3386 const xml::ElementNode *pelmDNS;
3387 if ((pelmDNS = elmMode.findChildElement("DNS")))
3388 {
3389 pelmDNS->getAttributeValue("pass-domain", nic.nat.fDNSPassDomain);
3390 pelmDNS->getAttributeValue("use-proxy", nic.nat.fDNSProxy);
3391 pelmDNS->getAttributeValue("use-host-resolver", nic.nat.fDNSUseHostResolver);
3392 }
3393 const xml::ElementNode *pelmAlias;
3394 if ((pelmAlias = elmMode.findChildElement("Alias")))
3395 {
3396 pelmAlias->getAttributeValue("logging", nic.nat.fAliasLog);
3397 pelmAlias->getAttributeValue("proxy-only", nic.nat.fAliasProxyOnly);
3398 pelmAlias->getAttributeValue("use-same-ports", nic.nat.fAliasUseSamePorts);
3399 }
3400 const xml::ElementNode *pelmTFTP;
3401 if ((pelmTFTP = elmMode.findChildElement("TFTP")))
3402 {
3403 pelmTFTP->getAttributeValue("prefix", nic.nat.strTFTPPrefix);
3404 pelmTFTP->getAttributeValue("boot-file", nic.nat.strTFTPBootFile);
3405 pelmTFTP->getAttributeValue("next-server", nic.nat.strTFTPNextServer);
3406 }
3407
3408 readNATForwardRulesMap(elmMode, nic.nat.mapRules);
3409 }
3410 else if ( elmMode.nameEquals("HostInterface")
3411 || elmMode.nameEquals("BridgedInterface"))
3412 {
3413 enmAttachmentType = NetworkAttachmentType_Bridged;
3414
3415 elmMode.getAttributeValue("name", nic.strBridgedName); // optional bridged interface name
3416 }
3417 else if (elmMode.nameEquals("InternalNetwork"))
3418 {
3419 enmAttachmentType = NetworkAttachmentType_Internal;
3420
3421 if (!elmMode.getAttributeValue("name", nic.strInternalNetworkName)) // required network name
3422 throw ConfigFileError(this, &elmMode, N_("Required InternalNetwork/@name element is missing"));
3423 }
3424 else if (elmMode.nameEquals("HostOnlyInterface"))
3425 {
3426 enmAttachmentType = NetworkAttachmentType_HostOnly;
3427
3428 if (!elmMode.getAttributeValue("name", nic.strHostOnlyName)) // required network name
3429 throw ConfigFileError(this, &elmMode, N_("Required HostOnlyInterface/@name element is missing"));
3430 }
3431 else if (elmMode.nameEquals("GenericInterface"))
3432 {
3433 enmAttachmentType = NetworkAttachmentType_Generic;
3434
3435 elmMode.getAttributeValue("driver", nic.strGenericDriver); // optional network attachment driver
3436
3437 // get all properties
3438 xml::NodesLoop nl(elmMode);
3439 const xml::ElementNode *pelmModeChild;
3440 while ((pelmModeChild = nl.forAllNodes()))
3441 {
3442 if (pelmModeChild->nameEquals("Property"))
3443 {
3444 Utf8Str strPropName, strPropValue;
3445 if ( pelmModeChild->getAttributeValue("name", strPropName)
3446 && pelmModeChild->getAttributeValue("value", strPropValue) )
3447 nic.genericProperties[strPropName] = strPropValue;
3448 else
3449 throw ConfigFileError(this, pelmModeChild, N_("Required GenericInterface/Property/@name or @value attribute is missing"));
3450 }
3451 }
3452 }
3453 else if (elmMode.nameEquals("NATNetwork"))
3454 {
3455 enmAttachmentType = NetworkAttachmentType_NATNetwork;
3456
3457 if (!elmMode.getAttributeValue("name", nic.strNATNetworkName)) // required network name
3458 throw ConfigFileError(this, &elmMode, N_("Required NATNetwork/@name element is missing"));
3459 }
3460 else if (elmMode.nameEquals("VDE"))
3461 {
3462 enmAttachmentType = NetworkAttachmentType_Generic;
3463
3464 com::Utf8Str strVDEName;
3465 elmMode.getAttributeValue("network", strVDEName); // optional network name
3466 nic.strGenericDriver = "VDE";
3467 nic.genericProperties["network"] = strVDEName;
3468 }
3469
3470 if (fEnabled && enmAttachmentType != NetworkAttachmentType_Null)
3471 nic.mode = enmAttachmentType;
3472}
3473
3474/**
3475 * Called from MachineConfigFile::readHardware() to read serial port information.
3476 * @param elmUART
3477 * @param ll
3478 */
3479void MachineConfigFile::readSerialPorts(const xml::ElementNode &elmUART,
3480 SerialPortsList &ll)
3481{
3482 xml::NodesLoop nl1(elmUART, "Port");
3483 const xml::ElementNode *pelmPort;
3484 while ((pelmPort = nl1.forAllNodes()))
3485 {
3486 SerialPort port;
3487 if (!pelmPort->getAttributeValue("slot", port.ulSlot))
3488 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@slot attribute is missing"));
3489
3490 // slot must be unique
3491 for (SerialPortsList::const_iterator it = ll.begin();
3492 it != ll.end();
3493 ++it)
3494 if ((*it).ulSlot == port.ulSlot)
3495 throw ConfigFileError(this, pelmPort, N_("Invalid value %RU32 in UART/Port/@slot attribute: value is not unique"), port.ulSlot);
3496
3497 if (!pelmPort->getAttributeValue("enabled", port.fEnabled))
3498 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@enabled attribute is missing"));
3499 if (!pelmPort->getAttributeValue("IOBase", port.ulIOBase))
3500 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@IOBase attribute is missing"));
3501 if (!pelmPort->getAttributeValue("IRQ", port.ulIRQ))
3502 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@IRQ attribute is missing"));
3503
3504 Utf8Str strPortMode;
3505 if (!pelmPort->getAttributeValue("hostMode", strPortMode))
3506 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@hostMode attribute is missing"));
3507 if (strPortMode == "RawFile")
3508 port.portMode = PortMode_RawFile;
3509 else if (strPortMode == "HostPipe")
3510 port.portMode = PortMode_HostPipe;
3511 else if (strPortMode == "HostDevice")
3512 port.portMode = PortMode_HostDevice;
3513 else if (strPortMode == "Disconnected")
3514 port.portMode = PortMode_Disconnected;
3515 else if (strPortMode == "TCP")
3516 port.portMode = PortMode_TCP;
3517 else
3518 throw ConfigFileError(this, pelmPort, N_("Invalid value '%s' in UART/Port/@hostMode attribute"), strPortMode.c_str());
3519
3520 pelmPort->getAttributeValue("path", port.strPath);
3521 pelmPort->getAttributeValue("server", port.fServer);
3522
3523 ll.push_back(port);
3524 }
3525}
3526
3527/**
3528 * Called from MachineConfigFile::readHardware() to read parallel port information.
3529 * @param elmLPT
3530 * @param ll
3531 */
3532void MachineConfigFile::readParallelPorts(const xml::ElementNode &elmLPT,
3533 ParallelPortsList &ll)
3534{
3535 xml::NodesLoop nl1(elmLPT, "Port");
3536 const xml::ElementNode *pelmPort;
3537 while ((pelmPort = nl1.forAllNodes()))
3538 {
3539 ParallelPort port;
3540 if (!pelmPort->getAttributeValue("slot", port.ulSlot))
3541 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@slot attribute is missing"));
3542
3543 // slot must be unique
3544 for (ParallelPortsList::const_iterator it = ll.begin();
3545 it != ll.end();
3546 ++it)
3547 if ((*it).ulSlot == port.ulSlot)
3548 throw ConfigFileError(this, pelmPort, N_("Invalid value %RU32 in LPT/Port/@slot attribute: value is not unique"), port.ulSlot);
3549
3550 if (!pelmPort->getAttributeValue("enabled", port.fEnabled))
3551 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@enabled attribute is missing"));
3552 if (!pelmPort->getAttributeValue("IOBase", port.ulIOBase))
3553 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@IOBase attribute is missing"));
3554 if (!pelmPort->getAttributeValue("IRQ", port.ulIRQ))
3555 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@IRQ attribute is missing"));
3556
3557 pelmPort->getAttributeValue("path", port.strPath);
3558
3559 ll.push_back(port);
3560 }
3561}
3562
3563/**
3564 * Called from MachineConfigFile::readHardware() to read audio adapter information
3565 * and maybe fix driver information depending on the current host hardware.
3566 *
3567 * @param elmAudioAdapter "AudioAdapter" XML element.
3568 * @param hw
3569 */
3570void MachineConfigFile::readAudioAdapter(const xml::ElementNode &elmAudioAdapter,
3571 AudioAdapter &aa)
3572{
3573 if (m->sv >= SettingsVersion_v1_15)
3574 {
3575 // get all properties
3576 xml::NodesLoop nl1(elmAudioAdapter, "Property");
3577 const xml::ElementNode *pelmModeChild;
3578 while ((pelmModeChild = nl1.forAllNodes()))
3579 {
3580 Utf8Str strPropName, strPropValue;
3581 if ( pelmModeChild->getAttributeValue("name", strPropName)
3582 && pelmModeChild->getAttributeValue("value", strPropValue) )
3583 aa.properties[strPropName] = strPropValue;
3584 else
3585 throw ConfigFileError(this, pelmModeChild, N_("Required AudioAdapter/Property/@name or @value attribute "
3586 "is missing"));
3587 }
3588 }
3589
3590 if (m->sv <= SettingsVersion_v1_14)
3591 {
3592 // Special default handling: tag presence hints it should be enabled
3593 aa.fEnabled = true;
3594 }
3595 elmAudioAdapter.getAttributeValue("enabled", aa.fEnabled);
3596
3597 Utf8Str strTemp;
3598 if (elmAudioAdapter.getAttributeValue("controller", strTemp))
3599 {
3600 if (strTemp == "SB16")
3601 aa.controllerType = AudioControllerType_SB16;
3602 else if (strTemp == "AC97")
3603 aa.controllerType = AudioControllerType_AC97;
3604 else if (strTemp == "HDA")
3605 aa.controllerType = AudioControllerType_HDA;
3606 else
3607 throw ConfigFileError(this, &elmAudioAdapter, N_("Invalid value '%s' in AudioAdapter/@controller attribute"), strTemp.c_str());
3608 }
3609
3610 if (elmAudioAdapter.getAttributeValue("codec", strTemp))
3611 {
3612 if (strTemp == "SB16")
3613 aa.codecType = AudioCodecType_SB16;
3614 else if (strTemp == "STAC9700")
3615 aa.codecType = AudioCodecType_STAC9700;
3616 else if (strTemp == "AD1980")
3617 aa.codecType = AudioCodecType_AD1980;
3618 else if (strTemp == "STAC9221")
3619 aa.codecType = AudioCodecType_STAC9221;
3620 else
3621 throw ConfigFileError(this, &elmAudioAdapter, N_("Invalid value '%s' in AudioAdapter/@codec attribute"), strTemp.c_str());
3622 }
3623 else
3624 {
3625 /* No codec attribute provided; use defaults. */
3626 switch (aa.controllerType)
3627 {
3628 case AudioControllerType_AC97:
3629 aa.codecType = AudioCodecType_STAC9700;
3630 break;
3631 case AudioControllerType_SB16:
3632 aa.codecType = AudioCodecType_SB16;
3633 break;
3634 case AudioControllerType_HDA:
3635 aa.codecType = AudioCodecType_STAC9221;
3636 break;
3637 default:
3638 Assert(false); /* We just checked the controller type above. */
3639 }
3640 }
3641
3642 if (elmAudioAdapter.getAttributeValue("driver", strTemp))
3643 {
3644 // settings before 1.3 used lower case so make sure this is case-insensitive
3645 strTemp.toUpper();
3646 if (strTemp == "NULL")
3647 aa.driverType = AudioDriverType_Null;
3648 else if (strTemp == "WINMM")
3649 aa.driverType = AudioDriverType_WinMM;
3650 else if ( (strTemp == "DIRECTSOUND") || (strTemp == "DSOUND") )
3651 aa.driverType = AudioDriverType_DirectSound;
3652 else if (strTemp == "SOLAUDIO")
3653 aa.driverType = AudioDriverType_SolAudio;
3654 else if (strTemp == "ALSA")
3655 aa.driverType = AudioDriverType_ALSA;
3656 else if (strTemp == "PULSE")
3657 aa.driverType = AudioDriverType_Pulse;
3658 else if (strTemp == "OSS")
3659 aa.driverType = AudioDriverType_OSS;
3660 else if (strTemp == "COREAUDIO")
3661 aa.driverType = AudioDriverType_CoreAudio;
3662 else if (strTemp == "MMPM")
3663 aa.driverType = AudioDriverType_MMPM;
3664 else
3665 throw ConfigFileError(this, &elmAudioAdapter, N_("Invalid value '%s' in AudioAdapter/@driver attribute"), strTemp.c_str());
3666
3667 // now check if this is actually supported on the current host platform;
3668 // people might be opening a file created on a Windows host, and that
3669 // VM should still start on a Linux host
3670 if (!isAudioDriverAllowedOnThisHost(aa.driverType))
3671 aa.driverType = getHostDefaultAudioDriver();
3672 }
3673}
3674
3675/**
3676 * Called from MachineConfigFile::readHardware() to read guest property information.
3677 * @param elmGuestProperties
3678 * @param hw
3679 */
3680void MachineConfigFile::readGuestProperties(const xml::ElementNode &elmGuestProperties,
3681 Hardware &hw)
3682{
3683 xml::NodesLoop nl1(elmGuestProperties, "GuestProperty");
3684 const xml::ElementNode *pelmProp;
3685 while ((pelmProp = nl1.forAllNodes()))
3686 {
3687 GuestProperty prop;
3688 pelmProp->getAttributeValue("name", prop.strName);
3689 pelmProp->getAttributeValue("value", prop.strValue);
3690
3691 pelmProp->getAttributeValue("timestamp", prop.timestamp);
3692 pelmProp->getAttributeValue("flags", prop.strFlags);
3693 hw.llGuestProperties.push_back(prop);
3694 }
3695}
3696
3697/**
3698 * Helper function to read attributes that are common to \<SATAController\> (pre-1.7)
3699 * and \<StorageController\>.
3700 * @param elmStorageController
3701 * @param strg
3702 */
3703void MachineConfigFile::readStorageControllerAttributes(const xml::ElementNode &elmStorageController,
3704 StorageController &sctl)
3705{
3706 elmStorageController.getAttributeValue("PortCount", sctl.ulPortCount);
3707 elmStorageController.getAttributeValue("useHostIOCache", sctl.fUseHostIOCache);
3708}
3709
3710/**
3711 * Reads in a \<Hardware\> block and stores it in the given structure. Used
3712 * both directly from readMachine and from readSnapshot, since snapshots
3713 * have their own hardware sections.
3714 *
3715 * For legacy pre-1.7 settings we also need a storage structure because
3716 * the IDE and SATA controllers used to be defined under \<Hardware\>.
3717 *
3718 * @param elmHardware
3719 * @param hw
3720 */
3721void MachineConfigFile::readHardware(const xml::ElementNode &elmHardware,
3722 Hardware &hw)
3723{
3724 if (m->sv >= SettingsVersion_v1_16)
3725 {
3726 /* Starting with VirtualBox 5.1 the default is Default, before it was
3727 * Legacy. This needs to matched by areParavirtDefaultSettings(). */
3728 hw.paravirtProvider = ParavirtProvider_Default;
3729 }
3730
3731 if (!elmHardware.getAttributeValue("version", hw.strVersion))
3732 {
3733 /* KLUDGE ALERT! For a while during the 3.1 development this was not
3734 written because it was thought to have a default value of "2". For
3735 sv <= 1.3 it defaults to "1" because the attribute didn't exist,
3736 while for 1.4+ it is sort of mandatory. Now, the buggy XML writer
3737 code only wrote 1.7 and later. So, if it's a 1.7+ XML file and it's
3738 missing the hardware version, then it probably should be "2" instead
3739 of "1". */
3740 if (m->sv < SettingsVersion_v1_7)
3741 hw.strVersion = "1";
3742 else
3743 hw.strVersion = "2";
3744 }
3745 Utf8Str strUUID;
3746 if (elmHardware.getAttributeValue("uuid", strUUID))
3747 parseUUID(hw.uuid, strUUID);
3748
3749 xml::NodesLoop nl1(elmHardware);
3750 const xml::ElementNode *pelmHwChild;
3751 while ((pelmHwChild = nl1.forAllNodes()))
3752 {
3753 if (pelmHwChild->nameEquals("CPU"))
3754 {
3755 if (!pelmHwChild->getAttributeValue("count", hw.cCPUs))
3756 {
3757 // pre-1.5 variant; not sure if this actually exists in the wild anywhere
3758 const xml::ElementNode *pelmCPUChild;
3759 if ((pelmCPUChild = pelmHwChild->findChildElement("CPUCount")))
3760 pelmCPUChild->getAttributeValue("count", hw.cCPUs);
3761 }
3762
3763 pelmHwChild->getAttributeValue("hotplug", hw.fCpuHotPlug);
3764 pelmHwChild->getAttributeValue("executionCap", hw.ulCpuExecutionCap);
3765
3766 const xml::ElementNode *pelmCPUChild;
3767 if (hw.fCpuHotPlug)
3768 {
3769 if ((pelmCPUChild = pelmHwChild->findChildElement("CpuTree")))
3770 readCpuTree(*pelmCPUChild, hw.llCpus);
3771 }
3772
3773 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtEx")))
3774 {
3775 pelmCPUChild->getAttributeValue("enabled", hw.fHardwareVirt);
3776 }
3777 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExNestedPaging")))
3778 pelmCPUChild->getAttributeValue("enabled", hw.fNestedPaging);
3779 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExLargePages")))
3780 pelmCPUChild->getAttributeValue("enabled", hw.fLargePages);
3781 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExVPID")))
3782 pelmCPUChild->getAttributeValue("enabled", hw.fVPID);
3783 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExUX")))
3784 pelmCPUChild->getAttributeValue("enabled", hw.fUnrestrictedExecution);
3785 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtForce")))
3786 pelmCPUChild->getAttributeValue("enabled", hw.fHardwareVirtForce);
3787
3788 if (!(pelmCPUChild = pelmHwChild->findChildElement("PAE")))
3789 {
3790 /* The default for pre 3.1 was false, so we must respect that. */
3791 if (m->sv < SettingsVersion_v1_9)
3792 hw.fPAE = false;
3793 }
3794 else
3795 pelmCPUChild->getAttributeValue("enabled", hw.fPAE);
3796
3797 bool fLongMode;
3798 if ( (pelmCPUChild = pelmHwChild->findChildElement("LongMode"))
3799 && pelmCPUChild->getAttributeValue("enabled", fLongMode) )
3800 hw.enmLongMode = fLongMode ? Hardware::LongMode_Enabled : Hardware::LongMode_Disabled;
3801 else
3802 hw.enmLongMode = Hardware::LongMode_Legacy;
3803
3804 if ((pelmCPUChild = pelmHwChild->findChildElement("SyntheticCpu")))
3805 {
3806 bool fSyntheticCpu = false;
3807 pelmCPUChild->getAttributeValue("enabled", fSyntheticCpu);
3808 hw.uCpuIdPortabilityLevel = fSyntheticCpu ? 1 : 0;
3809 }
3810 pelmHwChild->getAttributeValue("CpuIdPortabilityLevel", hw.uCpuIdPortabilityLevel);
3811 pelmHwChild->getAttributeValue("CpuProfile", hw.strCpuProfile);
3812
3813 if ((pelmCPUChild = pelmHwChild->findChildElement("TripleFaultReset")))
3814 pelmCPUChild->getAttributeValue("enabled", hw.fTripleFaultReset);
3815
3816 if ((pelmCPUChild = pelmHwChild->findChildElement("APIC")))
3817 pelmCPUChild->getAttributeValue("enabled", hw.fAPIC);
3818 if ((pelmCPUChild = pelmHwChild->findChildElement("X2APIC")))
3819 pelmCPUChild->getAttributeValue("enabled", hw.fX2APIC);
3820 if (hw.fX2APIC)
3821 hw.fAPIC = true;
3822
3823 if ((pelmCPUChild = pelmHwChild->findChildElement("CpuIdTree")))
3824 readCpuIdTree(*pelmCPUChild, hw.llCpuIdLeafs);
3825 }
3826 else if (pelmHwChild->nameEquals("Memory"))
3827 {
3828 pelmHwChild->getAttributeValue("RAMSize", hw.ulMemorySizeMB);
3829 pelmHwChild->getAttributeValue("PageFusion", hw.fPageFusionEnabled);
3830 }
3831 else if (pelmHwChild->nameEquals("Firmware"))
3832 {
3833 Utf8Str strFirmwareType;
3834 if (pelmHwChild->getAttributeValue("type", strFirmwareType))
3835 {
3836 if ( (strFirmwareType == "BIOS")
3837 || (strFirmwareType == "1") // some trunk builds used the number here
3838 )
3839 hw.firmwareType = FirmwareType_BIOS;
3840 else if ( (strFirmwareType == "EFI")
3841 || (strFirmwareType == "2") // some trunk builds used the number here
3842 )
3843 hw.firmwareType = FirmwareType_EFI;
3844 else if ( strFirmwareType == "EFI32")
3845 hw.firmwareType = FirmwareType_EFI32;
3846 else if ( strFirmwareType == "EFI64")
3847 hw.firmwareType = FirmwareType_EFI64;
3848 else if ( strFirmwareType == "EFIDUAL")
3849 hw.firmwareType = FirmwareType_EFIDUAL;
3850 else
3851 throw ConfigFileError(this,
3852 pelmHwChild,
3853 N_("Invalid value '%s' in Firmware/@type"),
3854 strFirmwareType.c_str());
3855 }
3856 }
3857 else if (pelmHwChild->nameEquals("HID"))
3858 {
3859 Utf8Str strHIDType;
3860 if (pelmHwChild->getAttributeValue("Keyboard", strHIDType))
3861 {
3862 if (strHIDType == "None")
3863 hw.keyboardHIDType = KeyboardHIDType_None;
3864 else if (strHIDType == "USBKeyboard")
3865 hw.keyboardHIDType = KeyboardHIDType_USBKeyboard;
3866 else if (strHIDType == "PS2Keyboard")
3867 hw.keyboardHIDType = KeyboardHIDType_PS2Keyboard;
3868 else if (strHIDType == "ComboKeyboard")
3869 hw.keyboardHIDType = KeyboardHIDType_ComboKeyboard;
3870 else
3871 throw ConfigFileError(this,
3872 pelmHwChild,
3873 N_("Invalid value '%s' in HID/Keyboard/@type"),
3874 strHIDType.c_str());
3875 }
3876 if (pelmHwChild->getAttributeValue("Pointing", strHIDType))
3877 {
3878 if (strHIDType == "None")
3879 hw.pointingHIDType = PointingHIDType_None;
3880 else if (strHIDType == "USBMouse")
3881 hw.pointingHIDType = PointingHIDType_USBMouse;
3882 else if (strHIDType == "USBTablet")
3883 hw.pointingHIDType = PointingHIDType_USBTablet;
3884 else if (strHIDType == "PS2Mouse")
3885 hw.pointingHIDType = PointingHIDType_PS2Mouse;
3886 else if (strHIDType == "ComboMouse")
3887 hw.pointingHIDType = PointingHIDType_ComboMouse;
3888 else if (strHIDType == "USBMultiTouch")
3889 hw.pointingHIDType = PointingHIDType_USBMultiTouch;
3890 else
3891 throw ConfigFileError(this,
3892 pelmHwChild,
3893 N_("Invalid value '%s' in HID/Pointing/@type"),
3894 strHIDType.c_str());
3895 }
3896 }
3897 else if (pelmHwChild->nameEquals("Chipset"))
3898 {
3899 Utf8Str strChipsetType;
3900 if (pelmHwChild->getAttributeValue("type", strChipsetType))
3901 {
3902 if (strChipsetType == "PIIX3")
3903 hw.chipsetType = ChipsetType_PIIX3;
3904 else if (strChipsetType == "ICH9")
3905 hw.chipsetType = ChipsetType_ICH9;
3906 else
3907 throw ConfigFileError(this,
3908 pelmHwChild,
3909 N_("Invalid value '%s' in Chipset/@type"),
3910 strChipsetType.c_str());
3911 }
3912 }
3913 else if (pelmHwChild->nameEquals("Paravirt"))
3914 {
3915 Utf8Str strProvider;
3916 if (pelmHwChild->getAttributeValue("provider", strProvider))
3917 {
3918 if (strProvider == "None")
3919 hw.paravirtProvider = ParavirtProvider_None;
3920 else if (strProvider == "Default")
3921 hw.paravirtProvider = ParavirtProvider_Default;
3922 else if (strProvider == "Legacy")
3923 hw.paravirtProvider = ParavirtProvider_Legacy;
3924 else if (strProvider == "Minimal")
3925 hw.paravirtProvider = ParavirtProvider_Minimal;
3926 else if (strProvider == "HyperV")
3927 hw.paravirtProvider = ParavirtProvider_HyperV;
3928 else if (strProvider == "KVM")
3929 hw.paravirtProvider = ParavirtProvider_KVM;
3930 else
3931 throw ConfigFileError(this,
3932 pelmHwChild,
3933 N_("Invalid value '%s' in Paravirt/@provider attribute"),
3934 strProvider.c_str());
3935 }
3936
3937 pelmHwChild->getAttributeValue("debug", hw.strParavirtDebug);
3938 }
3939 else if (pelmHwChild->nameEquals("HPET"))
3940 {
3941 pelmHwChild->getAttributeValue("enabled", hw.fHPETEnabled);
3942 }
3943 else if (pelmHwChild->nameEquals("Boot"))
3944 {
3945 hw.mapBootOrder.clear();
3946
3947 xml::NodesLoop nl2(*pelmHwChild, "Order");
3948 const xml::ElementNode *pelmOrder;
3949 while ((pelmOrder = nl2.forAllNodes()))
3950 {
3951 uint32_t ulPos;
3952 Utf8Str strDevice;
3953 if (!pelmOrder->getAttributeValue("position", ulPos))
3954 throw ConfigFileError(this, pelmOrder, N_("Required Boot/Order/@position attribute is missing"));
3955
3956 if ( ulPos < 1
3957 || ulPos > SchemaDefs::MaxBootPosition
3958 )
3959 throw ConfigFileError(this,
3960 pelmOrder,
3961 N_("Invalid value '%RU32' in Boot/Order/@position: must be greater than 0 and less than %RU32"),
3962 ulPos,
3963 SchemaDefs::MaxBootPosition + 1);
3964 // XML is 1-based but internal data is 0-based
3965 --ulPos;
3966
3967 if (hw.mapBootOrder.find(ulPos) != hw.mapBootOrder.end())
3968 throw ConfigFileError(this, pelmOrder, N_("Invalid value '%RU32' in Boot/Order/@position: value is not unique"), ulPos);
3969
3970 if (!pelmOrder->getAttributeValue("device", strDevice))
3971 throw ConfigFileError(this, pelmOrder, N_("Required Boot/Order/@device attribute is missing"));
3972
3973 DeviceType_T type;
3974 if (strDevice == "None")
3975 type = DeviceType_Null;
3976 else if (strDevice == "Floppy")
3977 type = DeviceType_Floppy;
3978 else if (strDevice == "DVD")
3979 type = DeviceType_DVD;
3980 else if (strDevice == "HardDisk")
3981 type = DeviceType_HardDisk;
3982 else if (strDevice == "Network")
3983 type = DeviceType_Network;
3984 else
3985 throw ConfigFileError(this, pelmOrder, N_("Invalid value '%s' in Boot/Order/@device attribute"), strDevice.c_str());
3986 hw.mapBootOrder[ulPos] = type;
3987 }
3988 }
3989 else if (pelmHwChild->nameEquals("Display"))
3990 {
3991 Utf8Str strGraphicsControllerType;
3992 if (!pelmHwChild->getAttributeValue("controller", strGraphicsControllerType))
3993 hw.graphicsControllerType = GraphicsControllerType_VBoxVGA;
3994 else
3995 {
3996 strGraphicsControllerType.toUpper();
3997 GraphicsControllerType_T type;
3998 if (strGraphicsControllerType == "VBOXVGA")
3999 type = GraphicsControllerType_VBoxVGA;
4000 else if (strGraphicsControllerType == "VMSVGA")
4001 type = GraphicsControllerType_VMSVGA;
4002 else if (strGraphicsControllerType == "NONE")
4003 type = GraphicsControllerType_Null;
4004 else
4005 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in Display/@controller attribute"), strGraphicsControllerType.c_str());
4006 hw.graphicsControllerType = type;
4007 }
4008 pelmHwChild->getAttributeValue("VRAMSize", hw.ulVRAMSizeMB);
4009 if (!pelmHwChild->getAttributeValue("monitorCount", hw.cMonitors))
4010 pelmHwChild->getAttributeValue("MonitorCount", hw.cMonitors); // pre-v1.5 variant
4011 if (!pelmHwChild->getAttributeValue("accelerate3D", hw.fAccelerate3D))
4012 pelmHwChild->getAttributeValue("Accelerate3D", hw.fAccelerate3D); // pre-v1.5 variant
4013 pelmHwChild->getAttributeValue("accelerate2DVideo", hw.fAccelerate2DVideo);
4014 }
4015 else if (pelmHwChild->nameEquals("VideoCapture"))
4016 {
4017 pelmHwChild->getAttributeValue("enabled", hw.fVideoCaptureEnabled);
4018 pelmHwChild->getAttributeValue("screens", hw.u64VideoCaptureScreens);
4019 pelmHwChild->getAttributeValuePath("file", hw.strVideoCaptureFile);
4020 pelmHwChild->getAttributeValue("horzRes", hw.ulVideoCaptureHorzRes);
4021 pelmHwChild->getAttributeValue("vertRes", hw.ulVideoCaptureVertRes);
4022 pelmHwChild->getAttributeValue("rate", hw.ulVideoCaptureRate);
4023 pelmHwChild->getAttributeValue("fps", hw.ulVideoCaptureFPS);
4024 pelmHwChild->getAttributeValue("maxTime", hw.ulVideoCaptureMaxTime);
4025 pelmHwChild->getAttributeValue("maxSize", hw.ulVideoCaptureMaxSize);
4026 }
4027 else if (pelmHwChild->nameEquals("RemoteDisplay"))
4028 {
4029 pelmHwChild->getAttributeValue("enabled", hw.vrdeSettings.fEnabled);
4030
4031 Utf8Str str;
4032 if (pelmHwChild->getAttributeValue("port", str))
4033 hw.vrdeSettings.mapProperties["TCP/Ports"] = str;
4034 if (pelmHwChild->getAttributeValue("netAddress", str))
4035 hw.vrdeSettings.mapProperties["TCP/Address"] = str;
4036
4037 Utf8Str strAuthType;
4038 if (pelmHwChild->getAttributeValue("authType", strAuthType))
4039 {
4040 // settings before 1.3 used lower case so make sure this is case-insensitive
4041 strAuthType.toUpper();
4042 if (strAuthType == "NULL")
4043 hw.vrdeSettings.authType = AuthType_Null;
4044 else if (strAuthType == "GUEST")
4045 hw.vrdeSettings.authType = AuthType_Guest;
4046 else if (strAuthType == "EXTERNAL")
4047 hw.vrdeSettings.authType = AuthType_External;
4048 else
4049 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in RemoteDisplay/@authType attribute"), strAuthType.c_str());
4050 }
4051
4052 pelmHwChild->getAttributeValue("authLibrary", hw.vrdeSettings.strAuthLibrary);
4053 pelmHwChild->getAttributeValue("authTimeout", hw.vrdeSettings.ulAuthTimeout);
4054 pelmHwChild->getAttributeValue("allowMultiConnection", hw.vrdeSettings.fAllowMultiConnection);
4055 pelmHwChild->getAttributeValue("reuseSingleConnection", hw.vrdeSettings.fReuseSingleConnection);
4056
4057 /* 3.2 and 4.0 betas, 4.0 has this information in VRDEProperties. */
4058 const xml::ElementNode *pelmVideoChannel;
4059 if ((pelmVideoChannel = pelmHwChild->findChildElement("VideoChannel")))
4060 {
4061 bool fVideoChannel = false;
4062 pelmVideoChannel->getAttributeValue("enabled", fVideoChannel);
4063 hw.vrdeSettings.mapProperties["VideoChannel/Enabled"] = fVideoChannel? "true": "false";
4064
4065 uint32_t ulVideoChannelQuality = 75;
4066 pelmVideoChannel->getAttributeValue("quality", ulVideoChannelQuality);
4067 ulVideoChannelQuality = RT_CLAMP(ulVideoChannelQuality, 10, 100);
4068 char *pszBuffer = NULL;
4069 if (RTStrAPrintf(&pszBuffer, "%d", ulVideoChannelQuality) >= 0)
4070 {
4071 hw.vrdeSettings.mapProperties["VideoChannel/Quality"] = pszBuffer;
4072 RTStrFree(pszBuffer);
4073 }
4074 else
4075 hw.vrdeSettings.mapProperties["VideoChannel/Quality"] = "75";
4076 }
4077 pelmHwChild->getAttributeValue("VRDEExtPack", hw.vrdeSettings.strVrdeExtPack);
4078
4079 const xml::ElementNode *pelmProperties = pelmHwChild->findChildElement("VRDEProperties");
4080 if (pelmProperties != NULL)
4081 {
4082 xml::NodesLoop nl(*pelmProperties);
4083 const xml::ElementNode *pelmProperty;
4084 while ((pelmProperty = nl.forAllNodes()))
4085 {
4086 if (pelmProperty->nameEquals("Property"))
4087 {
4088 /* <Property name="TCP/Ports" value="3000-3002"/> */
4089 Utf8Str strName, strValue;
4090 if ( pelmProperty->getAttributeValue("name", strName)
4091 && pelmProperty->getAttributeValue("value", strValue))
4092 hw.vrdeSettings.mapProperties[strName] = strValue;
4093 else
4094 throw ConfigFileError(this, pelmProperty, N_("Required VRDE Property/@name or @value attribute is missing"));
4095 }
4096 }
4097 }
4098 }
4099 else if (pelmHwChild->nameEquals("BIOS"))
4100 {
4101 const xml::ElementNode *pelmBIOSChild;
4102 if ((pelmBIOSChild = pelmHwChild->findChildElement("ACPI")))
4103 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fACPIEnabled);
4104 if ((pelmBIOSChild = pelmHwChild->findChildElement("IOAPIC")))
4105 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fIOAPICEnabled);
4106 if ((pelmBIOSChild = pelmHwChild->findChildElement("APIC")))
4107 {
4108 Utf8Str strAPIC;
4109 if (pelmBIOSChild->getAttributeValue("mode", strAPIC))
4110 {
4111 strAPIC.toUpper();
4112 if (strAPIC == "DISABLED")
4113 hw.biosSettings.apicMode = APICMode_Disabled;
4114 else if (strAPIC == "APIC")
4115 hw.biosSettings.apicMode = APICMode_APIC;
4116 else if (strAPIC == "X2APIC")
4117 hw.biosSettings.apicMode = APICMode_X2APIC;
4118 else
4119 throw ConfigFileError(this, pelmBIOSChild, N_("Invalid value '%s' in APIC/@mode attribute"), strAPIC.c_str());
4120 }
4121 }
4122 if ((pelmBIOSChild = pelmHwChild->findChildElement("Logo")))
4123 {
4124 pelmBIOSChild->getAttributeValue("fadeIn", hw.biosSettings.fLogoFadeIn);
4125 pelmBIOSChild->getAttributeValue("fadeOut", hw.biosSettings.fLogoFadeOut);
4126 pelmBIOSChild->getAttributeValue("displayTime", hw.biosSettings.ulLogoDisplayTime);
4127 pelmBIOSChild->getAttributeValue("imagePath", hw.biosSettings.strLogoImagePath);
4128 }
4129 if ((pelmBIOSChild = pelmHwChild->findChildElement("BootMenu")))
4130 {
4131 Utf8Str strBootMenuMode;
4132 if (pelmBIOSChild->getAttributeValue("mode", strBootMenuMode))
4133 {
4134 // settings before 1.3 used lower case so make sure this is case-insensitive
4135 strBootMenuMode.toUpper();
4136 if (strBootMenuMode == "DISABLED")
4137 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_Disabled;
4138 else if (strBootMenuMode == "MENUONLY")
4139 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_MenuOnly;
4140 else if (strBootMenuMode == "MESSAGEANDMENU")
4141 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_MessageAndMenu;
4142 else
4143 throw ConfigFileError(this, pelmBIOSChild, N_("Invalid value '%s' in BootMenu/@mode attribute"), strBootMenuMode.c_str());
4144 }
4145 }
4146 if ((pelmBIOSChild = pelmHwChild->findChildElement("PXEDebug")))
4147 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fPXEDebugEnabled);
4148 if ((pelmBIOSChild = pelmHwChild->findChildElement("TimeOffset")))
4149 pelmBIOSChild->getAttributeValue("value", hw.biosSettings.llTimeOffset);
4150
4151 // legacy BIOS/IDEController (pre 1.7)
4152 if ( (m->sv < SettingsVersion_v1_7)
4153 && (pelmBIOSChild = pelmHwChild->findChildElement("IDEController"))
4154 )
4155 {
4156 StorageController sctl;
4157 sctl.strName = "IDE Controller";
4158 sctl.storageBus = StorageBus_IDE;
4159
4160 Utf8Str strType;
4161 if (pelmBIOSChild->getAttributeValue("type", strType))
4162 {
4163 if (strType == "PIIX3")
4164 sctl.controllerType = StorageControllerType_PIIX3;
4165 else if (strType == "PIIX4")
4166 sctl.controllerType = StorageControllerType_PIIX4;
4167 else if (strType == "ICH6")
4168 sctl.controllerType = StorageControllerType_ICH6;
4169 else
4170 throw ConfigFileError(this, pelmBIOSChild, N_("Invalid value '%s' for IDEController/@type attribute"), strType.c_str());
4171 }
4172 sctl.ulPortCount = 2;
4173 hw.storage.llStorageControllers.push_back(sctl);
4174 }
4175 }
4176 else if ( (m->sv <= SettingsVersion_v1_14)
4177 && pelmHwChild->nameEquals("USBController"))
4178 {
4179 bool fEnabled = false;
4180
4181 pelmHwChild->getAttributeValue("enabled", fEnabled);
4182 if (fEnabled)
4183 {
4184 /* Create OHCI controller with default name. */
4185 USBController ctrl;
4186
4187 ctrl.strName = "OHCI";
4188 ctrl.enmType = USBControllerType_OHCI;
4189 hw.usbSettings.llUSBControllers.push_back(ctrl);
4190 }
4191
4192 pelmHwChild->getAttributeValue("enabledEhci", fEnabled);
4193 if (fEnabled)
4194 {
4195 /* Create OHCI controller with default name. */
4196 USBController ctrl;
4197
4198 ctrl.strName = "EHCI";
4199 ctrl.enmType = USBControllerType_EHCI;
4200 hw.usbSettings.llUSBControllers.push_back(ctrl);
4201 }
4202
4203 readUSBDeviceFilters(*pelmHwChild,
4204 hw.usbSettings.llDeviceFilters);
4205 }
4206 else if (pelmHwChild->nameEquals("USB"))
4207 {
4208 const xml::ElementNode *pelmUSBChild;
4209
4210 if ((pelmUSBChild = pelmHwChild->findChildElement("Controllers")))
4211 {
4212 xml::NodesLoop nl2(*pelmUSBChild, "Controller");
4213 const xml::ElementNode *pelmCtrl;
4214
4215 while ((pelmCtrl = nl2.forAllNodes()))
4216 {
4217 USBController ctrl;
4218 com::Utf8Str strCtrlType;
4219
4220 pelmCtrl->getAttributeValue("name", ctrl.strName);
4221
4222 if (pelmCtrl->getAttributeValue("type", strCtrlType))
4223 {
4224 if (strCtrlType == "OHCI")
4225 ctrl.enmType = USBControllerType_OHCI;
4226 else if (strCtrlType == "EHCI")
4227 ctrl.enmType = USBControllerType_EHCI;
4228 else if (strCtrlType == "XHCI")
4229 ctrl.enmType = USBControllerType_XHCI;
4230 else
4231 throw ConfigFileError(this, pelmCtrl, N_("Invalid value '%s' for Controller/@type attribute"), strCtrlType.c_str());
4232 }
4233
4234 hw.usbSettings.llUSBControllers.push_back(ctrl);
4235 }
4236 }
4237
4238 if ((pelmUSBChild = pelmHwChild->findChildElement("DeviceFilters")))
4239 readUSBDeviceFilters(*pelmUSBChild, hw.usbSettings.llDeviceFilters);
4240 }
4241 else if ( m->sv < SettingsVersion_v1_7
4242 && pelmHwChild->nameEquals("SATAController"))
4243 {
4244 bool f;
4245 if ( pelmHwChild->getAttributeValue("enabled", f)
4246 && f)
4247 {
4248 StorageController sctl;
4249 sctl.strName = "SATA Controller";
4250 sctl.storageBus = StorageBus_SATA;
4251 sctl.controllerType = StorageControllerType_IntelAhci;
4252
4253 readStorageControllerAttributes(*pelmHwChild, sctl);
4254
4255 hw.storage.llStorageControllers.push_back(sctl);
4256 }
4257 }
4258 else if (pelmHwChild->nameEquals("Network"))
4259 readNetworkAdapters(*pelmHwChild, hw.llNetworkAdapters);
4260 else if (pelmHwChild->nameEquals("RTC"))
4261 {
4262 Utf8Str strLocalOrUTC;
4263 machineUserData.fRTCUseUTC = pelmHwChild->getAttributeValue("localOrUTC", strLocalOrUTC)
4264 && strLocalOrUTC == "UTC";
4265 }
4266 else if ( pelmHwChild->nameEquals("UART")
4267 || pelmHwChild->nameEquals("Uart") // used before 1.3
4268 )
4269 readSerialPorts(*pelmHwChild, hw.llSerialPorts);
4270 else if ( pelmHwChild->nameEquals("LPT")
4271 || pelmHwChild->nameEquals("Lpt") // used before 1.3
4272 )
4273 readParallelPorts(*pelmHwChild, hw.llParallelPorts);
4274 else if (pelmHwChild->nameEquals("AudioAdapter"))
4275 readAudioAdapter(*pelmHwChild, hw.audioAdapter);
4276 else if (pelmHwChild->nameEquals("SharedFolders"))
4277 {
4278 xml::NodesLoop nl2(*pelmHwChild, "SharedFolder");
4279 const xml::ElementNode *pelmFolder;
4280 while ((pelmFolder = nl2.forAllNodes()))
4281 {
4282 SharedFolder sf;
4283 pelmFolder->getAttributeValue("name", sf.strName);
4284 pelmFolder->getAttributeValue("hostPath", sf.strHostPath);
4285 pelmFolder->getAttributeValue("writable", sf.fWritable);
4286 pelmFolder->getAttributeValue("autoMount", sf.fAutoMount);
4287 hw.llSharedFolders.push_back(sf);
4288 }
4289 }
4290 else if (pelmHwChild->nameEquals("Clipboard"))
4291 {
4292 Utf8Str strTemp;
4293 if (pelmHwChild->getAttributeValue("mode", strTemp))
4294 {
4295 if (strTemp == "Disabled")
4296 hw.clipboardMode = ClipboardMode_Disabled;
4297 else if (strTemp == "HostToGuest")
4298 hw.clipboardMode = ClipboardMode_HostToGuest;
4299 else if (strTemp == "GuestToHost")
4300 hw.clipboardMode = ClipboardMode_GuestToHost;
4301 else if (strTemp == "Bidirectional")
4302 hw.clipboardMode = ClipboardMode_Bidirectional;
4303 else
4304 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in Clipboard/@mode attribute"), strTemp.c_str());
4305 }
4306 }
4307 else if (pelmHwChild->nameEquals("DragAndDrop"))
4308 {
4309 Utf8Str strTemp;
4310 if (pelmHwChild->getAttributeValue("mode", strTemp))
4311 {
4312 if (strTemp == "Disabled")
4313 hw.dndMode = DnDMode_Disabled;
4314 else if (strTemp == "HostToGuest")
4315 hw.dndMode = DnDMode_HostToGuest;
4316 else if (strTemp == "GuestToHost")
4317 hw.dndMode = DnDMode_GuestToHost;
4318 else if (strTemp == "Bidirectional")
4319 hw.dndMode = DnDMode_Bidirectional;
4320 else
4321 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in DragAndDrop/@mode attribute"), strTemp.c_str());
4322 }
4323 }
4324 else if (pelmHwChild->nameEquals("Guest"))
4325 {
4326 if (!pelmHwChild->getAttributeValue("memoryBalloonSize", hw.ulMemoryBalloonSize))
4327 pelmHwChild->getAttributeValue("MemoryBalloonSize", hw.ulMemoryBalloonSize); // used before 1.3
4328 }
4329 else if (pelmHwChild->nameEquals("GuestProperties"))
4330 readGuestProperties(*pelmHwChild, hw);
4331 else if (pelmHwChild->nameEquals("IO"))
4332 {
4333 const xml::ElementNode *pelmBwGroups;
4334 const xml::ElementNode *pelmIOChild;
4335
4336 if ((pelmIOChild = pelmHwChild->findChildElement("IoCache")))
4337 {
4338 pelmIOChild->getAttributeValue("enabled", hw.ioSettings.fIOCacheEnabled);
4339 pelmIOChild->getAttributeValue("size", hw.ioSettings.ulIOCacheSize);
4340 }
4341
4342 if ((pelmBwGroups = pelmHwChild->findChildElement("BandwidthGroups")))
4343 {
4344 xml::NodesLoop nl2(*pelmBwGroups, "BandwidthGroup");
4345 const xml::ElementNode *pelmBandwidthGroup;
4346 while ((pelmBandwidthGroup = nl2.forAllNodes()))
4347 {
4348 BandwidthGroup gr;
4349 Utf8Str strTemp;
4350
4351 pelmBandwidthGroup->getAttributeValue("name", gr.strName);
4352
4353 if (pelmBandwidthGroup->getAttributeValue("type", strTemp))
4354 {
4355 if (strTemp == "Disk")
4356 gr.enmType = BandwidthGroupType_Disk;
4357 else if (strTemp == "Network")
4358 gr.enmType = BandwidthGroupType_Network;
4359 else
4360 throw ConfigFileError(this, pelmBandwidthGroup, N_("Invalid value '%s' in BandwidthGroup/@type attribute"), strTemp.c_str());
4361 }
4362 else
4363 throw ConfigFileError(this, pelmBandwidthGroup, N_("Missing BandwidthGroup/@type attribute"));
4364
4365 if (!pelmBandwidthGroup->getAttributeValue("maxBytesPerSec", gr.cMaxBytesPerSec))
4366 {
4367 pelmBandwidthGroup->getAttributeValue("maxMbPerSec", gr.cMaxBytesPerSec);
4368 gr.cMaxBytesPerSec *= _1M;
4369 }
4370 hw.ioSettings.llBandwidthGroups.push_back(gr);
4371 }
4372 }
4373 }
4374 else if (pelmHwChild->nameEquals("HostPci"))
4375 {
4376 const xml::ElementNode *pelmDevices;
4377
4378 if ((pelmDevices = pelmHwChild->findChildElement("Devices")))
4379 {
4380 xml::NodesLoop nl2(*pelmDevices, "Device");
4381 const xml::ElementNode *pelmDevice;
4382 while ((pelmDevice = nl2.forAllNodes()))
4383 {
4384 HostPCIDeviceAttachment hpda;
4385
4386 if (!pelmDevice->getAttributeValue("host", hpda.uHostAddress))
4387 throw ConfigFileError(this, pelmDevice, N_("Missing Device/@host attribute"));
4388
4389 if (!pelmDevice->getAttributeValue("guest", hpda.uGuestAddress))
4390 throw ConfigFileError(this, pelmDevice, N_("Missing Device/@guest attribute"));
4391
4392 /* name is optional */
4393 pelmDevice->getAttributeValue("name", hpda.strDeviceName);
4394
4395 hw.pciAttachments.push_back(hpda);
4396 }
4397 }
4398 }
4399 else if (pelmHwChild->nameEquals("EmulatedUSB"))
4400 {
4401 const xml::ElementNode *pelmCardReader;
4402
4403 if ((pelmCardReader = pelmHwChild->findChildElement("CardReader")))
4404 {
4405 pelmCardReader->getAttributeValue("enabled", hw.fEmulatedUSBCardReader);
4406 }
4407 }
4408 else if (pelmHwChild->nameEquals("Frontend"))
4409 {
4410 const xml::ElementNode *pelmDefault;
4411
4412 if ((pelmDefault = pelmHwChild->findChildElement("Default")))
4413 {
4414 pelmDefault->getAttributeValue("type", hw.strDefaultFrontend);
4415 }
4416 }
4417 else if (pelmHwChild->nameEquals("StorageControllers"))
4418 readStorageControllers(*pelmHwChild, hw.storage);
4419 }
4420
4421 if (hw.ulMemorySizeMB == (uint32_t)-1)
4422 throw ConfigFileError(this, &elmHardware, N_("Required Memory/@RAMSize element/attribute is missing"));
4423}
4424
4425/**
4426 * This gets called instead of readStorageControllers() for legacy pre-1.7 settings
4427 * files which have a \<HardDiskAttachments\> node and storage controller settings
4428 * hidden in the \<Hardware\> settings. We set the StorageControllers fields just the
4429 * same, just from different sources.
4430 * @param elmHardware \<Hardware\> XML node.
4431 * @param elmHardDiskAttachments \<HardDiskAttachments\> XML node.
4432 * @param strg
4433 */
4434void MachineConfigFile::readHardDiskAttachments_pre1_7(const xml::ElementNode &elmHardDiskAttachments,
4435 Storage &strg)
4436{
4437 StorageController *pIDEController = NULL;
4438 StorageController *pSATAController = NULL;
4439
4440 for (StorageControllersList::iterator it = strg.llStorageControllers.begin();
4441 it != strg.llStorageControllers.end();
4442 ++it)
4443 {
4444 StorageController &s = *it;
4445 if (s.storageBus == StorageBus_IDE)
4446 pIDEController = &s;
4447 else if (s.storageBus == StorageBus_SATA)
4448 pSATAController = &s;
4449 }
4450
4451 xml::NodesLoop nl1(elmHardDiskAttachments, "HardDiskAttachment");
4452 const xml::ElementNode *pelmAttachment;
4453 while ((pelmAttachment = nl1.forAllNodes()))
4454 {
4455 AttachedDevice att;
4456 Utf8Str strUUID, strBus;
4457
4458 if (!pelmAttachment->getAttributeValue("hardDisk", strUUID))
4459 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@hardDisk attribute is missing"));
4460 parseUUID(att.uuid, strUUID);
4461
4462 if (!pelmAttachment->getAttributeValue("bus", strBus))
4463 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@bus attribute is missing"));
4464 // pre-1.7 'channel' is now port
4465 if (!pelmAttachment->getAttributeValue("channel", att.lPort))
4466 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@channel attribute is missing"));
4467 // pre-1.7 'device' is still device
4468 if (!pelmAttachment->getAttributeValue("device", att.lDevice))
4469 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@device attribute is missing"));
4470
4471 att.deviceType = DeviceType_HardDisk;
4472
4473 if (strBus == "IDE")
4474 {
4475 if (!pIDEController)
4476 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus is 'IDE' but cannot find IDE controller"));
4477 pIDEController->llAttachedDevices.push_back(att);
4478 }
4479 else if (strBus == "SATA")
4480 {
4481 if (!pSATAController)
4482 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus is 'SATA' but cannot find SATA controller"));
4483 pSATAController->llAttachedDevices.push_back(att);
4484 }
4485 else
4486 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus attribute has illegal value '%s'"), strBus.c_str());
4487 }
4488}
4489
4490/**
4491 * Reads in a \<StorageControllers\> block and stores it in the given Storage structure.
4492 * Used both directly from readMachine and from readSnapshot, since snapshots
4493 * have their own storage controllers sections.
4494 *
4495 * This is only called for settings version 1.7 and above; see readHardDiskAttachments_pre1_7()
4496 * for earlier versions.
4497 *
4498 * @param elmStorageControllers
4499 */
4500void MachineConfigFile::readStorageControllers(const xml::ElementNode &elmStorageControllers,
4501 Storage &strg)
4502{
4503 xml::NodesLoop nlStorageControllers(elmStorageControllers, "StorageController");
4504 const xml::ElementNode *pelmController;
4505 while ((pelmController = nlStorageControllers.forAllNodes()))
4506 {
4507 StorageController sctl;
4508
4509 if (!pelmController->getAttributeValue("name", sctl.strName))
4510 throw ConfigFileError(this, pelmController, N_("Required StorageController/@name attribute is missing"));
4511 // canonicalize storage controller names for configs in the switchover
4512 // period.
4513 if (m->sv < SettingsVersion_v1_9)
4514 {
4515 if (sctl.strName == "IDE")
4516 sctl.strName = "IDE Controller";
4517 else if (sctl.strName == "SATA")
4518 sctl.strName = "SATA Controller";
4519 else if (sctl.strName == "SCSI")
4520 sctl.strName = "SCSI Controller";
4521 }
4522
4523 pelmController->getAttributeValue("Instance", sctl.ulInstance);
4524 // default from constructor is 0
4525
4526 pelmController->getAttributeValue("Bootable", sctl.fBootable);
4527 // default from constructor is true which is true
4528 // for settings below version 1.11 because they allowed only
4529 // one controller per type.
4530
4531 Utf8Str strType;
4532 if (!pelmController->getAttributeValue("type", strType))
4533 throw ConfigFileError(this, pelmController, N_("Required StorageController/@type attribute is missing"));
4534
4535 if (strType == "AHCI")
4536 {
4537 sctl.storageBus = StorageBus_SATA;
4538 sctl.controllerType = StorageControllerType_IntelAhci;
4539 }
4540 else if (strType == "LsiLogic")
4541 {
4542 sctl.storageBus = StorageBus_SCSI;
4543 sctl.controllerType = StorageControllerType_LsiLogic;
4544 }
4545 else if (strType == "BusLogic")
4546 {
4547 sctl.storageBus = StorageBus_SCSI;
4548 sctl.controllerType = StorageControllerType_BusLogic;
4549 }
4550 else if (strType == "PIIX3")
4551 {
4552 sctl.storageBus = StorageBus_IDE;
4553 sctl.controllerType = StorageControllerType_PIIX3;
4554 }
4555 else if (strType == "PIIX4")
4556 {
4557 sctl.storageBus = StorageBus_IDE;
4558 sctl.controllerType = StorageControllerType_PIIX4;
4559 }
4560 else if (strType == "ICH6")
4561 {
4562 sctl.storageBus = StorageBus_IDE;
4563 sctl.controllerType = StorageControllerType_ICH6;
4564 }
4565 else if ( (m->sv >= SettingsVersion_v1_9)
4566 && (strType == "I82078")
4567 )
4568 {
4569 sctl.storageBus = StorageBus_Floppy;
4570 sctl.controllerType = StorageControllerType_I82078;
4571 }
4572 else if (strType == "LsiLogicSas")
4573 {
4574 sctl.storageBus = StorageBus_SAS;
4575 sctl.controllerType = StorageControllerType_LsiLogicSas;
4576 }
4577 else if (strType == "USB")
4578 {
4579 sctl.storageBus = StorageBus_USB;
4580 sctl.controllerType = StorageControllerType_USB;
4581 }
4582 else if (strType == "NVMe")
4583 {
4584 sctl.storageBus = StorageBus_PCIe;
4585 sctl.controllerType = StorageControllerType_NVMe;
4586 }
4587 else
4588 throw ConfigFileError(this, pelmController, N_("Invalid value '%s' for StorageController/@type attribute"), strType.c_str());
4589
4590 readStorageControllerAttributes(*pelmController, sctl);
4591
4592 xml::NodesLoop nlAttached(*pelmController, "AttachedDevice");
4593 const xml::ElementNode *pelmAttached;
4594 while ((pelmAttached = nlAttached.forAllNodes()))
4595 {
4596 AttachedDevice att;
4597 Utf8Str strTemp;
4598 pelmAttached->getAttributeValue("type", strTemp);
4599
4600 att.fDiscard = false;
4601 att.fNonRotational = false;
4602 att.fHotPluggable = false;
4603
4604 if (strTemp == "HardDisk")
4605 {
4606 att.deviceType = DeviceType_HardDisk;
4607 pelmAttached->getAttributeValue("nonrotational", att.fNonRotational);
4608 pelmAttached->getAttributeValue("discard", att.fDiscard);
4609 }
4610 else if (m->sv >= SettingsVersion_v1_9)
4611 {
4612 // starting with 1.9 we list DVD and floppy drive info + attachments under <StorageControllers>
4613 if (strTemp == "DVD")
4614 {
4615 att.deviceType = DeviceType_DVD;
4616 pelmAttached->getAttributeValue("passthrough", att.fPassThrough);
4617 pelmAttached->getAttributeValue("tempeject", att.fTempEject);
4618 }
4619 else if (strTemp == "Floppy")
4620 att.deviceType = DeviceType_Floppy;
4621 }
4622
4623 if (att.deviceType != DeviceType_Null)
4624 {
4625 const xml::ElementNode *pelmImage;
4626 // all types can have images attached, but for HardDisk it's required
4627 if (!(pelmImage = pelmAttached->findChildElement("Image")))
4628 {
4629 if (att.deviceType == DeviceType_HardDisk)
4630 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/Image element is missing"));
4631 else
4632 {
4633 // DVDs and floppies can also have <HostDrive> instead of <Image>
4634 const xml::ElementNode *pelmHostDrive;
4635 if ((pelmHostDrive = pelmAttached->findChildElement("HostDrive")))
4636 if (!pelmHostDrive->getAttributeValue("src", att.strHostDriveSrc))
4637 throw ConfigFileError(this, pelmHostDrive, N_("Required AttachedDevice/HostDrive/@src attribute is missing"));
4638 }
4639 }
4640 else
4641 {
4642 if (!pelmImage->getAttributeValue("uuid", strTemp))
4643 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/Image/@uuid attribute is missing"));
4644 parseUUID(att.uuid, strTemp);
4645 }
4646
4647 if (!pelmAttached->getAttributeValue("port", att.lPort))
4648 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/@port attribute is missing"));
4649 if (!pelmAttached->getAttributeValue("device", att.lDevice))
4650 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/@device attribute is missing"));
4651
4652 /* AHCI controller ports are hotpluggable by default, keep compatibility with existing settings. */
4653 if (m->sv >= SettingsVersion_v1_15)
4654 pelmAttached->getAttributeValue("hotpluggable", att.fHotPluggable);
4655 else if (sctl.controllerType == StorageControllerType_IntelAhci)
4656 att.fHotPluggable = true;
4657
4658 pelmAttached->getAttributeValue("bandwidthGroup", att.strBwGroup);
4659 sctl.llAttachedDevices.push_back(att);
4660 }
4661 }
4662
4663 strg.llStorageControllers.push_back(sctl);
4664 }
4665}
4666
4667/**
4668 * This gets called for legacy pre-1.9 settings files after having parsed the
4669 * \<Hardware\> and \<StorageControllers\> sections to parse \<Hardware\> once more
4670 * for the \<DVDDrive\> and \<FloppyDrive\> sections.
4671 *
4672 * Before settings version 1.9, DVD and floppy drives were specified separately
4673 * under \<Hardware\>; we then need this extra loop to make sure the storage
4674 * controller structs are already set up so we can add stuff to them.
4675 *
4676 * @param elmHardware
4677 * @param strg
4678 */
4679void MachineConfigFile::readDVDAndFloppies_pre1_9(const xml::ElementNode &elmHardware,
4680 Storage &strg)
4681{
4682 xml::NodesLoop nl1(elmHardware);
4683 const xml::ElementNode *pelmHwChild;
4684 while ((pelmHwChild = nl1.forAllNodes()))
4685 {
4686 if (pelmHwChild->nameEquals("DVDDrive"))
4687 {
4688 // create a DVD "attached device" and attach it to the existing IDE controller
4689 AttachedDevice att;
4690 att.deviceType = DeviceType_DVD;
4691 // legacy DVD drive is always secondary master (port 1, device 0)
4692 att.lPort = 1;
4693 att.lDevice = 0;
4694 pelmHwChild->getAttributeValue("passthrough", att.fPassThrough);
4695 pelmHwChild->getAttributeValue("tempeject", att.fTempEject);
4696
4697 const xml::ElementNode *pDriveChild;
4698 Utf8Str strTmp;
4699 if ( (pDriveChild = pelmHwChild->findChildElement("Image")) != NULL
4700 && pDriveChild->getAttributeValue("uuid", strTmp))
4701 parseUUID(att.uuid, strTmp);
4702 else if ((pDriveChild = pelmHwChild->findChildElement("HostDrive")))
4703 pDriveChild->getAttributeValue("src", att.strHostDriveSrc);
4704
4705 // find the IDE controller and attach the DVD drive
4706 bool fFound = false;
4707 for (StorageControllersList::iterator it = strg.llStorageControllers.begin();
4708 it != strg.llStorageControllers.end();
4709 ++it)
4710 {
4711 StorageController &sctl = *it;
4712 if (sctl.storageBus == StorageBus_IDE)
4713 {
4714 sctl.llAttachedDevices.push_back(att);
4715 fFound = true;
4716 break;
4717 }
4718 }
4719
4720 if (!fFound)
4721 throw ConfigFileError(this, pelmHwChild, N_("Internal error: found DVD drive but IDE controller does not exist"));
4722 // shouldn't happen because pre-1.9 settings files always had at least one IDE controller in the settings
4723 // which should have gotten parsed in <StorageControllers> before this got called
4724 }
4725 else if (pelmHwChild->nameEquals("FloppyDrive"))
4726 {
4727 bool fEnabled;
4728 if ( pelmHwChild->getAttributeValue("enabled", fEnabled)
4729 && fEnabled)
4730 {
4731 // create a new floppy controller and attach a floppy "attached device"
4732 StorageController sctl;
4733 sctl.strName = "Floppy Controller";
4734 sctl.storageBus = StorageBus_Floppy;
4735 sctl.controllerType = StorageControllerType_I82078;
4736 sctl.ulPortCount = 1;
4737
4738 AttachedDevice att;
4739 att.deviceType = DeviceType_Floppy;
4740 att.lPort = 0;
4741 att.lDevice = 0;
4742
4743 const xml::ElementNode *pDriveChild;
4744 Utf8Str strTmp;
4745 if ( (pDriveChild = pelmHwChild->findChildElement("Image"))
4746 && pDriveChild->getAttributeValue("uuid", strTmp) )
4747 parseUUID(att.uuid, strTmp);
4748 else if ((pDriveChild = pelmHwChild->findChildElement("HostDrive")))
4749 pDriveChild->getAttributeValue("src", att.strHostDriveSrc);
4750
4751 // store attachment with controller
4752 sctl.llAttachedDevices.push_back(att);
4753 // store controller with storage
4754 strg.llStorageControllers.push_back(sctl);
4755 }
4756 }
4757 }
4758}
4759
4760/**
4761 * Called for reading the \<Teleporter\> element under \<Machine\>.
4762 */
4763void MachineConfigFile::readTeleporter(const xml::ElementNode *pElmTeleporter,
4764 MachineUserData *pUserData)
4765{
4766 pElmTeleporter->getAttributeValue("enabled", pUserData->fTeleporterEnabled);
4767 pElmTeleporter->getAttributeValue("port", pUserData->uTeleporterPort);
4768 pElmTeleporter->getAttributeValue("address", pUserData->strTeleporterAddress);
4769 pElmTeleporter->getAttributeValue("password", pUserData->strTeleporterPassword);
4770
4771 if ( pUserData->strTeleporterPassword.isNotEmpty()
4772 && !VBoxIsPasswordHashed(&pUserData->strTeleporterPassword))
4773 VBoxHashPassword(&pUserData->strTeleporterPassword);
4774}
4775
4776/**
4777 * Called for reading the \<Debugging\> element under \<Machine\> or \<Snapshot\>.
4778 */
4779void MachineConfigFile::readDebugging(const xml::ElementNode *pElmDebugging, Debugging *pDbg)
4780{
4781 if (!pElmDebugging || m->sv < SettingsVersion_v1_13)
4782 return;
4783
4784 const xml::ElementNode * const pelmTracing = pElmDebugging->findChildElement("Tracing");
4785 if (pelmTracing)
4786 {
4787 pelmTracing->getAttributeValue("enabled", pDbg->fTracingEnabled);
4788 pelmTracing->getAttributeValue("allowTracingToAccessVM", pDbg->fAllowTracingToAccessVM);
4789 pelmTracing->getAttributeValue("config", pDbg->strTracingConfig);
4790 }
4791}
4792
4793/**
4794 * Called for reading the \<Autostart\> element under \<Machine\> or \<Snapshot\>.
4795 */
4796void MachineConfigFile::readAutostart(const xml::ElementNode *pElmAutostart, Autostart *pAutostart)
4797{
4798 Utf8Str strAutostop;
4799
4800 if (!pElmAutostart || m->sv < SettingsVersion_v1_13)
4801 return;
4802
4803 pElmAutostart->getAttributeValue("enabled", pAutostart->fAutostartEnabled);
4804 pElmAutostart->getAttributeValue("delay", pAutostart->uAutostartDelay);
4805 pElmAutostart->getAttributeValue("autostop", strAutostop);
4806 if (strAutostop == "Disabled")
4807 pAutostart->enmAutostopType = AutostopType_Disabled;
4808 else if (strAutostop == "SaveState")
4809 pAutostart->enmAutostopType = AutostopType_SaveState;
4810 else if (strAutostop == "PowerOff")
4811 pAutostart->enmAutostopType = AutostopType_PowerOff;
4812 else if (strAutostop == "AcpiShutdown")
4813 pAutostart->enmAutostopType = AutostopType_AcpiShutdown;
4814 else
4815 throw ConfigFileError(this, pElmAutostart, N_("Invalid value '%s' for Autostart/@autostop attribute"), strAutostop.c_str());
4816}
4817
4818/**
4819 * Called for reading the \<Groups\> element under \<Machine\>.
4820 */
4821void MachineConfigFile::readGroups(const xml::ElementNode *pElmGroups, StringsList *pllGroups)
4822{
4823 pllGroups->clear();
4824 if (!pElmGroups || m->sv < SettingsVersion_v1_13)
4825 {
4826 pllGroups->push_back("/");
4827 return;
4828 }
4829
4830 xml::NodesLoop nlGroups(*pElmGroups);
4831 const xml::ElementNode *pelmGroup;
4832 while ((pelmGroup = nlGroups.forAllNodes()))
4833 {
4834 if (pelmGroup->nameEquals("Group"))
4835 {
4836 Utf8Str strGroup;
4837 if (!pelmGroup->getAttributeValue("name", strGroup))
4838 throw ConfigFileError(this, pelmGroup, N_("Required Group/@name attribute is missing"));
4839 pllGroups->push_back(strGroup);
4840 }
4841 }
4842}
4843
4844/**
4845 * Called initially for the \<Snapshot\> element under \<Machine\>, if present,
4846 * to store the snapshot's data into the given Snapshot structure (which is
4847 * then the one in the Machine struct). This might then recurse if
4848 * a \<Snapshots\> (plural) element is found in the snapshot, which should
4849 * contain a list of child snapshots; such lists are maintained in the
4850 * Snapshot structure.
4851 *
4852 * @param curSnapshotUuid
4853 * @param depth
4854 * @param elmSnapshot
4855 * @param snap
4856 * @returns true if curSnapshotUuid is in this snapshot subtree, otherwise false
4857 */
4858bool MachineConfigFile::readSnapshot(const Guid &curSnapshotUuid,
4859 uint32_t depth,
4860 const xml::ElementNode &elmSnapshot,
4861 Snapshot &snap)
4862{
4863 if (depth > SETTINGS_SNAPSHOT_DEPTH_MAX)
4864 throw ConfigFileError(this, &elmSnapshot, N_("Maximum snapshot tree depth of %u exceeded"), SETTINGS_SNAPSHOT_DEPTH_MAX);
4865
4866 Utf8Str strTemp;
4867
4868 if (!elmSnapshot.getAttributeValue("uuid", strTemp))
4869 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@uuid attribute is missing"));
4870 parseUUID(snap.uuid, strTemp);
4871 bool foundCurrentSnapshot = (snap.uuid == curSnapshotUuid);
4872
4873 if (!elmSnapshot.getAttributeValue("name", snap.strName))
4874 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@name attribute is missing"));
4875
4876 // earlier 3.1 trunk builds had a bug and added Description as an attribute, read it silently and write it back as an element
4877 elmSnapshot.getAttributeValue("Description", snap.strDescription);
4878
4879 if (!elmSnapshot.getAttributeValue("timeStamp", strTemp))
4880 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@timeStamp attribute is missing"));
4881 parseTimestamp(snap.timestamp, strTemp);
4882
4883 elmSnapshot.getAttributeValuePath("stateFile", snap.strStateFile); // online snapshots only
4884
4885 // parse Hardware before the other elements because other things depend on it
4886 const xml::ElementNode *pelmHardware;
4887 if (!(pelmHardware = elmSnapshot.findChildElement("Hardware")))
4888 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@Hardware element is missing"));
4889 readHardware(*pelmHardware, snap.hardware);
4890
4891 xml::NodesLoop nlSnapshotChildren(elmSnapshot);
4892 const xml::ElementNode *pelmSnapshotChild;
4893 while ((pelmSnapshotChild = nlSnapshotChildren.forAllNodes()))
4894 {
4895 if (pelmSnapshotChild->nameEquals("Description"))
4896 snap.strDescription = pelmSnapshotChild->getValue();
4897 else if ( m->sv < SettingsVersion_v1_7
4898 && pelmSnapshotChild->nameEquals("HardDiskAttachments"))
4899 readHardDiskAttachments_pre1_7(*pelmSnapshotChild, snap.hardware.storage);
4900 else if ( m->sv >= SettingsVersion_v1_7
4901 && pelmSnapshotChild->nameEquals("StorageControllers"))
4902 readStorageControllers(*pelmSnapshotChild, snap.hardware.storage);
4903 else if (pelmSnapshotChild->nameEquals("Snapshots"))
4904 {
4905 xml::NodesLoop nlChildSnapshots(*pelmSnapshotChild);
4906 const xml::ElementNode *pelmChildSnapshot;
4907 while ((pelmChildSnapshot = nlChildSnapshots.forAllNodes()))
4908 {
4909 if (pelmChildSnapshot->nameEquals("Snapshot"))
4910 {
4911 // recurse with this element and put the child at the
4912 // end of the list. XPCOM has very small stack, avoid
4913 // big local variables and use the list element.
4914 snap.llChildSnapshots.push_back(Snapshot::Empty);
4915 bool found = readSnapshot(curSnapshotUuid, depth + 1, *pelmChildSnapshot, snap.llChildSnapshots.back());
4916 foundCurrentSnapshot = foundCurrentSnapshot || found;
4917 }
4918 }
4919 }
4920 }
4921
4922 if (m->sv < SettingsVersion_v1_9)
4923 // go through Hardware once more to repair the settings controller structures
4924 // with data from old DVDDrive and FloppyDrive elements
4925 readDVDAndFloppies_pre1_9(*pelmHardware, snap.hardware.storage);
4926
4927 readDebugging(elmSnapshot.findChildElement("Debugging"), &snap.debugging);
4928 readAutostart(elmSnapshot.findChildElement("Autostart"), &snap.autostart);
4929 // note: Groups exist only for Machine, not for Snapshot
4930
4931 return foundCurrentSnapshot;
4932}
4933
4934const struct {
4935 const char *pcszOld;
4936 const char *pcszNew;
4937} aConvertOSTypes[] =
4938{
4939 { "unknown", "Other" },
4940 { "dos", "DOS" },
4941 { "win31", "Windows31" },
4942 { "win95", "Windows95" },
4943 { "win98", "Windows98" },
4944 { "winme", "WindowsMe" },
4945 { "winnt4", "WindowsNT4" },
4946 { "win2k", "Windows2000" },
4947 { "winxp", "WindowsXP" },
4948 { "win2k3", "Windows2003" },
4949 { "winvista", "WindowsVista" },
4950 { "win2k8", "Windows2008" },
4951 { "os2warp3", "OS2Warp3" },
4952 { "os2warp4", "OS2Warp4" },
4953 { "os2warp45", "OS2Warp45" },
4954 { "ecs", "OS2eCS" },
4955 { "linux22", "Linux22" },
4956 { "linux24", "Linux24" },
4957 { "linux26", "Linux26" },
4958 { "archlinux", "ArchLinux" },
4959 { "debian", "Debian" },
4960 { "opensuse", "OpenSUSE" },
4961 { "fedoracore", "Fedora" },
4962 { "gentoo", "Gentoo" },
4963 { "mandriva", "Mandriva" },
4964 { "redhat", "RedHat" },
4965 { "ubuntu", "Ubuntu" },
4966 { "xandros", "Xandros" },
4967 { "freebsd", "FreeBSD" },
4968 { "openbsd", "OpenBSD" },
4969 { "netbsd", "NetBSD" },
4970 { "netware", "Netware" },
4971 { "solaris", "Solaris" },
4972 { "opensolaris", "OpenSolaris" },
4973 { "l4", "L4" }
4974};
4975
4976void MachineConfigFile::convertOldOSType_pre1_5(Utf8Str &str)
4977{
4978 for (unsigned u = 0;
4979 u < RT_ELEMENTS(aConvertOSTypes);
4980 ++u)
4981 {
4982 if (str == aConvertOSTypes[u].pcszOld)
4983 {
4984 str = aConvertOSTypes[u].pcszNew;
4985 break;
4986 }
4987 }
4988}
4989
4990/**
4991 * Called from the constructor to actually read in the \<Machine\> element
4992 * of a machine config file.
4993 * @param elmMachine
4994 */
4995void MachineConfigFile::readMachine(const xml::ElementNode &elmMachine)
4996{
4997 Utf8Str strUUID;
4998 if ( elmMachine.getAttributeValue("uuid", strUUID)
4999 && elmMachine.getAttributeValue("name", machineUserData.strName))
5000 {
5001 parseUUID(uuid, strUUID);
5002
5003 elmMachine.getAttributeValue("directoryIncludesUUID", machineUserData.fDirectoryIncludesUUID);
5004 elmMachine.getAttributeValue("nameSync", machineUserData.fNameSync);
5005
5006 Utf8Str str;
5007 elmMachine.getAttributeValue("Description", machineUserData.strDescription);
5008 elmMachine.getAttributeValue("OSType", machineUserData.strOsType);
5009 if (m->sv < SettingsVersion_v1_5)
5010 convertOldOSType_pre1_5(machineUserData.strOsType);
5011
5012 elmMachine.getAttributeValuePath("stateFile", strStateFile);
5013
5014 if (elmMachine.getAttributeValue("currentSnapshot", str))
5015 parseUUID(uuidCurrentSnapshot, str);
5016
5017 elmMachine.getAttributeValuePath("snapshotFolder", machineUserData.strSnapshotFolder);
5018
5019 if (!elmMachine.getAttributeValue("currentStateModified", fCurrentStateModified))
5020 fCurrentStateModified = true;
5021 if (elmMachine.getAttributeValue("lastStateChange", str))
5022 parseTimestamp(timeLastStateChange, str);
5023 // constructor has called RTTimeNow(&timeLastStateChange) before
5024 if (elmMachine.getAttributeValue("aborted", fAborted))
5025 fAborted = true;
5026
5027 elmMachine.getAttributeValue("processPriority", machineUserData.strVMPriority);
5028
5029 str.setNull();
5030 elmMachine.getAttributeValue("icon", str);
5031 parseBase64(machineUserData.ovIcon, str);
5032
5033 // parse Hardware before the other elements because other things depend on it
5034 const xml::ElementNode *pelmHardware;
5035 if (!(pelmHardware = elmMachine.findChildElement("Hardware")))
5036 throw ConfigFileError(this, &elmMachine, N_("Required Machine/Hardware element is missing"));
5037 readHardware(*pelmHardware, hardwareMachine);
5038
5039 xml::NodesLoop nlRootChildren(elmMachine);
5040 const xml::ElementNode *pelmMachineChild;
5041 while ((pelmMachineChild = nlRootChildren.forAllNodes()))
5042 {
5043 if (pelmMachineChild->nameEquals("ExtraData"))
5044 readExtraData(*pelmMachineChild,
5045 mapExtraDataItems);
5046 else if ( (m->sv < SettingsVersion_v1_7)
5047 && (pelmMachineChild->nameEquals("HardDiskAttachments"))
5048 )
5049 readHardDiskAttachments_pre1_7(*pelmMachineChild, hardwareMachine.storage);
5050 else if ( (m->sv >= SettingsVersion_v1_7)
5051 && (pelmMachineChild->nameEquals("StorageControllers"))
5052 )
5053 readStorageControllers(*pelmMachineChild, hardwareMachine.storage);
5054 else if (pelmMachineChild->nameEquals("Snapshot"))
5055 {
5056 if (uuidCurrentSnapshot.isZero())
5057 throw ConfigFileError(this, &elmMachine, N_("Snapshots present but required Machine/@currentSnapshot attribute is missing"));
5058 bool foundCurrentSnapshot = false;
5059 Snapshot snap;
5060 // this will recurse into child snapshots, if necessary
5061 foundCurrentSnapshot = readSnapshot(uuidCurrentSnapshot, 1, *pelmMachineChild, snap);
5062 if (!foundCurrentSnapshot)
5063 throw ConfigFileError(this, &elmMachine, N_("Snapshots present but none matches the UUID in the Machine/@currentSnapshot attribute"));
5064 llFirstSnapshot.push_back(snap);
5065 }
5066 else if (pelmMachineChild->nameEquals("Description"))
5067 machineUserData.strDescription = pelmMachineChild->getValue();
5068 else if (pelmMachineChild->nameEquals("Teleporter"))
5069 readTeleporter(pelmMachineChild, &machineUserData);
5070 else if (pelmMachineChild->nameEquals("FaultTolerance"))
5071 {
5072 Utf8Str strFaultToleranceSate;
5073 if (pelmMachineChild->getAttributeValue("state", strFaultToleranceSate))
5074 {
5075 if (strFaultToleranceSate == "master")
5076 machineUserData.enmFaultToleranceState = FaultToleranceState_Master;
5077 else
5078 if (strFaultToleranceSate == "standby")
5079 machineUserData.enmFaultToleranceState = FaultToleranceState_Standby;
5080 else
5081 machineUserData.enmFaultToleranceState = FaultToleranceState_Inactive;
5082 }
5083 pelmMachineChild->getAttributeValue("port", machineUserData.uFaultTolerancePort);
5084 pelmMachineChild->getAttributeValue("address", machineUserData.strFaultToleranceAddress);
5085 pelmMachineChild->getAttributeValue("interval", machineUserData.uFaultToleranceInterval);
5086 pelmMachineChild->getAttributeValue("password", machineUserData.strFaultTolerancePassword);
5087 }
5088 else if (pelmMachineChild->nameEquals("MediaRegistry"))
5089 readMediaRegistry(*pelmMachineChild, mediaRegistry);
5090 else if (pelmMachineChild->nameEquals("Debugging"))
5091 readDebugging(pelmMachineChild, &debugging);
5092 else if (pelmMachineChild->nameEquals("Autostart"))
5093 readAutostart(pelmMachineChild, &autostart);
5094 else if (pelmMachineChild->nameEquals("Groups"))
5095 readGroups(pelmMachineChild, &machineUserData.llGroups);
5096 }
5097
5098 if (m->sv < SettingsVersion_v1_9)
5099 // go through Hardware once more to repair the settings controller structures
5100 // with data from old DVDDrive and FloppyDrive elements
5101 readDVDAndFloppies_pre1_9(*pelmHardware, hardwareMachine.storage);
5102 }
5103 else
5104 throw ConfigFileError(this, &elmMachine, N_("Required Machine/@uuid or @name attributes is missing"));
5105}
5106
5107/**
5108 * Creates a \<Hardware\> node under elmParent and then writes out the XML
5109 * keys under that. Called for both the \<Machine\> node and for snapshots.
5110 * @param elmParent
5111 * @param hw
5112 * @param fl
5113 * @param pllElementsWithUuidAttributes
5114 */
5115void MachineConfigFile::buildHardwareXML(xml::ElementNode &elmParent,
5116 const Hardware &hw,
5117 uint32_t fl,
5118 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes)
5119{
5120 xml::ElementNode *pelmHardware = elmParent.createChild("Hardware");
5121
5122 if ( m->sv >= SettingsVersion_v1_4
5123 && (m->sv < SettingsVersion_v1_7 ? hw.strVersion != "1" : hw.strVersion != "2"))
5124 pelmHardware->setAttribute("version", hw.strVersion);
5125
5126 if ((m->sv >= SettingsVersion_v1_9)
5127 && !hw.uuid.isZero()
5128 && hw.uuid.isValid()
5129 )
5130 pelmHardware->setAttribute("uuid", hw.uuid.toStringCurly());
5131
5132 xml::ElementNode *pelmCPU = pelmHardware->createChild("CPU");
5133
5134 if (!hw.fHardwareVirt)
5135 pelmCPU->createChild("HardwareVirtEx")->setAttribute("enabled", hw.fHardwareVirt);
5136 if (!hw.fNestedPaging)
5137 pelmCPU->createChild("HardwareVirtExNestedPaging")->setAttribute("enabled", hw.fNestedPaging);
5138 if (!hw.fVPID)
5139 pelmCPU->createChild("HardwareVirtExVPID")->setAttribute("enabled", hw.fVPID);
5140 if (!hw.fUnrestrictedExecution)
5141 pelmCPU->createChild("HardwareVirtExUX")->setAttribute("enabled", hw.fUnrestrictedExecution);
5142 // PAE has too crazy default handling, must always save this setting.
5143 pelmCPU->createChild("PAE")->setAttribute("enabled", hw.fPAE);
5144 if (m->sv >= SettingsVersion_v1_16)
5145 {
5146 }
5147 if (m->sv >= SettingsVersion_v1_14 && hw.enmLongMode != Hardware::LongMode_Legacy)
5148 {
5149 // LongMode has too crazy default handling, must always save this setting.
5150 pelmCPU->createChild("LongMode")->setAttribute("enabled", hw.enmLongMode == Hardware::LongMode_Enabled);
5151 }
5152
5153 if (hw.fTripleFaultReset)
5154 pelmCPU->createChild("TripleFaultReset")->setAttribute("enabled", hw.fTripleFaultReset);
5155 if (m->sv >= SettingsVersion_v1_14)
5156 {
5157 if (hw.fX2APIC)
5158 pelmCPU->createChild("X2APIC")->setAttribute("enabled", hw.fX2APIC);
5159 else if (!hw.fAPIC)
5160 pelmCPU->createChild("APIC")->setAttribute("enabled", hw.fAPIC);
5161 }
5162 if (hw.cCPUs > 1)
5163 pelmCPU->setAttribute("count", hw.cCPUs);
5164 if (hw.ulCpuExecutionCap != 100)
5165 pelmCPU->setAttribute("executionCap", hw.ulCpuExecutionCap);
5166 if (hw.uCpuIdPortabilityLevel != 0)
5167 pelmCPU->setAttribute("CpuIdPortabilityLevel", hw.uCpuIdPortabilityLevel);
5168 if (!hw.strCpuProfile.equals("host") && hw.strCpuProfile.isNotEmpty())
5169 pelmCPU->setAttribute("CpuProfile", hw.strCpuProfile);
5170
5171 // HardwareVirtExLargePages has too crazy default handling, must always save this setting.
5172 pelmCPU->createChild("HardwareVirtExLargePages")->setAttribute("enabled", hw.fLargePages);
5173
5174 if (m->sv >= SettingsVersion_v1_9)
5175 {
5176 if (hw.fHardwareVirtForce)
5177 pelmCPU->createChild("HardwareVirtForce")->setAttribute("enabled", hw.fHardwareVirtForce);
5178 }
5179
5180 if (m->sv >= SettingsVersion_v1_10)
5181 {
5182 if (hw.fCpuHotPlug)
5183 pelmCPU->setAttribute("hotplug", hw.fCpuHotPlug);
5184
5185 xml::ElementNode *pelmCpuTree = NULL;
5186 for (CpuList::const_iterator it = hw.llCpus.begin();
5187 it != hw.llCpus.end();
5188 ++it)
5189 {
5190 const Cpu &cpu = *it;
5191
5192 if (pelmCpuTree == NULL)
5193 pelmCpuTree = pelmCPU->createChild("CpuTree");
5194
5195 xml::ElementNode *pelmCpu = pelmCpuTree->createChild("Cpu");
5196 pelmCpu->setAttribute("id", cpu.ulId);
5197 }
5198 }
5199
5200 xml::ElementNode *pelmCpuIdTree = NULL;
5201 for (CpuIdLeafsList::const_iterator it = hw.llCpuIdLeafs.begin();
5202 it != hw.llCpuIdLeafs.end();
5203 ++it)
5204 {
5205 const CpuIdLeaf &leaf = *it;
5206
5207 if (pelmCpuIdTree == NULL)
5208 pelmCpuIdTree = pelmCPU->createChild("CpuIdTree");
5209
5210 xml::ElementNode *pelmCpuIdLeaf = pelmCpuIdTree->createChild("CpuIdLeaf");
5211 pelmCpuIdLeaf->setAttribute("id", leaf.ulId);
5212 pelmCpuIdLeaf->setAttribute("eax", leaf.ulEax);
5213 pelmCpuIdLeaf->setAttribute("ebx", leaf.ulEbx);
5214 pelmCpuIdLeaf->setAttribute("ecx", leaf.ulEcx);
5215 pelmCpuIdLeaf->setAttribute("edx", leaf.ulEdx);
5216 }
5217
5218 xml::ElementNode *pelmMemory = pelmHardware->createChild("Memory");
5219 pelmMemory->setAttribute("RAMSize", hw.ulMemorySizeMB);
5220 if (m->sv >= SettingsVersion_v1_10)
5221 {
5222 if (hw.fPageFusionEnabled)
5223 pelmMemory->setAttribute("PageFusion", hw.fPageFusionEnabled);
5224 }
5225
5226 if ( (m->sv >= SettingsVersion_v1_9)
5227 && (hw.firmwareType >= FirmwareType_EFI)
5228 )
5229 {
5230 xml::ElementNode *pelmFirmware = pelmHardware->createChild("Firmware");
5231 const char *pcszFirmware;
5232
5233 switch (hw.firmwareType)
5234 {
5235 case FirmwareType_EFI: pcszFirmware = "EFI"; break;
5236 case FirmwareType_EFI32: pcszFirmware = "EFI32"; break;
5237 case FirmwareType_EFI64: pcszFirmware = "EFI64"; break;
5238 case FirmwareType_EFIDUAL: pcszFirmware = "EFIDUAL"; break;
5239 default: pcszFirmware = "None"; break;
5240 }
5241 pelmFirmware->setAttribute("type", pcszFirmware);
5242 }
5243
5244 if ( m->sv >= SettingsVersion_v1_10
5245 && ( hw.pointingHIDType != PointingHIDType_PS2Mouse
5246 || hw.keyboardHIDType != KeyboardHIDType_PS2Keyboard))
5247 {
5248 xml::ElementNode *pelmHID = pelmHardware->createChild("HID");
5249 const char *pcszHID;
5250
5251 if (hw.pointingHIDType != PointingHIDType_PS2Mouse)
5252 {
5253 switch (hw.pointingHIDType)
5254 {
5255 case PointingHIDType_USBMouse: pcszHID = "USBMouse"; break;
5256 case PointingHIDType_USBTablet: pcszHID = "USBTablet"; break;
5257 case PointingHIDType_PS2Mouse: pcszHID = "PS2Mouse"; break;
5258 case PointingHIDType_ComboMouse: pcszHID = "ComboMouse"; break;
5259 case PointingHIDType_USBMultiTouch: pcszHID = "USBMultiTouch";break;
5260 case PointingHIDType_None: pcszHID = "None"; break;
5261 default: Assert(false); pcszHID = "PS2Mouse"; break;
5262 }
5263 pelmHID->setAttribute("Pointing", pcszHID);
5264 }
5265
5266 if (hw.keyboardHIDType != KeyboardHIDType_PS2Keyboard)
5267 {
5268 switch (hw.keyboardHIDType)
5269 {
5270 case KeyboardHIDType_USBKeyboard: pcszHID = "USBKeyboard"; break;
5271 case KeyboardHIDType_PS2Keyboard: pcszHID = "PS2Keyboard"; break;
5272 case KeyboardHIDType_ComboKeyboard: pcszHID = "ComboKeyboard"; break;
5273 case KeyboardHIDType_None: pcszHID = "None"; break;
5274 default: Assert(false); pcszHID = "PS2Keyboard"; break;
5275 }
5276 pelmHID->setAttribute("Keyboard", pcszHID);
5277 }
5278 }
5279
5280 if ( (m->sv >= SettingsVersion_v1_10)
5281 && hw.fHPETEnabled
5282 )
5283 {
5284 xml::ElementNode *pelmHPET = pelmHardware->createChild("HPET");
5285 pelmHPET->setAttribute("enabled", hw.fHPETEnabled);
5286 }
5287
5288 if ( (m->sv >= SettingsVersion_v1_11)
5289 )
5290 {
5291 if (hw.chipsetType != ChipsetType_PIIX3)
5292 {
5293 xml::ElementNode *pelmChipset = pelmHardware->createChild("Chipset");
5294 const char *pcszChipset;
5295
5296 switch (hw.chipsetType)
5297 {
5298 case ChipsetType_PIIX3: pcszChipset = "PIIX3"; break;
5299 case ChipsetType_ICH9: pcszChipset = "ICH9"; break;
5300 default: Assert(false); pcszChipset = "PIIX3"; break;
5301 }
5302 pelmChipset->setAttribute("type", pcszChipset);
5303 }
5304 }
5305
5306 if ( (m->sv >= SettingsVersion_v1_15)
5307 && !hw.areParavirtDefaultSettings(m->sv)
5308 )
5309 {
5310 const char *pcszParavirtProvider;
5311 switch (hw.paravirtProvider)
5312 {
5313 case ParavirtProvider_None: pcszParavirtProvider = "None"; break;
5314 case ParavirtProvider_Default: pcszParavirtProvider = "Default"; break;
5315 case ParavirtProvider_Legacy: pcszParavirtProvider = "Legacy"; break;
5316 case ParavirtProvider_Minimal: pcszParavirtProvider = "Minimal"; break;
5317 case ParavirtProvider_HyperV: pcszParavirtProvider = "HyperV"; break;
5318 case ParavirtProvider_KVM: pcszParavirtProvider = "KVM"; break;
5319 default: Assert(false); pcszParavirtProvider = "None"; break;
5320 }
5321
5322 xml::ElementNode *pelmParavirt = pelmHardware->createChild("Paravirt");
5323 pelmParavirt->setAttribute("provider", pcszParavirtProvider);
5324
5325 if ( m->sv >= SettingsVersion_v1_16
5326 && hw.strParavirtDebug.isNotEmpty())
5327 pelmParavirt->setAttribute("debug", hw.strParavirtDebug);
5328 }
5329
5330 if (!hw.areBootOrderDefaultSettings())
5331 {
5332 xml::ElementNode *pelmBoot = pelmHardware->createChild("Boot");
5333 for (BootOrderMap::const_iterator it = hw.mapBootOrder.begin();
5334 it != hw.mapBootOrder.end();
5335 ++it)
5336 {
5337 uint32_t i = it->first;
5338 DeviceType_T type = it->second;
5339 const char *pcszDevice;
5340
5341 switch (type)
5342 {
5343 case DeviceType_Floppy: pcszDevice = "Floppy"; break;
5344 case DeviceType_DVD: pcszDevice = "DVD"; break;
5345 case DeviceType_HardDisk: pcszDevice = "HardDisk"; break;
5346 case DeviceType_Network: pcszDevice = "Network"; break;
5347 default: /*case DeviceType_Null:*/ pcszDevice = "None"; break;
5348 }
5349
5350 xml::ElementNode *pelmOrder = pelmBoot->createChild("Order");
5351 pelmOrder->setAttribute("position",
5352 i + 1); // XML is 1-based but internal data is 0-based
5353 pelmOrder->setAttribute("device", pcszDevice);
5354 }
5355 }
5356
5357 if (!hw.areDisplayDefaultSettings())
5358 {
5359 xml::ElementNode *pelmDisplay = pelmHardware->createChild("Display");
5360 if (hw.graphicsControllerType != GraphicsControllerType_VBoxVGA)
5361 {
5362 const char *pcszGraphics;
5363 switch (hw.graphicsControllerType)
5364 {
5365 case GraphicsControllerType_VBoxVGA: pcszGraphics = "VBoxVGA"; break;
5366 case GraphicsControllerType_VMSVGA: pcszGraphics = "VMSVGA"; break;
5367 default: /*case GraphicsControllerType_Null:*/ pcszGraphics = "None"; break;
5368 }
5369 pelmDisplay->setAttribute("controller", pcszGraphics);
5370 }
5371 if (hw.ulVRAMSizeMB != 8)
5372 pelmDisplay->setAttribute("VRAMSize", hw.ulVRAMSizeMB);
5373 if (hw.cMonitors > 1)
5374 pelmDisplay->setAttribute("monitorCount", hw.cMonitors);
5375 if (hw.fAccelerate3D)
5376 pelmDisplay->setAttribute("accelerate3D", hw.fAccelerate3D);
5377
5378 if (m->sv >= SettingsVersion_v1_8)
5379 {
5380 if (hw.fAccelerate2DVideo)
5381 pelmDisplay->setAttribute("accelerate2DVideo", hw.fAccelerate2DVideo);
5382 }
5383 }
5384
5385 if (m->sv >= SettingsVersion_v1_14 && !hw.areVideoCaptureDefaultSettings())
5386 {
5387 xml::ElementNode *pelmVideoCapture = pelmHardware->createChild("VideoCapture");
5388 if (hw.fVideoCaptureEnabled)
5389 pelmVideoCapture->setAttribute("enabled", hw.fVideoCaptureEnabled);
5390 if (hw.u64VideoCaptureScreens != UINT64_C(0xffffffffffffffff))
5391 pelmVideoCapture->setAttribute("screens", hw.u64VideoCaptureScreens);
5392 if (!hw.strVideoCaptureFile.isEmpty())
5393 pelmVideoCapture->setAttributePath("file", hw.strVideoCaptureFile);
5394 if (hw.ulVideoCaptureHorzRes != 1024 || hw.ulVideoCaptureVertRes != 768)
5395 {
5396 pelmVideoCapture->setAttribute("horzRes", hw.ulVideoCaptureHorzRes);
5397 pelmVideoCapture->setAttribute("vertRes", hw.ulVideoCaptureVertRes);
5398 }
5399 if (hw.ulVideoCaptureRate != 512)
5400 pelmVideoCapture->setAttribute("rate", hw.ulVideoCaptureRate);
5401 if (hw.ulVideoCaptureFPS)
5402 pelmVideoCapture->setAttribute("fps", hw.ulVideoCaptureFPS);
5403 if (hw.ulVideoCaptureMaxTime)
5404 pelmVideoCapture->setAttribute("maxTime", hw.ulVideoCaptureMaxTime);
5405 if (hw.ulVideoCaptureMaxSize)
5406 pelmVideoCapture->setAttribute("maxSize", hw.ulVideoCaptureMaxSize);
5407 }
5408
5409 if (!hw.vrdeSettings.areDefaultSettings())
5410 {
5411 xml::ElementNode *pelmVRDE = pelmHardware->createChild("RemoteDisplay");
5412 if (hw.vrdeSettings.fEnabled)
5413 pelmVRDE->setAttribute("enabled", hw.vrdeSettings.fEnabled);
5414 if (m->sv < SettingsVersion_v1_11)
5415 {
5416 /* In VBox 4.0 these attributes are replaced with "Properties". */
5417 Utf8Str strPort;
5418 StringsMap::const_iterator it = hw.vrdeSettings.mapProperties.find("TCP/Ports");
5419 if (it != hw.vrdeSettings.mapProperties.end())
5420 strPort = it->second;
5421 if (!strPort.length())
5422 strPort = "3389";
5423 pelmVRDE->setAttribute("port", strPort);
5424
5425 Utf8Str strAddress;
5426 it = hw.vrdeSettings.mapProperties.find("TCP/Address");
5427 if (it != hw.vrdeSettings.mapProperties.end())
5428 strAddress = it->second;
5429 if (strAddress.length())
5430 pelmVRDE->setAttribute("netAddress", strAddress);
5431 }
5432 if (hw.vrdeSettings.authType != AuthType_Null)
5433 {
5434 const char *pcszAuthType;
5435 switch (hw.vrdeSettings.authType)
5436 {
5437 case AuthType_Guest: pcszAuthType = "Guest"; break;
5438 case AuthType_External: pcszAuthType = "External"; break;
5439 default: /*case AuthType_Null:*/ pcszAuthType = "Null"; break;
5440 }
5441 pelmVRDE->setAttribute("authType", pcszAuthType);
5442 }
5443
5444 if (hw.vrdeSettings.ulAuthTimeout != 0 && hw.vrdeSettings.ulAuthTimeout != 5000)
5445 pelmVRDE->setAttribute("authTimeout", hw.vrdeSettings.ulAuthTimeout);
5446 if (hw.vrdeSettings.fAllowMultiConnection)
5447 pelmVRDE->setAttribute("allowMultiConnection", hw.vrdeSettings.fAllowMultiConnection);
5448 if (hw.vrdeSettings.fReuseSingleConnection)
5449 pelmVRDE->setAttribute("reuseSingleConnection", hw.vrdeSettings.fReuseSingleConnection);
5450
5451 if (m->sv == SettingsVersion_v1_10)
5452 {
5453 xml::ElementNode *pelmVideoChannel = pelmVRDE->createChild("VideoChannel");
5454
5455 /* In 4.0 videochannel settings were replaced with properties, so look at properties. */
5456 Utf8Str str;
5457 StringsMap::const_iterator it = hw.vrdeSettings.mapProperties.find("VideoChannel/Enabled");
5458 if (it != hw.vrdeSettings.mapProperties.end())
5459 str = it->second;
5460 bool fVideoChannel = RTStrICmp(str.c_str(), "true") == 0
5461 || RTStrCmp(str.c_str(), "1") == 0;
5462 pelmVideoChannel->setAttribute("enabled", fVideoChannel);
5463
5464 it = hw.vrdeSettings.mapProperties.find("VideoChannel/Quality");
5465 if (it != hw.vrdeSettings.mapProperties.end())
5466 str = it->second;
5467 uint32_t ulVideoChannelQuality = RTStrToUInt32(str.c_str()); /* This returns 0 on invalid string which is ok. */
5468 if (ulVideoChannelQuality == 0)
5469 ulVideoChannelQuality = 75;
5470 else
5471 ulVideoChannelQuality = RT_CLAMP(ulVideoChannelQuality, 10, 100);
5472 pelmVideoChannel->setAttribute("quality", ulVideoChannelQuality);
5473 }
5474 if (m->sv >= SettingsVersion_v1_11)
5475 {
5476 if (hw.vrdeSettings.strAuthLibrary.length())
5477 pelmVRDE->setAttribute("authLibrary", hw.vrdeSettings.strAuthLibrary);
5478 if (hw.vrdeSettings.strVrdeExtPack.isNotEmpty())
5479 pelmVRDE->setAttribute("VRDEExtPack", hw.vrdeSettings.strVrdeExtPack);
5480 if (hw.vrdeSettings.mapProperties.size() > 0)
5481 {
5482 xml::ElementNode *pelmProperties = pelmVRDE->createChild("VRDEProperties");
5483 for (StringsMap::const_iterator it = hw.vrdeSettings.mapProperties.begin();
5484 it != hw.vrdeSettings.mapProperties.end();
5485 ++it)
5486 {
5487 const Utf8Str &strName = it->first;
5488 const Utf8Str &strValue = it->second;
5489 xml::ElementNode *pelm = pelmProperties->createChild("Property");
5490 pelm->setAttribute("name", strName);
5491 pelm->setAttribute("value", strValue);
5492 }
5493 }
5494 }
5495 }
5496
5497 if (!hw.biosSettings.areDefaultSettings())
5498 {
5499 xml::ElementNode *pelmBIOS = pelmHardware->createChild("BIOS");
5500 if (!hw.biosSettings.fACPIEnabled)
5501 pelmBIOS->createChild("ACPI")->setAttribute("enabled", hw.biosSettings.fACPIEnabled);
5502 if (hw.biosSettings.fIOAPICEnabled)
5503 pelmBIOS->createChild("IOAPIC")->setAttribute("enabled", hw.biosSettings.fIOAPICEnabled);
5504 if (hw.biosSettings.apicMode != APICMode_APIC)
5505 {
5506 const char *pcszAPIC;
5507 switch (hw.biosSettings.apicMode)
5508 {
5509 case APICMode_Disabled:
5510 pcszAPIC = "Disabled";
5511 break;
5512 case APICMode_APIC:
5513 default:
5514 pcszAPIC = "APIC";
5515 break;
5516 case APICMode_X2APIC:
5517 pcszAPIC = "X2APIC";
5518 break;
5519 }
5520 pelmBIOS->createChild("APIC")->setAttribute("mode", pcszAPIC);
5521 }
5522
5523 if ( !hw.biosSettings.fLogoFadeIn
5524 || !hw.biosSettings.fLogoFadeOut
5525 || hw.biosSettings.ulLogoDisplayTime
5526 || !hw.biosSettings.strLogoImagePath.isEmpty())
5527 {
5528 xml::ElementNode *pelmLogo = pelmBIOS->createChild("Logo");
5529 pelmLogo->setAttribute("fadeIn", hw.biosSettings.fLogoFadeIn);
5530 pelmLogo->setAttribute("fadeOut", hw.biosSettings.fLogoFadeOut);
5531 pelmLogo->setAttribute("displayTime", hw.biosSettings.ulLogoDisplayTime);
5532 if (!hw.biosSettings.strLogoImagePath.isEmpty())
5533 pelmLogo->setAttribute("imagePath", hw.biosSettings.strLogoImagePath);
5534 }
5535
5536 if (hw.biosSettings.biosBootMenuMode != BIOSBootMenuMode_MessageAndMenu)
5537 {
5538 const char *pcszBootMenu;
5539 switch (hw.biosSettings.biosBootMenuMode)
5540 {
5541 case BIOSBootMenuMode_Disabled: pcszBootMenu = "Disabled"; break;
5542 case BIOSBootMenuMode_MenuOnly: pcszBootMenu = "MenuOnly"; break;
5543 default: /*BIOSBootMenuMode_MessageAndMenu*/ pcszBootMenu = "MessageAndMenu"; break;
5544 }
5545 pelmBIOS->createChild("BootMenu")->setAttribute("mode", pcszBootMenu);
5546 }
5547 if (hw.biosSettings.llTimeOffset)
5548 pelmBIOS->createChild("TimeOffset")->setAttribute("value", hw.biosSettings.llTimeOffset);
5549 if (hw.biosSettings.fPXEDebugEnabled)
5550 pelmBIOS->createChild("PXEDebug")->setAttribute("enabled", hw.biosSettings.fPXEDebugEnabled);
5551 }
5552
5553 if (m->sv < SettingsVersion_v1_9)
5554 {
5555 // settings formats before 1.9 had separate DVDDrive and FloppyDrive items under Hardware;
5556 // run thru the storage controllers to see if we have a DVD or floppy drives
5557 size_t cDVDs = 0;
5558 size_t cFloppies = 0;
5559
5560 xml::ElementNode *pelmDVD = pelmHardware->createChild("DVDDrive");
5561 xml::ElementNode *pelmFloppy = pelmHardware->createChild("FloppyDrive");
5562
5563 for (StorageControllersList::const_iterator it = hw.storage.llStorageControllers.begin();
5564 it != hw.storage.llStorageControllers.end();
5565 ++it)
5566 {
5567 const StorageController &sctl = *it;
5568 // in old settings format, the DVD drive could only have been under the IDE controller
5569 if (sctl.storageBus == StorageBus_IDE)
5570 {
5571 for (AttachedDevicesList::const_iterator it2 = sctl.llAttachedDevices.begin();
5572 it2 != sctl.llAttachedDevices.end();
5573 ++it2)
5574 {
5575 const AttachedDevice &att = *it2;
5576 if (att.deviceType == DeviceType_DVD)
5577 {
5578 if (cDVDs > 0)
5579 throw ConfigFileError(this, NULL, N_("Internal error: cannot save more than one DVD drive with old settings format"));
5580
5581 ++cDVDs;
5582
5583 pelmDVD->setAttribute("passthrough", att.fPassThrough);
5584 if (att.fTempEject)
5585 pelmDVD->setAttribute("tempeject", att.fTempEject);
5586
5587 if (!att.uuid.isZero() && att.uuid.isValid())
5588 pelmDVD->createChild("Image")->setAttribute("uuid", att.uuid.toStringCurly());
5589 else if (att.strHostDriveSrc.length())
5590 pelmDVD->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
5591 }
5592 }
5593 }
5594 else if (sctl.storageBus == StorageBus_Floppy)
5595 {
5596 size_t cFloppiesHere = sctl.llAttachedDevices.size();
5597 if (cFloppiesHere > 1)
5598 throw ConfigFileError(this, NULL, N_("Internal error: floppy controller cannot have more than one device attachment"));
5599 if (cFloppiesHere)
5600 {
5601 const AttachedDevice &att = sctl.llAttachedDevices.front();
5602 pelmFloppy->setAttribute("enabled", true);
5603
5604 if (!att.uuid.isZero() && att.uuid.isValid())
5605 pelmFloppy->createChild("Image")->setAttribute("uuid", att.uuid.toStringCurly());
5606 else if (att.strHostDriveSrc.length())
5607 pelmFloppy->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
5608 }
5609
5610 cFloppies += cFloppiesHere;
5611 }
5612 }
5613
5614 if (cFloppies == 0)
5615 pelmFloppy->setAttribute("enabled", false);
5616 else if (cFloppies > 1)
5617 throw ConfigFileError(this, NULL, N_("Internal error: cannot save more than one floppy drive with old settings format"));
5618 }
5619
5620 if (m->sv < SettingsVersion_v1_14)
5621 {
5622 bool fOhciEnabled = false;
5623 bool fEhciEnabled = false;
5624 xml::ElementNode *pelmUSB = pelmHardware->createChild("USBController");
5625
5626 for (USBControllerList::const_iterator it = hw.usbSettings.llUSBControllers.begin();
5627 it != hw.usbSettings.llUSBControllers.end();
5628 ++it)
5629 {
5630 const USBController &ctrl = *it;
5631
5632 switch (ctrl.enmType)
5633 {
5634 case USBControllerType_OHCI:
5635 fOhciEnabled = true;
5636 break;
5637 case USBControllerType_EHCI:
5638 fEhciEnabled = true;
5639 break;
5640 default:
5641 AssertMsgFailed(("Unknown USB controller type %d\n", ctrl.enmType));
5642 }
5643 }
5644
5645 pelmUSB->setAttribute("enabled", fOhciEnabled);
5646 pelmUSB->setAttribute("enabledEhci", fEhciEnabled);
5647
5648 buildUSBDeviceFilters(*pelmUSB, hw.usbSettings.llDeviceFilters, false /* fHostMode */);
5649 }
5650 else
5651 {
5652 if ( hw.usbSettings.llUSBControllers.size()
5653 || hw.usbSettings.llDeviceFilters.size())
5654 {
5655 xml::ElementNode *pelmUSB = pelmHardware->createChild("USB");
5656 if (hw.usbSettings.llUSBControllers.size())
5657 {
5658 xml::ElementNode *pelmCtrls = pelmUSB->createChild("Controllers");
5659
5660 for (USBControllerList::const_iterator it = hw.usbSettings.llUSBControllers.begin();
5661 it != hw.usbSettings.llUSBControllers.end();
5662 ++it)
5663 {
5664 const USBController &ctrl = *it;
5665 com::Utf8Str strType;
5666 xml::ElementNode *pelmCtrl = pelmCtrls->createChild("Controller");
5667
5668 switch (ctrl.enmType)
5669 {
5670 case USBControllerType_OHCI:
5671 strType = "OHCI";
5672 break;
5673 case USBControllerType_EHCI:
5674 strType = "EHCI";
5675 break;
5676 case USBControllerType_XHCI:
5677 strType = "XHCI";
5678 break;
5679 default:
5680 AssertMsgFailed(("Unknown USB controller type %d\n", ctrl.enmType));
5681 }
5682
5683 pelmCtrl->setAttribute("name", ctrl.strName);
5684 pelmCtrl->setAttribute("type", strType);
5685 }
5686 }
5687
5688 if (hw.usbSettings.llDeviceFilters.size())
5689 {
5690 xml::ElementNode *pelmFilters = pelmUSB->createChild("DeviceFilters");
5691 buildUSBDeviceFilters(*pelmFilters, hw.usbSettings.llDeviceFilters, false /* fHostMode */);
5692 }
5693 }
5694 }
5695
5696 if ( hw.llNetworkAdapters.size()
5697 && !hw.areAllNetworkAdaptersDefaultSettings(m->sv))
5698 {
5699 xml::ElementNode *pelmNetwork = pelmHardware->createChild("Network");
5700 for (NetworkAdaptersList::const_iterator it = hw.llNetworkAdapters.begin();
5701 it != hw.llNetworkAdapters.end();
5702 ++it)
5703 {
5704 const NetworkAdapter &nic = *it;
5705
5706 if (!nic.areDefaultSettings(m->sv))
5707 {
5708 xml::ElementNode *pelmAdapter = pelmNetwork->createChild("Adapter");
5709 pelmAdapter->setAttribute("slot", nic.ulSlot);
5710 if (nic.fEnabled)
5711 pelmAdapter->setAttribute("enabled", nic.fEnabled);
5712 if (!nic.strMACAddress.isEmpty())
5713 pelmAdapter->setAttribute("MACAddress", nic.strMACAddress);
5714 if ( (m->sv >= SettingsVersion_v1_16 && !nic.fCableConnected)
5715 || (m->sv < SettingsVersion_v1_16 && nic.fCableConnected))
5716 pelmAdapter->setAttribute("cable", nic.fCableConnected);
5717 if (nic.ulLineSpeed)
5718 pelmAdapter->setAttribute("speed", nic.ulLineSpeed);
5719 if (nic.ulBootPriority != 0)
5720 pelmAdapter->setAttribute("bootPriority", nic.ulBootPriority);
5721 if (nic.fTraceEnabled)
5722 {
5723 pelmAdapter->setAttribute("trace", nic.fTraceEnabled);
5724 pelmAdapter->setAttribute("tracefile", nic.strTraceFile);
5725 }
5726 if (nic.strBandwidthGroup.isNotEmpty())
5727 pelmAdapter->setAttribute("bandwidthGroup", nic.strBandwidthGroup);
5728
5729 const char *pszPolicy;
5730 switch (nic.enmPromiscModePolicy)
5731 {
5732 case NetworkAdapterPromiscModePolicy_Deny: pszPolicy = NULL; break;
5733 case NetworkAdapterPromiscModePolicy_AllowNetwork: pszPolicy = "AllowNetwork"; break;
5734 case NetworkAdapterPromiscModePolicy_AllowAll: pszPolicy = "AllowAll"; break;
5735 default: pszPolicy = NULL; AssertFailed(); break;
5736 }
5737 if (pszPolicy)
5738 pelmAdapter->setAttribute("promiscuousModePolicy", pszPolicy);
5739
5740 if (nic.type != NetworkAdapterType_Am79C973)
5741 {
5742 const char *pcszType;
5743 switch (nic.type)
5744 {
5745 case NetworkAdapterType_Am79C973: pcszType = "Am79C973"; break;
5746 case NetworkAdapterType_I82540EM: pcszType = "82540EM"; break;
5747 case NetworkAdapterType_I82543GC: pcszType = "82543GC"; break;
5748 case NetworkAdapterType_I82545EM: pcszType = "82545EM"; break;
5749 case NetworkAdapterType_Virtio: pcszType = "virtio"; break;
5750 default: /*case NetworkAdapterType_Am79C970A:*/ pcszType = "Am79C970A"; break;
5751 }
5752 pelmAdapter->setAttribute("type", pcszType);
5753 }
5754
5755 xml::ElementNode *pelmNAT;
5756 if (m->sv < SettingsVersion_v1_10)
5757 {
5758 switch (nic.mode)
5759 {
5760 case NetworkAttachmentType_NAT:
5761 pelmNAT = pelmAdapter->createChild("NAT");
5762 if (nic.nat.strNetwork.length())
5763 pelmNAT->setAttribute("network", nic.nat.strNetwork);
5764 break;
5765
5766 case NetworkAttachmentType_Bridged:
5767 pelmAdapter->createChild("BridgedInterface")->setAttribute("name", nic.strBridgedName);
5768 break;
5769
5770 case NetworkAttachmentType_Internal:
5771 pelmAdapter->createChild("InternalNetwork")->setAttribute("name", nic.strInternalNetworkName);
5772 break;
5773
5774 case NetworkAttachmentType_HostOnly:
5775 pelmAdapter->createChild("HostOnlyInterface")->setAttribute("name", nic.strHostOnlyName);
5776 break;
5777
5778 default: /*case NetworkAttachmentType_Null:*/
5779 break;
5780 }
5781 }
5782 else
5783 {
5784 /* m->sv >= SettingsVersion_v1_10 */
5785 if (!nic.areDisabledDefaultSettings())
5786 {
5787 xml::ElementNode *pelmDisabledNode = pelmAdapter->createChild("DisabledModes");
5788 if (nic.mode != NetworkAttachmentType_NAT)
5789 buildNetworkXML(NetworkAttachmentType_NAT, false, *pelmDisabledNode, nic);
5790 if (nic.mode != NetworkAttachmentType_Bridged)
5791 buildNetworkXML(NetworkAttachmentType_Bridged, false, *pelmDisabledNode, nic);
5792 if (nic.mode != NetworkAttachmentType_Internal)
5793 buildNetworkXML(NetworkAttachmentType_Internal, false, *pelmDisabledNode, nic);
5794 if (nic.mode != NetworkAttachmentType_HostOnly)
5795 buildNetworkXML(NetworkAttachmentType_HostOnly, false, *pelmDisabledNode, nic);
5796 if (nic.mode != NetworkAttachmentType_Generic)
5797 buildNetworkXML(NetworkAttachmentType_Generic, false, *pelmDisabledNode, nic);
5798 if (nic.mode != NetworkAttachmentType_NATNetwork)
5799 buildNetworkXML(NetworkAttachmentType_NATNetwork, false, *pelmDisabledNode, nic);
5800 }
5801 buildNetworkXML(nic.mode, true, *pelmAdapter, nic);
5802 }
5803 }
5804 }
5805 }
5806
5807 if (hw.llSerialPorts.size())
5808 {
5809 xml::ElementNode *pelmPorts = pelmHardware->createChild("UART");
5810 for (SerialPortsList::const_iterator it = hw.llSerialPorts.begin();
5811 it != hw.llSerialPorts.end();
5812 ++it)
5813 {
5814 const SerialPort &port = *it;
5815 xml::ElementNode *pelmPort = pelmPorts->createChild("Port");
5816 pelmPort->setAttribute("slot", port.ulSlot);
5817 pelmPort->setAttribute("enabled", port.fEnabled);
5818 pelmPort->setAttributeHex("IOBase", port.ulIOBase);
5819 pelmPort->setAttribute("IRQ", port.ulIRQ);
5820
5821 const char *pcszHostMode;
5822 switch (port.portMode)
5823 {
5824 case PortMode_HostPipe: pcszHostMode = "HostPipe"; break;
5825 case PortMode_HostDevice: pcszHostMode = "HostDevice"; break;
5826 case PortMode_TCP: pcszHostMode = "TCP"; break;
5827 case PortMode_RawFile: pcszHostMode = "RawFile"; break;
5828 default: /*case PortMode_Disconnected:*/ pcszHostMode = "Disconnected"; break;
5829 }
5830 switch (port.portMode)
5831 {
5832 case PortMode_TCP:
5833 case PortMode_HostPipe:
5834 pelmPort->setAttribute("server", port.fServer);
5835 /* no break */
5836 case PortMode_HostDevice:
5837 case PortMode_RawFile:
5838 pelmPort->setAttribute("path", port.strPath);
5839 break;
5840
5841 default:
5842 break;
5843 }
5844 pelmPort->setAttribute("hostMode", pcszHostMode);
5845 }
5846 }
5847
5848 if (hw.llParallelPorts.size())
5849 {
5850 xml::ElementNode *pelmPorts = pelmHardware->createChild("LPT");
5851 for (ParallelPortsList::const_iterator it = hw.llParallelPorts.begin();
5852 it != hw.llParallelPorts.end();
5853 ++it)
5854 {
5855 const ParallelPort &port = *it;
5856 xml::ElementNode *pelmPort = pelmPorts->createChild("Port");
5857 pelmPort->setAttribute("slot", port.ulSlot);
5858 pelmPort->setAttribute("enabled", port.fEnabled);
5859 pelmPort->setAttributeHex("IOBase", port.ulIOBase);
5860 pelmPort->setAttribute("IRQ", port.ulIRQ);
5861 if (port.strPath.length())
5862 pelmPort->setAttribute("path", port.strPath);
5863 }
5864 }
5865
5866 if (!hw.audioAdapter.areDefaultSettings(m->sv))
5867 {
5868 xml::ElementNode *pelmAudio = pelmHardware->createChild("AudioAdapter");
5869 if (hw.audioAdapter.controllerType != AudioControllerType_AC97)
5870 {
5871 const char *pcszController;
5872 switch (hw.audioAdapter.controllerType)
5873 {
5874 case AudioControllerType_SB16:
5875 pcszController = "SB16";
5876 break;
5877 case AudioControllerType_HDA:
5878 if (m->sv >= SettingsVersion_v1_11)
5879 {
5880 pcszController = "HDA";
5881 break;
5882 }
5883 /* fall through */
5884 case AudioControllerType_AC97:
5885 default:
5886 pcszController = "AC97";
5887 break;
5888 }
5889 pelmAudio->setAttribute("controller", pcszController);
5890 }
5891
5892 const char *pcszCodec;
5893 switch (hw.audioAdapter.codecType)
5894 {
5895 /* Only write out the setting for non-default AC'97 codec
5896 * and leave the rest alone.
5897 */
5898#if 0
5899 case AudioCodecType_SB16:
5900 pcszCodec = "SB16";
5901 break;
5902 case AudioCodecType_STAC9221:
5903 pcszCodec = "STAC9221";
5904 break;
5905 case AudioCodecType_STAC9700:
5906 pcszCodec = "STAC9700";
5907 break;
5908#endif
5909 case AudioCodecType_AD1980:
5910 pcszCodec = "AD1980";
5911 break;
5912 default:
5913 /* Don't write out anything if unknown. */
5914 pcszCodec = NULL;
5915 }
5916 if (pcszCodec)
5917 pelmAudio->setAttribute("codec", pcszCodec);
5918
5919 const char *pcszDriver;
5920 switch (hw.audioAdapter.driverType)
5921 {
5922 case AudioDriverType_WinMM: pcszDriver = "WinMM"; break;
5923 case AudioDriverType_DirectSound: pcszDriver = "DirectSound"; break;
5924 case AudioDriverType_SolAudio: pcszDriver = "SolAudio"; break;
5925 case AudioDriverType_ALSA: pcszDriver = "ALSA"; break;
5926 case AudioDriverType_Pulse: pcszDriver = "Pulse"; break;
5927 case AudioDriverType_OSS: pcszDriver = "OSS"; break;
5928 case AudioDriverType_CoreAudio: pcszDriver = "CoreAudio"; break;
5929 case AudioDriverType_MMPM: pcszDriver = "MMPM"; break;
5930 default: /*case AudioDriverType_Null:*/ pcszDriver = "Null"; break;
5931 }
5932 pelmAudio->setAttribute("driver", pcszDriver);
5933
5934 if (hw.audioAdapter.fEnabled || m->sv <= SettingsVersion_v1_14)
5935 pelmAudio->setAttribute("enabled", hw.audioAdapter.fEnabled);
5936
5937 if (m->sv >= SettingsVersion_v1_15 && hw.audioAdapter.properties.size() > 0)
5938 {
5939 for (StringsMap::const_iterator it = hw.audioAdapter.properties.begin();
5940 it != hw.audioAdapter.properties.end();
5941 ++it)
5942 {
5943 const Utf8Str &strName = it->first;
5944 const Utf8Str &strValue = it->second;
5945 xml::ElementNode *pelm = pelmAudio->createChild("Property");
5946 pelm->setAttribute("name", strName);
5947 pelm->setAttribute("value", strValue);
5948 }
5949 }
5950 }
5951
5952 if (m->sv >= SettingsVersion_v1_10 && machineUserData.fRTCUseUTC)
5953 {
5954 xml::ElementNode *pelmRTC = pelmHardware->createChild("RTC");
5955 pelmRTC->setAttribute("localOrUTC", machineUserData.fRTCUseUTC ? "UTC" : "local");
5956 }
5957
5958 if (hw.llSharedFolders.size())
5959 {
5960 xml::ElementNode *pelmSharedFolders = pelmHardware->createChild("SharedFolders");
5961 for (SharedFoldersList::const_iterator it = hw.llSharedFolders.begin();
5962 it != hw.llSharedFolders.end();
5963 ++it)
5964 {
5965 const SharedFolder &sf = *it;
5966 xml::ElementNode *pelmThis = pelmSharedFolders->createChild("SharedFolder");
5967 pelmThis->setAttribute("name", sf.strName);
5968 pelmThis->setAttribute("hostPath", sf.strHostPath);
5969 pelmThis->setAttribute("writable", sf.fWritable);
5970 pelmThis->setAttribute("autoMount", sf.fAutoMount);
5971 }
5972 }
5973
5974 if (hw.clipboardMode != ClipboardMode_Disabled)
5975 {
5976 xml::ElementNode *pelmClip = pelmHardware->createChild("Clipboard");
5977 const char *pcszClip;
5978 switch (hw.clipboardMode)
5979 {
5980 default: /*case ClipboardMode_Disabled:*/ pcszClip = "Disabled"; break;
5981 case ClipboardMode_HostToGuest: pcszClip = "HostToGuest"; break;
5982 case ClipboardMode_GuestToHost: pcszClip = "GuestToHost"; break;
5983 case ClipboardMode_Bidirectional: pcszClip = "Bidirectional"; break;
5984 }
5985 pelmClip->setAttribute("mode", pcszClip);
5986 }
5987
5988 if (hw.dndMode != DnDMode_Disabled)
5989 {
5990 xml::ElementNode *pelmDragAndDrop = pelmHardware->createChild("DragAndDrop");
5991 const char *pcszDragAndDrop;
5992 switch (hw.dndMode)
5993 {
5994 default: /*case DnDMode_Disabled:*/ pcszDragAndDrop = "Disabled"; break;
5995 case DnDMode_HostToGuest: pcszDragAndDrop = "HostToGuest"; break;
5996 case DnDMode_GuestToHost: pcszDragAndDrop = "GuestToHost"; break;
5997 case DnDMode_Bidirectional: pcszDragAndDrop = "Bidirectional"; break;
5998 }
5999 pelmDragAndDrop->setAttribute("mode", pcszDragAndDrop);
6000 }
6001
6002 if ( m->sv >= SettingsVersion_v1_10
6003 && !hw.ioSettings.areDefaultSettings())
6004 {
6005 xml::ElementNode *pelmIO = pelmHardware->createChild("IO");
6006 xml::ElementNode *pelmIOCache;
6007
6008 if (!hw.ioSettings.areDefaultSettings())
6009 {
6010 pelmIOCache = pelmIO->createChild("IoCache");
6011 if (!hw.ioSettings.fIOCacheEnabled)
6012 pelmIOCache->setAttribute("enabled", hw.ioSettings.fIOCacheEnabled);
6013 if (hw.ioSettings.ulIOCacheSize != 5)
6014 pelmIOCache->setAttribute("size", hw.ioSettings.ulIOCacheSize);
6015 }
6016
6017 if ( m->sv >= SettingsVersion_v1_11
6018 && hw.ioSettings.llBandwidthGroups.size())
6019 {
6020 xml::ElementNode *pelmBandwidthGroups = pelmIO->createChild("BandwidthGroups");
6021 for (BandwidthGroupList::const_iterator it = hw.ioSettings.llBandwidthGroups.begin();
6022 it != hw.ioSettings.llBandwidthGroups.end();
6023 ++it)
6024 {
6025 const BandwidthGroup &gr = *it;
6026 const char *pcszType;
6027 xml::ElementNode *pelmThis = pelmBandwidthGroups->createChild("BandwidthGroup");
6028 pelmThis->setAttribute("name", gr.strName);
6029 switch (gr.enmType)
6030 {
6031 case BandwidthGroupType_Network: pcszType = "Network"; break;
6032 default: /* BandwidthGrouptype_Disk */ pcszType = "Disk"; break;
6033 }
6034 pelmThis->setAttribute("type", pcszType);
6035 if (m->sv >= SettingsVersion_v1_13)
6036 pelmThis->setAttribute("maxBytesPerSec", gr.cMaxBytesPerSec);
6037 else
6038 pelmThis->setAttribute("maxMbPerSec", gr.cMaxBytesPerSec / _1M);
6039 }
6040 }
6041 }
6042
6043 if ( m->sv >= SettingsVersion_v1_12
6044 && hw.pciAttachments.size())
6045 {
6046 xml::ElementNode *pelmPCI = pelmHardware->createChild("HostPci");
6047 xml::ElementNode *pelmPCIDevices = pelmPCI->createChild("Devices");
6048
6049 for (HostPCIDeviceAttachmentList::const_iterator it = hw.pciAttachments.begin();
6050 it != hw.pciAttachments.end();
6051 ++it)
6052 {
6053 const HostPCIDeviceAttachment &hpda = *it;
6054
6055 xml::ElementNode *pelmThis = pelmPCIDevices->createChild("Device");
6056
6057 pelmThis->setAttribute("host", hpda.uHostAddress);
6058 pelmThis->setAttribute("guest", hpda.uGuestAddress);
6059 pelmThis->setAttribute("name", hpda.strDeviceName);
6060 }
6061 }
6062
6063 if ( m->sv >= SettingsVersion_v1_12
6064 && hw.fEmulatedUSBCardReader)
6065 {
6066 xml::ElementNode *pelmEmulatedUSB = pelmHardware->createChild("EmulatedUSB");
6067
6068 xml::ElementNode *pelmCardReader = pelmEmulatedUSB->createChild("CardReader");
6069 pelmCardReader->setAttribute("enabled", hw.fEmulatedUSBCardReader);
6070 }
6071
6072 if ( m->sv >= SettingsVersion_v1_14
6073 && !hw.strDefaultFrontend.isEmpty())
6074 {
6075 xml::ElementNode *pelmFrontend = pelmHardware->createChild("Frontend");
6076 xml::ElementNode *pelmDefault = pelmFrontend->createChild("Default");
6077 pelmDefault->setAttribute("type", hw.strDefaultFrontend);
6078 }
6079
6080 if (hw.ulMemoryBalloonSize)
6081 {
6082 xml::ElementNode *pelmGuest = pelmHardware->createChild("Guest");
6083 pelmGuest->setAttribute("memoryBalloonSize", hw.ulMemoryBalloonSize);
6084 }
6085
6086 if (hw.llGuestProperties.size())
6087 {
6088 xml::ElementNode *pelmGuestProps = pelmHardware->createChild("GuestProperties");
6089 for (GuestPropertiesList::const_iterator it = hw.llGuestProperties.begin();
6090 it != hw.llGuestProperties.end();
6091 ++it)
6092 {
6093 const GuestProperty &prop = *it;
6094 xml::ElementNode *pelmProp = pelmGuestProps->createChild("GuestProperty");
6095 pelmProp->setAttribute("name", prop.strName);
6096 pelmProp->setAttribute("value", prop.strValue);
6097 pelmProp->setAttribute("timestamp", prop.timestamp);
6098 pelmProp->setAttribute("flags", prop.strFlags);
6099 }
6100 }
6101
6102 /** @todo In the future (6.0?) place the storage controllers under <Hardware>, because
6103 * this is where it always should've been. What else than hardware are they? */
6104 xml::ElementNode &elmStorageParent = (m->sv > SettingsVersion_Future) ? *pelmHardware : elmParent;
6105 buildStorageControllersXML(elmStorageParent,
6106 hw.storage,
6107 !!(fl & BuildMachineXML_SkipRemovableMedia),
6108 pllElementsWithUuidAttributes);
6109}
6110
6111/**
6112 * Fill a \<Network\> node. Only relevant for XML version >= v1_10.
6113 * @param mode
6114 * @param fEnabled
6115 * @param elmParent
6116 * @param nic
6117 */
6118void MachineConfigFile::buildNetworkXML(NetworkAttachmentType_T mode,
6119 bool fEnabled,
6120 xml::ElementNode &elmParent,
6121 const NetworkAdapter &nic)
6122{
6123 switch (mode)
6124 {
6125 case NetworkAttachmentType_NAT:
6126 // For the currently active network attachment type we have to
6127 // generate the tag, otherwise the attachment type is lost.
6128 if (fEnabled || !nic.nat.areDefaultSettings())
6129 {
6130 xml::ElementNode *pelmNAT = elmParent.createChild("NAT");
6131
6132 if (!nic.nat.areDefaultSettings())
6133 {
6134 if (nic.nat.strNetwork.length())
6135 pelmNAT->setAttribute("network", nic.nat.strNetwork);
6136 if (nic.nat.strBindIP.length())
6137 pelmNAT->setAttribute("hostip", nic.nat.strBindIP);
6138 if (nic.nat.u32Mtu)
6139 pelmNAT->setAttribute("mtu", nic.nat.u32Mtu);
6140 if (nic.nat.u32SockRcv)
6141 pelmNAT->setAttribute("sockrcv", nic.nat.u32SockRcv);
6142 if (nic.nat.u32SockSnd)
6143 pelmNAT->setAttribute("socksnd", nic.nat.u32SockSnd);
6144 if (nic.nat.u32TcpRcv)
6145 pelmNAT->setAttribute("tcprcv", nic.nat.u32TcpRcv);
6146 if (nic.nat.u32TcpSnd)
6147 pelmNAT->setAttribute("tcpsnd", nic.nat.u32TcpSnd);
6148 if (!nic.nat.areDNSDefaultSettings())
6149 {
6150 xml::ElementNode *pelmDNS = pelmNAT->createChild("DNS");
6151 if (!nic.nat.fDNSPassDomain)
6152 pelmDNS->setAttribute("pass-domain", nic.nat.fDNSPassDomain);
6153 if (nic.nat.fDNSProxy)
6154 pelmDNS->setAttribute("use-proxy", nic.nat.fDNSProxy);
6155 if (nic.nat.fDNSUseHostResolver)
6156 pelmDNS->setAttribute("use-host-resolver", nic.nat.fDNSUseHostResolver);
6157 }
6158
6159 if (!nic.nat.areAliasDefaultSettings())
6160 {
6161 xml::ElementNode *pelmAlias = pelmNAT->createChild("Alias");
6162 if (nic.nat.fAliasLog)
6163 pelmAlias->setAttribute("logging", nic.nat.fAliasLog);
6164 if (nic.nat.fAliasProxyOnly)
6165 pelmAlias->setAttribute("proxy-only", nic.nat.fAliasProxyOnly);
6166 if (nic.nat.fAliasUseSamePorts)
6167 pelmAlias->setAttribute("use-same-ports", nic.nat.fAliasUseSamePorts);
6168 }
6169
6170 if (!nic.nat.areTFTPDefaultSettings())
6171 {
6172 xml::ElementNode *pelmTFTP;
6173 pelmTFTP = pelmNAT->createChild("TFTP");
6174 if (nic.nat.strTFTPPrefix.length())
6175 pelmTFTP->setAttribute("prefix", nic.nat.strTFTPPrefix);
6176 if (nic.nat.strTFTPBootFile.length())
6177 pelmTFTP->setAttribute("boot-file", nic.nat.strTFTPBootFile);
6178 if (nic.nat.strTFTPNextServer.length())
6179 pelmTFTP->setAttribute("next-server", nic.nat.strTFTPNextServer);
6180 }
6181 buildNATForwardRulesMap(*pelmNAT, nic.nat.mapRules);
6182 }
6183 }
6184 break;
6185
6186 case NetworkAttachmentType_Bridged:
6187 // For the currently active network attachment type we have to
6188 // generate the tag, otherwise the attachment type is lost.
6189 if (fEnabled || !nic.strBridgedName.isEmpty())
6190 {
6191 xml::ElementNode *pelmMode = elmParent.createChild("BridgedInterface");
6192 if (!nic.strBridgedName.isEmpty())
6193 pelmMode->setAttribute("name", nic.strBridgedName);
6194 }
6195 break;
6196
6197 case NetworkAttachmentType_Internal:
6198 // For the currently active network attachment type we have to
6199 // generate the tag, otherwise the attachment type is lost.
6200 if (fEnabled || !nic.strInternalNetworkName.isEmpty())
6201 {
6202 xml::ElementNode *pelmMode = elmParent.createChild("InternalNetwork");
6203 if (!nic.strInternalNetworkName.isEmpty())
6204 pelmMode->setAttribute("name", nic.strInternalNetworkName);
6205 }
6206 break;
6207
6208 case NetworkAttachmentType_HostOnly:
6209 // For the currently active network attachment type we have to
6210 // generate the tag, otherwise the attachment type is lost.
6211 if (fEnabled || !nic.strHostOnlyName.isEmpty())
6212 {
6213 xml::ElementNode *pelmMode = elmParent.createChild("HostOnlyInterface");
6214 if (!nic.strHostOnlyName.isEmpty())
6215 pelmMode->setAttribute("name", nic.strHostOnlyName);
6216 }
6217 break;
6218
6219 case NetworkAttachmentType_Generic:
6220 // For the currently active network attachment type we have to
6221 // generate the tag, otherwise the attachment type is lost.
6222 if (fEnabled || !nic.areGenericDriverDefaultSettings())
6223 {
6224 xml::ElementNode *pelmMode = elmParent.createChild("GenericInterface");
6225 if (!nic.areGenericDriverDefaultSettings())
6226 {
6227 pelmMode->setAttribute("driver", nic.strGenericDriver);
6228 for (StringsMap::const_iterator it = nic.genericProperties.begin();
6229 it != nic.genericProperties.end();
6230 ++it)
6231 {
6232 xml::ElementNode *pelmProp = pelmMode->createChild("Property");
6233 pelmProp->setAttribute("name", it->first);
6234 pelmProp->setAttribute("value", it->second);
6235 }
6236 }
6237 }
6238 break;
6239
6240 case NetworkAttachmentType_NATNetwork:
6241 // For the currently active network attachment type we have to
6242 // generate the tag, otherwise the attachment type is lost.
6243 if (fEnabled || !nic.strNATNetworkName.isEmpty())
6244 {
6245 xml::ElementNode *pelmMode = elmParent.createChild("NATNetwork");
6246 if (!nic.strNATNetworkName.isEmpty())
6247 pelmMode->setAttribute("name", nic.strNATNetworkName);
6248 }
6249 break;
6250
6251 default: /*case NetworkAttachmentType_Null:*/
6252 break;
6253 }
6254}
6255
6256/**
6257 * Creates a \<StorageControllers\> node under elmParent and then writes out the XML
6258 * keys under that. Called for both the \<Machine\> node and for snapshots.
6259 * @param elmParent
6260 * @param st
6261 * @param fSkipRemovableMedia If true, DVD and floppy attachments are skipped and
6262 * an empty drive is always written instead. This is for the OVF export case.
6263 * This parameter is ignored unless the settings version is at least v1.9, which
6264 * is always the case when this gets called for OVF export.
6265 * @param pllElementsWithUuidAttributes If not NULL, must point to a list of element node
6266 * pointers to which we will append all elements that we created here that contain
6267 * UUID attributes. This allows the OVF export code to quickly replace the internal
6268 * media UUIDs with the UUIDs of the media that were exported.
6269 */
6270void MachineConfigFile::buildStorageControllersXML(xml::ElementNode &elmParent,
6271 const Storage &st,
6272 bool fSkipRemovableMedia,
6273 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes)
6274{
6275 if (!st.llStorageControllers.size())
6276 return;
6277 xml::ElementNode *pelmStorageControllers = elmParent.createChild("StorageControllers");
6278
6279 for (StorageControllersList::const_iterator it = st.llStorageControllers.begin();
6280 it != st.llStorageControllers.end();
6281 ++it)
6282 {
6283 const StorageController &sc = *it;
6284
6285 if ( (m->sv < SettingsVersion_v1_9)
6286 && (sc.controllerType == StorageControllerType_I82078)
6287 )
6288 // floppy controller already got written into <Hardware>/<FloppyController> in buildHardwareXML()
6289 // for pre-1.9 settings
6290 continue;
6291
6292 xml::ElementNode *pelmController = pelmStorageControllers->createChild("StorageController");
6293 com::Utf8Str name = sc.strName;
6294 if (m->sv < SettingsVersion_v1_8)
6295 {
6296 // pre-1.8 settings use shorter controller names, they are
6297 // expanded when reading the settings
6298 if (name == "IDE Controller")
6299 name = "IDE";
6300 else if (name == "SATA Controller")
6301 name = "SATA";
6302 else if (name == "SCSI Controller")
6303 name = "SCSI";
6304 }
6305 pelmController->setAttribute("name", sc.strName);
6306
6307 const char *pcszType;
6308 switch (sc.controllerType)
6309 {
6310 case StorageControllerType_IntelAhci: pcszType = "AHCI"; break;
6311 case StorageControllerType_LsiLogic: pcszType = "LsiLogic"; break;
6312 case StorageControllerType_BusLogic: pcszType = "BusLogic"; break;
6313 case StorageControllerType_PIIX4: pcszType = "PIIX4"; break;
6314 case StorageControllerType_ICH6: pcszType = "ICH6"; break;
6315 case StorageControllerType_I82078: pcszType = "I82078"; break;
6316 case StorageControllerType_LsiLogicSas: pcszType = "LsiLogicSas"; break;
6317 case StorageControllerType_USB: pcszType = "USB"; break;
6318 case StorageControllerType_NVMe: pcszType = "NVMe"; break;
6319 default: /*case StorageControllerType_PIIX3:*/ pcszType = "PIIX3"; break;
6320 }
6321 pelmController->setAttribute("type", pcszType);
6322
6323 pelmController->setAttribute("PortCount", sc.ulPortCount);
6324
6325 if (m->sv >= SettingsVersion_v1_9)
6326 if (sc.ulInstance)
6327 pelmController->setAttribute("Instance", sc.ulInstance);
6328
6329 if (m->sv >= SettingsVersion_v1_10)
6330 pelmController->setAttribute("useHostIOCache", sc.fUseHostIOCache);
6331
6332 if (m->sv >= SettingsVersion_v1_11)
6333 pelmController->setAttribute("Bootable", sc.fBootable);
6334
6335 if (sc.controllerType == StorageControllerType_IntelAhci)
6336 {
6337 pelmController->setAttribute("IDE0MasterEmulationPort", 0);
6338 pelmController->setAttribute("IDE0SlaveEmulationPort", 1);
6339 pelmController->setAttribute("IDE1MasterEmulationPort", 2);
6340 pelmController->setAttribute("IDE1SlaveEmulationPort", 3);
6341 }
6342
6343 for (AttachedDevicesList::const_iterator it2 = sc.llAttachedDevices.begin();
6344 it2 != sc.llAttachedDevices.end();
6345 ++it2)
6346 {
6347 const AttachedDevice &att = *it2;
6348
6349 // For settings version before 1.9, DVDs and floppies are in hardware, not storage controllers,
6350 // so we shouldn't write them here; we only get here for DVDs though because we ruled out
6351 // the floppy controller at the top of the loop
6352 if ( att.deviceType == DeviceType_DVD
6353 && m->sv < SettingsVersion_v1_9
6354 )
6355 continue;
6356
6357 xml::ElementNode *pelmDevice = pelmController->createChild("AttachedDevice");
6358
6359 pcszType = NULL;
6360
6361 switch (att.deviceType)
6362 {
6363 case DeviceType_HardDisk:
6364 pcszType = "HardDisk";
6365 if (att.fNonRotational)
6366 pelmDevice->setAttribute("nonrotational", att.fNonRotational);
6367 if (att.fDiscard)
6368 pelmDevice->setAttribute("discard", att.fDiscard);
6369 break;
6370
6371 case DeviceType_DVD:
6372 pcszType = "DVD";
6373 pelmDevice->setAttribute("passthrough", att.fPassThrough);
6374 if (att.fTempEject)
6375 pelmDevice->setAttribute("tempeject", att.fTempEject);
6376 break;
6377
6378 case DeviceType_Floppy:
6379 pcszType = "Floppy";
6380 break;
6381 }
6382
6383 pelmDevice->setAttribute("type", pcszType);
6384
6385 if (m->sv >= SettingsVersion_v1_15)
6386 pelmDevice->setAttribute("hotpluggable", att.fHotPluggable);
6387
6388 pelmDevice->setAttribute("port", att.lPort);
6389 pelmDevice->setAttribute("device", att.lDevice);
6390
6391 if (att.strBwGroup.length())
6392 pelmDevice->setAttribute("bandwidthGroup", att.strBwGroup);
6393
6394 // attached image, if any
6395 if (!att.uuid.isZero()
6396 && att.uuid.isValid()
6397 && (att.deviceType == DeviceType_HardDisk
6398 || !fSkipRemovableMedia
6399 )
6400 )
6401 {
6402 xml::ElementNode *pelmImage = pelmDevice->createChild("Image");
6403 pelmImage->setAttribute("uuid", att.uuid.toStringCurly());
6404
6405 // if caller wants a list of UUID elements, give it to them
6406 if (pllElementsWithUuidAttributes)
6407 pllElementsWithUuidAttributes->push_back(pelmImage);
6408 }
6409 else if ( (m->sv >= SettingsVersion_v1_9)
6410 && (att.strHostDriveSrc.length())
6411 )
6412 pelmDevice->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
6413 }
6414 }
6415}
6416
6417/**
6418 * Creates a \<Debugging\> node under elmParent and then writes out the XML
6419 * keys under that. Called for both the \<Machine\> node and for snapshots.
6420 *
6421 * @param pElmParent Pointer to the parent element.
6422 * @param pDbg Pointer to the debugging settings.
6423 */
6424void MachineConfigFile::buildDebuggingXML(xml::ElementNode *pElmParent, const Debugging *pDbg)
6425{
6426 if (m->sv < SettingsVersion_v1_13 || pDbg->areDefaultSettings())
6427 return;
6428
6429 xml::ElementNode *pElmDebugging = pElmParent->createChild("Debugging");
6430 xml::ElementNode *pElmTracing = pElmDebugging->createChild("Tracing");
6431 pElmTracing->setAttribute("enabled", pDbg->fTracingEnabled);
6432 pElmTracing->setAttribute("allowTracingToAccessVM", pDbg->fAllowTracingToAccessVM);
6433 pElmTracing->setAttribute("config", pDbg->strTracingConfig);
6434}
6435
6436/**
6437 * Creates a \<Autostart\> node under elmParent and then writes out the XML
6438 * keys under that. Called for both the \<Machine\> node and for snapshots.
6439 *
6440 * @param pElmParent Pointer to the parent element.
6441 * @param pAutostart Pointer to the autostart settings.
6442 */
6443void MachineConfigFile::buildAutostartXML(xml::ElementNode *pElmParent, const Autostart *pAutostart)
6444{
6445 const char *pcszAutostop = NULL;
6446
6447 if (m->sv < SettingsVersion_v1_13 || pAutostart->areDefaultSettings())
6448 return;
6449
6450 xml::ElementNode *pElmAutostart = pElmParent->createChild("Autostart");
6451 pElmAutostart->setAttribute("enabled", pAutostart->fAutostartEnabled);
6452 pElmAutostart->setAttribute("delay", pAutostart->uAutostartDelay);
6453
6454 switch (pAutostart->enmAutostopType)
6455 {
6456 case AutostopType_Disabled: pcszAutostop = "Disabled"; break;
6457 case AutostopType_SaveState: pcszAutostop = "SaveState"; break;
6458 case AutostopType_PowerOff: pcszAutostop = "PowerOff"; break;
6459 case AutostopType_AcpiShutdown: pcszAutostop = "AcpiShutdown"; break;
6460 default: Assert(false); pcszAutostop = "Disabled"; break;
6461 }
6462 pElmAutostart->setAttribute("autostop", pcszAutostop);
6463}
6464
6465/**
6466 * Creates a \<Groups\> node under elmParent and then writes out the XML
6467 * keys under that. Called for the \<Machine\> node only.
6468 *
6469 * @param pElmParent Pointer to the parent element.
6470 * @param pllGroups Pointer to the groups list.
6471 */
6472void MachineConfigFile::buildGroupsXML(xml::ElementNode *pElmParent, const StringsList *pllGroups)
6473{
6474 if ( m->sv < SettingsVersion_v1_13 || pllGroups->size() == 0
6475 || (pllGroups->size() == 1 && pllGroups->front() == "/"))
6476 return;
6477
6478 xml::ElementNode *pElmGroups = pElmParent->createChild("Groups");
6479 for (StringsList::const_iterator it = pllGroups->begin();
6480 it != pllGroups->end();
6481 ++it)
6482 {
6483 const Utf8Str &group = *it;
6484 xml::ElementNode *pElmGroup = pElmGroups->createChild("Group");
6485 pElmGroup->setAttribute("name", group);
6486 }
6487}
6488
6489/**
6490 * Writes a single snapshot into the DOM tree. Initially this gets called from MachineConfigFile::write()
6491 * for the root snapshot of a machine, if present; elmParent then points to the \<Snapshots\> node under the
6492 * \<Machine\> node to which \<Snapshot\> must be added. This may then recurse for child snapshots.
6493 *
6494 * @param depth
6495 * @param elmParent
6496 * @param snap
6497 */
6498void MachineConfigFile::buildSnapshotXML(uint32_t depth,
6499 xml::ElementNode &elmParent,
6500 const Snapshot &snap)
6501{
6502 if (depth > SETTINGS_SNAPSHOT_DEPTH_MAX)
6503 throw ConfigFileError(this, NULL, N_("Maximum snapshot tree depth of %u exceeded"), SETTINGS_SNAPSHOT_DEPTH_MAX);
6504
6505 xml::ElementNode *pelmSnapshot = elmParent.createChild("Snapshot");
6506
6507 pelmSnapshot->setAttribute("uuid", snap.uuid.toStringCurly());
6508 pelmSnapshot->setAttribute("name", snap.strName);
6509 pelmSnapshot->setAttribute("timeStamp", stringifyTimestamp(snap.timestamp));
6510
6511 if (snap.strStateFile.length())
6512 pelmSnapshot->setAttributePath("stateFile", snap.strStateFile);
6513
6514 if (snap.strDescription.length())
6515 pelmSnapshot->createChild("Description")->addContent(snap.strDescription);
6516
6517 // We only skip removable media for OVF, but OVF never includes snapshots.
6518 buildHardwareXML(*pelmSnapshot, snap.hardware, 0 /* fl */, NULL /* pllElementsWithUuidAttributes */);
6519 buildDebuggingXML(pelmSnapshot, &snap.debugging);
6520 buildAutostartXML(pelmSnapshot, &snap.autostart);
6521 // note: Groups exist only for Machine, not for Snapshot
6522
6523 if (snap.llChildSnapshots.size())
6524 {
6525 xml::ElementNode *pelmChildren = pelmSnapshot->createChild("Snapshots");
6526 for (SnapshotsList::const_iterator it = snap.llChildSnapshots.begin();
6527 it != snap.llChildSnapshots.end();
6528 ++it)
6529 {
6530 const Snapshot &child = *it;
6531 buildSnapshotXML(depth + 1, *pelmChildren, child);
6532 }
6533 }
6534}
6535
6536/**
6537 * Builds the XML DOM tree for the machine config under the given XML element.
6538 *
6539 * This has been separated out from write() so it can be called from elsewhere,
6540 * such as the OVF code, to build machine XML in an existing XML tree.
6541 *
6542 * As a result, this gets called from two locations:
6543 *
6544 * -- MachineConfigFile::write();
6545 *
6546 * -- Appliance::buildXMLForOneVirtualSystem()
6547 *
6548 * In fl, the following flag bits are recognized:
6549 *
6550 * -- BuildMachineXML_MediaRegistry: If set, the machine's media registry will
6551 * be written, if present. This is not set when called from OVF because OVF
6552 * has its own variant of a media registry. This flag is ignored unless the
6553 * settings version is at least v1.11 (VirtualBox 4.0).
6554 *
6555 * -- BuildMachineXML_IncludeSnapshots: If set, descend into the snapshots tree
6556 * of the machine and write out \<Snapshot\> and possibly more snapshots under
6557 * that, if snapshots are present. Otherwise all snapshots are suppressed
6558 * (when called from OVF).
6559 *
6560 * -- BuildMachineXML_WriteVBoxVersionAttribute: If set, add a settingsVersion
6561 * attribute to the machine tag with the vbox settings version. This is for
6562 * the OVF export case in which we don't have the settings version set in
6563 * the root element.
6564 *
6565 * -- BuildMachineXML_SkipRemovableMedia: If set, removable media attachments
6566 * (DVDs, floppies) are silently skipped. This is for the OVF export case
6567 * until we support copying ISO and RAW media as well. This flag is ignored
6568 * unless the settings version is at least v1.9, which is always the case
6569 * when this gets called for OVF export.
6570 *
6571 * -- BuildMachineXML_SuppressSavedState: If set, the Machine/@stateFile
6572 * attribute is never set. This is also for the OVF export case because we
6573 * cannot save states with OVF.
6574 *
6575 * @param elmMachine XML \<Machine\> element to add attributes and elements to.
6576 * @param fl Flags.
6577 * @param pllElementsWithUuidAttributes pointer to list that should receive UUID elements or NULL;
6578 * see buildStorageControllersXML() for details.
6579 */
6580void MachineConfigFile::buildMachineXML(xml::ElementNode &elmMachine,
6581 uint32_t fl,
6582 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes)
6583{
6584 if (fl & BuildMachineXML_WriteVBoxVersionAttribute)
6585 // add settings version attribute to machine element
6586 setVersionAttribute(elmMachine);
6587
6588 elmMachine.setAttribute("uuid", uuid.toStringCurly());
6589 elmMachine.setAttribute("name", machineUserData.strName);
6590 if (machineUserData.fDirectoryIncludesUUID)
6591 elmMachine.setAttribute("directoryIncludesUUID", machineUserData.fDirectoryIncludesUUID);
6592 if (!machineUserData.fNameSync)
6593 elmMachine.setAttribute("nameSync", machineUserData.fNameSync);
6594 if (machineUserData.strDescription.length())
6595 elmMachine.createChild("Description")->addContent(machineUserData.strDescription);
6596 elmMachine.setAttribute("OSType", machineUserData.strOsType);
6597 if ( strStateFile.length()
6598 && !(fl & BuildMachineXML_SuppressSavedState)
6599 )
6600 elmMachine.setAttributePath("stateFile", strStateFile);
6601
6602 if ((fl & BuildMachineXML_IncludeSnapshots)
6603 && !uuidCurrentSnapshot.isZero()
6604 && uuidCurrentSnapshot.isValid())
6605 elmMachine.setAttribute("currentSnapshot", uuidCurrentSnapshot.toStringCurly());
6606
6607 if (machineUserData.strSnapshotFolder.length())
6608 elmMachine.setAttributePath("snapshotFolder", machineUserData.strSnapshotFolder);
6609 if (!fCurrentStateModified)
6610 elmMachine.setAttribute("currentStateModified", fCurrentStateModified);
6611 elmMachine.setAttribute("lastStateChange", stringifyTimestamp(timeLastStateChange));
6612 if (fAborted)
6613 elmMachine.setAttribute("aborted", fAborted);
6614 if (machineUserData.strVMPriority.length())
6615 elmMachine.setAttribute("processPriority", machineUserData.strVMPriority);
6616 // Please keep the icon last so that one doesn't have to check if there
6617 // is anything in the line after this very long attribute in the XML.
6618 if (machineUserData.ovIcon.size())
6619 {
6620 Utf8Str strIcon;
6621 toBase64(strIcon, machineUserData.ovIcon);
6622 elmMachine.setAttribute("icon", strIcon);
6623 }
6624 if ( m->sv >= SettingsVersion_v1_9
6625 && ( machineUserData.fTeleporterEnabled
6626 || machineUserData.uTeleporterPort
6627 || !machineUserData.strTeleporterAddress.isEmpty()
6628 || !machineUserData.strTeleporterPassword.isEmpty()
6629 )
6630 )
6631 {
6632 xml::ElementNode *pelmTeleporter = elmMachine.createChild("Teleporter");
6633 pelmTeleporter->setAttribute("enabled", machineUserData.fTeleporterEnabled);
6634 pelmTeleporter->setAttribute("port", machineUserData.uTeleporterPort);
6635 pelmTeleporter->setAttribute("address", machineUserData.strTeleporterAddress);
6636 pelmTeleporter->setAttribute("password", machineUserData.strTeleporterPassword);
6637 }
6638
6639 if ( m->sv >= SettingsVersion_v1_11
6640 && ( machineUserData.enmFaultToleranceState != FaultToleranceState_Inactive
6641 || machineUserData.uFaultTolerancePort
6642 || machineUserData.uFaultToleranceInterval
6643 || !machineUserData.strFaultToleranceAddress.isEmpty()
6644 )
6645 )
6646 {
6647 xml::ElementNode *pelmFaultTolerance = elmMachine.createChild("FaultTolerance");
6648 switch (machineUserData.enmFaultToleranceState)
6649 {
6650 case FaultToleranceState_Inactive:
6651 pelmFaultTolerance->setAttribute("state", "inactive");
6652 break;
6653 case FaultToleranceState_Master:
6654 pelmFaultTolerance->setAttribute("state", "master");
6655 break;
6656 case FaultToleranceState_Standby:
6657 pelmFaultTolerance->setAttribute("state", "standby");
6658 break;
6659 }
6660
6661 pelmFaultTolerance->setAttribute("port", machineUserData.uFaultTolerancePort);
6662 pelmFaultTolerance->setAttribute("address", machineUserData.strFaultToleranceAddress);
6663 pelmFaultTolerance->setAttribute("interval", machineUserData.uFaultToleranceInterval);
6664 pelmFaultTolerance->setAttribute("password", machineUserData.strFaultTolerancePassword);
6665 }
6666
6667 if ( (fl & BuildMachineXML_MediaRegistry)
6668 && (m->sv >= SettingsVersion_v1_11)
6669 )
6670 buildMediaRegistry(elmMachine, mediaRegistry);
6671
6672 buildExtraData(elmMachine, mapExtraDataItems);
6673
6674 if ( (fl & BuildMachineXML_IncludeSnapshots)
6675 && llFirstSnapshot.size())
6676 buildSnapshotXML(1, elmMachine, llFirstSnapshot.front());
6677
6678 buildHardwareXML(elmMachine, hardwareMachine, fl, pllElementsWithUuidAttributes);
6679 buildDebuggingXML(&elmMachine, &debugging);
6680 buildAutostartXML(&elmMachine, &autostart);
6681 buildGroupsXML(&elmMachine, &machineUserData.llGroups);
6682}
6683
6684/**
6685 * Returns true only if the given AudioDriverType is supported on
6686 * the current host platform. For example, this would return false
6687 * for AudioDriverType_DirectSound when compiled on a Linux host.
6688 * @param drv AudioDriverType_* enum to test.
6689 * @return true only if the current host supports that driver.
6690 */
6691/*static*/
6692bool MachineConfigFile::isAudioDriverAllowedOnThisHost(AudioDriverType_T drv)
6693{
6694 switch (drv)
6695 {
6696 case AudioDriverType_Null:
6697#ifdef RT_OS_WINDOWS
6698# ifdef VBOX_WITH_WINMM
6699 case AudioDriverType_WinMM:
6700# endif
6701 case AudioDriverType_DirectSound:
6702#endif /* RT_OS_WINDOWS */
6703#ifdef RT_OS_SOLARIS
6704 case AudioDriverType_SolAudio:
6705#endif
6706#ifdef RT_OS_LINUX
6707# ifdef VBOX_WITH_ALSA
6708 case AudioDriverType_ALSA:
6709# endif
6710# ifdef VBOX_WITH_PULSE
6711 case AudioDriverType_Pulse:
6712# endif
6713#endif /* RT_OS_LINUX */
6714#if defined (RT_OS_LINUX) || defined (RT_OS_FREEBSD) || defined(VBOX_WITH_SOLARIS_OSS)
6715 case AudioDriverType_OSS:
6716#endif
6717#ifdef RT_OS_FREEBSD
6718# ifdef VBOX_WITH_PULSE
6719 case AudioDriverType_Pulse:
6720# endif
6721#endif
6722#ifdef RT_OS_DARWIN
6723 case AudioDriverType_CoreAudio:
6724#endif
6725#ifdef RT_OS_OS2
6726 case AudioDriverType_MMPM:
6727#endif
6728 return true;
6729 }
6730
6731 return false;
6732}
6733
6734/**
6735 * Returns the AudioDriverType_* which should be used by default on this
6736 * host platform. On Linux, this will check at runtime whether PulseAudio
6737 * or ALSA are actually supported on the first call.
6738 * @return
6739 */
6740/*static*/
6741AudioDriverType_T MachineConfigFile::getHostDefaultAudioDriver()
6742{
6743#if defined(RT_OS_WINDOWS)
6744# ifdef VBOX_WITH_WINMM
6745 return AudioDriverType_WinMM;
6746# else /* VBOX_WITH_WINMM */
6747 return AudioDriverType_DirectSound;
6748# endif /* !VBOX_WITH_WINMM */
6749#elif defined(RT_OS_SOLARIS)
6750 return AudioDriverType_SolAudio;
6751#elif defined(RT_OS_LINUX)
6752 // on Linux, we need to check at runtime what's actually supported...
6753 static RTCLockMtx s_mtx;
6754 static AudioDriverType_T s_linuxDriver = -1;
6755 RTCLock lock(s_mtx);
6756 if (s_linuxDriver == (AudioDriverType_T)-1)
6757 {
6758# if defined(VBOX_WITH_PULSE)
6759 /* Check for the pulse library & that the pulse audio daemon is running. */
6760 if (RTProcIsRunningByName("pulseaudio") &&
6761 RTLdrIsLoadable("libpulse.so.0"))
6762 s_linuxDriver = AudioDriverType_Pulse;
6763 else
6764# endif /* VBOX_WITH_PULSE */
6765# if defined(VBOX_WITH_ALSA)
6766 /* Check if we can load the ALSA library */
6767 if (RTLdrIsLoadable("libasound.so.2"))
6768 s_linuxDriver = AudioDriverType_ALSA;
6769 else
6770# endif /* VBOX_WITH_ALSA */
6771 s_linuxDriver = AudioDriverType_OSS;
6772 }
6773 return s_linuxDriver;
6774// end elif defined(RT_OS_LINUX)
6775#elif defined(RT_OS_DARWIN)
6776 return AudioDriverType_CoreAudio;
6777#elif defined(RT_OS_OS2)
6778 return AudioDriverType_MMPM;
6779#elif defined(RT_OS_FREEBSD)
6780 return AudioDriverType_OSS;
6781#else
6782 return AudioDriverType_Null;
6783#endif
6784}
6785
6786/**
6787 * Called from write() before calling ConfigFileBase::createStubDocument().
6788 * This adjusts the settings version in m->sv if incompatible settings require
6789 * a settings bump, whereas otherwise we try to preserve the settings version
6790 * to avoid breaking compatibility with older versions.
6791 *
6792 * We do the checks in here in reverse order: newest first, oldest last, so
6793 * that we avoid unnecessary checks since some of these are expensive.
6794 */
6795void MachineConfigFile::bumpSettingsVersionIfNeeded()
6796{
6797 if (m->sv < SettingsVersion_v1_16)
6798 {
6799 // VirtualBox 5.1 adds a NVMe storage controller, paravirt debug
6800 // options, cpu profile, APIC settings (CPU capability and BIOS).
6801
6802 if ( hardwareMachine.strParavirtDebug.isNotEmpty()
6803 || (!hardwareMachine.strCpuProfile.equals("host") && hardwareMachine.strCpuProfile.isNotEmpty())
6804 || hardwareMachine.biosSettings.apicMode != APICMode_APIC
6805 || !hardwareMachine.fAPIC
6806 || hardwareMachine.fX2APIC)
6807 {
6808 m->sv = SettingsVersion_v1_16;
6809 return;
6810 }
6811
6812 for (StorageControllersList::const_iterator it = hardwareMachine.storage.llStorageControllers.begin();
6813 it != hardwareMachine.storage.llStorageControllers.end();
6814 ++it)
6815 {
6816 const StorageController &sctl = *it;
6817
6818 if (sctl.controllerType == StorageControllerType_NVMe)
6819 {
6820 m->sv = SettingsVersion_v1_16;
6821 return;
6822 }
6823 }
6824 }
6825
6826 if (m->sv < SettingsVersion_v1_15)
6827 {
6828 // VirtualBox 5.0 adds paravirt providers, explicit AHCI port hotplug
6829 // setting, USB storage controller, xHCI, serial port TCP backend
6830 // and VM process priority.
6831
6832 /*
6833 * Check simple configuration bits first, loopy stuff afterwards.
6834 */
6835 if ( hardwareMachine.paravirtProvider != ParavirtProvider_Legacy
6836 || hardwareMachine.uCpuIdPortabilityLevel != 0
6837 || machineUserData.strVMPriority.length())
6838 {
6839 m->sv = SettingsVersion_v1_15;
6840 return;
6841 }
6842
6843 /*
6844 * Check whether the hotpluggable flag of all storage devices differs
6845 * from the default for old settings.
6846 * AHCI ports are hotpluggable by default every other device is not.
6847 * Also check if there are USB storage controllers.
6848 */
6849 for (StorageControllersList::const_iterator it = hardwareMachine.storage.llStorageControllers.begin();
6850 it != hardwareMachine.storage.llStorageControllers.end();
6851 ++it)
6852 {
6853 const StorageController &sctl = *it;
6854
6855 if (sctl.controllerType == StorageControllerType_USB)
6856 {
6857 m->sv = SettingsVersion_v1_15;
6858 return;
6859 }
6860
6861 for (AttachedDevicesList::const_iterator it2 = sctl.llAttachedDevices.begin();
6862 it2 != sctl.llAttachedDevices.end();
6863 ++it2)
6864 {
6865 const AttachedDevice &att = *it2;
6866
6867 if ( ( att.fHotPluggable
6868 && sctl.controllerType != StorageControllerType_IntelAhci)
6869 || ( !att.fHotPluggable
6870 && sctl.controllerType == StorageControllerType_IntelAhci))
6871 {
6872 m->sv = SettingsVersion_v1_15;
6873 return;
6874 }
6875 }
6876 }
6877
6878 /*
6879 * Check if there is an xHCI (USB3) USB controller.
6880 */
6881 for (USBControllerList::const_iterator it = hardwareMachine.usbSettings.llUSBControllers.begin();
6882 it != hardwareMachine.usbSettings.llUSBControllers.end();
6883 ++it)
6884 {
6885 const USBController &ctrl = *it;
6886 if (ctrl.enmType == USBControllerType_XHCI)
6887 {
6888 m->sv = SettingsVersion_v1_15;
6889 return;
6890 }
6891 }
6892
6893 /*
6894 * Check if any serial port uses the TCP backend.
6895 */
6896 for (SerialPortsList::const_iterator it = hardwareMachine.llSerialPorts.begin();
6897 it != hardwareMachine.llSerialPorts.end();
6898 ++it)
6899 {
6900 const SerialPort &port = *it;
6901 if (port.portMode == PortMode_TCP)
6902 {
6903 m->sv = SettingsVersion_v1_15;
6904 return;
6905 }
6906 }
6907 }
6908
6909 if (m->sv < SettingsVersion_v1_14)
6910 {
6911 // VirtualBox 4.3 adds default frontend setting, graphics controller
6912 // setting, explicit long mode setting, video capturing and NAT networking.
6913 if ( !hardwareMachine.strDefaultFrontend.isEmpty()
6914 || hardwareMachine.graphicsControllerType != GraphicsControllerType_VBoxVGA
6915 || hardwareMachine.enmLongMode != Hardware::LongMode_Legacy
6916 || machineUserData.ovIcon.size() > 0
6917 || hardwareMachine.fVideoCaptureEnabled)
6918 {
6919 m->sv = SettingsVersion_v1_14;
6920 return;
6921 }
6922 NetworkAdaptersList::const_iterator netit;
6923 for (netit = hardwareMachine.llNetworkAdapters.begin();
6924 netit != hardwareMachine.llNetworkAdapters.end();
6925 ++netit)
6926 {
6927 if (netit->mode == NetworkAttachmentType_NATNetwork)
6928 {
6929 m->sv = SettingsVersion_v1_14;
6930 break;
6931 }
6932 }
6933 }
6934
6935 if (m->sv < SettingsVersion_v1_14)
6936 {
6937 unsigned cOhciCtrls = 0;
6938 unsigned cEhciCtrls = 0;
6939 bool fNonStdName = false;
6940
6941 for (USBControllerList::const_iterator it = hardwareMachine.usbSettings.llUSBControllers.begin();
6942 it != hardwareMachine.usbSettings.llUSBControllers.end();
6943 ++it)
6944 {
6945 const USBController &ctrl = *it;
6946
6947 switch (ctrl.enmType)
6948 {
6949 case USBControllerType_OHCI:
6950 cOhciCtrls++;
6951 if (ctrl.strName != "OHCI")
6952 fNonStdName = true;
6953 break;
6954 case USBControllerType_EHCI:
6955 cEhciCtrls++;
6956 if (ctrl.strName != "EHCI")
6957 fNonStdName = true;
6958 break;
6959 default:
6960 /* Anything unknown forces a bump. */
6961 fNonStdName = true;
6962 }
6963
6964 /* Skip checking other controllers if the settings bump is necessary. */
6965 if (cOhciCtrls > 1 || cEhciCtrls > 1 || fNonStdName)
6966 {
6967 m->sv = SettingsVersion_v1_14;
6968 break;
6969 }
6970 }
6971 }
6972
6973 if (m->sv < SettingsVersion_v1_13)
6974 {
6975 // VirtualBox 4.2 adds tracing, autostart, UUID in directory and groups.
6976 if ( !debugging.areDefaultSettings()
6977 || !autostart.areDefaultSettings()
6978 || machineUserData.fDirectoryIncludesUUID
6979 || machineUserData.llGroups.size() > 1
6980 || machineUserData.llGroups.front() != "/")
6981 m->sv = SettingsVersion_v1_13;
6982 }
6983
6984 if (m->sv < SettingsVersion_v1_13)
6985 {
6986 // VirtualBox 4.2 changes the units for bandwidth group limits.
6987 for (BandwidthGroupList::const_iterator it = hardwareMachine.ioSettings.llBandwidthGroups.begin();
6988 it != hardwareMachine.ioSettings.llBandwidthGroups.end();
6989 ++it)
6990 {
6991 const BandwidthGroup &gr = *it;
6992 if (gr.cMaxBytesPerSec % _1M)
6993 {
6994 // Bump version if a limit cannot be expressed in megabytes
6995 m->sv = SettingsVersion_v1_13;
6996 break;
6997 }
6998 }
6999 }
7000
7001 if (m->sv < SettingsVersion_v1_12)
7002 {
7003 // VirtualBox 4.1 adds PCI passthrough and emulated USB Smart Card reader
7004 if ( hardwareMachine.pciAttachments.size()
7005 || hardwareMachine.fEmulatedUSBCardReader)
7006 m->sv = SettingsVersion_v1_12;
7007 }
7008
7009 if (m->sv < SettingsVersion_v1_12)
7010 {
7011 // VirtualBox 4.1 adds a promiscuous mode policy to the network
7012 // adapters and a generic network driver transport.
7013 NetworkAdaptersList::const_iterator netit;
7014 for (netit = hardwareMachine.llNetworkAdapters.begin();
7015 netit != hardwareMachine.llNetworkAdapters.end();
7016 ++netit)
7017 {
7018 if ( netit->enmPromiscModePolicy != NetworkAdapterPromiscModePolicy_Deny
7019 || netit->mode == NetworkAttachmentType_Generic
7020 || !netit->areGenericDriverDefaultSettings()
7021 )
7022 {
7023 m->sv = SettingsVersion_v1_12;
7024 break;
7025 }
7026 }
7027 }
7028
7029 if (m->sv < SettingsVersion_v1_11)
7030 {
7031 // VirtualBox 4.0 adds HD audio, CPU priorities, fault tolerance,
7032 // per-machine media registries, VRDE, JRockitVE, bandwidth groups,
7033 // ICH9 chipset
7034 if ( hardwareMachine.audioAdapter.controllerType == AudioControllerType_HDA
7035 || hardwareMachine.ulCpuExecutionCap != 100
7036 || machineUserData.enmFaultToleranceState != FaultToleranceState_Inactive
7037 || machineUserData.uFaultTolerancePort
7038 || machineUserData.uFaultToleranceInterval
7039 || !machineUserData.strFaultToleranceAddress.isEmpty()
7040 || mediaRegistry.llHardDisks.size()
7041 || mediaRegistry.llDvdImages.size()
7042 || mediaRegistry.llFloppyImages.size()
7043 || !hardwareMachine.vrdeSettings.strVrdeExtPack.isEmpty()
7044 || !hardwareMachine.vrdeSettings.strAuthLibrary.isEmpty()
7045 || machineUserData.strOsType == "JRockitVE"
7046 || hardwareMachine.ioSettings.llBandwidthGroups.size()
7047 || hardwareMachine.chipsetType == ChipsetType_ICH9
7048 )
7049 m->sv = SettingsVersion_v1_11;
7050 }
7051
7052 if (m->sv < SettingsVersion_v1_10)
7053 {
7054 /* If the properties contain elements other than "TCP/Ports" and "TCP/Address",
7055 * then increase the version to at least VBox 3.2, which can have video channel properties.
7056 */
7057 unsigned cOldProperties = 0;
7058
7059 StringsMap::const_iterator it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Ports");
7060 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
7061 cOldProperties++;
7062 it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Address");
7063 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
7064 cOldProperties++;
7065
7066 if (hardwareMachine.vrdeSettings.mapProperties.size() != cOldProperties)
7067 m->sv = SettingsVersion_v1_10;
7068 }
7069
7070 if (m->sv < SettingsVersion_v1_11)
7071 {
7072 /* If the properties contain elements other than "TCP/Ports", "TCP/Address",
7073 * "VideoChannel/Enabled" and "VideoChannel/Quality" then increase the version to VBox 4.0.
7074 */
7075 unsigned cOldProperties = 0;
7076
7077 StringsMap::const_iterator it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Ports");
7078 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
7079 cOldProperties++;
7080 it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Address");
7081 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
7082 cOldProperties++;
7083 it = hardwareMachine.vrdeSettings.mapProperties.find("VideoChannel/Enabled");
7084 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
7085 cOldProperties++;
7086 it = hardwareMachine.vrdeSettings.mapProperties.find("VideoChannel/Quality");
7087 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
7088 cOldProperties++;
7089
7090 if (hardwareMachine.vrdeSettings.mapProperties.size() != cOldProperties)
7091 m->sv = SettingsVersion_v1_11;
7092 }
7093
7094 // settings version 1.9 is required if there is not exactly one DVD
7095 // or more than one floppy drive present or the DVD is not at the secondary
7096 // master; this check is a bit more complicated
7097 //
7098 // settings version 1.10 is required if the host cache should be disabled
7099 //
7100 // settings version 1.11 is required for bandwidth limits and if more than
7101 // one controller of each type is present.
7102 if (m->sv < SettingsVersion_v1_11)
7103 {
7104 // count attached DVDs and floppies (only if < v1.9)
7105 size_t cDVDs = 0;
7106 size_t cFloppies = 0;
7107
7108 // count storage controllers (if < v1.11)
7109 size_t cSata = 0;
7110 size_t cScsiLsi = 0;
7111 size_t cScsiBuslogic = 0;
7112 size_t cSas = 0;
7113 size_t cIde = 0;
7114 size_t cFloppy = 0;
7115
7116 // need to run thru all the storage controllers and attached devices to figure this out
7117 for (StorageControllersList::const_iterator it = hardwareMachine.storage.llStorageControllers.begin();
7118 it != hardwareMachine.storage.llStorageControllers.end();
7119 ++it)
7120 {
7121 const StorageController &sctl = *it;
7122
7123 // count storage controllers of each type; 1.11 is required if more than one
7124 // controller of one type is present
7125 switch (sctl.storageBus)
7126 {
7127 case StorageBus_IDE:
7128 cIde++;
7129 break;
7130 case StorageBus_SATA:
7131 cSata++;
7132 break;
7133 case StorageBus_SAS:
7134 cSas++;
7135 break;
7136 case StorageBus_SCSI:
7137 if (sctl.controllerType == StorageControllerType_LsiLogic)
7138 cScsiLsi++;
7139 else
7140 cScsiBuslogic++;
7141 break;
7142 case StorageBus_Floppy:
7143 cFloppy++;
7144 break;
7145 default:
7146 // Do nothing
7147 break;
7148 }
7149
7150 if ( cSata > 1
7151 || cScsiLsi > 1
7152 || cScsiBuslogic > 1
7153 || cSas > 1
7154 || cIde > 1
7155 || cFloppy > 1)
7156 {
7157 m->sv = SettingsVersion_v1_11;
7158 break; // abort the loop -- we will not raise the version further
7159 }
7160
7161 for (AttachedDevicesList::const_iterator it2 = sctl.llAttachedDevices.begin();
7162 it2 != sctl.llAttachedDevices.end();
7163 ++it2)
7164 {
7165 const AttachedDevice &att = *it2;
7166
7167 // Bandwidth limitations are new in VirtualBox 4.0 (1.11)
7168 if (m->sv < SettingsVersion_v1_11)
7169 {
7170 if (att.strBwGroup.length() != 0)
7171 {
7172 m->sv = SettingsVersion_v1_11;
7173 break; // abort the loop -- we will not raise the version further
7174 }
7175 }
7176
7177 // disabling the host IO cache requires settings version 1.10
7178 if ( (m->sv < SettingsVersion_v1_10)
7179 && (!sctl.fUseHostIOCache)
7180 )
7181 m->sv = SettingsVersion_v1_10;
7182
7183 // we can only write the StorageController/@Instance attribute with v1.9
7184 if ( (m->sv < SettingsVersion_v1_9)
7185 && (sctl.ulInstance != 0)
7186 )
7187 m->sv = SettingsVersion_v1_9;
7188
7189 if (m->sv < SettingsVersion_v1_9)
7190 {
7191 if (att.deviceType == DeviceType_DVD)
7192 {
7193 if ( (sctl.storageBus != StorageBus_IDE) // DVD at bus other than DVD?
7194 || (att.lPort != 1) // DVDs not at secondary master?
7195 || (att.lDevice != 0)
7196 )
7197 m->sv = SettingsVersion_v1_9;
7198
7199 ++cDVDs;
7200 }
7201 else if (att.deviceType == DeviceType_Floppy)
7202 ++cFloppies;
7203 }
7204 }
7205
7206 if (m->sv >= SettingsVersion_v1_11)
7207 break; // abort the loop -- we will not raise the version further
7208 }
7209
7210 // VirtualBox before 3.1 had zero or one floppy and exactly one DVD,
7211 // so any deviation from that will require settings version 1.9
7212 if ( (m->sv < SettingsVersion_v1_9)
7213 && ( (cDVDs != 1)
7214 || (cFloppies > 1)
7215 )
7216 )
7217 m->sv = SettingsVersion_v1_9;
7218 }
7219
7220 // VirtualBox 3.2: Check for non default I/O settings
7221 if (m->sv < SettingsVersion_v1_10)
7222 {
7223 if ( (hardwareMachine.ioSettings.fIOCacheEnabled != true)
7224 || (hardwareMachine.ioSettings.ulIOCacheSize != 5)
7225 // and page fusion
7226 || (hardwareMachine.fPageFusionEnabled)
7227 // and CPU hotplug, RTC timezone control, HID type and HPET
7228 || machineUserData.fRTCUseUTC
7229 || hardwareMachine.fCpuHotPlug
7230 || hardwareMachine.pointingHIDType != PointingHIDType_PS2Mouse
7231 || hardwareMachine.keyboardHIDType != KeyboardHIDType_PS2Keyboard
7232 || hardwareMachine.fHPETEnabled
7233 )
7234 m->sv = SettingsVersion_v1_10;
7235 }
7236
7237 // VirtualBox 3.2 adds NAT and boot priority to the NIC config in Main
7238 // VirtualBox 4.0 adds network bandwitdth
7239 if (m->sv < SettingsVersion_v1_11)
7240 {
7241 NetworkAdaptersList::const_iterator netit;
7242 for (netit = hardwareMachine.llNetworkAdapters.begin();
7243 netit != hardwareMachine.llNetworkAdapters.end();
7244 ++netit)
7245 {
7246 if ( (m->sv < SettingsVersion_v1_12)
7247 && (netit->strBandwidthGroup.isNotEmpty())
7248 )
7249 {
7250 /* New in VirtualBox 4.1 */
7251 m->sv = SettingsVersion_v1_12;
7252 break;
7253 }
7254 else if ( (m->sv < SettingsVersion_v1_10)
7255 && (netit->fEnabled)
7256 && (netit->mode == NetworkAttachmentType_NAT)
7257 && ( netit->nat.u32Mtu != 0
7258 || netit->nat.u32SockRcv != 0
7259 || netit->nat.u32SockSnd != 0
7260 || netit->nat.u32TcpRcv != 0
7261 || netit->nat.u32TcpSnd != 0
7262 || !netit->nat.fDNSPassDomain
7263 || netit->nat.fDNSProxy
7264 || netit->nat.fDNSUseHostResolver
7265 || netit->nat.fAliasLog
7266 || netit->nat.fAliasProxyOnly
7267 || netit->nat.fAliasUseSamePorts
7268 || netit->nat.strTFTPPrefix.length()
7269 || netit->nat.strTFTPBootFile.length()
7270 || netit->nat.strTFTPNextServer.length()
7271 || netit->nat.mapRules.size()
7272 )
7273 )
7274 {
7275 m->sv = SettingsVersion_v1_10;
7276 // no break because we still might need v1.11 above
7277 }
7278 else if ( (m->sv < SettingsVersion_v1_10)
7279 && (netit->fEnabled)
7280 && (netit->ulBootPriority != 0)
7281 )
7282 {
7283 m->sv = SettingsVersion_v1_10;
7284 // no break because we still might need v1.11 above
7285 }
7286 }
7287 }
7288
7289 // all the following require settings version 1.9
7290 if ( (m->sv < SettingsVersion_v1_9)
7291 && ( (hardwareMachine.firmwareType >= FirmwareType_EFI)
7292 || machineUserData.fTeleporterEnabled
7293 || machineUserData.uTeleporterPort
7294 || !machineUserData.strTeleporterAddress.isEmpty()
7295 || !machineUserData.strTeleporterPassword.isEmpty()
7296 || (!hardwareMachine.uuid.isZero() && hardwareMachine.uuid.isValid())
7297 )
7298 )
7299 m->sv = SettingsVersion_v1_9;
7300
7301 // "accelerate 2d video" requires settings version 1.8
7302 if ( (m->sv < SettingsVersion_v1_8)
7303 && (hardwareMachine.fAccelerate2DVideo)
7304 )
7305 m->sv = SettingsVersion_v1_8;
7306
7307 // The hardware versions other than "1" requires settings version 1.4 (2.1+).
7308 if ( m->sv < SettingsVersion_v1_4
7309 && hardwareMachine.strVersion != "1"
7310 )
7311 m->sv = SettingsVersion_v1_4;
7312}
7313
7314/**
7315 * Called from Main code to write a machine config file to disk. This builds a DOM tree from
7316 * the member variables and then writes the XML file; it throws xml::Error instances on errors,
7317 * in particular if the file cannot be written.
7318 */
7319void MachineConfigFile::write(const com::Utf8Str &strFilename)
7320{
7321 try
7322 {
7323 // createStubDocument() sets the settings version to at least 1.7; however,
7324 // we might need to enfore a later settings version if incompatible settings
7325 // are present:
7326 bumpSettingsVersionIfNeeded();
7327
7328 m->strFilename = strFilename;
7329 createStubDocument();
7330
7331 xml::ElementNode *pelmMachine = m->pelmRoot->createChild("Machine");
7332 buildMachineXML(*pelmMachine,
7333 MachineConfigFile::BuildMachineXML_IncludeSnapshots
7334 | MachineConfigFile::BuildMachineXML_MediaRegistry,
7335 // but not BuildMachineXML_WriteVBoxVersionAttribute
7336 NULL); /* pllElementsWithUuidAttributes */
7337
7338 // now go write the XML
7339 xml::XmlFileWriter writer(*m->pDoc);
7340 writer.write(m->strFilename.c_str(), true /*fSafe*/);
7341
7342 m->fFileExists = true;
7343 clearDocument();
7344 }
7345 catch (...)
7346 {
7347 clearDocument();
7348 throw;
7349 }
7350}
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