VirtualBox

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

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

Main: Added paravirt. provider APIs.

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