VirtualBox

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

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

more warnings.

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