VirtualBox

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

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

Enable nested paging by default for new VMs

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