VirtualBox

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

Last change on this file since 103288 was 103085, checked in by vboxsync, 10 months ago

Main,FE/VBoxManage,FE/VirtualBox,ValidationKit: Allow setting the primary VM execution engine to make it easier to force particular engine for testing, bugref:10583

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Revision Author Id
File size: 417.2 KB
Line 
1/* $Id: Settings.cpp 103085 2024-01-26 16:17:43Z 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 * VBOX_XML_VERSION does not have to be changed if the settings for a default VM do not
20 * touch newly introduced attributes or tags. It has the benefit that older VirtualBox
21 * versions do not trigger their "newer" code path.
22 *
23 * Once a new settings version has been added, these are the rules for introducing a new
24 * setting: If an XML element or attribute or value is introduced that was not present in
25 * previous versions, then settings version checks need to be introduced. See the
26 * SettingsVersion enumeration in src/VBox/Main/idl/VirtualBox.xidl for details about which
27 * version was used when.
28 *
29 * The settings versions checks are necessary because since version 3.1, VirtualBox no longer
30 * automatically converts XML settings files but only if necessary, that is, if settings are
31 * present that the old format does not support. If we write an element or attribute to a
32 * settings file of an older version, then an old VirtualBox (before 3.1) will attempt to
33 * validate it with XML schema, and that will certainly fail.
34 *
35 * So, to introduce a new setting:
36 *
37 * 1) Make sure the constructor of corresponding settings structure has a proper default.
38 *
39 * 2) In the settings reader method, try to read the setting; if it's there, great, if not,
40 * the default value will have been set by the constructor. The rule is to be tolerant
41 * here.
42 *
43 * 3) In MachineConfigFile::bumpSettingsVersionIfNeeded(), check if the new setting has
44 * a non-default value (i.e. that differs from the constructor). If so, bump the
45 * settings version to the current version so the settings writer (4) can write out
46 * the non-default value properly.
47 *
48 * So far a corresponding method for MainConfigFile has not been necessary since there
49 * have been no incompatible changes yet.
50 *
51 * 4) In the settings writer method, write the setting _only_ if the current settings
52 * version (stored in m->sv) is high enough. That is, for VirtualBox 4.0, write it
53 * only if (m->sv >= SettingsVersion_v1_11).
54 *
55 * 5) You _must_ update xml/VirtualBox-settings.xsd to contain the new tags and attributes.
56 * Check that settings file from before and after your change are validating properly.
57 * Use "kmk testvalidsettings", it should not find any files which don't validate.
58 */
59
60/*
61 * Copyright (C) 2007-2023 Oracle and/or its affiliates.
62 *
63 * This file is part of VirtualBox base platform packages, as
64 * available from https://www.virtualbox.org.
65 *
66 * This program is free software; you can redistribute it and/or
67 * modify it under the terms of the GNU General Public License
68 * as published by the Free Software Foundation, in version 3 of the
69 * License.
70 *
71 * This program is distributed in the hope that it will be useful, but
72 * WITHOUT ANY WARRANTY; without even the implied warranty of
73 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
74 * General Public License for more details.
75 *
76 * You should have received a copy of the GNU General Public License
77 * along with this program; if not, see <https://www.gnu.org/licenses>.
78 *
79 * SPDX-License-Identifier: GPL-3.0-only
80 */
81
82#define LOG_GROUP LOG_GROUP_MAIN
83#include "VBox/com/string.h"
84#include "VBox/settings.h"
85#include <iprt/base64.h>
86#include <iprt/cpp/lock.h>
87#include <iprt/cpp/utils.h>
88#include <iprt/cpp/xml.h>
89#include <iprt/ctype.h>
90#include <iprt/err.h>
91#include <iprt/file.h>
92#include <iprt/ldr.h>
93#include <iprt/process.h>
94#include <iprt/stream.h>
95#ifdef RT_OS_WINDOWS
96# include <iprt/system.h> /* For RTSystemGetNtVersion() / RTSYSTEM_MAKE_NT_VERSION. */
97#endif
98#include <iprt/uri.h>
99
100// Guest Properties validation.
101#include "VBox/HostServices/GuestPropertySvc.h"
102
103// generated header
104#include "SchemaDefs.h"
105
106#include "HashedPw.h"
107#include "LoggingNew.h"
108
109using namespace com;
110using namespace settings;
111
112////////////////////////////////////////////////////////////////////////////////
113//
114// Defines
115//
116////////////////////////////////////////////////////////////////////////////////
117
118/** VirtualBox XML settings namespace */
119#define VBOX_XML_NAMESPACE "http://www.virtualbox.org/"
120
121/** VirtualBox XML schema location (relative URI) */
122#define VBOX_XML_SCHEMA "VirtualBox-settings.xsd"
123
124/** VirtualBox XML settings version number substring ("x.y") */
125#define VBOX_XML_VERSION "1.12"
126
127/** VirtualBox OVF settings import default version number substring ("x.y").
128 *
129 * Think twice before changing this, as all VirtualBox versions before 5.1
130 * wrote the settings version when exporting, but totally ignored it on
131 * importing (while it should have been a mandatory attribute), so 3rd party
132 * software out there creates OVF files with the VirtualBox specific settings
133 * but lacking the version attribute. This shouldn't happen any more, but
134 * breaking existing OVF files isn't nice. */
135#define VBOX_XML_IMPORT_VERSION "1.15"
136
137/** VirtualBox XML settings version platform substring */
138#if defined (RT_OS_DARWIN)
139# define VBOX_XML_PLATFORM "macosx"
140#elif defined (RT_OS_FREEBSD)
141# define VBOX_XML_PLATFORM "freebsd"
142#elif defined (RT_OS_LINUX)
143# define VBOX_XML_PLATFORM "linux"
144#elif defined (RT_OS_NETBSD)
145# define VBOX_XML_PLATFORM "netbsd"
146#elif defined (RT_OS_OPENBSD)
147# define VBOX_XML_PLATFORM "openbsd"
148#elif defined (RT_OS_OS2)
149# define VBOX_XML_PLATFORM "os2"
150#elif defined (RT_OS_SOLARIS)
151# define VBOX_XML_PLATFORM "solaris"
152#elif defined (RT_OS_WINDOWS)
153# define VBOX_XML_PLATFORM "windows"
154#else
155# error Unsupported platform!
156#endif
157
158/** VirtualBox XML settings full version string ("x.y-platform") */
159#define VBOX_XML_VERSION_FULL VBOX_XML_VERSION "-" VBOX_XML_PLATFORM
160
161/** VirtualBox OVF import default settings full version string ("x.y-platform") */
162#define VBOX_XML_IMPORT_VERSION_FULL VBOX_XML_IMPORT_VERSION "-" VBOX_XML_PLATFORM
163
164////////////////////////////////////////////////////////////////////////////////
165//
166// Internal data
167//
168////////////////////////////////////////////////////////////////////////////////
169
170/**
171 * Opaque data structore for ConfigFileBase (only declared
172 * in header, defined only here).
173 */
174
175struct ConfigFileBase::Data
176{
177 Data()
178 : pDoc(NULL),
179 pelmRoot(NULL),
180 sv(SettingsVersion_Null),
181 svRead(SettingsVersion_Null)
182 {}
183
184 ~Data()
185 {
186 cleanup();
187 }
188
189 RTCString strFilename;
190 bool fFileExists;
191
192 xml::Document *pDoc;
193 xml::ElementNode *pelmRoot;
194
195 com::Utf8Str strSettingsVersionFull; // e.g. "1.7-linux"
196 SettingsVersion_T sv; // e.g. SettingsVersion_v1_7
197
198 SettingsVersion_T svRead; // settings version that the original file had when it was read,
199 // or SettingsVersion_Null if none
200
201 void copyFrom(const Data &d)
202 {
203 strFilename = d.strFilename;
204 fFileExists = d.fFileExists;
205 strSettingsVersionFull = d.strSettingsVersionFull;
206 sv = d.sv;
207 svRead = d.svRead;
208 }
209
210 void cleanup()
211 {
212 if (pDoc)
213 {
214 delete pDoc;
215 pDoc = NULL;
216 pelmRoot = NULL;
217 }
218 }
219};
220
221/**
222 * Private exception class (not in the header file) that makes
223 * throwing xml::LogicError instances easier. That class is public
224 * and should be caught by client code.
225 */
226class settings::ConfigFileError : public xml::LogicError
227{
228public:
229 ConfigFileError(const ConfigFileBase *file,
230 const xml::Node *pNode,
231 const char *pcszFormat, ...)
232 : xml::LogicError()
233 {
234 va_list args;
235 va_start(args, pcszFormat);
236 Utf8Str strWhat(pcszFormat, args);
237 va_end(args);
238
239 Utf8Str strLine;
240 if (pNode)
241 strLine = Utf8StrFmt(" (line %RU32)", pNode->getLineNumber());
242
243 const char *pcsz = strLine.c_str();
244 Utf8StrFmt str(N_("Error in %s%s -- %s"),
245 file->m->strFilename.c_str(),
246 (pcsz) ? pcsz : "",
247 strWhat.c_str());
248
249 setWhat(str.c_str());
250 }
251};
252
253////////////////////////////////////////////////////////////////////////////////
254//
255// ConfigFileBase
256//
257////////////////////////////////////////////////////////////////////////////////
258
259/**
260 * Constructor. Allocates the XML internals, parses the XML file if
261 * pstrFilename is != NULL and reads the settings version from it.
262 * @param pstrFilename
263 */
264ConfigFileBase::ConfigFileBase(const com::Utf8Str *pstrFilename)
265 : m(new Data)
266{
267 m->fFileExists = false;
268
269 if (pstrFilename)
270 {
271 try
272 {
273 // reading existing settings file:
274 m->strFilename = *pstrFilename;
275
276 xml::XmlFileParser parser;
277 m->pDoc = new xml::Document;
278 parser.read(*pstrFilename,
279 *m->pDoc);
280
281 m->fFileExists = true;
282
283 m->pelmRoot = m->pDoc->getRootElement();
284 if (!m->pelmRoot || !m->pelmRoot->nameEquals("VirtualBox"))
285 throw ConfigFileError(this, m->pelmRoot, N_("Root element in VirtualBox settings files must be \"VirtualBox\""));
286
287 if (!(m->pelmRoot->getAttributeValue("version", m->strSettingsVersionFull)))
288 throw ConfigFileError(this, m->pelmRoot, N_("Required VirtualBox/@version attribute is missing"));
289
290 LogRel(("Loading settings file \"%s\" with version \"%s\"\n", m->strFilename.c_str(), m->strSettingsVersionFull.c_str()));
291
292 m->sv = parseVersion(m->strSettingsVersionFull, m->pelmRoot);
293
294 // remember the settings version we read in case it gets upgraded later,
295 // so we know when to make backups
296 m->svRead = m->sv;
297 }
298 catch(...)
299 {
300 /*
301 * The destructor is not called when an exception is thrown in the constructor,
302 * so we have to do the cleanup here.
303 */
304 delete m;
305 m = NULL;
306 throw;
307 }
308 }
309 else
310 {
311 // creating new settings file:
312 m->strSettingsVersionFull = VBOX_XML_VERSION_FULL;
313 m->sv = SettingsVersion_v1_12;
314 }
315}
316
317ConfigFileBase::ConfigFileBase(const ConfigFileBase &other)
318 : m(new Data)
319{
320 copyBaseFrom(other);
321 m->strFilename = "";
322 m->fFileExists = false;
323}
324
325/**
326 * Clean up.
327 */
328ConfigFileBase::~ConfigFileBase()
329{
330 if (m)
331 {
332 delete m;
333 m = NULL;
334 }
335}
336
337/**
338 * Helper function to convert a MediaType enum value into string from.
339 * @param t
340 */
341/*static*/
342const char *ConfigFileBase::stringifyMediaType(MediaType t)
343{
344 switch (t)
345 {
346 case HardDisk:
347 return "hard disk";
348 case DVDImage:
349 return "DVD";
350 case FloppyImage:
351 return "floppy";
352 default:
353 AssertMsgFailed(("media type %d\n", t));
354 return "UNKNOWN";
355 }
356}
357
358/**
359 * Helper function that parses a full version number.
360 *
361 * Allow future versions but fail if file is older than 1.6. Throws on errors.
362 * @returns settings version
363 * @param strVersion
364 * @param pElm
365 */
366SettingsVersion_T ConfigFileBase::parseVersion(const Utf8Str &strVersion, const xml::ElementNode *pElm)
367{
368 SettingsVersion_T sv = SettingsVersion_Null;
369 if (strVersion.length() > 3)
370 {
371 const char *pcsz = strVersion.c_str();
372
373 uint32_t uMajor = 0;
374 char ch;
375 while ( (ch = *pcsz)
376 && RT_C_IS_DIGIT(ch) )
377 {
378 uMajor *= 10;
379 uMajor += (uint32_t)(ch - '0');
380 ++pcsz;
381 }
382
383 uint32_t uMinor = 0;
384 if (ch == '.')
385 {
386 pcsz++;
387 while ( (ch = *pcsz)
388 && RT_C_IS_DIGIT(ch))
389 {
390 uMinor *= 10;
391 uMinor += (ULONG)(ch - '0');
392 ++pcsz;
393 }
394 }
395
396 if (uMajor == 1)
397 {
398 if (uMinor == 3)
399 sv = SettingsVersion_v1_3;
400 else if (uMinor == 4)
401 sv = SettingsVersion_v1_4;
402 else if (uMinor == 5)
403 sv = SettingsVersion_v1_5;
404 else if (uMinor == 6)
405 sv = SettingsVersion_v1_6;
406 else if (uMinor == 7)
407 sv = SettingsVersion_v1_7;
408 else if (uMinor == 8)
409 sv = SettingsVersion_v1_8;
410 else if (uMinor == 9)
411 sv = SettingsVersion_v1_9;
412 else if (uMinor == 10)
413 sv = SettingsVersion_v1_10;
414 else if (uMinor == 11)
415 sv = SettingsVersion_v1_11;
416 else if (uMinor == 12)
417 sv = SettingsVersion_v1_12;
418 else if (uMinor == 13)
419 sv = SettingsVersion_v1_13;
420 else if (uMinor == 14)
421 sv = SettingsVersion_v1_14;
422 else if (uMinor == 15)
423 sv = SettingsVersion_v1_15;
424 else if (uMinor == 16)
425 sv = SettingsVersion_v1_16;
426 else if (uMinor == 17)
427 sv = SettingsVersion_v1_17;
428 else if (uMinor == 18)
429 sv = SettingsVersion_v1_18;
430 else if (uMinor == 19)
431 sv = SettingsVersion_v1_19;
432 else if (uMinor == 20)
433 sv = SettingsVersion_v1_20;
434 else if (uMinor > 20)
435 sv = SettingsVersion_Future;
436 }
437 else if (uMajor > 1)
438 sv = SettingsVersion_Future;
439
440 Log(("Parsed settings version %d.%d to enum value %d\n", uMajor, uMinor, sv));
441 }
442
443 if (sv == SettingsVersion_Null)
444 throw ConfigFileError(this, pElm, N_("Cannot handle settings version '%s'"), strVersion.c_str());
445
446 return sv;
447}
448
449/**
450 * Helper function that parses a UUID in string form into
451 * a com::Guid item. Accepts UUIDs both with and without
452 * "{}" brackets. Throws on errors.
453 * @param guid
454 * @param strUUID
455 * @param pElm
456 */
457void ConfigFileBase::parseUUID(Guid &guid,
458 const Utf8Str &strUUID,
459 const xml::ElementNode *pElm) const
460{
461 guid = strUUID.c_str();
462 if (guid.isZero())
463 throw ConfigFileError(this, pElm, N_("UUID \"%s\" has zero format"), strUUID.c_str());
464 else if (!guid.isValid())
465 throw ConfigFileError(this, pElm, N_("UUID \"%s\" has invalid format"), strUUID.c_str());
466}
467
468/**
469 * Parses the given string in str and attempts to treat it as an ISO
470 * date/time stamp to put into timestamp. Throws on errors.
471 * @param timestamp
472 * @param str
473 * @param pElm
474 */
475void ConfigFileBase::parseTimestamp(RTTIMESPEC &timestamp,
476 const com::Utf8Str &str,
477 const xml::ElementNode *pElm) const
478{
479 const char *pcsz = str.c_str();
480 // yyyy-mm-ddThh:mm:ss
481 // "2009-07-10T11:54:03Z"
482 // 01234567890123456789
483 // 1
484 if (str.length() > 19)
485 {
486 // timezone must either be unspecified or 'Z' for UTC
487 if ( (pcsz[19])
488 && (pcsz[19] != 'Z')
489 )
490 throw ConfigFileError(this, pElm, N_("Cannot handle ISO timestamp '%s': is not UTC date"), str.c_str());
491
492 int32_t yyyy;
493 uint32_t mm, dd, hh, min, secs;
494 if ( (pcsz[4] == '-')
495 && (pcsz[7] == '-')
496 && (pcsz[10] == 'T')
497 && (pcsz[13] == ':')
498 && (pcsz[16] == ':')
499 )
500 {
501 int vrc;
502 if ( (RT_SUCCESS(vrc = RTStrToInt32Ex(pcsz, NULL, 0, &yyyy)))
503 // could theoretically be negative but let's assume that nobody
504 // created virtual machines before the Christian era
505 && (RT_SUCCESS(vrc = RTStrToUInt32Ex(pcsz + 5, NULL, 0, &mm)))
506 && (RT_SUCCESS(vrc = RTStrToUInt32Ex(pcsz + 8, NULL, 0, &dd)))
507 && (RT_SUCCESS(vrc = RTStrToUInt32Ex(pcsz + 11, NULL, 0, &hh)))
508 && (RT_SUCCESS(vrc = RTStrToUInt32Ex(pcsz + 14, NULL, 0, &min)))
509 && (RT_SUCCESS(vrc = RTStrToUInt32Ex(pcsz + 17, NULL, 0, &secs)))
510 )
511 {
512 RTTIME time =
513 {
514 yyyy,
515 (uint8_t)mm,
516 0,
517 0,
518 (uint8_t)dd,
519 (uint8_t)hh,
520 (uint8_t)min,
521 (uint8_t)secs,
522 0,
523 RTTIME_FLAGS_TYPE_UTC,
524 0
525 };
526 if (RTTimeNormalize(&time))
527 if (RTTimeImplode(&timestamp, &time))
528 return;
529 }
530
531 throw ConfigFileError(this, pElm, N_("Cannot parse ISO timestamp '%s': runtime error, %Rra"), str.c_str(), vrc);
532 }
533
534 throw ConfigFileError(this, pElm, N_("Cannot parse ISO timestamp '%s': invalid format"), str.c_str());
535 }
536}
537
538/**
539 * Helper function that parses a Base64 formatted string into a binary blob.
540 * @param binary
541 * @param str
542 * @param pElm
543 */
544void ConfigFileBase::parseBase64(IconBlob &binary,
545 const Utf8Str &str,
546 const xml::ElementNode *pElm) const
547{
548#define DECODE_STR_MAX _1M
549 const char* psz = str.c_str();
550 ssize_t cbOut = RTBase64DecodedSize(psz, NULL);
551 if (cbOut > DECODE_STR_MAX)
552 throw ConfigFileError(this, pElm, N_("Base64 encoded data too long (%d > %d)"), cbOut, DECODE_STR_MAX);
553 else if (cbOut < 0)
554 throw ConfigFileError(this, pElm, N_("Base64 encoded data '%s' invalid"), psz);
555 binary.resize((size_t)cbOut);
556 int vrc = VINF_SUCCESS;
557 if (cbOut)
558 vrc = RTBase64Decode(psz, &binary.front(), (size_t)cbOut, NULL, NULL);
559 if (RT_FAILURE(vrc))
560 {
561 binary.resize(0);
562 throw ConfigFileError(this, pElm, N_("Base64 encoded data could not be decoded (%Rrc)"), vrc);
563 }
564}
565
566/**
567 * Helper to create a string for a RTTIMESPEC for writing out ISO timestamps.
568 * @param stamp
569 * @return
570 */
571com::Utf8Str ConfigFileBase::stringifyTimestamp(const RTTIMESPEC &stamp) const
572{
573 RTTIME time;
574 if (!RTTimeExplode(&time, &stamp))
575 throw ConfigFileError(this, NULL, N_("Timespec %lld ms is invalid"), RTTimeSpecGetMilli(&stamp));
576
577 return Utf8StrFmt("%04u-%02u-%02uT%02u:%02u:%02uZ",
578 time.i32Year, time.u8Month, time.u8MonthDay,
579 time.u8Hour, time.u8Minute, time.u8Second);
580}
581
582/**
583 * Helper to create a base64 encoded string out of a binary blob.
584 * @param str
585 * @param binary
586 * @throws std::bad_alloc and ConfigFileError
587 */
588void ConfigFileBase::toBase64(com::Utf8Str &str, const IconBlob &binary) const
589{
590 size_t cb = binary.size();
591 if (cb > 0)
592 {
593 size_t cchOut = RTBase64EncodedLength(cb);
594 str.reserve(cchOut + 1);
595 int vrc = RTBase64Encode(&binary.front(), cb, str.mutableRaw(), str.capacity(), NULL);
596 if (RT_FAILURE(vrc))
597 throw ConfigFileError(this, NULL, N_("Failed to convert binary data to base64 format (%Rrc)"), vrc);
598 str.jolt();
599 }
600}
601
602/**
603 * Helper method to read in an ExtraData subtree and stores its contents
604 * in the given map of extradata items. Used for both main and machine
605 * extradata (MainConfigFile and MachineConfigFile).
606 * @param elmExtraData
607 * @param map
608 */
609void ConfigFileBase::readExtraData(const xml::ElementNode &elmExtraData,
610 StringsMap &map)
611{
612 xml::NodesLoop nlLevel4(elmExtraData);
613 const xml::ElementNode *pelmExtraDataItem;
614 while ((pelmExtraDataItem = nlLevel4.forAllNodes()))
615 {
616 if (pelmExtraDataItem->nameEquals("ExtraDataItem"))
617 {
618 // <ExtraDataItem name="GUI/LastWindowPostion" value="97,88,981,858"/>
619 Utf8Str strName, strValue;
620 if ( pelmExtraDataItem->getAttributeValue("name", strName)
621 && pelmExtraDataItem->getAttributeValue("value", strValue) )
622 map[strName] = strValue;
623 else
624 throw ConfigFileError(this, pelmExtraDataItem, N_("Required ExtraDataItem/@name or @value attribute is missing"));
625 }
626 }
627}
628
629/**
630 * Reads \<USBDeviceFilter\> entries from under the given elmDeviceFilters node and
631 * stores them in the given linklist. This is in ConfigFileBase because it's used
632 * from both MainConfigFile (for host filters) and MachineConfigFile (for machine
633 * filters).
634 * @param elmDeviceFilters
635 * @param ll
636 */
637void ConfigFileBase::readUSBDeviceFilters(const xml::ElementNode &elmDeviceFilters,
638 USBDeviceFiltersList &ll)
639{
640 xml::NodesLoop nl1(elmDeviceFilters, "DeviceFilter");
641 const xml::ElementNode *pelmLevel4Child;
642 while ((pelmLevel4Child = nl1.forAllNodes()))
643 {
644 USBDeviceFilter flt;
645 flt.action = USBDeviceFilterAction_Ignore;
646 Utf8Str strAction;
647 if ( pelmLevel4Child->getAttributeValue("name", flt.strName)
648 && pelmLevel4Child->getAttributeValue("active", flt.fActive))
649 {
650 if (!pelmLevel4Child->getAttributeValue("vendorId", flt.strVendorId))
651 pelmLevel4Child->getAttributeValue("vendorid", flt.strVendorId); // used before 1.3
652 if (!pelmLevel4Child->getAttributeValue("productId", flt.strProductId))
653 pelmLevel4Child->getAttributeValue("productid", flt.strProductId); // used before 1.3
654 pelmLevel4Child->getAttributeValue("revision", flt.strRevision);
655 pelmLevel4Child->getAttributeValue("manufacturer", flt.strManufacturer);
656 pelmLevel4Child->getAttributeValue("product", flt.strProduct);
657 if (!pelmLevel4Child->getAttributeValue("serialNumber", flt.strSerialNumber))
658 pelmLevel4Child->getAttributeValue("serialnumber", flt.strSerialNumber); // used before 1.3
659 pelmLevel4Child->getAttributeValue("port", flt.strPort);
660
661 // the next 2 are irrelevant for host USB objects
662 pelmLevel4Child->getAttributeValue("remote", flt.strRemote);
663 pelmLevel4Child->getAttributeValue("maskedInterfaces", flt.ulMaskedInterfaces);
664
665 // action is only used with host USB objects
666 if (pelmLevel4Child->getAttributeValue("action", strAction))
667 {
668 if (strAction == "Ignore")
669 flt.action = USBDeviceFilterAction_Ignore;
670 else if (strAction == "Hold")
671 flt.action = USBDeviceFilterAction_Hold;
672 else
673 throw ConfigFileError(this, pelmLevel4Child, N_("Invalid value '%s' in DeviceFilter/@action attribute"), strAction.c_str());
674 }
675
676 ll.push_back(flt);
677 }
678 }
679}
680
681/**
682 * Reads a media registry entry from the main VirtualBox.xml file.
683 *
684 * Whereas the current media registry code is fairly straightforward, it was quite a mess
685 * with settings format before 1.4 (VirtualBox 2.0 used settings format 1.3). The elements
686 * in the media registry were much more inconsistent, and different elements were used
687 * depending on the type of device and image.
688 *
689 * @param t
690 * @param elmMedium
691 * @param med
692 */
693void ConfigFileBase::readMediumOne(MediaType t,
694 const xml::ElementNode &elmMedium,
695 Medium &med)
696{
697 // <HardDisk uuid="{5471ecdb-1ddb-4012-a801-6d98e226868b}" location="/mnt/innotek-unix/vdis/Windows XP.vdi" format="VDI" type="Normal">
698
699 Utf8Str strUUID;
700 if (!elmMedium.getAttributeValue("uuid", strUUID))
701 throw ConfigFileError(this, &elmMedium, N_("Required %s/@uuid attribute is missing"), elmMedium.getName());
702
703 parseUUID(med.uuid, strUUID, &elmMedium);
704
705 bool fNeedsLocation = true;
706
707 if (t == HardDisk)
708 {
709 if (m->sv < SettingsVersion_v1_4)
710 {
711 // here the system is:
712 // <HardDisk uuid="{....}" type="normal">
713 // <VirtualDiskImage filePath="/path/to/xxx.vdi"/>
714 // </HardDisk>
715
716 fNeedsLocation = false;
717 bool fNeedsFilePath = true;
718 const xml::ElementNode *pelmImage;
719 if ((pelmImage = elmMedium.findChildElement("VirtualDiskImage")))
720 med.strFormat = "VDI";
721 else if ((pelmImage = elmMedium.findChildElement("VMDKImage")))
722 med.strFormat = "VMDK";
723 else if ((pelmImage = elmMedium.findChildElement("VHDImage")))
724 med.strFormat = "VHD";
725 else if ((pelmImage = elmMedium.findChildElement("ISCSIHardDisk")))
726 {
727 med.strFormat = "iSCSI";
728
729 fNeedsFilePath = false;
730 // location is special here: current settings specify an "iscsi://user@server:port/target/lun"
731 // string for the location and also have several disk properties for these, whereas this used
732 // to be hidden in several sub-elements before 1.4, so compose a location string and set up
733 // the properties:
734 med.strLocation = "iscsi://";
735 Utf8Str strUser, strServer, strPort, strTarget, strLun;
736 if (pelmImage->getAttributeValue("userName", strUser))
737 {
738 med.strLocation.append(strUser);
739 med.strLocation.append("@");
740 }
741 Utf8Str strServerAndPort;
742 if (pelmImage->getAttributeValue("server", strServer))
743 {
744 strServerAndPort = strServer;
745 }
746 if (pelmImage->getAttributeValue("port", strPort))
747 {
748 if (strServerAndPort.length())
749 strServerAndPort.append(":");
750 strServerAndPort.append(strPort);
751 }
752 med.strLocation.append(strServerAndPort);
753 if (pelmImage->getAttributeValue("target", strTarget))
754 {
755 med.strLocation.append("/");
756 med.strLocation.append(strTarget);
757 }
758 if (pelmImage->getAttributeValue("lun", strLun))
759 {
760 med.strLocation.append("/");
761 med.strLocation.append(strLun);
762 }
763
764 if (strServer.length() && strPort.length())
765 med.properties["TargetAddress"] = strServerAndPort;
766 if (strTarget.length())
767 med.properties["TargetName"] = strTarget;
768 if (strUser.length())
769 med.properties["InitiatorUsername"] = strUser;
770 Utf8Str strPassword;
771 if (pelmImage->getAttributeValue("password", strPassword))
772 med.properties["InitiatorSecret"] = strPassword;
773 if (strLun.length())
774 med.properties["LUN"] = strLun;
775 }
776 else if ((pelmImage = elmMedium.findChildElement("CustomHardDisk")))
777 {
778 fNeedsFilePath = false;
779 fNeedsLocation = true;
780 // also requires @format attribute, which will be queried below
781 }
782 else
783 throw ConfigFileError(this, &elmMedium, N_("Required %s/VirtualDiskImage element is missing"), elmMedium.getName());
784
785 if (fNeedsFilePath)
786 {
787 if (!(pelmImage->getAttributeValuePath("filePath", med.strLocation)))
788 throw ConfigFileError(this, &elmMedium, N_("Required %s/@filePath attribute is missing"), elmMedium.getName());
789 }
790 }
791
792 if (med.strFormat.isEmpty()) // not set with 1.4 format above, or 1.4 Custom format?
793 if (!elmMedium.getAttributeValue("format", med.strFormat))
794 throw ConfigFileError(this, &elmMedium, N_("Required %s/@format attribute is missing"), elmMedium.getName());
795
796 if (!elmMedium.getAttributeValue("autoReset", med.fAutoReset))
797 med.fAutoReset = false;
798
799 Utf8Str strType;
800 if (elmMedium.getAttributeValue("type", strType))
801 {
802 // pre-1.4 used lower case, so make this case-insensitive
803 strType.toUpper();
804 if (strType == "NORMAL")
805 med.hdType = MediumType_Normal;
806 else if (strType == "IMMUTABLE")
807 med.hdType = MediumType_Immutable;
808 else if (strType == "WRITETHROUGH")
809 med.hdType = MediumType_Writethrough;
810 else if (strType == "SHAREABLE")
811 med.hdType = MediumType_Shareable;
812 else if (strType == "READONLY")
813 med.hdType = MediumType_Readonly;
814 else if (strType == "MULTIATTACH")
815 med.hdType = MediumType_MultiAttach;
816 else
817 throw ConfigFileError(this, &elmMedium, N_("HardDisk/@type attribute must be one of Normal, Immutable, Writethrough, Shareable, Readonly or MultiAttach"));
818 }
819 }
820 else
821 {
822 if (m->sv < SettingsVersion_v1_4)
823 {
824 // DVD and floppy images before 1.4 had "src" attribute instead of "location"
825 if (!elmMedium.getAttributeValue("src", med.strLocation))
826 throw ConfigFileError(this, &elmMedium, N_("Required %s/@src attribute is missing"), elmMedium.getName());
827
828 fNeedsLocation = false;
829 }
830
831 if (!elmMedium.getAttributeValue("format", med.strFormat))
832 {
833 // DVD and floppy images before 1.11 had no format attribute. assign the default.
834 med.strFormat = "RAW";
835 }
836
837 if (t == DVDImage)
838 med.hdType = MediumType_Readonly;
839 else if (t == FloppyImage)
840 med.hdType = MediumType_Writethrough;
841 }
842
843 if (fNeedsLocation)
844 // current files and 1.4 CustomHardDisk elements must have a location attribute
845 if (!elmMedium.getAttributeValue("location", med.strLocation))
846 throw ConfigFileError(this, &elmMedium, N_("Required %s/@location attribute is missing"), elmMedium.getName());
847
848 // 3.2 builds added Description as an attribute, read it silently
849 // and write it back as an element starting with 5.1.26
850 elmMedium.getAttributeValue("Description", med.strDescription);
851
852 xml::NodesLoop nlMediumChildren(elmMedium);
853 const xml::ElementNode *pelmMediumChild;
854 while ((pelmMediumChild = nlMediumChildren.forAllNodes()))
855 {
856 if (pelmMediumChild->nameEquals("Description"))
857 med.strDescription = pelmMediumChild->getValue();
858 else if (pelmMediumChild->nameEquals("Property"))
859 {
860 // handle medium properties
861 Utf8Str strPropName, strPropValue;
862 if ( pelmMediumChild->getAttributeValue("name", strPropName)
863 && pelmMediumChild->getAttributeValue("value", strPropValue) )
864 med.properties[strPropName] = strPropValue;
865 else
866 throw ConfigFileError(this, pelmMediumChild, N_("Required HardDisk/Property/@name or @value attribute is missing"));
867 }
868 }
869}
870
871/**
872 * Reads a media registry entry from the main VirtualBox.xml file and
873 * likewise for all children where applicable.
874 *
875 * @param t
876 * @param elmMedium
877 * @param med
878 */
879void ConfigFileBase::readMedium(MediaType t,
880 const xml::ElementNode &elmMedium,
881 Medium &med)
882{
883 std::list<const xml::ElementNode *> llElementsTodo;
884 llElementsTodo.push_back(&elmMedium);
885 std::list<Medium *> llSettingsTodo;
886 llSettingsTodo.push_back(&med);
887 std::list<uint32_t> llDepthsTodo;
888 llDepthsTodo.push_back(1);
889
890 while (llElementsTodo.size() > 0)
891 {
892 const xml::ElementNode *pElement = llElementsTodo.front();
893 llElementsTodo.pop_front();
894 Medium *pMed = llSettingsTodo.front();
895 llSettingsTodo.pop_front();
896 uint32_t depth = llDepthsTodo.front();
897 llDepthsTodo.pop_front();
898
899 if (depth > SETTINGS_MEDIUM_DEPTH_MAX)
900 throw ConfigFileError(this, pElement, N_("Maximum medium tree depth of %u exceeded"), SETTINGS_MEDIUM_DEPTH_MAX);
901
902 readMediumOne(t, *pElement, *pMed);
903
904 if (t != HardDisk)
905 return;
906
907 // load all children
908 xml::NodesLoop nl2(*pElement, m->sv >= SettingsVersion_v1_4 ? "HardDisk" : "DiffHardDisk");
909 const xml::ElementNode *pelmHDChild;
910 while ((pelmHDChild = nl2.forAllNodes()))
911 {
912 llElementsTodo.push_back(pelmHDChild);
913 pMed->llChildren.push_back(Medium::Empty);
914 llSettingsTodo.push_back(&pMed->llChildren.back());
915 llDepthsTodo.push_back(depth + 1);
916 }
917 }
918}
919
920/**
921 * Reads in the entire \<MediaRegistry\> chunk and stores its media in the lists
922 * of the given MediaRegistry structure.
923 *
924 * This is used in both MainConfigFile and MachineConfigFile since starting with
925 * VirtualBox 4.0, we can have media registries in both.
926 *
927 * For pre-1.4 files, this gets called with the \<DiskRegistry\> chunk instead.
928 *
929 * @param elmMediaRegistry
930 * @param mr
931 */
932void ConfigFileBase::readMediaRegistry(const xml::ElementNode &elmMediaRegistry,
933 MediaRegistry &mr)
934{
935 xml::NodesLoop nl1(elmMediaRegistry);
936 const xml::ElementNode *pelmChild1;
937 while ((pelmChild1 = nl1.forAllNodes()))
938 {
939 MediaType t = Error;
940 if (pelmChild1->nameEquals("HardDisks"))
941 t = HardDisk;
942 else if (pelmChild1->nameEquals("DVDImages"))
943 t = DVDImage;
944 else if (pelmChild1->nameEquals("FloppyImages"))
945 t = FloppyImage;
946 else
947 continue;
948
949 xml::NodesLoop nl2(*pelmChild1);
950 const xml::ElementNode *pelmMedium;
951 while ((pelmMedium = nl2.forAllNodes()))
952 {
953 if ( t == HardDisk
954 && (pelmMedium->nameEquals("HardDisk")))
955 {
956 mr.llHardDisks.push_back(Medium::Empty);
957 readMedium(t, *pelmMedium, mr.llHardDisks.back());
958 }
959 else if ( t == DVDImage
960 && (pelmMedium->nameEquals("Image")))
961 {
962 mr.llDvdImages.push_back(Medium::Empty);
963 readMedium(t, *pelmMedium, mr.llDvdImages.back());
964 }
965 else if ( t == FloppyImage
966 && (pelmMedium->nameEquals("Image")))
967 {
968 mr.llFloppyImages.push_back(Medium::Empty);
969 readMedium(t, *pelmMedium, mr.llFloppyImages.back());
970 }
971 }
972 }
973}
974
975/**
976 * This is common version for reading NAT port forward rule in per-_machine's_adapter_ and
977 * per-network approaches.
978 * Note: this function doesn't in fill given list from xml::ElementNodesList, because there is conflicting
979 * declaration in ovmfreader.h.
980 */
981void ConfigFileBase::readNATForwardRulesMap(const xml::ElementNode &elmParent, NATRulesMap &mapRules)
982{
983 xml::ElementNodesList plstRules;
984 elmParent.getChildElements(plstRules, "Forwarding");
985 for (xml::ElementNodesList::iterator pf = plstRules.begin(); pf != plstRules.end(); ++pf)
986 {
987 NATRule rule;
988 uint32_t port = 0;
989 (*pf)->getAttributeValue("name", rule.strName);
990 (*pf)->getAttributeValue("proto", (uint32_t&)rule.proto);
991 (*pf)->getAttributeValue("hostip", rule.strHostIP);
992 (*pf)->getAttributeValue("hostport", port);
993 rule.u16HostPort = (uint16_t)port;
994 (*pf)->getAttributeValue("guestip", rule.strGuestIP);
995 (*pf)->getAttributeValue("guestport", port);
996 rule.u16GuestPort = (uint16_t)port;
997 mapRules.insert(std::make_pair(rule.strName, rule));
998 }
999}
1000
1001void ConfigFileBase::readNATLoopbacks(const xml::ElementNode &elmParent, NATLoopbackOffsetList &llLoopbacks)
1002{
1003 xml::ElementNodesList plstLoopbacks;
1004 elmParent.getChildElements(plstLoopbacks, "Loopback4");
1005 for (xml::ElementNodesList::iterator lo = plstLoopbacks.begin();
1006 lo != plstLoopbacks.end(); ++lo)
1007 {
1008 NATHostLoopbackOffset loopback;
1009 (*lo)->getAttributeValue("address", loopback.strLoopbackHostAddress);
1010 (*lo)->getAttributeValue("offset", (uint32_t&)loopback.u32Offset);
1011 llLoopbacks.push_back(loopback);
1012 }
1013}
1014
1015
1016/**
1017 * Adds a "version" attribute to the given XML element with the
1018 * VirtualBox settings version (e.g. "1.10-linux"). Used by
1019 * the XML format for the root element and by the OVF export
1020 * for the vbox:Machine element.
1021 * @param elm
1022 */
1023void ConfigFileBase::setVersionAttribute(xml::ElementNode &elm)
1024{
1025 const char *pcszVersion = NULL;
1026 switch (m->sv)
1027 {
1028 case SettingsVersion_v1_8:
1029 pcszVersion = "1.8";
1030 break;
1031
1032 case SettingsVersion_v1_9:
1033 pcszVersion = "1.9";
1034 break;
1035
1036 case SettingsVersion_v1_10:
1037 pcszVersion = "1.10";
1038 break;
1039
1040 case SettingsVersion_v1_11:
1041 pcszVersion = "1.11";
1042 break;
1043
1044 case SettingsVersion_v1_12:
1045 pcszVersion = "1.12";
1046 break;
1047
1048 case SettingsVersion_v1_13:
1049 pcszVersion = "1.13";
1050 break;
1051
1052 case SettingsVersion_v1_14:
1053 pcszVersion = "1.14";
1054 break;
1055
1056 case SettingsVersion_v1_15:
1057 pcszVersion = "1.15";
1058 break;
1059
1060 case SettingsVersion_v1_16:
1061 pcszVersion = "1.16";
1062 break;
1063
1064 case SettingsVersion_v1_17:
1065 pcszVersion = "1.17";
1066 break;
1067
1068 case SettingsVersion_v1_18:
1069 pcszVersion = "1.18";
1070 break;
1071
1072 case SettingsVersion_v1_19:
1073 pcszVersion = "1.19";
1074 break;
1075
1076 case SettingsVersion_v1_20:
1077 pcszVersion = "1.20";
1078 break;
1079
1080 default:
1081 // catch human error: the assertion below will trigger in debug
1082 // or dbgopt builds, so hopefully this will get noticed sooner in
1083 // the future, because it's easy to forget top update something.
1084 AssertMsg(m->sv <= SettingsVersion_v1_7, ("Settings.cpp: unexpected settings version %d, unhandled future version?\n", m->sv));
1085 // silently upgrade if this is less than 1.7 because that's the oldest we can write
1086 if (m->sv <= SettingsVersion_v1_7)
1087 {
1088 pcszVersion = "1.7";
1089 m->sv = SettingsVersion_v1_7;
1090 }
1091 else
1092 {
1093 // This is reached for SettingsVersion_Future and forgotten
1094 // settings version after SettingsVersion_v1_7, which should
1095 // not happen (see assertion above). Set the version to the
1096 // latest known version, to minimize loss of information, but
1097 // as we can't predict the future we have to use some format
1098 // we know, and latest should be the best choice. Note that
1099 // for "forgotten settings" this may not be the best choice,
1100 // but as it's an omission of someone who changed this file
1101 // it's the only generic possibility.
1102 pcszVersion = "1.20";
1103 m->sv = SettingsVersion_v1_20;
1104 }
1105 break;
1106 }
1107
1108 m->strSettingsVersionFull = Utf8StrFmt("%s-%s",
1109 pcszVersion,
1110 VBOX_XML_PLATFORM); // e.g. "linux"
1111 elm.setAttribute("version", m->strSettingsVersionFull);
1112}
1113
1114
1115/**
1116 * Creates a special backup file in case there is a version
1117 * bump, so that it is possible to go back to the previous
1118 * state. This is done only once (not for every settings
1119 * version bump), when the settings version is newer than
1120 * the version read from the config file. Must be called
1121 * before ConfigFileBase::createStubDocument, because that
1122 * method may alter information which this method needs.
1123 */
1124void ConfigFileBase::specialBackupIfFirstBump()
1125{
1126 // Since this gets called before the XML document is actually written out,
1127 // this is where we must check whether we're upgrading the settings version
1128 // and need to make a backup, so the user can go back to an earlier
1129 // VirtualBox version and recover his old settings files.
1130 if ( (m->svRead != SettingsVersion_Null) // old file exists?
1131 && (m->svRead < m->sv) // we're upgrading?
1132 )
1133 {
1134 // compose new filename: strip off trailing ".xml"/".vbox"
1135 Utf8Str strFilenameNew;
1136 Utf8Str strExt = ".xml";
1137 if (m->strFilename.endsWith(".xml"))
1138 strFilenameNew = m->strFilename.substr(0, m->strFilename.length() - 4);
1139 else if (m->strFilename.endsWith(".vbox"))
1140 {
1141 strFilenameNew = m->strFilename.substr(0, m->strFilename.length() - 5);
1142 strExt = ".vbox";
1143 }
1144
1145 // and append something like "-1.3-linux.xml"
1146 strFilenameNew.append("-");
1147 strFilenameNew.append(m->strSettingsVersionFull); // e.g. "1.3-linux"
1148 strFilenameNew.append(strExt); // .xml for main config, .vbox for machine config
1149
1150 // Copying the file cannot be avoided, as doing tricks with renaming
1151 // causes trouble on OS X with aliases (which follow the rename), and
1152 // on all platforms there is a risk of "losing" the VM config when
1153 // running out of space, as a rename here couldn't be rolled back.
1154 // Ignoring all errors besides running out of space is intentional, as
1155 // we don't want to do anything if the file already exists.
1156 int vrc = RTFileCopy(m->strFilename.c_str(), strFilenameNew.c_str());
1157 if (RT_UNLIKELY(vrc == VERR_DISK_FULL))
1158 throw ConfigFileError(this, NULL, N_("Cannot create settings backup file when upgrading to a newer settings format"));
1159
1160 // do this only once
1161 m->svRead = SettingsVersion_Null;
1162 }
1163}
1164
1165/**
1166 * Creates a new stub xml::Document in the m->pDoc member with the
1167 * root "VirtualBox" element set up. This is used by both
1168 * MainConfigFile and MachineConfigFile at the beginning of writing
1169 * out their XML.
1170 *
1171 * Before calling this, it is the responsibility of the caller to
1172 * set the "sv" member to the required settings version that is to
1173 * be written. For newly created files, the settings version will be
1174 * recent (1.12 or later if necessary); for files read in from disk
1175 * earlier, it will be the settings version indicated in the file.
1176 * However, this method will silently make sure that the settings
1177 * version is always at least 1.7 and change it if necessary, since
1178 * there is no write support for earlier settings versions.
1179 */
1180void ConfigFileBase::createStubDocument()
1181{
1182 Assert(m->pDoc == NULL);
1183 m->pDoc = new xml::Document;
1184
1185 m->pelmRoot = m->pDoc->createRootElement("VirtualBox",
1186 "\n"
1187 "** DO NOT EDIT THIS FILE.\n"
1188 "** If you make changes to this file while any VirtualBox related application\n"
1189 "** is running, your changes will be overwritten later, without taking effect.\n"
1190 "** Use VBoxManage or the VirtualBox Manager GUI to make changes.\n"
1191);
1192 m->pelmRoot->setAttribute("xmlns", VBOX_XML_NAMESPACE);
1193 // Have the code for producing a proper schema reference. Not used by most
1194 // tools, so don't bother doing it. The schema is not on the server anyway.
1195#ifdef VBOX_WITH_SETTINGS_SCHEMA
1196 m->pelmRoot->setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
1197 m->pelmRoot->setAttribute("xsi:schemaLocation", VBOX_XML_NAMESPACE " " VBOX_XML_SCHEMA);
1198#endif
1199
1200 // add settings version attribute to root element, update m->strSettingsVersionFull
1201 setVersionAttribute(*m->pelmRoot);
1202
1203 LogRel(("Saving settings file \"%s\" with version \"%s\"\n", m->strFilename.c_str(), m->strSettingsVersionFull.c_str()));
1204}
1205
1206/**
1207 * Creates an \<ExtraData\> node under the given parent element with
1208 * \<ExtraDataItem\> childern according to the contents of the given
1209 * map.
1210 *
1211 * This is in ConfigFileBase because it's used in both MainConfigFile
1212 * and MachineConfigFile, which both can have extradata.
1213 *
1214 * @param elmParent
1215 * @param me
1216 */
1217void ConfigFileBase::buildExtraData(xml::ElementNode &elmParent,
1218 const StringsMap &me)
1219{
1220 if (me.size())
1221 {
1222 xml::ElementNode *pelmExtraData = elmParent.createChild("ExtraData");
1223 for (StringsMap::const_iterator it = me.begin();
1224 it != me.end();
1225 ++it)
1226 {
1227 const Utf8Str &strName = it->first;
1228 const Utf8Str &strValue = it->second;
1229 xml::ElementNode *pelmThis = pelmExtraData->createChild("ExtraDataItem");
1230 pelmThis->setAttribute("name", strName);
1231 pelmThis->setAttribute("value", strValue);
1232 }
1233 }
1234}
1235
1236/**
1237 * Creates \<DeviceFilter\> nodes under the given parent element according to
1238 * the contents of the given USBDeviceFiltersList. This is in ConfigFileBase
1239 * because it's used in both MainConfigFile (for host filters) and
1240 * MachineConfigFile (for machine filters).
1241 *
1242 * If fHostMode is true, this means that we're supposed to write filters
1243 * for the IHost interface (respect "action", omit "strRemote" and
1244 * "ulMaskedInterfaces" in struct USBDeviceFilter).
1245 *
1246 * @param elmParent
1247 * @param ll
1248 * @param fHostMode
1249 */
1250void ConfigFileBase::buildUSBDeviceFilters(xml::ElementNode &elmParent,
1251 const USBDeviceFiltersList &ll,
1252 bool fHostMode)
1253{
1254 for (USBDeviceFiltersList::const_iterator it = ll.begin();
1255 it != ll.end();
1256 ++it)
1257 {
1258 const USBDeviceFilter &flt = *it;
1259 xml::ElementNode *pelmFilter = elmParent.createChild("DeviceFilter");
1260 pelmFilter->setAttribute("name", flt.strName);
1261 pelmFilter->setAttribute("active", flt.fActive);
1262 if (flt.strVendorId.length())
1263 pelmFilter->setAttribute("vendorId", flt.strVendorId);
1264 if (flt.strProductId.length())
1265 pelmFilter->setAttribute("productId", flt.strProductId);
1266 if (flt.strRevision.length())
1267 pelmFilter->setAttribute("revision", flt.strRevision);
1268 if (flt.strManufacturer.length())
1269 pelmFilter->setAttribute("manufacturer", flt.strManufacturer);
1270 if (flt.strProduct.length())
1271 pelmFilter->setAttribute("product", flt.strProduct);
1272 if (flt.strSerialNumber.length())
1273 pelmFilter->setAttribute("serialNumber", flt.strSerialNumber);
1274 if (flt.strPort.length())
1275 pelmFilter->setAttribute("port", flt.strPort);
1276
1277 if (fHostMode)
1278 {
1279 const char *pcsz =
1280 (flt.action == USBDeviceFilterAction_Ignore) ? "Ignore"
1281 : /*(flt.action == USBDeviceFilterAction_Hold) ?*/ "Hold";
1282 pelmFilter->setAttribute("action", pcsz);
1283 }
1284 else
1285 {
1286 if (flt.strRemote.length())
1287 pelmFilter->setAttribute("remote", flt.strRemote);
1288 if (flt.ulMaskedInterfaces)
1289 pelmFilter->setAttribute("maskedInterfaces", flt.ulMaskedInterfaces);
1290 }
1291 }
1292}
1293
1294/**
1295 * Creates a single \<HardDisk\> element for the given Medium structure
1296 * and all child hard disks underneath. Called from MainConfigFile::write().
1297 *
1298 * @param t
1299 * @param elmMedium
1300 * @param med
1301 */
1302void ConfigFileBase::buildMedium(MediaType t,
1303 xml::ElementNode &elmMedium,
1304 const Medium &med)
1305{
1306 std::list<const Medium *> llSettingsTodo;
1307 llSettingsTodo.push_back(&med);
1308 std::list<xml::ElementNode *> llElementsTodo;
1309 llElementsTodo.push_back(&elmMedium);
1310 std::list<uint32_t> llDepthsTodo;
1311 llDepthsTodo.push_back(1);
1312
1313 while (llSettingsTodo.size() > 0)
1314 {
1315 const Medium *pMed = llSettingsTodo.front();
1316 llSettingsTodo.pop_front();
1317 xml::ElementNode *pElement = llElementsTodo.front();
1318 llElementsTodo.pop_front();
1319 uint32_t depth = llDepthsTodo.front();
1320 llDepthsTodo.pop_front();
1321
1322 if (depth > SETTINGS_MEDIUM_DEPTH_MAX)
1323 throw ConfigFileError(this, pElement, N_("Maximum medium tree depth of %u exceeded"), SETTINGS_MEDIUM_DEPTH_MAX);
1324
1325 xml::ElementNode *pelmMedium;
1326
1327 if (t == HardDisk)
1328 pelmMedium = pElement->createChild("HardDisk");
1329 else
1330 pelmMedium = pElement->createChild("Image");
1331
1332 pelmMedium->setAttribute("uuid", pMed->uuid.toStringCurly());
1333
1334 pelmMedium->setAttributePath("location", pMed->strLocation);
1335
1336 if (t == HardDisk || RTStrICmp(pMed->strFormat.c_str(), "RAW"))
1337 pelmMedium->setAttribute("format", pMed->strFormat);
1338 if ( t == HardDisk
1339 && pMed->fAutoReset)
1340 pelmMedium->setAttribute("autoReset", pMed->fAutoReset);
1341 if (pMed->strDescription.length())
1342 pelmMedium->createChild("Description")->addContent(pMed->strDescription);
1343
1344 for (StringsMap::const_iterator it = pMed->properties.begin();
1345 it != pMed->properties.end();
1346 ++it)
1347 {
1348 xml::ElementNode *pelmProp = pelmMedium->createChild("Property");
1349 pelmProp->setAttribute("name", it->first);
1350 pelmProp->setAttribute("value", it->second);
1351 }
1352
1353 // only for base hard disks, save the type
1354 if (depth == 1)
1355 {
1356 // no need to save the usual DVD/floppy medium types
1357 if ( ( t != DVDImage
1358 || ( pMed->hdType != MediumType_Writethrough // shouldn't happen
1359 && pMed->hdType != MediumType_Readonly))
1360 && ( t != FloppyImage
1361 || pMed->hdType != MediumType_Writethrough))
1362 {
1363 const char *pcszType =
1364 pMed->hdType == MediumType_Normal ? "Normal" :
1365 pMed->hdType == MediumType_Immutable ? "Immutable" :
1366 pMed->hdType == MediumType_Writethrough ? "Writethrough" :
1367 pMed->hdType == MediumType_Shareable ? "Shareable" :
1368 pMed->hdType == MediumType_Readonly ? "Readonly" :
1369 pMed->hdType == MediumType_MultiAttach ? "MultiAttach" :
1370 "INVALID";
1371 pelmMedium->setAttribute("type", pcszType);
1372 }
1373 }
1374
1375 /* save all children */
1376 MediaList::const_iterator itBegin = pMed->llChildren.begin();
1377 MediaList::const_iterator itEnd = pMed->llChildren.end();
1378 for (MediaList::const_iterator it = itBegin; it != itEnd; ++it)
1379 {
1380 llSettingsTodo.push_back(&*it);
1381 llElementsTodo.push_back(pelmMedium);
1382 llDepthsTodo.push_back(depth + 1);
1383 }
1384 }
1385}
1386
1387/**
1388 * Creates a \<MediaRegistry\> node under the given parent and writes out all
1389 * hard disks and DVD and floppy images from the lists in the given MediaRegistry
1390 * structure under it.
1391 *
1392 * This is used in both MainConfigFile and MachineConfigFile since starting with
1393 * VirtualBox 4.0, we can have media registries in both.
1394 *
1395 * @param elmParent
1396 * @param mr
1397 */
1398void ConfigFileBase::buildMediaRegistry(xml::ElementNode &elmParent,
1399 const MediaRegistry &mr)
1400{
1401 if (mr.llHardDisks.size() == 0 && mr.llDvdImages.size() == 0 && mr.llFloppyImages.size() == 0)
1402 return;
1403
1404 xml::ElementNode *pelmMediaRegistry = elmParent.createChild("MediaRegistry");
1405
1406 if (mr.llHardDisks.size())
1407 {
1408 xml::ElementNode *pelmHardDisks = pelmMediaRegistry->createChild("HardDisks");
1409 for (MediaList::const_iterator it = mr.llHardDisks.begin();
1410 it != mr.llHardDisks.end();
1411 ++it)
1412 {
1413 buildMedium(HardDisk, *pelmHardDisks, *it);
1414 }
1415 }
1416
1417 if (mr.llDvdImages.size())
1418 {
1419 xml::ElementNode *pelmDVDImages = pelmMediaRegistry->createChild("DVDImages");
1420 for (MediaList::const_iterator it = mr.llDvdImages.begin();
1421 it != mr.llDvdImages.end();
1422 ++it)
1423 {
1424 buildMedium(DVDImage, *pelmDVDImages, *it);
1425 }
1426 }
1427
1428 if (mr.llFloppyImages.size())
1429 {
1430 xml::ElementNode *pelmFloppyImages = pelmMediaRegistry->createChild("FloppyImages");
1431 for (MediaList::const_iterator it = mr.llFloppyImages.begin();
1432 it != mr.llFloppyImages.end();
1433 ++it)
1434 {
1435 buildMedium(FloppyImage, *pelmFloppyImages, *it);
1436 }
1437 }
1438}
1439
1440/**
1441 * Serialize NAT port-forwarding rules in parent container.
1442 * Note: it's responsibility of caller to create parent of the list tag.
1443 * because this method used for serializing per-_mahine's_adapter_ and per-network approaches.
1444 */
1445void ConfigFileBase::buildNATForwardRulesMap(xml::ElementNode &elmParent, const NATRulesMap &mapRules)
1446{
1447 for (NATRulesMap::const_iterator r = mapRules.begin();
1448 r != mapRules.end(); ++r)
1449 {
1450 xml::ElementNode *pelmPF;
1451 pelmPF = elmParent.createChild("Forwarding");
1452 const NATRule &nr = r->second;
1453 if (nr.strName.length())
1454 pelmPF->setAttribute("name", nr.strName);
1455 pelmPF->setAttribute("proto", nr.proto);
1456 if (nr.strHostIP.length())
1457 pelmPF->setAttribute("hostip", nr.strHostIP);
1458 if (nr.u16HostPort)
1459 pelmPF->setAttribute("hostport", nr.u16HostPort);
1460 if (nr.strGuestIP.length())
1461 pelmPF->setAttribute("guestip", nr.strGuestIP);
1462 if (nr.u16GuestPort)
1463 pelmPF->setAttribute("guestport", nr.u16GuestPort);
1464 }
1465}
1466
1467
1468void ConfigFileBase::buildNATLoopbacks(xml::ElementNode &elmParent, const NATLoopbackOffsetList &natLoopbackOffsetList)
1469{
1470 for (NATLoopbackOffsetList::const_iterator lo = natLoopbackOffsetList.begin();
1471 lo != natLoopbackOffsetList.end(); ++lo)
1472 {
1473 xml::ElementNode *pelmLo;
1474 pelmLo = elmParent.createChild("Loopback4");
1475 pelmLo->setAttribute("address", (*lo).strLoopbackHostAddress);
1476 pelmLo->setAttribute("offset", (*lo).u32Offset);
1477 }
1478}
1479
1480/**
1481 * Cleans up memory allocated by the internal XML parser. To be called by
1482 * descendant classes when they're done analyzing the DOM tree to discard it.
1483 */
1484void ConfigFileBase::clearDocument()
1485{
1486 m->cleanup();
1487}
1488
1489/**
1490 * Returns true only if the underlying config file exists on disk;
1491 * either because the file has been loaded from disk, or it's been written
1492 * to disk, or both.
1493 * @return
1494 */
1495bool ConfigFileBase::fileExists()
1496{
1497 return m->fFileExists;
1498}
1499
1500/**
1501 * Returns the settings file version
1502 *
1503 * @returns Settings file version enum.
1504 */
1505SettingsVersion_T ConfigFileBase::getSettingsVersion()
1506{
1507 return m->sv;
1508}
1509
1510
1511/**
1512 * Copies the base variables from another instance. Used by Machine::saveSettings
1513 * so that the settings version does not get lost when a copy of the Machine settings
1514 * file is made to see if settings have actually changed.
1515 * @param b
1516 */
1517void ConfigFileBase::copyBaseFrom(const ConfigFileBase &b)
1518{
1519 m->copyFrom(*b.m);
1520}
1521
1522////////////////////////////////////////////////////////////////////////////////
1523//
1524// Structures shared between Machine XML and VirtualBox.xml
1525//
1526////////////////////////////////////////////////////////////////////////////////
1527
1528
1529/**
1530 * Constructor. Needs to set sane defaults which stand the test of time.
1531 */
1532USBDeviceFilter::USBDeviceFilter() :
1533 fActive(false),
1534 action(USBDeviceFilterAction_Null),
1535 ulMaskedInterfaces(0)
1536{
1537}
1538
1539/**
1540 * Comparison operator. This gets called from MachineConfigFile::operator==,
1541 * which in turn gets called from Machine::saveSettings to figure out whether
1542 * machine settings have really changed and thus need to be written out to disk.
1543 */
1544bool USBDeviceFilter::operator==(const USBDeviceFilter &u) const
1545{
1546 return (this == &u)
1547 || ( strName == u.strName
1548 && fActive == u.fActive
1549 && strVendorId == u.strVendorId
1550 && strProductId == u.strProductId
1551 && strRevision == u.strRevision
1552 && strManufacturer == u.strManufacturer
1553 && strProduct == u.strProduct
1554 && strSerialNumber == u.strSerialNumber
1555 && strPort == u.strPort
1556 && action == u.action
1557 && strRemote == u.strRemote
1558 && ulMaskedInterfaces == u.ulMaskedInterfaces);
1559}
1560
1561/**
1562 * Constructor. Needs to set sane defaults which stand the test of time.
1563 */
1564settings::Medium::Medium() :
1565 fAutoReset(false),
1566 hdType(MediumType_Normal)
1567{
1568}
1569
1570/**
1571 * Comparison operator. This gets called from MachineConfigFile::operator==,
1572 * which in turn gets called from Machine::saveSettings to figure out whether
1573 * machine settings have really changed and thus need to be written out to disk.
1574 */
1575bool settings::Medium::operator==(const settings::Medium &m) const
1576{
1577 return (this == &m)
1578 || ( uuid == m.uuid
1579 && strLocation == m.strLocation
1580 && strDescription == m.strDescription
1581 && strFormat == m.strFormat
1582 && fAutoReset == m.fAutoReset
1583 && properties == m.properties
1584 && hdType == m.hdType
1585 && llChildren == m.llChildren); // this is deep and recurses
1586}
1587
1588const struct settings::Medium settings::Medium::Empty; /* default ctor is OK */
1589
1590/**
1591 * Comparison operator. This gets called from MachineConfigFile::operator==,
1592 * which in turn gets called from Machine::saveSettings to figure out whether
1593 * machine settings have really changed and thus need to be written out to disk.
1594 */
1595bool MediaRegistry::operator==(const MediaRegistry &m) const
1596{
1597 return (this == &m)
1598 || ( llHardDisks == m.llHardDisks
1599 && llDvdImages == m.llDvdImages
1600 && llFloppyImages == m.llFloppyImages);
1601}
1602
1603/**
1604 * Constructor. Needs to set sane defaults which stand the test of time.
1605 */
1606NATRule::NATRule() :
1607 proto(NATProtocol_TCP),
1608 u16HostPort(0),
1609 u16GuestPort(0)
1610{
1611}
1612
1613/**
1614 * Comparison operator. This gets called from MachineConfigFile::operator==,
1615 * which in turn gets called from Machine::saveSettings to figure out whether
1616 * machine settings have really changed and thus need to be written out to disk.
1617 */
1618bool NATRule::operator==(const NATRule &r) const
1619{
1620 return (this == &r)
1621 || ( strName == r.strName
1622 && proto == r.proto
1623 && u16HostPort == r.u16HostPort
1624 && strHostIP == r.strHostIP
1625 && u16GuestPort == r.u16GuestPort
1626 && strGuestIP == r.strGuestIP);
1627}
1628
1629/**
1630 * Constructor. Needs to set sane defaults which stand the test of time.
1631 */
1632NATHostLoopbackOffset::NATHostLoopbackOffset() :
1633 u32Offset(0)
1634{
1635}
1636
1637/**
1638 * Comparison operator. This gets called from MachineConfigFile::operator==,
1639 * which in turn gets called from Machine::saveSettings to figure out whether
1640 * machine settings have really changed and thus need to be written out to disk.
1641 */
1642bool NATHostLoopbackOffset::operator==(const NATHostLoopbackOffset &o) const
1643{
1644 return (this == &o)
1645 || ( strLoopbackHostAddress == o.strLoopbackHostAddress
1646 && u32Offset == o.u32Offset);
1647}
1648
1649
1650////////////////////////////////////////////////////////////////////////////////
1651//
1652// VirtualBox.xml structures
1653//
1654////////////////////////////////////////////////////////////////////////////////
1655
1656PlatformProperties::PlatformProperties()
1657 : fExclusiveHwVirt(true)
1658{
1659#if defined(RT_OS_DARWIN) || defined(RT_OS_WINDOWS) || defined(RT_OS_SOLARIS)
1660 fExclusiveHwVirt = false; /** BUGBUG Does this apply to MacOS on ARM as well? */
1661#endif
1662}
1663
1664/**
1665 * Constructor. Needs to set sane defaults which stand the test of time.
1666 */
1667SystemProperties::SystemProperties()
1668 : uProxyMode(ProxyMode_System)
1669 , uLogHistoryCount(3)
1670{
1671}
1672
1673#ifdef VBOX_WITH_UPDATE_AGENT
1674UpdateAgent::UpdateAgent()
1675 : fEnabled(false)
1676 , enmChannel(UpdateChannel_Stable)
1677 , uCheckFreqSeconds(RT_SEC_1DAY)
1678 , uCheckCount(0)
1679{
1680}
1681#endif /* VBOX_WITH_UPDATE_AGENT */
1682
1683/**
1684 * Constructor. Needs to set sane defaults which stand the test of time.
1685 */
1686DhcpOptValue::DhcpOptValue()
1687 : strValue()
1688 , enmEncoding(DHCPOptionEncoding_Normal)
1689{
1690}
1691
1692/**
1693 * Non-standard constructor.
1694 */
1695DhcpOptValue::DhcpOptValue(const com::Utf8Str &aText, DHCPOptionEncoding_T aEncoding)
1696 : strValue(aText)
1697 , enmEncoding(aEncoding)
1698{
1699}
1700
1701/**
1702 * Default constructor.
1703 */
1704DHCPGroupCondition::DHCPGroupCondition()
1705 : fInclusive(true)
1706 , enmType(DHCPGroupConditionType_MAC)
1707 , strValue()
1708{
1709}
1710
1711/**
1712 * Default constructor.
1713 */
1714DHCPConfig::DHCPConfig()
1715 : mapOptions()
1716 , secMinLeaseTime(0)
1717 , secDefaultLeaseTime(0)
1718 , secMaxLeaseTime(0)
1719{
1720}
1721
1722/**
1723 * Default constructor.
1724 */
1725DHCPGroupConfig::DHCPGroupConfig()
1726 : DHCPConfig()
1727 , strName()
1728 , vecConditions()
1729{
1730}
1731
1732/**
1733 * Default constructor.
1734 */
1735DHCPIndividualConfig::DHCPIndividualConfig()
1736 : DHCPConfig()
1737 , strMACAddress()
1738 , strVMName()
1739 , uSlot(0)
1740{
1741}
1742
1743/**
1744 * Constructor. Needs to set sane defaults which stand the test of time.
1745 */
1746DHCPServer::DHCPServer()
1747 : fEnabled(false)
1748{
1749}
1750
1751/**
1752 * Constructor. Needs to set sane defaults which stand the test of time.
1753 */
1754NATNetwork::NATNetwork() :
1755 fEnabled(true),
1756 fIPv6Enabled(false),
1757 fAdvertiseDefaultIPv6Route(false),
1758 fNeedDhcpServer(true),
1759 u32HostLoopback6Offset(0)
1760{
1761}
1762
1763#ifdef VBOX_WITH_VMNET
1764/**
1765 * Constructor. Needs to set sane defaults which stand the test of time.
1766 */
1767HostOnlyNetwork::HostOnlyNetwork() :
1768 strNetworkMask("255.255.255.0"),
1769 strIPLower("192.168.56.1"),
1770 strIPUpper("192.168.56.199"),
1771 fEnabled(true)
1772{
1773 uuid.create();
1774}
1775#endif /* VBOX_WITH_VMNET */
1776
1777#ifdef VBOX_WITH_CLOUD_NET
1778/**
1779 * Constructor. Needs to set sane defaults which stand the test of time.
1780 */
1781CloudNetwork::CloudNetwork() :
1782 strProviderShortName("OCI"),
1783 strProfileName("Default"),
1784 fEnabled(true)
1785{
1786}
1787#endif /* VBOX_WITH_CLOUD_NET */
1788
1789
1790
1791////////////////////////////////////////////////////////////////////////////////
1792//
1793// MainConfigFile
1794//
1795////////////////////////////////////////////////////////////////////////////////
1796
1797/**
1798 * Reads one \<MachineEntry\> from the main VirtualBox.xml file.
1799 * @param elmMachineRegistry
1800 */
1801void MainConfigFile::readMachineRegistry(const xml::ElementNode &elmMachineRegistry)
1802{
1803 // <MachineEntry uuid="{ xxx }" src=" xxx "/>
1804 xml::NodesLoop nl1(elmMachineRegistry);
1805 const xml::ElementNode *pelmChild1;
1806 while ((pelmChild1 = nl1.forAllNodes()))
1807 {
1808 if (pelmChild1->nameEquals("MachineEntry"))
1809 {
1810 MachineRegistryEntry mre;
1811 Utf8Str strUUID;
1812 if ( pelmChild1->getAttributeValue("uuid", strUUID)
1813 && pelmChild1->getAttributeValue("src", mre.strSettingsFile) )
1814 {
1815 parseUUID(mre.uuid, strUUID, pelmChild1);
1816 llMachines.push_back(mre);
1817 }
1818 else
1819 throw ConfigFileError(this, pelmChild1, N_("Required MachineEntry/@uuid or @src attribute is missing"));
1820 }
1821 }
1822}
1823
1824/**
1825 * Builds the XML tree for the DHCP servers.
1826 */
1827void MainConfigFile::buildDHCPServers(xml::ElementNode &elmDHCPServers, DHCPServersList const &ll)
1828{
1829 for (DHCPServersList::const_iterator it = ll.begin(); it != ll.end(); ++it)
1830 {
1831 const DHCPServer &srv = *it;
1832 xml::ElementNode *pElmThis = elmDHCPServers.createChild("DHCPServer");
1833
1834 pElmThis->setAttribute("networkName", srv.strNetworkName);
1835 pElmThis->setAttribute("IPAddress", srv.strIPAddress);
1836 DhcpOptConstIterator itOpt = srv.globalConfig.mapOptions.find(DHCPOption_SubnetMask);
1837 if (itOpt != srv.globalConfig.mapOptions.end())
1838 pElmThis->setAttribute("networkMask", itOpt->second.strValue);
1839 pElmThis->setAttribute("lowerIP", srv.strIPLower);
1840 pElmThis->setAttribute("upperIP", srv.strIPUpper);
1841 pElmThis->setAttribute("enabled", (srv.fEnabled) ? 1 : 0); // too bad we chose 1 vs. 0 here
1842
1843 /* We don't want duplicate validation check of networkMask here*/
1844 if (srv.globalConfig.mapOptions.size() > (itOpt != srv.globalConfig.mapOptions.end() ? 1U : 0U))
1845 {
1846 xml::ElementNode *pElmOptions = pElmThis->createChild("Options");
1847 buildDHCPOptions(*pElmOptions, srv.globalConfig, true);
1848 }
1849
1850 for (DHCPGroupConfigVec::const_iterator itGroup = srv.vecGroupConfigs.begin();
1851 itGroup != srv.vecGroupConfigs.end(); ++itGroup)
1852 {
1853 DHCPGroupConfig const &rGroupConfig = *itGroup;
1854
1855 xml::ElementNode *pElmGroup = pElmThis->createChild("Group");
1856 pElmGroup->setAttribute("name", rGroupConfig.strName);
1857 buildDHCPOptions(*pElmGroup, rGroupConfig, false);
1858
1859 for (DHCPGroupConditionVec::const_iterator itCond = rGroupConfig.vecConditions.begin();
1860 itCond != rGroupConfig.vecConditions.end(); ++itCond)
1861 {
1862 xml::ElementNode *pElmCondition = pElmGroup->createChild("Condition");
1863 pElmCondition->setAttribute("inclusive", itCond->fInclusive);
1864 pElmCondition->setAttribute("type", (int32_t)itCond->enmType);
1865 pElmCondition->setAttribute("value", itCond->strValue);
1866 }
1867 }
1868
1869 for (DHCPIndividualConfigMap::const_iterator itHost = srv.mapIndividualConfigs.begin();
1870 itHost != srv.mapIndividualConfigs.end(); ++itHost)
1871 {
1872 DHCPIndividualConfig const &rIndividualConfig = itHost->second;
1873
1874 xml::ElementNode *pElmConfig = pElmThis->createChild("Config");
1875 if (rIndividualConfig.strMACAddress.isNotEmpty())
1876 pElmConfig->setAttribute("MACAddress", rIndividualConfig.strMACAddress);
1877 if (rIndividualConfig.strVMName.isNotEmpty())
1878 pElmConfig->setAttribute("vm-name", rIndividualConfig.strVMName);
1879 if (rIndividualConfig.uSlot != 0 || rIndividualConfig.strVMName.isNotEmpty())
1880 pElmConfig->setAttribute("slot", rIndividualConfig.uSlot);
1881 if (rIndividualConfig.strFixedAddress.isNotEmpty())
1882 pElmConfig->setAttribute("fixedAddress", rIndividualConfig.strFixedAddress);
1883 buildDHCPOptions(*pElmConfig, rIndividualConfig, false);
1884 }
1885 }
1886}
1887
1888/**
1889 * Worker for buildDHCPServers() that builds Options or Config element trees.
1890 */
1891void MainConfigFile::buildDHCPOptions(xml::ElementNode &elmOptions, DHCPConfig const &rConfig, bool fSkipSubnetMask)
1892{
1893 /* Generic (and optional) attributes on the Options or Config element: */
1894 if (rConfig.secMinLeaseTime > 0)
1895 elmOptions.setAttribute("secMinLeaseTime", rConfig.secMinLeaseTime);
1896 if (rConfig.secDefaultLeaseTime > 0)
1897 elmOptions.setAttribute("secDefaultLeaseTime", rConfig.secDefaultLeaseTime);
1898 if (rConfig.secMaxLeaseTime > 0)
1899 elmOptions.setAttribute("secMaxLeaseTime", rConfig.secMaxLeaseTime);
1900 if (rConfig.strForcedOptions.isNotEmpty())
1901 elmOptions.setAttribute("forcedOptions", rConfig.strForcedOptions);
1902 if (rConfig.strSuppressedOptions.isNotEmpty())
1903 elmOptions.setAttribute("suppressedOptions", rConfig.strSuppressedOptions);
1904
1905 /* The DHCP options are <Option> child elements: */
1906 for (DhcpOptConstIterator it = rConfig.mapOptions.begin(); it != rConfig.mapOptions.end(); ++it)
1907 if (it->first != DHCPOption_SubnetMask || !fSkipSubnetMask)
1908 {
1909 xml::ElementNode *pElmOption = elmOptions.createChild("Option");
1910 pElmOption->setAttribute("name", it->first);
1911 pElmOption->setAttribute("value", it->second.strValue);
1912 if (it->second.enmEncoding != DHCPOptionEncoding_Normal)
1913 pElmOption->setAttribute("encoding", (int32_t)it->second.enmEncoding);
1914 }
1915}
1916
1917/**
1918 * Reads in the \<DHCPServers\> chunk.
1919 * @param elmDHCPServers
1920 */
1921void MainConfigFile::readDHCPServers(const xml::ElementNode &elmDHCPServers)
1922{
1923 xml::NodesLoop nl1(elmDHCPServers);
1924 const xml::ElementNode *pelmServer;
1925 while ((pelmServer = nl1.forAllNodes()))
1926 {
1927 if (pelmServer->nameEquals("DHCPServer"))
1928 {
1929 DHCPServer srv;
1930 if ( pelmServer->getAttributeValue("networkName", srv.strNetworkName)
1931 && pelmServer->getAttributeValue("IPAddress", srv.strIPAddress)
1932 && pelmServer->getAttributeValue("networkMask", srv.globalConfig.mapOptions[DHCPOption_SubnetMask].strValue)
1933 && pelmServer->getAttributeValue("lowerIP", srv.strIPLower)
1934 && pelmServer->getAttributeValue("upperIP", srv.strIPUpper)
1935 && pelmServer->getAttributeValue("enabled", srv.fEnabled) )
1936 {
1937 /* Global options: */
1938 const xml::ElementNode *pElmOptions;
1939 xml::NodesLoop nlOptions(*pelmServer, "Options");
1940 while ((pElmOptions = nlOptions.forAllNodes()) != NULL) /** @todo this loop makes no sense, there can only be one \<Options\> child. */
1941 readDHCPOptions(srv.globalConfig, *pElmOptions, true /*fIgnoreSubnetMask*/);
1942
1943 /* Group configurations: */
1944 xml::NodesLoop nlGroup(*pelmServer, "Group");
1945 const xml::ElementNode *pElmGroup;
1946 size_t i = 0;
1947 while ((pElmGroup = nlGroup.forAllNodes()) != NULL)
1948 {
1949 srv.vecGroupConfigs.push_back(DHCPGroupConfig());
1950 DHCPGroupConfig &rGroupConfig = srv.vecGroupConfigs.back();
1951
1952 if (!pElmGroup->getAttributeValue("name", rGroupConfig.strName))
1953 rGroupConfig.strName.printf("Unamed Group #%u", ++i);
1954
1955 readDHCPOptions(rGroupConfig, *pElmGroup, false /*fIgnoreSubnetMask*/);
1956
1957 xml::NodesLoop nlCondition(*pElmGroup, "Condition");
1958 const xml::ElementNode *pElmCondition;
1959 while ((pElmCondition = nlCondition.forAllNodes()) != NULL)
1960 {
1961 rGroupConfig.vecConditions.push_back(DHCPGroupCondition());
1962 DHCPGroupCondition &rGroupCondition = rGroupConfig.vecConditions.back();
1963
1964 if (!pElmCondition->getAttributeValue("inclusive", rGroupCondition.fInclusive))
1965 rGroupCondition.fInclusive = true;
1966
1967 int32_t iType;
1968 if (!pElmCondition->getAttributeValue("type", iType))
1969 iType = DHCPGroupConditionType_MAC;
1970 rGroupCondition.enmType = (DHCPGroupConditionType_T)iType;
1971
1972 pElmCondition->getAttributeValue("value", rGroupCondition.strValue);
1973 }
1974 }
1975
1976 /* host specific configuration: */
1977 xml::NodesLoop nlConfig(*pelmServer, "Config");
1978 const xml::ElementNode *pElmConfig;
1979 while ((pElmConfig = nlConfig.forAllNodes()) != NULL)
1980 {
1981 com::Utf8Str strMACAddress;
1982 if (!pElmConfig->getAttributeValue("MACAddress", strMACAddress))
1983 strMACAddress.setNull();
1984
1985 com::Utf8Str strVMName;
1986 if (!pElmConfig->getAttributeValue("vm-name", strVMName))
1987 strVMName.setNull();
1988
1989 uint32_t uSlot;
1990 if (!pElmConfig->getAttributeValue("slot", uSlot))
1991 uSlot = 0;
1992
1993 com::Utf8Str strKey;
1994 if (strVMName.isNotEmpty())
1995 strKey.printf("%s/%u", strVMName.c_str(), uSlot);
1996 else
1997 strKey.printf("%s/%u", strMACAddress.c_str(), uSlot);
1998
1999 DHCPIndividualConfig &rIndividualConfig = srv.mapIndividualConfigs[strKey];
2000 rIndividualConfig.strMACAddress = strMACAddress;
2001 rIndividualConfig.strVMName = strVMName;
2002 rIndividualConfig.uSlot = uSlot;
2003 pElmConfig->getAttributeValue("fixedAddress", rIndividualConfig.strFixedAddress);
2004
2005 readDHCPOptions(rIndividualConfig, *pElmConfig, false /*fIgnoreSubnetMask*/);
2006 }
2007
2008 llDhcpServers.push_back(srv);
2009 }
2010 else
2011 throw ConfigFileError(this, pelmServer, N_("Required DHCPServer/@networkName, @IPAddress, @networkMask, @lowerIP, @upperIP or @enabled attribute is missing"));
2012 }
2013 }
2014}
2015
2016/**
2017 * Worker for readDHCPServers that reads a configuration, either global,
2018 * group or host (VM+NIC) specific.
2019 */
2020void MainConfigFile::readDHCPOptions(DHCPConfig &rConfig, const xml::ElementNode &elmConfig, bool fIgnoreSubnetMask)
2021{
2022 /* Generic (and optional) attributes on the Options or Config element: */
2023 if (!elmConfig.getAttributeValue("secMinLeaseTime", rConfig.secMinLeaseTime))
2024 rConfig.secMinLeaseTime = 0;
2025 if (!elmConfig.getAttributeValue("secDefaultLeaseTime", rConfig.secDefaultLeaseTime))
2026 rConfig.secDefaultLeaseTime = 0;
2027 if (!elmConfig.getAttributeValue("secMaxLeaseTime", rConfig.secMaxLeaseTime))
2028 rConfig.secMaxLeaseTime = 0;
2029 if (!elmConfig.getAttributeValue("forcedOptions", rConfig.strForcedOptions))
2030 rConfig.strSuppressedOptions.setNull();
2031 if (!elmConfig.getAttributeValue("suppressedOptions", rConfig.strSuppressedOptions))
2032 rConfig.strSuppressedOptions.setNull();
2033
2034 /* The DHCP options are <Option> child elements: */
2035 xml::NodesLoop nl2(elmConfig, "Option");
2036 const xml::ElementNode *pElmOption;
2037 while ((pElmOption = nl2.forAllNodes()) != NULL)
2038 {
2039 int32_t iOptName;
2040 if (!pElmOption->getAttributeValue("name", iOptName))
2041 continue;
2042 DHCPOption_T OptName = (DHCPOption_T)iOptName;
2043 if (OptName == DHCPOption_SubnetMask && fIgnoreSubnetMask)
2044 continue;
2045
2046 com::Utf8Str strValue;
2047 pElmOption->getAttributeValue("value", strValue);
2048
2049 int32_t iOptEnc;
2050 if (!pElmOption->getAttributeValue("encoding", iOptEnc))
2051 iOptEnc = DHCPOptionEncoding_Normal;
2052
2053 rConfig.mapOptions[OptName] = DhcpOptValue(strValue, (DHCPOptionEncoding_T)iOptEnc);
2054 } /* end of forall("Option") */
2055
2056}
2057
2058/**
2059 * Reads in the \<NATNetworks\> chunk.
2060 * @param elmNATNetworks
2061 */
2062void MainConfigFile::readNATNetworks(const xml::ElementNode &elmNATNetworks)
2063{
2064 xml::NodesLoop nl1(elmNATNetworks);
2065 const xml::ElementNode *pelmNet;
2066 while ((pelmNet = nl1.forAllNodes()))
2067 {
2068 if (pelmNet->nameEquals("NATNetwork"))
2069 {
2070 NATNetwork net;
2071 if ( pelmNet->getAttributeValue("networkName", net.strNetworkName)
2072 && pelmNet->getAttributeValue("enabled", net.fEnabled)
2073 && pelmNet->getAttributeValue("network", net.strIPv4NetworkCidr)
2074 && pelmNet->getAttributeValue("ipv6", net.fIPv6Enabled)
2075 && pelmNet->getAttributeValue("ipv6prefix", net.strIPv6Prefix)
2076 && pelmNet->getAttributeValue("advertiseDefaultIPv6Route", net.fAdvertiseDefaultIPv6Route)
2077 && pelmNet->getAttributeValue("needDhcp", net.fNeedDhcpServer) )
2078 {
2079 pelmNet->getAttributeValue("loopback6", net.u32HostLoopback6Offset);
2080 const xml::ElementNode *pelmMappings;
2081 if ((pelmMappings = pelmNet->findChildElement("Mappings")))
2082 readNATLoopbacks(*pelmMappings, net.llHostLoopbackOffsetList);
2083
2084 const xml::ElementNode *pelmPortForwardRules4;
2085 if ((pelmPortForwardRules4 = pelmNet->findChildElement("PortForwarding4")))
2086 readNATForwardRulesMap(*pelmPortForwardRules4,
2087 net.mapPortForwardRules4);
2088
2089 const xml::ElementNode *pelmPortForwardRules6;
2090 if ((pelmPortForwardRules6 = pelmNet->findChildElement("PortForwarding6")))
2091 readNATForwardRulesMap(*pelmPortForwardRules6,
2092 net.mapPortForwardRules6);
2093
2094 llNATNetworks.push_back(net);
2095 }
2096 else
2097 throw ConfigFileError(this, pelmNet, N_("Required NATNetwork/@networkName, @gateway, @network,@advertiseDefaultIpv6Route , @needDhcp or @enabled attribute is missing"));
2098 }
2099 }
2100}
2101
2102#ifdef VBOX_WITH_VMNET
2103/**
2104 * Reads in the \<HostOnlyNetworks\> chunk.
2105 * @param elmHostOnlyNetworks
2106 */
2107void MainConfigFile::readHostOnlyNetworks(const xml::ElementNode &elmHostOnlyNetworks)
2108{
2109 xml::NodesLoop nl1(elmHostOnlyNetworks);
2110 const xml::ElementNode *pelmNet;
2111 while ((pelmNet = nl1.forAllNodes()))
2112 {
2113 if (pelmNet->nameEquals("HostOnlyNetwork"))
2114 {
2115 HostOnlyNetwork net;
2116 Utf8Str strID;
2117 if ( pelmNet->getAttributeValue("name", net.strNetworkName)
2118 && pelmNet->getAttributeValue("mask", net.strNetworkMask)
2119 && pelmNet->getAttributeValue("ipLower", net.strIPLower)
2120 && pelmNet->getAttributeValue("ipUpper", net.strIPUpper)
2121 && pelmNet->getAttributeValue("id", strID)
2122 && pelmNet->getAttributeValue("enabled", net.fEnabled) )
2123 {
2124 parseUUID(net.uuid, strID, pelmNet);
2125 llHostOnlyNetworks.push_back(net);
2126 }
2127 else
2128 throw ConfigFileError(this, pelmNet, N_("Required HostOnlyNetwork/@name, @mask, @ipLower, @ipUpper, @id or @enabled attribute is missing"));
2129 }
2130 }
2131}
2132#endif /* VBOX_WITH_VMNET */
2133
2134#ifdef VBOX_WITH_CLOUD_NET
2135/**
2136 * Reads in the \<CloudNetworks\> chunk.
2137 * @param elmCloudNetworks
2138 */
2139void MainConfigFile::readCloudNetworks(const xml::ElementNode &elmCloudNetworks)
2140{
2141 xml::NodesLoop nl1(elmCloudNetworks);
2142 const xml::ElementNode *pelmNet;
2143 while ((pelmNet = nl1.forAllNodes()))
2144 {
2145 if (pelmNet->nameEquals("CloudNetwork"))
2146 {
2147 CloudNetwork net;
2148 if ( pelmNet->getAttributeValue("name", net.strNetworkName)
2149 && pelmNet->getAttributeValue("provider", net.strProviderShortName)
2150 && pelmNet->getAttributeValue("profile", net.strProfileName)
2151 && pelmNet->getAttributeValue("id", net.strNetworkId)
2152 && pelmNet->getAttributeValue("enabled", net.fEnabled) )
2153 {
2154 llCloudNetworks.push_back(net);
2155 }
2156 else
2157 throw ConfigFileError(this, pelmNet, N_("Required CloudNetwork/@name, @provider, @profile, @id or @enabled attribute is missing"));
2158 }
2159 }
2160}
2161#endif /* VBOX_WITH_CLOUD_NET */
2162
2163/**
2164 * Creates \<USBDeviceSource\> nodes under the given parent element according to
2165 * the contents of the given USBDeviceSourcesList.
2166 *
2167 * @param elmParent
2168 * @param ll
2169 */
2170void MainConfigFile::buildUSBDeviceSources(xml::ElementNode &elmParent,
2171 const USBDeviceSourcesList &ll)
2172{
2173 for (USBDeviceSourcesList::const_iterator it = ll.begin();
2174 it != ll.end();
2175 ++it)
2176 {
2177 const USBDeviceSource &src = *it;
2178 xml::ElementNode *pelmSource = elmParent.createChild("USBDeviceSource");
2179 pelmSource->setAttribute("name", src.strName);
2180 pelmSource->setAttribute("backend", src.strBackend);
2181 pelmSource->setAttribute("address", src.strAddress);
2182
2183 /* Write the properties. */
2184 for (StringsMap::const_iterator itProp = src.properties.begin();
2185 itProp != src.properties.end();
2186 ++itProp)
2187 {
2188 xml::ElementNode *pelmProp = pelmSource->createChild("Property");
2189 pelmProp->setAttribute("name", itProp->first);
2190 pelmProp->setAttribute("value", itProp->second);
2191 }
2192 }
2193}
2194
2195/**
2196 * Reads \<USBDeviceFilter\> entries from under the given elmDeviceFilters node and
2197 * stores them in the given linklist. This is in ConfigFileBase because it's used
2198 * from both MainConfigFile (for host filters) and MachineConfigFile (for machine
2199 * filters).
2200 * @param elmDeviceSources
2201 * @param ll
2202 */
2203void MainConfigFile::readUSBDeviceSources(const xml::ElementNode &elmDeviceSources,
2204 USBDeviceSourcesList &ll)
2205{
2206 xml::NodesLoop nl1(elmDeviceSources, "USBDeviceSource");
2207 const xml::ElementNode *pelmChild;
2208 while ((pelmChild = nl1.forAllNodes()))
2209 {
2210 USBDeviceSource src;
2211
2212 if ( pelmChild->getAttributeValue("name", src.strName)
2213 && pelmChild->getAttributeValue("backend", src.strBackend)
2214 && pelmChild->getAttributeValue("address", src.strAddress))
2215 {
2216 // handle medium properties
2217 xml::NodesLoop nl2(*pelmChild, "Property");
2218 const xml::ElementNode *pelmSrcChild;
2219 while ((pelmSrcChild = nl2.forAllNodes()))
2220 {
2221 Utf8Str strPropName, strPropValue;
2222 if ( pelmSrcChild->getAttributeValue("name", strPropName)
2223 && pelmSrcChild->getAttributeValue("value", strPropValue) )
2224 src.properties[strPropName] = strPropValue;
2225 else
2226 throw ConfigFileError(this, pelmSrcChild, N_("Required USBDeviceSource/Property/@name or @value attribute is missing"));
2227 }
2228
2229 ll.push_back(src);
2230 }
2231 }
2232}
2233
2234/**
2235 * Converts old style Proxy settings from ExtraData/UI section.
2236 *
2237 * Saves proxy settings directly to systemProperties structure.
2238 *
2239 * @returns true if conversion was successfull, false if not.
2240 * @param strUIProxySettings The GUI settings string to convert.
2241 */
2242bool MainConfigFile::convertGuiProxySettings(const com::Utf8Str &strUIProxySettings)
2243{
2244 /*
2245 * Possible variants:
2246 * - "ProxyAuto,proxyserver.url,1080,authDisabled,,"
2247 * - "ProxyDisabled,proxyserver.url,1080,authDisabled,,"
2248 * - "ProxyEnabled,proxyserver.url,1080,authDisabled,,"
2249 *
2250 * Note! We only need to bother with the first three fields as the last
2251 * three was never really used or ever actually passed to the HTTP
2252 * client code.
2253 */
2254 /* First field: The proxy mode. */
2255 const char *psz = RTStrStripL(strUIProxySettings.c_str());
2256 static const struct { const char *psz; size_t cch; ProxyMode_T enmMode; } s_aModes[] =
2257 {
2258 { RT_STR_TUPLE("ProxyAuto"), ProxyMode_System },
2259 { RT_STR_TUPLE("ProxyDisabled"), ProxyMode_NoProxy },
2260 { RT_STR_TUPLE("ProxyEnabled"), ProxyMode_Manual },
2261 };
2262 for (size_t i = 0; i < RT_ELEMENTS(s_aModes); i++)
2263 if (RTStrNICmpAscii(psz, s_aModes[i].psz, s_aModes[i].cch) == 0)
2264 {
2265 systemProperties.uProxyMode = s_aModes[i].enmMode;
2266 psz = RTStrStripL(psz + s_aModes[i].cch);
2267 if (*psz == ',')
2268 {
2269 /* Second field: The proxy host, possibly fully fledged proxy URL. */
2270 psz = RTStrStripL(psz + 1);
2271 if (*psz != '\0' && *psz != ',')
2272 {
2273 const char *pszEnd = strchr(psz, ',');
2274 size_t cchHost = pszEnd ? (size_t)(pszEnd - psz) : strlen(psz);
2275 while (cchHost > 0 && RT_C_IS_SPACE(psz[cchHost - 1]))
2276 cchHost--;
2277 systemProperties.strProxyUrl.assign(psz, cchHost);
2278 if (systemProperties.strProxyUrl.find("://") == RTCString::npos)
2279 systemProperties.strProxyUrl.replace(0, 0, "http://");
2280
2281 /* Third field: The proxy port. Defaulted to 1080 for all proxies.
2282 The new settings has type specific default ports. */
2283 uint16_t uPort = 1080;
2284 if (pszEnd)
2285 {
2286 int vrc = RTStrToUInt16Ex(RTStrStripL(pszEnd + 1), NULL, 10, &uPort);
2287 if (RT_FAILURE(vrc))
2288 uPort = 1080;
2289 }
2290 RTURIPARSED Parsed;
2291 int vrc = RTUriParse(systemProperties.strProxyUrl.c_str(), &Parsed);
2292 if (RT_SUCCESS(vrc))
2293 {
2294 if (Parsed.uAuthorityPort == UINT32_MAX)
2295 systemProperties.strProxyUrl.appendPrintf(systemProperties.strProxyUrl.endsWith(":")
2296 ? "%u" : ":%u", uPort);
2297 }
2298 else
2299 {
2300 LogRelFunc(("Dropping invalid proxy URL for %u: %s\n",
2301 systemProperties.uProxyMode, systemProperties.strProxyUrl.c_str()));
2302 systemProperties.strProxyUrl.setNull();
2303 }
2304 }
2305 /* else: don't bother with the rest if we haven't got a host. */
2306 }
2307 if ( systemProperties.strProxyUrl.isEmpty()
2308 && systemProperties.uProxyMode == ProxyMode_Manual)
2309 {
2310 systemProperties.uProxyMode = ProxyMode_System;
2311 return false;
2312 }
2313 return true;
2314 }
2315 LogRelFunc(("Unknown proxy type: %s\n", psz));
2316 return false;
2317}
2318
2319/**
2320 * Constructor.
2321 *
2322 * If pstrFilename is != NULL, this reads the given settings file into the member
2323 * variables and various substructures and lists. Otherwise, the member variables
2324 * are initialized with default values.
2325 *
2326 * Throws variants of xml::Error for I/O, XML and logical content errors, which
2327 * the caller should catch; if this constructor does not throw, then the member
2328 * variables contain meaningful values (either from the file or defaults).
2329 *
2330 * @param pstrFilename
2331 */
2332MainConfigFile::MainConfigFile(const Utf8Str *pstrFilename)
2333 : ConfigFileBase(pstrFilename)
2334{
2335 if (pstrFilename)
2336 {
2337 // the ConfigFileBase constructor has loaded the XML file, so now
2338 // we need only analyze what is in there
2339 xml::NodesLoop nlRootChildren(*m->pelmRoot);
2340 const xml::ElementNode *pelmRootChild;
2341 bool fCopyProxySettingsFromExtraData = false;
2342 while ((pelmRootChild = nlRootChildren.forAllNodes()))
2343 {
2344 if (pelmRootChild->nameEquals("Global"))
2345 {
2346 xml::NodesLoop nlGlobalChildren(*pelmRootChild);
2347 const xml::ElementNode *pelmGlobalChild;
2348 while ((pelmGlobalChild = nlGlobalChildren.forAllNodes()))
2349 {
2350 if (pelmGlobalChild->nameEquals("SystemProperties"))
2351 {
2352 pelmGlobalChild->getAttributeValue("defaultMachineFolder", systemProperties.strDefaultMachineFolder);
2353 pelmGlobalChild->getAttributeValue("LoggingLevel", systemProperties.strLoggingLevel);
2354 pelmGlobalChild->getAttributeValue("defaultHardDiskFormat", systemProperties.strDefaultHardDiskFormat);
2355 if (!pelmGlobalChild->getAttributeValue("VRDEAuthLibrary", systemProperties.strVRDEAuthLibrary))
2356 // pre-1.11 used @remoteDisplayAuthLibrary instead
2357 pelmGlobalChild->getAttributeValue("remoteDisplayAuthLibrary", systemProperties.strVRDEAuthLibrary);
2358 pelmGlobalChild->getAttributeValue("webServiceAuthLibrary", systemProperties.strWebServiceAuthLibrary);
2359 pelmGlobalChild->getAttributeValue("defaultVRDEExtPack", systemProperties.strDefaultVRDEExtPack);
2360 pelmGlobalChild->getAttributeValue("defaultCryptoExtPack", systemProperties.strDefaultCryptoExtPack);
2361 pelmGlobalChild->getAttributeValue("LogHistoryCount", systemProperties.uLogHistoryCount);
2362 pelmGlobalChild->getAttributeValue("autostartDatabasePath", systemProperties.strAutostartDatabasePath);
2363 pelmGlobalChild->getAttributeValue("defaultFrontend", systemProperties.strDefaultFrontend);
2364 if (m->sv < SettingsVersion_v1_20) /* exclusiveHwVirt was part of SystemProperties for < v1.20. */
2365 pelmGlobalChild->getAttributeValue("exclusiveHwVirt", platformProperties.fExclusiveHwVirt);
2366 if (!pelmGlobalChild->getAttributeValue("proxyMode", systemProperties.uProxyMode))
2367 fCopyProxySettingsFromExtraData = true;
2368 pelmGlobalChild->getAttributeValue("proxyUrl", systemProperties.strProxyUrl);
2369 pelmGlobalChild->getAttributeValue("LanguageId", systemProperties.strLanguageId);
2370 }
2371 if ( pelmGlobalChild->nameEquals("PlatformProperties")
2372 && m->sv >= SettingsVersion_v1_20)
2373 {
2374 /* Since settings v1.20 exclusiveHwVirt is part of PlatformProperties. */
2375 pelmGlobalChild->getAttributeValue("exclusiveHwVirt", platformProperties.fExclusiveHwVirt);
2376 }
2377#ifdef VBOX_WITH_UPDATE_AGENT
2378 else if (pelmGlobalChild->nameEquals("Updates"))
2379 {
2380 /* We keep the updates configuration as part of the host for now, as the API exposes the IHost::updateHost attribute,
2381 * but use an own "Updates" branch in the XML for better structurizing stuff in the future. */
2382 UpdateAgent &updateHost = host.updateHost;
2383
2384 xml::NodesLoop nlLevel4(*pelmGlobalChild);
2385 const xml::ElementNode *pelmLevel4Child;
2386 while ((pelmLevel4Child = nlLevel4.forAllNodes()))
2387 {
2388 if (pelmLevel4Child->nameEquals("Host"))
2389 {
2390 pelmLevel4Child->getAttributeValue("enabled", updateHost.fEnabled);
2391 pelmLevel4Child->getAttributeValue("channel", (uint32_t&)updateHost.enmChannel);
2392 pelmLevel4Child->getAttributeValue("checkFreqSec", updateHost.uCheckFreqSeconds);
2393 pelmLevel4Child->getAttributeValue("repoUrl", updateHost.strRepoUrl);
2394 pelmLevel4Child->getAttributeValue("lastCheckDate", updateHost.strLastCheckDate);
2395 pelmLevel4Child->getAttributeValue("checkCount", updateHost.uCheckCount);
2396 }
2397 /** @todo Add update settings for ExtPack and Guest Additions here later. See @bugref{7983}. */
2398 }
2399
2400 /* Global enabled switch for updates. Currently bound to host updates, as this is the only update we have so far. */
2401 pelmGlobalChild->getAttributeValue("enabled", updateHost.fEnabled);
2402 }
2403#endif
2404 else if (pelmGlobalChild->nameEquals("ExtraData"))
2405 readExtraData(*pelmGlobalChild, mapExtraDataItems);
2406 else if (pelmGlobalChild->nameEquals("MachineRegistry"))
2407 readMachineRegistry(*pelmGlobalChild);
2408 else if ( (pelmGlobalChild->nameEquals("MediaRegistry"))
2409 || ( (m->sv < SettingsVersion_v1_4)
2410 && (pelmGlobalChild->nameEquals("DiskRegistry"))
2411 )
2412 )
2413 readMediaRegistry(*pelmGlobalChild, mediaRegistry);
2414 else if (pelmGlobalChild->nameEquals("NetserviceRegistry"))
2415 {
2416 xml::NodesLoop nlLevel4(*pelmGlobalChild);
2417 const xml::ElementNode *pelmLevel4Child;
2418 while ((pelmLevel4Child = nlLevel4.forAllNodes()))
2419 {
2420 if (pelmLevel4Child->nameEquals("DHCPServers"))
2421 readDHCPServers(*pelmLevel4Child);
2422 if (pelmLevel4Child->nameEquals("NATNetworks"))
2423 readNATNetworks(*pelmLevel4Child);
2424#ifdef VBOX_WITH_VMNET
2425 if (pelmLevel4Child->nameEquals("HostOnlyNetworks"))
2426 readHostOnlyNetworks(*pelmLevel4Child);
2427#endif /* VBOX_WITH_VMNET */
2428#ifdef VBOX_WITH_CLOUD_NET
2429 if (pelmLevel4Child->nameEquals("CloudNetworks"))
2430 readCloudNetworks(*pelmLevel4Child);
2431#endif /* VBOX_WITH_CLOUD_NET */
2432 }
2433 }
2434 else if (pelmGlobalChild->nameEquals("USBDeviceFilters"))
2435 readUSBDeviceFilters(*pelmGlobalChild, host.llUSBDeviceFilters);
2436 else if (pelmGlobalChild->nameEquals("USBDeviceSources"))
2437 readUSBDeviceSources(*pelmGlobalChild, host.llUSBDeviceSources);
2438 }
2439 } // end if (pelmRootChild->nameEquals("Global"))
2440 }
2441
2442 if (fCopyProxySettingsFromExtraData)
2443 for (StringsMap::const_iterator it = mapExtraDataItems.begin(); it != mapExtraDataItems.end(); ++it)
2444 if (it->first.equals("GUI/ProxySettings"))
2445 {
2446 convertGuiProxySettings(it->second);
2447 break;
2448 }
2449
2450 clearDocument();
2451 }
2452
2453 // DHCP servers were introduced with settings version 1.7; if we're loading
2454 // from an older version OR this is a fresh install, then add one DHCP server
2455 // with default settings
2456 if ( (!llDhcpServers.size())
2457 && ( (!pstrFilename) // empty VirtualBox.xml file
2458 || (m->sv < SettingsVersion_v1_7) // upgrading from before 1.7
2459 )
2460 )
2461 {
2462 DHCPServer srv;
2463#ifdef RT_OS_WINDOWS
2464 srv.strNetworkName = "HostInterfaceNetworking-VirtualBox Host-Only Ethernet Adapter";
2465#else
2466 srv.strNetworkName = "HostInterfaceNetworking-vboxnet0";
2467#endif
2468 srv.strIPAddress = "192.168.56.100";
2469 srv.globalConfig.mapOptions[DHCPOption_SubnetMask] = DhcpOptValue("255.255.255.0");
2470 srv.strIPLower = "192.168.56.101";
2471 srv.strIPUpper = "192.168.56.254";
2472 srv.fEnabled = true;
2473 llDhcpServers.push_back(srv);
2474 }
2475}
2476
2477void MainConfigFile::bumpSettingsVersionIfNeeded()
2478{
2479#ifdef VBOX_WITH_VMNET
2480 if (m->sv < SettingsVersion_v1_19)
2481 {
2482 // VirtualBox 7.0 adds support for host-only networks.
2483 if (!llHostOnlyNetworks.empty())
2484 m->sv = SettingsVersion_v1_19;
2485 }
2486#endif /* VBOX_WITH_VMNET */
2487#ifdef VBOX_WITH_CLOUD_NET
2488 if (m->sv < SettingsVersion_v1_18)
2489 {
2490 // VirtualBox 6.1 adds support for cloud networks.
2491 if (!llCloudNetworks.empty())
2492 m->sv = SettingsVersion_v1_18;
2493 }
2494#endif /* VBOX_WITH_CLOUD_NET */
2495
2496 if (m->sv < SettingsVersion_v1_16)
2497 {
2498 // VirtualBox 5.1 add support for additional USB device sources.
2499 if (!host.llUSBDeviceSources.empty())
2500 m->sv = SettingsVersion_v1_16;
2501 }
2502
2503 if (m->sv < SettingsVersion_v1_14)
2504 {
2505 // VirtualBox 4.3 adds NAT networks.
2506 if ( !llNATNetworks.empty())
2507 m->sv = SettingsVersion_v1_14;
2508 }
2509}
2510
2511
2512/**
2513 * Called from the IVirtualBox interface to write out VirtualBox.xml. This
2514 * builds an XML DOM tree and writes it out to disk.
2515 */
2516void MainConfigFile::write(const com::Utf8Str strFilename)
2517{
2518 bumpSettingsVersionIfNeeded();
2519
2520 m->strFilename = strFilename;
2521 specialBackupIfFirstBump();
2522 createStubDocument();
2523
2524 xml::ElementNode *pelmGlobal = m->pelmRoot->createChild("Global");
2525
2526 buildExtraData(*pelmGlobal, mapExtraDataItems);
2527
2528 xml::ElementNode *pelmMachineRegistry = pelmGlobal->createChild("MachineRegistry");
2529 for (MachinesRegistry::const_iterator it = llMachines.begin();
2530 it != llMachines.end();
2531 ++it)
2532 {
2533 // <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"/>
2534 const MachineRegistryEntry &mre = *it;
2535 xml::ElementNode *pelmMachineEntry = pelmMachineRegistry->createChild("MachineEntry");
2536 pelmMachineEntry->setAttribute("uuid", mre.uuid.toStringCurly());
2537 pelmMachineEntry->setAttribute("src", mre.strSettingsFile);
2538 }
2539
2540 buildMediaRegistry(*pelmGlobal, mediaRegistry);
2541
2542 xml::ElementNode *pelmNetServiceRegistry = pelmGlobal->createChild("NetserviceRegistry"); /** @todo r=bird: wrong capitalization of NetServiceRegistry. sigh. */
2543 buildDHCPServers(*pelmNetServiceRegistry->createChild("DHCPServers"), llDhcpServers);
2544
2545 xml::ElementNode *pelmNATNetworks;
2546 /* don't create entry if no NAT networks are registered. */
2547 if (!llNATNetworks.empty())
2548 {
2549 pelmNATNetworks = pelmNetServiceRegistry->createChild("NATNetworks");
2550 for (NATNetworksList::const_iterator it = llNATNetworks.begin();
2551 it != llNATNetworks.end();
2552 ++it)
2553 {
2554 const NATNetwork &n = *it;
2555 xml::ElementNode *pelmThis = pelmNATNetworks->createChild("NATNetwork");
2556 pelmThis->setAttribute("networkName", n.strNetworkName);
2557 pelmThis->setAttribute("network", n.strIPv4NetworkCidr);
2558 pelmThis->setAttribute("ipv6", n.fIPv6Enabled ? 1 : 0);
2559 pelmThis->setAttribute("ipv6prefix", n.strIPv6Prefix);
2560 pelmThis->setAttribute("advertiseDefaultIPv6Route", (n.fAdvertiseDefaultIPv6Route)? 1 : 0);
2561 pelmThis->setAttribute("needDhcp", (n.fNeedDhcpServer) ? 1 : 0);
2562 pelmThis->setAttribute("enabled", (n.fEnabled) ? 1 : 0); // too bad we chose 1 vs. 0 here
2563 if (n.mapPortForwardRules4.size())
2564 {
2565 xml::ElementNode *pelmPf4 = pelmThis->createChild("PortForwarding4");
2566 buildNATForwardRulesMap(*pelmPf4, n.mapPortForwardRules4);
2567 }
2568 if (n.mapPortForwardRules6.size())
2569 {
2570 xml::ElementNode *pelmPf6 = pelmThis->createChild("PortForwarding6");
2571 buildNATForwardRulesMap(*pelmPf6, n.mapPortForwardRules6);
2572 }
2573
2574 if (n.llHostLoopbackOffsetList.size())
2575 {
2576 xml::ElementNode *pelmMappings = pelmThis->createChild("Mappings");
2577 buildNATLoopbacks(*pelmMappings, n.llHostLoopbackOffsetList);
2578
2579 }
2580 }
2581 }
2582
2583#ifdef VBOX_WITH_VMNET
2584 xml::ElementNode *pelmHostOnlyNetworks;
2585 /* don't create entry if no HostOnly networks are registered. */
2586 if (!llHostOnlyNetworks.empty())
2587 {
2588 pelmHostOnlyNetworks = pelmNetServiceRegistry->createChild("HostOnlyNetworks");
2589 for (HostOnlyNetworksList::const_iterator it = llHostOnlyNetworks.begin();
2590 it != llHostOnlyNetworks.end();
2591 ++it)
2592 {
2593 const HostOnlyNetwork &n = *it;
2594 xml::ElementNode *pelmThis = pelmHostOnlyNetworks->createChild("HostOnlyNetwork");
2595 pelmThis->setAttribute("name", n.strNetworkName);
2596 pelmThis->setAttribute("mask", n.strNetworkMask);
2597 pelmThis->setAttribute("ipLower", n.strIPLower);
2598 pelmThis->setAttribute("ipUpper", n.strIPUpper);
2599 pelmThis->setAttribute("id", n.uuid.toStringCurly());
2600 pelmThis->setAttribute("enabled", (n.fEnabled) ? 1 : 0); // too bad we chose 1 vs. 0 here
2601 }
2602 }
2603#endif /* VBOX_WITH_VMNET */
2604#ifdef VBOX_WITH_CLOUD_NET
2605 xml::ElementNode *pelmCloudNetworks;
2606 /* don't create entry if no cloud networks are registered. */
2607 if (!llCloudNetworks.empty())
2608 {
2609 pelmCloudNetworks = pelmNetServiceRegistry->createChild("CloudNetworks");
2610 for (CloudNetworksList::const_iterator it = llCloudNetworks.begin();
2611 it != llCloudNetworks.end();
2612 ++it)
2613 {
2614 const CloudNetwork &n = *it;
2615 xml::ElementNode *pelmThis = pelmCloudNetworks->createChild("CloudNetwork");
2616 pelmThis->setAttribute("name", n.strNetworkName);
2617 pelmThis->setAttribute("provider", n.strProviderShortName);
2618 pelmThis->setAttribute("profile", n.strProfileName);
2619 pelmThis->setAttribute("id", n.strNetworkId);
2620 pelmThis->setAttribute("enabled", (n.fEnabled) ? 1 : 0); // too bad we chose 1 vs. 0 here
2621 }
2622 }
2623#endif /* VBOX_WITH_CLOUD_NET */
2624
2625#ifdef VBOX_WITH_UPDATE_AGENT
2626 /* We keep the updates configuration as part of the host for now, as the API exposes the IHost::updateHost attribute,
2627 * but use an own "Updates" branch in the XML for better structurizing stuff in the future. */
2628 UpdateAgent &updateHost = host.updateHost;
2629
2630 xml::ElementNode *pelmUpdates = pelmGlobal->createChild("Updates");
2631 /* Global enabled switch for updates. Currently bound to host updates, as this is the only update we have so far. */
2632 pelmUpdates->setAttribute("enabled", updateHost.fEnabled);
2633
2634 xml::ElementNode *pelmUpdateHost = pelmUpdates->createChild("Host");
2635 pelmUpdateHost->setAttribute("enabled", updateHost.fEnabled);
2636 pelmUpdateHost->setAttribute("channel", (int32_t)updateHost.enmChannel);
2637 pelmUpdateHost->setAttribute("checkFreqSec", updateHost.uCheckFreqSeconds);
2638 if (updateHost.strRepoUrl.length())
2639 pelmUpdateHost->setAttribute("repoUrl", updateHost.strRepoUrl);
2640 if (updateHost.strLastCheckDate.length())
2641 pelmUpdateHost->setAttribute("lastCheckDate", updateHost.strLastCheckDate);
2642 pelmUpdateHost->setAttribute("checkCount", updateHost.uCheckCount);
2643 /** @todo Add update settings for ExtPack and Guest Additions here later. See @bugref{7983}. */
2644#endif
2645
2646 xml::ElementNode *pelmSysProps = pelmGlobal->createChild("SystemProperties");
2647 if (systemProperties.strDefaultMachineFolder.length())
2648 pelmSysProps->setAttribute("defaultMachineFolder", systemProperties.strDefaultMachineFolder);
2649 if (systemProperties.strLoggingLevel.length())
2650 pelmSysProps->setAttribute("LoggingLevel", systemProperties.strLoggingLevel);
2651 if (systemProperties.strDefaultHardDiskFormat.length())
2652 pelmSysProps->setAttribute("defaultHardDiskFormat", systemProperties.strDefaultHardDiskFormat);
2653 if (systemProperties.strVRDEAuthLibrary.length())
2654 pelmSysProps->setAttribute("VRDEAuthLibrary", systemProperties.strVRDEAuthLibrary);
2655 if (systemProperties.strWebServiceAuthLibrary.length())
2656 pelmSysProps->setAttribute("webServiceAuthLibrary", systemProperties.strWebServiceAuthLibrary);
2657 if (systemProperties.strDefaultVRDEExtPack.length())
2658 pelmSysProps->setAttribute("defaultVRDEExtPack", systemProperties.strDefaultVRDEExtPack);
2659 if (systemProperties.strDefaultCryptoExtPack.length())
2660 pelmSysProps->setAttribute("defaultCryptoExtPack", systemProperties.strDefaultCryptoExtPack);
2661 pelmSysProps->setAttribute("LogHistoryCount", systemProperties.uLogHistoryCount);
2662 if (systemProperties.strAutostartDatabasePath.length())
2663 pelmSysProps->setAttribute("autostartDatabasePath", systemProperties.strAutostartDatabasePath);
2664 if (systemProperties.strDefaultFrontend.length())
2665 pelmSysProps->setAttribute("defaultFrontend", systemProperties.strDefaultFrontend);
2666 if (systemProperties.strProxyUrl.length())
2667 pelmSysProps->setAttribute("proxyUrl", systemProperties.strProxyUrl);
2668 pelmSysProps->setAttribute("proxyMode", systemProperties.uProxyMode);
2669 if (m->sv >= SettingsVersion_v1_20) /* Since settings v1.20 exclusiveHwVirt is part of PlatformProperties. */
2670 {
2671 xml::ElementNode *pelmPlatProps = pelmGlobal->createChild("PlatformProperties");
2672 pelmPlatProps->setAttribute("exclusiveHwVirt", platformProperties.fExclusiveHwVirt);
2673 }
2674 else
2675 pelmSysProps->setAttribute("exclusiveHwVirt", platformProperties.fExclusiveHwVirt);
2676 if (systemProperties.strLanguageId.isNotEmpty())
2677 pelmSysProps->setAttribute("LanguageId", systemProperties.strLanguageId);
2678
2679 buildUSBDeviceFilters(*pelmGlobal->createChild("USBDeviceFilters"),
2680 host.llUSBDeviceFilters,
2681 true); // fHostMode
2682
2683 if (!host.llUSBDeviceSources.empty())
2684 buildUSBDeviceSources(*pelmGlobal->createChild("USBDeviceSources"),
2685 host.llUSBDeviceSources);
2686
2687 // now go write the XML
2688 xml::XmlFileWriter writer(*m->pDoc);
2689 writer.write(m->strFilename.c_str(), true /*fSafe*/);
2690
2691 m->fFileExists = true;
2692
2693 clearDocument();
2694 LogRel(("Finished saving settings file \"%s\"\n", m->strFilename.c_str()));
2695}
2696
2697////////////////////////////////////////////////////////////////////////////////
2698//
2699// Machine XML structures
2700//
2701////////////////////////////////////////////////////////////////////////////////
2702
2703/**
2704 * Constructor. Needs to set sane defaults which stand the test of time.
2705 */
2706VRDESettings::VRDESettings() :
2707 fEnabled(true), // default for old VMs, for new ones it's false
2708 authType(AuthType_Null),
2709 ulAuthTimeout(5000),
2710 fAllowMultiConnection(false),
2711 fReuseSingleConnection(false)
2712{
2713}
2714
2715/**
2716 * Check if all settings have default values.
2717 */
2718bool VRDESettings::areDefaultSettings(SettingsVersion_T sv) const
2719{
2720 return (sv < SettingsVersion_v1_16 ? fEnabled : !fEnabled)
2721 && authType == AuthType_Null
2722 && (ulAuthTimeout == 5000 || ulAuthTimeout == 0)
2723 && strAuthLibrary.isEmpty()
2724 && !fAllowMultiConnection
2725 && !fReuseSingleConnection
2726 && strVrdeExtPack.isEmpty()
2727 && mapProperties.size() == 0;
2728}
2729
2730/**
2731 * Comparison operator. This gets called from MachineConfigFile::operator==,
2732 * which in turn gets called from Machine::saveSettings to figure out whether
2733 * machine settings have really changed and thus need to be written out to disk.
2734 */
2735bool VRDESettings::operator==(const VRDESettings& v) const
2736{
2737 return (this == &v)
2738 || ( fEnabled == v.fEnabled
2739 && authType == v.authType
2740 && ulAuthTimeout == v.ulAuthTimeout
2741 && strAuthLibrary == v.strAuthLibrary
2742 && fAllowMultiConnection == v.fAllowMultiConnection
2743 && fReuseSingleConnection == v.fReuseSingleConnection
2744 && strVrdeExtPack == v.strVrdeExtPack
2745 && mapProperties == v.mapProperties);
2746}
2747
2748/**
2749 * Constructor. Needs to set sane defaults which stand the test of time.
2750 */
2751FirmwareSettings::FirmwareSettings() :
2752 firmwareType(FirmwareType_BIOS),
2753 fACPIEnabled(true),
2754 fIOAPICEnabled(false),
2755 fLogoFadeIn(true),
2756 fLogoFadeOut(true),
2757 fPXEDebugEnabled(false),
2758 fSmbiosUuidLittleEndian(true),
2759 fAutoSerialNumGen(true),
2760 ulLogoDisplayTime(0),
2761 enmBootMenuMode(FirmwareBootMenuMode_MessageAndMenu),
2762 apicMode(APICMode_APIC),
2763 llTimeOffset(0)
2764{
2765}
2766
2767/**
2768 * Returns if all settings have default values.
2769 *
2770 * @returns \c true if all settings have default values, \c false if not.
2771 * @param enmCPUArch CPU architecture to use for checking the default values for.
2772 */
2773bool FirmwareSettings::areDefaultSettings(CPUArchitecture_T enmCPUArch) const
2774{
2775 switch (enmCPUArch)
2776 {
2777 case CPUArchitecture_x86:
2778 RT_FALL_THROUGH();
2779 case CPUArchitecture_AMD64:
2780 return
2781 firmwareType == FirmwareType_BIOS
2782 && !fIOAPICEnabled
2783 && fLogoFadeIn
2784 && fLogoFadeOut
2785 && !fPXEDebugEnabled
2786 && !fSmbiosUuidLittleEndian
2787 && !fAutoSerialNumGen
2788 && ulLogoDisplayTime == 0
2789 && enmBootMenuMode == FirmwareBootMenuMode_MessageAndMenu
2790 && apicMode == APICMode_APIC
2791 && llTimeOffset == 0
2792 && strLogoImagePath.isEmpty();
2793
2794 case CPUArchitecture_ARMv8_32:
2795 RT_FALL_THROUGH();
2796 case CPUArchitecture_ARMv8_64:
2797 return
2798 ( enmCPUArch == CPUArchitecture_ARMv8_32
2799 ? firmwareType == FirmwareType_EFI32
2800 : firmwareType == FirmwareType_EFI64)
2801 && !fIOAPICEnabled
2802 && fLogoFadeIn
2803 && fLogoFadeOut
2804 && !fPXEDebugEnabled
2805 && !fSmbiosUuidLittleEndian
2806 && !fAutoSerialNumGen
2807 && ulLogoDisplayTime == 0
2808 && enmBootMenuMode == FirmwareBootMenuMode_MessageAndMenu
2809 && apicMode == APICMode_APIC
2810 && llTimeOffset == 0
2811 && strLogoImagePath.isEmpty();
2812 break;
2813
2814 default:
2815 break;
2816 }
2817
2818 AssertFailedReturn(false);
2819}
2820
2821/**
2822 * Comparison operator. This gets called from MachineConfigFile::operator==,
2823 * which in turn gets called from Machine::saveSettings to figure out whether
2824 * machine settings have really changed and thus need to be written out to disk.
2825 */
2826bool FirmwareSettings::operator==(const FirmwareSettings &d) const
2827{
2828 return (this == &d)
2829 || ( firmwareType == d.firmwareType
2830 && fACPIEnabled == d.fACPIEnabled
2831 && fIOAPICEnabled == d.fIOAPICEnabled
2832 && fLogoFadeIn == d.fLogoFadeIn
2833 && fLogoFadeOut == d.fLogoFadeOut
2834 && fPXEDebugEnabled == d.fPXEDebugEnabled
2835 && fSmbiosUuidLittleEndian == d.fSmbiosUuidLittleEndian
2836 && fAutoSerialNumGen == d.fAutoSerialNumGen
2837 && ulLogoDisplayTime == d.ulLogoDisplayTime
2838 && enmBootMenuMode == d.enmBootMenuMode
2839 && apicMode == d.apicMode
2840 && llTimeOffset == d.llTimeOffset
2841 && strLogoImagePath == d.strLogoImagePath);
2842}
2843
2844RecordingScreenSettings::RecordingScreenSettings(uint32_t a_idScreen /* = UINT32_MAX */)
2845 : idScreen(a_idScreen)
2846{
2847 applyDefaults();
2848}
2849
2850RecordingScreenSettings::~RecordingScreenSettings()
2851{
2852
2853}
2854
2855/**
2856 * Returns the default options string for screen recording settings.
2857 *
2858 * @returns Default options string for a given screen.
2859 */
2860/* static */
2861const char *RecordingScreenSettings::getDefaultOptions(void)
2862{
2863 /* Note: Needs to be kept in sync with FE/Qt's UIMachineSettingsDisplay::putToCache()! */
2864 return "vc_enabled=true,ac_enabled=false,ac_profile=med";
2865}
2866
2867/**
2868 * Returns a recording settings feature map from a given string.
2869 *
2870 * @returns VBox status code.
2871 * @param strFeatures String of features to convert.
2872 * @param featureMap Where to return the converted features on success.
2873 */
2874/* static */
2875int RecordingScreenSettings::featuresFromString(const com::Utf8Str &strFeatures, RecordingFeatureMap &featureMap)
2876{
2877 featureMap.clear();
2878
2879 RTCList<RTCString> lstFeatures = strFeatures.split(" ");
2880 for (size_t i = 0; i < lstFeatures.size(); i++)
2881 {
2882 if (lstFeatures.at(i).compare("video", RTCString::CaseInsensitive) == 0)
2883 featureMap[RecordingFeature_Video] = true;
2884 else if (lstFeatures.at(i).compare("audio", RTCString::CaseInsensitive) == 0)
2885 featureMap[RecordingFeature_Audio] = true;
2886 /* ignore everything else */
2887 }
2888
2889 return VINF_SUCCESS;
2890}
2891
2892/**
2893 * Converts a feature map to a serializable string.
2894 *
2895 * @param featureMap Feature map to convert.
2896 * @param strFeatures Where to return the features converted as a string.
2897 */
2898/* static */
2899void RecordingScreenSettings::featuresToString(const RecordingFeatureMap &featureMap, com::Utf8Str &strFeatures)
2900{
2901 strFeatures = "";
2902
2903 RecordingFeatureMap::const_iterator itFeature = featureMap.begin();
2904 while (itFeature != featureMap.end())
2905 {
2906 if (itFeature->first == RecordingFeature_Video && itFeature->second)
2907 strFeatures += "video ";
2908 if (itFeature->first == RecordingFeature_Audio && itFeature->second)
2909 strFeatures += "audio ";
2910 ++itFeature;
2911 }
2912 strFeatures.strip();
2913}
2914
2915/**
2916 * Returns a recording settings audio codec from a given string.
2917 *
2918 * @returns VBox status code.
2919 * @retval VERR_NOT_SUPPORTED if audio codec is invalid or not supported.
2920 * @param strCodec String that contains the codec name.
2921 * @param enmCodec Where to return the audio codec on success.
2922 *
2923 * @note An empty string will return "none" (no codec).
2924 */
2925/* static */
2926int RecordingScreenSettings::audioCodecFromString(const com::Utf8Str &strCodec, RecordingAudioCodec_T &enmCodec)
2927{
2928 if ( RTStrIStr(strCodec.c_str(), "none")
2929 || strCodec.isEmpty())
2930 {
2931 enmCodec = RecordingAudioCodec_None;
2932 return VINF_SUCCESS;
2933 }
2934 else if (RTStrIStr(strCodec.c_str(), "wav"))
2935 {
2936 enmCodec = RecordingAudioCodec_WavPCM;
2937 return VINF_SUCCESS;
2938 }
2939 else if (RTStrIStr(strCodec.c_str(), "mp3"))
2940 {
2941 enmCodec = RecordingAudioCodec_MP3;
2942 return VINF_SUCCESS;
2943 }
2944 else if (RTStrIStr(strCodec.c_str(), "opus"))
2945 {
2946 enmCodec = RecordingAudioCodec_Opus;
2947 return VINF_SUCCESS;
2948 }
2949 else if (RTStrIStr(strCodec.c_str(), "vorbis"))
2950 {
2951 enmCodec = RecordingAudioCodec_OggVorbis;
2952 return VINF_SUCCESS;
2953 }
2954
2955 AssertFailedReturn(VERR_NOT_SUPPORTED);
2956}
2957
2958/**
2959 * Converts an audio codec to a serializable string.
2960 *
2961 * @param enmCodec Codec to convert to a string.
2962 * @param strCodec Where to return the audio codec converted as a string.
2963 */
2964/* static */
2965void RecordingScreenSettings::audioCodecToString(const RecordingAudioCodec_T &enmCodec, com::Utf8Str &strCodec)
2966{
2967 switch (enmCodec)
2968 {
2969 case RecordingAudioCodec_None: strCodec = "none"; return;
2970 case RecordingAudioCodec_WavPCM: strCodec = "wav"; return;
2971 case RecordingAudioCodec_MP3: strCodec = "mp3"; return;
2972 case RecordingAudioCodec_Opus: strCodec = "opus"; return;
2973 case RecordingAudioCodec_OggVorbis: strCodec = "vorbis"; return;
2974 default: AssertFailedReturnVoid();
2975 }
2976}
2977
2978/**
2979 * Returns a recording settings video codec from a given string.
2980 *
2981 * @returns VBox status code.
2982 * @retval VERR_NOT_SUPPORTED if video codec is invalid or not supported.
2983 * @param strCodec String that contains the codec name.
2984 * @param enmCodec Where to return the video codec on success.
2985 *
2986 * @note An empty string will return "none" (no codec).
2987 */
2988/* static */
2989int RecordingScreenSettings::videoCodecFromString(const com::Utf8Str &strCodec, RecordingVideoCodec_T &enmCodec)
2990{
2991 if ( RTStrIStr(strCodec.c_str(), "none")
2992 || strCodec.isEmpty())
2993 {
2994 enmCodec = RecordingVideoCodec_None;
2995 return VINF_SUCCESS;
2996 }
2997 else if (RTStrIStr(strCodec.c_str(), "MJPEG"))
2998 {
2999 enmCodec = RecordingVideoCodec_MJPEG;
3000 return VINF_SUCCESS;
3001 }
3002 else if (RTStrIStr(strCodec.c_str(), "H262"))
3003 {
3004 enmCodec = RecordingVideoCodec_H262;
3005 return VINF_SUCCESS;
3006 }
3007 else if (RTStrIStr(strCodec.c_str(), "H264"))
3008 {
3009 enmCodec = RecordingVideoCodec_H264;
3010 return VINF_SUCCESS;
3011 }
3012 else if (RTStrIStr(strCodec.c_str(), "H265"))
3013 {
3014 enmCodec = RecordingVideoCodec_H265;
3015 return VINF_SUCCESS;
3016 }
3017 else if (RTStrIStr(strCodec.c_str(), "H266"))
3018 {
3019 enmCodec = RecordingVideoCodec_H266;
3020 return VINF_SUCCESS;
3021 }
3022 else if (RTStrIStr(strCodec.c_str(), "VP8"))
3023 {
3024 enmCodec = RecordingVideoCodec_VP8;
3025 return VINF_SUCCESS;
3026 }
3027 else if (RTStrIStr(strCodec.c_str(), "VP9"))
3028 {
3029 enmCodec = RecordingVideoCodec_VP9;
3030 return VINF_SUCCESS;
3031 }
3032 else if (RTStrIStr(strCodec.c_str(), "AV1"))
3033 {
3034 enmCodec = RecordingVideoCodec_AV1;
3035 return VINF_SUCCESS;
3036 }
3037 else if (RTStrIStr(strCodec.c_str(), "other"))
3038 {
3039 enmCodec = RecordingVideoCodec_Other;
3040 return VINF_SUCCESS;
3041 }
3042
3043 AssertFailedReturn(VERR_NOT_SUPPORTED);
3044}
3045
3046/**
3047 * Converts a video codec to a serializable string.
3048 *
3049 * @param enmCodec Codec to convert to a string.
3050 * @param strCodec Where to return the video codec converted as a string.
3051 */
3052/* static */
3053void RecordingScreenSettings::videoCodecToString(const RecordingVideoCodec_T &enmCodec, com::Utf8Str &strCodec)
3054{
3055 switch (enmCodec)
3056 {
3057 case RecordingVideoCodec_None: strCodec = "none"; return;
3058 case RecordingVideoCodec_MJPEG: strCodec = "MJPEG"; return;
3059 case RecordingVideoCodec_H262: strCodec = "H262"; return;
3060 case RecordingVideoCodec_H264: strCodec = "H264"; return;
3061 case RecordingVideoCodec_H265: strCodec = "H265"; return;
3062 case RecordingVideoCodec_H266: strCodec = "H266"; return;
3063 case RecordingVideoCodec_VP8: strCodec = "VP8"; return;
3064 case RecordingVideoCodec_VP9: strCodec = "VP9"; return;
3065 case RecordingVideoCodec_AV1: strCodec = "AV1"; return;
3066 case RecordingVideoCodec_Other: strCodec = "other"; return;
3067 default: AssertFailedReturnVoid();
3068 }
3069}
3070
3071/**
3072 * Applies the default settings.
3073 */
3074void RecordingScreenSettings::applyDefaults(void)
3075{
3076 /*
3077 * Set sensible defaults.
3078 */
3079
3080 /*
3081 * Enable screen 0 by default.
3082 * Otherwise enabling recording without any screen enabled at all makes no sense.
3083 *
3084 * Note: When tweaking this, make sure to also alter RecordingScreenSettings::areDefaultSettings().
3085 */
3086 fEnabled = idScreen == 0 ? true : false;;
3087 enmDest = RecordingDestination_File;
3088 ulMaxTimeS = 0;
3089 strOptions = RecordingScreenSettings::getDefaultOptions();
3090 File.ulMaxSizeMB = 0;
3091 File.strName = "";
3092 Video.enmCodec = RecordingVideoCodec_VP8;
3093 Video.enmDeadline = RecordingCodecDeadline_Default;
3094 Video.enmRateCtlMode = RecordingRateControlMode_VBR;
3095 Video.enmScalingMode = RecordingVideoScalingMode_None;
3096 Video.ulWidth = 1024;
3097 Video.ulHeight = 768;
3098 Video.ulRate = 512;
3099 Video.ulFPS = 25;
3100#ifdef VBOX_WITH_AUDIO_RECORDING
3101# if defined(VBOX_WITH_LIBVORBIS)
3102 Audio.enmCodec = RecordingAudioCodec_OggVorbis;
3103# else
3104 Audio.enmCodec = RecordingAudioCodec_None;
3105# endif
3106#else
3107 Audio.enmCodec = RecordingAudioCodec_None;
3108#endif /* VBOX_WITH_RECORDING */
3109 Audio.enmDeadline = RecordingCodecDeadline_Default;
3110 Audio.enmRateCtlMode = RecordingRateControlMode_VBR;
3111 Audio.cBits = 16;
3112 Audio.cChannels = 2;
3113 Audio.uHz = 22050;
3114
3115 featureMap[RecordingFeature_Video] = true;
3116 featureMap[RecordingFeature_Audio] = false; /** @todo Audio is not yet enabled by default. */
3117}
3118
3119/**
3120 * Check if all settings have default values.
3121 *
3122 * @returns @c true if default, @c false if not.
3123 */
3124bool RecordingScreenSettings::areDefaultSettings(void) const
3125{
3126 return ( fEnabled == false
3127 /* Screen 0 is special: There we ALWAYS enable recording by default. */
3128 || ( idScreen == 0
3129 && fEnabled == true)
3130 )
3131 && enmDest == RecordingDestination_File
3132 && ulMaxTimeS == 0
3133 && strOptions == RecordingScreenSettings::getDefaultOptions()
3134 && File.ulMaxSizeMB == 0
3135 && File.strName == ""
3136 && Video.enmCodec == RecordingVideoCodec_VP8
3137 && Video.enmDeadline == RecordingCodecDeadline_Default
3138 && Video.enmRateCtlMode == RecordingRateControlMode_VBR
3139 && Video.enmScalingMode == RecordingVideoScalingMode_None
3140 && Video.ulWidth == 1024
3141 && Video.ulHeight == 768
3142 && Video.ulRate == 512
3143 && Video.ulFPS == 25
3144#ifdef VBOX_WITH_AUDIO_RECORDING
3145# if defined(VBOX_WITH_LIBVORBIS)
3146 && Audio.enmCodec == RecordingAudioCodec_OggVorbis
3147# else
3148 && Audio.enmCodec == RecordingAudioCodec_None
3149# endif
3150#else
3151 && Audio.enmCodec == RecordingAudioCodec_None
3152#endif /* VBOX_WITH_AUDIO_RECORDING */
3153 && Audio.enmDeadline == RecordingCodecDeadline_Default
3154 && Audio.enmRateCtlMode == RecordingRateControlMode_VBR
3155 && Audio.cBits == 16
3156 && Audio.cChannels == 2
3157 && Audio.uHz == 22050
3158 && featureMap.find(RecordingFeature_Video)->second == true
3159 && featureMap.find(RecordingFeature_Audio)->second == false;
3160}
3161
3162/**
3163 * Returns if a certain recording feature is enabled or not.
3164 *
3165 * @returns @c true if the feature is enabled, @c false if not.
3166 * @param enmFeature Feature to check.
3167 */
3168bool RecordingScreenSettings::isFeatureEnabled(RecordingFeature_T enmFeature) const
3169{
3170 RecordingFeatureMap::const_iterator itFeature = featureMap.find(enmFeature);
3171 if (itFeature != featureMap.end())
3172 return itFeature->second;
3173
3174 return false;
3175}
3176
3177/**
3178 * Comparison operator. This gets called from MachineConfigFile::operator==,
3179 * which in turn gets called from Machine::saveSettings to figure out whether
3180 * machine settings have really changed and thus need to be written out to disk.
3181 */
3182bool RecordingScreenSettings::operator==(const RecordingScreenSettings &d) const
3183{
3184 return fEnabled == d.fEnabled
3185 && enmDest == d.enmDest
3186 && featureMap == d.featureMap
3187 && ulMaxTimeS == d.ulMaxTimeS
3188 && strOptions == d.strOptions
3189 && File.strName == d.File.strName
3190 && File.ulMaxSizeMB == d.File.ulMaxSizeMB
3191 && Video.enmCodec == d.Video.enmCodec
3192 && Video.enmDeadline == d.Video.enmDeadline
3193 && Video.enmRateCtlMode == d.Video.enmRateCtlMode
3194 && Video.enmScalingMode == d.Video.enmScalingMode
3195 && Video.ulWidth == d.Video.ulWidth
3196 && Video.ulHeight == d.Video.ulHeight
3197 && Video.ulRate == d.Video.ulRate
3198 && Video.ulFPS == d.Video.ulFPS
3199 && Audio.enmCodec == d.Audio.enmCodec
3200 && Audio.enmDeadline == d.Audio.enmDeadline
3201 && Audio.enmRateCtlMode == d.Audio.enmRateCtlMode
3202 && Audio.cBits == d.Audio.cBits
3203 && Audio.cChannels == d.Audio.cChannels
3204 && Audio.uHz == d.Audio.uHz
3205 && featureMap == d.featureMap;
3206}
3207
3208/**
3209 * Constructor. Needs to set sane defaults which stand the test of time.
3210 */
3211RecordingCommonSettings::RecordingCommonSettings()
3212{
3213 applyDefaults();
3214}
3215
3216/**
3217 * Applies the default settings.
3218 */
3219void RecordingCommonSettings::applyDefaults(void)
3220{
3221 fEnabled = false;
3222}
3223
3224/**
3225 * Check if all settings have default values.
3226 */
3227bool RecordingCommonSettings::areDefaultSettings(void) const
3228{
3229 return fEnabled == false;
3230}
3231
3232/**
3233 * Comparison operator. This gets called from MachineConfigFile::operator==,
3234 * which in turn gets called from Machine::saveSettings to figure out whether
3235 * machine settings have really changed and thus need to be written out to disk.
3236 */
3237bool RecordingCommonSettings::operator==(const RecordingCommonSettings &d) const
3238{
3239 if (this == &d)
3240 return true;
3241
3242 return fEnabled == d.fEnabled;
3243}
3244
3245/**
3246 * Constructor. Needs to set sane defaults which stand the test of time.
3247 */
3248RecordingSettings::RecordingSettings()
3249{
3250 applyDefaults();
3251}
3252
3253/**
3254 * Applies the default settings.
3255 */
3256void RecordingSettings::applyDefaults(void)
3257{
3258 common.applyDefaults();
3259
3260 mapScreens.clear();
3261
3262 try
3263 {
3264 /* Always add screen 0 to the default configuration. */
3265 RecordingScreenSettings screenSettings(0 /* Screen ID */);
3266
3267 mapScreens[0 /* Screen ID */] = screenSettings;
3268 }
3269 catch (std::bad_alloc &)
3270 {
3271 AssertFailed();
3272 }
3273}
3274
3275/**
3276 * Check if all settings have default values.
3277 */
3278bool RecordingSettings::areDefaultSettings(void) const
3279{
3280 AssertReturn(mapScreens.size() >= 1, false); /* The first screen always must be present. */
3281
3282 if (!common.areDefaultSettings())
3283 return false;
3284
3285 RecordingScreenSettingsMap::const_iterator itScreen = mapScreens.begin();
3286 while (itScreen != mapScreens.end())
3287 {
3288 if (!itScreen->second.areDefaultSettings())
3289 return false;
3290 ++itScreen;
3291 }
3292
3293 return true;
3294}
3295
3296/**
3297 * Comparison operator. This gets called from MachineConfigFile::operator==,
3298 * which in turn gets called from Machine::saveSettings to figure out whether
3299 * machine settings have really changed and thus need to be written out to disk.
3300 */
3301bool RecordingSettings::operator==(const RecordingSettings &that) const
3302{
3303 if (this == &that) /* If pointers match, take a shortcut. */
3304 return true;
3305
3306 if (common == that.common)
3307 {
3308 /* Too lazy for a != operator. */
3309 }
3310 else
3311 return false;
3312
3313 if (mapScreens.size() != that.mapScreens.size())
3314 return false;
3315
3316 RecordingScreenSettingsMap::const_iterator itScreen = mapScreens.begin();
3317 RecordingScreenSettingsMap::const_iterator itScreenThat = that.mapScreens.begin();
3318 while ( itScreen != mapScreens.end()
3319 && itScreenThat != that.mapScreens.end())
3320 {
3321 if (itScreen->second == itScreenThat->second)
3322 {
3323 /* Nothing to do in here (yet). */
3324 }
3325 else
3326 return false;
3327
3328 ++itScreen;
3329 ++itScreenThat;
3330 }
3331
3332 return true;
3333}
3334
3335/**
3336 * Constructor. Needs to set sane defaults which stand the test of time.
3337 */
3338GraphicsAdapter::GraphicsAdapter() :
3339 graphicsControllerType(GraphicsControllerType_VBoxVGA),
3340 ulVRAMSizeMB(8),
3341 cMonitors(1),
3342 fAccelerate3D(false),
3343 fAccelerate2DVideo(false)
3344{
3345}
3346
3347/**
3348 * Check if all settings have default values.
3349 */
3350bool GraphicsAdapter::areDefaultSettings() const
3351{
3352 return graphicsControllerType == GraphicsControllerType_VBoxVGA
3353 && ulVRAMSizeMB == 8
3354 && cMonitors <= 1
3355 && !fAccelerate3D
3356 && !fAccelerate2DVideo;
3357}
3358
3359/**
3360 * Comparison operator. This gets called from MachineConfigFile::operator==,
3361 * which in turn gets called from Machine::saveSettings to figure out whether
3362 * machine settings have really changed and thus need to be written out to disk.
3363 */
3364bool GraphicsAdapter::operator==(const GraphicsAdapter &g) const
3365{
3366 return (this == &g)
3367 || ( graphicsControllerType == g.graphicsControllerType
3368 && ulVRAMSizeMB == g.ulVRAMSizeMB
3369 && cMonitors == g.cMonitors
3370 && fAccelerate3D == g.fAccelerate3D
3371 && fAccelerate2DVideo == g.fAccelerate2DVideo);
3372}
3373
3374/**
3375 * Constructor. Needs to set sane defaults which stand the test of time.
3376 */
3377TpmSettings::TpmSettings() :
3378 tpmType(TpmType_None)
3379{
3380}
3381
3382/**
3383 * Check if all settings have default values.
3384 */
3385bool TpmSettings::areDefaultSettings() const
3386{
3387 return tpmType == TpmType_None
3388 && strLocation.isEmpty();
3389}
3390
3391/**
3392 * Comparison operator. This gets called from MachineConfigFile::operator==,
3393 * which in turn gets called from Machine::saveSettings to figure out whether
3394 * machine settings have really changed and thus need to be written out to disk.
3395 */
3396bool TpmSettings::operator==(const TpmSettings &g) const
3397{
3398 return (this == &g)
3399 || ( tpmType == g.tpmType
3400 && strLocation == g.strLocation);
3401}
3402
3403/**
3404 * Constructor. Needs to set sane defaults which stand the test of time.
3405 */
3406NvramSettings::NvramSettings()
3407{
3408}
3409
3410/**
3411 * Check if all settings have default values.
3412 */
3413bool NvramSettings::areDefaultSettings() const
3414{
3415 return strNvramPath.isEmpty()
3416 && strKeyId.isEmpty()
3417 && strKeyStore.isEmpty();
3418}
3419
3420/**
3421 * Comparison operator. This gets called from MachineConfigFile::operator==,
3422 * which in turn gets called from Machine::saveSettings to figure out whether
3423 * machine settings have really changed and thus need to be written out to disk.
3424 */
3425bool NvramSettings::operator==(const NvramSettings &g) const
3426{
3427 return (this == &g)
3428 || (strNvramPath == g.strNvramPath)
3429 || (strKeyId == g.strKeyId)
3430 || (strKeyStore == g.strKeyStore);
3431}
3432
3433
3434/**
3435 * Constructor. Needs to set sane defaults which stand the test of time.
3436 */
3437USBController::USBController() :
3438 enmType(USBControllerType_Null)
3439{
3440}
3441
3442/**
3443 * Comparison operator. This gets called from MachineConfigFile::operator==,
3444 * which in turn gets called from Machine::saveSettings to figure out whether
3445 * machine settings have really changed and thus need to be written out to disk.
3446 */
3447bool USBController::operator==(const USBController &u) const
3448{
3449 return (this == &u)
3450 || ( strName == u.strName
3451 && enmType == u.enmType);
3452}
3453
3454/**
3455 * Constructor. Needs to set sane defaults which stand the test of time.
3456 */
3457USB::USB()
3458{
3459}
3460
3461/**
3462 * Comparison operator. This gets called from MachineConfigFile::operator==,
3463 * which in turn gets called from Machine::saveSettings to figure out whether
3464 * machine settings have really changed and thus need to be written out to disk.
3465 */
3466bool USB::operator==(const USB &u) const
3467{
3468 return (this == &u)
3469 || ( llUSBControllers == u.llUSBControllers
3470 && llDeviceFilters == u.llDeviceFilters);
3471}
3472
3473/**
3474 * Constructor. Needs to set sane defaults which stand the test of time.
3475 */
3476NAT::NAT() :
3477 u32Mtu(0),
3478 u32SockRcv(0),
3479 u32SockSnd(0),
3480 u32TcpRcv(0),
3481 u32TcpSnd(0),
3482 fDNSPassDomain(true), /* historically this value is true */
3483 fDNSProxy(false),
3484 fDNSUseHostResolver(false),
3485 fAliasLog(false),
3486 fAliasProxyOnly(false),
3487 fAliasUseSamePorts(false),
3488 fLocalhostReachable(true) /* Historically this value is true. */
3489{
3490}
3491
3492/**
3493 * Check if all DNS settings have default values.
3494 */
3495bool NAT::areDNSDefaultSettings() const
3496{
3497 return fDNSPassDomain && !fDNSProxy && !fDNSUseHostResolver;
3498}
3499
3500/**
3501 * Check if all Alias settings have default values.
3502 */
3503bool NAT::areAliasDefaultSettings() const
3504{
3505 return !fAliasLog && !fAliasProxyOnly && !fAliasUseSamePorts;
3506}
3507
3508/**
3509 * Check if all TFTP settings have default values.
3510 */
3511bool NAT::areTFTPDefaultSettings() const
3512{
3513 return strTFTPPrefix.isEmpty()
3514 && strTFTPBootFile.isEmpty()
3515 && strTFTPNextServer.isEmpty();
3516}
3517
3518/**
3519 * Check whether the localhost-reachable setting is the default for the given settings version.
3520 */
3521bool NAT::areLocalhostReachableDefaultSettings(SettingsVersion_T sv) const
3522{
3523 return ( fLocalhostReachable
3524 && sv < SettingsVersion_v1_19)
3525 || ( !fLocalhostReachable
3526 && sv >= SettingsVersion_v1_19);
3527}
3528
3529/**
3530 * Check if all settings have default values.
3531 */
3532bool NAT::areDefaultSettings(SettingsVersion_T sv) const
3533{
3534 /*
3535 * Before settings version 1.19 localhost was reachable by default
3536 * when using NAT which was changed with version 1.19+, see @bugref{9896}
3537 * for more information.
3538 */
3539 return strNetwork.isEmpty()
3540 && strBindIP.isEmpty()
3541 && u32Mtu == 0
3542 && u32SockRcv == 0
3543 && u32SockSnd == 0
3544 && u32TcpRcv == 0
3545 && u32TcpSnd == 0
3546 && areDNSDefaultSettings()
3547 && areAliasDefaultSettings()
3548 && areTFTPDefaultSettings()
3549 && mapRules.size() == 0
3550 && areLocalhostReachableDefaultSettings(sv);
3551}
3552
3553/**
3554 * Comparison operator. This gets called from MachineConfigFile::operator==,
3555 * which in turn gets called from Machine::saveSettings to figure out whether
3556 * machine settings have really changed and thus need to be written out to disk.
3557 */
3558bool NAT::operator==(const NAT &n) const
3559{
3560 return (this == &n)
3561 || ( strNetwork == n.strNetwork
3562 && strBindIP == n.strBindIP
3563 && u32Mtu == n.u32Mtu
3564 && u32SockRcv == n.u32SockRcv
3565 && u32SockSnd == n.u32SockSnd
3566 && u32TcpSnd == n.u32TcpSnd
3567 && u32TcpRcv == n.u32TcpRcv
3568 && strTFTPPrefix == n.strTFTPPrefix
3569 && strTFTPBootFile == n.strTFTPBootFile
3570 && strTFTPNextServer == n.strTFTPNextServer
3571 && fDNSPassDomain == n.fDNSPassDomain
3572 && fDNSProxy == n.fDNSProxy
3573 && fDNSUseHostResolver == n.fDNSUseHostResolver
3574 && fAliasLog == n.fAliasLog
3575 && fAliasProxyOnly == n.fAliasProxyOnly
3576 && fAliasUseSamePorts == n.fAliasUseSamePorts
3577 && fLocalhostReachable == n.fLocalhostReachable
3578 && mapRules == n.mapRules);
3579}
3580
3581/**
3582 * Constructor. Needs to set sane defaults which stand the test of time.
3583 */
3584NetworkAdapter::NetworkAdapter() :
3585 ulSlot(0),
3586 type(NetworkAdapterType_Am79C970A), // default for old VMs, for new ones it's Am79C973
3587 fEnabled(false),
3588 fCableConnected(false), // default for old VMs, for new ones it's true
3589 ulLineSpeed(0),
3590 enmPromiscModePolicy(NetworkAdapterPromiscModePolicy_Deny),
3591 fTraceEnabled(false),
3592 mode(NetworkAttachmentType_Null),
3593 ulBootPriority(0)
3594{
3595}
3596
3597/**
3598 * Check if all Generic Driver settings have default values.
3599 */
3600bool NetworkAdapter::areGenericDriverDefaultSettings() const
3601{
3602 return strGenericDriver.isEmpty()
3603 && genericProperties.size() == 0;
3604}
3605
3606/**
3607 * Check if all settings have default values.
3608 */
3609bool NetworkAdapter::areDefaultSettings(SettingsVersion_T sv) const
3610{
3611 // 5.0 and earlier had a default of fCableConnected=false, which doesn't
3612 // make a lot of sense (but it's a fact). Later versions don't save the
3613 // setting if it's at the default value and thus must get it right.
3614 return !fEnabled
3615 && strMACAddress.isEmpty()
3616 && ( (sv >= SettingsVersion_v1_16 && fCableConnected && type == NetworkAdapterType_Am79C973)
3617 || (sv < SettingsVersion_v1_16 && !fCableConnected && type == NetworkAdapterType_Am79C970A))
3618 && ulLineSpeed == 0
3619 && enmPromiscModePolicy == NetworkAdapterPromiscModePolicy_Deny
3620 && mode == NetworkAttachmentType_Null
3621 && nat.areDefaultSettings(sv)
3622 && strBridgedName.isEmpty()
3623 && strInternalNetworkName.isEmpty()
3624#ifdef VBOX_WITH_VMNET
3625 && strHostOnlyNetworkName.isEmpty()
3626#endif /* VBOX_WITH_VMNET */
3627#ifdef VBOX_WITH_CLOUD_NET
3628 && strCloudNetworkName.isEmpty()
3629#endif /* VBOX_WITH_CLOUD_NET */
3630 && strHostOnlyName.isEmpty()
3631 && areGenericDriverDefaultSettings()
3632 && strNATNetworkName.isEmpty();
3633}
3634
3635/**
3636 * Special check if settings of the non-current attachment type have default values.
3637 */
3638bool NetworkAdapter::areDisabledDefaultSettings(SettingsVersion_T sv) const
3639{
3640 return (mode != NetworkAttachmentType_NAT ? nat.areDefaultSettings(sv) : true)
3641 && (mode != NetworkAttachmentType_Bridged ? strBridgedName.isEmpty() : true)
3642 && (mode != NetworkAttachmentType_Internal ? strInternalNetworkName.isEmpty() : true)
3643#ifdef VBOX_WITH_VMNET
3644 && (mode != NetworkAttachmentType_HostOnlyNetwork ? strHostOnlyNetworkName.isEmpty() : true)
3645#endif /* VBOX_WITH_VMNET */
3646#ifdef VBOX_WITH_CLOUD_NET
3647 && (mode != NetworkAttachmentType_Cloud ? strCloudNetworkName.isEmpty() : true)
3648#endif /* VBOX_WITH_CLOUD_NET */
3649 && (mode != NetworkAttachmentType_HostOnly ? strHostOnlyName.isEmpty() : true)
3650 && (mode != NetworkAttachmentType_Generic ? areGenericDriverDefaultSettings() : true)
3651 && (mode != NetworkAttachmentType_NATNetwork ? strNATNetworkName.isEmpty() : true);
3652}
3653
3654/**
3655 * Comparison operator. This gets called from MachineConfigFile::operator==,
3656 * which in turn gets called from Machine::saveSettings to figure out whether
3657 * machine settings have really changed and thus need to be written out to disk.
3658 */
3659bool NetworkAdapter::operator==(const NetworkAdapter &n) const
3660{
3661 return (this == &n)
3662 || ( ulSlot == n.ulSlot
3663 && type == n.type
3664 && fEnabled == n.fEnabled
3665 && strMACAddress == n.strMACAddress
3666 && fCableConnected == n.fCableConnected
3667 && ulLineSpeed == n.ulLineSpeed
3668 && enmPromiscModePolicy == n.enmPromiscModePolicy
3669 && fTraceEnabled == n.fTraceEnabled
3670 && strTraceFile == n.strTraceFile
3671 && mode == n.mode
3672 && nat == n.nat
3673 && strBridgedName == n.strBridgedName
3674 && strHostOnlyName == n.strHostOnlyName
3675#ifdef VBOX_WITH_VMNET
3676 && strHostOnlyNetworkName == n.strHostOnlyNetworkName
3677#endif /* VBOX_WITH_VMNET */
3678 && strInternalNetworkName == n.strInternalNetworkName
3679#ifdef VBOX_WITH_CLOUD_NET
3680 && strCloudNetworkName == n.strCloudNetworkName
3681#endif /* VBOX_WITH_CLOUD_NET */
3682 && strGenericDriver == n.strGenericDriver
3683 && genericProperties == n.genericProperties
3684 && ulBootPriority == n.ulBootPriority
3685 && strBandwidthGroup == n.strBandwidthGroup);
3686}
3687
3688/**
3689 * Constructor. Needs to set sane defaults which stand the test of time.
3690 */
3691SerialPort::SerialPort() :
3692 ulSlot(0),
3693 fEnabled(false),
3694 ulIOAddress(0x3f8),
3695 ulIRQ(4),
3696 portMode(PortMode_Disconnected),
3697 fServer(false),
3698 uartType(UartType_U16550A)
3699{
3700}
3701
3702/**
3703 * Comparison operator. This gets called from MachineConfigFile::operator==,
3704 * which in turn gets called from Machine::saveSettings to figure out whether
3705 * machine settings have really changed and thus need to be written out to disk.
3706 */
3707bool SerialPort::operator==(const SerialPort &s) const
3708{
3709 return (this == &s)
3710 || ( ulSlot == s.ulSlot
3711 && fEnabled == s.fEnabled
3712 && ulIOAddress == s.ulIOAddress
3713 && ulIRQ == s.ulIRQ
3714 && portMode == s.portMode
3715 && strPath == s.strPath
3716 && fServer == s.fServer
3717 && uartType == s.uartType);
3718}
3719
3720/**
3721 * Constructor. Needs to set sane defaults which stand the test of time.
3722 */
3723ParallelPort::ParallelPort() :
3724 ulSlot(0),
3725 fEnabled(false),
3726 ulIOBase(0x378),
3727 ulIRQ(7)
3728{
3729}
3730
3731/**
3732 * Comparison operator. This gets called from MachineConfigFile::operator==,
3733 * which in turn gets called from Machine::saveSettings to figure out whether
3734 * machine settings have really changed and thus need to be written out to disk.
3735 */
3736bool ParallelPort::operator==(const ParallelPort &s) const
3737{
3738 return (this == &s)
3739 || ( ulSlot == s.ulSlot
3740 && fEnabled == s.fEnabled
3741 && ulIOBase == s.ulIOBase
3742 && ulIRQ == s.ulIRQ
3743 && strPath == s.strPath);
3744}
3745
3746/**
3747 * Constructor. Needs to set sane defaults which stand the test of time.
3748 */
3749AudioAdapter::AudioAdapter() :
3750 fEnabled(true), // default for old VMs, for new ones it's false
3751 fEnabledIn(true), // default for old VMs, for new ones it's false
3752 fEnabledOut(true), // default for old VMs, for new ones it's false
3753 controllerType(AudioControllerType_AC97),
3754 codecType(AudioCodecType_STAC9700),
3755 driverType(AudioDriverType_Null)
3756{
3757}
3758
3759/**
3760 * Check if all settings have default values.
3761 */
3762bool AudioAdapter::areDefaultSettings(SettingsVersion_T sv) const
3763{
3764 return (sv < SettingsVersion_v1_16 ? false : !fEnabled)
3765 && (sv <= SettingsVersion_v1_16 ? fEnabledIn : !fEnabledIn)
3766 && (sv <= SettingsVersion_v1_16 ? fEnabledOut : !fEnabledOut)
3767 && fEnabledOut == true
3768 && controllerType == AudioControllerType_AC97
3769 && codecType == AudioCodecType_STAC9700
3770 && properties.size() == 0;
3771}
3772
3773/**
3774 * Comparison operator. This gets called from MachineConfigFile::operator==,
3775 * which in turn gets called from Machine::saveSettings to figure out whether
3776 * machine settings have really changed and thus need to be written out to disk.
3777 */
3778bool AudioAdapter::operator==(const AudioAdapter &a) const
3779{
3780 return (this == &a)
3781 || ( fEnabled == a.fEnabled
3782 && fEnabledIn == a.fEnabledIn
3783 && fEnabledOut == a.fEnabledOut
3784 && controllerType == a.controllerType
3785 && codecType == a.codecType
3786 && driverType == a.driverType
3787 && properties == a.properties);
3788}
3789
3790/**
3791 * Constructor. Needs to set sane defaults which stand the test of time.
3792 */
3793SharedFolder::SharedFolder() :
3794 fWritable(false),
3795 fAutoMount(false)
3796{
3797}
3798
3799/**
3800 * Comparison operator. This gets called from MachineConfigFile::operator==,
3801 * which in turn gets called from Machine::saveSettings to figure out whether
3802 * machine settings have really changed and thus need to be written out to disk.
3803 */
3804bool SharedFolder::operator==(const SharedFolder &g) const
3805{
3806 return (this == &g)
3807 || ( strName == g.strName
3808 && strHostPath == g.strHostPath
3809 && fWritable == g.fWritable
3810 && fAutoMount == g.fAutoMount
3811 && strAutoMountPoint == g.strAutoMountPoint);
3812}
3813
3814/**
3815 * Constructor. Needs to set sane defaults which stand the test of time.
3816 */
3817GuestProperty::GuestProperty() :
3818 timestamp(0)
3819{
3820}
3821
3822/**
3823 * Comparison operator. This gets called from MachineConfigFile::operator==,
3824 * which in turn gets called from Machine::saveSettings to figure out whether
3825 * machine settings have really changed and thus need to be written out to disk.
3826 */
3827bool GuestProperty::operator==(const GuestProperty &g) const
3828{
3829 return (this == &g)
3830 || ( strName == g.strName
3831 && strValue == g.strValue
3832 && timestamp == g.timestamp
3833 && strFlags == g.strFlags);
3834}
3835
3836/**
3837 * Constructor. Needs to set sane defaults which stand the test of time.
3838 */
3839CpuIdLeafX86::CpuIdLeafX86() :
3840 idx(UINT32_MAX),
3841 idxSub(0),
3842 uEax(0),
3843 uEbx(0),
3844 uEcx(0),
3845 uEdx(0)
3846{
3847}
3848
3849/**
3850 * Comparison operator. This gets called from MachineConfigFile::operator==,
3851 * which in turn gets called from Machine::saveSettings to figure out whether
3852 * machine settings have really changed and thus need to be written out to disk.
3853 */
3854bool CpuIdLeafX86::operator==(const CpuIdLeafX86 &c) const
3855{
3856 return (this == &c)
3857 || ( idx == c.idx
3858 && idxSub == c.idxSub
3859 && uEax == c.uEax
3860 && uEbx == c.uEbx
3861 && uEcx == c.uEcx
3862 && uEdx == c.uEdx);
3863}
3864
3865/**
3866 * Constructor. Needs to set sane defaults which stand the test of time.
3867 */
3868Cpu::Cpu() :
3869 ulId(UINT32_MAX)
3870{
3871}
3872
3873/**
3874 * Comparison operator. This gets called from MachineConfigFile::operator==,
3875 * which in turn gets called from Machine::saveSettings to figure out whether
3876 * machine settings have really changed and thus need to be written out to disk.
3877 */
3878bool Cpu::operator==(const Cpu &c) const
3879{
3880 return (this == &c)
3881 || (ulId == c.ulId);
3882}
3883
3884/**
3885 * Constructor. Needs to set sane defaults which stand the test of time.
3886 */
3887BandwidthGroup::BandwidthGroup() :
3888 cMaxBytesPerSec(0),
3889 enmType(BandwidthGroupType_Null)
3890{
3891}
3892
3893/**
3894 * Comparison operator. This gets called from MachineConfigFile::operator==,
3895 * which in turn gets called from Machine::saveSettings to figure out whether
3896 * machine settings have really changed and thus need to be written out to disk.
3897 */
3898bool BandwidthGroup::operator==(const BandwidthGroup &i) const
3899{
3900 return (this == &i)
3901 || ( strName == i.strName
3902 && cMaxBytesPerSec == i.cMaxBytesPerSec
3903 && enmType == i.enmType);
3904}
3905
3906/**
3907 * IOSettings constructor.
3908 */
3909IOSettings::IOSettings() :
3910 fIOCacheEnabled(true),
3911 ulIOCacheSize(5)
3912{
3913}
3914
3915/**
3916 * Check if all IO Cache settings have default values.
3917 */
3918bool IOSettings::areIOCacheDefaultSettings() const
3919{
3920 return fIOCacheEnabled
3921 && ulIOCacheSize == 5;
3922}
3923
3924/**
3925 * Check if all settings have default values.
3926 */
3927bool IOSettings::areDefaultSettings() const
3928{
3929 return areIOCacheDefaultSettings()
3930 && llBandwidthGroups.size() == 0;
3931}
3932
3933/**
3934 * Comparison operator. This gets called from MachineConfigFile::operator==,
3935 * which in turn gets called from Machine::saveSettings to figure out whether
3936 * machine settings have really changed and thus need to be written out to disk.
3937 */
3938bool IOSettings::operator==(const IOSettings &i) const
3939{
3940 return (this == &i)
3941 || ( fIOCacheEnabled == i.fIOCacheEnabled
3942 && ulIOCacheSize == i.ulIOCacheSize
3943 && llBandwidthGroups == i.llBandwidthGroups);
3944}
3945
3946/**
3947 * Constructor. Needs to set sane defaults which stand the test of time.
3948 */
3949HostPCIDeviceAttachment::HostPCIDeviceAttachment() :
3950 uHostAddress(0),
3951 uGuestAddress(0)
3952{
3953}
3954
3955/**
3956 * Comparison operator. This gets called from MachineConfigFile::operator==,
3957 * which in turn gets called from Machine::saveSettings to figure out whether
3958 * machine settings have really changed and thus need to be written out to disk.
3959 */
3960bool HostPCIDeviceAttachment::operator==(const HostPCIDeviceAttachment &a) const
3961{
3962 return (this == &a)
3963 || ( uHostAddress == a.uHostAddress
3964 && uGuestAddress == a.uGuestAddress
3965 && strDeviceName == a.strDeviceName);
3966}
3967
3968#ifdef VBOX_WITH_VIRT_ARMV8
3969PlatformARM::PlatformARM()
3970{
3971}
3972
3973bool PlatformARM::operator==(const PlatformARM& h) const
3974{
3975 RT_NOREF(h);
3976 return true;
3977}
3978#endif /* VBOX_WITH_VIRT_ARMV8 */
3979
3980PlatformX86::PlatformX86() :
3981 fPAE(false),
3982 fAPIC(true),
3983 fX2APIC(false),
3984 fHPETEnabled(false),
3985 enmLongMode(HC_ARCH_BITS == 64 ? PlatformX86::LongMode_Enabled : PlatformX86::LongMode_Disabled),
3986 fTripleFaultReset(false),
3987 fIBPBOnVMExit(false),
3988 fIBPBOnVMEntry(false),
3989 fSpecCtrl(false),
3990 fSpecCtrlByHost(false),
3991 fL1DFlushOnSched(true),
3992 fL1DFlushOnVMEntry(false),
3993 fMDSClearOnSched(true),
3994 fMDSClearOnVMEntry(false),
3995 fHWVirtEx(true),
3996 fHWVirtExNestedPaging(true),
3997 fHWVirtExVPID(true),
3998 fHWVirtExUX(true),
3999 fHWVirtExForce(false),
4000 fHWVirtExUseNativeApi(false),
4001 fHWVirtExVirtVmsaveVmload(true),
4002 fNestedHWVirt(false)
4003{
4004 /* The default value for PAE depends on the host:
4005 * - 64 bits host -> always true
4006 * - 32 bits host -> true for Windows & Darwin (masked off if the host cpu doesn't support it anyway)
4007 */
4008#if HC_ARCH_BITS == 64 || defined(RT_OS_WINDOWS) || defined(RT_OS_DARWIN)
4009 fPAE = true;
4010#endif
4011
4012 /* The default value of large page supports depends on the host:
4013 * - 64 bits host -> true, unless it's Linux (pending further prediction work due to excessively expensive large page allocations)
4014 * - 32 bits host -> false
4015 */
4016#if HC_ARCH_BITS == 64 && !defined(RT_OS_LINUX)
4017 fHWVirtExLargePages = true; /** @todo BUGBUG Does this apply for ARM as well? */
4018#else
4019 /* Not supported on 32 bits hosts. */
4020 fHWVirtExLargePages = false;
4021#endif
4022}
4023
4024/**
4025 * Comparison operator. This gets called from MachineConfigFile::operator==,
4026 * which in turn gets called from Platform::saveSettings to figure out whether
4027 * machine settings have really changed and thus need to be written out to disk.
4028 */
4029bool PlatformX86::operator==(const PlatformX86& h) const
4030{
4031 return (this == &h)
4032 || ( fPAE == h.fPAE
4033 && fAPIC == h.fAPIC
4034 && fX2APIC == h.fX2APIC
4035 && fHPETEnabled == h.fHPETEnabled
4036 && enmLongMode == h.enmLongMode
4037 && llCpuIdLeafs == h.llCpuIdLeafs
4038 && fTripleFaultReset == h.fTripleFaultReset
4039 && fIBPBOnVMExit == h.fIBPBOnVMExit
4040 && fIBPBOnVMEntry == h.fIBPBOnVMEntry
4041 && fSpecCtrl == h.fSpecCtrl
4042 && fSpecCtrlByHost == h.fSpecCtrlByHost
4043 && fL1DFlushOnSched == h.fL1DFlushOnSched
4044 && fL1DFlushOnVMEntry == h.fL1DFlushOnVMEntry
4045 && fMDSClearOnSched == h.fMDSClearOnSched
4046 && fMDSClearOnVMEntry == h.fMDSClearOnVMEntry
4047 && fHWVirtEx == h.fHWVirtEx
4048 && fHWVirtExNestedPaging == h.fHWVirtExNestedPaging
4049 && fHWVirtExLargePages == h.fHWVirtExLargePages
4050 && fHWVirtExVPID == h.fHWVirtExVPID
4051 && fHWVirtExUX == h.fHWVirtExUX
4052 && fHWVirtExForce == h.fHWVirtExForce
4053 && fHWVirtExUseNativeApi == h.fHWVirtExUseNativeApi
4054 && fHWVirtExVirtVmsaveVmload == h.fHWVirtExVirtVmsaveVmload
4055 && fNestedHWVirt == h.fNestedHWVirt);
4056}
4057
4058/**
4059 * Constructor. Needs to set sane defaults which stand the test of time.
4060 */
4061Platform::Platform() :
4062 architectureType(PlatformArchitecture_x86), /* We default to x86 here, as this is what we ever had so far. */
4063 chipsetType(ChipsetType_PIIX3),
4064 iommuType(IommuType_None),
4065 fRTCUseUTC(false)
4066{
4067}
4068
4069/**
4070 * Comparison operator. This gets called from MachineConfigFile::operator==,
4071 * which in turn gets called from Platform::saveSettings to figure out whether
4072 * machine settings have really changed and thus need to be written out to disk.
4073 */
4074bool Platform::operator==(const Platform& h) const
4075{
4076 bool fRc = (this == &h)
4077 || ( architectureType == h.architectureType
4078 && chipsetType == h.chipsetType
4079 && iommuType == h.iommuType
4080 && fRTCUseUTC == h.fRTCUseUTC);
4081 if (fRc)
4082 {
4083 switch (architectureType)
4084 {
4085 case PlatformArchitecture_x86:
4086 return x86 == h.x86;
4087#ifdef VBOX_WITH_VIRT_ARMV8
4088 case PlatformArchitecture_ARM:
4089 return arm == h.arm;
4090#endif
4091 default:
4092 AssertFailedReturn(false);
4093 }
4094 }
4095
4096 return fRc;
4097}
4098
4099/**
4100 * Constructor. Needs to set sane defaults which stand the test of time.
4101 */
4102Hardware::Hardware() :
4103 strVersion("1"),
4104 cCPUs(1),
4105 fCpuHotPlug(false),
4106 ulCpuExecutionCap(100),
4107 uCpuIdPortabilityLevel(0),
4108 strCpuProfile("host"),
4109 ulMemorySizeMB((uint32_t)-1),
4110 pointingHIDType(PointingHIDType_PS2Mouse),
4111 keyboardHIDType(KeyboardHIDType_PS2Keyboard),
4112 paravirtProvider(ParavirtProvider_Legacy), // default for old VMs, for new ones it's ParavirtProvider_Default
4113 strParavirtDebug(""),
4114 fEmulatedUSBCardReader(false),
4115 clipboardMode(ClipboardMode_Disabled),
4116 fClipboardFileTransfersEnabled(false),
4117 dndMode(DnDMode_Disabled),
4118 ulMemoryBalloonSize(0),
4119 fPageFusionEnabled(false)
4120{
4121 mapBootOrder[0] = DeviceType_Floppy;
4122 mapBootOrder[1] = DeviceType_DVD;
4123 mapBootOrder[2] = DeviceType_HardDisk;
4124}
4125
4126/**
4127 * Check if all Paravirt settings have default values.
4128 */
4129bool Hardware::areParavirtDefaultSettings(SettingsVersion_T sv) const
4130{
4131 // 5.0 didn't save the paravirt settings if it is ParavirtProvider_Legacy,
4132 // so this default must be kept. Later versions don't save the setting if
4133 // it's at the default value.
4134 return ( (sv >= SettingsVersion_v1_16 && paravirtProvider == ParavirtProvider_Default)
4135 || (sv < SettingsVersion_v1_16 && paravirtProvider == ParavirtProvider_Legacy))
4136 && strParavirtDebug.isEmpty();
4137}
4138
4139/**
4140 * Check if all Boot Order settings have default values.
4141 */
4142bool Hardware::areBootOrderDefaultSettings() const
4143{
4144 BootOrderMap::const_iterator it0 = mapBootOrder.find(0);
4145 BootOrderMap::const_iterator it1 = mapBootOrder.find(1);
4146 BootOrderMap::const_iterator it2 = mapBootOrder.find(2);
4147 BootOrderMap::const_iterator it3 = mapBootOrder.find(3);
4148 return ( mapBootOrder.size() == 3
4149 || ( mapBootOrder.size() == 4
4150 && (it3 != mapBootOrder.end() && it3->second == DeviceType_Null)))
4151 && (it0 != mapBootOrder.end() && it0->second == DeviceType_Floppy)
4152 && (it1 != mapBootOrder.end() && it1->second == DeviceType_DVD)
4153 && (it2 != mapBootOrder.end() && it2->second == DeviceType_HardDisk);
4154}
4155
4156/**
4157 * Check if all Network Adapter settings have default values.
4158 */
4159bool Hardware::areAllNetworkAdaptersDefaultSettings(SettingsVersion_T sv) const
4160{
4161 for (NetworkAdaptersList::const_iterator it = llNetworkAdapters.begin();
4162 it != llNetworkAdapters.end();
4163 ++it)
4164 {
4165 if (!it->areDefaultSettings(sv))
4166 return false;
4167 }
4168 return true;
4169}
4170
4171/**
4172 * Comparison operator. This gets called from MachineConfigFile::operator==,
4173 * which in turn gets called from Machine::saveSettings to figure out whether
4174 * machine settings have really changed and thus need to be written out to disk.
4175 */
4176bool Hardware::operator==(const Hardware& h) const
4177{
4178 return (this == &h)
4179 || ( strVersion == h.strVersion
4180 && uuid == h.uuid
4181 && cCPUs == h.cCPUs
4182 && fCpuHotPlug == h.fCpuHotPlug
4183 && ulCpuExecutionCap == h.ulCpuExecutionCap
4184 && uCpuIdPortabilityLevel == h.uCpuIdPortabilityLevel
4185 && strCpuProfile == h.strCpuProfile
4186 && llCpus == h.llCpus
4187 && ulMemorySizeMB == h.ulMemorySizeMB
4188 && mapBootOrder == h.mapBootOrder
4189 && pointingHIDType == h.pointingHIDType
4190 && keyboardHIDType == h.keyboardHIDType
4191 && paravirtProvider == h.paravirtProvider
4192 && strParavirtDebug == h.strParavirtDebug
4193 && fEmulatedUSBCardReader == h.fEmulatedUSBCardReader
4194 && vrdeSettings == h.vrdeSettings
4195 && platformSettings == h.platformSettings
4196 && firmwareSettings == h.firmwareSettings
4197 && nvramSettings == h.nvramSettings
4198 && graphicsAdapter == h.graphicsAdapter
4199 && usbSettings == h.usbSettings
4200 && tpmSettings == h.tpmSettings
4201 && llNetworkAdapters == h.llNetworkAdapters
4202 && llSerialPorts == h.llSerialPorts
4203 && llParallelPorts == h.llParallelPorts
4204 && audioAdapter == h.audioAdapter
4205 && storage == h.storage
4206 && llSharedFolders == h.llSharedFolders
4207 && clipboardMode == h.clipboardMode
4208 && fClipboardFileTransfersEnabled == h.fClipboardFileTransfersEnabled
4209 && dndMode == h.dndMode
4210 && ulMemoryBalloonSize == h.ulMemoryBalloonSize
4211 && fPageFusionEnabled == h.fPageFusionEnabled
4212 && llGuestProperties == h.llGuestProperties
4213 && ioSettings == h.ioSettings
4214 && pciAttachments == h.pciAttachments
4215 && strDefaultFrontend == h.strDefaultFrontend);
4216}
4217
4218/**
4219 * Constructor. Needs to set sane defaults which stand the test of time.
4220 */
4221AttachedDevice::AttachedDevice() :
4222 deviceType(DeviceType_Null),
4223 fPassThrough(false),
4224 fTempEject(false),
4225 fNonRotational(false),
4226 fDiscard(false),
4227 fHotPluggable(false),
4228 lPort(0),
4229 lDevice(0)
4230{
4231}
4232
4233/**
4234 * Comparison operator. This gets called from MachineConfigFile::operator==,
4235 * which in turn gets called from Machine::saveSettings to figure out whether
4236 * machine settings have really changed and thus need to be written out to disk.
4237 */
4238bool AttachedDevice::operator==(const AttachedDevice &a) const
4239{
4240 return (this == &a)
4241 || ( deviceType == a.deviceType
4242 && fPassThrough == a.fPassThrough
4243 && fTempEject == a.fTempEject
4244 && fNonRotational == a.fNonRotational
4245 && fDiscard == a.fDiscard
4246 && fHotPluggable == a.fHotPluggable
4247 && lPort == a.lPort
4248 && lDevice == a.lDevice
4249 && uuid == a.uuid
4250 && strHostDriveSrc == a.strHostDriveSrc
4251 && strBwGroup == a.strBwGroup);
4252}
4253
4254/**
4255 * Constructor. Needs to set sane defaults which stand the test of time.
4256 */
4257StorageController::StorageController() :
4258 storageBus(StorageBus_IDE),
4259 controllerType(StorageControllerType_PIIX3),
4260 ulPortCount(2),
4261 ulInstance(0),
4262 fUseHostIOCache(true),
4263 fBootable(true)
4264{
4265}
4266
4267/**
4268 * Comparison operator. This gets called from MachineConfigFile::operator==,
4269 * which in turn gets called from Machine::saveSettings to figure out whether
4270 * machine settings have really changed and thus need to be written out to disk.
4271 */
4272bool StorageController::operator==(const StorageController &s) const
4273{
4274 return (this == &s)
4275 || ( strName == s.strName
4276 && storageBus == s.storageBus
4277 && controllerType == s.controllerType
4278 && ulPortCount == s.ulPortCount
4279 && ulInstance == s.ulInstance
4280 && fUseHostIOCache == s.fUseHostIOCache
4281 && llAttachedDevices == s.llAttachedDevices);
4282}
4283
4284/**
4285 * Comparison operator. This gets called from MachineConfigFile::operator==,
4286 * which in turn gets called from Machine::saveSettings to figure out whether
4287 * machine settings have really changed and thus need to be written out to disk.
4288 */
4289bool Storage::operator==(const Storage &s) const
4290{
4291 return (this == &s)
4292 || (llStorageControllers == s.llStorageControllers); // deep compare
4293}
4294
4295/**
4296 * Constructor. Needs to set sane defaults which stand the test of time.
4297 */
4298Debugging::Debugging() :
4299 fTracingEnabled(false),
4300 fAllowTracingToAccessVM(false),
4301 strTracingConfig(),
4302 enmDbgProvider(GuestDebugProvider_None),
4303 enmIoProvider(GuestDebugIoProvider_None),
4304 strAddress(),
4305 ulPort(0)
4306{
4307}
4308
4309/**
4310 * Check if all settings have default values.
4311 */
4312bool Debugging::areDefaultSettings() const
4313{
4314 return !fTracingEnabled
4315 && !fAllowTracingToAccessVM
4316 && strTracingConfig.isEmpty()
4317 && enmDbgProvider == GuestDebugProvider_None
4318 && enmIoProvider == GuestDebugIoProvider_None
4319 && strAddress.isEmpty()
4320 && ulPort == 0;
4321}
4322
4323/**
4324 * Comparison operator. This gets called from MachineConfigFile::operator==,
4325 * which in turn gets called from Machine::saveSettings to figure out whether
4326 * machine settings have really changed and thus need to be written out to disk.
4327 */
4328bool Debugging::operator==(const Debugging &d) const
4329{
4330 return (this == &d)
4331 || ( fTracingEnabled == d.fTracingEnabled
4332 && fAllowTracingToAccessVM == d.fAllowTracingToAccessVM
4333 && strTracingConfig == d.strTracingConfig
4334 && enmDbgProvider == d.enmDbgProvider
4335 && enmIoProvider == d.enmIoProvider
4336 && strAddress == d.strAddress
4337 && ulPort == d.ulPort);
4338}
4339
4340/**
4341 * Constructor. Needs to set sane defaults which stand the test of time.
4342 */
4343Autostart::Autostart() :
4344 fAutostartEnabled(false),
4345 uAutostartDelay(0),
4346 enmAutostopType(AutostopType_Disabled)
4347{
4348}
4349
4350/**
4351 * Check if all settings have default values.
4352 */
4353bool Autostart::areDefaultSettings() const
4354{
4355 return !fAutostartEnabled
4356 && !uAutostartDelay
4357 && enmAutostopType == AutostopType_Disabled;
4358}
4359
4360/**
4361 * Comparison operator. This gets called from MachineConfigFile::operator==,
4362 * which in turn gets called from Machine::saveSettings to figure out whether
4363 * machine settings have really changed and thus need to be written out to disk.
4364 */
4365bool Autostart::operator==(const Autostart &a) const
4366{
4367 return (this == &a)
4368 || ( fAutostartEnabled == a.fAutostartEnabled
4369 && uAutostartDelay == a.uAutostartDelay
4370 && enmAutostopType == a.enmAutostopType);
4371}
4372
4373/**
4374 * Constructor. Needs to set sane defaults which stand the test of time.
4375 */
4376Snapshot::Snapshot()
4377{
4378 RTTimeSpecSetNano(&timestamp, 0);
4379}
4380
4381/**
4382 * Comparison operator. This gets called from MachineConfigFile::operator==,
4383 * which in turn gets called from Machine::saveSettings to figure out whether
4384 * machine settings have really changed and thus need to be written out to disk.
4385 */
4386bool Snapshot::operator==(const Snapshot &s) const
4387{
4388 return (this == &s)
4389 || ( uuid == s.uuid
4390 && strName == s.strName
4391 && strDescription == s.strDescription
4392 && RTTimeSpecIsEqual(&timestamp, &s.timestamp)
4393 && strStateFile == s.strStateFile
4394 && hardware == s.hardware // deep compare
4395 && recordingSettings == s.recordingSettings // deep compare
4396 && llChildSnapshots == s.llChildSnapshots // deep compare
4397 && debugging == s.debugging
4398 && autostart == s.autostart);
4399}
4400
4401const struct Snapshot settings::Snapshot::Empty; /* default ctor is OK */
4402
4403/**
4404 * Constructor. Needs to set sane defaults which stand the test of time.
4405 */
4406MachineUserData::MachineUserData() :
4407 fDirectoryIncludesUUID(false),
4408 fNameSync(true),
4409 fTeleporterEnabled(false),
4410 uTeleporterPort(0),
4411 enmVMPriority(VMProcPriority_Default),
4412 enmExecEngine(VMExecutionEngine_Default)
4413{
4414 llGroups.push_back("/");
4415}
4416
4417/**
4418 * Comparison operator. This gets called from MachineConfigFile::operator==,
4419 * which in turn gets called from Machine::saveSettings to figure out whether
4420 * machine settings have really changed and thus need to be written out to disk.
4421 */
4422bool MachineUserData::operator==(const MachineUserData &c) const
4423{
4424 return (this == &c)
4425 || ( strName == c.strName
4426 && fDirectoryIncludesUUID == c.fDirectoryIncludesUUID
4427 && fNameSync == c.fNameSync
4428 && strDescription == c.strDescription
4429 && llGroups == c.llGroups
4430 && strOsType == c.strOsType
4431 && strSnapshotFolder == c.strSnapshotFolder
4432 && fTeleporterEnabled == c.fTeleporterEnabled
4433 && uTeleporterPort == c.uTeleporterPort
4434 && strTeleporterAddress == c.strTeleporterAddress
4435 && strTeleporterPassword == c.strTeleporterPassword
4436 && ovIcon == c.ovIcon
4437 && enmVMPriority == c.enmVMPriority
4438 && enmExecEngine == c.enmExecEngine);
4439}
4440
4441
4442////////////////////////////////////////////////////////////////////////////////
4443//
4444// MachineConfigFile
4445//
4446////////////////////////////////////////////////////////////////////////////////
4447
4448/**
4449 * Constructor.
4450 *
4451 * If pstrFilename is != NULL, this reads the given settings file into the member
4452 * variables and various substructures and lists. Otherwise, the member variables
4453 * are initialized with default values.
4454 *
4455 * Throws variants of xml::Error for I/O, XML and logical content errors, which
4456 * the caller should catch; if this constructor does not throw, then the member
4457 * variables contain meaningful values (either from the file or defaults).
4458 *
4459 * @param pstrFilename
4460 * @param pCryptoIf Pointer to the cryptographic interface, required for an encrypted machine config.
4461 * @param pszPassword The password to use for an encrypted machine config.
4462 */
4463MachineConfigFile::MachineConfigFile(const Utf8Str *pstrFilename, PCVBOXCRYPTOIF pCryptoIf, const char *pszPassword)
4464 : ConfigFileBase(pstrFilename),
4465 enmParseState(ParseState_NotParsed),
4466 fCurrentStateModified(true),
4467 fAborted(false)
4468{
4469 RTTimeNow(&timeLastStateChange);
4470
4471 if (pstrFilename)
4472 {
4473 // the ConfigFileBase constructor has loaded the XML file, so now
4474 // we need only analyze what is in there
4475
4476 xml::NodesLoop nlRootChildren(*m->pelmRoot);
4477 const xml::ElementNode *pelmRootChild;
4478 while ((pelmRootChild = nlRootChildren.forAllNodes()))
4479 {
4480 if (pelmRootChild->nameEquals("MachineEncrypted"))
4481 readMachineEncrypted(*pelmRootChild, pCryptoIf, pszPassword);
4482 if (pelmRootChild->nameEquals("Machine"))
4483 readMachine(*pelmRootChild);
4484 }
4485
4486 // clean up memory allocated by XML engine
4487 clearDocument();
4488
4489 if (enmParseState == ParseState_NotParsed)
4490 enmParseState = ParseState_Parsed;
4491 }
4492}
4493
4494/**
4495 * Public routine which returns true if this machine config file can have its
4496 * own media registry (which is true for settings version v1.11 and higher,
4497 * i.e. files created by VirtualBox 4.0 and higher).
4498 * @return
4499 */
4500bool MachineConfigFile::canHaveOwnMediaRegistry() const
4501{
4502 return (m->sv >= SettingsVersion_v1_11);
4503}
4504
4505/**
4506 * Public routine which copies encryption settings. Used by Machine::saveSettings
4507 * so that the encryption settings do not get lost when a copy of the Machine settings
4508 * file is made to see if settings have actually changed.
4509 * @param other
4510 */
4511void MachineConfigFile::copyEncryptionSettingsFrom(const MachineConfigFile &other)
4512{
4513 strKeyId = other.strKeyId;
4514 strKeyStore = other.strKeyStore;
4515}
4516
4517/**
4518 * Public routine which allows for importing machine XML from an external DOM tree.
4519 * Use this after having called the constructor with a NULL argument.
4520 *
4521 * This is used by the OVF code if a <vbox:Machine> element has been encountered
4522 * in an OVF VirtualSystem element.
4523 *
4524 * @param elmMachine
4525 */
4526void MachineConfigFile::importMachineXML(const xml::ElementNode &elmMachine)
4527{
4528 // Ideally the version should be mandatory, but since VirtualBox didn't
4529 // care about it until 5.1 came with different defaults, there are OVF
4530 // files created by magicians (not using VirtualBox, which always wrote it)
4531 // which lack this information. Let's hope that they learn to add the
4532 // version when they switch to the newer settings style/defaults of 5.1.
4533 if (!(elmMachine.getAttributeValue("version", m->strSettingsVersionFull)))
4534 m->strSettingsVersionFull = VBOX_XML_IMPORT_VERSION_FULL;
4535
4536 LogRel(("Import settings with version \"%s\"\n", m->strSettingsVersionFull.c_str()));
4537
4538 m->sv = parseVersion(m->strSettingsVersionFull, &elmMachine);
4539
4540 // remember the settings version we read in case it gets upgraded later,
4541 // so we know when to make backups
4542 m->svRead = m->sv;
4543
4544 readMachine(elmMachine);
4545}
4546
4547/**
4548 * Comparison operator. This gets called from Machine::saveSettings to figure out
4549 * whether machine settings have really changed and thus need to be written out to disk.
4550 *
4551 * Even though this is called operator==, this does NOT compare all fields; the "equals"
4552 * should be understood as "has the same machine config as". The following fields are
4553 * NOT compared:
4554 * -- settings versions and file names inherited from ConfigFileBase;
4555 * -- fCurrentStateModified because that is considered separately in Machine::saveSettings!!
4556 *
4557 * The "deep" comparisons marked below will invoke the operator== functions of the
4558 * structs defined in this file, which may in turn go into comparing lists of
4559 * other structures. As a result, invoking this can be expensive, but it's
4560 * less expensive than writing out XML to disk.
4561 */
4562bool MachineConfigFile::operator==(const MachineConfigFile &c) const
4563{
4564 return (this == &c)
4565 || ( uuid == c.uuid
4566 && machineUserData == c.machineUserData
4567 && strStateFile == c.strStateFile
4568 && uuidCurrentSnapshot == c.uuidCurrentSnapshot
4569 // skip fCurrentStateModified!
4570 && RTTimeSpecIsEqual(&timeLastStateChange, &c.timeLastStateChange)
4571 && fAborted == c.fAborted
4572 && hardwareMachine == c.hardwareMachine // this one's deep
4573 && mediaRegistry == c.mediaRegistry // this one's deep
4574 // skip mapExtraDataItems! there is no old state available as it's always forced
4575 && llFirstSnapshot == c.llFirstSnapshot // this one's deep
4576 && recordingSettings == c.recordingSettings // this one's deep
4577 && strKeyId == c.strKeyId
4578 && strKeyStore == c.strKeyStore
4579 && strStateKeyId == c.strStateKeyId
4580 && strStateKeyStore == c.strStateKeyStore
4581 && strLogKeyId == c.strLogKeyId
4582 && strLogKeyStore == c.strLogKeyStore);
4583}
4584
4585/**
4586 * Called from MachineConfigFile::readHardware() to read CPU information.
4587 *
4588 * @param elmCpu
4589 * @param ll
4590 */
4591void MachineConfigFile::readCpuTree(const xml::ElementNode &elmCpu,
4592 CpuList &ll)
4593{
4594 xml::NodesLoop nl1(elmCpu, "Cpu");
4595 const xml::ElementNode *pelmCpu;
4596 while ((pelmCpu = nl1.forAllNodes()))
4597 {
4598 Cpu cpu;
4599
4600 if (!pelmCpu->getAttributeValue("id", cpu.ulId))
4601 throw ConfigFileError(this, pelmCpu, N_("Required Cpu/@id attribute is missing"));
4602
4603 ll.push_back(cpu);
4604 }
4605}
4606
4607/**
4608 * Called from MachineConfigFile::readPlatformX86() to read x86 CPUID information.
4609 *
4610 * @param elmCpuid
4611 * @param ll
4612 */
4613void MachineConfigFile::readCpuIdTreeX86(const xml::ElementNode &elmCpuid,
4614 CpuIdLeafsX86List &ll)
4615{
4616 xml::NodesLoop nl1(elmCpuid, "CpuIdLeaf");
4617 const xml::ElementNode *pelmCpuIdLeaf;
4618 while ((pelmCpuIdLeaf = nl1.forAllNodes()))
4619 {
4620 CpuIdLeafX86 leaf;
4621
4622 if (!pelmCpuIdLeaf->getAttributeValue("id", leaf.idx))
4623 throw ConfigFileError(this, pelmCpuIdLeaf, N_("Required CpuIdLeaf/@id attribute is missing"));
4624
4625 if (!pelmCpuIdLeaf->getAttributeValue("subleaf", leaf.idxSub))
4626 leaf.idxSub = 0;
4627 pelmCpuIdLeaf->getAttributeValue("eax", leaf.uEax);
4628 pelmCpuIdLeaf->getAttributeValue("ebx", leaf.uEbx);
4629 pelmCpuIdLeaf->getAttributeValue("ecx", leaf.uEcx);
4630 pelmCpuIdLeaf->getAttributeValue("edx", leaf.uEdx);
4631
4632 ll.push_back(leaf);
4633 }
4634}
4635
4636/**
4637 * Called from MachineConfigFile::readHardware() to network information.
4638 * @param elmNetwork
4639 * @param ll
4640 */
4641void MachineConfigFile::readNetworkAdapters(const xml::ElementNode &elmNetwork,
4642 NetworkAdaptersList &ll)
4643{
4644 xml::NodesLoop nl1(elmNetwork, "Adapter");
4645 const xml::ElementNode *pelmAdapter;
4646 while ((pelmAdapter = nl1.forAllNodes()))
4647 {
4648 NetworkAdapter nic;
4649
4650 if (m->sv >= SettingsVersion_v1_16)
4651 {
4652 /* Starting with VirtualBox 5.1 the default is cable connected and
4653 * PCnet-FAST III. Needs to match NetworkAdapter.areDefaultSettings(). */
4654 nic.fCableConnected = true;
4655 nic.type = NetworkAdapterType_Am79C973;
4656 }
4657
4658 if (!pelmAdapter->getAttributeValue("slot", nic.ulSlot))
4659 throw ConfigFileError(this, pelmAdapter, N_("Required Adapter/@slot attribute is missing"));
4660
4661 Utf8Str strTemp;
4662 if (pelmAdapter->getAttributeValue("type", strTemp))
4663 {
4664 if (strTemp == "Am79C970A")
4665 nic.type = NetworkAdapterType_Am79C970A;
4666 else if (strTemp == "Am79C973")
4667 nic.type = NetworkAdapterType_Am79C973;
4668 else if (strTemp == "Am79C960")
4669 nic.type = NetworkAdapterType_Am79C960;
4670 else if (strTemp == "82540EM")
4671 nic.type = NetworkAdapterType_I82540EM;
4672 else if (strTemp == "82543GC")
4673 nic.type = NetworkAdapterType_I82543GC;
4674 else if (strTemp == "82545EM")
4675 nic.type = NetworkAdapterType_I82545EM;
4676 else if (strTemp == "virtio")
4677 nic.type = NetworkAdapterType_Virtio;
4678 else if (strTemp == "NE1000")
4679 nic.type = NetworkAdapterType_NE1000;
4680 else if (strTemp == "NE2000")
4681 nic.type = NetworkAdapterType_NE2000;
4682 else if (strTemp == "WD8003")
4683 nic.type = NetworkAdapterType_WD8003;
4684 else if (strTemp == "WD8013")
4685 nic.type = NetworkAdapterType_WD8013;
4686 else if (strTemp == "3C503")
4687 nic.type = NetworkAdapterType_ELNK2;
4688 else if (strTemp == "3C501")
4689 nic.type = NetworkAdapterType_ELNK1;
4690 else
4691 throw ConfigFileError(this, pelmAdapter, N_("Invalid value '%s' in Adapter/@type attribute"), strTemp.c_str());
4692 }
4693
4694 pelmAdapter->getAttributeValue("enabled", nic.fEnabled);
4695 pelmAdapter->getAttributeValue("MACAddress", nic.strMACAddress);
4696 pelmAdapter->getAttributeValue("cable", nic.fCableConnected);
4697 pelmAdapter->getAttributeValue("speed", nic.ulLineSpeed);
4698
4699 if (pelmAdapter->getAttributeValue("promiscuousModePolicy", strTemp))
4700 {
4701 if (strTemp == "Deny")
4702 nic.enmPromiscModePolicy = NetworkAdapterPromiscModePolicy_Deny;
4703 else if (strTemp == "AllowNetwork")
4704 nic.enmPromiscModePolicy = NetworkAdapterPromiscModePolicy_AllowNetwork;
4705 else if (strTemp == "AllowAll")
4706 nic.enmPromiscModePolicy = NetworkAdapterPromiscModePolicy_AllowAll;
4707 else
4708 throw ConfigFileError(this, pelmAdapter,
4709 N_("Invalid value '%s' in Adapter/@promiscuousModePolicy attribute"), strTemp.c_str());
4710 }
4711
4712 pelmAdapter->getAttributeValue("trace", nic.fTraceEnabled);
4713 pelmAdapter->getAttributeValue("tracefile", nic.strTraceFile);
4714 pelmAdapter->getAttributeValue("bootPriority", nic.ulBootPriority);
4715 pelmAdapter->getAttributeValue("bandwidthGroup", nic.strBandwidthGroup);
4716
4717 xml::ElementNodesList llNetworkModes;
4718 pelmAdapter->getChildElements(llNetworkModes);
4719 xml::ElementNodesList::iterator it;
4720 /* We should have only active mode descriptor and disabled modes set */
4721 if (llNetworkModes.size() > 2)
4722 {
4723 throw ConfigFileError(this, pelmAdapter, N_("Invalid number of modes ('%d') attached to Adapter attribute"), llNetworkModes.size());
4724 }
4725 for (it = llNetworkModes.begin(); it != llNetworkModes.end(); ++it)
4726 {
4727 const xml::ElementNode *pelmNode = *it;
4728 if (pelmNode->nameEquals("DisabledModes"))
4729 {
4730 xml::ElementNodesList llDisabledNetworkModes;
4731 xml::ElementNodesList::iterator itDisabled;
4732 pelmNode->getChildElements(llDisabledNetworkModes);
4733 /* run over disabled list and load settings */
4734 for (itDisabled = llDisabledNetworkModes.begin();
4735 itDisabled != llDisabledNetworkModes.end(); ++itDisabled)
4736 {
4737 const xml::ElementNode *pelmDisabledNode = *itDisabled;
4738 readAttachedNetworkMode(*pelmDisabledNode, false, nic);
4739 }
4740 }
4741 else
4742 readAttachedNetworkMode(*pelmNode, true, nic);
4743 }
4744 // else: default is NetworkAttachmentType_Null
4745
4746 ll.push_back(nic);
4747 }
4748}
4749
4750void MachineConfigFile::readAttachedNetworkMode(const xml::ElementNode &elmMode, bool fEnabled, NetworkAdapter &nic)
4751{
4752 NetworkAttachmentType_T enmAttachmentType = NetworkAttachmentType_Null;
4753
4754 if (elmMode.nameEquals("NAT"))
4755 {
4756 enmAttachmentType = NetworkAttachmentType_NAT;
4757
4758 elmMode.getAttributeValue("network", nic.nat.strNetwork);
4759 elmMode.getAttributeValue("hostip", nic.nat.strBindIP);
4760 elmMode.getAttributeValue("mtu", nic.nat.u32Mtu);
4761 elmMode.getAttributeValue("sockrcv", nic.nat.u32SockRcv);
4762 elmMode.getAttributeValue("socksnd", nic.nat.u32SockSnd);
4763 elmMode.getAttributeValue("tcprcv", nic.nat.u32TcpRcv);
4764 elmMode.getAttributeValue("tcpsnd", nic.nat.u32TcpSnd);
4765 elmMode.getAttributeValue("localhost-reachable", nic.nat.fLocalhostReachable);
4766 const xml::ElementNode *pelmDNS;
4767 if ((pelmDNS = elmMode.findChildElement("DNS")))
4768 {
4769 pelmDNS->getAttributeValue("pass-domain", nic.nat.fDNSPassDomain);
4770 pelmDNS->getAttributeValue("use-proxy", nic.nat.fDNSProxy);
4771 pelmDNS->getAttributeValue("use-host-resolver", nic.nat.fDNSUseHostResolver);
4772 }
4773 const xml::ElementNode *pelmAlias;
4774 if ((pelmAlias = elmMode.findChildElement("Alias")))
4775 {
4776 pelmAlias->getAttributeValue("logging", nic.nat.fAliasLog);
4777 pelmAlias->getAttributeValue("proxy-only", nic.nat.fAliasProxyOnly);
4778 pelmAlias->getAttributeValue("use-same-ports", nic.nat.fAliasUseSamePorts);
4779 }
4780 const xml::ElementNode *pelmTFTP;
4781 if ((pelmTFTP = elmMode.findChildElement("TFTP")))
4782 {
4783 pelmTFTP->getAttributeValue("prefix", nic.nat.strTFTPPrefix);
4784 pelmTFTP->getAttributeValue("boot-file", nic.nat.strTFTPBootFile);
4785 pelmTFTP->getAttributeValue("next-server", nic.nat.strTFTPNextServer);
4786 }
4787
4788 readNATForwardRulesMap(elmMode, nic.nat.mapRules);
4789 }
4790 else if ( elmMode.nameEquals("HostInterface")
4791 || elmMode.nameEquals("BridgedInterface"))
4792 {
4793 enmAttachmentType = NetworkAttachmentType_Bridged;
4794
4795 // optional network name, cannot be required or we have trouble with
4796 // settings which are saved before configuring the network name
4797 elmMode.getAttributeValue("name", nic.strBridgedName);
4798 }
4799 else if (elmMode.nameEquals("InternalNetwork"))
4800 {
4801 enmAttachmentType = NetworkAttachmentType_Internal;
4802
4803 // optional network name, cannot be required or we have trouble with
4804 // settings which are saved before configuring the network name
4805 elmMode.getAttributeValue("name", nic.strInternalNetworkName);
4806 }
4807 else if (elmMode.nameEquals("HostOnlyInterface"))
4808 {
4809 enmAttachmentType = NetworkAttachmentType_HostOnly;
4810
4811 // optional network name, cannot be required or we have trouble with
4812 // settings which are saved before configuring the network name
4813 elmMode.getAttributeValue("name", nic.strHostOnlyName);
4814 }
4815#ifdef VBOX_WITH_VMNET
4816 else if (elmMode.nameEquals("HostOnlyNetwork"))
4817 {
4818 enmAttachmentType = NetworkAttachmentType_HostOnlyNetwork;
4819
4820 // optional network name, cannot be required or we have trouble with
4821 // settings which are saved before configuring the network name
4822 elmMode.getAttributeValue("name", nic.strHostOnlyNetworkName);
4823 }
4824#endif /* VBOX_WITH_VMNET */
4825 else if (elmMode.nameEquals("GenericInterface"))
4826 {
4827 enmAttachmentType = NetworkAttachmentType_Generic;
4828
4829 elmMode.getAttributeValue("driver", nic.strGenericDriver); // optional network attachment driver
4830
4831 // get all properties
4832 xml::NodesLoop nl(elmMode);
4833 const xml::ElementNode *pelmModeChild;
4834 while ((pelmModeChild = nl.forAllNodes()))
4835 {
4836 if (pelmModeChild->nameEquals("Property"))
4837 {
4838 Utf8Str strPropName, strPropValue;
4839 if ( pelmModeChild->getAttributeValue("name", strPropName)
4840 && pelmModeChild->getAttributeValue("value", strPropValue) )
4841 nic.genericProperties[strPropName] = strPropValue;
4842 else
4843 throw ConfigFileError(this, pelmModeChild, N_("Required GenericInterface/Property/@name or @value attribute is missing"));
4844 }
4845 }
4846 }
4847 else if (elmMode.nameEquals("NATNetwork"))
4848 {
4849 enmAttachmentType = NetworkAttachmentType_NATNetwork;
4850
4851 // optional network name, cannot be required or we have trouble with
4852 // settings which are saved before configuring the network name
4853 elmMode.getAttributeValue("name", nic.strNATNetworkName);
4854 }
4855 else if (elmMode.nameEquals("VDE"))
4856 {
4857 // inofficial hack (VDE networking was never part of the official
4858 // settings, so it's not mentioned in VirtualBox-settings.xsd)
4859 enmAttachmentType = NetworkAttachmentType_Generic;
4860
4861 com::Utf8Str strVDEName;
4862 elmMode.getAttributeValue("network", strVDEName); // optional network name
4863 nic.strGenericDriver = "VDE";
4864 nic.genericProperties["network"] = strVDEName;
4865 }
4866#ifdef VBOX_WITH_VMNET
4867 else if (elmMode.nameEquals("HostOnlyNetwork"))
4868 {
4869 enmAttachmentType = NetworkAttachmentType_HostOnly;
4870
4871 // optional network name, cannot be required or we have trouble with
4872 // settings which are saved before configuring the network name
4873 elmMode.getAttributeValue("name", nic.strHostOnlyNetworkName);
4874 }
4875#endif /* VBOX_WITH_VMNET */
4876#ifdef VBOX_WITH_CLOUD_NET
4877 else if (elmMode.nameEquals("CloudNetwork"))
4878 {
4879 enmAttachmentType = NetworkAttachmentType_Cloud;
4880
4881 // optional network name, cannot be required or we have trouble with
4882 // settings which are saved before configuring the network name
4883 elmMode.getAttributeValue("name", nic.strCloudNetworkName);
4884 }
4885#endif /* VBOX_WITH_CLOUD_NET */
4886
4887 if (fEnabled && enmAttachmentType != NetworkAttachmentType_Null)
4888 nic.mode = enmAttachmentType;
4889}
4890
4891/**
4892 * Called from MachineConfigFile::readHardware() to read serial port information.
4893 * @param elmUART
4894 * @param ll
4895 */
4896void MachineConfigFile::readSerialPorts(const xml::ElementNode &elmUART,
4897 SerialPortsList &ll)
4898{
4899 xml::NodesLoop nl1(elmUART, "Port");
4900 const xml::ElementNode *pelmPort;
4901 while ((pelmPort = nl1.forAllNodes()))
4902 {
4903 SerialPort port;
4904 if (!pelmPort->getAttributeValue("slot", port.ulSlot))
4905 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@slot attribute is missing"));
4906
4907 // slot must be unique
4908 for (SerialPortsList::const_iterator it = ll.begin();
4909 it != ll.end();
4910 ++it)
4911 if ((*it).ulSlot == port.ulSlot)
4912 throw ConfigFileError(this, pelmPort, N_("Invalid value %RU32 in UART/Port/@slot attribute: value is not unique"), port.ulSlot);
4913
4914 if (!pelmPort->getAttributeValue("enabled", port.fEnabled))
4915 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@enabled attribute is missing"));
4916 if (m->sv >= SettingsVersion_v1_20) /* IOBase was changed to IOAddress since settings v1.20. */
4917 {
4918 if (!pelmPort->getAttributeValue("IOAddress", port.ulIOAddress))
4919 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@IOAddress attribute is missing"));
4920 }
4921 else /* Settings < v1.20. */
4922 {
4923 if (!pelmPort->getAttributeValue("IOBase", port.ulIOAddress))
4924 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@IOBase attribute is missing"));
4925 }
4926 if (!pelmPort->getAttributeValue("IRQ", port.ulIRQ))
4927 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@IRQ attribute is missing"));
4928
4929 Utf8Str strPortMode;
4930 if (!pelmPort->getAttributeValue("hostMode", strPortMode))
4931 throw ConfigFileError(this, pelmPort, N_("Required UART/Port/@hostMode attribute is missing"));
4932 if (strPortMode == "RawFile")
4933 port.portMode = PortMode_RawFile;
4934 else if (strPortMode == "HostPipe")
4935 port.portMode = PortMode_HostPipe;
4936 else if (strPortMode == "HostDevice")
4937 port.portMode = PortMode_HostDevice;
4938 else if (strPortMode == "Disconnected")
4939 port.portMode = PortMode_Disconnected;
4940 else if (strPortMode == "TCP")
4941 port.portMode = PortMode_TCP;
4942 else
4943 throw ConfigFileError(this, pelmPort, N_("Invalid value '%s' in UART/Port/@hostMode attribute"), strPortMode.c_str());
4944
4945 pelmPort->getAttributeValue("path", port.strPath);
4946 pelmPort->getAttributeValue("server", port.fServer);
4947
4948 Utf8Str strUartType;
4949 if (pelmPort->getAttributeValue("uartType", strUartType))
4950 {
4951 if (strUartType == "16450")
4952 port.uartType = UartType_U16450;
4953 else if (strUartType == "16550A")
4954 port.uartType = UartType_U16550A;
4955 else if (strUartType == "16750")
4956 port.uartType = UartType_U16750;
4957 else
4958 throw ConfigFileError(this, pelmPort, N_("Invalid value '%s' in UART/Port/@uartType attribute"), strUartType.c_str());
4959 }
4960
4961 ll.push_back(port);
4962 }
4963}
4964
4965/**
4966 * Called from MachineConfigFile::readHardware() to read parallel port information.
4967 * @param elmLPT
4968 * @param ll
4969 */
4970void MachineConfigFile::readParallelPorts(const xml::ElementNode &elmLPT,
4971 ParallelPortsList &ll)
4972{
4973 xml::NodesLoop nl1(elmLPT, "Port");
4974 const xml::ElementNode *pelmPort;
4975 while ((pelmPort = nl1.forAllNodes()))
4976 {
4977 ParallelPort port;
4978 if (!pelmPort->getAttributeValue("slot", port.ulSlot))
4979 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@slot attribute is missing"));
4980
4981 // slot must be unique
4982 for (ParallelPortsList::const_iterator it = ll.begin();
4983 it != ll.end();
4984 ++it)
4985 if ((*it).ulSlot == port.ulSlot)
4986 throw ConfigFileError(this, pelmPort, N_("Invalid value %RU32 in LPT/Port/@slot attribute: value is not unique"), port.ulSlot);
4987
4988 if (!pelmPort->getAttributeValue("enabled", port.fEnabled))
4989 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@enabled attribute is missing"));
4990 if (!pelmPort->getAttributeValue("IOBase", port.ulIOBase))
4991 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@IOBase attribute is missing"));
4992 if (!pelmPort->getAttributeValue("IRQ", port.ulIRQ))
4993 throw ConfigFileError(this, pelmPort, N_("Required LPT/Port/@IRQ attribute is missing"));
4994
4995 pelmPort->getAttributeValue("path", port.strPath);
4996
4997 ll.push_back(port);
4998 }
4999}
5000
5001/**
5002 * Called from MachineConfigFile::readHardware() to read audio adapter information
5003 * and maybe fix driver information depending on the current host hardware.
5004 *
5005 * @param elmAudioAdapter "AudioAdapter" XML element.
5006 * @param aa
5007 */
5008void MachineConfigFile::readAudioAdapter(const xml::ElementNode &elmAudioAdapter,
5009 AudioAdapter &aa)
5010{
5011 if (m->sv >= SettingsVersion_v1_15)
5012 {
5013 // get all properties
5014 xml::NodesLoop nl1(elmAudioAdapter, "Property");
5015 const xml::ElementNode *pelmModeChild;
5016 while ((pelmModeChild = nl1.forAllNodes()))
5017 {
5018 Utf8Str strPropName, strPropValue;
5019 if ( pelmModeChild->getAttributeValue("name", strPropName)
5020 && pelmModeChild->getAttributeValue("value", strPropValue) )
5021 aa.properties[strPropName] = strPropValue;
5022 else
5023 throw ConfigFileError(this, pelmModeChild, N_("Required AudioAdapter/Property/@name or @value attribute "
5024 "is missing"));
5025 }
5026 }
5027
5028 elmAudioAdapter.getAttributeValue("enabled", aa.fEnabled);
5029 elmAudioAdapter.getAttributeValue("enabledIn", aa.fEnabledIn);
5030 elmAudioAdapter.getAttributeValue("enabledOut", aa.fEnabledOut);
5031
5032 Utf8Str strTemp;
5033 if (elmAudioAdapter.getAttributeValue("controller", strTemp))
5034 {
5035 if (strTemp == "SB16")
5036 aa.controllerType = AudioControllerType_SB16;
5037 else if (strTemp == "AC97")
5038 aa.controllerType = AudioControllerType_AC97;
5039 else if (strTemp == "HDA")
5040 aa.controllerType = AudioControllerType_HDA;
5041 else if (strTemp == "Virtio-Sound")
5042 aa.controllerType = AudioControllerType_VirtioSound;
5043 else
5044 throw ConfigFileError(this, &elmAudioAdapter, N_("Invalid value '%s' in AudioAdapter/@controller attribute"), strTemp.c_str());
5045 }
5046
5047 if (elmAudioAdapter.getAttributeValue("codec", strTemp))
5048 {
5049 if (strTemp == "SB16")
5050 aa.codecType = AudioCodecType_SB16;
5051 else if (strTemp == "STAC9700")
5052 aa.codecType = AudioCodecType_STAC9700;
5053 else if (strTemp == "AD1980")
5054 aa.codecType = AudioCodecType_AD1980;
5055 else if (strTemp == "STAC9221")
5056 aa.codecType = AudioCodecType_STAC9221;
5057 else
5058 throw ConfigFileError(this, &elmAudioAdapter, N_("Invalid value '%s' in AudioAdapter/@codec attribute"), strTemp.c_str());
5059 }
5060 else
5061 {
5062 /* No codec attribute provided; use defaults. */
5063 switch (aa.controllerType)
5064 {
5065 case AudioControllerType_AC97:
5066 aa.codecType = AudioCodecType_STAC9700;
5067 break;
5068 case AudioControllerType_SB16:
5069 aa.codecType = AudioCodecType_SB16;
5070 break;
5071 case AudioControllerType_HDA:
5072 aa.codecType = AudioCodecType_STAC9221;
5073 break;
5074 case AudioControllerType_VirtioSound:
5075 aa.codecType = AudioCodecType_Null;
5076 break;
5077 default:
5078 Assert(false); /* We just checked the controller type above. */
5079 }
5080 }
5081
5082 if (elmAudioAdapter.getAttributeValue("driver", strTemp))
5083 {
5084 // settings before 1.3 used lower case so make sure this is case-insensitive
5085 strTemp.toUpper();
5086 if (strTemp == "DEFAULT") /* Keep this to be backwards compatible for settings < r152556. */
5087 aa.driverType = AudioDriverType_Default;
5088 else if (strTemp == "NULL")
5089 aa.driverType = AudioDriverType_Null;
5090 else if (strTemp == "WAS")
5091 aa.driverType = AudioDriverType_WAS;
5092 else if (strTemp == "WINMM")
5093 aa.driverType = AudioDriverType_WinMM;
5094 else if ( (strTemp == "DIRECTSOUND") || (strTemp == "DSOUND") )
5095 aa.driverType = AudioDriverType_DirectSound;
5096 else if (strTemp == "SOLAUDIO") /* Deprecated -- Solaris will use OSS by default now. */
5097 aa.driverType = AudioDriverType_SolAudio;
5098 else if (strTemp == "ALSA")
5099 aa.driverType = AudioDriverType_ALSA;
5100 else if (strTemp == "PULSE")
5101 aa.driverType = AudioDriverType_Pulse;
5102 else if (strTemp == "OSS")
5103 aa.driverType = AudioDriverType_OSS;
5104 else if (strTemp == "COREAUDIO")
5105 aa.driverType = AudioDriverType_CoreAudio;
5106 else if (strTemp == "MMPM") /* Deprecated; only kept for backwards compatibility. */
5107 aa.driverType = AudioDriverType_MMPM;
5108 else
5109 {
5110 /* Be nice when loading the settings on downgraded versions: In case the selected backend isn't available / known
5111 * to this version, fall back to the default backend, telling the user in the release log. See @bugref{10051c7}. */
5112 LogRel(("WARNING: Invalid value '%s' in AudioAdapter/@driver attribute found; falling back to default audio backend\n",
5113 strTemp.c_str()));
5114 aa.driverType = AudioDriverType_Default;
5115 }
5116
5117 /* When loading settings >= 1.19 (VBox 7.0), the attribute "useDefault" will determine if the VM should use
5118 * the OS' default audio driver or not. This additional attribute is necessary in order to be backwards compatible
5119 * with older VBox versions. */
5120 bool fUseDefault = false;
5121 if ( elmAudioAdapter.getAttributeValue("useDefault", &fUseDefault) /* Overrides "driver" above (if set). */
5122 && fUseDefault)
5123 aa.driverType = AudioDriverType_Default;
5124
5125 // now check if this is actually supported on the current host platform;
5126 // people might be opening a file created on a Windows host, and that
5127 // VM should still start on a Linux host
5128 if (!isAudioDriverAllowedOnThisHost(aa.driverType))
5129 aa.driverType = getHostDefaultAudioDriver();
5130 }
5131}
5132
5133/**
5134 * Called from MachineConfigFile::readHardware() to read guest property information.
5135 * @param elmGuestProperties
5136 * @param hw
5137 */
5138void MachineConfigFile::readGuestProperties(const xml::ElementNode &elmGuestProperties,
5139 Hardware &hw)
5140{
5141 xml::NodesLoop nl1(elmGuestProperties, "GuestProperty");
5142 const xml::ElementNode *pelmProp;
5143 while ((pelmProp = nl1.forAllNodes()))
5144 {
5145 GuestProperty prop;
5146
5147 pelmProp->getAttributeValue("name", prop.strName);
5148 pelmProp->getAttributeValue("value", prop.strValue);
5149
5150 pelmProp->getAttributeValue("timestamp", prop.timestamp);
5151 pelmProp->getAttributeValue("flags", prop.strFlags);
5152
5153 /* Check guest property 'name' and 'value' for correctness before
5154 * placing it to local cache. */
5155
5156 int vrc = GuestPropValidateName(prop.strName.c_str(), prop.strName.length() + 1 /* '\0' */);
5157 if (RT_FAILURE(vrc))
5158 {
5159 LogRel(("WARNING: Guest property with invalid name (%s) present in VM configuration file. Guest property will be dropped.\n",
5160 prop.strName.c_str()));
5161 continue;
5162 }
5163
5164 vrc = GuestPropValidateValue(prop.strValue.c_str(), prop.strValue.length() + 1 /* '\0' */);
5165 if (vrc == VERR_TOO_MUCH_DATA)
5166 {
5167 LogRel(("WARNING: Guest property '%s' present in VM configuration file and has too long value. Guest property value will be truncated.\n",
5168 prop.strName.c_str()));
5169
5170 /* In order to pass validation, guest property value length (including '\0') in bytes
5171 * should be less than GUEST_PROP_MAX_VALUE_LEN. Chop it down to an appropriate length. */
5172 prop.strValue.truncate(GUEST_PROP_MAX_VALUE_LEN - 1 /*terminator*/);
5173 }
5174 else if (RT_FAILURE(vrc))
5175 {
5176 LogRel(("WARNING: Guest property '%s' present in VM configuration file and has invalid value. Guest property will be dropped.\n",
5177 prop.strName.c_str()));
5178 continue;
5179 }
5180
5181 hw.llGuestProperties.push_back(prop);
5182 }
5183}
5184
5185/**
5186 * Helper function to read attributes that are common to \<SATAController\> (pre-1.7)
5187 * and \<StorageController\>.
5188 * @param elmStorageController
5189 * @param sctl
5190 */
5191void MachineConfigFile::readStorageControllerAttributes(const xml::ElementNode &elmStorageController,
5192 StorageController &sctl)
5193{
5194 elmStorageController.getAttributeValue("PortCount", sctl.ulPortCount);
5195 elmStorageController.getAttributeValue("useHostIOCache", sctl.fUseHostIOCache);
5196}
5197
5198/**
5199 * Reads the x86 CPUID tree.
5200 *
5201 * For settings >= v1.20 these were stored under the "Platform/x86/CPU" node.
5202 * For settings < v1.20 these were stored under the "Hardware/CPU" node.
5203 *
5204 * @param elmPlatformOrHardware Platform or Hardware node to read from.
5205 * @param platX86 Where to store the platform settings.
5206 */
5207void MachineConfigFile::readPlatformCPUIDTreeX86(const xml::ElementNode &elmPlatformOrHardware,
5208 PlatformX86 &platX86)
5209{
5210 const xml::ElementNode *pelmCPUChild;
5211 if ((pelmCPUChild = elmPlatformOrHardware.findChildElement("CpuIdTree")))
5212 readCpuIdTreeX86(*pelmCPUChild, platX86.llCpuIdLeafs);
5213}
5214
5215/**
5216 * Reads the x86 platform settings.
5217 *
5218 * For settings >= v1.20 these were stored under the "Platform/x86" node.
5219 * For settings < v1.20 these were stored under the "Hardware" node.
5220 *
5221 * @param elmPlatformX86OrHardware Platform/x86 or Hardware node to read from.
5222 * @param platX86 Where to store the x86 platform settings.
5223 */
5224void MachineConfigFile::readPlatformX86(const xml::ElementNode &elmPlatformX86OrHardware,
5225 PlatformX86 &platX86)
5226{
5227 xml::NodesLoop nl1(elmPlatformX86OrHardware);
5228
5229 const xml::ElementNode *pelChild;
5230 while ((pelChild = nl1.forAllNodes()))
5231 {
5232 if (pelChild->nameEquals("HPET"))
5233 {
5234 pelChild->getAttributeValue("enabled", platX86.fHPETEnabled);
5235 }
5236 else if (pelChild->nameEquals("CPU"))
5237 {
5238 const xml::ElementNode *pelmCPUChild;
5239 if ((pelmCPUChild = pelChild->findChildElement("HardwareVirtEx")))
5240 pelmCPUChild->getAttributeValue("enabled", platX86.fHWVirtEx);