VirtualBox

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

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

Main/Medium: new stub medium type "Shareable", plus assorted frontend changes to prepare its use.

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette