VirtualBox

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

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

Main/MediumAttachment+Machine: add a setting which controls the guest-triggered medium eject behavior, fix handling "implicit" media, and corresponding VBoxManage and documentation updates

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