VirtualBox

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

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

XmlFileWrite::write: Added a fSafe argument for safe writing of the xml file. See method description for details.

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

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