VirtualBox

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

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

Main/xml/Settings.cpp: forgotten code to handle the new settings version

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