VirtualBox

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

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

Main: configurable HID types work

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Revision Author Id
File size: 150.3 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 fVPID(true),
1464 fSyntheticCpu(false),
1465 fPAE(false),
1466 cCPUs(1),
1467 fCpuHotPlug(false),
1468 ulMemorySizeMB((uint32_t)-1),
1469 ulVRAMSizeMB(8),
1470 cMonitors(1),
1471 fAccelerate3D(false),
1472 fAccelerate2DVideo(false),
1473 firmwareType(FirmwareType_BIOS),
1474 pointingHidType(PointingHidType_PS2Mouse),
1475 keyboardHidType(KeyboardHidType_PS2Keyboard),
1476 clipboardMode(ClipboardMode_Bidirectional),
1477 ulMemoryBalloonSize(0),
1478 ulStatisticsUpdateInterval(0)
1479{
1480 mapBootOrder[0] = DeviceType_Floppy;
1481 mapBootOrder[1] = DeviceType_DVD;
1482 mapBootOrder[2] = DeviceType_HardDisk;
1483
1484 /* The default value for PAE depends on the host:
1485 * - 64 bits host -> always true
1486 * - 32 bits host -> true for Windows & Darwin (masked off if the host cpu doesn't support it anyway)
1487 */
1488#if HC_ARCH_BITS == 64 || defined(RT_OS_WINDOWS) || defined(RT_OS_DARWIN)
1489 fPAE = true;
1490#endif
1491}
1492
1493/**
1494 * Comparison operator. This gets called from MachineConfigFile::operator==,
1495 * which in turn gets called from Machine::saveSettings to figure out whether
1496 * machine settings have really changed and thus need to be written out to disk.
1497 */
1498bool Hardware::operator==(const Hardware& h) const
1499{
1500 return ( (this == &h)
1501 || ( (strVersion == h.strVersion)
1502 && (uuid == h.uuid)
1503 && (fHardwareVirt == h.fHardwareVirt)
1504 && (fHardwareVirtExclusive == h.fHardwareVirtExclusive)
1505 && (fNestedPaging == h.fNestedPaging)
1506 && (fVPID == h.fVPID)
1507 && (fSyntheticCpu == h.fSyntheticCpu)
1508 && (fPAE == h.fPAE)
1509 && (cCPUs == h.cCPUs)
1510 && (fCpuHotPlug == h.fCpuHotPlug)
1511 && (llCpus == h.llCpus)
1512 && (llCpuIdLeafs == h.llCpuIdLeafs)
1513 && (ulMemorySizeMB == h.ulMemorySizeMB)
1514 && (mapBootOrder == h.mapBootOrder)
1515 && (ulVRAMSizeMB == h.ulVRAMSizeMB)
1516 && (cMonitors == h.cMonitors)
1517 && (fAccelerate3D == h.fAccelerate3D)
1518 && (fAccelerate2DVideo == h.fAccelerate2DVideo)
1519 && (firmwareType == h.firmwareType)
1520 && (pointingHidType == h.pointingHidType)
1521 && (keyboardHidType == h.keyboardHidType)
1522 && (vrdpSettings == h.vrdpSettings)
1523 && (biosSettings == h.biosSettings)
1524 && (usbController == h.usbController)
1525 && (llNetworkAdapters == h.llNetworkAdapters)
1526 && (llSerialPorts == h.llSerialPorts)
1527 && (llParallelPorts == h.llParallelPorts)
1528 && (audioAdapter == h.audioAdapter)
1529 && (llSharedFolders == h.llSharedFolders)
1530 && (clipboardMode == h.clipboardMode)
1531 && (ulMemoryBalloonSize == h.ulMemoryBalloonSize)
1532 && (ulStatisticsUpdateInterval == h.ulStatisticsUpdateInterval)
1533 && (llGuestProperties == h.llGuestProperties)
1534 && (strNotificationPatterns == h.strNotificationPatterns)
1535 )
1536 );
1537}
1538
1539/**
1540 * Comparison operator. This gets called from MachineConfigFile::operator==,
1541 * which in turn gets called from Machine::saveSettings to figure out whether
1542 * machine settings have really changed and thus need to be written out to disk.
1543 */
1544bool AttachedDevice::operator==(const AttachedDevice &a) const
1545{
1546 return ( (this == &a)
1547 || ( (deviceType == a.deviceType)
1548 && (fPassThrough == a.fPassThrough)
1549 && (lPort == a.lPort)
1550 && (lDevice == a.lDevice)
1551 && (uuid == a.uuid)
1552 && (strHostDriveSrc == a.strHostDriveSrc)
1553 )
1554 );
1555}
1556
1557/**
1558 * Comparison operator. This gets called from MachineConfigFile::operator==,
1559 * which in turn gets called from Machine::saveSettings to figure out whether
1560 * machine settings have really changed and thus need to be written out to disk.
1561 */
1562bool StorageController::operator==(const StorageController &s) const
1563{
1564 return ( (this == &s)
1565 || ( (strName == s.strName)
1566 && (storageBus == s.storageBus)
1567 && (controllerType == s.controllerType)
1568 && (ulPortCount == s.ulPortCount)
1569 && (ulInstance == s.ulInstance)
1570 && (lIDE0MasterEmulationPort == s.lIDE0MasterEmulationPort)
1571 && (lIDE0SlaveEmulationPort == s.lIDE0SlaveEmulationPort)
1572 && (lIDE1MasterEmulationPort == s.lIDE1MasterEmulationPort)
1573 && (lIDE1SlaveEmulationPort == s.lIDE1SlaveEmulationPort)
1574 && (llAttachedDevices == s.llAttachedDevices)
1575 )
1576 );
1577}
1578
1579/**
1580 * Comparison operator. This gets called from MachineConfigFile::operator==,
1581 * which in turn gets called from Machine::saveSettings to figure out whether
1582 * machine settings have really changed and thus need to be written out to disk.
1583 */
1584bool Storage::operator==(const Storage &s) const
1585{
1586 return ( (this == &s)
1587 || (llStorageControllers == s.llStorageControllers) // deep compare
1588 );
1589}
1590
1591/**
1592 * Comparison operator. This gets called from MachineConfigFile::operator==,
1593 * which in turn gets called from Machine::saveSettings to figure out whether
1594 * machine settings have really changed and thus need to be written out to disk.
1595 */
1596bool Snapshot::operator==(const Snapshot &s) const
1597{
1598 return ( (this == &s)
1599 || ( (uuid == s.uuid)
1600 && (strName == s.strName)
1601 && (strDescription == s.strDescription)
1602 && (RTTimeSpecIsEqual(&timestamp, &s.timestamp))
1603 && (strStateFile == s.strStateFile)
1604 && (hardware == s.hardware) // deep compare
1605 && (storage == s.storage) // deep compare
1606 && (llChildSnapshots == s.llChildSnapshots) // deep compare
1607 )
1608 );
1609}
1610
1611////////////////////////////////////////////////////////////////////////////////
1612//
1613// MachineConfigFile
1614//
1615////////////////////////////////////////////////////////////////////////////////
1616
1617/**
1618 * Constructor.
1619 *
1620 * If pstrFilename is != NULL, this reads the given settings file into the member
1621 * variables and various substructures and lists. Otherwise, the member variables
1622 * are initialized with default values.
1623 *
1624 * Throws variants of xml::Error for I/O, XML and logical content errors, which
1625 * the caller should catch; if this constructor does not throw, then the member
1626 * variables contain meaningful values (either from the file or defaults).
1627 *
1628 * @param strFilename
1629 */
1630MachineConfigFile::MachineConfigFile(const Utf8Str *pstrFilename)
1631 : ConfigFileBase(pstrFilename),
1632 fNameSync(true),
1633 fTeleporterEnabled(false),
1634 uTeleporterPort(0),
1635 fRTCUseUTC(false),
1636 fCurrentStateModified(true),
1637 fAborted(false)
1638{
1639 RTTimeNow(&timeLastStateChange);
1640
1641 if (pstrFilename)
1642 {
1643 // the ConfigFileBase constructor has loaded the XML file, so now
1644 // we need only analyze what is in there
1645
1646 xml::NodesLoop nlRootChildren(*m->pelmRoot);
1647 const xml::ElementNode *pelmRootChild;
1648 while ((pelmRootChild = nlRootChildren.forAllNodes()))
1649 {
1650 if (pelmRootChild->nameEquals("Machine"))
1651 readMachine(*pelmRootChild);
1652 }
1653
1654 // clean up memory allocated by XML engine
1655 clearDocument();
1656 }
1657}
1658
1659/**
1660 * Comparison operator. This gets called from Machine::saveSettings to figure out
1661 * whether machine settings have really changed and thus need to be written out to disk.
1662 *
1663 * Even though this is called operator==, this does NOT compare all fields; the "equals"
1664 * should be understood as "has the same machine config as". The following fields are
1665 * NOT compared:
1666 * -- settings versions and file names inherited from ConfigFileBase;
1667 * -- fCurrentStateModified because that is considered separately in Machine::saveSettings!!
1668 *
1669 * The "deep" comparisons marked below will invoke the operator== functions of the
1670 * structs defined in this file, which may in turn go into comparing lists of
1671 * other structures. As a result, invoking this can be expensive, but it's
1672 * less expensive than writing out XML to disk.
1673 */
1674bool MachineConfigFile::operator==(const MachineConfigFile &c) const
1675{
1676 return ( (this == &c)
1677 || ( (uuid == c.uuid)
1678 && (strName == c.strName)
1679 && (fNameSync == c.fNameSync)
1680 && (strDescription == c.strDescription)
1681 && (strOsType == c.strOsType)
1682 && (strStateFile == c.strStateFile)
1683 && (uuidCurrentSnapshot == c.uuidCurrentSnapshot)
1684 && (strSnapshotFolder == c.strSnapshotFolder)
1685 && (fTeleporterEnabled == c.fTeleporterEnabled)
1686 && (uTeleporterPort == c.uTeleporterPort)
1687 && (strTeleporterAddress == c.strTeleporterAddress)
1688 && (strTeleporterPassword == c.strTeleporterPassword)
1689 && (fRTCUseUTC == c.fRTCUseUTC)
1690 // skip fCurrentStateModified!
1691 && (RTTimeSpecIsEqual(&timeLastStateChange, &c.timeLastStateChange))
1692 && (fAborted == c.fAborted)
1693 && (hardwareMachine == c.hardwareMachine) // this one's deep
1694 && (storageMachine == c.storageMachine) // this one's deep
1695 && (mapExtraDataItems == c.mapExtraDataItems) // this one's deep
1696 && (llFirstSnapshot == c.llFirstSnapshot) // this one's deep
1697 )
1698 );
1699}
1700
1701/**
1702 * Called from MachineConfigFile::readHardware() to read cpu information.
1703 * @param elmCpuid
1704 * @param ll
1705 */
1706void MachineConfigFile::readCpuTree(const xml::ElementNode &elmCpu,
1707 CpuList &ll)
1708{
1709 xml::NodesLoop nl1(elmCpu, "Cpu");
1710 const xml::ElementNode *pelmCpu;
1711 while ((pelmCpu = nl1.forAllNodes()))
1712 {
1713 Cpu cpu;
1714
1715 if (!pelmCpu->getAttributeValue("id", cpu.ulId))
1716 throw ConfigFileError(this, pelmCpu, N_("Required Cpu/@id attribute is missing"));
1717
1718 ll.push_back(cpu);
1719 }
1720}
1721
1722/**
1723 * Called from MachineConfigFile::readHardware() to cpuid information.
1724 * @param elmCpuid
1725 * @param ll
1726 */
1727void MachineConfigFile::readCpuIdTree(const xml::ElementNode &elmCpuid,
1728 CpuIdLeafsList &ll)
1729{
1730 xml::NodesLoop nl1(elmCpuid, "CpuIdLeaf");
1731 const xml::ElementNode *pelmCpuIdLeaf;
1732 while ((pelmCpuIdLeaf = nl1.forAllNodes()))
1733 {
1734 CpuIdLeaf leaf;
1735
1736 if (!pelmCpuIdLeaf->getAttributeValue("id", leaf.ulId))
1737 throw ConfigFileError(this, pelmCpuIdLeaf, N_("Required CpuId/@id attribute is missing"));
1738
1739 pelmCpuIdLeaf->getAttributeValue("eax", leaf.ulEax);
1740 pelmCpuIdLeaf->getAttributeValue("ebx", leaf.ulEbx);
1741 pelmCpuIdLeaf->getAttributeValue("ecx", leaf.ulEcx);
1742 pelmCpuIdLeaf->getAttributeValue("edx", leaf.ulEdx);
1743
1744 ll.push_back(leaf);
1745 }
1746}
1747
1748/**
1749 * Called from MachineConfigFile::readHardware() to network information.
1750 * @param elmNetwork
1751 * @param ll
1752 */
1753void MachineConfigFile::readNetworkAdapters(const xml::ElementNode &elmNetwork,
1754 NetworkAdaptersList &ll)
1755{
1756 xml::NodesLoop nl1(elmNetwork, "Adapter");
1757 const xml::ElementNode *pelmAdapter;
1758 while ((pelmAdapter = nl1.forAllNodes()))
1759 {
1760 NetworkAdapter nic;
1761
1762 if (!pelmAdapter->getAttributeValue("slot", nic.ulSlot))
1763 throw ConfigFileError(this, pelmAdapter, N_("Required Adapter/@slot attribute is missing"));
1764
1765 Utf8Str strTemp;
1766 if (pelmAdapter->getAttributeValue("type", strTemp))
1767 {
1768 if (strTemp == "Am79C970A")
1769 nic.type = NetworkAdapterType_Am79C970A;
1770 else if (strTemp == "Am79C973")
1771 nic.type = NetworkAdapterType_Am79C973;
1772 else if (strTemp == "82540EM")
1773 nic.type = NetworkAdapterType_I82540EM;
1774 else if (strTemp == "82543GC")
1775 nic.type = NetworkAdapterType_I82543GC;
1776 else if (strTemp == "82545EM")
1777 nic.type = NetworkAdapterType_I82545EM;
1778 else if (strTemp == "virtio")
1779 nic.type = NetworkAdapterType_Virtio;
1780 else
1781 throw ConfigFileError(this, pelmAdapter, N_("Invalid value '%s' in Adapter/@type attribute"), strTemp.c_str());
1782 }
1783
1784 pelmAdapter->getAttributeValue("enabled", nic.fEnabled);
1785 pelmAdapter->getAttributeValue("MACAddress", nic.strMACAddress);
1786 pelmAdapter->getAttributeValue("cable", nic.fCableConnected);
1787 pelmAdapter->getAttributeValue("speed", nic.ulLineSpeed);
1788 pelmAdapter->getAttributeValue("trace", nic.fTraceEnabled);
1789 pelmAdapter->getAttributeValue("tracefile", nic.strTraceFile);
1790
1791 const xml::ElementNode *pelmAdapterChild;
1792 if ((pelmAdapterChild = pelmAdapter->findChildElement("NAT")))
1793 {
1794 nic.mode = NetworkAttachmentType_NAT;
1795 pelmAdapterChild->getAttributeValue("name", nic.strName); // optional network name
1796 }
1797 else if ( ((pelmAdapterChild = pelmAdapter->findChildElement("HostInterface")))
1798 || ((pelmAdapterChild = pelmAdapter->findChildElement("BridgedInterface")))
1799 )
1800 {
1801 nic.mode = NetworkAttachmentType_Bridged;
1802 pelmAdapterChild->getAttributeValue("name", nic.strName); // optional host interface name
1803 }
1804 else if ((pelmAdapterChild = pelmAdapter->findChildElement("InternalNetwork")))
1805 {
1806 nic.mode = NetworkAttachmentType_Internal;
1807 if (!pelmAdapterChild->getAttributeValue("name", nic.strName)) // required network name
1808 throw ConfigFileError(this, pelmAdapterChild, N_("Required InternalNetwork/@name element is missing"));
1809 }
1810 else if ((pelmAdapterChild = pelmAdapter->findChildElement("HostOnlyInterface")))
1811 {
1812 nic.mode = NetworkAttachmentType_HostOnly;
1813 if (!pelmAdapterChild->getAttributeValue("name", nic.strName)) // required network name
1814 throw ConfigFileError(this, pelmAdapterChild, N_("Required HostOnlyInterface/@name element is missing"));
1815 }
1816 // else: default is NetworkAttachmentType_Null
1817
1818 ll.push_back(nic);
1819 }
1820}
1821
1822/**
1823 * Called from MachineConfigFile::readHardware() to read serial port information.
1824 * @param elmUART
1825 * @param ll
1826 */
1827void MachineConfigFile::readSerialPorts(const xml::ElementNode &elmUART,
1828 SerialPortsList &ll)
1829{
1830 xml::NodesLoop nl1(elmUART, "Port");
1831 const xml::ElementNode *pelmPort;
1832 while ((pelmPort = nl1.forAllNodes()))
1833 {
1834 SerialPort port;
1835 if (!pelmPort->getAttributeValue("slot", port.ulSlot))
1836 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@slot attribute is missing"));
1837
1838 // slot must be unique
1839 for (SerialPortsList::const_iterator it = ll.begin();
1840 it != ll.end();
1841 ++it)
1842 if ((*it).ulSlot == port.ulSlot)
1843 throw ConfigFileError(this, pelmPort, N_("Invalid value %RU32 in UART/Port/@slot attribute: value is not unique"), port.ulSlot);
1844
1845 if (!pelmPort->getAttributeValue("enabled", port.fEnabled))
1846 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@enabled attribute is missing"));
1847 if (!pelmPort->getAttributeValue("IOBase", port.ulIOBase))
1848 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@IOBase attribute is missing"));
1849 if (!pelmPort->getAttributeValue("IRQ", port.ulIRQ))
1850 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@IRQ attribute is missing"));
1851
1852 Utf8Str strPortMode;
1853 if (!pelmPort->getAttributeValue("hostMode", strPortMode))
1854 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@hostMode attribute is missing"));
1855 if (strPortMode == "RawFile")
1856 port.portMode = PortMode_RawFile;
1857 else if (strPortMode == "HostPipe")
1858 port.portMode = PortMode_HostPipe;
1859 else if (strPortMode == "HostDevice")
1860 port.portMode = PortMode_HostDevice;
1861 else if (strPortMode == "Disconnected")
1862 port.portMode = PortMode_Disconnected;
1863 else
1864 throw ConfigFileError(this, pelmPort, N_("Invalid value '%s' in UART/Port/@hostMode attribute"), strPortMode.c_str());
1865
1866 pelmPort->getAttributeValue("path", port.strPath);
1867 pelmPort->getAttributeValue("server", port.fServer);
1868
1869 ll.push_back(port);
1870 }
1871}
1872
1873/**
1874 * Called from MachineConfigFile::readHardware() to read parallel port information.
1875 * @param elmLPT
1876 * @param ll
1877 */
1878void MachineConfigFile::readParallelPorts(const xml::ElementNode &elmLPT,
1879 ParallelPortsList &ll)
1880{
1881 xml::NodesLoop nl1(elmLPT, "Port");
1882 const xml::ElementNode *pelmPort;
1883 while ((pelmPort = nl1.forAllNodes()))
1884 {
1885 ParallelPort port;
1886 if (!pelmPort->getAttributeValue("slot", port.ulSlot))
1887 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@slot attribute is missing"));
1888
1889 // slot must be unique
1890 for (ParallelPortsList::const_iterator it = ll.begin();
1891 it != ll.end();
1892 ++it)
1893 if ((*it).ulSlot == port.ulSlot)
1894 throw ConfigFileError(this, pelmPort, N_("Invalid value %RU32 in LPT/Port/@slot attribute: value is not unique"), port.ulSlot);
1895
1896 if (!pelmPort->getAttributeValue("enabled", port.fEnabled))
1897 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@enabled attribute is missing"));
1898 if (!pelmPort->getAttributeValue("IOBase", port.ulIOBase))
1899 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@IOBase attribute is missing"));
1900 if (!pelmPort->getAttributeValue("IRQ", port.ulIRQ))
1901 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@IRQ attribute is missing"));
1902
1903 pelmPort->getAttributeValue("path", port.strPath);
1904
1905 ll.push_back(port);
1906 }
1907}
1908
1909/**
1910 * Called from MachineConfigFile::readHardware() to read guest property information.
1911 * @param elmGuestProperties
1912 * @param hw
1913 */
1914void MachineConfigFile::readGuestProperties(const xml::ElementNode &elmGuestProperties,
1915 Hardware &hw)
1916{
1917 xml::NodesLoop nl1(elmGuestProperties, "GuestProperty");
1918 const xml::ElementNode *pelmProp;
1919 while ((pelmProp = nl1.forAllNodes()))
1920 {
1921 GuestProperty prop;
1922 pelmProp->getAttributeValue("name", prop.strName);
1923 pelmProp->getAttributeValue("value", prop.strValue);
1924
1925 pelmProp->getAttributeValue("timestamp", prop.timestamp);
1926 pelmProp->getAttributeValue("flags", prop.strFlags);
1927 hw.llGuestProperties.push_back(prop);
1928 }
1929
1930 elmGuestProperties.getAttributeValue("notificationPatterns", hw.strNotificationPatterns);
1931}
1932
1933/**
1934 * Helper function to read attributes that are common to <SATAController> (pre-1.7)
1935 * and <StorageController>.
1936 * @param elmStorageController
1937 * @param strg
1938 */
1939void MachineConfigFile::readStorageControllerAttributes(const xml::ElementNode &elmStorageController,
1940 StorageController &sctl)
1941{
1942 elmStorageController.getAttributeValue("PortCount", sctl.ulPortCount);
1943 elmStorageController.getAttributeValue("IDE0MasterEmulationPort", sctl.lIDE0MasterEmulationPort);
1944 elmStorageController.getAttributeValue("IDE0SlaveEmulationPort", sctl.lIDE0SlaveEmulationPort);
1945 elmStorageController.getAttributeValue("IDE1MasterEmulationPort", sctl.lIDE1MasterEmulationPort);
1946 elmStorageController.getAttributeValue("IDE1SlaveEmulationPort", sctl.lIDE1SlaveEmulationPort);
1947}
1948
1949/**
1950 * Reads in a <Hardware> block and stores it in the given structure. Used
1951 * both directly from readMachine and from readSnapshot, since snapshots
1952 * have their own hardware sections.
1953 *
1954 * For legacy pre-1.7 settings we also need a storage structure because
1955 * the IDE and SATA controllers used to be defined under <Hardware>.
1956 *
1957 * @param elmHardware
1958 * @param hw
1959 */
1960void MachineConfigFile::readHardware(const xml::ElementNode &elmHardware,
1961 Hardware &hw,
1962 Storage &strg)
1963{
1964 if (!elmHardware.getAttributeValue("version", hw.strVersion))
1965 {
1966 /* KLUDGE ALERT! For a while during the 3.1 development this was not
1967 written because it was thought to have a default value of "2". For
1968 sv <= 1.3 it defaults to "1" because the attribute didn't exist,
1969 while for 1.4+ it is sort of mandatory. Now, the buggy XML writer
1970 code only wrote 1.7 and later. So, if it's a 1.7+ XML file and it's
1971 missing the hardware version, then it probably should be "2" instead
1972 of "1". */
1973 if (m->sv < SettingsVersion_v1_7)
1974 hw.strVersion = "1";
1975 else
1976 hw.strVersion = "2";
1977 }
1978 Utf8Str strUUID;
1979 if (elmHardware.getAttributeValue("uuid", strUUID))
1980 parseUUID(hw.uuid, strUUID);
1981
1982 xml::NodesLoop nl1(elmHardware);
1983 const xml::ElementNode *pelmHwChild;
1984 while ((pelmHwChild = nl1.forAllNodes()))
1985 {
1986 if (pelmHwChild->nameEquals("CPU"))
1987 {
1988 if (!pelmHwChild->getAttributeValue("count", hw.cCPUs))
1989 {
1990 // pre-1.5 variant; not sure if this actually exists in the wild anywhere
1991 const xml::ElementNode *pelmCPUChild;
1992 if ((pelmCPUChild = pelmHwChild->findChildElement("CPUCount")))
1993 pelmCPUChild->getAttributeValue("count", hw.cCPUs);
1994 }
1995
1996 pelmHwChild->getAttributeValue("hotplug", hw.fCpuHotPlug);
1997
1998 const xml::ElementNode *pelmCPUChild;
1999 if (hw.fCpuHotPlug)
2000 {
2001 if ((pelmCPUChild = pelmHwChild->findChildElement("CpuTree")))
2002 readCpuTree(*pelmCPUChild, hw.llCpus);
2003 }
2004
2005 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtEx")))
2006 {
2007 pelmCPUChild->getAttributeValue("enabled", hw.fHardwareVirt);
2008 pelmCPUChild->getAttributeValue("exclusive", hw.fHardwareVirtExclusive); // settings version 1.9
2009 }
2010 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExNestedPaging")))
2011 pelmCPUChild->getAttributeValue("enabled", hw.fNestedPaging);
2012 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExVPID")))
2013 pelmCPUChild->getAttributeValue("enabled", hw.fVPID);
2014
2015 if (!(pelmCPUChild = pelmHwChild->findChildElement("PAE")))
2016 {
2017 /* The default for pre 3.1 was false, so we must respect that. */
2018 if (m->sv < SettingsVersion_v1_9)
2019 hw.fPAE = false;
2020 }
2021 else
2022 pelmCPUChild->getAttributeValue("enabled", hw.fPAE);
2023
2024 if ((pelmCPUChild = pelmHwChild->findChildElement("SyntheticCpu")))
2025 pelmCPUChild->getAttributeValue("enabled", hw.fSyntheticCpu);
2026 if ((pelmCPUChild = pelmHwChild->findChildElement("CpuIdTree")))
2027 readCpuIdTree(*pelmCPUChild, hw.llCpuIdLeafs);
2028 }
2029 else if (pelmHwChild->nameEquals("Memory"))
2030 pelmHwChild->getAttributeValue("RAMSize", hw.ulMemorySizeMB);
2031 else if (pelmHwChild->nameEquals("Firmware"))
2032 {
2033 Utf8Str strFirmwareType;
2034 if (pelmHwChild->getAttributeValue("type", strFirmwareType))
2035 {
2036 if ( (strFirmwareType == "BIOS")
2037 || (strFirmwareType == "1") // some trunk builds used the number here
2038 )
2039 hw.firmwareType = FirmwareType_BIOS;
2040 else if ( (strFirmwareType == "EFI")
2041 || (strFirmwareType == "2") // some trunk builds used the number here
2042 )
2043 hw.firmwareType = FirmwareType_EFI;
2044 else if ( strFirmwareType == "EFI32")
2045 hw.firmwareType = FirmwareType_EFI32;
2046 else if ( strFirmwareType == "EFI64")
2047 hw.firmwareType = FirmwareType_EFI64;
2048 else if ( strFirmwareType == "EFIDUAL")
2049 hw.firmwareType = FirmwareType_EFIDUAL;
2050 else
2051 throw ConfigFileError(this,
2052 pelmHwChild,
2053 N_("Invalid value '%s' in Firmware/@type"),
2054 strFirmwareType.c_str());
2055 }
2056 }
2057 else if (pelmHwChild->nameEquals("HID"))
2058 {
2059 Utf8Str strHidType;
2060 if (pelmHwChild->getAttributeValue("Keyboard", strHidType))
2061 {
2062 if ( (strHidType == "None")
2063 )
2064 hw.keyboardHidType = KeyboardHidType_None;
2065 else if ( (strHidType == "USBKeyboard")
2066 )
2067 hw.keyboardHidType = KeyboardHidType_USBKeyboard;
2068 else if ( (strHidType == "PS2Keyboard")
2069 )
2070 hw.keyboardHidType = KeyboardHidType_PS2Keyboard;
2071 else if ( (strHidType == "ComboKeyboard")
2072 )
2073 hw.keyboardHidType = KeyboardHidType_ComboKeyboard;
2074 else
2075 throw ConfigFileError(this,
2076 pelmHwChild,
2077 N_("Invalid value '%s' in HID/Keyboard/@type"),
2078 strHidType.c_str());
2079 }
2080 if (pelmHwChild->getAttributeValue("Pointing", strHidType))
2081 {
2082 if ( (strHidType == "None")
2083 )
2084 hw.pointingHidType = PointingHidType_None;
2085 else if ( (strHidType == "USBMouse")
2086 )
2087 hw.pointingHidType = PointingHidType_USBMouse;
2088 else if ( (strHidType == "UsbTablet")
2089 )
2090 hw.pointingHidType = PointingHidType_USBTablet;
2091 else if ( (strHidType == "PS2Mouse")
2092 )
2093 hw.pointingHidType = PointingHidType_PS2Mouse;
2094 else if ( (strHidType == "ComboMouse")
2095 )
2096 hw.pointingHidType = PointingHidType_ComboMouse;
2097 else
2098 throw ConfigFileError(this,
2099 pelmHwChild,
2100 N_("Invalid value '%s' in HID/Pointing/@type"),
2101 strHidType.c_str());
2102 }
2103 }
2104 else if (pelmHwChild->nameEquals("Boot"))
2105 {
2106 hw.mapBootOrder.clear();
2107
2108 xml::NodesLoop nl2(*pelmHwChild, "Order");
2109 const xml::ElementNode *pelmOrder;
2110 while ((pelmOrder = nl2.forAllNodes()))
2111 {
2112 uint32_t ulPos;
2113 Utf8Str strDevice;
2114 if (!pelmOrder->getAttributeValue("position", ulPos))
2115 throw ConfigFileError(this, pelmOrder, N_("Required Boot/Order/@position attribute is missing"));
2116
2117 if ( ulPos < 1
2118 || ulPos > SchemaDefs::MaxBootPosition
2119 )
2120 throw ConfigFileError(this,
2121 pelmOrder,
2122 N_("Invalid value '%RU32' in Boot/Order/@position: must be greater than 0 and less than %RU32"),
2123 ulPos,
2124 SchemaDefs::MaxBootPosition + 1);
2125 // XML is 1-based but internal data is 0-based
2126 --ulPos;
2127
2128 if (hw.mapBootOrder.find(ulPos) != hw.mapBootOrder.end())
2129 throw ConfigFileError(this, pelmOrder, N_("Invalid value '%RU32' in Boot/Order/@position: value is not unique"), ulPos);
2130
2131 if (!pelmOrder->getAttributeValue("device", strDevice))
2132 throw ConfigFileError(this, pelmOrder, N_("Required Boot/Order/@device attribute is missing"));
2133
2134 DeviceType_T type;
2135 if (strDevice == "None")
2136 type = DeviceType_Null;
2137 else if (strDevice == "Floppy")
2138 type = DeviceType_Floppy;
2139 else if (strDevice == "DVD")
2140 type = DeviceType_DVD;
2141 else if (strDevice == "HardDisk")
2142 type = DeviceType_HardDisk;
2143 else if (strDevice == "Network")
2144 type = DeviceType_Network;
2145 else
2146 throw ConfigFileError(this, pelmOrder, N_("Invalid value '%s' in Boot/Order/@device attribute"), strDevice.c_str());
2147 hw.mapBootOrder[ulPos] = type;
2148 }
2149 }
2150 else if (pelmHwChild->nameEquals("Display"))
2151 {
2152 pelmHwChild->getAttributeValue("VRAMSize", hw.ulVRAMSizeMB);
2153 if (!pelmHwChild->getAttributeValue("monitorCount", hw.cMonitors))
2154 pelmHwChild->getAttributeValue("MonitorCount", hw.cMonitors); // pre-v1.5 variant
2155 if (!pelmHwChild->getAttributeValue("accelerate3D", hw.fAccelerate3D))
2156 pelmHwChild->getAttributeValue("Accelerate3D", hw.fAccelerate3D); // pre-v1.5 variant
2157 pelmHwChild->getAttributeValue("accelerate2DVideo", hw.fAccelerate2DVideo);
2158 }
2159 else if (pelmHwChild->nameEquals("RemoteDisplay"))
2160 {
2161 pelmHwChild->getAttributeValue("enabled", hw.vrdpSettings.fEnabled);
2162 pelmHwChild->getAttributeValue("port", hw.vrdpSettings.strPort);
2163 pelmHwChild->getAttributeValue("netAddress", hw.vrdpSettings.strNetAddress);
2164
2165 Utf8Str strAuthType;
2166 if (pelmHwChild->getAttributeValue("authType", strAuthType))
2167 {
2168 // settings before 1.3 used lower case so make sure this is case-insensitive
2169 strAuthType.toUpper();
2170 if (strAuthType == "NULL")
2171 hw.vrdpSettings.authType = VRDPAuthType_Null;
2172 else if (strAuthType == "GUEST")
2173 hw.vrdpSettings.authType = VRDPAuthType_Guest;
2174 else if (strAuthType == "EXTERNAL")
2175 hw.vrdpSettings.authType = VRDPAuthType_External;
2176 else
2177 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in RemoteDisplay/@authType attribute"), strAuthType.c_str());
2178 }
2179
2180 pelmHwChild->getAttributeValue("authTimeout", hw.vrdpSettings.ulAuthTimeout);
2181 pelmHwChild->getAttributeValue("allowMultiConnection", hw.vrdpSettings.fAllowMultiConnection);
2182 pelmHwChild->getAttributeValue("reuseSingleConnection", hw.vrdpSettings.fReuseSingleConnection);
2183 }
2184 else if (pelmHwChild->nameEquals("BIOS"))
2185 {
2186 const xml::ElementNode *pelmBIOSChild;
2187 if ((pelmBIOSChild = pelmHwChild->findChildElement("ACPI")))
2188 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fACPIEnabled);
2189 if ((pelmBIOSChild = pelmHwChild->findChildElement("IOAPIC")))
2190 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fIOAPICEnabled);
2191 if ((pelmBIOSChild = pelmHwChild->findChildElement("Logo")))
2192 {
2193 pelmBIOSChild->getAttributeValue("fadeIn", hw.biosSettings.fLogoFadeIn);
2194 pelmBIOSChild->getAttributeValue("fadeOut", hw.biosSettings.fLogoFadeOut);
2195 pelmBIOSChild->getAttributeValue("displayTime", hw.biosSettings.ulLogoDisplayTime);
2196 pelmBIOSChild->getAttributeValue("imagePath", hw.biosSettings.strLogoImagePath);
2197 }
2198 if ((pelmBIOSChild = pelmHwChild->findChildElement("BootMenu")))
2199 {
2200 Utf8Str strBootMenuMode;
2201 if (pelmBIOSChild->getAttributeValue("mode", strBootMenuMode))
2202 {
2203 // settings before 1.3 used lower case so make sure this is case-insensitive
2204 strBootMenuMode.toUpper();
2205 if (strBootMenuMode == "DISABLED")
2206 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_Disabled;
2207 else if (strBootMenuMode == "MENUONLY")
2208 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_MenuOnly;
2209 else if (strBootMenuMode == "MESSAGEANDMENU")
2210 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_MessageAndMenu;
2211 else
2212 throw ConfigFileError(this, pelmBIOSChild, N_("Invalid value '%s' in BootMenu/@mode attribute"), strBootMenuMode.c_str());
2213 }
2214 }
2215 if ((pelmBIOSChild = pelmHwChild->findChildElement("PXEDebug")))
2216 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fPXEDebugEnabled);
2217 if ((pelmBIOSChild = pelmHwChild->findChildElement("TimeOffset")))
2218 pelmBIOSChild->getAttributeValue("value", hw.biosSettings.llTimeOffset);
2219
2220 // legacy BIOS/IDEController (pre 1.7)
2221 if ( (m->sv < SettingsVersion_v1_7)
2222 && ((pelmBIOSChild = pelmHwChild->findChildElement("IDEController")))
2223 )
2224 {
2225 StorageController sctl;
2226 sctl.strName = "IDE Controller";
2227 sctl.storageBus = StorageBus_IDE;
2228
2229 Utf8Str strType;
2230 if (pelmBIOSChild->getAttributeValue("type", strType))
2231 {
2232 if (strType == "PIIX3")
2233 sctl.controllerType = StorageControllerType_PIIX3;
2234 else if (strType == "PIIX4")
2235 sctl.controllerType = StorageControllerType_PIIX4;
2236 else if (strType == "ICH6")
2237 sctl.controllerType = StorageControllerType_ICH6;
2238 else
2239 throw ConfigFileError(this, pelmBIOSChild, N_("Invalid value '%s' for IDEController/@type attribute"), strType.c_str());
2240 }
2241 sctl.ulPortCount = 2;
2242 strg.llStorageControllers.push_back(sctl);
2243 }
2244 }
2245 else if (pelmHwChild->nameEquals("USBController"))
2246 {
2247 pelmHwChild->getAttributeValue("enabled", hw.usbController.fEnabled);
2248 pelmHwChild->getAttributeValue("enabledEhci", hw.usbController.fEnabledEHCI);
2249
2250 readUSBDeviceFilters(*pelmHwChild,
2251 hw.usbController.llDeviceFilters);
2252 }
2253 else if ( (m->sv < SettingsVersion_v1_7)
2254 && (pelmHwChild->nameEquals("SATAController"))
2255 )
2256 {
2257 bool f;
2258 if ( (pelmHwChild->getAttributeValue("enabled", f))
2259 && (f)
2260 )
2261 {
2262 StorageController sctl;
2263 sctl.strName = "SATA Controller";
2264 sctl.storageBus = StorageBus_SATA;
2265 sctl.controllerType = StorageControllerType_IntelAhci;
2266
2267 readStorageControllerAttributes(*pelmHwChild, sctl);
2268
2269 strg.llStorageControllers.push_back(sctl);
2270 }
2271 }
2272 else if (pelmHwChild->nameEquals("Network"))
2273 readNetworkAdapters(*pelmHwChild, hw.llNetworkAdapters);
2274 else if (pelmHwChild->nameEquals("RTC"))
2275 {
2276 Utf8Str strLocalOrUTC;
2277 fRTCUseUTC = pelmHwChild->getAttributeValue("localOrUTC", strLocalOrUTC)
2278 && strLocalOrUTC == "UTC";
2279 }
2280 else if ( (pelmHwChild->nameEquals("UART"))
2281 || (pelmHwChild->nameEquals("Uart")) // used before 1.3
2282 )
2283 readSerialPorts(*pelmHwChild, hw.llSerialPorts);
2284 else if ( (pelmHwChild->nameEquals("LPT"))
2285 || (pelmHwChild->nameEquals("Lpt")) // used before 1.3
2286 )
2287 readParallelPorts(*pelmHwChild, hw.llParallelPorts);
2288 else if (pelmHwChild->nameEquals("AudioAdapter"))
2289 {
2290 pelmHwChild->getAttributeValue("enabled", hw.audioAdapter.fEnabled);
2291
2292 Utf8Str strTemp;
2293 if (pelmHwChild->getAttributeValue("controller", strTemp))
2294 {
2295 if (strTemp == "SB16")
2296 hw.audioAdapter.controllerType = AudioControllerType_SB16;
2297 else if (strTemp == "AC97")
2298 hw.audioAdapter.controllerType = AudioControllerType_AC97;
2299 else
2300 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in AudioAdapter/@controller attribute"), strTemp.c_str());
2301 }
2302 if (pelmHwChild->getAttributeValue("driver", strTemp))
2303 {
2304 // settings before 1.3 used lower case so make sure this is case-insensitive
2305 strTemp.toUpper();
2306 if (strTemp == "NULL")
2307 hw.audioAdapter.driverType = AudioDriverType_Null;
2308 else if (strTemp == "WINMM")
2309 hw.audioAdapter.driverType = AudioDriverType_WinMM;
2310 else if ( (strTemp == "DIRECTSOUND") || (strTemp == "DSOUND") )
2311 hw.audioAdapter.driverType = AudioDriverType_DirectSound;
2312 else if (strTemp == "SOLAUDIO")
2313 hw.audioAdapter.driverType = AudioDriverType_SolAudio;
2314 else if (strTemp == "ALSA")
2315 hw.audioAdapter.driverType = AudioDriverType_ALSA;
2316 else if (strTemp == "PULSE")
2317 hw.audioAdapter.driverType = AudioDriverType_Pulse;
2318 else if (strTemp == "OSS")
2319 hw.audioAdapter.driverType = AudioDriverType_OSS;
2320 else if (strTemp == "COREAUDIO")
2321 hw.audioAdapter.driverType = AudioDriverType_CoreAudio;
2322 else if (strTemp == "MMPM")
2323 hw.audioAdapter.driverType = AudioDriverType_MMPM;
2324 else
2325 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in AudioAdapter/@driver attribute"), strTemp.c_str());
2326 }
2327 }
2328 else if (pelmHwChild->nameEquals("SharedFolders"))
2329 {
2330 xml::NodesLoop nl2(*pelmHwChild, "SharedFolder");
2331 const xml::ElementNode *pelmFolder;
2332 while ((pelmFolder = nl2.forAllNodes()))
2333 {
2334 SharedFolder sf;
2335 pelmFolder->getAttributeValue("name", sf.strName);
2336 pelmFolder->getAttributeValue("hostPath", sf.strHostPath);
2337 pelmFolder->getAttributeValue("writable", sf.fWritable);
2338 hw.llSharedFolders.push_back(sf);
2339 }
2340 }
2341 else if (pelmHwChild->nameEquals("Clipboard"))
2342 {
2343 Utf8Str strTemp;
2344 if (pelmHwChild->getAttributeValue("mode", strTemp))
2345 {
2346 if (strTemp == "Disabled")
2347 hw.clipboardMode = ClipboardMode_Disabled;
2348 else if (strTemp == "HostToGuest")
2349 hw.clipboardMode = ClipboardMode_HostToGuest;
2350 else if (strTemp == "GuestToHost")
2351 hw.clipboardMode = ClipboardMode_GuestToHost;
2352 else if (strTemp == "Bidirectional")
2353 hw.clipboardMode = ClipboardMode_Bidirectional;
2354 else
2355 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in Clipbord/@mode attribute"), strTemp.c_str());
2356 }
2357 }
2358 else if (pelmHwChild->nameEquals("Guest"))
2359 {
2360 if (!pelmHwChild->getAttributeValue("memoryBalloonSize", hw.ulMemoryBalloonSize))
2361 pelmHwChild->getAttributeValue("MemoryBalloonSize", hw.ulMemoryBalloonSize); // used before 1.3
2362 if (!pelmHwChild->getAttributeValue("statisticsUpdateInterval", hw.ulStatisticsUpdateInterval))
2363 pelmHwChild->getAttributeValue("StatisticsUpdateInterval", hw.ulStatisticsUpdateInterval);
2364 }
2365 else if (pelmHwChild->nameEquals("GuestProperties"))
2366 readGuestProperties(*pelmHwChild, hw);
2367 }
2368
2369 if (hw.ulMemorySizeMB == (uint32_t)-1)
2370 throw ConfigFileError(this, &elmHardware, N_("Required Memory/@RAMSize element/attribute is missing"));
2371}
2372
2373/**
2374 * This gets called instead of readStorageControllers() for legacy pre-1.7 settings
2375 * files which have a <HardDiskAttachments> node and storage controller settings
2376 * hidden in the <Hardware> settings. We set the StorageControllers fields just the
2377 * same, just from different sources.
2378 * @param elmHardware <Hardware> XML node.
2379 * @param elmHardDiskAttachments <HardDiskAttachments> XML node.
2380 * @param strg
2381 */
2382void MachineConfigFile::readHardDiskAttachments_pre1_7(const xml::ElementNode &elmHardDiskAttachments,
2383 Storage &strg)
2384{
2385 StorageController *pIDEController = NULL;
2386 StorageController *pSATAController = NULL;
2387
2388 for (StorageControllersList::iterator it = strg.llStorageControllers.begin();
2389 it != strg.llStorageControllers.end();
2390 ++it)
2391 {
2392 StorageController &s = *it;
2393 if (s.storageBus == StorageBus_IDE)
2394 pIDEController = &s;
2395 else if (s.storageBus == StorageBus_SATA)
2396 pSATAController = &s;
2397 }
2398
2399 xml::NodesLoop nl1(elmHardDiskAttachments, "HardDiskAttachment");
2400 const xml::ElementNode *pelmAttachment;
2401 while ((pelmAttachment = nl1.forAllNodes()))
2402 {
2403 AttachedDevice att;
2404 Utf8Str strUUID, strBus;
2405
2406 if (!pelmAttachment->getAttributeValue("hardDisk", strUUID))
2407 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@hardDisk attribute is missing"));
2408 parseUUID(att.uuid, strUUID);
2409
2410 if (!pelmAttachment->getAttributeValue("bus", strBus))
2411 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@bus attribute is missing"));
2412 // pre-1.7 'channel' is now port
2413 if (!pelmAttachment->getAttributeValue("channel", att.lPort))
2414 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@channel attribute is missing"));
2415 // pre-1.7 'device' is still device
2416 if (!pelmAttachment->getAttributeValue("device", att.lDevice))
2417 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@device attribute is missing"));
2418
2419 att.deviceType = DeviceType_HardDisk;
2420
2421 if (strBus == "IDE")
2422 {
2423 if (!pIDEController)
2424 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus is 'IDE' but cannot find IDE controller"));
2425 pIDEController->llAttachedDevices.push_back(att);
2426 }
2427 else if (strBus == "SATA")
2428 {
2429 if (!pSATAController)
2430 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus is 'SATA' but cannot find SATA controller"));
2431 pSATAController->llAttachedDevices.push_back(att);
2432 }
2433 else
2434 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus attribute has illegal value '%s'"), strBus.c_str());
2435 }
2436}
2437
2438/**
2439 * Reads in a <StorageControllers> block and stores it in the given Storage structure.
2440 * Used both directly from readMachine and from readSnapshot, since snapshots
2441 * have their own storage controllers sections.
2442 *
2443 * This is only called for settings version 1.7 and above; see readHardDiskAttachments_pre1_7()
2444 * for earlier versions.
2445 *
2446 * @param elmStorageControllers
2447 */
2448void MachineConfigFile::readStorageControllers(const xml::ElementNode &elmStorageControllers,
2449 Storage &strg)
2450{
2451 xml::NodesLoop nlStorageControllers(elmStorageControllers, "StorageController");
2452 const xml::ElementNode *pelmController;
2453 while ((pelmController = nlStorageControllers.forAllNodes()))
2454 {
2455 StorageController sctl;
2456
2457 if (!pelmController->getAttributeValue("name", sctl.strName))
2458 throw ConfigFileError(this, pelmController, N_("Required StorageController/@name attribute is missing"));
2459 // canonicalize storage controller names for configs in the switchover
2460 // period.
2461 if (m->sv < SettingsVersion_v1_9)
2462 {
2463 if (sctl.strName == "IDE")
2464 sctl.strName = "IDE Controller";
2465 else if (sctl.strName == "SATA")
2466 sctl.strName = "SATA Controller";
2467 else if (sctl.strName == "SCSI")
2468 sctl.strName = "SCSI Controller";
2469 }
2470
2471 pelmController->getAttributeValue("Instance", sctl.ulInstance);
2472 // default from constructor is 0
2473
2474 Utf8Str strType;
2475 if (!pelmController->getAttributeValue("type", strType))
2476 throw ConfigFileError(this, pelmController, N_("Required StorageController/@type attribute is missing"));
2477
2478 if (strType == "AHCI")
2479 {
2480 sctl.storageBus = StorageBus_SATA;
2481 sctl.controllerType = StorageControllerType_IntelAhci;
2482 }
2483 else if (strType == "LsiLogic")
2484 {
2485 sctl.storageBus = StorageBus_SCSI;
2486 sctl.controllerType = StorageControllerType_LsiLogic;
2487 }
2488 else if (strType == "BusLogic")
2489 {
2490 sctl.storageBus = StorageBus_SCSI;
2491 sctl.controllerType = StorageControllerType_BusLogic;
2492 }
2493 else if (strType == "PIIX3")
2494 {
2495 sctl.storageBus = StorageBus_IDE;
2496 sctl.controllerType = StorageControllerType_PIIX3;
2497 }
2498 else if (strType == "PIIX4")
2499 {
2500 sctl.storageBus = StorageBus_IDE;
2501 sctl.controllerType = StorageControllerType_PIIX4;
2502 }
2503 else if (strType == "ICH6")
2504 {
2505 sctl.storageBus = StorageBus_IDE;
2506 sctl.controllerType = StorageControllerType_ICH6;
2507 }
2508 else if ( (m->sv >= SettingsVersion_v1_9)
2509 && (strType == "I82078")
2510 )
2511 {
2512 sctl.storageBus = StorageBus_Floppy;
2513 sctl.controllerType = StorageControllerType_I82078;
2514 }
2515 else if (strType == "LsiLogicSas")
2516 {
2517 sctl.storageBus = StorageBus_SAS;
2518 sctl.controllerType = StorageControllerType_LsiLogicSas;
2519 }
2520 else
2521 throw ConfigFileError(this, pelmController, N_("Invalid value '%s' for StorageController/@type attribute"), strType.c_str());
2522
2523 readStorageControllerAttributes(*pelmController, sctl);
2524
2525 xml::NodesLoop nlAttached(*pelmController, "AttachedDevice");
2526 const xml::ElementNode *pelmAttached;
2527 while ((pelmAttached = nlAttached.forAllNodes()))
2528 {
2529 AttachedDevice att;
2530 Utf8Str strTemp;
2531 pelmAttached->getAttributeValue("type", strTemp);
2532
2533 if (strTemp == "HardDisk")
2534 att.deviceType = DeviceType_HardDisk;
2535 else if (m->sv >= SettingsVersion_v1_9)
2536 {
2537 // starting with 1.9 we list DVD and floppy drive info + attachments under <StorageControllers>
2538 if (strTemp == "DVD")
2539 {
2540 att.deviceType = DeviceType_DVD;
2541 pelmAttached->getAttributeValue("passthrough", att.fPassThrough);
2542 }
2543 else if (strTemp == "Floppy")
2544 att.deviceType = DeviceType_Floppy;
2545 }
2546
2547 if (att.deviceType != DeviceType_Null)
2548 {
2549 const xml::ElementNode *pelmImage;
2550 // all types can have images attached, but for HardDisk it's required
2551 if (!(pelmImage = pelmAttached->findChildElement("Image")))
2552 {
2553 if (att.deviceType == DeviceType_HardDisk)
2554 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/Image element is missing"));
2555 else
2556 {
2557 // DVDs and floppies can also have <HostDrive> instead of <Image>
2558 const xml::ElementNode *pelmHostDrive;
2559 if ((pelmHostDrive = pelmAttached->findChildElement("HostDrive")))
2560 if (!pelmHostDrive->getAttributeValue("src", att.strHostDriveSrc))
2561 throw ConfigFileError(this, pelmHostDrive, N_("Required AttachedDevice/HostDrive/@src attribute is missing"));
2562 }
2563 }
2564 else
2565 {
2566 if (!pelmImage->getAttributeValue("uuid", strTemp))
2567 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/Image/@uuid attribute is missing"));
2568 parseUUID(att.uuid, strTemp);
2569 }
2570
2571 if (!pelmAttached->getAttributeValue("port", att.lPort))
2572 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/@port attribute is missing"));
2573 if (!pelmAttached->getAttributeValue("device", att.lDevice))
2574 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/@device attribute is missing"));
2575
2576 sctl.llAttachedDevices.push_back(att);
2577 }
2578 }
2579
2580 strg.llStorageControllers.push_back(sctl);
2581 }
2582}
2583
2584/**
2585 * This gets called for legacy pre-1.9 settings files after having parsed the
2586 * <Hardware> and <StorageControllers> sections to parse <Hardware> once more
2587 * for the <DVDDrive> and <FloppyDrive> sections.
2588 *
2589 * Before settings version 1.9, DVD and floppy drives were specified separately
2590 * under <Hardware>; we then need this extra loop to make sure the storage
2591 * controller structs are already set up so we can add stuff to them.
2592 *
2593 * @param elmHardware
2594 * @param strg
2595 */
2596void MachineConfigFile::readDVDAndFloppies_pre1_9(const xml::ElementNode &elmHardware,
2597 Storage &strg)
2598{
2599 xml::NodesLoop nl1(elmHardware);
2600 const xml::ElementNode *pelmHwChild;
2601 while ((pelmHwChild = nl1.forAllNodes()))
2602 {
2603 if (pelmHwChild->nameEquals("DVDDrive"))
2604 {
2605 // create a DVD "attached device" and attach it to the existing IDE controller
2606 AttachedDevice att;
2607 att.deviceType = DeviceType_DVD;
2608 // legacy DVD drive is always secondary master (port 1, device 0)
2609 att.lPort = 1;
2610 att.lDevice = 0;
2611 pelmHwChild->getAttributeValue("passthrough", att.fPassThrough);
2612
2613 const xml::ElementNode *pDriveChild;
2614 Utf8Str strTmp;
2615 if ( ((pDriveChild = pelmHwChild->findChildElement("Image")))
2616 && (pDriveChild->getAttributeValue("uuid", strTmp))
2617 )
2618 parseUUID(att.uuid, strTmp);
2619 else if ((pDriveChild = pelmHwChild->findChildElement("HostDrive")))
2620 pDriveChild->getAttributeValue("src", att.strHostDriveSrc);
2621
2622 // find the IDE controller and attach the DVD drive
2623 bool fFound = false;
2624 for (StorageControllersList::iterator it = strg.llStorageControllers.begin();
2625 it != strg.llStorageControllers.end();
2626 ++it)
2627 {
2628 StorageController &sctl = *it;
2629 if (sctl.storageBus == StorageBus_IDE)
2630 {
2631 sctl.llAttachedDevices.push_back(att);
2632 fFound = true;
2633 break;
2634 }
2635 }
2636
2637 if (!fFound)
2638 throw ConfigFileError(this, pelmHwChild, N_("Internal error: found DVD drive but IDE controller does not exist"));
2639 // shouldn't happen because pre-1.9 settings files always had at least one IDE controller in the settings
2640 // which should have gotten parsed in <StorageControllers> before this got called
2641 }
2642 else if (pelmHwChild->nameEquals("FloppyDrive"))
2643 {
2644 bool fEnabled;
2645 if ( (pelmHwChild->getAttributeValue("enabled", fEnabled))
2646 && (fEnabled)
2647 )
2648 {
2649 // create a new floppy controller and attach a floppy "attached device"
2650 StorageController sctl;
2651 sctl.strName = "Floppy Controller";
2652 sctl.storageBus = StorageBus_Floppy;
2653 sctl.controllerType = StorageControllerType_I82078;
2654 sctl.ulPortCount = 1;
2655
2656 AttachedDevice att;
2657 att.deviceType = DeviceType_Floppy;
2658 att.lPort = 0;
2659 att.lDevice = 0;
2660
2661 const xml::ElementNode *pDriveChild;
2662 Utf8Str strTmp;
2663 if ( ((pDriveChild = pelmHwChild->findChildElement("Image")))
2664 && (pDriveChild->getAttributeValue("uuid", strTmp))
2665 )
2666 parseUUID(att.uuid, strTmp);
2667 else if ((pDriveChild = pelmHwChild->findChildElement("HostDrive")))
2668 pDriveChild->getAttributeValue("src", att.strHostDriveSrc);
2669
2670 // store attachment with controller
2671 sctl.llAttachedDevices.push_back(att);
2672 // store controller with storage
2673 strg.llStorageControllers.push_back(sctl);
2674 }
2675 }
2676 }
2677}
2678
2679/**
2680 * Called initially for the <Snapshot> element under <Machine>, if present,
2681 * to store the snapshot's data into the given Snapshot structure (which is
2682 * then the one in the Machine struct). This might then recurse if
2683 * a <Snapshots> (plural) element is found in the snapshot, which should
2684 * contain a list of child snapshots; such lists are maintained in the
2685 * Snapshot structure.
2686 *
2687 * @param elmSnapshot
2688 * @param snap
2689 */
2690void MachineConfigFile::readSnapshot(const xml::ElementNode &elmSnapshot,
2691 Snapshot &snap)
2692{
2693 Utf8Str strTemp;
2694
2695 if (!elmSnapshot.getAttributeValue("uuid", strTemp))
2696 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@uuid attribute is missing"));
2697 parseUUID(snap.uuid, strTemp);
2698
2699 if (!elmSnapshot.getAttributeValue("name", snap.strName))
2700 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@name attribute is missing"));
2701
2702 // earlier 3.1 trunk builds had a bug and added Description as an attribute, read it silently and write it back as an element
2703 elmSnapshot.getAttributeValue("Description", snap.strDescription);
2704
2705 if (!elmSnapshot.getAttributeValue("timeStamp", strTemp))
2706 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@timeStamp attribute is missing"));
2707 parseTimestamp(snap.timestamp, strTemp);
2708
2709 elmSnapshot.getAttributeValue("stateFile", snap.strStateFile); // online snapshots only
2710
2711 // parse Hardware before the other elements because other things depend on it
2712 const xml::ElementNode *pelmHardware;
2713 if (!(pelmHardware = elmSnapshot.findChildElement("Hardware")))
2714 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@Hardware element is missing"));
2715 readHardware(*pelmHardware, snap.hardware, snap.storage);
2716
2717 xml::NodesLoop nlSnapshotChildren(elmSnapshot);
2718 const xml::ElementNode *pelmSnapshotChild;
2719 while ((pelmSnapshotChild = nlSnapshotChildren.forAllNodes()))
2720 {
2721 if (pelmSnapshotChild->nameEquals("Description"))
2722 snap.strDescription = pelmSnapshotChild->getValue();
2723 else if ( (m->sv < SettingsVersion_v1_7)
2724 && (pelmSnapshotChild->nameEquals("HardDiskAttachments"))
2725 )
2726 readHardDiskAttachments_pre1_7(*pelmSnapshotChild, snap.storage);
2727 else if ( (m->sv >= SettingsVersion_v1_7)
2728 && (pelmSnapshotChild->nameEquals("StorageControllers"))
2729 )
2730 readStorageControllers(*pelmSnapshotChild, snap.storage);
2731 else if (pelmSnapshotChild->nameEquals("Snapshots"))
2732 {
2733 xml::NodesLoop nlChildSnapshots(*pelmSnapshotChild);
2734 const xml::ElementNode *pelmChildSnapshot;
2735 while ((pelmChildSnapshot = nlChildSnapshots.forAllNodes()))
2736 {
2737 if (pelmChildSnapshot->nameEquals("Snapshot"))
2738 {
2739 Snapshot child;
2740 readSnapshot(*pelmChildSnapshot, child);
2741 snap.llChildSnapshots.push_back(child);
2742 }
2743 }
2744 }
2745 }
2746
2747 if (m->sv < SettingsVersion_v1_9)
2748 // go through Hardware once more to repair the settings controller structures
2749 // with data from old DVDDrive and FloppyDrive elements
2750 readDVDAndFloppies_pre1_9(*pelmHardware, snap.storage);
2751}
2752
2753void MachineConfigFile::convertOldOSType_pre1_5(Utf8Str &str)
2754{
2755 if (str == "unknown") str = "Other";
2756 else if (str == "dos") str = "DOS";
2757 else if (str == "win31") str = "Windows31";
2758 else if (str == "win95") str = "Windows95";
2759 else if (str == "win98") str = "Windows98";
2760 else if (str == "winme") str = "WindowsMe";
2761 else if (str == "winnt4") str = "WindowsNT4";
2762 else if (str == "win2k") str = "Windows2000";
2763 else if (str == "winxp") str = "WindowsXP";
2764 else if (str == "win2k3") str = "Windows2003";
2765 else if (str == "winvista") str = "WindowsVista";
2766 else if (str == "win2k8") str = "Windows2008";
2767 else if (str == "os2warp3") str = "OS2Warp3";
2768 else if (str == "os2warp4") str = "OS2Warp4";
2769 else if (str == "os2warp45") str = "OS2Warp45";
2770 else if (str == "ecs") str = "OS2eCS";
2771 else if (str == "linux22") str = "Linux22";
2772 else if (str == "linux24") str = "Linux24";
2773 else if (str == "linux26") str = "Linux26";
2774 else if (str == "archlinux") str = "ArchLinux";
2775 else if (str == "debian") str = "Debian";
2776 else if (str == "opensuse") str = "OpenSUSE";
2777 else if (str == "fedoracore") str = "Fedora";
2778 else if (str == "gentoo") str = "Gentoo";
2779 else if (str == "mandriva") str = "Mandriva";
2780 else if (str == "redhat") str = "RedHat";
2781 else if (str == "ubuntu") str = "Ubuntu";
2782 else if (str == "xandros") str = "Xandros";
2783 else if (str == "freebsd") str = "FreeBSD";
2784 else if (str == "openbsd") str = "OpenBSD";
2785 else if (str == "netbsd") str = "NetBSD";
2786 else if (str == "netware") str = "Netware";
2787 else if (str == "solaris") str = "Solaris";
2788 else if (str == "opensolaris") str = "OpenSolaris";
2789 else if (str == "l4") str = "L4";
2790}
2791
2792/**
2793 * Called from the constructor to actually read in the <Machine> element
2794 * of a machine config file.
2795 * @param elmMachine
2796 */
2797void MachineConfigFile::readMachine(const xml::ElementNode &elmMachine)
2798{
2799 Utf8Str strUUID;
2800 if ( (elmMachine.getAttributeValue("uuid", strUUID))
2801 && (elmMachine.getAttributeValue("name", strName))
2802 )
2803 {
2804 parseUUID(uuid, strUUID);
2805
2806 if (!elmMachine.getAttributeValue("nameSync", fNameSync))
2807 fNameSync = true;
2808
2809 Utf8Str str;
2810 elmMachine.getAttributeValue("Description", strDescription);
2811
2812 elmMachine.getAttributeValue("OSType", strOsType);
2813 if (m->sv < SettingsVersion_v1_5)
2814 convertOldOSType_pre1_5(strOsType);
2815
2816 elmMachine.getAttributeValue("stateFile", strStateFile);
2817 if (elmMachine.getAttributeValue("currentSnapshot", str))
2818 parseUUID(uuidCurrentSnapshot, str);
2819 elmMachine.getAttributeValue("snapshotFolder", strSnapshotFolder);
2820 if (!elmMachine.getAttributeValue("currentStateModified", fCurrentStateModified))
2821 fCurrentStateModified = true;
2822 if (elmMachine.getAttributeValue("lastStateChange", str))
2823 parseTimestamp(timeLastStateChange, str);
2824 // constructor has called RTTimeNow(&timeLastStateChange) before
2825
2826 // parse Hardware before the other elements because other things depend on it
2827 const xml::ElementNode *pelmHardware;
2828 if (!(pelmHardware = elmMachine.findChildElement("Hardware")))
2829 throw ConfigFileError(this, &elmMachine, N_("Required Machine/Hardware element is missing"));
2830 readHardware(*pelmHardware, hardwareMachine, storageMachine);
2831
2832 xml::NodesLoop nlRootChildren(elmMachine);
2833 const xml::ElementNode *pelmMachineChild;
2834 while ((pelmMachineChild = nlRootChildren.forAllNodes()))
2835 {
2836 if (pelmMachineChild->nameEquals("ExtraData"))
2837 readExtraData(*pelmMachineChild,
2838 mapExtraDataItems);
2839 else if ( (m->sv < SettingsVersion_v1_7)
2840 && (pelmMachineChild->nameEquals("HardDiskAttachments"))
2841 )
2842 readHardDiskAttachments_pre1_7(*pelmMachineChild, storageMachine);
2843 else if ( (m->sv >= SettingsVersion_v1_7)
2844 && (pelmMachineChild->nameEquals("StorageControllers"))
2845 )
2846 readStorageControllers(*pelmMachineChild, storageMachine);
2847 else if (pelmMachineChild->nameEquals("Snapshot"))
2848 {
2849 Snapshot snap;
2850 // this will recurse into child snapshots, if necessary
2851 readSnapshot(*pelmMachineChild, snap);
2852 llFirstSnapshot.push_back(snap);
2853 }
2854 else if (pelmMachineChild->nameEquals("Description"))
2855 strDescription = pelmMachineChild->getValue();
2856 else if (pelmMachineChild->nameEquals("Teleporter"))
2857 {
2858 if (!pelmMachineChild->getAttributeValue("enabled", fTeleporterEnabled))
2859 fTeleporterEnabled = false;
2860 if (!pelmMachineChild->getAttributeValue("port", uTeleporterPort))
2861 uTeleporterPort = 0;
2862 if (!pelmMachineChild->getAttributeValue("address", strTeleporterAddress))
2863 strTeleporterAddress = "";
2864 if (!pelmMachineChild->getAttributeValue("password", strTeleporterPassword))
2865 strTeleporterPassword = "";
2866 }
2867 }
2868
2869 if (m->sv < SettingsVersion_v1_9)
2870 // go through Hardware once more to repair the settings controller structures
2871 // with data from old DVDDrive and FloppyDrive elements
2872 readDVDAndFloppies_pre1_9(*pelmHardware, storageMachine);
2873 }
2874 else
2875 throw ConfigFileError(this, &elmMachine, N_("Required Machine/@uuid or @name attributes is missing"));
2876}
2877
2878/**
2879 * Creates a <Hardware> node under elmParent and then writes out the XML
2880 * keys under that. Called for both the <Machine> node and for snapshots.
2881 * @param elmParent
2882 * @param st
2883 */
2884void MachineConfigFile::writeHardware(xml::ElementNode &elmParent,
2885 const Hardware &hw,
2886 const Storage &strg)
2887{
2888 xml::ElementNode *pelmHardware = elmParent.createChild("Hardware");
2889
2890 if (m->sv >= SettingsVersion_v1_4)
2891 pelmHardware->setAttribute("version", hw.strVersion);
2892 if ( (m->sv >= SettingsVersion_v1_9)
2893 && (!hw.uuid.isEmpty())
2894 )
2895 pelmHardware->setAttribute("uuid", makeString(hw.uuid));
2896
2897 xml::ElementNode *pelmCPU = pelmHardware->createChild("CPU");
2898
2899 xml::ElementNode *pelmHwVirtEx = pelmCPU->createChild("HardwareVirtEx");
2900 pelmHwVirtEx->setAttribute("enabled", hw.fHardwareVirt);
2901 if (m->sv >= SettingsVersion_v1_9)
2902 pelmHwVirtEx->setAttribute("exclusive", hw.fHardwareVirtExclusive);
2903
2904 pelmCPU->createChild("HardwareVirtExNestedPaging")->setAttribute("enabled", hw.fNestedPaging);
2905 pelmCPU->createChild("HardwareVirtExVPID")->setAttribute("enabled", hw.fVPID);
2906 pelmCPU->createChild("PAE")->setAttribute("enabled", hw.fPAE);
2907
2908 if (hw.fSyntheticCpu)
2909 pelmCPU->createChild("SyntheticCpu")->setAttribute("enabled", hw.fSyntheticCpu);
2910 pelmCPU->setAttribute("count", hw.cCPUs);
2911
2912 if (m->sv >= SettingsVersion_v1_10)
2913 {
2914 pelmCPU->setAttribute("hotplug", hw.fCpuHotPlug);
2915
2916 xml::ElementNode *pelmCpuTree = NULL;
2917 for (CpuList::const_iterator it = hw.llCpus.begin();
2918 it != hw.llCpus.end();
2919 ++it)
2920 {
2921 const Cpu &cpu = *it;
2922
2923 if (pelmCpuTree == NULL)
2924 pelmCpuTree = pelmCPU->createChild("CpuTree");
2925
2926 xml::ElementNode *pelmCpu = pelmCpuTree->createChild("Cpu");
2927 pelmCpu->setAttribute("id", cpu.ulId);
2928 }
2929 }
2930
2931 xml::ElementNode *pelmCpuIdTree = NULL;
2932 for (CpuIdLeafsList::const_iterator it = hw.llCpuIdLeafs.begin();
2933 it != hw.llCpuIdLeafs.end();
2934 ++it)
2935 {
2936 const CpuIdLeaf &leaf = *it;
2937
2938 if (pelmCpuIdTree == NULL)
2939 pelmCpuIdTree = pelmCPU->createChild("CpuIdTree");
2940
2941 xml::ElementNode *pelmCpuIdLeaf = pelmCpuIdTree->createChild("CpuIdLeaf");
2942 pelmCpuIdLeaf->setAttribute("id", leaf.ulId);
2943 pelmCpuIdLeaf->setAttribute("eax", leaf.ulEax);
2944 pelmCpuIdLeaf->setAttribute("ebx", leaf.ulEbx);
2945 pelmCpuIdLeaf->setAttribute("ecx", leaf.ulEcx);
2946 pelmCpuIdLeaf->setAttribute("edx", leaf.ulEdx);
2947 }
2948
2949 xml::ElementNode *pelmMemory = pelmHardware->createChild("Memory");
2950 pelmMemory->setAttribute("RAMSize", hw.ulMemorySizeMB);
2951
2952 if ( (m->sv >= SettingsVersion_v1_9)
2953 && (hw.firmwareType >= FirmwareType_EFI)
2954 )
2955 {
2956 xml::ElementNode *pelmFirmware = pelmHardware->createChild("Firmware");
2957 const char *pcszFirmware;
2958
2959 switch (hw.firmwareType)
2960 {
2961 case FirmwareType_EFI: pcszFirmware = "EFI"; break;
2962 case FirmwareType_EFI32: pcszFirmware = "EFI32"; break;
2963 case FirmwareType_EFI64: pcszFirmware = "EFI64"; break;
2964 case FirmwareType_EFIDUAL: pcszFirmware = "EFIDUAL"; break;
2965 default: pcszFirmware = "None"; break;
2966 }
2967 pelmFirmware->setAttribute("type", pcszFirmware);
2968 }
2969
2970 if ( (m->sv >= SettingsVersion_v1_10)
2971 )
2972 {
2973 xml::ElementNode *pelmHid = pelmHardware->createChild("HID");
2974 const char *pcszHid;
2975
2976 switch (hw.pointingHidType)
2977 {
2978 case PointingHidType_USBMouse: pcszHid = "USBMouse"; break;
2979 case PointingHidType_USBTablet: pcszHid = "USBTablet"; break;
2980 case PointingHidType_PS2Mouse: pcszHid = "PS2Mouse"; break;
2981 case PointingHidType_ComboMouse: pcszHid = "ComboMouse"; break;
2982 case PointingHidType_None: pcszHid = "None"; break;
2983 default: Assert(false); pcszHid = "PS2Mouse"; break;
2984 }
2985 pelmHid->setAttribute("Pointing", pcszHid);
2986
2987 switch (hw.keyboardHidType)
2988 {
2989 case KeyboardHidType_USBKeyboard: pcszHid = "USBKeyboard"; break;
2990 case KeyboardHidType_PS2Keyboard: pcszHid = "PS2Keyboard"; break;
2991 case KeyboardHidType_ComboKeyboard: pcszHid = "ComboKeyboard"; break;
2992 case KeyboardHidType_None: pcszHid = "None"; break;
2993 default: Assert(false); pcszHid = "PS2Keyboard"; break;
2994 }
2995 pelmHid->setAttribute("Keyboard", pcszHid);
2996 }
2997
2998 xml::ElementNode *pelmBoot = pelmHardware->createChild("Boot");
2999 for (BootOrderMap::const_iterator it = hw.mapBootOrder.begin();
3000 it != hw.mapBootOrder.end();
3001 ++it)
3002 {
3003 uint32_t i = it->first;
3004 DeviceType_T type = it->second;
3005 const char *pcszDevice;
3006
3007 switch (type)
3008 {
3009 case DeviceType_Floppy: pcszDevice = "Floppy"; break;
3010 case DeviceType_DVD: pcszDevice = "DVD"; break;
3011 case DeviceType_HardDisk: pcszDevice = "HardDisk"; break;
3012 case DeviceType_Network: pcszDevice = "Network"; break;
3013 default: /*case DeviceType_Null:*/ pcszDevice = "None"; break;
3014 }
3015
3016 xml::ElementNode *pelmOrder = pelmBoot->createChild("Order");
3017 pelmOrder->setAttribute("position",
3018 i + 1); // XML is 1-based but internal data is 0-based
3019 pelmOrder->setAttribute("device", pcszDevice);
3020 }
3021
3022 xml::ElementNode *pelmDisplay = pelmHardware->createChild("Display");
3023 pelmDisplay->setAttribute("VRAMSize", hw.ulVRAMSizeMB);
3024 pelmDisplay->setAttribute("monitorCount", hw.cMonitors);
3025 pelmDisplay->setAttribute("accelerate3D", hw.fAccelerate3D);
3026
3027 if (m->sv >= SettingsVersion_v1_8)
3028 pelmDisplay->setAttribute("accelerate2DVideo", hw.fAccelerate2DVideo);
3029
3030 xml::ElementNode *pelmVRDP = pelmHardware->createChild("RemoteDisplay");
3031 pelmVRDP->setAttribute("enabled", hw.vrdpSettings.fEnabled);
3032 Utf8Str strPort = hw.vrdpSettings.strPort;
3033 if (!strPort.length())
3034 strPort = "3389";
3035 pelmVRDP->setAttribute("port", strPort);
3036 if (hw.vrdpSettings.strNetAddress.length())
3037 pelmVRDP->setAttribute("netAddress", hw.vrdpSettings.strNetAddress);
3038 const char *pcszAuthType;
3039 switch (hw.vrdpSettings.authType)
3040 {
3041 case VRDPAuthType_Guest: pcszAuthType = "Guest"; break;
3042 case VRDPAuthType_External: pcszAuthType = "External"; break;
3043 default: /*case VRDPAuthType_Null:*/ pcszAuthType = "Null"; break;
3044 }
3045 pelmVRDP->setAttribute("authType", pcszAuthType);
3046
3047 if (hw.vrdpSettings.ulAuthTimeout != 0)
3048 pelmVRDP->setAttribute("authTimeout", hw.vrdpSettings.ulAuthTimeout);
3049 if (hw.vrdpSettings.fAllowMultiConnection)
3050 pelmVRDP->setAttribute("allowMultiConnection", hw.vrdpSettings.fAllowMultiConnection);
3051 if (hw.vrdpSettings.fReuseSingleConnection)
3052 pelmVRDP->setAttribute("reuseSingleConnection", hw.vrdpSettings.fReuseSingleConnection);
3053
3054 xml::ElementNode *pelmBIOS = pelmHardware->createChild("BIOS");
3055 pelmBIOS->createChild("ACPI")->setAttribute("enabled", hw.biosSettings.fACPIEnabled);
3056 pelmBIOS->createChild("IOAPIC")->setAttribute("enabled", hw.biosSettings.fIOAPICEnabled);
3057
3058 xml::ElementNode *pelmLogo = pelmBIOS->createChild("Logo");
3059 pelmLogo->setAttribute("fadeIn", hw.biosSettings.fLogoFadeIn);
3060 pelmLogo->setAttribute("fadeOut", hw.biosSettings.fLogoFadeOut);
3061 pelmLogo->setAttribute("displayTime", hw.biosSettings.ulLogoDisplayTime);
3062 if (hw.biosSettings.strLogoImagePath.length())
3063 pelmLogo->setAttribute("imagePath", hw.biosSettings.strLogoImagePath);
3064
3065 const char *pcszBootMenu;
3066 switch (hw.biosSettings.biosBootMenuMode)
3067 {
3068 case BIOSBootMenuMode_Disabled: pcszBootMenu = "Disabled"; break;
3069 case BIOSBootMenuMode_MenuOnly: pcszBootMenu = "MenuOnly"; break;
3070 default: /*BIOSBootMenuMode_MessageAndMenu*/ pcszBootMenu = "MessageAndMenu"; break;
3071 }
3072 pelmBIOS->createChild("BootMenu")->setAttribute("mode", pcszBootMenu);
3073 pelmBIOS->createChild("TimeOffset")->setAttribute("value", hw.biosSettings.llTimeOffset);
3074 pelmBIOS->createChild("PXEDebug")->setAttribute("enabled", hw.biosSettings.fPXEDebugEnabled);
3075
3076 if (m->sv < SettingsVersion_v1_9)
3077 {
3078 // settings formats before 1.9 had separate DVDDrive and FloppyDrive items under Hardware;
3079 // run thru the storage controllers to see if we have a DVD or floppy drives
3080 size_t cDVDs = 0;
3081 size_t cFloppies = 0;
3082
3083 xml::ElementNode *pelmDVD = pelmHardware->createChild("DVDDrive");
3084 xml::ElementNode *pelmFloppy = pelmHardware->createChild("FloppyDrive");
3085
3086 for (StorageControllersList::const_iterator it = strg.llStorageControllers.begin();
3087 it != strg.llStorageControllers.end();
3088 ++it)
3089 {
3090 const StorageController &sctl = *it;
3091 // in old settings format, the DVD drive could only have been under the IDE controller
3092 if (sctl.storageBus == StorageBus_IDE)
3093 {
3094 for (AttachedDevicesList::const_iterator it2 = sctl.llAttachedDevices.begin();
3095 it2 != sctl.llAttachedDevices.end();
3096 ++it2)
3097 {
3098 const AttachedDevice &att = *it2;
3099 if (att.deviceType == DeviceType_DVD)
3100 {
3101 if (cDVDs > 0)
3102 throw ConfigFileError(this, NULL, N_("Internal error: cannot save more than one DVD drive with old settings format"));
3103
3104 ++cDVDs;
3105
3106 pelmDVD->setAttribute("passthrough", att.fPassThrough);
3107 if (!att.uuid.isEmpty())
3108 pelmDVD->createChild("Image")->setAttribute("uuid", makeString(att.uuid));
3109 else if (att.strHostDriveSrc.length())
3110 pelmDVD->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
3111 }
3112 }
3113 }
3114 else if (sctl.storageBus == StorageBus_Floppy)
3115 {
3116 size_t cFloppiesHere = sctl.llAttachedDevices.size();
3117 if (cFloppiesHere > 1)
3118 throw ConfigFileError(this, NULL, N_("Internal error: floppy controller cannot have more than one device attachment"));
3119 if (cFloppiesHere)
3120 {
3121 const AttachedDevice &att = sctl.llAttachedDevices.front();
3122 pelmFloppy->setAttribute("enabled", true);
3123 if (!att.uuid.isEmpty())
3124 pelmFloppy->createChild("Image")->setAttribute("uuid", makeString(att.uuid));
3125 else if (att.strHostDriveSrc.length())
3126 pelmFloppy->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
3127 }
3128
3129 cFloppies += cFloppiesHere;
3130 }
3131 }
3132
3133 if (cFloppies == 0)
3134 pelmFloppy->setAttribute("enabled", false);
3135 else if (cFloppies > 1)
3136 throw ConfigFileError(this, NULL, N_("Internal error: cannot save more than one floppy drive with old settings format"));
3137 }
3138
3139 xml::ElementNode *pelmUSB = pelmHardware->createChild("USBController");
3140 pelmUSB->setAttribute("enabled", hw.usbController.fEnabled);
3141 pelmUSB->setAttribute("enabledEhci", hw.usbController.fEnabledEHCI);
3142
3143 writeUSBDeviceFilters(*pelmUSB,
3144 hw.usbController.llDeviceFilters,
3145 false); // fHostMode
3146
3147 xml::ElementNode *pelmNetwork = pelmHardware->createChild("Network");
3148 for (NetworkAdaptersList::const_iterator it = hw.llNetworkAdapters.begin();
3149 it != hw.llNetworkAdapters.end();
3150 ++it)
3151 {
3152 const NetworkAdapter &nic = *it;
3153
3154 xml::ElementNode *pelmAdapter = pelmNetwork->createChild("Adapter");
3155 pelmAdapter->setAttribute("slot", nic.ulSlot);
3156 pelmAdapter->setAttribute("enabled", nic.fEnabled);
3157 pelmAdapter->setAttribute("MACAddress", nic.strMACAddress);
3158 pelmAdapter->setAttribute("cable", nic.fCableConnected);
3159 pelmAdapter->setAttribute("speed", nic.ulLineSpeed);
3160 if (nic.fTraceEnabled)
3161 {
3162 pelmAdapter->setAttribute("trace", nic.fTraceEnabled);
3163 pelmAdapter->setAttribute("tracefile", nic.strTraceFile);
3164 }
3165
3166 const char *pcszType;
3167 switch (nic.type)
3168 {
3169 case NetworkAdapterType_Am79C973: pcszType = "Am79C973"; break;
3170 case NetworkAdapterType_I82540EM: pcszType = "82540EM"; break;
3171 case NetworkAdapterType_I82543GC: pcszType = "82543GC"; break;
3172 case NetworkAdapterType_I82545EM: pcszType = "82545EM"; break;
3173 case NetworkAdapterType_Virtio: pcszType = "virtio"; break;
3174 default: /*case NetworkAdapterType_Am79C970A:*/ pcszType = "Am79C970A"; break;
3175 }
3176 pelmAdapter->setAttribute("type", pcszType);
3177
3178 xml::ElementNode *pelmNAT;
3179 switch (nic.mode)
3180 {
3181 case NetworkAttachmentType_NAT:
3182 pelmNAT = pelmAdapter->createChild("NAT");
3183 if (nic.strName.length())
3184 pelmNAT->setAttribute("network", nic.strName);
3185 break;
3186
3187 case NetworkAttachmentType_Bridged:
3188 pelmAdapter->createChild("BridgedInterface")->setAttribute("name", nic.strName);
3189 break;
3190
3191 case NetworkAttachmentType_Internal:
3192 pelmAdapter->createChild("InternalNetwork")->setAttribute("name", nic.strName);
3193 break;
3194
3195 case NetworkAttachmentType_HostOnly:
3196 pelmAdapter->createChild("HostOnlyInterface")->setAttribute("name", nic.strName);
3197 break;
3198
3199 default: /*case NetworkAttachmentType_Null:*/
3200 break;
3201 }
3202 }
3203
3204 xml::ElementNode *pelmPorts = pelmHardware->createChild("UART");
3205 for (SerialPortsList::const_iterator it = hw.llSerialPorts.begin();
3206 it != hw.llSerialPorts.end();
3207 ++it)
3208 {
3209 const SerialPort &port = *it;
3210 xml::ElementNode *pelmPort = pelmPorts->createChild("Port");
3211 pelmPort->setAttribute("slot", port.ulSlot);
3212 pelmPort->setAttribute("enabled", port.fEnabled);
3213 pelmPort->setAttributeHex("IOBase", port.ulIOBase);
3214 pelmPort->setAttribute("IRQ", port.ulIRQ);
3215
3216 const char *pcszHostMode;
3217 switch (port.portMode)
3218 {
3219 case PortMode_HostPipe: pcszHostMode = "HostPipe"; break;
3220 case PortMode_HostDevice: pcszHostMode = "HostDevice"; break;
3221 case PortMode_RawFile: pcszHostMode = "RawFile"; break;
3222 default: /*case PortMode_Disconnected:*/ pcszHostMode = "Disconnected"; break;
3223 }
3224 switch (port.portMode)
3225 {
3226 case PortMode_HostPipe:
3227 pelmPort->setAttribute("server", port.fServer);
3228 /* no break */
3229 case PortMode_HostDevice:
3230 case PortMode_RawFile:
3231 pelmPort->setAttribute("path", port.strPath);
3232 break;
3233
3234 default:
3235 break;
3236 }
3237 pelmPort->setAttribute("hostMode", pcszHostMode);
3238 }
3239
3240 pelmPorts = pelmHardware->createChild("LPT");
3241 for (ParallelPortsList::const_iterator it = hw.llParallelPorts.begin();
3242 it != hw.llParallelPorts.end();
3243 ++it)
3244 {
3245 const ParallelPort &port = *it;
3246 xml::ElementNode *pelmPort = pelmPorts->createChild("Port");
3247 pelmPort->setAttribute("slot", port.ulSlot);
3248 pelmPort->setAttribute("enabled", port.fEnabled);
3249 pelmPort->setAttributeHex("IOBase", port.ulIOBase);
3250 pelmPort->setAttribute("IRQ", port.ulIRQ);
3251 if (port.strPath.length())
3252 pelmPort->setAttribute("path", port.strPath);
3253 }
3254
3255 xml::ElementNode *pelmAudio = pelmHardware->createChild("AudioAdapter");
3256 pelmAudio->setAttribute("controller", (hw.audioAdapter.controllerType == AudioControllerType_SB16) ? "SB16" : "AC97");
3257
3258 if ( m->sv >= SettingsVersion_v1_10)
3259 {
3260 xml::ElementNode *pelmRTC = pelmHardware->createChild("RTC");
3261 pelmRTC->setAttribute("localOrUTC", fRTCUseUTC ? "UTC" : "local");
3262 }
3263
3264 const char *pcszDriver;
3265 switch (hw.audioAdapter.driverType)
3266 {
3267 case AudioDriverType_WinMM: pcszDriver = "WinMM"; break;
3268 case AudioDriverType_DirectSound: pcszDriver = "DirectSound"; break;
3269 case AudioDriverType_SolAudio: pcszDriver = "SolAudio"; break;
3270 case AudioDriverType_ALSA: pcszDriver = "ALSA"; break;
3271 case AudioDriverType_Pulse: pcszDriver = "Pulse"; break;
3272 case AudioDriverType_OSS: pcszDriver = "OSS"; break;
3273 case AudioDriverType_CoreAudio: pcszDriver = "CoreAudio"; break;
3274 case AudioDriverType_MMPM: pcszDriver = "MMPM"; break;
3275 default: /*case AudioDriverType_Null:*/ pcszDriver = "Null"; break;
3276 }
3277 pelmAudio->setAttribute("driver", pcszDriver);
3278
3279 pelmAudio->setAttribute("enabled", hw.audioAdapter.fEnabled);
3280
3281 xml::ElementNode *pelmSharedFolders = pelmHardware->createChild("SharedFolders");
3282 for (SharedFoldersList::const_iterator it = hw.llSharedFolders.begin();
3283 it != hw.llSharedFolders.end();
3284 ++it)
3285 {
3286 const SharedFolder &sf = *it;
3287 xml::ElementNode *pelmThis = pelmSharedFolders->createChild("SharedFolder");
3288 pelmThis->setAttribute("name", sf.strName);
3289 pelmThis->setAttribute("hostPath", sf.strHostPath);
3290 pelmThis->setAttribute("writable", sf.fWritable);
3291 }
3292
3293 xml::ElementNode *pelmClip = pelmHardware->createChild("Clipboard");
3294 const char *pcszClip;
3295 switch (hw.clipboardMode)
3296 {
3297 case ClipboardMode_Disabled: pcszClip = "Disabled"; break;
3298 case ClipboardMode_HostToGuest: pcszClip = "HostToGuest"; break;
3299 case ClipboardMode_GuestToHost: pcszClip = "GuestToHost"; break;
3300 default: /*case ClipboardMode_Bidirectional:*/ pcszClip = "Bidirectional"; break;
3301 }
3302 pelmClip->setAttribute("mode", pcszClip);
3303
3304 xml::ElementNode *pelmGuest = pelmHardware->createChild("Guest");
3305 pelmGuest->setAttribute("memoryBalloonSize", hw.ulMemoryBalloonSize);
3306 pelmGuest->setAttribute("statisticsUpdateInterval", hw.ulStatisticsUpdateInterval);
3307
3308 xml::ElementNode *pelmGuestProps = pelmHardware->createChild("GuestProperties");
3309 for (GuestPropertiesList::const_iterator it = hw.llGuestProperties.begin();
3310 it != hw.llGuestProperties.end();
3311 ++it)
3312 {
3313 const GuestProperty &prop = *it;
3314 xml::ElementNode *pelmProp = pelmGuestProps->createChild("GuestProperty");
3315 pelmProp->setAttribute("name", prop.strName);
3316 pelmProp->setAttribute("value", prop.strValue);
3317 pelmProp->setAttribute("timestamp", prop.timestamp);
3318 pelmProp->setAttribute("flags", prop.strFlags);
3319 }
3320
3321 if (hw.strNotificationPatterns.length())
3322 pelmGuestProps->setAttribute("notificationPatterns", hw.strNotificationPatterns);
3323}
3324
3325/**
3326 * Creates a <StorageControllers> node under elmParent and then writes out the XML
3327 * keys under that. Called for both the <Machine> node and for snapshots.
3328 * @param elmParent
3329 * @param st
3330 */
3331void MachineConfigFile::writeStorageControllers(xml::ElementNode &elmParent,
3332 const Storage &st)
3333{
3334 xml::ElementNode *pelmStorageControllers = elmParent.createChild("StorageControllers");
3335
3336 for (StorageControllersList::const_iterator it = st.llStorageControllers.begin();
3337 it != st.llStorageControllers.end();
3338 ++it)
3339 {
3340 const StorageController &sc = *it;
3341
3342 if ( (m->sv < SettingsVersion_v1_9)
3343 && (sc.controllerType == StorageControllerType_I82078)
3344 )
3345 // floppy controller already got written into <Hardware>/<FloppyController> in writeHardware()
3346 // for pre-1.9 settings
3347 continue;
3348
3349 xml::ElementNode *pelmController = pelmStorageControllers->createChild("StorageController");
3350 com::Utf8Str name = sc.strName.raw();
3351 //
3352 if (m->sv < SettingsVersion_v1_8)
3353 {
3354 // pre-1.8 settings use shorter controller names, they are
3355 // expanded when reading the settings
3356 if (name == "IDE Controller")
3357 name = "IDE";
3358 else if (name == "SATA Controller")
3359 name = "SATA";
3360 else if (name == "SCSI Controller")
3361 name = "SCSI";
3362 }
3363 pelmController->setAttribute("name", sc.strName);
3364
3365 const char *pcszType;
3366 switch (sc.controllerType)
3367 {
3368 case StorageControllerType_IntelAhci: pcszType = "AHCI"; break;
3369 case StorageControllerType_LsiLogic: pcszType = "LsiLogic"; break;
3370 case StorageControllerType_BusLogic: pcszType = "BusLogic"; break;
3371 case StorageControllerType_PIIX4: pcszType = "PIIX4"; break;
3372 case StorageControllerType_ICH6: pcszType = "ICH6"; break;
3373 case StorageControllerType_I82078: pcszType = "I82078"; break;
3374 case StorageControllerType_LsiLogicSas: pcszType = "LsiLogicSas"; break;
3375 default: /*case StorageControllerType_PIIX3:*/ pcszType = "PIIX3"; break;
3376 }
3377 pelmController->setAttribute("type", pcszType);
3378
3379 pelmController->setAttribute("PortCount", sc.ulPortCount);
3380
3381 if (m->sv >= SettingsVersion_v1_9)
3382 if (sc.ulInstance)
3383 pelmController->setAttribute("Instance", sc.ulInstance);
3384
3385 if (sc.controllerType == StorageControllerType_IntelAhci)
3386 {
3387 pelmController->setAttribute("IDE0MasterEmulationPort", sc.lIDE0MasterEmulationPort);
3388 pelmController->setAttribute("IDE0SlaveEmulationPort", sc.lIDE0SlaveEmulationPort);
3389 pelmController->setAttribute("IDE1MasterEmulationPort", sc.lIDE1MasterEmulationPort);
3390 pelmController->setAttribute("IDE1SlaveEmulationPort", sc.lIDE1SlaveEmulationPort);
3391 }
3392
3393 for (AttachedDevicesList::const_iterator it2 = sc.llAttachedDevices.begin();
3394 it2 != sc.llAttachedDevices.end();
3395 ++it2)
3396 {
3397 const AttachedDevice &att = *it2;
3398
3399 // For settings version before 1.9, DVDs and floppies are in hardware, not storage controllers,
3400 // so we shouldn't write them here; we only get here for DVDs though because we ruled out
3401 // the floppy controller at the top of the loop
3402 if ( att.deviceType == DeviceType_DVD
3403 && m->sv < SettingsVersion_v1_9
3404 )
3405 continue;
3406
3407 xml::ElementNode *pelmDevice = pelmController->createChild("AttachedDevice");
3408
3409 pcszType = NULL;
3410
3411 switch (att.deviceType)
3412 {
3413 case DeviceType_HardDisk:
3414 pcszType = "HardDisk";
3415 break;
3416
3417 case DeviceType_DVD:
3418 pcszType = "DVD";
3419 pelmDevice->setAttribute("passthrough", att.fPassThrough);
3420 break;
3421
3422 case DeviceType_Floppy:
3423 pcszType = "Floppy";
3424 break;
3425 }
3426
3427 pelmDevice->setAttribute("type", pcszType);
3428
3429 pelmDevice->setAttribute("port", att.lPort);
3430 pelmDevice->setAttribute("device", att.lDevice);
3431
3432 if (!att.uuid.isEmpty())
3433 pelmDevice->createChild("Image")->setAttribute("uuid", makeString(att.uuid));
3434 else if ( (m->sv >= SettingsVersion_v1_9)
3435 && (att.strHostDriveSrc.length())
3436 )
3437 pelmDevice->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
3438 }
3439 }
3440}
3441
3442/**
3443 * Writes a single snapshot into the DOM tree. Initially this gets called from MachineConfigFile::write()
3444 * for the root snapshot of a machine, if present; elmParent then points to the <Snapshots> node under the
3445 * <Machine> node to which <Snapshot> must be added. This may then recurse for child snapshots.
3446 * @param elmParent
3447 * @param snap
3448 */
3449void MachineConfigFile::writeSnapshot(xml::ElementNode &elmParent,
3450 const Snapshot &snap)
3451{
3452 xml::ElementNode *pelmSnapshot = elmParent.createChild("Snapshot");
3453
3454 pelmSnapshot->setAttribute("uuid", makeString(snap.uuid));
3455 pelmSnapshot->setAttribute("name", snap.strName);
3456 pelmSnapshot->setAttribute("timeStamp", makeString(snap.timestamp));
3457
3458 if (snap.strStateFile.length())
3459 pelmSnapshot->setAttribute("stateFile", snap.strStateFile);
3460
3461 if (snap.strDescription.length())
3462 pelmSnapshot->createChild("Description")->addContent(snap.strDescription);
3463
3464 writeHardware(*pelmSnapshot, snap.hardware, snap.storage);
3465 writeStorageControllers(*pelmSnapshot, snap.storage);
3466
3467 if (snap.llChildSnapshots.size())
3468 {
3469 xml::ElementNode *pelmChildren = pelmSnapshot->createChild("Snapshots");
3470 for (SnapshotsList::const_iterator it = snap.llChildSnapshots.begin();
3471 it != snap.llChildSnapshots.end();
3472 ++it)
3473 {
3474 const Snapshot &child = *it;
3475 writeSnapshot(*pelmChildren, child);
3476 }
3477 }
3478}
3479
3480/**
3481 * Called from write() before calling ConfigFileBase::createStubDocument().
3482 * This adjusts the settings version in m->sv if incompatible settings require
3483 * a settings bump, whereas otherwise we try to preserve the settings version
3484 * to avoid breaking compatibility with older versions.
3485 */
3486void MachineConfigFile::bumpSettingsVersionIfNeeded()
3487{
3488 // The hardware versions other than "1" requires settings version 1.4 (2.1+).
3489 if ( m->sv < SettingsVersion_v1_4
3490 && hardwareMachine.strVersion != "1"
3491 )
3492 m->sv = SettingsVersion_v1_4;
3493
3494 // "accelerate 2d video" requires settings version 1.8
3495 if ( (m->sv < SettingsVersion_v1_8)
3496 && (hardwareMachine.fAccelerate2DVideo)
3497 )
3498 m->sv = SettingsVersion_v1_8;
3499
3500 // all the following require settings version 1.9
3501 if ( (m->sv < SettingsVersion_v1_9)
3502 && ( (hardwareMachine.firmwareType >= FirmwareType_EFI)
3503 || (hardwareMachine.fHardwareVirtExclusive != HWVIRTEXCLUSIVEDEFAULT)
3504 || fTeleporterEnabled
3505 || uTeleporterPort
3506 || !strTeleporterAddress.isEmpty()
3507 || !strTeleporterPassword.isEmpty()
3508 || !hardwareMachine.uuid.isEmpty()
3509 )
3510 )
3511 m->sv = SettingsVersion_v1_9;
3512
3513 // settings version 1.9 is also required if there is not exactly one DVD
3514 // or more than one floppy drive present or the DVD is not at the secondary
3515 // master; this check is a bit more complicated
3516 if (m->sv < SettingsVersion_v1_9)
3517 {
3518 size_t cDVDs = 0;
3519 size_t cFloppies = 0;
3520
3521 // need to run thru all the storage controllers to figure this out
3522 for (StorageControllersList::const_iterator it = storageMachine.llStorageControllers.begin();
3523 it != storageMachine.llStorageControllers.end()
3524 && m->sv < SettingsVersion_v1_9;
3525 ++it)
3526 {
3527 const StorageController &sctl = *it;
3528 for (AttachedDevicesList::const_iterator it2 = sctl.llAttachedDevices.begin();
3529 it2 != sctl.llAttachedDevices.end();
3530 ++it2)
3531 {
3532 if (sctl.ulInstance != 0) // we can only write the StorageController/@Instance attribute with v1.9
3533 {
3534 m->sv = SettingsVersion_v1_9;
3535 break;
3536 }
3537
3538 const AttachedDevice &att = *it2;
3539 if (att.deviceType == DeviceType_DVD)
3540 {
3541 if ( (sctl.storageBus != StorageBus_IDE) // DVD at bus other than DVD?
3542 || (att.lPort != 1) // DVDs not at secondary master?
3543 || (att.lDevice != 0)
3544 )
3545 {
3546 m->sv = SettingsVersion_v1_9;
3547 break;
3548 }
3549
3550 ++cDVDs;
3551 }
3552 else if (att.deviceType == DeviceType_Floppy)
3553 ++cFloppies;
3554 }
3555 }
3556
3557 // VirtualBox before 3.1 had zero or one floppy and exactly one DVD,
3558 // so any deviation from that will require settings version 1.9
3559 if ( (m->sv < SettingsVersion_v1_9)
3560 && ( (cDVDs != 1)
3561 || (cFloppies > 1)
3562 )
3563 )
3564 m->sv = SettingsVersion_v1_9;
3565 }
3566
3567 if ( m->sv < SettingsVersion_v1_10
3568 && ( fRTCUseUTC
3569 || hardwareMachine.fCpuHotPlug
3570 || hardwareMachine.pointingHidType != PointingHidType_PS2Mouse
3571 || hardwareMachine.keyboardHidType != KeyboardHidType_PS2Keyboard
3572 )
3573 )
3574 m->sv = SettingsVersion_v1_10;
3575}
3576
3577/**
3578 * Called from Main code to write a machine config file to disk. This builds a DOM tree from
3579 * the member variables and then writes the XML file; it throws xml::Error instances on errors,
3580 * in particular if the file cannot be written.
3581 */
3582void MachineConfigFile::write(const com::Utf8Str &strFilename)
3583{
3584 try
3585 {
3586 // createStubDocument() sets the settings version to at least 1.7; however,
3587 // we might need to enfore a later settings version if incompatible settings
3588 // are present:
3589 bumpSettingsVersionIfNeeded();
3590
3591 m->strFilename = strFilename;
3592 createStubDocument();
3593
3594 xml::ElementNode *pelmMachine = m->pelmRoot->createChild("Machine");
3595
3596 pelmMachine->setAttribute("uuid", makeString(uuid));
3597 pelmMachine->setAttribute("name", strName);
3598 if (!fNameSync)
3599 pelmMachine->setAttribute("nameSync", fNameSync);
3600 if (strDescription.length())
3601 pelmMachine->createChild("Description")->addContent(strDescription);
3602 pelmMachine->setAttribute("OSType", strOsType);
3603 if (strStateFile.length())
3604 pelmMachine->setAttribute("stateFile", strStateFile);
3605 if (!uuidCurrentSnapshot.isEmpty())
3606 pelmMachine->setAttribute("currentSnapshot", makeString(uuidCurrentSnapshot));
3607 if (strSnapshotFolder.length())
3608 pelmMachine->setAttribute("snapshotFolder", strSnapshotFolder);
3609 if (!fCurrentStateModified)
3610 pelmMachine->setAttribute("currentStateModified", fCurrentStateModified);
3611 pelmMachine->setAttribute("lastStateChange", makeString(timeLastStateChange));
3612 if (fAborted)
3613 pelmMachine->setAttribute("aborted", fAborted);
3614 if ( m->sv >= SettingsVersion_v1_9
3615 && ( fTeleporterEnabled
3616 || uTeleporterPort
3617 || !strTeleporterAddress.isEmpty()
3618 || !strTeleporterPassword.isEmpty()
3619 )
3620 )
3621 {
3622 xml::ElementNode *pelmTeleporter = pelmMachine->createChild("Teleporter");
3623 pelmTeleporter->setAttribute("enabled", fTeleporterEnabled);
3624 pelmTeleporter->setAttribute("port", uTeleporterPort);
3625 pelmTeleporter->setAttribute("address", strTeleporterAddress);
3626 pelmTeleporter->setAttribute("password", strTeleporterPassword);
3627 }
3628
3629 writeExtraData(*pelmMachine, mapExtraDataItems);
3630
3631 if (llFirstSnapshot.size())
3632 writeSnapshot(*pelmMachine, llFirstSnapshot.front());
3633
3634 writeHardware(*pelmMachine, hardwareMachine, storageMachine);
3635 writeStorageControllers(*pelmMachine, storageMachine);
3636
3637 // now go write the XML
3638 xml::XmlFileWriter writer(*m->pDoc);
3639 writer.write(m->strFilename.c_str());
3640
3641 m->fFileExists = true;
3642 clearDocument();
3643 }
3644 catch (...)
3645 {
3646 clearDocument();
3647 throw;
3648 }
3649}
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