VirtualBox

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

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

Main/Network: DHCP server has got the ear in Main, and we able create/describe more complex infrostructures. DHCP server together with Lwip NAT can handle per vm/slot configuration and store them in xml settings.

place-holder: Host interface nameserver list, domain name and search strings, I suppose that this functions should be used on initialization stage and then on host configuration change even or directly from event.

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