VirtualBox

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

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

Main/Settings: fixed reading of the NAT/network attribute (r71896 regression)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Revision Author Id
File size: 202.6 KB
Line 
1/* $Id: Settings.cpp 38100 2011-07-21 14:07:48Z 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 && (lPort == a.lPort)
1696 && (lDevice == a.lDevice)
1697 && (uuid == a.uuid)
1698 && (strHostDriveSrc == a.strHostDriveSrc)
1699 && (strBwGroup == a.strBwGroup)
1700 )
1701 );
1702}
1703
1704/**
1705 * Comparison operator. This gets called from MachineConfigFile::operator==,
1706 * which in turn gets called from Machine::saveSettings to figure out whether
1707 * machine settings have really changed and thus need to be written out to disk.
1708 */
1709bool StorageController::operator==(const StorageController &s) const
1710{
1711 return ( (this == &s)
1712 || ( (strName == s.strName)
1713 && (storageBus == s.storageBus)
1714 && (controllerType == s.controllerType)
1715 && (ulPortCount == s.ulPortCount)
1716 && (ulInstance == s.ulInstance)
1717 && (fUseHostIOCache == s.fUseHostIOCache)
1718 && (lIDE0MasterEmulationPort == s.lIDE0MasterEmulationPort)
1719 && (lIDE0SlaveEmulationPort == s.lIDE0SlaveEmulationPort)
1720 && (lIDE1MasterEmulationPort == s.lIDE1MasterEmulationPort)
1721 && (lIDE1SlaveEmulationPort == s.lIDE1SlaveEmulationPort)
1722 && (llAttachedDevices == s.llAttachedDevices)
1723 )
1724 );
1725}
1726
1727/**
1728 * Comparison operator. This gets called from MachineConfigFile::operator==,
1729 * which in turn gets called from Machine::saveSettings to figure out whether
1730 * machine settings have really changed and thus need to be written out to disk.
1731 */
1732bool Storage::operator==(const Storage &s) const
1733{
1734 return ( (this == &s)
1735 || (llStorageControllers == s.llStorageControllers) // deep compare
1736 );
1737}
1738
1739/**
1740 * Comparison operator. This gets called from MachineConfigFile::operator==,
1741 * which in turn gets called from Machine::saveSettings to figure out whether
1742 * machine settings have really changed and thus need to be written out to disk.
1743 */
1744bool Snapshot::operator==(const Snapshot &s) const
1745{
1746 return ( (this == &s)
1747 || ( (uuid == s.uuid)
1748 && (strName == s.strName)
1749 && (strDescription == s.strDescription)
1750 && (RTTimeSpecIsEqual(&timestamp, &s.timestamp))
1751 && (strStateFile == s.strStateFile)
1752 && (hardware == s.hardware) // deep compare
1753 && (storage == s.storage) // deep compare
1754 && (llChildSnapshots == s.llChildSnapshots) // deep compare
1755 )
1756 );
1757}
1758
1759/**
1760 * IoSettings constructor.
1761 */
1762IoSettings::IoSettings()
1763{
1764 fIoCacheEnabled = true;
1765 ulIoCacheSize = 5;
1766}
1767
1768////////////////////////////////////////////////////////////////////////////////
1769//
1770// MachineConfigFile
1771//
1772////////////////////////////////////////////////////////////////////////////////
1773
1774/**
1775 * Constructor.
1776 *
1777 * If pstrFilename is != NULL, this reads the given settings file into the member
1778 * variables and various substructures and lists. Otherwise, the member variables
1779 * are initialized with default values.
1780 *
1781 * Throws variants of xml::Error for I/O, XML and logical content errors, which
1782 * the caller should catch; if this constructor does not throw, then the member
1783 * variables contain meaningful values (either from the file or defaults).
1784 *
1785 * @param strFilename
1786 */
1787MachineConfigFile::MachineConfigFile(const Utf8Str *pstrFilename)
1788 : ConfigFileBase(pstrFilename),
1789 fCurrentStateModified(true),
1790 fAborted(false)
1791{
1792 RTTimeNow(&timeLastStateChange);
1793
1794 if (pstrFilename)
1795 {
1796 // the ConfigFileBase constructor has loaded the XML file, so now
1797 // we need only analyze what is in there
1798
1799 xml::NodesLoop nlRootChildren(*m->pelmRoot);
1800 const xml::ElementNode *pelmRootChild;
1801 while ((pelmRootChild = nlRootChildren.forAllNodes()))
1802 {
1803 if (pelmRootChild->nameEquals("Machine"))
1804 readMachine(*pelmRootChild);
1805 }
1806
1807 // clean up memory allocated by XML engine
1808 clearDocument();
1809 }
1810}
1811
1812/**
1813 * Public routine which returns true if this machine config file can have its
1814 * own media registry (which is true for settings version v1.11 and higher,
1815 * i.e. files created by VirtualBox 4.0 and higher).
1816 * @return
1817 */
1818bool MachineConfigFile::canHaveOwnMediaRegistry() const
1819{
1820 return (m->sv >= SettingsVersion_v1_11);
1821}
1822
1823/**
1824 * Public routine which allows for importing machine XML from an external DOM tree.
1825 * Use this after having called the constructor with a NULL argument.
1826 *
1827 * This is used by the OVF code if a <vbox:Machine> element has been encountered
1828 * in an OVF VirtualSystem element.
1829 *
1830 * @param elmMachine
1831 */
1832void MachineConfigFile::importMachineXML(const xml::ElementNode &elmMachine)
1833{
1834 readMachine(elmMachine);
1835}
1836
1837/**
1838 * Comparison operator. This gets called from Machine::saveSettings to figure out
1839 * whether machine settings have really changed and thus need to be written out to disk.
1840 *
1841 * Even though this is called operator==, this does NOT compare all fields; the "equals"
1842 * should be understood as "has the same machine config as". The following fields are
1843 * NOT compared:
1844 * -- settings versions and file names inherited from ConfigFileBase;
1845 * -- fCurrentStateModified because that is considered separately in Machine::saveSettings!!
1846 *
1847 * The "deep" comparisons marked below will invoke the operator== functions of the
1848 * structs defined in this file, which may in turn go into comparing lists of
1849 * other structures. As a result, invoking this can be expensive, but it's
1850 * less expensive than writing out XML to disk.
1851 */
1852bool MachineConfigFile::operator==(const MachineConfigFile &c) const
1853{
1854 return ( (this == &c)
1855 || ( (uuid == c.uuid)
1856 && (machineUserData == c.machineUserData)
1857 && (strStateFile == c.strStateFile)
1858 && (uuidCurrentSnapshot == c.uuidCurrentSnapshot)
1859 // skip fCurrentStateModified!
1860 && (RTTimeSpecIsEqual(&timeLastStateChange, &c.timeLastStateChange))
1861 && (fAborted == c.fAborted)
1862 && (hardwareMachine == c.hardwareMachine) // this one's deep
1863 && (storageMachine == c.storageMachine) // this one's deep
1864 && (mediaRegistry == c.mediaRegistry) // this one's deep
1865 && (mapExtraDataItems == c.mapExtraDataItems) // this one's deep
1866 && (llFirstSnapshot == c.llFirstSnapshot) // this one's deep
1867 )
1868 );
1869}
1870
1871/**
1872 * Called from MachineConfigFile::readHardware() to read cpu information.
1873 * @param elmCpuid
1874 * @param ll
1875 */
1876void MachineConfigFile::readCpuTree(const xml::ElementNode &elmCpu,
1877 CpuList &ll)
1878{
1879 xml::NodesLoop nl1(elmCpu, "Cpu");
1880 const xml::ElementNode *pelmCpu;
1881 while ((pelmCpu = nl1.forAllNodes()))
1882 {
1883 Cpu cpu;
1884
1885 if (!pelmCpu->getAttributeValue("id", cpu.ulId))
1886 throw ConfigFileError(this, pelmCpu, N_("Required Cpu/@id attribute is missing"));
1887
1888 ll.push_back(cpu);
1889 }
1890}
1891
1892/**
1893 * Called from MachineConfigFile::readHardware() to cpuid information.
1894 * @param elmCpuid
1895 * @param ll
1896 */
1897void MachineConfigFile::readCpuIdTree(const xml::ElementNode &elmCpuid,
1898 CpuIdLeafsList &ll)
1899{
1900 xml::NodesLoop nl1(elmCpuid, "CpuIdLeaf");
1901 const xml::ElementNode *pelmCpuIdLeaf;
1902 while ((pelmCpuIdLeaf = nl1.forAllNodes()))
1903 {
1904 CpuIdLeaf leaf;
1905
1906 if (!pelmCpuIdLeaf->getAttributeValue("id", leaf.ulId))
1907 throw ConfigFileError(this, pelmCpuIdLeaf, N_("Required CpuId/@id attribute is missing"));
1908
1909 pelmCpuIdLeaf->getAttributeValue("eax", leaf.ulEax);
1910 pelmCpuIdLeaf->getAttributeValue("ebx", leaf.ulEbx);
1911 pelmCpuIdLeaf->getAttributeValue("ecx", leaf.ulEcx);
1912 pelmCpuIdLeaf->getAttributeValue("edx", leaf.ulEdx);
1913
1914 ll.push_back(leaf);
1915 }
1916}
1917
1918/**
1919 * Called from MachineConfigFile::readHardware() to network information.
1920 * @param elmNetwork
1921 * @param ll
1922 */
1923void MachineConfigFile::readNetworkAdapters(const xml::ElementNode &elmNetwork,
1924 NetworkAdaptersList &ll)
1925{
1926 xml::NodesLoop nl1(elmNetwork, "Adapter");
1927 const xml::ElementNode *pelmAdapter;
1928 while ((pelmAdapter = nl1.forAllNodes()))
1929 {
1930 NetworkAdapter nic;
1931
1932 if (!pelmAdapter->getAttributeValue("slot", nic.ulSlot))
1933 throw ConfigFileError(this, pelmAdapter, N_("Required Adapter/@slot attribute is missing"));
1934
1935 Utf8Str strTemp;
1936 if (pelmAdapter->getAttributeValue("type", strTemp))
1937 {
1938 if (strTemp == "Am79C970A")
1939 nic.type = NetworkAdapterType_Am79C970A;
1940 else if (strTemp == "Am79C973")
1941 nic.type = NetworkAdapterType_Am79C973;
1942 else if (strTemp == "82540EM")
1943 nic.type = NetworkAdapterType_I82540EM;
1944 else if (strTemp == "82543GC")
1945 nic.type = NetworkAdapterType_I82543GC;
1946 else if (strTemp == "82545EM")
1947 nic.type = NetworkAdapterType_I82545EM;
1948 else if (strTemp == "virtio")
1949 nic.type = NetworkAdapterType_Virtio;
1950 else
1951 throw ConfigFileError(this, pelmAdapter, N_("Invalid value '%s' in Adapter/@type attribute"), strTemp.c_str());
1952 }
1953
1954 pelmAdapter->getAttributeValue("enabled", nic.fEnabled);
1955 pelmAdapter->getAttributeValue("MACAddress", nic.strMACAddress);
1956 pelmAdapter->getAttributeValue("cable", nic.fCableConnected);
1957 pelmAdapter->getAttributeValue("speed", nic.ulLineSpeed);
1958
1959 if (pelmAdapter->getAttributeValue("promiscuousModePolicy", strTemp))
1960 {
1961 if (strTemp == "Deny")
1962 nic.enmPromiscModePolicy = NetworkAdapterPromiscModePolicy_Deny;
1963 else if (strTemp == "AllowNetwork")
1964 nic.enmPromiscModePolicy = NetworkAdapterPromiscModePolicy_AllowNetwork;
1965 else if (strTemp == "AllowAll")
1966 nic.enmPromiscModePolicy = NetworkAdapterPromiscModePolicy_AllowAll;
1967 else
1968 throw ConfigFileError(this, pelmAdapter,
1969 N_("Invalid value '%s' in Adapter/@promiscuousModePolicy attribute"), strTemp.c_str());
1970 }
1971
1972 pelmAdapter->getAttributeValue("trace", nic.fTraceEnabled);
1973 pelmAdapter->getAttributeValue("tracefile", nic.strTraceFile);
1974 pelmAdapter->getAttributeValue("bootPriority", nic.ulBootPriority);
1975 pelmAdapter->getAttributeValue("bandwidthGroup", nic.strBandwidthGroup);
1976
1977 xml::ElementNodesList llNetworkModes;
1978 pelmAdapter->getChildElements(llNetworkModes);
1979 xml::ElementNodesList::iterator it;
1980 /* We should have only active mode descriptor and disabled modes set */
1981 if (llNetworkModes.size() > 2)
1982 {
1983 throw ConfigFileError(this, pelmAdapter, N_("Invalid number of modes ('%d') attached to Adapter attribute"), llNetworkModes.size());
1984 }
1985 for (it = llNetworkModes.begin(); it != llNetworkModes.end(); ++it)
1986 {
1987 const xml::ElementNode *pelmNode = *it;
1988 if (pelmNode->nameEquals("DisabledModes"))
1989 {
1990 xml::ElementNodesList llDisabledNetworkModes;
1991 xml::ElementNodesList::iterator itDisabled;
1992 pelmNode->getChildElements(llDisabledNetworkModes);
1993 /* run over disabled list and load settings */
1994 for (itDisabled = llDisabledNetworkModes.begin();
1995 itDisabled != llDisabledNetworkModes.end(); ++itDisabled)
1996 {
1997 const xml::ElementNode *pelmDisabledNode = *itDisabled;
1998 readAttachedNetworkMode(*pelmDisabledNode, false, nic);
1999 }
2000 }
2001 else
2002 readAttachedNetworkMode(*pelmNode, true, nic);
2003 }
2004 // else: default is NetworkAttachmentType_Null
2005
2006 ll.push_back(nic);
2007 }
2008}
2009
2010void MachineConfigFile::readAttachedNetworkMode(const xml::ElementNode &elmMode, bool fEnabled, NetworkAdapter &nic)
2011{
2012 NetworkAttachmentType_T enmAttachmentType = NetworkAttachmentType_Null;
2013
2014 if (elmMode.nameEquals("NAT"))
2015 {
2016 enmAttachmentType = NetworkAttachmentType_NAT;
2017
2018 elmMode.getAttributeValue("network", nic.nat.strNetwork);
2019 elmMode.getAttributeValue("hostip", nic.nat.strBindIP);
2020 elmMode.getAttributeValue("mtu", nic.nat.u32Mtu);
2021 elmMode.getAttributeValue("sockrcv", nic.nat.u32SockRcv);
2022 elmMode.getAttributeValue("socksnd", nic.nat.u32SockSnd);
2023 elmMode.getAttributeValue("tcprcv", nic.nat.u32TcpRcv);
2024 elmMode.getAttributeValue("tcpsnd", nic.nat.u32TcpSnd);
2025 const xml::ElementNode *pelmDNS;
2026 if ((pelmDNS = elmMode.findChildElement("DNS")))
2027 {
2028 pelmDNS->getAttributeValue("pass-domain", nic.nat.fDnsPassDomain);
2029 pelmDNS->getAttributeValue("use-proxy", nic.nat.fDnsProxy);
2030 pelmDNS->getAttributeValue("use-host-resolver", nic.nat.fDnsUseHostResolver);
2031 }
2032 const xml::ElementNode *pelmAlias;
2033 if ((pelmAlias = elmMode.findChildElement("Alias")))
2034 {
2035 pelmAlias->getAttributeValue("logging", nic.nat.fAliasLog);
2036 pelmAlias->getAttributeValue("proxy-only", nic.nat.fAliasProxyOnly);
2037 pelmAlias->getAttributeValue("use-same-ports", nic.nat.fAliasUseSamePorts);
2038 }
2039 const xml::ElementNode *pelmTFTP;
2040 if ((pelmTFTP = elmMode.findChildElement("TFTP")))
2041 {
2042 pelmTFTP->getAttributeValue("prefix", nic.nat.strTftpPrefix);
2043 pelmTFTP->getAttributeValue("boot-file", nic.nat.strTftpBootFile);
2044 pelmTFTP->getAttributeValue("next-server", nic.nat.strTftpNextServer);
2045 }
2046 xml::ElementNodesList plstNatPF;
2047 elmMode.getChildElements(plstNatPF, "Forwarding");
2048 for (xml::ElementNodesList::iterator pf = plstNatPF.begin(); pf != plstNatPF.end(); ++pf)
2049 {
2050 NATRule rule;
2051 uint32_t port = 0;
2052 (*pf)->getAttributeValue("name", rule.strName);
2053 (*pf)->getAttributeValue("proto", (uint32_t&)rule.proto);
2054 (*pf)->getAttributeValue("hostip", rule.strHostIP);
2055 (*pf)->getAttributeValue("hostport", port);
2056 rule.u16HostPort = port;
2057 (*pf)->getAttributeValue("guestip", rule.strGuestIP);
2058 (*pf)->getAttributeValue("guestport", port);
2059 rule.u16GuestPort = port;
2060 nic.nat.llRules.push_back(rule);
2061 }
2062 }
2063 else if ( (elmMode.nameEquals("HostInterface"))
2064 || (elmMode.nameEquals("BridgedInterface")))
2065 {
2066 enmAttachmentType = NetworkAttachmentType_Bridged;
2067
2068 elmMode.getAttributeValue("name", nic.strBridgedName); // optional bridged interface name
2069 }
2070 else if (elmMode.nameEquals("InternalNetwork"))
2071 {
2072 enmAttachmentType = NetworkAttachmentType_Internal;
2073
2074 if (!elmMode.getAttributeValue("name", nic.strInternalNetworkName)) // required network name
2075 throw ConfigFileError(this, &elmMode, N_("Required InternalNetwork/@name element is missing"));
2076 }
2077 else if (elmMode.nameEquals("HostOnlyInterface"))
2078 {
2079 enmAttachmentType = NetworkAttachmentType_HostOnly;
2080
2081 if (!elmMode.getAttributeValue("name", nic.strHostOnlyName)) // required network name
2082 throw ConfigFileError(this, &elmMode, N_("Required HostOnlyInterface/@name element is missing"));
2083 }
2084 else if (elmMode.nameEquals("GenericInterface"))
2085 {
2086 enmAttachmentType = NetworkAttachmentType_Generic;
2087
2088 elmMode.getAttributeValue("driver", nic.strGenericDriver); // optional network attachment driver
2089
2090 // get all properties
2091 xml::NodesLoop nl(elmMode);
2092 const xml::ElementNode *pelmModeChild;
2093 while ((pelmModeChild = nl.forAllNodes()))
2094 {
2095 if (pelmModeChild->nameEquals("Property"))
2096 {
2097 Utf8Str strPropName, strPropValue;
2098 if ( (pelmModeChild->getAttributeValue("name", strPropName))
2099 && (pelmModeChild->getAttributeValue("value", strPropValue))
2100 )
2101 nic.genericProperties[strPropName] = strPropValue;
2102 else
2103 throw ConfigFileError(this, pelmModeChild, N_("Required GenericInterface/Property/@name or @value attribute is missing"));
2104 }
2105 }
2106 }
2107 else if (elmMode.nameEquals("VDE"))
2108 {
2109 enmAttachmentType = NetworkAttachmentType_Generic;
2110
2111 com::Utf8Str strVDEName;
2112 elmMode.getAttributeValue("network", strVDEName); // optional network name
2113 nic.strGenericDriver = "VDE";
2114 nic.genericProperties["network"] = strVDEName;
2115 }
2116
2117 if (fEnabled && enmAttachmentType != NetworkAttachmentType_Null)
2118 nic.mode = enmAttachmentType;
2119}
2120
2121/**
2122 * Called from MachineConfigFile::readHardware() to read serial port information.
2123 * @param elmUART
2124 * @param ll
2125 */
2126void MachineConfigFile::readSerialPorts(const xml::ElementNode &elmUART,
2127 SerialPortsList &ll)
2128{
2129 xml::NodesLoop nl1(elmUART, "Port");
2130 const xml::ElementNode *pelmPort;
2131 while ((pelmPort = nl1.forAllNodes()))
2132 {
2133 SerialPort port;
2134 if (!pelmPort->getAttributeValue("slot", port.ulSlot))
2135 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@slot attribute is missing"));
2136
2137 // slot must be unique
2138 for (SerialPortsList::const_iterator it = ll.begin();
2139 it != ll.end();
2140 ++it)
2141 if ((*it).ulSlot == port.ulSlot)
2142 throw ConfigFileError(this, pelmPort, N_("Invalid value %RU32 in UART/Port/@slot attribute: value is not unique"), port.ulSlot);
2143
2144 if (!pelmPort->getAttributeValue("enabled", port.fEnabled))
2145 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@enabled attribute is missing"));
2146 if (!pelmPort->getAttributeValue("IOBase", port.ulIOBase))
2147 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@IOBase attribute is missing"));
2148 if (!pelmPort->getAttributeValue("IRQ", port.ulIRQ))
2149 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@IRQ attribute is missing"));
2150
2151 Utf8Str strPortMode;
2152 if (!pelmPort->getAttributeValue("hostMode", strPortMode))
2153 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@hostMode attribute is missing"));
2154 if (strPortMode == "RawFile")
2155 port.portMode = PortMode_RawFile;
2156 else if (strPortMode == "HostPipe")
2157 port.portMode = PortMode_HostPipe;
2158 else if (strPortMode == "HostDevice")
2159 port.portMode = PortMode_HostDevice;
2160 else if (strPortMode == "Disconnected")
2161 port.portMode = PortMode_Disconnected;
2162 else
2163 throw ConfigFileError(this, pelmPort, N_("Invalid value '%s' in UART/Port/@hostMode attribute"), strPortMode.c_str());
2164
2165 pelmPort->getAttributeValue("path", port.strPath);
2166 pelmPort->getAttributeValue("server", port.fServer);
2167
2168 ll.push_back(port);
2169 }
2170}
2171
2172/**
2173 * Called from MachineConfigFile::readHardware() to read parallel port information.
2174 * @param elmLPT
2175 * @param ll
2176 */
2177void MachineConfigFile::readParallelPorts(const xml::ElementNode &elmLPT,
2178 ParallelPortsList &ll)
2179{
2180 xml::NodesLoop nl1(elmLPT, "Port");
2181 const xml::ElementNode *pelmPort;
2182 while ((pelmPort = nl1.forAllNodes()))
2183 {
2184 ParallelPort port;
2185 if (!pelmPort->getAttributeValue("slot", port.ulSlot))
2186 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@slot attribute is missing"));
2187
2188 // slot must be unique
2189 for (ParallelPortsList::const_iterator it = ll.begin();
2190 it != ll.end();
2191 ++it)
2192 if ((*it).ulSlot == port.ulSlot)
2193 throw ConfigFileError(this, pelmPort, N_("Invalid value %RU32 in LPT/Port/@slot attribute: value is not unique"), port.ulSlot);
2194
2195 if (!pelmPort->getAttributeValue("enabled", port.fEnabled))
2196 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@enabled attribute is missing"));
2197 if (!pelmPort->getAttributeValue("IOBase", port.ulIOBase))
2198 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@IOBase attribute is missing"));
2199 if (!pelmPort->getAttributeValue("IRQ", port.ulIRQ))
2200 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@IRQ attribute is missing"));
2201
2202 pelmPort->getAttributeValue("path", port.strPath);
2203
2204 ll.push_back(port);
2205 }
2206}
2207
2208/**
2209 * Called from MachineConfigFile::readHardware() to read audio adapter information
2210 * and maybe fix driver information depending on the current host hardware.
2211 *
2212 * @param elmAudioAdapter "AudioAdapter" XML element.
2213 * @param hw
2214 */
2215void MachineConfigFile::readAudioAdapter(const xml::ElementNode &elmAudioAdapter,
2216 AudioAdapter &aa)
2217{
2218 elmAudioAdapter.getAttributeValue("enabled", aa.fEnabled);
2219
2220 Utf8Str strTemp;
2221 if (elmAudioAdapter.getAttributeValue("controller", strTemp))
2222 {
2223 if (strTemp == "SB16")
2224 aa.controllerType = AudioControllerType_SB16;
2225 else if (strTemp == "AC97")
2226 aa.controllerType = AudioControllerType_AC97;
2227 else if (strTemp == "HDA")
2228 aa.controllerType = AudioControllerType_HDA;
2229 else
2230 throw ConfigFileError(this, &elmAudioAdapter, N_("Invalid value '%s' in AudioAdapter/@controller attribute"), strTemp.c_str());
2231 }
2232
2233 if (elmAudioAdapter.getAttributeValue("driver", strTemp))
2234 {
2235 // settings before 1.3 used lower case so make sure this is case-insensitive
2236 strTemp.toUpper();
2237 if (strTemp == "NULL")
2238 aa.driverType = AudioDriverType_Null;
2239 else if (strTemp == "WINMM")
2240 aa.driverType = AudioDriverType_WinMM;
2241 else if ( (strTemp == "DIRECTSOUND") || (strTemp == "DSOUND") )
2242 aa.driverType = AudioDriverType_DirectSound;
2243 else if (strTemp == "SOLAUDIO")
2244 aa.driverType = AudioDriverType_SolAudio;
2245 else if (strTemp == "ALSA")
2246 aa.driverType = AudioDriverType_ALSA;
2247 else if (strTemp == "PULSE")
2248 aa.driverType = AudioDriverType_Pulse;
2249 else if (strTemp == "OSS")
2250 aa.driverType = AudioDriverType_OSS;
2251 else if (strTemp == "COREAUDIO")
2252 aa.driverType = AudioDriverType_CoreAudio;
2253 else if (strTemp == "MMPM")
2254 aa.driverType = AudioDriverType_MMPM;
2255 else
2256 throw ConfigFileError(this, &elmAudioAdapter, N_("Invalid value '%s' in AudioAdapter/@driver attribute"), strTemp.c_str());
2257
2258 // now check if this is actually supported on the current host platform;
2259 // people might be opening a file created on a Windows host, and that
2260 // VM should still start on a Linux host
2261 if (!isAudioDriverAllowedOnThisHost(aa.driverType))
2262 aa.driverType = getHostDefaultAudioDriver();
2263 }
2264}
2265
2266/**
2267 * Called from MachineConfigFile::readHardware() to read guest property information.
2268 * @param elmGuestProperties
2269 * @param hw
2270 */
2271void MachineConfigFile::readGuestProperties(const xml::ElementNode &elmGuestProperties,
2272 Hardware &hw)
2273{
2274 xml::NodesLoop nl1(elmGuestProperties, "GuestProperty");
2275 const xml::ElementNode *pelmProp;
2276 while ((pelmProp = nl1.forAllNodes()))
2277 {
2278 GuestProperty prop;
2279 pelmProp->getAttributeValue("name", prop.strName);
2280 pelmProp->getAttributeValue("value", prop.strValue);
2281
2282 pelmProp->getAttributeValue("timestamp", prop.timestamp);
2283 pelmProp->getAttributeValue("flags", prop.strFlags);
2284 hw.llGuestProperties.push_back(prop);
2285 }
2286
2287 elmGuestProperties.getAttributeValue("notificationPatterns", hw.strNotificationPatterns);
2288}
2289
2290/**
2291 * Helper function to read attributes that are common to <SATAController> (pre-1.7)
2292 * and <StorageController>.
2293 * @param elmStorageController
2294 * @param strg
2295 */
2296void MachineConfigFile::readStorageControllerAttributes(const xml::ElementNode &elmStorageController,
2297 StorageController &sctl)
2298{
2299 elmStorageController.getAttributeValue("PortCount", sctl.ulPortCount);
2300 elmStorageController.getAttributeValue("IDE0MasterEmulationPort", sctl.lIDE0MasterEmulationPort);
2301 elmStorageController.getAttributeValue("IDE0SlaveEmulationPort", sctl.lIDE0SlaveEmulationPort);
2302 elmStorageController.getAttributeValue("IDE1MasterEmulationPort", sctl.lIDE1MasterEmulationPort);
2303 elmStorageController.getAttributeValue("IDE1SlaveEmulationPort", sctl.lIDE1SlaveEmulationPort);
2304
2305 elmStorageController.getAttributeValue("useHostIOCache", sctl.fUseHostIOCache);
2306}
2307
2308/**
2309 * Reads in a <Hardware> block and stores it in the given structure. Used
2310 * both directly from readMachine and from readSnapshot, since snapshots
2311 * have their own hardware sections.
2312 *
2313 * For legacy pre-1.7 settings we also need a storage structure because
2314 * the IDE and SATA controllers used to be defined under <Hardware>.
2315 *
2316 * @param elmHardware
2317 * @param hw
2318 */
2319void MachineConfigFile::readHardware(const xml::ElementNode &elmHardware,
2320 Hardware &hw,
2321 Storage &strg)
2322{
2323 if (!elmHardware.getAttributeValue("version", hw.strVersion))
2324 {
2325 /* KLUDGE ALERT! For a while during the 3.1 development this was not
2326 written because it was thought to have a default value of "2". For
2327 sv <= 1.3 it defaults to "1" because the attribute didn't exist,
2328 while for 1.4+ it is sort of mandatory. Now, the buggy XML writer
2329 code only wrote 1.7 and later. So, if it's a 1.7+ XML file and it's
2330 missing the hardware version, then it probably should be "2" instead
2331 of "1". */
2332 if (m->sv < SettingsVersion_v1_7)
2333 hw.strVersion = "1";
2334 else
2335 hw.strVersion = "2";
2336 }
2337 Utf8Str strUUID;
2338 if (elmHardware.getAttributeValue("uuid", strUUID))
2339 parseUUID(hw.uuid, strUUID);
2340
2341 xml::NodesLoop nl1(elmHardware);
2342 const xml::ElementNode *pelmHwChild;
2343 while ((pelmHwChild = nl1.forAllNodes()))
2344 {
2345 if (pelmHwChild->nameEquals("CPU"))
2346 {
2347 if (!pelmHwChild->getAttributeValue("count", hw.cCPUs))
2348 {
2349 // pre-1.5 variant; not sure if this actually exists in the wild anywhere
2350 const xml::ElementNode *pelmCPUChild;
2351 if ((pelmCPUChild = pelmHwChild->findChildElement("CPUCount")))
2352 pelmCPUChild->getAttributeValue("count", hw.cCPUs);
2353 }
2354
2355 pelmHwChild->getAttributeValue("hotplug", hw.fCpuHotPlug);
2356 pelmHwChild->getAttributeValue("executionCap", hw.ulCpuExecutionCap);
2357
2358 const xml::ElementNode *pelmCPUChild;
2359 if (hw.fCpuHotPlug)
2360 {
2361 if ((pelmCPUChild = pelmHwChild->findChildElement("CpuTree")))
2362 readCpuTree(*pelmCPUChild, hw.llCpus);
2363 }
2364
2365 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtEx")))
2366 {
2367 pelmCPUChild->getAttributeValue("enabled", hw.fHardwareVirt);
2368 pelmCPUChild->getAttributeValue("exclusive", hw.fHardwareVirtExclusive); // settings version 1.9
2369 }
2370 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExNestedPaging")))
2371 pelmCPUChild->getAttributeValue("enabled", hw.fNestedPaging);
2372 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExLargePages")))
2373 pelmCPUChild->getAttributeValue("enabled", hw.fLargePages);
2374 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExVPID")))
2375 pelmCPUChild->getAttributeValue("enabled", hw.fVPID);
2376 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtForce")))
2377 pelmCPUChild->getAttributeValue("enabled", hw.fHardwareVirtForce);
2378
2379 if (!(pelmCPUChild = pelmHwChild->findChildElement("PAE")))
2380 {
2381 /* The default for pre 3.1 was false, so we must respect that. */
2382 if (m->sv < SettingsVersion_v1_9)
2383 hw.fPAE = false;
2384 }
2385 else
2386 pelmCPUChild->getAttributeValue("enabled", hw.fPAE);
2387
2388 if ((pelmCPUChild = pelmHwChild->findChildElement("SyntheticCpu")))
2389 pelmCPUChild->getAttributeValue("enabled", hw.fSyntheticCpu);
2390 if ((pelmCPUChild = pelmHwChild->findChildElement("CpuIdTree")))
2391 readCpuIdTree(*pelmCPUChild, hw.llCpuIdLeafs);
2392 }
2393 else if (pelmHwChild->nameEquals("Memory"))
2394 {
2395 pelmHwChild->getAttributeValue("RAMSize", hw.ulMemorySizeMB);
2396 pelmHwChild->getAttributeValue("PageFusion", hw.fPageFusionEnabled);
2397 }
2398 else if (pelmHwChild->nameEquals("Firmware"))
2399 {
2400 Utf8Str strFirmwareType;
2401 if (pelmHwChild->getAttributeValue("type", strFirmwareType))
2402 {
2403 if ( (strFirmwareType == "BIOS")
2404 || (strFirmwareType == "1") // some trunk builds used the number here
2405 )
2406 hw.firmwareType = FirmwareType_BIOS;
2407 else if ( (strFirmwareType == "EFI")
2408 || (strFirmwareType == "2") // some trunk builds used the number here
2409 )
2410 hw.firmwareType = FirmwareType_EFI;
2411 else if ( strFirmwareType == "EFI32")
2412 hw.firmwareType = FirmwareType_EFI32;
2413 else if ( strFirmwareType == "EFI64")
2414 hw.firmwareType = FirmwareType_EFI64;
2415 else if ( strFirmwareType == "EFIDUAL")
2416 hw.firmwareType = FirmwareType_EFIDUAL;
2417 else
2418 throw ConfigFileError(this,
2419 pelmHwChild,
2420 N_("Invalid value '%s' in Firmware/@type"),
2421 strFirmwareType.c_str());
2422 }
2423 }
2424 else if (pelmHwChild->nameEquals("HID"))
2425 {
2426 Utf8Str strHidType;
2427 if (pelmHwChild->getAttributeValue("Keyboard", strHidType))
2428 {
2429 if (strHidType == "None")
2430 hw.keyboardHidType = KeyboardHidType_None;
2431 else if (strHidType == "USBKeyboard")
2432 hw.keyboardHidType = KeyboardHidType_USBKeyboard;
2433 else if (strHidType == "PS2Keyboard")
2434 hw.keyboardHidType = KeyboardHidType_PS2Keyboard;
2435 else if (strHidType == "ComboKeyboard")
2436 hw.keyboardHidType = KeyboardHidType_ComboKeyboard;
2437 else
2438 throw ConfigFileError(this,
2439 pelmHwChild,
2440 N_("Invalid value '%s' in HID/Keyboard/@type"),
2441 strHidType.c_str());
2442 }
2443 if (pelmHwChild->getAttributeValue("Pointing", strHidType))
2444 {
2445 if (strHidType == "None")
2446 hw.pointingHidType = PointingHidType_None;
2447 else if (strHidType == "USBMouse")
2448 hw.pointingHidType = PointingHidType_USBMouse;
2449 else if (strHidType == "USBTablet")
2450 hw.pointingHidType = PointingHidType_USBTablet;
2451 else if (strHidType == "PS2Mouse")
2452 hw.pointingHidType = PointingHidType_PS2Mouse;
2453 else if (strHidType == "ComboMouse")
2454 hw.pointingHidType = PointingHidType_ComboMouse;
2455 else
2456 throw ConfigFileError(this,
2457 pelmHwChild,
2458 N_("Invalid value '%s' in HID/Pointing/@type"),
2459 strHidType.c_str());
2460 }
2461 }
2462 else if (pelmHwChild->nameEquals("Chipset"))
2463 {
2464 Utf8Str strChipsetType;
2465 if (pelmHwChild->getAttributeValue("type", strChipsetType))
2466 {
2467 if (strChipsetType == "PIIX3")
2468 hw.chipsetType = ChipsetType_PIIX3;
2469 else if (strChipsetType == "ICH9")
2470 hw.chipsetType = ChipsetType_ICH9;
2471 else
2472 throw ConfigFileError(this,
2473 pelmHwChild,
2474 N_("Invalid value '%s' in Chipset/@type"),
2475 strChipsetType.c_str());
2476 }
2477 }
2478 else if (pelmHwChild->nameEquals("HPET"))
2479 {
2480 pelmHwChild->getAttributeValue("enabled", hw.fHpetEnabled);
2481 }
2482 else if (pelmHwChild->nameEquals("Boot"))
2483 {
2484 hw.mapBootOrder.clear();
2485
2486 xml::NodesLoop nl2(*pelmHwChild, "Order");
2487 const xml::ElementNode *pelmOrder;
2488 while ((pelmOrder = nl2.forAllNodes()))
2489 {
2490 uint32_t ulPos;
2491 Utf8Str strDevice;
2492 if (!pelmOrder->getAttributeValue("position", ulPos))
2493 throw ConfigFileError(this, pelmOrder, N_("Required Boot/Order/@position attribute is missing"));
2494
2495 if ( ulPos < 1
2496 || ulPos > SchemaDefs::MaxBootPosition
2497 )
2498 throw ConfigFileError(this,
2499 pelmOrder,
2500 N_("Invalid value '%RU32' in Boot/Order/@position: must be greater than 0 and less than %RU32"),
2501 ulPos,
2502 SchemaDefs::MaxBootPosition + 1);
2503 // XML is 1-based but internal data is 0-based
2504 --ulPos;
2505
2506 if (hw.mapBootOrder.find(ulPos) != hw.mapBootOrder.end())
2507 throw ConfigFileError(this, pelmOrder, N_("Invalid value '%RU32' in Boot/Order/@position: value is not unique"), ulPos);
2508
2509 if (!pelmOrder->getAttributeValue("device", strDevice))
2510 throw ConfigFileError(this, pelmOrder, N_("Required Boot/Order/@device attribute is missing"));
2511
2512 DeviceType_T type;
2513 if (strDevice == "None")
2514 type = DeviceType_Null;
2515 else if (strDevice == "Floppy")
2516 type = DeviceType_Floppy;
2517 else if (strDevice == "DVD")
2518 type = DeviceType_DVD;
2519 else if (strDevice == "HardDisk")
2520 type = DeviceType_HardDisk;
2521 else if (strDevice == "Network")
2522 type = DeviceType_Network;
2523 else
2524 throw ConfigFileError(this, pelmOrder, N_("Invalid value '%s' in Boot/Order/@device attribute"), strDevice.c_str());
2525 hw.mapBootOrder[ulPos] = type;
2526 }
2527 }
2528 else if (pelmHwChild->nameEquals("Display"))
2529 {
2530 pelmHwChild->getAttributeValue("VRAMSize", hw.ulVRAMSizeMB);
2531 if (!pelmHwChild->getAttributeValue("monitorCount", hw.cMonitors))
2532 pelmHwChild->getAttributeValue("MonitorCount", hw.cMonitors); // pre-v1.5 variant
2533 if (!pelmHwChild->getAttributeValue("accelerate3D", hw.fAccelerate3D))
2534 pelmHwChild->getAttributeValue("Accelerate3D", hw.fAccelerate3D); // pre-v1.5 variant
2535 pelmHwChild->getAttributeValue("accelerate2DVideo", hw.fAccelerate2DVideo);
2536 }
2537 else if (pelmHwChild->nameEquals("RemoteDisplay"))
2538 {
2539 pelmHwChild->getAttributeValue("enabled", hw.vrdeSettings.fEnabled);
2540
2541 Utf8Str str;
2542 if (pelmHwChild->getAttributeValue("port", str))
2543 hw.vrdeSettings.mapProperties["TCP/Ports"] = str;
2544 if (pelmHwChild->getAttributeValue("netAddress", str))
2545 hw.vrdeSettings.mapProperties["TCP/Address"] = str;
2546
2547 Utf8Str strAuthType;
2548 if (pelmHwChild->getAttributeValue("authType", strAuthType))
2549 {
2550 // settings before 1.3 used lower case so make sure this is case-insensitive
2551 strAuthType.toUpper();
2552 if (strAuthType == "NULL")
2553 hw.vrdeSettings.authType = AuthType_Null;
2554 else if (strAuthType == "GUEST")
2555 hw.vrdeSettings.authType = AuthType_Guest;
2556 else if (strAuthType == "EXTERNAL")
2557 hw.vrdeSettings.authType = AuthType_External;
2558 else
2559 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in RemoteDisplay/@authType attribute"), strAuthType.c_str());
2560 }
2561
2562 pelmHwChild->getAttributeValue("authLibrary", hw.vrdeSettings.strAuthLibrary);
2563 pelmHwChild->getAttributeValue("authTimeout", hw.vrdeSettings.ulAuthTimeout);
2564 pelmHwChild->getAttributeValue("allowMultiConnection", hw.vrdeSettings.fAllowMultiConnection);
2565 pelmHwChild->getAttributeValue("reuseSingleConnection", hw.vrdeSettings.fReuseSingleConnection);
2566
2567 /* 3.2 and 4.0 betas, 4.0 has this information in VRDEProperties. */
2568 const xml::ElementNode *pelmVideoChannel;
2569 if ((pelmVideoChannel = pelmHwChild->findChildElement("VideoChannel")))
2570 {
2571 bool fVideoChannel = false;
2572 pelmVideoChannel->getAttributeValue("enabled", fVideoChannel);
2573 hw.vrdeSettings.mapProperties["VideoChannel/Enabled"] = fVideoChannel? "true": "false";
2574
2575 uint32_t ulVideoChannelQuality = 75;
2576 pelmVideoChannel->getAttributeValue("quality", ulVideoChannelQuality);
2577 ulVideoChannelQuality = RT_CLAMP(ulVideoChannelQuality, 10, 100);
2578 char *pszBuffer = NULL;
2579 if (RTStrAPrintf(&pszBuffer, "%d", ulVideoChannelQuality) >= 0)
2580 {
2581 hw.vrdeSettings.mapProperties["VideoChannel/Quality"] = pszBuffer;
2582 RTStrFree(pszBuffer);
2583 }
2584 else
2585 hw.vrdeSettings.mapProperties["VideoChannel/Quality"] = "75";
2586 }
2587 pelmHwChild->getAttributeValue("VRDEExtPack", hw.vrdeSettings.strVrdeExtPack);
2588
2589 const xml::ElementNode *pelmProperties = pelmHwChild->findChildElement("VRDEProperties");
2590 if (pelmProperties != NULL)
2591 {
2592 xml::NodesLoop nl(*pelmProperties);
2593 const xml::ElementNode *pelmProperty;
2594 while ((pelmProperty = nl.forAllNodes()))
2595 {
2596 if (pelmProperty->nameEquals("Property"))
2597 {
2598 /* <Property name="TCP/Ports" value="3000-3002"/> */
2599 Utf8Str strName, strValue;
2600 if ( ((pelmProperty->getAttributeValue("name", strName)))
2601 && ((pelmProperty->getAttributeValue("value", strValue)))
2602 )
2603 hw.vrdeSettings.mapProperties[strName] = strValue;
2604 else
2605 throw ConfigFileError(this, pelmProperty, N_("Required VRDE Property/@name or @value attribute is missing"));
2606 }
2607 }
2608 }
2609 }
2610 else if (pelmHwChild->nameEquals("BIOS"))
2611 {
2612 const xml::ElementNode *pelmBIOSChild;
2613 if ((pelmBIOSChild = pelmHwChild->findChildElement("ACPI")))
2614 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fACPIEnabled);
2615 if ((pelmBIOSChild = pelmHwChild->findChildElement("IOAPIC")))
2616 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fIOAPICEnabled);
2617 if ((pelmBIOSChild = pelmHwChild->findChildElement("Logo")))
2618 {
2619 pelmBIOSChild->getAttributeValue("fadeIn", hw.biosSettings.fLogoFadeIn);
2620 pelmBIOSChild->getAttributeValue("fadeOut", hw.biosSettings.fLogoFadeOut);
2621 pelmBIOSChild->getAttributeValue("displayTime", hw.biosSettings.ulLogoDisplayTime);
2622 pelmBIOSChild->getAttributeValue("imagePath", hw.biosSettings.strLogoImagePath);
2623 }
2624 if ((pelmBIOSChild = pelmHwChild->findChildElement("BootMenu")))
2625 {
2626 Utf8Str strBootMenuMode;
2627 if (pelmBIOSChild->getAttributeValue("mode", strBootMenuMode))
2628 {
2629 // settings before 1.3 used lower case so make sure this is case-insensitive
2630 strBootMenuMode.toUpper();
2631 if (strBootMenuMode == "DISABLED")
2632 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_Disabled;
2633 else if (strBootMenuMode == "MENUONLY")
2634 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_MenuOnly;
2635 else if (strBootMenuMode == "MESSAGEANDMENU")
2636 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_MessageAndMenu;
2637 else
2638 throw ConfigFileError(this, pelmBIOSChild, N_("Invalid value '%s' in BootMenu/@mode attribute"), strBootMenuMode.c_str());
2639 }
2640 }
2641 if ((pelmBIOSChild = pelmHwChild->findChildElement("PXEDebug")))
2642 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fPXEDebugEnabled);
2643 if ((pelmBIOSChild = pelmHwChild->findChildElement("TimeOffset")))
2644 pelmBIOSChild->getAttributeValue("value", hw.biosSettings.llTimeOffset);
2645
2646 // legacy BIOS/IDEController (pre 1.7)
2647 if ( (m->sv < SettingsVersion_v1_7)
2648 && ((pelmBIOSChild = pelmHwChild->findChildElement("IDEController")))
2649 )
2650 {
2651 StorageController sctl;
2652 sctl.strName = "IDE Controller";
2653 sctl.storageBus = StorageBus_IDE;
2654
2655 Utf8Str strType;
2656 if (pelmBIOSChild->getAttributeValue("type", strType))
2657 {
2658 if (strType == "PIIX3")
2659 sctl.controllerType = StorageControllerType_PIIX3;
2660 else if (strType == "PIIX4")
2661 sctl.controllerType = StorageControllerType_PIIX4;
2662 else if (strType == "ICH6")
2663 sctl.controllerType = StorageControllerType_ICH6;
2664 else
2665 throw ConfigFileError(this, pelmBIOSChild, N_("Invalid value '%s' for IDEController/@type attribute"), strType.c_str());
2666 }
2667 sctl.ulPortCount = 2;
2668 strg.llStorageControllers.push_back(sctl);
2669 }
2670 }
2671 else if (pelmHwChild->nameEquals("USBController"))
2672 {
2673 pelmHwChild->getAttributeValue("enabled", hw.usbController.fEnabled);
2674 pelmHwChild->getAttributeValue("enabledEhci", hw.usbController.fEnabledEHCI);
2675
2676 readUSBDeviceFilters(*pelmHwChild,
2677 hw.usbController.llDeviceFilters);
2678 }
2679 else if ( (m->sv < SettingsVersion_v1_7)
2680 && (pelmHwChild->nameEquals("SATAController"))
2681 )
2682 {
2683 bool f;
2684 if ( (pelmHwChild->getAttributeValue("enabled", f))
2685 && (f)
2686 )
2687 {
2688 StorageController sctl;
2689 sctl.strName = "SATA Controller";
2690 sctl.storageBus = StorageBus_SATA;
2691 sctl.controllerType = StorageControllerType_IntelAhci;
2692
2693 readStorageControllerAttributes(*pelmHwChild, sctl);
2694
2695 strg.llStorageControllers.push_back(sctl);
2696 }
2697 }
2698 else if (pelmHwChild->nameEquals("Network"))
2699 readNetworkAdapters(*pelmHwChild, hw.llNetworkAdapters);
2700 else if (pelmHwChild->nameEquals("RTC"))
2701 {
2702 Utf8Str strLocalOrUTC;
2703 machineUserData.fRTCUseUTC = pelmHwChild->getAttributeValue("localOrUTC", strLocalOrUTC)
2704 && strLocalOrUTC == "UTC";
2705 }
2706 else if ( (pelmHwChild->nameEquals("UART"))
2707 || (pelmHwChild->nameEquals("Uart")) // used before 1.3
2708 )
2709 readSerialPorts(*pelmHwChild, hw.llSerialPorts);
2710 else if ( (pelmHwChild->nameEquals("LPT"))
2711 || (pelmHwChild->nameEquals("Lpt")) // used before 1.3
2712 )
2713 readParallelPorts(*pelmHwChild, hw.llParallelPorts);
2714 else if (pelmHwChild->nameEquals("AudioAdapter"))
2715 readAudioAdapter(*pelmHwChild, hw.audioAdapter);
2716 else if (pelmHwChild->nameEquals("SharedFolders"))
2717 {
2718 xml::NodesLoop nl2(*pelmHwChild, "SharedFolder");
2719 const xml::ElementNode *pelmFolder;
2720 while ((pelmFolder = nl2.forAllNodes()))
2721 {
2722 SharedFolder sf;
2723 pelmFolder->getAttributeValue("name", sf.strName);
2724 pelmFolder->getAttributeValue("hostPath", sf.strHostPath);
2725 pelmFolder->getAttributeValue("writable", sf.fWritable);
2726 pelmFolder->getAttributeValue("autoMount", sf.fAutoMount);
2727 hw.llSharedFolders.push_back(sf);
2728 }
2729 }
2730 else if (pelmHwChild->nameEquals("Clipboard"))
2731 {
2732 Utf8Str strTemp;
2733 if (pelmHwChild->getAttributeValue("mode", strTemp))
2734 {
2735 if (strTemp == "Disabled")
2736 hw.clipboardMode = ClipboardMode_Disabled;
2737 else if (strTemp == "HostToGuest")
2738 hw.clipboardMode = ClipboardMode_HostToGuest;
2739 else if (strTemp == "GuestToHost")
2740 hw.clipboardMode = ClipboardMode_GuestToHost;
2741 else if (strTemp == "Bidirectional")
2742 hw.clipboardMode = ClipboardMode_Bidirectional;
2743 else
2744 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in Clipboard/@mode attribute"), strTemp.c_str());
2745 }
2746 }
2747 else if (pelmHwChild->nameEquals("Guest"))
2748 {
2749 if (!pelmHwChild->getAttributeValue("memoryBalloonSize", hw.ulMemoryBalloonSize))
2750 pelmHwChild->getAttributeValue("MemoryBalloonSize", hw.ulMemoryBalloonSize); // used before 1.3
2751 }
2752 else if (pelmHwChild->nameEquals("GuestProperties"))
2753 readGuestProperties(*pelmHwChild, hw);
2754 else if (pelmHwChild->nameEquals("IO"))
2755 {
2756 const xml::ElementNode *pelmBwGroups;
2757 const xml::ElementNode *pelmIoChild;
2758
2759 if ((pelmIoChild = pelmHwChild->findChildElement("IoCache")))
2760 {
2761 pelmIoChild->getAttributeValue("enabled", hw.ioSettings.fIoCacheEnabled);
2762 pelmIoChild->getAttributeValue("size", hw.ioSettings.ulIoCacheSize);
2763 }
2764
2765 if ((pelmBwGroups = pelmHwChild->findChildElement("BandwidthGroups")))
2766 {
2767 xml::NodesLoop nl2(*pelmBwGroups, "BandwidthGroup");
2768 const xml::ElementNode *pelmBandwidthGroup;
2769 while ((pelmBandwidthGroup = nl2.forAllNodes()))
2770 {
2771 BandwidthGroup gr;
2772 Utf8Str strTemp;
2773
2774 pelmBandwidthGroup->getAttributeValue("name", gr.strName);
2775
2776 if (pelmBandwidthGroup->getAttributeValue("type", strTemp))
2777 {
2778 if (strTemp == "Disk")
2779 gr.enmType = BandwidthGroupType_Disk;
2780 else if (strTemp == "Network")
2781 gr.enmType = BandwidthGroupType_Network;
2782 else
2783 throw ConfigFileError(this, pelmBandwidthGroup, N_("Invalid value '%s' in BandwidthGroup/@type attribute"), strTemp.c_str());
2784 }
2785 else
2786 throw ConfigFileError(this, pelmBandwidthGroup, N_("Missing BandwidthGroup/@type attribute"));
2787
2788 pelmBandwidthGroup->getAttributeValue("maxMbPerSec", gr.cMaxMbPerSec);
2789 hw.ioSettings.llBandwidthGroups.push_back(gr);
2790 }
2791 }
2792 } else if (pelmHwChild->nameEquals("HostPci")) {
2793 const xml::ElementNode *pelmDevices;
2794
2795 if ((pelmDevices = pelmHwChild->findChildElement("Devices")))
2796 {
2797 xml::NodesLoop nl2(*pelmDevices, "Device");
2798 const xml::ElementNode *pelmDevice;
2799 while ((pelmDevice = nl2.forAllNodes()))
2800 {
2801 HostPciDeviceAttachment hpda;
2802
2803 if (!pelmDevice->getAttributeValue("host", hpda.uHostAddress))
2804 throw ConfigFileError(this, pelmDevice, N_("Missing Device/@host attribute"));
2805
2806 if (!pelmDevice->getAttributeValue("guest", hpda.uGuestAddress))
2807 throw ConfigFileError(this, pelmDevice, N_("Missing Device/@guest attribute"));
2808
2809 /* name is optional */
2810 pelmDevice->getAttributeValue("name", hpda.strDeviceName);
2811
2812 hw.pciAttachments.push_back(hpda);
2813 }
2814 }
2815 }
2816 }
2817
2818 if (hw.ulMemorySizeMB == (uint32_t)-1)
2819 throw ConfigFileError(this, &elmHardware, N_("Required Memory/@RAMSize element/attribute is missing"));
2820}
2821
2822/**
2823 * This gets called instead of readStorageControllers() for legacy pre-1.7 settings
2824 * files which have a <HardDiskAttachments> node and storage controller settings
2825 * hidden in the <Hardware> settings. We set the StorageControllers fields just the
2826 * same, just from different sources.
2827 * @param elmHardware <Hardware> XML node.
2828 * @param elmHardDiskAttachments <HardDiskAttachments> XML node.
2829 * @param strg
2830 */
2831void MachineConfigFile::readHardDiskAttachments_pre1_7(const xml::ElementNode &elmHardDiskAttachments,
2832 Storage &strg)
2833{
2834 StorageController *pIDEController = NULL;
2835 StorageController *pSATAController = NULL;
2836
2837 for (StorageControllersList::iterator it = strg.llStorageControllers.begin();
2838 it != strg.llStorageControllers.end();
2839 ++it)
2840 {
2841 StorageController &s = *it;
2842 if (s.storageBus == StorageBus_IDE)
2843 pIDEController = &s;
2844 else if (s.storageBus == StorageBus_SATA)
2845 pSATAController = &s;
2846 }
2847
2848 xml::NodesLoop nl1(elmHardDiskAttachments, "HardDiskAttachment");
2849 const xml::ElementNode *pelmAttachment;
2850 while ((pelmAttachment = nl1.forAllNodes()))
2851 {
2852 AttachedDevice att;
2853 Utf8Str strUUID, strBus;
2854
2855 if (!pelmAttachment->getAttributeValue("hardDisk", strUUID))
2856 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@hardDisk attribute is missing"));
2857 parseUUID(att.uuid, strUUID);
2858
2859 if (!pelmAttachment->getAttributeValue("bus", strBus))
2860 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@bus attribute is missing"));
2861 // pre-1.7 'channel' is now port
2862 if (!pelmAttachment->getAttributeValue("channel", att.lPort))
2863 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@channel attribute is missing"));
2864 // pre-1.7 'device' is still device
2865 if (!pelmAttachment->getAttributeValue("device", att.lDevice))
2866 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@device attribute is missing"));
2867
2868 att.deviceType = DeviceType_HardDisk;
2869
2870 if (strBus == "IDE")
2871 {
2872 if (!pIDEController)
2873 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus is 'IDE' but cannot find IDE controller"));
2874 pIDEController->llAttachedDevices.push_back(att);
2875 }
2876 else if (strBus == "SATA")
2877 {
2878 if (!pSATAController)
2879 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus is 'SATA' but cannot find SATA controller"));
2880 pSATAController->llAttachedDevices.push_back(att);
2881 }
2882 else
2883 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus attribute has illegal value '%s'"), strBus.c_str());
2884 }
2885}
2886
2887/**
2888 * Reads in a <StorageControllers> block and stores it in the given Storage structure.
2889 * Used both directly from readMachine and from readSnapshot, since snapshots
2890 * have their own storage controllers sections.
2891 *
2892 * This is only called for settings version 1.7 and above; see readHardDiskAttachments_pre1_7()
2893 * for earlier versions.
2894 *
2895 * @param elmStorageControllers
2896 */
2897void MachineConfigFile::readStorageControllers(const xml::ElementNode &elmStorageControllers,
2898 Storage &strg)
2899{
2900 xml::NodesLoop nlStorageControllers(elmStorageControllers, "StorageController");
2901 const xml::ElementNode *pelmController;
2902 while ((pelmController = nlStorageControllers.forAllNodes()))
2903 {
2904 StorageController sctl;
2905
2906 if (!pelmController->getAttributeValue("name", sctl.strName))
2907 throw ConfigFileError(this, pelmController, N_("Required StorageController/@name attribute is missing"));
2908 // canonicalize storage controller names for configs in the switchover
2909 // period.
2910 if (m->sv < SettingsVersion_v1_9)
2911 {
2912 if (sctl.strName == "IDE")
2913 sctl.strName = "IDE Controller";
2914 else if (sctl.strName == "SATA")
2915 sctl.strName = "SATA Controller";
2916 else if (sctl.strName == "SCSI")
2917 sctl.strName = "SCSI Controller";
2918 }
2919
2920 pelmController->getAttributeValue("Instance", sctl.ulInstance);
2921 // default from constructor is 0
2922
2923 pelmController->getAttributeValue("Bootable", sctl.fBootable);
2924 // default from constructor is true which is true
2925 // for settings below version 1.11 because they allowed only
2926 // one controller per type.
2927
2928 Utf8Str strType;
2929 if (!pelmController->getAttributeValue("type", strType))
2930 throw ConfigFileError(this, pelmController, N_("Required StorageController/@type attribute is missing"));
2931
2932 if (strType == "AHCI")
2933 {
2934 sctl.storageBus = StorageBus_SATA;
2935 sctl.controllerType = StorageControllerType_IntelAhci;
2936 }
2937 else if (strType == "LsiLogic")
2938 {
2939 sctl.storageBus = StorageBus_SCSI;
2940 sctl.controllerType = StorageControllerType_LsiLogic;
2941 }
2942 else if (strType == "BusLogic")
2943 {
2944 sctl.storageBus = StorageBus_SCSI;
2945 sctl.controllerType = StorageControllerType_BusLogic;
2946 }
2947 else if (strType == "PIIX3")
2948 {
2949 sctl.storageBus = StorageBus_IDE;
2950 sctl.controllerType = StorageControllerType_PIIX3;
2951 }
2952 else if (strType == "PIIX4")
2953 {
2954 sctl.storageBus = StorageBus_IDE;
2955 sctl.controllerType = StorageControllerType_PIIX4;
2956 }
2957 else if (strType == "ICH6")
2958 {
2959 sctl.storageBus = StorageBus_IDE;
2960 sctl.controllerType = StorageControllerType_ICH6;
2961 }
2962 else if ( (m->sv >= SettingsVersion_v1_9)
2963 && (strType == "I82078")
2964 )
2965 {
2966 sctl.storageBus = StorageBus_Floppy;
2967 sctl.controllerType = StorageControllerType_I82078;
2968 }
2969 else if (strType == "LsiLogicSas")
2970 {
2971 sctl.storageBus = StorageBus_SAS;
2972 sctl.controllerType = StorageControllerType_LsiLogicSas;
2973 }
2974 else
2975 throw ConfigFileError(this, pelmController, N_("Invalid value '%s' for StorageController/@type attribute"), strType.c_str());
2976
2977 readStorageControllerAttributes(*pelmController, sctl);
2978
2979 xml::NodesLoop nlAttached(*pelmController, "AttachedDevice");
2980 const xml::ElementNode *pelmAttached;
2981 while ((pelmAttached = nlAttached.forAllNodes()))
2982 {
2983 AttachedDevice att;
2984 Utf8Str strTemp;
2985 pelmAttached->getAttributeValue("type", strTemp);
2986
2987 if (strTemp == "HardDisk")
2988 {
2989 att.deviceType = DeviceType_HardDisk;
2990 pelmAttached->getAttributeValue("nonrotational", att.fNonRotational);
2991 }
2992 else if (m->sv >= SettingsVersion_v1_9)
2993 {
2994 // starting with 1.9 we list DVD and floppy drive info + attachments under <StorageControllers>
2995 if (strTemp == "DVD")
2996 {
2997 att.deviceType = DeviceType_DVD;
2998 pelmAttached->getAttributeValue("passthrough", att.fPassThrough);
2999 pelmAttached->getAttributeValue("tempeject", att.fTempEject);
3000 }
3001 else if (strTemp == "Floppy")
3002 att.deviceType = DeviceType_Floppy;
3003 }
3004
3005 if (att.deviceType != DeviceType_Null)
3006 {
3007 const xml::ElementNode *pelmImage;
3008 // all types can have images attached, but for HardDisk it's required
3009 if (!(pelmImage = pelmAttached->findChildElement("Image")))
3010 {
3011 if (att.deviceType == DeviceType_HardDisk)
3012 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/Image element is missing"));
3013 else
3014 {
3015 // DVDs and floppies can also have <HostDrive> instead of <Image>
3016 const xml::ElementNode *pelmHostDrive;
3017 if ((pelmHostDrive = pelmAttached->findChildElement("HostDrive")))
3018 if (!pelmHostDrive->getAttributeValue("src", att.strHostDriveSrc))
3019 throw ConfigFileError(this, pelmHostDrive, N_("Required AttachedDevice/HostDrive/@src attribute is missing"));
3020 }
3021 }
3022 else
3023 {
3024 if (!pelmImage->getAttributeValue("uuid", strTemp))
3025 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/Image/@uuid attribute is missing"));
3026 parseUUID(att.uuid, strTemp);
3027 }
3028
3029 if (!pelmAttached->getAttributeValue("port", att.lPort))
3030 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/@port attribute is missing"));
3031 if (!pelmAttached->getAttributeValue("device", att.lDevice))
3032 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/@device attribute is missing"));
3033
3034 pelmAttached->getAttributeValue("bandwidthGroup", att.strBwGroup);
3035 sctl.llAttachedDevices.push_back(att);
3036 }
3037 }
3038
3039 strg.llStorageControllers.push_back(sctl);
3040 }
3041}
3042
3043/**
3044 * This gets called for legacy pre-1.9 settings files after having parsed the
3045 * <Hardware> and <StorageControllers> sections to parse <Hardware> once more
3046 * for the <DVDDrive> and <FloppyDrive> sections.
3047 *
3048 * Before settings version 1.9, DVD and floppy drives were specified separately
3049 * under <Hardware>; we then need this extra loop to make sure the storage
3050 * controller structs are already set up so we can add stuff to them.
3051 *
3052 * @param elmHardware
3053 * @param strg
3054 */
3055void MachineConfigFile::readDVDAndFloppies_pre1_9(const xml::ElementNode &elmHardware,
3056 Storage &strg)
3057{
3058 xml::NodesLoop nl1(elmHardware);
3059 const xml::ElementNode *pelmHwChild;
3060 while ((pelmHwChild = nl1.forAllNodes()))
3061 {
3062 if (pelmHwChild->nameEquals("DVDDrive"))
3063 {
3064 // create a DVD "attached device" and attach it to the existing IDE controller
3065 AttachedDevice att;
3066 att.deviceType = DeviceType_DVD;
3067 // legacy DVD drive is always secondary master (port 1, device 0)
3068 att.lPort = 1;
3069 att.lDevice = 0;
3070 pelmHwChild->getAttributeValue("passthrough", att.fPassThrough);
3071 pelmHwChild->getAttributeValue("tempeject", att.fTempEject);
3072
3073 const xml::ElementNode *pDriveChild;
3074 Utf8Str strTmp;
3075 if ( ((pDriveChild = pelmHwChild->findChildElement("Image")))
3076 && (pDriveChild->getAttributeValue("uuid", strTmp))
3077 )
3078 parseUUID(att.uuid, strTmp);
3079 else if ((pDriveChild = pelmHwChild->findChildElement("HostDrive")))
3080 pDriveChild->getAttributeValue("src", att.strHostDriveSrc);
3081
3082 // find the IDE controller and attach the DVD drive
3083 bool fFound = false;
3084 for (StorageControllersList::iterator it = strg.llStorageControllers.begin();
3085 it != strg.llStorageControllers.end();
3086 ++it)
3087 {
3088 StorageController &sctl = *it;
3089 if (sctl.storageBus == StorageBus_IDE)
3090 {
3091 sctl.llAttachedDevices.push_back(att);
3092 fFound = true;
3093 break;
3094 }
3095 }
3096
3097 if (!fFound)
3098 throw ConfigFileError(this, pelmHwChild, N_("Internal error: found DVD drive but IDE controller does not exist"));
3099 // shouldn't happen because pre-1.9 settings files always had at least one IDE controller in the settings
3100 // which should have gotten parsed in <StorageControllers> before this got called
3101 }
3102 else if (pelmHwChild->nameEquals("FloppyDrive"))
3103 {
3104 bool fEnabled;
3105 if ( (pelmHwChild->getAttributeValue("enabled", fEnabled))
3106 && (fEnabled)
3107 )
3108 {
3109 // create a new floppy controller and attach a floppy "attached device"
3110 StorageController sctl;
3111 sctl.strName = "Floppy Controller";
3112 sctl.storageBus = StorageBus_Floppy;
3113 sctl.controllerType = StorageControllerType_I82078;
3114 sctl.ulPortCount = 1;
3115
3116 AttachedDevice att;
3117 att.deviceType = DeviceType_Floppy;
3118 att.lPort = 0;
3119 att.lDevice = 0;
3120
3121 const xml::ElementNode *pDriveChild;
3122 Utf8Str strTmp;
3123 if ( ((pDriveChild = pelmHwChild->findChildElement("Image")))
3124 && (pDriveChild->getAttributeValue("uuid", strTmp))
3125 )
3126 parseUUID(att.uuid, strTmp);
3127 else if ((pDriveChild = pelmHwChild->findChildElement("HostDrive")))
3128 pDriveChild->getAttributeValue("src", att.strHostDriveSrc);
3129
3130 // store attachment with controller
3131 sctl.llAttachedDevices.push_back(att);
3132 // store controller with storage
3133 strg.llStorageControllers.push_back(sctl);
3134 }
3135 }
3136 }
3137}
3138
3139/**
3140 * Called initially for the <Snapshot> element under <Machine>, if present,
3141 * to store the snapshot's data into the given Snapshot structure (which is
3142 * then the one in the Machine struct). This might then recurse if
3143 * a <Snapshots> (plural) element is found in the snapshot, which should
3144 * contain a list of child snapshots; such lists are maintained in the
3145 * Snapshot structure.
3146 *
3147 * @param elmSnapshot
3148 * @param snap
3149 */
3150void MachineConfigFile::readSnapshot(const xml::ElementNode &elmSnapshot,
3151 Snapshot &snap)
3152{
3153 Utf8Str strTemp;
3154
3155 if (!elmSnapshot.getAttributeValue("uuid", strTemp))
3156 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@uuid attribute is missing"));
3157 parseUUID(snap.uuid, strTemp);
3158
3159 if (!elmSnapshot.getAttributeValue("name", snap.strName))
3160 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@name attribute is missing"));
3161
3162 // earlier 3.1 trunk builds had a bug and added Description as an attribute, read it silently and write it back as an element
3163 elmSnapshot.getAttributeValue("Description", snap.strDescription);
3164
3165 if (!elmSnapshot.getAttributeValue("timeStamp", strTemp))
3166 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@timeStamp attribute is missing"));
3167 parseTimestamp(snap.timestamp, strTemp);
3168
3169 elmSnapshot.getAttributeValuePath("stateFile", snap.strStateFile); // online snapshots only
3170
3171 // parse Hardware before the other elements because other things depend on it
3172 const xml::ElementNode *pelmHardware;
3173 if (!(pelmHardware = elmSnapshot.findChildElement("Hardware")))
3174 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@Hardware element is missing"));
3175 readHardware(*pelmHardware, snap.hardware, snap.storage);
3176
3177 xml::NodesLoop nlSnapshotChildren(elmSnapshot);
3178 const xml::ElementNode *pelmSnapshotChild;
3179 while ((pelmSnapshotChild = nlSnapshotChildren.forAllNodes()))
3180 {
3181 if (pelmSnapshotChild->nameEquals("Description"))
3182 snap.strDescription = pelmSnapshotChild->getValue();
3183 else if ( (m->sv < SettingsVersion_v1_7)
3184 && (pelmSnapshotChild->nameEquals("HardDiskAttachments"))
3185 )
3186 readHardDiskAttachments_pre1_7(*pelmSnapshotChild, snap.storage);
3187 else if ( (m->sv >= SettingsVersion_v1_7)
3188 && (pelmSnapshotChild->nameEquals("StorageControllers"))
3189 )
3190 readStorageControllers(*pelmSnapshotChild, snap.storage);
3191 else if (pelmSnapshotChild->nameEquals("Snapshots"))
3192 {
3193 xml::NodesLoop nlChildSnapshots(*pelmSnapshotChild);
3194 const xml::ElementNode *pelmChildSnapshot;
3195 while ((pelmChildSnapshot = nlChildSnapshots.forAllNodes()))
3196 {
3197 if (pelmChildSnapshot->nameEquals("Snapshot"))
3198 {
3199 Snapshot child;
3200 readSnapshot(*pelmChildSnapshot, child);
3201 snap.llChildSnapshots.push_back(child);
3202 }
3203 }
3204 }
3205 }
3206
3207 if (m->sv < SettingsVersion_v1_9)
3208 // go through Hardware once more to repair the settings controller structures
3209 // with data from old DVDDrive and FloppyDrive elements
3210 readDVDAndFloppies_pre1_9(*pelmHardware, snap.storage);
3211}
3212
3213const struct {
3214 const char *pcszOld;
3215 const char *pcszNew;
3216} aConvertOSTypes[] =
3217{
3218 { "unknown", "Other" },
3219 { "dos", "DOS" },
3220 { "win31", "Windows31" },
3221 { "win95", "Windows95" },
3222 { "win98", "Windows98" },
3223 { "winme", "WindowsMe" },
3224 { "winnt4", "WindowsNT4" },
3225 { "win2k", "Windows2000" },
3226 { "winxp", "WindowsXP" },
3227 { "win2k3", "Windows2003" },
3228 { "winvista", "WindowsVista" },
3229 { "win2k8", "Windows2008" },
3230 { "os2warp3", "OS2Warp3" },
3231 { "os2warp4", "OS2Warp4" },
3232 { "os2warp45", "OS2Warp45" },
3233 { "ecs", "OS2eCS" },
3234 { "linux22", "Linux22" },
3235 { "linux24", "Linux24" },
3236 { "linux26", "Linux26" },
3237 { "archlinux", "ArchLinux" },
3238 { "debian", "Debian" },
3239 { "opensuse", "OpenSUSE" },
3240 { "fedoracore", "Fedora" },
3241 { "gentoo", "Gentoo" },
3242 { "mandriva", "Mandriva" },
3243 { "redhat", "RedHat" },
3244 { "ubuntu", "Ubuntu" },
3245 { "xandros", "Xandros" },
3246 { "freebsd", "FreeBSD" },
3247 { "openbsd", "OpenBSD" },
3248 { "netbsd", "NetBSD" },
3249 { "netware", "Netware" },
3250 { "solaris", "Solaris" },
3251 { "opensolaris", "OpenSolaris" },
3252 { "l4", "L4" }
3253};
3254
3255void MachineConfigFile::convertOldOSType_pre1_5(Utf8Str &str)
3256{
3257 for (unsigned u = 0;
3258 u < RT_ELEMENTS(aConvertOSTypes);
3259 ++u)
3260 {
3261 if (str == aConvertOSTypes[u].pcszOld)
3262 {
3263 str = aConvertOSTypes[u].pcszNew;
3264 break;
3265 }
3266 }
3267}
3268
3269/**
3270 * Called from the constructor to actually read in the <Machine> element
3271 * of a machine config file.
3272 * @param elmMachine
3273 */
3274void MachineConfigFile::readMachine(const xml::ElementNode &elmMachine)
3275{
3276 Utf8Str strUUID;
3277 if ( (elmMachine.getAttributeValue("uuid", strUUID))
3278 && (elmMachine.getAttributeValue("name", machineUserData.strName))
3279 )
3280 {
3281 parseUUID(uuid, strUUID);
3282
3283 elmMachine.getAttributeValue("nameSync", machineUserData.fNameSync);
3284
3285 Utf8Str str;
3286 elmMachine.getAttributeValue("Description", machineUserData.strDescription);
3287
3288 elmMachine.getAttributeValue("OSType", machineUserData.strOsType);
3289 if (m->sv < SettingsVersion_v1_5)
3290 convertOldOSType_pre1_5(machineUserData.strOsType);
3291
3292 elmMachine.getAttributeValuePath("stateFile", strStateFile);
3293
3294 if (elmMachine.getAttributeValue("currentSnapshot", str))
3295 parseUUID(uuidCurrentSnapshot, str);
3296
3297 elmMachine.getAttributeValuePath("snapshotFolder", machineUserData.strSnapshotFolder);
3298
3299 if (!elmMachine.getAttributeValue("currentStateModified", fCurrentStateModified))
3300 fCurrentStateModified = true;
3301 if (elmMachine.getAttributeValue("lastStateChange", str))
3302 parseTimestamp(timeLastStateChange, str);
3303 // constructor has called RTTimeNow(&timeLastStateChange) before
3304 if (elmMachine.getAttributeValue("aborted", fAborted))
3305 fAborted = true;
3306
3307 // parse Hardware before the other elements because other things depend on it
3308 const xml::ElementNode *pelmHardware;
3309 if (!(pelmHardware = elmMachine.findChildElement("Hardware")))
3310 throw ConfigFileError(this, &elmMachine, N_("Required Machine/Hardware element is missing"));
3311 readHardware(*pelmHardware, hardwareMachine, storageMachine);
3312
3313 xml::NodesLoop nlRootChildren(elmMachine);
3314 const xml::ElementNode *pelmMachineChild;
3315 while ((pelmMachineChild = nlRootChildren.forAllNodes()))
3316 {
3317 if (pelmMachineChild->nameEquals("ExtraData"))
3318 readExtraData(*pelmMachineChild,
3319 mapExtraDataItems);
3320 else if ( (m->sv < SettingsVersion_v1_7)
3321 && (pelmMachineChild->nameEquals("HardDiskAttachments"))
3322 )
3323 readHardDiskAttachments_pre1_7(*pelmMachineChild, storageMachine);
3324 else if ( (m->sv >= SettingsVersion_v1_7)
3325 && (pelmMachineChild->nameEquals("StorageControllers"))
3326 )
3327 readStorageControllers(*pelmMachineChild, storageMachine);
3328 else if (pelmMachineChild->nameEquals("Snapshot"))
3329 {
3330 Snapshot snap;
3331 // this will recurse into child snapshots, if necessary
3332 readSnapshot(*pelmMachineChild, snap);
3333 llFirstSnapshot.push_back(snap);
3334 }
3335 else if (pelmMachineChild->nameEquals("Description"))
3336 machineUserData.strDescription = pelmMachineChild->getValue();
3337 else if (pelmMachineChild->nameEquals("Teleporter"))
3338 {
3339 pelmMachineChild->getAttributeValue("enabled", machineUserData.fTeleporterEnabled);
3340 pelmMachineChild->getAttributeValue("port", machineUserData.uTeleporterPort);
3341 pelmMachineChild->getAttributeValue("address", machineUserData.strTeleporterAddress);
3342 pelmMachineChild->getAttributeValue("password", machineUserData.strTeleporterPassword);
3343 }
3344 else if (pelmMachineChild->nameEquals("FaultTolerance"))
3345 {
3346 Utf8Str strFaultToleranceSate;
3347 if (pelmMachineChild->getAttributeValue("state", strFaultToleranceSate))
3348 {
3349 if (strFaultToleranceSate == "master")
3350 machineUserData.enmFaultToleranceState = FaultToleranceState_Master;
3351 else
3352 if (strFaultToleranceSate == "standby")
3353 machineUserData.enmFaultToleranceState = FaultToleranceState_Standby;
3354 else
3355 machineUserData.enmFaultToleranceState = FaultToleranceState_Inactive;
3356 }
3357 pelmMachineChild->getAttributeValue("port", machineUserData.uFaultTolerancePort);
3358 pelmMachineChild->getAttributeValue("address", machineUserData.strFaultToleranceAddress);
3359 pelmMachineChild->getAttributeValue("interval", machineUserData.uFaultToleranceInterval);
3360 pelmMachineChild->getAttributeValue("password", machineUserData.strFaultTolerancePassword);
3361 }
3362 else if (pelmMachineChild->nameEquals("MediaRegistry"))
3363 readMediaRegistry(*pelmMachineChild, mediaRegistry);
3364 }
3365
3366 if (m->sv < SettingsVersion_v1_9)
3367 // go through Hardware once more to repair the settings controller structures
3368 // with data from old DVDDrive and FloppyDrive elements
3369 readDVDAndFloppies_pre1_9(*pelmHardware, storageMachine);
3370 }
3371 else
3372 throw ConfigFileError(this, &elmMachine, N_("Required Machine/@uuid or @name attributes is missing"));
3373}
3374
3375/**
3376 * Creates a <Hardware> node under elmParent and then writes out the XML
3377 * keys under that. Called for both the <Machine> node and for snapshots.
3378 * @param elmParent
3379 * @param st
3380 */
3381void MachineConfigFile::buildHardwareXML(xml::ElementNode &elmParent,
3382 const Hardware &hw,
3383 const Storage &strg)
3384{
3385 xml::ElementNode *pelmHardware = elmParent.createChild("Hardware");
3386
3387 if (m->sv >= SettingsVersion_v1_4)
3388 pelmHardware->setAttribute("version", hw.strVersion);
3389 if ( (m->sv >= SettingsVersion_v1_9)
3390 && (!hw.uuid.isEmpty())
3391 )
3392 pelmHardware->setAttribute("uuid", hw.uuid.toStringCurly());
3393
3394 xml::ElementNode *pelmCPU = pelmHardware->createChild("CPU");
3395
3396 xml::ElementNode *pelmHwVirtEx = pelmCPU->createChild("HardwareVirtEx");
3397 pelmHwVirtEx->setAttribute("enabled", hw.fHardwareVirt);
3398 if (m->sv >= SettingsVersion_v1_9)
3399 pelmHwVirtEx->setAttribute("exclusive", hw.fHardwareVirtExclusive);
3400
3401 pelmCPU->createChild("HardwareVirtExNestedPaging")->setAttribute("enabled", hw.fNestedPaging);
3402 pelmCPU->createChild("HardwareVirtExVPID")->setAttribute("enabled", hw.fVPID);
3403 pelmCPU->createChild("PAE")->setAttribute("enabled", hw.fPAE);
3404
3405 if (hw.fSyntheticCpu)
3406 pelmCPU->createChild("SyntheticCpu")->setAttribute("enabled", hw.fSyntheticCpu);
3407 pelmCPU->setAttribute("count", hw.cCPUs);
3408 if (hw.ulCpuExecutionCap != 100)
3409 pelmCPU->setAttribute("executionCap", hw.ulCpuExecutionCap);
3410
3411 /* Always save this setting as we have changed the default in 4.0 (on for large memory 64-bit systems). */
3412 pelmCPU->createChild("HardwareVirtExLargePages")->setAttribute("enabled", hw.fLargePages);
3413
3414 if (m->sv >= SettingsVersion_v1_9)
3415 pelmCPU->createChild("HardwareVirtForce")->setAttribute("enabled", hw.fHardwareVirtForce);
3416
3417 if (m->sv >= SettingsVersion_v1_10)
3418 {
3419 pelmCPU->setAttribute("hotplug", hw.fCpuHotPlug);
3420
3421 xml::ElementNode *pelmCpuTree = NULL;
3422 for (CpuList::const_iterator it = hw.llCpus.begin();
3423 it != hw.llCpus.end();
3424 ++it)
3425 {
3426 const Cpu &cpu = *it;
3427
3428 if (pelmCpuTree == NULL)
3429 pelmCpuTree = pelmCPU->createChild("CpuTree");
3430
3431 xml::ElementNode *pelmCpu = pelmCpuTree->createChild("Cpu");
3432 pelmCpu->setAttribute("id", cpu.ulId);
3433 }
3434 }
3435
3436 xml::ElementNode *pelmCpuIdTree = NULL;
3437 for (CpuIdLeafsList::const_iterator it = hw.llCpuIdLeafs.begin();
3438 it != hw.llCpuIdLeafs.end();
3439 ++it)
3440 {
3441 const CpuIdLeaf &leaf = *it;
3442
3443 if (pelmCpuIdTree == NULL)
3444 pelmCpuIdTree = pelmCPU->createChild("CpuIdTree");
3445
3446 xml::ElementNode *pelmCpuIdLeaf = pelmCpuIdTree->createChild("CpuIdLeaf");
3447 pelmCpuIdLeaf->setAttribute("id", leaf.ulId);
3448 pelmCpuIdLeaf->setAttribute("eax", leaf.ulEax);
3449 pelmCpuIdLeaf->setAttribute("ebx", leaf.ulEbx);
3450 pelmCpuIdLeaf->setAttribute("ecx", leaf.ulEcx);
3451 pelmCpuIdLeaf->setAttribute("edx", leaf.ulEdx);
3452 }
3453
3454 xml::ElementNode *pelmMemory = pelmHardware->createChild("Memory");
3455 pelmMemory->setAttribute("RAMSize", hw.ulMemorySizeMB);
3456 if (m->sv >= SettingsVersion_v1_10)
3457 {
3458 pelmMemory->setAttribute("PageFusion", hw.fPageFusionEnabled);
3459 }
3460
3461 if ( (m->sv >= SettingsVersion_v1_9)
3462 && (hw.firmwareType >= FirmwareType_EFI)
3463 )
3464 {
3465 xml::ElementNode *pelmFirmware = pelmHardware->createChild("Firmware");
3466 const char *pcszFirmware;
3467
3468 switch (hw.firmwareType)
3469 {
3470 case FirmwareType_EFI: pcszFirmware = "EFI"; break;
3471 case FirmwareType_EFI32: pcszFirmware = "EFI32"; break;
3472 case FirmwareType_EFI64: pcszFirmware = "EFI64"; break;
3473 case FirmwareType_EFIDUAL: pcszFirmware = "EFIDUAL"; break;
3474 default: pcszFirmware = "None"; break;
3475 }
3476 pelmFirmware->setAttribute("type", pcszFirmware);
3477 }
3478
3479 if ( (m->sv >= SettingsVersion_v1_10)
3480 )
3481 {
3482 xml::ElementNode *pelmHid = pelmHardware->createChild("HID");
3483 const char *pcszHid;
3484
3485 switch (hw.pointingHidType)
3486 {
3487 case PointingHidType_USBMouse: pcszHid = "USBMouse"; break;
3488 case PointingHidType_USBTablet: pcszHid = "USBTablet"; break;
3489 case PointingHidType_PS2Mouse: pcszHid = "PS2Mouse"; break;
3490 case PointingHidType_ComboMouse: pcszHid = "ComboMouse"; break;
3491 case PointingHidType_None: pcszHid = "None"; break;
3492 default: Assert(false); pcszHid = "PS2Mouse"; break;
3493 }
3494 pelmHid->setAttribute("Pointing", pcszHid);
3495
3496 switch (hw.keyboardHidType)
3497 {
3498 case KeyboardHidType_USBKeyboard: pcszHid = "USBKeyboard"; break;
3499 case KeyboardHidType_PS2Keyboard: pcszHid = "PS2Keyboard"; break;
3500 case KeyboardHidType_ComboKeyboard: pcszHid = "ComboKeyboard"; break;
3501 case KeyboardHidType_None: pcszHid = "None"; break;
3502 default: Assert(false); pcszHid = "PS2Keyboard"; break;
3503 }
3504 pelmHid->setAttribute("Keyboard", pcszHid);
3505 }
3506
3507 if ( (m->sv >= SettingsVersion_v1_10)
3508 )
3509 {
3510 xml::ElementNode *pelmHpet = pelmHardware->createChild("HPET");
3511 pelmHpet->setAttribute("enabled", hw.fHpetEnabled);
3512 }
3513
3514 if ( (m->sv >= SettingsVersion_v1_11)
3515 )
3516 {
3517 xml::ElementNode *pelmChipset = pelmHardware->createChild("Chipset");
3518 const char *pcszChipset;
3519
3520 switch (hw.chipsetType)
3521 {
3522 case ChipsetType_PIIX3: pcszChipset = "PIIX3"; break;
3523 case ChipsetType_ICH9: pcszChipset = "ICH9"; break;
3524 default: Assert(false); pcszChipset = "PIIX3"; break;
3525 }
3526 pelmChipset->setAttribute("type", pcszChipset);
3527 }
3528
3529 xml::ElementNode *pelmBoot = pelmHardware->createChild("Boot");
3530 for (BootOrderMap::const_iterator it = hw.mapBootOrder.begin();
3531 it != hw.mapBootOrder.end();
3532 ++it)
3533 {
3534 uint32_t i = it->first;
3535 DeviceType_T type = it->second;
3536 const char *pcszDevice;
3537
3538 switch (type)
3539 {
3540 case DeviceType_Floppy: pcszDevice = "Floppy"; break;
3541 case DeviceType_DVD: pcszDevice = "DVD"; break;
3542 case DeviceType_HardDisk: pcszDevice = "HardDisk"; break;
3543 case DeviceType_Network: pcszDevice = "Network"; break;
3544 default: /*case DeviceType_Null:*/ pcszDevice = "None"; break;
3545 }
3546
3547 xml::ElementNode *pelmOrder = pelmBoot->createChild("Order");
3548 pelmOrder->setAttribute("position",
3549 i + 1); // XML is 1-based but internal data is 0-based
3550 pelmOrder->setAttribute("device", pcszDevice);
3551 }
3552
3553 xml::ElementNode *pelmDisplay = pelmHardware->createChild("Display");
3554 pelmDisplay->setAttribute("VRAMSize", hw.ulVRAMSizeMB);
3555 pelmDisplay->setAttribute("monitorCount", hw.cMonitors);
3556 pelmDisplay->setAttribute("accelerate3D", hw.fAccelerate3D);
3557
3558 if (m->sv >= SettingsVersion_v1_8)
3559 pelmDisplay->setAttribute("accelerate2DVideo", hw.fAccelerate2DVideo);
3560
3561 xml::ElementNode *pelmVRDE = pelmHardware->createChild("RemoteDisplay");
3562 pelmVRDE->setAttribute("enabled", hw.vrdeSettings.fEnabled);
3563 if (m->sv < SettingsVersion_v1_11)
3564 {
3565 /* In VBox 4.0 these attributes are replaced with "Properties". */
3566 Utf8Str strPort;
3567 StringsMap::const_iterator it = hw.vrdeSettings.mapProperties.find("TCP/Ports");
3568 if (it != hw.vrdeSettings.mapProperties.end())
3569 strPort = it->second;
3570 if (!strPort.length())
3571 strPort = "3389";
3572 pelmVRDE->setAttribute("port", strPort);
3573
3574 Utf8Str strAddress;
3575 it = hw.vrdeSettings.mapProperties.find("TCP/Address");
3576 if (it != hw.vrdeSettings.mapProperties.end())
3577 strAddress = it->second;
3578 if (strAddress.length())
3579 pelmVRDE->setAttribute("netAddress", strAddress);
3580 }
3581 const char *pcszAuthType;
3582 switch (hw.vrdeSettings.authType)
3583 {
3584 case AuthType_Guest: pcszAuthType = "Guest"; break;
3585 case AuthType_External: pcszAuthType = "External"; break;
3586 default: /*case AuthType_Null:*/ pcszAuthType = "Null"; break;
3587 }
3588 pelmVRDE->setAttribute("authType", pcszAuthType);
3589
3590 if (hw.vrdeSettings.ulAuthTimeout != 0)
3591 pelmVRDE->setAttribute("authTimeout", hw.vrdeSettings.ulAuthTimeout);
3592 if (hw.vrdeSettings.fAllowMultiConnection)
3593 pelmVRDE->setAttribute("allowMultiConnection", hw.vrdeSettings.fAllowMultiConnection);
3594 if (hw.vrdeSettings.fReuseSingleConnection)
3595 pelmVRDE->setAttribute("reuseSingleConnection", hw.vrdeSettings.fReuseSingleConnection);
3596
3597 if (m->sv == SettingsVersion_v1_10)
3598 {
3599 xml::ElementNode *pelmVideoChannel = pelmVRDE->createChild("VideoChannel");
3600
3601 /* In 4.0 videochannel settings were replaced with properties, so look at properties. */
3602 Utf8Str str;
3603 StringsMap::const_iterator it = hw.vrdeSettings.mapProperties.find("VideoChannel/Enabled");
3604 if (it != hw.vrdeSettings.mapProperties.end())
3605 str = it->second;
3606 bool fVideoChannel = RTStrICmp(str.c_str(), "true") == 0
3607 || RTStrCmp(str.c_str(), "1") == 0;
3608 pelmVideoChannel->setAttribute("enabled", fVideoChannel);
3609
3610 it = hw.vrdeSettings.mapProperties.find("VideoChannel/Quality");
3611 if (it != hw.vrdeSettings.mapProperties.end())
3612 str = it->second;
3613 uint32_t ulVideoChannelQuality = RTStrToUInt32(str.c_str()); /* This returns 0 on invalid string which is ok. */
3614 if (ulVideoChannelQuality == 0)
3615 ulVideoChannelQuality = 75;
3616 else
3617 ulVideoChannelQuality = RT_CLAMP(ulVideoChannelQuality, 10, 100);
3618 pelmVideoChannel->setAttribute("quality", ulVideoChannelQuality);
3619 }
3620 if (m->sv >= SettingsVersion_v1_11)
3621 {
3622 if (hw.vrdeSettings.strAuthLibrary.length())
3623 pelmVRDE->setAttribute("authLibrary", hw.vrdeSettings.strAuthLibrary);
3624 if (hw.vrdeSettings.strVrdeExtPack.isNotEmpty())
3625 pelmVRDE->setAttribute("VRDEExtPack", hw.vrdeSettings.strVrdeExtPack);
3626 if (hw.vrdeSettings.mapProperties.size() > 0)
3627 {
3628 xml::ElementNode *pelmProperties = pelmVRDE->createChild("VRDEProperties");
3629 for (StringsMap::const_iterator it = hw.vrdeSettings.mapProperties.begin();
3630 it != hw.vrdeSettings.mapProperties.end();
3631 ++it)
3632 {
3633 const Utf8Str &strName = it->first;
3634 const Utf8Str &strValue = it->second;
3635 xml::ElementNode *pelm = pelmProperties->createChild("Property");
3636 pelm->setAttribute("name", strName);
3637 pelm->setAttribute("value", strValue);
3638 }
3639 }
3640 }
3641
3642 xml::ElementNode *pelmBIOS = pelmHardware->createChild("BIOS");
3643 pelmBIOS->createChild("ACPI")->setAttribute("enabled", hw.biosSettings.fACPIEnabled);
3644 pelmBIOS->createChild("IOAPIC")->setAttribute("enabled", hw.biosSettings.fIOAPICEnabled);
3645
3646 xml::ElementNode *pelmLogo = pelmBIOS->createChild("Logo");
3647 pelmLogo->setAttribute("fadeIn", hw.biosSettings.fLogoFadeIn);
3648 pelmLogo->setAttribute("fadeOut", hw.biosSettings.fLogoFadeOut);
3649 pelmLogo->setAttribute("displayTime", hw.biosSettings.ulLogoDisplayTime);
3650 if (hw.biosSettings.strLogoImagePath.length())
3651 pelmLogo->setAttribute("imagePath", hw.biosSettings.strLogoImagePath);
3652
3653 const char *pcszBootMenu;
3654 switch (hw.biosSettings.biosBootMenuMode)
3655 {
3656 case BIOSBootMenuMode_Disabled: pcszBootMenu = "Disabled"; break;
3657 case BIOSBootMenuMode_MenuOnly: pcszBootMenu = "MenuOnly"; break;
3658 default: /*BIOSBootMenuMode_MessageAndMenu*/ pcszBootMenu = "MessageAndMenu"; break;
3659 }
3660 pelmBIOS->createChild("BootMenu")->setAttribute("mode", pcszBootMenu);
3661 pelmBIOS->createChild("TimeOffset")->setAttribute("value", hw.biosSettings.llTimeOffset);
3662 pelmBIOS->createChild("PXEDebug")->setAttribute("enabled", hw.biosSettings.fPXEDebugEnabled);
3663
3664 if (m->sv < SettingsVersion_v1_9)
3665 {
3666 // settings formats before 1.9 had separate DVDDrive and FloppyDrive items under Hardware;
3667 // run thru the storage controllers to see if we have a DVD or floppy drives
3668 size_t cDVDs = 0;
3669 size_t cFloppies = 0;
3670
3671 xml::ElementNode *pelmDVD = pelmHardware->createChild("DVDDrive");
3672 xml::ElementNode *pelmFloppy = pelmHardware->createChild("FloppyDrive");
3673
3674 for (StorageControllersList::const_iterator it = strg.llStorageControllers.begin();
3675 it != strg.llStorageControllers.end();
3676 ++it)
3677 {
3678 const StorageController &sctl = *it;
3679 // in old settings format, the DVD drive could only have been under the IDE controller
3680 if (sctl.storageBus == StorageBus_IDE)
3681 {
3682 for (AttachedDevicesList::const_iterator it2 = sctl.llAttachedDevices.begin();
3683 it2 != sctl.llAttachedDevices.end();
3684 ++it2)
3685 {
3686 const AttachedDevice &att = *it2;
3687 if (att.deviceType == DeviceType_DVD)
3688 {
3689 if (cDVDs > 0)
3690 throw ConfigFileError(this, NULL, N_("Internal error: cannot save more than one DVD drive with old settings format"));
3691
3692 ++cDVDs;
3693
3694 pelmDVD->setAttribute("passthrough", att.fPassThrough);
3695 if (att.fTempEject)
3696 pelmDVD->setAttribute("tempeject", att.fTempEject);
3697 if (!att.uuid.isEmpty())
3698 pelmDVD->createChild("Image")->setAttribute("uuid", att.uuid.toStringCurly());
3699 else if (att.strHostDriveSrc.length())
3700 pelmDVD->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
3701 }
3702 }
3703 }
3704 else if (sctl.storageBus == StorageBus_Floppy)
3705 {
3706 size_t cFloppiesHere = sctl.llAttachedDevices.size();
3707 if (cFloppiesHere > 1)
3708 throw ConfigFileError(this, NULL, N_("Internal error: floppy controller cannot have more than one device attachment"));
3709 if (cFloppiesHere)
3710 {
3711 const AttachedDevice &att = sctl.llAttachedDevices.front();
3712 pelmFloppy->setAttribute("enabled", true);
3713 if (!att.uuid.isEmpty())
3714 pelmFloppy->createChild("Image")->setAttribute("uuid", att.uuid.toStringCurly());
3715 else if (att.strHostDriveSrc.length())
3716 pelmFloppy->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
3717 }
3718
3719 cFloppies += cFloppiesHere;
3720 }
3721 }
3722
3723 if (cFloppies == 0)
3724 pelmFloppy->setAttribute("enabled", false);
3725 else if (cFloppies > 1)
3726 throw ConfigFileError(this, NULL, N_("Internal error: cannot save more than one floppy drive with old settings format"));
3727 }
3728
3729 xml::ElementNode *pelmUSB = pelmHardware->createChild("USBController");
3730 pelmUSB->setAttribute("enabled", hw.usbController.fEnabled);
3731 pelmUSB->setAttribute("enabledEhci", hw.usbController.fEnabledEHCI);
3732
3733 buildUSBDeviceFilters(*pelmUSB,
3734 hw.usbController.llDeviceFilters,
3735 false); // fHostMode
3736
3737 xml::ElementNode *pelmNetwork = pelmHardware->createChild("Network");
3738 for (NetworkAdaptersList::const_iterator it = hw.llNetworkAdapters.begin();
3739 it != hw.llNetworkAdapters.end();
3740 ++it)
3741 {
3742 const NetworkAdapter &nic = *it;
3743
3744 xml::ElementNode *pelmAdapter = pelmNetwork->createChild("Adapter");
3745 pelmAdapter->setAttribute("slot", nic.ulSlot);
3746 pelmAdapter->setAttribute("enabled", nic.fEnabled);
3747 pelmAdapter->setAttribute("MACAddress", nic.strMACAddress);
3748 pelmAdapter->setAttribute("cable", nic.fCableConnected);
3749 pelmAdapter->setAttribute("speed", nic.ulLineSpeed);
3750 if (nic.ulBootPriority != 0)
3751 {
3752 pelmAdapter->setAttribute("bootPriority", nic.ulBootPriority);
3753 }
3754 if (nic.fTraceEnabled)
3755 {
3756 pelmAdapter->setAttribute("trace", nic.fTraceEnabled);
3757 pelmAdapter->setAttribute("tracefile", nic.strTraceFile);
3758 }
3759 if (nic.strBandwidthGroup.isNotEmpty())
3760 pelmAdapter->setAttribute("bandwidthGroup", nic.strBandwidthGroup);
3761
3762 const char *pszPolicy;
3763 switch (nic.enmPromiscModePolicy)
3764 {
3765 case NetworkAdapterPromiscModePolicy_Deny: pszPolicy = NULL; break;
3766 case NetworkAdapterPromiscModePolicy_AllowNetwork: pszPolicy = "AllowNetwork"; break;
3767 case NetworkAdapterPromiscModePolicy_AllowAll: pszPolicy = "AllowAll"; break;
3768 default: pszPolicy = NULL; AssertFailed(); break;
3769 }
3770 if (pszPolicy)
3771 pelmAdapter->setAttribute("promiscuousModePolicy", pszPolicy);
3772
3773 const char *pcszType;
3774 switch (nic.type)
3775 {
3776 case NetworkAdapterType_Am79C973: pcszType = "Am79C973"; break;
3777 case NetworkAdapterType_I82540EM: pcszType = "82540EM"; break;
3778 case NetworkAdapterType_I82543GC: pcszType = "82543GC"; break;
3779 case NetworkAdapterType_I82545EM: pcszType = "82545EM"; break;
3780 case NetworkAdapterType_Virtio: pcszType = "virtio"; break;
3781 default: /*case NetworkAdapterType_Am79C970A:*/ pcszType = "Am79C970A"; break;
3782 }
3783 pelmAdapter->setAttribute("type", pcszType);
3784
3785 xml::ElementNode *pelmNAT;
3786 if (m->sv < SettingsVersion_v1_10)
3787 {
3788 switch (nic.mode)
3789 {
3790 case NetworkAttachmentType_NAT:
3791 pelmNAT = pelmAdapter->createChild("NAT");
3792 if (nic.nat.strNetwork.length())
3793 pelmNAT->setAttribute("network", nic.nat.strNetwork);
3794 break;
3795
3796 case NetworkAttachmentType_Bridged:
3797 pelmAdapter->createChild("BridgedInterface")->setAttribute("name", nic.strBridgedName);
3798 break;
3799
3800 case NetworkAttachmentType_Internal:
3801 pelmAdapter->createChild("InternalNetwork")->setAttribute("name", nic.strInternalNetworkName);
3802 break;
3803
3804 case NetworkAttachmentType_HostOnly:
3805 pelmAdapter->createChild("HostOnlyInterface")->setAttribute("name", nic.strHostOnlyName);
3806 break;
3807
3808 default: /*case NetworkAttachmentType_Null:*/
3809 break;
3810 }
3811 }
3812 else
3813 {
3814 /* m->sv >= SettingsVersion_v1_10 */
3815 xml::ElementNode *pelmDisabledNode = NULL;
3816 pelmDisabledNode = pelmAdapter->createChild("DisabledModes");
3817 if (nic.mode != NetworkAttachmentType_NAT)
3818 buildNetworkXML(NetworkAttachmentType_NAT, *pelmDisabledNode, false, nic);
3819 if (nic.mode != NetworkAttachmentType_Bridged)
3820 buildNetworkXML(NetworkAttachmentType_Bridged, *pelmDisabledNode, false, nic);
3821 if (nic.mode != NetworkAttachmentType_Internal)
3822 buildNetworkXML(NetworkAttachmentType_HostOnly, *pelmDisabledNode, false, nic);
3823 if (nic.mode != NetworkAttachmentType_HostOnly)
3824 buildNetworkXML(NetworkAttachmentType_HostOnly, *pelmDisabledNode, false, nic);
3825 if (nic.mode != NetworkAttachmentType_Generic)
3826 buildNetworkXML(NetworkAttachmentType_Generic, *pelmDisabledNode, false, nic);
3827 buildNetworkXML(nic.mode, *pelmAdapter, true, nic);
3828 }
3829 }
3830
3831 xml::ElementNode *pelmPorts = pelmHardware->createChild("UART");
3832 for (SerialPortsList::const_iterator it = hw.llSerialPorts.begin();
3833 it != hw.llSerialPorts.end();
3834 ++it)
3835 {
3836 const SerialPort &port = *it;
3837 xml::ElementNode *pelmPort = pelmPorts->createChild("Port");
3838 pelmPort->setAttribute("slot", port.ulSlot);
3839 pelmPort->setAttribute("enabled", port.fEnabled);
3840 pelmPort->setAttributeHex("IOBase", port.ulIOBase);
3841 pelmPort->setAttribute("IRQ", port.ulIRQ);
3842
3843 const char *pcszHostMode;
3844 switch (port.portMode)
3845 {
3846 case PortMode_HostPipe: pcszHostMode = "HostPipe"; break;
3847 case PortMode_HostDevice: pcszHostMode = "HostDevice"; break;
3848 case PortMode_RawFile: pcszHostMode = "RawFile"; break;
3849 default: /*case PortMode_Disconnected:*/ pcszHostMode = "Disconnected"; break;
3850 }
3851 switch (port.portMode)
3852 {
3853 case PortMode_HostPipe:
3854 pelmPort->setAttribute("server", port.fServer);
3855 /* no break */
3856 case PortMode_HostDevice:
3857 case PortMode_RawFile:
3858 pelmPort->setAttribute("path", port.strPath);
3859 break;
3860
3861 default:
3862 break;
3863 }
3864 pelmPort->setAttribute("hostMode", pcszHostMode);
3865 }
3866
3867 pelmPorts = pelmHardware->createChild("LPT");
3868 for (ParallelPortsList::const_iterator it = hw.llParallelPorts.begin();
3869 it != hw.llParallelPorts.end();
3870 ++it)
3871 {
3872 const ParallelPort &port = *it;
3873 xml::ElementNode *pelmPort = pelmPorts->createChild("Port");
3874 pelmPort->setAttribute("slot", port.ulSlot);
3875 pelmPort->setAttribute("enabled", port.fEnabled);
3876 pelmPort->setAttributeHex("IOBase", port.ulIOBase);
3877 pelmPort->setAttribute("IRQ", port.ulIRQ);
3878 if (port.strPath.length())
3879 pelmPort->setAttribute("path", port.strPath);
3880 }
3881
3882 xml::ElementNode *pelmAudio = pelmHardware->createChild("AudioAdapter");
3883 const char *pcszController;
3884 switch (hw.audioAdapter.controllerType)
3885 {
3886 case AudioControllerType_SB16:
3887 pcszController = "SB16";
3888 break;
3889 case AudioControllerType_HDA:
3890 if (m->sv >= SettingsVersion_v1_11)
3891 {
3892 pcszController = "HDA";
3893 break;
3894 }
3895 /* fall through */
3896 case AudioControllerType_AC97:
3897 default:
3898 pcszController = "AC97";
3899 break;
3900 }
3901 pelmAudio->setAttribute("controller", pcszController);
3902
3903 if (m->sv >= SettingsVersion_v1_10)
3904 {
3905 xml::ElementNode *pelmRTC = pelmHardware->createChild("RTC");
3906 pelmRTC->setAttribute("localOrUTC", machineUserData.fRTCUseUTC ? "UTC" : "local");
3907 }
3908
3909 const char *pcszDriver;
3910 switch (hw.audioAdapter.driverType)
3911 {
3912 case AudioDriverType_WinMM: pcszDriver = "WinMM"; break;
3913 case AudioDriverType_DirectSound: pcszDriver = "DirectSound"; break;
3914 case AudioDriverType_SolAudio: pcszDriver = "SolAudio"; break;
3915 case AudioDriverType_ALSA: pcszDriver = "ALSA"; break;
3916 case AudioDriverType_Pulse: pcszDriver = "Pulse"; break;
3917 case AudioDriverType_OSS: pcszDriver = "OSS"; break;
3918 case AudioDriverType_CoreAudio: pcszDriver = "CoreAudio"; break;
3919 case AudioDriverType_MMPM: pcszDriver = "MMPM"; break;
3920 default: /*case AudioDriverType_Null:*/ pcszDriver = "Null"; break;
3921 }
3922 pelmAudio->setAttribute("driver", pcszDriver);
3923
3924 pelmAudio->setAttribute("enabled", hw.audioAdapter.fEnabled);
3925
3926 xml::ElementNode *pelmSharedFolders = pelmHardware->createChild("SharedFolders");
3927 for (SharedFoldersList::const_iterator it = hw.llSharedFolders.begin();
3928 it != hw.llSharedFolders.end();
3929 ++it)
3930 {
3931 const SharedFolder &sf = *it;
3932 xml::ElementNode *pelmThis = pelmSharedFolders->createChild("SharedFolder");
3933 pelmThis->setAttribute("name", sf.strName);
3934 pelmThis->setAttribute("hostPath", sf.strHostPath);
3935 pelmThis->setAttribute("writable", sf.fWritable);
3936 pelmThis->setAttribute("autoMount", sf.fAutoMount);
3937 }
3938
3939 xml::ElementNode *pelmClip = pelmHardware->createChild("Clipboard");
3940 const char *pcszClip;
3941 switch (hw.clipboardMode)
3942 {
3943 case ClipboardMode_Disabled: pcszClip = "Disabled"; break;
3944 case ClipboardMode_HostToGuest: pcszClip = "HostToGuest"; break;
3945 case ClipboardMode_GuestToHost: pcszClip = "GuestToHost"; break;
3946 default: /*case ClipboardMode_Bidirectional:*/ pcszClip = "Bidirectional"; break;
3947 }
3948 pelmClip->setAttribute("mode", pcszClip);
3949
3950 if (m->sv >= SettingsVersion_v1_10)
3951 {
3952 xml::ElementNode *pelmIo = pelmHardware->createChild("IO");
3953 xml::ElementNode *pelmIoCache;
3954
3955 pelmIoCache = pelmIo->createChild("IoCache");
3956 pelmIoCache->setAttribute("enabled", hw.ioSettings.fIoCacheEnabled);
3957 pelmIoCache->setAttribute("size", hw.ioSettings.ulIoCacheSize);
3958
3959 if (m->sv >= SettingsVersion_v1_11)
3960 {
3961 xml::ElementNode *pelmBandwidthGroups = pelmIo->createChild("BandwidthGroups");
3962 for (BandwidthGroupList::const_iterator it = hw.ioSettings.llBandwidthGroups.begin();
3963 it != hw.ioSettings.llBandwidthGroups.end();
3964 ++it)
3965 {
3966 const BandwidthGroup &gr = *it;
3967 const char *pcszType;
3968 xml::ElementNode *pelmThis = pelmBandwidthGroups->createChild("BandwidthGroup");
3969 pelmThis->setAttribute("name", gr.strName);
3970 switch (gr.enmType)
3971 {
3972 case BandwidthGroupType_Network: pcszType = "Network"; break;
3973 default: /* BandwidthGrouptype_Disk */ pcszType = "Disk"; break;
3974 }
3975 pelmThis->setAttribute("type", pcszType);
3976 pelmThis->setAttribute("maxMbPerSec", gr.cMaxMbPerSec);
3977 }
3978 }
3979 }
3980
3981 if (m->sv >= SettingsVersion_v1_12)
3982 {
3983 xml::ElementNode *pelmPci = pelmHardware->createChild("HostPci");
3984 xml::ElementNode *pelmPciDevices = pelmPci->createChild("Devices");
3985
3986 for (HostPciDeviceAttachmentList::const_iterator it = hw.pciAttachments.begin();
3987 it != hw.pciAttachments.end();
3988 ++it)
3989 {
3990 const HostPciDeviceAttachment &hpda = *it;
3991
3992 xml::ElementNode *pelmThis = pelmPciDevices->createChild("Device");
3993
3994 pelmThis->setAttribute("host", hpda.uHostAddress);
3995 pelmThis->setAttribute("guest", hpda.uGuestAddress);
3996 pelmThis->setAttribute("name", hpda.strDeviceName);
3997 }
3998 }
3999
4000 xml::ElementNode *pelmGuest = pelmHardware->createChild("Guest");
4001 pelmGuest->setAttribute("memoryBalloonSize", hw.ulMemoryBalloonSize);
4002
4003 xml::ElementNode *pelmGuestProps = pelmHardware->createChild("GuestProperties");
4004 for (GuestPropertiesList::const_iterator it = hw.llGuestProperties.begin();
4005 it != hw.llGuestProperties.end();
4006 ++it)
4007 {
4008 const GuestProperty &prop = *it;
4009 xml::ElementNode *pelmProp = pelmGuestProps->createChild("GuestProperty");
4010 pelmProp->setAttribute("name", prop.strName);
4011 pelmProp->setAttribute("value", prop.strValue);
4012 pelmProp->setAttribute("timestamp", prop.timestamp);
4013 pelmProp->setAttribute("flags", prop.strFlags);
4014 }
4015
4016 if (hw.strNotificationPatterns.length())
4017 pelmGuestProps->setAttribute("notificationPatterns", hw.strNotificationPatterns);
4018}
4019
4020/**
4021 * Fill a <Network> node. Only relevant for XML version >= v1_10.
4022 * @param mode
4023 * @param elmParent
4024 * @param fEnabled
4025 * @param nic
4026 */
4027void MachineConfigFile::buildNetworkXML(NetworkAttachmentType_T mode,
4028 xml::ElementNode &elmParent,
4029 bool fEnabled,
4030 const NetworkAdapter &nic)
4031{
4032 switch (mode)
4033 {
4034 case NetworkAttachmentType_NAT:
4035 xml::ElementNode *pelmNAT;
4036 pelmNAT = elmParent.createChild("NAT");
4037
4038 if (nic.nat.strNetwork.length())
4039 pelmNAT->setAttribute("network", nic.nat.strNetwork);
4040 if (nic.nat.strBindIP.length())
4041 pelmNAT->setAttribute("hostip", nic.nat.strBindIP);
4042 if (nic.nat.u32Mtu)
4043 pelmNAT->setAttribute("mtu", nic.nat.u32Mtu);
4044 if (nic.nat.u32SockRcv)
4045 pelmNAT->setAttribute("sockrcv", nic.nat.u32SockRcv);
4046 if (nic.nat.u32SockSnd)
4047 pelmNAT->setAttribute("socksnd", nic.nat.u32SockSnd);
4048 if (nic.nat.u32TcpRcv)
4049 pelmNAT->setAttribute("tcprcv", nic.nat.u32TcpRcv);
4050 if (nic.nat.u32TcpSnd)
4051 pelmNAT->setAttribute("tcpsnd", nic.nat.u32TcpSnd);
4052 xml::ElementNode *pelmDNS;
4053 pelmDNS = pelmNAT->createChild("DNS");
4054 pelmDNS->setAttribute("pass-domain", nic.nat.fDnsPassDomain);
4055 pelmDNS->setAttribute("use-proxy", nic.nat.fDnsProxy);
4056 pelmDNS->setAttribute("use-host-resolver", nic.nat.fDnsUseHostResolver);
4057
4058 xml::ElementNode *pelmAlias;
4059 pelmAlias = pelmNAT->createChild("Alias");
4060 pelmAlias->setAttribute("logging", nic.nat.fAliasLog);
4061 pelmAlias->setAttribute("proxy-only", nic.nat.fAliasProxyOnly);
4062 pelmAlias->setAttribute("use-same-ports", nic.nat.fAliasUseSamePorts);
4063
4064 if ( nic.nat.strTftpPrefix.length()
4065 || nic.nat.strTftpBootFile.length()
4066 || nic.nat.strTftpNextServer.length())
4067 {
4068 xml::ElementNode *pelmTFTP;
4069 pelmTFTP = pelmNAT->createChild("TFTP");
4070 if (nic.nat.strTftpPrefix.length())
4071 pelmTFTP->setAttribute("prefix", nic.nat.strTftpPrefix);
4072 if (nic.nat.strTftpBootFile.length())
4073 pelmTFTP->setAttribute("boot-file", nic.nat.strTftpBootFile);
4074 if (nic.nat.strTftpNextServer.length())
4075 pelmTFTP->setAttribute("next-server", nic.nat.strTftpNextServer);
4076 }
4077 for (NATRuleList::const_iterator rule = nic.nat.llRules.begin();
4078 rule != nic.nat.llRules.end(); ++rule)
4079 {
4080 xml::ElementNode *pelmPF;
4081 pelmPF = pelmNAT->createChild("Forwarding");
4082 if ((*rule).strName.length())
4083 pelmPF->setAttribute("name", (*rule).strName);
4084 pelmPF->setAttribute("proto", (*rule).proto);
4085 if ((*rule).strHostIP.length())
4086 pelmPF->setAttribute("hostip", (*rule).strHostIP);
4087 if ((*rule).u16HostPort)
4088 pelmPF->setAttribute("hostport", (*rule).u16HostPort);
4089 if ((*rule).strGuestIP.length())
4090 pelmPF->setAttribute("guestip", (*rule).strGuestIP);
4091 if ((*rule).u16GuestPort)
4092 pelmPF->setAttribute("guestport", (*rule).u16GuestPort);
4093 }
4094 break;
4095
4096 case NetworkAttachmentType_Bridged:
4097 if (fEnabled || !nic.strBridgedName.isEmpty())
4098 elmParent.createChild("BridgedInterface")->setAttribute("name", nic.strBridgedName);
4099 break;
4100
4101 case NetworkAttachmentType_Internal:
4102 if (fEnabled || !nic.strInternalNetworkName.isEmpty())
4103 elmParent.createChild("InternalNetwork")->setAttribute("name", nic.strInternalNetworkName);
4104 break;
4105
4106 case NetworkAttachmentType_HostOnly:
4107 if (fEnabled || !nic.strHostOnlyName.isEmpty())
4108 elmParent.createChild("HostOnlyInterface")->setAttribute("name", nic.strHostOnlyName);
4109 break;
4110
4111 case NetworkAttachmentType_Generic:
4112 if (fEnabled || !nic.strGenericDriver.isEmpty() || nic.genericProperties.size())
4113 {
4114 xml::ElementNode *pelmMode = elmParent.createChild("GenericInterface");
4115 pelmMode->setAttribute("driver", nic.strGenericDriver);
4116 for (StringsMap::const_iterator it = nic.genericProperties.begin();
4117 it != nic.genericProperties.end();
4118 ++it)
4119 {
4120 xml::ElementNode *pelmProp = pelmMode->createChild("Property");
4121 pelmProp->setAttribute("name", it->first);
4122 pelmProp->setAttribute("value", it->second);
4123 }
4124 }
4125 break;
4126
4127 default: /*case NetworkAttachmentType_Null:*/
4128 break;
4129 }
4130}
4131
4132/**
4133 * Creates a <StorageControllers> node under elmParent and then writes out the XML
4134 * keys under that. Called for both the <Machine> node and for snapshots.
4135 * @param elmParent
4136 * @param st
4137 * @param fSkipRemovableMedia If true, DVD and floppy attachments are skipped and
4138 * an empty drive is always written instead. This is for the OVF export case.
4139 * This parameter is ignored unless the settings version is at least v1.9, which
4140 * is always the case when this gets called for OVF export.
4141 * @param pllElementsWithUuidAttributes If not NULL, must point to a list of element node
4142 * pointers to which we will append all elements that we created here that contain
4143 * UUID attributes. This allows the OVF export code to quickly replace the internal
4144 * media UUIDs with the UUIDs of the media that were exported.
4145 */
4146void MachineConfigFile::buildStorageControllersXML(xml::ElementNode &elmParent,
4147 const Storage &st,
4148 bool fSkipRemovableMedia,
4149 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes)
4150{
4151 xml::ElementNode *pelmStorageControllers = elmParent.createChild("StorageControllers");
4152
4153 for (StorageControllersList::const_iterator it = st.llStorageControllers.begin();
4154 it != st.llStorageControllers.end();
4155 ++it)
4156 {
4157 const StorageController &sc = *it;
4158
4159 if ( (m->sv < SettingsVersion_v1_9)
4160 && (sc.controllerType == StorageControllerType_I82078)
4161 )
4162 // floppy controller already got written into <Hardware>/<FloppyController> in writeHardware()
4163 // for pre-1.9 settings
4164 continue;
4165
4166 xml::ElementNode *pelmController = pelmStorageControllers->createChild("StorageController");
4167 com::Utf8Str name = sc.strName;
4168 if (m->sv < SettingsVersion_v1_8)
4169 {
4170 // pre-1.8 settings use shorter controller names, they are
4171 // expanded when reading the settings
4172 if (name == "IDE Controller")
4173 name = "IDE";
4174 else if (name == "SATA Controller")
4175 name = "SATA";
4176 else if (name == "SCSI Controller")
4177 name = "SCSI";
4178 }
4179 pelmController->setAttribute("name", sc.strName);
4180
4181 const char *pcszType;
4182 switch (sc.controllerType)
4183 {
4184 case StorageControllerType_IntelAhci: pcszType = "AHCI"; break;
4185 case StorageControllerType_LsiLogic: pcszType = "LsiLogic"; break;
4186 case StorageControllerType_BusLogic: pcszType = "BusLogic"; break;
4187 case StorageControllerType_PIIX4: pcszType = "PIIX4"; break;
4188 case StorageControllerType_ICH6: pcszType = "ICH6"; break;
4189 case StorageControllerType_I82078: pcszType = "I82078"; break;
4190 case StorageControllerType_LsiLogicSas: pcszType = "LsiLogicSas"; break;
4191 default: /*case StorageControllerType_PIIX3:*/ pcszType = "PIIX3"; break;
4192 }
4193 pelmController->setAttribute("type", pcszType);
4194
4195 pelmController->setAttribute("PortCount", sc.ulPortCount);
4196
4197 if (m->sv >= SettingsVersion_v1_9)
4198 if (sc.ulInstance)
4199 pelmController->setAttribute("Instance", sc.ulInstance);
4200
4201 if (m->sv >= SettingsVersion_v1_10)
4202 pelmController->setAttribute("useHostIOCache", sc.fUseHostIOCache);
4203
4204 if (m->sv >= SettingsVersion_v1_11)
4205 pelmController->setAttribute("Bootable", sc.fBootable);
4206
4207 if (sc.controllerType == StorageControllerType_IntelAhci)
4208 {
4209 pelmController->setAttribute("IDE0MasterEmulationPort", sc.lIDE0MasterEmulationPort);
4210 pelmController->setAttribute("IDE0SlaveEmulationPort", sc.lIDE0SlaveEmulationPort);
4211 pelmController->setAttribute("IDE1MasterEmulationPort", sc.lIDE1MasterEmulationPort);
4212 pelmController->setAttribute("IDE1SlaveEmulationPort", sc.lIDE1SlaveEmulationPort);
4213 }
4214
4215 for (AttachedDevicesList::const_iterator it2 = sc.llAttachedDevices.begin();
4216 it2 != sc.llAttachedDevices.end();
4217 ++it2)
4218 {
4219 const AttachedDevice &att = *it2;
4220
4221 // For settings version before 1.9, DVDs and floppies are in hardware, not storage controllers,
4222 // so we shouldn't write them here; we only get here for DVDs though because we ruled out
4223 // the floppy controller at the top of the loop
4224 if ( att.deviceType == DeviceType_DVD
4225 && m->sv < SettingsVersion_v1_9
4226 )
4227 continue;
4228
4229 xml::ElementNode *pelmDevice = pelmController->createChild("AttachedDevice");
4230
4231 pcszType = NULL;
4232
4233 switch (att.deviceType)
4234 {
4235 case DeviceType_HardDisk:
4236 pcszType = "HardDisk";
4237 if (att.fNonRotational)
4238 pelmDevice->setAttribute("nonrotational", att.fNonRotational);
4239 break;
4240
4241 case DeviceType_DVD:
4242 pcszType = "DVD";
4243 pelmDevice->setAttribute("passthrough", att.fPassThrough);
4244 if (att.fTempEject)
4245 pelmDevice->setAttribute("tempeject", att.fTempEject);
4246 break;
4247
4248 case DeviceType_Floppy:
4249 pcszType = "Floppy";
4250 break;
4251 }
4252
4253 pelmDevice->setAttribute("type", pcszType);
4254
4255 pelmDevice->setAttribute("port", att.lPort);
4256 pelmDevice->setAttribute("device", att.lDevice);
4257
4258 if (att.strBwGroup.length())
4259 pelmDevice->setAttribute("bandwidthGroup", att.strBwGroup);
4260
4261 // attached image, if any
4262 if ( !att.uuid.isEmpty()
4263 && ( att.deviceType == DeviceType_HardDisk
4264 || !fSkipRemovableMedia
4265 )
4266 )
4267 {
4268 xml::ElementNode *pelmImage = pelmDevice->createChild("Image");
4269 pelmImage->setAttribute("uuid", att.uuid.toStringCurly());
4270
4271 // if caller wants a list of UUID elements, give it to them
4272 if (pllElementsWithUuidAttributes)
4273 pllElementsWithUuidAttributes->push_back(pelmImage);
4274 }
4275 else if ( (m->sv >= SettingsVersion_v1_9)
4276 && (att.strHostDriveSrc.length())
4277 )
4278 pelmDevice->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
4279 }
4280 }
4281}
4282
4283/**
4284 * Writes a single snapshot into the DOM tree. Initially this gets called from MachineConfigFile::write()
4285 * for the root snapshot of a machine, if present; elmParent then points to the <Snapshots> node under the
4286 * <Machine> node to which <Snapshot> must be added. This may then recurse for child snapshots.
4287 * @param elmParent
4288 * @param snap
4289 */
4290void MachineConfigFile::buildSnapshotXML(xml::ElementNode &elmParent,
4291 const Snapshot &snap)
4292{
4293 xml::ElementNode *pelmSnapshot = elmParent.createChild("Snapshot");
4294
4295 pelmSnapshot->setAttribute("uuid", snap.uuid.toStringCurly());
4296 pelmSnapshot->setAttribute("name", snap.strName);
4297 pelmSnapshot->setAttribute("timeStamp", makeString(snap.timestamp));
4298
4299 if (snap.strStateFile.length())
4300 pelmSnapshot->setAttributePath("stateFile", snap.strStateFile);
4301
4302 if (snap.strDescription.length())
4303 pelmSnapshot->createChild("Description")->addContent(snap.strDescription);
4304
4305 buildHardwareXML(*pelmSnapshot, snap.hardware, snap.storage);
4306 buildStorageControllersXML(*pelmSnapshot,
4307 snap.storage,
4308 false /* fSkipRemovableMedia */,
4309 NULL); /* pllElementsWithUuidAttributes */
4310 // we only skip removable media for OVF, but we never get here for OVF
4311 // since snapshots never get written then
4312
4313 if (snap.llChildSnapshots.size())
4314 {
4315 xml::ElementNode *pelmChildren = pelmSnapshot->createChild("Snapshots");
4316 for (SnapshotsList::const_iterator it = snap.llChildSnapshots.begin();
4317 it != snap.llChildSnapshots.end();
4318 ++it)
4319 {
4320 const Snapshot &child = *it;
4321 buildSnapshotXML(*pelmChildren, child);
4322 }
4323 }
4324}
4325
4326/**
4327 * Builds the XML DOM tree for the machine config under the given XML element.
4328 *
4329 * This has been separated out from write() so it can be called from elsewhere,
4330 * such as the OVF code, to build machine XML in an existing XML tree.
4331 *
4332 * As a result, this gets called from two locations:
4333 *
4334 * -- MachineConfigFile::write();
4335 *
4336 * -- Appliance::buildXMLForOneVirtualSystem()
4337 *
4338 * In fl, the following flag bits are recognized:
4339 *
4340 * -- BuildMachineXML_MediaRegistry: If set, the machine's media registry will
4341 * be written, if present. This is not set when called from OVF because OVF
4342 * has its own variant of a media registry. This flag is ignored unless the
4343 * settings version is at least v1.11 (VirtualBox 4.0).
4344 *
4345 * -- BuildMachineXML_IncludeSnapshots: If set, descend into the snapshots tree
4346 * of the machine and write out <Snapshot> and possibly more snapshots under
4347 * that, if snapshots are present. Otherwise all snapshots are suppressed
4348 * (when called from OVF).
4349 *
4350 * -- BuildMachineXML_WriteVboxVersionAttribute: If set, add a settingsVersion
4351 * attribute to the machine tag with the vbox settings version. This is for
4352 * the OVF export case in which we don't have the settings version set in
4353 * the root element.
4354 *
4355 * -- BuildMachineXML_SkipRemovableMedia: If set, removable media attachments
4356 * (DVDs, floppies) are silently skipped. This is for the OVF export case
4357 * until we support copying ISO and RAW media as well. This flag is ignored
4358 * unless the settings version is at least v1.9, which is always the case
4359 * when this gets called for OVF export.
4360 *
4361 * -- BuildMachineXML_SuppressSavedState: If set, the Machine/@stateFile
4362 * attribute is never set. This is also for the OVF export case because we
4363 * cannot save states with OVF.
4364 *
4365 * @param elmMachine XML <Machine> element to add attributes and elements to.
4366 * @param fl Flags.
4367 * @param pllElementsWithUuidAttributes pointer to list that should receive UUID elements or NULL;
4368 * see buildStorageControllersXML() for details.
4369 */
4370void MachineConfigFile::buildMachineXML(xml::ElementNode &elmMachine,
4371 uint32_t fl,
4372 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes)
4373{
4374 if (fl & BuildMachineXML_WriteVboxVersionAttribute)
4375 // add settings version attribute to machine element
4376 setVersionAttribute(elmMachine);
4377
4378 elmMachine.setAttribute("uuid", uuid.toStringCurly());
4379 elmMachine.setAttribute("name", machineUserData.strName);
4380 if (!machineUserData.fNameSync)
4381 elmMachine.setAttribute("nameSync", machineUserData.fNameSync);
4382 if (machineUserData.strDescription.length())
4383 elmMachine.createChild("Description")->addContent(machineUserData.strDescription);
4384 elmMachine.setAttribute("OSType", machineUserData.strOsType);
4385 if ( strStateFile.length()
4386 && !(fl & BuildMachineXML_SuppressSavedState)
4387 )
4388 elmMachine.setAttributePath("stateFile", strStateFile);
4389 if ( (fl & BuildMachineXML_IncludeSnapshots)
4390 && !uuidCurrentSnapshot.isEmpty())
4391 elmMachine.setAttribute("currentSnapshot", uuidCurrentSnapshot.toStringCurly());
4392
4393 if (machineUserData.strSnapshotFolder.length())
4394 elmMachine.setAttributePath("snapshotFolder", machineUserData.strSnapshotFolder);
4395 if (!fCurrentStateModified)
4396 elmMachine.setAttribute("currentStateModified", fCurrentStateModified);
4397 elmMachine.setAttribute("lastStateChange", makeString(timeLastStateChange));
4398 if (fAborted)
4399 elmMachine.setAttribute("aborted", fAborted);
4400 if ( m->sv >= SettingsVersion_v1_9
4401 && ( machineUserData.fTeleporterEnabled
4402 || machineUserData.uTeleporterPort
4403 || !machineUserData.strTeleporterAddress.isEmpty()
4404 || !machineUserData.strTeleporterPassword.isEmpty()
4405 )
4406 )
4407 {
4408 xml::ElementNode *pelmTeleporter = elmMachine.createChild("Teleporter");
4409 pelmTeleporter->setAttribute("enabled", machineUserData.fTeleporterEnabled);
4410 pelmTeleporter->setAttribute("port", machineUserData.uTeleporterPort);
4411 pelmTeleporter->setAttribute("address", machineUserData.strTeleporterAddress);
4412 pelmTeleporter->setAttribute("password", machineUserData.strTeleporterPassword);
4413 }
4414
4415 if ( m->sv >= SettingsVersion_v1_11
4416 && ( machineUserData.enmFaultToleranceState != FaultToleranceState_Inactive
4417 || machineUserData.uFaultTolerancePort
4418 || machineUserData.uFaultToleranceInterval
4419 || !machineUserData.strFaultToleranceAddress.isEmpty()
4420 )
4421 )
4422 {
4423 xml::ElementNode *pelmFaultTolerance = elmMachine.createChild("FaultTolerance");
4424 switch (machineUserData.enmFaultToleranceState)
4425 {
4426 case FaultToleranceState_Inactive:
4427 pelmFaultTolerance->setAttribute("state", "inactive");
4428 break;
4429 case FaultToleranceState_Master:
4430 pelmFaultTolerance->setAttribute("state", "master");
4431 break;
4432 case FaultToleranceState_Standby:
4433 pelmFaultTolerance->setAttribute("state", "standby");
4434 break;
4435 }
4436
4437 pelmFaultTolerance->setAttribute("port", machineUserData.uFaultTolerancePort);
4438 pelmFaultTolerance->setAttribute("address", machineUserData.strFaultToleranceAddress);
4439 pelmFaultTolerance->setAttribute("interval", machineUserData.uFaultToleranceInterval);
4440 pelmFaultTolerance->setAttribute("password", machineUserData.strFaultTolerancePassword);
4441 }
4442
4443 if ( (fl & BuildMachineXML_MediaRegistry)
4444 && (m->sv >= SettingsVersion_v1_11)
4445 )
4446 buildMediaRegistry(elmMachine, mediaRegistry);
4447
4448 buildExtraData(elmMachine, mapExtraDataItems);
4449
4450 if ( (fl & BuildMachineXML_IncludeSnapshots)
4451 && llFirstSnapshot.size())
4452 buildSnapshotXML(elmMachine, llFirstSnapshot.front());
4453
4454 buildHardwareXML(elmMachine, hardwareMachine, storageMachine);
4455 buildStorageControllersXML(elmMachine,
4456 storageMachine,
4457 !!(fl & BuildMachineXML_SkipRemovableMedia),
4458 pllElementsWithUuidAttributes);
4459}
4460
4461/**
4462 * Returns true only if the given AudioDriverType is supported on
4463 * the current host platform. For example, this would return false
4464 * for AudioDriverType_DirectSound when compiled on a Linux host.
4465 * @param drv AudioDriverType_* enum to test.
4466 * @return true only if the current host supports that driver.
4467 */
4468/*static*/
4469bool MachineConfigFile::isAudioDriverAllowedOnThisHost(AudioDriverType_T drv)
4470{
4471 switch (drv)
4472 {
4473 case AudioDriverType_Null:
4474#ifdef RT_OS_WINDOWS
4475# ifdef VBOX_WITH_WINMM
4476 case AudioDriverType_WinMM:
4477# endif
4478 case AudioDriverType_DirectSound:
4479#endif /* RT_OS_WINDOWS */
4480#ifdef RT_OS_SOLARIS
4481 case AudioDriverType_SolAudio:
4482#endif
4483#ifdef RT_OS_LINUX
4484# ifdef VBOX_WITH_ALSA
4485 case AudioDriverType_ALSA:
4486# endif
4487# ifdef VBOX_WITH_PULSE
4488 case AudioDriverType_Pulse:
4489# endif
4490#endif /* RT_OS_LINUX */
4491#if defined (RT_OS_LINUX) || defined (RT_OS_FREEBSD) || defined(VBOX_WITH_SOLARIS_OSS)
4492 case AudioDriverType_OSS:
4493#endif
4494#ifdef RT_OS_FREEBSD
4495# ifdef VBOX_WITH_PULSE
4496 case AudioDriverType_Pulse:
4497# endif
4498#endif
4499#ifdef RT_OS_DARWIN
4500 case AudioDriverType_CoreAudio:
4501#endif
4502#ifdef RT_OS_OS2
4503 case AudioDriverType_MMPM:
4504#endif
4505 return true;
4506 }
4507
4508 return false;
4509}
4510
4511/**
4512 * Returns the AudioDriverType_* which should be used by default on this
4513 * host platform. On Linux, this will check at runtime whether PulseAudio
4514 * or ALSA are actually supported on the first call.
4515 * @return
4516 */
4517/*static*/
4518AudioDriverType_T MachineConfigFile::getHostDefaultAudioDriver()
4519{
4520#if defined(RT_OS_WINDOWS)
4521# ifdef VBOX_WITH_WINMM
4522 return AudioDriverType_WinMM;
4523# else /* VBOX_WITH_WINMM */
4524 return AudioDriverType_DirectSound;
4525# endif /* !VBOX_WITH_WINMM */
4526#elif defined(RT_OS_SOLARIS)
4527 return AudioDriverType_SolAudio;
4528#elif defined(RT_OS_LINUX)
4529 // on Linux, we need to check at runtime what's actually supported...
4530 static RTCLockMtx s_mtx;
4531 static AudioDriverType_T s_linuxDriver = -1;
4532 RTCLock lock(s_mtx);
4533 if (s_linuxDriver == (AudioDriverType_T)-1)
4534 {
4535# if defined(VBOX_WITH_PULSE)
4536 /* Check for the pulse library & that the pulse audio daemon is running. */
4537 if (RTProcIsRunningByName("pulseaudio") &&
4538 RTLdrIsLoadable("libpulse.so.0"))
4539 s_linuxDriver = AudioDriverType_Pulse;
4540 else
4541# endif /* VBOX_WITH_PULSE */
4542# if defined(VBOX_WITH_ALSA)
4543 /* Check if we can load the ALSA library */
4544 if (RTLdrIsLoadable("libasound.so.2"))
4545 s_linuxDriver = AudioDriverType_ALSA;
4546 else
4547# endif /* VBOX_WITH_ALSA */
4548 s_linuxDriver = AudioDriverType_OSS;
4549 }
4550 return s_linuxDriver;
4551// end elif defined(RT_OS_LINUX)
4552#elif defined(RT_OS_DARWIN)
4553 return AudioDriverType_CoreAudio;
4554#elif defined(RT_OS_OS2)
4555 return AudioDriverType_MMPM;
4556#elif defined(RT_OS_FREEBSD)
4557 return AudioDriverType_OSS;
4558#else
4559 return AudioDriverType_Null;
4560#endif
4561}
4562
4563/**
4564 * Called from write() before calling ConfigFileBase::createStubDocument().
4565 * This adjusts the settings version in m->sv if incompatible settings require
4566 * a settings bump, whereas otherwise we try to preserve the settings version
4567 * to avoid breaking compatibility with older versions.
4568 *
4569 * We do the checks in here in reverse order: newest first, oldest last, so
4570 * that we avoid unnecessary checks since some of these are expensive.
4571 */
4572void MachineConfigFile::bumpSettingsVersionIfNeeded()
4573{
4574 if (m->sv < SettingsVersion_v1_12)
4575 {
4576 // VirtualBox 4.1 adds PCI passthrough.
4577 if (hardwareMachine.pciAttachments.size())
4578 m->sv = SettingsVersion_v1_12;
4579 }
4580
4581 if (m->sv < SettingsVersion_v1_12)
4582 {
4583 // VirtualBox 4.1 adds a promiscuous mode policy to the network
4584 // adapters and a generic network driver transport.
4585 NetworkAdaptersList::const_iterator netit;
4586 for (netit = hardwareMachine.llNetworkAdapters.begin();
4587 netit != hardwareMachine.llNetworkAdapters.end();
4588 ++netit)
4589 {
4590 if ( netit->enmPromiscModePolicy != NetworkAdapterPromiscModePolicy_Deny
4591 || netit->mode == NetworkAttachmentType_Generic
4592 || !netit->strGenericDriver.isEmpty()
4593 || netit->genericProperties.size()
4594 )
4595 {
4596 m->sv = SettingsVersion_v1_12;
4597 break;
4598 }
4599 }
4600 }
4601
4602 if (m->sv < SettingsVersion_v1_11)
4603 {
4604 // VirtualBox 4.0 adds HD audio, CPU priorities, fault tolerance,
4605 // per-machine media registries, VRDE, JRockitVE, bandwidth gorups,
4606 // ICH9 chipset
4607 if ( hardwareMachine.audioAdapter.controllerType == AudioControllerType_HDA
4608 || hardwareMachine.ulCpuExecutionCap != 100
4609 || machineUserData.enmFaultToleranceState != FaultToleranceState_Inactive
4610 || machineUserData.uFaultTolerancePort
4611 || machineUserData.uFaultToleranceInterval
4612 || !machineUserData.strFaultToleranceAddress.isEmpty()
4613 || mediaRegistry.llHardDisks.size()
4614 || mediaRegistry.llDvdImages.size()
4615 || mediaRegistry.llFloppyImages.size()
4616 || !hardwareMachine.vrdeSettings.strVrdeExtPack.isEmpty()
4617 || !hardwareMachine.vrdeSettings.strAuthLibrary.isEmpty()
4618 || machineUserData.strOsType == "JRockitVE"
4619 || hardwareMachine.ioSettings.llBandwidthGroups.size()
4620 || hardwareMachine.chipsetType == ChipsetType_ICH9
4621 )
4622 m->sv = SettingsVersion_v1_11;
4623 }
4624
4625 if (m->sv < SettingsVersion_v1_10)
4626 {
4627 /* If the properties contain elements other than "TCP/Ports" and "TCP/Address",
4628 * then increase the version to at least VBox 3.2, which can have video channel properties.
4629 */
4630 unsigned cOldProperties = 0;
4631
4632 StringsMap::const_iterator it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Ports");
4633 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4634 cOldProperties++;
4635 it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Address");
4636 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4637 cOldProperties++;
4638
4639 if (hardwareMachine.vrdeSettings.mapProperties.size() != cOldProperties)
4640 m->sv = SettingsVersion_v1_10;
4641 }
4642
4643 if (m->sv < SettingsVersion_v1_11)
4644 {
4645 /* If the properties contain elements other than "TCP/Ports", "TCP/Address",
4646 * "VideoChannel/Enabled" and "VideoChannel/Quality" then increase the version to VBox 4.0.
4647 */
4648 unsigned cOldProperties = 0;
4649
4650 StringsMap::const_iterator it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Ports");
4651 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4652 cOldProperties++;
4653 it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Address");
4654 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4655 cOldProperties++;
4656 it = hardwareMachine.vrdeSettings.mapProperties.find("VideoChannel/Enabled");
4657 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4658 cOldProperties++;
4659 it = hardwareMachine.vrdeSettings.mapProperties.find("VideoChannel/Quality");
4660 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4661 cOldProperties++;
4662
4663 if (hardwareMachine.vrdeSettings.mapProperties.size() != cOldProperties)
4664 m->sv = SettingsVersion_v1_11;
4665 }
4666
4667 // settings version 1.9 is required if there is not exactly one DVD
4668 // or more than one floppy drive present or the DVD is not at the secondary
4669 // master; this check is a bit more complicated
4670 //
4671 // settings version 1.10 is required if the host cache should be disabled
4672 //
4673 // settings version 1.11 is required for bandwidth limits and if more than
4674 // one controller of each type is present.
4675 if (m->sv < SettingsVersion_v1_11)
4676 {
4677 // count attached DVDs and floppies (only if < v1.9)
4678 size_t cDVDs = 0;
4679 size_t cFloppies = 0;
4680
4681 // count storage controllers (if < v1.11)
4682 size_t cSata = 0;
4683 size_t cScsiLsi = 0;
4684 size_t cScsiBuslogic = 0;
4685 size_t cSas = 0;
4686 size_t cIde = 0;
4687 size_t cFloppy = 0;
4688
4689 // need to run thru all the storage controllers and attached devices to figure this out
4690 for (StorageControllersList::const_iterator it = storageMachine.llStorageControllers.begin();
4691 it != storageMachine.llStorageControllers.end();
4692 ++it)
4693 {
4694 const StorageController &sctl = *it;
4695
4696 // count storage controllers of each type; 1.11 is required if more than one
4697 // controller of one type is present
4698 switch (sctl.storageBus)
4699 {
4700 case StorageBus_IDE:
4701 cIde++;
4702 break;
4703 case StorageBus_SATA:
4704 cSata++;
4705 break;
4706 case StorageBus_SAS:
4707 cSas++;
4708 break;
4709 case StorageBus_SCSI:
4710 if (sctl.controllerType == StorageControllerType_LsiLogic)
4711 cScsiLsi++;
4712 else
4713 cScsiBuslogic++;
4714 break;
4715 case StorageBus_Floppy:
4716 cFloppy++;
4717 break;
4718 default:
4719 // Do nothing
4720 break;
4721 }
4722
4723 if ( cSata > 1
4724 || cScsiLsi > 1
4725 || cScsiBuslogic > 1
4726 || cSas > 1
4727 || cIde > 1
4728 || cFloppy > 1)
4729 {
4730 m->sv = SettingsVersion_v1_11;
4731 break; // abort the loop -- we will not raise the version further
4732 }
4733
4734 for (AttachedDevicesList::const_iterator it2 = sctl.llAttachedDevices.begin();
4735 it2 != sctl.llAttachedDevices.end();
4736 ++it2)
4737 {
4738 const AttachedDevice &att = *it2;
4739
4740 // Bandwidth limitations are new in VirtualBox 4.0 (1.11)
4741 if (m->sv < SettingsVersion_v1_11)
4742 {
4743 if (att.strBwGroup.length() != 0)
4744 {
4745 m->sv = SettingsVersion_v1_11;
4746 break; // abort the loop -- we will not raise the version further
4747 }
4748 }
4749
4750 // disabling the host IO cache requires settings version 1.10
4751 if ( (m->sv < SettingsVersion_v1_10)
4752 && (!sctl.fUseHostIOCache)
4753 )
4754 m->sv = SettingsVersion_v1_10;
4755
4756 // we can only write the StorageController/@Instance attribute with v1.9
4757 if ( (m->sv < SettingsVersion_v1_9)
4758 && (sctl.ulInstance != 0)
4759 )
4760 m->sv = SettingsVersion_v1_9;
4761
4762 if (m->sv < SettingsVersion_v1_9)
4763 {
4764 if (att.deviceType == DeviceType_DVD)
4765 {
4766 if ( (sctl.storageBus != StorageBus_IDE) // DVD at bus other than DVD?
4767 || (att.lPort != 1) // DVDs not at secondary master?
4768 || (att.lDevice != 0)
4769 )
4770 m->sv = SettingsVersion_v1_9;
4771
4772 ++cDVDs;
4773 }
4774 else if (att.deviceType == DeviceType_Floppy)
4775 ++cFloppies;
4776 }
4777 }
4778
4779 if (m->sv >= SettingsVersion_v1_11)
4780 break; // abort the loop -- we will not raise the version further
4781 }
4782
4783 // VirtualBox before 3.1 had zero or one floppy and exactly one DVD,
4784 // so any deviation from that will require settings version 1.9
4785 if ( (m->sv < SettingsVersion_v1_9)
4786 && ( (cDVDs != 1)
4787 || (cFloppies > 1)
4788 )
4789 )
4790 m->sv = SettingsVersion_v1_9;
4791 }
4792
4793 // VirtualBox 3.2: Check for non default I/O settings
4794 if (m->sv < SettingsVersion_v1_10)
4795 {
4796 if ( (hardwareMachine.ioSettings.fIoCacheEnabled != true)
4797 || (hardwareMachine.ioSettings.ulIoCacheSize != 5)
4798 // and page fusion
4799 || (hardwareMachine.fPageFusionEnabled)
4800 // and CPU hotplug, RTC timezone control, HID type and HPET
4801 || machineUserData.fRTCUseUTC
4802 || hardwareMachine.fCpuHotPlug
4803 || hardwareMachine.pointingHidType != PointingHidType_PS2Mouse
4804 || hardwareMachine.keyboardHidType != KeyboardHidType_PS2Keyboard
4805 || hardwareMachine.fHpetEnabled
4806 )
4807 m->sv = SettingsVersion_v1_10;
4808 }
4809
4810 // VirtualBox 3.2 adds NAT and boot priority to the NIC config in Main
4811 // VirtualBox 4.0 adds network bandwitdth
4812 if (m->sv < SettingsVersion_v1_11)
4813 {
4814 NetworkAdaptersList::const_iterator netit;
4815 for (netit = hardwareMachine.llNetworkAdapters.begin();
4816 netit != hardwareMachine.llNetworkAdapters.end();
4817 ++netit)
4818 {
4819 if ( (m->sv < SettingsVersion_v1_12)
4820 && (netit->strBandwidthGroup.isNotEmpty())
4821 )
4822 {
4823 /* New in VirtualBox 4.1 */
4824 m->sv = SettingsVersion_v1_12;
4825 break;
4826 }
4827 else if ( (m->sv < SettingsVersion_v1_10)
4828 && (netit->fEnabled)
4829 && (netit->mode == NetworkAttachmentType_NAT)
4830 && ( netit->nat.u32Mtu != 0
4831 || netit->nat.u32SockRcv != 0
4832 || netit->nat.u32SockSnd != 0
4833 || netit->nat.u32TcpRcv != 0
4834 || netit->nat.u32TcpSnd != 0
4835 || !netit->nat.fDnsPassDomain
4836 || netit->nat.fDnsProxy
4837 || netit->nat.fDnsUseHostResolver
4838 || netit->nat.fAliasLog
4839 || netit->nat.fAliasProxyOnly
4840 || netit->nat.fAliasUseSamePorts
4841 || netit->nat.strTftpPrefix.length()
4842 || netit->nat.strTftpBootFile.length()
4843 || netit->nat.strTftpNextServer.length()
4844 || netit->nat.llRules.size()
4845 )
4846 )
4847 {
4848 m->sv = SettingsVersion_v1_10;
4849 // no break because we still might need v1.11 above
4850 }
4851 else if ( (m->sv < SettingsVersion_v1_10)
4852 && (netit->fEnabled)
4853 && (netit->ulBootPriority != 0)
4854 )
4855 {
4856 m->sv = SettingsVersion_v1_10;
4857 // no break because we still might need v1.11 above
4858 }
4859 }
4860 }
4861
4862 // all the following require settings version 1.9
4863 if ( (m->sv < SettingsVersion_v1_9)
4864 && ( (hardwareMachine.firmwareType >= FirmwareType_EFI)
4865 || (hardwareMachine.fHardwareVirtExclusive != HWVIRTEXCLUSIVEDEFAULT)
4866 || machineUserData.fTeleporterEnabled
4867 || machineUserData.uTeleporterPort
4868 || !machineUserData.strTeleporterAddress.isEmpty()
4869 || !machineUserData.strTeleporterPassword.isEmpty()
4870 || !hardwareMachine.uuid.isEmpty()
4871 )
4872 )
4873 m->sv = SettingsVersion_v1_9;
4874
4875 // "accelerate 2d video" requires settings version 1.8
4876 if ( (m->sv < SettingsVersion_v1_8)
4877 && (hardwareMachine.fAccelerate2DVideo)
4878 )
4879 m->sv = SettingsVersion_v1_8;
4880
4881 // The hardware versions other than "1" requires settings version 1.4 (2.1+).
4882 if ( m->sv < SettingsVersion_v1_4
4883 && hardwareMachine.strVersion != "1"
4884 )
4885 m->sv = SettingsVersion_v1_4;
4886}
4887
4888/**
4889 * Called from Main code to write a machine config file to disk. This builds a DOM tree from
4890 * the member variables and then writes the XML file; it throws xml::Error instances on errors,
4891 * in particular if the file cannot be written.
4892 */
4893void MachineConfigFile::write(const com::Utf8Str &strFilename)
4894{
4895 try
4896 {
4897 // createStubDocument() sets the settings version to at least 1.7; however,
4898 // we might need to enfore a later settings version if incompatible settings
4899 // are present:
4900 bumpSettingsVersionIfNeeded();
4901
4902 m->strFilename = strFilename;
4903 createStubDocument();
4904
4905 xml::ElementNode *pelmMachine = m->pelmRoot->createChild("Machine");
4906 buildMachineXML(*pelmMachine,
4907 MachineConfigFile::BuildMachineXML_IncludeSnapshots
4908 | MachineConfigFile::BuildMachineXML_MediaRegistry,
4909 // but not BuildMachineXML_WriteVboxVersionAttribute
4910 NULL); /* pllElementsWithUuidAttributes */
4911
4912 // now go write the XML
4913 xml::XmlFileWriter writer(*m->pDoc);
4914 writer.write(m->strFilename.c_str(), true /*fSafe*/);
4915
4916 m->fFileExists = true;
4917 clearDocument();
4918 }
4919 catch (...)
4920 {
4921 clearDocument();
4922 throw;
4923 }
4924}
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