VirtualBox

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

Last change on this file since 48935 was 48879, checked in by vboxsync, 11 years ago

Main/MediumAttachment+Machine: stub attribute/method for an explicit hot-pluggable medium attachment flag, to be used by AHCI soon

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