VirtualBox

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

Last change on this file since 48328 was 48093, checked in by vboxsync, 11 years ago

NAT/xml: loopback mappings introduces NATNetwork entities:

<Mappings>

<Loopback4 address="127.0.1.1" offset="6"/>
<Loopback4 address="127.0.1.2" offset="7"/>

</Mappings>

to describe mapppings any hostid in 127/8 network to our NAT network, e.g. in this case 127.0.1.1 corresponds to network id + 6 (network id here from CIDR defined on creation), for IPv6 (as soon localhost6 could be only one) attribute "loopback6" is reserved in NATNetwork tag.

operators: NATHostLoopbackOffset::operator == (const Utf8Str&) and NATHostLoopbackOffset::operator==(uint32_t) are introduced got using std::find on adding and modification operations in NATNetworkImpl.

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