VirtualBox

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

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

NetShaper,E1000: Basic framework and partial implementation for network shaper

  • 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 40652 2012-03-26 16:36:16Z 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 && (strBandwidthGroup == n.strBandwidthGroup)
1502 )
1503 );
1504}
1505
1506/**
1507 * Comparison operator. This gets called from MachineConfigFile::operator==,
1508 * which in turn gets called from Machine::saveSettings to figure out whether
1509 * machine settings have really changed and thus need to be written out to disk.
1510 */
1511bool SerialPort::operator==(const SerialPort &s) const
1512{
1513 return ( (this == &s)
1514 || ( (ulSlot == s.ulSlot)
1515 && (fEnabled == s.fEnabled)
1516 && (ulIOBase == s.ulIOBase)
1517 && (ulIRQ == s.ulIRQ)
1518 && (portMode == s.portMode)
1519 && (strPath == s.strPath)
1520 && (fServer == s.fServer)
1521 )
1522 );
1523}
1524
1525/**
1526 * Comparison operator. This gets called from MachineConfigFile::operator==,
1527 * which in turn gets called from Machine::saveSettings to figure out whether
1528 * machine settings have really changed and thus need to be written out to disk.
1529 */
1530bool ParallelPort::operator==(const ParallelPort &s) const
1531{
1532 return ( (this == &s)
1533 || ( (ulSlot == s.ulSlot)
1534 && (fEnabled == s.fEnabled)
1535 && (ulIOBase == s.ulIOBase)
1536 && (ulIRQ == s.ulIRQ)
1537 && (strPath == s.strPath)
1538 )
1539 );
1540}
1541
1542/**
1543 * Comparison operator. This gets called from MachineConfigFile::operator==,
1544 * which in turn gets called from Machine::saveSettings to figure out whether
1545 * machine settings have really changed and thus need to be written out to disk.
1546 */
1547bool SharedFolder::operator==(const SharedFolder &g) const
1548{
1549 return ( (this == &g)
1550 || ( (strName == g.strName)
1551 && (strHostPath == g.strHostPath)
1552 && (fWritable == g.fWritable)
1553 && (fAutoMount == g.fAutoMount)
1554 )
1555 );
1556}
1557
1558/**
1559 * Comparison operator. This gets called from MachineConfigFile::operator==,
1560 * which in turn gets called from Machine::saveSettings to figure out whether
1561 * machine settings have really changed and thus need to be written out to disk.
1562 */
1563bool GuestProperty::operator==(const GuestProperty &g) const
1564{
1565 return ( (this == &g)
1566 || ( (strName == g.strName)
1567 && (strValue == g.strValue)
1568 && (timestamp == g.timestamp)
1569 && (strFlags == g.strFlags)
1570 )
1571 );
1572}
1573
1574// use a define for the platform-dependent default value of
1575// hwvirt exclusivity, since we'll need to check that value
1576// in bumpSettingsVersionIfNeeded()
1577#if defined(RT_OS_DARWIN) || defined(RT_OS_WINDOWS)
1578 #define HWVIRTEXCLUSIVEDEFAULT false
1579#else
1580 #define HWVIRTEXCLUSIVEDEFAULT true
1581#endif
1582
1583/**
1584 * Hardware struct constructor.
1585 */
1586Hardware::Hardware()
1587 : strVersion("1"),
1588 fHardwareVirt(true),
1589 fHardwareVirtExclusive(HWVIRTEXCLUSIVEDEFAULT),
1590 fNestedPaging(true),
1591 fVPID(true),
1592 fHardwareVirtForce(false),
1593 fSyntheticCpu(false),
1594 fPAE(false),
1595 cCPUs(1),
1596 fCpuHotPlug(false),
1597 fHpetEnabled(false),
1598 ulCpuExecutionCap(100),
1599 ulMemorySizeMB((uint32_t)-1),
1600 ulVRAMSizeMB(8),
1601 cMonitors(1),
1602 fAccelerate3D(false),
1603 fAccelerate2DVideo(false),
1604 firmwareType(FirmwareType_BIOS),
1605 pointingHidType(PointingHidType_PS2Mouse),
1606 keyboardHidType(KeyboardHidType_PS2Keyboard),
1607 chipsetType(ChipsetType_PIIX3),
1608 clipboardMode(ClipboardMode_Bidirectional),
1609 ulMemoryBalloonSize(0),
1610 fPageFusionEnabled(false)
1611{
1612 mapBootOrder[0] = DeviceType_Floppy;
1613 mapBootOrder[1] = DeviceType_DVD;
1614 mapBootOrder[2] = DeviceType_HardDisk;
1615
1616 /* The default value for PAE depends on the host:
1617 * - 64 bits host -> always true
1618 * - 32 bits host -> true for Windows & Darwin (masked off if the host cpu doesn't support it anyway)
1619 */
1620#if HC_ARCH_BITS == 64 || defined(RT_OS_WINDOWS) || defined(RT_OS_DARWIN)
1621 fPAE = true;
1622#endif
1623
1624 /* The default value of large page supports depends on the host:
1625 * - 64 bits host -> true, unless it's Linux (pending further prediction work due to excessively expensive large page allocations)
1626 * - 32 bits host -> false
1627 */
1628#if HC_ARCH_BITS == 64 && !defined(RT_OS_LINUX)
1629 fLargePages = true;
1630#else
1631 /* Not supported on 32 bits hosts. */
1632 fLargePages = false;
1633#endif
1634}
1635
1636/**
1637 * Comparison operator. This gets called from MachineConfigFile::operator==,
1638 * which in turn gets called from Machine::saveSettings to figure out whether
1639 * machine settings have really changed and thus need to be written out to disk.
1640 */
1641bool Hardware::operator==(const Hardware& h) const
1642{
1643 return ( (this == &h)
1644 || ( (strVersion == h.strVersion)
1645 && (uuid == h.uuid)
1646 && (fHardwareVirt == h.fHardwareVirt)
1647 && (fHardwareVirtExclusive == h.fHardwareVirtExclusive)
1648 && (fNestedPaging == h.fNestedPaging)
1649 && (fLargePages == h.fLargePages)
1650 && (fVPID == h.fVPID)
1651 && (fHardwareVirtForce == h.fHardwareVirtForce)
1652 && (fSyntheticCpu == h.fSyntheticCpu)
1653 && (fPAE == h.fPAE)
1654 && (cCPUs == h.cCPUs)
1655 && (fCpuHotPlug == h.fCpuHotPlug)
1656 && (ulCpuExecutionCap == h.ulCpuExecutionCap)
1657 && (fHpetEnabled == h.fHpetEnabled)
1658 && (llCpus == h.llCpus)
1659 && (llCpuIdLeafs == h.llCpuIdLeafs)
1660 && (ulMemorySizeMB == h.ulMemorySizeMB)
1661 && (mapBootOrder == h.mapBootOrder)
1662 && (ulVRAMSizeMB == h.ulVRAMSizeMB)
1663 && (cMonitors == h.cMonitors)
1664 && (fAccelerate3D == h.fAccelerate3D)
1665 && (fAccelerate2DVideo == h.fAccelerate2DVideo)
1666 && (firmwareType == h.firmwareType)
1667 && (pointingHidType == h.pointingHidType)
1668 && (keyboardHidType == h.keyboardHidType)
1669 && (chipsetType == h.chipsetType)
1670 && (vrdeSettings == h.vrdeSettings)
1671 && (biosSettings == h.biosSettings)
1672 && (usbController == h.usbController)
1673 && (llNetworkAdapters == h.llNetworkAdapters)
1674 && (llSerialPorts == h.llSerialPorts)
1675 && (llParallelPorts == h.llParallelPorts)
1676 && (audioAdapter == h.audioAdapter)
1677 && (llSharedFolders == h.llSharedFolders)
1678 && (clipboardMode == h.clipboardMode)
1679 && (ulMemoryBalloonSize == h.ulMemoryBalloonSize)
1680 && (fPageFusionEnabled == h.fPageFusionEnabled)
1681 && (llGuestProperties == h.llGuestProperties)
1682 && (strNotificationPatterns == h.strNotificationPatterns)
1683 && (ioSettings == h.ioSettings)
1684 && (pciAttachments == h.pciAttachments)
1685 )
1686 );
1687}
1688
1689/**
1690 * Comparison operator. This gets called from MachineConfigFile::operator==,
1691 * which in turn gets called from Machine::saveSettings to figure out whether
1692 * machine settings have really changed and thus need to be written out to disk.
1693 */
1694bool AttachedDevice::operator==(const AttachedDevice &a) const
1695{
1696 return ( (this == &a)
1697 || ( (deviceType == a.deviceType)
1698 && (fPassThrough == a.fPassThrough)
1699 && (fTempEject == a.fTempEject)
1700 && (fNonRotational == a.fNonRotational)
1701 && (fDiscard == a.fDiscard)
1702 && (lPort == a.lPort)
1703 && (lDevice == a.lDevice)
1704 && (uuid == a.uuid)
1705 && (strHostDriveSrc == a.strHostDriveSrc)
1706 && (strBwGroup == a.strBwGroup)
1707 )
1708 );
1709}
1710
1711/**
1712 * Comparison operator. This gets called from MachineConfigFile::operator==,
1713 * which in turn gets called from Machine::saveSettings to figure out whether
1714 * machine settings have really changed and thus need to be written out to disk.
1715 */
1716bool StorageController::operator==(const StorageController &s) const
1717{
1718 return ( (this == &s)
1719 || ( (strName == s.strName)
1720 && (storageBus == s.storageBus)
1721 && (controllerType == s.controllerType)
1722 && (ulPortCount == s.ulPortCount)
1723 && (ulInstance == s.ulInstance)
1724 && (fUseHostIOCache == s.fUseHostIOCache)
1725 && (lIDE0MasterEmulationPort == s.lIDE0MasterEmulationPort)
1726 && (lIDE0SlaveEmulationPort == s.lIDE0SlaveEmulationPort)
1727 && (lIDE1MasterEmulationPort == s.lIDE1MasterEmulationPort)
1728 && (lIDE1SlaveEmulationPort == s.lIDE1SlaveEmulationPort)
1729 && (llAttachedDevices == s.llAttachedDevices)
1730 )
1731 );
1732}
1733
1734/**
1735 * Comparison operator. This gets called from MachineConfigFile::operator==,
1736 * which in turn gets called from Machine::saveSettings to figure out whether
1737 * machine settings have really changed and thus need to be written out to disk.
1738 */
1739bool Storage::operator==(const Storage &s) const
1740{
1741 return ( (this == &s)
1742 || (llStorageControllers == s.llStorageControllers) // deep compare
1743 );
1744}
1745
1746/**
1747 * Comparison operator. This gets called from MachineConfigFile::operator==,
1748 * which in turn gets called from Machine::saveSettings to figure out whether
1749 * machine settings have really changed and thus need to be written out to disk.
1750 */
1751bool Snapshot::operator==(const Snapshot &s) const
1752{
1753 return ( (this == &s)
1754 || ( (uuid == s.uuid)
1755 && (strName == s.strName)
1756 && (strDescription == s.strDescription)
1757 && (RTTimeSpecIsEqual(&timestamp, &s.timestamp))
1758 && (strStateFile == s.strStateFile)
1759 && (hardware == s.hardware) // deep compare
1760 && (storage == s.storage) // deep compare
1761 && (llChildSnapshots == s.llChildSnapshots) // deep compare
1762 && debugging == s.debugging
1763 )
1764 );
1765}
1766
1767/**
1768 * IoSettings constructor.
1769 */
1770IoSettings::IoSettings()
1771{
1772 fIoCacheEnabled = true;
1773 ulIoCacheSize = 5;
1774}
1775
1776////////////////////////////////////////////////////////////////////////////////
1777//
1778// MachineConfigFile
1779//
1780////////////////////////////////////////////////////////////////////////////////
1781
1782/**
1783 * Constructor.
1784 *
1785 * If pstrFilename is != NULL, this reads the given settings file into the member
1786 * variables and various substructures and lists. Otherwise, the member variables
1787 * are initialized with default values.
1788 *
1789 * Throws variants of xml::Error for I/O, XML and logical content errors, which
1790 * the caller should catch; if this constructor does not throw, then the member
1791 * variables contain meaningful values (either from the file or defaults).
1792 *
1793 * @param strFilename
1794 */
1795MachineConfigFile::MachineConfigFile(const Utf8Str *pstrFilename)
1796 : ConfigFileBase(pstrFilename),
1797 fCurrentStateModified(true),
1798 fAborted(false)
1799{
1800 RTTimeNow(&timeLastStateChange);
1801
1802 if (pstrFilename)
1803 {
1804 // the ConfigFileBase constructor has loaded the XML file, so now
1805 // we need only analyze what is in there
1806
1807 xml::NodesLoop nlRootChildren(*m->pelmRoot);
1808 const xml::ElementNode *pelmRootChild;
1809 while ((pelmRootChild = nlRootChildren.forAllNodes()))
1810 {
1811 if (pelmRootChild->nameEquals("Machine"))
1812 readMachine(*pelmRootChild);
1813 }
1814
1815 // clean up memory allocated by XML engine
1816 clearDocument();
1817 }
1818}
1819
1820/**
1821 * Public routine which returns true if this machine config file can have its
1822 * own media registry (which is true for settings version v1.11 and higher,
1823 * i.e. files created by VirtualBox 4.0 and higher).
1824 * @return
1825 */
1826bool MachineConfigFile::canHaveOwnMediaRegistry() const
1827{
1828 return (m->sv >= SettingsVersion_v1_11);
1829}
1830
1831/**
1832 * Public routine which allows for importing machine XML from an external DOM tree.
1833 * Use this after having called the constructor with a NULL argument.
1834 *
1835 * This is used by the OVF code if a <vbox:Machine> element has been encountered
1836 * in an OVF VirtualSystem element.
1837 *
1838 * @param elmMachine
1839 */
1840void MachineConfigFile::importMachineXML(const xml::ElementNode &elmMachine)
1841{
1842 readMachine(elmMachine);
1843}
1844
1845/**
1846 * Comparison operator. This gets called from Machine::saveSettings to figure out
1847 * whether machine settings have really changed and thus need to be written out to disk.
1848 *
1849 * Even though this is called operator==, this does NOT compare all fields; the "equals"
1850 * should be understood as "has the same machine config as". The following fields are
1851 * NOT compared:
1852 * -- settings versions and file names inherited from ConfigFileBase;
1853 * -- fCurrentStateModified because that is considered separately in Machine::saveSettings!!
1854 *
1855 * The "deep" comparisons marked below will invoke the operator== functions of the
1856 * structs defined in this file, which may in turn go into comparing lists of
1857 * other structures. As a result, invoking this can be expensive, but it's
1858 * less expensive than writing out XML to disk.
1859 */
1860bool MachineConfigFile::operator==(const MachineConfigFile &c) const
1861{
1862 return ( (this == &c)
1863 || ( (uuid == c.uuid)
1864 && (machineUserData == c.machineUserData)
1865 && (strStateFile == c.strStateFile)
1866 && (uuidCurrentSnapshot == c.uuidCurrentSnapshot)
1867 // skip fCurrentStateModified!
1868 && (RTTimeSpecIsEqual(&timeLastStateChange, &c.timeLastStateChange))
1869 && (fAborted == c.fAborted)
1870 && (hardwareMachine == c.hardwareMachine) // this one's deep
1871 && (storageMachine == c.storageMachine) // this one's deep
1872 && (mediaRegistry == c.mediaRegistry) // this one's deep
1873 && (mapExtraDataItems == c.mapExtraDataItems) // this one's deep
1874 && (llFirstSnapshot == c.llFirstSnapshot) // this one's deep
1875 )
1876 );
1877}
1878
1879/**
1880 * Called from MachineConfigFile::readHardware() to read cpu information.
1881 * @param elmCpuid
1882 * @param ll
1883 */
1884void MachineConfigFile::readCpuTree(const xml::ElementNode &elmCpu,
1885 CpuList &ll)
1886{
1887 xml::NodesLoop nl1(elmCpu, "Cpu");
1888 const xml::ElementNode *pelmCpu;
1889 while ((pelmCpu = nl1.forAllNodes()))
1890 {
1891 Cpu cpu;
1892
1893 if (!pelmCpu->getAttributeValue("id", cpu.ulId))
1894 throw ConfigFileError(this, pelmCpu, N_("Required Cpu/@id attribute is missing"));
1895
1896 ll.push_back(cpu);
1897 }
1898}
1899
1900/**
1901 * Called from MachineConfigFile::readHardware() to cpuid information.
1902 * @param elmCpuid
1903 * @param ll
1904 */
1905void MachineConfigFile::readCpuIdTree(const xml::ElementNode &elmCpuid,
1906 CpuIdLeafsList &ll)
1907{
1908 xml::NodesLoop nl1(elmCpuid, "CpuIdLeaf");
1909 const xml::ElementNode *pelmCpuIdLeaf;
1910 while ((pelmCpuIdLeaf = nl1.forAllNodes()))
1911 {
1912 CpuIdLeaf leaf;
1913
1914 if (!pelmCpuIdLeaf->getAttributeValue("id", leaf.ulId))
1915 throw ConfigFileError(this, pelmCpuIdLeaf, N_("Required CpuId/@id attribute is missing"));
1916
1917 pelmCpuIdLeaf->getAttributeValue("eax", leaf.ulEax);
1918 pelmCpuIdLeaf->getAttributeValue("ebx", leaf.ulEbx);
1919 pelmCpuIdLeaf->getAttributeValue("ecx", leaf.ulEcx);
1920 pelmCpuIdLeaf->getAttributeValue("edx", leaf.ulEdx);
1921
1922 ll.push_back(leaf);
1923 }
1924}
1925
1926/**
1927 * Called from MachineConfigFile::readHardware() to network information.
1928 * @param elmNetwork
1929 * @param ll
1930 */
1931void MachineConfigFile::readNetworkAdapters(const xml::ElementNode &elmNetwork,
1932 NetworkAdaptersList &ll)
1933{
1934 xml::NodesLoop nl1(elmNetwork, "Adapter");
1935 const xml::ElementNode *pelmAdapter;
1936 while ((pelmAdapter = nl1.forAllNodes()))
1937 {
1938 NetworkAdapter nic;
1939
1940 if (!pelmAdapter->getAttributeValue("slot", nic.ulSlot))
1941 throw ConfigFileError(this, pelmAdapter, N_("Required Adapter/@slot attribute is missing"));
1942
1943 Utf8Str strTemp;
1944 if (pelmAdapter->getAttributeValue("type", strTemp))
1945 {
1946 if (strTemp == "Am79C970A")
1947 nic.type = NetworkAdapterType_Am79C970A;
1948 else if (strTemp == "Am79C973")
1949 nic.type = NetworkAdapterType_Am79C973;
1950 else if (strTemp == "82540EM")
1951 nic.type = NetworkAdapterType_I82540EM;
1952 else if (strTemp == "82543GC")
1953 nic.type = NetworkAdapterType_I82543GC;
1954 else if (strTemp == "82545EM")
1955 nic.type = NetworkAdapterType_I82545EM;
1956 else if (strTemp == "virtio")
1957 nic.type = NetworkAdapterType_Virtio;
1958 else
1959 throw ConfigFileError(this, pelmAdapter, N_("Invalid value '%s' in Adapter/@type attribute"), strTemp.c_str());
1960 }
1961
1962 pelmAdapter->getAttributeValue("enabled", nic.fEnabled);
1963 pelmAdapter->getAttributeValue("MACAddress", nic.strMACAddress);
1964 pelmAdapter->getAttributeValue("cable", nic.fCableConnected);
1965 pelmAdapter->getAttributeValue("speed", nic.ulLineSpeed);
1966
1967 if (pelmAdapter->getAttributeValue("promiscuousModePolicy", strTemp))
1968 {
1969 if (strTemp == "Deny")
1970 nic.enmPromiscModePolicy = NetworkAdapterPromiscModePolicy_Deny;
1971 else if (strTemp == "AllowNetwork")
1972 nic.enmPromiscModePolicy = NetworkAdapterPromiscModePolicy_AllowNetwork;
1973 else if (strTemp == "AllowAll")
1974 nic.enmPromiscModePolicy = NetworkAdapterPromiscModePolicy_AllowAll;
1975 else
1976 throw ConfigFileError(this, pelmAdapter,
1977 N_("Invalid value '%s' in Adapter/@promiscuousModePolicy attribute"), strTemp.c_str());
1978 }
1979
1980 pelmAdapter->getAttributeValue("trace", nic.fTraceEnabled);
1981 pelmAdapter->getAttributeValue("tracefile", nic.strTraceFile);
1982 pelmAdapter->getAttributeValue("bootPriority", nic.ulBootPriority);
1983 pelmAdapter->getAttributeValue("bandwidthGroup", nic.strBandwidthGroup);
1984
1985 xml::ElementNodesList llNetworkModes;
1986 pelmAdapter->getChildElements(llNetworkModes);
1987 xml::ElementNodesList::iterator it;
1988 /* We should have only active mode descriptor and disabled modes set */
1989 if (llNetworkModes.size() > 2)
1990 {
1991 throw ConfigFileError(this, pelmAdapter, N_("Invalid number of modes ('%d') attached to Adapter attribute"), llNetworkModes.size());
1992 }
1993 for (it = llNetworkModes.begin(); it != llNetworkModes.end(); ++it)
1994 {
1995 const xml::ElementNode *pelmNode = *it;
1996 if (pelmNode->nameEquals("DisabledModes"))
1997 {
1998 xml::ElementNodesList llDisabledNetworkModes;
1999 xml::ElementNodesList::iterator itDisabled;
2000 pelmNode->getChildElements(llDisabledNetworkModes);
2001 /* run over disabled list and load settings */
2002 for (itDisabled = llDisabledNetworkModes.begin();
2003 itDisabled != llDisabledNetworkModes.end(); ++itDisabled)
2004 {
2005 const xml::ElementNode *pelmDisabledNode = *itDisabled;
2006 readAttachedNetworkMode(*pelmDisabledNode, false, nic);
2007 }
2008 }
2009 else
2010 readAttachedNetworkMode(*pelmNode, true, nic);
2011 }
2012 // else: default is NetworkAttachmentType_Null
2013
2014 ll.push_back(nic);
2015 }
2016}
2017
2018void MachineConfigFile::readAttachedNetworkMode(const xml::ElementNode &elmMode, bool fEnabled, NetworkAdapter &nic)
2019{
2020 NetworkAttachmentType_T enmAttachmentType = NetworkAttachmentType_Null;
2021
2022 if (elmMode.nameEquals("NAT"))
2023 {
2024 enmAttachmentType = NetworkAttachmentType_NAT;
2025
2026 elmMode.getAttributeValue("network", nic.nat.strNetwork);
2027 elmMode.getAttributeValue("hostip", nic.nat.strBindIP);
2028 elmMode.getAttributeValue("mtu", nic.nat.u32Mtu);
2029 elmMode.getAttributeValue("sockrcv", nic.nat.u32SockRcv);
2030 elmMode.getAttributeValue("socksnd", nic.nat.u32SockSnd);
2031 elmMode.getAttributeValue("tcprcv", nic.nat.u32TcpRcv);
2032 elmMode.getAttributeValue("tcpsnd", nic.nat.u32TcpSnd);
2033 const xml::ElementNode *pelmDNS;
2034 if ((pelmDNS = elmMode.findChildElement("DNS")))
2035 {
2036 pelmDNS->getAttributeValue("pass-domain", nic.nat.fDnsPassDomain);
2037 pelmDNS->getAttributeValue("use-proxy", nic.nat.fDnsProxy);
2038 pelmDNS->getAttributeValue("use-host-resolver", nic.nat.fDnsUseHostResolver);
2039 }
2040 const xml::ElementNode *pelmAlias;
2041 if ((pelmAlias = elmMode.findChildElement("Alias")))
2042 {
2043 pelmAlias->getAttributeValue("logging", nic.nat.fAliasLog);
2044 pelmAlias->getAttributeValue("proxy-only", nic.nat.fAliasProxyOnly);
2045 pelmAlias->getAttributeValue("use-same-ports", nic.nat.fAliasUseSamePorts);
2046 }
2047 const xml::ElementNode *pelmTFTP;
2048 if ((pelmTFTP = elmMode.findChildElement("TFTP")))
2049 {
2050 pelmTFTP->getAttributeValue("prefix", nic.nat.strTftpPrefix);
2051 pelmTFTP->getAttributeValue("boot-file", nic.nat.strTftpBootFile);
2052 pelmTFTP->getAttributeValue("next-server", nic.nat.strTftpNextServer);
2053 }
2054 xml::ElementNodesList plstNatPF;
2055 elmMode.getChildElements(plstNatPF, "Forwarding");
2056 for (xml::ElementNodesList::iterator pf = plstNatPF.begin(); pf != plstNatPF.end(); ++pf)
2057 {
2058 NATRule rule;
2059 uint32_t port = 0;
2060 (*pf)->getAttributeValue("name", rule.strName);
2061 (*pf)->getAttributeValue("proto", (uint32_t&)rule.proto);
2062 (*pf)->getAttributeValue("hostip", rule.strHostIP);
2063 (*pf)->getAttributeValue("hostport", port);
2064 rule.u16HostPort = port;
2065 (*pf)->getAttributeValue("guestip", rule.strGuestIP);
2066 (*pf)->getAttributeValue("guestport", port);
2067 rule.u16GuestPort = port;
2068 nic.nat.llRules.push_back(rule);
2069 }
2070 }
2071 else if ( (elmMode.nameEquals("HostInterface"))
2072 || (elmMode.nameEquals("BridgedInterface")))
2073 {
2074 enmAttachmentType = NetworkAttachmentType_Bridged;
2075
2076 elmMode.getAttributeValue("name", nic.strBridgedName); // optional bridged interface name
2077 }
2078 else if (elmMode.nameEquals("InternalNetwork"))
2079 {
2080 enmAttachmentType = NetworkAttachmentType_Internal;
2081
2082 if (!elmMode.getAttributeValue("name", nic.strInternalNetworkName)) // required network name
2083 throw ConfigFileError(this, &elmMode, N_("Required InternalNetwork/@name element is missing"));
2084 }
2085 else if (elmMode.nameEquals("HostOnlyInterface"))
2086 {
2087 enmAttachmentType = NetworkAttachmentType_HostOnly;
2088
2089 if (!elmMode.getAttributeValue("name", nic.strHostOnlyName)) // required network name
2090 throw ConfigFileError(this, &elmMode, N_("Required HostOnlyInterface/@name element is missing"));
2091 }
2092 else if (elmMode.nameEquals("GenericInterface"))
2093 {
2094 enmAttachmentType = NetworkAttachmentType_Generic;
2095
2096 elmMode.getAttributeValue("driver", nic.strGenericDriver); // optional network attachment driver
2097
2098 // get all properties
2099 xml::NodesLoop nl(elmMode);
2100 const xml::ElementNode *pelmModeChild;
2101 while ((pelmModeChild = nl.forAllNodes()))
2102 {
2103 if (pelmModeChild->nameEquals("Property"))
2104 {
2105 Utf8Str strPropName, strPropValue;
2106 if ( (pelmModeChild->getAttributeValue("name", strPropName))
2107 && (pelmModeChild->getAttributeValue("value", strPropValue))
2108 )
2109 nic.genericProperties[strPropName] = strPropValue;
2110 else
2111 throw ConfigFileError(this, pelmModeChild, N_("Required GenericInterface/Property/@name or @value attribute is missing"));
2112 }
2113 }
2114 }
2115 else if (elmMode.nameEquals("VDE"))
2116 {
2117 enmAttachmentType = NetworkAttachmentType_Generic;
2118
2119 com::Utf8Str strVDEName;
2120 elmMode.getAttributeValue("network", strVDEName); // optional network name
2121 nic.strGenericDriver = "VDE";
2122 nic.genericProperties["network"] = strVDEName;
2123 }
2124
2125 if (fEnabled && enmAttachmentType != NetworkAttachmentType_Null)
2126 nic.mode = enmAttachmentType;
2127}
2128
2129/**
2130 * Called from MachineConfigFile::readHardware() to read serial port information.
2131 * @param elmUART
2132 * @param ll
2133 */
2134void MachineConfigFile::readSerialPorts(const xml::ElementNode &elmUART,
2135 SerialPortsList &ll)
2136{
2137 xml::NodesLoop nl1(elmUART, "Port");
2138 const xml::ElementNode *pelmPort;
2139 while ((pelmPort = nl1.forAllNodes()))
2140 {
2141 SerialPort port;
2142 if (!pelmPort->getAttributeValue("slot", port.ulSlot))
2143 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@slot attribute is missing"));
2144
2145 // slot must be unique
2146 for (SerialPortsList::const_iterator it = ll.begin();
2147 it != ll.end();
2148 ++it)
2149 if ((*it).ulSlot == port.ulSlot)
2150 throw ConfigFileError(this, pelmPort, N_("Invalid value %RU32 in UART/Port/@slot attribute: value is not unique"), port.ulSlot);
2151
2152 if (!pelmPort->getAttributeValue("enabled", port.fEnabled))
2153 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@enabled attribute is missing"));
2154 if (!pelmPort->getAttributeValue("IOBase", port.ulIOBase))
2155 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@IOBase attribute is missing"));
2156 if (!pelmPort->getAttributeValue("IRQ", port.ulIRQ))
2157 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@IRQ attribute is missing"));
2158
2159 Utf8Str strPortMode;
2160 if (!pelmPort->getAttributeValue("hostMode", strPortMode))
2161 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@hostMode attribute is missing"));
2162 if (strPortMode == "RawFile")
2163 port.portMode = PortMode_RawFile;
2164 else if (strPortMode == "HostPipe")
2165 port.portMode = PortMode_HostPipe;
2166 else if (strPortMode == "HostDevice")
2167 port.portMode = PortMode_HostDevice;
2168 else if (strPortMode == "Disconnected")
2169 port.portMode = PortMode_Disconnected;
2170 else
2171 throw ConfigFileError(this, pelmPort, N_("Invalid value '%s' in UART/Port/@hostMode attribute"), strPortMode.c_str());
2172
2173 pelmPort->getAttributeValue("path", port.strPath);
2174 pelmPort->getAttributeValue("server", port.fServer);
2175
2176 ll.push_back(port);
2177 }
2178}
2179
2180/**
2181 * Called from MachineConfigFile::readHardware() to read parallel port information.
2182 * @param elmLPT
2183 * @param ll
2184 */
2185void MachineConfigFile::readParallelPorts(const xml::ElementNode &elmLPT,
2186 ParallelPortsList &ll)
2187{
2188 xml::NodesLoop nl1(elmLPT, "Port");
2189 const xml::ElementNode *pelmPort;
2190 while ((pelmPort = nl1.forAllNodes()))
2191 {
2192 ParallelPort port;
2193 if (!pelmPort->getAttributeValue("slot", port.ulSlot))
2194 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@slot attribute is missing"));
2195
2196 // slot must be unique
2197 for (ParallelPortsList::const_iterator it = ll.begin();
2198 it != ll.end();
2199 ++it)
2200 if ((*it).ulSlot == port.ulSlot)
2201 throw ConfigFileError(this, pelmPort, N_("Invalid value %RU32 in LPT/Port/@slot attribute: value is not unique"), port.ulSlot);
2202
2203 if (!pelmPort->getAttributeValue("enabled", port.fEnabled))
2204 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@enabled attribute is missing"));
2205 if (!pelmPort->getAttributeValue("IOBase", port.ulIOBase))
2206 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@IOBase attribute is missing"));
2207 if (!pelmPort->getAttributeValue("IRQ", port.ulIRQ))
2208 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@IRQ attribute is missing"));
2209
2210 pelmPort->getAttributeValue("path", port.strPath);
2211
2212 ll.push_back(port);
2213 }
2214}
2215
2216/**
2217 * Called from MachineConfigFile::readHardware() to read audio adapter information
2218 * and maybe fix driver information depending on the current host hardware.
2219 *
2220 * @param elmAudioAdapter "AudioAdapter" XML element.
2221 * @param hw
2222 */
2223void MachineConfigFile::readAudioAdapter(const xml::ElementNode &elmAudioAdapter,
2224 AudioAdapter &aa)
2225{
2226 elmAudioAdapter.getAttributeValue("enabled", aa.fEnabled);
2227
2228 Utf8Str strTemp;
2229 if (elmAudioAdapter.getAttributeValue("controller", strTemp))
2230 {
2231 if (strTemp == "SB16")
2232 aa.controllerType = AudioControllerType_SB16;
2233 else if (strTemp == "AC97")
2234 aa.controllerType = AudioControllerType_AC97;
2235 else if (strTemp == "HDA")
2236 aa.controllerType = AudioControllerType_HDA;
2237 else
2238 throw ConfigFileError(this, &elmAudioAdapter, N_("Invalid value '%s' in AudioAdapter/@controller attribute"), strTemp.c_str());
2239 }
2240
2241 if (elmAudioAdapter.getAttributeValue("driver", strTemp))
2242 {
2243 // settings before 1.3 used lower case so make sure this is case-insensitive
2244 strTemp.toUpper();
2245 if (strTemp == "NULL")
2246 aa.driverType = AudioDriverType_Null;
2247 else if (strTemp == "WINMM")
2248 aa.driverType = AudioDriverType_WinMM;
2249 else if ( (strTemp == "DIRECTSOUND") || (strTemp == "DSOUND") )
2250 aa.driverType = AudioDriverType_DirectSound;
2251 else if (strTemp == "SOLAUDIO")
2252 aa.driverType = AudioDriverType_SolAudio;
2253 else if (strTemp == "ALSA")
2254 aa.driverType = AudioDriverType_ALSA;
2255 else if (strTemp == "PULSE")
2256 aa.driverType = AudioDriverType_Pulse;
2257 else if (strTemp == "OSS")
2258 aa.driverType = AudioDriverType_OSS;
2259 else if (strTemp == "COREAUDIO")
2260 aa.driverType = AudioDriverType_CoreAudio;
2261 else if (strTemp == "MMPM")
2262 aa.driverType = AudioDriverType_MMPM;
2263 else
2264 throw ConfigFileError(this, &elmAudioAdapter, N_("Invalid value '%s' in AudioAdapter/@driver attribute"), strTemp.c_str());
2265
2266 // now check if this is actually supported on the current host platform;
2267 // people might be opening a file created on a Windows host, and that
2268 // VM should still start on a Linux host
2269 if (!isAudioDriverAllowedOnThisHost(aa.driverType))
2270 aa.driverType = getHostDefaultAudioDriver();
2271 }
2272}
2273
2274/**
2275 * Called from MachineConfigFile::readHardware() to read guest property information.
2276 * @param elmGuestProperties
2277 * @param hw
2278 */
2279void MachineConfigFile::readGuestProperties(const xml::ElementNode &elmGuestProperties,
2280 Hardware &hw)
2281{
2282 xml::NodesLoop nl1(elmGuestProperties, "GuestProperty");
2283 const xml::ElementNode *pelmProp;
2284 while ((pelmProp = nl1.forAllNodes()))
2285 {
2286 GuestProperty prop;
2287 pelmProp->getAttributeValue("name", prop.strName);
2288 pelmProp->getAttributeValue("value", prop.strValue);
2289
2290 pelmProp->getAttributeValue("timestamp", prop.timestamp);
2291 pelmProp->getAttributeValue("flags", prop.strFlags);
2292 hw.llGuestProperties.push_back(prop);
2293 }
2294
2295 elmGuestProperties.getAttributeValue("notificationPatterns", hw.strNotificationPatterns);
2296}
2297
2298/**
2299 * Helper function to read attributes that are common to <SATAController> (pre-1.7)
2300 * and <StorageController>.
2301 * @param elmStorageController
2302 * @param strg
2303 */
2304void MachineConfigFile::readStorageControllerAttributes(const xml::ElementNode &elmStorageController,
2305 StorageController &sctl)
2306{
2307 elmStorageController.getAttributeValue("PortCount", sctl.ulPortCount);
2308 elmStorageController.getAttributeValue("IDE0MasterEmulationPort", sctl.lIDE0MasterEmulationPort);
2309 elmStorageController.getAttributeValue("IDE0SlaveEmulationPort", sctl.lIDE0SlaveEmulationPort);
2310 elmStorageController.getAttributeValue("IDE1MasterEmulationPort", sctl.lIDE1MasterEmulationPort);
2311 elmStorageController.getAttributeValue("IDE1SlaveEmulationPort", sctl.lIDE1SlaveEmulationPort);
2312
2313 elmStorageController.getAttributeValue("useHostIOCache", sctl.fUseHostIOCache);
2314}
2315
2316/**
2317 * Reads in a <Hardware> block and stores it in the given structure. Used
2318 * both directly from readMachine and from readSnapshot, since snapshots
2319 * have their own hardware sections.
2320 *
2321 * For legacy pre-1.7 settings we also need a storage structure because
2322 * the IDE and SATA controllers used to be defined under <Hardware>.
2323 *
2324 * @param elmHardware
2325 * @param hw
2326 */
2327void MachineConfigFile::readHardware(const xml::ElementNode &elmHardware,
2328 Hardware &hw,
2329 Storage &strg)
2330{
2331 if (!elmHardware.getAttributeValue("version", hw.strVersion))
2332 {
2333 /* KLUDGE ALERT! For a while during the 3.1 development this was not
2334 written because it was thought to have a default value of "2". For
2335 sv <= 1.3 it defaults to "1" because the attribute didn't exist,
2336 while for 1.4+ it is sort of mandatory. Now, the buggy XML writer
2337 code only wrote 1.7 and later. So, if it's a 1.7+ XML file and it's
2338 missing the hardware version, then it probably should be "2" instead
2339 of "1". */
2340 if (m->sv < SettingsVersion_v1_7)
2341 hw.strVersion = "1";
2342 else
2343 hw.strVersion = "2";
2344 }
2345 Utf8Str strUUID;
2346 if (elmHardware.getAttributeValue("uuid", strUUID))
2347 parseUUID(hw.uuid, strUUID);
2348
2349 xml::NodesLoop nl1(elmHardware);
2350 const xml::ElementNode *pelmHwChild;
2351 while ((pelmHwChild = nl1.forAllNodes()))
2352 {
2353 if (pelmHwChild->nameEquals("CPU"))
2354 {
2355 if (!pelmHwChild->getAttributeValue("count", hw.cCPUs))
2356 {
2357 // pre-1.5 variant; not sure if this actually exists in the wild anywhere
2358 const xml::ElementNode *pelmCPUChild;
2359 if ((pelmCPUChild = pelmHwChild->findChildElement("CPUCount")))
2360 pelmCPUChild->getAttributeValue("count", hw.cCPUs);
2361 }
2362
2363 pelmHwChild->getAttributeValue("hotplug", hw.fCpuHotPlug);
2364 pelmHwChild->getAttributeValue("executionCap", hw.ulCpuExecutionCap);
2365
2366 const xml::ElementNode *pelmCPUChild;
2367 if (hw.fCpuHotPlug)
2368 {
2369 if ((pelmCPUChild = pelmHwChild->findChildElement("CpuTree")))
2370 readCpuTree(*pelmCPUChild, hw.llCpus);
2371 }
2372
2373 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtEx")))
2374 {
2375 pelmCPUChild->getAttributeValue("enabled", hw.fHardwareVirt);
2376 pelmCPUChild->getAttributeValue("exclusive", hw.fHardwareVirtExclusive); // settings version 1.9
2377 }
2378 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExNestedPaging")))
2379 pelmCPUChild->getAttributeValue("enabled", hw.fNestedPaging);
2380 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExLargePages")))
2381 pelmCPUChild->getAttributeValue("enabled", hw.fLargePages);
2382 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExVPID")))
2383 pelmCPUChild->getAttributeValue("enabled", hw.fVPID);
2384 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtForce")))
2385 pelmCPUChild->getAttributeValue("enabled", hw.fHardwareVirtForce);
2386
2387 if (!(pelmCPUChild = pelmHwChild->findChildElement("PAE")))
2388 {
2389 /* The default for pre 3.1 was false, so we must respect that. */
2390 if (m->sv < SettingsVersion_v1_9)
2391 hw.fPAE = false;
2392 }
2393 else
2394 pelmCPUChild->getAttributeValue("enabled", hw.fPAE);
2395
2396 if ((pelmCPUChild = pelmHwChild->findChildElement("SyntheticCpu")))
2397 pelmCPUChild->getAttributeValue("enabled", hw.fSyntheticCpu);
2398 if ((pelmCPUChild = pelmHwChild->findChildElement("CpuIdTree")))
2399 readCpuIdTree(*pelmCPUChild, hw.llCpuIdLeafs);
2400 }
2401 else if (pelmHwChild->nameEquals("Memory"))
2402 {
2403 pelmHwChild->getAttributeValue("RAMSize", hw.ulMemorySizeMB);
2404 pelmHwChild->getAttributeValue("PageFusion", hw.fPageFusionEnabled);
2405 }
2406 else if (pelmHwChild->nameEquals("Firmware"))
2407 {
2408 Utf8Str strFirmwareType;
2409 if (pelmHwChild->getAttributeValue("type", strFirmwareType))
2410 {
2411 if ( (strFirmwareType == "BIOS")
2412 || (strFirmwareType == "1") // some trunk builds used the number here
2413 )
2414 hw.firmwareType = FirmwareType_BIOS;
2415 else if ( (strFirmwareType == "EFI")
2416 || (strFirmwareType == "2") // some trunk builds used the number here
2417 )
2418 hw.firmwareType = FirmwareType_EFI;
2419 else if ( strFirmwareType == "EFI32")
2420 hw.firmwareType = FirmwareType_EFI32;
2421 else if ( strFirmwareType == "EFI64")
2422 hw.firmwareType = FirmwareType_EFI64;
2423 else if ( strFirmwareType == "EFIDUAL")
2424 hw.firmwareType = FirmwareType_EFIDUAL;
2425 else
2426 throw ConfigFileError(this,
2427 pelmHwChild,
2428 N_("Invalid value '%s' in Firmware/@type"),
2429 strFirmwareType.c_str());
2430 }
2431 }
2432 else if (pelmHwChild->nameEquals("HID"))
2433 {
2434 Utf8Str strHidType;
2435 if (pelmHwChild->getAttributeValue("Keyboard", strHidType))
2436 {
2437 if (strHidType == "None")
2438 hw.keyboardHidType = KeyboardHidType_None;
2439 else if (strHidType == "USBKeyboard")
2440 hw.keyboardHidType = KeyboardHidType_USBKeyboard;
2441 else if (strHidType == "PS2Keyboard")
2442 hw.keyboardHidType = KeyboardHidType_PS2Keyboard;
2443 else if (strHidType == "ComboKeyboard")
2444 hw.keyboardHidType = KeyboardHidType_ComboKeyboard;
2445 else
2446 throw ConfigFileError(this,
2447 pelmHwChild,
2448 N_("Invalid value '%s' in HID/Keyboard/@type"),
2449 strHidType.c_str());
2450 }
2451 if (pelmHwChild->getAttributeValue("Pointing", strHidType))
2452 {
2453 if (strHidType == "None")
2454 hw.pointingHidType = PointingHidType_None;
2455 else if (strHidType == "USBMouse")
2456 hw.pointingHidType = PointingHidType_USBMouse;
2457 else if (strHidType == "USBTablet")
2458 hw.pointingHidType = PointingHidType_USBTablet;
2459 else if (strHidType == "PS2Mouse")
2460 hw.pointingHidType = PointingHidType_PS2Mouse;
2461 else if (strHidType == "ComboMouse")
2462 hw.pointingHidType = PointingHidType_ComboMouse;
2463 else
2464 throw ConfigFileError(this,
2465 pelmHwChild,
2466 N_("Invalid value '%s' in HID/Pointing/@type"),
2467 strHidType.c_str());
2468 }
2469 }
2470 else if (pelmHwChild->nameEquals("Chipset"))
2471 {
2472 Utf8Str strChipsetType;
2473 if (pelmHwChild->getAttributeValue("type", strChipsetType))
2474 {
2475 if (strChipsetType == "PIIX3")
2476 hw.chipsetType = ChipsetType_PIIX3;
2477 else if (strChipsetType == "ICH9")
2478 hw.chipsetType = ChipsetType_ICH9;
2479 else
2480 throw ConfigFileError(this,
2481 pelmHwChild,
2482 N_("Invalid value '%s' in Chipset/@type"),
2483 strChipsetType.c_str());
2484 }
2485 }
2486 else if (pelmHwChild->nameEquals("HPET"))
2487 {
2488 pelmHwChild->getAttributeValue("enabled", hw.fHpetEnabled);
2489 }
2490 else if (pelmHwChild->nameEquals("Boot"))
2491 {
2492 hw.mapBootOrder.clear();
2493
2494 xml::NodesLoop nl2(*pelmHwChild, "Order");
2495 const xml::ElementNode *pelmOrder;
2496 while ((pelmOrder = nl2.forAllNodes()))
2497 {
2498 uint32_t ulPos;
2499 Utf8Str strDevice;
2500 if (!pelmOrder->getAttributeValue("position", ulPos))
2501 throw ConfigFileError(this, pelmOrder, N_("Required Boot/Order/@position attribute is missing"));
2502
2503 if ( ulPos < 1
2504 || ulPos > SchemaDefs::MaxBootPosition
2505 )
2506 throw ConfigFileError(this,
2507 pelmOrder,
2508 N_("Invalid value '%RU32' in Boot/Order/@position: must be greater than 0 and less than %RU32"),
2509 ulPos,
2510 SchemaDefs::MaxBootPosition + 1);
2511 // XML is 1-based but internal data is 0-based
2512 --ulPos;
2513
2514 if (hw.mapBootOrder.find(ulPos) != hw.mapBootOrder.end())
2515 throw ConfigFileError(this, pelmOrder, N_("Invalid value '%RU32' in Boot/Order/@position: value is not unique"), ulPos);
2516
2517 if (!pelmOrder->getAttributeValue("device", strDevice))
2518 throw ConfigFileError(this, pelmOrder, N_("Required Boot/Order/@device attribute is missing"));
2519
2520 DeviceType_T type;
2521 if (strDevice == "None")
2522 type = DeviceType_Null;
2523 else if (strDevice == "Floppy")
2524 type = DeviceType_Floppy;
2525 else if (strDevice == "DVD")
2526 type = DeviceType_DVD;
2527 else if (strDevice == "HardDisk")
2528 type = DeviceType_HardDisk;
2529 else if (strDevice == "Network")
2530 type = DeviceType_Network;
2531 else
2532 throw ConfigFileError(this, pelmOrder, N_("Invalid value '%s' in Boot/Order/@device attribute"), strDevice.c_str());
2533 hw.mapBootOrder[ulPos] = type;
2534 }
2535 }
2536 else if (pelmHwChild->nameEquals("Display"))
2537 {
2538 pelmHwChild->getAttributeValue("VRAMSize", hw.ulVRAMSizeMB);
2539 if (!pelmHwChild->getAttributeValue("monitorCount", hw.cMonitors))
2540 pelmHwChild->getAttributeValue("MonitorCount", hw.cMonitors); // pre-v1.5 variant
2541 if (!pelmHwChild->getAttributeValue("accelerate3D", hw.fAccelerate3D))
2542 pelmHwChild->getAttributeValue("Accelerate3D", hw.fAccelerate3D); // pre-v1.5 variant
2543 pelmHwChild->getAttributeValue("accelerate2DVideo", hw.fAccelerate2DVideo);
2544 }
2545 else if (pelmHwChild->nameEquals("RemoteDisplay"))
2546 {
2547 pelmHwChild->getAttributeValue("enabled", hw.vrdeSettings.fEnabled);
2548
2549 Utf8Str str;
2550 if (pelmHwChild->getAttributeValue("port", str))
2551 hw.vrdeSettings.mapProperties["TCP/Ports"] = str;
2552 if (pelmHwChild->getAttributeValue("netAddress", str))
2553 hw.vrdeSettings.mapProperties["TCP/Address"] = str;
2554
2555 Utf8Str strAuthType;
2556 if (pelmHwChild->getAttributeValue("authType", strAuthType))
2557 {
2558 // settings before 1.3 used lower case so make sure this is case-insensitive
2559 strAuthType.toUpper();
2560 if (strAuthType == "NULL")
2561 hw.vrdeSettings.authType = AuthType_Null;
2562 else if (strAuthType == "GUEST")
2563 hw.vrdeSettings.authType = AuthType_Guest;
2564 else if (strAuthType == "EXTERNAL")
2565 hw.vrdeSettings.authType = AuthType_External;
2566 else
2567 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in RemoteDisplay/@authType attribute"), strAuthType.c_str());
2568 }
2569
2570 pelmHwChild->getAttributeValue("authLibrary", hw.vrdeSettings.strAuthLibrary);
2571 pelmHwChild->getAttributeValue("authTimeout", hw.vrdeSettings.ulAuthTimeout);
2572 pelmHwChild->getAttributeValue("allowMultiConnection", hw.vrdeSettings.fAllowMultiConnection);
2573 pelmHwChild->getAttributeValue("reuseSingleConnection", hw.vrdeSettings.fReuseSingleConnection);
2574
2575 /* 3.2 and 4.0 betas, 4.0 has this information in VRDEProperties. */
2576 const xml::ElementNode *pelmVideoChannel;
2577 if ((pelmVideoChannel = pelmHwChild->findChildElement("VideoChannel")))
2578 {
2579 bool fVideoChannel = false;
2580 pelmVideoChannel->getAttributeValue("enabled", fVideoChannel);
2581 hw.vrdeSettings.mapProperties["VideoChannel/Enabled"] = fVideoChannel? "true": "false";
2582
2583 uint32_t ulVideoChannelQuality = 75;
2584 pelmVideoChannel->getAttributeValue("quality", ulVideoChannelQuality);
2585 ulVideoChannelQuality = RT_CLAMP(ulVideoChannelQuality, 10, 100);
2586 char *pszBuffer = NULL;
2587 if (RTStrAPrintf(&pszBuffer, "%d", ulVideoChannelQuality) >= 0)
2588 {
2589 hw.vrdeSettings.mapProperties["VideoChannel/Quality"] = pszBuffer;
2590 RTStrFree(pszBuffer);
2591 }
2592 else
2593 hw.vrdeSettings.mapProperties["VideoChannel/Quality"] = "75";
2594 }
2595 pelmHwChild->getAttributeValue("VRDEExtPack", hw.vrdeSettings.strVrdeExtPack);
2596
2597 const xml::ElementNode *pelmProperties = pelmHwChild->findChildElement("VRDEProperties");
2598 if (pelmProperties != NULL)
2599 {
2600 xml::NodesLoop nl(*pelmProperties);
2601 const xml::ElementNode *pelmProperty;
2602 while ((pelmProperty = nl.forAllNodes()))
2603 {
2604 if (pelmProperty->nameEquals("Property"))
2605 {
2606 /* <Property name="TCP/Ports" value="3000-3002"/> */
2607 Utf8Str strName, strValue;
2608 if ( ((pelmProperty->getAttributeValue("name", strName)))
2609 && ((pelmProperty->getAttributeValue("value", strValue)))
2610 )
2611 hw.vrdeSettings.mapProperties[strName] = strValue;
2612 else
2613 throw ConfigFileError(this, pelmProperty, N_("Required VRDE Property/@name or @value attribute is missing"));
2614 }
2615 }
2616 }
2617 }
2618 else if (pelmHwChild->nameEquals("BIOS"))
2619 {
2620 const xml::ElementNode *pelmBIOSChild;
2621 if ((pelmBIOSChild = pelmHwChild->findChildElement("ACPI")))
2622 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fACPIEnabled);
2623 if ((pelmBIOSChild = pelmHwChild->findChildElement("IOAPIC")))
2624 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fIOAPICEnabled);
2625 if ((pelmBIOSChild = pelmHwChild->findChildElement("Logo")))
2626 {
2627 pelmBIOSChild->getAttributeValue("fadeIn", hw.biosSettings.fLogoFadeIn);
2628 pelmBIOSChild->getAttributeValue("fadeOut", hw.biosSettings.fLogoFadeOut);
2629 pelmBIOSChild->getAttributeValue("displayTime", hw.biosSettings.ulLogoDisplayTime);
2630 pelmBIOSChild->getAttributeValue("imagePath", hw.biosSettings.strLogoImagePath);
2631 }
2632 if ((pelmBIOSChild = pelmHwChild->findChildElement("BootMenu")))
2633 {
2634 Utf8Str strBootMenuMode;
2635 if (pelmBIOSChild->getAttributeValue("mode", strBootMenuMode))
2636 {
2637 // settings before 1.3 used lower case so make sure this is case-insensitive
2638 strBootMenuMode.toUpper();
2639 if (strBootMenuMode == "DISABLED")
2640 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_Disabled;
2641 else if (strBootMenuMode == "MENUONLY")
2642 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_MenuOnly;
2643 else if (strBootMenuMode == "MESSAGEANDMENU")
2644 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_MessageAndMenu;
2645 else
2646 throw ConfigFileError(this, pelmBIOSChild, N_("Invalid value '%s' in BootMenu/@mode attribute"), strBootMenuMode.c_str());
2647 }
2648 }
2649 if ((pelmBIOSChild = pelmHwChild->findChildElement("PXEDebug")))
2650 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fPXEDebugEnabled);
2651 if ((pelmBIOSChild = pelmHwChild->findChildElement("TimeOffset")))
2652 pelmBIOSChild->getAttributeValue("value", hw.biosSettings.llTimeOffset);
2653
2654 // legacy BIOS/IDEController (pre 1.7)
2655 if ( (m->sv < SettingsVersion_v1_7)
2656 && ((pelmBIOSChild = pelmHwChild->findChildElement("IDEController")))
2657 )
2658 {
2659 StorageController sctl;
2660 sctl.strName = "IDE Controller";
2661 sctl.storageBus = StorageBus_IDE;
2662
2663 Utf8Str strType;
2664 if (pelmBIOSChild->getAttributeValue("type", strType))
2665 {
2666 if (strType == "PIIX3")
2667 sctl.controllerType = StorageControllerType_PIIX3;
2668 else if (strType == "PIIX4")
2669 sctl.controllerType = StorageControllerType_PIIX4;
2670 else if (strType == "ICH6")
2671 sctl.controllerType = StorageControllerType_ICH6;
2672 else
2673 throw ConfigFileError(this, pelmBIOSChild, N_("Invalid value '%s' for IDEController/@type attribute"), strType.c_str());
2674 }
2675 sctl.ulPortCount = 2;
2676 strg.llStorageControllers.push_back(sctl);
2677 }
2678 }
2679 else if (pelmHwChild->nameEquals("USBController"))
2680 {
2681 pelmHwChild->getAttributeValue("enabled", hw.usbController.fEnabled);
2682 pelmHwChild->getAttributeValue("enabledEhci", hw.usbController.fEnabledEHCI);
2683
2684 readUSBDeviceFilters(*pelmHwChild,
2685 hw.usbController.llDeviceFilters);
2686 }
2687 else if ( (m->sv < SettingsVersion_v1_7)
2688 && (pelmHwChild->nameEquals("SATAController"))
2689 )
2690 {
2691 bool f;
2692 if ( (pelmHwChild->getAttributeValue("enabled", f))
2693 && (f)
2694 )
2695 {
2696 StorageController sctl;
2697 sctl.strName = "SATA Controller";
2698 sctl.storageBus = StorageBus_SATA;
2699 sctl.controllerType = StorageControllerType_IntelAhci;
2700
2701 readStorageControllerAttributes(*pelmHwChild, sctl);
2702
2703 strg.llStorageControllers.push_back(sctl);
2704 }
2705 }
2706 else if (pelmHwChild->nameEquals("Network"))
2707 readNetworkAdapters(*pelmHwChild, hw.llNetworkAdapters);
2708 else if (pelmHwChild->nameEquals("RTC"))
2709 {
2710 Utf8Str strLocalOrUTC;
2711 machineUserData.fRTCUseUTC = pelmHwChild->getAttributeValue("localOrUTC", strLocalOrUTC)
2712 && strLocalOrUTC == "UTC";
2713 }
2714 else if ( (pelmHwChild->nameEquals("UART"))
2715 || (pelmHwChild->nameEquals("Uart")) // used before 1.3
2716 )
2717 readSerialPorts(*pelmHwChild, hw.llSerialPorts);
2718 else if ( (pelmHwChild->nameEquals("LPT"))
2719 || (pelmHwChild->nameEquals("Lpt")) // used before 1.3
2720 )
2721 readParallelPorts(*pelmHwChild, hw.llParallelPorts);
2722 else if (pelmHwChild->nameEquals("AudioAdapter"))
2723 readAudioAdapter(*pelmHwChild, hw.audioAdapter);
2724 else if (pelmHwChild->nameEquals("SharedFolders"))
2725 {
2726 xml::NodesLoop nl2(*pelmHwChild, "SharedFolder");
2727 const xml::ElementNode *pelmFolder;
2728 while ((pelmFolder = nl2.forAllNodes()))
2729 {
2730 SharedFolder sf;
2731 pelmFolder->getAttributeValue("name", sf.strName);
2732 pelmFolder->getAttributeValue("hostPath", sf.strHostPath);
2733 pelmFolder->getAttributeValue("writable", sf.fWritable);
2734 pelmFolder->getAttributeValue("autoMount", sf.fAutoMount);
2735 hw.llSharedFolders.push_back(sf);
2736 }
2737 }
2738 else if (pelmHwChild->nameEquals("Clipboard"))
2739 {
2740 Utf8Str strTemp;
2741 if (pelmHwChild->getAttributeValue("mode", strTemp))
2742 {
2743 if (strTemp == "Disabled")
2744 hw.clipboardMode = ClipboardMode_Disabled;
2745 else if (strTemp == "HostToGuest")
2746 hw.clipboardMode = ClipboardMode_HostToGuest;
2747 else if (strTemp == "GuestToHost")
2748 hw.clipboardMode = ClipboardMode_GuestToHost;
2749 else if (strTemp == "Bidirectional")
2750 hw.clipboardMode = ClipboardMode_Bidirectional;
2751 else
2752 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in Clipboard/@mode attribute"), strTemp.c_str());
2753 }
2754 }
2755 else if (pelmHwChild->nameEquals("Guest"))
2756 {
2757 if (!pelmHwChild->getAttributeValue("memoryBalloonSize", hw.ulMemoryBalloonSize))
2758 pelmHwChild->getAttributeValue("MemoryBalloonSize", hw.ulMemoryBalloonSize); // used before 1.3
2759 }
2760 else if (pelmHwChild->nameEquals("GuestProperties"))
2761 readGuestProperties(*pelmHwChild, hw);
2762 else if (pelmHwChild->nameEquals("IO"))
2763 {
2764 const xml::ElementNode *pelmBwGroups;
2765 const xml::ElementNode *pelmIoChild;
2766
2767 if ((pelmIoChild = pelmHwChild->findChildElement("IoCache")))
2768 {
2769 pelmIoChild->getAttributeValue("enabled", hw.ioSettings.fIoCacheEnabled);
2770 pelmIoChild->getAttributeValue("size", hw.ioSettings.ulIoCacheSize);
2771 }
2772
2773 if ((pelmBwGroups = pelmHwChild->findChildElement("BandwidthGroups")))
2774 {
2775 xml::NodesLoop nl2(*pelmBwGroups, "BandwidthGroup");
2776 const xml::ElementNode *pelmBandwidthGroup;
2777 while ((pelmBandwidthGroup = nl2.forAllNodes()))
2778 {
2779 BandwidthGroup gr;
2780 Utf8Str strTemp;
2781
2782 pelmBandwidthGroup->getAttributeValue("name", gr.strName);
2783
2784 if (pelmBandwidthGroup->getAttributeValue("type", strTemp))
2785 {
2786 if (strTemp == "Disk")
2787 gr.enmType = BandwidthGroupType_Disk;
2788 else if (strTemp == "Network")
2789 gr.enmType = BandwidthGroupType_Network;
2790 else
2791 throw ConfigFileError(this, pelmBandwidthGroup, N_("Invalid value '%s' in BandwidthGroup/@type attribute"), strTemp.c_str());
2792 }
2793 else
2794 throw ConfigFileError(this, pelmBandwidthGroup, N_("Missing BandwidthGroup/@type attribute"));
2795
2796 pelmBandwidthGroup->getAttributeValue("maxMbPerSec", gr.cMaxMbPerSec);
2797 hw.ioSettings.llBandwidthGroups.push_back(gr);
2798 }
2799 }
2800 } else if (pelmHwChild->nameEquals("HostPci")) {
2801 const xml::ElementNode *pelmDevices;
2802
2803 if ((pelmDevices = pelmHwChild->findChildElement("Devices")))
2804 {
2805 xml::NodesLoop nl2(*pelmDevices, "Device");
2806 const xml::ElementNode *pelmDevice;
2807 while ((pelmDevice = nl2.forAllNodes()))
2808 {
2809 HostPciDeviceAttachment hpda;
2810
2811 if (!pelmDevice->getAttributeValue("host", hpda.uHostAddress))
2812 throw ConfigFileError(this, pelmDevice, N_("Missing Device/@host attribute"));
2813
2814 if (!pelmDevice->getAttributeValue("guest", hpda.uGuestAddress))
2815 throw ConfigFileError(this, pelmDevice, N_("Missing Device/@guest attribute"));
2816
2817 /* name is optional */
2818 pelmDevice->getAttributeValue("name", hpda.strDeviceName);
2819
2820 hw.pciAttachments.push_back(hpda);
2821 }
2822 }
2823 }
2824 }
2825
2826 if (hw.ulMemorySizeMB == (uint32_t)-1)
2827 throw ConfigFileError(this, &elmHardware, N_("Required Memory/@RAMSize element/attribute is missing"));
2828}
2829
2830/**
2831 * This gets called instead of readStorageControllers() for legacy pre-1.7 settings
2832 * files which have a <HardDiskAttachments> node and storage controller settings
2833 * hidden in the <Hardware> settings. We set the StorageControllers fields just the
2834 * same, just from different sources.
2835 * @param elmHardware <Hardware> XML node.
2836 * @param elmHardDiskAttachments <HardDiskAttachments> XML node.
2837 * @param strg
2838 */
2839void MachineConfigFile::readHardDiskAttachments_pre1_7(const xml::ElementNode &elmHardDiskAttachments,
2840 Storage &strg)
2841{
2842 StorageController *pIDEController = NULL;
2843 StorageController *pSATAController = NULL;
2844
2845 for (StorageControllersList::iterator it = strg.llStorageControllers.begin();
2846 it != strg.llStorageControllers.end();
2847 ++it)
2848 {
2849 StorageController &s = *it;
2850 if (s.storageBus == StorageBus_IDE)
2851 pIDEController = &s;
2852 else if (s.storageBus == StorageBus_SATA)
2853 pSATAController = &s;
2854 }
2855
2856 xml::NodesLoop nl1(elmHardDiskAttachments, "HardDiskAttachment");
2857 const xml::ElementNode *pelmAttachment;
2858 while ((pelmAttachment = nl1.forAllNodes()))
2859 {
2860 AttachedDevice att;
2861 Utf8Str strUUID, strBus;
2862
2863 if (!pelmAttachment->getAttributeValue("hardDisk", strUUID))
2864 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@hardDisk attribute is missing"));
2865 parseUUID(att.uuid, strUUID);
2866
2867 if (!pelmAttachment->getAttributeValue("bus", strBus))
2868 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@bus attribute is missing"));
2869 // pre-1.7 'channel' is now port
2870 if (!pelmAttachment->getAttributeValue("channel", att.lPort))
2871 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@channel attribute is missing"));
2872 // pre-1.7 'device' is still device
2873 if (!pelmAttachment->getAttributeValue("device", att.lDevice))
2874 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@device attribute is missing"));
2875
2876 att.deviceType = DeviceType_HardDisk;
2877
2878 if (strBus == "IDE")
2879 {
2880 if (!pIDEController)
2881 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus is 'IDE' but cannot find IDE controller"));
2882 pIDEController->llAttachedDevices.push_back(att);
2883 }
2884 else if (strBus == "SATA")
2885 {
2886 if (!pSATAController)
2887 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus is 'SATA' but cannot find SATA controller"));
2888 pSATAController->llAttachedDevices.push_back(att);
2889 }
2890 else
2891 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus attribute has illegal value '%s'"), strBus.c_str());
2892 }
2893}
2894
2895/**
2896 * Reads in a <StorageControllers> block and stores it in the given Storage structure.
2897 * Used both directly from readMachine and from readSnapshot, since snapshots
2898 * have their own storage controllers sections.
2899 *
2900 * This is only called for settings version 1.7 and above; see readHardDiskAttachments_pre1_7()
2901 * for earlier versions.
2902 *
2903 * @param elmStorageControllers
2904 */
2905void MachineConfigFile::readStorageControllers(const xml::ElementNode &elmStorageControllers,
2906 Storage &strg)
2907{
2908 xml::NodesLoop nlStorageControllers(elmStorageControllers, "StorageController");
2909 const xml::ElementNode *pelmController;
2910 while ((pelmController = nlStorageControllers.forAllNodes()))
2911 {
2912 StorageController sctl;
2913
2914 if (!pelmController->getAttributeValue("name", sctl.strName))
2915 throw ConfigFileError(this, pelmController, N_("Required StorageController/@name attribute is missing"));
2916 // canonicalize storage controller names for configs in the switchover
2917 // period.
2918 if (m->sv < SettingsVersion_v1_9)
2919 {
2920 if (sctl.strName == "IDE")
2921 sctl.strName = "IDE Controller";
2922 else if (sctl.strName == "SATA")
2923 sctl.strName = "SATA Controller";
2924 else if (sctl.strName == "SCSI")
2925 sctl.strName = "SCSI Controller";
2926 }
2927
2928 pelmController->getAttributeValue("Instance", sctl.ulInstance);
2929 // default from constructor is 0
2930
2931 pelmController->getAttributeValue("Bootable", sctl.fBootable);
2932 // default from constructor is true which is true
2933 // for settings below version 1.11 because they allowed only
2934 // one controller per type.
2935
2936 Utf8Str strType;
2937 if (!pelmController->getAttributeValue("type", strType))
2938 throw ConfigFileError(this, pelmController, N_("Required StorageController/@type attribute is missing"));
2939
2940 if (strType == "AHCI")
2941 {
2942 sctl.storageBus = StorageBus_SATA;
2943 sctl.controllerType = StorageControllerType_IntelAhci;
2944 }
2945 else if (strType == "LsiLogic")
2946 {
2947 sctl.storageBus = StorageBus_SCSI;
2948 sctl.controllerType = StorageControllerType_LsiLogic;
2949 }
2950 else if (strType == "BusLogic")
2951 {
2952 sctl.storageBus = StorageBus_SCSI;
2953 sctl.controllerType = StorageControllerType_BusLogic;
2954 }
2955 else if (strType == "PIIX3")
2956 {
2957 sctl.storageBus = StorageBus_IDE;
2958 sctl.controllerType = StorageControllerType_PIIX3;
2959 }
2960 else if (strType == "PIIX4")
2961 {
2962 sctl.storageBus = StorageBus_IDE;
2963 sctl.controllerType = StorageControllerType_PIIX4;
2964 }
2965 else if (strType == "ICH6")
2966 {
2967 sctl.storageBus = StorageBus_IDE;
2968 sctl.controllerType = StorageControllerType_ICH6;
2969 }
2970 else if ( (m->sv >= SettingsVersion_v1_9)
2971 && (strType == "I82078")
2972 )
2973 {
2974 sctl.storageBus = StorageBus_Floppy;
2975 sctl.controllerType = StorageControllerType_I82078;
2976 }
2977 else if (strType == "LsiLogicSas")
2978 {
2979 sctl.storageBus = StorageBus_SAS;
2980 sctl.controllerType = StorageControllerType_LsiLogicSas;
2981 }
2982 else
2983 throw ConfigFileError(this, pelmController, N_("Invalid value '%s' for StorageController/@type attribute"), strType.c_str());
2984
2985 readStorageControllerAttributes(*pelmController, sctl);
2986
2987 xml::NodesLoop nlAttached(*pelmController, "AttachedDevice");
2988 const xml::ElementNode *pelmAttached;
2989 while ((pelmAttached = nlAttached.forAllNodes()))
2990 {
2991 AttachedDevice att;
2992 Utf8Str strTemp;
2993 pelmAttached->getAttributeValue("type", strTemp);
2994
2995 att.fDiscard = false;
2996 att.fNonRotational = false;
2997
2998 if (strTemp == "HardDisk")
2999 {
3000 att.deviceType = DeviceType_HardDisk;
3001 pelmAttached->getAttributeValue("nonrotational", att.fNonRotational);
3002 pelmAttached->getAttributeValue("discard", att.fDiscard);
3003 }
3004 else if (m->sv >= SettingsVersion_v1_9)
3005 {
3006 // starting with 1.9 we list DVD and floppy drive info + attachments under <StorageControllers>
3007 if (strTemp == "DVD")
3008 {
3009 att.deviceType = DeviceType_DVD;
3010 pelmAttached->getAttributeValue("passthrough", att.fPassThrough);
3011 pelmAttached->getAttributeValue("tempeject", att.fTempEject);
3012 }
3013 else if (strTemp == "Floppy")
3014 att.deviceType = DeviceType_Floppy;
3015 }
3016
3017 if (att.deviceType != DeviceType_Null)
3018 {
3019 const xml::ElementNode *pelmImage;
3020 // all types can have images attached, but for HardDisk it's required
3021 if (!(pelmImage = pelmAttached->findChildElement("Image")))
3022 {
3023 if (att.deviceType == DeviceType_HardDisk)
3024 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/Image element is missing"));
3025 else
3026 {
3027 // DVDs and floppies can also have <HostDrive> instead of <Image>
3028 const xml::ElementNode *pelmHostDrive;
3029 if ((pelmHostDrive = pelmAttached->findChildElement("HostDrive")))
3030 if (!pelmHostDrive->getAttributeValue("src", att.strHostDriveSrc))
3031 throw ConfigFileError(this, pelmHostDrive, N_("Required AttachedDevice/HostDrive/@src attribute is missing"));
3032 }
3033 }
3034 else
3035 {
3036 if (!pelmImage->getAttributeValue("uuid", strTemp))
3037 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/Image/@uuid attribute is missing"));
3038 parseUUID(att.uuid, strTemp);
3039 }
3040
3041 if (!pelmAttached->getAttributeValue("port", att.lPort))
3042 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/@port attribute is missing"));
3043 if (!pelmAttached->getAttributeValue("device", att.lDevice))
3044 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/@device attribute is missing"));
3045
3046 pelmAttached->getAttributeValue("bandwidthGroup", att.strBwGroup);
3047 sctl.llAttachedDevices.push_back(att);
3048 }
3049 }
3050
3051 strg.llStorageControllers.push_back(sctl);
3052 }
3053}
3054
3055/**
3056 * This gets called for legacy pre-1.9 settings files after having parsed the
3057 * <Hardware> and <StorageControllers> sections to parse <Hardware> once more
3058 * for the <DVDDrive> and <FloppyDrive> sections.
3059 *
3060 * Before settings version 1.9, DVD and floppy drives were specified separately
3061 * under <Hardware>; we then need this extra loop to make sure the storage
3062 * controller structs are already set up so we can add stuff to them.
3063 *
3064 * @param elmHardware
3065 * @param strg
3066 */
3067void MachineConfigFile::readDVDAndFloppies_pre1_9(const xml::ElementNode &elmHardware,
3068 Storage &strg)
3069{
3070 xml::NodesLoop nl1(elmHardware);
3071 const xml::ElementNode *pelmHwChild;
3072 while ((pelmHwChild = nl1.forAllNodes()))
3073 {
3074 if (pelmHwChild->nameEquals("DVDDrive"))
3075 {
3076 // create a DVD "attached device" and attach it to the existing IDE controller
3077 AttachedDevice att;
3078 att.deviceType = DeviceType_DVD;
3079 // legacy DVD drive is always secondary master (port 1, device 0)
3080 att.lPort = 1;
3081 att.lDevice = 0;
3082 pelmHwChild->getAttributeValue("passthrough", att.fPassThrough);
3083 pelmHwChild->getAttributeValue("tempeject", att.fTempEject);
3084
3085 const xml::ElementNode *pDriveChild;
3086 Utf8Str strTmp;
3087 if ( ((pDriveChild = pelmHwChild->findChildElement("Image")))
3088 && (pDriveChild->getAttributeValue("uuid", strTmp))
3089 )
3090 parseUUID(att.uuid, strTmp);
3091 else if ((pDriveChild = pelmHwChild->findChildElement("HostDrive")))
3092 pDriveChild->getAttributeValue("src", att.strHostDriveSrc);
3093
3094 // find the IDE controller and attach the DVD drive
3095 bool fFound = false;
3096 for (StorageControllersList::iterator it = strg.llStorageControllers.begin();
3097 it != strg.llStorageControllers.end();
3098 ++it)
3099 {
3100 StorageController &sctl = *it;
3101 if (sctl.storageBus == StorageBus_IDE)
3102 {
3103 sctl.llAttachedDevices.push_back(att);
3104 fFound = true;
3105 break;
3106 }
3107 }
3108
3109 if (!fFound)
3110 throw ConfigFileError(this, pelmHwChild, N_("Internal error: found DVD drive but IDE controller does not exist"));
3111 // shouldn't happen because pre-1.9 settings files always had at least one IDE controller in the settings
3112 // which should have gotten parsed in <StorageControllers> before this got called
3113 }
3114 else if (pelmHwChild->nameEquals("FloppyDrive"))
3115 {
3116 bool fEnabled;
3117 if ( (pelmHwChild->getAttributeValue("enabled", fEnabled))
3118 && (fEnabled)
3119 )
3120 {
3121 // create a new floppy controller and attach a floppy "attached device"
3122 StorageController sctl;
3123 sctl.strName = "Floppy Controller";
3124 sctl.storageBus = StorageBus_Floppy;
3125 sctl.controllerType = StorageControllerType_I82078;
3126 sctl.ulPortCount = 1;
3127
3128 AttachedDevice att;
3129 att.deviceType = DeviceType_Floppy;
3130 att.lPort = 0;
3131 att.lDevice = 0;
3132
3133 const xml::ElementNode *pDriveChild;
3134 Utf8Str strTmp;
3135 if ( ((pDriveChild = pelmHwChild->findChildElement("Image")))
3136 && (pDriveChild->getAttributeValue("uuid", strTmp))
3137 )
3138 parseUUID(att.uuid, strTmp);
3139 else if ((pDriveChild = pelmHwChild->findChildElement("HostDrive")))
3140 pDriveChild->getAttributeValue("src", att.strHostDriveSrc);
3141
3142 // store attachment with controller
3143 sctl.llAttachedDevices.push_back(att);
3144 // store controller with storage
3145 strg.llStorageControllers.push_back(sctl);
3146 }
3147 }
3148 }
3149}
3150
3151/**
3152 * Called for reading the <Teleporter> element under <Machine>.
3153 */
3154void MachineConfigFile::readTeleporter(const xml::ElementNode *pElmTeleporter,
3155 MachineUserData *pUserData)
3156{
3157 pElmTeleporter->getAttributeValue("enabled", pUserData->fTeleporterEnabled);
3158 pElmTeleporter->getAttributeValue("port", pUserData->uTeleporterPort);
3159 pElmTeleporter->getAttributeValue("address", pUserData->strTeleporterAddress);
3160 pElmTeleporter->getAttributeValue("password", pUserData->strTeleporterPassword);
3161
3162 if ( pUserData->strTeleporterPassword.isNotEmpty()
3163 && !VBoxIsPasswordHashed(&pUserData->strTeleporterPassword))
3164 VBoxHashPassword(&pUserData->strTeleporterPassword);
3165}
3166
3167/**
3168 * Called for reading the <Debugging> element under <Machine> or <Snapshot>.
3169 */
3170void MachineConfigFile::readDebugging(const xml::ElementNode *pElmDebugging, Debugging *pDbg)
3171{
3172 if (!pElmDebugging || m->sv < SettingsVersion_v1_13)
3173 return;
3174
3175 const xml::ElementNode * const pelmTracing = pElmDebugging->findChildElement("Tracing");
3176 if (pelmTracing)
3177 {
3178 pelmTracing->getAttributeValue("enabled", pDbg->fTracingEnabled);
3179 pelmTracing->getAttributeValue("allowTracingToAccessVM", pDbg->fAllowTracingToAccessVM);
3180 pelmTracing->getAttributeValue("config", pDbg->strTracingConfig);
3181 }
3182}
3183
3184/**
3185 * Called initially for the <Snapshot> element under <Machine>, if present,
3186 * to store the snapshot's data into the given Snapshot structure (which is
3187 * then the one in the Machine struct). This might then recurse if
3188 * a <Snapshots> (plural) element is found in the snapshot, which should
3189 * contain a list of child snapshots; such lists are maintained in the
3190 * Snapshot structure.
3191 *
3192 * @param elmSnapshot
3193 * @param snap
3194 */
3195void MachineConfigFile::readSnapshot(const xml::ElementNode &elmSnapshot,
3196 Snapshot &snap)
3197{
3198 Utf8Str strTemp;
3199
3200 if (!elmSnapshot.getAttributeValue("uuid", strTemp))
3201 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@uuid attribute is missing"));
3202 parseUUID(snap.uuid, strTemp);
3203
3204 if (!elmSnapshot.getAttributeValue("name", snap.strName))
3205 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@name attribute is missing"));
3206
3207 // earlier 3.1 trunk builds had a bug and added Description as an attribute, read it silently and write it back as an element
3208 elmSnapshot.getAttributeValue("Description", snap.strDescription);
3209
3210 if (!elmSnapshot.getAttributeValue("timeStamp", strTemp))
3211 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@timeStamp attribute is missing"));
3212 parseTimestamp(snap.timestamp, strTemp);
3213
3214 elmSnapshot.getAttributeValuePath("stateFile", snap.strStateFile); // online snapshots only
3215
3216 // parse Hardware before the other elements because other things depend on it
3217 const xml::ElementNode *pelmHardware;
3218 if (!(pelmHardware = elmSnapshot.findChildElement("Hardware")))
3219 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@Hardware element is missing"));
3220 readHardware(*pelmHardware, snap.hardware, snap.storage);
3221
3222 xml::NodesLoop nlSnapshotChildren(elmSnapshot);
3223 const xml::ElementNode *pelmSnapshotChild;
3224 while ((pelmSnapshotChild = nlSnapshotChildren.forAllNodes()))
3225 {
3226 if (pelmSnapshotChild->nameEquals("Description"))
3227 snap.strDescription = pelmSnapshotChild->getValue();
3228 else if ( (m->sv < SettingsVersion_v1_7)
3229 && (pelmSnapshotChild->nameEquals("HardDiskAttachments"))
3230 )
3231 readHardDiskAttachments_pre1_7(*pelmSnapshotChild, snap.storage);
3232 else if ( (m->sv >= SettingsVersion_v1_7)
3233 && (pelmSnapshotChild->nameEquals("StorageControllers"))
3234 )
3235 readStorageControllers(*pelmSnapshotChild, snap.storage);
3236 else if (pelmSnapshotChild->nameEquals("Snapshots"))
3237 {
3238 xml::NodesLoop nlChildSnapshots(*pelmSnapshotChild);
3239 const xml::ElementNode *pelmChildSnapshot;
3240 while ((pelmChildSnapshot = nlChildSnapshots.forAllNodes()))
3241 {
3242 if (pelmChildSnapshot->nameEquals("Snapshot"))
3243 {
3244 Snapshot child;
3245 readSnapshot(*pelmChildSnapshot, child);
3246 snap.llChildSnapshots.push_back(child);
3247 }
3248 }
3249 }
3250 }
3251
3252 if (m->sv < SettingsVersion_v1_9)
3253 // go through Hardware once more to repair the settings controller structures
3254 // with data from old DVDDrive and FloppyDrive elements
3255 readDVDAndFloppies_pre1_9(*pelmHardware, snap.storage);
3256
3257 readDebugging(elmSnapshot.findChildElement("Debugging"), &snap.debugging);
3258}
3259
3260const struct {
3261 const char *pcszOld;
3262 const char *pcszNew;
3263} aConvertOSTypes[] =
3264{
3265 { "unknown", "Other" },
3266 { "dos", "DOS" },
3267 { "win31", "Windows31" },
3268 { "win95", "Windows95" },
3269 { "win98", "Windows98" },
3270 { "winme", "WindowsMe" },
3271 { "winnt4", "WindowsNT4" },
3272 { "win2k", "Windows2000" },
3273 { "winxp", "WindowsXP" },
3274 { "win2k3", "Windows2003" },
3275 { "winvista", "WindowsVista" },
3276 { "win2k8", "Windows2008" },
3277 { "os2warp3", "OS2Warp3" },
3278 { "os2warp4", "OS2Warp4" },
3279 { "os2warp45", "OS2Warp45" },
3280 { "ecs", "OS2eCS" },
3281 { "linux22", "Linux22" },
3282 { "linux24", "Linux24" },
3283 { "linux26", "Linux26" },
3284 { "archlinux", "ArchLinux" },
3285 { "debian", "Debian" },
3286 { "opensuse", "OpenSUSE" },
3287 { "fedoracore", "Fedora" },
3288 { "gentoo", "Gentoo" },
3289 { "mandriva", "Mandriva" },
3290 { "redhat", "RedHat" },
3291 { "ubuntu", "Ubuntu" },
3292 { "xandros", "Xandros" },
3293 { "freebsd", "FreeBSD" },
3294 { "openbsd", "OpenBSD" },
3295 { "netbsd", "NetBSD" },
3296 { "netware", "Netware" },
3297 { "solaris", "Solaris" },
3298 { "opensolaris", "OpenSolaris" },
3299 { "l4", "L4" }
3300};
3301
3302void MachineConfigFile::convertOldOSType_pre1_5(Utf8Str &str)
3303{
3304 for (unsigned u = 0;
3305 u < RT_ELEMENTS(aConvertOSTypes);
3306 ++u)
3307 {
3308 if (str == aConvertOSTypes[u].pcszOld)
3309 {
3310 str = aConvertOSTypes[u].pcszNew;
3311 break;
3312 }
3313 }
3314}
3315
3316/**
3317 * Called from the constructor to actually read in the <Machine> element
3318 * of a machine config file.
3319 * @param elmMachine
3320 */
3321void MachineConfigFile::readMachine(const xml::ElementNode &elmMachine)
3322{
3323 Utf8Str strUUID;
3324 if ( (elmMachine.getAttributeValue("uuid", strUUID))
3325 && (elmMachine.getAttributeValue("name", machineUserData.strName))
3326 )
3327 {
3328 parseUUID(uuid, strUUID);
3329
3330 elmMachine.getAttributeValue("nameSync", machineUserData.fNameSync);
3331
3332 Utf8Str str;
3333 elmMachine.getAttributeValue("Description", machineUserData.strDescription);
3334
3335 elmMachine.getAttributeValue("OSType", machineUserData.strOsType);
3336 if (m->sv < SettingsVersion_v1_5)
3337 convertOldOSType_pre1_5(machineUserData.strOsType);
3338
3339 elmMachine.getAttributeValuePath("stateFile", strStateFile);
3340
3341 if (elmMachine.getAttributeValue("currentSnapshot", str))
3342 parseUUID(uuidCurrentSnapshot, str);
3343
3344 elmMachine.getAttributeValuePath("snapshotFolder", machineUserData.strSnapshotFolder);
3345
3346 if (!elmMachine.getAttributeValue("currentStateModified", fCurrentStateModified))
3347 fCurrentStateModified = true;
3348 if (elmMachine.getAttributeValue("lastStateChange", str))
3349 parseTimestamp(timeLastStateChange, str);
3350 // constructor has called RTTimeNow(&timeLastStateChange) before
3351 if (elmMachine.getAttributeValue("aborted", fAborted))
3352 fAborted = true;
3353
3354 // parse Hardware before the other elements because other things depend on it
3355 const xml::ElementNode *pelmHardware;
3356 if (!(pelmHardware = elmMachine.findChildElement("Hardware")))
3357 throw ConfigFileError(this, &elmMachine, N_("Required Machine/Hardware element is missing"));
3358 readHardware(*pelmHardware, hardwareMachine, storageMachine);
3359
3360 xml::NodesLoop nlRootChildren(elmMachine);
3361 const xml::ElementNode *pelmMachineChild;
3362 while ((pelmMachineChild = nlRootChildren.forAllNodes()))
3363 {
3364 if (pelmMachineChild->nameEquals("ExtraData"))
3365 readExtraData(*pelmMachineChild,
3366 mapExtraDataItems);
3367 else if ( (m->sv < SettingsVersion_v1_7)
3368 && (pelmMachineChild->nameEquals("HardDiskAttachments"))
3369 )
3370 readHardDiskAttachments_pre1_7(*pelmMachineChild, storageMachine);
3371 else if ( (m->sv >= SettingsVersion_v1_7)
3372 && (pelmMachineChild->nameEquals("StorageControllers"))
3373 )
3374 readStorageControllers(*pelmMachineChild, storageMachine);
3375 else if (pelmMachineChild->nameEquals("Snapshot"))
3376 {
3377 Snapshot snap;
3378 // this will recurse into child snapshots, if necessary
3379 readSnapshot(*pelmMachineChild, snap);
3380 llFirstSnapshot.push_back(snap);
3381 }
3382 else if (pelmMachineChild->nameEquals("Description"))
3383 machineUserData.strDescription = pelmMachineChild->getValue();
3384 else if (pelmMachineChild->nameEquals("Teleporter"))
3385 readTeleporter(pelmMachineChild, &machineUserData);
3386 else if (pelmMachineChild->nameEquals("FaultTolerance"))
3387 {
3388 Utf8Str strFaultToleranceSate;
3389 if (pelmMachineChild->getAttributeValue("state", strFaultToleranceSate))
3390 {
3391 if (strFaultToleranceSate == "master")
3392 machineUserData.enmFaultToleranceState = FaultToleranceState_Master;
3393 else
3394 if (strFaultToleranceSate == "standby")
3395 machineUserData.enmFaultToleranceState = FaultToleranceState_Standby;
3396 else
3397 machineUserData.enmFaultToleranceState = FaultToleranceState_Inactive;
3398 }
3399 pelmMachineChild->getAttributeValue("port", machineUserData.uFaultTolerancePort);
3400 pelmMachineChild->getAttributeValue("address", machineUserData.strFaultToleranceAddress);
3401 pelmMachineChild->getAttributeValue("interval", machineUserData.uFaultToleranceInterval);
3402 pelmMachineChild->getAttributeValue("password", machineUserData.strFaultTolerancePassword);
3403 }
3404 else if (pelmMachineChild->nameEquals("MediaRegistry"))
3405 readMediaRegistry(*pelmMachineChild, mediaRegistry);
3406 else if (pelmMachineChild->nameEquals("Debugging"))
3407 readDebugging(pelmMachineChild, &debugging);
3408 }
3409
3410 if (m->sv < SettingsVersion_v1_9)
3411 // go through Hardware once more to repair the settings controller structures
3412 // with data from old DVDDrive and FloppyDrive elements
3413 readDVDAndFloppies_pre1_9(*pelmHardware, storageMachine);
3414 }
3415 else
3416 throw ConfigFileError(this, &elmMachine, N_("Required Machine/@uuid or @name attributes is missing"));
3417}
3418
3419/**
3420 * Creates a <Hardware> node under elmParent and then writes out the XML
3421 * keys under that. Called for both the <Machine> node and for snapshots.
3422 * @param elmParent
3423 * @param st
3424 */
3425void MachineConfigFile::buildHardwareXML(xml::ElementNode &elmParent,
3426 const Hardware &hw,
3427 const Storage &strg)
3428{
3429 xml::ElementNode *pelmHardware = elmParent.createChild("Hardware");
3430
3431 if (m->sv >= SettingsVersion_v1_4)
3432 pelmHardware->setAttribute("version", hw.strVersion);
3433 if ( (m->sv >= SettingsVersion_v1_9)
3434 && (!hw.uuid.isEmpty())
3435 )
3436 pelmHardware->setAttribute("uuid", hw.uuid.toStringCurly());
3437
3438 xml::ElementNode *pelmCPU = pelmHardware->createChild("CPU");
3439
3440 xml::ElementNode *pelmHwVirtEx = pelmCPU->createChild("HardwareVirtEx");
3441 pelmHwVirtEx->setAttribute("enabled", hw.fHardwareVirt);
3442 if (m->sv >= SettingsVersion_v1_9)
3443 pelmHwVirtEx->setAttribute("exclusive", hw.fHardwareVirtExclusive);
3444
3445 pelmCPU->createChild("HardwareVirtExNestedPaging")->setAttribute("enabled", hw.fNestedPaging);
3446 pelmCPU->createChild("HardwareVirtExVPID")->setAttribute("enabled", hw.fVPID);
3447 pelmCPU->createChild("PAE")->setAttribute("enabled", hw.fPAE);
3448
3449 if (hw.fSyntheticCpu)
3450 pelmCPU->createChild("SyntheticCpu")->setAttribute("enabled", hw.fSyntheticCpu);
3451 pelmCPU->setAttribute("count", hw.cCPUs);
3452 if (hw.ulCpuExecutionCap != 100)
3453 pelmCPU->setAttribute("executionCap", hw.ulCpuExecutionCap);
3454
3455 /* Always save this setting as we have changed the default in 4.0 (on for large memory 64-bit systems). */
3456 pelmCPU->createChild("HardwareVirtExLargePages")->setAttribute("enabled", hw.fLargePages);
3457
3458 if (m->sv >= SettingsVersion_v1_9)
3459 pelmCPU->createChild("HardwareVirtForce")->setAttribute("enabled", hw.fHardwareVirtForce);
3460
3461 if (m->sv >= SettingsVersion_v1_10)
3462 {
3463 pelmCPU->setAttribute("hotplug", hw.fCpuHotPlug);
3464
3465 xml::ElementNode *pelmCpuTree = NULL;
3466 for (CpuList::const_iterator it = hw.llCpus.begin();
3467 it != hw.llCpus.end();
3468 ++it)
3469 {
3470 const Cpu &cpu = *it;
3471
3472 if (pelmCpuTree == NULL)
3473 pelmCpuTree = pelmCPU->createChild("CpuTree");
3474
3475 xml::ElementNode *pelmCpu = pelmCpuTree->createChild("Cpu");
3476 pelmCpu->setAttribute("id", cpu.ulId);
3477 }
3478 }
3479
3480 xml::ElementNode *pelmCpuIdTree = NULL;
3481 for (CpuIdLeafsList::const_iterator it = hw.llCpuIdLeafs.begin();
3482 it != hw.llCpuIdLeafs.end();
3483 ++it)
3484 {
3485 const CpuIdLeaf &leaf = *it;
3486
3487 if (pelmCpuIdTree == NULL)
3488 pelmCpuIdTree = pelmCPU->createChild("CpuIdTree");
3489
3490 xml::ElementNode *pelmCpuIdLeaf = pelmCpuIdTree->createChild("CpuIdLeaf");
3491 pelmCpuIdLeaf->setAttribute("id", leaf.ulId);
3492 pelmCpuIdLeaf->setAttribute("eax", leaf.ulEax);
3493 pelmCpuIdLeaf->setAttribute("ebx", leaf.ulEbx);
3494 pelmCpuIdLeaf->setAttribute("ecx", leaf.ulEcx);
3495 pelmCpuIdLeaf->setAttribute("edx", leaf.ulEdx);
3496 }
3497
3498 xml::ElementNode *pelmMemory = pelmHardware->createChild("Memory");
3499 pelmMemory->setAttribute("RAMSize", hw.ulMemorySizeMB);
3500 if (m->sv >= SettingsVersion_v1_10)
3501 {
3502 pelmMemory->setAttribute("PageFusion", hw.fPageFusionEnabled);
3503 }
3504
3505 if ( (m->sv >= SettingsVersion_v1_9)
3506 && (hw.firmwareType >= FirmwareType_EFI)
3507 )
3508 {
3509 xml::ElementNode *pelmFirmware = pelmHardware->createChild("Firmware");
3510 const char *pcszFirmware;
3511
3512 switch (hw.firmwareType)
3513 {
3514 case FirmwareType_EFI: pcszFirmware = "EFI"; break;
3515 case FirmwareType_EFI32: pcszFirmware = "EFI32"; break;
3516 case FirmwareType_EFI64: pcszFirmware = "EFI64"; break;
3517 case FirmwareType_EFIDUAL: pcszFirmware = "EFIDUAL"; break;
3518 default: pcszFirmware = "None"; break;
3519 }
3520 pelmFirmware->setAttribute("type", pcszFirmware);
3521 }
3522
3523 if ( (m->sv >= SettingsVersion_v1_10)
3524 )
3525 {
3526 xml::ElementNode *pelmHid = pelmHardware->createChild("HID");
3527 const char *pcszHid;
3528
3529 switch (hw.pointingHidType)
3530 {
3531 case PointingHidType_USBMouse: pcszHid = "USBMouse"; break;
3532 case PointingHidType_USBTablet: pcszHid = "USBTablet"; break;
3533 case PointingHidType_PS2Mouse: pcszHid = "PS2Mouse"; break;
3534 case PointingHidType_ComboMouse: pcszHid = "ComboMouse"; break;
3535 case PointingHidType_None: pcszHid = "None"; break;
3536 default: Assert(false); pcszHid = "PS2Mouse"; break;
3537 }
3538 pelmHid->setAttribute("Pointing", pcszHid);
3539
3540 switch (hw.keyboardHidType)
3541 {
3542 case KeyboardHidType_USBKeyboard: pcszHid = "USBKeyboard"; break;
3543 case KeyboardHidType_PS2Keyboard: pcszHid = "PS2Keyboard"; break;
3544 case KeyboardHidType_ComboKeyboard: pcszHid = "ComboKeyboard"; break;
3545 case KeyboardHidType_None: pcszHid = "None"; break;
3546 default: Assert(false); pcszHid = "PS2Keyboard"; break;
3547 }
3548 pelmHid->setAttribute("Keyboard", pcszHid);
3549 }
3550
3551 if ( (m->sv >= SettingsVersion_v1_10)
3552 )
3553 {
3554 xml::ElementNode *pelmHpet = pelmHardware->createChild("HPET");
3555 pelmHpet->setAttribute("enabled", hw.fHpetEnabled);
3556 }
3557
3558 if ( (m->sv >= SettingsVersion_v1_11)
3559 )
3560 {
3561 xml::ElementNode *pelmChipset = pelmHardware->createChild("Chipset");
3562 const char *pcszChipset;
3563
3564 switch (hw.chipsetType)
3565 {
3566 case ChipsetType_PIIX3: pcszChipset = "PIIX3"; break;
3567 case ChipsetType_ICH9: pcszChipset = "ICH9"; break;
3568 default: Assert(false); pcszChipset = "PIIX3"; break;
3569 }
3570 pelmChipset->setAttribute("type", pcszChipset);
3571 }
3572
3573 xml::ElementNode *pelmBoot = pelmHardware->createChild("Boot");
3574 for (BootOrderMap::const_iterator it = hw.mapBootOrder.begin();
3575 it != hw.mapBootOrder.end();
3576 ++it)
3577 {
3578 uint32_t i = it->first;
3579 DeviceType_T type = it->second;
3580 const char *pcszDevice;
3581
3582 switch (type)
3583 {
3584 case DeviceType_Floppy: pcszDevice = "Floppy"; break;
3585 case DeviceType_DVD: pcszDevice = "DVD"; break;
3586 case DeviceType_HardDisk: pcszDevice = "HardDisk"; break;
3587 case DeviceType_Network: pcszDevice = "Network"; break;
3588 default: /*case DeviceType_Null:*/ pcszDevice = "None"; break;
3589 }
3590
3591 xml::ElementNode *pelmOrder = pelmBoot->createChild("Order");
3592 pelmOrder->setAttribute("position",
3593 i + 1); // XML is 1-based but internal data is 0-based
3594 pelmOrder->setAttribute("device", pcszDevice);
3595 }
3596
3597 xml::ElementNode *pelmDisplay = pelmHardware->createChild("Display");
3598 pelmDisplay->setAttribute("VRAMSize", hw.ulVRAMSizeMB);
3599 pelmDisplay->setAttribute("monitorCount", hw.cMonitors);
3600 pelmDisplay->setAttribute("accelerate3D", hw.fAccelerate3D);
3601
3602 if (m->sv >= SettingsVersion_v1_8)
3603 pelmDisplay->setAttribute("accelerate2DVideo", hw.fAccelerate2DVideo);
3604
3605 xml::ElementNode *pelmVRDE = pelmHardware->createChild("RemoteDisplay");
3606 pelmVRDE->setAttribute("enabled", hw.vrdeSettings.fEnabled);
3607 if (m->sv < SettingsVersion_v1_11)
3608 {
3609 /* In VBox 4.0 these attributes are replaced with "Properties". */
3610 Utf8Str strPort;
3611 StringsMap::const_iterator it = hw.vrdeSettings.mapProperties.find("TCP/Ports");
3612 if (it != hw.vrdeSettings.mapProperties.end())
3613 strPort = it->second;
3614 if (!strPort.length())
3615 strPort = "3389";
3616 pelmVRDE->setAttribute("port", strPort);
3617
3618 Utf8Str strAddress;
3619 it = hw.vrdeSettings.mapProperties.find("TCP/Address");
3620 if (it != hw.vrdeSettings.mapProperties.end())
3621 strAddress = it->second;
3622 if (strAddress.length())
3623 pelmVRDE->setAttribute("netAddress", strAddress);
3624 }
3625 const char *pcszAuthType;
3626 switch (hw.vrdeSettings.authType)
3627 {
3628 case AuthType_Guest: pcszAuthType = "Guest"; break;
3629 case AuthType_External: pcszAuthType = "External"; break;
3630 default: /*case AuthType_Null:*/ pcszAuthType = "Null"; break;
3631 }
3632 pelmVRDE->setAttribute("authType", pcszAuthType);
3633
3634 if (hw.vrdeSettings.ulAuthTimeout != 0)
3635 pelmVRDE->setAttribute("authTimeout", hw.vrdeSettings.ulAuthTimeout);
3636 if (hw.vrdeSettings.fAllowMultiConnection)
3637 pelmVRDE->setAttribute("allowMultiConnection", hw.vrdeSettings.fAllowMultiConnection);
3638 if (hw.vrdeSettings.fReuseSingleConnection)
3639 pelmVRDE->setAttribute("reuseSingleConnection", hw.vrdeSettings.fReuseSingleConnection);
3640
3641 if (m->sv == SettingsVersion_v1_10)
3642 {
3643 xml::ElementNode *pelmVideoChannel = pelmVRDE->createChild("VideoChannel");
3644
3645 /* In 4.0 videochannel settings were replaced with properties, so look at properties. */
3646 Utf8Str str;
3647 StringsMap::const_iterator it = hw.vrdeSettings.mapProperties.find("VideoChannel/Enabled");
3648 if (it != hw.vrdeSettings.mapProperties.end())
3649 str = it->second;
3650 bool fVideoChannel = RTStrICmp(str.c_str(), "true") == 0
3651 || RTStrCmp(str.c_str(), "1") == 0;
3652 pelmVideoChannel->setAttribute("enabled", fVideoChannel);
3653
3654 it = hw.vrdeSettings.mapProperties.find("VideoChannel/Quality");
3655 if (it != hw.vrdeSettings.mapProperties.end())
3656 str = it->second;
3657 uint32_t ulVideoChannelQuality = RTStrToUInt32(str.c_str()); /* This returns 0 on invalid string which is ok. */
3658 if (ulVideoChannelQuality == 0)
3659 ulVideoChannelQuality = 75;
3660 else
3661 ulVideoChannelQuality = RT_CLAMP(ulVideoChannelQuality, 10, 100);
3662 pelmVideoChannel->setAttribute("quality", ulVideoChannelQuality);
3663 }
3664 if (m->sv >= SettingsVersion_v1_11)
3665 {
3666 if (hw.vrdeSettings.strAuthLibrary.length())
3667 pelmVRDE->setAttribute("authLibrary", hw.vrdeSettings.strAuthLibrary);
3668 if (hw.vrdeSettings.strVrdeExtPack.isNotEmpty())
3669 pelmVRDE->setAttribute("VRDEExtPack", hw.vrdeSettings.strVrdeExtPack);
3670 if (hw.vrdeSettings.mapProperties.size() > 0)
3671 {
3672 xml::ElementNode *pelmProperties = pelmVRDE->createChild("VRDEProperties");
3673 for (StringsMap::const_iterator it = hw.vrdeSettings.mapProperties.begin();
3674 it != hw.vrdeSettings.mapProperties.end();
3675 ++it)
3676 {
3677 const Utf8Str &strName = it->first;
3678 const Utf8Str &strValue = it->second;
3679 xml::ElementNode *pelm = pelmProperties->createChild("Property");
3680 pelm->setAttribute("name", strName);
3681 pelm->setAttribute("value", strValue);
3682 }
3683 }
3684 }
3685
3686 xml::ElementNode *pelmBIOS = pelmHardware->createChild("BIOS");
3687 pelmBIOS->createChild("ACPI")->setAttribute("enabled", hw.biosSettings.fACPIEnabled);
3688 pelmBIOS->createChild("IOAPIC")->setAttribute("enabled", hw.biosSettings.fIOAPICEnabled);
3689
3690 xml::ElementNode *pelmLogo = pelmBIOS->createChild("Logo");
3691 pelmLogo->setAttribute("fadeIn", hw.biosSettings.fLogoFadeIn);
3692 pelmLogo->setAttribute("fadeOut", hw.biosSettings.fLogoFadeOut);
3693 pelmLogo->setAttribute("displayTime", hw.biosSettings.ulLogoDisplayTime);
3694 if (hw.biosSettings.strLogoImagePath.length())
3695 pelmLogo->setAttribute("imagePath", hw.biosSettings.strLogoImagePath);
3696
3697 const char *pcszBootMenu;
3698 switch (hw.biosSettings.biosBootMenuMode)
3699 {
3700 case BIOSBootMenuMode_Disabled: pcszBootMenu = "Disabled"; break;
3701 case BIOSBootMenuMode_MenuOnly: pcszBootMenu = "MenuOnly"; break;
3702 default: /*BIOSBootMenuMode_MessageAndMenu*/ pcszBootMenu = "MessageAndMenu"; break;
3703 }
3704 pelmBIOS->createChild("BootMenu")->setAttribute("mode", pcszBootMenu);
3705 pelmBIOS->createChild("TimeOffset")->setAttribute("value", hw.biosSettings.llTimeOffset);
3706 pelmBIOS->createChild("PXEDebug")->setAttribute("enabled", hw.biosSettings.fPXEDebugEnabled);
3707
3708 if (m->sv < SettingsVersion_v1_9)
3709 {
3710 // settings formats before 1.9 had separate DVDDrive and FloppyDrive items under Hardware;
3711 // run thru the storage controllers to see if we have a DVD or floppy drives
3712 size_t cDVDs = 0;
3713 size_t cFloppies = 0;
3714
3715 xml::ElementNode *pelmDVD = pelmHardware->createChild("DVDDrive");
3716 xml::ElementNode *pelmFloppy = pelmHardware->createChild("FloppyDrive");
3717
3718 for (StorageControllersList::const_iterator it = strg.llStorageControllers.begin();
3719 it != strg.llStorageControllers.end();
3720 ++it)
3721 {
3722 const StorageController &sctl = *it;
3723 // in old settings format, the DVD drive could only have been under the IDE controller
3724 if (sctl.storageBus == StorageBus_IDE)
3725 {
3726 for (AttachedDevicesList::const_iterator it2 = sctl.llAttachedDevices.begin();
3727 it2 != sctl.llAttachedDevices.end();
3728 ++it2)
3729 {
3730 const AttachedDevice &att = *it2;
3731 if (att.deviceType == DeviceType_DVD)
3732 {
3733 if (cDVDs > 0)
3734 throw ConfigFileError(this, NULL, N_("Internal error: cannot save more than one DVD drive with old settings format"));
3735
3736 ++cDVDs;
3737
3738 pelmDVD->setAttribute("passthrough", att.fPassThrough);
3739 if (att.fTempEject)
3740 pelmDVD->setAttribute("tempeject", att.fTempEject);
3741 if (!att.uuid.isEmpty())
3742 pelmDVD->createChild("Image")->setAttribute("uuid", att.uuid.toStringCurly());
3743 else if (att.strHostDriveSrc.length())
3744 pelmDVD->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
3745 }
3746 }
3747 }
3748 else if (sctl.storageBus == StorageBus_Floppy)
3749 {
3750 size_t cFloppiesHere = sctl.llAttachedDevices.size();
3751 if (cFloppiesHere > 1)
3752 throw ConfigFileError(this, NULL, N_("Internal error: floppy controller cannot have more than one device attachment"));
3753 if (cFloppiesHere)
3754 {
3755 const AttachedDevice &att = sctl.llAttachedDevices.front();
3756 pelmFloppy->setAttribute("enabled", true);
3757 if (!att.uuid.isEmpty())
3758 pelmFloppy->createChild("Image")->setAttribute("uuid", att.uuid.toStringCurly());
3759 else if (att.strHostDriveSrc.length())
3760 pelmFloppy->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
3761 }
3762
3763 cFloppies += cFloppiesHere;
3764 }
3765 }
3766
3767 if (cFloppies == 0)
3768 pelmFloppy->setAttribute("enabled", false);
3769 else if (cFloppies > 1)
3770 throw ConfigFileError(this, NULL, N_("Internal error: cannot save more than one floppy drive with old settings format"));
3771 }
3772
3773 xml::ElementNode *pelmUSB = pelmHardware->createChild("USBController");
3774 pelmUSB->setAttribute("enabled", hw.usbController.fEnabled);
3775 pelmUSB->setAttribute("enabledEhci", hw.usbController.fEnabledEHCI);
3776
3777 buildUSBDeviceFilters(*pelmUSB,
3778 hw.usbController.llDeviceFilters,
3779 false); // fHostMode
3780
3781 xml::ElementNode *pelmNetwork = pelmHardware->createChild("Network");
3782 for (NetworkAdaptersList::const_iterator it = hw.llNetworkAdapters.begin();
3783 it != hw.llNetworkAdapters.end();
3784 ++it)
3785 {
3786 const NetworkAdapter &nic = *it;
3787
3788 xml::ElementNode *pelmAdapter = pelmNetwork->createChild("Adapter");
3789 pelmAdapter->setAttribute("slot", nic.ulSlot);
3790 pelmAdapter->setAttribute("enabled", nic.fEnabled);
3791 pelmAdapter->setAttribute("MACAddress", nic.strMACAddress);
3792 pelmAdapter->setAttribute("cable", nic.fCableConnected);
3793 pelmAdapter->setAttribute("speed", nic.ulLineSpeed);
3794 if (nic.ulBootPriority != 0)
3795 {
3796 pelmAdapter->setAttribute("bootPriority", nic.ulBootPriority);
3797 }
3798 if (nic.fTraceEnabled)
3799 {
3800 pelmAdapter->setAttribute("trace", nic.fTraceEnabled);
3801 pelmAdapter->setAttribute("tracefile", nic.strTraceFile);
3802 }
3803 if (nic.strBandwidthGroup.isNotEmpty())
3804 pelmAdapter->setAttribute("bandwidthGroup", nic.strBandwidthGroup);
3805
3806 const char *pszPolicy;
3807 switch (nic.enmPromiscModePolicy)
3808 {
3809 case NetworkAdapterPromiscModePolicy_Deny: pszPolicy = NULL; break;
3810 case NetworkAdapterPromiscModePolicy_AllowNetwork: pszPolicy = "AllowNetwork"; break;
3811 case NetworkAdapterPromiscModePolicy_AllowAll: pszPolicy = "AllowAll"; break;
3812 default: pszPolicy = NULL; AssertFailed(); break;
3813 }
3814 if (pszPolicy)
3815 pelmAdapter->setAttribute("promiscuousModePolicy", pszPolicy);
3816
3817 const char *pcszType;
3818 switch (nic.type)
3819 {
3820 case NetworkAdapterType_Am79C973: pcszType = "Am79C973"; break;
3821 case NetworkAdapterType_I82540EM: pcszType = "82540EM"; break;
3822 case NetworkAdapterType_I82543GC: pcszType = "82543GC"; break;
3823 case NetworkAdapterType_I82545EM: pcszType = "82545EM"; break;
3824 case NetworkAdapterType_Virtio: pcszType = "virtio"; break;
3825 default: /*case NetworkAdapterType_Am79C970A:*/ pcszType = "Am79C970A"; break;
3826 }
3827 pelmAdapter->setAttribute("type", pcszType);
3828
3829 xml::ElementNode *pelmNAT;
3830 if (m->sv < SettingsVersion_v1_10)
3831 {
3832 switch (nic.mode)
3833 {
3834 case NetworkAttachmentType_NAT:
3835 pelmNAT = pelmAdapter->createChild("NAT");
3836 if (nic.nat.strNetwork.length())
3837 pelmNAT->setAttribute("network", nic.nat.strNetwork);
3838 break;
3839
3840 case NetworkAttachmentType_Bridged:
3841 pelmAdapter->createChild("BridgedInterface")->setAttribute("name", nic.strBridgedName);
3842 break;
3843
3844 case NetworkAttachmentType_Internal:
3845 pelmAdapter->createChild("InternalNetwork")->setAttribute("name", nic.strInternalNetworkName);
3846 break;
3847
3848 case NetworkAttachmentType_HostOnly:
3849 pelmAdapter->createChild("HostOnlyInterface")->setAttribute("name", nic.strHostOnlyName);
3850 break;
3851
3852 default: /*case NetworkAttachmentType_Null:*/
3853 break;
3854 }
3855 }
3856 else
3857 {
3858 /* m->sv >= SettingsVersion_v1_10 */
3859 xml::ElementNode *pelmDisabledNode = NULL;
3860 pelmDisabledNode = pelmAdapter->createChild("DisabledModes");
3861 if (nic.mode != NetworkAttachmentType_NAT)
3862 buildNetworkXML(NetworkAttachmentType_NAT, *pelmDisabledNode, false, nic);
3863 if (nic.mode != NetworkAttachmentType_Bridged)
3864 buildNetworkXML(NetworkAttachmentType_Bridged, *pelmDisabledNode, false, nic);
3865 if (nic.mode != NetworkAttachmentType_Internal)
3866 buildNetworkXML(NetworkAttachmentType_HostOnly, *pelmDisabledNode, false, nic);
3867 if (nic.mode != NetworkAttachmentType_HostOnly)
3868 buildNetworkXML(NetworkAttachmentType_HostOnly, *pelmDisabledNode, false, nic);
3869 if (nic.mode != NetworkAttachmentType_Generic)
3870 buildNetworkXML(NetworkAttachmentType_Generic, *pelmDisabledNode, false, nic);
3871 buildNetworkXML(nic.mode, *pelmAdapter, true, nic);
3872 }
3873 }
3874
3875 xml::ElementNode *pelmPorts = pelmHardware->createChild("UART");
3876 for (SerialPortsList::const_iterator it = hw.llSerialPorts.begin();
3877 it != hw.llSerialPorts.end();
3878 ++it)
3879 {
3880 const SerialPort &port = *it;
3881 xml::ElementNode *pelmPort = pelmPorts->createChild("Port");
3882 pelmPort->setAttribute("slot", port.ulSlot);
3883 pelmPort->setAttribute("enabled", port.fEnabled);
3884 pelmPort->setAttributeHex("IOBase", port.ulIOBase);
3885 pelmPort->setAttribute("IRQ", port.ulIRQ);
3886
3887 const char *pcszHostMode;
3888 switch (port.portMode)
3889 {
3890 case PortMode_HostPipe: pcszHostMode = "HostPipe"; break;
3891 case PortMode_HostDevice: pcszHostMode = "HostDevice"; break;
3892 case PortMode_RawFile: pcszHostMode = "RawFile"; break;
3893 default: /*case PortMode_Disconnected:*/ pcszHostMode = "Disconnected"; break;
3894 }
3895 switch (port.portMode)
3896 {
3897 case PortMode_HostPipe:
3898 pelmPort->setAttribute("server", port.fServer);
3899 /* no break */
3900 case PortMode_HostDevice:
3901 case PortMode_RawFile:
3902 pelmPort->setAttribute("path", port.strPath);
3903 break;
3904
3905 default:
3906 break;
3907 }
3908 pelmPort->setAttribute("hostMode", pcszHostMode);
3909 }
3910
3911 pelmPorts = pelmHardware->createChild("LPT");
3912 for (ParallelPortsList::const_iterator it = hw.llParallelPorts.begin();
3913 it != hw.llParallelPorts.end();
3914 ++it)
3915 {
3916 const ParallelPort &port = *it;
3917 xml::ElementNode *pelmPort = pelmPorts->createChild("Port");
3918 pelmPort->setAttribute("slot", port.ulSlot);
3919 pelmPort->setAttribute("enabled", port.fEnabled);
3920 pelmPort->setAttributeHex("IOBase", port.ulIOBase);
3921 pelmPort->setAttribute("IRQ", port.ulIRQ);
3922 if (port.strPath.length())
3923 pelmPort->setAttribute("path", port.strPath);
3924 }
3925
3926 xml::ElementNode *pelmAudio = pelmHardware->createChild("AudioAdapter");
3927 const char *pcszController;
3928 switch (hw.audioAdapter.controllerType)
3929 {
3930 case AudioControllerType_SB16:
3931 pcszController = "SB16";
3932 break;
3933 case AudioControllerType_HDA:
3934 if (m->sv >= SettingsVersion_v1_11)
3935 {
3936 pcszController = "HDA";
3937 break;
3938 }
3939 /* fall through */
3940 case AudioControllerType_AC97:
3941 default:
3942 pcszController = "AC97";
3943 break;
3944 }
3945 pelmAudio->setAttribute("controller", pcszController);
3946
3947 if (m->sv >= SettingsVersion_v1_10)
3948 {
3949 xml::ElementNode *pelmRTC = pelmHardware->createChild("RTC");
3950 pelmRTC->setAttribute("localOrUTC", machineUserData.fRTCUseUTC ? "UTC" : "local");
3951 }
3952
3953 const char *pcszDriver;
3954 switch (hw.audioAdapter.driverType)
3955 {
3956 case AudioDriverType_WinMM: pcszDriver = "WinMM"; break;
3957 case AudioDriverType_DirectSound: pcszDriver = "DirectSound"; break;
3958 case AudioDriverType_SolAudio: pcszDriver = "SolAudio"; break;
3959 case AudioDriverType_ALSA: pcszDriver = "ALSA"; break;
3960 case AudioDriverType_Pulse: pcszDriver = "Pulse"; break;
3961 case AudioDriverType_OSS: pcszDriver = "OSS"; break;
3962 case AudioDriverType_CoreAudio: pcszDriver = "CoreAudio"; break;
3963 case AudioDriverType_MMPM: pcszDriver = "MMPM"; break;
3964 default: /*case AudioDriverType_Null:*/ pcszDriver = "Null"; break;
3965 }
3966 pelmAudio->setAttribute("driver", pcszDriver);
3967
3968 pelmAudio->setAttribute("enabled", hw.audioAdapter.fEnabled);
3969
3970 xml::ElementNode *pelmSharedFolders = pelmHardware->createChild("SharedFolders");
3971 for (SharedFoldersList::const_iterator it = hw.llSharedFolders.begin();
3972 it != hw.llSharedFolders.end();
3973 ++it)
3974 {
3975 const SharedFolder &sf = *it;
3976 xml::ElementNode *pelmThis = pelmSharedFolders->createChild("SharedFolder");
3977 pelmThis->setAttribute("name", sf.strName);
3978 pelmThis->setAttribute("hostPath", sf.strHostPath);
3979 pelmThis->setAttribute("writable", sf.fWritable);
3980 pelmThis->setAttribute("autoMount", sf.fAutoMount);
3981 }
3982
3983 xml::ElementNode *pelmClip = pelmHardware->createChild("Clipboard");
3984 const char *pcszClip;
3985 switch (hw.clipboardMode)
3986 {
3987 case ClipboardMode_Disabled: pcszClip = "Disabled"; break;
3988 case ClipboardMode_HostToGuest: pcszClip = "HostToGuest"; break;
3989 case ClipboardMode_GuestToHost: pcszClip = "GuestToHost"; break;
3990 default: /*case ClipboardMode_Bidirectional:*/ pcszClip = "Bidirectional"; break;
3991 }
3992 pelmClip->setAttribute("mode", pcszClip);
3993
3994 if (m->sv >= SettingsVersion_v1_10)
3995 {
3996 xml::ElementNode *pelmIo = pelmHardware->createChild("IO");
3997 xml::ElementNode *pelmIoCache;
3998
3999 pelmIoCache = pelmIo->createChild("IoCache");
4000 pelmIoCache->setAttribute("enabled", hw.ioSettings.fIoCacheEnabled);
4001 pelmIoCache->setAttribute("size", hw.ioSettings.ulIoCacheSize);
4002
4003 if (m->sv >= SettingsVersion_v1_11)
4004 {
4005 xml::ElementNode *pelmBandwidthGroups = pelmIo->createChild("BandwidthGroups");
4006 for (BandwidthGroupList::const_iterator it = hw.ioSettings.llBandwidthGroups.begin();
4007 it != hw.ioSettings.llBandwidthGroups.end();
4008 ++it)
4009 {
4010 const BandwidthGroup &gr = *it;
4011 const char *pcszType;
4012 xml::ElementNode *pelmThis = pelmBandwidthGroups->createChild("BandwidthGroup");
4013 pelmThis->setAttribute("name", gr.strName);
4014 switch (gr.enmType)
4015 {
4016 case BandwidthGroupType_Network: pcszType = "Network"; break;
4017 default: /* BandwidthGrouptype_Disk */ pcszType = "Disk"; break;
4018 }
4019 pelmThis->setAttribute("type", pcszType);
4020 pelmThis->setAttribute("maxMbPerSec", gr.cMaxMbPerSec);
4021 }
4022 }
4023 }
4024
4025 if (m->sv >= SettingsVersion_v1_12)
4026 {
4027 xml::ElementNode *pelmPci = pelmHardware->createChild("HostPci");
4028 xml::ElementNode *pelmPciDevices = pelmPci->createChild("Devices");
4029
4030 for (HostPciDeviceAttachmentList::const_iterator it = hw.pciAttachments.begin();
4031 it != hw.pciAttachments.end();
4032 ++it)
4033 {
4034 const HostPciDeviceAttachment &hpda = *it;
4035
4036 xml::ElementNode *pelmThis = pelmPciDevices->createChild("Device");
4037
4038 pelmThis->setAttribute("host", hpda.uHostAddress);
4039 pelmThis->setAttribute("guest", hpda.uGuestAddress);
4040 pelmThis->setAttribute("name", hpda.strDeviceName);
4041 }
4042 }
4043
4044 xml::ElementNode *pelmGuest = pelmHardware->createChild("Guest");
4045 pelmGuest->setAttribute("memoryBalloonSize", hw.ulMemoryBalloonSize);
4046
4047 xml::ElementNode *pelmGuestProps = pelmHardware->createChild("GuestProperties");
4048 for (GuestPropertiesList::const_iterator it = hw.llGuestProperties.begin();
4049 it != hw.llGuestProperties.end();
4050 ++it)
4051 {
4052 const GuestProperty &prop = *it;
4053 xml::ElementNode *pelmProp = pelmGuestProps->createChild("GuestProperty");
4054 pelmProp->setAttribute("name", prop.strName);
4055 pelmProp->setAttribute("value", prop.strValue);
4056 pelmProp->setAttribute("timestamp", prop.timestamp);
4057 pelmProp->setAttribute("flags", prop.strFlags);
4058 }
4059
4060 if (hw.strNotificationPatterns.length())
4061 pelmGuestProps->setAttribute("notificationPatterns", hw.strNotificationPatterns);
4062}
4063
4064/**
4065 * Fill a <Network> node. Only relevant for XML version >= v1_10.
4066 * @param mode
4067 * @param elmParent
4068 * @param fEnabled
4069 * @param nic
4070 */
4071void MachineConfigFile::buildNetworkXML(NetworkAttachmentType_T mode,
4072 xml::ElementNode &elmParent,
4073 bool fEnabled,
4074 const NetworkAdapter &nic)
4075{
4076 switch (mode)
4077 {
4078 case NetworkAttachmentType_NAT:
4079 xml::ElementNode *pelmNAT;
4080 pelmNAT = elmParent.createChild("NAT");
4081
4082 if (nic.nat.strNetwork.length())
4083 pelmNAT->setAttribute("network", nic.nat.strNetwork);
4084 if (nic.nat.strBindIP.length())
4085 pelmNAT->setAttribute("hostip", nic.nat.strBindIP);
4086 if (nic.nat.u32Mtu)
4087 pelmNAT->setAttribute("mtu", nic.nat.u32Mtu);
4088 if (nic.nat.u32SockRcv)
4089 pelmNAT->setAttribute("sockrcv", nic.nat.u32SockRcv);
4090 if (nic.nat.u32SockSnd)
4091 pelmNAT->setAttribute("socksnd", nic.nat.u32SockSnd);
4092 if (nic.nat.u32TcpRcv)
4093 pelmNAT->setAttribute("tcprcv", nic.nat.u32TcpRcv);
4094 if (nic.nat.u32TcpSnd)
4095 pelmNAT->setAttribute("tcpsnd", nic.nat.u32TcpSnd);
4096 xml::ElementNode *pelmDNS;
4097 pelmDNS = pelmNAT->createChild("DNS");
4098 pelmDNS->setAttribute("pass-domain", nic.nat.fDnsPassDomain);
4099 pelmDNS->setAttribute("use-proxy", nic.nat.fDnsProxy);
4100 pelmDNS->setAttribute("use-host-resolver", nic.nat.fDnsUseHostResolver);
4101
4102 xml::ElementNode *pelmAlias;
4103 pelmAlias = pelmNAT->createChild("Alias");
4104 pelmAlias->setAttribute("logging", nic.nat.fAliasLog);
4105 pelmAlias->setAttribute("proxy-only", nic.nat.fAliasProxyOnly);
4106 pelmAlias->setAttribute("use-same-ports", nic.nat.fAliasUseSamePorts);
4107
4108 if ( nic.nat.strTftpPrefix.length()
4109 || nic.nat.strTftpBootFile.length()
4110 || nic.nat.strTftpNextServer.length())
4111 {
4112 xml::ElementNode *pelmTFTP;
4113 pelmTFTP = pelmNAT->createChild("TFTP");
4114 if (nic.nat.strTftpPrefix.length())
4115 pelmTFTP->setAttribute("prefix", nic.nat.strTftpPrefix);
4116 if (nic.nat.strTftpBootFile.length())
4117 pelmTFTP->setAttribute("boot-file", nic.nat.strTftpBootFile);
4118 if (nic.nat.strTftpNextServer.length())
4119 pelmTFTP->setAttribute("next-server", nic.nat.strTftpNextServer);
4120 }
4121 for (NATRuleList::const_iterator rule = nic.nat.llRules.begin();
4122 rule != nic.nat.llRules.end(); ++rule)
4123 {
4124 xml::ElementNode *pelmPF;
4125 pelmPF = pelmNAT->createChild("Forwarding");
4126 if ((*rule).strName.length())
4127 pelmPF->setAttribute("name", (*rule).strName);
4128 pelmPF->setAttribute("proto", (*rule).proto);
4129 if ((*rule).strHostIP.length())
4130 pelmPF->setAttribute("hostip", (*rule).strHostIP);
4131 if ((*rule).u16HostPort)
4132 pelmPF->setAttribute("hostport", (*rule).u16HostPort);
4133 if ((*rule).strGuestIP.length())
4134 pelmPF->setAttribute("guestip", (*rule).strGuestIP);
4135 if ((*rule).u16GuestPort)
4136 pelmPF->setAttribute("guestport", (*rule).u16GuestPort);
4137 }
4138 break;
4139
4140 case NetworkAttachmentType_Bridged:
4141 if (fEnabled || !nic.strBridgedName.isEmpty())
4142 elmParent.createChild("BridgedInterface")->setAttribute("name", nic.strBridgedName);
4143 break;
4144
4145 case NetworkAttachmentType_Internal:
4146 if (fEnabled || !nic.strInternalNetworkName.isEmpty())
4147 elmParent.createChild("InternalNetwork")->setAttribute("name", nic.strInternalNetworkName);
4148 break;
4149
4150 case NetworkAttachmentType_HostOnly:
4151 if (fEnabled || !nic.strHostOnlyName.isEmpty())
4152 elmParent.createChild("HostOnlyInterface")->setAttribute("name", nic.strHostOnlyName);
4153 break;
4154
4155 case NetworkAttachmentType_Generic:
4156 if (fEnabled || !nic.strGenericDriver.isEmpty() || nic.genericProperties.size())
4157 {
4158 xml::ElementNode *pelmMode = elmParent.createChild("GenericInterface");
4159 pelmMode->setAttribute("driver", nic.strGenericDriver);
4160 for (StringsMap::const_iterator it = nic.genericProperties.begin();
4161 it != nic.genericProperties.end();
4162 ++it)
4163 {
4164 xml::ElementNode *pelmProp = pelmMode->createChild("Property");
4165 pelmProp->setAttribute("name", it->first);
4166 pelmProp->setAttribute("value", it->second);
4167 }
4168 }
4169 break;
4170
4171 default: /*case NetworkAttachmentType_Null:*/
4172 break;
4173 }
4174}
4175
4176/**
4177 * Creates a <StorageControllers> node under elmParent and then writes out the XML
4178 * keys under that. Called for both the <Machine> node and for snapshots.
4179 * @param elmParent
4180 * @param st
4181 * @param fSkipRemovableMedia If true, DVD and floppy attachments are skipped and
4182 * an empty drive is always written instead. This is for the OVF export case.
4183 * This parameter is ignored unless the settings version is at least v1.9, which
4184 * is always the case when this gets called for OVF export.
4185 * @param pllElementsWithUuidAttributes If not NULL, must point to a list of element node
4186 * pointers to which we will append all elements that we created here that contain
4187 * UUID attributes. This allows the OVF export code to quickly replace the internal
4188 * media UUIDs with the UUIDs of the media that were exported.
4189 */
4190void MachineConfigFile::buildStorageControllersXML(xml::ElementNode &elmParent,
4191 const Storage &st,
4192 bool fSkipRemovableMedia,
4193 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes)
4194{
4195 xml::ElementNode *pelmStorageControllers = elmParent.createChild("StorageControllers");
4196
4197 for (StorageControllersList::const_iterator it = st.llStorageControllers.begin();
4198 it != st.llStorageControllers.end();
4199 ++it)
4200 {
4201 const StorageController &sc = *it;
4202
4203 if ( (m->sv < SettingsVersion_v1_9)
4204 && (sc.controllerType == StorageControllerType_I82078)
4205 )
4206 // floppy controller already got written into <Hardware>/<FloppyController> in writeHardware()
4207 // for pre-1.9 settings
4208 continue;
4209
4210 xml::ElementNode *pelmController = pelmStorageControllers->createChild("StorageController");
4211 com::Utf8Str name = sc.strName;
4212 if (m->sv < SettingsVersion_v1_8)
4213 {
4214 // pre-1.8 settings use shorter controller names, they are
4215 // expanded when reading the settings
4216 if (name == "IDE Controller")
4217 name = "IDE";
4218 else if (name == "SATA Controller")
4219 name = "SATA";
4220 else if (name == "SCSI Controller")
4221 name = "SCSI";
4222 }
4223 pelmController->setAttribute("name", sc.strName);
4224
4225 const char *pcszType;
4226 switch (sc.controllerType)
4227 {
4228 case StorageControllerType_IntelAhci: pcszType = "AHCI"; break;
4229 case StorageControllerType_LsiLogic: pcszType = "LsiLogic"; break;
4230 case StorageControllerType_BusLogic: pcszType = "BusLogic"; break;
4231 case StorageControllerType_PIIX4: pcszType = "PIIX4"; break;
4232 case StorageControllerType_ICH6: pcszType = "ICH6"; break;
4233 case StorageControllerType_I82078: pcszType = "I82078"; break;
4234 case StorageControllerType_LsiLogicSas: pcszType = "LsiLogicSas"; break;
4235 default: /*case StorageControllerType_PIIX3:*/ pcszType = "PIIX3"; break;
4236 }
4237 pelmController->setAttribute("type", pcszType);
4238
4239 pelmController->setAttribute("PortCount", sc.ulPortCount);
4240
4241 if (m->sv >= SettingsVersion_v1_9)
4242 if (sc.ulInstance)
4243 pelmController->setAttribute("Instance", sc.ulInstance);
4244
4245 if (m->sv >= SettingsVersion_v1_10)
4246 pelmController->setAttribute("useHostIOCache", sc.fUseHostIOCache);
4247
4248 if (m->sv >= SettingsVersion_v1_11)
4249 pelmController->setAttribute("Bootable", sc.fBootable);
4250
4251 if (sc.controllerType == StorageControllerType_IntelAhci)
4252 {
4253 pelmController->setAttribute("IDE0MasterEmulationPort", sc.lIDE0MasterEmulationPort);
4254 pelmController->setAttribute("IDE0SlaveEmulationPort", sc.lIDE0SlaveEmulationPort);
4255 pelmController->setAttribute("IDE1MasterEmulationPort", sc.lIDE1MasterEmulationPort);
4256 pelmController->setAttribute("IDE1SlaveEmulationPort", sc.lIDE1SlaveEmulationPort);
4257 }
4258
4259 for (AttachedDevicesList::const_iterator it2 = sc.llAttachedDevices.begin();
4260 it2 != sc.llAttachedDevices.end();
4261 ++it2)
4262 {
4263 const AttachedDevice &att = *it2;
4264
4265 // For settings version before 1.9, DVDs and floppies are in hardware, not storage controllers,
4266 // so we shouldn't write them here; we only get here for DVDs though because we ruled out
4267 // the floppy controller at the top of the loop
4268 if ( att.deviceType == DeviceType_DVD
4269 && m->sv < SettingsVersion_v1_9
4270 )
4271 continue;
4272
4273 xml::ElementNode *pelmDevice = pelmController->createChild("AttachedDevice");
4274
4275 pcszType = NULL;
4276
4277 switch (att.deviceType)
4278 {
4279 case DeviceType_HardDisk:
4280 pcszType = "HardDisk";
4281 if (att.fNonRotational)
4282 pelmDevice->setAttribute("nonrotational", att.fNonRotational);
4283 if (att.fDiscard)
4284 pelmDevice->setAttribute("discard", att.fDiscard);
4285 break;
4286
4287 case DeviceType_DVD:
4288 pcszType = "DVD";
4289 pelmDevice->setAttribute("passthrough", att.fPassThrough);
4290 if (att.fTempEject)
4291 pelmDevice->setAttribute("tempeject", att.fTempEject);
4292 break;
4293
4294 case DeviceType_Floppy:
4295 pcszType = "Floppy";
4296 break;
4297 }
4298
4299 pelmDevice->setAttribute("type", pcszType);
4300
4301 pelmDevice->setAttribute("port", att.lPort);
4302 pelmDevice->setAttribute("device", att.lDevice);
4303
4304 if (att.strBwGroup.length())
4305 pelmDevice->setAttribute("bandwidthGroup", att.strBwGroup);
4306
4307 // attached image, if any
4308 if ( !att.uuid.isEmpty()
4309 && ( att.deviceType == DeviceType_HardDisk
4310 || !fSkipRemovableMedia
4311 )
4312 )
4313 {
4314 xml::ElementNode *pelmImage = pelmDevice->createChild("Image");
4315 pelmImage->setAttribute("uuid", att.uuid.toStringCurly());
4316
4317 // if caller wants a list of UUID elements, give it to them
4318 if (pllElementsWithUuidAttributes)
4319 pllElementsWithUuidAttributes->push_back(pelmImage);
4320 }
4321 else if ( (m->sv >= SettingsVersion_v1_9)
4322 && (att.strHostDriveSrc.length())
4323 )
4324 pelmDevice->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
4325 }
4326 }
4327}
4328
4329/**
4330 * Creates a <Debugging> node under elmParent and then writes out the XML
4331 * keys under that. Called for both the <Machine> node and for snapshots.
4332 *
4333 * @param pElmParent Pointer to the parent element.
4334 * @param pDbg Pointer to the debugging settings.
4335 */
4336void MachineConfigFile::buildDebuggingXML(xml::ElementNode *pElmParent, const Debugging *pDbg)
4337{
4338 if (m->sv < SettingsVersion_v1_13 || pDbg->areDefaultSettings())
4339 return;
4340
4341 xml::ElementNode *pElmDebugging = pElmParent->createChild("Debugging");
4342 xml::ElementNode *pElmTracing = pElmDebugging->createChild("Tracing");
4343 pElmTracing->setAttribute("enabled", pDbg->fTracingEnabled);
4344 pElmTracing->setAttribute("allowTracingToAccessVM", pDbg->fAllowTracingToAccessVM);
4345 pElmTracing->setAttribute("config", pDbg->strTracingConfig);
4346}
4347
4348/**
4349 * Writes a single snapshot into the DOM tree. Initially this gets called from MachineConfigFile::write()
4350 * for the root snapshot of a machine, if present; elmParent then points to the <Snapshots> node under the
4351 * <Machine> node to which <Snapshot> must be added. This may then recurse for child snapshots.
4352 * @param elmParent
4353 * @param snap
4354 */
4355void MachineConfigFile::buildSnapshotXML(xml::ElementNode &elmParent,
4356 const Snapshot &snap)
4357{
4358 xml::ElementNode *pelmSnapshot = elmParent.createChild("Snapshot");
4359
4360 pelmSnapshot->setAttribute("uuid", snap.uuid.toStringCurly());
4361 pelmSnapshot->setAttribute("name", snap.strName);
4362 pelmSnapshot->setAttribute("timeStamp", makeString(snap.timestamp));
4363
4364 if (snap.strStateFile.length())
4365 pelmSnapshot->setAttributePath("stateFile", snap.strStateFile);
4366
4367 if (snap.strDescription.length())
4368 pelmSnapshot->createChild("Description")->addContent(snap.strDescription);
4369
4370 buildHardwareXML(*pelmSnapshot, snap.hardware, snap.storage);
4371 buildStorageControllersXML(*pelmSnapshot,
4372 snap.storage,
4373 false /* fSkipRemovableMedia */,
4374 NULL); /* pllElementsWithUuidAttributes */
4375 // we only skip removable media for OVF, but we never get here for OVF
4376 // since snapshots never get written then
4377 buildDebuggingXML(pelmSnapshot, &snap.debugging);
4378
4379 if (snap.llChildSnapshots.size())
4380 {
4381 xml::ElementNode *pelmChildren = pelmSnapshot->createChild("Snapshots");
4382 for (SnapshotsList::const_iterator it = snap.llChildSnapshots.begin();
4383 it != snap.llChildSnapshots.end();
4384 ++it)
4385 {
4386 const Snapshot &child = *it;
4387 buildSnapshotXML(*pelmChildren, child);
4388 }
4389 }
4390}
4391
4392/**
4393 * Builds the XML DOM tree for the machine config under the given XML element.
4394 *
4395 * This has been separated out from write() so it can be called from elsewhere,
4396 * such as the OVF code, to build machine XML in an existing XML tree.
4397 *
4398 * As a result, this gets called from two locations:
4399 *
4400 * -- MachineConfigFile::write();
4401 *
4402 * -- Appliance::buildXMLForOneVirtualSystem()
4403 *
4404 * In fl, the following flag bits are recognized:
4405 *
4406 * -- BuildMachineXML_MediaRegistry: If set, the machine's media registry will
4407 * be written, if present. This is not set when called from OVF because OVF
4408 * has its own variant of a media registry. This flag is ignored unless the
4409 * settings version is at least v1.11 (VirtualBox 4.0).
4410 *
4411 * -- BuildMachineXML_IncludeSnapshots: If set, descend into the snapshots tree
4412 * of the machine and write out <Snapshot> and possibly more snapshots under
4413 * that, if snapshots are present. Otherwise all snapshots are suppressed
4414 * (when called from OVF).
4415 *
4416 * -- BuildMachineXML_WriteVboxVersionAttribute: If set, add a settingsVersion
4417 * attribute to the machine tag with the vbox settings version. This is for
4418 * the OVF export case in which we don't have the settings version set in
4419 * the root element.
4420 *
4421 * -- BuildMachineXML_SkipRemovableMedia: If set, removable media attachments
4422 * (DVDs, floppies) are silently skipped. This is for the OVF export case
4423 * until we support copying ISO and RAW media as well. This flag is ignored
4424 * unless the settings version is at least v1.9, which is always the case
4425 * when this gets called for OVF export.
4426 *
4427 * -- BuildMachineXML_SuppressSavedState: If set, the Machine/@stateFile
4428 * attribute is never set. This is also for the OVF export case because we
4429 * cannot save states with OVF.
4430 *
4431 * @param elmMachine XML <Machine> element to add attributes and elements to.
4432 * @param fl Flags.
4433 * @param pllElementsWithUuidAttributes pointer to list that should receive UUID elements or NULL;
4434 * see buildStorageControllersXML() for details.
4435 */
4436void MachineConfigFile::buildMachineXML(xml::ElementNode &elmMachine,
4437 uint32_t fl,
4438 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes)
4439{
4440 if (fl & BuildMachineXML_WriteVboxVersionAttribute)
4441 // add settings version attribute to machine element
4442 setVersionAttribute(elmMachine);
4443
4444 elmMachine.setAttribute("uuid", uuid.toStringCurly());
4445 elmMachine.setAttribute("name", machineUserData.strName);
4446 if (!machineUserData.fNameSync)
4447 elmMachine.setAttribute("nameSync", machineUserData.fNameSync);
4448 if (machineUserData.strDescription.length())
4449 elmMachine.createChild("Description")->addContent(machineUserData.strDescription);
4450 elmMachine.setAttribute("OSType", machineUserData.strOsType);
4451 if ( strStateFile.length()
4452 && !(fl & BuildMachineXML_SuppressSavedState)
4453 )
4454 elmMachine.setAttributePath("stateFile", strStateFile);
4455 if ( (fl & BuildMachineXML_IncludeSnapshots)
4456 && !uuidCurrentSnapshot.isEmpty())
4457 elmMachine.setAttribute("currentSnapshot", uuidCurrentSnapshot.toStringCurly());
4458
4459 if (machineUserData.strSnapshotFolder.length())
4460 elmMachine.setAttributePath("snapshotFolder", machineUserData.strSnapshotFolder);
4461 if (!fCurrentStateModified)
4462 elmMachine.setAttribute("currentStateModified", fCurrentStateModified);
4463 elmMachine.setAttribute("lastStateChange", makeString(timeLastStateChange));
4464 if (fAborted)
4465 elmMachine.setAttribute("aborted", fAborted);
4466 if ( m->sv >= SettingsVersion_v1_9
4467 && ( machineUserData.fTeleporterEnabled
4468 || machineUserData.uTeleporterPort
4469 || !machineUserData.strTeleporterAddress.isEmpty()
4470 || !machineUserData.strTeleporterPassword.isEmpty()
4471 )
4472 )
4473 {
4474 xml::ElementNode *pelmTeleporter = elmMachine.createChild("Teleporter");
4475 pelmTeleporter->setAttribute("enabled", machineUserData.fTeleporterEnabled);
4476 pelmTeleporter->setAttribute("port", machineUserData.uTeleporterPort);
4477 pelmTeleporter->setAttribute("address", machineUserData.strTeleporterAddress);
4478 pelmTeleporter->setAttribute("password", machineUserData.strTeleporterPassword);
4479 }
4480
4481 if ( m->sv >= SettingsVersion_v1_11
4482 && ( machineUserData.enmFaultToleranceState != FaultToleranceState_Inactive
4483 || machineUserData.uFaultTolerancePort
4484 || machineUserData.uFaultToleranceInterval
4485 || !machineUserData.strFaultToleranceAddress.isEmpty()
4486 )
4487 )
4488 {
4489 xml::ElementNode *pelmFaultTolerance = elmMachine.createChild("FaultTolerance");
4490 switch (machineUserData.enmFaultToleranceState)
4491 {
4492 case FaultToleranceState_Inactive:
4493 pelmFaultTolerance->setAttribute("state", "inactive");
4494 break;
4495 case FaultToleranceState_Master:
4496 pelmFaultTolerance->setAttribute("state", "master");
4497 break;
4498 case FaultToleranceState_Standby:
4499 pelmFaultTolerance->setAttribute("state", "standby");
4500 break;
4501 }
4502
4503 pelmFaultTolerance->setAttribute("port", machineUserData.uFaultTolerancePort);
4504 pelmFaultTolerance->setAttribute("address", machineUserData.strFaultToleranceAddress);
4505 pelmFaultTolerance->setAttribute("interval", machineUserData.uFaultToleranceInterval);
4506 pelmFaultTolerance->setAttribute("password", machineUserData.strFaultTolerancePassword);
4507 }
4508
4509 if ( (fl & BuildMachineXML_MediaRegistry)
4510 && (m->sv >= SettingsVersion_v1_11)
4511 )
4512 buildMediaRegistry(elmMachine, mediaRegistry);
4513
4514 buildExtraData(elmMachine, mapExtraDataItems);
4515
4516 if ( (fl & BuildMachineXML_IncludeSnapshots)
4517 && llFirstSnapshot.size())
4518 buildSnapshotXML(elmMachine, llFirstSnapshot.front());
4519
4520 buildHardwareXML(elmMachine, hardwareMachine, storageMachine);
4521 buildStorageControllersXML(elmMachine,
4522 storageMachine,
4523 !!(fl & BuildMachineXML_SkipRemovableMedia),
4524 pllElementsWithUuidAttributes);
4525 buildDebuggingXML(&elmMachine, &debugging);
4526}
4527
4528/**
4529 * Returns true only if the given AudioDriverType is supported on
4530 * the current host platform. For example, this would return false
4531 * for AudioDriverType_DirectSound when compiled on a Linux host.
4532 * @param drv AudioDriverType_* enum to test.
4533 * @return true only if the current host supports that driver.
4534 */
4535/*static*/
4536bool MachineConfigFile::isAudioDriverAllowedOnThisHost(AudioDriverType_T drv)
4537{
4538 switch (drv)
4539 {
4540 case AudioDriverType_Null:
4541#ifdef RT_OS_WINDOWS
4542# ifdef VBOX_WITH_WINMM
4543 case AudioDriverType_WinMM:
4544# endif
4545 case AudioDriverType_DirectSound:
4546#endif /* RT_OS_WINDOWS */
4547#ifdef RT_OS_SOLARIS
4548 case AudioDriverType_SolAudio:
4549#endif
4550#ifdef RT_OS_LINUX
4551# ifdef VBOX_WITH_ALSA
4552 case AudioDriverType_ALSA:
4553# endif
4554# ifdef VBOX_WITH_PULSE
4555 case AudioDriverType_Pulse:
4556# endif
4557#endif /* RT_OS_LINUX */
4558#if defined (RT_OS_LINUX) || defined (RT_OS_FREEBSD) || defined(VBOX_WITH_SOLARIS_OSS)
4559 case AudioDriverType_OSS:
4560#endif
4561#ifdef RT_OS_FREEBSD
4562# ifdef VBOX_WITH_PULSE
4563 case AudioDriverType_Pulse:
4564# endif
4565#endif
4566#ifdef RT_OS_DARWIN
4567 case AudioDriverType_CoreAudio:
4568#endif
4569#ifdef RT_OS_OS2
4570 case AudioDriverType_MMPM:
4571#endif
4572 return true;
4573 }
4574
4575 return false;
4576}
4577
4578/**
4579 * Returns the AudioDriverType_* which should be used by default on this
4580 * host platform. On Linux, this will check at runtime whether PulseAudio
4581 * or ALSA are actually supported on the first call.
4582 * @return
4583 */
4584/*static*/
4585AudioDriverType_T MachineConfigFile::getHostDefaultAudioDriver()
4586{
4587#if defined(RT_OS_WINDOWS)
4588# ifdef VBOX_WITH_WINMM
4589 return AudioDriverType_WinMM;
4590# else /* VBOX_WITH_WINMM */
4591 return AudioDriverType_DirectSound;
4592# endif /* !VBOX_WITH_WINMM */
4593#elif defined(RT_OS_SOLARIS)
4594 return AudioDriverType_SolAudio;
4595#elif defined(RT_OS_LINUX)
4596 // on Linux, we need to check at runtime what's actually supported...
4597 static RTCLockMtx s_mtx;
4598 static AudioDriverType_T s_linuxDriver = -1;
4599 RTCLock lock(s_mtx);
4600 if (s_linuxDriver == (AudioDriverType_T)-1)
4601 {
4602# if defined(VBOX_WITH_PULSE)
4603 /* Check for the pulse library & that the pulse audio daemon is running. */
4604 if (RTProcIsRunningByName("pulseaudio") &&
4605 RTLdrIsLoadable("libpulse.so.0"))
4606 s_linuxDriver = AudioDriverType_Pulse;
4607 else
4608# endif /* VBOX_WITH_PULSE */
4609# if defined(VBOX_WITH_ALSA)
4610 /* Check if we can load the ALSA library */
4611 if (RTLdrIsLoadable("libasound.so.2"))
4612 s_linuxDriver = AudioDriverType_ALSA;
4613 else
4614# endif /* VBOX_WITH_ALSA */
4615 s_linuxDriver = AudioDriverType_OSS;
4616 }
4617 return s_linuxDriver;
4618// end elif defined(RT_OS_LINUX)
4619#elif defined(RT_OS_DARWIN)
4620 return AudioDriverType_CoreAudio;
4621#elif defined(RT_OS_OS2)
4622 return AudioDriverType_MMPM;
4623#elif defined(RT_OS_FREEBSD)
4624 return AudioDriverType_OSS;
4625#else
4626 return AudioDriverType_Null;
4627#endif
4628}
4629
4630/**
4631 * Called from write() before calling ConfigFileBase::createStubDocument().
4632 * This adjusts the settings version in m->sv if incompatible settings require
4633 * a settings bump, whereas otherwise we try to preserve the settings version
4634 * to avoid breaking compatibility with older versions.
4635 *
4636 * We do the checks in here in reverse order: newest first, oldest last, so
4637 * that we avoid unnecessary checks since some of these are expensive.
4638 */
4639void MachineConfigFile::bumpSettingsVersionIfNeeded()
4640{
4641 if (m->sv < SettingsVersion_v1_13)
4642 {
4643 // VirtualBox 4.2 adds tracing.
4644 if (!debugging.areDefaultSettings())
4645 m->sv = SettingsVersion_v1_13;
4646 }
4647
4648 if (m->sv < SettingsVersion_v1_12)
4649 {
4650 // VirtualBox 4.1 adds PCI passthrough.
4651 if (hardwareMachine.pciAttachments.size())
4652 m->sv = SettingsVersion_v1_12;
4653 }
4654
4655 if (m->sv < SettingsVersion_v1_12)
4656 {
4657 // VirtualBox 4.1 adds a promiscuous mode policy to the network
4658 // adapters and a generic network driver transport.
4659 NetworkAdaptersList::const_iterator netit;
4660 for (netit = hardwareMachine.llNetworkAdapters.begin();
4661 netit != hardwareMachine.llNetworkAdapters.end();
4662 ++netit)
4663 {
4664 if ( netit->enmPromiscModePolicy != NetworkAdapterPromiscModePolicy_Deny
4665 || netit->mode == NetworkAttachmentType_Generic
4666 || !netit->strGenericDriver.isEmpty()
4667 || netit->genericProperties.size()
4668 )
4669 {
4670 m->sv = SettingsVersion_v1_12;
4671 break;
4672 }
4673 }
4674 }
4675
4676 if (m->sv < SettingsVersion_v1_11)
4677 {
4678 // VirtualBox 4.0 adds HD audio, CPU priorities, fault tolerance,
4679 // per-machine media registries, VRDE, JRockitVE, bandwidth groups,
4680 // ICH9 chipset
4681 if ( hardwareMachine.audioAdapter.controllerType == AudioControllerType_HDA
4682 || hardwareMachine.ulCpuExecutionCap != 100
4683 || machineUserData.enmFaultToleranceState != FaultToleranceState_Inactive
4684 || machineUserData.uFaultTolerancePort
4685 || machineUserData.uFaultToleranceInterval
4686 || !machineUserData.strFaultToleranceAddress.isEmpty()
4687 || mediaRegistry.llHardDisks.size()
4688 || mediaRegistry.llDvdImages.size()
4689 || mediaRegistry.llFloppyImages.size()
4690 || !hardwareMachine.vrdeSettings.strVrdeExtPack.isEmpty()
4691 || !hardwareMachine.vrdeSettings.strAuthLibrary.isEmpty()
4692 || machineUserData.strOsType == "JRockitVE"
4693 || hardwareMachine.ioSettings.llBandwidthGroups.size()
4694 || hardwareMachine.chipsetType == ChipsetType_ICH9
4695 )
4696 m->sv = SettingsVersion_v1_11;
4697 }
4698
4699 if (m->sv < SettingsVersion_v1_10)
4700 {
4701 /* If the properties contain elements other than "TCP/Ports" and "TCP/Address",
4702 * then increase the version to at least VBox 3.2, which can have video channel properties.
4703 */
4704 unsigned cOldProperties = 0;
4705
4706 StringsMap::const_iterator it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Ports");
4707 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4708 cOldProperties++;
4709 it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Address");
4710 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4711 cOldProperties++;
4712
4713 if (hardwareMachine.vrdeSettings.mapProperties.size() != cOldProperties)
4714 m->sv = SettingsVersion_v1_10;
4715 }
4716
4717 if (m->sv < SettingsVersion_v1_11)
4718 {
4719 /* If the properties contain elements other than "TCP/Ports", "TCP/Address",
4720 * "VideoChannel/Enabled" and "VideoChannel/Quality" then increase the version to VBox 4.0.
4721 */
4722 unsigned cOldProperties = 0;
4723
4724 StringsMap::const_iterator it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Ports");
4725 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4726 cOldProperties++;
4727 it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Address");
4728 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4729 cOldProperties++;
4730 it = hardwareMachine.vrdeSettings.mapProperties.find("VideoChannel/Enabled");
4731 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4732 cOldProperties++;
4733 it = hardwareMachine.vrdeSettings.mapProperties.find("VideoChannel/Quality");
4734 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4735 cOldProperties++;
4736
4737 if (hardwareMachine.vrdeSettings.mapProperties.size() != cOldProperties)
4738 m->sv = SettingsVersion_v1_11;
4739 }
4740
4741 // settings version 1.9 is required if there is not exactly one DVD
4742 // or more than one floppy drive present or the DVD is not at the secondary
4743 // master; this check is a bit more complicated
4744 //
4745 // settings version 1.10 is required if the host cache should be disabled
4746 //
4747 // settings version 1.11 is required for bandwidth limits and if more than
4748 // one controller of each type is present.
4749 if (m->sv < SettingsVersion_v1_11)
4750 {
4751 // count attached DVDs and floppies (only if < v1.9)
4752 size_t cDVDs = 0;
4753 size_t cFloppies = 0;
4754
4755 // count storage controllers (if < v1.11)
4756 size_t cSata = 0;
4757 size_t cScsiLsi = 0;
4758 size_t cScsiBuslogic = 0;
4759 size_t cSas = 0;
4760 size_t cIde = 0;
4761 size_t cFloppy = 0;
4762
4763 // need to run thru all the storage controllers and attached devices to figure this out
4764 for (StorageControllersList::const_iterator it = storageMachine.llStorageControllers.begin();
4765 it != storageMachine.llStorageControllers.end();
4766 ++it)
4767 {
4768 const StorageController &sctl = *it;
4769
4770 // count storage controllers of each type; 1.11 is required if more than one
4771 // controller of one type is present
4772 switch (sctl.storageBus)
4773 {
4774 case StorageBus_IDE:
4775 cIde++;
4776 break;
4777 case StorageBus_SATA:
4778 cSata++;
4779 break;
4780 case StorageBus_SAS:
4781 cSas++;
4782 break;
4783 case StorageBus_SCSI:
4784 if (sctl.controllerType == StorageControllerType_LsiLogic)
4785 cScsiLsi++;
4786 else
4787 cScsiBuslogic++;
4788 break;
4789 case StorageBus_Floppy:
4790 cFloppy++;
4791 break;
4792 default:
4793 // Do nothing
4794 break;
4795 }
4796
4797 if ( cSata > 1
4798 || cScsiLsi > 1
4799 || cScsiBuslogic > 1
4800 || cSas > 1
4801 || cIde > 1
4802 || cFloppy > 1)
4803 {
4804 m->sv = SettingsVersion_v1_11;
4805 break; // abort the loop -- we will not raise the version further
4806 }
4807
4808 for (AttachedDevicesList::const_iterator it2 = sctl.llAttachedDevices.begin();
4809 it2 != sctl.llAttachedDevices.end();
4810 ++it2)
4811 {
4812 const AttachedDevice &att = *it2;
4813
4814 // Bandwidth limitations are new in VirtualBox 4.0 (1.11)
4815 if (m->sv < SettingsVersion_v1_11)
4816 {
4817 if (att.strBwGroup.length() != 0)
4818 {
4819 m->sv = SettingsVersion_v1_11;
4820 break; // abort the loop -- we will not raise the version further
4821 }
4822 }
4823
4824 // disabling the host IO cache requires settings version 1.10
4825 if ( (m->sv < SettingsVersion_v1_10)
4826 && (!sctl.fUseHostIOCache)
4827 )
4828 m->sv = SettingsVersion_v1_10;
4829
4830 // we can only write the StorageController/@Instance attribute with v1.9
4831 if ( (m->sv < SettingsVersion_v1_9)
4832 && (sctl.ulInstance != 0)
4833 )
4834 m->sv = SettingsVersion_v1_9;
4835
4836 if (m->sv < SettingsVersion_v1_9)
4837 {
4838 if (att.deviceType == DeviceType_DVD)
4839 {
4840 if ( (sctl.storageBus != StorageBus_IDE) // DVD at bus other than DVD?
4841 || (att.lPort != 1) // DVDs not at secondary master?
4842 || (att.lDevice != 0)
4843 )
4844 m->sv = SettingsVersion_v1_9;
4845
4846 ++cDVDs;
4847 }
4848 else if (att.deviceType == DeviceType_Floppy)
4849 ++cFloppies;
4850 }
4851 }
4852
4853 if (m->sv >= SettingsVersion_v1_11)
4854 break; // abort the loop -- we will not raise the version further
4855 }
4856
4857 // VirtualBox before 3.1 had zero or one floppy and exactly one DVD,
4858 // so any deviation from that will require settings version 1.9
4859 if ( (m->sv < SettingsVersion_v1_9)
4860 && ( (cDVDs != 1)
4861 || (cFloppies > 1)
4862 )
4863 )
4864 m->sv = SettingsVersion_v1_9;
4865 }
4866
4867 // VirtualBox 3.2: Check for non default I/O settings
4868 if (m->sv < SettingsVersion_v1_10)
4869 {
4870 if ( (hardwareMachine.ioSettings.fIoCacheEnabled != true)
4871 || (hardwareMachine.ioSettings.ulIoCacheSize != 5)
4872 // and page fusion
4873 || (hardwareMachine.fPageFusionEnabled)
4874 // and CPU hotplug, RTC timezone control, HID type and HPET
4875 || machineUserData.fRTCUseUTC
4876 || hardwareMachine.fCpuHotPlug
4877 || hardwareMachine.pointingHidType != PointingHidType_PS2Mouse
4878 || hardwareMachine.keyboardHidType != KeyboardHidType_PS2Keyboard
4879 || hardwareMachine.fHpetEnabled
4880 )
4881 m->sv = SettingsVersion_v1_10;
4882 }
4883
4884 // VirtualBox 3.2 adds NAT and boot priority to the NIC config in Main
4885 // VirtualBox 4.0 adds network bandwitdth
4886 if (m->sv < SettingsVersion_v1_11)
4887 {
4888 NetworkAdaptersList::const_iterator netit;
4889 for (netit = hardwareMachine.llNetworkAdapters.begin();
4890 netit != hardwareMachine.llNetworkAdapters.end();
4891 ++netit)
4892 {
4893 if ( (m->sv < SettingsVersion_v1_12)
4894 && (netit->strBandwidthGroup.isNotEmpty())
4895 )
4896 {
4897 /* New in VirtualBox 4.1 */
4898 m->sv = SettingsVersion_v1_12;
4899 break;
4900 }
4901 else if ( (m->sv < SettingsVersion_v1_10)
4902 && (netit->fEnabled)
4903 && (netit->mode == NetworkAttachmentType_NAT)
4904 && ( netit->nat.u32Mtu != 0
4905 || netit->nat.u32SockRcv != 0
4906 || netit->nat.u32SockSnd != 0
4907 || netit->nat.u32TcpRcv != 0
4908 || netit->nat.u32TcpSnd != 0
4909 || !netit->nat.fDnsPassDomain
4910 || netit->nat.fDnsProxy
4911 || netit->nat.fDnsUseHostResolver
4912 || netit->nat.fAliasLog
4913 || netit->nat.fAliasProxyOnly
4914 || netit->nat.fAliasUseSamePorts
4915 || netit->nat.strTftpPrefix.length()
4916 || netit->nat.strTftpBootFile.length()
4917 || netit->nat.strTftpNextServer.length()
4918 || netit->nat.llRules.size()
4919 )
4920 )
4921 {
4922 m->sv = SettingsVersion_v1_10;
4923 // no break because we still might need v1.11 above
4924 }
4925 else if ( (m->sv < SettingsVersion_v1_10)
4926 && (netit->fEnabled)
4927 && (netit->ulBootPriority != 0)
4928 )
4929 {
4930 m->sv = SettingsVersion_v1_10;
4931 // no break because we still might need v1.11 above
4932 }
4933 }
4934 }
4935
4936 // all the following require settings version 1.9
4937 if ( (m->sv < SettingsVersion_v1_9)
4938 && ( (hardwareMachine.firmwareType >= FirmwareType_EFI)
4939 || (hardwareMachine.fHardwareVirtExclusive != HWVIRTEXCLUSIVEDEFAULT)
4940 || machineUserData.fTeleporterEnabled
4941 || machineUserData.uTeleporterPort
4942 || !machineUserData.strTeleporterAddress.isEmpty()
4943 || !machineUserData.strTeleporterPassword.isEmpty()
4944 || !hardwareMachine.uuid.isEmpty()
4945 )
4946 )
4947 m->sv = SettingsVersion_v1_9;
4948
4949 // "accelerate 2d video" requires settings version 1.8
4950 if ( (m->sv < SettingsVersion_v1_8)
4951 && (hardwareMachine.fAccelerate2DVideo)
4952 )
4953 m->sv = SettingsVersion_v1_8;
4954
4955 // The hardware versions other than "1" requires settings version 1.4 (2.1+).
4956 if ( m->sv < SettingsVersion_v1_4
4957 && hardwareMachine.strVersion != "1"
4958 )
4959 m->sv = SettingsVersion_v1_4;
4960}
4961
4962/**
4963 * Called from Main code to write a machine config file to disk. This builds a DOM tree from
4964 * the member variables and then writes the XML file; it throws xml::Error instances on errors,
4965 * in particular if the file cannot be written.
4966 */
4967void MachineConfigFile::write(const com::Utf8Str &strFilename)
4968{
4969 try
4970 {
4971 // createStubDocument() sets the settings version to at least 1.7; however,
4972 // we might need to enfore a later settings version if incompatible settings
4973 // are present:
4974 bumpSettingsVersionIfNeeded();
4975
4976 m->strFilename = strFilename;
4977 createStubDocument();
4978
4979 xml::ElementNode *pelmMachine = m->pelmRoot->createChild("Machine");
4980 buildMachineXML(*pelmMachine,
4981 MachineConfigFile::BuildMachineXML_IncludeSnapshots
4982 | MachineConfigFile::BuildMachineXML_MediaRegistry,
4983 // but not BuildMachineXML_WriteVboxVersionAttribute
4984 NULL); /* pllElementsWithUuidAttributes */
4985
4986 // now go write the XML
4987 xml::XmlFileWriter writer(*m->pDoc);
4988 writer.write(m->strFilename.c_str(), true /*fSafe*/);
4989
4990 m->fFileExists = true;
4991 clearDocument();
4992 }
4993 catch (...)
4994 {
4995 clearDocument();
4996 throw;
4997 }
4998}
Note: See TracBrowser for help on using the repository browser.

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