VirtualBox

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

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

Main/xml/Settings: fAutoReset and hdType were sometimes not correctly initialized

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

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