VirtualBox

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

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

Main+Frontends/VBoxManage: implement saving the settings, and add the matching VBoxManage support

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