VirtualBox

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

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

Main/SystemProperties+Machine: new config setting for default VM frontend.
Frontend/VirtualBox+VBoxManage: changes to use the default VM frontend when starting a VM, other minor cleanups
Main/xml/*.xsd: attempt to bring the XML schema close to reality
doc/manual: document the new possibilities, and fix a few long standing inaccuracies

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