VirtualBox

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

Last change on this file since 27166 was 27166, checked in by vboxsync, 15 years ago

Added large page property.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Revision Author Id
File size: 150.9 KB
Line 
1/** @file
2 * Settings File Manipulation API.
3 *
4 * Two classes, MainConfigFile and MachineConfigFile, represent the VirtualBox.xml and
5 * machine XML files. They share a common ancestor class, ConfigFileBase, which shares
6 * functionality such as talking to the XML back-end classes and settings version management.
7 *
8 * The code can read all VirtualBox settings files version 1.3 and higher. That version was
9 * written by VirtualBox 2.0. It can write settings version 1.7 (used by VirtualBox 2.2 and
10 * 3.0) and 1.9 (used by VirtualBox 3.1).
11 *
12 * Rules for introducing new settings: If an element or attribute is introduced that was not
13 * present before VirtualBox 3.1, then settings version checks need to be introduced. The
14 * settings version for VirtualBox 3.1 is 1.9; see the SettingsVersion enumeration in
15 * src/VBox/Main/idl/VirtualBox.xidl for details about which version was used when.
16 *
17 * The settings versions checks are necessary because VirtualBox 3.1 no longer automatically
18 * converts XML settings files but only if necessary, that is, if settings are present that
19 * the old format does not support. If we write an element or attribute to a settings file
20 * of an older version, then an old VirtualBox (before 3.1) will attempt to validate it
21 * with XML schema, and that will certainly fail.
22 *
23 * So, to introduce a new setting:
24 *
25 * 1) Make sure the constructor of corresponding settings structure has a proper default.
26 *
27 * 2) In the settings reader method, try to read the setting; if it's there, great, if not,
28 * the default value will have been set by the constructor.
29 *
30 * 3) In the settings writer method, write the setting _only_ if the current settings
31 * version (stored in m->sv) is high enough. That is, for VirtualBox 3.2, write it
32 * only if (m->sv >= SettingsVersion_v1_10).
33 *
34 * 4) In MachineConfigFile::bumpSettingsVersionIfNeeded(), check if the new setting has
35 * a non-default value (i.e. that differs from the constructor). If so, bump the
36 * settings version to the current version so the settings writer (3) can write out
37 * the non-default value properly.
38 *
39 * So far a corresponding method for MainConfigFile has not been necessary since there
40 * have been no incompatible changes yet.
41 */
42
43/*
44 * Copyright (C) 2007-2010 Sun Microsystems, Inc.
45 *
46 * This file is part of VirtualBox Open Source Edition (OSE), as
47 * available from http://www.virtualbox.org. This file is free software;
48 * you can redistribute it and/or modify it under the terms of the GNU
49 * General Public License (GPL) as published by the Free Software
50 * Foundation, in version 2 as it comes in the "COPYING" file of the
51 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
52 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
53 *
54 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
55 * Clara, CA 95054 USA or visit http://www.sun.com if you need
56 * additional information or have any questions.
57 */
58
59#include "VBox/com/string.h"
60#include "VBox/settings.h"
61#include <iprt/cpp/xml.h>
62#include <iprt/stream.h>
63#include <iprt/ctype.h>
64#include <iprt/file.h>
65
66// generated header
67#include "SchemaDefs.h"
68
69#include "Logging.h"
70
71using namespace com;
72using namespace settings;
73
74////////////////////////////////////////////////////////////////////////////////
75//
76// Defines
77//
78////////////////////////////////////////////////////////////////////////////////
79
80/** VirtualBox XML settings namespace */
81#define VBOX_XML_NAMESPACE "http://www.innotek.de/VirtualBox-settings"
82
83/** VirtualBox XML settings version number substring ("x.y") */
84#define VBOX_XML_VERSION "1.10"
85
86/** VirtualBox XML settings version platform substring */
87#if defined (RT_OS_DARWIN)
88# define VBOX_XML_PLATFORM "macosx"
89#elif defined (RT_OS_FREEBSD)
90# define VBOX_XML_PLATFORM "freebsd"
91#elif defined (RT_OS_LINUX)
92# define VBOX_XML_PLATFORM "linux"
93#elif defined (RT_OS_NETBSD)
94# define VBOX_XML_PLATFORM "netbsd"
95#elif defined (RT_OS_OPENBSD)
96# define VBOX_XML_PLATFORM "openbsd"
97#elif defined (RT_OS_OS2)
98# define VBOX_XML_PLATFORM "os2"
99#elif defined (RT_OS_SOLARIS)
100# define VBOX_XML_PLATFORM "solaris"
101#elif defined (RT_OS_WINDOWS)
102# define VBOX_XML_PLATFORM "windows"
103#else
104# error Unsupported platform!
105#endif
106
107/** VirtualBox XML settings full version string ("x.y-platform") */
108#define VBOX_XML_VERSION_FULL VBOX_XML_VERSION "-" VBOX_XML_PLATFORM
109
110////////////////////////////////////////////////////////////////////////////////
111//
112// Internal data
113//
114////////////////////////////////////////////////////////////////////////////////
115
116/**
117 * Opaque data structore for ConfigFileBase (only declared
118 * in header, defined only here).
119 */
120
121struct ConfigFileBase::Data
122{
123 Data()
124 : pParser(NULL),
125 pDoc(NULL),
126 pelmRoot(NULL),
127 sv(SettingsVersion_Null),
128 svRead(SettingsVersion_Null)
129 {}
130
131 ~Data()
132 {
133 cleanup();
134 }
135
136 iprt::MiniString strFilename;
137 bool fFileExists;
138
139 xml::XmlFileParser *pParser;
140 xml::Document *pDoc;
141 xml::ElementNode *pelmRoot;
142
143 com::Utf8Str strSettingsVersionFull; // e.g. "1.7-linux"
144 SettingsVersion_T sv; // e.g. SettingsVersion_v1_7
145
146 SettingsVersion_T svRead; // settings version that the original file had when it was read,
147 // or SettingsVersion_Null if none
148
149 void copyFrom(const Data &d)
150 {
151 strFilename = d.strFilename;
152 fFileExists = d.fFileExists;
153 strSettingsVersionFull = d.strSettingsVersionFull;
154 sv = d.sv;
155 svRead = d.svRead;
156 }
157
158 void cleanup()
159 {
160 if (pDoc)
161 {
162 delete pDoc;
163 pDoc = NULL;
164 pelmRoot = NULL;
165 }
166
167 if (pParser)
168 {
169 delete pParser;
170 pParser = NULL;
171 }
172 }
173};
174
175/**
176 * Private exception class (not in the header file) that makes
177 * throwing xml::LogicError instances easier. That class is public
178 * and should be caught by client code.
179 */
180class settings::ConfigFileError : public xml::LogicError
181{
182public:
183 ConfigFileError(const ConfigFileBase *file,
184 const xml::Node *pNode,
185 const char *pcszFormat, ...)
186 : xml::LogicError()
187 {
188 va_list args;
189 va_start(args, pcszFormat);
190 Utf8StrFmtVA strWhat(pcszFormat, args);
191 va_end(args);
192
193 Utf8Str strLine;
194 if (pNode)
195 strLine = Utf8StrFmt(" (line %RU32)", pNode->getLineNumber());
196
197 const char *pcsz = strLine.c_str();
198 Utf8StrFmt str(N_("Error in %s%s -- %s"),
199 file->m->strFilename.c_str(),
200 (pcsz) ? pcsz : "",
201 strWhat.c_str());
202
203 setWhat(str.c_str());
204 }
205};
206
207////////////////////////////////////////////////////////////////////////////////
208//
209// ConfigFileBase
210//
211////////////////////////////////////////////////////////////////////////////////
212
213/**
214 * Constructor. Allocates the XML internals.
215 * @param strFilename
216 */
217ConfigFileBase::ConfigFileBase(const com::Utf8Str *pstrFilename)
218 : m(new Data)
219{
220 Utf8Str strMajor;
221 Utf8Str strMinor;
222
223 m->fFileExists = false;
224
225 if (pstrFilename)
226 {
227 // reading existing settings file:
228 m->strFilename = *pstrFilename;
229
230 m->pParser = new xml::XmlFileParser;
231 m->pDoc = new xml::Document;
232 m->pParser->read(*pstrFilename,
233 *m->pDoc);
234
235 m->fFileExists = true;
236
237 m->pelmRoot = m->pDoc->getRootElement();
238 if (!m->pelmRoot || !m->pelmRoot->nameEquals("VirtualBox"))
239 throw ConfigFileError(this, NULL, N_("Root element in VirtualBox settings files must be \"VirtualBox\"."));
240
241 if (!(m->pelmRoot->getAttributeValue("version", m->strSettingsVersionFull)))
242 throw ConfigFileError(this, m->pelmRoot, N_("Required VirtualBox/@version attribute is missing"));
243
244 LogRel(("Loading settings file \"%s\" with version \"%s\"\n", m->strFilename.c_str(), m->strSettingsVersionFull.c_str()));
245
246 // parse settings version; allow future versions but fail if file is older than 1.6
247 m->sv = SettingsVersion_Null;
248 if (m->strSettingsVersionFull.length() > 3)
249 {
250 const char *pcsz = m->strSettingsVersionFull.c_str();
251 char c;
252
253 while ( (c = *pcsz)
254 && RT_C_IS_DIGIT(c)
255 )
256 {
257 strMajor.append(c);
258 ++pcsz;
259 }
260
261 if (*pcsz++ == '.')
262 {
263 while ( (c = *pcsz)
264 && RT_C_IS_DIGIT(c)
265 )
266 {
267 strMinor.append(c);
268 ++pcsz;
269 }
270 }
271
272 uint32_t ulMajor = RTStrToUInt32(strMajor.c_str());
273 uint32_t ulMinor = RTStrToUInt32(strMinor.c_str());
274
275 if (ulMajor == 1)
276 {
277 if (ulMinor == 3)
278 m->sv = SettingsVersion_v1_3;
279 else if (ulMinor == 4)
280 m->sv = SettingsVersion_v1_4;
281 else if (ulMinor == 5)
282 m->sv = SettingsVersion_v1_5;
283 else if (ulMinor == 6)
284 m->sv = SettingsVersion_v1_6;
285 else if (ulMinor == 7)
286 m->sv = SettingsVersion_v1_7;
287 else if (ulMinor == 8)
288 m->sv = SettingsVersion_v1_8;
289 else if (ulMinor == 9)
290 m->sv = SettingsVersion_v1_9;
291 else if (ulMinor == 10)
292 m->sv = SettingsVersion_v1_10;
293 else if (ulMinor > 10)
294 m->sv = SettingsVersion_Future;
295 }
296 else if (ulMajor > 1)
297 m->sv = SettingsVersion_Future;
298
299 LogRel(("Parsed settings version %d.%d to enum value %d\n", ulMajor, ulMinor, m->sv));
300 }
301
302 if (m->sv == SettingsVersion_Null)
303 throw ConfigFileError(this, m->pelmRoot, N_("Cannot handle settings version '%s'"), m->strSettingsVersionFull.c_str());
304
305 // remember the settings version we read in case it gets upgraded later,
306 // so we know when to make backups
307 m->svRead = m->sv;
308 }
309 else
310 {
311 // creating new settings file:
312 m->strSettingsVersionFull = VBOX_XML_VERSION_FULL;
313 m->sv = SettingsVersion_v1_10;
314 }
315}
316
317/**
318 * Clean up.
319 */
320ConfigFileBase::~ConfigFileBase()
321{
322 if (m)
323 {
324 delete m;
325 m = NULL;
326 }
327}
328
329/**
330 * Helper function that parses a UUID in string form into
331 * a com::Guid item. Since that uses an IPRT function which
332 * does not accept "{}" characters around the UUID string,
333 * we handle that here. Throws on errors.
334 * @param guid
335 * @param strUUID
336 */
337void ConfigFileBase::parseUUID(Guid &guid,
338 const Utf8Str &strUUID) const
339{
340 // {5f102a55-a51b-48e3-b45a-b28d33469488}
341 // 01234567890123456789012345678901234567
342 // 1 2 3
343 if ( (strUUID[0] == '{')
344 && (strUUID[37] == '}')
345 )
346 guid = strUUID.substr(1, 36).c_str();
347 else
348 guid = strUUID.c_str();
349
350 if (guid.isEmpty())
351 throw ConfigFileError(this, NULL, N_("UUID \"%s\" has invalid format"), strUUID.c_str());
352}
353
354/**
355 * Parses the given string in str and attempts to treat it as an ISO
356 * date/time stamp to put into timestamp. Throws on errors.
357 * @param timestamp
358 * @param str
359 */
360void ConfigFileBase::parseTimestamp(RTTIMESPEC &timestamp,
361 const com::Utf8Str &str) const
362{
363 const char *pcsz = str.c_str();
364 // yyyy-mm-ddThh:mm:ss
365 // "2009-07-10T11:54:03Z"
366 // 01234567890123456789
367 // 1
368 if (str.length() > 19)
369 {
370 // timezone must either be unspecified or 'Z' for UTC
371 if ( (pcsz[19])
372 && (pcsz[19] != 'Z')
373 )
374 throw ConfigFileError(this, NULL, N_("Cannot handle ISO timestamp '%s': is not UTC date"), str.c_str());
375
376 int32_t yyyy;
377 uint32_t mm, dd, hh, min, secs;
378 if ( (pcsz[4] == '-')
379 && (pcsz[7] == '-')
380 && (pcsz[10] == 'T')
381 && (pcsz[13] == ':')
382 && (pcsz[16] == ':')
383 )
384 {
385 int rc;
386 if ( (RT_SUCCESS(rc = RTStrToInt32Ex(pcsz, NULL, 0, &yyyy)))
387 // could theoretically be negative but let's assume that nobody
388 // created virtual machines before the Christian era
389 && (RT_SUCCESS(rc = RTStrToUInt32Ex(pcsz + 5, NULL, 0, &mm)))
390 && (RT_SUCCESS(rc = RTStrToUInt32Ex(pcsz + 8, NULL, 0, &dd)))
391 && (RT_SUCCESS(rc = RTStrToUInt32Ex(pcsz + 11, NULL, 0, &hh)))
392 && (RT_SUCCESS(rc = RTStrToUInt32Ex(pcsz + 14, NULL, 0, &min)))
393 && (RT_SUCCESS(rc = RTStrToUInt32Ex(pcsz + 17, NULL, 0, &secs)))
394 )
395 {
396 RTTIME time =
397 {
398 yyyy,
399 (uint8_t)mm,
400 0,
401 0,
402 (uint8_t)dd,
403 (uint8_t)hh,
404 (uint8_t)min,
405 (uint8_t)secs,
406 0,
407 RTTIME_FLAGS_TYPE_UTC,
408 0
409 };
410 if (RTTimeNormalize(&time))
411 if (RTTimeImplode(&timestamp, &time))
412 return;
413 }
414
415 throw ConfigFileError(this, NULL, N_("Cannot parse ISO timestamp '%s': runtime error, %Rra"), str.c_str(), rc);
416 }
417
418 throw ConfigFileError(this, NULL, N_("Cannot parse ISO timestamp '%s': invalid format"), str.c_str());
419 }
420}
421
422/**
423 * Helper to create a string for a RTTIMESPEC for writing out ISO timestamps.
424 * @param stamp
425 * @return
426 */
427com::Utf8Str ConfigFileBase::makeString(const RTTIMESPEC &stamp)
428{
429 RTTIME time;
430 if (!RTTimeExplode(&time, &stamp))
431 throw ConfigFileError(this, NULL, N_("Timespec %lld ms is invalid"), RTTimeSpecGetMilli(&stamp));
432
433 return Utf8StrFmt("%04ld-%02hd-%02hdT%02hd:%02hd:%02hdZ",
434 time.i32Year,
435 (uint16_t)time.u8Month,
436 (uint16_t)time.u8MonthDay,
437 (uint16_t)time.u8Hour,
438 (uint16_t)time.u8Minute,
439 (uint16_t)time.u8Second);
440}
441
442/**
443 * Helper to create a string for a GUID.
444 * @param guid
445 * @return
446 */
447com::Utf8Str ConfigFileBase::makeString(const Guid &guid)
448{
449 Utf8Str str("{");
450 str.append(guid.toString());
451 str.append("}");
452 return str;
453}
454
455/**
456 * Helper method to read in an ExtraData subtree and stores its contents
457 * in the given map of extradata items. Used for both main and machine
458 * extradata (MainConfigFile and MachineConfigFile).
459 * @param elmExtraData
460 * @param map
461 */
462void ConfigFileBase::readExtraData(const xml::ElementNode &elmExtraData,
463 ExtraDataItemsMap &map)
464{
465 xml::NodesLoop nlLevel4(elmExtraData);
466 const xml::ElementNode *pelmExtraDataItem;
467 while ((pelmExtraDataItem = nlLevel4.forAllNodes()))
468 {
469 if (pelmExtraDataItem->nameEquals("ExtraDataItem"))
470 {
471 // <ExtraDataItem name="GUI/LastWindowPostion" value="97,88,981,858"/>
472 Utf8Str strName, strValue;
473 if ( ((pelmExtraDataItem->getAttributeValue("name", strName)))
474 && ((pelmExtraDataItem->getAttributeValue("value", strValue)))
475 )
476 map[strName] = strValue;
477 else
478 throw ConfigFileError(this, pelmExtraDataItem, N_("Required ExtraDataItem/@name or @value attribute is missing"));
479 }
480 }
481}
482
483/**
484 * Reads <USBDeviceFilter> entries from under the given elmDeviceFilters node and
485 * stores them in the given linklist. This is in ConfigFileBase because it's used
486 * from both MainConfigFile (for host filters) and MachineConfigFile (for machine
487 * filters).
488 * @param elmDeviceFilters
489 * @param ll
490 */
491void ConfigFileBase::readUSBDeviceFilters(const xml::ElementNode &elmDeviceFilters,
492 USBDeviceFiltersList &ll)
493{
494 xml::NodesLoop nl1(elmDeviceFilters, "DeviceFilter");
495 const xml::ElementNode *pelmLevel4Child;
496 while ((pelmLevel4Child = nl1.forAllNodes()))
497 {
498 USBDeviceFilter flt;
499 flt.action = USBDeviceFilterAction_Ignore;
500 Utf8Str strAction;
501 if ( (pelmLevel4Child->getAttributeValue("name", flt.strName))
502 && (pelmLevel4Child->getAttributeValue("active", flt.fActive))
503 )
504 {
505 if (!pelmLevel4Child->getAttributeValue("vendorId", flt.strVendorId))
506 pelmLevel4Child->getAttributeValue("vendorid", flt.strVendorId); // used before 1.3
507 if (!pelmLevel4Child->getAttributeValue("productId", flt.strProductId))
508 pelmLevel4Child->getAttributeValue("productid", flt.strProductId); // used before 1.3
509 pelmLevel4Child->getAttributeValue("revision", flt.strRevision);
510 pelmLevel4Child->getAttributeValue("manufacturer", flt.strManufacturer);
511 pelmLevel4Child->getAttributeValue("product", flt.strProduct);
512 if (!pelmLevel4Child->getAttributeValue("serialNumber", flt.strSerialNumber))
513 pelmLevel4Child->getAttributeValue("serialnumber", flt.strSerialNumber); // used before 1.3
514 pelmLevel4Child->getAttributeValue("port", flt.strPort);
515
516 // the next 2 are irrelevant for host USB objects
517 pelmLevel4Child->getAttributeValue("remote", flt.strRemote);
518 pelmLevel4Child->getAttributeValue("maskedInterfaces", flt.ulMaskedInterfaces);
519
520 // action is only used with host USB objects
521 if (pelmLevel4Child->getAttributeValue("action", strAction))
522 {
523 if (strAction == "Ignore")
524 flt.action = USBDeviceFilterAction_Ignore;
525 else if (strAction == "Hold")
526 flt.action = USBDeviceFilterAction_Hold;
527 else
528 throw ConfigFileError(this, pelmLevel4Child, N_("Invalid value '%s' in DeviceFilter/@action attribute"), strAction.c_str());
529 }
530
531 ll.push_back(flt);
532 }
533 }
534}
535
536/**
537 * Creates a new stub xml::Document in the m->pDoc member with the
538 * root "VirtualBox" element set up. This is used by both
539 * MainConfigFile and MachineConfigFile at the beginning of writing
540 * out their XML.
541 *
542 * Before calling this, it is the responsibility of the caller to
543 * set the "sv" member to the required settings version that is to
544 * be written. For newly created files, the settings version will be
545 * the latest (1.9); for files read in from disk earlier, it will be
546 * the settings version indicated in the file. However, this method
547 * will silently make sure that the settings version is always
548 * at least 1.7 and change it if necessary, since there is no write
549 * support for earlier settings versions.
550 */
551void ConfigFileBase::createStubDocument()
552{
553 Assert(m->pDoc == NULL);
554 m->pDoc = new xml::Document;
555
556 m->pelmRoot = m->pDoc->createRootElement("VirtualBox");
557 m->pelmRoot->setAttribute("xmlns", VBOX_XML_NAMESPACE);
558
559 const char *pcszVersion = NULL;
560 switch (m->sv)
561 {
562 case SettingsVersion_v1_8:
563 pcszVersion = "1.8";
564 break;
565
566 case SettingsVersion_v1_9:
567 pcszVersion = "1.9";
568 break;
569
570 case SettingsVersion_v1_10:
571 case SettingsVersion_Future: // can be set if this code runs on XML files that were created by a future version of VBox;
572 // in that case, downgrade to current version when writing since we can't write future versions...
573 pcszVersion = "1.10";
574 m->sv = SettingsVersion_v1_10;
575 break;
576
577 default:
578 // silently upgrade if this is less than 1.7 because that's the oldest we can write
579 pcszVersion = "1.7";
580 m->sv = SettingsVersion_v1_7;
581 break;
582 }
583
584 m->pelmRoot->setAttribute("version", Utf8StrFmt("%s-%s",
585 pcszVersion,
586 VBOX_XML_PLATFORM)); // e.g. "linux"
587
588 // since this gets called before the XML document is actually written out
589 // do this, this is where we must check whether we're upgrading the settings
590 // version and need to make a backup, so the user can go back to an earlier
591 // VirtualBox version and recover his old settings files.
592 if ( (m->svRead != SettingsVersion_Null) // old file exists?
593 && (m->svRead < m->sv) // we're upgrading?
594 )
595 {
596 // compose new filename: strip off trailing ".xml"
597 Utf8Str strFilenameNew = m->strFilename.substr(0, m->strFilename.length() - 4);
598 // and append something likd "-1.3-linux.xml"
599 strFilenameNew.append("-");
600 strFilenameNew.append(m->strSettingsVersionFull); // e.g. "1.3-linux"
601 strFilenameNew.append(".xml");
602
603 RTFileMove(m->strFilename.c_str(),
604 strFilenameNew.c_str(),
605 0); // no RTFILEMOVE_FLAGS_REPLACE
606
607 // do this only once
608 m->svRead = SettingsVersion_Null;
609 }
610}
611
612/**
613 * Creates an <ExtraData> node under the given parent element with
614 * <ExtraDataItem> childern according to the contents of the given
615 * map.
616 * This is in ConfigFileBase because it's used in both MainConfigFile
617 * MachineConfigFile, which both can have extradata.
618 *
619 * @param elmParent
620 * @param me
621 */
622void ConfigFileBase::writeExtraData(xml::ElementNode &elmParent,
623 const ExtraDataItemsMap &me)
624{
625 if (me.size())
626 {
627 xml::ElementNode *pelmExtraData = elmParent.createChild("ExtraData");
628 for (ExtraDataItemsMap::const_iterator it = me.begin();
629 it != me.end();
630 ++it)
631 {
632 const Utf8Str &strName = it->first;
633 const Utf8Str &strValue = it->second;
634 xml::ElementNode *pelmThis = pelmExtraData->createChild("ExtraDataItem");
635 pelmThis->setAttribute("name", strName);
636 pelmThis->setAttribute("value", strValue);
637 }
638 }
639}
640
641/**
642 * Creates <DeviceFilter> nodes under the given parent element according to
643 * the contents of the given USBDeviceFiltersList. This is in ConfigFileBase
644 * because it's used in both MainConfigFile (for host filters) and
645 * MachineConfigFile (for machine filters).
646 *
647 * If fHostMode is true, this means that we're supposed to write filters
648 * for the IHost interface (respect "action", omit "strRemote" and
649 * "ulMaskedInterfaces" in struct USBDeviceFilter).
650 *
651 * @param elmParent
652 * @param ll
653 * @param fHostMode
654 */
655void ConfigFileBase::writeUSBDeviceFilters(xml::ElementNode &elmParent,
656 const USBDeviceFiltersList &ll,
657 bool fHostMode)
658{
659 for (USBDeviceFiltersList::const_iterator it = ll.begin();
660 it != ll.end();
661 ++it)
662 {
663 const USBDeviceFilter &flt = *it;
664 xml::ElementNode *pelmFilter = elmParent.createChild("DeviceFilter");
665 pelmFilter->setAttribute("name", flt.strName);
666 pelmFilter->setAttribute("active", flt.fActive);
667 if (flt.strVendorId.length())
668 pelmFilter->setAttribute("vendorId", flt.strVendorId);
669 if (flt.strProductId.length())
670 pelmFilter->setAttribute("productId", flt.strProductId);
671 if (flt.strRevision.length())
672 pelmFilter->setAttribute("revision", flt.strRevision);
673 if (flt.strManufacturer.length())
674 pelmFilter->setAttribute("manufacturer", flt.strManufacturer);
675 if (flt.strProduct.length())
676 pelmFilter->setAttribute("product", flt.strProduct);
677 if (flt.strSerialNumber.length())
678 pelmFilter->setAttribute("serialNumber", flt.strSerialNumber);
679 if (flt.strPort.length())
680 pelmFilter->setAttribute("port", flt.strPort);
681
682 if (fHostMode)
683 {
684 const char *pcsz =
685 (flt.action == USBDeviceFilterAction_Ignore) ? "Ignore"
686 : /*(flt.action == USBDeviceFilterAction_Hold) ?*/ "Hold";
687 pelmFilter->setAttribute("action", pcsz);
688 }
689 else
690 {
691 if (flt.strRemote.length())
692 pelmFilter->setAttribute("remote", flt.strRemote);
693 if (flt.ulMaskedInterfaces)
694 pelmFilter->setAttribute("maskedInterfaces", flt.ulMaskedInterfaces);
695 }
696 }
697}
698
699/**
700 * Cleans up memory allocated by the internal XML parser. To be called by
701 * descendant classes when they're done analyzing the DOM tree to discard it.
702 */
703void ConfigFileBase::clearDocument()
704{
705 m->cleanup();
706}
707
708/**
709 * Returns true only if the underlying config file exists on disk;
710 * either because the file has been loaded from disk, or it's been written
711 * to disk, or both.
712 * @return
713 */
714bool ConfigFileBase::fileExists()
715{
716 return m->fFileExists;
717}
718
719/**
720 * Copies the base variables from another instance. Used by Machine::saveSettings
721 * so that the settings version does not get lost when a copy of the Machine settings
722 * file is made to see if settings have actually changed.
723 * @param b
724 */
725void ConfigFileBase::copyBaseFrom(const ConfigFileBase &b)
726{
727 m->copyFrom(*b.m);
728}
729
730////////////////////////////////////////////////////////////////////////////////
731//
732// Structures shared between Machine XML and VirtualBox.xml
733//
734////////////////////////////////////////////////////////////////////////////////
735
736/**
737 * Comparison operator. This gets called from MachineConfigFile::operator==,
738 * which in turn gets called from Machine::saveSettings to figure out whether
739 * machine settings have really changed and thus need to be written out to disk.
740 */
741bool USBDeviceFilter::operator==(const USBDeviceFilter &u) const
742{
743 return ( (this == &u)
744 || ( (strName == u.strName)
745 && (fActive == u.fActive)
746 && (strVendorId == u.strVendorId)
747 && (strProductId == u.strProductId)
748 && (strRevision == u.strRevision)
749 && (strManufacturer == u.strManufacturer)
750 && (strProduct == u.strProduct)
751 && (strSerialNumber == u.strSerialNumber)
752 && (strPort == u.strPort)
753 && (action == u.action)
754 && (strRemote == u.strRemote)
755 && (ulMaskedInterfaces == u.ulMaskedInterfaces)
756 )
757 );
758}
759
760////////////////////////////////////////////////////////////////////////////////
761//
762// MainConfigFile
763//
764////////////////////////////////////////////////////////////////////////////////
765
766/**
767 * Reads one <MachineEntry> from the main VirtualBox.xml file.
768 * @param elmMachineRegistry
769 */
770void MainConfigFile::readMachineRegistry(const xml::ElementNode &elmMachineRegistry)
771{
772 // <MachineEntry uuid="{ xxx }" src=" xxx "/>
773 xml::NodesLoop nl1(elmMachineRegistry);
774 const xml::ElementNode *pelmChild1;
775 while ((pelmChild1 = nl1.forAllNodes()))
776 {
777 if (pelmChild1->nameEquals("MachineEntry"))
778 {
779 MachineRegistryEntry mre;
780 Utf8Str strUUID;
781 if ( ((pelmChild1->getAttributeValue("uuid", strUUID)))
782 && ((pelmChild1->getAttributeValue("src", mre.strSettingsFile)))
783 )
784 {
785 parseUUID(mre.uuid, strUUID);
786 llMachines.push_back(mre);
787 }
788 else
789 throw ConfigFileError(this, pelmChild1, N_("Required MachineEntry/@uuid or @src attribute is missing"));
790 }
791 }
792}
793
794/**
795 * Reads a media registry entry from the main VirtualBox.xml file.
796 *
797 * Whereas the current media registry code is fairly straightforward, it was quite a mess
798 * with settings format before 1.4 (VirtualBox 2.0 used settings format 1.3). The elements
799 * in the media registry were much more inconsistent, and different elements were used
800 * depending on the type of device and image.
801 *
802 * @param t
803 * @param elmMedium
804 * @param llMedia
805 */
806void MainConfigFile::readMedium(MediaType t,
807 const xml::ElementNode &elmMedium, // HardDisk node if root; if recursing,
808 // child HardDisk node or DiffHardDisk node for pre-1.4
809 MediaList &llMedia) // list to append medium to (root disk or child list)
810{
811 // <HardDisk uuid="{5471ecdb-1ddb-4012-a801-6d98e226868b}" location="/mnt/innotek-unix/vdis/Windows XP.vdi" format="VDI" type="Normal">
812 settings::Medium med;
813 Utf8Str strUUID;
814 if (!(elmMedium.getAttributeValue("uuid", strUUID)))
815 throw ConfigFileError(this, &elmMedium, N_("Required %s/@uuid attribute is missing"), elmMedium.getName());
816
817 parseUUID(med.uuid, strUUID);
818
819 bool fNeedsLocation = true;
820
821 if (t == HardDisk)
822 {
823 if (m->sv < SettingsVersion_v1_4)
824 {
825 // here the system is:
826 // <HardDisk uuid="{....}" type="normal">
827 // <VirtualDiskImage filePath="/path/to/xxx.vdi"/>
828 // </HardDisk>
829
830 fNeedsLocation = false;
831 bool fNeedsFilePath = true;
832 const xml::ElementNode *pelmImage;
833 if ((pelmImage = elmMedium.findChildElement("VirtualDiskImage")))
834 med.strFormat = "VDI";
835 else if ((pelmImage = elmMedium.findChildElement("VMDKImage")))
836 med.strFormat = "VMDK";
837 else if ((pelmImage = elmMedium.findChildElement("VHDImage")))
838 med.strFormat = "VHD";
839 else if ((pelmImage = elmMedium.findChildElement("ISCSIHardDisk")))
840 {
841 med.strFormat = "iSCSI";
842
843 fNeedsFilePath = false;
844 // location is special here: current settings specify an "iscsi://user@server:port/target/lun"
845 // string for the location and also have several disk properties for these, whereas this used
846 // to be hidden in several sub-elements before 1.4, so compose a location string and set up
847 // the properties:
848 med.strLocation = "iscsi://";
849 Utf8Str strUser, strServer, strPort, strTarget, strLun;
850 if (pelmImage->getAttributeValue("userName", strUser))
851 {
852 med.strLocation.append(strUser);
853 med.strLocation.append("@");
854 }
855 Utf8Str strServerAndPort;
856 if (pelmImage->getAttributeValue("server", strServer))
857 {
858 strServerAndPort = strServer;
859 }
860 if (pelmImage->getAttributeValue("port", strPort))
861 {
862 if (strServerAndPort.length())
863 strServerAndPort.append(":");
864 strServerAndPort.append(strPort);
865 }
866 med.strLocation.append(strServerAndPort);
867 if (pelmImage->getAttributeValue("target", strTarget))
868 {
869 med.strLocation.append("/");
870 med.strLocation.append(strTarget);
871 }
872 if (pelmImage->getAttributeValue("lun", strLun))
873 {
874 med.strLocation.append("/");
875 med.strLocation.append(strLun);
876 }
877
878 if (strServer.length() && strPort.length())
879 med.properties["TargetAddress"] = strServerAndPort;
880 if (strTarget.length())
881 med.properties["TargetName"] = strTarget;
882 if (strUser.length())
883 med.properties["InitiatorUsername"] = strUser;
884 Utf8Str strPassword;
885 if (pelmImage->getAttributeValue("password", strPassword))
886 med.properties["InitiatorSecret"] = strPassword;
887 if (strLun.length())
888 med.properties["LUN"] = strLun;
889 }
890 else if ((pelmImage = elmMedium.findChildElement("CustomHardDisk")))
891 {
892 fNeedsFilePath = false;
893 fNeedsLocation = true;
894 // also requires @format attribute, which will be queried below
895 }
896 else
897 throw ConfigFileError(this, &elmMedium, N_("Required %s/VirtualDiskImage element is missing"), elmMedium.getName());
898
899 if (fNeedsFilePath)
900 if (!(pelmImage->getAttributeValue("filePath", med.strLocation)))
901 throw ConfigFileError(this, &elmMedium, N_("Required %s/@filePath attribute is missing"), elmMedium.getName());
902 }
903
904 if (med.strFormat.isEmpty()) // not set with 1.4 format above, or 1.4 Custom format?
905 if (!(elmMedium.getAttributeValue("format", med.strFormat)))
906 throw ConfigFileError(this, &elmMedium, N_("Required %s/@format attribute is missing"), elmMedium.getName());
907
908 if (!(elmMedium.getAttributeValue("autoReset", med.fAutoReset)))
909 med.fAutoReset = false;
910
911 Utf8Str strType;
912 if ((elmMedium.getAttributeValue("type", strType)))
913 {
914 // pre-1.4 used lower case, so make this case-insensitive
915 strType.toUpper();
916 if (strType == "NORMAL")
917 med.hdType = MediumType_Normal;
918 else if (strType == "IMMUTABLE")
919 med.hdType = MediumType_Immutable;
920 else if (strType == "WRITETHROUGH")
921 med.hdType = MediumType_Writethrough;
922 else
923 throw ConfigFileError(this, &elmMedium, N_("HardDisk/@type attribute must be one of Normal, Immutable or Writethrough"));
924 }
925 }
926 else if (m->sv < SettingsVersion_v1_4)
927 {
928 // DVD and floppy images before 1.4 had "src" attribute instead of "location"
929 if (!(elmMedium.getAttributeValue("src", med.strLocation)))
930 throw ConfigFileError(this, &elmMedium, N_("Required %s/@src attribute is missing"), elmMedium.getName());
931
932 fNeedsLocation = false;
933 }
934
935 if (fNeedsLocation)
936 // current files and 1.4 CustomHardDisk elements must have a location attribute
937 if (!(elmMedium.getAttributeValue("location", med.strLocation)))
938 throw ConfigFileError(this, &elmMedium, N_("Required %s/@location attribute is missing"), elmMedium.getName());
939
940 elmMedium.getAttributeValue("Description", med.strDescription); // optional
941
942 // recurse to handle children
943 xml::NodesLoop nl2(elmMedium);
944 const xml::ElementNode *pelmHDChild;
945 while ((pelmHDChild = nl2.forAllNodes()))
946 {
947 if ( t == HardDisk
948 && ( pelmHDChild->nameEquals("HardDisk")
949 || ( (m->sv < SettingsVersion_v1_4)
950 && (pelmHDChild->nameEquals("DiffHardDisk"))
951 )
952 )
953 )
954 // recurse with this element and push the child onto our current children list
955 readMedium(t,
956 *pelmHDChild,
957 med.llChildren);
958 else if (pelmHDChild->nameEquals("Property"))
959 {
960 Utf8Str strPropName, strPropValue;
961 if ( (pelmHDChild->getAttributeValue("name", strPropName))
962 && (pelmHDChild->getAttributeValue("value", strPropValue))
963 )
964 med.properties[strPropName] = strPropValue;
965 else
966 throw ConfigFileError(this, pelmHDChild, N_("Required HardDisk/Property/@name or @value attribute is missing"));
967 }
968 }
969
970 llMedia.push_back(med);
971}
972
973/**
974 * Reads in the entire <MediaRegistry> chunk. For pre-1.4 files, this gets called
975 * with the <DiskRegistry> chunk instead.
976 * @param elmMediaRegistry
977 */
978void MainConfigFile::readMediaRegistry(const xml::ElementNode &elmMediaRegistry)
979{
980 xml::NodesLoop nl1(elmMediaRegistry);
981 const xml::ElementNode *pelmChild1;
982 while ((pelmChild1 = nl1.forAllNodes()))
983 {
984 MediaType t = Error;
985 if (pelmChild1->nameEquals("HardDisks"))
986 t = HardDisk;
987 else if (pelmChild1->nameEquals("DVDImages"))
988 t = DVDImage;
989 else if (pelmChild1->nameEquals("FloppyImages"))
990 t = FloppyImage;
991 else
992 continue;
993
994 xml::NodesLoop nl2(*pelmChild1);
995 const xml::ElementNode *pelmMedium;
996 while ((pelmMedium = nl2.forAllNodes()))
997 {
998 if ( t == HardDisk
999 && (pelmMedium->nameEquals("HardDisk"))
1000 )
1001 readMedium(t,
1002 *pelmMedium,
1003 llHardDisks); // list to append hard disk data to: the root list
1004 else if ( t == DVDImage
1005 && (pelmMedium->nameEquals("Image"))
1006 )
1007 readMedium(t,
1008 *pelmMedium,
1009 llDvdImages); // list to append dvd images to: the root list
1010 else if ( t == FloppyImage
1011 && (pelmMedium->nameEquals("Image"))
1012 )
1013 readMedium(t,
1014 *pelmMedium,
1015 llFloppyImages); // list to append floppy images to: the root list
1016 }
1017 }
1018}
1019
1020/**
1021 * Reads in the <DHCPServers> chunk.
1022 * @param elmDHCPServers
1023 */
1024void MainConfigFile::readDHCPServers(const xml::ElementNode &elmDHCPServers)
1025{
1026 xml::NodesLoop nl1(elmDHCPServers);
1027 const xml::ElementNode *pelmServer;
1028 while ((pelmServer = nl1.forAllNodes()))
1029 {
1030 if (pelmServer->nameEquals("DHCPServer"))
1031 {
1032 DHCPServer srv;
1033 if ( (pelmServer->getAttributeValue("networkName", srv.strNetworkName))
1034 && (pelmServer->getAttributeValue("IPAddress", srv.strIPAddress))
1035 && (pelmServer->getAttributeValue("networkMask", srv.strIPNetworkMask))
1036 && (pelmServer->getAttributeValue("lowerIP", srv.strIPLower))
1037 && (pelmServer->getAttributeValue("upperIP", srv.strIPUpper))
1038 && (pelmServer->getAttributeValue("enabled", srv.fEnabled))
1039 )
1040 llDhcpServers.push_back(srv);
1041 else
1042 throw ConfigFileError(this, pelmServer, N_("Required DHCPServer/@networkName, @IPAddress, @networkMask, @lowerIP, @upperIP or @enabled attribute is missing"));
1043 }
1044 }
1045}
1046
1047/**
1048 * Constructor.
1049 *
1050 * If pstrFilename is != NULL, this reads the given settings file into the member
1051 * variables and various substructures and lists. Otherwise, the member variables
1052 * are initialized with default values.
1053 *
1054 * Throws variants of xml::Error for I/O, XML and logical content errors, which
1055 * the caller should catch; if this constructor does not throw, then the member
1056 * variables contain meaningful values (either from the file or defaults).
1057 *
1058 * @param strFilename
1059 */
1060MainConfigFile::MainConfigFile(const Utf8Str *pstrFilename)
1061 : ConfigFileBase(pstrFilename)
1062{
1063 if (pstrFilename)
1064 {
1065 // the ConfigFileBase constructor has loaded the XML file, so now
1066 // we need only analyze what is in there
1067 xml::NodesLoop nlRootChildren(*m->pelmRoot);
1068 const xml::ElementNode *pelmRootChild;
1069 while ((pelmRootChild = nlRootChildren.forAllNodes()))
1070 {
1071 if (pelmRootChild->nameEquals("Global"))
1072 {
1073 xml::NodesLoop nlGlobalChildren(*pelmRootChild);
1074 const xml::ElementNode *pelmGlobalChild;
1075 while ((pelmGlobalChild = nlGlobalChildren.forAllNodes()))
1076 {
1077 if (pelmGlobalChild->nameEquals("SystemProperties"))
1078 {
1079 pelmGlobalChild->getAttributeValue("defaultMachineFolder", systemProperties.strDefaultMachineFolder);
1080 if (!pelmGlobalChild->getAttributeValue("defaultHardDiskFolder", systemProperties.strDefaultHardDiskFolder))
1081 // pre-1.4 used @defaultVDIFolder instead
1082 pelmGlobalChild->getAttributeValue("defaultVDIFolder", systemProperties.strDefaultHardDiskFolder);
1083 pelmGlobalChild->getAttributeValue("defaultHardDiskFormat", systemProperties.strDefaultHardDiskFormat);
1084 pelmGlobalChild->getAttributeValue("remoteDisplayAuthLibrary", systemProperties.strRemoteDisplayAuthLibrary);
1085 pelmGlobalChild->getAttributeValue("webServiceAuthLibrary", systemProperties.strWebServiceAuthLibrary);
1086 pelmGlobalChild->getAttributeValue("LogHistoryCount", systemProperties.ulLogHistoryCount);
1087 }
1088 else if (pelmGlobalChild->nameEquals("ExtraData"))
1089 readExtraData(*pelmGlobalChild, mapExtraDataItems);
1090 else if (pelmGlobalChild->nameEquals("MachineRegistry"))
1091 readMachineRegistry(*pelmGlobalChild);
1092 else if ( (pelmGlobalChild->nameEquals("MediaRegistry"))
1093 || ( (m->sv < SettingsVersion_v1_4)
1094 && (pelmGlobalChild->nameEquals("DiskRegistry"))
1095 )
1096 )
1097 readMediaRegistry(*pelmGlobalChild);
1098 else if (pelmGlobalChild->nameEquals("NetserviceRegistry"))
1099 {
1100 xml::NodesLoop nlLevel4(*pelmGlobalChild);
1101 const xml::ElementNode *pelmLevel4Child;
1102 while ((pelmLevel4Child = nlLevel4.forAllNodes()))
1103 {
1104 if (pelmLevel4Child->nameEquals("DHCPServers"))
1105 readDHCPServers(*pelmLevel4Child);
1106 }
1107 }
1108 else if (pelmGlobalChild->nameEquals("USBDeviceFilters"))
1109 readUSBDeviceFilters(*pelmGlobalChild, host.llUSBDeviceFilters);
1110 }
1111 } // end if (pelmRootChild->nameEquals("Global"))
1112 }
1113
1114 clearDocument();
1115 }
1116
1117 // DHCP servers were introduced with settings version 1.7; if we're loading
1118 // from an older version OR this is a fresh install, then add one DHCP server
1119 // with default settings
1120 if ( (!llDhcpServers.size())
1121 && ( (!pstrFilename) // empty VirtualBox.xml file
1122 || (m->sv < SettingsVersion_v1_7) // upgrading from before 1.7
1123 )
1124 )
1125 {
1126 DHCPServer srv;
1127 srv.strNetworkName =
1128#ifdef RT_OS_WINDOWS
1129 "HostInterfaceNetworking-VirtualBox Host-Only Ethernet Adapter";
1130#else
1131 "HostInterfaceNetworking-vboxnet0";
1132#endif
1133 srv.strIPAddress = "192.168.56.100";
1134 srv.strIPNetworkMask = "255.255.255.0";
1135 srv.strIPLower = "192.168.56.101";
1136 srv.strIPUpper = "192.168.56.254";
1137 srv.fEnabled = true;
1138 llDhcpServers.push_back(srv);
1139 }
1140}
1141
1142/**
1143 * Creates a single <HardDisk> element for the given Medium structure
1144 * and recurses to write the child hard disks underneath. Called from
1145 * MainConfigFile::write().
1146 *
1147 * @param elmMedium
1148 * @param m
1149 * @param level
1150 */
1151void MainConfigFile::writeHardDisk(xml::ElementNode &elmMedium,
1152 const Medium &mdm,
1153 uint32_t level) // 0 for "root" call, incremented with each recursion
1154{
1155 xml::ElementNode *pelmHardDisk = elmMedium.createChild("HardDisk");
1156 pelmHardDisk->setAttribute("uuid", makeString(mdm.uuid));
1157 pelmHardDisk->setAttribute("location", mdm.strLocation);
1158 pelmHardDisk->setAttribute("format", mdm.strFormat);
1159 if (mdm.fAutoReset)
1160 pelmHardDisk->setAttribute("autoReset", mdm.fAutoReset);
1161 if (mdm.strDescription.length())
1162 pelmHardDisk->setAttribute("Description", mdm.strDescription);
1163
1164 for (PropertiesMap::const_iterator it = mdm.properties.begin();
1165 it != mdm.properties.end();
1166 ++it)
1167 {
1168 xml::ElementNode *pelmProp = pelmHardDisk->createChild("Property");
1169 pelmProp->setAttribute("name", it->first);
1170 pelmProp->setAttribute("value", it->second);
1171 }
1172
1173 // only for base hard disks, save the type
1174 if (level == 0)
1175 {
1176 const char *pcszType =
1177 mdm.hdType == MediumType_Normal ? "Normal" :
1178 mdm.hdType == MediumType_Immutable ? "Immutable" :
1179 /*mdm.hdType == MediumType_Writethrough ?*/ "Writethrough";
1180 pelmHardDisk->setAttribute("type", pcszType);
1181 }
1182
1183 for (MediaList::const_iterator it = mdm.llChildren.begin();
1184 it != mdm.llChildren.end();
1185 ++it)
1186 {
1187 // recurse for children
1188 writeHardDisk(*pelmHardDisk, // parent
1189 *it, // settings::Medium
1190 ++level); // recursion level
1191 }
1192}
1193
1194/**
1195 * Called from the IVirtualBox interface to write out VirtualBox.xml. This
1196 * builds an XML DOM tree and writes it out to disk.
1197 */
1198void MainConfigFile::write(const com::Utf8Str strFilename)
1199{
1200 m->strFilename = strFilename;
1201 createStubDocument();
1202
1203 xml::ElementNode *pelmGlobal = m->pelmRoot->createChild("Global");
1204
1205 writeExtraData(*pelmGlobal, mapExtraDataItems);
1206
1207 xml::ElementNode *pelmMachineRegistry = pelmGlobal->createChild("MachineRegistry");
1208 for (MachinesRegistry::const_iterator it = llMachines.begin();
1209 it != llMachines.end();
1210 ++it)
1211 {
1212 // <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"/>
1213 const MachineRegistryEntry &mre = *it;
1214 xml::ElementNode *pelmMachineEntry = pelmMachineRegistry->createChild("MachineEntry");
1215 pelmMachineEntry->setAttribute("uuid", makeString(mre.uuid));
1216 pelmMachineEntry->setAttribute("src", mre.strSettingsFile);
1217 }
1218
1219 xml::ElementNode *pelmMediaRegistry = pelmGlobal->createChild("MediaRegistry");
1220
1221 xml::ElementNode *pelmHardDisks = pelmMediaRegistry->createChild("HardDisks");
1222 for (MediaList::const_iterator it = llHardDisks.begin();
1223 it != llHardDisks.end();
1224 ++it)
1225 {
1226 writeHardDisk(*pelmHardDisks, *it, 0);
1227 }
1228
1229 xml::ElementNode *pelmDVDImages = pelmMediaRegistry->createChild("DVDImages");
1230 for (MediaList::const_iterator it = llDvdImages.begin();
1231 it != llDvdImages.end();
1232 ++it)
1233 {
1234 const Medium &mdm = *it;
1235 xml::ElementNode *pelmMedium = pelmDVDImages->createChild("Image");
1236 pelmMedium->setAttribute("uuid", makeString(mdm.uuid));
1237 pelmMedium->setAttribute("location", mdm.strLocation);
1238 if (mdm.strDescription.length())
1239 pelmMedium->setAttribute("Description", mdm.strDescription);
1240 }
1241
1242 xml::ElementNode *pelmFloppyImages = pelmMediaRegistry->createChild("FloppyImages");
1243 for (MediaList::const_iterator it = llFloppyImages.begin();
1244 it != llFloppyImages.end();
1245 ++it)
1246 {
1247 const Medium &mdm = *it;
1248 xml::ElementNode *pelmMedium = pelmFloppyImages->createChild("Image");
1249 pelmMedium->setAttribute("uuid", makeString(mdm.uuid));
1250 pelmMedium->setAttribute("location", mdm.strLocation);
1251 if (mdm.strDescription.length())
1252 pelmMedium->setAttribute("Description", mdm.strDescription);
1253 }
1254
1255 xml::ElementNode *pelmNetserviceRegistry = pelmGlobal->createChild("NetserviceRegistry");
1256 xml::ElementNode *pelmDHCPServers = pelmNetserviceRegistry->createChild("DHCPServers");
1257 for (DHCPServersList::const_iterator it = llDhcpServers.begin();
1258 it != llDhcpServers.end();
1259 ++it)
1260 {
1261 const DHCPServer &d = *it;
1262 xml::ElementNode *pelmThis = pelmDHCPServers->createChild("DHCPServer");
1263 pelmThis->setAttribute("networkName", d.strNetworkName);
1264 pelmThis->setAttribute("IPAddress", d.strIPAddress);
1265 pelmThis->setAttribute("networkMask", d.strIPNetworkMask);
1266 pelmThis->setAttribute("lowerIP", d.strIPLower);
1267 pelmThis->setAttribute("upperIP", d.strIPUpper);
1268 pelmThis->setAttribute("enabled", (d.fEnabled) ? 1 : 0); // too bad we chose 1 vs. 0 here
1269 }
1270
1271 xml::ElementNode *pelmSysProps = pelmGlobal->createChild("SystemProperties");
1272 if (systemProperties.strDefaultMachineFolder.length())
1273 pelmSysProps->setAttribute("defaultMachineFolder", systemProperties.strDefaultMachineFolder);
1274 if (systemProperties.strDefaultHardDiskFolder.length())
1275 pelmSysProps->setAttribute("defaultHardDiskFolder", systemProperties.strDefaultHardDiskFolder);
1276 if (systemProperties.strDefaultHardDiskFormat.length())
1277 pelmSysProps->setAttribute("defaultHardDiskFormat", systemProperties.strDefaultHardDiskFormat);
1278 if (systemProperties.strRemoteDisplayAuthLibrary.length())
1279 pelmSysProps->setAttribute("remoteDisplayAuthLibrary", systemProperties.strRemoteDisplayAuthLibrary);
1280 if (systemProperties.strWebServiceAuthLibrary.length())
1281 pelmSysProps->setAttribute("webServiceAuthLibrary", systemProperties.strWebServiceAuthLibrary);
1282 pelmSysProps->setAttribute("LogHistoryCount", systemProperties.ulLogHistoryCount);
1283
1284 writeUSBDeviceFilters(*pelmGlobal->createChild("USBDeviceFilters"),
1285 host.llUSBDeviceFilters,
1286 true); // fHostMode
1287
1288 // now go write the XML
1289 xml::XmlFileWriter writer(*m->pDoc);
1290 writer.write(m->strFilename.c_str());
1291
1292 m->fFileExists = true;
1293
1294 clearDocument();
1295}
1296
1297////////////////////////////////////////////////////////////////////////////////
1298//
1299// Machine XML structures
1300//
1301////////////////////////////////////////////////////////////////////////////////
1302
1303/**
1304 * Comparison operator. This gets called from MachineConfigFile::operator==,
1305 * which in turn gets called from Machine::saveSettings to figure out whether
1306 * machine settings have really changed and thus need to be written out to disk.
1307 */
1308bool VRDPSettings::operator==(const VRDPSettings& v) const
1309{
1310 return ( (this == &v)
1311 || ( (fEnabled == v.fEnabled)
1312 && (strPort == v.strPort)
1313 && (strNetAddress == v.strNetAddress)
1314 && (authType == v.authType)
1315 && (ulAuthTimeout == v.ulAuthTimeout)
1316 && (fAllowMultiConnection == v.fAllowMultiConnection)
1317 && (fReuseSingleConnection == v.fReuseSingleConnection)
1318 )
1319 );
1320}
1321
1322/**
1323 * Comparison operator. This gets called from MachineConfigFile::operator==,
1324 * which in turn gets called from Machine::saveSettings to figure out whether
1325 * machine settings have really changed and thus need to be written out to disk.
1326 */
1327bool BIOSSettings::operator==(const BIOSSettings &d) const
1328{
1329 return ( (this == &d)
1330 || ( fACPIEnabled == d.fACPIEnabled
1331 && fIOAPICEnabled == d.fIOAPICEnabled
1332 && fLogoFadeIn == d.fLogoFadeIn
1333 && fLogoFadeOut == d.fLogoFadeOut
1334 && ulLogoDisplayTime == d.ulLogoDisplayTime
1335 && strLogoImagePath == d.strLogoImagePath
1336 && biosBootMenuMode == d.biosBootMenuMode
1337 && fPXEDebugEnabled == d.fPXEDebugEnabled
1338 && llTimeOffset == d.llTimeOffset)
1339 );
1340}
1341
1342/**
1343 * Comparison operator. This gets called from MachineConfigFile::operator==,
1344 * which in turn gets called from Machine::saveSettings to figure out whether
1345 * machine settings have really changed and thus need to be written out to disk.
1346 */
1347bool USBController::operator==(const USBController &u) const
1348{
1349 return ( (this == &u)
1350 || ( (fEnabled == u.fEnabled)
1351 && (fEnabledEHCI == u.fEnabledEHCI)
1352 && (llDeviceFilters == u.llDeviceFilters)
1353 )
1354 );
1355}
1356
1357/**
1358 * Comparison operator. This gets called from MachineConfigFile::operator==,
1359 * which in turn gets called from Machine::saveSettings to figure out whether
1360 * machine settings have really changed and thus need to be written out to disk.
1361 */
1362bool NetworkAdapter::operator==(const NetworkAdapter &n) const
1363{
1364 return ( (this == &n)
1365 || ( (ulSlot == n.ulSlot)
1366 && (type == n.type)
1367 && (fEnabled == n.fEnabled)
1368 && (strMACAddress == n.strMACAddress)
1369 && (fCableConnected == n.fCableConnected)
1370 && (ulLineSpeed == n.ulLineSpeed)
1371 && (fTraceEnabled == n.fTraceEnabled)
1372 && (strTraceFile == n.strTraceFile)
1373 && (mode == n.mode)
1374 && (strName == n.strName)
1375 )
1376 );
1377}
1378
1379/**
1380 * Comparison operator. This gets called from MachineConfigFile::operator==,
1381 * which in turn gets called from Machine::saveSettings to figure out whether
1382 * machine settings have really changed and thus need to be written out to disk.
1383 */
1384bool SerialPort::operator==(const SerialPort &s) const
1385{
1386 return ( (this == &s)
1387 || ( (ulSlot == s.ulSlot)
1388 && (fEnabled == s.fEnabled)
1389 && (ulIOBase == s.ulIOBase)
1390 && (ulIRQ == s.ulIRQ)
1391 && (portMode == s.portMode)
1392 && (strPath == s.strPath)
1393 && (fServer == s.fServer)
1394 )
1395 );
1396}
1397
1398/**
1399 * Comparison operator. This gets called from MachineConfigFile::operator==,
1400 * which in turn gets called from Machine::saveSettings to figure out whether
1401 * machine settings have really changed and thus need to be written out to disk.
1402 */
1403bool ParallelPort::operator==(const ParallelPort &s) const
1404{
1405 return ( (this == &s)
1406 || ( (ulSlot == s.ulSlot)
1407 && (fEnabled == s.fEnabled)
1408 && (ulIOBase == s.ulIOBase)
1409 && (ulIRQ == s.ulIRQ)
1410 && (strPath == s.strPath)
1411 )
1412 );
1413}
1414
1415/**
1416 * Comparison operator. This gets called from MachineConfigFile::operator==,
1417 * which in turn gets called from Machine::saveSettings to figure out whether
1418 * machine settings have really changed and thus need to be written out to disk.
1419 */
1420bool SharedFolder::operator==(const SharedFolder &g) const
1421{
1422 return ( (this == &g)
1423 || ( (strName == g.strName)
1424 && (strHostPath == g.strHostPath)
1425 && (fWritable == g.fWritable)
1426 )
1427 );
1428}
1429
1430/**
1431 * Comparison operator. This gets called from MachineConfigFile::operator==,
1432 * which in turn gets called from Machine::saveSettings to figure out whether
1433 * machine settings have really changed and thus need to be written out to disk.
1434 */
1435bool GuestProperty::operator==(const GuestProperty &g) const
1436{
1437 return ( (this == &g)
1438 || ( (strName == g.strName)
1439 && (strValue == g.strValue)
1440 && (timestamp == g.timestamp)
1441 && (strFlags == g.strFlags)
1442 )
1443 );
1444}
1445
1446// use a define for the platform-dependent default value of
1447// hwvirt exclusivity, since we'll need to check that value
1448// in bumpSettingsVersionIfNeeded()
1449#if defined(RT_OS_DARWIN) || defined(RT_OS_WINDOWS)
1450 #define HWVIRTEXCLUSIVEDEFAULT false
1451#else
1452 #define HWVIRTEXCLUSIVEDEFAULT true
1453#endif
1454
1455/**
1456 * Hardware struct constructor.
1457 */
1458Hardware::Hardware()
1459 : strVersion("1"),
1460 fHardwareVirt(true),
1461 fHardwareVirtExclusive(HWVIRTEXCLUSIVEDEFAULT),
1462 fNestedPaging(true),
1463 fLargePages(false),
1464 fVPID(true),
1465 fSyntheticCpu(false),
1466 fPAE(false),
1467 cCPUs(1),
1468 fCpuHotPlug(false),
1469 fHpetEnabled(false),
1470 ulMemorySizeMB((uint32_t)-1),
1471 ulVRAMSizeMB(8),
1472 cMonitors(1),
1473 fAccelerate3D(false),
1474 fAccelerate2DVideo(false),
1475 firmwareType(FirmwareType_BIOS),
1476 pointingHidType(PointingHidType_PS2Mouse),
1477 keyboardHidType(KeyboardHidType_PS2Keyboard),
1478 clipboardMode(ClipboardMode_Bidirectional),
1479 ulMemoryBalloonSize(0),
1480 ulStatisticsUpdateInterval(0)
1481{
1482 mapBootOrder[0] = DeviceType_Floppy;
1483 mapBootOrder[1] = DeviceType_DVD;
1484 mapBootOrder[2] = DeviceType_HardDisk;
1485
1486 /* The default value for PAE depends on the host:
1487 * - 64 bits host -> always true
1488 * - 32 bits host -> true for Windows & Darwin (masked off if the host cpu doesn't support it anyway)
1489 */
1490#if HC_ARCH_BITS == 64 || defined(RT_OS_WINDOWS) || defined(RT_OS_DARWIN)
1491 fPAE = true;
1492#endif
1493}
1494
1495/**
1496 * Comparison operator. This gets called from MachineConfigFile::operator==,
1497 * which in turn gets called from Machine::saveSettings to figure out whether
1498 * machine settings have really changed and thus need to be written out to disk.
1499 */
1500bool Hardware::operator==(const Hardware& h) const
1501{
1502 return ( (this == &h)
1503 || ( (strVersion == h.strVersion)
1504 && (uuid == h.uuid)
1505 && (fHardwareVirt == h.fHardwareVirt)
1506 && (fHardwareVirtExclusive == h.fHardwareVirtExclusive)
1507 && (fNestedPaging == h.fNestedPaging)
1508 && (fLargePages == h.fLargePages)
1509 && (fVPID == h.fVPID)
1510 && (fSyntheticCpu == h.fSyntheticCpu)
1511 && (fPAE == h.fPAE)
1512 && (cCPUs == h.cCPUs)
1513 && (fCpuHotPlug == h.fCpuHotPlug)
1514 && (fHpetEnabled == h.fHpetEnabled)
1515 && (llCpus == h.llCpus)
1516 && (llCpuIdLeafs == h.llCpuIdLeafs)
1517 && (ulMemorySizeMB == h.ulMemorySizeMB)
1518 && (mapBootOrder == h.mapBootOrder)
1519 && (ulVRAMSizeMB == h.ulVRAMSizeMB)
1520 && (cMonitors == h.cMonitors)
1521 && (fAccelerate3D == h.fAccelerate3D)
1522 && (fAccelerate2DVideo == h.fAccelerate2DVideo)
1523 && (firmwareType == h.firmwareType)
1524 && (pointingHidType == h.pointingHidType)
1525 && (keyboardHidType == h.keyboardHidType)
1526 && (vrdpSettings == h.vrdpSettings)
1527 && (biosSettings == h.biosSettings)
1528 && (usbController == h.usbController)
1529 && (llNetworkAdapters == h.llNetworkAdapters)
1530 && (llSerialPorts == h.llSerialPorts)
1531 && (llParallelPorts == h.llParallelPorts)
1532 && (audioAdapter == h.audioAdapter)
1533 && (llSharedFolders == h.llSharedFolders)
1534 && (clipboardMode == h.clipboardMode)
1535 && (ulMemoryBalloonSize == h.ulMemoryBalloonSize)
1536 && (ulStatisticsUpdateInterval == h.ulStatisticsUpdateInterval)
1537 && (llGuestProperties == h.llGuestProperties)
1538 && (strNotificationPatterns == h.strNotificationPatterns)
1539 )
1540 );
1541}
1542
1543/**
1544 * Comparison operator. This gets called from MachineConfigFile::operator==,
1545 * which in turn gets called from Machine::saveSettings to figure out whether
1546 * machine settings have really changed and thus need to be written out to disk.
1547 */
1548bool AttachedDevice::operator==(const AttachedDevice &a) const
1549{
1550 return ( (this == &a)
1551 || ( (deviceType == a.deviceType)
1552 && (fPassThrough == a.fPassThrough)
1553 && (lPort == a.lPort)
1554 && (lDevice == a.lDevice)
1555 && (uuid == a.uuid)
1556 && (strHostDriveSrc == a.strHostDriveSrc)
1557 )
1558 );
1559}
1560
1561/**
1562 * Comparison operator. This gets called from MachineConfigFile::operator==,
1563 * which in turn gets called from Machine::saveSettings to figure out whether
1564 * machine settings have really changed and thus need to be written out to disk.
1565 */
1566bool StorageController::operator==(const StorageController &s) const
1567{
1568 return ( (this == &s)
1569 || ( (strName == s.strName)
1570 && (storageBus == s.storageBus)
1571 && (controllerType == s.controllerType)
1572 && (ulPortCount == s.ulPortCount)
1573 && (ulInstance == s.ulInstance)
1574 && (lIDE0MasterEmulationPort == s.lIDE0MasterEmulationPort)
1575 && (lIDE0SlaveEmulationPort == s.lIDE0SlaveEmulationPort)
1576 && (lIDE1MasterEmulationPort == s.lIDE1MasterEmulationPort)
1577 && (lIDE1SlaveEmulationPort == s.lIDE1SlaveEmulationPort)
1578 && (llAttachedDevices == s.llAttachedDevices)
1579 )
1580 );
1581}
1582
1583/**
1584 * Comparison operator. This gets called from MachineConfigFile::operator==,
1585 * which in turn gets called from Machine::saveSettings to figure out whether
1586 * machine settings have really changed and thus need to be written out to disk.
1587 */
1588bool Storage::operator==(const Storage &s) const
1589{
1590 return ( (this == &s)
1591 || (llStorageControllers == s.llStorageControllers) // deep compare
1592 );
1593}
1594
1595/**
1596 * Comparison operator. This gets called from MachineConfigFile::operator==,
1597 * which in turn gets called from Machine::saveSettings to figure out whether
1598 * machine settings have really changed and thus need to be written out to disk.
1599 */
1600bool Snapshot::operator==(const Snapshot &s) const
1601{
1602 return ( (this == &s)
1603 || ( (uuid == s.uuid)
1604 && (strName == s.strName)
1605 && (strDescription == s.strDescription)
1606 && (RTTimeSpecIsEqual(&timestamp, &s.timestamp))
1607 && (strStateFile == s.strStateFile)
1608 && (hardware == s.hardware) // deep compare
1609 && (storage == s.storage) // deep compare
1610 && (llChildSnapshots == s.llChildSnapshots) // deep compare
1611 )
1612 );
1613}
1614
1615////////////////////////////////////////////////////////////////////////////////
1616//
1617// MachineConfigFile
1618//
1619////////////////////////////////////////////////////////////////////////////////
1620
1621/**
1622 * Constructor.
1623 *
1624 * If pstrFilename is != NULL, this reads the given settings file into the member
1625 * variables and various substructures and lists. Otherwise, the member variables
1626 * are initialized with default values.
1627 *
1628 * Throws variants of xml::Error for I/O, XML and logical content errors, which
1629 * the caller should catch; if this constructor does not throw, then the member
1630 * variables contain meaningful values (either from the file or defaults).
1631 *
1632 * @param strFilename
1633 */
1634MachineConfigFile::MachineConfigFile(const Utf8Str *pstrFilename)
1635 : ConfigFileBase(pstrFilename),
1636 fNameSync(true),
1637 fTeleporterEnabled(false),
1638 uTeleporterPort(0),
1639 fRTCUseUTC(false),
1640 fCurrentStateModified(true),
1641 fAborted(false)
1642{
1643 RTTimeNow(&timeLastStateChange);
1644
1645 if (pstrFilename)
1646 {
1647 // the ConfigFileBase constructor has loaded the XML file, so now
1648 // we need only analyze what is in there
1649
1650 xml::NodesLoop nlRootChildren(*m->pelmRoot);
1651 const xml::ElementNode *pelmRootChild;
1652 while ((pelmRootChild = nlRootChildren.forAllNodes()))
1653 {
1654 if (pelmRootChild->nameEquals("Machine"))
1655 readMachine(*pelmRootChild);
1656 }
1657
1658 // clean up memory allocated by XML engine
1659 clearDocument();
1660 }
1661}
1662
1663/**
1664 * Comparison operator. This gets called from Machine::saveSettings to figure out
1665 * whether machine settings have really changed and thus need to be written out to disk.
1666 *
1667 * Even though this is called operator==, this does NOT compare all fields; the "equals"
1668 * should be understood as "has the same machine config as". The following fields are
1669 * NOT compared:
1670 * -- settings versions and file names inherited from ConfigFileBase;
1671 * -- fCurrentStateModified because that is considered separately in Machine::saveSettings!!
1672 *
1673 * The "deep" comparisons marked below will invoke the operator== functions of the
1674 * structs defined in this file, which may in turn go into comparing lists of
1675 * other structures. As a result, invoking this can be expensive, but it's
1676 * less expensive than writing out XML to disk.
1677 */
1678bool MachineConfigFile::operator==(const MachineConfigFile &c) const
1679{
1680 return ( (this == &c)
1681 || ( (uuid == c.uuid)
1682 && (strName == c.strName)
1683 && (fNameSync == c.fNameSync)
1684 && (strDescription == c.strDescription)
1685 && (strOsType == c.strOsType)
1686 && (strStateFile == c.strStateFile)
1687 && (uuidCurrentSnapshot == c.uuidCurrentSnapshot)
1688 && (strSnapshotFolder == c.strSnapshotFolder)
1689 && (fTeleporterEnabled == c.fTeleporterEnabled)
1690 && (uTeleporterPort == c.uTeleporterPort)
1691 && (strTeleporterAddress == c.strTeleporterAddress)
1692 && (strTeleporterPassword == c.strTeleporterPassword)
1693 && (fRTCUseUTC == c.fRTCUseUTC)
1694 // skip fCurrentStateModified!
1695 && (RTTimeSpecIsEqual(&timeLastStateChange, &c.timeLastStateChange))
1696 && (fAborted == c.fAborted)
1697 && (hardwareMachine == c.hardwareMachine) // this one's deep
1698 && (storageMachine == c.storageMachine) // this one's deep
1699 && (mapExtraDataItems == c.mapExtraDataItems) // this one's deep
1700 && (llFirstSnapshot == c.llFirstSnapshot) // this one's deep
1701 )
1702 );
1703}
1704
1705/**
1706 * Called from MachineConfigFile::readHardware() to read cpu information.
1707 * @param elmCpuid
1708 * @param ll
1709 */
1710void MachineConfigFile::readCpuTree(const xml::ElementNode &elmCpu,
1711 CpuList &ll)
1712{
1713 xml::NodesLoop nl1(elmCpu, "Cpu");
1714 const xml::ElementNode *pelmCpu;
1715 while ((pelmCpu = nl1.forAllNodes()))
1716 {
1717 Cpu cpu;
1718
1719 if (!pelmCpu->getAttributeValue("id", cpu.ulId))
1720 throw ConfigFileError(this, pelmCpu, N_("Required Cpu/@id attribute is missing"));
1721
1722 ll.push_back(cpu);
1723 }
1724}
1725
1726/**
1727 * Called from MachineConfigFile::readHardware() to cpuid information.
1728 * @param elmCpuid
1729 * @param ll
1730 */
1731void MachineConfigFile::readCpuIdTree(const xml::ElementNode &elmCpuid,
1732 CpuIdLeafsList &ll)
1733{
1734 xml::NodesLoop nl1(elmCpuid, "CpuIdLeaf");
1735 const xml::ElementNode *pelmCpuIdLeaf;
1736 while ((pelmCpuIdLeaf = nl1.forAllNodes()))
1737 {
1738 CpuIdLeaf leaf;
1739
1740 if (!pelmCpuIdLeaf->getAttributeValue("id", leaf.ulId))
1741 throw ConfigFileError(this, pelmCpuIdLeaf, N_("Required CpuId/@id attribute is missing"));
1742
1743 pelmCpuIdLeaf->getAttributeValue("eax", leaf.ulEax);
1744 pelmCpuIdLeaf->getAttributeValue("ebx", leaf.ulEbx);
1745 pelmCpuIdLeaf->getAttributeValue("ecx", leaf.ulEcx);
1746 pelmCpuIdLeaf->getAttributeValue("edx", leaf.ulEdx);
1747
1748 ll.push_back(leaf);
1749 }
1750}
1751
1752/**
1753 * Called from MachineConfigFile::readHardware() to network information.
1754 * @param elmNetwork
1755 * @param ll
1756 */
1757void MachineConfigFile::readNetworkAdapters(const xml::ElementNode &elmNetwork,
1758 NetworkAdaptersList &ll)
1759{
1760 xml::NodesLoop nl1(elmNetwork, "Adapter");
1761 const xml::ElementNode *pelmAdapter;
1762 while ((pelmAdapter = nl1.forAllNodes()))
1763 {
1764 NetworkAdapter nic;
1765
1766 if (!pelmAdapter->getAttributeValue("slot", nic.ulSlot))
1767 throw ConfigFileError(this, pelmAdapter, N_("Required Adapter/@slot attribute is missing"));
1768
1769 Utf8Str strTemp;
1770 if (pelmAdapter->getAttributeValue("type", strTemp))
1771 {
1772 if (strTemp == "Am79C970A")
1773 nic.type = NetworkAdapterType_Am79C970A;
1774 else if (strTemp == "Am79C973")
1775 nic.type = NetworkAdapterType_Am79C973;
1776 else if (strTemp == "82540EM")
1777 nic.type = NetworkAdapterType_I82540EM;
1778 else if (strTemp == "82543GC")
1779 nic.type = NetworkAdapterType_I82543GC;
1780 else if (strTemp == "82545EM")
1781 nic.type = NetworkAdapterType_I82545EM;
1782 else if (strTemp == "virtio")
1783 nic.type = NetworkAdapterType_Virtio;
1784 else
1785 throw ConfigFileError(this, pelmAdapter, N_("Invalid value '%s' in Adapter/@type attribute"), strTemp.c_str());
1786 }
1787
1788 pelmAdapter->getAttributeValue("enabled", nic.fEnabled);
1789 pelmAdapter->getAttributeValue("MACAddress", nic.strMACAddress);
1790 pelmAdapter->getAttributeValue("cable", nic.fCableConnected);
1791 pelmAdapter->getAttributeValue("speed", nic.ulLineSpeed);
1792 pelmAdapter->getAttributeValue("trace", nic.fTraceEnabled);
1793 pelmAdapter->getAttributeValue("tracefile", nic.strTraceFile);
1794
1795 const xml::ElementNode *pelmAdapterChild;
1796 if ((pelmAdapterChild = pelmAdapter->findChildElement("NAT")))
1797 {
1798 nic.mode = NetworkAttachmentType_NAT;
1799 pelmAdapterChild->getAttributeValue("network", nic.strName); // optional network name
1800 }
1801 else if ( ((pelmAdapterChild = pelmAdapter->findChildElement("HostInterface")))
1802 || ((pelmAdapterChild = pelmAdapter->findChildElement("BridgedInterface")))
1803 )
1804 {
1805 nic.mode = NetworkAttachmentType_Bridged;
1806 pelmAdapterChild->getAttributeValue("name", nic.strName); // optional host interface name
1807 }
1808 else if ((pelmAdapterChild = pelmAdapter->findChildElement("InternalNetwork")))
1809 {
1810 nic.mode = NetworkAttachmentType_Internal;
1811 if (!pelmAdapterChild->getAttributeValue("name", nic.strName)) // required network name
1812 throw ConfigFileError(this, pelmAdapterChild, N_("Required InternalNetwork/@name element is missing"));
1813 }
1814 else if ((pelmAdapterChild = pelmAdapter->findChildElement("HostOnlyInterface")))
1815 {
1816 nic.mode = NetworkAttachmentType_HostOnly;
1817 if (!pelmAdapterChild->getAttributeValue("name", nic.strName)) // required network name
1818 throw ConfigFileError(this, pelmAdapterChild, N_("Required HostOnlyInterface/@name element is missing"));
1819 }
1820 // else: default is NetworkAttachmentType_Null
1821
1822 ll.push_back(nic);
1823 }
1824}
1825
1826/**
1827 * Called from MachineConfigFile::readHardware() to read serial port information.
1828 * @param elmUART
1829 * @param ll
1830 */
1831void MachineConfigFile::readSerialPorts(const xml::ElementNode &elmUART,
1832 SerialPortsList &ll)
1833{
1834 xml::NodesLoop nl1(elmUART, "Port");
1835 const xml::ElementNode *pelmPort;
1836 while ((pelmPort = nl1.forAllNodes()))
1837 {
1838 SerialPort port;
1839 if (!pelmPort->getAttributeValue("slot", port.ulSlot))
1840 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@slot attribute is missing"));
1841
1842 // slot must be unique
1843 for (SerialPortsList::const_iterator it = ll.begin();
1844 it != ll.end();
1845 ++it)
1846 if ((*it).ulSlot == port.ulSlot)
1847 throw ConfigFileError(this, pelmPort, N_("Invalid value %RU32 in UART/Port/@slot attribute: value is not unique"), port.ulSlot);
1848
1849 if (!pelmPort->getAttributeValue("enabled", port.fEnabled))
1850 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@enabled attribute is missing"));
1851 if (!pelmPort->getAttributeValue("IOBase", port.ulIOBase))
1852 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@IOBase attribute is missing"));
1853 if (!pelmPort->getAttributeValue("IRQ", port.ulIRQ))
1854 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@IRQ attribute is missing"));
1855
1856 Utf8Str strPortMode;
1857 if (!pelmPort->getAttributeValue("hostMode", strPortMode))
1858 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@hostMode attribute is missing"));
1859 if (strPortMode == "RawFile")
1860 port.portMode = PortMode_RawFile;
1861 else if (strPortMode == "HostPipe")
1862 port.portMode = PortMode_HostPipe;
1863 else if (strPortMode == "HostDevice")
1864 port.portMode = PortMode_HostDevice;
1865 else if (strPortMode == "Disconnected")
1866 port.portMode = PortMode_Disconnected;
1867 else
1868 throw ConfigFileError(this, pelmPort, N_("Invalid value '%s' in UART/Port/@hostMode attribute"), strPortMode.c_str());
1869
1870 pelmPort->getAttributeValue("path", port.strPath);
1871 pelmPort->getAttributeValue("server", port.fServer);
1872
1873 ll.push_back(port);
1874 }
1875}
1876
1877/**
1878 * Called from MachineConfigFile::readHardware() to read parallel port information.
1879 * @param elmLPT
1880 * @param ll
1881 */
1882void MachineConfigFile::readParallelPorts(const xml::ElementNode &elmLPT,
1883 ParallelPortsList &ll)
1884{
1885 xml::NodesLoop nl1(elmLPT, "Port");
1886 const xml::ElementNode *pelmPort;
1887 while ((pelmPort = nl1.forAllNodes()))
1888 {
1889 ParallelPort port;
1890 if (!pelmPort->getAttributeValue("slot", port.ulSlot))
1891 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@slot attribute is missing"));
1892
1893 // slot must be unique
1894 for (ParallelPortsList::const_iterator it = ll.begin();
1895 it != ll.end();
1896 ++it)
1897 if ((*it).ulSlot == port.ulSlot)
1898 throw ConfigFileError(this, pelmPort, N_("Invalid value %RU32 in LPT/Port/@slot attribute: value is not unique"), port.ulSlot);
1899
1900 if (!pelmPort->getAttributeValue("enabled", port.fEnabled))
1901 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@enabled attribute is missing"));
1902 if (!pelmPort->getAttributeValue("IOBase", port.ulIOBase))
1903 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@IOBase attribute is missing"));
1904 if (!pelmPort->getAttributeValue("IRQ", port.ulIRQ))
1905 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@IRQ attribute is missing"));
1906
1907 pelmPort->getAttributeValue("path", port.strPath);
1908
1909 ll.push_back(port);
1910 }
1911}
1912
1913/**
1914 * Called from MachineConfigFile::readHardware() to read guest property information.
1915 * @param elmGuestProperties
1916 * @param hw
1917 */
1918void MachineConfigFile::readGuestProperties(const xml::ElementNode &elmGuestProperties,
1919 Hardware &hw)
1920{
1921 xml::NodesLoop nl1(elmGuestProperties, "GuestProperty");
1922 const xml::ElementNode *pelmProp;
1923 while ((pelmProp = nl1.forAllNodes()))
1924 {
1925 GuestProperty prop;
1926 pelmProp->getAttributeValue("name", prop.strName);
1927 pelmProp->getAttributeValue("value", prop.strValue);
1928
1929 pelmProp->getAttributeValue("timestamp", prop.timestamp);
1930 pelmProp->getAttributeValue("flags", prop.strFlags);
1931 hw.llGuestProperties.push_back(prop);
1932 }
1933
1934 elmGuestProperties.getAttributeValue("notificationPatterns", hw.strNotificationPatterns);
1935}
1936
1937/**
1938 * Helper function to read attributes that are common to <SATAController> (pre-1.7)
1939 * and <StorageController>.
1940 * @param elmStorageController
1941 * @param strg
1942 */
1943void MachineConfigFile::readStorageControllerAttributes(const xml::ElementNode &elmStorageController,
1944 StorageController &sctl)
1945{
1946 elmStorageController.getAttributeValue("PortCount", sctl.ulPortCount);
1947 elmStorageController.getAttributeValue("IDE0MasterEmulationPort", sctl.lIDE0MasterEmulationPort);
1948 elmStorageController.getAttributeValue("IDE0SlaveEmulationPort", sctl.lIDE0SlaveEmulationPort);
1949 elmStorageController.getAttributeValue("IDE1MasterEmulationPort", sctl.lIDE1MasterEmulationPort);
1950 elmStorageController.getAttributeValue("IDE1SlaveEmulationPort", sctl.lIDE1SlaveEmulationPort);
1951}
1952
1953/**
1954 * Reads in a <Hardware> block and stores it in the given structure. Used
1955 * both directly from readMachine and from readSnapshot, since snapshots
1956 * have their own hardware sections.
1957 *
1958 * For legacy pre-1.7 settings we also need a storage structure because
1959 * the IDE and SATA controllers used to be defined under <Hardware>.
1960 *
1961 * @param elmHardware
1962 * @param hw
1963 */
1964void MachineConfigFile::readHardware(const xml::ElementNode &elmHardware,
1965 Hardware &hw,
1966 Storage &strg)
1967{
1968 if (!elmHardware.getAttributeValue("version", hw.strVersion))
1969 {
1970 /* KLUDGE ALERT! For a while during the 3.1 development this was not
1971 written because it was thought to have a default value of "2". For
1972 sv <= 1.3 it defaults to "1" because the attribute didn't exist,
1973 while for 1.4+ it is sort of mandatory. Now, the buggy XML writer
1974 code only wrote 1.7 and later. So, if it's a 1.7+ XML file and it's
1975 missing the hardware version, then it probably should be "2" instead
1976 of "1". */
1977 if (m->sv < SettingsVersion_v1_7)
1978 hw.strVersion = "1";
1979 else
1980 hw.strVersion = "2";
1981 }
1982 Utf8Str strUUID;
1983 if (elmHardware.getAttributeValue("uuid", strUUID))
1984 parseUUID(hw.uuid, strUUID);
1985
1986 xml::NodesLoop nl1(elmHardware);
1987 const xml::ElementNode *pelmHwChild;
1988 while ((pelmHwChild = nl1.forAllNodes()))
1989 {
1990 if (pelmHwChild->nameEquals("CPU"))
1991 {
1992 if (!pelmHwChild->getAttributeValue("count", hw.cCPUs))
1993 {
1994 // pre-1.5 variant; not sure if this actually exists in the wild anywhere
1995 const xml::ElementNode *pelmCPUChild;
1996 if ((pelmCPUChild = pelmHwChild->findChildElement("CPUCount")))
1997 pelmCPUChild->getAttributeValue("count", hw.cCPUs);
1998 }
1999
2000 pelmHwChild->getAttributeValue("hotplug", hw.fCpuHotPlug);
2001
2002 const xml::ElementNode *pelmCPUChild;
2003 if (hw.fCpuHotPlug)
2004 {
2005 if ((pelmCPUChild = pelmHwChild->findChildElement("CpuTree")))
2006 readCpuTree(*pelmCPUChild, hw.llCpus);
2007 }
2008
2009 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtEx")))
2010 {
2011 pelmCPUChild->getAttributeValue("enabled", hw.fHardwareVirt);
2012 pelmCPUChild->getAttributeValue("exclusive", hw.fHardwareVirtExclusive); // settings version 1.9
2013 }
2014 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExNestedPaging")))
2015 pelmCPUChild->getAttributeValue("enabled", hw.fNestedPaging);
2016 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExLargePages")))
2017 pelmCPUChild->getAttributeValue("enabled", hw.fLargePages);
2018 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExVPID")))
2019 pelmCPUChild->getAttributeValue("enabled", hw.fVPID);
2020
2021 if (!(pelmCPUChild = pelmHwChild->findChildElement("PAE")))
2022 {
2023 /* The default for pre 3.1 was false, so we must respect that. */
2024 if (m->sv < SettingsVersion_v1_9)
2025 hw.fPAE = false;
2026 }
2027 else
2028 pelmCPUChild->getAttributeValue("enabled", hw.fPAE);
2029
2030 if ((pelmCPUChild = pelmHwChild->findChildElement("SyntheticCpu")))
2031 pelmCPUChild->getAttributeValue("enabled", hw.fSyntheticCpu);
2032 if ((pelmCPUChild = pelmHwChild->findChildElement("CpuIdTree")))
2033 readCpuIdTree(*pelmCPUChild, hw.llCpuIdLeafs);
2034 }
2035 else if (pelmHwChild->nameEquals("Memory"))
2036 pelmHwChild->getAttributeValue("RAMSize", hw.ulMemorySizeMB);
2037 else if (pelmHwChild->nameEquals("Firmware"))
2038 {
2039 Utf8Str strFirmwareType;
2040 if (pelmHwChild->getAttributeValue("type", strFirmwareType))
2041 {
2042 if ( (strFirmwareType == "BIOS")
2043 || (strFirmwareType == "1") // some trunk builds used the number here
2044 )
2045 hw.firmwareType = FirmwareType_BIOS;
2046 else if ( (strFirmwareType == "EFI")
2047 || (strFirmwareType == "2") // some trunk builds used the number here
2048 )
2049 hw.firmwareType = FirmwareType_EFI;
2050 else if ( strFirmwareType == "EFI32")
2051 hw.firmwareType = FirmwareType_EFI32;
2052 else if ( strFirmwareType == "EFI64")
2053 hw.firmwareType = FirmwareType_EFI64;
2054 else if ( strFirmwareType == "EFIDUAL")
2055 hw.firmwareType = FirmwareType_EFIDUAL;
2056 else
2057 throw ConfigFileError(this,
2058 pelmHwChild,
2059 N_("Invalid value '%s' in Firmware/@type"),
2060 strFirmwareType.c_str());
2061 }
2062 }
2063 else if (pelmHwChild->nameEquals("HID"))
2064 {
2065 Utf8Str strHidType;
2066 if (pelmHwChild->getAttributeValue("Keyboard", strHidType))
2067 {
2068 if (strHidType == "None")
2069 hw.keyboardHidType = KeyboardHidType_None;
2070 else if (strHidType == "USBKeyboard")
2071 hw.keyboardHidType = KeyboardHidType_USBKeyboard;
2072 else if (strHidType == "PS2Keyboard")
2073 hw.keyboardHidType = KeyboardHidType_PS2Keyboard;
2074 else if (strHidType == "ComboKeyboard")
2075 hw.keyboardHidType = KeyboardHidType_ComboKeyboard;
2076 else
2077 throw ConfigFileError(this,
2078 pelmHwChild,
2079 N_("Invalid value '%s' in HID/Keyboard/@type"),
2080 strHidType.c_str());
2081 }
2082 if (pelmHwChild->getAttributeValue("Pointing", strHidType))
2083 {
2084 if (strHidType == "None")
2085 hw.pointingHidType = PointingHidType_None;
2086 else if (strHidType == "USBMouse")
2087 hw.pointingHidType = PointingHidType_USBMouse;
2088 else if (strHidType == "USBTablet")
2089 hw.pointingHidType = PointingHidType_USBTablet;
2090 else if (strHidType == "PS2Mouse")
2091 hw.pointingHidType = PointingHidType_PS2Mouse;
2092 else if (strHidType == "ComboMouse")
2093 hw.pointingHidType = PointingHidType_ComboMouse;
2094 else
2095 throw ConfigFileError(this,
2096 pelmHwChild,
2097 N_("Invalid value '%s' in HID/Pointing/@type"),
2098 strHidType.c_str());
2099 }
2100 }
2101 else if (pelmHwChild->nameEquals("HPET"))
2102 {
2103 pelmHwChild->getAttributeValue("enabled", hw.fHpetEnabled);
2104 }
2105 else if (pelmHwChild->nameEquals("Boot"))
2106 {
2107 hw.mapBootOrder.clear();
2108
2109 xml::NodesLoop nl2(*pelmHwChild, "Order");
2110 const xml::ElementNode *pelmOrder;
2111 while ((pelmOrder = nl2.forAllNodes()))
2112 {
2113 uint32_t ulPos;
2114 Utf8Str strDevice;
2115 if (!pelmOrder->getAttributeValue("position", ulPos))
2116 throw ConfigFileError(this, pelmOrder, N_("Required Boot/Order/@position attribute is missing"));
2117
2118 if ( ulPos < 1
2119 || ulPos > SchemaDefs::MaxBootPosition
2120 )
2121 throw ConfigFileError(this,
2122 pelmOrder,
2123 N_("Invalid value '%RU32' in Boot/Order/@position: must be greater than 0 and less than %RU32"),
2124 ulPos,
2125 SchemaDefs::MaxBootPosition + 1);
2126 // XML is 1-based but internal data is 0-based
2127 --ulPos;
2128
2129 if (hw.mapBootOrder.find(ulPos) != hw.mapBootOrder.end())
2130 throw ConfigFileError(this, pelmOrder, N_("Invalid value '%RU32' in Boot/Order/@position: value is not unique"), ulPos);
2131
2132 if (!pelmOrder->getAttributeValue("device", strDevice))
2133 throw ConfigFileError(this, pelmOrder, N_("Required Boot/Order/@device attribute is missing"));
2134
2135 DeviceType_T type;
2136 if (strDevice == "None")
2137 type = DeviceType_Null;
2138 else if (strDevice == "Floppy")
2139 type = DeviceType_Floppy;
2140 else if (strDevice == "DVD")
2141 type = DeviceType_DVD;
2142 else if (strDevice == "HardDisk")
2143 type = DeviceType_HardDisk;
2144 else if (strDevice == "Network")
2145 type = DeviceType_Network;
2146 else
2147 throw ConfigFileError(this, pelmOrder, N_("Invalid value '%s' in Boot/Order/@device attribute"), strDevice.c_str());
2148 hw.mapBootOrder[ulPos] = type;
2149 }
2150 }
2151 else if (pelmHwChild->nameEquals("Display"))
2152 {
2153 pelmHwChild->getAttributeValue("VRAMSize", hw.ulVRAMSizeMB);
2154 if (!pelmHwChild->getAttributeValue("monitorCount", hw.cMonitors))
2155 pelmHwChild->getAttributeValue("MonitorCount", hw.cMonitors); // pre-v1.5 variant
2156 if (!pelmHwChild->getAttributeValue("accelerate3D", hw.fAccelerate3D))
2157 pelmHwChild->getAttributeValue("Accelerate3D", hw.fAccelerate3D); // pre-v1.5 variant
2158 pelmHwChild->getAttributeValue("accelerate2DVideo", hw.fAccelerate2DVideo);
2159 }
2160 else if (pelmHwChild->nameEquals("RemoteDisplay"))
2161 {
2162 pelmHwChild->getAttributeValue("enabled", hw.vrdpSettings.fEnabled);
2163 pelmHwChild->getAttributeValue("port", hw.vrdpSettings.strPort);
2164 pelmHwChild->getAttributeValue("netAddress", hw.vrdpSettings.strNetAddress);
2165
2166 Utf8Str strAuthType;
2167 if (pelmHwChild->getAttributeValue("authType", strAuthType))
2168 {
2169 // settings before 1.3 used lower case so make sure this is case-insensitive
2170 strAuthType.toUpper();
2171 if (strAuthType == "NULL")
2172 hw.vrdpSettings.authType = VRDPAuthType_Null;
2173 else if (strAuthType == "GUEST")
2174 hw.vrdpSettings.authType = VRDPAuthType_Guest;
2175 else if (strAuthType == "EXTERNAL")
2176 hw.vrdpSettings.authType = VRDPAuthType_External;
2177 else
2178 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in RemoteDisplay/@authType attribute"), strAuthType.c_str());
2179 }
2180
2181 pelmHwChild->getAttributeValue("authTimeout", hw.vrdpSettings.ulAuthTimeout);
2182 pelmHwChild->getAttributeValue("allowMultiConnection", hw.vrdpSettings.fAllowMultiConnection);
2183 pelmHwChild->getAttributeValue("reuseSingleConnection", hw.vrdpSettings.fReuseSingleConnection);
2184 }
2185 else if (pelmHwChild->nameEquals("BIOS"))
2186 {
2187 const xml::ElementNode *pelmBIOSChild;
2188 if ((pelmBIOSChild = pelmHwChild->findChildElement("ACPI")))
2189 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fACPIEnabled);
2190 if ((pelmBIOSChild = pelmHwChild->findChildElement("IOAPIC")))
2191 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fIOAPICEnabled);
2192 if ((pelmBIOSChild = pelmHwChild->findChildElement("Logo")))
2193 {
2194 pelmBIOSChild->getAttributeValue("fadeIn", hw.biosSettings.fLogoFadeIn);
2195 pelmBIOSChild->getAttributeValue("fadeOut", hw.biosSettings.fLogoFadeOut);
2196 pelmBIOSChild->getAttributeValue("displayTime", hw.biosSettings.ulLogoDisplayTime);
2197 pelmBIOSChild->getAttributeValue("imagePath", hw.biosSettings.strLogoImagePath);
2198 }
2199 if ((pelmBIOSChild = pelmHwChild->findChildElement("BootMenu")))
2200 {
2201 Utf8Str strBootMenuMode;
2202 if (pelmBIOSChild->getAttributeValue("mode", strBootMenuMode))
2203 {
2204 // settings before 1.3 used lower case so make sure this is case-insensitive
2205 strBootMenuMode.toUpper();
2206 if (strBootMenuMode == "DISABLED")
2207 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_Disabled;
2208 else if (strBootMenuMode == "MENUONLY")
2209 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_MenuOnly;
2210 else if (strBootMenuMode == "MESSAGEANDMENU")
2211 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_MessageAndMenu;
2212 else
2213 throw ConfigFileError(this, pelmBIOSChild, N_("Invalid value '%s' in BootMenu/@mode attribute"), strBootMenuMode.c_str());
2214 }
2215 }
2216 if ((pelmBIOSChild = pelmHwChild->findChildElement("PXEDebug")))
2217 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fPXEDebugEnabled);
2218 if ((pelmBIOSChild = pelmHwChild->findChildElement("TimeOffset")))
2219 pelmBIOSChild->getAttributeValue("value", hw.biosSettings.llTimeOffset);
2220
2221 // legacy BIOS/IDEController (pre 1.7)
2222 if ( (m->sv < SettingsVersion_v1_7)
2223 && ((pelmBIOSChild = pelmHwChild->findChildElement("IDEController")))
2224 )
2225 {
2226 StorageController sctl;
2227 sctl.strName = "IDE Controller";
2228 sctl.storageBus = StorageBus_IDE;
2229
2230 Utf8Str strType;
2231 if (pelmBIOSChild->getAttributeValue("type", strType))
2232 {
2233 if (strType == "PIIX3")
2234 sctl.controllerType = StorageControllerType_PIIX3;
2235 else if (strType == "PIIX4")
2236 sctl.controllerType = StorageControllerType_PIIX4;
2237 else if (strType == "ICH6")
2238 sctl.controllerType = StorageControllerType_ICH6;
2239 else
2240 throw ConfigFileError(this, pelmBIOSChild, N_("Invalid value '%s' for IDEController/@type attribute"), strType.c_str());
2241 }
2242 sctl.ulPortCount = 2;
2243 strg.llStorageControllers.push_back(sctl);
2244 }
2245 }
2246 else if (pelmHwChild->nameEquals("USBController"))
2247 {
2248 pelmHwChild->getAttributeValue("enabled", hw.usbController.fEnabled);
2249 pelmHwChild->getAttributeValue("enabledEhci", hw.usbController.fEnabledEHCI);
2250
2251 readUSBDeviceFilters(*pelmHwChild,
2252 hw.usbController.llDeviceFilters);
2253 }
2254 else if ( (m->sv < SettingsVersion_v1_7)
2255 && (pelmHwChild->nameEquals("SATAController"))
2256 )
2257 {
2258 bool f;
2259 if ( (pelmHwChild->getAttributeValue("enabled", f))
2260 && (f)
2261 )
2262 {
2263 StorageController sctl;
2264 sctl.strName = "SATA Controller";
2265 sctl.storageBus = StorageBus_SATA;
2266 sctl.controllerType = StorageControllerType_IntelAhci;
2267
2268 readStorageControllerAttributes(*pelmHwChild, sctl);
2269
2270 strg.llStorageControllers.push_back(sctl);
2271 }
2272 }
2273 else if (pelmHwChild->nameEquals("Network"))
2274 readNetworkAdapters(*pelmHwChild, hw.llNetworkAdapters);
2275 else if (pelmHwChild->nameEquals("RTC"))
2276 {
2277 Utf8Str strLocalOrUTC;
2278 fRTCUseUTC = pelmHwChild->getAttributeValue("localOrUTC", strLocalOrUTC)
2279 && strLocalOrUTC == "UTC";
2280 }
2281 else if ( (pelmHwChild->nameEquals("UART"))
2282 || (pelmHwChild->nameEquals("Uart")) // used before 1.3
2283 )
2284 readSerialPorts(*pelmHwChild, hw.llSerialPorts);
2285 else if ( (pelmHwChild->nameEquals("LPT"))
2286 || (pelmHwChild->nameEquals("Lpt")) // used before 1.3
2287 )
2288 readParallelPorts(*pelmHwChild, hw.llParallelPorts);
2289 else if (pelmHwChild->nameEquals("AudioAdapter"))
2290 {
2291 pelmHwChild->getAttributeValue("enabled", hw.audioAdapter.fEnabled);
2292
2293 Utf8Str strTemp;
2294 if (pelmHwChild->getAttributeValue("controller", strTemp))
2295 {
2296 if (strTemp == "SB16")
2297 hw.audioAdapter.controllerType = AudioControllerType_SB16;
2298 else if (strTemp == "AC97")
2299 hw.audioAdapter.controllerType = AudioControllerType_AC97;
2300 else
2301 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in AudioAdapter/@controller attribute"), strTemp.c_str());
2302 }
2303 if (pelmHwChild->getAttributeValue("driver", strTemp))
2304 {
2305 // settings before 1.3 used lower case so make sure this is case-insensitive
2306 strTemp.toUpper();
2307 if (strTemp == "NULL")
2308 hw.audioAdapter.driverType = AudioDriverType_Null;
2309 else if (strTemp == "WINMM")
2310 hw.audioAdapter.driverType = AudioDriverType_WinMM;
2311 else if ( (strTemp == "DIRECTSOUND") || (strTemp == "DSOUND") )
2312 hw.audioAdapter.driverType = AudioDriverType_DirectSound;
2313 else if (strTemp == "SOLAUDIO")
2314 hw.audioAdapter.driverType = AudioDriverType_SolAudio;
2315 else if (strTemp == "ALSA")
2316 hw.audioAdapter.driverType = AudioDriverType_ALSA;
2317 else if (strTemp == "PULSE")
2318 hw.audioAdapter.driverType = AudioDriverType_Pulse;
2319 else if (strTemp == "OSS")
2320 hw.audioAdapter.driverType = AudioDriverType_OSS;
2321 else if (strTemp == "COREAUDIO")
2322 hw.audioAdapter.driverType = AudioDriverType_CoreAudio;
2323 else if (strTemp == "MMPM")
2324 hw.audioAdapter.driverType = AudioDriverType_MMPM;
2325 else
2326 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in AudioAdapter/@driver attribute"), strTemp.c_str());
2327 }
2328 }
2329 else if (pelmHwChild->nameEquals("SharedFolders"))
2330 {
2331 xml::NodesLoop nl2(*pelmHwChild, "SharedFolder");
2332 const xml::ElementNode *pelmFolder;
2333 while ((pelmFolder = nl2.forAllNodes()))
2334 {
2335 SharedFolder sf;
2336 pelmFolder->getAttributeValue("name", sf.strName);
2337 pelmFolder->getAttributeValue("hostPath", sf.strHostPath);
2338 pelmFolder->getAttributeValue("writable", sf.fWritable);
2339 hw.llSharedFolders.push_back(sf);
2340 }
2341 }
2342 else if (pelmHwChild->nameEquals("Clipboard"))
2343 {
2344 Utf8Str strTemp;
2345 if (pelmHwChild->getAttributeValue("mode", strTemp))
2346 {
2347 if (strTemp == "Disabled")
2348 hw.clipboardMode = ClipboardMode_Disabled;
2349 else if (strTemp == "HostToGuest")
2350 hw.clipboardMode = ClipboardMode_HostToGuest;
2351 else if (strTemp == "GuestToHost")
2352 hw.clipboardMode = ClipboardMode_GuestToHost;
2353 else if (strTemp == "Bidirectional")
2354 hw.clipboardMode = ClipboardMode_Bidirectional;
2355 else
2356 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in Clipbord/@mode attribute"), strTemp.c_str());
2357 }
2358 }
2359 else if (pelmHwChild->nameEquals("Guest"))
2360 {
2361 if (!pelmHwChild->getAttributeValue("memoryBalloonSize", hw.ulMemoryBalloonSize))
2362 pelmHwChild->getAttributeValue("MemoryBalloonSize", hw.ulMemoryBalloonSize); // used before 1.3
2363 if (!pelmHwChild->getAttributeValue("statisticsUpdateInterval", hw.ulStatisticsUpdateInterval))
2364 pelmHwChild->getAttributeValue("StatisticsUpdateInterval", hw.ulStatisticsUpdateInterval);
2365 }
2366 else if (pelmHwChild->nameEquals("GuestProperties"))
2367 readGuestProperties(*pelmHwChild, hw);
2368 }
2369
2370 if (hw.ulMemorySizeMB == (uint32_t)-1)
2371 throw ConfigFileError(this, &elmHardware, N_("Required Memory/@RAMSize element/attribute is missing"));
2372}
2373
2374/**
2375 * This gets called instead of readStorageControllers() for legacy pre-1.7 settings
2376 * files which have a <HardDiskAttachments> node and storage controller settings
2377 * hidden in the <Hardware> settings. We set the StorageControllers fields just the
2378 * same, just from different sources.
2379 * @param elmHardware <Hardware> XML node.
2380 * @param elmHardDiskAttachments <HardDiskAttachments> XML node.
2381 * @param strg
2382 */
2383void MachineConfigFile::readHardDiskAttachments_pre1_7(const xml::ElementNode &elmHardDiskAttachments,
2384 Storage &strg)
2385{
2386 StorageController *pIDEController = NULL;
2387 StorageController *pSATAController = NULL;
2388
2389 for (StorageControllersList::iterator it = strg.llStorageControllers.begin();
2390 it != strg.llStorageControllers.end();
2391 ++it)
2392 {
2393 StorageController &s = *it;
2394 if (s.storageBus == StorageBus_IDE)
2395 pIDEController = &s;
2396 else if (s.storageBus == StorageBus_SATA)
2397 pSATAController = &s;
2398 }
2399
2400 xml::NodesLoop nl1(elmHardDiskAttachments, "HardDiskAttachment");
2401 const xml::ElementNode *pelmAttachment;
2402 while ((pelmAttachment = nl1.forAllNodes()))
2403 {
2404 AttachedDevice att;
2405 Utf8Str strUUID, strBus;
2406
2407 if (!pelmAttachment->getAttributeValue("hardDisk", strUUID))
2408 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@hardDisk attribute is missing"));
2409 parseUUID(att.uuid, strUUID);
2410
2411 if (!pelmAttachment->getAttributeValue("bus", strBus))
2412 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@bus attribute is missing"));
2413 // pre-1.7 'channel' is now port
2414 if (!pelmAttachment->getAttributeValue("channel", att.lPort))
2415 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@channel attribute is missing"));
2416 // pre-1.7 'device' is still device
2417 if (!pelmAttachment->getAttributeValue("device", att.lDevice))
2418 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@device attribute is missing"));
2419
2420 att.deviceType = DeviceType_HardDisk;
2421
2422 if (strBus == "IDE")
2423 {
2424 if (!pIDEController)
2425 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus is 'IDE' but cannot find IDE controller"));
2426 pIDEController->llAttachedDevices.push_back(att);
2427 }
2428 else if (strBus == "SATA")
2429 {
2430 if (!pSATAController)
2431 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus is 'SATA' but cannot find SATA controller"));
2432 pSATAController->llAttachedDevices.push_back(att);
2433 }
2434 else
2435 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus attribute has illegal value '%s'"), strBus.c_str());
2436 }
2437}
2438
2439/**
2440 * Reads in a <StorageControllers> block and stores it in the given Storage structure.
2441 * Used both directly from readMachine and from readSnapshot, since snapshots
2442 * have their own storage controllers sections.
2443 *
2444 * This is only called for settings version 1.7 and above; see readHardDiskAttachments_pre1_7()
2445 * for earlier versions.
2446 *
2447 * @param elmStorageControllers
2448 */
2449void MachineConfigFile::readStorageControllers(const xml::ElementNode &elmStorageControllers,
2450 Storage &strg)
2451{
2452 xml::NodesLoop nlStorageControllers(elmStorageControllers, "StorageController");
2453 const xml::ElementNode *pelmController;
2454 while ((pelmController = nlStorageControllers.forAllNodes()))
2455 {
2456 StorageController sctl;
2457
2458 if (!pelmController->getAttributeValue("name", sctl.strName))
2459 throw ConfigFileError(this, pelmController, N_("Required StorageController/@name attribute is missing"));
2460 // canonicalize storage controller names for configs in the switchover
2461 // period.
2462 if (m->sv < SettingsVersion_v1_9)
2463 {
2464 if (sctl.strName == "IDE")
2465 sctl.strName = "IDE Controller";
2466 else if (sctl.strName == "SATA")
2467 sctl.strName = "SATA Controller";
2468 else if (sctl.strName == "SCSI")
2469 sctl.strName = "SCSI Controller";
2470 }
2471
2472 pelmController->getAttributeValue("Instance", sctl.ulInstance);
2473 // default from constructor is 0
2474
2475 Utf8Str strType;
2476 if (!pelmController->getAttributeValue("type", strType))
2477 throw ConfigFileError(this, pelmController, N_("Required StorageController/@type attribute is missing"));
2478
2479 if (strType == "AHCI")
2480 {
2481 sctl.storageBus = StorageBus_SATA;
2482 sctl.controllerType = StorageControllerType_IntelAhci;
2483 }
2484 else if (strType == "LsiLogic")
2485 {
2486 sctl.storageBus = StorageBus_SCSI;
2487 sctl.controllerType = StorageControllerType_LsiLogic;
2488 }
2489 else if (strType == "BusLogic")
2490 {
2491 sctl.storageBus = StorageBus_SCSI;
2492 sctl.controllerType = StorageControllerType_BusLogic;
2493 }
2494 else if (strType == "PIIX3")
2495 {
2496 sctl.storageBus = StorageBus_IDE;
2497 sctl.controllerType = StorageControllerType_PIIX3;
2498 }
2499 else if (strType == "PIIX4")
2500 {
2501 sctl.storageBus = StorageBus_IDE;
2502 sctl.controllerType = StorageControllerType_PIIX4;
2503 }
2504 else if (strType == "ICH6")
2505 {
2506 sctl.storageBus = StorageBus_IDE;
2507 sctl.controllerType = StorageControllerType_ICH6;
2508 }
2509 else if ( (m->sv >= SettingsVersion_v1_9)
2510 && (strType == "I82078")
2511 )
2512 {
2513 sctl.storageBus = StorageBus_Floppy;
2514 sctl.controllerType = StorageControllerType_I82078;
2515 }
2516 else if (strType == "LsiLogicSas")
2517 {
2518 sctl.storageBus = StorageBus_SAS;
2519 sctl.controllerType = StorageControllerType_LsiLogicSas;
2520 }
2521 else
2522 throw ConfigFileError(this, pelmController, N_("Invalid value '%s' for StorageController/@type attribute"), strType.c_str());
2523
2524 readStorageControllerAttributes(*pelmController, sctl);
2525
2526 xml::NodesLoop nlAttached(*pelmController, "AttachedDevice");
2527 const xml::ElementNode *pelmAttached;
2528 while ((pelmAttached = nlAttached.forAllNodes()))
2529 {
2530 AttachedDevice att;
2531 Utf8Str strTemp;
2532 pelmAttached->getAttributeValue("type", strTemp);
2533
2534 if (strTemp == "HardDisk")
2535 att.deviceType = DeviceType_HardDisk;
2536 else if (m->sv >= SettingsVersion_v1_9)
2537 {
2538 // starting with 1.9 we list DVD and floppy drive info + attachments under <StorageControllers>
2539 if (strTemp == "DVD")
2540 {
2541 att.deviceType = DeviceType_DVD;
2542 pelmAttached->getAttributeValue("passthrough", att.fPassThrough);
2543 }
2544 else if (strTemp == "Floppy")
2545 att.deviceType = DeviceType_Floppy;
2546 }
2547
2548 if (att.deviceType != DeviceType_Null)
2549 {
2550 const xml::ElementNode *pelmImage;
2551 // all types can have images attached, but for HardDisk it's required
2552 if (!(pelmImage = pelmAttached->findChildElement("Image")))
2553 {
2554 if (att.deviceType == DeviceType_HardDisk)
2555 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/Image element is missing"));
2556 else
2557 {
2558 // DVDs and floppies can also have <HostDrive> instead of <Image>
2559 const xml::ElementNode *pelmHostDrive;
2560 if ((pelmHostDrive = pelmAttached->findChildElement("HostDrive")))
2561 if (!pelmHostDrive->getAttributeValue("src", att.strHostDriveSrc))
2562 throw ConfigFileError(this, pelmHostDrive, N_("Required AttachedDevice/HostDrive/@src attribute is missing"));
2563 }
2564 }
2565 else
2566 {
2567 if (!pelmImage->getAttributeValue("uuid", strTemp))
2568 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/Image/@uuid attribute is missing"));
2569 parseUUID(att.uuid, strTemp);
2570 }
2571
2572 if (!pelmAttached->getAttributeValue("port", att.lPort))
2573 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/@port attribute is missing"));
2574 if (!pelmAttached->getAttributeValue("device", att.lDevice))
2575 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/@device attribute is missing"));
2576
2577 sctl.llAttachedDevices.push_back(att);
2578 }
2579 }
2580
2581 strg.llStorageControllers.push_back(sctl);
2582 }
2583}
2584
2585/**
2586 * This gets called for legacy pre-1.9 settings files after having parsed the
2587 * <Hardware> and <StorageControllers> sections to parse <Hardware> once more
2588 * for the <DVDDrive> and <FloppyDrive> sections.
2589 *
2590 * Before settings version 1.9, DVD and floppy drives were specified separately
2591 * under <Hardware>; we then need this extra loop to make sure the storage
2592 * controller structs are already set up so we can add stuff to them.
2593 *
2594 * @param elmHardware
2595 * @param strg
2596 */
2597void MachineConfigFile::readDVDAndFloppies_pre1_9(const xml::ElementNode &elmHardware,
2598 Storage &strg)
2599{
2600 xml::NodesLoop nl1(elmHardware);
2601 const xml::ElementNode *pelmHwChild;
2602 while ((pelmHwChild = nl1.forAllNodes()))
2603 {
2604 if (pelmHwChild->nameEquals("DVDDrive"))
2605 {
2606 // create a DVD "attached device" and attach it to the existing IDE controller
2607 AttachedDevice att;
2608 att.deviceType = DeviceType_DVD;
2609 // legacy DVD drive is always secondary master (port 1, device 0)
2610 att.lPort = 1;
2611 att.lDevice = 0;
2612 pelmHwChild->getAttributeValue("passthrough", att.fPassThrough);
2613
2614 const xml::ElementNode *pDriveChild;
2615 Utf8Str strTmp;
2616 if ( ((pDriveChild = pelmHwChild->findChildElement("Image")))
2617 && (pDriveChild->getAttributeValue("uuid", strTmp))
2618 )
2619 parseUUID(att.uuid, strTmp);
2620 else if ((pDriveChild = pelmHwChild->findChildElement("HostDrive")))
2621 pDriveChild->getAttributeValue("src", att.strHostDriveSrc);
2622
2623 // find the IDE controller and attach the DVD drive
2624 bool fFound = false;
2625 for (StorageControllersList::iterator it = strg.llStorageControllers.begin();
2626 it != strg.llStorageControllers.end();
2627 ++it)
2628 {
2629 StorageController &sctl = *it;
2630 if (sctl.storageBus == StorageBus_IDE)
2631 {
2632 sctl.llAttachedDevices.push_back(att);
2633 fFound = true;
2634 break;
2635 }
2636 }
2637
2638 if (!fFound)
2639 throw ConfigFileError(this, pelmHwChild, N_("Internal error: found DVD drive but IDE controller does not exist"));
2640 // shouldn't happen because pre-1.9 settings files always had at least one IDE controller in the settings
2641 // which should have gotten parsed in <StorageControllers> before this got called
2642 }
2643 else if (pelmHwChild->nameEquals("FloppyDrive"))
2644 {
2645 bool fEnabled;
2646 if ( (pelmHwChild->getAttributeValue("enabled", fEnabled))
2647 && (fEnabled)
2648 )
2649 {
2650 // create a new floppy controller and attach a floppy "attached device"
2651 StorageController sctl;
2652 sctl.strName = "Floppy Controller";
2653 sctl.storageBus = StorageBus_Floppy;
2654 sctl.controllerType = StorageControllerType_I82078;
2655 sctl.ulPortCount = 1;
2656
2657 AttachedDevice att;
2658 att.deviceType = DeviceType_Floppy;
2659 att.lPort = 0;
2660 att.lDevice = 0;
2661
2662 const xml::ElementNode *pDriveChild;
2663 Utf8Str strTmp;
2664 if ( ((pDriveChild = pelmHwChild->findChildElement("Image")))
2665 && (pDriveChild->getAttributeValue("uuid", strTmp))
2666 )
2667 parseUUID(att.uuid, strTmp);
2668 else if ((pDriveChild = pelmHwChild->findChildElement("HostDrive")))
2669 pDriveChild->getAttributeValue("src", att.strHostDriveSrc);
2670
2671 // store attachment with controller
2672 sctl.llAttachedDevices.push_back(att);
2673 // store controller with storage
2674 strg.llStorageControllers.push_back(sctl);
2675 }
2676 }
2677 }
2678}
2679
2680/**
2681 * Called initially for the <Snapshot> element under <Machine>, if present,
2682 * to store the snapshot's data into the given Snapshot structure (which is
2683 * then the one in the Machine struct). This might then recurse if
2684 * a <Snapshots> (plural) element is found in the snapshot, which should
2685 * contain a list of child snapshots; such lists are maintained in the
2686 * Snapshot structure.
2687 *
2688 * @param elmSnapshot
2689 * @param snap
2690 */
2691void MachineConfigFile::readSnapshot(const xml::ElementNode &elmSnapshot,
2692 Snapshot &snap)
2693{
2694 Utf8Str strTemp;
2695
2696 if (!elmSnapshot.getAttributeValue("uuid", strTemp))
2697 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@uuid attribute is missing"));
2698 parseUUID(snap.uuid, strTemp);
2699
2700 if (!elmSnapshot.getAttributeValue("name", snap.strName))
2701 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@name attribute is missing"));
2702
2703 // earlier 3.1 trunk builds had a bug and added Description as an attribute, read it silently and write it back as an element
2704 elmSnapshot.getAttributeValue("Description", snap.strDescription);
2705
2706 if (!elmSnapshot.getAttributeValue("timeStamp", strTemp))
2707 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@timeStamp attribute is missing"));
2708 parseTimestamp(snap.timestamp, strTemp);
2709
2710 elmSnapshot.getAttributeValue("stateFile", snap.strStateFile); // online snapshots only
2711
2712 // parse Hardware before the other elements because other things depend on it
2713 const xml::ElementNode *pelmHardware;
2714 if (!(pelmHardware = elmSnapshot.findChildElement("Hardware")))
2715 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@Hardware element is missing"));
2716 readHardware(*pelmHardware, snap.hardware, snap.storage);
2717
2718 xml::NodesLoop nlSnapshotChildren(elmSnapshot);
2719 const xml::ElementNode *pelmSnapshotChild;
2720 while ((pelmSnapshotChild = nlSnapshotChildren.forAllNodes()))
2721 {
2722 if (pelmSnapshotChild->nameEquals("Description"))
2723 snap.strDescription = pelmSnapshotChild->getValue();
2724 else if ( (m->sv < SettingsVersion_v1_7)
2725 && (pelmSnapshotChild->nameEquals("HardDiskAttachments"))
2726 )
2727 readHardDiskAttachments_pre1_7(*pelmSnapshotChild, snap.storage);
2728 else if ( (m->sv >= SettingsVersion_v1_7)
2729 && (pelmSnapshotChild->nameEquals("StorageControllers"))
2730 )
2731 readStorageControllers(*pelmSnapshotChild, snap.storage);
2732 else if (pelmSnapshotChild->nameEquals("Snapshots"))
2733 {
2734 xml::NodesLoop nlChildSnapshots(*pelmSnapshotChild);
2735 const xml::ElementNode *pelmChildSnapshot;
2736 while ((pelmChildSnapshot = nlChildSnapshots.forAllNodes()))
2737 {
2738 if (pelmChildSnapshot->nameEquals("Snapshot"))
2739 {
2740 Snapshot child;
2741 readSnapshot(*pelmChildSnapshot, child);
2742 snap.llChildSnapshots.push_back(child);
2743 }
2744 }
2745 }
2746 }
2747
2748 if (m->sv < SettingsVersion_v1_9)
2749 // go through Hardware once more to repair the settings controller structures
2750 // with data from old DVDDrive and FloppyDrive elements
2751 readDVDAndFloppies_pre1_9(*pelmHardware, snap.storage);
2752}
2753
2754void MachineConfigFile::convertOldOSType_pre1_5(Utf8Str &str)
2755{
2756 if (str == "unknown") str = "Other";
2757 else if (str == "dos") str = "DOS";
2758 else if (str == "win31") str = "Windows31";
2759 else if (str == "win95") str = "Windows95";
2760 else if (str == "win98") str = "Windows98";
2761 else if (str == "winme") str = "WindowsMe";
2762 else if (str == "winnt4") str = "WindowsNT4";
2763 else if (str == "win2k") str = "Windows2000";
2764 else if (str == "winxp") str = "WindowsXP";
2765 else if (str == "win2k3") str = "Windows2003";
2766 else if (str == "winvista") str = "WindowsVista";
2767 else if (str == "win2k8") str = "Windows2008";
2768 else if (str == "os2warp3") str = "OS2Warp3";
2769 else if (str == "os2warp4") str = "OS2Warp4";
2770 else if (str == "os2warp45") str = "OS2Warp45";
2771 else if (str == "ecs") str = "OS2eCS";
2772 else if (str == "linux22") str = "Linux22";
2773 else if (str == "linux24") str = "Linux24";
2774 else if (str == "linux26") str = "Linux26";
2775 else if (str == "archlinux") str = "ArchLinux";
2776 else if (str == "debian") str = "Debian";
2777 else if (str == "opensuse") str = "OpenSUSE";
2778 else if (str == "fedoracore") str = "Fedora";
2779 else if (str == "gentoo") str = "Gentoo";
2780 else if (str == "mandriva") str = "Mandriva";
2781 else if (str == "redhat") str = "RedHat";
2782 else if (str == "ubuntu") str = "Ubuntu";
2783 else if (str == "xandros") str = "Xandros";
2784 else if (str == "freebsd") str = "FreeBSD";
2785 else if (str == "openbsd") str = "OpenBSD";
2786 else if (str == "netbsd") str = "NetBSD";
2787 else if (str == "netware") str = "Netware";
2788 else if (str == "solaris") str = "Solaris";
2789 else if (str == "opensolaris") str = "OpenSolaris";
2790 else if (str == "l4") str = "L4";
2791}
2792
2793/**
2794 * Called from the constructor to actually read in the <Machine> element
2795 * of a machine config file.
2796 * @param elmMachine
2797 */
2798void MachineConfigFile::readMachine(const xml::ElementNode &elmMachine)
2799{
2800 Utf8Str strUUID;
2801 if ( (elmMachine.getAttributeValue("uuid", strUUID))
2802 && (elmMachine.getAttributeValue("name", strName))
2803 )
2804 {
2805 parseUUID(uuid, strUUID);
2806
2807 if (!elmMachine.getAttributeValue("nameSync", fNameSync))
2808 fNameSync = true;
2809
2810 Utf8Str str;
2811 elmMachine.getAttributeValue("Description", strDescription);
2812
2813 elmMachine.getAttributeValue("OSType", strOsType);
2814 if (m->sv < SettingsVersion_v1_5)
2815 convertOldOSType_pre1_5(strOsType);
2816
2817 elmMachine.getAttributeValue("stateFile", strStateFile);
2818 if (elmMachine.getAttributeValue("currentSnapshot", str))
2819 parseUUID(uuidCurrentSnapshot, str);
2820 elmMachine.getAttributeValue("snapshotFolder", strSnapshotFolder);
2821 if (!elmMachine.getAttributeValue("currentStateModified", fCurrentStateModified))
2822 fCurrentStateModified = true;
2823 if (elmMachine.getAttributeValue("lastStateChange", str))
2824 parseTimestamp(timeLastStateChange, str);
2825 // constructor has called RTTimeNow(&timeLastStateChange) before
2826
2827 // parse Hardware before the other elements because other things depend on it
2828 const xml::ElementNode *pelmHardware;
2829 if (!(pelmHardware = elmMachine.findChildElement("Hardware")))
2830 throw ConfigFileError(this, &elmMachine, N_("Required Machine/Hardware element is missing"));
2831 readHardware(*pelmHardware, hardwareMachine, storageMachine);
2832
2833 xml::NodesLoop nlRootChildren(elmMachine);
2834 const xml::ElementNode *pelmMachineChild;
2835 while ((pelmMachineChild = nlRootChildren.forAllNodes()))
2836 {
2837 if (pelmMachineChild->nameEquals("ExtraData"))
2838 readExtraData(*pelmMachineChild,
2839 mapExtraDataItems);
2840 else if ( (m->sv < SettingsVersion_v1_7)
2841 && (pelmMachineChild->nameEquals("HardDiskAttachments"))
2842 )
2843 readHardDiskAttachments_pre1_7(*pelmMachineChild, storageMachine);
2844 else if ( (m->sv >= SettingsVersion_v1_7)
2845 && (pelmMachineChild->nameEquals("StorageControllers"))
2846 )
2847 readStorageControllers(*pelmMachineChild, storageMachine);
2848 else if (pelmMachineChild->nameEquals("Snapshot"))
2849 {
2850 Snapshot snap;
2851 // this will recurse into child snapshots, if necessary
2852 readSnapshot(*pelmMachineChild, snap);
2853 llFirstSnapshot.push_back(snap);
2854 }
2855 else if (pelmMachineChild->nameEquals("Description"))
2856 strDescription = pelmMachineChild->getValue();
2857 else if (pelmMachineChild->nameEquals("Teleporter"))
2858 {
2859 if (!pelmMachineChild->getAttributeValue("enabled", fTeleporterEnabled))
2860 fTeleporterEnabled = false;
2861 if (!pelmMachineChild->getAttributeValue("port", uTeleporterPort))
2862 uTeleporterPort = 0;
2863 if (!pelmMachineChild->getAttributeValue("address", strTeleporterAddress))
2864 strTeleporterAddress = "";
2865 if (!pelmMachineChild->getAttributeValue("password", strTeleporterPassword))
2866 strTeleporterPassword = "";
2867 }
2868 }
2869
2870 if (m->sv < SettingsVersion_v1_9)
2871 // go through Hardware once more to repair the settings controller structures
2872 // with data from old DVDDrive and FloppyDrive elements
2873 readDVDAndFloppies_pre1_9(*pelmHardware, storageMachine);
2874 }
2875 else
2876 throw ConfigFileError(this, &elmMachine, N_("Required Machine/@uuid or @name attributes is missing"));
2877}
2878
2879/**
2880 * Creates a <Hardware> node under elmParent and then writes out the XML
2881 * keys under that. Called for both the <Machine> node and for snapshots.
2882 * @param elmParent
2883 * @param st
2884 */
2885void MachineConfigFile::writeHardware(xml::ElementNode &elmParent,
2886 const Hardware &hw,
2887 const Storage &strg)
2888{
2889 xml::ElementNode *pelmHardware = elmParent.createChild("Hardware");
2890
2891 if (m->sv >= SettingsVersion_v1_4)
2892 pelmHardware->setAttribute("version", hw.strVersion);
2893 if ( (m->sv >= SettingsVersion_v1_9)
2894 && (!hw.uuid.isEmpty())
2895 )
2896 pelmHardware->setAttribute("uuid", makeString(hw.uuid));
2897
2898 xml::ElementNode *pelmCPU = pelmHardware->createChild("CPU");
2899
2900 xml::ElementNode *pelmHwVirtEx = pelmCPU->createChild("HardwareVirtEx");
2901 pelmHwVirtEx->setAttribute("enabled", hw.fHardwareVirt);
2902 if (m->sv >= SettingsVersion_v1_9)
2903 pelmHwVirtEx->setAttribute("exclusive", hw.fHardwareVirtExclusive);
2904
2905 pelmCPU->createChild("HardwareVirtExNestedPaging")->setAttribute("enabled", hw.fNestedPaging);
2906 pelmCPU->createChild("HardwareVirtExVPID")->setAttribute("enabled", hw.fVPID);
2907 pelmCPU->createChild("PAE")->setAttribute("enabled", hw.fPAE);
2908
2909 if (hw.fSyntheticCpu)
2910 pelmCPU->createChild("SyntheticCpu")->setAttribute("enabled", hw.fSyntheticCpu);
2911 pelmCPU->setAttribute("count", hw.cCPUs);
2912
2913 if (m->sv >= SettingsVersion_v1_10)
2914 {
2915 pelmCPU->createChild("HardwareVirtExLargePages")->setAttribute("enabled", hw.fLargePages);
2916 pelmCPU->setAttribute("hotplug", hw.fCpuHotPlug);
2917
2918 xml::ElementNode *pelmCpuTree = NULL;
2919 for (CpuList::const_iterator it = hw.llCpus.begin();
2920 it != hw.llCpus.end();
2921 ++it)
2922 {
2923 const Cpu &cpu = *it;
2924
2925 if (pelmCpuTree == NULL)
2926 pelmCpuTree = pelmCPU->createChild("CpuTree");
2927
2928 xml::ElementNode *pelmCpu = pelmCpuTree->createChild("Cpu");
2929 pelmCpu->setAttribute("id", cpu.ulId);
2930 }
2931 }
2932
2933 xml::ElementNode *pelmCpuIdTree = NULL;
2934 for (CpuIdLeafsList::const_iterator it = hw.llCpuIdLeafs.begin();
2935 it != hw.llCpuIdLeafs.end();
2936 ++it)
2937 {
2938 const CpuIdLeaf &leaf = *it;
2939
2940 if (pelmCpuIdTree == NULL)
2941 pelmCpuIdTree = pelmCPU->createChild("CpuIdTree");
2942
2943 xml::ElementNode *pelmCpuIdLeaf = pelmCpuIdTree->createChild("CpuIdLeaf");
2944 pelmCpuIdLeaf->setAttribute("id", leaf.ulId);
2945 pelmCpuIdLeaf->setAttribute("eax", leaf.ulEax);
2946 pelmCpuIdLeaf->setAttribute("ebx", leaf.ulEbx);
2947 pelmCpuIdLeaf->setAttribute("ecx", leaf.ulEcx);
2948 pelmCpuIdLeaf->setAttribute("edx", leaf.ulEdx);
2949 }
2950
2951 xml::ElementNode *pelmMemory = pelmHardware->createChild("Memory");
2952 pelmMemory->setAttribute("RAMSize", hw.ulMemorySizeMB);
2953
2954 if ( (m->sv >= SettingsVersion_v1_9)
2955 && (hw.firmwareType >= FirmwareType_EFI)
2956 )
2957 {
2958 xml::ElementNode *pelmFirmware = pelmHardware->createChild("Firmware");
2959 const char *pcszFirmware;
2960
2961 switch (hw.firmwareType)
2962 {
2963 case FirmwareType_EFI: pcszFirmware = "EFI"; break;
2964 case FirmwareType_EFI32: pcszFirmware = "EFI32"; break;
2965 case FirmwareType_EFI64: pcszFirmware = "EFI64"; break;
2966 case FirmwareType_EFIDUAL: pcszFirmware = "EFIDUAL"; break;
2967 default: pcszFirmware = "None"; break;
2968 }
2969 pelmFirmware->setAttribute("type", pcszFirmware);
2970 }
2971
2972 if ( (m->sv >= SettingsVersion_v1_10)
2973 )
2974 {
2975 xml::ElementNode *pelmHid = pelmHardware->createChild("HID");
2976 const char *pcszHid;
2977
2978 switch (hw.pointingHidType)
2979 {
2980 case PointingHidType_USBMouse: pcszHid = "USBMouse"; break;
2981 case PointingHidType_USBTablet: pcszHid = "USBTablet"; break;
2982 case PointingHidType_PS2Mouse: pcszHid = "PS2Mouse"; break;
2983 case PointingHidType_ComboMouse: pcszHid = "ComboMouse"; break;
2984 case PointingHidType_None: pcszHid = "None"; break;
2985 default: Assert(false); pcszHid = "PS2Mouse"; break;
2986 }
2987 pelmHid->setAttribute("Pointing", pcszHid);
2988
2989 switch (hw.keyboardHidType)
2990 {
2991 case KeyboardHidType_USBKeyboard: pcszHid = "USBKeyboard"; break;
2992 case KeyboardHidType_PS2Keyboard: pcszHid = "PS2Keyboard"; break;
2993 case KeyboardHidType_ComboKeyboard: pcszHid = "ComboKeyboard"; break;
2994 case KeyboardHidType_None: pcszHid = "None"; break;
2995 default: Assert(false); pcszHid = "PS2Keyboard"; break;
2996 }
2997 pelmHid->setAttribute("Keyboard", pcszHid);
2998 }
2999
3000 if ( (m->sv >= SettingsVersion_v1_10)
3001 )
3002 {
3003 xml::ElementNode *pelmHpet = pelmHardware->createChild("HPET");
3004 pelmHpet->setAttribute("enabled", hw.fHpetEnabled);
3005 }
3006
3007 xml::ElementNode *pelmBoot = pelmHardware->createChild("Boot");
3008 for (BootOrderMap::const_iterator it = hw.mapBootOrder.begin();
3009 it != hw.mapBootOrder.end();
3010 ++it)
3011 {
3012 uint32_t i = it->first;
3013 DeviceType_T type = it->second;
3014 const char *pcszDevice;
3015
3016 switch (type)
3017 {
3018 case DeviceType_Floppy: pcszDevice = "Floppy"; break;
3019 case DeviceType_DVD: pcszDevice = "DVD"; break;
3020 case DeviceType_HardDisk: pcszDevice = "HardDisk"; break;
3021 case DeviceType_Network: pcszDevice = "Network"; break;
3022 default: /*case DeviceType_Null:*/ pcszDevice = "None"; break;
3023 }
3024
3025 xml::ElementNode *pelmOrder = pelmBoot->createChild("Order");
3026 pelmOrder->setAttribute("position",
3027 i + 1); // XML is 1-based but internal data is 0-based
3028 pelmOrder->setAttribute("device", pcszDevice);
3029 }
3030
3031 xml::ElementNode *pelmDisplay = pelmHardware->createChild("Display");
3032 pelmDisplay->setAttribute("VRAMSize", hw.ulVRAMSizeMB);
3033 pelmDisplay->setAttribute("monitorCount", hw.cMonitors);
3034 pelmDisplay->setAttribute("accelerate3D", hw.fAccelerate3D);
3035
3036 if (m->sv >= SettingsVersion_v1_8)
3037 pelmDisplay->setAttribute("accelerate2DVideo", hw.fAccelerate2DVideo);
3038
3039 xml::ElementNode *pelmVRDP = pelmHardware->createChild("RemoteDisplay");
3040 pelmVRDP->setAttribute("enabled", hw.vrdpSettings.fEnabled);
3041 Utf8Str strPort = hw.vrdpSettings.strPort;
3042 if (!strPort.length())
3043 strPort = "3389";
3044 pelmVRDP->setAttribute("port", strPort);
3045 if (hw.vrdpSettings.strNetAddress.length())
3046 pelmVRDP->setAttribute("netAddress", hw.vrdpSettings.strNetAddress);
3047 const char *pcszAuthType;
3048 switch (hw.vrdpSettings.authType)
3049 {
3050 case VRDPAuthType_Guest: pcszAuthType = "Guest"; break;
3051 case VRDPAuthType_External: pcszAuthType = "External"; break;
3052 default: /*case VRDPAuthType_Null:*/ pcszAuthType = "Null"; break;
3053 }
3054 pelmVRDP->setAttribute("authType", pcszAuthType);
3055
3056 if (hw.vrdpSettings.ulAuthTimeout != 0)
3057 pelmVRDP->setAttribute("authTimeout", hw.vrdpSettings.ulAuthTimeout);
3058 if (hw.vrdpSettings.fAllowMultiConnection)
3059 pelmVRDP->setAttribute("allowMultiConnection", hw.vrdpSettings.fAllowMultiConnection);
3060 if (hw.vrdpSettings.fReuseSingleConnection)
3061 pelmVRDP->setAttribute("reuseSingleConnection", hw.vrdpSettings.fReuseSingleConnection);
3062
3063 xml::ElementNode *pelmBIOS = pelmHardware->createChild("BIOS");
3064 pelmBIOS->createChild("ACPI")->setAttribute("enabled", hw.biosSettings.fACPIEnabled);
3065 pelmBIOS->createChild("IOAPIC")->setAttribute("enabled", hw.biosSettings.fIOAPICEnabled);
3066
3067 xml::ElementNode *pelmLogo = pelmBIOS->createChild("Logo");
3068 pelmLogo->setAttribute("fadeIn", hw.biosSettings.fLogoFadeIn);
3069 pelmLogo->setAttribute("fadeOut", hw.biosSettings.fLogoFadeOut);
3070 pelmLogo->setAttribute("displayTime", hw.biosSettings.ulLogoDisplayTime);
3071 if (hw.biosSettings.strLogoImagePath.length())
3072 pelmLogo->setAttribute("imagePath", hw.biosSettings.strLogoImagePath);
3073
3074 const char *pcszBootMenu;
3075 switch (hw.biosSettings.biosBootMenuMode)
3076 {
3077 case BIOSBootMenuMode_Disabled: pcszBootMenu = "Disabled"; break;
3078 case BIOSBootMenuMode_MenuOnly: pcszBootMenu = "MenuOnly"; break;
3079 default: /*BIOSBootMenuMode_MessageAndMenu*/ pcszBootMenu = "MessageAndMenu"; break;
3080 }
3081 pelmBIOS->createChild("BootMenu")->setAttribute("mode", pcszBootMenu);
3082 pelmBIOS->createChild("TimeOffset")->setAttribute("value", hw.biosSettings.llTimeOffset);
3083 pelmBIOS->createChild("PXEDebug")->setAttribute("enabled", hw.biosSettings.fPXEDebugEnabled);
3084
3085 if (m->sv < SettingsVersion_v1_9)
3086 {
3087 // settings formats before 1.9 had separate DVDDrive and FloppyDrive items under Hardware;
3088 // run thru the storage controllers to see if we have a DVD or floppy drives
3089 size_t cDVDs = 0;
3090 size_t cFloppies = 0;
3091
3092 xml::ElementNode *pelmDVD = pelmHardware->createChild("DVDDrive");
3093 xml::ElementNode *pelmFloppy = pelmHardware->createChild("FloppyDrive");
3094
3095 for (StorageControllersList::const_iterator it = strg.llStorageControllers.begin();
3096 it != strg.llStorageControllers.end();
3097 ++it)
3098 {
3099 const StorageController &sctl = *it;
3100 // in old settings format, the DVD drive could only have been under the IDE controller
3101 if (sctl.storageBus == StorageBus_IDE)
3102 {
3103 for (AttachedDevicesList::const_iterator it2 = sctl.llAttachedDevices.begin();
3104 it2 != sctl.llAttachedDevices.end();
3105 ++it2)
3106 {
3107 const AttachedDevice &att = *it2;
3108 if (att.deviceType == DeviceType_DVD)
3109 {
3110 if (cDVDs > 0)
3111 throw ConfigFileError(this, NULL, N_("Internal error: cannot save more than one DVD drive with old settings format"));
3112
3113 ++cDVDs;
3114
3115 pelmDVD->setAttribute("passthrough", att.fPassThrough);
3116 if (!att.uuid.isEmpty())
3117 pelmDVD->createChild("Image")->setAttribute("uuid", makeString(att.uuid));
3118 else if (att.strHostDriveSrc.length())
3119 pelmDVD->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
3120 }
3121 }
3122 }
3123 else if (sctl.storageBus == StorageBus_Floppy)
3124 {
3125 size_t cFloppiesHere = sctl.llAttachedDevices.size();
3126 if (cFloppiesHere > 1)
3127 throw ConfigFileError(this, NULL, N_("Internal error: floppy controller cannot have more than one device attachment"));
3128 if (cFloppiesHere)
3129 {
3130 const AttachedDevice &att = sctl.llAttachedDevices.front();
3131 pelmFloppy->setAttribute("enabled", true);
3132 if (!att.uuid.isEmpty())
3133 pelmFloppy->createChild("Image")->setAttribute("uuid", makeString(att.uuid));
3134 else if (att.strHostDriveSrc.length())
3135 pelmFloppy->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
3136 }
3137
3138 cFloppies += cFloppiesHere;
3139 }
3140 }
3141
3142 if (cFloppies == 0)
3143 pelmFloppy->setAttribute("enabled", false);
3144 else if (cFloppies > 1)
3145 throw ConfigFileError(this, NULL, N_("Internal error: cannot save more than one floppy drive with old settings format"));
3146 }
3147
3148 xml::ElementNode *pelmUSB = pelmHardware->createChild("USBController");
3149 pelmUSB->setAttribute("enabled", hw.usbController.fEnabled);
3150 pelmUSB->setAttribute("enabledEhci", hw.usbController.fEnabledEHCI);
3151
3152 writeUSBDeviceFilters(*pelmUSB,
3153 hw.usbController.llDeviceFilters,
3154 false); // fHostMode
3155
3156 xml::ElementNode *pelmNetwork = pelmHardware->createChild("Network");
3157 for (NetworkAdaptersList::const_iterator it = hw.llNetworkAdapters.begin();
3158 it != hw.llNetworkAdapters.end();
3159 ++it)
3160 {
3161 const NetworkAdapter &nic = *it;
3162
3163 xml::ElementNode *pelmAdapter = pelmNetwork->createChild("Adapter");
3164 pelmAdapter->setAttribute("slot", nic.ulSlot);
3165 pelmAdapter->setAttribute("enabled", nic.fEnabled);
3166 pelmAdapter->setAttribute("MACAddress", nic.strMACAddress);
3167 pelmAdapter->setAttribute("cable", nic.fCableConnected);
3168 pelmAdapter->setAttribute("speed", nic.ulLineSpeed);
3169 if (nic.fTraceEnabled)
3170 {
3171 pelmAdapter->setAttribute("trace", nic.fTraceEnabled);
3172 pelmAdapter->setAttribute("tracefile", nic.strTraceFile);
3173 }
3174
3175 const char *pcszType;
3176 switch (nic.type)
3177 {
3178 case NetworkAdapterType_Am79C973: pcszType = "Am79C973"; break;
3179 case NetworkAdapterType_I82540EM: pcszType = "82540EM"; break;
3180 case NetworkAdapterType_I82543GC: pcszType = "82543GC"; break;
3181 case NetworkAdapterType_I82545EM: pcszType = "82545EM"; break;
3182 case NetworkAdapterType_Virtio: pcszType = "virtio"; break;
3183 default: /*case NetworkAdapterType_Am79C970A:*/ pcszType = "Am79C970A"; break;
3184 }
3185 pelmAdapter->setAttribute("type", pcszType);
3186
3187 xml::ElementNode *pelmNAT;
3188 switch (nic.mode)
3189 {
3190 case NetworkAttachmentType_NAT:
3191 pelmNAT = pelmAdapter->createChild("NAT");
3192 if (nic.strName.length())
3193 pelmNAT->setAttribute("network", nic.strName);
3194 break;
3195
3196 case NetworkAttachmentType_Bridged:
3197 pelmAdapter->createChild("BridgedInterface")->setAttribute("name", nic.strName);
3198 break;
3199
3200 case NetworkAttachmentType_Internal:
3201 pelmAdapter->createChild("InternalNetwork")->setAttribute("name", nic.strName);
3202 break;
3203
3204 case NetworkAttachmentType_HostOnly:
3205 pelmAdapter->createChild("HostOnlyInterface")->setAttribute("name", nic.strName);
3206 break;
3207
3208 default: /*case NetworkAttachmentType_Null:*/
3209 break;
3210 }
3211 }
3212
3213 xml::ElementNode *pelmPorts = pelmHardware->createChild("UART");
3214 for (SerialPortsList::const_iterator it = hw.llSerialPorts.begin();
3215 it != hw.llSerialPorts.end();
3216 ++it)
3217 {
3218 const SerialPort &port = *it;
3219 xml::ElementNode *pelmPort = pelmPorts->createChild("Port");
3220 pelmPort->setAttribute("slot", port.ulSlot);
3221 pelmPort->setAttribute("enabled", port.fEnabled);
3222 pelmPort->setAttributeHex("IOBase", port.ulIOBase);
3223 pelmPort->setAttribute("IRQ", port.ulIRQ);
3224
3225 const char *pcszHostMode;
3226 switch (port.portMode)
3227 {
3228 case PortMode_HostPipe: pcszHostMode = "HostPipe"; break;
3229 case PortMode_HostDevice: pcszHostMode = "HostDevice"; break;
3230 case PortMode_RawFile: pcszHostMode = "RawFile"; break;
3231 default: /*case PortMode_Disconnected:*/ pcszHostMode = "Disconnected"; break;
3232 }
3233 switch (port.portMode)
3234 {
3235 case PortMode_HostPipe:
3236 pelmPort->setAttribute("server", port.fServer);
3237 /* no break */
3238 case PortMode_HostDevice:
3239 case PortMode_RawFile:
3240 pelmPort->setAttribute("path", port.strPath);
3241 break;
3242
3243 default:
3244 break;
3245 }
3246 pelmPort->setAttribute("hostMode", pcszHostMode);
3247 }
3248
3249 pelmPorts = pelmHardware->createChild("LPT");
3250 for (ParallelPortsList::const_iterator it = hw.llParallelPorts.begin();
3251 it != hw.llParallelPorts.end();
3252 ++it)
3253 {
3254 const ParallelPort &port = *it;
3255 xml::ElementNode *pelmPort = pelmPorts->createChild("Port");
3256 pelmPort->setAttribute("slot", port.ulSlot);
3257 pelmPort->setAttribute("enabled", port.fEnabled);
3258 pelmPort->setAttributeHex("IOBase", port.ulIOBase);
3259 pelmPort->setAttribute("IRQ", port.ulIRQ);
3260 if (port.strPath.length())
3261 pelmPort->setAttribute("path", port.strPath);
3262 }
3263
3264 xml::ElementNode *pelmAudio = pelmHardware->createChild("AudioAdapter");
3265 pelmAudio->setAttribute("controller", (hw.audioAdapter.controllerType == AudioControllerType_SB16) ? "SB16" : "AC97");
3266
3267 if ( m->sv >= SettingsVersion_v1_10)
3268 {
3269 xml::ElementNode *pelmRTC = pelmHardware->createChild("RTC");
3270 pelmRTC->setAttribute("localOrUTC", fRTCUseUTC ? "UTC" : "local");
3271 }
3272
3273 const char *pcszDriver;
3274 switch (hw.audioAdapter.driverType)
3275 {
3276 case AudioDriverType_WinMM: pcszDriver = "WinMM"; break;
3277 case AudioDriverType_DirectSound: pcszDriver = "DirectSound"; break;
3278 case AudioDriverType_SolAudio: pcszDriver = "SolAudio"; break;
3279 case AudioDriverType_ALSA: pcszDriver = "ALSA"; break;
3280 case AudioDriverType_Pulse: pcszDriver = "Pulse"; break;
3281 case AudioDriverType_OSS: pcszDriver = "OSS"; break;
3282 case AudioDriverType_CoreAudio: pcszDriver = "CoreAudio"; break;
3283 case AudioDriverType_MMPM: pcszDriver = "MMPM"; break;
3284 default: /*case AudioDriverType_Null:*/ pcszDriver = "Null"; break;
3285 }
3286 pelmAudio->setAttribute("driver", pcszDriver);
3287
3288 pelmAudio->setAttribute("enabled", hw.audioAdapter.fEnabled);
3289
3290 xml::ElementNode *pelmSharedFolders = pelmHardware->createChild("SharedFolders");
3291 for (SharedFoldersList::const_iterator it = hw.llSharedFolders.begin();
3292 it != hw.llSharedFolders.end();
3293 ++it)
3294 {
3295 const SharedFolder &sf = *it;
3296 xml::ElementNode *pelmThis = pelmSharedFolders->createChild("SharedFolder");
3297 pelmThis->setAttribute("name", sf.strName);
3298 pelmThis->setAttribute("hostPath", sf.strHostPath);
3299 pelmThis->setAttribute("writable", sf.fWritable);
3300 }
3301
3302 xml::ElementNode *pelmClip = pelmHardware->createChild("Clipboard");
3303 const char *pcszClip;
3304 switch (hw.clipboardMode)
3305 {
3306 case ClipboardMode_Disabled: pcszClip = "Disabled"; break;
3307 case ClipboardMode_HostToGuest: pcszClip = "HostToGuest"; break;
3308 case ClipboardMode_GuestToHost: pcszClip = "GuestToHost"; break;
3309 default: /*case ClipboardMode_Bidirectional:*/ pcszClip = "Bidirectional"; break;
3310 }
3311 pelmClip->setAttribute("mode", pcszClip);
3312
3313 xml::ElementNode *pelmGuest = pelmHardware->createChild("Guest");
3314 pelmGuest->setAttribute("memoryBalloonSize", hw.ulMemoryBalloonSize);
3315 pelmGuest->setAttribute("statisticsUpdateInterval", hw.ulStatisticsUpdateInterval);
3316
3317 xml::ElementNode *pelmGuestProps = pelmHardware->createChild("GuestProperties");
3318 for (GuestPropertiesList::const_iterator it = hw.llGuestProperties.begin();
3319 it != hw.llGuestProperties.end();
3320 ++it)
3321 {
3322 const GuestProperty &prop = *it;
3323 xml::ElementNode *pelmProp = pelmGuestProps->createChild("GuestProperty");
3324 pelmProp->setAttribute("name", prop.strName);
3325 pelmProp->setAttribute("value", prop.strValue);
3326 pelmProp->setAttribute("timestamp", prop.timestamp);
3327 pelmProp->setAttribute("flags", prop.strFlags);
3328 }
3329
3330 if (hw.strNotificationPatterns.length())
3331 pelmGuestProps->setAttribute("notificationPatterns", hw.strNotificationPatterns);
3332}
3333
3334/**
3335 * Creates a <StorageControllers> node under elmParent and then writes out the XML
3336 * keys under that. Called for both the <Machine> node and for snapshots.
3337 * @param elmParent
3338 * @param st
3339 */
3340void MachineConfigFile::writeStorageControllers(xml::ElementNode &elmParent,
3341 const Storage &st)
3342{
3343 xml::ElementNode *pelmStorageControllers = elmParent.createChild("StorageControllers");
3344
3345 for (StorageControllersList::const_iterator it = st.llStorageControllers.begin();
3346 it != st.llStorageControllers.end();
3347 ++it)
3348 {
3349 const StorageController &sc = *it;
3350
3351 if ( (m->sv < SettingsVersion_v1_9)
3352 && (sc.controllerType == StorageControllerType_I82078)
3353 )
3354 // floppy controller already got written into <Hardware>/<FloppyController> in writeHardware()
3355 // for pre-1.9 settings
3356 continue;
3357
3358 xml::ElementNode *pelmController = pelmStorageControllers->createChild("StorageController");
3359 com::Utf8Str name = sc.strName.raw();
3360 //
3361 if (m->sv < SettingsVersion_v1_8)
3362 {
3363 // pre-1.8 settings use shorter controller names, they are
3364 // expanded when reading the settings
3365 if (name == "IDE Controller")
3366 name = "IDE";
3367 else if (name == "SATA Controller")
3368 name = "SATA";
3369 else if (name == "SCSI Controller")
3370 name = "SCSI";
3371 }
3372 pelmController->setAttribute("name", sc.strName);
3373
3374 const char *pcszType;
3375 switch (sc.controllerType)
3376 {
3377 case StorageControllerType_IntelAhci: pcszType = "AHCI"; break;
3378 case StorageControllerType_LsiLogic: pcszType = "LsiLogic"; break;
3379 case StorageControllerType_BusLogic: pcszType = "BusLogic"; break;
3380 case StorageControllerType_PIIX4: pcszType = "PIIX4"; break;
3381 case StorageControllerType_ICH6: pcszType = "ICH6"; break;
3382 case StorageControllerType_I82078: pcszType = "I82078"; break;
3383 case StorageControllerType_LsiLogicSas: pcszType = "LsiLogicSas"; break;
3384 default: /*case StorageControllerType_PIIX3:*/ pcszType = "PIIX3"; break;
3385 }
3386 pelmController->setAttribute("type", pcszType);
3387
3388 pelmController->setAttribute("PortCount", sc.ulPortCount);
3389
3390 if (m->sv >= SettingsVersion_v1_9)
3391 if (sc.ulInstance)
3392 pelmController->setAttribute("Instance", sc.ulInstance);
3393
3394 if (sc.controllerType == StorageControllerType_IntelAhci)
3395 {
3396 pelmController->setAttribute("IDE0MasterEmulationPort", sc.lIDE0MasterEmulationPort);
3397 pelmController->setAttribute("IDE0SlaveEmulationPort", sc.lIDE0SlaveEmulationPort);
3398 pelmController->setAttribute("IDE1MasterEmulationPort", sc.lIDE1MasterEmulationPort);
3399 pelmController->setAttribute("IDE1SlaveEmulationPort", sc.lIDE1SlaveEmulationPort);
3400 }
3401
3402 for (AttachedDevicesList::const_iterator it2 = sc.llAttachedDevices.begin();
3403 it2 != sc.llAttachedDevices.end();
3404 ++it2)
3405 {
3406 const AttachedDevice &att = *it2;
3407
3408 // For settings version before 1.9, DVDs and floppies are in hardware, not storage controllers,
3409 // so we shouldn't write them here; we only get here for DVDs though because we ruled out
3410 // the floppy controller at the top of the loop
3411 if ( att.deviceType == DeviceType_DVD
3412 && m->sv < SettingsVersion_v1_9
3413 )
3414 continue;
3415
3416 xml::ElementNode *pelmDevice = pelmController->createChild("AttachedDevice");
3417
3418 pcszType = NULL;
3419
3420 switch (att.deviceType)
3421 {
3422 case DeviceType_HardDisk:
3423 pcszType = "HardDisk";
3424 break;
3425
3426 case DeviceType_DVD:
3427 pcszType = "DVD";
3428 pelmDevice->setAttribute("passthrough", att.fPassThrough);
3429 break;
3430
3431 case DeviceType_Floppy:
3432 pcszType = "Floppy";
3433 break;
3434 }
3435
3436 pelmDevice->setAttribute("type", pcszType);
3437
3438 pelmDevice->setAttribute("port", att.lPort);
3439 pelmDevice->setAttribute("device", att.lDevice);
3440
3441 if (!att.uuid.isEmpty())
3442 pelmDevice->createChild("Image")->setAttribute("uuid", makeString(att.uuid));
3443 else if ( (m->sv >= SettingsVersion_v1_9)
3444 && (att.strHostDriveSrc.length())
3445 )
3446 pelmDevice->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
3447 }
3448 }
3449}
3450
3451/**
3452 * Writes a single snapshot into the DOM tree. Initially this gets called from MachineConfigFile::write()
3453 * for the root snapshot of a machine, if present; elmParent then points to the <Snapshots> node under the
3454 * <Machine> node to which <Snapshot> must be added. This may then recurse for child snapshots.
3455 * @param elmParent
3456 * @param snap
3457 */
3458void MachineConfigFile::writeSnapshot(xml::ElementNode &elmParent,
3459 const Snapshot &snap)
3460{
3461 xml::ElementNode *pelmSnapshot = elmParent.createChild("Snapshot");
3462
3463 pelmSnapshot->setAttribute("uuid", makeString(snap.uuid));
3464 pelmSnapshot->setAttribute("name", snap.strName);
3465 pelmSnapshot->setAttribute("timeStamp", makeString(snap.timestamp));
3466
3467 if (snap.strStateFile.length())
3468 pelmSnapshot->setAttribute("stateFile", snap.strStateFile);
3469
3470 if (snap.strDescription.length())
3471 pelmSnapshot->createChild("Description")->addContent(snap.strDescription);
3472
3473 writeHardware(*pelmSnapshot, snap.hardware, snap.storage);
3474 writeStorageControllers(*pelmSnapshot, snap.storage);
3475
3476 if (snap.llChildSnapshots.size())
3477 {
3478 xml::ElementNode *pelmChildren = pelmSnapshot->createChild("Snapshots");
3479 for (SnapshotsList::const_iterator it = snap.llChildSnapshots.begin();
3480 it != snap.llChildSnapshots.end();
3481 ++it)
3482 {
3483 const Snapshot &child = *it;
3484 writeSnapshot(*pelmChildren, child);
3485 }
3486 }
3487}
3488
3489/**
3490 * Called from write() before calling ConfigFileBase::createStubDocument().
3491 * This adjusts the settings version in m->sv if incompatible settings require
3492 * a settings bump, whereas otherwise we try to preserve the settings version
3493 * to avoid breaking compatibility with older versions.
3494 */
3495void MachineConfigFile::bumpSettingsVersionIfNeeded()
3496{
3497 // The hardware versions other than "1" requires settings version 1.4 (2.1+).
3498 if ( m->sv < SettingsVersion_v1_4
3499 && hardwareMachine.strVersion != "1"
3500 )
3501 m->sv = SettingsVersion_v1_4;
3502
3503 // "accelerate 2d video" requires settings version 1.8
3504 if ( (m->sv < SettingsVersion_v1_8)
3505 && (hardwareMachine.fAccelerate2DVideo)
3506 )
3507 m->sv = SettingsVersion_v1_8;
3508
3509 // all the following require settings version 1.9
3510 if ( (m->sv < SettingsVersion_v1_9)
3511 && ( (hardwareMachine.firmwareType >= FirmwareType_EFI)
3512 || (hardwareMachine.fHardwareVirtExclusive != HWVIRTEXCLUSIVEDEFAULT)
3513 || fTeleporterEnabled
3514 || uTeleporterPort
3515 || !strTeleporterAddress.isEmpty()
3516 || !strTeleporterPassword.isEmpty()
3517 || !hardwareMachine.uuid.isEmpty()
3518 )
3519 )
3520 m->sv = SettingsVersion_v1_9;
3521
3522 // settings version 1.9 is also required if there is not exactly one DVD
3523 // or more than one floppy drive present or the DVD is not at the secondary
3524 // master; this check is a bit more complicated
3525 if (m->sv < SettingsVersion_v1_9)
3526 {
3527 size_t cDVDs = 0;
3528 size_t cFloppies = 0;
3529
3530 // need to run thru all the storage controllers to figure this out
3531 for (StorageControllersList::const_iterator it = storageMachine.llStorageControllers.begin();
3532 it != storageMachine.llStorageControllers.end()
3533 && m->sv < SettingsVersion_v1_9;
3534 ++it)
3535 {
3536 const StorageController &sctl = *it;
3537 for (AttachedDevicesList::const_iterator it2 = sctl.llAttachedDevices.begin();
3538 it2 != sctl.llAttachedDevices.end();
3539 ++it2)
3540 {
3541 if (sctl.ulInstance != 0) // we can only write the StorageController/@Instance attribute with v1.9
3542 {
3543 m->sv = SettingsVersion_v1_9;
3544 break;
3545 }
3546
3547 const AttachedDevice &att = *it2;
3548 if (att.deviceType == DeviceType_DVD)
3549 {
3550 if ( (sctl.storageBus != StorageBus_IDE) // DVD at bus other than DVD?
3551 || (att.lPort != 1) // DVDs not at secondary master?
3552 || (att.lDevice != 0)
3553 )
3554 {
3555 m->sv = SettingsVersion_v1_9;
3556 break;
3557 }
3558
3559 ++cDVDs;
3560 }
3561 else if (att.deviceType == DeviceType_Floppy)
3562 ++cFloppies;
3563 }
3564 }
3565
3566 // VirtualBox before 3.1 had zero or one floppy and exactly one DVD,
3567 // so any deviation from that will require settings version 1.9
3568 if ( (m->sv < SettingsVersion_v1_9)
3569 && ( (cDVDs != 1)
3570 || (cFloppies > 1)
3571 )
3572 )
3573 m->sv = SettingsVersion_v1_9;
3574 }
3575
3576 // VirtualBox 3.2 adds support for CPU hotplug, RTC timezone control, HID type and HPET
3577 if ( m->sv < SettingsVersion_v1_10
3578 && ( fRTCUseUTC
3579 || hardwareMachine.fCpuHotPlug
3580 || hardwareMachine.pointingHidType != PointingHidType_PS2Mouse
3581 || hardwareMachine.keyboardHidType != KeyboardHidType_PS2Keyboard
3582 || hardwareMachine.fHpetEnabled
3583 )
3584 )
3585 m->sv = SettingsVersion_v1_10;
3586}
3587
3588/**
3589 * Called from Main code to write a machine config file to disk. This builds a DOM tree from
3590 * the member variables and then writes the XML file; it throws xml::Error instances on errors,
3591 * in particular if the file cannot be written.
3592 */
3593void MachineConfigFile::write(const com::Utf8Str &strFilename)
3594{
3595 try
3596 {
3597 // createStubDocument() sets the settings version to at least 1.7; however,
3598 // we might need to enfore a later settings version if incompatible settings
3599 // are present:
3600 bumpSettingsVersionIfNeeded();
3601
3602 m->strFilename = strFilename;
3603 createStubDocument();
3604
3605 xml::ElementNode *pelmMachine = m->pelmRoot->createChild("Machine");
3606
3607 pelmMachine->setAttribute("uuid", makeString(uuid));
3608 pelmMachine->setAttribute("name", strName);
3609 if (!fNameSync)
3610 pelmMachine->setAttribute("nameSync", fNameSync);
3611 if (strDescription.length())
3612 pelmMachine->createChild("Description")->addContent(strDescription);
3613 pelmMachine->setAttribute("OSType", strOsType);
3614 if (strStateFile.length())
3615 pelmMachine->setAttribute("stateFile", strStateFile);
3616 if (!uuidCurrentSnapshot.isEmpty())
3617 pelmMachine->setAttribute("currentSnapshot", makeString(uuidCurrentSnapshot));
3618 if (strSnapshotFolder.length())
3619 pelmMachine->setAttribute("snapshotFolder", strSnapshotFolder);
3620 if (!fCurrentStateModified)
3621 pelmMachine->setAttribute("currentStateModified", fCurrentStateModified);
3622 pelmMachine->setAttribute("lastStateChange", makeString(timeLastStateChange));
3623 if (fAborted)
3624 pelmMachine->setAttribute("aborted", fAborted);
3625 if ( m->sv >= SettingsVersion_v1_9
3626 && ( fTeleporterEnabled
3627 || uTeleporterPort
3628 || !strTeleporterAddress.isEmpty()
3629 || !strTeleporterPassword.isEmpty()
3630 )
3631 )
3632 {
3633 xml::ElementNode *pelmTeleporter = pelmMachine->createChild("Teleporter");
3634 pelmTeleporter->setAttribute("enabled", fTeleporterEnabled);
3635 pelmTeleporter->setAttribute("port", uTeleporterPort);
3636 pelmTeleporter->setAttribute("address", strTeleporterAddress);
3637 pelmTeleporter->setAttribute("password", strTeleporterPassword);
3638 }
3639
3640 writeExtraData(*pelmMachine, mapExtraDataItems);
3641
3642 if (llFirstSnapshot.size())
3643 writeSnapshot(*pelmMachine, llFirstSnapshot.front());
3644
3645 writeHardware(*pelmMachine, hardwareMachine, storageMachine);
3646 writeStorageControllers(*pelmMachine, storageMachine);
3647
3648 // now go write the XML
3649 xml::XmlFileWriter writer(*m->pDoc);
3650 writer.write(m->strFilename.c_str());
3651
3652 m->fFileExists = true;
3653 clearDocument();
3654 }
3655 catch (...)
3656 {
3657 clearDocument();
3658 throw;
3659 }
3660}
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