VirtualBox

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

Last change on this file since 33944 was 33828, checked in by vboxsync, 14 years ago

xml: win build fix. (explicit type conversion).

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