VirtualBox

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

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

Main,Config.kmk,VBoxManage,ExtPacks: Moved the VRDE bits from IVirtualBox to the extension packs; changed ISystemProperties and IVRDEServer to talk about VRDE extension packs instead of VRDE libraries.

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