VirtualBox

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

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

Make vrde auth library configurable per VM.

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