VirtualBox

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

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

Main: renavation com::Guid class. PR5744

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