VirtualBox

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

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

Main/Settings: correctly bump from v1.10 to v1.11 if a network bandwith is set

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

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