VirtualBox

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

Last change on this file since 31688 was 31615, checked in by vboxsync, 14 years ago

Main: Implemenation of per-machine media registries; VirtualBox::openMedium() no longer adds media to the global registry, instead a media are stored in a machine XML registry after Machine::AttachDevice() has been called; Machine::AttachDevice() now takes an IMedium object instead of a UUID; also make Machine::Unregister() work again for inaccessible machines

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

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