VirtualBox

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

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

hash the teleporter token.

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