VirtualBox

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

Last change on this file since 38873 was 38873, checked in by vboxsync, 13 years ago

Main: Add API to set the discard flag for harddisks

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