VirtualBox

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

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

Main/settings: leave out RAW format definition for DVD and floppy images, it is the default and is selected when nothing is specified

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

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