VirtualBox

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

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

OVF: fix incorrect disk UUIDs in machine XML on export

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