VirtualBox

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

Last change on this file since 36168 was 36168, checked in by vboxsync, 14 years ago

Main: a few more time format fixes

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