VirtualBox

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

最後變更 在這個檔案從35149是 35149,由 vboxsync 提交於 14 年 前

Main/settings: small correction for suppressing the default DVD/floppy medium types

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

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