VirtualBox

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

Last change on this file since 44873 was 44873, checked in by vboxsync, 12 years ago

Main/xml/Settings.cpp: fix copy/paste bug which lost the inactive internal network configuration

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