VirtualBox

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

Last change on this file since 46123 was 46123, checked in by vboxsync, 12 years ago

Main/VPX, VBoxManage: added IMachine::VideoCaptureScreens and IDisplay::{enableVideoCapture,disableVideoCapture}

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette