VirtualBox

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

Last change on this file since 57216 was 57216, checked in by vboxsync, 10 years ago

pr7972. OVF: fixed VBox version to correctly support new features during OVF export and import.

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