VirtualBox

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

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

LsiLogic: Add SAS support for Main and Frontends

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Revision Author Id
File size: 129.5 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.1, write it
32 * only if (m->sv >= SettingsVersion_v1_9).
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-2009 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.9"
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 : pParser(NULL),
125 pDoc(NULL),
126 pelmRoot(NULL),
127 sv(SettingsVersion_Null),
128 svRead(SettingsVersion_Null)
129 {}
130
131 ~Data()
132 {
133 cleanup();
134 }
135
136 iprt::MiniString strFilename;
137 bool fFileExists;
138
139 xml::XmlFileParser *pParser;
140 xml::Document *pDoc;
141 xml::ElementNode *pelmRoot;
142
143 com::Utf8Str strSettingsVersionFull; // e.g. "1.7-linux"
144 SettingsVersion_T sv; // e.g. SettingsVersion_v1_7
145
146 SettingsVersion_T svRead; // settings version that the original file had when it was read,
147 // or SettingsVersion_Null if none
148
149 void cleanup()
150 {
151 if (pDoc)
152 {
153 delete pDoc;
154 pDoc = NULL;
155 pelmRoot = NULL;
156 }
157
158 if (pParser)
159 {
160 delete pParser;
161 pParser = NULL;
162 }
163 }
164};
165
166/**
167 * Private exception class (not in the header file) that makes
168 * throwing xml::LogicError instances easier. That class is public
169 * and should be caught by client code.
170 */
171class settings::ConfigFileError : public xml::LogicError
172{
173public:
174 ConfigFileError(const ConfigFileBase *file,
175 const xml::Node *pNode,
176 const char *pcszFormat, ...)
177 : xml::LogicError()
178 {
179 va_list args;
180 va_start(args, pcszFormat);
181 Utf8StrFmtVA strWhat(pcszFormat, args);
182 va_end(args);
183
184 Utf8Str strLine;
185 if (pNode)
186 strLine = Utf8StrFmt(" (line %RU32)", pNode->getLineNumber());
187
188 const char *pcsz = strLine.c_str();
189 Utf8StrFmt str(N_("Error in %s%s -- %s"),
190 file->m->strFilename.c_str(),
191 (pcsz) ? pcsz : "",
192 strWhat.c_str());
193
194 setWhat(str.c_str());
195 }
196};
197
198////////////////////////////////////////////////////////////////////////////////
199//
200// ConfigFileBase
201//
202////////////////////////////////////////////////////////////////////////////////
203
204/**
205 * Constructor. Allocates the XML internals.
206 * @param strFilename
207 */
208ConfigFileBase::ConfigFileBase(const com::Utf8Str *pstrFilename)
209 : m(new Data)
210{
211 Utf8Str strMajor;
212 Utf8Str strMinor;
213
214 m->fFileExists = false;
215
216 if (pstrFilename)
217 {
218 m->strFilename = *pstrFilename;
219
220 m->pParser = new xml::XmlFileParser;
221 m->pDoc = new xml::Document;
222 m->pParser->read(*pstrFilename,
223 *m->pDoc);
224
225 m->fFileExists = true;
226
227 m->pelmRoot = m->pDoc->getRootElement();
228 if (!m->pelmRoot || !m->pelmRoot->nameEquals("VirtualBox"))
229 throw ConfigFileError(this, NULL, N_("Root element in VirtualBox settings files must be \"VirtualBox\"."));
230
231 if (!(m->pelmRoot->getAttributeValue("version", m->strSettingsVersionFull)))
232 throw ConfigFileError(this, m->pelmRoot, N_("Required VirtualBox/@version attribute is missing"));
233
234 LogRel(("Loading settings file \"%s\" with version \"%s\"\n", m->strFilename.c_str(), m->strSettingsVersionFull.c_str()));
235
236 // parse settings version; allow future versions but fail if file is older than 1.6
237 m->sv = SettingsVersion_Null;
238 if (m->strSettingsVersionFull.length() > 3)
239 {
240 const char *pcsz = m->strSettingsVersionFull.c_str();
241 char c;
242
243 while ( (c = *pcsz)
244 && RT_C_IS_DIGIT(c)
245 )
246 {
247 strMajor.append(c);
248 ++pcsz;
249 }
250
251 if (*pcsz++ == '.')
252 {
253 while ( (c = *pcsz)
254 && RT_C_IS_DIGIT(c)
255 )
256 {
257 strMinor.append(c);
258 ++pcsz;
259 }
260 }
261
262 uint32_t ulMajor = RTStrToUInt32(strMajor.c_str());
263 uint32_t ulMinor = RTStrToUInt32(strMinor.c_str());
264
265 if (ulMajor == 1)
266 {
267 if (ulMinor == 3)
268 m->sv = SettingsVersion_v1_3;
269 else if (ulMinor == 4)
270 m->sv = SettingsVersion_v1_4;
271 else if (ulMinor == 5)
272 m->sv = SettingsVersion_v1_5;
273 else if (ulMinor == 6)
274 m->sv = SettingsVersion_v1_6;
275 else if (ulMinor == 7)
276 m->sv = SettingsVersion_v1_7;
277 else if (ulMinor == 8)
278 m->sv = SettingsVersion_v1_8;
279 else if (ulMinor == 9)
280 m->sv = SettingsVersion_v1_9;
281 else if (ulMinor > 9)
282 m->sv = SettingsVersion_Future;
283 }
284 else if (ulMajor > 1)
285 m->sv = SettingsVersion_Future;
286
287 LogRel(("Parsed settings version %d.%d to enum value %d\n", ulMajor, ulMinor, m->sv));
288 }
289
290 if (m->sv == SettingsVersion_Null)
291 throw ConfigFileError(this, m->pelmRoot, N_("Cannot handle settings version '%s'"), m->strSettingsVersionFull.c_str());
292
293 // remember the settings version we read in case it gets upgraded later,
294 // so we know when to make backups
295 m->svRead = m->sv;
296 }
297 else
298 {
299 m->strSettingsVersionFull = VBOX_XML_VERSION_FULL;
300 m->sv = SettingsVersion_v1_9;
301 }
302}
303
304/**
305 * Clean up.
306 */
307ConfigFileBase::~ConfigFileBase()
308{
309 if (m)
310 {
311 delete m;
312 m = NULL;
313 }
314}
315
316/**
317 * Helper function that parses a UUID in string form into
318 * a com::Guid item. Since that uses an IPRT function which
319 * does not accept "{}" characters around the UUID string,
320 * we handle that here. Throws on errors.
321 * @param guid
322 * @param strUUID
323 */
324void ConfigFileBase::parseUUID(Guid &guid,
325 const Utf8Str &strUUID) const
326{
327 // {5f102a55-a51b-48e3-b45a-b28d33469488}
328 // 01234567890123456789012345678901234567
329 // 1 2 3
330 if ( (strUUID[0] == '{')
331 && (strUUID[37] == '}')
332 )
333 guid = strUUID.substr(1, 36).c_str();
334 else
335 guid = strUUID.c_str();
336
337 if (guid.isEmpty())
338 throw ConfigFileError(this, NULL, N_("UUID \"%s\" has invalid format"), strUUID.c_str());
339}
340
341/**
342 * Parses the given string in str and attempts to treat it as an ISO
343 * date/time stamp to put into timestamp. Throws on errors.
344 * @param timestamp
345 * @param str
346 */
347void ConfigFileBase::parseTimestamp(RTTIMESPEC &timestamp,
348 const com::Utf8Str &str) const
349{
350 const char *pcsz = str.c_str();
351 // yyyy-mm-ddThh:mm:ss
352 // "2009-07-10T11:54:03Z"
353 // 01234567890123456789
354 // 1
355 if (str.length() > 19)
356 {
357 // timezone must either be unspecified or 'Z' for UTC
358 if ( (pcsz[19])
359 && (pcsz[19] != 'Z')
360 )
361 throw ConfigFileError(this, NULL, N_("Cannot handle ISO timestamp '%s': is not UTC date"), str.c_str());
362
363 int32_t yyyy;
364 uint32_t mm, dd, hh, min, secs;
365 if ( (pcsz[4] == '-')
366 && (pcsz[7] == '-')
367 && (pcsz[10] == 'T')
368 && (pcsz[13] == ':')
369 && (pcsz[16] == ':')
370 )
371 {
372 int rc;
373 if ( (RT_SUCCESS(rc = RTStrToInt32Ex(pcsz, NULL, 0, &yyyy)))
374 // could theoretically be negative but let's assume that nobody
375 // created virtual machines before the Christian era
376 && (RT_SUCCESS(rc = RTStrToUInt32Ex(pcsz + 5, NULL, 0, &mm)))
377 && (RT_SUCCESS(rc = RTStrToUInt32Ex(pcsz + 8, NULL, 0, &dd)))
378 && (RT_SUCCESS(rc = RTStrToUInt32Ex(pcsz + 11, NULL, 0, &hh)))
379 && (RT_SUCCESS(rc = RTStrToUInt32Ex(pcsz + 14, NULL, 0, &min)))
380 && (RT_SUCCESS(rc = RTStrToUInt32Ex(pcsz + 17, NULL, 0, &secs)))
381 )
382 {
383 RTTIME time = { yyyy,
384 (uint8_t)mm,
385 0,
386 0,
387 (uint8_t)dd,
388 (uint8_t)hh,
389 (uint8_t)min,
390 (uint8_t)secs,
391 0,
392 RTTIME_FLAGS_TYPE_UTC };
393 if (RTTimeNormalize(&time))
394 if (RTTimeImplode(&timestamp, &time))
395 return;
396 }
397
398 throw ConfigFileError(this, NULL, N_("Cannot parse ISO timestamp '%s': runtime error, %Rra"), str.c_str(), rc);
399 }
400
401 throw ConfigFileError(this, NULL, N_("Cannot parse ISO timestamp '%s': invalid format"), str.c_str());
402 }
403}
404
405/**
406 * Helper to create a string for a RTTIMESPEC for writing out ISO timestamps.
407 * @param stamp
408 * @return
409 */
410com::Utf8Str ConfigFileBase::makeString(const RTTIMESPEC &stamp)
411{
412 RTTIME time;
413 if (!RTTimeExplode(&time, &stamp))
414 throw ConfigFileError(this, NULL, N_("Timespec %lld ms is invalid"), RTTimeSpecGetMilli(&stamp));
415
416 return Utf8StrFmt("%04ld-%02hd-%02hdT%02hd:%02hd:%02hdZ",
417 time.i32Year,
418 (uint16_t)time.u8Month,
419 (uint16_t)time.u8MonthDay,
420 (uint16_t)time.u8Hour,
421 (uint16_t)time.u8Minute,
422 (uint16_t)time.u8Second);
423}
424
425/**
426 * Helper to create a string for a GUID.
427 * @param guid
428 * @return
429 */
430com::Utf8Str ConfigFileBase::makeString(const Guid &guid)
431{
432 Utf8Str str("{");
433 str.append(guid.toString());
434 str.append("}");
435 return str;
436}
437
438/**
439 * Helper method to read in an ExtraData subtree and stores its contents
440 * in the given map of extradata items. Used for both main and machine
441 * extradata (MainConfigFile and MachineConfigFile).
442 * @param elmExtraData
443 * @param map
444 */
445void ConfigFileBase::readExtraData(const xml::ElementNode &elmExtraData,
446 ExtraDataItemsMap &map)
447{
448 xml::NodesLoop nlLevel4(elmExtraData);
449 const xml::ElementNode *pelmExtraDataItem;
450 while ((pelmExtraDataItem = nlLevel4.forAllNodes()))
451 {
452 if (pelmExtraDataItem->nameEquals("ExtraDataItem"))
453 {
454 // <ExtraDataItem name="GUI/LastWindowPostion" value="97,88,981,858"/>
455 Utf8Str strName, strValue;
456 if ( ((pelmExtraDataItem->getAttributeValue("name", strName)))
457 && ((pelmExtraDataItem->getAttributeValue("value", strValue)))
458 )
459 map[strName] = strValue;
460 else
461 throw ConfigFileError(this, pelmExtraDataItem, N_("Required ExtraDataItem/@name or @value attribute is missing"));
462 }
463 }
464}
465
466/**
467 * Reads <USBDeviceFilter> entries from under the given elmDeviceFilters node and
468 * stores them in the given linklist. This is in ConfigFileBase because it's used
469 * from both MainConfigFile (for host filters) and MachineConfigFile (for machine
470 * filters).
471 * @param elmDeviceFilters
472 * @param ll
473 */
474void ConfigFileBase::readUSBDeviceFilters(const xml::ElementNode &elmDeviceFilters,
475 USBDeviceFiltersList &ll)
476{
477 xml::NodesLoop nl1(elmDeviceFilters, "DeviceFilter");
478 const xml::ElementNode *pelmLevel4Child;
479 while ((pelmLevel4Child = nl1.forAllNodes()))
480 {
481 USBDeviceFilter flt;
482 flt.action = USBDeviceFilterAction_Ignore;
483 Utf8Str strAction;
484 if ( (pelmLevel4Child->getAttributeValue("name", flt.strName))
485 && (pelmLevel4Child->getAttributeValue("active", flt.fActive))
486 )
487 {
488 if (!pelmLevel4Child->getAttributeValue("vendorId", flt.strVendorId))
489 pelmLevel4Child->getAttributeValue("vendorid", flt.strVendorId); // used before 1.3
490 if (!pelmLevel4Child->getAttributeValue("productId", flt.strProductId))
491 pelmLevel4Child->getAttributeValue("productid", flt.strProductId); // used before 1.3
492 pelmLevel4Child->getAttributeValue("revision", flt.strRevision);
493 pelmLevel4Child->getAttributeValue("manufacturer", flt.strManufacturer);
494 pelmLevel4Child->getAttributeValue("product", flt.strProduct);
495 if (!pelmLevel4Child->getAttributeValue("serialNumber", flt.strSerialNumber))
496 pelmLevel4Child->getAttributeValue("serialnumber", flt.strSerialNumber); // used before 1.3
497 pelmLevel4Child->getAttributeValue("port", flt.strPort);
498
499 // the next 2 are irrelevant for host USB objects
500 pelmLevel4Child->getAttributeValue("remote", flt.strRemote);
501 pelmLevel4Child->getAttributeValue("maskedInterfaces", flt.ulMaskedInterfaces);
502
503 // action is only used with host USB objects
504 if (pelmLevel4Child->getAttributeValue("action", strAction))
505 {
506 if (strAction == "Ignore")
507 flt.action = USBDeviceFilterAction_Ignore;
508 else if (strAction == "Hold")
509 flt.action = USBDeviceFilterAction_Hold;
510 else
511 throw ConfigFileError(this, pelmLevel4Child, N_("Invalid value '%s' in DeviceFilter/@action attribute"), strAction.c_str());
512 }
513
514 ll.push_back(flt);
515 }
516 }
517}
518
519/**
520 * Creates a new stub xml::Document in the m->pDoc member with the
521 * root "VirtualBox" element set up. This is used by both
522 * MainConfigFile and MachineConfigFile at the beginning of writing
523 * out their XML.
524 *
525 * Before calling this, it is the responsibility of the caller to
526 * set the "sv" member to the required settings version that is to
527 * be written. For newly created files, the settings version will be
528 * the latest (1.9); for files read in from disk earlier, it will be
529 * the settings version indicated in the file. However, this method
530 * will silently make sure that the settings version is always
531 * at least 1.7 and change it if necessary, since there is no write
532 * support for earlier settings versions.
533 */
534void ConfigFileBase::createStubDocument()
535{
536 Assert(m->pDoc == NULL);
537 m->pDoc = new xml::Document;
538
539 m->pelmRoot = m->pDoc->createRootElement("VirtualBox");
540 m->pelmRoot->setAttribute("xmlns", VBOX_XML_NAMESPACE);
541
542 const char *pcszVersion = NULL;
543 switch (m->sv)
544 {
545 case SettingsVersion_v1_8:
546 pcszVersion = "1.8";
547 break;
548
549 case SettingsVersion_v1_9:
550 case SettingsVersion_Future: // can be set if this code runs on XML files that were created by a future version of VBox;
551 // in that case, downgrade to current version when writing since we can't write future versions...
552 pcszVersion = "1.9";
553 m->sv = SettingsVersion_v1_9;
554 break;
555
556 default:
557 // silently upgrade if this is less than 1.7 because that's the oldest we can write
558 pcszVersion = "1.7";
559 m->sv = SettingsVersion_v1_7;
560 break;
561 }
562
563 m->pelmRoot->setAttribute("version", Utf8StrFmt("%s-%s",
564 pcszVersion,
565 VBOX_XML_PLATFORM)); // e.g. "linux"
566
567 // since this gets called before the XML document is actually written out
568 // do this, this is where we must check whether we're upgrading the settings
569 // version and need to make a backup, so the user can go back to an earlier
570 // VirtualBox version and recover his old settings files.
571 if ( (m->svRead != SettingsVersion_Null) // old file exists?
572 && (m->svRead < m->sv) // we're upgrading?
573 )
574 {
575 // compose new filename: strip off trailing ".xml"
576 Utf8Str strFilenameNew = m->strFilename.substr(0, m->strFilename.length() - 4);
577 // and append something likd "-1.3-linux.xml"
578 strFilenameNew.append("-");
579 strFilenameNew.append(m->strSettingsVersionFull); // e.g. "1.3-linux"
580 strFilenameNew.append(".xml");
581
582 RTFileMove(m->strFilename.c_str(),
583 strFilenameNew.c_str(),
584 0); // no RTFILEMOVE_FLAGS_REPLACE
585
586 // do this only once
587 m->svRead = SettingsVersion_Null;
588 }
589}
590
591/**
592 * Creates an <ExtraData> node under the given parent element with
593 * <ExtraDataItem> childern according to the contents of the given
594 * map.
595 * This is in ConfigFileBase because it's used in both MainConfigFile
596 * MachineConfigFile, which both can have extradata.
597 *
598 * @param elmParent
599 * @param me
600 */
601void ConfigFileBase::writeExtraData(xml::ElementNode &elmParent,
602 const ExtraDataItemsMap &me)
603{
604 if (me.size())
605 {
606 xml::ElementNode *pelmExtraData = elmParent.createChild("ExtraData");
607 for (ExtraDataItemsMap::const_iterator it = me.begin();
608 it != me.end();
609 ++it)
610 {
611 const Utf8Str &strName = it->first;
612 const Utf8Str &strValue = it->second;
613 xml::ElementNode *pelmThis = pelmExtraData->createChild("ExtraDataItem");
614 pelmThis->setAttribute("name", strName);
615 pelmThis->setAttribute("value", strValue);
616 }
617 }
618}
619
620/**
621 * Creates <DeviceFilter> nodes under the given parent element according to
622 * the contents of the given USBDeviceFiltersList. This is in ConfigFileBase
623 * because it's used in both MainConfigFile (for host filters) and
624 * MachineConfigFile (for machine filters).
625 *
626 * If fHostMode is true, this means that we're supposed to write filters
627 * for the IHost interface (respect "action", omit "strRemote" and
628 * "ulMaskedInterfaces" in struct USBDeviceFilter).
629 *
630 * @param elmParent
631 * @param ll
632 * @param fHostMode
633 */
634void ConfigFileBase::writeUSBDeviceFilters(xml::ElementNode &elmParent,
635 const USBDeviceFiltersList &ll,
636 bool fHostMode)
637{
638 for (USBDeviceFiltersList::const_iterator it = ll.begin();
639 it != ll.end();
640 ++it)
641 {
642 const USBDeviceFilter &flt = *it;
643 xml::ElementNode *pelmFilter = elmParent.createChild("DeviceFilter");
644 pelmFilter->setAttribute("name", flt.strName);
645 pelmFilter->setAttribute("active", flt.fActive);
646 if (flt.strVendorId.length())
647 pelmFilter->setAttribute("vendorId", flt.strVendorId);
648 if (flt.strProductId.length())
649 pelmFilter->setAttribute("productId", flt.strProductId);
650 if (flt.strRevision.length())
651 pelmFilter->setAttribute("revision", flt.strRevision);
652 if (flt.strManufacturer.length())
653 pelmFilter->setAttribute("manufacturer", flt.strManufacturer);
654 if (flt.strProduct.length())
655 pelmFilter->setAttribute("product", flt.strProduct);
656 if (flt.strSerialNumber.length())
657 pelmFilter->setAttribute("serialNumber", flt.strSerialNumber);
658 if (flt.strPort.length())
659 pelmFilter->setAttribute("port", flt.strPort);
660
661 if (fHostMode)
662 {
663 const char *pcsz =
664 (flt.action == USBDeviceFilterAction_Ignore) ? "Ignore"
665 : /*(flt.action == USBDeviceFilterAction_Hold) ?*/ "Hold";
666 pelmFilter->setAttribute("action", pcsz);
667 }
668 else
669 {
670 if (flt.strRemote.length())
671 pelmFilter->setAttribute("remote", flt.strRemote);
672 if (flt.ulMaskedInterfaces)
673 pelmFilter->setAttribute("maskedInterfaces", flt.ulMaskedInterfaces);
674 }
675 }
676}
677
678/**
679 * Cleans up memory allocated by the internal XML parser. To be called by
680 * descendant classes when they're done analyzing the DOM tree to discard it.
681 */
682void ConfigFileBase::clearDocument()
683{
684 m->cleanup();
685}
686
687/**
688 * Returns true only if the underlying config file exists on disk;
689 * either because the file has been loaded from disk, or it's been written
690 * to disk, or both.
691 * @return
692 */
693bool ConfigFileBase::fileExists()
694{
695 return m->fFileExists;
696}
697
698
699////////////////////////////////////////////////////////////////////////////////
700//
701// MainConfigFile
702//
703////////////////////////////////////////////////////////////////////////////////
704
705/**
706 * Reads one <MachineEntry> from the main VirtualBox.xml file.
707 * @param elmMachineRegistry
708 */
709void MainConfigFile::readMachineRegistry(const xml::ElementNode &elmMachineRegistry)
710{
711 // <MachineEntry uuid="{ xxx }" src=" xxx "/>
712 xml::NodesLoop nl1(elmMachineRegistry);
713 const xml::ElementNode *pelmChild1;
714 while ((pelmChild1 = nl1.forAllNodes()))
715 {
716 if (pelmChild1->nameEquals("MachineEntry"))
717 {
718 MachineRegistryEntry mre;
719 Utf8Str strUUID;
720 if ( ((pelmChild1->getAttributeValue("uuid", strUUID)))
721 && ((pelmChild1->getAttributeValue("src", mre.strSettingsFile)))
722 )
723 {
724 parseUUID(mre.uuid, strUUID);
725 llMachines.push_back(mre);
726 }
727 else
728 throw ConfigFileError(this, pelmChild1, N_("Required MachineEntry/@uuid or @src attribute is missing"));
729 }
730 }
731}
732
733/**
734 * Reads a media registry entry from the main VirtualBox.xml file.
735 *
736 * Whereas the current media registry code is fairly straightforward, it was quite a mess
737 * with settings format before 1.4 (VirtualBox 2.0 used settings format 1.3). The elements
738 * in the media registry were much more inconsistent, and different elements were used
739 * depending on the type of device and image.
740 *
741 * @param t
742 * @param elmMedium
743 * @param llMedia
744 */
745void MainConfigFile::readMedium(MediaType t,
746 const xml::ElementNode &elmMedium, // HardDisk node if root; if recursing,
747 // child HardDisk node or DiffHardDisk node for pre-1.4
748 MediaList &llMedia) // list to append medium to (root disk or child list)
749{
750 // <HardDisk uuid="{5471ecdb-1ddb-4012-a801-6d98e226868b}" location="/mnt/innotek-unix/vdis/Windows XP.vdi" format="VDI" type="Normal">
751 settings::Medium med;
752 Utf8Str strUUID;
753 if (!(elmMedium.getAttributeValue("uuid", strUUID)))
754 throw ConfigFileError(this, &elmMedium, N_("Required %s/@uuid attribute is missing"), elmMedium.getName());
755
756 parseUUID(med.uuid, strUUID);
757
758 bool fNeedsLocation = true;
759
760 if (t == HardDisk)
761 {
762 if (m->sv < SettingsVersion_v1_4)
763 {
764 // here the system is:
765 // <HardDisk uuid="{....}" type="normal">
766 // <VirtualDiskImage filePath="/path/to/xxx.vdi"/>
767 // </HardDisk>
768
769 fNeedsLocation = false;
770 bool fNeedsFilePath = true;
771 const xml::ElementNode *pelmImage;
772 if ((pelmImage = elmMedium.findChildElement("VirtualDiskImage")))
773 med.strFormat = "VDI";
774 else if ((pelmImage = elmMedium.findChildElement("VMDKImage")))
775 med.strFormat = "VMDK";
776 else if ((pelmImage = elmMedium.findChildElement("VHDImage")))
777 med.strFormat = "VHD";
778 else if ((pelmImage = elmMedium.findChildElement("ISCSIHardDisk")))
779 {
780 med.strFormat = "iSCSI";
781
782 fNeedsFilePath = false;
783 // location is special here: current settings specify an "iscsi://user@server:port/target/lun"
784 // string for the location and also have several disk properties for these, whereas this used
785 // to be hidden in several sub-elements before 1.4, so compose a location string and set up
786 // the properties:
787 med.strLocation = "iscsi://";
788 Utf8Str strUser, strServer, strPort, strTarget, strLun;
789 if (pelmImage->getAttributeValue("userName", strUser))
790 {
791 med.strLocation.append(strUser);
792 med.strLocation.append("@");
793 }
794 Utf8Str strServerAndPort;
795 if (pelmImage->getAttributeValue("server", strServer))
796 {
797 strServerAndPort = strServer;
798 }
799 if (pelmImage->getAttributeValue("port", strPort))
800 {
801 if (strServerAndPort.length())
802 strServerAndPort.append(":");
803 strServerAndPort.append(strPort);
804 }
805 med.strLocation.append(strServerAndPort);
806 if (pelmImage->getAttributeValue("target", strTarget))
807 {
808 med.strLocation.append("/");
809 med.strLocation.append(strTarget);
810 }
811 if (pelmImage->getAttributeValue("lun", strLun))
812 {
813 med.strLocation.append("/");
814 med.strLocation.append(strLun);
815 }
816
817 if (strServer.length() && strPort.length())
818 med.properties["TargetAddress"] = strServerAndPort;
819 if (strTarget.length())
820 med.properties["TargetName"] = strTarget;
821 if (strUser.length())
822 med.properties["InitiatorUsername"] = strUser;
823 Utf8Str strPassword;
824 if (pelmImage->getAttributeValue("password", strPassword))
825 med.properties["InitiatorSecret"] = strPassword;
826 if (strLun.length())
827 med.properties["LUN"] = strLun;
828 }
829 else if ((pelmImage = elmMedium.findChildElement("CustomHardDisk")))
830 {
831 fNeedsFilePath = false;
832 fNeedsLocation = true;
833 // also requires @format attribute, which will be queried below
834 }
835 else
836 throw ConfigFileError(this, &elmMedium, N_("Required %s/VirtualDiskImage element is missing"), elmMedium.getName());
837
838 if (fNeedsFilePath)
839 if (!(pelmImage->getAttributeValue("filePath", med.strLocation)))
840 throw ConfigFileError(this, &elmMedium, N_("Required %s/@filePath attribute is missing"), elmMedium.getName());
841 }
842
843 if (med.strFormat.isEmpty()) // not set with 1.4 format above, or 1.4 Custom format?
844 if (!(elmMedium.getAttributeValue("format", med.strFormat)))
845 throw ConfigFileError(this, &elmMedium, N_("Required %s/@format attribute is missing"), elmMedium.getName());
846
847 if (!(elmMedium.getAttributeValue("autoReset", med.fAutoReset)))
848 med.fAutoReset = false;
849
850 Utf8Str strType;
851 if ((elmMedium.getAttributeValue("type", strType)))
852 {
853 // pre-1.4 used lower case, so make this case-insensitive
854 strType.toUpper();
855 if (strType == "NORMAL")
856 med.hdType = MediumType_Normal;
857 else if (strType == "IMMUTABLE")
858 med.hdType = MediumType_Immutable;
859 else if (strType == "WRITETHROUGH")
860 med.hdType = MediumType_Writethrough;
861 else
862 throw ConfigFileError(this, &elmMedium, N_("HardDisk/@type attribute must be one of Normal, Immutable or Writethrough"));
863 }
864 }
865 else if (m->sv < SettingsVersion_v1_4)
866 {
867 // DVD and floppy images before 1.4 had "src" attribute instead of "location"
868 if (!(elmMedium.getAttributeValue("src", med.strLocation)))
869 throw ConfigFileError(this, &elmMedium, N_("Required %s/@src attribute is missing"), elmMedium.getName());
870
871 fNeedsLocation = false;
872 }
873
874 if (fNeedsLocation)
875 // current files and 1.4 CustomHardDisk elements must have a location attribute
876 if (!(elmMedium.getAttributeValue("location", med.strLocation)))
877 throw ConfigFileError(this, &elmMedium, N_("Required %s/@location attribute is missing"), elmMedium.getName());
878
879 elmMedium.getAttributeValue("Description", med.strDescription); // optional
880
881 // recurse to handle children
882 xml::NodesLoop nl2(elmMedium);
883 const xml::ElementNode *pelmHDChild;
884 while ((pelmHDChild = nl2.forAllNodes()))
885 {
886 if ( t == HardDisk
887 && ( pelmHDChild->nameEquals("HardDisk")
888 || ( (m->sv < SettingsVersion_v1_4)
889 && (pelmHDChild->nameEquals("DiffHardDisk"))
890 )
891 )
892 )
893 // recurse with this element and push the child onto our current children list
894 readMedium(t,
895 *pelmHDChild,
896 med.llChildren);
897 else if (pelmHDChild->nameEquals("Property"))
898 {
899 Utf8Str strPropName, strPropValue;
900 if ( (pelmHDChild->getAttributeValue("name", strPropName))
901 && (pelmHDChild->getAttributeValue("value", strPropValue))
902 )
903 med.properties[strPropName] = strPropValue;
904 else
905 throw ConfigFileError(this, pelmHDChild, N_("Required HardDisk/Property/@name or @value attribute is missing"));
906 }
907 }
908
909 llMedia.push_back(med);
910}
911
912/**
913 * Reads in the entire <MediaRegistry> chunk. For pre-1.4 files, this gets called
914 * with the <DiskRegistry> chunk instead.
915 * @param elmMediaRegistry
916 */
917void MainConfigFile::readMediaRegistry(const xml::ElementNode &elmMediaRegistry)
918{
919 xml::NodesLoop nl1(elmMediaRegistry);
920 const xml::ElementNode *pelmChild1;
921 while ((pelmChild1 = nl1.forAllNodes()))
922 {
923 MediaType t = Error;
924 if (pelmChild1->nameEquals("HardDisks"))
925 t = HardDisk;
926 else if (pelmChild1->nameEquals("DVDImages"))
927 t = DVDImage;
928 else if (pelmChild1->nameEquals("FloppyImages"))
929 t = FloppyImage;
930 else
931 continue;
932
933 xml::NodesLoop nl2(*pelmChild1);
934 const xml::ElementNode *pelmMedium;
935 while ((pelmMedium = nl2.forAllNodes()))
936 {
937 if ( t == HardDisk
938 && (pelmMedium->nameEquals("HardDisk"))
939 )
940 readMedium(t,
941 *pelmMedium,
942 llHardDisks); // list to append hard disk data to: the root list
943 else if ( t == DVDImage
944 && (pelmMedium->nameEquals("Image"))
945 )
946 readMedium(t,
947 *pelmMedium,
948 llDvdImages); // list to append dvd images to: the root list
949 else if ( t == FloppyImage
950 && (pelmMedium->nameEquals("Image"))
951 )
952 readMedium(t,
953 *pelmMedium,
954 llFloppyImages); // list to append floppy images to: the root list
955 }
956 }
957}
958
959/**
960 * Reads in the <DHCPServers> chunk.
961 * @param elmDHCPServers
962 */
963void MainConfigFile::readDHCPServers(const xml::ElementNode &elmDHCPServers)
964{
965 xml::NodesLoop nl1(elmDHCPServers);
966 const xml::ElementNode *pelmServer;
967 while ((pelmServer = nl1.forAllNodes()))
968 {
969 if (pelmServer->nameEquals("DHCPServer"))
970 {
971 DHCPServer srv;
972 if ( (pelmServer->getAttributeValue("networkName", srv.strNetworkName))
973 && (pelmServer->getAttributeValue("IPAddress", srv.strIPAddress))
974 && (pelmServer->getAttributeValue("networkMask", srv.strIPNetworkMask))
975 && (pelmServer->getAttributeValue("lowerIP", srv.strIPLower))
976 && (pelmServer->getAttributeValue("upperIP", srv.strIPUpper))
977 && (pelmServer->getAttributeValue("enabled", srv.fEnabled))
978 )
979 llDhcpServers.push_back(srv);
980 else
981 throw ConfigFileError(this, pelmServer, N_("Required DHCPServer/@networkName, @IPAddress, @networkMask, @lowerIP, @upperIP or @enabled attribute is missing"));
982 }
983 }
984}
985
986/**
987 * Constructor.
988 *
989 * If pstrFilename is != NULL, this reads the given settings file into the member
990 * variables and various substructures and lists. Otherwise, the member variables
991 * are initialized with default values.
992 *
993 * Throws variants of xml::Error for I/O, XML and logical content errors, which
994 * the caller should catch; if this constructor does not throw, then the member
995 * variables contain meaningful values (either from the file or defaults).
996 *
997 * @param strFilename
998 */
999MainConfigFile::MainConfigFile(const Utf8Str *pstrFilename)
1000 : ConfigFileBase(pstrFilename)
1001{
1002 if (pstrFilename)
1003 {
1004 // the ConfigFileBase constructor has loaded the XML file, so now
1005 // we need only analyze what is in there
1006 xml::NodesLoop nlRootChildren(*m->pelmRoot);
1007 const xml::ElementNode *pelmRootChild;
1008 while ((pelmRootChild = nlRootChildren.forAllNodes()))
1009 {
1010 if (pelmRootChild->nameEquals("Global"))
1011 {
1012 xml::NodesLoop nlGlobalChildren(*pelmRootChild);
1013 const xml::ElementNode *pelmGlobalChild;
1014 while ((pelmGlobalChild = nlGlobalChildren.forAllNodes()))
1015 {
1016 if (pelmGlobalChild->nameEquals("SystemProperties"))
1017 {
1018 pelmGlobalChild->getAttributeValue("defaultMachineFolder", systemProperties.strDefaultMachineFolder);
1019 if (!pelmGlobalChild->getAttributeValue("defaultHardDiskFolder", systemProperties.strDefaultHardDiskFolder))
1020 // pre-1.4 used @defaultVDIFolder instead
1021 pelmGlobalChild->getAttributeValue("defaultVDIFolder", systemProperties.strDefaultHardDiskFolder);
1022 pelmGlobalChild->getAttributeValue("defaultHardDiskFormat", systemProperties.strDefaultHardDiskFormat);
1023 pelmGlobalChild->getAttributeValue("remoteDisplayAuthLibrary", systemProperties.strRemoteDisplayAuthLibrary);
1024 pelmGlobalChild->getAttributeValue("webServiceAuthLibrary", systemProperties.strWebServiceAuthLibrary);
1025 pelmGlobalChild->getAttributeValue("LogHistoryCount", systemProperties.ulLogHistoryCount);
1026 }
1027 else if (pelmGlobalChild->nameEquals("ExtraData"))
1028 readExtraData(*pelmGlobalChild, mapExtraDataItems);
1029 else if (pelmGlobalChild->nameEquals("MachineRegistry"))
1030 readMachineRegistry(*pelmGlobalChild);
1031 else if ( (pelmGlobalChild->nameEquals("MediaRegistry"))
1032 || ( (m->sv < SettingsVersion_v1_4)
1033 && (pelmGlobalChild->nameEquals("DiskRegistry"))
1034 )
1035 )
1036 readMediaRegistry(*pelmGlobalChild);
1037 else if (pelmGlobalChild->nameEquals("NetserviceRegistry"))
1038 {
1039 xml::NodesLoop nlLevel4(*pelmGlobalChild);
1040 const xml::ElementNode *pelmLevel4Child;
1041 while ((pelmLevel4Child = nlLevel4.forAllNodes()))
1042 {
1043 if (pelmLevel4Child->nameEquals("DHCPServers"))
1044 readDHCPServers(*pelmLevel4Child);
1045 }
1046 }
1047 else if (pelmGlobalChild->nameEquals("USBDeviceFilters"))
1048 readUSBDeviceFilters(*pelmGlobalChild, host.llUSBDeviceFilters);
1049 }
1050 } // end if (pelmRootChild->nameEquals("Global"))
1051 }
1052
1053 clearDocument();
1054 }
1055
1056 // DHCP servers were introduced with settings version 1.7; if we're loading
1057 // from an older version OR this is a fresh install, then add one DHCP server
1058 // with default settings
1059 if ( (!llDhcpServers.size())
1060 && ( (!pstrFilename) // empty VirtualBox.xml file
1061 || (m->sv < SettingsVersion_v1_7) // upgrading from before 1.7
1062 )
1063 )
1064 {
1065 DHCPServer srv;
1066 srv.strNetworkName =
1067#ifdef RT_OS_WINDOWS
1068 "HostInterfaceNetworking-VirtualBox Host-Only Ethernet Adapter";
1069#else
1070 "HostInterfaceNetworking-vboxnet0";
1071#endif
1072 srv.strIPAddress = "192.168.56.100";
1073 srv.strIPNetworkMask = "255.255.255.0";
1074 srv.strIPLower = "192.168.56.101";
1075 srv.strIPUpper = "192.168.56.254";
1076 srv.fEnabled = true;
1077 llDhcpServers.push_back(srv);
1078 }
1079}
1080
1081/**
1082 * Creates a single <HardDisk> element for the given Medium structure
1083 * and recurses to write the child hard disks underneath. Called from
1084 * MainConfigFile::write().
1085 *
1086 * @param elmMedium
1087 * @param m
1088 * @param level
1089 */
1090void MainConfigFile::writeHardDisk(xml::ElementNode &elmMedium,
1091 const Medium &mdm,
1092 uint32_t level) // 0 for "root" call, incremented with each recursion
1093{
1094 xml::ElementNode *pelmHardDisk = elmMedium.createChild("HardDisk");
1095 pelmHardDisk->setAttribute("uuid", makeString(mdm.uuid));
1096 pelmHardDisk->setAttribute("location", mdm.strLocation);
1097 pelmHardDisk->setAttribute("format", mdm.strFormat);
1098 if (mdm.fAutoReset)
1099 pelmHardDisk->setAttribute("autoReset", mdm.fAutoReset);
1100 if (mdm.strDescription.length())
1101 pelmHardDisk->setAttribute("Description", mdm.strDescription);
1102
1103 for (PropertiesMap::const_iterator it = mdm.properties.begin();
1104 it != mdm.properties.end();
1105 ++it)
1106 {
1107 xml::ElementNode *pelmProp = pelmHardDisk->createChild("Property");
1108 pelmProp->setAttribute("name", it->first);
1109 pelmProp->setAttribute("value", it->second);
1110 }
1111
1112 // only for base hard disks, save the type
1113 if (level == 0)
1114 {
1115 const char *pcszType =
1116 mdm.hdType == MediumType_Normal ? "Normal" :
1117 mdm.hdType == MediumType_Immutable ? "Immutable" :
1118 /*mdm.hdType == MediumType_Writethrough ?*/ "Writethrough";
1119 pelmHardDisk->setAttribute("type", pcszType);
1120 }
1121
1122 for (MediaList::const_iterator it = mdm.llChildren.begin();
1123 it != mdm.llChildren.end();
1124 ++it)
1125 {
1126 // recurse for children
1127 writeHardDisk(*pelmHardDisk, // parent
1128 *it, // settings::Medium
1129 ++level); // recursion level
1130 }
1131}
1132
1133/**
1134 * Called from the IVirtualBox interface to write out VirtualBox.xml. This
1135 * builds an XML DOM tree and writes it out to disk.
1136 */
1137void MainConfigFile::write(const com::Utf8Str strFilename)
1138{
1139 m->strFilename = strFilename;
1140 createStubDocument();
1141
1142 xml::ElementNode *pelmGlobal = m->pelmRoot->createChild("Global");
1143
1144 writeExtraData(*pelmGlobal, mapExtraDataItems);
1145
1146 xml::ElementNode *pelmMachineRegistry = pelmGlobal->createChild("MachineRegistry");
1147 for (MachinesRegistry::const_iterator it = llMachines.begin();
1148 it != llMachines.end();
1149 ++it)
1150 {
1151 // <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"/>
1152 const MachineRegistryEntry &mre = *it;
1153 xml::ElementNode *pelmMachineEntry = pelmMachineRegistry->createChild("MachineEntry");
1154 pelmMachineEntry->setAttribute("uuid", makeString(mre.uuid));
1155 pelmMachineEntry->setAttribute("src", mre.strSettingsFile);
1156 }
1157
1158 xml::ElementNode *pelmMediaRegistry = pelmGlobal->createChild("MediaRegistry");
1159
1160 xml::ElementNode *pelmHardDisks = pelmMediaRegistry->createChild("HardDisks");
1161 for (MediaList::const_iterator it = llHardDisks.begin();
1162 it != llHardDisks.end();
1163 ++it)
1164 {
1165 writeHardDisk(*pelmHardDisks, *it, 0);
1166 }
1167
1168 xml::ElementNode *pelmDVDImages = pelmMediaRegistry->createChild("DVDImages");
1169 for (MediaList::const_iterator it = llDvdImages.begin();
1170 it != llDvdImages.end();
1171 ++it)
1172 {
1173 const Medium &mdm = *it;
1174 xml::ElementNode *pelmMedium = pelmDVDImages->createChild("Image");
1175 pelmMedium->setAttribute("uuid", makeString(mdm.uuid));
1176 pelmMedium->setAttribute("location", mdm.strLocation);
1177 if (mdm.strDescription.length())
1178 pelmMedium->setAttribute("Description", mdm.strDescription);
1179 }
1180
1181 xml::ElementNode *pelmFloppyImages = pelmMediaRegistry->createChild("FloppyImages");
1182 for (MediaList::const_iterator it = llFloppyImages.begin();
1183 it != llFloppyImages.end();
1184 ++it)
1185 {
1186 const Medium &mdm = *it;
1187 xml::ElementNode *pelmMedium = pelmFloppyImages->createChild("Image");
1188 pelmMedium->setAttribute("uuid", makeString(mdm.uuid));
1189 pelmMedium->setAttribute("location", mdm.strLocation);
1190 if (mdm.strDescription.length())
1191 pelmMedium->setAttribute("Description", mdm.strDescription);
1192 }
1193
1194 xml::ElementNode *pelmNetserviceRegistry = pelmGlobal->createChild("NetserviceRegistry");
1195 xml::ElementNode *pelmDHCPServers = pelmNetserviceRegistry->createChild("DHCPServers");
1196 for (DHCPServersList::const_iterator it = llDhcpServers.begin();
1197 it != llDhcpServers.end();
1198 ++it)
1199 {
1200 const DHCPServer &d = *it;
1201 xml::ElementNode *pelmThis = pelmDHCPServers->createChild("DHCPServer");
1202 pelmThis->setAttribute("networkName", d.strNetworkName);
1203 pelmThis->setAttribute("IPAddress", d.strIPAddress);
1204 pelmThis->setAttribute("networkMask", d.strIPNetworkMask);
1205 pelmThis->setAttribute("lowerIP", d.strIPLower);
1206 pelmThis->setAttribute("upperIP", d.strIPUpper);
1207 pelmThis->setAttribute("enabled", (d.fEnabled) ? 1 : 0); // too bad we chose 1 vs. 0 here
1208 }
1209
1210 xml::ElementNode *pelmSysProps = pelmGlobal->createChild("SystemProperties");
1211 if (systemProperties.strDefaultMachineFolder.length())
1212 pelmSysProps->setAttribute("defaultMachineFolder", systemProperties.strDefaultMachineFolder);
1213 if (systemProperties.strDefaultHardDiskFolder.length())
1214 pelmSysProps->setAttribute("defaultHardDiskFolder", systemProperties.strDefaultHardDiskFolder);
1215 if (systemProperties.strDefaultHardDiskFormat.length())
1216 pelmSysProps->setAttribute("defaultHardDiskFormat", systemProperties.strDefaultHardDiskFormat);
1217 if (systemProperties.strRemoteDisplayAuthLibrary.length())
1218 pelmSysProps->setAttribute("remoteDisplayAuthLibrary", systemProperties.strRemoteDisplayAuthLibrary);
1219 if (systemProperties.strWebServiceAuthLibrary.length())
1220 pelmSysProps->setAttribute("webServiceAuthLibrary", systemProperties.strWebServiceAuthLibrary);
1221 pelmSysProps->setAttribute("LogHistoryCount", systemProperties.ulLogHistoryCount);
1222
1223 writeUSBDeviceFilters(*pelmGlobal->createChild("USBDeviceFilters"),
1224 host.llUSBDeviceFilters,
1225 true); // fHostMode
1226
1227 // now go write the XML
1228 xml::XmlFileWriter writer(*m->pDoc);
1229 writer.write(m->strFilename.c_str());
1230
1231 m->fFileExists = true;
1232
1233 clearDocument();
1234}
1235
1236// use a define for the platform-dependent default value of
1237// hwvirt exclusivity, since we'll need to check that value
1238// in bumpSettingsVersionIfNeeded()
1239#if defined(RT_OS_DARWIN) || defined(RT_OS_WINDOWS)
1240 #define HWVIRTEXCLUSIVEDEFAULT false
1241#else
1242 #define HWVIRTEXCLUSIVEDEFAULT true
1243#endif
1244
1245/**
1246 * Hardware struct constructor.
1247 */
1248Hardware::Hardware()
1249 : strVersion("1"),
1250 fHardwareVirt(true),
1251 fHardwareVirtExclusive(HWVIRTEXCLUSIVEDEFAULT),
1252 fNestedPaging(false),
1253 fVPID(true),
1254 fSyntheticCpu(false),
1255 fPAE(false),
1256 cCPUs(1),
1257 ulMemorySizeMB((uint32_t)-1),
1258 ulVRAMSizeMB(8),
1259 cMonitors(1),
1260 fAccelerate3D(false),
1261 fAccelerate2DVideo(false),
1262 firmwareType(FirmwareType_BIOS),
1263 clipboardMode(ClipboardMode_Bidirectional),
1264 ulMemoryBalloonSize(0),
1265 ulStatisticsUpdateInterval(0)
1266{
1267 mapBootOrder[0] = DeviceType_Floppy;
1268 mapBootOrder[1] = DeviceType_DVD;
1269 mapBootOrder[2] = DeviceType_HardDisk;
1270
1271 /* The default value for PAE depends on the host:
1272 * - 64 bits host -> always true
1273 * - 32 bits host -> true for Windows & Darwin (masked off if the host cpu doesn't support it anyway)
1274 */
1275#if HC_ARCH_BITS == 64 || defined(RT_OS_WINDOWS) || defined(RT_OS_DARWIN)
1276 fPAE = true;
1277#endif
1278}
1279
1280/**
1281 * Called from MachineConfigFile::readHardware() to cpuid information.
1282 * @param elmCpuid
1283 * @param ll
1284 */
1285void MachineConfigFile::readCpuIdTree(const xml::ElementNode &elmCpuid,
1286 CpuIdLeafsList &ll)
1287{
1288 xml::NodesLoop nl1(elmCpuid, "CpuIdLeaf");
1289 const xml::ElementNode *pelmCpuIdLeaf;
1290 while ((pelmCpuIdLeaf = nl1.forAllNodes()))
1291 {
1292 CpuIdLeaf leaf;
1293
1294 if (!pelmCpuIdLeaf->getAttributeValue("id", leaf.ulId))
1295 throw ConfigFileError(this, pelmCpuIdLeaf, N_("Required CpuId/@id attribute is missing"));
1296
1297 pelmCpuIdLeaf->getAttributeValue("eax", leaf.ulEax);
1298 pelmCpuIdLeaf->getAttributeValue("ebx", leaf.ulEbx);
1299 pelmCpuIdLeaf->getAttributeValue("ecx", leaf.ulEcx);
1300 pelmCpuIdLeaf->getAttributeValue("edx", leaf.ulEdx);
1301
1302 ll.push_back(leaf);
1303 }
1304}
1305
1306/**
1307 * Called from MachineConfigFile::readHardware() to network information.
1308 * @param elmNetwork
1309 * @param ll
1310 */
1311void MachineConfigFile::readNetworkAdapters(const xml::ElementNode &elmNetwork,
1312 NetworkAdaptersList &ll)
1313{
1314 xml::NodesLoop nl1(elmNetwork, "Adapter");
1315 const xml::ElementNode *pelmAdapter;
1316 while ((pelmAdapter = nl1.forAllNodes()))
1317 {
1318 NetworkAdapter nic;
1319
1320 if (!pelmAdapter->getAttributeValue("slot", nic.ulSlot))
1321 throw ConfigFileError(this, pelmAdapter, N_("Required Adapter/@slot attribute is missing"));
1322
1323 Utf8Str strTemp;
1324 if (pelmAdapter->getAttributeValue("type", strTemp))
1325 {
1326 if (strTemp == "Am79C970A")
1327 nic.type = NetworkAdapterType_Am79C970A;
1328 else if (strTemp == "Am79C973")
1329 nic.type = NetworkAdapterType_Am79C973;
1330 else if (strTemp == "82540EM")
1331 nic.type = NetworkAdapterType_I82540EM;
1332 else if (strTemp == "82543GC")
1333 nic.type = NetworkAdapterType_I82543GC;
1334 else if (strTemp == "82545EM")
1335 nic.type = NetworkAdapterType_I82545EM;
1336 else if (strTemp == "virtio")
1337 nic.type = NetworkAdapterType_Virtio;
1338 else
1339 throw ConfigFileError(this, pelmAdapter, N_("Invalid value '%s' in Adapter/@type attribute"), strTemp.c_str());
1340 }
1341
1342 pelmAdapter->getAttributeValue("enabled", nic.fEnabled);
1343 pelmAdapter->getAttributeValue("MACAddress", nic.strMACAddress);
1344 pelmAdapter->getAttributeValue("cable", nic.fCableConnected);
1345 pelmAdapter->getAttributeValue("speed", nic.ulLineSpeed);
1346 pelmAdapter->getAttributeValue("trace", nic.fTraceEnabled);
1347 pelmAdapter->getAttributeValue("tracefile", nic.strTraceFile);
1348
1349 const xml::ElementNode *pelmAdapterChild;
1350 if ((pelmAdapterChild = pelmAdapter->findChildElement("NAT")))
1351 {
1352 nic.mode = NetworkAttachmentType_NAT;
1353 pelmAdapterChild->getAttributeValue("name", nic.strName); // optional network name
1354 }
1355 else if ( ((pelmAdapterChild = pelmAdapter->findChildElement("HostInterface")))
1356 || ((pelmAdapterChild = pelmAdapter->findChildElement("BridgedInterface")))
1357 )
1358 {
1359 nic.mode = NetworkAttachmentType_Bridged;
1360 pelmAdapterChild->getAttributeValue("name", nic.strName); // optional host interface name
1361 }
1362 else if ((pelmAdapterChild = pelmAdapter->findChildElement("InternalNetwork")))
1363 {
1364 nic.mode = NetworkAttachmentType_Internal;
1365 if (!pelmAdapterChild->getAttributeValue("name", nic.strName)) // required network name
1366 throw ConfigFileError(this, pelmAdapterChild, N_("Required InternalNetwork/@name element is missing"));
1367 }
1368 else if ((pelmAdapterChild = pelmAdapter->findChildElement("HostOnlyInterface")))
1369 {
1370 nic.mode = NetworkAttachmentType_HostOnly;
1371 if (!pelmAdapterChild->getAttributeValue("name", nic.strName)) // required network name
1372 throw ConfigFileError(this, pelmAdapterChild, N_("Required HostOnlyInterface/@name element is missing"));
1373 }
1374 // else: default is NetworkAttachmentType_Null
1375
1376 ll.push_back(nic);
1377 }
1378}
1379
1380/**
1381 * Called from MachineConfigFile::readHardware() to read serial port information.
1382 * @param elmUART
1383 * @param ll
1384 */
1385void MachineConfigFile::readSerialPorts(const xml::ElementNode &elmUART,
1386 SerialPortsList &ll)
1387{
1388 xml::NodesLoop nl1(elmUART, "Port");
1389 const xml::ElementNode *pelmPort;
1390 while ((pelmPort = nl1.forAllNodes()))
1391 {
1392 SerialPort port;
1393 if (!pelmPort->getAttributeValue("slot", port.ulSlot))
1394 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@slot attribute is missing"));
1395
1396 // slot must be unique
1397 for (SerialPortsList::const_iterator it = ll.begin();
1398 it != ll.end();
1399 ++it)
1400 if ((*it).ulSlot == port.ulSlot)
1401 throw ConfigFileError(this, pelmPort, N_("Invalid value %RU32 in UART/Port/@slot attribute: value is not unique"), port.ulSlot);
1402
1403 if (!pelmPort->getAttributeValue("enabled", port.fEnabled))
1404 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@enabled attribute is missing"));
1405 if (!pelmPort->getAttributeValue("IOBase", port.ulIOBase))
1406 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@IOBase attribute is missing"));
1407 if (!pelmPort->getAttributeValue("IRQ", port.ulIRQ))
1408 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@IRQ attribute is missing"));
1409
1410 Utf8Str strPortMode;
1411 if (!pelmPort->getAttributeValue("hostMode", strPortMode))
1412 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@hostMode attribute is missing"));
1413 if (strPortMode == "RawFile")
1414 port.portMode = PortMode_RawFile;
1415 else if (strPortMode == "HostPipe")
1416 port.portMode = PortMode_HostPipe;
1417 else if (strPortMode == "HostDevice")
1418 port.portMode = PortMode_HostDevice;
1419 else if (strPortMode == "Disconnected")
1420 port.portMode = PortMode_Disconnected;
1421 else
1422 throw ConfigFileError(this, pelmPort, N_("Invalid value '%s' in UART/Port/@hostMode attribute"), strPortMode.c_str());
1423
1424 pelmPort->getAttributeValue("path", port.strPath);
1425 pelmPort->getAttributeValue("server", port.fServer);
1426
1427 ll.push_back(port);
1428 }
1429}
1430
1431/**
1432 * Called from MachineConfigFile::readHardware() to read parallel port information.
1433 * @param elmLPT
1434 * @param ll
1435 */
1436void MachineConfigFile::readParallelPorts(const xml::ElementNode &elmLPT,
1437 ParallelPortsList &ll)
1438{
1439 xml::NodesLoop nl1(elmLPT, "Port");
1440 const xml::ElementNode *pelmPort;
1441 while ((pelmPort = nl1.forAllNodes()))
1442 {
1443 ParallelPort port;
1444 if (!pelmPort->getAttributeValue("slot", port.ulSlot))
1445 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@slot attribute is missing"));
1446
1447 // slot must be unique
1448 for (ParallelPortsList::const_iterator it = ll.begin();
1449 it != ll.end();
1450 ++it)
1451 if ((*it).ulSlot == port.ulSlot)
1452 throw ConfigFileError(this, pelmPort, N_("Invalid value %RU32 in LPT/Port/@slot attribute: value is not unique"), port.ulSlot);
1453
1454 if (!pelmPort->getAttributeValue("enabled", port.fEnabled))
1455 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@enabled attribute is missing"));
1456 if (!pelmPort->getAttributeValue("IOBase", port.ulIOBase))
1457 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@IOBase attribute is missing"));
1458 if (!pelmPort->getAttributeValue("IRQ", port.ulIRQ))
1459 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@IRQ attribute is missing"));
1460
1461 pelmPort->getAttributeValue("path", port.strPath);
1462
1463 ll.push_back(port);
1464 }
1465}
1466
1467/**
1468 * Called from MachineConfigFile::readHardware() to read guest property information.
1469 * @param elmGuestProperties
1470 * @param hw
1471 */
1472void MachineConfigFile::readGuestProperties(const xml::ElementNode &elmGuestProperties,
1473 Hardware &hw)
1474{
1475 xml::NodesLoop nl1(elmGuestProperties, "GuestProperty");
1476 const xml::ElementNode *pelmProp;
1477 while ((pelmProp = nl1.forAllNodes()))
1478 {
1479 GuestProperty prop;
1480 pelmProp->getAttributeValue("name", prop.strName);
1481 pelmProp->getAttributeValue("value", prop.strValue);
1482
1483 pelmProp->getAttributeValue("timestamp", prop.timestamp);
1484 pelmProp->getAttributeValue("flags", prop.strFlags);
1485 hw.llGuestProperties.push_back(prop);
1486 }
1487
1488 elmGuestProperties.getAttributeValue("notificationPatterns", hw.strNotificationPatterns);
1489}
1490
1491/**
1492 * Helper function to read attributes that are common to <SATAController> (pre-1.7)
1493 * and <StorageController>.
1494 * @param elmStorageController
1495 * @param strg
1496 */
1497void MachineConfigFile::readStorageControllerAttributes(const xml::ElementNode &elmStorageController,
1498 StorageController &sctl)
1499{
1500 elmStorageController.getAttributeValue("PortCount", sctl.ulPortCount);
1501 elmStorageController.getAttributeValue("IDE0MasterEmulationPort", sctl.lIDE0MasterEmulationPort);
1502 elmStorageController.getAttributeValue("IDE0SlaveEmulationPort", sctl.lIDE0SlaveEmulationPort);
1503 elmStorageController.getAttributeValue("IDE1MasterEmulationPort", sctl.lIDE1MasterEmulationPort);
1504 elmStorageController.getAttributeValue("IDE1SlaveEmulationPort", sctl.lIDE1SlaveEmulationPort);
1505}
1506
1507/**
1508 * Reads in a <Hardware> block and stores it in the given structure. Used
1509 * both directly from readMachine and from readSnapshot, since snapshots
1510 * have their own hardware sections.
1511 *
1512 * For legacy pre-1.7 settings we also need a storage structure because
1513 * the IDE and SATA controllers used to be defined under <Hardware>.
1514 *
1515 * @param elmHardware
1516 * @param hw
1517 */
1518void MachineConfigFile::readHardware(const xml::ElementNode &elmHardware,
1519 Hardware &hw,
1520 Storage &strg)
1521{
1522 if (!elmHardware.getAttributeValue("version", hw.strVersion))
1523 {
1524 /* KLUDGE ALERT! For a while during the 3.1 development this was not
1525 written because it was thought to have a default value of "2". For
1526 sv <= 1.3 it defaults to "1" because the attribute didn't exist,
1527 while for 1.4+ it is sort of mandatory. Now, the buggy XML writer
1528 code only wrote 1.7 and later. So, if it's a 1.7+ XML file and it's
1529 missing the hardware version, then it probably should be "2" instead
1530 of "1". */
1531 if (m->sv < SettingsVersion_v1_7)
1532 hw.strVersion = "1";
1533 else
1534 hw.strVersion = "2";
1535 }
1536 Utf8Str strUUID;
1537 if (elmHardware.getAttributeValue("uuid", strUUID))
1538 parseUUID(hw.uuid, strUUID);
1539
1540 xml::NodesLoop nl1(elmHardware);
1541 const xml::ElementNode *pelmHwChild;
1542 while ((pelmHwChild = nl1.forAllNodes()))
1543 {
1544 if (pelmHwChild->nameEquals("CPU"))
1545 {
1546 if (!pelmHwChild->getAttributeValue("count", hw.cCPUs))
1547 {
1548 // pre-1.5 variant; not sure if this actually exists in the wild anywhere
1549 const xml::ElementNode *pelmCPUChild;
1550 if ((pelmCPUChild = pelmHwChild->findChildElement("CPUCount")))
1551 pelmCPUChild->getAttributeValue("count", hw.cCPUs);
1552 }
1553
1554 const xml::ElementNode *pelmCPUChild;
1555 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtEx")))
1556 {
1557 pelmCPUChild->getAttributeValue("enabled", hw.fHardwareVirt);
1558 pelmCPUChild->getAttributeValue("exclusive", hw.fHardwareVirtExclusive); // settings version 1.9
1559 }
1560 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExNestedPaging")))
1561 pelmCPUChild->getAttributeValue("enabled", hw.fNestedPaging);
1562 if ((pelmCPUChild = pelmHwChild->findChildElement("HardwareVirtExVPID")))
1563 pelmCPUChild->getAttributeValue("enabled", hw.fVPID);
1564
1565 if (!(pelmCPUChild = pelmHwChild->findChildElement("PAE")))
1566 {
1567 /* The default for pre 3.1 was false, so we must respect that. */
1568 if (m->sv < SettingsVersion_v1_9)
1569 hw.fPAE = false;
1570 }
1571 else
1572 pelmCPUChild->getAttributeValue("enabled", hw.fPAE);
1573
1574 if ((pelmCPUChild = pelmHwChild->findChildElement("SyntheticCpu")))
1575 pelmCPUChild->getAttributeValue("enabled", hw.fSyntheticCpu);
1576 if ((pelmCPUChild = pelmHwChild->findChildElement("CpuIdTree")))
1577 readCpuIdTree(*pelmCPUChild, hw.llCpuIdLeafs);
1578 }
1579 else if (pelmHwChild->nameEquals("Memory"))
1580 pelmHwChild->getAttributeValue("RAMSize", hw.ulMemorySizeMB);
1581 else if (pelmHwChild->nameEquals("Firmware"))
1582 {
1583 Utf8Str strFirmwareType;
1584 if (pelmHwChild->getAttributeValue("type", strFirmwareType))
1585 {
1586 if ( (strFirmwareType == "BIOS")
1587 || (strFirmwareType == "1") // some trunk builds used the number here
1588 )
1589 hw.firmwareType = FirmwareType_BIOS;
1590 else if ( (strFirmwareType == "EFI")
1591 || (strFirmwareType == "2") // some trunk builds used the number here
1592 )
1593 hw.firmwareType = FirmwareType_EFI;
1594 else if ( strFirmwareType == "EFI32")
1595 hw.firmwareType = FirmwareType_EFI32;
1596 else if ( strFirmwareType == "EFI64")
1597 hw.firmwareType = FirmwareType_EFI64;
1598 else if ( strFirmwareType == "EFIDUAL")
1599 hw.firmwareType = FirmwareType_EFIDUAL;
1600 else
1601 throw ConfigFileError(this,
1602 pelmHwChild,
1603 N_("Invalid value '%s' in Boot/Firmware/@type"),
1604 strFirmwareType.c_str());
1605 }
1606 }
1607 else if (pelmHwChild->nameEquals("Boot"))
1608 {
1609 hw.mapBootOrder.clear();
1610
1611 xml::NodesLoop nl2(*pelmHwChild, "Order");
1612 const xml::ElementNode *pelmOrder;
1613 while ((pelmOrder = nl2.forAllNodes()))
1614 {
1615 uint32_t ulPos;
1616 Utf8Str strDevice;
1617 if (!pelmOrder->getAttributeValue("position", ulPos))
1618 throw ConfigFileError(this, pelmOrder, N_("Required Boot/Order/@position attribute is missing"));
1619
1620 if ( ulPos < 1
1621 || ulPos > SchemaDefs::MaxBootPosition
1622 )
1623 throw ConfigFileError(this,
1624 pelmOrder,
1625 N_("Invalid value '%RU32' in Boot/Order/@position: must be greater than 0 and less than %RU32"),
1626 ulPos,
1627 SchemaDefs::MaxBootPosition + 1);
1628 // XML is 1-based but internal data is 0-based
1629 --ulPos;
1630
1631 if (hw.mapBootOrder.find(ulPos) != hw.mapBootOrder.end())
1632 throw ConfigFileError(this, pelmOrder, N_("Invalid value '%RU32' in Boot/Order/@position: value is not unique"), ulPos);
1633
1634 if (!pelmOrder->getAttributeValue("device", strDevice))
1635 throw ConfigFileError(this, pelmOrder, N_("Required Boot/Order/@device attribute is missing"));
1636
1637 DeviceType_T type;
1638 if (strDevice == "None")
1639 type = DeviceType_Null;
1640 else if (strDevice == "Floppy")
1641 type = DeviceType_Floppy;
1642 else if (strDevice == "DVD")
1643 type = DeviceType_DVD;
1644 else if (strDevice == "HardDisk")
1645 type = DeviceType_HardDisk;
1646 else if (strDevice == "Network")
1647 type = DeviceType_Network;
1648 else
1649 throw ConfigFileError(this, pelmOrder, N_("Invalid value '%s' in Boot/Order/@device attribute"), strDevice.c_str());
1650 hw.mapBootOrder[ulPos] = type;
1651 }
1652 }
1653 else if (pelmHwChild->nameEquals("Display"))
1654 {
1655 pelmHwChild->getAttributeValue("VRAMSize", hw.ulVRAMSizeMB);
1656 if (!pelmHwChild->getAttributeValue("monitorCount", hw.cMonitors))
1657 pelmHwChild->getAttributeValue("MonitorCount", hw.cMonitors); // pre-v1.5 variant
1658 if (!pelmHwChild->getAttributeValue("accelerate3D", hw.fAccelerate3D))
1659 pelmHwChild->getAttributeValue("Accelerate3D", hw.fAccelerate3D); // pre-v1.5 variant
1660 pelmHwChild->getAttributeValue("accelerate2DVideo", hw.fAccelerate2DVideo);
1661 }
1662 else if (pelmHwChild->nameEquals("RemoteDisplay"))
1663 {
1664 pelmHwChild->getAttributeValue("enabled", hw.vrdpSettings.fEnabled);
1665 pelmHwChild->getAttributeValue("port", hw.vrdpSettings.strPort);
1666 pelmHwChild->getAttributeValue("netAddress", hw.vrdpSettings.strNetAddress);
1667
1668 Utf8Str strAuthType;
1669 if (pelmHwChild->getAttributeValue("authType", strAuthType))
1670 {
1671 // settings before 1.3 used lower case so make sure this is case-insensitive
1672 strAuthType.toUpper();
1673 if (strAuthType == "NULL")
1674 hw.vrdpSettings.authType = VRDPAuthType_Null;
1675 else if (strAuthType == "GUEST")
1676 hw.vrdpSettings.authType = VRDPAuthType_Guest;
1677 else if (strAuthType == "EXTERNAL")
1678 hw.vrdpSettings.authType = VRDPAuthType_External;
1679 else
1680 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in RemoteDisplay/@authType attribute"), strAuthType.c_str());
1681 }
1682
1683 pelmHwChild->getAttributeValue("authTimeout", hw.vrdpSettings.ulAuthTimeout);
1684 pelmHwChild->getAttributeValue("allowMultiConnection", hw.vrdpSettings.fAllowMultiConnection);
1685 pelmHwChild->getAttributeValue("reuseSingleConnection", hw.vrdpSettings.fReuseSingleConnection);
1686 }
1687 else if (pelmHwChild->nameEquals("BIOS"))
1688 {
1689 const xml::ElementNode *pelmBIOSChild;
1690 if ((pelmBIOSChild = pelmHwChild->findChildElement("ACPI")))
1691 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fACPIEnabled);
1692 if ((pelmBIOSChild = pelmHwChild->findChildElement("IOAPIC")))
1693 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fIOAPICEnabled);
1694 if ((pelmBIOSChild = pelmHwChild->findChildElement("Logo")))
1695 {
1696 pelmBIOSChild->getAttributeValue("fadeIn", hw.biosSettings.fLogoFadeIn);
1697 pelmBIOSChild->getAttributeValue("fadeOut", hw.biosSettings.fLogoFadeOut);
1698 pelmBIOSChild->getAttributeValue("displayTime", hw.biosSettings.ulLogoDisplayTime);
1699 pelmBIOSChild->getAttributeValue("imagePath", hw.biosSettings.strLogoImagePath);
1700 }
1701 if ((pelmBIOSChild = pelmHwChild->findChildElement("BootMenu")))
1702 {
1703 Utf8Str strBootMenuMode;
1704 if (pelmBIOSChild->getAttributeValue("mode", strBootMenuMode))
1705 {
1706 // settings before 1.3 used lower case so make sure this is case-insensitive
1707 strBootMenuMode.toUpper();
1708 if (strBootMenuMode == "DISABLED")
1709 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_Disabled;
1710 else if (strBootMenuMode == "MENUONLY")
1711 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_MenuOnly;
1712 else if (strBootMenuMode == "MESSAGEANDMENU")
1713 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_MessageAndMenu;
1714 else
1715 throw ConfigFileError(this, pelmBIOSChild, N_("Invalid value '%s' in BootMenu/@mode attribute"), strBootMenuMode.c_str());
1716 }
1717 }
1718 if ((pelmBIOSChild = pelmHwChild->findChildElement("PXEDebug")))
1719 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fPXEDebugEnabled);
1720 if ((pelmBIOSChild = pelmHwChild->findChildElement("TimeOffset")))
1721 pelmBIOSChild->getAttributeValue("value", hw.biosSettings.llTimeOffset);
1722
1723 // legacy BIOS/IDEController (pre 1.7)
1724 if ( (m->sv < SettingsVersion_v1_7)
1725 && ((pelmBIOSChild = pelmHwChild->findChildElement("IDEController")))
1726 )
1727 {
1728 StorageController sctl;
1729 sctl.strName = "IDE Controller";
1730 sctl.storageBus = StorageBus_IDE;
1731
1732 Utf8Str strType;
1733 if (pelmBIOSChild->getAttributeValue("type", strType))
1734 {
1735 if (strType == "PIIX3")
1736 sctl.controllerType = StorageControllerType_PIIX3;
1737 else if (strType == "PIIX4")
1738 sctl.controllerType = StorageControllerType_PIIX4;
1739 else if (strType == "ICH6")
1740 sctl.controllerType = StorageControllerType_ICH6;
1741 else
1742 throw ConfigFileError(this, pelmBIOSChild, N_("Invalid value '%s' for IDEController/@type attribute"), strType.c_str());
1743 }
1744 sctl.ulPortCount = 2;
1745 strg.llStorageControllers.push_back(sctl);
1746 }
1747 }
1748 else if (pelmHwChild->nameEquals("USBController"))
1749 {
1750 pelmHwChild->getAttributeValue("enabled", hw.usbController.fEnabled);
1751 pelmHwChild->getAttributeValue("enabledEhci", hw.usbController.fEnabledEHCI);
1752
1753 readUSBDeviceFilters(*pelmHwChild,
1754 hw.usbController.llDeviceFilters);
1755 }
1756 else if ( (m->sv < SettingsVersion_v1_7)
1757 && (pelmHwChild->nameEquals("SATAController"))
1758 )
1759 {
1760 bool f;
1761 if ( (pelmHwChild->getAttributeValue("enabled", f))
1762 && (f)
1763 )
1764 {
1765 StorageController sctl;
1766 sctl.strName = "SATA Controller";
1767 sctl.storageBus = StorageBus_SATA;
1768 sctl.controllerType = StorageControllerType_IntelAhci;
1769
1770 readStorageControllerAttributes(*pelmHwChild, sctl);
1771
1772 strg.llStorageControllers.push_back(sctl);
1773 }
1774 }
1775 else if (pelmHwChild->nameEquals("Network"))
1776 readNetworkAdapters(*pelmHwChild, hw.llNetworkAdapters);
1777 else if ( (pelmHwChild->nameEquals("UART"))
1778 || (pelmHwChild->nameEquals("Uart")) // used before 1.3
1779 )
1780 readSerialPorts(*pelmHwChild, hw.llSerialPorts);
1781 else if ( (pelmHwChild->nameEquals("LPT"))
1782 || (pelmHwChild->nameEquals("Lpt")) // used before 1.3
1783 )
1784 readParallelPorts(*pelmHwChild, hw.llParallelPorts);
1785 else if (pelmHwChild->nameEquals("AudioAdapter"))
1786 {
1787 pelmHwChild->getAttributeValue("enabled", hw.audioAdapter.fEnabled);
1788
1789 Utf8Str strTemp;
1790 if (pelmHwChild->getAttributeValue("controller", strTemp))
1791 {
1792 if (strTemp == "SB16")
1793 hw.audioAdapter.controllerType = AudioControllerType_SB16;
1794 else if (strTemp == "AC97")
1795 hw.audioAdapter.controllerType = AudioControllerType_AC97;
1796 else
1797 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in AudioAdapter/@controller attribute"), strTemp.c_str());
1798 }
1799 if (pelmHwChild->getAttributeValue("driver", strTemp))
1800 {
1801 // settings before 1.3 used lower case so make sure this is case-insensitive
1802 strTemp.toUpper();
1803 if (strTemp == "NULL")
1804 hw.audioAdapter.driverType = AudioDriverType_Null;
1805 else if (strTemp == "WINMM")
1806 hw.audioAdapter.driverType = AudioDriverType_WinMM;
1807 else if ( (strTemp == "DIRECTSOUND") || (strTemp == "DSOUND") )
1808 hw.audioAdapter.driverType = AudioDriverType_DirectSound;
1809 else if (strTemp == "SOLAUDIO")
1810 hw.audioAdapter.driverType = AudioDriverType_SolAudio;
1811 else if (strTemp == "ALSA")
1812 hw.audioAdapter.driverType = AudioDriverType_ALSA;
1813 else if (strTemp == "PULSE")
1814 hw.audioAdapter.driverType = AudioDriverType_Pulse;
1815 else if (strTemp == "OSS")
1816 hw.audioAdapter.driverType = AudioDriverType_OSS;
1817 else if (strTemp == "COREAUDIO")
1818 hw.audioAdapter.driverType = AudioDriverType_CoreAudio;
1819 else if (strTemp == "MMPM")
1820 hw.audioAdapter.driverType = AudioDriverType_MMPM;
1821 else
1822 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in AudioAdapter/@driver attribute"), strTemp.c_str());
1823 }
1824 }
1825 else if (pelmHwChild->nameEquals("SharedFolders"))
1826 {
1827 xml::NodesLoop nl2(*pelmHwChild, "SharedFolder");
1828 const xml::ElementNode *pelmFolder;
1829 while ((pelmFolder = nl2.forAllNodes()))
1830 {
1831 SharedFolder sf;
1832 pelmFolder->getAttributeValue("name", sf.strName);
1833 pelmFolder->getAttributeValue("hostPath", sf.strHostPath);
1834 pelmFolder->getAttributeValue("writable", sf.fWritable);
1835 hw.llSharedFolders.push_back(sf);
1836 }
1837 }
1838 else if (pelmHwChild->nameEquals("Clipboard"))
1839 {
1840 Utf8Str strTemp;
1841 if (pelmHwChild->getAttributeValue("mode", strTemp))
1842 {
1843 if (strTemp == "Disabled")
1844 hw.clipboardMode = ClipboardMode_Disabled;
1845 else if (strTemp == "HostToGuest")
1846 hw.clipboardMode = ClipboardMode_HostToGuest;
1847 else if (strTemp == "GuestToHost")
1848 hw.clipboardMode = ClipboardMode_GuestToHost;
1849 else if (strTemp == "Bidirectional")
1850 hw.clipboardMode = ClipboardMode_Bidirectional;
1851 else
1852 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in Clipbord/@mode attribute"), strTemp.c_str());
1853 }
1854 }
1855 else if (pelmHwChild->nameEquals("Guest"))
1856 {
1857 if (!pelmHwChild->getAttributeValue("memoryBalloonSize", hw.ulMemoryBalloonSize))
1858 pelmHwChild->getAttributeValue("MemoryBalloonSize", hw.ulMemoryBalloonSize); // used before 1.3
1859 if (!pelmHwChild->getAttributeValue("statisticsUpdateInterval", hw.ulStatisticsUpdateInterval))
1860 pelmHwChild->getAttributeValue("StatisticsUpdateInterval", hw.ulStatisticsUpdateInterval);
1861 }
1862 else if (pelmHwChild->nameEquals("GuestProperties"))
1863 readGuestProperties(*pelmHwChild, hw);
1864 }
1865
1866 if (hw.ulMemorySizeMB == (uint32_t)-1)
1867 throw ConfigFileError(this, &elmHardware, N_("Required Memory/@RAMSize element/attribute is missing"));
1868}
1869
1870/**
1871 * This gets called instead of readStorageControllers() for legacy pre-1.7 settings
1872 * files which have a <HardDiskAttachments> node and storage controller settings
1873 * hidden in the <Hardware> settings. We set the StorageControllers fields just the
1874 * same, just from different sources.
1875 * @param elmHardware <Hardware> XML node.
1876 * @param elmHardDiskAttachments <HardDiskAttachments> XML node.
1877 * @param strg
1878 */
1879void MachineConfigFile::readHardDiskAttachments_pre1_7(const xml::ElementNode &elmHardDiskAttachments,
1880 Storage &strg)
1881{
1882 StorageController *pIDEController = NULL;
1883 StorageController *pSATAController = NULL;
1884
1885 for (StorageControllersList::iterator it = strg.llStorageControllers.begin();
1886 it != strg.llStorageControllers.end();
1887 ++it)
1888 {
1889 StorageController &s = *it;
1890 if (s.storageBus == StorageBus_IDE)
1891 pIDEController = &s;
1892 else if (s.storageBus == StorageBus_SATA)
1893 pSATAController = &s;
1894 }
1895
1896 xml::NodesLoop nl1(elmHardDiskAttachments, "HardDiskAttachment");
1897 const xml::ElementNode *pelmAttachment;
1898 while ((pelmAttachment = nl1.forAllNodes()))
1899 {
1900 AttachedDevice att;
1901 Utf8Str strUUID, strBus;
1902
1903 if (!pelmAttachment->getAttributeValue("hardDisk", strUUID))
1904 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@hardDisk attribute is missing"));
1905 parseUUID(att.uuid, strUUID);
1906
1907 if (!pelmAttachment->getAttributeValue("bus", strBus))
1908 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@bus attribute is missing"));
1909 // pre-1.7 'channel' is now port
1910 if (!pelmAttachment->getAttributeValue("channel", att.lPort))
1911 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@channel attribute is missing"));
1912 // pre-1.7 'device' is still device
1913 if (!pelmAttachment->getAttributeValue("device", att.lDevice))
1914 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@device attribute is missing"));
1915
1916 att.deviceType = DeviceType_HardDisk;
1917
1918 if (strBus == "IDE")
1919 {
1920 if (!pIDEController)
1921 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus is 'IDE' but cannot find IDE controller"));
1922 pIDEController->llAttachedDevices.push_back(att);
1923 }
1924 else if (strBus == "SATA")
1925 {
1926 if (!pSATAController)
1927 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus is 'SATA' but cannot find SATA controller"));
1928 pSATAController->llAttachedDevices.push_back(att);
1929 }
1930 else
1931 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus attribute has illegal value '%s'"), strBus.c_str());
1932 }
1933}
1934
1935/**
1936 * Reads in a <StorageControllers> block and stores it in the given Storage structure.
1937 * Used both directly from readMachine and from readSnapshot, since snapshots
1938 * have their own storage controllers sections.
1939 *
1940 * This is only called for settings version 1.7 and above; see readHardDiskAttachments_pre1_7()
1941 * for earlier versions.
1942 *
1943 * @param elmStorageControllers
1944 */
1945void MachineConfigFile::readStorageControllers(const xml::ElementNode &elmStorageControllers,
1946 Storage &strg)
1947{
1948 xml::NodesLoop nlStorageControllers(elmStorageControllers, "StorageController");
1949 const xml::ElementNode *pelmController;
1950 while ((pelmController = nlStorageControllers.forAllNodes()))
1951 {
1952 StorageController sctl;
1953
1954 if (!pelmController->getAttributeValue("name", sctl.strName))
1955 throw ConfigFileError(this, pelmController, N_("Required StorageController/@name attribute is missing"));
1956 // canonicalize storage controller names for configs in the switchover
1957 // period.
1958 if (m->sv <= SettingsVersion_v1_9)
1959 {
1960 if (sctl.strName == "IDE")
1961 sctl.strName = "IDE Controller";
1962 else if (sctl.strName == "SATA")
1963 sctl.strName = "SATA Controller";
1964 else if (sctl.strName == "SCSI")
1965 sctl.strName = "SCSI Controller";
1966 }
1967
1968 pelmController->getAttributeValue("Instance", sctl.ulInstance);
1969 // default from constructor is 0
1970
1971 Utf8Str strType;
1972 if (!pelmController->getAttributeValue("type", strType))
1973 throw ConfigFileError(this, pelmController, N_("Required StorageController/@type attribute is missing"));
1974
1975 if (strType == "AHCI")
1976 {
1977 sctl.storageBus = StorageBus_SATA;
1978 sctl.controllerType = StorageControllerType_IntelAhci;
1979 }
1980 else if (strType == "LsiLogic")
1981 {
1982 sctl.storageBus = StorageBus_SCSI;
1983 sctl.controllerType = StorageControllerType_LsiLogic;
1984 }
1985 else if (strType == "BusLogic")
1986 {
1987 sctl.storageBus = StorageBus_SCSI;
1988 sctl.controllerType = StorageControllerType_BusLogic;
1989 }
1990 else if (strType == "PIIX3")
1991 {
1992 sctl.storageBus = StorageBus_IDE;
1993 sctl.controllerType = StorageControllerType_PIIX3;
1994 }
1995 else if (strType == "PIIX4")
1996 {
1997 sctl.storageBus = StorageBus_IDE;
1998 sctl.controllerType = StorageControllerType_PIIX4;
1999 }
2000 else if (strType == "ICH6")
2001 {
2002 sctl.storageBus = StorageBus_IDE;
2003 sctl.controllerType = StorageControllerType_ICH6;
2004 }
2005 else if ( (m->sv >= SettingsVersion_v1_9)
2006 && (strType == "I82078")
2007 )
2008 {
2009 sctl.storageBus = StorageBus_Floppy;
2010 sctl.controllerType = StorageControllerType_I82078;
2011 }
2012 else if (strType == "LsiLogicSas")
2013 {
2014 sctl.storageBus = StorageBus_SAS;
2015 sctl.controllerType = StorageControllerType_LsiLogicSas;
2016 }
2017 else
2018 throw ConfigFileError(this, pelmController, N_("Invalid value '%s' for StorageController/@type attribute"), strType.c_str());
2019
2020 readStorageControllerAttributes(*pelmController, sctl);
2021
2022 xml::NodesLoop nlAttached(*pelmController, "AttachedDevice");
2023 const xml::ElementNode *pelmAttached;
2024 while ((pelmAttached = nlAttached.forAllNodes()))
2025 {
2026 AttachedDevice att;
2027 Utf8Str strTemp;
2028 pelmAttached->getAttributeValue("type", strTemp);
2029
2030 if (strTemp == "HardDisk")
2031 att.deviceType = DeviceType_HardDisk;
2032 else if (m->sv >= SettingsVersion_v1_9)
2033 {
2034 // starting with 1.9 we list DVD and floppy drive info + attachments under <StorageControllers>
2035 if (strTemp == "DVD")
2036 {
2037 att.deviceType = DeviceType_DVD;
2038 pelmAttached->getAttributeValue("passthrough", att.fPassThrough);
2039 }
2040 else if (strTemp == "Floppy")
2041 att.deviceType = DeviceType_Floppy;
2042 }
2043
2044 if (att.deviceType != DeviceType_Null)
2045 {
2046 const xml::ElementNode *pelmImage;
2047 // all types can have images attached, but for HardDisk it's required
2048 if (!(pelmImage = pelmAttached->findChildElement("Image")))
2049 {
2050 if (att.deviceType == DeviceType_HardDisk)
2051 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/Image element is missing"));
2052 else
2053 {
2054 // DVDs and floppies can also have <HostDrive> instead of <Image>
2055 const xml::ElementNode *pelmHostDrive;
2056 if ((pelmHostDrive = pelmAttached->findChildElement("HostDrive")))
2057 if (!pelmHostDrive->getAttributeValue("src", att.strHostDriveSrc))
2058 throw ConfigFileError(this, pelmHostDrive, N_("Required AttachedDevice/HostDrive/@src attribute is missing"));
2059 }
2060 }
2061 else
2062 {
2063 if (!pelmImage->getAttributeValue("uuid", strTemp))
2064 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/Image/@uuid attribute is missing"));
2065 parseUUID(att.uuid, strTemp);
2066 }
2067
2068 if (!pelmAttached->getAttributeValue("port", att.lPort))
2069 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/@port attribute is missing"));
2070 if (!pelmAttached->getAttributeValue("device", att.lDevice))
2071 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/@device attribute is missing"));
2072
2073 sctl.llAttachedDevices.push_back(att);
2074 }
2075 }
2076
2077 strg.llStorageControllers.push_back(sctl);
2078 }
2079}
2080
2081/**
2082 * This gets called for legacy pre-1.9 settings files after having parsed the
2083 * <Hardware> and <StorageControllers> sections to parse <Hardware> once more
2084 * for the <DVDDrive> and <FloppyDrive> sections.
2085 *
2086 * Before settings version 1.9, DVD and floppy drives were specified separately
2087 * under <Hardware>; we then need this extra loop to make sure the storage
2088 * controller structs are already set up so we can add stuff to them.
2089 *
2090 * @param elmHardware
2091 * @param strg
2092 */
2093void MachineConfigFile::readDVDAndFloppies_pre1_9(const xml::ElementNode &elmHardware,
2094 Storage &strg)
2095{
2096 xml::NodesLoop nl1(elmHardware);
2097 const xml::ElementNode *pelmHwChild;
2098 while ((pelmHwChild = nl1.forAllNodes()))
2099 {
2100 if (pelmHwChild->nameEquals("DVDDrive"))
2101 {
2102 // create a DVD "attached device" and attach it to the existing IDE controller
2103 AttachedDevice att;
2104 att.deviceType = DeviceType_DVD;
2105 // legacy DVD drive is always secondary master (port 1, device 0)
2106 att.lPort = 1;
2107 att.lDevice = 0;
2108 pelmHwChild->getAttributeValue("passthrough", att.fPassThrough);
2109
2110 const xml::ElementNode *pDriveChild;
2111 Utf8Str strTmp;
2112 if ( ((pDriveChild = pelmHwChild->findChildElement("Image")))
2113 && (pDriveChild->getAttributeValue("uuid", strTmp))
2114 )
2115 parseUUID(att.uuid, strTmp);
2116 else if ((pDriveChild = pelmHwChild->findChildElement("HostDrive")))
2117 pDriveChild->getAttributeValue("src", att.strHostDriveSrc);
2118
2119 // find the IDE controller and attach the DVD drive
2120 bool fFound = false;
2121 for (StorageControllersList::iterator it = strg.llStorageControllers.begin();
2122 it != strg.llStorageControllers.end();
2123 ++it)
2124 {
2125 StorageController &sctl = *it;
2126 if (sctl.storageBus == StorageBus_IDE)
2127 {
2128 sctl.llAttachedDevices.push_back(att);
2129 fFound = true;
2130 break;
2131 }
2132 }
2133
2134 if (!fFound)
2135 throw ConfigFileError(this, pelmHwChild, N_("Internal error: found DVD drive but IDE controller does not exist"));
2136 // shouldn't happen because pre-1.9 settings files always had at least one IDE controller in the settings
2137 // which should have gotten parsed in <StorageControllers> before this got called
2138 }
2139 else if (pelmHwChild->nameEquals("FloppyDrive"))
2140 {
2141 bool fEnabled;
2142 if ( (pelmHwChild->getAttributeValue("enabled", fEnabled))
2143 && (fEnabled)
2144 )
2145 {
2146 // create a new floppy controller and attach a floppy "attached device"
2147 StorageController sctl;
2148 sctl.strName = "Floppy Controller";
2149 sctl.storageBus = StorageBus_Floppy;
2150 sctl.controllerType = StorageControllerType_I82078;
2151 sctl.ulPortCount = 1;
2152
2153 AttachedDevice att;
2154 att.deviceType = DeviceType_Floppy;
2155 att.lPort = 0;
2156 att.lDevice = 0;
2157
2158 const xml::ElementNode *pDriveChild;
2159 Utf8Str strTmp;
2160 if ( ((pDriveChild = pelmHwChild->findChildElement("Image")))
2161 && (pDriveChild->getAttributeValue("uuid", strTmp))
2162 )
2163 parseUUID(att.uuid, strTmp);
2164 else if ((pDriveChild = pelmHwChild->findChildElement("HostDrive")))
2165 pDriveChild->getAttributeValue("src", att.strHostDriveSrc);
2166
2167 // store attachment with controller
2168 sctl.llAttachedDevices.push_back(att);
2169 // store controller with storage
2170 strg.llStorageControllers.push_back(sctl);
2171 }
2172 }
2173 }
2174}
2175
2176/**
2177 * Called initially for the <Snapshot> element under <Machine>, if present,
2178 * to store the snapshot's data into the given Snapshot structure (which is
2179 * then the one in the Machine struct). This might then recurse if
2180 * a <Snapshots> (plural) element is found in the snapshot, which should
2181 * contain a list of child snapshots; such lists are maintained in the
2182 * Snapshot structure.
2183 *
2184 * @param elmSnapshot
2185 * @param snap
2186 */
2187void MachineConfigFile::readSnapshot(const xml::ElementNode &elmSnapshot,
2188 Snapshot &snap)
2189{
2190 Utf8Str strTemp;
2191
2192 if (!elmSnapshot.getAttributeValue("uuid", strTemp))
2193 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@uuid attribute is missing"));
2194 parseUUID(snap.uuid, strTemp);
2195
2196 if (!elmSnapshot.getAttributeValue("name", snap.strName))
2197 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@name attribute is missing"));
2198
2199 // earlier 3.1 trunk builds had a bug and added Description as an attribute, read it silently and write it back as an element
2200 elmSnapshot.getAttributeValue("Description", snap.strDescription);
2201
2202 if (!elmSnapshot.getAttributeValue("timeStamp", strTemp))
2203 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@timeStamp attribute is missing"));
2204 parseTimestamp(snap.timestamp, strTemp);
2205
2206 elmSnapshot.getAttributeValue("stateFile", snap.strStateFile); // online snapshots only
2207
2208 // parse Hardware before the other elements because other things depend on it
2209 const xml::ElementNode *pelmHardware;
2210 if (!(pelmHardware = elmSnapshot.findChildElement("Hardware")))
2211 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@Hardware element is missing"));
2212 readHardware(*pelmHardware, snap.hardware, snap.storage);
2213
2214 xml::NodesLoop nlSnapshotChildren(elmSnapshot);
2215 const xml::ElementNode *pelmSnapshotChild;
2216 while ((pelmSnapshotChild = nlSnapshotChildren.forAllNodes()))
2217 {
2218 if (pelmSnapshotChild->nameEquals("Description"))
2219 snap.strDescription = pelmSnapshotChild->getValue();
2220 else if ( (m->sv < SettingsVersion_v1_7)
2221 && (pelmSnapshotChild->nameEquals("HardDiskAttachments"))
2222 )
2223 readHardDiskAttachments_pre1_7(*pelmSnapshotChild, snap.storage);
2224 else if ( (m->sv >= SettingsVersion_v1_7)
2225 && (pelmSnapshotChild->nameEquals("StorageControllers"))
2226 )
2227 readStorageControllers(*pelmSnapshotChild, snap.storage);
2228 else if (pelmSnapshotChild->nameEquals("Snapshots"))
2229 {
2230 xml::NodesLoop nlChildSnapshots(*pelmSnapshotChild);
2231 const xml::ElementNode *pelmChildSnapshot;
2232 while ((pelmChildSnapshot = nlChildSnapshots.forAllNodes()))
2233 {
2234 if (pelmChildSnapshot->nameEquals("Snapshot"))
2235 {
2236 Snapshot child;
2237 readSnapshot(*pelmChildSnapshot, child);
2238 snap.llChildSnapshots.push_back(child);
2239 }
2240 }
2241 }
2242 }
2243
2244 if (m->sv < SettingsVersion_v1_9)
2245 // go through Hardware once more to repair the settings controller structures
2246 // with data from old DVDDrive and FloppyDrive elements
2247 readDVDAndFloppies_pre1_9(*pelmHardware, snap.storage);
2248}
2249
2250void MachineConfigFile::convertOldOSType_pre1_5(Utf8Str &str)
2251{
2252 if (str == "unknown") str = "Other";
2253 else if (str == "dos") str = "DOS";
2254 else if (str == "win31") str = "Windows31";
2255 else if (str == "win95") str = "Windows95";
2256 else if (str == "win98") str = "Windows98";
2257 else if (str == "winme") str = "WindowsMe";
2258 else if (str == "winnt4") str = "WindowsNT4";
2259 else if (str == "win2k") str = "Windows2000";
2260 else if (str == "winxp") str = "WindowsXP";
2261 else if (str == "win2k3") str = "Windows2003";
2262 else if (str == "winvista") str = "WindowsVista";
2263 else if (str == "win2k8") str = "Windows2008";
2264 else if (str == "os2warp3") str = "OS2Warp3";
2265 else if (str == "os2warp4") str = "OS2Warp4";
2266 else if (str == "os2warp45") str = "OS2Warp45";
2267 else if (str == "ecs") str = "OS2eCS";
2268 else if (str == "linux22") str = "Linux22";
2269 else if (str == "linux24") str = "Linux24";
2270 else if (str == "linux26") str = "Linux26";
2271 else if (str == "archlinux") str = "ArchLinux";
2272 else if (str == "debian") str = "Debian";
2273 else if (str == "opensuse") str = "OpenSUSE";
2274 else if (str == "fedoracore") str = "Fedora";
2275 else if (str == "gentoo") str = "Gentoo";
2276 else if (str == "mandriva") str = "Mandriva";
2277 else if (str == "redhat") str = "RedHat";
2278 else if (str == "ubuntu") str = "Ubuntu";
2279 else if (str == "xandros") str = "Xandros";
2280 else if (str == "freebsd") str = "FreeBSD";
2281 else if (str == "openbsd") str = "OpenBSD";
2282 else if (str == "netbsd") str = "NetBSD";
2283 else if (str == "netware") str = "Netware";
2284 else if (str == "solaris") str = "Solaris";
2285 else if (str == "opensolaris") str = "OpenSolaris";
2286 else if (str == "l4") str = "L4";
2287}
2288
2289/**
2290 * Called from the constructor to actually read in the <Machine> element
2291 * of a machine config file.
2292 * @param elmMachine
2293 */
2294void MachineConfigFile::readMachine(const xml::ElementNode &elmMachine)
2295{
2296 Utf8Str strUUID;
2297 if ( (elmMachine.getAttributeValue("uuid", strUUID))
2298 && (elmMachine.getAttributeValue("name", strName))
2299 )
2300 {
2301 parseUUID(uuid, strUUID);
2302
2303 if (!elmMachine.getAttributeValue("nameSync", fNameSync))
2304 fNameSync = true;
2305
2306 Utf8Str str;
2307 elmMachine.getAttributeValue("Description", strDescription);
2308
2309 elmMachine.getAttributeValue("OSType", strOsType);
2310 if (m->sv < SettingsVersion_v1_5)
2311 convertOldOSType_pre1_5(strOsType);
2312
2313 elmMachine.getAttributeValue("stateFile", strStateFile);
2314 if (elmMachine.getAttributeValue("currentSnapshot", str))
2315 parseUUID(uuidCurrentSnapshot, str);
2316 elmMachine.getAttributeValue("snapshotFolder", strSnapshotFolder);
2317 if (!elmMachine.getAttributeValue("currentStateModified", fCurrentStateModified))
2318 fCurrentStateModified = true;
2319 if (elmMachine.getAttributeValue("lastStateChange", str))
2320 parseTimestamp(timeLastStateChange, str);
2321 // constructor has called RTTimeNow(&timeLastStateChange) before
2322
2323#if 1 /** @todo Teleportation: Obsolete. Remove in a couple of days. */
2324 if (!elmMachine.getAttributeValue("teleporterEnabled", fTeleporterEnabled)
2325 && !elmMachine.getAttributeValue("liveMigrationTarget", fTeleporterEnabled))
2326 fTeleporterEnabled = false;
2327 if (!elmMachine.getAttributeValue("teleporterPort", uTeleporterPort)
2328 && !elmMachine.getAttributeValue("liveMigrationPort", uTeleporterPort))
2329 uTeleporterPort = 0;
2330 if (!elmMachine.getAttributeValue("teleporterAddress", strTeleporterAddress))
2331 strTeleporterAddress = "";
2332 if (!elmMachine.getAttributeValue("teleporterPassword", strTeleporterPassword)
2333 && !elmMachine.getAttributeValue("liveMigrationPassword", strTeleporterPassword))
2334 strTeleporterPassword = "";
2335#endif
2336
2337 // parse Hardware before the other elements because other things depend on it
2338 const xml::ElementNode *pelmHardware;
2339 if (!(pelmHardware = elmMachine.findChildElement("Hardware")))
2340 throw ConfigFileError(this, &elmMachine, N_("Required Machine/Hardware element is missing"));
2341 readHardware(*pelmHardware, hardwareMachine, storageMachine);
2342
2343 xml::NodesLoop nlRootChildren(elmMachine);
2344 const xml::ElementNode *pelmMachineChild;
2345 while ((pelmMachineChild = nlRootChildren.forAllNodes()))
2346 {
2347 if (pelmMachineChild->nameEquals("ExtraData"))
2348 readExtraData(*pelmMachineChild,
2349 mapExtraDataItems);
2350 else if ( (m->sv < SettingsVersion_v1_7)
2351 && (pelmMachineChild->nameEquals("HardDiskAttachments"))
2352 )
2353 readHardDiskAttachments_pre1_7(*pelmMachineChild, storageMachine);
2354 else if ( (m->sv >= SettingsVersion_v1_7)
2355 && (pelmMachineChild->nameEquals("StorageControllers"))
2356 )
2357 readStorageControllers(*pelmMachineChild, storageMachine);
2358 else if (pelmMachineChild->nameEquals("Snapshot"))
2359 {
2360 Snapshot snap;
2361 // this will recurse into child snapshots, if necessary
2362 readSnapshot(*pelmMachineChild, snap);
2363 llFirstSnapshot.push_back(snap);
2364 }
2365 else if (pelmMachineChild->nameEquals("Description"))
2366 strDescription = pelmMachineChild->getValue();
2367 else if (pelmMachineChild->nameEquals("Teleporter"))
2368 {
2369 if (!pelmMachineChild->getAttributeValue("enabled", fTeleporterEnabled))
2370 fTeleporterEnabled = false;
2371 if (!pelmMachineChild->getAttributeValue("port", uTeleporterPort))
2372 uTeleporterPort = 0;
2373 if (!pelmMachineChild->getAttributeValue("address", strTeleporterAddress))
2374 strTeleporterAddress = "";
2375 if (!pelmMachineChild->getAttributeValue("password", strTeleporterPassword))
2376 strTeleporterPassword = "";
2377 }
2378 }
2379
2380 if (m->sv < SettingsVersion_v1_9)
2381 // go through Hardware once more to repair the settings controller structures
2382 // with data from old DVDDrive and FloppyDrive elements
2383 readDVDAndFloppies_pre1_9(*pelmHardware, storageMachine);
2384 }
2385 else
2386 throw ConfigFileError(this, &elmMachine, N_("Required Machine/@uuid or @name attributes is missing"));
2387}
2388
2389////////////////////////////////////////////////////////////////////////////////
2390//
2391// MachineConfigFile
2392//
2393////////////////////////////////////////////////////////////////////////////////
2394
2395/**
2396 * Constructor.
2397 *
2398 * If pstrFilename is != NULL, this reads the given settings file into the member
2399 * variables and various substructures and lists. Otherwise, the member variables
2400 * are initialized with default values.
2401 *
2402 * Throws variants of xml::Error for I/O, XML and logical content errors, which
2403 * the caller should catch; if this constructor does not throw, then the member
2404 * variables contain meaningful values (either from the file or defaults).
2405 *
2406 * @param strFilename
2407 */
2408MachineConfigFile::MachineConfigFile(const Utf8Str *pstrFilename)
2409 : ConfigFileBase(pstrFilename),
2410 fNameSync(true),
2411 fTeleporterEnabled(false),
2412 uTeleporterPort(0),
2413 fCurrentStateModified(true),
2414 fAborted(false)
2415{
2416 RTTimeNow(&timeLastStateChange);
2417
2418 if (pstrFilename)
2419 {
2420 // the ConfigFileBase constructor has loaded the XML file, so now
2421 // we need only analyze what is in there
2422
2423 xml::NodesLoop nlRootChildren(*m->pelmRoot);
2424 const xml::ElementNode *pelmRootChild;
2425 while ((pelmRootChild = nlRootChildren.forAllNodes()))
2426 {
2427 if (pelmRootChild->nameEquals("Machine"))
2428 readMachine(*pelmRootChild);
2429 }
2430
2431 // clean up memory allocated by XML engine
2432 clearDocument();
2433 }
2434}
2435
2436/**
2437 * Creates a <Hardware> node under elmParent and then writes out the XML
2438 * keys under that. Called for both the <Machine> node and for snapshots.
2439 * @param elmParent
2440 * @param st
2441 */
2442void MachineConfigFile::writeHardware(xml::ElementNode &elmParent,
2443 const Hardware &hw,
2444 const Storage &strg)
2445{
2446 xml::ElementNode *pelmHardware = elmParent.createChild("Hardware");
2447
2448 if (m->sv >= SettingsVersion_v1_4)
2449 pelmHardware->setAttribute("version", hw.strVersion);
2450 if ( (m->sv >= SettingsVersion_v1_9)
2451 && (!hw.uuid.isEmpty())
2452 )
2453 pelmHardware->setAttribute("uuid", makeString(hw.uuid));
2454
2455 xml::ElementNode *pelmCPU = pelmHardware->createChild("CPU");
2456
2457 xml::ElementNode *pelmHwVirtEx = pelmCPU->createChild("HardwareVirtEx");
2458 pelmHwVirtEx->setAttribute("enabled", hw.fHardwareVirt);
2459 if (m->sv >= SettingsVersion_v1_9)
2460 pelmHwVirtEx->setAttribute("exclusive", hw.fHardwareVirtExclusive);
2461
2462 pelmCPU->createChild("HardwareVirtExNestedPaging")->setAttribute("enabled", hw.fNestedPaging);
2463 pelmCPU->createChild("HardwareVirtExVPID")->setAttribute("enabled", hw.fVPID);
2464 pelmCPU->createChild("PAE")->setAttribute("enabled", hw.fPAE);
2465
2466 if (hw.fSyntheticCpu)
2467 pelmCPU->createChild("SyntheticCpu")->setAttribute("enabled", hw.fSyntheticCpu);
2468 pelmCPU->setAttribute("count", hw.cCPUs);
2469 xml::ElementNode *pelmCpuIdTree = NULL;
2470 for (CpuIdLeafsList::const_iterator it = hw.llCpuIdLeafs.begin();
2471 it != hw.llCpuIdLeafs.end();
2472 ++it)
2473 {
2474 const CpuIdLeaf &leaf = *it;
2475
2476 if (pelmCpuIdTree == NULL)
2477 pelmCpuIdTree = pelmCPU->createChild("CpuIdTree");
2478
2479 xml::ElementNode *pelmCpuIdLeaf = pelmCpuIdTree->createChild("CpuIdLeaf");
2480 pelmCpuIdLeaf->setAttribute("id", leaf.ulId);
2481 pelmCpuIdLeaf->setAttribute("eax", leaf.ulEax);
2482 pelmCpuIdLeaf->setAttribute("ebx", leaf.ulEbx);
2483 pelmCpuIdLeaf->setAttribute("ecx", leaf.ulEcx);
2484 pelmCpuIdLeaf->setAttribute("edx", leaf.ulEdx);
2485 }
2486
2487 xml::ElementNode *pelmMemory = pelmHardware->createChild("Memory");
2488 pelmMemory->setAttribute("RAMSize", hw.ulMemorySizeMB);
2489
2490 if ( (m->sv >= SettingsVersion_v1_9)
2491 && (hw.firmwareType >= FirmwareType_EFI)
2492 )
2493 {
2494 xml::ElementNode *pelmFirmware = pelmHardware->createChild("Firmware");
2495 const char *pcszFirmware;
2496
2497 switch (hw.firmwareType)
2498 {
2499 case FirmwareType_EFI: pcszFirmware = "EFI"; break;
2500 case FirmwareType_EFI32: pcszFirmware = "EFI32"; break;
2501 case FirmwareType_EFI64: pcszFirmware = "EFI64"; break;
2502 case FirmwareType_EFIDUAL: pcszFirmware = "EFIDUAL"; break;
2503 default: pcszFirmware = "None"; break;
2504 }
2505 pelmFirmware->setAttribute("type", pcszFirmware);
2506 }
2507
2508 xml::ElementNode *pelmBoot = pelmHardware->createChild("Boot");
2509 for (BootOrderMap::const_iterator it = hw.mapBootOrder.begin();
2510 it != hw.mapBootOrder.end();
2511 ++it)
2512 {
2513 uint32_t i = it->first;
2514 DeviceType_T type = it->second;
2515 const char *pcszDevice;
2516
2517 switch (type)
2518 {
2519 case DeviceType_Floppy: pcszDevice = "Floppy"; break;
2520 case DeviceType_DVD: pcszDevice = "DVD"; break;
2521 case DeviceType_HardDisk: pcszDevice = "HardDisk"; break;
2522 case DeviceType_Network: pcszDevice = "Network"; break;
2523 default: /*case DeviceType_Null:*/ pcszDevice = "None"; break;
2524 }
2525
2526 xml::ElementNode *pelmOrder = pelmBoot->createChild("Order");
2527 pelmOrder->setAttribute("position",
2528 i + 1); // XML is 1-based but internal data is 0-based
2529 pelmOrder->setAttribute("device", pcszDevice);
2530 }
2531
2532 xml::ElementNode *pelmDisplay = pelmHardware->createChild("Display");
2533 pelmDisplay->setAttribute("VRAMSize", hw.ulVRAMSizeMB);
2534 pelmDisplay->setAttribute("monitorCount", hw.cMonitors);
2535 pelmDisplay->setAttribute("accelerate3D", hw.fAccelerate3D);
2536
2537 if (m->sv >= SettingsVersion_v1_8)
2538 pelmDisplay->setAttribute("accelerate2DVideo", hw.fAccelerate2DVideo);
2539
2540 xml::ElementNode *pelmVRDP = pelmHardware->createChild("RemoteDisplay");
2541 pelmVRDP->setAttribute("enabled", hw.vrdpSettings.fEnabled);
2542 Utf8Str strPort = hw.vrdpSettings.strPort;
2543 if (!strPort.length())
2544 strPort = "3389";
2545 pelmVRDP->setAttribute("port", strPort);
2546 if (hw.vrdpSettings.strNetAddress.length())
2547 pelmVRDP->setAttribute("netAddress", hw.vrdpSettings.strNetAddress);
2548 const char *pcszAuthType;
2549 switch (hw.vrdpSettings.authType)
2550 {
2551 case VRDPAuthType_Guest: pcszAuthType = "Guest"; break;
2552 case VRDPAuthType_External: pcszAuthType = "External"; break;
2553 default: /*case VRDPAuthType_Null:*/ pcszAuthType = "Null"; break;
2554 }
2555 pelmVRDP->setAttribute("authType", pcszAuthType);
2556
2557 if (hw.vrdpSettings.ulAuthTimeout != 0)
2558 pelmVRDP->setAttribute("authTimeout", hw.vrdpSettings.ulAuthTimeout);
2559 if (hw.vrdpSettings.fAllowMultiConnection)
2560 pelmVRDP->setAttribute("allowMultiConnection", hw.vrdpSettings.fAllowMultiConnection);
2561 if (hw.vrdpSettings.fReuseSingleConnection)
2562 pelmVRDP->setAttribute("reuseSingleConnection", hw.vrdpSettings.fReuseSingleConnection);
2563
2564 xml::ElementNode *pelmBIOS = pelmHardware->createChild("BIOS");
2565 pelmBIOS->createChild("ACPI")->setAttribute("enabled", hw.biosSettings.fACPIEnabled);
2566 pelmBIOS->createChild("IOAPIC")->setAttribute("enabled", hw.biosSettings.fIOAPICEnabled);
2567
2568 xml::ElementNode *pelmLogo = pelmBIOS->createChild("Logo");
2569 pelmLogo->setAttribute("fadeIn", hw.biosSettings.fLogoFadeIn);
2570 pelmLogo->setAttribute("fadeOut", hw.biosSettings.fLogoFadeOut);
2571 pelmLogo->setAttribute("displayTime", hw.biosSettings.ulLogoDisplayTime);
2572 if (hw.biosSettings.strLogoImagePath.length())
2573 pelmLogo->setAttribute("imagePath", hw.biosSettings.strLogoImagePath);
2574
2575 const char *pcszBootMenu;
2576 switch (hw.biosSettings.biosBootMenuMode)
2577 {
2578 case BIOSBootMenuMode_Disabled: pcszBootMenu = "Disabled"; break;
2579 case BIOSBootMenuMode_MenuOnly: pcszBootMenu = "MenuOnly"; break;
2580 default: /*BIOSBootMenuMode_MessageAndMenu*/ pcszBootMenu = "MessageAndMenu"; break;
2581 }
2582 pelmBIOS->createChild("BootMenu")->setAttribute("mode", pcszBootMenu);
2583 pelmBIOS->createChild("TimeOffset")->setAttribute("value", hw.biosSettings.llTimeOffset);
2584 pelmBIOS->createChild("PXEDebug")->setAttribute("enabled", hw.biosSettings.fPXEDebugEnabled);
2585
2586 if (m->sv < SettingsVersion_v1_9)
2587 {
2588 // settings formats before 1.9 had separate DVDDrive and FloppyDrive items under Hardware;
2589 // run thru the storage controllers to see if we have a DVD or floppy drives
2590 size_t cDVDs = 0;
2591 size_t cFloppies = 0;
2592
2593 xml::ElementNode *pelmDVD = pelmHardware->createChild("DVDDrive");
2594 xml::ElementNode *pelmFloppy = pelmHardware->createChild("FloppyDrive");
2595
2596 for (StorageControllersList::const_iterator it = strg.llStorageControllers.begin();
2597 it != strg.llStorageControllers.end();
2598 ++it)
2599 {
2600 const StorageController &sctl = *it;
2601 // in old settings format, the DVD drive could only have been under the IDE controller
2602 if (sctl.storageBus == StorageBus_IDE)
2603 {
2604 for (AttachedDevicesList::const_iterator it2 = sctl.llAttachedDevices.begin();
2605 it2 != sctl.llAttachedDevices.end();
2606 ++it2)
2607 {
2608 const AttachedDevice &att = *it2;
2609 if (att.deviceType == DeviceType_DVD)
2610 {
2611 if (cDVDs > 0)
2612 throw ConfigFileError(this, NULL, N_("Internal error: cannot save more than one DVD drive with old settings format"));
2613
2614 ++cDVDs;
2615
2616 pelmDVD->setAttribute("passthrough", att.fPassThrough);
2617 if (!att.uuid.isEmpty())
2618 pelmDVD->createChild("Image")->setAttribute("uuid", makeString(att.uuid));
2619 else if (att.strHostDriveSrc.length())
2620 pelmDVD->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
2621 }
2622 }
2623 }
2624 else if (sctl.storageBus == StorageBus_Floppy)
2625 {
2626 size_t cFloppiesHere = sctl.llAttachedDevices.size();
2627 if (cFloppiesHere > 1)
2628 throw ConfigFileError(this, NULL, N_("Internal error: floppy controller cannot have more than one device attachment"));
2629 if (cFloppiesHere)
2630 {
2631 const AttachedDevice &att = sctl.llAttachedDevices.front();
2632 pelmFloppy->setAttribute("enabled", true);
2633 if (!att.uuid.isEmpty())
2634 pelmFloppy->createChild("Image")->setAttribute("uuid", makeString(att.uuid));
2635 else if (att.strHostDriveSrc.length())
2636 pelmFloppy->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
2637 }
2638
2639 cFloppies += cFloppiesHere;
2640 }
2641 }
2642
2643 if (cFloppies == 0)
2644 pelmFloppy->setAttribute("enabled", false);
2645 else if (cFloppies > 1)
2646 throw ConfigFileError(this, NULL, N_("Internal error: cannot save more than one floppy drive with old settings format"));
2647 }
2648
2649 xml::ElementNode *pelmUSB = pelmHardware->createChild("USBController");
2650 pelmUSB->setAttribute("enabled", hw.usbController.fEnabled);
2651 pelmUSB->setAttribute("enabledEhci", hw.usbController.fEnabledEHCI);
2652
2653 writeUSBDeviceFilters(*pelmUSB,
2654 hw.usbController.llDeviceFilters,
2655 false); // fHostMode
2656
2657 xml::ElementNode *pelmNetwork = pelmHardware->createChild("Network");
2658 for (NetworkAdaptersList::const_iterator it = hw.llNetworkAdapters.begin();
2659 it != hw.llNetworkAdapters.end();
2660 ++it)
2661 {
2662 const NetworkAdapter &nic = *it;
2663
2664 xml::ElementNode *pelmAdapter = pelmNetwork->createChild("Adapter");
2665 pelmAdapter->setAttribute("slot", nic.ulSlot);
2666 pelmAdapter->setAttribute("enabled", nic.fEnabled);
2667 pelmAdapter->setAttribute("MACAddress", nic.strMACAddress);
2668 pelmAdapter->setAttribute("cable", nic.fCableConnected);
2669 pelmAdapter->setAttribute("speed", nic.ulLineSpeed);
2670 if (nic.fTraceEnabled)
2671 {
2672 pelmAdapter->setAttribute("trace", nic.fTraceEnabled);
2673 pelmAdapter->setAttribute("tracefile", nic.strTraceFile);
2674 }
2675
2676 const char *pcszType;
2677 switch (nic.type)
2678 {
2679 case NetworkAdapterType_Am79C973: pcszType = "Am79C973"; break;
2680 case NetworkAdapterType_I82540EM: pcszType = "82540EM"; break;
2681 case NetworkAdapterType_I82543GC: pcszType = "82543GC"; break;
2682 case NetworkAdapterType_I82545EM: pcszType = "82545EM"; break;
2683 case NetworkAdapterType_Virtio: pcszType = "virtio"; break;
2684 default: /*case NetworkAdapterType_Am79C970A:*/ pcszType = "Am79C970A"; break;
2685 }
2686 pelmAdapter->setAttribute("type", pcszType);
2687
2688 xml::ElementNode *pelmNAT;
2689 switch (nic.mode)
2690 {
2691 case NetworkAttachmentType_NAT:
2692 pelmNAT = pelmAdapter->createChild("NAT");
2693 if (nic.strName.length())
2694 pelmNAT->setAttribute("network", nic.strName);
2695 break;
2696
2697 case NetworkAttachmentType_Bridged:
2698 pelmAdapter->createChild("BridgedInterface")->setAttribute("name", nic.strName);
2699 break;
2700
2701 case NetworkAttachmentType_Internal:
2702 pelmAdapter->createChild("InternalNetwork")->setAttribute("name", nic.strName);
2703 break;
2704
2705 case NetworkAttachmentType_HostOnly:
2706 pelmAdapter->createChild("HostOnlyInterface")->setAttribute("name", nic.strName);
2707 break;
2708
2709 default: /*case NetworkAttachmentType_Null:*/
2710 break;
2711 }
2712 }
2713
2714 xml::ElementNode *pelmPorts = pelmHardware->createChild("UART");
2715 for (SerialPortsList::const_iterator it = hw.llSerialPorts.begin();
2716 it != hw.llSerialPorts.end();
2717 ++it)
2718 {
2719 const SerialPort &port = *it;
2720 xml::ElementNode *pelmPort = pelmPorts->createChild("Port");
2721 pelmPort->setAttribute("slot", port.ulSlot);
2722 pelmPort->setAttribute("enabled", port.fEnabled);
2723 pelmPort->setAttributeHex("IOBase", port.ulIOBase);
2724 pelmPort->setAttribute("IRQ", port.ulIRQ);
2725
2726 const char *pcszHostMode;
2727 switch (port.portMode)
2728 {
2729 case PortMode_HostPipe: pcszHostMode = "HostPipe"; break;
2730 case PortMode_HostDevice: pcszHostMode = "HostDevice"; break;
2731 case PortMode_RawFile: pcszHostMode = "RawFile"; break;
2732 default: /*case PortMode_Disconnected:*/ pcszHostMode = "Disconnected"; break;
2733 }
2734 switch (port.portMode)
2735 {
2736 case PortMode_HostPipe:
2737 pelmPort->setAttribute("server", port.fServer);
2738 /* no break */
2739 case PortMode_HostDevice:
2740 case PortMode_RawFile:
2741 pelmPort->setAttribute("path", port.strPath);
2742 break;
2743
2744 default:
2745 break;
2746 }
2747 pelmPort->setAttribute("hostMode", pcszHostMode);
2748 }
2749
2750 pelmPorts = pelmHardware->createChild("LPT");
2751 for (ParallelPortsList::const_iterator it = hw.llParallelPorts.begin();
2752 it != hw.llParallelPorts.end();
2753 ++it)
2754 {
2755 const ParallelPort &port = *it;
2756 xml::ElementNode *pelmPort = pelmPorts->createChild("Port");
2757 pelmPort->setAttribute("slot", port.ulSlot);
2758 pelmPort->setAttribute("enabled", port.fEnabled);
2759 pelmPort->setAttributeHex("IOBase", port.ulIOBase);
2760 pelmPort->setAttribute("IRQ", port.ulIRQ);
2761 if (port.strPath.length())
2762 pelmPort->setAttribute("path", port.strPath);
2763 }
2764
2765 xml::ElementNode *pelmAudio = pelmHardware->createChild("AudioAdapter");
2766 pelmAudio->setAttribute("controller", (hw.audioAdapter.controllerType == AudioControllerType_SB16) ? "SB16" : "AC97");
2767
2768 const char *pcszDriver;
2769 switch (hw.audioAdapter.driverType)
2770 {
2771 case AudioDriverType_WinMM: pcszDriver = "WinMM"; break;
2772 case AudioDriverType_DirectSound: pcszDriver = "DirectSound"; break;
2773 case AudioDriverType_SolAudio: pcszDriver = "SolAudio"; break;
2774 case AudioDriverType_ALSA: pcszDriver = "ALSA"; break;
2775 case AudioDriverType_Pulse: pcszDriver = "Pulse"; break;
2776 case AudioDriverType_OSS: pcszDriver = "OSS"; break;
2777 case AudioDriverType_CoreAudio: pcszDriver = "CoreAudio"; break;
2778 case AudioDriverType_MMPM: pcszDriver = "MMPM"; break;
2779 default: /*case AudioDriverType_Null:*/ pcszDriver = "Null"; break;
2780 }
2781 pelmAudio->setAttribute("driver", pcszDriver);
2782
2783 pelmAudio->setAttribute("enabled", hw.audioAdapter.fEnabled);
2784
2785 xml::ElementNode *pelmSharedFolders = pelmHardware->createChild("SharedFolders");
2786 for (SharedFoldersList::const_iterator it = hw.llSharedFolders.begin();
2787 it != hw.llSharedFolders.end();
2788 ++it)
2789 {
2790 const SharedFolder &sf = *it;
2791 xml::ElementNode *pelmThis = pelmSharedFolders->createChild("SharedFolder");
2792 pelmThis->setAttribute("name", sf.strName);
2793 pelmThis->setAttribute("hostPath", sf.strHostPath);
2794 pelmThis->setAttribute("writable", sf.fWritable);
2795 }
2796
2797 xml::ElementNode *pelmClip = pelmHardware->createChild("Clipboard");
2798 const char *pcszClip;
2799 switch (hw.clipboardMode)
2800 {
2801 case ClipboardMode_Disabled: pcszClip = "Disabled"; break;
2802 case ClipboardMode_HostToGuest: pcszClip = "HostToGuest"; break;
2803 case ClipboardMode_GuestToHost: pcszClip = "GuestToHost"; break;
2804 default: /*case ClipboardMode_Bidirectional:*/ pcszClip = "Bidirectional"; break;
2805 }
2806 pelmClip->setAttribute("mode", pcszClip);
2807
2808 xml::ElementNode *pelmGuest = pelmHardware->createChild("Guest");
2809 pelmGuest->setAttribute("memoryBalloonSize", hw.ulMemoryBalloonSize);
2810 pelmGuest->setAttribute("statisticsUpdateInterval", hw.ulStatisticsUpdateInterval);
2811
2812 xml::ElementNode *pelmGuestProps = pelmHardware->createChild("GuestProperties");
2813 for (GuestPropertiesList::const_iterator it = hw.llGuestProperties.begin();
2814 it != hw.llGuestProperties.end();
2815 ++it)
2816 {
2817 const GuestProperty &prop = *it;
2818 xml::ElementNode *pelmProp = pelmGuestProps->createChild("GuestProperty");
2819 pelmProp->setAttribute("name", prop.strName);
2820 pelmProp->setAttribute("value", prop.strValue);
2821 pelmProp->setAttribute("timestamp", prop.timestamp);
2822 pelmProp->setAttribute("flags", prop.strFlags);
2823 }
2824
2825 if (hw.strNotificationPatterns.length())
2826 pelmGuestProps->setAttribute("notificationPatterns", hw.strNotificationPatterns);
2827}
2828
2829/**
2830 * Creates a <StorageControllers> node under elmParent and then writes out the XML
2831 * keys under that. Called for both the <Machine> node and for snapshots.
2832 * @param elmParent
2833 * @param st
2834 */
2835void MachineConfigFile::writeStorageControllers(xml::ElementNode &elmParent,
2836 const Storage &st)
2837{
2838 xml::ElementNode *pelmStorageControllers = elmParent.createChild("StorageControllers");
2839
2840 for (StorageControllersList::const_iterator it = st.llStorageControllers.begin();
2841 it != st.llStorageControllers.end();
2842 ++it)
2843 {
2844 const StorageController &sc = *it;
2845
2846 if ( (m->sv < SettingsVersion_v1_9)
2847 && (sc.controllerType == StorageControllerType_I82078)
2848 )
2849 // floppy controller already got written into <Hardware>/<FloppyController> in writeHardware()
2850 // for pre-1.9 settings
2851 continue;
2852
2853 xml::ElementNode *pelmController = pelmStorageControllers->createChild("StorageController");
2854 com::Utf8Str name = sc.strName.raw();
2855 //
2856 if (m->sv < SettingsVersion_v1_8)
2857 {
2858 // pre-1.8 settings use shorter controller names, they are
2859 // expanded when reading the settings
2860 if (name == "IDE Controller")
2861 name = "IDE";
2862 else if (name == "SATA Controller")
2863 name = "SATA";
2864 else if (name == "SCSI Controller")
2865 name = "SCSI";
2866 }
2867 pelmController->setAttribute("name", sc.strName);
2868
2869 const char *pcszType;
2870 switch (sc.controllerType)
2871 {
2872 case StorageControllerType_IntelAhci: pcszType = "AHCI"; break;
2873 case StorageControllerType_LsiLogic: pcszType = "LsiLogic"; break;
2874 case StorageControllerType_BusLogic: pcszType = "BusLogic"; break;
2875 case StorageControllerType_PIIX4: pcszType = "PIIX4"; break;
2876 case StorageControllerType_ICH6: pcszType = "ICH6"; break;
2877 case StorageControllerType_I82078: pcszType = "I82078"; break;
2878 case StorageControllerType_LsiLogicSas: pcszType = "LsiLogicSas"; break;
2879 default: /*case StorageControllerType_PIIX3:*/ pcszType = "PIIX3"; break;
2880 }
2881 pelmController->setAttribute("type", pcszType);
2882
2883 pelmController->setAttribute("PortCount", sc.ulPortCount);
2884
2885 if (m->sv >= SettingsVersion_v1_9)
2886 if (sc.ulInstance)
2887 pelmController->setAttribute("Instance", sc.ulInstance);
2888
2889 if (sc.controllerType == StorageControllerType_IntelAhci)
2890 {
2891 pelmController->setAttribute("IDE0MasterEmulationPort", sc.lIDE0MasterEmulationPort);
2892 pelmController->setAttribute("IDE0SlaveEmulationPort", sc.lIDE0SlaveEmulationPort);
2893 pelmController->setAttribute("IDE1MasterEmulationPort", sc.lIDE1MasterEmulationPort);
2894 pelmController->setAttribute("IDE1SlaveEmulationPort", sc.lIDE1SlaveEmulationPort);
2895 }
2896
2897 for (AttachedDevicesList::const_iterator it2 = sc.llAttachedDevices.begin();
2898 it2 != sc.llAttachedDevices.end();
2899 ++it2)
2900 {
2901 const AttachedDevice &att = *it2;
2902
2903 // For settings version before 1.9, DVDs and floppies are in hardware, not storage controllers,
2904 // so we shouldn't write them here; we only get here for DVDs though because we ruled out
2905 // the floppy controller at the top of the loop
2906 if ( att.deviceType == DeviceType_DVD
2907 && m->sv < SettingsVersion_v1_9
2908 )
2909 continue;
2910
2911 xml::ElementNode *pelmDevice = pelmController->createChild("AttachedDevice");
2912
2913 pcszType = NULL;
2914
2915 switch (att.deviceType)
2916 {
2917 case DeviceType_HardDisk:
2918 pcszType = "HardDisk";
2919 break;
2920
2921 case DeviceType_DVD:
2922 pcszType = "DVD";
2923 if (att.fPassThrough)
2924 pelmDevice->setAttribute("passthrough", att.fPassThrough);
2925 break;
2926
2927 case DeviceType_Floppy:
2928 pcszType = "Floppy";
2929 break;
2930 }
2931
2932 pelmDevice->setAttribute("type", pcszType);
2933
2934 pelmDevice->setAttribute("port", att.lPort);
2935 pelmDevice->setAttribute("device", att.lDevice);
2936
2937 if (!att.uuid.isEmpty())
2938 pelmDevice->createChild("Image")->setAttribute("uuid", makeString(att.uuid));
2939 else if ( (m->sv >= SettingsVersion_v1_9)
2940 && (att.strHostDriveSrc.length())
2941 )
2942 pelmDevice->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
2943 }
2944 }
2945}
2946
2947/**
2948 * Writes a single snapshot into the DOM tree. Initially this gets called from MachineConfigFile::write()
2949 * for the root snapshot of a machine, if present; elmParent then points to the <Snapshots> node under the
2950 * <Machine> node to which <Snapshot> must be added. This may then recurse for child snapshots.
2951 * @param elmParent
2952 * @param snap
2953 */
2954void MachineConfigFile::writeSnapshot(xml::ElementNode &elmParent,
2955 const Snapshot &snap)
2956{
2957 xml::ElementNode *pelmSnapshot = elmParent.createChild("Snapshot");
2958
2959 pelmSnapshot->setAttribute("uuid", makeString(snap.uuid));
2960 pelmSnapshot->setAttribute("name", snap.strName);
2961 pelmSnapshot->setAttribute("timeStamp", makeString(snap.timestamp));
2962
2963 if (snap.strStateFile.length())
2964 pelmSnapshot->setAttribute("stateFile", snap.strStateFile);
2965
2966 if (snap.strDescription.length())
2967 pelmSnapshot->createChild("Description")->addContent(snap.strDescription);
2968
2969 writeHardware(*pelmSnapshot, snap.hardware, snap.storage);
2970 writeStorageControllers(*pelmSnapshot, snap.storage);
2971
2972 if (snap.llChildSnapshots.size())
2973 {
2974 xml::ElementNode *pelmChildren = pelmSnapshot->createChild("Snapshots");
2975 for (SnapshotsList::const_iterator it = snap.llChildSnapshots.begin();
2976 it != snap.llChildSnapshots.end();
2977 ++it)
2978 {
2979 const Snapshot &child = *it;
2980 writeSnapshot(*pelmChildren, child);
2981 }
2982 }
2983}
2984
2985/**
2986 * Called from write() before calling ConfigFileBase::createStubDocument().
2987 * This adjusts the settings version in m->sv if incompatible settings require
2988 * a settings bump, whereas otherwise we try to preserve the settings version
2989 * to avoid breaking compatibility with older versions.
2990 */
2991void MachineConfigFile::bumpSettingsVersionIfNeeded()
2992{
2993 // The hardware versions other than "1" requires settings version 1.4 (2.1+).
2994 if ( m->sv < SettingsVersion_v1_4
2995 && hardwareMachine.strVersion != "1"
2996 )
2997 m->sv = SettingsVersion_v1_4;
2998
2999 // "accelerate 2d video" requires settings version 1.8
3000 if ( (m->sv < SettingsVersion_v1_8)
3001 && (hardwareMachine.fAccelerate2DVideo)
3002 )
3003 m->sv = SettingsVersion_v1_8;
3004
3005 // all the following require settings version 1.9
3006 if ( (m->sv < SettingsVersion_v1_9)
3007 && ( (hardwareMachine.firmwareType >= FirmwareType_EFI)
3008 || (hardwareMachine.fHardwareVirtExclusive != HWVIRTEXCLUSIVEDEFAULT)
3009 || fTeleporterEnabled
3010 || uTeleporterPort
3011 || !strTeleporterAddress.isEmpty()
3012 || !strTeleporterPassword.isEmpty()
3013 || !hardwareMachine.uuid.isEmpty()
3014 )
3015 )
3016 m->sv = SettingsVersion_v1_9;
3017
3018 // settings version 1.9 is also required if there is not exactly one DVD
3019 // or more than one floppy drive present or the DVD is not at the secondary
3020 // master; this check is a bit more complicated
3021 if (m->sv < SettingsVersion_v1_9)
3022 {
3023 size_t cDVDs = 0;
3024 size_t cFloppies = 0;
3025
3026 // need to run thru all the storage controllers to figure this out
3027 for (StorageControllersList::const_iterator it = storageMachine.llStorageControllers.begin();
3028 it != storageMachine.llStorageControllers.end()
3029 && m->sv < SettingsVersion_v1_9;
3030 ++it)
3031 {
3032 const StorageController &sctl = *it;
3033 for (AttachedDevicesList::const_iterator it2 = sctl.llAttachedDevices.begin();
3034 it2 != sctl.llAttachedDevices.end();
3035 ++it2)
3036 {
3037 if (sctl.ulInstance != 0) // we can only write the StorageController/@Instance attribute with v1.9
3038 {
3039 m->sv = SettingsVersion_v1_9;
3040 break;
3041 }
3042
3043 const AttachedDevice &att = *it2;
3044 if (att.deviceType == DeviceType_DVD)
3045 {
3046 if ( (sctl.storageBus != StorageBus_IDE) // DVD at bus other than DVD?
3047 || (att.lPort != 1) // DVDs not at secondary master?
3048 || (att.lDevice != 0)
3049 )
3050 {
3051 m->sv = SettingsVersion_v1_9;
3052 break;
3053 }
3054
3055 ++cDVDs;
3056 }
3057 else if (att.deviceType == DeviceType_Floppy)
3058 ++cFloppies;
3059 }
3060 }
3061
3062 // VirtualBox before 3.1 had zero or one floppy and exactly one DVD,
3063 // so any deviation from that will require settings version 1.9
3064 if ( (m->sv < SettingsVersion_v1_9)
3065 && ( (cDVDs != 1)
3066 || (cFloppies > 1)
3067 )
3068 )
3069 m->sv = SettingsVersion_v1_9;
3070 }
3071}
3072
3073/**
3074 * Called from Main code to write a machine config file to disk. This builds a DOM tree from
3075 * the member variables and then writes the XML file; it throws xml::Error instances on errors,
3076 * in particular if the file cannot be written.
3077 */
3078void MachineConfigFile::write(const com::Utf8Str &strFilename)
3079{
3080 try
3081 {
3082 // createStubDocument() sets the settings version to at least 1.7; however,
3083 // we might need to enfore a later settings version if incompatible settings
3084 // are present:
3085 bumpSettingsVersionIfNeeded();
3086
3087 m->strFilename = strFilename;
3088 createStubDocument();
3089
3090 xml::ElementNode *pelmMachine = m->pelmRoot->createChild("Machine");
3091
3092 pelmMachine->setAttribute("uuid", makeString(uuid));
3093 pelmMachine->setAttribute("name", strName);
3094 if (!fNameSync)
3095 pelmMachine->setAttribute("nameSync", fNameSync);
3096 if (strDescription.length())
3097 pelmMachine->createChild("Description")->addContent(strDescription);
3098 pelmMachine->setAttribute("OSType", strOsType);
3099 if (strStateFile.length())
3100 pelmMachine->setAttribute("stateFile", strStateFile);
3101 if (!uuidCurrentSnapshot.isEmpty())
3102 pelmMachine->setAttribute("currentSnapshot", makeString(uuidCurrentSnapshot));
3103 if (strSnapshotFolder.length())
3104 pelmMachine->setAttribute("snapshotFolder", strSnapshotFolder);
3105 if (!fCurrentStateModified)
3106 pelmMachine->setAttribute("currentStateModified", fCurrentStateModified);
3107 pelmMachine->setAttribute("lastStateChange", makeString(timeLastStateChange));
3108 if (fAborted)
3109 pelmMachine->setAttribute("aborted", fAborted);
3110 if ( m->sv >= SettingsVersion_v1_9
3111 && ( fTeleporterEnabled
3112 || uTeleporterPort
3113 || !strTeleporterAddress.isEmpty()
3114 || !strTeleporterPassword.isEmpty()
3115 )
3116 )
3117 {
3118 xml::ElementNode *pelmTeleporter = pelmMachine->createChild("Teleporter");
3119 pelmTeleporter->setAttribute("enabled", fTeleporterEnabled);
3120 pelmTeleporter->setAttribute("port", uTeleporterPort);
3121 pelmTeleporter->setAttribute("address", strTeleporterAddress);
3122 pelmTeleporter->setAttribute("password", strTeleporterPassword);
3123 }
3124
3125 writeExtraData(*pelmMachine, mapExtraDataItems);
3126
3127 if (llFirstSnapshot.size())
3128 writeSnapshot(*pelmMachine, llFirstSnapshot.front());
3129
3130 writeHardware(*pelmMachine, hardwareMachine, storageMachine);
3131 writeStorageControllers(*pelmMachine, storageMachine);
3132
3133 // now go write the XML
3134 xml::XmlFileWriter writer(*m->pDoc);
3135 writer.write(m->strFilename.c_str());
3136
3137 m->fFileExists = true;
3138 clearDocument();
3139 }
3140 catch (...)
3141 {
3142 clearDocument();
3143 throw;
3144 }
3145}
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