VirtualBox

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

Last change on this file since 51502 was 51476, checked in by vboxsync, 10 years ago

DnD: API overhaul; now using IDnDTarget + IDnDSource. Renamed DragAndDrop* enumerations to DnD*. Also rewrote some internal code.

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