VirtualBox

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

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

iprt::MiniString -> RTCString.

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