VirtualBox

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

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

Missing changes

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Revision Author Id
File size: 212.5 KB
Line 
1/* $Id: Settings.cpp 42179 2012-07-17 12:42:32Z 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 pelmGlobalChild->getAttributeValue("autostartDatabasePath", systemProperties.strAutostartDatabasePath);
1297 }
1298 else if (pelmGlobalChild->nameEquals("ExtraData"))
1299 readExtraData(*pelmGlobalChild, mapExtraDataItems);
1300 else if (pelmGlobalChild->nameEquals("MachineRegistry"))
1301 readMachineRegistry(*pelmGlobalChild);
1302 else if ( (pelmGlobalChild->nameEquals("MediaRegistry"))
1303 || ( (m->sv < SettingsVersion_v1_4)
1304 && (pelmGlobalChild->nameEquals("DiskRegistry"))
1305 )
1306 )
1307 readMediaRegistry(*pelmGlobalChild, mediaRegistry);
1308 else if (pelmGlobalChild->nameEquals("NetserviceRegistry"))
1309 {
1310 xml::NodesLoop nlLevel4(*pelmGlobalChild);
1311 const xml::ElementNode *pelmLevel4Child;
1312 while ((pelmLevel4Child = nlLevel4.forAllNodes()))
1313 {
1314 if (pelmLevel4Child->nameEquals("DHCPServers"))
1315 readDHCPServers(*pelmLevel4Child);
1316 }
1317 }
1318 else if (pelmGlobalChild->nameEquals("USBDeviceFilters"))
1319 readUSBDeviceFilters(*pelmGlobalChild, host.llUSBDeviceFilters);
1320 }
1321 } // end if (pelmRootChild->nameEquals("Global"))
1322 }
1323
1324 clearDocument();
1325 }
1326
1327 // DHCP servers were introduced with settings version 1.7; if we're loading
1328 // from an older version OR this is a fresh install, then add one DHCP server
1329 // with default settings
1330 if ( (!llDhcpServers.size())
1331 && ( (!pstrFilename) // empty VirtualBox.xml file
1332 || (m->sv < SettingsVersion_v1_7) // upgrading from before 1.7
1333 )
1334 )
1335 {
1336 DHCPServer srv;
1337 srv.strNetworkName =
1338#ifdef RT_OS_WINDOWS
1339 "HostInterfaceNetworking-VirtualBox Host-Only Ethernet Adapter";
1340#else
1341 "HostInterfaceNetworking-vboxnet0";
1342#endif
1343 srv.strIPAddress = "192.168.56.100";
1344 srv.strIPNetworkMask = "255.255.255.0";
1345 srv.strIPLower = "192.168.56.101";
1346 srv.strIPUpper = "192.168.56.254";
1347 srv.fEnabled = true;
1348 llDhcpServers.push_back(srv);
1349 }
1350}
1351
1352/**
1353 * Called from the IVirtualBox interface to write out VirtualBox.xml. This
1354 * builds an XML DOM tree and writes it out to disk.
1355 */
1356void MainConfigFile::write(const com::Utf8Str strFilename)
1357{
1358 m->strFilename = strFilename;
1359 createStubDocument();
1360
1361 xml::ElementNode *pelmGlobal = m->pelmRoot->createChild("Global");
1362
1363 buildExtraData(*pelmGlobal, mapExtraDataItems);
1364
1365 xml::ElementNode *pelmMachineRegistry = pelmGlobal->createChild("MachineRegistry");
1366 for (MachinesRegistry::const_iterator it = llMachines.begin();
1367 it != llMachines.end();
1368 ++it)
1369 {
1370 // <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"/>
1371 const MachineRegistryEntry &mre = *it;
1372 xml::ElementNode *pelmMachineEntry = pelmMachineRegistry->createChild("MachineEntry");
1373 pelmMachineEntry->setAttribute("uuid", mre.uuid.toStringCurly());
1374 pelmMachineEntry->setAttribute("src", mre.strSettingsFile);
1375 }
1376
1377 buildMediaRegistry(*pelmGlobal, mediaRegistry);
1378
1379 xml::ElementNode *pelmNetserviceRegistry = pelmGlobal->createChild("NetserviceRegistry");
1380 xml::ElementNode *pelmDHCPServers = pelmNetserviceRegistry->createChild("DHCPServers");
1381 for (DHCPServersList::const_iterator it = llDhcpServers.begin();
1382 it != llDhcpServers.end();
1383 ++it)
1384 {
1385 const DHCPServer &d = *it;
1386 xml::ElementNode *pelmThis = pelmDHCPServers->createChild("DHCPServer");
1387 pelmThis->setAttribute("networkName", d.strNetworkName);
1388 pelmThis->setAttribute("IPAddress", d.strIPAddress);
1389 pelmThis->setAttribute("networkMask", d.strIPNetworkMask);
1390 pelmThis->setAttribute("lowerIP", d.strIPLower);
1391 pelmThis->setAttribute("upperIP", d.strIPUpper);
1392 pelmThis->setAttribute("enabled", (d.fEnabled) ? 1 : 0); // too bad we chose 1 vs. 0 here
1393 }
1394
1395 xml::ElementNode *pelmSysProps = pelmGlobal->createChild("SystemProperties");
1396 if (systemProperties.strDefaultMachineFolder.length())
1397 pelmSysProps->setAttribute("defaultMachineFolder", systemProperties.strDefaultMachineFolder);
1398 if (systemProperties.strDefaultHardDiskFormat.length())
1399 pelmSysProps->setAttribute("defaultHardDiskFormat", systemProperties.strDefaultHardDiskFormat);
1400 if (systemProperties.strVRDEAuthLibrary.length())
1401 pelmSysProps->setAttribute("VRDEAuthLibrary", systemProperties.strVRDEAuthLibrary);
1402 if (systemProperties.strWebServiceAuthLibrary.length())
1403 pelmSysProps->setAttribute("webServiceAuthLibrary", systemProperties.strWebServiceAuthLibrary);
1404 if (systemProperties.strDefaultVRDEExtPack.length())
1405 pelmSysProps->setAttribute("defaultVRDEExtPack", systemProperties.strDefaultVRDEExtPack);
1406 pelmSysProps->setAttribute("LogHistoryCount", systemProperties.ulLogHistoryCount);
1407 if (systemProperties.strAutostartDatabasePath.length())
1408 pelmSysProps->setAttribute("autostartDatabasePath", systemProperties.strAutostartDatabasePath);
1409
1410 buildUSBDeviceFilters(*pelmGlobal->createChild("USBDeviceFilters"),
1411 host.llUSBDeviceFilters,
1412 true); // fHostMode
1413
1414 // now go write the XML
1415 xml::XmlFileWriter writer(*m->pDoc);
1416 writer.write(m->strFilename.c_str(), true /*fSafe*/);
1417
1418 m->fFileExists = true;
1419
1420 clearDocument();
1421}
1422
1423////////////////////////////////////////////////////////////////////////////////
1424//
1425// Machine XML structures
1426//
1427////////////////////////////////////////////////////////////////////////////////
1428
1429/**
1430 * Comparison operator. This gets called from MachineConfigFile::operator==,
1431 * which in turn gets called from Machine::saveSettings to figure out whether
1432 * machine settings have really changed and thus need to be written out to disk.
1433 */
1434bool VRDESettings::operator==(const VRDESettings& v) const
1435{
1436 return ( (this == &v)
1437 || ( (fEnabled == v.fEnabled)
1438 && (authType == v.authType)
1439 && (ulAuthTimeout == v.ulAuthTimeout)
1440 && (strAuthLibrary == v.strAuthLibrary)
1441 && (fAllowMultiConnection == v.fAllowMultiConnection)
1442 && (fReuseSingleConnection == v.fReuseSingleConnection)
1443 && (strVrdeExtPack == v.strVrdeExtPack)
1444 && (mapProperties == v.mapProperties)
1445 )
1446 );
1447}
1448
1449/**
1450 * Comparison operator. This gets called from MachineConfigFile::operator==,
1451 * which in turn gets called from Machine::saveSettings to figure out whether
1452 * machine settings have really changed and thus need to be written out to disk.
1453 */
1454bool BIOSSettings::operator==(const BIOSSettings &d) const
1455{
1456 return ( (this == &d)
1457 || ( fACPIEnabled == d.fACPIEnabled
1458 && fIOAPICEnabled == d.fIOAPICEnabled
1459 && fLogoFadeIn == d.fLogoFadeIn
1460 && fLogoFadeOut == d.fLogoFadeOut
1461 && ulLogoDisplayTime == d.ulLogoDisplayTime
1462 && strLogoImagePath == d.strLogoImagePath
1463 && biosBootMenuMode == d.biosBootMenuMode
1464 && fPXEDebugEnabled == d.fPXEDebugEnabled
1465 && llTimeOffset == d.llTimeOffset)
1466 );
1467}
1468
1469/**
1470 * Comparison operator. This gets called from MachineConfigFile::operator==,
1471 * which in turn gets called from Machine::saveSettings to figure out whether
1472 * machine settings have really changed and thus need to be written out to disk.
1473 */
1474bool USBController::operator==(const USBController &u) const
1475{
1476 return ( (this == &u)
1477 || ( (fEnabled == u.fEnabled)
1478 && (fEnabledEHCI == u.fEnabledEHCI)
1479 && (llDeviceFilters == u.llDeviceFilters)
1480 )
1481 );
1482}
1483
1484/**
1485 * Comparison operator. This gets called from MachineConfigFile::operator==,
1486 * which in turn gets called from Machine::saveSettings to figure out whether
1487 * machine settings have really changed and thus need to be written out to disk.
1488 */
1489bool NetworkAdapter::operator==(const NetworkAdapter &n) const
1490{
1491 return ( (this == &n)
1492 || ( (ulSlot == n.ulSlot)
1493 && (type == n.type)
1494 && (fEnabled == n.fEnabled)
1495 && (strMACAddress == n.strMACAddress)
1496 && (fCableConnected == n.fCableConnected)
1497 && (ulLineSpeed == n.ulLineSpeed)
1498 && (enmPromiscModePolicy == n.enmPromiscModePolicy)
1499 && (fTraceEnabled == n.fTraceEnabled)
1500 && (strTraceFile == n.strTraceFile)
1501 && (mode == n.mode)
1502 && (nat == n.nat)
1503 && (strBridgedName == n.strBridgedName)
1504 && (strHostOnlyName == n.strHostOnlyName)
1505 && (strInternalNetworkName == n.strInternalNetworkName)
1506 && (strGenericDriver == n.strGenericDriver)
1507 && (genericProperties == n.genericProperties)
1508 && (ulBootPriority == n.ulBootPriority)
1509 && (strBandwidthGroup == n.strBandwidthGroup)
1510 )
1511 );
1512}
1513
1514/**
1515 * Comparison operator. This gets called from MachineConfigFile::operator==,
1516 * which in turn gets called from Machine::saveSettings to figure out whether
1517 * machine settings have really changed and thus need to be written out to disk.
1518 */
1519bool SerialPort::operator==(const SerialPort &s) const
1520{
1521 return ( (this == &s)
1522 || ( (ulSlot == s.ulSlot)
1523 && (fEnabled == s.fEnabled)
1524 && (ulIOBase == s.ulIOBase)
1525 && (ulIRQ == s.ulIRQ)
1526 && (portMode == s.portMode)
1527 && (strPath == s.strPath)
1528 && (fServer == s.fServer)
1529 )
1530 );
1531}
1532
1533/**
1534 * Comparison operator. This gets called from MachineConfigFile::operator==,
1535 * which in turn gets called from Machine::saveSettings to figure out whether
1536 * machine settings have really changed and thus need to be written out to disk.
1537 */
1538bool ParallelPort::operator==(const ParallelPort &s) const
1539{
1540 return ( (this == &s)
1541 || ( (ulSlot == s.ulSlot)
1542 && (fEnabled == s.fEnabled)
1543 && (ulIOBase == s.ulIOBase)
1544 && (ulIRQ == s.ulIRQ)
1545 && (strPath == s.strPath)
1546 )
1547 );
1548}
1549
1550/**
1551 * Comparison operator. This gets called from MachineConfigFile::operator==,
1552 * which in turn gets called from Machine::saveSettings to figure out whether
1553 * machine settings have really changed and thus need to be written out to disk.
1554 */
1555bool SharedFolder::operator==(const SharedFolder &g) const
1556{
1557 return ( (this == &g)
1558 || ( (strName == g.strName)
1559 && (strHostPath == g.strHostPath)
1560 && (fWritable == g.fWritable)
1561 && (fAutoMount == g.fAutoMount)
1562 )
1563 );
1564}
1565
1566/**
1567 * Comparison operator. This gets called from MachineConfigFile::operator==,
1568 * which in turn gets called from Machine::saveSettings to figure out whether
1569 * machine settings have really changed and thus need to be written out to disk.
1570 */
1571bool GuestProperty::operator==(const GuestProperty &g) const
1572{
1573 return ( (this == &g)
1574 || ( (strName == g.strName)
1575 && (strValue == g.strValue)
1576 && (timestamp == g.timestamp)
1577 && (strFlags == g.strFlags)
1578 )
1579 );
1580}
1581
1582// use a define for the platform-dependent default value of
1583// hwvirt exclusivity, since we'll need to check that value
1584// in bumpSettingsVersionIfNeeded()
1585#if defined(RT_OS_DARWIN) || defined(RT_OS_WINDOWS)
1586 #define HWVIRTEXCLUSIVEDEFAULT false
1587#else
1588 #define HWVIRTEXCLUSIVEDEFAULT true
1589#endif
1590
1591/**
1592 * Hardware struct constructor.
1593 */
1594Hardware::Hardware()
1595 : strVersion("1"),
1596 fHardwareVirt(true),
1597 fHardwareVirtExclusive(HWVIRTEXCLUSIVEDEFAULT),
1598 fNestedPaging(true),
1599 fVPID(true),
1600 fHardwareVirtForce(false),
1601 fSyntheticCpu(false),
1602 fPAE(false),
1603 cCPUs(1),
1604 fCpuHotPlug(false),
1605 fHpetEnabled(false),
1606 ulCpuExecutionCap(100),
1607 ulMemorySizeMB((uint32_t)-1),
1608 ulVRAMSizeMB(8),
1609 cMonitors(1),
1610 fAccelerate3D(false),
1611 fAccelerate2DVideo(false),
1612 firmwareType(FirmwareType_BIOS),
1613 pointingHidType(PointingHidType_PS2Mouse),
1614 keyboardHidType(KeyboardHidType_PS2Keyboard),
1615 chipsetType(ChipsetType_PIIX3),
1616 fEmulatedUSBCardReader(false),
1617 clipboardMode(ClipboardMode_Bidirectional),
1618 ulMemoryBalloonSize(0),
1619 fPageFusionEnabled(false)
1620{
1621 mapBootOrder[0] = DeviceType_Floppy;
1622 mapBootOrder[1] = DeviceType_DVD;
1623 mapBootOrder[2] = DeviceType_HardDisk;
1624
1625 /* The default value for PAE depends on the host:
1626 * - 64 bits host -> always true
1627 * - 32 bits host -> true for Windows & Darwin (masked off if the host cpu doesn't support it anyway)
1628 */
1629#if HC_ARCH_BITS == 64 || defined(RT_OS_WINDOWS) || defined(RT_OS_DARWIN)
1630 fPAE = true;
1631#endif
1632
1633 /* The default value of large page supports depends on the host:
1634 * - 64 bits host -> true, unless it's Linux (pending further prediction work due to excessively expensive large page allocations)
1635 * - 32 bits host -> false
1636 */
1637#if HC_ARCH_BITS == 64 && !defined(RT_OS_LINUX)
1638 fLargePages = true;
1639#else
1640 /* Not supported on 32 bits hosts. */
1641 fLargePages = false;
1642#endif
1643}
1644
1645/**
1646 * Comparison operator. This gets called from MachineConfigFile::operator==,
1647 * which in turn gets called from Machine::saveSettings to figure out whether
1648 * machine settings have really changed and thus need to be written out to disk.
1649 */
1650bool Hardware::operator==(const Hardware& h) const
1651{
1652 return ( (this == &h)
1653 || ( (strVersion == h.strVersion)
1654 && (uuid == h.uuid)
1655 && (fHardwareVirt == h.fHardwareVirt)
1656 && (fHardwareVirtExclusive == h.fHardwareVirtExclusive)
1657 && (fNestedPaging == h.fNestedPaging)
1658 && (fLargePages == h.fLargePages)
1659 && (fVPID == h.fVPID)
1660 && (fHardwareVirtForce == h.fHardwareVirtForce)
1661 && (fSyntheticCpu == h.fSyntheticCpu)
1662 && (fPAE == h.fPAE)
1663 && (cCPUs == h.cCPUs)
1664 && (fCpuHotPlug == h.fCpuHotPlug)
1665 && (ulCpuExecutionCap == h.ulCpuExecutionCap)
1666 && (fHpetEnabled == h.fHpetEnabled)
1667 && (llCpus == h.llCpus)
1668 && (llCpuIdLeafs == h.llCpuIdLeafs)
1669 && (ulMemorySizeMB == h.ulMemorySizeMB)
1670 && (mapBootOrder == h.mapBootOrder)
1671 && (ulVRAMSizeMB == h.ulVRAMSizeMB)
1672 && (cMonitors == h.cMonitors)
1673 && (fAccelerate3D == h.fAccelerate3D)
1674 && (fAccelerate2DVideo == h.fAccelerate2DVideo)
1675 && (firmwareType == h.firmwareType)
1676 && (pointingHidType == h.pointingHidType)
1677 && (keyboardHidType == h.keyboardHidType)
1678 && (chipsetType == h.chipsetType)
1679 && (fEmulatedUSBCardReader == h.fEmulatedUSBCardReader)
1680 && (vrdeSettings == h.vrdeSettings)
1681 && (biosSettings == h.biosSettings)
1682 && (usbController == h.usbController)
1683 && (llNetworkAdapters == h.llNetworkAdapters)
1684 && (llSerialPorts == h.llSerialPorts)
1685 && (llParallelPorts == h.llParallelPorts)
1686 && (audioAdapter == h.audioAdapter)
1687 && (llSharedFolders == h.llSharedFolders)
1688 && (clipboardMode == h.clipboardMode)
1689 && (ulMemoryBalloonSize == h.ulMemoryBalloonSize)
1690 && (fPageFusionEnabled == h.fPageFusionEnabled)
1691 && (llGuestProperties == h.llGuestProperties)
1692 && (strNotificationPatterns == h.strNotificationPatterns)
1693 && (ioSettings == h.ioSettings)
1694 && (pciAttachments == h.pciAttachments)
1695 )
1696 );
1697}
1698
1699/**
1700 * Comparison operator. This gets called from MachineConfigFile::operator==,
1701 * which in turn gets called from Machine::saveSettings to figure out whether
1702 * machine settings have really changed and thus need to be written out to disk.
1703 */
1704bool AttachedDevice::operator==(const AttachedDevice &a) const
1705{
1706 return ( (this == &a)
1707 || ( (deviceType == a.deviceType)
1708 && (fPassThrough == a.fPassThrough)
1709 && (fTempEject == a.fTempEject)
1710 && (fNonRotational == a.fNonRotational)
1711 && (fDiscard == a.fDiscard)
1712 && (lPort == a.lPort)
1713 && (lDevice == a.lDevice)
1714 && (uuid == a.uuid)
1715 && (strHostDriveSrc == a.strHostDriveSrc)
1716 && (strBwGroup == a.strBwGroup)
1717 )
1718 );
1719}
1720
1721/**
1722 * Comparison operator. This gets called from MachineConfigFile::operator==,
1723 * which in turn gets called from Machine::saveSettings to figure out whether
1724 * machine settings have really changed and thus need to be written out to disk.
1725 */
1726bool StorageController::operator==(const StorageController &s) const
1727{
1728 return ( (this == &s)
1729 || ( (strName == s.strName)
1730 && (storageBus == s.storageBus)
1731 && (controllerType == s.controllerType)
1732 && (ulPortCount == s.ulPortCount)
1733 && (ulInstance == s.ulInstance)
1734 && (fUseHostIOCache == s.fUseHostIOCache)
1735 && (lIDE0MasterEmulationPort == s.lIDE0MasterEmulationPort)
1736 && (lIDE0SlaveEmulationPort == s.lIDE0SlaveEmulationPort)
1737 && (lIDE1MasterEmulationPort == s.lIDE1MasterEmulationPort)
1738 && (lIDE1SlaveEmulationPort == s.lIDE1SlaveEmulationPort)
1739 && (llAttachedDevices == s.llAttachedDevices)
1740 )
1741 );
1742}
1743
1744/**
1745 * Comparison operator. This gets called from MachineConfigFile::operator==,
1746 * which in turn gets called from Machine::saveSettings to figure out whether
1747 * machine settings have really changed and thus need to be written out to disk.
1748 */
1749bool Storage::operator==(const Storage &s) const
1750{
1751 return ( (this == &s)
1752 || (llStorageControllers == s.llStorageControllers) // deep compare
1753 );
1754}
1755
1756/**
1757 * Comparison operator. This gets called from MachineConfigFile::operator==,
1758 * which in turn gets called from Machine::saveSettings to figure out whether
1759 * machine settings have really changed and thus need to be written out to disk.
1760 */
1761bool Snapshot::operator==(const Snapshot &s) const
1762{
1763 return ( (this == &s)
1764 || ( (uuid == s.uuid)
1765 && (strName == s.strName)
1766 && (strDescription == s.strDescription)
1767 && (RTTimeSpecIsEqual(&timestamp, &s.timestamp))
1768 && (strStateFile == s.strStateFile)
1769 && (hardware == s.hardware) // deep compare
1770 && (storage == s.storage) // deep compare
1771 && (llChildSnapshots == s.llChildSnapshots) // deep compare
1772 && debugging == s.debugging
1773 && autostart == s.autostart
1774 )
1775 );
1776}
1777
1778/**
1779 * IoSettings constructor.
1780 */
1781IoSettings::IoSettings()
1782{
1783 fIoCacheEnabled = true;
1784 ulIoCacheSize = 5;
1785}
1786
1787////////////////////////////////////////////////////////////////////////////////
1788//
1789// MachineConfigFile
1790//
1791////////////////////////////////////////////////////////////////////////////////
1792
1793/**
1794 * Constructor.
1795 *
1796 * If pstrFilename is != NULL, this reads the given settings file into the member
1797 * variables and various substructures and lists. Otherwise, the member variables
1798 * are initialized with default values.
1799 *
1800 * Throws variants of xml::Error for I/O, XML and logical content errors, which
1801 * the caller should catch; if this constructor does not throw, then the member
1802 * variables contain meaningful values (either from the file or defaults).
1803 *
1804 * @param strFilename
1805 */
1806MachineConfigFile::MachineConfigFile(const Utf8Str *pstrFilename)
1807 : ConfigFileBase(pstrFilename),
1808 fCurrentStateModified(true),
1809 fAborted(false)
1810{
1811 RTTimeNow(&timeLastStateChange);
1812
1813 if (pstrFilename)
1814 {
1815 // the ConfigFileBase constructor has loaded the XML file, so now
1816 // we need only analyze what is in there
1817
1818 xml::NodesLoop nlRootChildren(*m->pelmRoot);
1819 const xml::ElementNode *pelmRootChild;
1820 while ((pelmRootChild = nlRootChildren.forAllNodes()))
1821 {
1822 if (pelmRootChild->nameEquals("Machine"))
1823 readMachine(*pelmRootChild);
1824 }
1825
1826 // clean up memory allocated by XML engine
1827 clearDocument();
1828 }
1829}
1830
1831/**
1832 * Public routine which returns true if this machine config file can have its
1833 * own media registry (which is true for settings version v1.11 and higher,
1834 * i.e. files created by VirtualBox 4.0 and higher).
1835 * @return
1836 */
1837bool MachineConfigFile::canHaveOwnMediaRegistry() const
1838{
1839 return (m->sv >= SettingsVersion_v1_11);
1840}
1841
1842/**
1843 * Public routine which allows for importing machine XML from an external DOM tree.
1844 * Use this after having called the constructor with a NULL argument.
1845 *
1846 * This is used by the OVF code if a <vbox:Machine> element has been encountered
1847 * in an OVF VirtualSystem element.
1848 *
1849 * @param elmMachine
1850 */
1851void MachineConfigFile::importMachineXML(const xml::ElementNode &elmMachine)
1852{
1853 readMachine(elmMachine);
1854}
1855
1856/**
1857 * Comparison operator. This gets called from Machine::saveSettings to figure out
1858 * whether machine settings have really changed and thus need to be written out to disk.
1859 *
1860 * Even though this is called operator==, this does NOT compare all fields; the "equals"
1861 * should be understood as "has the same machine config as". The following fields are
1862 * NOT compared:
1863 * -- settings versions and file names inherited from ConfigFileBase;
1864 * -- fCurrentStateModified because that is considered separately in Machine::saveSettings!!
1865 *
1866 * The "deep" comparisons marked below will invoke the operator== functions of the
1867 * structs defined in this file, which may in turn go into comparing lists of
1868 * other structures. As a result, invoking this can be expensive, but it's
1869 * less expensive than writing out XML to disk.
1870 */
1871bool MachineConfigFile::operator==(const MachineConfigFile &c) const
1872{
1873 return ( (this == &c)
1874 || ( (uuid == c.uuid)
1875 && (machineUserData == c.machineUserData)
1876 && (strStateFile == c.strStateFile)
1877 && (uuidCurrentSnapshot == c.uuidCurrentSnapshot)
1878 // skip fCurrentStateModified!
1879 && (RTTimeSpecIsEqual(&timeLastStateChange, &c.timeLastStateChange))
1880 && (fAborted == c.fAborted)
1881 && (hardwareMachine == c.hardwareMachine) // this one's deep
1882 && (storageMachine == c.storageMachine) // this one's deep
1883 && (mediaRegistry == c.mediaRegistry) // this one's deep
1884 && (mapExtraDataItems == c.mapExtraDataItems) // this one's deep
1885 && (llFirstSnapshot == c.llFirstSnapshot) // this one's deep
1886 )
1887 );
1888}
1889
1890/**
1891 * Called from MachineConfigFile::readHardware() to read cpu information.
1892 * @param elmCpuid
1893 * @param ll
1894 */
1895void MachineConfigFile::readCpuTree(const xml::ElementNode &elmCpu,
1896 CpuList &ll)
1897{
1898 xml::NodesLoop nl1(elmCpu, "Cpu");
1899 const xml::ElementNode *pelmCpu;
1900 while ((pelmCpu = nl1.forAllNodes()))
1901 {
1902 Cpu cpu;
1903
1904 if (!pelmCpu->getAttributeValue("id", cpu.ulId))
1905 throw ConfigFileError(this, pelmCpu, N_("Required Cpu/@id attribute is missing"));
1906
1907 ll.push_back(cpu);
1908 }
1909}
1910
1911/**
1912 * Called from MachineConfigFile::readHardware() to cpuid information.
1913 * @param elmCpuid
1914 * @param ll
1915 */
1916void MachineConfigFile::readCpuIdTree(const xml::ElementNode &elmCpuid,
1917 CpuIdLeafsList &ll)
1918{
1919 xml::NodesLoop nl1(elmCpuid, "CpuIdLeaf");
1920 const xml::ElementNode *pelmCpuIdLeaf;
1921 while ((pelmCpuIdLeaf = nl1.forAllNodes()))
1922 {
1923 CpuIdLeaf leaf;
1924
1925 if (!pelmCpuIdLeaf->getAttributeValue("id", leaf.ulId))
1926 throw ConfigFileError(this, pelmCpuIdLeaf, N_("Required CpuId/@id attribute is missing"));
1927
1928 pelmCpuIdLeaf->getAttributeValue("eax", leaf.ulEax);
1929 pelmCpuIdLeaf->getAttributeValue("ebx", leaf.ulEbx);
1930 pelmCpuIdLeaf->getAttributeValue("ecx", leaf.ulEcx);
1931 pelmCpuIdLeaf->getAttributeValue("edx", leaf.ulEdx);
1932
1933 ll.push_back(leaf);
1934 }
1935}
1936
1937/**
1938 * Called from MachineConfigFile::readHardware() to network information.
1939 * @param elmNetwork
1940 * @param ll
1941 */
1942void MachineConfigFile::readNetworkAdapters(const xml::ElementNode &elmNetwork,
1943 NetworkAdaptersList &ll)
1944{
1945 xml::NodesLoop nl1(elmNetwork, "Adapter");
1946 const xml::ElementNode *pelmAdapter;
1947 while ((pelmAdapter = nl1.forAllNodes()))
1948 {
1949 NetworkAdapter nic;
1950
1951 if (!pelmAdapter->getAttributeValue("slot", nic.ulSlot))
1952 throw ConfigFileError(this, pelmAdapter, N_("Required Adapter/@slot attribute is missing"));
1953
1954 Utf8Str strTemp;
1955 if (pelmAdapter->getAttributeValue("type", strTemp))
1956 {
1957 if (strTemp == "Am79C970A")
1958 nic.type = NetworkAdapterType_Am79C970A;
1959 else if (strTemp == "Am79C973")
1960 nic.type = NetworkAdapterType_Am79C973;
1961 else if (strTemp == "82540EM")
1962 nic.type = NetworkAdapterType_I82540EM;
1963 else if (strTemp == "82543GC")
1964 nic.type = NetworkAdapterType_I82543GC;
1965 else if (strTemp == "82545EM")
1966 nic.type = NetworkAdapterType_I82545EM;
1967 else if (strTemp == "virtio")
1968 nic.type = NetworkAdapterType_Virtio;
1969 else
1970 throw ConfigFileError(this, pelmAdapter, N_("Invalid value '%s' in Adapter/@type attribute"), strTemp.c_str());
1971 }
1972
1973 pelmAdapter->getAttributeValue("enabled", nic.fEnabled);
1974 pelmAdapter->getAttributeValue("MACAddress", nic.strMACAddress);
1975 pelmAdapter->getAttributeValue("cable", nic.fCableConnected);
1976 pelmAdapter->getAttributeValue("speed", nic.ulLineSpeed);
1977
1978 if (pelmAdapter->getAttributeValue("promiscuousModePolicy", strTemp))
1979 {
1980 if (strTemp == "Deny")
1981 nic.enmPromiscModePolicy = NetworkAdapterPromiscModePolicy_Deny;
1982 else if (strTemp == "AllowNetwork")
1983 nic.enmPromiscModePolicy = NetworkAdapterPromiscModePolicy_AllowNetwork;
1984 else if (strTemp == "AllowAll")
1985 nic.enmPromiscModePolicy = NetworkAdapterPromiscModePolicy_AllowAll;
1986 else
1987 throw ConfigFileError(this, pelmAdapter,
1988 N_("Invalid value '%s' in Adapter/@promiscuousModePolicy attribute"), strTemp.c_str());
1989 }
1990
1991 pelmAdapter->getAttributeValue("trace", nic.fTraceEnabled);
1992 pelmAdapter->getAttributeValue("tracefile", nic.strTraceFile);
1993 pelmAdapter->getAttributeValue("bootPriority", nic.ulBootPriority);
1994 pelmAdapter->getAttributeValue("bandwidthGroup", nic.strBandwidthGroup);
1995
1996 xml::ElementNodesList llNetworkModes;
1997 pelmAdapter->getChildElements(llNetworkModes);
1998 xml::ElementNodesList::iterator it;
1999 /* We should have only active mode descriptor and disabled modes set */
2000 if (llNetworkModes.size() > 2)
2001 {
2002 throw ConfigFileError(this, pelmAdapter, N_("Invalid number of modes ('%d') attached to Adapter attribute"), llNetworkModes.size());
2003 }
2004 for (it = llNetworkModes.begin(); it != llNetworkModes.end(); ++it)
2005 {
2006 const xml::ElementNode *pelmNode = *it;
2007 if (pelmNode->nameEquals("DisabledModes"))
2008 {
2009 xml::ElementNodesList llDisabledNetworkModes;
2010 xml::ElementNodesList::iterator itDisabled;
2011 pelmNode->getChildElements(llDisabledNetworkModes);
2012 /* run over disabled list and load settings */
2013 for (itDisabled = llDisabledNetworkModes.begin();
2014 itDisabled != llDisabledNetworkModes.end(); ++itDisabled)
2015 {
2016 const xml::ElementNode *pelmDisabledNode = *itDisabled;
2017 readAttachedNetworkMode(*pelmDisabledNode, false, nic);
2018 }
2019 }
2020 else
2021 readAttachedNetworkMode(*pelmNode, true, nic);
2022 }
2023 // else: default is NetworkAttachmentType_Null
2024
2025 ll.push_back(nic);
2026 }
2027}
2028
2029void MachineConfigFile::readAttachedNetworkMode(const xml::ElementNode &elmMode, bool fEnabled, NetworkAdapter &nic)
2030{
2031 NetworkAttachmentType_T enmAttachmentType = NetworkAttachmentType_Null;
2032
2033 if (elmMode.nameEquals("NAT"))
2034 {
2035 enmAttachmentType = NetworkAttachmentType_NAT;
2036
2037 elmMode.getAttributeValue("network", nic.nat.strNetwork);
2038 elmMode.getAttributeValue("hostip", nic.nat.strBindIP);
2039 elmMode.getAttributeValue("mtu", nic.nat.u32Mtu);
2040 elmMode.getAttributeValue("sockrcv", nic.nat.u32SockRcv);
2041 elmMode.getAttributeValue("socksnd", nic.nat.u32SockSnd);
2042 elmMode.getAttributeValue("tcprcv", nic.nat.u32TcpRcv);
2043 elmMode.getAttributeValue("tcpsnd", nic.nat.u32TcpSnd);
2044 const xml::ElementNode *pelmDNS;
2045 if ((pelmDNS = elmMode.findChildElement("DNS")))
2046 {
2047 pelmDNS->getAttributeValue("pass-domain", nic.nat.fDnsPassDomain);
2048 pelmDNS->getAttributeValue("use-proxy", nic.nat.fDnsProxy);
2049 pelmDNS->getAttributeValue("use-host-resolver", nic.nat.fDnsUseHostResolver);
2050 }
2051 const xml::ElementNode *pelmAlias;
2052 if ((pelmAlias = elmMode.findChildElement("Alias")))
2053 {
2054 pelmAlias->getAttributeValue("logging", nic.nat.fAliasLog);
2055 pelmAlias->getAttributeValue("proxy-only", nic.nat.fAliasProxyOnly);
2056 pelmAlias->getAttributeValue("use-same-ports", nic.nat.fAliasUseSamePorts);
2057 }
2058 const xml::ElementNode *pelmTFTP;
2059 if ((pelmTFTP = elmMode.findChildElement("TFTP")))
2060 {
2061 pelmTFTP->getAttributeValue("prefix", nic.nat.strTftpPrefix);
2062 pelmTFTP->getAttributeValue("boot-file", nic.nat.strTftpBootFile);
2063 pelmTFTP->getAttributeValue("next-server", nic.nat.strTftpNextServer);
2064 }
2065 xml::ElementNodesList plstNatPF;
2066 elmMode.getChildElements(plstNatPF, "Forwarding");
2067 for (xml::ElementNodesList::iterator pf = plstNatPF.begin(); pf != plstNatPF.end(); ++pf)
2068 {
2069 NATRule rule;
2070 uint32_t port = 0;
2071 (*pf)->getAttributeValue("name", rule.strName);
2072 (*pf)->getAttributeValue("proto", (uint32_t&)rule.proto);
2073 (*pf)->getAttributeValue("hostip", rule.strHostIP);
2074 (*pf)->getAttributeValue("hostport", port);
2075 rule.u16HostPort = port;
2076 (*pf)->getAttributeValue("guestip", rule.strGuestIP);
2077 (*pf)->getAttributeValue("guestport", port);
2078 rule.u16GuestPort = port;
2079 nic.nat.llRules.push_back(rule);
2080 }
2081 }
2082 else if ( (elmMode.nameEquals("HostInterface"))
2083 || (elmMode.nameEquals("BridgedInterface")))
2084 {
2085 enmAttachmentType = NetworkAttachmentType_Bridged;
2086
2087 elmMode.getAttributeValue("name", nic.strBridgedName); // optional bridged interface name
2088 }
2089 else if (elmMode.nameEquals("InternalNetwork"))
2090 {
2091 enmAttachmentType = NetworkAttachmentType_Internal;
2092
2093 if (!elmMode.getAttributeValue("name", nic.strInternalNetworkName)) // required network name
2094 throw ConfigFileError(this, &elmMode, N_("Required InternalNetwork/@name element is missing"));
2095 }
2096 else if (elmMode.nameEquals("HostOnlyInterface"))
2097 {
2098 enmAttachmentType = NetworkAttachmentType_HostOnly;
2099
2100 if (!elmMode.getAttributeValue("name", nic.strHostOnlyName)) // required network name
2101 throw ConfigFileError(this, &elmMode, N_("Required HostOnlyInterface/@name element is missing"));
2102 }
2103 else if (elmMode.nameEquals("GenericInterface"))
2104 {
2105 enmAttachmentType = NetworkAttachmentType_Generic;
2106
2107 elmMode.getAttributeValue("driver", nic.strGenericDriver); // optional network attachment driver
2108
2109 // get all properties
2110 xml::NodesLoop nl(elmMode);
2111 const xml::ElementNode *pelmModeChild;
2112 while ((pelmModeChild = nl.forAllNodes()))
2113 {
2114 if (pelmModeChild->nameEquals("Property"))
2115 {
2116 Utf8Str strPropName, strPropValue;
2117 if ( (pelmModeChild->getAttributeValue("name", strPropName))
2118 && (pelmModeChild->getAttributeValue("value", strPropValue))
2119 )
2120 nic.genericProperties[strPropName] = strPropValue;
2121 else
2122 throw ConfigFileError(this, pelmModeChild, N_("Required GenericInterface/Property/@name or @value attribute is missing"));
2123 }
2124 }
2125 }
2126 else if (elmMode.nameEquals("VDE"))
2127 {
2128 enmAttachmentType = NetworkAttachmentType_Generic;
2129
2130 com::Utf8Str strVDEName;
2131 elmMode.getAttributeValue("network", strVDEName); // optional network name
2132 nic.strGenericDriver = "VDE";
2133 nic.genericProperties["network"] = strVDEName;
2134 }
2135
2136 if (fEnabled && enmAttachmentType != NetworkAttachmentType_Null)
2137 nic.mode = enmAttachmentType;
2138}
2139
2140/**
2141 * Called from MachineConfigFile::readHardware() to read serial port information.
2142 * @param elmUART
2143 * @param ll
2144 */
2145void MachineConfigFile::readSerialPorts(const xml::ElementNode &elmUART,
2146 SerialPortsList &ll)
2147{
2148 xml::NodesLoop nl1(elmUART, "Port");
2149 const xml::ElementNode *pelmPort;
2150 while ((pelmPort = nl1.forAllNodes()))
2151 {
2152 SerialPort port;
2153 if (!pelmPort->getAttributeValue("slot", port.ulSlot))
2154 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@slot attribute is missing"));
2155
2156 // slot must be unique
2157 for (SerialPortsList::const_iterator it = ll.begin();
2158 it != ll.end();
2159 ++it)
2160 if ((*it).ulSlot == port.ulSlot)
2161 throw ConfigFileError(this, pelmPort, N_("Invalid value %RU32 in UART/Port/@slot attribute: value is not unique"), port.ulSlot);
2162
2163 if (!pelmPort->getAttributeValue("enabled", port.fEnabled))
2164 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@enabled attribute is missing"));
2165 if (!pelmPort->getAttributeValue("IOBase", port.ulIOBase))
2166 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@IOBase attribute is missing"));
2167 if (!pelmPort->getAttributeValue("IRQ", port.ulIRQ))
2168 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@IRQ attribute is missing"));
2169
2170 Utf8Str strPortMode;
2171 if (!pelmPort->getAttributeValue("hostMode", strPortMode))
2172 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@hostMode attribute is missing"));
2173 if (strPortMode == "RawFile")
2174 port.portMode = PortMode_RawFile;
2175 else if (strPortMode == "HostPipe")
2176 port.portMode = PortMode_HostPipe;
2177 else if (strPortMode == "HostDevice")
2178 port.portMode = PortMode_HostDevice;
2179 else if (strPortMode == "Disconnected")
2180 port.portMode = PortMode_Disconnected;
2181 else
2182 throw ConfigFileError(this, pelmPort, N_("Invalid value '%s' in UART/Port/@hostMode attribute"), strPortMode.c_str());
2183
2184 pelmPort->getAttributeValue("path", port.strPath);
2185 pelmPort->getAttributeValue("server", port.fServer);
2186
2187 ll.push_back(port);
2188 }
2189}
2190
2191/**
2192 * Called from MachineConfigFile::readHardware() to read parallel port information.
2193 * @param elmLPT
2194 * @param ll
2195 */
2196void MachineConfigFile::readParallelPorts(const xml::ElementNode &elmLPT,
2197 ParallelPortsList &ll)
2198{
2199 xml::NodesLoop nl1(elmLPT, "Port");
2200 const xml::ElementNode *pelmPort;
2201 while ((pelmPort = nl1.forAllNodes()))
2202 {
2203 ParallelPort port;
2204 if (!pelmPort->getAttributeValue("slot", port.ulSlot))
2205 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@slot attribute is missing"));
2206
2207 // slot must be unique
2208 for (ParallelPortsList::const_iterator it = ll.begin();
2209 it != ll.end();
2210 ++it)
2211 if ((*it).ulSlot == port.ulSlot)
2212 throw ConfigFileError(this, pelmPort, N_("Invalid value %RU32 in LPT/Port/@slot attribute: value is not unique"), port.ulSlot);
2213
2214 if (!pelmPort->getAttributeValue("enabled", port.fEnabled))
2215 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@enabled attribute is missing"));
2216 if (!pelmPort->getAttributeValue("IOBase", port.ulIOBase))
2217 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@IOBase attribute is missing"));
2218 if (!pelmPort->getAttributeValue("IRQ", port.ulIRQ))
2219 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@IRQ attribute is missing"));
2220
2221 pelmPort->getAttributeValue("path", port.strPath);
2222
2223 ll.push_back(port);
2224 }
2225}
2226
2227/**
2228 * Called from MachineConfigFile::readHardware() to read audio adapter information
2229 * and maybe fix driver information depending on the current host hardware.
2230 *
2231 * @param elmAudioAdapter "AudioAdapter" XML element.
2232 * @param hw
2233 */
2234void MachineConfigFile::readAudioAdapter(const xml::ElementNode &elmAudioAdapter,
2235 AudioAdapter &aa)
2236{
2237 elmAudioAdapter.getAttributeValue("enabled", aa.fEnabled);
2238
2239 Utf8Str strTemp;
2240 if (elmAudioAdapter.getAttributeValue("controller", strTemp))
2241 {
2242 if (strTemp == "SB16")
2243 aa.controllerType = AudioControllerType_SB16;
2244 else if (strTemp == "AC97")
2245 aa.controllerType = AudioControllerType_AC97;
2246 else if (strTemp == "HDA")
2247 aa.controllerType = AudioControllerType_HDA;
2248 else
2249 throw ConfigFileError(this, &elmAudioAdapter, N_("Invalid value '%s' in AudioAdapter/@controller attribute"), strTemp.c_str());
2250 }
2251
2252 if (elmAudioAdapter.getAttributeValue("driver", strTemp))
2253 {
2254 // settings before 1.3 used lower case so make sure this is case-insensitive
2255 strTemp.toUpper();
2256 if (strTemp == "NULL")
2257 aa.driverType = AudioDriverType_Null;
2258 else if (strTemp == "WINMM")
2259 aa.driverType = AudioDriverType_WinMM;
2260 else if ( (strTemp == "DIRECTSOUND") || (strTemp == "DSOUND") )
2261 aa.driverType = AudioDriverType_DirectSound;
2262 else if (strTemp == "SOLAUDIO")
2263 aa.driverType = AudioDriverType_SolAudio;
2264 else if (strTemp == "ALSA")
2265 aa.driverType = AudioDriverType_ALSA;
2266 else if (strTemp == "PULSE")
2267 aa.driverType = AudioDriverType_Pulse;
2268 else if (strTemp == "OSS")
2269 aa.driverType = AudioDriverType_OSS;
2270 else if (strTemp == "COREAUDIO")
2271 aa.driverType = AudioDriverType_CoreAudio;
2272 else if (strTemp == "MMPM")
2273 aa.driverType = AudioDriverType_MMPM;
2274 else
2275 throw ConfigFileError(this, &elmAudioAdapter, N_("Invalid value '%s' in AudioAdapter/@driver attribute"), strTemp.c_str());
2276
2277 // now check if this is actually supported on the current host platform;
2278 // people might be opening a file created on a Windows host, and that
2279 // VM should still start on a Linux host
2280 if (!isAudioDriverAllowedOnThisHost(aa.driverType))
2281 aa.driverType = getHostDefaultAudioDriver();
2282 }
2283}
2284
2285/**
2286 * Called from MachineConfigFile::readHardware() to read guest property information.
2287 * @param elmGuestProperties
2288 * @param hw
2289 */
2290void MachineConfigFile::readGuestProperties(const xml::ElementNode &elmGuestProperties,
2291 Hardware &hw)
2292{
2293 xml::NodesLoop nl1(elmGuestProperties, "GuestProperty");
2294 const xml::ElementNode *pelmProp;
2295 while ((pelmProp = nl1.forAllNodes()))
2296 {
2297 GuestProperty prop;
2298 pelmProp->getAttributeValue("name", prop.strName);
2299 pelmProp->getAttributeValue("value", prop.strValue);
2300
2301 pelmProp->getAttributeValue("timestamp", prop.timestamp);
2302 pelmProp->getAttributeValue("flags", prop.strFlags);
2303 hw.llGuestProperties.push_back(prop);
2304 }
2305
2306 elmGuestProperties.getAttributeValue("notificationPatterns", hw.strNotificationPatterns);
2307}
2308
2309/**
2310 * Helper function to read attributes that are common to <SATAController> (pre-1.7)
2311 * and <StorageController>.
2312 * @param elmStorageController
2313 * @param strg
2314 */
2315void MachineConfigFile::readStorageControllerAttributes(const xml::ElementNode &elmStorageController,
2316 StorageController &sctl)
2317{
2318 elmStorageController.getAttributeValue("PortCount", sctl.ulPortCount);
2319 elmStorageController.getAttributeValue("IDE0MasterEmulationPort", sctl.lIDE0MasterEmulationPort);
2320 elmStorageController.getAttributeValue("IDE0SlaveEmulationPort", sctl.lIDE0SlaveEmulationPort);
2321 elmStorageController.getAttributeValue("IDE1MasterEmulationPort", sctl.lIDE1MasterEmulationPort);
2322 elmStorageController.getAttributeValue("IDE1SlaveEmulationPort", sctl.lIDE1SlaveEmulationPort);
2323
2324 elmStorageController.getAttributeValue("useHostIOCache", sctl.fUseHostIOCache);
2325}
2326
2327/**
2328 * Reads in a <Hardware> block and stores it in the given structure. Used
2329 * both directly from readMachine and from readSnapshot, since snapshots
2330 * have their own hardware sections.
2331 *
2332 * For legacy pre-1.7 settings we also need a storage structure because
2333 * the IDE and SATA controllers used to be defined under <Hardware>.
2334 *
2335 * @param elmHardware
2336 * @param hw
2337 */
2338void MachineConfigFile::readHardware(const xml::ElementNode &elmHardware,
2339 Hardware &hw,
2340 Storage &strg)
2341{
2342 if (!elmHardware.getAttributeValue("version", hw.strVersion))
2343 {
2344 /* KLUDGE ALERT! For a while during the 3.1 development this was not
2345 written because it was thought to have a default value of "2". For
2346 sv <= 1.3 it defaults to "1" because the attribute didn't exist,
2347 while for 1.4+ it is sort of mandatory. Now, the buggy XML writer
2348 code only wrote 1.7 and later. So, if it's a 1.7+ XML file and it's
2349 missing the hardware version, then it probably should be "2" instead
2350 of "1". */
2351 if (m->sv < SettingsVersion_v1_7)
2352 hw.strVersion = "1";
2353 else
2354 hw.strVersion = "2";
2355 }
2356 Utf8Str strUUID;
2357 if (elmHardware.getAttributeValue("uuid", strUUID))
2358 parseUUID(hw.uuid, strUUID);
2359
2360 xml::NodesLoop nl1(elmHardware);
2361 const xml::ElementNode *pelmHwChild;
2362 while ((pelmHwChild = nl1.forAllNodes()))
2363 {
2364 if (pelmHwChild->nameEquals("CPU"))
2365 {
2366 if (!pelmHwChild->getAttributeValue("count", hw.cCPUs))
2367 {
2368 // pre-1.5 variant; not sure if this actually exists in the wild anywhere
2369 const xml::ElementNode *pelmCPUChild;
2370 if ((pelmCPUChild = pelmHwChild->findChildElement("CPUCount")))
2371 pelmCPUChild->getAttributeValue("count", hw.cCPUs);
2372 }
2373
2374 pelmHwChild->getAttributeValue("hotplug", hw.fCpuHotPlug);
2375 pelmHwChild->getAttributeValue("executionCap", hw.ulCpuExecutionCap);
2376
2377 const xml::ElementNode *pelmCPUChild;
2378 if (hw.fCpuHotPlug)
2379 {
2380 if ((pelmCPUChild = pelmHwChild->findChildElement("CpuTree")))
2381 readCpuTree(*pelmCPUChild, hw.llCpus);
2382 }
2383
2384 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtEx")))
2385 {
2386 pelmCPUChild->getAttributeValue("enabled", hw.fHardwareVirt);
2387 pelmCPUChild->getAttributeValue("exclusive", hw.fHardwareVirtExclusive); // settings version 1.9
2388 }
2389 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExNestedPaging")))
2390 pelmCPUChild->getAttributeValue("enabled", hw.fNestedPaging);
2391 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExLargePages")))
2392 pelmCPUChild->getAttributeValue("enabled", hw.fLargePages);
2393 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExVPID")))
2394 pelmCPUChild->getAttributeValue("enabled", hw.fVPID);
2395 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtForce")))
2396 pelmCPUChild->getAttributeValue("enabled", hw.fHardwareVirtForce);
2397
2398 if (!(pelmCPUChild = pelmHwChild->findChildElement("PAE")))
2399 {
2400 /* The default for pre 3.1 was false, so we must respect that. */
2401 if (m->sv < SettingsVersion_v1_9)
2402 hw.fPAE = false;
2403 }
2404 else
2405 pelmCPUChild->getAttributeValue("enabled", hw.fPAE);
2406
2407 if ((pelmCPUChild = pelmHwChild->findChildElement("SyntheticCpu")))
2408 pelmCPUChild->getAttributeValue("enabled", hw.fSyntheticCpu);
2409 if ((pelmCPUChild = pelmHwChild->findChildElement("CpuIdTree")))
2410 readCpuIdTree(*pelmCPUChild, hw.llCpuIdLeafs);
2411 }
2412 else if (pelmHwChild->nameEquals("Memory"))
2413 {
2414 pelmHwChild->getAttributeValue("RAMSize", hw.ulMemorySizeMB);
2415 pelmHwChild->getAttributeValue("PageFusion", hw.fPageFusionEnabled);
2416 }
2417 else if (pelmHwChild->nameEquals("Firmware"))
2418 {
2419 Utf8Str strFirmwareType;
2420 if (pelmHwChild->getAttributeValue("type", strFirmwareType))
2421 {
2422 if ( (strFirmwareType == "BIOS")
2423 || (strFirmwareType == "1") // some trunk builds used the number here
2424 )
2425 hw.firmwareType = FirmwareType_BIOS;
2426 else if ( (strFirmwareType == "EFI")
2427 || (strFirmwareType == "2") // some trunk builds used the number here
2428 )
2429 hw.firmwareType = FirmwareType_EFI;
2430 else if ( strFirmwareType == "EFI32")
2431 hw.firmwareType = FirmwareType_EFI32;
2432 else if ( strFirmwareType == "EFI64")
2433 hw.firmwareType = FirmwareType_EFI64;
2434 else if ( strFirmwareType == "EFIDUAL")
2435 hw.firmwareType = FirmwareType_EFIDUAL;
2436 else
2437 throw ConfigFileError(this,
2438 pelmHwChild,
2439 N_("Invalid value '%s' in Firmware/@type"),
2440 strFirmwareType.c_str());
2441 }
2442 }
2443 else if (pelmHwChild->nameEquals("HID"))
2444 {
2445 Utf8Str strHidType;
2446 if (pelmHwChild->getAttributeValue("Keyboard", strHidType))
2447 {
2448 if (strHidType == "None")
2449 hw.keyboardHidType = KeyboardHidType_None;
2450 else if (strHidType == "USBKeyboard")
2451 hw.keyboardHidType = KeyboardHidType_USBKeyboard;
2452 else if (strHidType == "PS2Keyboard")
2453 hw.keyboardHidType = KeyboardHidType_PS2Keyboard;
2454 else if (strHidType == "ComboKeyboard")
2455 hw.keyboardHidType = KeyboardHidType_ComboKeyboard;
2456 else
2457 throw ConfigFileError(this,
2458 pelmHwChild,
2459 N_("Invalid value '%s' in HID/Keyboard/@type"),
2460 strHidType.c_str());
2461 }
2462 if (pelmHwChild->getAttributeValue("Pointing", strHidType))
2463 {
2464 if (strHidType == "None")
2465 hw.pointingHidType = PointingHidType_None;
2466 else if (strHidType == "USBMouse")
2467 hw.pointingHidType = PointingHidType_USBMouse;
2468 else if (strHidType == "USBTablet")
2469 hw.pointingHidType = PointingHidType_USBTablet;
2470 else if (strHidType == "PS2Mouse")
2471 hw.pointingHidType = PointingHidType_PS2Mouse;
2472 else if (strHidType == "ComboMouse")
2473 hw.pointingHidType = PointingHidType_ComboMouse;
2474 else
2475 throw ConfigFileError(this,
2476 pelmHwChild,
2477 N_("Invalid value '%s' in HID/Pointing/@type"),
2478 strHidType.c_str());
2479 }
2480 }
2481 else if (pelmHwChild->nameEquals("Chipset"))
2482 {
2483 Utf8Str strChipsetType;
2484 if (pelmHwChild->getAttributeValue("type", strChipsetType))
2485 {
2486 if (strChipsetType == "PIIX3")
2487 hw.chipsetType = ChipsetType_PIIX3;
2488 else if (strChipsetType == "ICH9")
2489 hw.chipsetType = ChipsetType_ICH9;
2490 else
2491 throw ConfigFileError(this,
2492 pelmHwChild,
2493 N_("Invalid value '%s' in Chipset/@type"),
2494 strChipsetType.c_str());
2495 }
2496 }
2497 else if (pelmHwChild->nameEquals("HPET"))
2498 {
2499 pelmHwChild->getAttributeValue("enabled", hw.fHpetEnabled);
2500 }
2501 else if (pelmHwChild->nameEquals("Boot"))
2502 {
2503 hw.mapBootOrder.clear();
2504
2505 xml::NodesLoop nl2(*pelmHwChild, "Order");
2506 const xml::ElementNode *pelmOrder;
2507 while ((pelmOrder = nl2.forAllNodes()))
2508 {
2509 uint32_t ulPos;
2510 Utf8Str strDevice;
2511 if (!pelmOrder->getAttributeValue("position", ulPos))
2512 throw ConfigFileError(this, pelmOrder, N_("Required Boot/Order/@position attribute is missing"));
2513
2514 if ( ulPos < 1
2515 || ulPos > SchemaDefs::MaxBootPosition
2516 )
2517 throw ConfigFileError(this,
2518 pelmOrder,
2519 N_("Invalid value '%RU32' in Boot/Order/@position: must be greater than 0 and less than %RU32"),
2520 ulPos,
2521 SchemaDefs::MaxBootPosition + 1);
2522 // XML is 1-based but internal data is 0-based
2523 --ulPos;
2524
2525 if (hw.mapBootOrder.find(ulPos) != hw.mapBootOrder.end())
2526 throw ConfigFileError(this, pelmOrder, N_("Invalid value '%RU32' in Boot/Order/@position: value is not unique"), ulPos);
2527
2528 if (!pelmOrder->getAttributeValue("device", strDevice))
2529 throw ConfigFileError(this, pelmOrder, N_("Required Boot/Order/@device attribute is missing"));
2530
2531 DeviceType_T type;
2532 if (strDevice == "None")
2533 type = DeviceType_Null;
2534 else if (strDevice == "Floppy")
2535 type = DeviceType_Floppy;
2536 else if (strDevice == "DVD")
2537 type = DeviceType_DVD;
2538 else if (strDevice == "HardDisk")
2539 type = DeviceType_HardDisk;
2540 else if (strDevice == "Network")
2541 type = DeviceType_Network;
2542 else
2543 throw ConfigFileError(this, pelmOrder, N_("Invalid value '%s' in Boot/Order/@device attribute"), strDevice.c_str());
2544 hw.mapBootOrder[ulPos] = type;
2545 }
2546 }
2547 else if (pelmHwChild->nameEquals("Display"))
2548 {
2549 pelmHwChild->getAttributeValue("VRAMSize", hw.ulVRAMSizeMB);
2550 if (!pelmHwChild->getAttributeValue("monitorCount", hw.cMonitors))
2551 pelmHwChild->getAttributeValue("MonitorCount", hw.cMonitors); // pre-v1.5 variant
2552 if (!pelmHwChild->getAttributeValue("accelerate3D", hw.fAccelerate3D))
2553 pelmHwChild->getAttributeValue("Accelerate3D", hw.fAccelerate3D); // pre-v1.5 variant
2554 pelmHwChild->getAttributeValue("accelerate2DVideo", hw.fAccelerate2DVideo);
2555 }
2556 else if (pelmHwChild->nameEquals("RemoteDisplay"))
2557 {
2558 pelmHwChild->getAttributeValue("enabled", hw.vrdeSettings.fEnabled);
2559
2560 Utf8Str str;
2561 if (pelmHwChild->getAttributeValue("port", str))
2562 hw.vrdeSettings.mapProperties["TCP/Ports"] = str;
2563 if (pelmHwChild->getAttributeValue("netAddress", str))
2564 hw.vrdeSettings.mapProperties["TCP/Address"] = str;
2565
2566 Utf8Str strAuthType;
2567 if (pelmHwChild->getAttributeValue("authType", strAuthType))
2568 {
2569 // settings before 1.3 used lower case so make sure this is case-insensitive
2570 strAuthType.toUpper();
2571 if (strAuthType == "NULL")
2572 hw.vrdeSettings.authType = AuthType_Null;
2573 else if (strAuthType == "GUEST")
2574 hw.vrdeSettings.authType = AuthType_Guest;
2575 else if (strAuthType == "EXTERNAL")
2576 hw.vrdeSettings.authType = AuthType_External;
2577 else
2578 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in RemoteDisplay/@authType attribute"), strAuthType.c_str());
2579 }
2580
2581 pelmHwChild->getAttributeValue("authLibrary", hw.vrdeSettings.strAuthLibrary);
2582 pelmHwChild->getAttributeValue("authTimeout", hw.vrdeSettings.ulAuthTimeout);
2583 pelmHwChild->getAttributeValue("allowMultiConnection", hw.vrdeSettings.fAllowMultiConnection);
2584 pelmHwChild->getAttributeValue("reuseSingleConnection", hw.vrdeSettings.fReuseSingleConnection);
2585
2586 /* 3.2 and 4.0 betas, 4.0 has this information in VRDEProperties. */
2587 const xml::ElementNode *pelmVideoChannel;
2588 if ((pelmVideoChannel = pelmHwChild->findChildElement("VideoChannel")))
2589 {
2590 bool fVideoChannel = false;
2591 pelmVideoChannel->getAttributeValue("enabled", fVideoChannel);
2592 hw.vrdeSettings.mapProperties["VideoChannel/Enabled"] = fVideoChannel? "true": "false";
2593
2594 uint32_t ulVideoChannelQuality = 75;
2595 pelmVideoChannel->getAttributeValue("quality", ulVideoChannelQuality);
2596 ulVideoChannelQuality = RT_CLAMP(ulVideoChannelQuality, 10, 100);
2597 char *pszBuffer = NULL;
2598 if (RTStrAPrintf(&pszBuffer, "%d", ulVideoChannelQuality) >= 0)
2599 {
2600 hw.vrdeSettings.mapProperties["VideoChannel/Quality"] = pszBuffer;
2601 RTStrFree(pszBuffer);
2602 }
2603 else
2604 hw.vrdeSettings.mapProperties["VideoChannel/Quality"] = "75";
2605 }
2606 pelmHwChild->getAttributeValue("VRDEExtPack", hw.vrdeSettings.strVrdeExtPack);
2607
2608 const xml::ElementNode *pelmProperties = pelmHwChild->findChildElement("VRDEProperties");
2609 if (pelmProperties != NULL)
2610 {
2611 xml::NodesLoop nl(*pelmProperties);
2612 const xml::ElementNode *pelmProperty;
2613 while ((pelmProperty = nl.forAllNodes()))
2614 {
2615 if (pelmProperty->nameEquals("Property"))
2616 {
2617 /* <Property name="TCP/Ports" value="3000-3002"/> */
2618 Utf8Str strName, strValue;
2619 if ( ((pelmProperty->getAttributeValue("name", strName)))
2620 && ((pelmProperty->getAttributeValue("value", strValue)))
2621 )
2622 hw.vrdeSettings.mapProperties[strName] = strValue;
2623 else
2624 throw ConfigFileError(this, pelmProperty, N_("Required VRDE Property/@name or @value attribute is missing"));
2625 }
2626 }
2627 }
2628 }
2629 else if (pelmHwChild->nameEquals("BIOS"))
2630 {
2631 const xml::ElementNode *pelmBIOSChild;
2632 if ((pelmBIOSChild = pelmHwChild->findChildElement("ACPI")))
2633 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fACPIEnabled);
2634 if ((pelmBIOSChild = pelmHwChild->findChildElement("IOAPIC")))
2635 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fIOAPICEnabled);
2636 if ((pelmBIOSChild = pelmHwChild->findChildElement("Logo")))
2637 {
2638 pelmBIOSChild->getAttributeValue("fadeIn", hw.biosSettings.fLogoFadeIn);
2639 pelmBIOSChild->getAttributeValue("fadeOut", hw.biosSettings.fLogoFadeOut);
2640 pelmBIOSChild->getAttributeValue("displayTime", hw.biosSettings.ulLogoDisplayTime);
2641 pelmBIOSChild->getAttributeValue("imagePath", hw.biosSettings.strLogoImagePath);
2642 }
2643 if ((pelmBIOSChild = pelmHwChild->findChildElement("BootMenu")))
2644 {
2645 Utf8Str strBootMenuMode;
2646 if (pelmBIOSChild->getAttributeValue("mode", strBootMenuMode))
2647 {
2648 // settings before 1.3 used lower case so make sure this is case-insensitive
2649 strBootMenuMode.toUpper();
2650 if (strBootMenuMode == "DISABLED")
2651 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_Disabled;
2652 else if (strBootMenuMode == "MENUONLY")
2653 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_MenuOnly;
2654 else if (strBootMenuMode == "MESSAGEANDMENU")
2655 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_MessageAndMenu;
2656 else
2657 throw ConfigFileError(this, pelmBIOSChild, N_("Invalid value '%s' in BootMenu/@mode attribute"), strBootMenuMode.c_str());
2658 }
2659 }
2660 if ((pelmBIOSChild = pelmHwChild->findChildElement("PXEDebug")))
2661 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fPXEDebugEnabled);
2662 if ((pelmBIOSChild = pelmHwChild->findChildElement("TimeOffset")))
2663 pelmBIOSChild->getAttributeValue("value", hw.biosSettings.llTimeOffset);
2664
2665 // legacy BIOS/IDEController (pre 1.7)
2666 if ( (m->sv < SettingsVersion_v1_7)
2667 && ((pelmBIOSChild = pelmHwChild->findChildElement("IDEController")))
2668 )
2669 {
2670 StorageController sctl;
2671 sctl.strName = "IDE Controller";
2672 sctl.storageBus = StorageBus_IDE;
2673
2674 Utf8Str strType;
2675 if (pelmBIOSChild->getAttributeValue("type", strType))
2676 {
2677 if (strType == "PIIX3")
2678 sctl.controllerType = StorageControllerType_PIIX3;
2679 else if (strType == "PIIX4")
2680 sctl.controllerType = StorageControllerType_PIIX4;
2681 else if (strType == "ICH6")
2682 sctl.controllerType = StorageControllerType_ICH6;
2683 else
2684 throw ConfigFileError(this, pelmBIOSChild, N_("Invalid value '%s' for IDEController/@type attribute"), strType.c_str());
2685 }
2686 sctl.ulPortCount = 2;
2687 strg.llStorageControllers.push_back(sctl);
2688 }
2689 }
2690 else if (pelmHwChild->nameEquals("USBController"))
2691 {
2692 pelmHwChild->getAttributeValue("enabled", hw.usbController.fEnabled);
2693 pelmHwChild->getAttributeValue("enabledEhci", hw.usbController.fEnabledEHCI);
2694
2695 readUSBDeviceFilters(*pelmHwChild,
2696 hw.usbController.llDeviceFilters);
2697 }
2698 else if ( (m->sv < SettingsVersion_v1_7)
2699 && (pelmHwChild->nameEquals("SATAController"))
2700 )
2701 {
2702 bool f;
2703 if ( (pelmHwChild->getAttributeValue("enabled", f))
2704 && (f)
2705 )
2706 {
2707 StorageController sctl;
2708 sctl.strName = "SATA Controller";
2709 sctl.storageBus = StorageBus_SATA;
2710 sctl.controllerType = StorageControllerType_IntelAhci;
2711
2712 readStorageControllerAttributes(*pelmHwChild, sctl);
2713
2714 strg.llStorageControllers.push_back(sctl);
2715 }
2716 }
2717 else if (pelmHwChild->nameEquals("Network"))
2718 readNetworkAdapters(*pelmHwChild, hw.llNetworkAdapters);
2719 else if (pelmHwChild->nameEquals("RTC"))
2720 {
2721 Utf8Str strLocalOrUTC;
2722 machineUserData.fRTCUseUTC = pelmHwChild->getAttributeValue("localOrUTC", strLocalOrUTC)
2723 && strLocalOrUTC == "UTC";
2724 }
2725 else if ( (pelmHwChild->nameEquals("UART"))
2726 || (pelmHwChild->nameEquals("Uart")) // used before 1.3
2727 )
2728 readSerialPorts(*pelmHwChild, hw.llSerialPorts);
2729 else if ( (pelmHwChild->nameEquals("LPT"))
2730 || (pelmHwChild->nameEquals("Lpt")) // used before 1.3
2731 )
2732 readParallelPorts(*pelmHwChild, hw.llParallelPorts);
2733 else if (pelmHwChild->nameEquals("AudioAdapter"))
2734 readAudioAdapter(*pelmHwChild, hw.audioAdapter);
2735 else if (pelmHwChild->nameEquals("SharedFolders"))
2736 {
2737 xml::NodesLoop nl2(*pelmHwChild, "SharedFolder");
2738 const xml::ElementNode *pelmFolder;
2739 while ((pelmFolder = nl2.forAllNodes()))
2740 {
2741 SharedFolder sf;
2742 pelmFolder->getAttributeValue("name", sf.strName);
2743 pelmFolder->getAttributeValue("hostPath", sf.strHostPath);
2744 pelmFolder->getAttributeValue("writable", sf.fWritable);
2745 pelmFolder->getAttributeValue("autoMount", sf.fAutoMount);
2746 hw.llSharedFolders.push_back(sf);
2747 }
2748 }
2749 else if (pelmHwChild->nameEquals("Clipboard"))
2750 {
2751 Utf8Str strTemp;
2752 if (pelmHwChild->getAttributeValue("mode", strTemp))
2753 {
2754 if (strTemp == "Disabled")
2755 hw.clipboardMode = ClipboardMode_Disabled;
2756 else if (strTemp == "HostToGuest")
2757 hw.clipboardMode = ClipboardMode_HostToGuest;
2758 else if (strTemp == "GuestToHost")
2759 hw.clipboardMode = ClipboardMode_GuestToHost;
2760 else if (strTemp == "Bidirectional")
2761 hw.clipboardMode = ClipboardMode_Bidirectional;
2762 else
2763 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in Clipboard/@mode attribute"), strTemp.c_str());
2764 }
2765 }
2766 else if (pelmHwChild->nameEquals("Guest"))
2767 {
2768 if (!pelmHwChild->getAttributeValue("memoryBalloonSize", hw.ulMemoryBalloonSize))
2769 pelmHwChild->getAttributeValue("MemoryBalloonSize", hw.ulMemoryBalloonSize); // used before 1.3
2770 }
2771 else if (pelmHwChild->nameEquals("GuestProperties"))
2772 readGuestProperties(*pelmHwChild, hw);
2773 else if (pelmHwChild->nameEquals("IO"))
2774 {
2775 const xml::ElementNode *pelmBwGroups;
2776 const xml::ElementNode *pelmIoChild;
2777
2778 if ((pelmIoChild = pelmHwChild->findChildElement("IoCache")))
2779 {
2780 pelmIoChild->getAttributeValue("enabled", hw.ioSettings.fIoCacheEnabled);
2781 pelmIoChild->getAttributeValue("size", hw.ioSettings.ulIoCacheSize);
2782 }
2783
2784 if ((pelmBwGroups = pelmHwChild->findChildElement("BandwidthGroups")))
2785 {
2786 xml::NodesLoop nl2(*pelmBwGroups, "BandwidthGroup");
2787 const xml::ElementNode *pelmBandwidthGroup;
2788 while ((pelmBandwidthGroup = nl2.forAllNodes()))
2789 {
2790 BandwidthGroup gr;
2791 Utf8Str strTemp;
2792
2793 pelmBandwidthGroup->getAttributeValue("name", gr.strName);
2794
2795 if (pelmBandwidthGroup->getAttributeValue("type", strTemp))
2796 {
2797 if (strTemp == "Disk")
2798 gr.enmType = BandwidthGroupType_Disk;
2799 else if (strTemp == "Network")
2800 gr.enmType = BandwidthGroupType_Network;
2801 else
2802 throw ConfigFileError(this, pelmBandwidthGroup, N_("Invalid value '%s' in BandwidthGroup/@type attribute"), strTemp.c_str());
2803 }
2804 else
2805 throw ConfigFileError(this, pelmBandwidthGroup, N_("Missing BandwidthGroup/@type attribute"));
2806
2807 if (!pelmBandwidthGroup->getAttributeValue("maxBytesPerSec", gr.cMaxBytesPerSec))
2808 {
2809 pelmBandwidthGroup->getAttributeValue("maxMbPerSec", gr.cMaxBytesPerSec);
2810 gr.cMaxBytesPerSec *= _1M;
2811 }
2812 hw.ioSettings.llBandwidthGroups.push_back(gr);
2813 }
2814 }
2815 } else if (pelmHwChild->nameEquals("HostPci")) {
2816 const xml::ElementNode *pelmDevices;
2817
2818 if ((pelmDevices = pelmHwChild->findChildElement("Devices")))
2819 {
2820 xml::NodesLoop nl2(*pelmDevices, "Device");
2821 const xml::ElementNode *pelmDevice;
2822 while ((pelmDevice = nl2.forAllNodes()))
2823 {
2824 HostPciDeviceAttachment hpda;
2825
2826 if (!pelmDevice->getAttributeValue("host", hpda.uHostAddress))
2827 throw ConfigFileError(this, pelmDevice, N_("Missing Device/@host attribute"));
2828
2829 if (!pelmDevice->getAttributeValue("guest", hpda.uGuestAddress))
2830 throw ConfigFileError(this, pelmDevice, N_("Missing Device/@guest attribute"));
2831
2832 /* name is optional */
2833 pelmDevice->getAttributeValue("name", hpda.strDeviceName);
2834
2835 hw.pciAttachments.push_back(hpda);
2836 }
2837 }
2838 }
2839 else if (pelmHwChild->nameEquals("EmulatedUSB"))
2840 {
2841 const xml::ElementNode *pelmCardReader;
2842
2843 if ((pelmCardReader = pelmHwChild->findChildElement("CardReader")))
2844 {
2845 pelmCardReader->getAttributeValue("enabled", hw.fEmulatedUSBCardReader);
2846 }
2847 }
2848 }
2849
2850 if (hw.ulMemorySizeMB == (uint32_t)-1)
2851 throw ConfigFileError(this, &elmHardware, N_("Required Memory/@RAMSize element/attribute is missing"));
2852}
2853
2854/**
2855 * This gets called instead of readStorageControllers() for legacy pre-1.7 settings
2856 * files which have a <HardDiskAttachments> node and storage controller settings
2857 * hidden in the <Hardware> settings. We set the StorageControllers fields just the
2858 * same, just from different sources.
2859 * @param elmHardware <Hardware> XML node.
2860 * @param elmHardDiskAttachments <HardDiskAttachments> XML node.
2861 * @param strg
2862 */
2863void MachineConfigFile::readHardDiskAttachments_pre1_7(const xml::ElementNode &elmHardDiskAttachments,
2864 Storage &strg)
2865{
2866 StorageController *pIDEController = NULL;
2867 StorageController *pSATAController = NULL;
2868
2869 for (StorageControllersList::iterator it = strg.llStorageControllers.begin();
2870 it != strg.llStorageControllers.end();
2871 ++it)
2872 {
2873 StorageController &s = *it;
2874 if (s.storageBus == StorageBus_IDE)
2875 pIDEController = &s;
2876 else if (s.storageBus == StorageBus_SATA)
2877 pSATAController = &s;
2878 }
2879
2880 xml::NodesLoop nl1(elmHardDiskAttachments, "HardDiskAttachment");
2881 const xml::ElementNode *pelmAttachment;
2882 while ((pelmAttachment = nl1.forAllNodes()))
2883 {
2884 AttachedDevice att;
2885 Utf8Str strUUID, strBus;
2886
2887 if (!pelmAttachment->getAttributeValue("hardDisk", strUUID))
2888 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@hardDisk attribute is missing"));
2889 parseUUID(att.uuid, strUUID);
2890
2891 if (!pelmAttachment->getAttributeValue("bus", strBus))
2892 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@bus attribute is missing"));
2893 // pre-1.7 'channel' is now port
2894 if (!pelmAttachment->getAttributeValue("channel", att.lPort))
2895 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@channel attribute is missing"));
2896 // pre-1.7 'device' is still device
2897 if (!pelmAttachment->getAttributeValue("device", att.lDevice))
2898 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@device attribute is missing"));
2899
2900 att.deviceType = DeviceType_HardDisk;
2901
2902 if (strBus == "IDE")
2903 {
2904 if (!pIDEController)
2905 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus is 'IDE' but cannot find IDE controller"));
2906 pIDEController->llAttachedDevices.push_back(att);
2907 }
2908 else if (strBus == "SATA")
2909 {
2910 if (!pSATAController)
2911 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus is 'SATA' but cannot find SATA controller"));
2912 pSATAController->llAttachedDevices.push_back(att);
2913 }
2914 else
2915 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus attribute has illegal value '%s'"), strBus.c_str());
2916 }
2917}
2918
2919/**
2920 * Reads in a <StorageControllers> block and stores it in the given Storage structure.
2921 * Used both directly from readMachine and from readSnapshot, since snapshots
2922 * have their own storage controllers sections.
2923 *
2924 * This is only called for settings version 1.7 and above; see readHardDiskAttachments_pre1_7()
2925 * for earlier versions.
2926 *
2927 * @param elmStorageControllers
2928 */
2929void MachineConfigFile::readStorageControllers(const xml::ElementNode &elmStorageControllers,
2930 Storage &strg)
2931{
2932 xml::NodesLoop nlStorageControllers(elmStorageControllers, "StorageController");
2933 const xml::ElementNode *pelmController;
2934 while ((pelmController = nlStorageControllers.forAllNodes()))
2935 {
2936 StorageController sctl;
2937
2938 if (!pelmController->getAttributeValue("name", sctl.strName))
2939 throw ConfigFileError(this, pelmController, N_("Required StorageController/@name attribute is missing"));
2940 // canonicalize storage controller names for configs in the switchover
2941 // period.
2942 if (m->sv < SettingsVersion_v1_9)
2943 {
2944 if (sctl.strName == "IDE")
2945 sctl.strName = "IDE Controller";
2946 else if (sctl.strName == "SATA")
2947 sctl.strName = "SATA Controller";
2948 else if (sctl.strName == "SCSI")
2949 sctl.strName = "SCSI Controller";
2950 }
2951
2952 pelmController->getAttributeValue("Instance", sctl.ulInstance);
2953 // default from constructor is 0
2954
2955 pelmController->getAttributeValue("Bootable", sctl.fBootable);
2956 // default from constructor is true which is true
2957 // for settings below version 1.11 because they allowed only
2958 // one controller per type.
2959
2960 Utf8Str strType;
2961 if (!pelmController->getAttributeValue("type", strType))
2962 throw ConfigFileError(this, pelmController, N_("Required StorageController/@type attribute is missing"));
2963
2964 if (strType == "AHCI")
2965 {
2966 sctl.storageBus = StorageBus_SATA;
2967 sctl.controllerType = StorageControllerType_IntelAhci;
2968 }
2969 else if (strType == "LsiLogic")
2970 {
2971 sctl.storageBus = StorageBus_SCSI;
2972 sctl.controllerType = StorageControllerType_LsiLogic;
2973 }
2974 else if (strType == "BusLogic")
2975 {
2976 sctl.storageBus = StorageBus_SCSI;
2977 sctl.controllerType = StorageControllerType_BusLogic;
2978 }
2979 else if (strType == "PIIX3")
2980 {
2981 sctl.storageBus = StorageBus_IDE;
2982 sctl.controllerType = StorageControllerType_PIIX3;
2983 }
2984 else if (strType == "PIIX4")
2985 {
2986 sctl.storageBus = StorageBus_IDE;
2987 sctl.controllerType = StorageControllerType_PIIX4;
2988 }
2989 else if (strType == "ICH6")
2990 {
2991 sctl.storageBus = StorageBus_IDE;
2992 sctl.controllerType = StorageControllerType_ICH6;
2993 }
2994 else if ( (m->sv >= SettingsVersion_v1_9)
2995 && (strType == "I82078")
2996 )
2997 {
2998 sctl.storageBus = StorageBus_Floppy;
2999 sctl.controllerType = StorageControllerType_I82078;
3000 }
3001 else if (strType == "LsiLogicSas")
3002 {
3003 sctl.storageBus = StorageBus_SAS;
3004 sctl.controllerType = StorageControllerType_LsiLogicSas;
3005 }
3006 else
3007 throw ConfigFileError(this, pelmController, N_("Invalid value '%s' for StorageController/@type attribute"), strType.c_str());
3008
3009 readStorageControllerAttributes(*pelmController, sctl);
3010
3011 xml::NodesLoop nlAttached(*pelmController, "AttachedDevice");
3012 const xml::ElementNode *pelmAttached;
3013 while ((pelmAttached = nlAttached.forAllNodes()))
3014 {
3015 AttachedDevice att;
3016 Utf8Str strTemp;
3017 pelmAttached->getAttributeValue("type", strTemp);
3018
3019 att.fDiscard = false;
3020 att.fNonRotational = false;
3021
3022 if (strTemp == "HardDisk")
3023 {
3024 att.deviceType = DeviceType_HardDisk;
3025 pelmAttached->getAttributeValue("nonrotational", att.fNonRotational);
3026 pelmAttached->getAttributeValue("discard", att.fDiscard);
3027 }
3028 else if (m->sv >= SettingsVersion_v1_9)
3029 {
3030 // starting with 1.9 we list DVD and floppy drive info + attachments under <StorageControllers>
3031 if (strTemp == "DVD")
3032 {
3033 att.deviceType = DeviceType_DVD;
3034 pelmAttached->getAttributeValue("passthrough", att.fPassThrough);
3035 pelmAttached->getAttributeValue("tempeject", att.fTempEject);
3036 }
3037 else if (strTemp == "Floppy")
3038 att.deviceType = DeviceType_Floppy;
3039 }
3040
3041 if (att.deviceType != DeviceType_Null)
3042 {
3043 const xml::ElementNode *pelmImage;
3044 // all types can have images attached, but for HardDisk it's required
3045 if (!(pelmImage = pelmAttached->findChildElement("Image")))
3046 {
3047 if (att.deviceType == DeviceType_HardDisk)
3048 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/Image element is missing"));
3049 else
3050 {
3051 // DVDs and floppies can also have <HostDrive> instead of <Image>
3052 const xml::ElementNode *pelmHostDrive;
3053 if ((pelmHostDrive = pelmAttached->findChildElement("HostDrive")))
3054 if (!pelmHostDrive->getAttributeValue("src", att.strHostDriveSrc))
3055 throw ConfigFileError(this, pelmHostDrive, N_("Required AttachedDevice/HostDrive/@src attribute is missing"));
3056 }
3057 }
3058 else
3059 {
3060 if (!pelmImage->getAttributeValue("uuid", strTemp))
3061 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/Image/@uuid attribute is missing"));
3062 parseUUID(att.uuid, strTemp);
3063 }
3064
3065 if (!pelmAttached->getAttributeValue("port", att.lPort))
3066 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/@port attribute is missing"));
3067 if (!pelmAttached->getAttributeValue("device", att.lDevice))
3068 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/@device attribute is missing"));
3069
3070 pelmAttached->getAttributeValue("bandwidthGroup", att.strBwGroup);
3071 sctl.llAttachedDevices.push_back(att);
3072 }
3073 }
3074
3075 strg.llStorageControllers.push_back(sctl);
3076 }
3077}
3078
3079/**
3080 * This gets called for legacy pre-1.9 settings files after having parsed the
3081 * <Hardware> and <StorageControllers> sections to parse <Hardware> once more
3082 * for the <DVDDrive> and <FloppyDrive> sections.
3083 *
3084 * Before settings version 1.9, DVD and floppy drives were specified separately
3085 * under <Hardware>; we then need this extra loop to make sure the storage
3086 * controller structs are already set up so we can add stuff to them.
3087 *
3088 * @param elmHardware
3089 * @param strg
3090 */
3091void MachineConfigFile::readDVDAndFloppies_pre1_9(const xml::ElementNode &elmHardware,
3092 Storage &strg)
3093{
3094 xml::NodesLoop nl1(elmHardware);
3095 const xml::ElementNode *pelmHwChild;
3096 while ((pelmHwChild = nl1.forAllNodes()))
3097 {
3098 if (pelmHwChild->nameEquals("DVDDrive"))
3099 {
3100 // create a DVD "attached device" and attach it to the existing IDE controller
3101 AttachedDevice att;
3102 att.deviceType = DeviceType_DVD;
3103 // legacy DVD drive is always secondary master (port 1, device 0)
3104 att.lPort = 1;
3105 att.lDevice = 0;
3106 pelmHwChild->getAttributeValue("passthrough", att.fPassThrough);
3107 pelmHwChild->getAttributeValue("tempeject", att.fTempEject);
3108
3109 const xml::ElementNode *pDriveChild;
3110 Utf8Str strTmp;
3111 if ( ((pDriveChild = pelmHwChild->findChildElement("Image")))
3112 && (pDriveChild->getAttributeValue("uuid", strTmp))
3113 )
3114 parseUUID(att.uuid, strTmp);
3115 else if ((pDriveChild = pelmHwChild->findChildElement("HostDrive")))
3116 pDriveChild->getAttributeValue("src", att.strHostDriveSrc);
3117
3118 // find the IDE controller and attach the DVD drive
3119 bool fFound = false;
3120 for (StorageControllersList::iterator it = strg.llStorageControllers.begin();
3121 it != strg.llStorageControllers.end();
3122 ++it)
3123 {
3124 StorageController &sctl = *it;
3125 if (sctl.storageBus == StorageBus_IDE)
3126 {
3127 sctl.llAttachedDevices.push_back(att);
3128 fFound = true;
3129 break;
3130 }
3131 }
3132
3133 if (!fFound)
3134 throw ConfigFileError(this, pelmHwChild, N_("Internal error: found DVD drive but IDE controller does not exist"));
3135 // shouldn't happen because pre-1.9 settings files always had at least one IDE controller in the settings
3136 // which should have gotten parsed in <StorageControllers> before this got called
3137 }
3138 else if (pelmHwChild->nameEquals("FloppyDrive"))
3139 {
3140 bool fEnabled;
3141 if ( (pelmHwChild->getAttributeValue("enabled", fEnabled))
3142 && (fEnabled)
3143 )
3144 {
3145 // create a new floppy controller and attach a floppy "attached device"
3146 StorageController sctl;
3147 sctl.strName = "Floppy Controller";
3148 sctl.storageBus = StorageBus_Floppy;
3149 sctl.controllerType = StorageControllerType_I82078;
3150 sctl.ulPortCount = 1;
3151
3152 AttachedDevice att;
3153 att.deviceType = DeviceType_Floppy;
3154 att.lPort = 0;
3155 att.lDevice = 0;
3156
3157 const xml::ElementNode *pDriveChild;
3158 Utf8Str strTmp;
3159 if ( ((pDriveChild = pelmHwChild->findChildElement("Image")))
3160 && (pDriveChild->getAttributeValue("uuid", strTmp))
3161 )
3162 parseUUID(att.uuid, strTmp);
3163 else if ((pDriveChild = pelmHwChild->findChildElement("HostDrive")))
3164 pDriveChild->getAttributeValue("src", att.strHostDriveSrc);
3165
3166 // store attachment with controller
3167 sctl.llAttachedDevices.push_back(att);
3168 // store controller with storage
3169 strg.llStorageControllers.push_back(sctl);
3170 }
3171 }
3172 }
3173}
3174
3175/**
3176 * Called for reading the <Teleporter> element under <Machine>.
3177 */
3178void MachineConfigFile::readTeleporter(const xml::ElementNode *pElmTeleporter,
3179 MachineUserData *pUserData)
3180{
3181 pElmTeleporter->getAttributeValue("enabled", pUserData->fTeleporterEnabled);
3182 pElmTeleporter->getAttributeValue("port", pUserData->uTeleporterPort);
3183 pElmTeleporter->getAttributeValue("address", pUserData->strTeleporterAddress);
3184 pElmTeleporter->getAttributeValue("password", pUserData->strTeleporterPassword);
3185
3186 if ( pUserData->strTeleporterPassword.isNotEmpty()
3187 && !VBoxIsPasswordHashed(&pUserData->strTeleporterPassword))
3188 VBoxHashPassword(&pUserData->strTeleporterPassword);
3189}
3190
3191/**
3192 * Called for reading the <Debugging> element under <Machine> or <Snapshot>.
3193 */
3194void MachineConfigFile::readDebugging(const xml::ElementNode *pElmDebugging, Debugging *pDbg)
3195{
3196 if (!pElmDebugging || m->sv < SettingsVersion_v1_13)
3197 return;
3198
3199 const xml::ElementNode * const pelmTracing = pElmDebugging->findChildElement("Tracing");
3200 if (pelmTracing)
3201 {
3202 pelmTracing->getAttributeValue("enabled", pDbg->fTracingEnabled);
3203 pelmTracing->getAttributeValue("allowTracingToAccessVM", pDbg->fAllowTracingToAccessVM);
3204 pelmTracing->getAttributeValue("config", pDbg->strTracingConfig);
3205 }
3206}
3207
3208/**
3209 * Called for reading the <Autostart> element under <Machine> or <Snapshot>.
3210 */
3211void MachineConfigFile::readAutostart(const xml::ElementNode *pElmAutostart, Autostart *pAutostart)
3212{
3213 Utf8Str strAutostop;
3214
3215 if (!pElmAutostart || m->sv < SettingsVersion_v1_13)
3216 return;
3217
3218 pElmAutostart->getAttributeValue("enabled", pAutostart->fAutostartEnabled);
3219 pElmAutostart->getAttributeValue("delay", pAutostart->uAutostartDelay);
3220 pElmAutostart->getAttributeValue("autostop", strAutostop);
3221 if (strAutostop == "Disabled")
3222 pAutostart->enmAutostopType = AutostopType_Disabled;
3223 else if (strAutostop == "SaveState")
3224 pAutostart->enmAutostopType = AutostopType_SaveState;
3225 else if (strAutostop == "PowerOff")
3226 pAutostart->enmAutostopType = AutostopType_PowerOff;
3227 else if (strAutostop == "AcpiShutdown")
3228 pAutostart->enmAutostopType = AutostopType_AcpiShutdown;
3229 else
3230 throw ConfigFileError(this, pElmAutostart, N_("Invalid value '%s' for Autostart/@autostop attribute"), strAutostop.c_str());
3231}
3232
3233/**
3234 * Called for reading the <Groups> element under <Machine>.
3235 */
3236void MachineConfigFile::readGroups(const xml::ElementNode *pElmGroups, StringsList *pllGroups)
3237{
3238 pllGroups->clear();
3239 if (!pElmGroups || m->sv < SettingsVersion_v1_13)
3240 {
3241 pllGroups->push_back("/");
3242 return;
3243 }
3244
3245 xml::NodesLoop nlGroups(*pElmGroups);
3246 const xml::ElementNode *pelmGroup;
3247 while ((pelmGroup = nlGroups.forAllNodes()))
3248 {
3249 if (pelmGroup->nameEquals("Group"))
3250 {
3251 Utf8Str strGroup;
3252 if (!pelmGroup->getAttributeValue("name", strGroup))
3253 throw ConfigFileError(this, pelmGroup, N_("Required Group/@name attribute is missing"));
3254 pllGroups->push_back(strGroup);
3255 }
3256 }
3257}
3258
3259/**
3260 * Called initially for the <Snapshot> element under <Machine>, if present,
3261 * to store the snapshot's data into the given Snapshot structure (which is
3262 * then the one in the Machine struct). This might then recurse if
3263 * a <Snapshots> (plural) element is found in the snapshot, which should
3264 * contain a list of child snapshots; such lists are maintained in the
3265 * Snapshot structure.
3266 *
3267 * @param elmSnapshot
3268 * @param snap
3269 */
3270void MachineConfigFile::readSnapshot(const xml::ElementNode &elmSnapshot,
3271 Snapshot &snap)
3272{
3273 Utf8Str strTemp;
3274
3275 if (!elmSnapshot.getAttributeValue("uuid", strTemp))
3276 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@uuid attribute is missing"));
3277 parseUUID(snap.uuid, strTemp);
3278
3279 if (!elmSnapshot.getAttributeValue("name", snap.strName))
3280 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@name attribute is missing"));
3281
3282 // earlier 3.1 trunk builds had a bug and added Description as an attribute, read it silently and write it back as an element
3283 elmSnapshot.getAttributeValue("Description", snap.strDescription);
3284
3285 if (!elmSnapshot.getAttributeValue("timeStamp", strTemp))
3286 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@timeStamp attribute is missing"));
3287 parseTimestamp(snap.timestamp, strTemp);
3288
3289 elmSnapshot.getAttributeValuePath("stateFile", snap.strStateFile); // online snapshots only
3290
3291 // parse Hardware before the other elements because other things depend on it
3292 const xml::ElementNode *pelmHardware;
3293 if (!(pelmHardware = elmSnapshot.findChildElement("Hardware")))
3294 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@Hardware element is missing"));
3295 readHardware(*pelmHardware, snap.hardware, snap.storage);
3296
3297 xml::NodesLoop nlSnapshotChildren(elmSnapshot);
3298 const xml::ElementNode *pelmSnapshotChild;
3299 while ((pelmSnapshotChild = nlSnapshotChildren.forAllNodes()))
3300 {
3301 if (pelmSnapshotChild->nameEquals("Description"))
3302 snap.strDescription = pelmSnapshotChild->getValue();
3303 else if ( (m->sv < SettingsVersion_v1_7)
3304 && (pelmSnapshotChild->nameEquals("HardDiskAttachments"))
3305 )
3306 readHardDiskAttachments_pre1_7(*pelmSnapshotChild, snap.storage);
3307 else if ( (m->sv >= SettingsVersion_v1_7)
3308 && (pelmSnapshotChild->nameEquals("StorageControllers"))
3309 )
3310 readStorageControllers(*pelmSnapshotChild, snap.storage);
3311 else if (pelmSnapshotChild->nameEquals("Snapshots"))
3312 {
3313 xml::NodesLoop nlChildSnapshots(*pelmSnapshotChild);
3314 const xml::ElementNode *pelmChildSnapshot;
3315 while ((pelmChildSnapshot = nlChildSnapshots.forAllNodes()))
3316 {
3317 if (pelmChildSnapshot->nameEquals("Snapshot"))
3318 {
3319 Snapshot child;
3320 readSnapshot(*pelmChildSnapshot, child);
3321 snap.llChildSnapshots.push_back(child);
3322 }
3323 }
3324 }
3325 }
3326
3327 if (m->sv < SettingsVersion_v1_9)
3328 // go through Hardware once more to repair the settings controller structures
3329 // with data from old DVDDrive and FloppyDrive elements
3330 readDVDAndFloppies_pre1_9(*pelmHardware, snap.storage);
3331
3332 readDebugging(elmSnapshot.findChildElement("Debugging"), &snap.debugging);
3333 readAutostart(elmSnapshot.findChildElement("Autostart"), &snap.autostart);
3334 // note: Groups exist only for Machine, not for Snapshot
3335}
3336
3337const struct {
3338 const char *pcszOld;
3339 const char *pcszNew;
3340} aConvertOSTypes[] =
3341{
3342 { "unknown", "Other" },
3343 { "dos", "DOS" },
3344 { "win31", "Windows31" },
3345 { "win95", "Windows95" },
3346 { "win98", "Windows98" },
3347 { "winme", "WindowsMe" },
3348 { "winnt4", "WindowsNT4" },
3349 { "win2k", "Windows2000" },
3350 { "winxp", "WindowsXP" },
3351 { "win2k3", "Windows2003" },
3352 { "winvista", "WindowsVista" },
3353 { "win2k8", "Windows2008" },
3354 { "os2warp3", "OS2Warp3" },
3355 { "os2warp4", "OS2Warp4" },
3356 { "os2warp45", "OS2Warp45" },
3357 { "ecs", "OS2eCS" },
3358 { "linux22", "Linux22" },
3359 { "linux24", "Linux24" },
3360 { "linux26", "Linux26" },
3361 { "archlinux", "ArchLinux" },
3362 { "debian", "Debian" },
3363 { "opensuse", "OpenSUSE" },
3364 { "fedoracore", "Fedora" },
3365 { "gentoo", "Gentoo" },
3366 { "mandriva", "Mandriva" },
3367 { "redhat", "RedHat" },
3368 { "ubuntu", "Ubuntu" },
3369 { "xandros", "Xandros" },
3370 { "freebsd", "FreeBSD" },
3371 { "openbsd", "OpenBSD" },
3372 { "netbsd", "NetBSD" },
3373 { "netware", "Netware" },
3374 { "solaris", "Solaris" },
3375 { "opensolaris", "OpenSolaris" },
3376 { "l4", "L4" }
3377};
3378
3379void MachineConfigFile::convertOldOSType_pre1_5(Utf8Str &str)
3380{
3381 for (unsigned u = 0;
3382 u < RT_ELEMENTS(aConvertOSTypes);
3383 ++u)
3384 {
3385 if (str == aConvertOSTypes[u].pcszOld)
3386 {
3387 str = aConvertOSTypes[u].pcszNew;
3388 break;
3389 }
3390 }
3391}
3392
3393/**
3394 * Called from the constructor to actually read in the <Machine> element
3395 * of a machine config file.
3396 * @param elmMachine
3397 */
3398void MachineConfigFile::readMachine(const xml::ElementNode &elmMachine)
3399{
3400 Utf8Str strUUID;
3401 if ( (elmMachine.getAttributeValue("uuid", strUUID))
3402 && (elmMachine.getAttributeValue("name", machineUserData.strName))
3403 )
3404 {
3405 parseUUID(uuid, strUUID);
3406
3407 elmMachine.getAttributeValue("nameSync", machineUserData.fNameSync);
3408
3409 Utf8Str str;
3410 elmMachine.getAttributeValue("Description", machineUserData.strDescription);
3411
3412 elmMachine.getAttributeValue("OSType", machineUserData.strOsType);
3413 if (m->sv < SettingsVersion_v1_5)
3414 convertOldOSType_pre1_5(machineUserData.strOsType);
3415
3416 elmMachine.getAttributeValuePath("stateFile", strStateFile);
3417
3418 if (elmMachine.getAttributeValue("currentSnapshot", str))
3419 parseUUID(uuidCurrentSnapshot, str);
3420
3421 elmMachine.getAttributeValuePath("snapshotFolder", machineUserData.strSnapshotFolder);
3422
3423 if (!elmMachine.getAttributeValue("currentStateModified", fCurrentStateModified))
3424 fCurrentStateModified = true;
3425 if (elmMachine.getAttributeValue("lastStateChange", str))
3426 parseTimestamp(timeLastStateChange, str);
3427 // constructor has called RTTimeNow(&timeLastStateChange) before
3428 if (elmMachine.getAttributeValue("aborted", fAborted))
3429 fAborted = true;
3430
3431 // parse Hardware before the other elements because other things depend on it
3432 const xml::ElementNode *pelmHardware;
3433 if (!(pelmHardware = elmMachine.findChildElement("Hardware")))
3434 throw ConfigFileError(this, &elmMachine, N_("Required Machine/Hardware element is missing"));
3435 readHardware(*pelmHardware, hardwareMachine, storageMachine);
3436
3437 xml::NodesLoop nlRootChildren(elmMachine);
3438 const xml::ElementNode *pelmMachineChild;
3439 while ((pelmMachineChild = nlRootChildren.forAllNodes()))
3440 {
3441 if (pelmMachineChild->nameEquals("ExtraData"))
3442 readExtraData(*pelmMachineChild,
3443 mapExtraDataItems);
3444 else if ( (m->sv < SettingsVersion_v1_7)
3445 && (pelmMachineChild->nameEquals("HardDiskAttachments"))
3446 )
3447 readHardDiskAttachments_pre1_7(*pelmMachineChild, storageMachine);
3448 else if ( (m->sv >= SettingsVersion_v1_7)
3449 && (pelmMachineChild->nameEquals("StorageControllers"))
3450 )
3451 readStorageControllers(*pelmMachineChild, storageMachine);
3452 else if (pelmMachineChild->nameEquals("Snapshot"))
3453 {
3454 Snapshot snap;
3455 // this will recurse into child snapshots, if necessary
3456 readSnapshot(*pelmMachineChild, snap);
3457 llFirstSnapshot.push_back(snap);
3458 }
3459 else if (pelmMachineChild->nameEquals("Description"))
3460 machineUserData.strDescription = pelmMachineChild->getValue();
3461 else if (pelmMachineChild->nameEquals("Teleporter"))
3462 readTeleporter(pelmMachineChild, &machineUserData);
3463 else if (pelmMachineChild->nameEquals("FaultTolerance"))
3464 {
3465 Utf8Str strFaultToleranceSate;
3466 if (pelmMachineChild->getAttributeValue("state", strFaultToleranceSate))
3467 {
3468 if (strFaultToleranceSate == "master")
3469 machineUserData.enmFaultToleranceState = FaultToleranceState_Master;
3470 else
3471 if (strFaultToleranceSate == "standby")
3472 machineUserData.enmFaultToleranceState = FaultToleranceState_Standby;
3473 else
3474 machineUserData.enmFaultToleranceState = FaultToleranceState_Inactive;
3475 }
3476 pelmMachineChild->getAttributeValue("port", machineUserData.uFaultTolerancePort);
3477 pelmMachineChild->getAttributeValue("address", machineUserData.strFaultToleranceAddress);
3478 pelmMachineChild->getAttributeValue("interval", machineUserData.uFaultToleranceInterval);
3479 pelmMachineChild->getAttributeValue("password", machineUserData.strFaultTolerancePassword);
3480 }
3481 else if (pelmMachineChild->nameEquals("MediaRegistry"))
3482 readMediaRegistry(*pelmMachineChild, mediaRegistry);
3483 else if (pelmMachineChild->nameEquals("Debugging"))
3484 readDebugging(pelmMachineChild, &debugging);
3485 else if (pelmMachineChild->nameEquals("Autostart"))
3486 readAutostart(pelmMachineChild, &autostart);
3487 else if (pelmMachineChild->nameEquals("Groups"))
3488 readGroups(pelmMachineChild, &machineUserData.llGroups);
3489 }
3490
3491 if (m->sv < SettingsVersion_v1_9)
3492 // go through Hardware once more to repair the settings controller structures
3493 // with data from old DVDDrive and FloppyDrive elements
3494 readDVDAndFloppies_pre1_9(*pelmHardware, storageMachine);
3495 }
3496 else
3497 throw ConfigFileError(this, &elmMachine, N_("Required Machine/@uuid or @name attributes is missing"));
3498}
3499
3500/**
3501 * Creates a <Hardware> node under elmParent and then writes out the XML
3502 * keys under that. Called for both the <Machine> node and for snapshots.
3503 * @param elmParent
3504 * @param st
3505 */
3506void MachineConfigFile::buildHardwareXML(xml::ElementNode &elmParent,
3507 const Hardware &hw,
3508 const Storage &strg)
3509{
3510 xml::ElementNode *pelmHardware = elmParent.createChild("Hardware");
3511
3512 if (m->sv >= SettingsVersion_v1_4)
3513 pelmHardware->setAttribute("version", hw.strVersion);
3514 if ( (m->sv >= SettingsVersion_v1_9)
3515 && (!hw.uuid.isEmpty())
3516 )
3517 pelmHardware->setAttribute("uuid", hw.uuid.toStringCurly());
3518
3519 xml::ElementNode *pelmCPU = pelmHardware->createChild("CPU");
3520
3521 xml::ElementNode *pelmHwVirtEx = pelmCPU->createChild("HardwareVirtEx");
3522 pelmHwVirtEx->setAttribute("enabled", hw.fHardwareVirt);
3523 if (m->sv >= SettingsVersion_v1_9)
3524 pelmHwVirtEx->setAttribute("exclusive", hw.fHardwareVirtExclusive);
3525
3526 pelmCPU->createChild("HardwareVirtExNestedPaging")->setAttribute("enabled", hw.fNestedPaging);
3527 pelmCPU->createChild("HardwareVirtExVPID")->setAttribute("enabled", hw.fVPID);
3528 pelmCPU->createChild("PAE")->setAttribute("enabled", hw.fPAE);
3529
3530 if (hw.fSyntheticCpu)
3531 pelmCPU->createChild("SyntheticCpu")->setAttribute("enabled", hw.fSyntheticCpu);
3532 pelmCPU->setAttribute("count", hw.cCPUs);
3533 if (hw.ulCpuExecutionCap != 100)
3534 pelmCPU->setAttribute("executionCap", hw.ulCpuExecutionCap);
3535
3536 /* Always save this setting as we have changed the default in 4.0 (on for large memory 64-bit systems). */
3537 pelmCPU->createChild("HardwareVirtExLargePages")->setAttribute("enabled", hw.fLargePages);
3538
3539 if (m->sv >= SettingsVersion_v1_9)
3540 pelmCPU->createChild("HardwareVirtForce")->setAttribute("enabled", hw.fHardwareVirtForce);
3541
3542 if (m->sv >= SettingsVersion_v1_10)
3543 {
3544 pelmCPU->setAttribute("hotplug", hw.fCpuHotPlug);
3545
3546 xml::ElementNode *pelmCpuTree = NULL;
3547 for (CpuList::const_iterator it = hw.llCpus.begin();
3548 it != hw.llCpus.end();
3549 ++it)
3550 {
3551 const Cpu &cpu = *it;
3552
3553 if (pelmCpuTree == NULL)
3554 pelmCpuTree = pelmCPU->createChild("CpuTree");
3555
3556 xml::ElementNode *pelmCpu = pelmCpuTree->createChild("Cpu");
3557 pelmCpu->setAttribute("id", cpu.ulId);
3558 }
3559 }
3560
3561 xml::ElementNode *pelmCpuIdTree = NULL;
3562 for (CpuIdLeafsList::const_iterator it = hw.llCpuIdLeafs.begin();
3563 it != hw.llCpuIdLeafs.end();
3564 ++it)
3565 {
3566 const CpuIdLeaf &leaf = *it;
3567
3568 if (pelmCpuIdTree == NULL)
3569 pelmCpuIdTree = pelmCPU->createChild("CpuIdTree");
3570
3571 xml::ElementNode *pelmCpuIdLeaf = pelmCpuIdTree->createChild("CpuIdLeaf");
3572 pelmCpuIdLeaf->setAttribute("id", leaf.ulId);
3573 pelmCpuIdLeaf->setAttribute("eax", leaf.ulEax);
3574 pelmCpuIdLeaf->setAttribute("ebx", leaf.ulEbx);
3575 pelmCpuIdLeaf->setAttribute("ecx", leaf.ulEcx);
3576 pelmCpuIdLeaf->setAttribute("edx", leaf.ulEdx);
3577 }
3578
3579 xml::ElementNode *pelmMemory = pelmHardware->createChild("Memory");
3580 pelmMemory->setAttribute("RAMSize", hw.ulMemorySizeMB);
3581 if (m->sv >= SettingsVersion_v1_10)
3582 {
3583 pelmMemory->setAttribute("PageFusion", hw.fPageFusionEnabled);
3584 }
3585
3586 if ( (m->sv >= SettingsVersion_v1_9)
3587 && (hw.firmwareType >= FirmwareType_EFI)
3588 )
3589 {
3590 xml::ElementNode *pelmFirmware = pelmHardware->createChild("Firmware");
3591 const char *pcszFirmware;
3592
3593 switch (hw.firmwareType)
3594 {
3595 case FirmwareType_EFI: pcszFirmware = "EFI"; break;
3596 case FirmwareType_EFI32: pcszFirmware = "EFI32"; break;
3597 case FirmwareType_EFI64: pcszFirmware = "EFI64"; break;
3598 case FirmwareType_EFIDUAL: pcszFirmware = "EFIDUAL"; break;
3599 default: pcszFirmware = "None"; break;
3600 }
3601 pelmFirmware->setAttribute("type", pcszFirmware);
3602 }
3603
3604 if ( (m->sv >= SettingsVersion_v1_10)
3605 )
3606 {
3607 xml::ElementNode *pelmHid = pelmHardware->createChild("HID");
3608 const char *pcszHid;
3609
3610 switch (hw.pointingHidType)
3611 {
3612 case PointingHidType_USBMouse: pcszHid = "USBMouse"; break;
3613 case PointingHidType_USBTablet: pcszHid = "USBTablet"; break;
3614 case PointingHidType_PS2Mouse: pcszHid = "PS2Mouse"; break;
3615 case PointingHidType_ComboMouse: pcszHid = "ComboMouse"; break;
3616 case PointingHidType_None: pcszHid = "None"; break;
3617 default: Assert(false); pcszHid = "PS2Mouse"; break;
3618 }
3619 pelmHid->setAttribute("Pointing", pcszHid);
3620
3621 switch (hw.keyboardHidType)
3622 {
3623 case KeyboardHidType_USBKeyboard: pcszHid = "USBKeyboard"; break;
3624 case KeyboardHidType_PS2Keyboard: pcszHid = "PS2Keyboard"; break;
3625 case KeyboardHidType_ComboKeyboard: pcszHid = "ComboKeyboard"; break;
3626 case KeyboardHidType_None: pcszHid = "None"; break;
3627 default: Assert(false); pcszHid = "PS2Keyboard"; break;
3628 }
3629 pelmHid->setAttribute("Keyboard", pcszHid);
3630 }
3631
3632 if ( (m->sv >= SettingsVersion_v1_10)
3633 )
3634 {
3635 xml::ElementNode *pelmHpet = pelmHardware->createChild("HPET");
3636 pelmHpet->setAttribute("enabled", hw.fHpetEnabled);
3637 }
3638
3639 if ( (m->sv >= SettingsVersion_v1_11)
3640 )
3641 {
3642 xml::ElementNode *pelmChipset = pelmHardware->createChild("Chipset");
3643 const char *pcszChipset;
3644
3645 switch (hw.chipsetType)
3646 {
3647 case ChipsetType_PIIX3: pcszChipset = "PIIX3"; break;
3648 case ChipsetType_ICH9: pcszChipset = "ICH9"; break;
3649 default: Assert(false); pcszChipset = "PIIX3"; break;
3650 }
3651 pelmChipset->setAttribute("type", pcszChipset);
3652 }
3653
3654 xml::ElementNode *pelmBoot = pelmHardware->createChild("Boot");
3655 for (BootOrderMap::const_iterator it = hw.mapBootOrder.begin();
3656 it != hw.mapBootOrder.end();
3657 ++it)
3658 {
3659 uint32_t i = it->first;
3660 DeviceType_T type = it->second;
3661 const char *pcszDevice;
3662
3663 switch (type)
3664 {
3665 case DeviceType_Floppy: pcszDevice = "Floppy"; break;
3666 case DeviceType_DVD: pcszDevice = "DVD"; break;
3667 case DeviceType_HardDisk: pcszDevice = "HardDisk"; break;
3668 case DeviceType_Network: pcszDevice = "Network"; break;
3669 default: /*case DeviceType_Null:*/ pcszDevice = "None"; break;
3670 }
3671
3672 xml::ElementNode *pelmOrder = pelmBoot->createChild("Order");
3673 pelmOrder->setAttribute("position",
3674 i + 1); // XML is 1-based but internal data is 0-based
3675 pelmOrder->setAttribute("device", pcszDevice);
3676 }
3677
3678 xml::ElementNode *pelmDisplay = pelmHardware->createChild("Display");
3679 pelmDisplay->setAttribute("VRAMSize", hw.ulVRAMSizeMB);
3680 pelmDisplay->setAttribute("monitorCount", hw.cMonitors);
3681 pelmDisplay->setAttribute("accelerate3D", hw.fAccelerate3D);
3682
3683 if (m->sv >= SettingsVersion_v1_8)
3684 pelmDisplay->setAttribute("accelerate2DVideo", hw.fAccelerate2DVideo);
3685
3686 xml::ElementNode *pelmVRDE = pelmHardware->createChild("RemoteDisplay");
3687 pelmVRDE->setAttribute("enabled", hw.vrdeSettings.fEnabled);
3688 if (m->sv < SettingsVersion_v1_11)
3689 {
3690 /* In VBox 4.0 these attributes are replaced with "Properties". */
3691 Utf8Str strPort;
3692 StringsMap::const_iterator it = hw.vrdeSettings.mapProperties.find("TCP/Ports");
3693 if (it != hw.vrdeSettings.mapProperties.end())
3694 strPort = it->second;
3695 if (!strPort.length())
3696 strPort = "3389";
3697 pelmVRDE->setAttribute("port", strPort);
3698
3699 Utf8Str strAddress;
3700 it = hw.vrdeSettings.mapProperties.find("TCP/Address");
3701 if (it != hw.vrdeSettings.mapProperties.end())
3702 strAddress = it->second;
3703 if (strAddress.length())
3704 pelmVRDE->setAttribute("netAddress", strAddress);
3705 }
3706 const char *pcszAuthType;
3707 switch (hw.vrdeSettings.authType)
3708 {
3709 case AuthType_Guest: pcszAuthType = "Guest"; break;
3710 case AuthType_External: pcszAuthType = "External"; break;
3711 default: /*case AuthType_Null:*/ pcszAuthType = "Null"; break;
3712 }
3713 pelmVRDE->setAttribute("authType", pcszAuthType);
3714
3715 if (hw.vrdeSettings.ulAuthTimeout != 0)
3716 pelmVRDE->setAttribute("authTimeout", hw.vrdeSettings.ulAuthTimeout);
3717 if (hw.vrdeSettings.fAllowMultiConnection)
3718 pelmVRDE->setAttribute("allowMultiConnection", hw.vrdeSettings.fAllowMultiConnection);
3719 if (hw.vrdeSettings.fReuseSingleConnection)
3720 pelmVRDE->setAttribute("reuseSingleConnection", hw.vrdeSettings.fReuseSingleConnection);
3721
3722 if (m->sv == SettingsVersion_v1_10)
3723 {
3724 xml::ElementNode *pelmVideoChannel = pelmVRDE->createChild("VideoChannel");
3725
3726 /* In 4.0 videochannel settings were replaced with properties, so look at properties. */
3727 Utf8Str str;
3728 StringsMap::const_iterator it = hw.vrdeSettings.mapProperties.find("VideoChannel/Enabled");
3729 if (it != hw.vrdeSettings.mapProperties.end())
3730 str = it->second;
3731 bool fVideoChannel = RTStrICmp(str.c_str(), "true") == 0
3732 || RTStrCmp(str.c_str(), "1") == 0;
3733 pelmVideoChannel->setAttribute("enabled", fVideoChannel);
3734
3735 it = hw.vrdeSettings.mapProperties.find("VideoChannel/Quality");
3736 if (it != hw.vrdeSettings.mapProperties.end())
3737 str = it->second;
3738 uint32_t ulVideoChannelQuality = RTStrToUInt32(str.c_str()); /* This returns 0 on invalid string which is ok. */
3739 if (ulVideoChannelQuality == 0)
3740 ulVideoChannelQuality = 75;
3741 else
3742 ulVideoChannelQuality = RT_CLAMP(ulVideoChannelQuality, 10, 100);
3743 pelmVideoChannel->setAttribute("quality", ulVideoChannelQuality);
3744 }
3745 if (m->sv >= SettingsVersion_v1_11)
3746 {
3747 if (hw.vrdeSettings.strAuthLibrary.length())
3748 pelmVRDE->setAttribute("authLibrary", hw.vrdeSettings.strAuthLibrary);
3749 if (hw.vrdeSettings.strVrdeExtPack.isNotEmpty())
3750 pelmVRDE->setAttribute("VRDEExtPack", hw.vrdeSettings.strVrdeExtPack);
3751 if (hw.vrdeSettings.mapProperties.size() > 0)
3752 {
3753 xml::ElementNode *pelmProperties = pelmVRDE->createChild("VRDEProperties");
3754 for (StringsMap::const_iterator it = hw.vrdeSettings.mapProperties.begin();
3755 it != hw.vrdeSettings.mapProperties.end();
3756 ++it)
3757 {
3758 const Utf8Str &strName = it->first;
3759 const Utf8Str &strValue = it->second;
3760 xml::ElementNode *pelm = pelmProperties->createChild("Property");
3761 pelm->setAttribute("name", strName);
3762 pelm->setAttribute("value", strValue);
3763 }
3764 }
3765 }
3766
3767 xml::ElementNode *pelmBIOS = pelmHardware->createChild("BIOS");
3768 pelmBIOS->createChild("ACPI")->setAttribute("enabled", hw.biosSettings.fACPIEnabled);
3769 pelmBIOS->createChild("IOAPIC")->setAttribute("enabled", hw.biosSettings.fIOAPICEnabled);
3770
3771 xml::ElementNode *pelmLogo = pelmBIOS->createChild("Logo");
3772 pelmLogo->setAttribute("fadeIn", hw.biosSettings.fLogoFadeIn);
3773 pelmLogo->setAttribute("fadeOut", hw.biosSettings.fLogoFadeOut);
3774 pelmLogo->setAttribute("displayTime", hw.biosSettings.ulLogoDisplayTime);
3775 if (hw.biosSettings.strLogoImagePath.length())
3776 pelmLogo->setAttribute("imagePath", hw.biosSettings.strLogoImagePath);
3777
3778 const char *pcszBootMenu;
3779 switch (hw.biosSettings.biosBootMenuMode)
3780 {
3781 case BIOSBootMenuMode_Disabled: pcszBootMenu = "Disabled"; break;
3782 case BIOSBootMenuMode_MenuOnly: pcszBootMenu = "MenuOnly"; break;
3783 default: /*BIOSBootMenuMode_MessageAndMenu*/ pcszBootMenu = "MessageAndMenu"; break;
3784 }
3785 pelmBIOS->createChild("BootMenu")->setAttribute("mode", pcszBootMenu);
3786 pelmBIOS->createChild("TimeOffset")->setAttribute("value", hw.biosSettings.llTimeOffset);
3787 pelmBIOS->createChild("PXEDebug")->setAttribute("enabled", hw.biosSettings.fPXEDebugEnabled);
3788
3789 if (m->sv < SettingsVersion_v1_9)
3790 {
3791 // settings formats before 1.9 had separate DVDDrive and FloppyDrive items under Hardware;
3792 // run thru the storage controllers to see if we have a DVD or floppy drives
3793 size_t cDVDs = 0;
3794 size_t cFloppies = 0;
3795
3796 xml::ElementNode *pelmDVD = pelmHardware->createChild("DVDDrive");
3797 xml::ElementNode *pelmFloppy = pelmHardware->createChild("FloppyDrive");
3798
3799 for (StorageControllersList::const_iterator it = strg.llStorageControllers.begin();
3800 it != strg.llStorageControllers.end();
3801 ++it)
3802 {
3803 const StorageController &sctl = *it;
3804 // in old settings format, the DVD drive could only have been under the IDE controller
3805 if (sctl.storageBus == StorageBus_IDE)
3806 {
3807 for (AttachedDevicesList::const_iterator it2 = sctl.llAttachedDevices.begin();
3808 it2 != sctl.llAttachedDevices.end();
3809 ++it2)
3810 {
3811 const AttachedDevice &att = *it2;
3812 if (att.deviceType == DeviceType_DVD)
3813 {
3814 if (cDVDs > 0)
3815 throw ConfigFileError(this, NULL, N_("Internal error: cannot save more than one DVD drive with old settings format"));
3816
3817 ++cDVDs;
3818
3819 pelmDVD->setAttribute("passthrough", att.fPassThrough);
3820 if (att.fTempEject)
3821 pelmDVD->setAttribute("tempeject", att.fTempEject);
3822 if (!att.uuid.isEmpty())
3823 pelmDVD->createChild("Image")->setAttribute("uuid", att.uuid.toStringCurly());
3824 else if (att.strHostDriveSrc.length())
3825 pelmDVD->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
3826 }
3827 }
3828 }
3829 else if (sctl.storageBus == StorageBus_Floppy)
3830 {
3831 size_t cFloppiesHere = sctl.llAttachedDevices.size();
3832 if (cFloppiesHere > 1)
3833 throw ConfigFileError(this, NULL, N_("Internal error: floppy controller cannot have more than one device attachment"));
3834 if (cFloppiesHere)
3835 {
3836 const AttachedDevice &att = sctl.llAttachedDevices.front();
3837 pelmFloppy->setAttribute("enabled", true);
3838 if (!att.uuid.isEmpty())
3839 pelmFloppy->createChild("Image")->setAttribute("uuid", att.uuid.toStringCurly());
3840 else if (att.strHostDriveSrc.length())
3841 pelmFloppy->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
3842 }
3843
3844 cFloppies += cFloppiesHere;
3845 }
3846 }
3847
3848 if (cFloppies == 0)
3849 pelmFloppy->setAttribute("enabled", false);
3850 else if (cFloppies > 1)
3851 throw ConfigFileError(this, NULL, N_("Internal error: cannot save more than one floppy drive with old settings format"));
3852 }
3853
3854 xml::ElementNode *pelmUSB = pelmHardware->createChild("USBController");
3855 pelmUSB->setAttribute("enabled", hw.usbController.fEnabled);
3856 pelmUSB->setAttribute("enabledEhci", hw.usbController.fEnabledEHCI);
3857
3858 buildUSBDeviceFilters(*pelmUSB,
3859 hw.usbController.llDeviceFilters,
3860 false); // fHostMode
3861
3862 xml::ElementNode *pelmNetwork = pelmHardware->createChild("Network");
3863 for (NetworkAdaptersList::const_iterator it = hw.llNetworkAdapters.begin();
3864 it != hw.llNetworkAdapters.end();
3865 ++it)
3866 {
3867 const NetworkAdapter &nic = *it;
3868
3869 xml::ElementNode *pelmAdapter = pelmNetwork->createChild("Adapter");
3870 pelmAdapter->setAttribute("slot", nic.ulSlot);
3871 pelmAdapter->setAttribute("enabled", nic.fEnabled);
3872 pelmAdapter->setAttribute("MACAddress", nic.strMACAddress);
3873 pelmAdapter->setAttribute("cable", nic.fCableConnected);
3874 pelmAdapter->setAttribute("speed", nic.ulLineSpeed);
3875 if (nic.ulBootPriority != 0)
3876 {
3877 pelmAdapter->setAttribute("bootPriority", nic.ulBootPriority);
3878 }
3879 if (nic.fTraceEnabled)
3880 {
3881 pelmAdapter->setAttribute("trace", nic.fTraceEnabled);
3882 pelmAdapter->setAttribute("tracefile", nic.strTraceFile);
3883 }
3884 if (nic.strBandwidthGroup.isNotEmpty())
3885 pelmAdapter->setAttribute("bandwidthGroup", nic.strBandwidthGroup);
3886
3887 const char *pszPolicy;
3888 switch (nic.enmPromiscModePolicy)
3889 {
3890 case NetworkAdapterPromiscModePolicy_Deny: pszPolicy = NULL; break;
3891 case NetworkAdapterPromiscModePolicy_AllowNetwork: pszPolicy = "AllowNetwork"; break;
3892 case NetworkAdapterPromiscModePolicy_AllowAll: pszPolicy = "AllowAll"; break;
3893 default: pszPolicy = NULL; AssertFailed(); break;
3894 }
3895 if (pszPolicy)
3896 pelmAdapter->setAttribute("promiscuousModePolicy", pszPolicy);
3897
3898 const char *pcszType;
3899 switch (nic.type)
3900 {
3901 case NetworkAdapterType_Am79C973: pcszType = "Am79C973"; break;
3902 case NetworkAdapterType_I82540EM: pcszType = "82540EM"; break;
3903 case NetworkAdapterType_I82543GC: pcszType = "82543GC"; break;
3904 case NetworkAdapterType_I82545EM: pcszType = "82545EM"; break;
3905 case NetworkAdapterType_Virtio: pcszType = "virtio"; break;
3906 default: /*case NetworkAdapterType_Am79C970A:*/ pcszType = "Am79C970A"; break;
3907 }
3908 pelmAdapter->setAttribute("type", pcszType);
3909
3910 xml::ElementNode *pelmNAT;
3911 if (m->sv < SettingsVersion_v1_10)
3912 {
3913 switch (nic.mode)
3914 {
3915 case NetworkAttachmentType_NAT:
3916 pelmNAT = pelmAdapter->createChild("NAT");
3917 if (nic.nat.strNetwork.length())
3918 pelmNAT->setAttribute("network", nic.nat.strNetwork);
3919 break;
3920
3921 case NetworkAttachmentType_Bridged:
3922 pelmAdapter->createChild("BridgedInterface")->setAttribute("name", nic.strBridgedName);
3923 break;
3924
3925 case NetworkAttachmentType_Internal:
3926 pelmAdapter->createChild("InternalNetwork")->setAttribute("name", nic.strInternalNetworkName);
3927 break;
3928
3929 case NetworkAttachmentType_HostOnly:
3930 pelmAdapter->createChild("HostOnlyInterface")->setAttribute("name", nic.strHostOnlyName);
3931 break;
3932
3933 default: /*case NetworkAttachmentType_Null:*/
3934 break;
3935 }
3936 }
3937 else
3938 {
3939 /* m->sv >= SettingsVersion_v1_10 */
3940 xml::ElementNode *pelmDisabledNode = NULL;
3941 pelmDisabledNode = pelmAdapter->createChild("DisabledModes");
3942 if (nic.mode != NetworkAttachmentType_NAT)
3943 buildNetworkXML(NetworkAttachmentType_NAT, *pelmDisabledNode, false, nic);
3944 if (nic.mode != NetworkAttachmentType_Bridged)
3945 buildNetworkXML(NetworkAttachmentType_Bridged, *pelmDisabledNode, false, nic);
3946 if (nic.mode != NetworkAttachmentType_Internal)
3947 buildNetworkXML(NetworkAttachmentType_HostOnly, *pelmDisabledNode, false, nic);
3948 if (nic.mode != NetworkAttachmentType_HostOnly)
3949 buildNetworkXML(NetworkAttachmentType_HostOnly, *pelmDisabledNode, false, nic);
3950 if (nic.mode != NetworkAttachmentType_Generic)
3951 buildNetworkXML(NetworkAttachmentType_Generic, *pelmDisabledNode, false, nic);
3952 buildNetworkXML(nic.mode, *pelmAdapter, true, nic);
3953 }
3954 }
3955
3956 xml::ElementNode *pelmPorts = pelmHardware->createChild("UART");
3957 for (SerialPortsList::const_iterator it = hw.llSerialPorts.begin();
3958 it != hw.llSerialPorts.end();
3959 ++it)
3960 {
3961 const SerialPort &port = *it;
3962 xml::ElementNode *pelmPort = pelmPorts->createChild("Port");
3963 pelmPort->setAttribute("slot", port.ulSlot);
3964 pelmPort->setAttribute("enabled", port.fEnabled);
3965 pelmPort->setAttributeHex("IOBase", port.ulIOBase);
3966 pelmPort->setAttribute("IRQ", port.ulIRQ);
3967
3968 const char *pcszHostMode;
3969 switch (port.portMode)
3970 {
3971 case PortMode_HostPipe: pcszHostMode = "HostPipe"; break;
3972 case PortMode_HostDevice: pcszHostMode = "HostDevice"; break;
3973 case PortMode_RawFile: pcszHostMode = "RawFile"; break;
3974 default: /*case PortMode_Disconnected:*/ pcszHostMode = "Disconnected"; break;
3975 }
3976 switch (port.portMode)
3977 {
3978 case PortMode_HostPipe:
3979 pelmPort->setAttribute("server", port.fServer);
3980 /* no break */
3981 case PortMode_HostDevice:
3982 case PortMode_RawFile:
3983 pelmPort->setAttribute("path", port.strPath);
3984 break;
3985
3986 default:
3987 break;
3988 }
3989 pelmPort->setAttribute("hostMode", pcszHostMode);
3990 }
3991
3992 pelmPorts = pelmHardware->createChild("LPT");
3993 for (ParallelPortsList::const_iterator it = hw.llParallelPorts.begin();
3994 it != hw.llParallelPorts.end();
3995 ++it)
3996 {
3997 const ParallelPort &port = *it;
3998 xml::ElementNode *pelmPort = pelmPorts->createChild("Port");
3999 pelmPort->setAttribute("slot", port.ulSlot);
4000 pelmPort->setAttribute("enabled", port.fEnabled);
4001 pelmPort->setAttributeHex("IOBase", port.ulIOBase);
4002 pelmPort->setAttribute("IRQ", port.ulIRQ);
4003 if (port.strPath.length())
4004 pelmPort->setAttribute("path", port.strPath);
4005 }
4006
4007 xml::ElementNode *pelmAudio = pelmHardware->createChild("AudioAdapter");
4008 const char *pcszController;
4009 switch (hw.audioAdapter.controllerType)
4010 {
4011 case AudioControllerType_SB16:
4012 pcszController = "SB16";
4013 break;
4014 case AudioControllerType_HDA:
4015 if (m->sv >= SettingsVersion_v1_11)
4016 {
4017 pcszController = "HDA";
4018 break;
4019 }
4020 /* fall through */
4021 case AudioControllerType_AC97:
4022 default:
4023 pcszController = "AC97";
4024 break;
4025 }
4026 pelmAudio->setAttribute("controller", pcszController);
4027
4028 if (m->sv >= SettingsVersion_v1_10)
4029 {
4030 xml::ElementNode *pelmRTC = pelmHardware->createChild("RTC");
4031 pelmRTC->setAttribute("localOrUTC", machineUserData.fRTCUseUTC ? "UTC" : "local");
4032 }
4033
4034 const char *pcszDriver;
4035 switch (hw.audioAdapter.driverType)
4036 {
4037 case AudioDriverType_WinMM: pcszDriver = "WinMM"; break;
4038 case AudioDriverType_DirectSound: pcszDriver = "DirectSound"; break;
4039 case AudioDriverType_SolAudio: pcszDriver = "SolAudio"; break;
4040 case AudioDriverType_ALSA: pcszDriver = "ALSA"; break;
4041 case AudioDriverType_Pulse: pcszDriver = "Pulse"; break;
4042 case AudioDriverType_OSS: pcszDriver = "OSS"; break;
4043 case AudioDriverType_CoreAudio: pcszDriver = "CoreAudio"; break;
4044 case AudioDriverType_MMPM: pcszDriver = "MMPM"; break;
4045 default: /*case AudioDriverType_Null:*/ pcszDriver = "Null"; break;
4046 }
4047 pelmAudio->setAttribute("driver", pcszDriver);
4048
4049 pelmAudio->setAttribute("enabled", hw.audioAdapter.fEnabled);
4050
4051 xml::ElementNode *pelmSharedFolders = pelmHardware->createChild("SharedFolders");
4052 for (SharedFoldersList::const_iterator it = hw.llSharedFolders.begin();
4053 it != hw.llSharedFolders.end();
4054 ++it)
4055 {
4056 const SharedFolder &sf = *it;
4057 xml::ElementNode *pelmThis = pelmSharedFolders->createChild("SharedFolder");
4058 pelmThis->setAttribute("name", sf.strName);
4059 pelmThis->setAttribute("hostPath", sf.strHostPath);
4060 pelmThis->setAttribute("writable", sf.fWritable);
4061 pelmThis->setAttribute("autoMount", sf.fAutoMount);
4062 }
4063
4064 xml::ElementNode *pelmClip = pelmHardware->createChild("Clipboard");
4065 const char *pcszClip;
4066 switch (hw.clipboardMode)
4067 {
4068 case ClipboardMode_Disabled: pcszClip = "Disabled"; break;
4069 case ClipboardMode_HostToGuest: pcszClip = "HostToGuest"; break;
4070 case ClipboardMode_GuestToHost: pcszClip = "GuestToHost"; break;
4071 default: /*case ClipboardMode_Bidirectional:*/ pcszClip = "Bidirectional"; break;
4072 }
4073 pelmClip->setAttribute("mode", pcszClip);
4074
4075 if (m->sv >= SettingsVersion_v1_10)
4076 {
4077 xml::ElementNode *pelmIo = pelmHardware->createChild("IO");
4078 xml::ElementNode *pelmIoCache;
4079
4080 pelmIoCache = pelmIo->createChild("IoCache");
4081 pelmIoCache->setAttribute("enabled", hw.ioSettings.fIoCacheEnabled);
4082 pelmIoCache->setAttribute("size", hw.ioSettings.ulIoCacheSize);
4083
4084 if (m->sv >= SettingsVersion_v1_11)
4085 {
4086 xml::ElementNode *pelmBandwidthGroups = pelmIo->createChild("BandwidthGroups");
4087 for (BandwidthGroupList::const_iterator it = hw.ioSettings.llBandwidthGroups.begin();
4088 it != hw.ioSettings.llBandwidthGroups.end();
4089 ++it)
4090 {
4091 const BandwidthGroup &gr = *it;
4092 const char *pcszType;
4093 xml::ElementNode *pelmThis = pelmBandwidthGroups->createChild("BandwidthGroup");
4094 pelmThis->setAttribute("name", gr.strName);
4095 switch (gr.enmType)
4096 {
4097 case BandwidthGroupType_Network: pcszType = "Network"; break;
4098 default: /* BandwidthGrouptype_Disk */ pcszType = "Disk"; break;
4099 }
4100 pelmThis->setAttribute("type", pcszType);
4101 if (m->sv >= SettingsVersion_v1_13)
4102 pelmThis->setAttribute("maxBytesPerSec", gr.cMaxBytesPerSec);
4103 else
4104 pelmThis->setAttribute("maxMbPerSec", gr.cMaxBytesPerSec / _1M);
4105 }
4106 }
4107 }
4108
4109 if (m->sv >= SettingsVersion_v1_12)
4110 {
4111 xml::ElementNode *pelmPci = pelmHardware->createChild("HostPci");
4112 xml::ElementNode *pelmPciDevices = pelmPci->createChild("Devices");
4113
4114 for (HostPciDeviceAttachmentList::const_iterator it = hw.pciAttachments.begin();
4115 it != hw.pciAttachments.end();
4116 ++it)
4117 {
4118 const HostPciDeviceAttachment &hpda = *it;
4119
4120 xml::ElementNode *pelmThis = pelmPciDevices->createChild("Device");
4121
4122 pelmThis->setAttribute("host", hpda.uHostAddress);
4123 pelmThis->setAttribute("guest", hpda.uGuestAddress);
4124 pelmThis->setAttribute("name", hpda.strDeviceName);
4125 }
4126 }
4127
4128 if (m->sv >= SettingsVersion_v1_12)
4129 {
4130 xml::ElementNode *pelmEmulatedUSB = pelmHardware->createChild("EmulatedUSB");
4131 xml::ElementNode *pelmCardReader = pelmEmulatedUSB->createChild("CardReader");
4132
4133 pelmCardReader->setAttribute("enabled", hw.fEmulatedUSBCardReader);
4134 }
4135
4136 xml::ElementNode *pelmGuest = pelmHardware->createChild("Guest");
4137 pelmGuest->setAttribute("memoryBalloonSize", hw.ulMemoryBalloonSize);
4138
4139 xml::ElementNode *pelmGuestProps = pelmHardware->createChild("GuestProperties");
4140 for (GuestPropertiesList::const_iterator it = hw.llGuestProperties.begin();
4141 it != hw.llGuestProperties.end();
4142 ++it)
4143 {
4144 const GuestProperty &prop = *it;
4145 xml::ElementNode *pelmProp = pelmGuestProps->createChild("GuestProperty");
4146 pelmProp->setAttribute("name", prop.strName);
4147 pelmProp->setAttribute("value", prop.strValue);
4148 pelmProp->setAttribute("timestamp", prop.timestamp);
4149 pelmProp->setAttribute("flags", prop.strFlags);
4150 }
4151
4152 if (hw.strNotificationPatterns.length())
4153 pelmGuestProps->setAttribute("notificationPatterns", hw.strNotificationPatterns);
4154}
4155
4156/**
4157 * Fill a <Network> node. Only relevant for XML version >= v1_10.
4158 * @param mode
4159 * @param elmParent
4160 * @param fEnabled
4161 * @param nic
4162 */
4163void MachineConfigFile::buildNetworkXML(NetworkAttachmentType_T mode,
4164 xml::ElementNode &elmParent,
4165 bool fEnabled,
4166 const NetworkAdapter &nic)
4167{
4168 switch (mode)
4169 {
4170 case NetworkAttachmentType_NAT:
4171 xml::ElementNode *pelmNAT;
4172 pelmNAT = elmParent.createChild("NAT");
4173
4174 if (nic.nat.strNetwork.length())
4175 pelmNAT->setAttribute("network", nic.nat.strNetwork);
4176 if (nic.nat.strBindIP.length())
4177 pelmNAT->setAttribute("hostip", nic.nat.strBindIP);
4178 if (nic.nat.u32Mtu)
4179 pelmNAT->setAttribute("mtu", nic.nat.u32Mtu);
4180 if (nic.nat.u32SockRcv)
4181 pelmNAT->setAttribute("sockrcv", nic.nat.u32SockRcv);
4182 if (nic.nat.u32SockSnd)
4183 pelmNAT->setAttribute("socksnd", nic.nat.u32SockSnd);
4184 if (nic.nat.u32TcpRcv)
4185 pelmNAT->setAttribute("tcprcv", nic.nat.u32TcpRcv);
4186 if (nic.nat.u32TcpSnd)
4187 pelmNAT->setAttribute("tcpsnd", nic.nat.u32TcpSnd);
4188 xml::ElementNode *pelmDNS;
4189 pelmDNS = pelmNAT->createChild("DNS");
4190 pelmDNS->setAttribute("pass-domain", nic.nat.fDnsPassDomain);
4191 pelmDNS->setAttribute("use-proxy", nic.nat.fDnsProxy);
4192 pelmDNS->setAttribute("use-host-resolver", nic.nat.fDnsUseHostResolver);
4193
4194 xml::ElementNode *pelmAlias;
4195 pelmAlias = pelmNAT->createChild("Alias");
4196 pelmAlias->setAttribute("logging", nic.nat.fAliasLog);
4197 pelmAlias->setAttribute("proxy-only", nic.nat.fAliasProxyOnly);
4198 pelmAlias->setAttribute("use-same-ports", nic.nat.fAliasUseSamePorts);
4199
4200 if ( nic.nat.strTftpPrefix.length()
4201 || nic.nat.strTftpBootFile.length()
4202 || nic.nat.strTftpNextServer.length())
4203 {
4204 xml::ElementNode *pelmTFTP;
4205 pelmTFTP = pelmNAT->createChild("TFTP");
4206 if (nic.nat.strTftpPrefix.length())
4207 pelmTFTP->setAttribute("prefix", nic.nat.strTftpPrefix);
4208 if (nic.nat.strTftpBootFile.length())
4209 pelmTFTP->setAttribute("boot-file", nic.nat.strTftpBootFile);
4210 if (nic.nat.strTftpNextServer.length())
4211 pelmTFTP->setAttribute("next-server", nic.nat.strTftpNextServer);
4212 }
4213 for (NATRuleList::const_iterator rule = nic.nat.llRules.begin();
4214 rule != nic.nat.llRules.end(); ++rule)
4215 {
4216 xml::ElementNode *pelmPF;
4217 pelmPF = pelmNAT->createChild("Forwarding");
4218 if ((*rule).strName.length())
4219 pelmPF->setAttribute("name", (*rule).strName);
4220 pelmPF->setAttribute("proto", (*rule).proto);
4221 if ((*rule).strHostIP.length())
4222 pelmPF->setAttribute("hostip", (*rule).strHostIP);
4223 if ((*rule).u16HostPort)
4224 pelmPF->setAttribute("hostport", (*rule).u16HostPort);
4225 if ((*rule).strGuestIP.length())
4226 pelmPF->setAttribute("guestip", (*rule).strGuestIP);
4227 if ((*rule).u16GuestPort)
4228 pelmPF->setAttribute("guestport", (*rule).u16GuestPort);
4229 }
4230 break;
4231
4232 case NetworkAttachmentType_Bridged:
4233 if (fEnabled || !nic.strBridgedName.isEmpty())
4234 elmParent.createChild("BridgedInterface")->setAttribute("name", nic.strBridgedName);
4235 break;
4236
4237 case NetworkAttachmentType_Internal:
4238 if (fEnabled || !nic.strInternalNetworkName.isEmpty())
4239 elmParent.createChild("InternalNetwork")->setAttribute("name", nic.strInternalNetworkName);
4240 break;
4241
4242 case NetworkAttachmentType_HostOnly:
4243 if (fEnabled || !nic.strHostOnlyName.isEmpty())
4244 elmParent.createChild("HostOnlyInterface")->setAttribute("name", nic.strHostOnlyName);
4245 break;
4246
4247 case NetworkAttachmentType_Generic:
4248 if (fEnabled || !nic.strGenericDriver.isEmpty() || nic.genericProperties.size())
4249 {
4250 xml::ElementNode *pelmMode = elmParent.createChild("GenericInterface");
4251 pelmMode->setAttribute("driver", nic.strGenericDriver);
4252 for (StringsMap::const_iterator it = nic.genericProperties.begin();
4253 it != nic.genericProperties.end();
4254 ++it)
4255 {
4256 xml::ElementNode *pelmProp = pelmMode->createChild("Property");
4257 pelmProp->setAttribute("name", it->first);
4258 pelmProp->setAttribute("value", it->second);
4259 }
4260 }
4261 break;
4262
4263 default: /*case NetworkAttachmentType_Null:*/
4264 break;
4265 }
4266}
4267
4268/**
4269 * Creates a <StorageControllers> node under elmParent and then writes out the XML
4270 * keys under that. Called for both the <Machine> node and for snapshots.
4271 * @param elmParent
4272 * @param st
4273 * @param fSkipRemovableMedia If true, DVD and floppy attachments are skipped and
4274 * an empty drive is always written instead. This is for the OVF export case.
4275 * This parameter is ignored unless the settings version is at least v1.9, which
4276 * is always the case when this gets called for OVF export.
4277 * @param pllElementsWithUuidAttributes If not NULL, must point to a list of element node
4278 * pointers to which we will append all elements that we created here that contain
4279 * UUID attributes. This allows the OVF export code to quickly replace the internal
4280 * media UUIDs with the UUIDs of the media that were exported.
4281 */
4282void MachineConfigFile::buildStorageControllersXML(xml::ElementNode &elmParent,
4283 const Storage &st,
4284 bool fSkipRemovableMedia,
4285 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes)
4286{
4287 xml::ElementNode *pelmStorageControllers = elmParent.createChild("StorageControllers");
4288
4289 for (StorageControllersList::const_iterator it = st.llStorageControllers.begin();
4290 it != st.llStorageControllers.end();
4291 ++it)
4292 {
4293 const StorageController &sc = *it;
4294
4295 if ( (m->sv < SettingsVersion_v1_9)
4296 && (sc.controllerType == StorageControllerType_I82078)
4297 )
4298 // floppy controller already got written into <Hardware>/<FloppyController> in writeHardware()
4299 // for pre-1.9 settings
4300 continue;
4301
4302 xml::ElementNode *pelmController = pelmStorageControllers->createChild("StorageController");
4303 com::Utf8Str name = sc.strName;
4304 if (m->sv < SettingsVersion_v1_8)
4305 {
4306 // pre-1.8 settings use shorter controller names, they are
4307 // expanded when reading the settings
4308 if (name == "IDE Controller")
4309 name = "IDE";
4310 else if (name == "SATA Controller")
4311 name = "SATA";
4312 else if (name == "SCSI Controller")
4313 name = "SCSI";
4314 }
4315 pelmController->setAttribute("name", sc.strName);
4316
4317 const char *pcszType;
4318 switch (sc.controllerType)
4319 {
4320 case StorageControllerType_IntelAhci: pcszType = "AHCI"; break;
4321 case StorageControllerType_LsiLogic: pcszType = "LsiLogic"; break;
4322 case StorageControllerType_BusLogic: pcszType = "BusLogic"; break;
4323 case StorageControllerType_PIIX4: pcszType = "PIIX4"; break;
4324 case StorageControllerType_ICH6: pcszType = "ICH6"; break;
4325 case StorageControllerType_I82078: pcszType = "I82078"; break;
4326 case StorageControllerType_LsiLogicSas: pcszType = "LsiLogicSas"; break;
4327 default: /*case StorageControllerType_PIIX3:*/ pcszType = "PIIX3"; break;
4328 }
4329 pelmController->setAttribute("type", pcszType);
4330
4331 pelmController->setAttribute("PortCount", sc.ulPortCount);
4332
4333 if (m->sv >= SettingsVersion_v1_9)
4334 if (sc.ulInstance)
4335 pelmController->setAttribute("Instance", sc.ulInstance);
4336
4337 if (m->sv >= SettingsVersion_v1_10)
4338 pelmController->setAttribute("useHostIOCache", sc.fUseHostIOCache);
4339
4340 if (m->sv >= SettingsVersion_v1_11)
4341 pelmController->setAttribute("Bootable", sc.fBootable);
4342
4343 if (sc.controllerType == StorageControllerType_IntelAhci)
4344 {
4345 pelmController->setAttribute("IDE0MasterEmulationPort", sc.lIDE0MasterEmulationPort);
4346 pelmController->setAttribute("IDE0SlaveEmulationPort", sc.lIDE0SlaveEmulationPort);
4347 pelmController->setAttribute("IDE1MasterEmulationPort", sc.lIDE1MasterEmulationPort);
4348 pelmController->setAttribute("IDE1SlaveEmulationPort", sc.lIDE1SlaveEmulationPort);
4349 }
4350
4351 for (AttachedDevicesList::const_iterator it2 = sc.llAttachedDevices.begin();
4352 it2 != sc.llAttachedDevices.end();
4353 ++it2)
4354 {
4355 const AttachedDevice &att = *it2;
4356
4357 // For settings version before 1.9, DVDs and floppies are in hardware, not storage controllers,
4358 // so we shouldn't write them here; we only get here for DVDs though because we ruled out
4359 // the floppy controller at the top of the loop
4360 if ( att.deviceType == DeviceType_DVD
4361 && m->sv < SettingsVersion_v1_9
4362 )
4363 continue;
4364
4365 xml::ElementNode *pelmDevice = pelmController->createChild("AttachedDevice");
4366
4367 pcszType = NULL;
4368
4369 switch (att.deviceType)
4370 {
4371 case DeviceType_HardDisk:
4372 pcszType = "HardDisk";
4373 if (att.fNonRotational)
4374 pelmDevice->setAttribute("nonrotational", att.fNonRotational);
4375 if (att.fDiscard)
4376 pelmDevice->setAttribute("discard", att.fDiscard);
4377 break;
4378
4379 case DeviceType_DVD:
4380 pcszType = "DVD";
4381 pelmDevice->setAttribute("passthrough", att.fPassThrough);
4382 if (att.fTempEject)
4383 pelmDevice->setAttribute("tempeject", att.fTempEject);
4384 break;
4385
4386 case DeviceType_Floppy:
4387 pcszType = "Floppy";
4388 break;
4389 }
4390
4391 pelmDevice->setAttribute("type", pcszType);
4392
4393 pelmDevice->setAttribute("port", att.lPort);
4394 pelmDevice->setAttribute("device", att.lDevice);
4395
4396 if (att.strBwGroup.length())
4397 pelmDevice->setAttribute("bandwidthGroup", att.strBwGroup);
4398
4399 // attached image, if any
4400 if ( !att.uuid.isEmpty()
4401 && ( att.deviceType == DeviceType_HardDisk
4402 || !fSkipRemovableMedia
4403 )
4404 )
4405 {
4406 xml::ElementNode *pelmImage = pelmDevice->createChild("Image");
4407 pelmImage->setAttribute("uuid", att.uuid.toStringCurly());
4408
4409 // if caller wants a list of UUID elements, give it to them
4410 if (pllElementsWithUuidAttributes)
4411 pllElementsWithUuidAttributes->push_back(pelmImage);
4412 }
4413 else if ( (m->sv >= SettingsVersion_v1_9)
4414 && (att.strHostDriveSrc.length())
4415 )
4416 pelmDevice->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
4417 }
4418 }
4419}
4420
4421/**
4422 * Creates a <Debugging> node under elmParent and then writes out the XML
4423 * keys under that. Called for both the <Machine> node and for snapshots.
4424 *
4425 * @param pElmParent Pointer to the parent element.
4426 * @param pDbg Pointer to the debugging settings.
4427 */
4428void MachineConfigFile::buildDebuggingXML(xml::ElementNode *pElmParent, const Debugging *pDbg)
4429{
4430 if (m->sv < SettingsVersion_v1_13 || pDbg->areDefaultSettings())
4431 return;
4432
4433 xml::ElementNode *pElmDebugging = pElmParent->createChild("Debugging");
4434 xml::ElementNode *pElmTracing = pElmDebugging->createChild("Tracing");
4435 pElmTracing->setAttribute("enabled", pDbg->fTracingEnabled);
4436 pElmTracing->setAttribute("allowTracingToAccessVM", pDbg->fAllowTracingToAccessVM);
4437 pElmTracing->setAttribute("config", pDbg->strTracingConfig);
4438}
4439
4440/**
4441 * Creates a <Autostart> node under elmParent and then writes out the XML
4442 * keys under that. Called for both the <Machine> node and for snapshots.
4443 *
4444 * @param pElmParent Pointer to the parent element.
4445 * @param pAutostart Pointer to the autostart settings.
4446 */
4447void MachineConfigFile::buildAutostartXML(xml::ElementNode *pElmParent, const Autostart *pAutostart)
4448{
4449 const char *pcszAutostop = NULL;
4450
4451 if (m->sv < SettingsVersion_v1_13 || pAutostart->areDefaultSettings())
4452 return;
4453
4454 xml::ElementNode *pElmAutostart = pElmParent->createChild("Autostart");
4455 pElmAutostart->setAttribute("enabled", pAutostart->fAutostartEnabled);
4456 pElmAutostart->setAttribute("delay", pAutostart->uAutostartDelay);
4457
4458 switch (pAutostart->enmAutostopType)
4459 {
4460 case AutostopType_Disabled: pcszAutostop = "Disabled"; break;
4461 case AutostopType_SaveState: pcszAutostop = "SaveState"; break;
4462 case AutostopType_PowerOff: pcszAutostop = "PowerOff"; break;
4463 case AutostopType_AcpiShutdown: pcszAutostop = "AcpiShutdown"; break;
4464 default: Assert(false); pcszAutostop = "Disabled"; break;
4465 }
4466 pElmAutostart->setAttribute("autostop", pcszAutostop);
4467}
4468
4469/**
4470 * Creates a <Groups> node under elmParent and then writes out the XML
4471 * keys under that. Called for the <Machine> node only.
4472 *
4473 * @param pElmParent Pointer to the parent element.
4474 * @param pllGroups Pointer to the groups list.
4475 */
4476void MachineConfigFile::buildGroupsXML(xml::ElementNode *pElmParent, const StringsList *pllGroups)
4477{
4478 if ( m->sv < SettingsVersion_v1_13 || pllGroups->size() == 0
4479 || (pllGroups->size() == 1 && pllGroups->front() == "/"))
4480 return;
4481
4482 xml::ElementNode *pElmGroups = pElmParent->createChild("Groups");
4483 for (StringsList::const_iterator it = pllGroups->begin();
4484 it != pllGroups->end();
4485 ++it)
4486 {
4487 const Utf8Str &group = *it;
4488 xml::ElementNode *pElmGroup = pElmGroups->createChild("Group");
4489 pElmGroup->setAttribute("name", group);
4490 }
4491}
4492
4493/**
4494 * Writes a single snapshot into the DOM tree. Initially this gets called from MachineConfigFile::write()
4495 * for the root snapshot of a machine, if present; elmParent then points to the <Snapshots> node under the
4496 * <Machine> node to which <Snapshot> must be added. This may then recurse for child snapshots.
4497 * @param elmParent
4498 * @param snap
4499 */
4500void MachineConfigFile::buildSnapshotXML(xml::ElementNode &elmParent,
4501 const Snapshot &snap)
4502{
4503 xml::ElementNode *pelmSnapshot = elmParent.createChild("Snapshot");
4504
4505 pelmSnapshot->setAttribute("uuid", snap.uuid.toStringCurly());
4506 pelmSnapshot->setAttribute("name", snap.strName);
4507 pelmSnapshot->setAttribute("timeStamp", makeString(snap.timestamp));
4508
4509 if (snap.strStateFile.length())
4510 pelmSnapshot->setAttributePath("stateFile", snap.strStateFile);
4511
4512 if (snap.strDescription.length())
4513 pelmSnapshot->createChild("Description")->addContent(snap.strDescription);
4514
4515 buildHardwareXML(*pelmSnapshot, snap.hardware, snap.storage);
4516 buildStorageControllersXML(*pelmSnapshot,
4517 snap.storage,
4518 false /* fSkipRemovableMedia */,
4519 NULL); /* pllElementsWithUuidAttributes */
4520 // we only skip removable media for OVF, but we never get here for OVF
4521 // since snapshots never get written then
4522 buildDebuggingXML(pelmSnapshot, &snap.debugging);
4523 buildAutostartXML(pelmSnapshot, &snap.autostart);
4524 // note: Groups exist only for Machine, not for Snapshot
4525
4526 if (snap.llChildSnapshots.size())
4527 {
4528 xml::ElementNode *pelmChildren = pelmSnapshot->createChild("Snapshots");
4529 for (SnapshotsList::const_iterator it = snap.llChildSnapshots.begin();
4530 it != snap.llChildSnapshots.end();
4531 ++it)
4532 {
4533 const Snapshot &child = *it;
4534 buildSnapshotXML(*pelmChildren, child);
4535 }
4536 }
4537}
4538
4539/**
4540 * Builds the XML DOM tree for the machine config under the given XML element.
4541 *
4542 * This has been separated out from write() so it can be called from elsewhere,
4543 * such as the OVF code, to build machine XML in an existing XML tree.
4544 *
4545 * As a result, this gets called from two locations:
4546 *
4547 * -- MachineConfigFile::write();
4548 *
4549 * -- Appliance::buildXMLForOneVirtualSystem()
4550 *
4551 * In fl, the following flag bits are recognized:
4552 *
4553 * -- BuildMachineXML_MediaRegistry: If set, the machine's media registry will
4554 * be written, if present. This is not set when called from OVF because OVF
4555 * has its own variant of a media registry. This flag is ignored unless the
4556 * settings version is at least v1.11 (VirtualBox 4.0).
4557 *
4558 * -- BuildMachineXML_IncludeSnapshots: If set, descend into the snapshots tree
4559 * of the machine and write out <Snapshot> and possibly more snapshots under
4560 * that, if snapshots are present. Otherwise all snapshots are suppressed
4561 * (when called from OVF).
4562 *
4563 * -- BuildMachineXML_WriteVboxVersionAttribute: If set, add a settingsVersion
4564 * attribute to the machine tag with the vbox settings version. This is for
4565 * the OVF export case in which we don't have the settings version set in
4566 * the root element.
4567 *
4568 * -- BuildMachineXML_SkipRemovableMedia: If set, removable media attachments
4569 * (DVDs, floppies) are silently skipped. This is for the OVF export case
4570 * until we support copying ISO and RAW media as well. This flag is ignored
4571 * unless the settings version is at least v1.9, which is always the case
4572 * when this gets called for OVF export.
4573 *
4574 * -- BuildMachineXML_SuppressSavedState: If set, the Machine/@stateFile
4575 * attribute is never set. This is also for the OVF export case because we
4576 * cannot save states with OVF.
4577 *
4578 * @param elmMachine XML <Machine> element to add attributes and elements to.
4579 * @param fl Flags.
4580 * @param pllElementsWithUuidAttributes pointer to list that should receive UUID elements or NULL;
4581 * see buildStorageControllersXML() for details.
4582 */
4583void MachineConfigFile::buildMachineXML(xml::ElementNode &elmMachine,
4584 uint32_t fl,
4585 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes)
4586{
4587 if (fl & BuildMachineXML_WriteVboxVersionAttribute)
4588 // add settings version attribute to machine element
4589 setVersionAttribute(elmMachine);
4590
4591 elmMachine.setAttribute("uuid", uuid.toStringCurly());
4592 elmMachine.setAttribute("name", machineUserData.strName);
4593 if (!machineUserData.fNameSync)
4594 elmMachine.setAttribute("nameSync", machineUserData.fNameSync);
4595 if (machineUserData.strDescription.length())
4596 elmMachine.createChild("Description")->addContent(machineUserData.strDescription);
4597 elmMachine.setAttribute("OSType", machineUserData.strOsType);
4598 if ( strStateFile.length()
4599 && !(fl & BuildMachineXML_SuppressSavedState)
4600 )
4601 elmMachine.setAttributePath("stateFile", strStateFile);
4602 if ( (fl & BuildMachineXML_IncludeSnapshots)
4603 && !uuidCurrentSnapshot.isEmpty())
4604 elmMachine.setAttribute("currentSnapshot", uuidCurrentSnapshot.toStringCurly());
4605
4606 if (machineUserData.strSnapshotFolder.length())
4607 elmMachine.setAttributePath("snapshotFolder", machineUserData.strSnapshotFolder);
4608 if (!fCurrentStateModified)
4609 elmMachine.setAttribute("currentStateModified", fCurrentStateModified);
4610 elmMachine.setAttribute("lastStateChange", makeString(timeLastStateChange));
4611 if (fAborted)
4612 elmMachine.setAttribute("aborted", fAborted);
4613 if ( m->sv >= SettingsVersion_v1_9
4614 && ( machineUserData.fTeleporterEnabled
4615 || machineUserData.uTeleporterPort
4616 || !machineUserData.strTeleporterAddress.isEmpty()
4617 || !machineUserData.strTeleporterPassword.isEmpty()
4618 )
4619 )
4620 {
4621 xml::ElementNode *pelmTeleporter = elmMachine.createChild("Teleporter");
4622 pelmTeleporter->setAttribute("enabled", machineUserData.fTeleporterEnabled);
4623 pelmTeleporter->setAttribute("port", machineUserData.uTeleporterPort);
4624 pelmTeleporter->setAttribute("address", machineUserData.strTeleporterAddress);
4625 pelmTeleporter->setAttribute("password", machineUserData.strTeleporterPassword);
4626 }
4627
4628 if ( m->sv >= SettingsVersion_v1_11
4629 && ( machineUserData.enmFaultToleranceState != FaultToleranceState_Inactive
4630 || machineUserData.uFaultTolerancePort
4631 || machineUserData.uFaultToleranceInterval
4632 || !machineUserData.strFaultToleranceAddress.isEmpty()
4633 )
4634 )
4635 {
4636 xml::ElementNode *pelmFaultTolerance = elmMachine.createChild("FaultTolerance");
4637 switch (machineUserData.enmFaultToleranceState)
4638 {
4639 case FaultToleranceState_Inactive:
4640 pelmFaultTolerance->setAttribute("state", "inactive");
4641 break;
4642 case FaultToleranceState_Master:
4643 pelmFaultTolerance->setAttribute("state", "master");
4644 break;
4645 case FaultToleranceState_Standby:
4646 pelmFaultTolerance->setAttribute("state", "standby");
4647 break;
4648 }
4649
4650 pelmFaultTolerance->setAttribute("port", machineUserData.uFaultTolerancePort);
4651 pelmFaultTolerance->setAttribute("address", machineUserData.strFaultToleranceAddress);
4652 pelmFaultTolerance->setAttribute("interval", machineUserData.uFaultToleranceInterval);
4653 pelmFaultTolerance->setAttribute("password", machineUserData.strFaultTolerancePassword);
4654 }
4655
4656 if ( (fl & BuildMachineXML_MediaRegistry)
4657 && (m->sv >= SettingsVersion_v1_11)
4658 )
4659 buildMediaRegistry(elmMachine, mediaRegistry);
4660
4661 buildExtraData(elmMachine, mapExtraDataItems);
4662
4663 if ( (fl & BuildMachineXML_IncludeSnapshots)
4664 && llFirstSnapshot.size())
4665 buildSnapshotXML(elmMachine, llFirstSnapshot.front());
4666
4667 buildHardwareXML(elmMachine, hardwareMachine, storageMachine);
4668 buildStorageControllersXML(elmMachine,
4669 storageMachine,
4670 !!(fl & BuildMachineXML_SkipRemovableMedia),
4671 pllElementsWithUuidAttributes);
4672 buildDebuggingXML(&elmMachine, &debugging);
4673 buildAutostartXML(&elmMachine, &autostart);
4674 buildGroupsXML(&elmMachine, &machineUserData.llGroups);
4675}
4676
4677/**
4678 * Returns true only if the given AudioDriverType is supported on
4679 * the current host platform. For example, this would return false
4680 * for AudioDriverType_DirectSound when compiled on a Linux host.
4681 * @param drv AudioDriverType_* enum to test.
4682 * @return true only if the current host supports that driver.
4683 */
4684/*static*/
4685bool MachineConfigFile::isAudioDriverAllowedOnThisHost(AudioDriverType_T drv)
4686{
4687 switch (drv)
4688 {
4689 case AudioDriverType_Null:
4690#ifdef RT_OS_WINDOWS
4691# ifdef VBOX_WITH_WINMM
4692 case AudioDriverType_WinMM:
4693# endif
4694 case AudioDriverType_DirectSound:
4695#endif /* RT_OS_WINDOWS */
4696#ifdef RT_OS_SOLARIS
4697 case AudioDriverType_SolAudio:
4698#endif
4699#ifdef RT_OS_LINUX
4700# ifdef VBOX_WITH_ALSA
4701 case AudioDriverType_ALSA:
4702# endif
4703# ifdef VBOX_WITH_PULSE
4704 case AudioDriverType_Pulse:
4705# endif
4706#endif /* RT_OS_LINUX */
4707#if defined (RT_OS_LINUX) || defined (RT_OS_FREEBSD) || defined(VBOX_WITH_SOLARIS_OSS)
4708 case AudioDriverType_OSS:
4709#endif
4710#ifdef RT_OS_FREEBSD
4711# ifdef VBOX_WITH_PULSE
4712 case AudioDriverType_Pulse:
4713# endif
4714#endif
4715#ifdef RT_OS_DARWIN
4716 case AudioDriverType_CoreAudio:
4717#endif
4718#ifdef RT_OS_OS2
4719 case AudioDriverType_MMPM:
4720#endif
4721 return true;
4722 }
4723
4724 return false;
4725}
4726
4727/**
4728 * Returns the AudioDriverType_* which should be used by default on this
4729 * host platform. On Linux, this will check at runtime whether PulseAudio
4730 * or ALSA are actually supported on the first call.
4731 * @return
4732 */
4733/*static*/
4734AudioDriverType_T MachineConfigFile::getHostDefaultAudioDriver()
4735{
4736#if defined(RT_OS_WINDOWS)
4737# ifdef VBOX_WITH_WINMM
4738 return AudioDriverType_WinMM;
4739# else /* VBOX_WITH_WINMM */
4740 return AudioDriverType_DirectSound;
4741# endif /* !VBOX_WITH_WINMM */
4742#elif defined(RT_OS_SOLARIS)
4743 return AudioDriverType_SolAudio;
4744#elif defined(RT_OS_LINUX)
4745 // on Linux, we need to check at runtime what's actually supported...
4746 static RTCLockMtx s_mtx;
4747 static AudioDriverType_T s_linuxDriver = -1;
4748 RTCLock lock(s_mtx);
4749 if (s_linuxDriver == (AudioDriverType_T)-1)
4750 {
4751# if defined(VBOX_WITH_PULSE)
4752 /* Check for the pulse library & that the pulse audio daemon is running. */
4753 if (RTProcIsRunningByName("pulseaudio") &&
4754 RTLdrIsLoadable("libpulse.so.0"))
4755 s_linuxDriver = AudioDriverType_Pulse;
4756 else
4757# endif /* VBOX_WITH_PULSE */
4758# if defined(VBOX_WITH_ALSA)
4759 /* Check if we can load the ALSA library */
4760 if (RTLdrIsLoadable("libasound.so.2"))
4761 s_linuxDriver = AudioDriverType_ALSA;
4762 else
4763# endif /* VBOX_WITH_ALSA */
4764 s_linuxDriver = AudioDriverType_OSS;
4765 }
4766 return s_linuxDriver;
4767// end elif defined(RT_OS_LINUX)
4768#elif defined(RT_OS_DARWIN)
4769 return AudioDriverType_CoreAudio;
4770#elif defined(RT_OS_OS2)
4771 return AudioDriverType_MMPM;
4772#elif defined(RT_OS_FREEBSD)
4773 return AudioDriverType_OSS;
4774#else
4775 return AudioDriverType_Null;
4776#endif
4777}
4778
4779/**
4780 * Called from write() before calling ConfigFileBase::createStubDocument().
4781 * This adjusts the settings version in m->sv if incompatible settings require
4782 * a settings bump, whereas otherwise we try to preserve the settings version
4783 * to avoid breaking compatibility with older versions.
4784 *
4785 * We do the checks in here in reverse order: newest first, oldest last, so
4786 * that we avoid unnecessary checks since some of these are expensive.
4787 */
4788void MachineConfigFile::bumpSettingsVersionIfNeeded()
4789{
4790 if (m->sv < SettingsVersion_v1_13)
4791 {
4792 // VirtualBox 4.2 adds tracing, autostart and groups.
4793 if ( !debugging.areDefaultSettings()
4794 || !autostart.areDefaultSettings()
4795 || machineUserData.llGroups.size() > 1
4796 || machineUserData.llGroups.front() != "/")
4797 m->sv = SettingsVersion_v1_13;
4798 }
4799
4800 if (m->sv < SettingsVersion_v1_13)
4801 {
4802 // VirtualBox 4.2 changes the units for bandwidth group limits.
4803 for (BandwidthGroupList::const_iterator it = hardwareMachine.ioSettings.llBandwidthGroups.begin();
4804 it != hardwareMachine.ioSettings.llBandwidthGroups.end();
4805 ++it)
4806 {
4807 const BandwidthGroup &gr = *it;
4808 if (gr.cMaxBytesPerSec % _1M)
4809 {
4810 // Bump version if a limit cannot be expressed in megabytes
4811 m->sv = SettingsVersion_v1_13;
4812 break;
4813 }
4814 }
4815 }
4816
4817 if (m->sv < SettingsVersion_v1_12)
4818 {
4819 // 4.1: Emulated USB devices.
4820 if (hardwareMachine.fEmulatedUSBCardReader)
4821 m->sv = SettingsVersion_v1_12;
4822 }
4823
4824 if (m->sv < SettingsVersion_v1_12)
4825 {
4826 // VirtualBox 4.1 adds PCI passthrough.
4827 if (hardwareMachine.pciAttachments.size())
4828 m->sv = SettingsVersion_v1_12;
4829 }
4830
4831 if (m->sv < SettingsVersion_v1_12)
4832 {
4833 // VirtualBox 4.1 adds a promiscuous mode policy to the network
4834 // adapters and a generic network driver transport.
4835 NetworkAdaptersList::const_iterator netit;
4836 for (netit = hardwareMachine.llNetworkAdapters.begin();
4837 netit != hardwareMachine.llNetworkAdapters.end();
4838 ++netit)
4839 {
4840 if ( netit->enmPromiscModePolicy != NetworkAdapterPromiscModePolicy_Deny
4841 || netit->mode == NetworkAttachmentType_Generic
4842 || !netit->strGenericDriver.isEmpty()
4843 || netit->genericProperties.size()
4844 )
4845 {
4846 m->sv = SettingsVersion_v1_12;
4847 break;
4848 }
4849 }
4850 }
4851
4852 if (m->sv < SettingsVersion_v1_11)
4853 {
4854 // VirtualBox 4.0 adds HD audio, CPU priorities, fault tolerance,
4855 // per-machine media registries, VRDE, JRockitVE, bandwidth groups,
4856 // ICH9 chipset
4857 if ( hardwareMachine.audioAdapter.controllerType == AudioControllerType_HDA
4858 || hardwareMachine.ulCpuExecutionCap != 100
4859 || machineUserData.enmFaultToleranceState != FaultToleranceState_Inactive
4860 || machineUserData.uFaultTolerancePort
4861 || machineUserData.uFaultToleranceInterval
4862 || !machineUserData.strFaultToleranceAddress.isEmpty()
4863 || mediaRegistry.llHardDisks.size()
4864 || mediaRegistry.llDvdImages.size()
4865 || mediaRegistry.llFloppyImages.size()
4866 || !hardwareMachine.vrdeSettings.strVrdeExtPack.isEmpty()
4867 || !hardwareMachine.vrdeSettings.strAuthLibrary.isEmpty()
4868 || machineUserData.strOsType == "JRockitVE"
4869 || hardwareMachine.ioSettings.llBandwidthGroups.size()
4870 || hardwareMachine.chipsetType == ChipsetType_ICH9
4871 )
4872 m->sv = SettingsVersion_v1_11;
4873 }
4874
4875 if (m->sv < SettingsVersion_v1_10)
4876 {
4877 /* If the properties contain elements other than "TCP/Ports" and "TCP/Address",
4878 * then increase the version to at least VBox 3.2, which can have video channel properties.
4879 */
4880 unsigned cOldProperties = 0;
4881
4882 StringsMap::const_iterator it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Ports");
4883 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4884 cOldProperties++;
4885 it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Address");
4886 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4887 cOldProperties++;
4888
4889 if (hardwareMachine.vrdeSettings.mapProperties.size() != cOldProperties)
4890 m->sv = SettingsVersion_v1_10;
4891 }
4892
4893 if (m->sv < SettingsVersion_v1_11)
4894 {
4895 /* If the properties contain elements other than "TCP/Ports", "TCP/Address",
4896 * "VideoChannel/Enabled" and "VideoChannel/Quality" then increase the version to VBox 4.0.
4897 */
4898 unsigned cOldProperties = 0;
4899
4900 StringsMap::const_iterator it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Ports");
4901 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4902 cOldProperties++;
4903 it = hardwareMachine.vrdeSettings.mapProperties.find("TCP/Address");
4904 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4905 cOldProperties++;
4906 it = hardwareMachine.vrdeSettings.mapProperties.find("VideoChannel/Enabled");
4907 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4908 cOldProperties++;
4909 it = hardwareMachine.vrdeSettings.mapProperties.find("VideoChannel/Quality");
4910 if (it != hardwareMachine.vrdeSettings.mapProperties.end())
4911 cOldProperties++;
4912
4913 if (hardwareMachine.vrdeSettings.mapProperties.size() != cOldProperties)
4914 m->sv = SettingsVersion_v1_11;
4915 }
4916
4917 // settings version 1.9 is required if there is not exactly one DVD
4918 // or more than one floppy drive present or the DVD is not at the secondary
4919 // master; this check is a bit more complicated
4920 //
4921 // settings version 1.10 is required if the host cache should be disabled
4922 //
4923 // settings version 1.11 is required for bandwidth limits and if more than
4924 // one controller of each type is present.
4925 if (m->sv < SettingsVersion_v1_11)
4926 {
4927 // count attached DVDs and floppies (only if < v1.9)
4928 size_t cDVDs = 0;
4929 size_t cFloppies = 0;
4930
4931 // count storage controllers (if < v1.11)
4932 size_t cSata = 0;
4933 size_t cScsiLsi = 0;
4934 size_t cScsiBuslogic = 0;
4935 size_t cSas = 0;
4936 size_t cIde = 0;
4937 size_t cFloppy = 0;
4938
4939 // need to run thru all the storage controllers and attached devices to figure this out
4940 for (StorageControllersList::const_iterator it = storageMachine.llStorageControllers.begin();
4941 it != storageMachine.llStorageControllers.end();
4942 ++it)
4943 {
4944 const StorageController &sctl = *it;
4945
4946 // count storage controllers of each type; 1.11 is required if more than one
4947 // controller of one type is present
4948 switch (sctl.storageBus)
4949 {
4950 case StorageBus_IDE:
4951 cIde++;
4952 break;
4953 case StorageBus_SATA:
4954 cSata++;
4955 break;
4956 case StorageBus_SAS:
4957 cSas++;
4958 break;
4959 case StorageBus_SCSI:
4960 if (sctl.controllerType == StorageControllerType_LsiLogic)
4961 cScsiLsi++;
4962 else
4963 cScsiBuslogic++;
4964 break;
4965 case StorageBus_Floppy:
4966 cFloppy++;
4967 break;
4968 default:
4969 // Do nothing
4970 break;
4971 }
4972
4973 if ( cSata > 1
4974 || cScsiLsi > 1
4975 || cScsiBuslogic > 1
4976 || cSas > 1
4977 || cIde > 1
4978 || cFloppy > 1)
4979 {
4980 m->sv = SettingsVersion_v1_11;
4981 break; // abort the loop -- we will not raise the version further
4982 }
4983
4984 for (AttachedDevicesList::const_iterator it2 = sctl.llAttachedDevices.begin();
4985 it2 != sctl.llAttachedDevices.end();
4986 ++it2)
4987 {
4988 const AttachedDevice &att = *it2;
4989
4990 // Bandwidth limitations are new in VirtualBox 4.0 (1.11)
4991 if (m->sv < SettingsVersion_v1_11)
4992 {
4993 if (att.strBwGroup.length() != 0)
4994 {
4995 m->sv = SettingsVersion_v1_11;
4996 break; // abort the loop -- we will not raise the version further
4997 }
4998 }
4999
5000 // disabling the host IO cache requires settings version 1.10
5001 if ( (m->sv < SettingsVersion_v1_10)
5002 && (!sctl.fUseHostIOCache)
5003 )
5004 m->sv = SettingsVersion_v1_10;
5005
5006 // we can only write the StorageController/@Instance attribute with v1.9
5007 if ( (m->sv < SettingsVersion_v1_9)
5008 && (sctl.ulInstance != 0)
5009 )
5010 m->sv = SettingsVersion_v1_9;
5011
5012 if (m->sv < SettingsVersion_v1_9)
5013 {
5014 if (att.deviceType == DeviceType_DVD)
5015 {
5016 if ( (sctl.storageBus != StorageBus_IDE) // DVD at bus other than DVD?
5017 || (att.lPort != 1) // DVDs not at secondary master?
5018 || (att.lDevice != 0)
5019 )
5020 m->sv = SettingsVersion_v1_9;
5021
5022 ++cDVDs;
5023 }
5024 else if (att.deviceType == DeviceType_Floppy)
5025 ++cFloppies;
5026 }
5027 }
5028
5029 if (m->sv >= SettingsVersion_v1_11)
5030 break; // abort the loop -- we will not raise the version further
5031 }
5032
5033 // VirtualBox before 3.1 had zero or one floppy and exactly one DVD,
5034 // so any deviation from that will require settings version 1.9
5035 if ( (m->sv < SettingsVersion_v1_9)
5036 && ( (cDVDs != 1)
5037 || (cFloppies > 1)
5038 )
5039 )
5040 m->sv = SettingsVersion_v1_9;
5041 }
5042
5043 // VirtualBox 3.2: Check for non default I/O settings
5044 if (m->sv < SettingsVersion_v1_10)
5045 {
5046 if ( (hardwareMachine.ioSettings.fIoCacheEnabled != true)
5047 || (hardwareMachine.ioSettings.ulIoCacheSize != 5)
5048 // and page fusion
5049 || (hardwareMachine.fPageFusionEnabled)
5050 // and CPU hotplug, RTC timezone control, HID type and HPET
5051 || machineUserData.fRTCUseUTC
5052 || hardwareMachine.fCpuHotPlug
5053 || hardwareMachine.pointingHidType != PointingHidType_PS2Mouse
5054 || hardwareMachine.keyboardHidType != KeyboardHidType_PS2Keyboard
5055 || hardwareMachine.fHpetEnabled
5056 )
5057 m->sv = SettingsVersion_v1_10;
5058 }
5059
5060 // VirtualBox 3.2 adds NAT and boot priority to the NIC config in Main
5061 // VirtualBox 4.0 adds network bandwitdth
5062 if (m->sv < SettingsVersion_v1_11)
5063 {
5064 NetworkAdaptersList::const_iterator netit;
5065 for (netit = hardwareMachine.llNetworkAdapters.begin();
5066 netit != hardwareMachine.llNetworkAdapters.end();
5067 ++netit)
5068 {
5069 if ( (m->sv < SettingsVersion_v1_12)
5070 && (netit->strBandwidthGroup.isNotEmpty())
5071 )
5072 {
5073 /* New in VirtualBox 4.1 */
5074 m->sv = SettingsVersion_v1_12;
5075 break;
5076 }
5077 else if ( (m->sv < SettingsVersion_v1_10)
5078 && (netit->fEnabled)
5079 && (netit->mode == NetworkAttachmentType_NAT)
5080 && ( netit->nat.u32Mtu != 0
5081 || netit->nat.u32SockRcv != 0
5082 || netit->nat.u32SockSnd != 0
5083 || netit->nat.u32TcpRcv != 0
5084 || netit->nat.u32TcpSnd != 0
5085 || !netit->nat.fDnsPassDomain
5086 || netit->nat.fDnsProxy
5087 || netit->nat.fDnsUseHostResolver
5088 || netit->nat.fAliasLog
5089 || netit->nat.fAliasProxyOnly
5090 || netit->nat.fAliasUseSamePorts
5091 || netit->nat.strTftpPrefix.length()
5092 || netit->nat.strTftpBootFile.length()
5093 || netit->nat.strTftpNextServer.length()
5094 || netit->nat.llRules.size()
5095 )
5096 )
5097 {
5098 m->sv = SettingsVersion_v1_10;
5099 // no break because we still might need v1.11 above
5100 }
5101 else if ( (m->sv < SettingsVersion_v1_10)
5102 && (netit->fEnabled)
5103 && (netit->ulBootPriority != 0)
5104 )
5105 {
5106 m->sv = SettingsVersion_v1_10;
5107 // no break because we still might need v1.11 above
5108 }
5109 }
5110 }
5111
5112 // all the following require settings version 1.9
5113 if ( (m->sv < SettingsVersion_v1_9)
5114 && ( (hardwareMachine.firmwareType >= FirmwareType_EFI)
5115 || (hardwareMachine.fHardwareVirtExclusive != HWVIRTEXCLUSIVEDEFAULT)
5116 || machineUserData.fTeleporterEnabled
5117 || machineUserData.uTeleporterPort
5118 || !machineUserData.strTeleporterAddress.isEmpty()
5119 || !machineUserData.strTeleporterPassword.isEmpty()
5120 || !hardwareMachine.uuid.isEmpty()
5121 )
5122 )
5123 m->sv = SettingsVersion_v1_9;
5124
5125 // "accelerate 2d video" requires settings version 1.8
5126 if ( (m->sv < SettingsVersion_v1_8)
5127 && (hardwareMachine.fAccelerate2DVideo)
5128 )
5129 m->sv = SettingsVersion_v1_8;
5130
5131 // The hardware versions other than "1" requires settings version 1.4 (2.1+).
5132 if ( m->sv < SettingsVersion_v1_4
5133 && hardwareMachine.strVersion != "1"
5134 )
5135 m->sv = SettingsVersion_v1_4;
5136}
5137
5138/**
5139 * Called from Main code to write a machine config file to disk. This builds a DOM tree from
5140 * the member variables and then writes the XML file; it throws xml::Error instances on errors,
5141 * in particular if the file cannot be written.
5142 */
5143void MachineConfigFile::write(const com::Utf8Str &strFilename)
5144{
5145 try
5146 {
5147 // createStubDocument() sets the settings version to at least 1.7; however,
5148 // we might need to enfore a later settings version if incompatible settings
5149 // are present:
5150 bumpSettingsVersionIfNeeded();
5151
5152 m->strFilename = strFilename;
5153 createStubDocument();
5154
5155 xml::ElementNode *pelmMachine = m->pelmRoot->createChild("Machine");
5156 buildMachineXML(*pelmMachine,
5157 MachineConfigFile::BuildMachineXML_IncludeSnapshots
5158 | MachineConfigFile::BuildMachineXML_MediaRegistry,
5159 // but not BuildMachineXML_WriteVboxVersionAttribute
5160 NULL); /* pllElementsWithUuidAttributes */
5161
5162 // now go write the XML
5163 xml::XmlFileWriter writer(*m->pDoc);
5164 writer.write(m->strFilename.c_str(), true /*fSafe*/);
5165
5166 m->fFileExists = true;
5167 clearDocument();
5168 }
5169 catch (...)
5170 {
5171 clearDocument();
5172 throw;
5173 }
5174}
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