VirtualBox

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

Last change on this file since 61015 was 61011, checked in by vboxsync, 9 years ago

Main/xml/Settings.cpp: clear string before getting icon override data (otherwise keeps previous content) and handle base64 encoding errors better

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