VirtualBox

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

Last change on this file since 40418 was 40418, checked in by vboxsync, 13 years ago

Main: Extended IMachine and the settings XML with three tracing related properties.

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