VirtualBox

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

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

virtio: string mismatch between device and some parts of main.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Revision Author Id
File size: 128.2 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/xml_cpp.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 what(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 what.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 &m,
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(m.uuid));
1096 pelmHardDisk->setAttribute("location", m.strLocation);
1097 pelmHardDisk->setAttribute("format", m.strFormat);
1098 if (m.fAutoReset)
1099 pelmHardDisk->setAttribute("autoReset", m.fAutoReset);
1100 if (m.strDescription.length())
1101 pelmHardDisk->setAttribute("Description", m.strDescription);
1102
1103 for (PropertiesMap::const_iterator it = m.properties.begin();
1104 it != m.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 m.hdType == MediumType_Normal ? "Normal" :
1117 m.hdType == MediumType_Immutable ? "Immutable" :
1118 /*m.hdType == MediumType_Writethrough ?*/ "Writethrough";
1119 pelmHardDisk->setAttribute("type", pcszType);
1120 }
1121
1122 for (MediaList::const_iterator it = m.llChildren.begin();
1123 it != m.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 &m = *it;
1174 xml::ElementNode *pelmMedium = pelmDVDImages->createChild("Image");
1175 pelmMedium->setAttribute("uuid", makeString(m.uuid));
1176 pelmMedium->setAttribute("location", m.strLocation);
1177 if (m.strDescription.length())
1178 pelmMedium->setAttribute("Description", m.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 &m = *it;
1187 xml::ElementNode *pelmMedium = pelmFloppyImages->createChild("Image");
1188 pelmMedium->setAttribute("uuid", makeString(m.uuid));
1189 pelmMedium->setAttribute("location", m.strLocation);
1190 if (m.strDescription.length())
1191 pelmMedium->setAttribute("Description", m.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(false),
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-net")
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
1595 throw ConfigFileError(this,
1596 pelmHwChild,
1597 N_("Invalid value '%s' in Boot/Firmware/@type"),
1598 strFirmwareType.c_str());
1599 }
1600 }
1601 else if (pelmHwChild->nameEquals("Boot"))
1602 {
1603 hw.mapBootOrder.clear();
1604
1605 xml::NodesLoop nl2(*pelmHwChild, "Order");
1606 const xml::ElementNode *pelmOrder;
1607 while ((pelmOrder = nl2.forAllNodes()))
1608 {
1609 uint32_t ulPos;
1610 Utf8Str strDevice;
1611 if (!pelmOrder->getAttributeValue("position", ulPos))
1612 throw ConfigFileError(this, pelmOrder, N_("Required Boot/Order/@position attribute is missing"));
1613
1614 if ( ulPos < 1
1615 || ulPos > SchemaDefs::MaxBootPosition
1616 )
1617 throw ConfigFileError(this,
1618 pelmOrder,
1619 N_("Invalid value '%RU32' in Boot/Order/@position: must be greater than 0 and less than %RU32"),
1620 ulPos,
1621 SchemaDefs::MaxBootPosition + 1);
1622 // XML is 1-based but internal data is 0-based
1623 --ulPos;
1624
1625 if (hw.mapBootOrder.find(ulPos) != hw.mapBootOrder.end())
1626 throw ConfigFileError(this, pelmOrder, N_("Invalid value '%RU32' in Boot/Order/@position: value is not unique"), ulPos);
1627
1628 if (!pelmOrder->getAttributeValue("device", strDevice))
1629 throw ConfigFileError(this, pelmOrder, N_("Required Boot/Order/@device attribute is missing"));
1630
1631 DeviceType_T type;
1632 if (strDevice == "None")
1633 type = DeviceType_Null;
1634 else if (strDevice == "Floppy")
1635 type = DeviceType_Floppy;
1636 else if (strDevice == "DVD")
1637 type = DeviceType_DVD;
1638 else if (strDevice == "HardDisk")
1639 type = DeviceType_HardDisk;
1640 else if (strDevice == "Network")
1641 type = DeviceType_Network;
1642 else
1643 throw ConfigFileError(this, pelmOrder, N_("Invalid value '%s' in Boot/Order/@device attribute"), strDevice.c_str());
1644 hw.mapBootOrder[ulPos] = type;
1645 }
1646 }
1647 else if (pelmHwChild->nameEquals("Display"))
1648 {
1649 pelmHwChild->getAttributeValue("VRAMSize", hw.ulVRAMSizeMB);
1650 if (!pelmHwChild->getAttributeValue("monitorCount", hw.cMonitors))
1651 pelmHwChild->getAttributeValue("MonitorCount", hw.cMonitors); // pre-v1.5 variant
1652 if (!pelmHwChild->getAttributeValue("accelerate3D", hw.fAccelerate3D))
1653 pelmHwChild->getAttributeValue("Accelerate3D", hw.fAccelerate3D); // pre-v1.5 variant
1654 pelmHwChild->getAttributeValue("accelerate2DVideo", hw.fAccelerate2DVideo);
1655 }
1656 else if (pelmHwChild->nameEquals("RemoteDisplay"))
1657 {
1658 pelmHwChild->getAttributeValue("enabled", hw.vrdpSettings.fEnabled);
1659 pelmHwChild->getAttributeValue("port", hw.vrdpSettings.strPort);
1660 pelmHwChild->getAttributeValue("netAddress", hw.vrdpSettings.strNetAddress);
1661
1662 Utf8Str strAuthType;
1663 if (pelmHwChild->getAttributeValue("authType", strAuthType))
1664 {
1665 // settings before 1.3 used lower case so make sure this is case-insensitive
1666 strAuthType.toUpper();
1667 if (strAuthType == "NULL")
1668 hw.vrdpSettings.authType = VRDPAuthType_Null;
1669 else if (strAuthType == "GUEST")
1670 hw.vrdpSettings.authType = VRDPAuthType_Guest;
1671 else if (strAuthType == "EXTERNAL")
1672 hw.vrdpSettings.authType = VRDPAuthType_External;
1673 else
1674 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in RemoteDisplay/@authType attribute"), strAuthType.c_str());
1675 }
1676
1677 pelmHwChild->getAttributeValue("authTimeout", hw.vrdpSettings.ulAuthTimeout);
1678 pelmHwChild->getAttributeValue("allowMultiConnection", hw.vrdpSettings.fAllowMultiConnection);
1679 pelmHwChild->getAttributeValue("reuseSingleConnection", hw.vrdpSettings.fReuseSingleConnection);
1680 }
1681 else if (pelmHwChild->nameEquals("BIOS"))
1682 {
1683 const xml::ElementNode *pelmBIOSChild;
1684 if ((pelmBIOSChild = pelmHwChild->findChildElement("ACPI")))
1685 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fACPIEnabled);
1686 if ((pelmBIOSChild = pelmHwChild->findChildElement("IOAPIC")))
1687 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fIOAPICEnabled);
1688 if ((pelmBIOSChild = pelmHwChild->findChildElement("Logo")))
1689 {
1690 pelmBIOSChild->getAttributeValue("fadeIn", hw.biosSettings.fLogoFadeIn);
1691 pelmBIOSChild->getAttributeValue("fadeOut", hw.biosSettings.fLogoFadeOut);
1692 pelmBIOSChild->getAttributeValue("displayTime", hw.biosSettings.ulLogoDisplayTime);
1693 pelmBIOSChild->getAttributeValue("imagePath", hw.biosSettings.strLogoImagePath);
1694 }
1695 if ((pelmBIOSChild = pelmHwChild->findChildElement("BootMenu")))
1696 {
1697 Utf8Str strBootMenuMode;
1698 if (pelmBIOSChild->getAttributeValue("mode", strBootMenuMode))
1699 {
1700 // settings before 1.3 used lower case so make sure this is case-insensitive
1701 strBootMenuMode.toUpper();
1702 if (strBootMenuMode == "DISABLED")
1703 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_Disabled;
1704 else if (strBootMenuMode == "MENUONLY")
1705 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_MenuOnly;
1706 else if (strBootMenuMode == "MESSAGEANDMENU")
1707 hw.biosSettings.biosBootMenuMode = BIOSBootMenuMode_MessageAndMenu;
1708 else
1709 throw ConfigFileError(this, pelmBIOSChild, N_("Invalid value '%s' in BootMenu/@mode attribute"), strBootMenuMode.c_str());
1710 }
1711 }
1712 if ((pelmBIOSChild = pelmHwChild->findChildElement("PXEDebug")))
1713 pelmBIOSChild->getAttributeValue("enabled", hw.biosSettings.fPXEDebugEnabled);
1714 if ((pelmBIOSChild = pelmHwChild->findChildElement("TimeOffset")))
1715 pelmBIOSChild->getAttributeValue("value", hw.biosSettings.llTimeOffset);
1716
1717 // legacy BIOS/IDEController (pre 1.7)
1718 if ( (m->sv < SettingsVersion_v1_7)
1719 && ((pelmBIOSChild = pelmHwChild->findChildElement("IDEController")))
1720 )
1721 {
1722 StorageController sctl;
1723 sctl.strName = "IDE Controller";
1724 sctl.storageBus = StorageBus_IDE;
1725
1726 Utf8Str strType;
1727 if (pelmBIOSChild->getAttributeValue("type", strType))
1728 {
1729 if (strType == "PIIX3")
1730 sctl.controllerType = StorageControllerType_PIIX3;
1731 else if (strType == "PIIX4")
1732 sctl.controllerType = StorageControllerType_PIIX4;
1733 else if (strType == "ICH6")
1734 sctl.controllerType = StorageControllerType_ICH6;
1735 else
1736 throw ConfigFileError(this, pelmBIOSChild, N_("Invalid value '%s' for IDEController/@type attribute"), strType.c_str());
1737 }
1738 sctl.ulPortCount = 2;
1739 strg.llStorageControllers.push_back(sctl);
1740 }
1741 }
1742 else if (pelmHwChild->nameEquals("USBController"))
1743 {
1744 pelmHwChild->getAttributeValue("enabled", hw.usbController.fEnabled);
1745 pelmHwChild->getAttributeValue("enabledEhci", hw.usbController.fEnabledEHCI);
1746
1747 readUSBDeviceFilters(*pelmHwChild,
1748 hw.usbController.llDeviceFilters);
1749 }
1750 else if ( (m->sv < SettingsVersion_v1_7)
1751 && (pelmHwChild->nameEquals("SATAController"))
1752 )
1753 {
1754 bool f;
1755 if ( (pelmHwChild->getAttributeValue("enabled", f))
1756 && (f)
1757 )
1758 {
1759 StorageController sctl;
1760 sctl.strName = "SATA Controller";
1761 sctl.storageBus = StorageBus_SATA;
1762 sctl.controllerType = StorageControllerType_IntelAhci;
1763
1764 readStorageControllerAttributes(*pelmHwChild, sctl);
1765
1766 strg.llStorageControllers.push_back(sctl);
1767 }
1768 }
1769 else if (pelmHwChild->nameEquals("Network"))
1770 readNetworkAdapters(*pelmHwChild, hw.llNetworkAdapters);
1771 else if ( (pelmHwChild->nameEquals("UART"))
1772 || (pelmHwChild->nameEquals("Uart")) // used before 1.3
1773 )
1774 readSerialPorts(*pelmHwChild, hw.llSerialPorts);
1775 else if ( (pelmHwChild->nameEquals("LPT"))
1776 || (pelmHwChild->nameEquals("Lpt")) // used before 1.3
1777 )
1778 readParallelPorts(*pelmHwChild, hw.llParallelPorts);
1779 else if (pelmHwChild->nameEquals("AudioAdapter"))
1780 {
1781 pelmHwChild->getAttributeValue("enabled", hw.audioAdapter.fEnabled);
1782
1783 Utf8Str strTemp;
1784 if (pelmHwChild->getAttributeValue("controller", strTemp))
1785 {
1786 if (strTemp == "SB16")
1787 hw.audioAdapter.controllerType = AudioControllerType_SB16;
1788 else if (strTemp == "AC97")
1789 hw.audioAdapter.controllerType = AudioControllerType_AC97;
1790 else
1791 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in AudioAdapter/@controller attribute"), strTemp.c_str());
1792 }
1793 if (pelmHwChild->getAttributeValue("driver", strTemp))
1794 {
1795 // settings before 1.3 used lower case so make sure this is case-insensitive
1796 strTemp.toUpper();
1797 if (strTemp == "NULL")
1798 hw.audioAdapter.driverType = AudioDriverType_Null;
1799 else if (strTemp == "WINMM")
1800 hw.audioAdapter.driverType = AudioDriverType_WinMM;
1801 else if ( (strTemp == "DIRECTSOUND") || (strTemp == "DSOUND") )
1802 hw.audioAdapter.driverType = AudioDriverType_DirectSound;
1803 else if (strTemp == "SOLAUDIO")
1804 hw.audioAdapter.driverType = AudioDriverType_SolAudio;
1805 else if (strTemp == "ALSA")
1806 hw.audioAdapter.driverType = AudioDriverType_ALSA;
1807 else if (strTemp == "PULSE")
1808 hw.audioAdapter.driverType = AudioDriverType_Pulse;
1809 else if (strTemp == "OSS")
1810 hw.audioAdapter.driverType = AudioDriverType_OSS;
1811 else if (strTemp == "COREAUDIO")
1812 hw.audioAdapter.driverType = AudioDriverType_CoreAudio;
1813 else if (strTemp == "MMPM")
1814 hw.audioAdapter.driverType = AudioDriverType_MMPM;
1815 else
1816 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in AudioAdapter/@driver attribute"), strTemp.c_str());
1817 }
1818 }
1819 else if (pelmHwChild->nameEquals("SharedFolders"))
1820 {
1821 xml::NodesLoop nl2(*pelmHwChild, "SharedFolder");
1822 const xml::ElementNode *pelmFolder;
1823 while ((pelmFolder = nl2.forAllNodes()))
1824 {
1825 SharedFolder sf;
1826 pelmFolder->getAttributeValue("name", sf.strName);
1827 pelmFolder->getAttributeValue("hostPath", sf.strHostPath);
1828 pelmFolder->getAttributeValue("writable", sf.fWritable);
1829 hw.llSharedFolders.push_back(sf);
1830 }
1831 }
1832 else if (pelmHwChild->nameEquals("Clipboard"))
1833 {
1834 Utf8Str strTemp;
1835 if (pelmHwChild->getAttributeValue("mode", strTemp))
1836 {
1837 if (strTemp == "Disabled")
1838 hw.clipboardMode = ClipboardMode_Disabled;
1839 else if (strTemp == "HostToGuest")
1840 hw.clipboardMode = ClipboardMode_HostToGuest;
1841 else if (strTemp == "GuestToHost")
1842 hw.clipboardMode = ClipboardMode_GuestToHost;
1843 else if (strTemp == "Bidirectional")
1844 hw.clipboardMode = ClipboardMode_Bidirectional;
1845 else
1846 throw ConfigFileError(this, pelmHwChild, N_("Invalid value '%s' in Clipbord/@mode attribute"), strTemp.c_str());
1847 }
1848 }
1849 else if (pelmHwChild->nameEquals("Guest"))
1850 {
1851 if (!pelmHwChild->getAttributeValue("memoryBalloonSize", hw.ulMemoryBalloonSize))
1852 pelmHwChild->getAttributeValue("MemoryBalloonSize", hw.ulMemoryBalloonSize); // used before 1.3
1853 if (!pelmHwChild->getAttributeValue("statisticsUpdateInterval", hw.ulStatisticsUpdateInterval))
1854 pelmHwChild->getAttributeValue("StatisticsUpdateInterval", hw.ulStatisticsUpdateInterval);
1855 }
1856 else if (pelmHwChild->nameEquals("GuestProperties"))
1857 readGuestProperties(*pelmHwChild, hw);
1858 }
1859
1860 if (hw.ulMemorySizeMB == (uint32_t)-1)
1861 throw ConfigFileError(this, &elmHardware, N_("Required Memory/@RAMSize element/attribute is missing"));
1862}
1863
1864/**
1865 * This gets called instead of readStorageControllers() for legacy pre-1.7 settings
1866 * files which have a <HardDiskAttachments> node and storage controller settings
1867 * hidden in the <Hardware> settings. We set the StorageControllers fields just the
1868 * same, just from different sources.
1869 * @param elmHardware <Hardware> XML node.
1870 * @param elmHardDiskAttachments <HardDiskAttachments> XML node.
1871 * @param strg
1872 */
1873void MachineConfigFile::readHardDiskAttachments_pre1_7(const xml::ElementNode &elmHardDiskAttachments,
1874 Storage &strg)
1875{
1876 StorageController *pIDEController = NULL;
1877 StorageController *pSATAController = NULL;
1878
1879 for (StorageControllersList::iterator it = strg.llStorageControllers.begin();
1880 it != strg.llStorageControllers.end();
1881 ++it)
1882 {
1883 StorageController &s = *it;
1884 if (s.storageBus == StorageBus_IDE)
1885 pIDEController = &s;
1886 else if (s.storageBus == StorageBus_SATA)
1887 pSATAController = &s;
1888 }
1889
1890 xml::NodesLoop nl1(elmHardDiskAttachments, "HardDiskAttachment");
1891 const xml::ElementNode *pelmAttachment;
1892 while ((pelmAttachment = nl1.forAllNodes()))
1893 {
1894 AttachedDevice att;
1895 Utf8Str strUUID, strBus;
1896
1897 if (!pelmAttachment->getAttributeValue("hardDisk", strUUID))
1898 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@hardDisk attribute is missing"));
1899 parseUUID(att.uuid, strUUID);
1900
1901 if (!pelmAttachment->getAttributeValue("bus", strBus))
1902 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@bus attribute is missing"));
1903 // pre-1.7 'channel' is now port
1904 if (!pelmAttachment->getAttributeValue("channel", att.lPort))
1905 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@channel attribute is missing"));
1906 // pre-1.7 'device' is still device
1907 if (!pelmAttachment->getAttributeValue("device", att.lDevice))
1908 throw ConfigFileError(this, pelmAttachment, N_("Required HardDiskAttachment/@device attribute is missing"));
1909
1910 att.deviceType = DeviceType_HardDisk;
1911
1912 if (strBus == "IDE")
1913 {
1914 if (!pIDEController)
1915 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus is 'IDE' but cannot find IDE controller"));
1916 pIDEController->llAttachedDevices.push_back(att);
1917 }
1918 else if (strBus == "SATA")
1919 {
1920 if (!pSATAController)
1921 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus is 'SATA' but cannot find SATA controller"));
1922 pSATAController->llAttachedDevices.push_back(att);
1923 }
1924 else
1925 throw ConfigFileError(this, pelmAttachment, N_("HardDiskAttachment/@bus attribute has illegal value '%s'"), strBus.c_str());
1926 }
1927}
1928
1929/**
1930 * Reads in a <StorageControllers> block and stores it in the given Storage structure.
1931 * Used both directly from readMachine and from readSnapshot, since snapshots
1932 * have their own storage controllers sections.
1933 *
1934 * This is only called for settings version 1.7 and above; see readHardDiskAttachments_pre1_7()
1935 * for earlier versions.
1936 *
1937 * @param elmStorageControllers
1938 */
1939void MachineConfigFile::readStorageControllers(const xml::ElementNode &elmStorageControllers,
1940 Storage &strg)
1941{
1942 xml::NodesLoop nlStorageControllers(elmStorageControllers, "StorageController");
1943 const xml::ElementNode *pelmController;
1944 while ((pelmController = nlStorageControllers.forAllNodes()))
1945 {
1946 StorageController sctl;
1947
1948 if (!pelmController->getAttributeValue("name", sctl.strName))
1949 throw ConfigFileError(this, pelmController, N_("Required StorageController/@name attribute is missing"));
1950 // canonicalize storage controller names for configs in the switchover
1951 // period.
1952 if (m->sv <= SettingsVersion_v1_9)
1953 {
1954 if (sctl.strName == "IDE")
1955 sctl.strName = "IDE Controller";
1956 else if (sctl.strName == "SATA")
1957 sctl.strName = "SATA Controller";
1958 else if (sctl.strName == "SCSI")
1959 sctl.strName = "SCSI Controller";
1960 }
1961
1962 pelmController->getAttributeValue("Instance", sctl.ulInstance);
1963 // default from constructor is 0
1964
1965 Utf8Str strType;
1966 if (!pelmController->getAttributeValue("type", strType))
1967 throw ConfigFileError(this, pelmController, N_("Required StorageController/@type attribute is missing"));
1968
1969 if (strType == "AHCI")
1970 {
1971 sctl.storageBus = StorageBus_SATA;
1972 sctl.controllerType = StorageControllerType_IntelAhci;
1973 }
1974 else if (strType == "LsiLogic")
1975 {
1976 sctl.storageBus = StorageBus_SCSI;
1977 sctl.controllerType = StorageControllerType_LsiLogic;
1978 }
1979 else if (strType == "BusLogic")
1980 {
1981 sctl.storageBus = StorageBus_SCSI;
1982 sctl.controllerType = StorageControllerType_BusLogic;
1983 }
1984 else if (strType == "PIIX3")
1985 {
1986 sctl.storageBus = StorageBus_IDE;
1987 sctl.controllerType = StorageControllerType_PIIX3;
1988 }
1989 else if (strType == "PIIX4")
1990 {
1991 sctl.storageBus = StorageBus_IDE;
1992 sctl.controllerType = StorageControllerType_PIIX4;
1993 }
1994 else if (strType == "ICH6")
1995 {
1996 sctl.storageBus = StorageBus_IDE;
1997 sctl.controllerType = StorageControllerType_ICH6;
1998 }
1999 else if ( (m->sv >= SettingsVersion_v1_9)
2000 && (strType == "I82078")
2001 )
2002 {
2003 sctl.storageBus = StorageBus_Floppy;
2004 sctl.controllerType = StorageControllerType_I82078;
2005 }
2006 else
2007 throw ConfigFileError(this, pelmController, N_("Invalid value '%s' for StorageController/@type attribute"), strType.c_str());
2008
2009 readStorageControllerAttributes(*pelmController, sctl);
2010
2011 xml::NodesLoop nlAttached(*pelmController, "AttachedDevice");
2012 const xml::ElementNode *pelmAttached;
2013 while ((pelmAttached = nlAttached.forAllNodes()))
2014 {
2015 AttachedDevice att;
2016 Utf8Str strTemp;
2017 pelmAttached->getAttributeValue("type", strTemp);
2018
2019 if (strTemp == "HardDisk")
2020 att.deviceType = DeviceType_HardDisk;
2021 else if (m->sv >= SettingsVersion_v1_9)
2022 {
2023 // starting with 1.9 we list DVD and floppy drive info + attachments under <StorageControllers>
2024 if (strTemp == "DVD")
2025 {
2026 att.deviceType = DeviceType_DVD;
2027 pelmAttached->getAttributeValue("passthrough", att.fPassThrough);
2028 }
2029 else if (strTemp == "Floppy")
2030 att.deviceType = DeviceType_Floppy;
2031 }
2032
2033 if (att.deviceType != DeviceType_Null)
2034 {
2035 const xml::ElementNode *pelmImage;
2036 // all types can have images attached, but for HardDisk it's required
2037 if (!(pelmImage = pelmAttached->findChildElement("Image")))
2038 {
2039 if (att.deviceType == DeviceType_HardDisk)
2040 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/Image element is missing"));
2041 else
2042 {
2043 // DVDs and floppies can also have <HostDrive> instead of <Image>
2044 const xml::ElementNode *pelmHostDrive;
2045 if ((pelmHostDrive = pelmAttached->findChildElement("HostDrive")))
2046 if (!pelmHostDrive->getAttributeValue("src", att.strHostDriveSrc))
2047 throw ConfigFileError(this, pelmHostDrive, N_("Required AttachedDevice/HostDrive/@src attribute is missing"));
2048 }
2049 }
2050 else
2051 {
2052 if (!pelmImage->getAttributeValue("uuid", strTemp))
2053 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/Image/@uuid attribute is missing"));
2054 parseUUID(att.uuid, strTemp);
2055 }
2056
2057 if (!pelmAttached->getAttributeValue("port", att.lPort))
2058 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/@port attribute is missing"));
2059 if (!pelmAttached->getAttributeValue("device", att.lDevice))
2060 throw ConfigFileError(this, pelmImage, N_("Required AttachedDevice/@device attribute is missing"));
2061
2062 sctl.llAttachedDevices.push_back(att);
2063 }
2064 }
2065
2066 strg.llStorageControllers.push_back(sctl);
2067 }
2068}
2069
2070/**
2071 * This gets called for legacy pre-1.9 settings files after having parsed the
2072 * <Hardware> and <StorageControllers> sections to parse <Hardware> once more
2073 * for the <DVDDrive> and <FloppyDrive> sections.
2074 *
2075 * Before settings version 1.9, DVD and floppy drives were specified separately
2076 * under <Hardware>; we then need this extra loop to make sure the storage
2077 * controller structs are already set up so we can add stuff to them.
2078 *
2079 * @param elmHardware
2080 * @param strg
2081 */
2082void MachineConfigFile::readDVDAndFloppies_pre1_9(const xml::ElementNode &elmHardware,
2083 Storage &strg)
2084{
2085 xml::NodesLoop nl1(elmHardware);
2086 const xml::ElementNode *pelmHwChild;
2087 while ((pelmHwChild = nl1.forAllNodes()))
2088 {
2089 if (pelmHwChild->nameEquals("DVDDrive"))
2090 {
2091 // create a DVD "attached device" and attach it to the existing IDE controller
2092 AttachedDevice att;
2093 att.deviceType = DeviceType_DVD;
2094 // legacy DVD drive is always secondary master (port 1, device 0)
2095 att.lPort = 1;
2096 att.lDevice = 0;
2097 pelmHwChild->getAttributeValue("passthrough", att.fPassThrough);
2098
2099 const xml::ElementNode *pDriveChild;
2100 Utf8Str strTmp;
2101 if ( ((pDriveChild = pelmHwChild->findChildElement("Image")))
2102 && (pDriveChild->getAttributeValue("uuid", strTmp))
2103 )
2104 parseUUID(att.uuid, strTmp);
2105 else if ((pDriveChild = pelmHwChild->findChildElement("HostDrive")))
2106 pDriveChild->getAttributeValue("src", att.strHostDriveSrc);
2107
2108 // find the IDE controller and attach the DVD drive
2109 bool fFound = false;
2110 for (StorageControllersList::iterator it = strg.llStorageControllers.begin();
2111 it != strg.llStorageControllers.end();
2112 ++it)
2113 {
2114 StorageController &sctl = *it;
2115 if (sctl.storageBus == StorageBus_IDE)
2116 {
2117 sctl.llAttachedDevices.push_back(att);
2118 fFound = true;
2119 break;
2120 }
2121 }
2122
2123 if (!fFound)
2124 throw ConfigFileError(this, pelmHwChild, N_("Internal error: found DVD drive but IDE controller does not exist"));
2125 // shouldn't happen because pre-1.9 settings files always had at least one IDE controller in the settings
2126 // which should have gotten parsed in <StorageControllers> before this got called
2127 }
2128 else if (pelmHwChild->nameEquals("FloppyDrive"))
2129 {
2130 bool fEnabled;
2131 if ( (pelmHwChild->getAttributeValue("enabled", fEnabled))
2132 && (fEnabled)
2133 )
2134 {
2135 // create a new floppy controller and attach a floppy "attached device"
2136 StorageController sctl;
2137 sctl.strName = "Floppy Controller";
2138 sctl.storageBus = StorageBus_Floppy;
2139 sctl.controllerType = StorageControllerType_I82078;
2140 sctl.ulPortCount = 1;
2141
2142 AttachedDevice att;
2143 att.deviceType = DeviceType_Floppy;
2144 att.lPort = 0;
2145 att.lDevice = 0;
2146
2147 const xml::ElementNode *pDriveChild;
2148 Utf8Str strTmp;
2149 if ( ((pDriveChild = pelmHwChild->findChildElement("Image")))
2150 && (pDriveChild->getAttributeValue("uuid", strTmp))
2151 )
2152 parseUUID(att.uuid, strTmp);
2153 else if ((pDriveChild = pelmHwChild->findChildElement("HostDrive")))
2154 pDriveChild->getAttributeValue("src", att.strHostDriveSrc);
2155
2156 // store attachment with controller
2157 sctl.llAttachedDevices.push_back(att);
2158 // store controller with storage
2159 strg.llStorageControllers.push_back(sctl);
2160 }
2161 }
2162 }
2163}
2164
2165/**
2166 * Called initially for the <Snapshot> element under <Machine>, if present,
2167 * to store the snapshot's data into the given Snapshot structure (which is
2168 * then the one in the Machine struct). This might then recurse if
2169 * a <Snapshots> (plural) element is found in the snapshot, which should
2170 * contain a list of child snapshots; such lists are maintained in the
2171 * Snapshot structure.
2172 *
2173 * @param elmSnapshot
2174 * @param snap
2175 */
2176void MachineConfigFile::readSnapshot(const xml::ElementNode &elmSnapshot,
2177 Snapshot &snap)
2178{
2179 Utf8Str strTemp;
2180
2181 if (!elmSnapshot.getAttributeValue("uuid", strTemp))
2182 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@uuid attribute is missing"));
2183 parseUUID(snap.uuid, strTemp);
2184
2185 if (!elmSnapshot.getAttributeValue("name", snap.strName))
2186 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@name attribute is missing"));
2187
2188 // earlier 3.1 trunk builds had a bug and added Description as an attribute, read it silently and write it back as an element
2189 elmSnapshot.getAttributeValue("Description", snap.strDescription);
2190
2191 if (!elmSnapshot.getAttributeValue("timeStamp", strTemp))
2192 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@timeStamp attribute is missing"));
2193 parseTimestamp(snap.timestamp, strTemp);
2194
2195 elmSnapshot.getAttributeValue("stateFile", snap.strStateFile); // online snapshots only
2196
2197 // parse Hardware before the other elements because other things depend on it
2198 const xml::ElementNode *pelmHardware;
2199 if (!(pelmHardware = elmSnapshot.findChildElement("Hardware")))
2200 throw ConfigFileError(this, &elmSnapshot, N_("Required Snapshot/@Hardware element is missing"));
2201 readHardware(*pelmHardware, snap.hardware, snap.storage);
2202
2203 xml::NodesLoop nlSnapshotChildren(elmSnapshot);
2204 const xml::ElementNode *pelmSnapshotChild;
2205 while ((pelmSnapshotChild = nlSnapshotChildren.forAllNodes()))
2206 {
2207 if (pelmSnapshotChild->nameEquals("Description"))
2208 snap.strDescription = pelmSnapshotChild->getValue();
2209 else if ( (m->sv < SettingsVersion_v1_7)
2210 && (pelmSnapshotChild->nameEquals("HardDiskAttachments"))
2211 )
2212 readHardDiskAttachments_pre1_7(*pelmSnapshotChild, snap.storage);
2213 else if ( (m->sv >= SettingsVersion_v1_7)
2214 && (pelmSnapshotChild->nameEquals("StorageControllers"))
2215 )
2216 readStorageControllers(*pelmSnapshotChild, snap.storage);
2217 else if (pelmSnapshotChild->nameEquals("Snapshots"))
2218 {
2219 xml::NodesLoop nlChildSnapshots(*pelmSnapshotChild);
2220 const xml::ElementNode *pelmChildSnapshot;
2221 while ((pelmChildSnapshot = nlChildSnapshots.forAllNodes()))
2222 {
2223 if (pelmChildSnapshot->nameEquals("Snapshot"))
2224 {
2225 Snapshot child;
2226 readSnapshot(*pelmChildSnapshot, child);
2227 snap.llChildSnapshots.push_back(child);
2228 }
2229 }
2230 }
2231 }
2232
2233 if (m->sv < SettingsVersion_v1_9)
2234 // go through Hardware once more to repair the settings controller structures
2235 // with data from old DVDDrive and FloppyDrive elements
2236 readDVDAndFloppies_pre1_9(*pelmHardware, snap.storage);
2237}
2238
2239void MachineConfigFile::convertOldOSType_pre1_5(Utf8Str &str)
2240{
2241 if (str == "unknown") str = "Other";
2242 else if (str == "dos") str = "DOS";
2243 else if (str == "win31") str = "Windows31";
2244 else if (str == "win95") str = "Windows95";
2245 else if (str == "win98") str = "Windows98";
2246 else if (str == "winme") str = "WindowsMe";
2247 else if (str == "winnt4") str = "WindowsNT4";
2248 else if (str == "win2k") str = "Windows2000";
2249 else if (str == "winxp") str = "WindowsXP";
2250 else if (str == "win2k3") str = "Windows2003";
2251 else if (str == "winvista") str = "WindowsVista";
2252 else if (str == "win2k8") str = "Windows2008";
2253 else if (str == "os2warp3") str = "OS2Warp3";
2254 else if (str == "os2warp4") str = "OS2Warp4";
2255 else if (str == "os2warp45") str = "OS2Warp45";
2256 else if (str == "ecs") str = "OS2eCS";
2257 else if (str == "linux22") str = "Linux22";
2258 else if (str == "linux24") str = "Linux24";
2259 else if (str == "linux26") str = "Linux26";
2260 else if (str == "archlinux") str = "ArchLinux";
2261 else if (str == "debian") str = "Debian";
2262 else if (str == "opensuse") str = "OpenSUSE";
2263 else if (str == "fedoracore") str = "Fedora";
2264 else if (str == "gentoo") str = "Gentoo";
2265 else if (str == "mandriva") str = "Mandriva";
2266 else if (str == "redhat") str = "RedHat";
2267 else if (str == "ubuntu") str = "Ubuntu";
2268 else if (str == "xandros") str = "Xandros";
2269 else if (str == "freebsd") str = "FreeBSD";
2270 else if (str == "openbsd") str = "OpenBSD";
2271 else if (str == "netbsd") str = "NetBSD";
2272 else if (str == "netware") str = "Netware";
2273 else if (str == "solaris") str = "Solaris";
2274 else if (str == "opensolaris") str = "OpenSolaris";
2275 else if (str == "l4") str = "L4";
2276}
2277
2278/**
2279 * Called from the constructor to actually read in the <Machine> element
2280 * of a machine config file.
2281 * @param elmMachine
2282 */
2283void MachineConfigFile::readMachine(const xml::ElementNode &elmMachine)
2284{
2285 Utf8Str strUUID;
2286 if ( (elmMachine.getAttributeValue("uuid", strUUID))
2287 && (elmMachine.getAttributeValue("name", strName))
2288 )
2289 {
2290 parseUUID(uuid, strUUID);
2291
2292 if (!elmMachine.getAttributeValue("nameSync", fNameSync))
2293 fNameSync = true;
2294
2295 Utf8Str str;
2296 elmMachine.getAttributeValue("Description", strDescription);
2297
2298 elmMachine.getAttributeValue("OSType", strOsType);
2299 if (m->sv < SettingsVersion_v1_5)
2300 convertOldOSType_pre1_5(strOsType);
2301
2302 elmMachine.getAttributeValue("stateFile", strStateFile);
2303 if (elmMachine.getAttributeValue("currentSnapshot", str))
2304 parseUUID(uuidCurrentSnapshot, str);
2305 elmMachine.getAttributeValue("snapshotFolder", strSnapshotFolder);
2306 if (!elmMachine.getAttributeValue("currentStateModified", fCurrentStateModified))
2307 fCurrentStateModified = true;
2308 if (elmMachine.getAttributeValue("lastStateChange", str))
2309 parseTimestamp(timeLastStateChange, str);
2310 // constructor has called RTTimeNow(&timeLastStateChange) before
2311
2312#if 1 /** @todo Teleportation: Obsolete. Remove in a couple of days. */
2313 if (!elmMachine.getAttributeValue("teleporterEnabled", fTeleporterEnabled)
2314 && !elmMachine.getAttributeValue("liveMigrationTarget", fTeleporterEnabled))
2315 fTeleporterEnabled = false;
2316 if (!elmMachine.getAttributeValue("teleporterPort", uTeleporterPort)
2317 && !elmMachine.getAttributeValue("liveMigrationPort", uTeleporterPort))
2318 uTeleporterPort = 0;
2319 if (!elmMachine.getAttributeValue("teleporterAddress", strTeleporterAddress))
2320 strTeleporterAddress = "";
2321 if (!elmMachine.getAttributeValue("teleporterPassword", strTeleporterPassword)
2322 && !elmMachine.getAttributeValue("liveMigrationPassword", strTeleporterPassword))
2323 strTeleporterPassword = "";
2324#endif
2325
2326 // parse Hardware before the other elements because other things depend on it
2327 const xml::ElementNode *pelmHardware;
2328 if (!(pelmHardware = elmMachine.findChildElement("Hardware")))
2329 throw ConfigFileError(this, &elmMachine, N_("Required Machine/Hardware element is missing"));
2330 readHardware(*pelmHardware, hardwareMachine, storageMachine);
2331
2332 xml::NodesLoop nlRootChildren(elmMachine);
2333 const xml::ElementNode *pelmMachineChild;
2334 while ((pelmMachineChild = nlRootChildren.forAllNodes()))
2335 {
2336 if (pelmMachineChild->nameEquals("ExtraData"))
2337 readExtraData(*pelmMachineChild,
2338 mapExtraDataItems);
2339 else if ( (m->sv < SettingsVersion_v1_7)
2340 && (pelmMachineChild->nameEquals("HardDiskAttachments"))
2341 )
2342 readHardDiskAttachments_pre1_7(*pelmMachineChild, storageMachine);
2343 else if ( (m->sv >= SettingsVersion_v1_7)
2344 && (pelmMachineChild->nameEquals("StorageControllers"))
2345 )
2346 readStorageControllers(*pelmMachineChild, storageMachine);
2347 else if (pelmMachineChild->nameEquals("Snapshot"))
2348 {
2349 Snapshot snap;
2350 // this will recurse into child snapshots, if necessary
2351 readSnapshot(*pelmMachineChild, snap);
2352 llFirstSnapshot.push_back(snap);
2353 }
2354 else if (pelmMachineChild->nameEquals("Description"))
2355 strDescription = pelmMachineChild->getValue();
2356 else if (pelmMachineChild->nameEquals("Teleporter"))
2357 {
2358 if (!pelmMachineChild->getAttributeValue("enabled", fTeleporterEnabled))
2359 fTeleporterEnabled = false;
2360 if (!pelmMachineChild->getAttributeValue("port", uTeleporterPort))
2361 uTeleporterPort = 0;
2362 if (!pelmMachineChild->getAttributeValue("address", strTeleporterAddress))
2363 strTeleporterAddress = "";
2364 if (!pelmMachineChild->getAttributeValue("password", strTeleporterPassword))
2365 strTeleporterPassword = "";
2366 }
2367 }
2368
2369 if (m->sv < SettingsVersion_v1_9)
2370 // go through Hardware once more to repair the settings controller structures
2371 // with data from old DVDDrive and FloppyDrive elements
2372 readDVDAndFloppies_pre1_9(*pelmHardware, storageMachine);
2373 }
2374 else
2375 throw ConfigFileError(this, &elmMachine, N_("Required Machine/@uuid or @name attributes is missing"));
2376}
2377
2378////////////////////////////////////////////////////////////////////////////////
2379//
2380// MachineConfigFile
2381//
2382////////////////////////////////////////////////////////////////////////////////
2383
2384/**
2385 * Constructor.
2386 *
2387 * If pstrFilename is != NULL, this reads the given settings file into the member
2388 * variables and various substructures and lists. Otherwise, the member variables
2389 * are initialized with default values.
2390 *
2391 * Throws variants of xml::Error for I/O, XML and logical content errors, which
2392 * the caller should catch; if this constructor does not throw, then the member
2393 * variables contain meaningful values (either from the file or defaults).
2394 *
2395 * @param strFilename
2396 */
2397MachineConfigFile::MachineConfigFile(const Utf8Str *pstrFilename)
2398 : ConfigFileBase(pstrFilename),
2399 fNameSync(true),
2400 fTeleporterEnabled(false),
2401 uTeleporterPort(0),
2402 fCurrentStateModified(true),
2403 fAborted(false)
2404{
2405 RTTimeNow(&timeLastStateChange);
2406
2407 if (pstrFilename)
2408 {
2409 // the ConfigFileBase constructor has loaded the XML file, so now
2410 // we need only analyze what is in there
2411
2412 xml::NodesLoop nlRootChildren(*m->pelmRoot);
2413 const xml::ElementNode *pelmRootChild;
2414 while ((pelmRootChild = nlRootChildren.forAllNodes()))
2415 {
2416 if (pelmRootChild->nameEquals("Machine"))
2417 readMachine(*pelmRootChild);
2418 }
2419
2420 // clean up memory allocated by XML engine
2421 clearDocument();
2422 }
2423}
2424
2425/**
2426 * Creates a <Hardware> node under elmParent and then writes out the XML
2427 * keys under that. Called for both the <Machine> node and for snapshots.
2428 * @param elmParent
2429 * @param st
2430 */
2431void MachineConfigFile::writeHardware(xml::ElementNode &elmParent,
2432 const Hardware &hw,
2433 const Storage &strg)
2434{
2435 xml::ElementNode *pelmHardware = elmParent.createChild("Hardware");
2436
2437 if (m->sv >= SettingsVersion_v1_4)
2438 pelmHardware->setAttribute("version", hw.strVersion);
2439 if ( (m->sv >= SettingsVersion_v1_9)
2440 && (!hw.uuid.isEmpty())
2441 )
2442 pelmHardware->setAttribute("uuid", makeString(hw.uuid));
2443
2444 xml::ElementNode *pelmCPU = pelmHardware->createChild("CPU");
2445
2446 xml::ElementNode *pelmHwVirtEx = pelmCPU->createChild("HardwareVirtEx");
2447 pelmHwVirtEx->setAttribute("enabled", hw.fHardwareVirt);
2448 if (m->sv >= SettingsVersion_v1_9)
2449 pelmHwVirtEx->setAttribute("exclusive", hw.fHardwareVirtExclusive);
2450
2451 pelmCPU->createChild("HardwareVirtExNestedPaging")->setAttribute("enabled", hw.fNestedPaging);
2452 pelmCPU->createChild("HardwareVirtExVPID")->setAttribute("enabled", hw.fVPID);
2453 pelmCPU->createChild("PAE")->setAttribute("enabled", hw.fPAE);
2454
2455 if (hw.fSyntheticCpu)
2456 pelmCPU->createChild("SyntheticCpu")->setAttribute("enabled", hw.fSyntheticCpu);
2457 pelmCPU->setAttribute("count", hw.cCPUs);
2458 xml::ElementNode *pelmCpuIdTree = pelmCPU->createChild("CpuIdTree");
2459 for (CpuIdLeafsList::const_iterator it = hw.llCpuIdLeafs.begin();
2460 it != hw.llCpuIdLeafs.end();
2461 ++it)
2462 {
2463 const CpuIdLeaf &leaf = *it;
2464
2465 xml::ElementNode *pelmCpuIdLeaf = pelmCpuIdTree->createChild("CpuIdLeaf");
2466 pelmCpuIdLeaf->setAttribute("id", leaf.ulId);
2467 pelmCpuIdLeaf->setAttribute("eax", leaf.ulEax);
2468 pelmCpuIdLeaf->setAttribute("ebx", leaf.ulEbx);
2469 pelmCpuIdLeaf->setAttribute("ecx", leaf.ulEcx);
2470 pelmCpuIdLeaf->setAttribute("edx", leaf.ulEdx);
2471 }
2472
2473 xml::ElementNode *pelmMemory = pelmHardware->createChild("Memory");
2474 pelmMemory->setAttribute("RAMSize", hw.ulMemorySizeMB);
2475
2476 if ( (m->sv >= SettingsVersion_v1_9)
2477 && (hw.firmwareType == FirmwareType_EFI)
2478 )
2479 {
2480 xml::ElementNode *pelmFirmware = pelmHardware->createChild("Firmware");
2481 pelmFirmware->setAttribute("type", "EFI");
2482 }
2483
2484 xml::ElementNode *pelmBoot = pelmHardware->createChild("Boot");
2485 for (BootOrderMap::const_iterator it = hw.mapBootOrder.begin();
2486 it != hw.mapBootOrder.end();
2487 ++it)
2488 {
2489 uint32_t i = it->first;
2490 DeviceType_T type = it->second;
2491 const char *pcszDevice;
2492
2493 switch (type)
2494 {
2495 case DeviceType_Floppy: pcszDevice = "Floppy"; break;
2496 case DeviceType_DVD: pcszDevice = "DVD"; break;
2497 case DeviceType_HardDisk: pcszDevice = "HardDisk"; break;
2498 case DeviceType_Network: pcszDevice = "Network"; break;
2499 default: /*case DeviceType_Null:*/ pcszDevice = "None"; break;
2500 }
2501
2502 xml::ElementNode *pelmOrder = pelmBoot->createChild("Order");
2503 pelmOrder->setAttribute("position",
2504 i + 1); // XML is 1-based but internal data is 0-based
2505 pelmOrder->setAttribute("device", pcszDevice);
2506 }
2507
2508 xml::ElementNode *pelmDisplay = pelmHardware->createChild("Display");
2509 pelmDisplay->setAttribute("VRAMSize", hw.ulVRAMSizeMB);
2510 pelmDisplay->setAttribute("monitorCount", hw.cMonitors);
2511 pelmDisplay->setAttribute("accelerate3D", hw.fAccelerate3D);
2512
2513 if (m->sv >= SettingsVersion_v1_8)
2514 pelmDisplay->setAttribute("accelerate2DVideo", hw.fAccelerate2DVideo);
2515
2516 xml::ElementNode *pelmVRDP = pelmHardware->createChild("RemoteDisplay");
2517 pelmVRDP->setAttribute("enabled", hw.vrdpSettings.fEnabled);
2518 pelmVRDP->setAttribute("port", hw.vrdpSettings.strPort);
2519 if (hw.vrdpSettings.strNetAddress.length())
2520 pelmVRDP->setAttribute("netAddress", hw.vrdpSettings.strNetAddress);
2521 const char *pcszAuthType;
2522 switch (hw.vrdpSettings.authType)
2523 {
2524 case VRDPAuthType_Guest: pcszAuthType = "Guest"; break;
2525 case VRDPAuthType_External: pcszAuthType = "External"; break;
2526 default: /*case VRDPAuthType_Null:*/ pcszAuthType = "Null"; break;
2527 }
2528 pelmVRDP->setAttribute("authType", pcszAuthType);
2529
2530 if (hw.vrdpSettings.ulAuthTimeout != 0)
2531 pelmVRDP->setAttribute("authTimeout", hw.vrdpSettings.ulAuthTimeout);
2532 if (hw.vrdpSettings.fAllowMultiConnection)
2533 pelmVRDP->setAttribute("allowMultiConnection", hw.vrdpSettings.fAllowMultiConnection);
2534 if (hw.vrdpSettings.fReuseSingleConnection)
2535 pelmVRDP->setAttribute("reuseSingleConnection", hw.vrdpSettings.fReuseSingleConnection);
2536
2537 xml::ElementNode *pelmBIOS = pelmHardware->createChild("BIOS");
2538 pelmBIOS->createChild("ACPI")->setAttribute("enabled", hw.biosSettings.fACPIEnabled);
2539 pelmBIOS->createChild("IOAPIC")->setAttribute("enabled", hw.biosSettings.fIOAPICEnabled);
2540
2541 xml::ElementNode *pelmLogo = pelmBIOS->createChild("Logo");
2542 pelmLogo->setAttribute("fadeIn", hw.biosSettings.fLogoFadeIn);
2543 pelmLogo->setAttribute("fadeOut", hw.biosSettings.fLogoFadeOut);
2544 pelmLogo->setAttribute("displayTime", hw.biosSettings.ulLogoDisplayTime);
2545 if (hw.biosSettings.strLogoImagePath.length())
2546 pelmLogo->setAttribute("imagePath", hw.biosSettings.strLogoImagePath);
2547
2548 const char *pcszBootMenu;
2549 switch (hw.biosSettings.biosBootMenuMode)
2550 {
2551 case BIOSBootMenuMode_Disabled: pcszBootMenu = "Disabled"; break;
2552 case BIOSBootMenuMode_MenuOnly: pcszBootMenu = "MenuOnly"; break;
2553 default: /*BIOSBootMenuMode_MessageAndMenu*/ pcszBootMenu = "MessageAndMenu"; break;
2554 }
2555 pelmBIOS->createChild("BootMenu")->setAttribute("mode", pcszBootMenu);
2556 pelmBIOS->createChild("TimeOffset")->setAttribute("value", hw.biosSettings.llTimeOffset);
2557 pelmBIOS->createChild("PXEDebug")->setAttribute("enabled", hw.biosSettings.fPXEDebugEnabled);
2558
2559 if (m->sv < SettingsVersion_v1_9)
2560 {
2561 // settings formats before 1.9 had separate DVDDrive and FloppyDrive items under Hardware;
2562 // run thru the storage controllers to see if we have a DVD or floppy drives
2563 size_t cDVDs = 0;
2564 size_t cFloppies = 0;
2565
2566 xml::ElementNode *pelmDVD = pelmHardware->createChild("DVDDrive");
2567 xml::ElementNode *pelmFloppy = pelmHardware->createChild("FloppyDrive");
2568
2569 for (StorageControllersList::const_iterator it = strg.llStorageControllers.begin();
2570 it != strg.llStorageControllers.end();
2571 ++it)
2572 {
2573 const StorageController &sctl = *it;
2574 // in old settings format, the DVD drive could only have been under the IDE controller
2575 if (sctl.storageBus == StorageBus_IDE)
2576 {
2577 for (AttachedDevicesList::const_iterator it2 = sctl.llAttachedDevices.begin();
2578 it2 != sctl.llAttachedDevices.end();
2579 ++it2)
2580 {
2581 const AttachedDevice &att = *it2;
2582 if (att.deviceType == DeviceType_DVD)
2583 {
2584 if (cDVDs > 0)
2585 throw ConfigFileError(this, NULL, N_("Internal error: cannot save more than one DVD drive with old settings format"));
2586
2587 ++cDVDs;
2588
2589 pelmDVD->setAttribute("passthrough", att.fPassThrough);
2590 if (!att.uuid.isEmpty())
2591 pelmDVD->createChild("Image")->setAttribute("uuid", makeString(att.uuid));
2592 else if (att.strHostDriveSrc.length())
2593 pelmDVD->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
2594 }
2595 }
2596 }
2597 else if (sctl.storageBus == StorageBus_Floppy)
2598 {
2599 size_t cFloppiesHere = sctl.llAttachedDevices.size();
2600 if (cFloppiesHere > 1)
2601 throw ConfigFileError(this, NULL, N_("Internal error: floppy controller cannot have more than one device attachment"));
2602 if (cFloppiesHere)
2603 {
2604 const AttachedDevice &att = sctl.llAttachedDevices.front();
2605 pelmFloppy->setAttribute("enabled", true);
2606 if (!att.uuid.isEmpty())
2607 pelmFloppy->createChild("Image")->setAttribute("uuid", makeString(att.uuid));
2608 else if (att.strHostDriveSrc.length())
2609 pelmFloppy->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
2610 }
2611
2612 cFloppies += cFloppiesHere;
2613 }
2614 }
2615
2616 if (cFloppies == 0)
2617 pelmFloppy->setAttribute("enabled", false);
2618 else if (cFloppies > 1)
2619 throw ConfigFileError(this, NULL, N_("Internal error: cannot save more than one floppy drive with old settings format"));
2620 }
2621
2622 xml::ElementNode *pelmUSB = pelmHardware->createChild("USBController");
2623 pelmUSB->setAttribute("enabled", hw.usbController.fEnabled);
2624 pelmUSB->setAttribute("enabledEhci", hw.usbController.fEnabledEHCI);
2625
2626 writeUSBDeviceFilters(*pelmUSB,
2627 hw.usbController.llDeviceFilters,
2628 false); // fHostMode
2629
2630 xml::ElementNode *pelmNetwork = pelmHardware->createChild("Network");
2631 for (NetworkAdaptersList::const_iterator it = hw.llNetworkAdapters.begin();
2632 it != hw.llNetworkAdapters.end();
2633 ++it)
2634 {
2635 const NetworkAdapter &nic = *it;
2636
2637 xml::ElementNode *pelmAdapter = pelmNetwork->createChild("Adapter");
2638 pelmAdapter->setAttribute("slot", nic.ulSlot);
2639 pelmAdapter->setAttribute("enabled", nic.fEnabled);
2640 pelmAdapter->setAttribute("MACAddress", nic.strMACAddress);
2641 pelmAdapter->setAttribute("cable", nic.fCableConnected);
2642 pelmAdapter->setAttribute("speed", nic.ulLineSpeed);
2643 if (nic.fTraceEnabled)
2644 {
2645 pelmAdapter->setAttribute("trace", nic.fTraceEnabled);
2646 pelmAdapter->setAttribute("tracefile", nic.strTraceFile);
2647 }
2648
2649 const char *pcszType;
2650 switch (nic.type)
2651 {
2652 case NetworkAdapterType_Am79C973: pcszType = "Am79C973"; break;
2653 case NetworkAdapterType_I82540EM: pcszType = "82540EM"; break;
2654 case NetworkAdapterType_I82543GC: pcszType = "82543GC"; break;
2655 case NetworkAdapterType_I82545EM: pcszType = "82545EM"; break;
2656 case NetworkAdapterType_Virtio: pcszType = "virtio-net"; break;
2657 default: /*case NetworkAdapterType_Am79C970A:*/ pcszType = "Am79C970A"; break;
2658 }
2659 pelmAdapter->setAttribute("type", pcszType);
2660
2661 xml::ElementNode *pelmNAT;
2662 switch (nic.mode)
2663 {
2664 case NetworkAttachmentType_NAT:
2665 pelmNAT = pelmAdapter->createChild("NAT");
2666 if (nic.strName.length())
2667 pelmNAT->setAttribute("network", nic.strName);
2668 break;
2669
2670 case NetworkAttachmentType_Bridged:
2671 pelmAdapter->createChild("BridgedInterface")->setAttribute("name", nic.strName);
2672 break;
2673
2674 case NetworkAttachmentType_Internal:
2675 pelmAdapter->createChild("InternalNetwork")->setAttribute("name", nic.strName);
2676 break;
2677
2678 case NetworkAttachmentType_HostOnly:
2679 pelmAdapter->createChild("HostOnlyInterface")->setAttribute("name", nic.strName);
2680 break;
2681
2682 default: /*case NetworkAttachmentType_Null:*/
2683 break;
2684 }
2685 }
2686
2687 xml::ElementNode *pelmPorts = pelmHardware->createChild("UART");
2688 for (SerialPortsList::const_iterator it = hw.llSerialPorts.begin();
2689 it != hw.llSerialPorts.end();
2690 ++it)
2691 {
2692 const SerialPort &port = *it;
2693 xml::ElementNode *pelmPort = pelmPorts->createChild("Port");
2694 pelmPort->setAttribute("slot", port.ulSlot);
2695 pelmPort->setAttribute("enabled", port.fEnabled);
2696 pelmPort->setAttributeHex("IOBase", port.ulIOBase);
2697 pelmPort->setAttribute("IRQ", port.ulIRQ);
2698
2699 const char *pcszHostMode;
2700 switch (port.portMode)
2701 {
2702 case PortMode_HostPipe: pcszHostMode = "HostPipe"; break;
2703 case PortMode_HostDevice: pcszHostMode = "HostDevice"; break;
2704 case PortMode_RawFile: pcszHostMode = "RawFile"; break;
2705 default: /*case PortMode_Disconnected:*/ pcszHostMode = "Disconnected"; break;
2706 }
2707 switch (port.portMode)
2708 {
2709 case PortMode_HostPipe:
2710 pelmPort->setAttribute("server", port.fServer);
2711 /* no break */
2712 case PortMode_HostDevice:
2713 case PortMode_RawFile:
2714 pelmPort->setAttribute("path", port.strPath);
2715 break;
2716
2717 default:
2718 break;
2719 }
2720 pelmPort->setAttribute("hostMode", pcszHostMode);
2721 }
2722
2723 pelmPorts = pelmHardware->createChild("LPT");
2724 for (ParallelPortsList::const_iterator it = hw.llParallelPorts.begin();
2725 it != hw.llParallelPorts.end();
2726 ++it)
2727 {
2728 const ParallelPort &port = *it;
2729 xml::ElementNode *pelmPort = pelmPorts->createChild("Port");
2730 pelmPort->setAttribute("slot", port.ulSlot);
2731 pelmPort->setAttribute("enabled", port.fEnabled);
2732 pelmPort->setAttributeHex("IOBase", port.ulIOBase);
2733 pelmPort->setAttribute("IRQ", port.ulIRQ);
2734 if (port.strPath.length())
2735 pelmPort->setAttribute("path", port.strPath);
2736 }
2737
2738 xml::ElementNode *pelmAudio = pelmHardware->createChild("AudioAdapter");
2739 pelmAudio->setAttribute("controller", (hw.audioAdapter.controllerType == AudioControllerType_SB16) ? "SB16" : "AC97");
2740
2741 const char *pcszDriver;
2742 switch (hw.audioAdapter.driverType)
2743 {
2744 case AudioDriverType_WinMM: pcszDriver = "WinMM"; break;
2745 case AudioDriverType_DirectSound: pcszDriver = "DirectSound"; break;
2746 case AudioDriverType_SolAudio: pcszDriver = "SolAudio"; break;
2747 case AudioDriverType_ALSA: pcszDriver = "ALSA"; break;
2748 case AudioDriverType_Pulse: pcszDriver = "Pulse"; break;
2749 case AudioDriverType_OSS: pcszDriver = "OSS"; break;
2750 case AudioDriverType_CoreAudio: pcszDriver = "CoreAudio"; break;
2751 case AudioDriverType_MMPM: pcszDriver = "MMPM"; break;
2752 default: /*case AudioDriverType_Null:*/ pcszDriver = "Null"; break;
2753 }
2754 pelmAudio->setAttribute("driver", pcszDriver);
2755
2756 pelmAudio->setAttribute("enabled", hw.audioAdapter.fEnabled);
2757
2758 xml::ElementNode *pelmSharedFolders = pelmHardware->createChild("SharedFolders");
2759 for (SharedFoldersList::const_iterator it = hw.llSharedFolders.begin();
2760 it != hw.llSharedFolders.end();
2761 ++it)
2762 {
2763 const SharedFolder &sf = *it;
2764 xml::ElementNode *pelmThis = pelmSharedFolders->createChild("SharedFolder");
2765 pelmThis->setAttribute("name", sf.strName);
2766 pelmThis->setAttribute("hostPath", sf.strHostPath);
2767 pelmThis->setAttribute("writable", sf.fWritable);
2768 }
2769
2770 xml::ElementNode *pelmClip = pelmHardware->createChild("Clipboard");
2771 const char *pcszClip;
2772 switch (hw.clipboardMode)
2773 {
2774 case ClipboardMode_Disabled: pcszClip = "Disabled"; break;
2775 case ClipboardMode_HostToGuest: pcszClip = "HostToGuest"; break;
2776 case ClipboardMode_GuestToHost: pcszClip = "GuestToHost"; break;
2777 default: /*case ClipboardMode_Bidirectional:*/ pcszClip = "Bidirectional"; break;
2778 }
2779 pelmClip->setAttribute("mode", pcszClip);
2780
2781 xml::ElementNode *pelmGuest = pelmHardware->createChild("Guest");
2782 pelmGuest->setAttribute("memoryBalloonSize", hw.ulMemoryBalloonSize);
2783 pelmGuest->setAttribute("statisticsUpdateInterval", hw.ulStatisticsUpdateInterval);
2784
2785 xml::ElementNode *pelmGuestProps = pelmHardware->createChild("GuestProperties");
2786 for (GuestPropertiesList::const_iterator it = hw.llGuestProperties.begin();
2787 it != hw.llGuestProperties.end();
2788 ++it)
2789 {
2790 const GuestProperty &prop = *it;
2791 xml::ElementNode *pelmProp = pelmGuestProps->createChild("GuestProperty");
2792 pelmProp->setAttribute("name", prop.strName);
2793 pelmProp->setAttribute("value", prop.strValue);
2794 pelmProp->setAttribute("timestamp", prop.timestamp);
2795 pelmProp->setAttribute("flags", prop.strFlags);
2796 }
2797
2798 if (hw.strNotificationPatterns.length())
2799 pelmGuestProps->setAttribute("notificationPatterns", hw.strNotificationPatterns);
2800}
2801
2802/**
2803 * Creates a <StorageControllers> node under elmParent and then writes out the XML
2804 * keys under that. Called for both the <Machine> node and for snapshots.
2805 * @param elmParent
2806 * @param st
2807 */
2808void MachineConfigFile::writeStorageControllers(xml::ElementNode &elmParent,
2809 const Storage &st)
2810{
2811 xml::ElementNode *pelmStorageControllers = elmParent.createChild("StorageControllers");
2812
2813 for (StorageControllersList::const_iterator it = st.llStorageControllers.begin();
2814 it != st.llStorageControllers.end();
2815 ++it)
2816 {
2817 const StorageController &sc = *it;
2818
2819 if ( (m->sv < SettingsVersion_v1_9)
2820 && (sc.controllerType == StorageControllerType_I82078)
2821 )
2822 // floppy controller already got written into <Hardware>/<FloppyController> in writeHardware()
2823 // for pre-1.9 settings
2824 continue;
2825
2826 xml::ElementNode *pelmController = pelmStorageControllers->createChild("StorageController");
2827 com::Utf8Str name = sc.strName.raw();
2828 //
2829 if (m->sv < SettingsVersion_v1_8)
2830 {
2831 // pre-1.8 settings use shorter controller names, they are
2832 // expanded when reading the settings
2833 if (name == "IDE Controller")
2834 name = "IDE";
2835 else if (name == "SATA Controller")
2836 name = "SATA";
2837 else if (name == "SCSI Controller")
2838 name = "SCSI";
2839 }
2840 pelmController->setAttribute("name", sc.strName);
2841
2842 const char *pcszType;
2843 switch (sc.controllerType)
2844 {
2845 case StorageControllerType_IntelAhci: pcszType = "AHCI"; break;
2846 case StorageControllerType_LsiLogic: pcszType = "LsiLogic"; break;
2847 case StorageControllerType_BusLogic: pcszType = "BusLogic"; break;
2848 case StorageControllerType_PIIX4: pcszType = "PIIX4"; break;
2849 case StorageControllerType_ICH6: pcszType = "ICH6"; break;
2850 case StorageControllerType_I82078: pcszType = "I82078"; break;
2851 default: /*case StorageControllerType_PIIX3:*/ pcszType = "PIIX3"; break;
2852 }
2853 pelmController->setAttribute("type", pcszType);
2854
2855 pelmController->setAttribute("PortCount", sc.ulPortCount);
2856
2857 if (m->sv >= SettingsVersion_v1_9)
2858 if (sc.ulInstance)
2859 pelmController->setAttribute("Instance", sc.ulInstance);
2860
2861 if (sc.controllerType == StorageControllerType_IntelAhci)
2862 {
2863 pelmController->setAttribute("IDE0MasterEmulationPort", sc.lIDE0MasterEmulationPort);
2864 pelmController->setAttribute("IDE0SlaveEmulationPort", sc.lIDE0SlaveEmulationPort);
2865 pelmController->setAttribute("IDE1MasterEmulationPort", sc.lIDE1MasterEmulationPort);
2866 pelmController->setAttribute("IDE1SlaveEmulationPort", sc.lIDE1SlaveEmulationPort);
2867 }
2868
2869 for (AttachedDevicesList::const_iterator it2 = sc.llAttachedDevices.begin();
2870 it2 != sc.llAttachedDevices.end();
2871 ++it2)
2872 {
2873 const AttachedDevice &att = *it2;
2874
2875 // For settings version before 1.9, DVDs and floppies are in hardware, not storage controllers,
2876 // so we shouldn't write them here; we only get here for DVDs though because we ruled out
2877 // the floppy controller at the top of the loop
2878 if ( att.deviceType == DeviceType_DVD
2879 && m->sv < SettingsVersion_v1_9
2880 )
2881 continue;
2882
2883 xml::ElementNode *pelmDevice = pelmController->createChild("AttachedDevice");
2884
2885 pcszType = NULL;
2886
2887 switch (att.deviceType)
2888 {
2889 case DeviceType_HardDisk:
2890 pcszType = "HardDisk";
2891 break;
2892
2893 case DeviceType_DVD:
2894 pcszType = "DVD";
2895 if (att.fPassThrough)
2896 pelmDevice->setAttribute("passthrough", att.fPassThrough);
2897 break;
2898
2899 case DeviceType_Floppy:
2900 pcszType = "Floppy";
2901 break;
2902 }
2903
2904 pelmDevice->setAttribute("type", pcszType);
2905
2906 pelmDevice->setAttribute("port", att.lPort);
2907 pelmDevice->setAttribute("device", att.lDevice);
2908
2909 if (!att.uuid.isEmpty())
2910 pelmDevice->createChild("Image")->setAttribute("uuid", makeString(att.uuid));
2911 else if ( (m->sv >= SettingsVersion_v1_9)
2912 && (att.strHostDriveSrc.length())
2913 )
2914 pelmDevice->createChild("HostDrive")->setAttribute("src", att.strHostDriveSrc);
2915 }
2916 }
2917}
2918
2919/**
2920 * Writes a single snapshot into the DOM tree. Initially this gets called from MachineConfigFile::write()
2921 * for the root snapshot of a machine, if present; elmParent then points to the <Snapshots> node under the
2922 * <Machine> node to which <Snapshot> must be added. This may then recurse for child snapshots.
2923 * @param elmParent
2924 * @param snap
2925 */
2926void MachineConfigFile::writeSnapshot(xml::ElementNode &elmParent,
2927 const Snapshot &snap)
2928{
2929 xml::ElementNode *pelmSnapshot = elmParent.createChild("Snapshot");
2930
2931 pelmSnapshot->setAttribute("uuid", makeString(snap.uuid));
2932 pelmSnapshot->setAttribute("name", snap.strName);
2933 pelmSnapshot->setAttribute("timeStamp", makeString(snap.timestamp));
2934
2935 if (snap.strStateFile.length())
2936 pelmSnapshot->setAttribute("stateFile", snap.strStateFile);
2937
2938 if (snap.strDescription.length())
2939 pelmSnapshot->createChild("Description")->addContent(snap.strDescription);
2940
2941 writeHardware(*pelmSnapshot, snap.hardware, snap.storage);
2942 writeStorageControllers(*pelmSnapshot, snap.storage);
2943
2944 if (snap.llChildSnapshots.size())
2945 {
2946 xml::ElementNode *pelmChildren = pelmSnapshot->createChild("Snapshots");
2947 for (SnapshotsList::const_iterator it = snap.llChildSnapshots.begin();
2948 it != snap.llChildSnapshots.end();
2949 ++it)
2950 {
2951 const Snapshot &child = *it;
2952 writeSnapshot(*pelmChildren, child);
2953 }
2954 }
2955}
2956
2957/**
2958 * Called from write() before calling ConfigFileBase::createStubDocument().
2959 * This adjusts the settings version in m->sv if incompatible settings require
2960 * a settings bump, whereas otherwise we try to preserve the settings version
2961 * to avoid breaking compatibility with older versions.
2962 */
2963void MachineConfigFile::bumpSettingsVersionIfNeeded()
2964{
2965 // The hardware versions other than "1" requires settings version 1.4 (2.1+).
2966 if ( m->sv < SettingsVersion_v1_4
2967 && hardwareMachine.strVersion != "1"
2968 )
2969 m->sv = SettingsVersion_v1_4;
2970
2971 // "accelerate 2d video" requires settings version 1.8
2972 if ( (m->sv < SettingsVersion_v1_8)
2973 && (hardwareMachine.fAccelerate2DVideo)
2974 )
2975 m->sv = SettingsVersion_v1_8;
2976
2977 // all the following require settings version 1.9
2978 if ( (m->sv < SettingsVersion_v1_9)
2979 && ( (hardwareMachine.firmwareType == FirmwareType_EFI)
2980 || (hardwareMachine.fHardwareVirtExclusive != HWVIRTEXCLUSIVEDEFAULT)
2981 || fTeleporterEnabled
2982 || uTeleporterPort
2983 || !strTeleporterAddress.isEmpty()
2984 || !strTeleporterPassword.isEmpty()
2985 || !hardwareMachine.uuid.isEmpty()
2986 )
2987 )
2988 m->sv = SettingsVersion_v1_9;
2989
2990 // settings version 1.9 is also required if there is not exactly one DVD
2991 // or more than one floppy drive present or the DVD is not at the secondary
2992 // master; this check is a bit more complicated
2993 if (m->sv < SettingsVersion_v1_9)
2994 {
2995 size_t cDVDs = 0;
2996 size_t cFloppies = 0;
2997
2998 // need to run thru all the storage controllers to figure this out
2999 for (StorageControllersList::const_iterator it = storageMachine.llStorageControllers.begin();
3000 it != storageMachine.llStorageControllers.end()
3001 && m->sv < SettingsVersion_v1_9;
3002 ++it)
3003 {
3004 const StorageController &sctl = *it;
3005 for (AttachedDevicesList::const_iterator it2 = sctl.llAttachedDevices.begin();
3006 it2 != sctl.llAttachedDevices.end();
3007 ++it2)
3008 {
3009 if (sctl.ulInstance != 0) // we can only write the StorageController/@Instance attribute with v1.9
3010 {
3011 m->sv = SettingsVersion_v1_9;
3012 break;
3013 }
3014
3015 const AttachedDevice &att = *it2;
3016 if (att.deviceType == DeviceType_DVD)
3017 {
3018 if ( (sctl.storageBus != StorageBus_IDE) // DVD at bus other than DVD?
3019 || (att.lPort != 1) // DVDs not at secondary master?
3020 || (att.lDevice != 0)
3021 )
3022 {
3023 m->sv = SettingsVersion_v1_9;
3024 break;
3025 }
3026
3027 ++cDVDs;
3028 }
3029 else if (att.deviceType == DeviceType_Floppy)
3030 ++cFloppies;
3031 }
3032 }
3033
3034 // VirtualBox before 3.1 had zero or one floppy and exactly one DVD,
3035 // so any deviation from that will require settings version 1.9
3036 if ( (m->sv < SettingsVersion_v1_9)
3037 && ( (cDVDs != 1)
3038 || (cFloppies > 1)
3039 )
3040 )
3041 m->sv = SettingsVersion_v1_9;
3042 }
3043}
3044
3045/**
3046 * Called from Main code to write a machine config file to disk. This builds a DOM tree from
3047 * the member variables and then writes the XML file; it throws xml::Error instances on errors,
3048 * in particular if the file cannot be written.
3049 */
3050void MachineConfigFile::write(const com::Utf8Str &strFilename)
3051{
3052 try
3053 {
3054 // createStubDocument() sets the settings version to at least 1.7; however,
3055 // we might need to enfore a later settings version if incompatible settings
3056 // are present:
3057 bumpSettingsVersionIfNeeded();
3058
3059 m->strFilename = strFilename;
3060 createStubDocument();
3061
3062 xml::ElementNode *pelmMachine = m->pelmRoot->createChild("Machine");
3063
3064 pelmMachine->setAttribute("uuid", makeString(uuid));
3065 pelmMachine->setAttribute("name", strName);
3066 if (!fNameSync)
3067 pelmMachine->setAttribute("nameSync", fNameSync);
3068 if (strDescription.length())
3069 pelmMachine->createChild("Description")->addContent(strDescription);
3070 pelmMachine->setAttribute("OSType", strOsType);
3071 if (strStateFile.length())
3072 pelmMachine->setAttribute("stateFile", strStateFile);
3073 if (!uuidCurrentSnapshot.isEmpty())
3074 pelmMachine->setAttribute("currentSnapshot", makeString(uuidCurrentSnapshot));
3075 if (strSnapshotFolder.length())
3076 pelmMachine->setAttribute("snapshotFolder", strSnapshotFolder);
3077 if (!fCurrentStateModified)
3078 pelmMachine->setAttribute("currentStateModified", fCurrentStateModified);
3079 pelmMachine->setAttribute("lastStateChange", makeString(timeLastStateChange));
3080 if (fAborted)
3081 pelmMachine->setAttribute("aborted", fAborted);
3082 if ( m->sv >= SettingsVersion_v1_9
3083 && ( fTeleporterEnabled
3084 || uTeleporterPort
3085 || !strTeleporterAddress.isEmpty()
3086 || !strTeleporterPassword.isEmpty()
3087 )
3088 )
3089 {
3090 xml::ElementNode *pelmTeleporter = pelmMachine->createChild("Teleporter");
3091 pelmTeleporter->setAttribute("enabled", fTeleporterEnabled);
3092 pelmTeleporter->setAttribute("port", uTeleporterPort);
3093 pelmTeleporter->setAttribute("address", strTeleporterAddress);
3094 pelmTeleporter->setAttribute("password", strTeleporterPassword);
3095 }
3096
3097 writeExtraData(*pelmMachine, mapExtraDataItems);
3098
3099 if (llFirstSnapshot.size())
3100 writeSnapshot(*pelmMachine, llFirstSnapshot.front());
3101
3102 writeHardware(*pelmMachine, hardwareMachine, storageMachine);
3103 writeStorageControllers(*pelmMachine, storageMachine);
3104
3105 // now go write the XML
3106 xml::XmlFileWriter writer(*m->pDoc);
3107 writer.write(m->strFilename.c_str());
3108
3109 m->fFileExists = true;
3110 clearDocument();
3111 }
3112 catch (...)
3113 {
3114 clearDocument();
3115 throw;
3116 }
3117}
Note: See TracBrowser for help on using the repository browser.

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