VirtualBox

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

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

Main: Introduce a per controller setting to switch to the unbuffered async I/O interface (UseNewIo). Configurable through VBoxManage, default is still buffered

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