VirtualBox

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

Last change on this file since 42551 was 42551, checked in by vboxsync, 12 years ago

Main: big API naming cleanup, use all caps acronyms everywhere, including SDK docs
Frontends/VBoxManage: implement guestcontrol execute for new API, disabled by default

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