VirtualBox

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

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

Main: Introduce various I/O control settings:

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