VirtualBox

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

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

Main, VMM, vboxshell: more PCI work (persistent settings, logging, more driver API), API consumer in vboxshell

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

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