VirtualBox

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

Last change on this file since 49866 was 49687, checked in by vboxsync, 11 years ago

Main/Snapshot: block deleting of current snapshot if it has child snapshots, as this would lead to VM config corruption, plus safety belts in the GUI and settings reader

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

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