VirtualBox

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

Last change on this file since 41842 was 41842, checked in by vboxsync, 12 years ago

Main,VBoxManage,docs: bandwidth units changed to bytes (#5582)

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

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