VirtualBox

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

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

Main: bump settings version if NAT networks are defined

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