VirtualBox

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

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

Main: some mis-indented breaks

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