VirtualBox

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

Last change on this file since 35119 was 35119, checked in by vboxsync, 14 years ago

Main/settings: Do not write the "type" attribute for DVD images. Causes unnecessary config file bloat with no extra information. All VirtualBox versions ignore that attribute when reading the config.

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