VirtualBox

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

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

Main: fix end marker bug in VRDE settings processing

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