VirtualBox

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

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

Bump xml version if page fusion is enabled

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