VirtualBox

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

Last change on this file since 53409 was 52959, checked in by vboxsync, 10 years ago

Main: warnings

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