VirtualBox

source: vbox/trunk/src/VBox/Main/src-client/ConsoleImplConfigCommon.cpp@ 101458

Last change on this file since 101458 was 101458, checked in by vboxsync, 15 months ago

Main/ConsoleImpl: Move the audio controller configuration out of the x86 config constructor into a separate method in order to be able to use it from the Armv8 variant later on, bugref:10528

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 166.1 KB
Line 
1/* $Id: ConsoleImplConfigCommon.cpp 101458 2023-10-17 08:09:12Z vboxsync $ */
2/** @file
3 * VBox Console COM Class implementation - VM Configuration Bits.
4 *
5 * @remark We've split out the code that the 64-bit VC++ v8 compiler finds
6 * problematic to optimize so we can disable optimizations and later,
7 * perhaps, find a real solution for it (like rewriting the code and
8 * to stop resemble a tonne of spaghetti).
9 */
10
11/*
12 * Copyright (C) 2006-2023 Oracle and/or its affiliates.
13 *
14 * This file is part of VirtualBox base platform packages, as
15 * available from https://www.virtualbox.org.
16 *
17 * This program is free software; you can redistribute it and/or
18 * modify it under the terms of the GNU General Public License
19 * as published by the Free Software Foundation, in version 3 of the
20 * License.
21 *
22 * This program is distributed in the hope that it will be useful, but
23 * WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
25 * General Public License for more details.
26 *
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, see <https://www.gnu.org/licenses>.
29 *
30 * SPDX-License-Identifier: GPL-3.0-only
31 */
32
33
34/*********************************************************************************************************************************
35* Header Files *
36*********************************************************************************************************************************/
37#define LOG_GROUP LOG_GROUP_MAIN_CONSOLE
38#include "LoggingNew.h"
39
40// VBoxNetCfg-win.h needs winsock2.h and thus MUST be included before any other
41// header file includes Windows.h.
42#if defined(RT_OS_WINDOWS) && defined(VBOX_WITH_NETFLT)
43# include <VBox/VBoxNetCfg-win.h>
44#endif
45
46#include "ConsoleImpl.h"
47#include "DisplayImpl.h"
48#include "NvramStoreImpl.h"
49#include "BusAssignmentManager.h"
50#ifdef VBOX_WITH_DRAG_AND_DROP
51# include "GuestImpl.h"
52# include "GuestDnDPrivate.h"
53#endif
54#include "VMMDev.h"
55#include "Global.h"
56#ifdef VBOX_WITH_PCI_PASSTHROUGH
57# include "PCIRawDevImpl.h"
58#endif
59
60// generated header
61#include "SchemaDefs.h"
62
63#include "AutoCaller.h"
64
65#include <iprt/base64.h>
66#include <iprt/buildconfig.h>
67#include <iprt/ctype.h>
68#include <iprt/dir.h>
69#include <iprt/file.h>
70#include <iprt/param.h>
71#include <iprt/path.h>
72#include <iprt/string.h>
73#include <iprt/system.h>
74#if 0 /* enable to play with lots of memory. */
75# include <iprt/env.h>
76#endif
77#include <iprt/stream.h>
78
79#include <iprt/http.h>
80#include <iprt/socket.h>
81#include <iprt/uri.h>
82
83#include <VBox/vmm/vmmr3vtable.h>
84#include <VBox/vmm/vmapi.h>
85#include <VBox/err.h>
86#include <VBox/param.h>
87#include <VBox/settings.h> /* For MachineConfigFile::getHostDefaultAudioDriver(). */
88#include <VBox/vmm/pdmapi.h> /* For PDMR3DriverAttach/PDMR3DriverDetach. */
89#include <VBox/vmm/pdmusb.h> /* For PDMR3UsbCreateEmulatedDevice. */
90#include <VBox/vmm/pdmdev.h> /* For PDMAPICMODE enum. */
91#include <VBox/vmm/pdmstorageifs.h>
92#include <VBox/version.h>
93#ifdef VBOX_WITH_SHARED_CLIPBOARD
94# include <VBox/HostServices/VBoxClipboardSvc.h>
95#endif
96#ifdef VBOX_WITH_GUEST_PROPS
97# include <VBox/HostServices/GuestPropertySvc.h>
98# include <VBox/com/defs.h>
99# include <VBox/com/array.h>
100# include <vector>
101#endif /* VBOX_WITH_GUEST_PROPS */
102#include <VBox/intnet.h>
103
104#include <VBox/com/com.h>
105#include <VBox/com/string.h>
106#include <VBox/com/array.h>
107
108#ifdef VBOX_WITH_NETFLT
109# if defined(RT_OS_SOLARIS)
110# include <zone.h>
111# elif defined(RT_OS_LINUX)
112# include <unistd.h>
113# include <sys/ioctl.h>
114# include <sys/socket.h>
115# include <linux/types.h>
116# include <linux/if.h>
117# elif defined(RT_OS_FREEBSD)
118# include <unistd.h>
119# include <sys/types.h>
120# include <sys/ioctl.h>
121# include <sys/socket.h>
122# include <net/if.h>
123# include <net80211/ieee80211_ioctl.h>
124# endif
125# if defined(RT_OS_WINDOWS)
126# include <iprt/win/ntddndis.h>
127# include <devguid.h>
128# else
129# include <HostNetworkInterfaceImpl.h>
130# include <netif.h>
131# include <stdlib.h>
132# endif
133#endif /* VBOX_WITH_NETFLT */
134
135#ifdef VBOX_WITH_AUDIO_VRDE
136# include "DrvAudioVRDE.h"
137#endif
138#ifdef VBOX_WITH_AUDIO_RECORDING
139# include "DrvAudioRec.h"
140#endif
141#include "NetworkServiceRunner.h"
142#ifdef VBOX_WITH_EXTPACK
143# include "ExtPackManagerImpl.h"
144#endif
145
146
147/*********************************************************************************************************************************
148* Internal Functions *
149*********************************************************************************************************************************/
150
151/* Darwin compile kludge */
152#undef PVM
153
154/**
155 * Helper that calls CFGMR3InsertString and throws an RTCError if that
156 * fails (C-string variant).
157 * @param pNode See CFGMR3InsertString.
158 * @param pcszName See CFGMR3InsertString.
159 * @param pcszValue The string value.
160 */
161void Console::InsertConfigString(PCFGMNODE pNode, const char *pcszName, const char *pcszValue)
162{
163 int vrc = mpVMM->pfnCFGMR3InsertString(pNode, pcszName, pcszValue);
164 if (RT_FAILURE(vrc))
165 throw ConfigError("CFGMR3InsertString", vrc, pcszName);
166}
167
168/**
169 * Helper that calls CFGMR3InsertString and throws an RTCError if that
170 * fails (Utf8Str variant).
171 * @param pNode See CFGMR3InsertStringN.
172 * @param pcszName See CFGMR3InsertStringN.
173 * @param rStrValue The string value.
174 */
175void Console::InsertConfigString(PCFGMNODE pNode, const char *pcszName, const Utf8Str &rStrValue)
176{
177 int vrc = mpVMM->pfnCFGMR3InsertStringN(pNode, pcszName, rStrValue.c_str(), rStrValue.length());
178 if (RT_FAILURE(vrc))
179 throw ConfigError("CFGMR3InsertStringLengthKnown", vrc, pcszName);
180}
181
182/**
183 * Helper that calls CFGMR3InsertString and throws an RTCError if that
184 * fails (Bstr variant).
185 *
186 * @param pNode See CFGMR3InsertStringN.
187 * @param pcszName See CFGMR3InsertStringN.
188 * @param rBstrValue The string value.
189 */
190void Console::InsertConfigString(PCFGMNODE pNode, const char *pcszName, const Bstr &rBstrValue)
191{
192 InsertConfigString(pNode, pcszName, Utf8Str(rBstrValue));
193}
194
195/**
196 * Helper that calls CFGMR3InsertStringFV and throws an RTCError if that fails.
197 * @param pNode See CFGMR3InsertStringF.
198 * @param pcszName See CFGMR3InsertStringF.
199 * @param pszFormat See CFGMR3InsertStringF.
200 * @param ... See CFGMR3InsertStringF.
201 */
202void Console::InsertConfigStringF(PCFGMNODE pNode, const char *pcszName, const char *pszFormat, ...)
203{
204 va_list va;
205 va_start(va, pszFormat);
206 int vrc = mpVMM->pfnCFGMR3InsertStringFV(pNode, pcszName, pszFormat, va);
207 va_end(va);
208 if (RT_FAILURE(vrc))
209 throw ConfigError("CFGMR3InsertStringFV", vrc, pcszName);
210}
211
212
213/**
214 * Helper that calls CFGMR3InsertPassword and throws an RTCError if that
215 * fails (Utf8Str variant).
216 * @param pNode See CFGMR3InsertPasswordN.
217 * @param pcszName See CFGMR3InsertPasswordN.
218 * @param rStrValue The string value.
219 */
220void Console::InsertConfigPassword(PCFGMNODE pNode, const char *pcszName, const Utf8Str &rStrValue)
221{
222 int vrc = mpVMM->pfnCFGMR3InsertPasswordN(pNode, pcszName, rStrValue.c_str(), rStrValue.length());
223 if (RT_FAILURE(vrc))
224 throw ConfigError("CFGMR3InsertPasswordLengthKnown", vrc, pcszName);
225}
226
227/**
228 * Helper that calls CFGMR3InsertBytes and throws an RTCError if that fails.
229 *
230 * @param pNode See CFGMR3InsertBytes.
231 * @param pcszName See CFGMR3InsertBytes.
232 * @param pvBytes See CFGMR3InsertBytes.
233 * @param cbBytes See CFGMR3InsertBytes.
234 */
235void Console::InsertConfigBytes(PCFGMNODE pNode, const char *pcszName, const void *pvBytes, size_t cbBytes)
236{
237 int vrc = mpVMM->pfnCFGMR3InsertBytes(pNode, pcszName, pvBytes, cbBytes);
238 if (RT_FAILURE(vrc))
239 throw ConfigError("CFGMR3InsertBytes", vrc, pcszName);
240}
241
242/**
243 * Helper that calls CFGMR3InsertInteger and throws an RTCError if that
244 * fails.
245 *
246 * @param pNode See CFGMR3InsertInteger.
247 * @param pcszName See CFGMR3InsertInteger.
248 * @param u64Integer See CFGMR3InsertInteger.
249 */
250void Console::InsertConfigInteger(PCFGMNODE pNode, const char *pcszName, uint64_t u64Integer)
251{
252 int vrc = mpVMM->pfnCFGMR3InsertInteger(pNode, pcszName, u64Integer);
253 if (RT_FAILURE(vrc))
254 throw ConfigError("CFGMR3InsertInteger", vrc, pcszName);
255}
256
257/**
258 * Helper that calls CFGMR3InsertNode and throws an RTCError if that fails.
259 *
260 * @param pNode See CFGMR3InsertNode.
261 * @param pcszName See CFGMR3InsertNode.
262 * @param ppChild See CFGMR3InsertNode.
263 */
264void Console::InsertConfigNode(PCFGMNODE pNode, const char *pcszName, PCFGMNODE *ppChild)
265{
266 int vrc = mpVMM->pfnCFGMR3InsertNode(pNode, pcszName, ppChild);
267 if (RT_FAILURE(vrc))
268 throw ConfigError("CFGMR3InsertNode", vrc, pcszName);
269}
270
271/**
272 * Helper that calls CFGMR3InsertNodeF and throws an RTCError if that fails.
273 *
274 * @param pNode See CFGMR3InsertNodeF.
275 * @param ppChild See CFGMR3InsertNodeF.
276 * @param pszNameFormat Name format string, see CFGMR3InsertNodeF.
277 * @param ... Format arguments.
278 */
279void Console::InsertConfigNodeF(PCFGMNODE pNode, PCFGMNODE *ppChild, const char *pszNameFormat, ...)
280{
281 va_list va;
282 va_start(va, pszNameFormat);
283 int vrc = mpVMM->pfnCFGMR3InsertNodeF(pNode, ppChild, "%N", pszNameFormat, &va);
284 va_end(va);
285 if (RT_FAILURE(vrc))
286 throw ConfigError("CFGMR3InsertNodeF", vrc, pszNameFormat);
287}
288
289/**
290 * Helper that calls CFGMR3RemoveValue and throws an RTCError if that fails.
291 *
292 * @param pNode See CFGMR3RemoveValue.
293 * @param pcszName See CFGMR3RemoveValue.
294 */
295void Console::RemoveConfigValue(PCFGMNODE pNode, const char *pcszName)
296{
297 int vrc = mpVMM->pfnCFGMR3RemoveValue(pNode, pcszName);
298 if (RT_FAILURE(vrc))
299 throw ConfigError("CFGMR3RemoveValue", vrc, pcszName);
300}
301
302/**
303 * Gets an extra data value, consulting both machine and global extra data.
304 *
305 * @throws HRESULT on failure
306 * @returns pStrValue for the callers convenience.
307 * @param pVirtualBox Pointer to the IVirtualBox interface.
308 * @param pMachine Pointer to the IMachine interface.
309 * @param pszName The value to get.
310 * @param pStrValue Where to return it's value (empty string if not
311 * found).
312 */
313DECL_HIDDEN_THROW(Utf8Str *) GetExtraDataBoth(IVirtualBox *pVirtualBox, IMachine *pMachine, const char *pszName, Utf8Str *pStrValue)
314{
315 pStrValue->setNull();
316
317 Bstr bstrName(pszName);
318 Bstr bstrValue;
319 HRESULT hrc = pMachine->GetExtraData(bstrName.raw(), bstrValue.asOutParam());
320 if (FAILED(hrc))
321 throw hrc;
322 if (bstrValue.isEmpty())
323 {
324 hrc = pVirtualBox->GetExtraData(bstrName.raw(), bstrValue.asOutParam());
325 if (FAILED(hrc))
326 throw hrc;
327 }
328
329 if (bstrValue.isNotEmpty())
330 *pStrValue = bstrValue;
331 return pStrValue;
332}
333
334
335/**
336 * Updates the device type for a LED.
337 *
338 * @param penmSubTypeEntry The sub-type entry to update.
339 * @param enmNewType The new type.
340 */
341void Console::i_setLedType(DeviceType_T *penmSubTypeEntry, DeviceType_T enmNewType)
342{
343 /*
344 * ASSUMES no race conditions here wrt concurrent type updating.
345 */
346 if (*penmSubTypeEntry != enmNewType)
347 {
348 *penmSubTypeEntry = enmNewType;
349 ASMAtomicIncU32(&muLedGen);
350 }
351}
352
353
354/**
355 * Allocate a set of LEDs.
356 *
357 * This grabs a maLedSets entry and populates it with @a cLeds.
358 *
359 * @returns Index into maLedSets.
360 * @param cLeds The number of LEDs in the set.
361 * @param fTypes Bitmask of DeviceType_T values, e.g.
362 * RT_BIT_32(DeviceType_Network).
363 * @param ppaSubTypes When not NULL, subtypes for each LED and return the
364 * array pointer here.
365 */
366uint32_t Console::i_allocateDriverLeds(uint32_t cLeds, uint32_t fTypes, DeviceType_T **ppaSubTypes)
367{
368 Assert(cLeds > 0);
369 Assert(cLeds < 1024); /* Adjust if any driver supports >=1024 units! */
370 Assert(!(fTypes & (RT_BIT_32(DeviceType_Null) | ~(RT_BIT_32(DeviceType_End) - 1))));
371
372 /* Preallocate the arrays we need, bunching them together. */
373 AssertCompile((unsigned)DeviceType_Null == 0);
374 PPDMLED volatile *papLeds = (PPDMLED volatile *)RTMemAllocZ( (sizeof(PPDMLED) + (ppaSubTypes ? sizeof(**ppaSubTypes) : 0))
375 * cLeds);
376 AssertStmt(papLeds, throw E_OUTOFMEMORY);
377
378 /* Take the LED lock in allocation mode and see if there are more LED set entries availalbe. */
379 {
380 AutoWriteLock alock(mLedLock COMMA_LOCKVAL_SRC_POS);
381 uint32_t const idxLedSet = mcLedSets;
382 if (idxLedSet < RT_ELEMENTS(maLedSets))
383 {
384 /* Initialize the set and return the index. */
385 PLEDSET pLS = &maLedSets[idxLedSet];
386 pLS->papLeds = papLeds;
387 pLS->cLeds = cLeds;
388 pLS->fTypes = fTypes;
389 if (ppaSubTypes)
390 *ppaSubTypes = pLS->paSubTypes = (DeviceType_T *)&papLeds[cLeds];
391 else
392 pLS->paSubTypes = NULL;
393
394 mcLedSets = idxLedSet + 1;
395 LogRel2(("return idxLedSet=%d (mcLedSets=%u out of max %zu)\n", idxLedSet, mcLedSets, RT_ELEMENTS(maLedSets)));
396 return idxLedSet;
397 }
398 }
399
400 RTMemFree((void *)papLeds);
401 AssertFailed();
402 throw ConfigError("AllocateDriverPapLeds", VERR_OUT_OF_RANGE, "Too many LED sets");
403}
404
405
406/**
407 * @throws ConfigError and std::bad_alloc.
408 */
409void Console::i_attachStatusDriver(PCFGMNODE pCtlInst, uint32_t fTypes, uint32_t cLeds, DeviceType_T **ppaSubTypes,
410 Console::MediumAttachmentMap *pmapMediumAttachments,
411 const char *pcszDevice, unsigned uInstance)
412{
413 PCFGMNODE pLunL0;
414 InsertConfigNode(pCtlInst, "LUN#999", &pLunL0);
415 InsertConfigString(pLunL0, "Driver", "MainStatus");
416 PCFGMNODE pCfg;
417 InsertConfigNode(pLunL0, "Config", &pCfg);
418 uint32_t const iLedSet = i_allocateDriverLeds(cLeds, fTypes, ppaSubTypes);
419 InsertConfigInteger(pCfg, "iLedSet", iLedSet);
420
421 InsertConfigInteger(pCfg, "HasMediumAttachments", pmapMediumAttachments != NULL);
422 if (pmapMediumAttachments)
423 {
424 AssertPtr(pcszDevice);
425 InsertConfigStringF(pCfg, "DeviceInstance", "%s/%u", pcszDevice, uInstance);
426 }
427 InsertConfigInteger(pCfg, "First", 0);
428 InsertConfigInteger(pCfg, "Last", cLeds - 1);
429}
430
431
432/**
433 * @throws ConfigError and std::bad_alloc.
434 */
435void Console::i_attachStatusDriver(PCFGMNODE pCtlInst, DeviceType_T enmType, uint32_t cLeds /*= 1*/)
436{
437 Assert(enmType > DeviceType_Null && enmType < DeviceType_End);
438 i_attachStatusDriver(pCtlInst, RT_BIT_32(enmType), cLeds, NULL, NULL, NULL, 0);
439}
440
441
442/**
443 * Construct the VM configuration tree (CFGM).
444 *
445 * This is a callback for VMR3Create() call. It is called from CFGMR3Init() in
446 * the emulation thread (EMT). Any per thread COM/XPCOM initialization is done
447 * here.
448 *
449 * @returns VBox status code.
450 * @param pUVM The user mode VM handle.
451 * @param pVM The cross context VM handle.
452 * @param pVMM The VMM ring-3 vtable.
453 * @param pvConsole Pointer to the VMPowerUpTask object.
454 *
455 * @note Locks the Console object for writing.
456 */
457/*static*/ DECLCALLBACK(int)
458Console::i_configConstructor(PUVM pUVM, PVM pVM, PCVMMR3VTABLE pVMM, void *pvConsole)
459{
460 LogFlowFuncEnter();
461
462 AssertReturn(pvConsole, VERR_INVALID_POINTER);
463 ComObjPtr<Console> pConsole = static_cast<Console *>(pvConsole);
464
465 AutoCaller autoCaller(pConsole);
466 AssertComRCReturn(autoCaller.hrc(), VERR_ACCESS_DENIED);
467
468 /* lock the console because we widely use internal fields and methods */
469 AutoWriteLock alock(pConsole COMMA_LOCKVAL_SRC_POS);
470
471 /*
472 * Set the VM handle and do the rest of the job in an worker method so we
473 * can easily reset the VM handle on failure.
474 */
475 pConsole->mpUVM = pUVM;
476 pVMM->pfnVMR3RetainUVM(pUVM);
477 int vrc;
478 try
479 {
480 vrc = pConsole->i_configConstructorInner(pUVM, pVM, pVMM, &alock);
481 }
482 catch (...)
483 {
484 vrc = VERR_UNEXPECTED_EXCEPTION;
485 }
486 if (RT_FAILURE(vrc))
487 {
488 pConsole->mpUVM = NULL;
489 pVMM->pfnVMR3ReleaseUVM(pUVM);
490 }
491
492 return vrc;
493}
494
495
496/**
497 * Worker for configConstructor.
498 *
499 * @return VBox status code.
500 * @return VERR_PLATFORM_ARCH_NOT_SUPPORTED if the machine's platform architecture is not supported.
501 * @param pUVM The user mode VM handle.
502 * @param pVM The cross context VM handle.
503 * @param pVMM The VMM vtable.
504 * @param pAlock The automatic lock instance. This is for when we have
505 * to leave it in order to avoid deadlocks (ext packs and
506 * more).
507 */
508int Console::i_configConstructorInner(PUVM pUVM, PVM pVM, PCVMMR3VTABLE pVMM, AutoWriteLock *pAlock)
509{
510 ComPtr<IMachine> const pMachine = i_machine();
511
512 ComPtr<IPlatform> pPlatform;
513 HRESULT hrc = pMachine->COMGETTER(Platform)(pPlatform.asOutParam());
514 AssertComRCReturn(hrc, VERR_COM_VM_ERROR);
515
516 PlatformArchitecture_T platformArch;
517 hrc = pPlatform->COMGETTER(Architecture)(&platformArch);
518 AssertComRCReturn(hrc, VERR_COM_VM_ERROR);
519
520 switch (platformArch)
521 {
522 case PlatformArchitecture_x86:
523 return i_configConstructorX86(pUVM, pVM, pVMM, pAlock);
524
525#ifdef VBOX_WITH_VIRT_ARMV8
526 case PlatformArchitecture_ARM:
527 return i_configConstructorArmV8(pUVM, pVM, pVMM, pAlock);
528#endif
529 default:
530 break;
531 }
532
533 return VERR_PLATFORM_ARCH_NOT_SUPPORTED;
534}
535
536
537/**
538 * Configures an audio driver via CFGM by getting (optional) values from extra data.
539 *
540 * @param pVirtualBox Pointer to IVirtualBox instance.
541 * @param pMachine Pointer to IMachine instance.
542 * @param pLUN Pointer to CFGM node of LUN (the driver) to configure.
543 * @param pszDrvName Name of the driver to configure.
544 * @param fAudioEnabledIn IAudioAdapter::enabledIn value.
545 * @param fAudioEnabledOut IAudioAdapter::enabledOut value.
546 *
547 * @throws ConfigError or HRESULT on if there is trouble.
548 */
549void Console::i_configAudioDriver(IVirtualBox *pVirtualBox, IMachine *pMachine, PCFGMNODE pLUN, const char *pszDrvName,
550 bool fAudioEnabledIn, bool fAudioEnabledOut)
551{
552#define H() AssertLogRelMsgStmt(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), \
553 throw ConfigError(__FUNCTION__, VERR_MAIN_CONFIG_CONSTRUCTOR_COM_ERROR, "line: " RT_XSTR(__LINE__)))
554
555 InsertConfigString(pLUN, "Driver", "AUDIO");
556
557 PCFGMNODE pCfg;
558 InsertConfigNode(pLUN, "Config", &pCfg);
559 InsertConfigString(pCfg, "DriverName", pszDrvName);
560 InsertConfigInteger(pCfg, "InputEnabled", fAudioEnabledIn);
561 InsertConfigInteger(pCfg, "OutputEnabled", fAudioEnabledOut);
562
563 Utf8Str strTmp;
564 GetExtraDataBoth(pVirtualBox, pMachine, "VBoxInternal2/Audio/Debug/Enabled", &strTmp);
565 const uint64_t fDebugEnabled = strTmp.equalsIgnoreCase("true") || strTmp.equalsIgnoreCase("1");
566 if (fDebugEnabled)
567 {
568 InsertConfigInteger(pCfg, "DebugEnabled", fDebugEnabled);
569
570 Utf8Str strDebugPathOut;
571 GetExtraDataBoth(pVirtualBox, pMachine, "VBoxInternal2/Audio/Debug/PathOut", &strDebugPathOut);
572 InsertConfigString(pCfg, "DebugPathOut", strDebugPathOut.c_str());
573 }
574
575 /*
576 * PCM input parameters (playback + recording).
577 * We have host driver specific ones as: VBoxInternal2/Audio/<DrvName>/<Value>
578 * And global ones for all host drivers: VBoxInternal2/Audio/<Value>
579 */
580 for (unsigned iDir = 0; iDir < 2; iDir++)
581 {
582 static const struct
583 {
584 const char *pszExtraName;
585 const char *pszCfgmName;
586 } s_aToCopy[] =
587 { /* PCM parameters: */
588 { "PCMSampleBit", "PCMSampleBit" },
589 { "PCMSampleHz", "PCMSampleHz" },
590 { "PCMSampleSigned", "PCMSampleSigned" },
591 { "PCMSampleSwapEndian", "PCMSampleSwapEndian" },
592 { "PCMSampleChannels", "PCMSampleChannels" },
593 /* Buffering stuff: */
594 { "PeriodSizeMs", "PeriodSizeMs" },
595 { "BufferSizeMs", "BufferSizeMs" },
596 { "PreBufferSizeMs", "PreBufferSizeMs" },
597 };
598
599 PCFGMNODE pDirNode = NULL;
600 const char *pszDir = iDir == 0 ? "In" : "Out";
601 for (size_t i = 0; i < RT_ELEMENTS(s_aToCopy); i++)
602 {
603 char szExtra[128];
604 RTStrPrintf(szExtra, sizeof(szExtra), "VBoxInternal2/Audio/%s/%s%s", pszDrvName, s_aToCopy[i].pszExtraName, pszDir);
605 GetExtraDataBoth(pVirtualBox, pMachine, szExtra, &strTmp); /* throws hrc */
606 if (strTmp.isEmpty())
607 {
608 RTStrPrintf(szExtra, sizeof(szExtra), "VBoxInternal2/Audio/%s%s", s_aToCopy[i].pszExtraName, pszDir);
609 GetExtraDataBoth(pVirtualBox, pMachine, szExtra, &strTmp);
610 if (strTmp.isEmpty())
611 continue;
612 }
613
614 uint32_t uValue;
615 int vrc = RTStrToUInt32Full(strTmp.c_str(), 0, &uValue);
616 if (RT_SUCCESS(vrc))
617 {
618 if (!pDirNode)
619 InsertConfigNode(pCfg, pszDir, &pDirNode);
620 InsertConfigInteger(pDirNode, s_aToCopy[i].pszCfgmName, uValue);
621 }
622 else
623 LogRel(("Ignoring malformed 32-bit unsigned integer config value '%s' = '%s': %Rrc\n", szExtra, strTmp.c_str(), vrc));
624 }
625 }
626
627 PCFGMNODE pLunL1;
628 InsertConfigNode(pLUN, "AttachedDriver", &pLunL1);
629 InsertConfigString(pLunL1, "Driver", pszDrvName);
630 InsertConfigNode(pLunL1, "Config", &pCfg);
631
632#ifdef RT_OS_WINDOWS
633 if (strcmp(pszDrvName, "HostAudioWas") == 0)
634 {
635 Bstr bstrTmp;
636 HRESULT hrc = pMachine->COMGETTER(Id)(bstrTmp.asOutParam()); H();
637 InsertConfigString(pCfg, "VmUuid", bstrTmp);
638 }
639#endif
640
641#if defined(RT_OS_WINDOWS) || defined(RT_OS_LINUX)
642 if ( strcmp(pszDrvName, "HostAudioWas") == 0
643 || strcmp(pszDrvName, "PulseAudio") == 0)
644 {
645 Bstr bstrTmp;
646 HRESULT hrc = pMachine->COMGETTER(Name)(bstrTmp.asOutParam()); H();
647 InsertConfigString(pCfg, "VmName", bstrTmp);
648 }
649#endif
650
651 LogFlowFunc(("szDrivName=%s\n", pszDrvName));
652
653#undef H
654}
655
656/**
657 * Applies the CFGM overlay as specified by VBoxInternal/XXX extra data
658 * values.
659 *
660 * @returns VBox status code.
661 * @param pRoot The root of the configuration tree.
662 * @param pVirtualBox Pointer to the IVirtualBox interface.
663 * @param pMachine Pointer to the IMachine interface.
664 */
665/* static */
666int Console::i_configCfgmOverlay(PCFGMNODE pRoot, IVirtualBox *pVirtualBox, IMachine *pMachine)
667{
668 /*
669 * CFGM overlay handling.
670 *
671 * Here we check the extra data entries for CFGM values
672 * and create the nodes and insert the values on the fly. Existing
673 * values will be removed and reinserted. CFGM is typed, so by default
674 * we will guess whether it's a string or an integer (byte arrays are
675 * not currently supported). It's possible to override this autodetection
676 * by adding "string:", "integer:" or "bytes:" (future).
677 *
678 * We first perform a run on global extra data, then on the machine
679 * extra data to support global settings with local overrides.
680 */
681 int vrc = VINF_SUCCESS;
682 bool fFirst = true;
683 try
684 {
685 /** @todo add support for removing nodes and byte blobs. */
686 /*
687 * Get the next key
688 */
689 SafeArray<BSTR> aGlobalExtraDataKeys;
690 SafeArray<BSTR> aMachineExtraDataKeys;
691 HRESULT hrc = pVirtualBox->GetExtraDataKeys(ComSafeArrayAsOutParam(aGlobalExtraDataKeys));
692 AssertMsg(SUCCEEDED(hrc), ("VirtualBox::GetExtraDataKeys failed with %Rhrc\n", hrc));
693
694 // remember the no. of global values so we can call the correct method below
695 size_t cGlobalValues = aGlobalExtraDataKeys.size();
696
697 hrc = pMachine->GetExtraDataKeys(ComSafeArrayAsOutParam(aMachineExtraDataKeys));
698 AssertMsg(SUCCEEDED(hrc), ("Machine::GetExtraDataKeys failed with %Rhrc\n", hrc));
699
700 // build a combined list from global keys...
701 std::list<Utf8Str> llExtraDataKeys;
702
703 for (size_t i = 0; i < aGlobalExtraDataKeys.size(); ++i)
704 llExtraDataKeys.push_back(Utf8Str(aGlobalExtraDataKeys[i]));
705 // ... and machine keys
706 for (size_t i = 0; i < aMachineExtraDataKeys.size(); ++i)
707 llExtraDataKeys.push_back(Utf8Str(aMachineExtraDataKeys[i]));
708
709 size_t i2 = 0;
710 for (std::list<Utf8Str>::const_iterator it = llExtraDataKeys.begin();
711 it != llExtraDataKeys.end();
712 ++it, ++i2)
713 {
714 const Utf8Str &strKey = *it;
715
716 /*
717 * We only care about keys starting with "VBoxInternal/" (skip "G:" or "M:")
718 */
719 if (!strKey.startsWith("VBoxInternal/"))
720 continue;
721
722 const char *pszExtraDataKey = strKey.c_str() + sizeof("VBoxInternal/") - 1;
723
724 // get the value
725 Bstr bstrExtraDataValue;
726 if (i2 < cGlobalValues)
727 // this is still one of the global values:
728 hrc = pVirtualBox->GetExtraData(Bstr(strKey).raw(), bstrExtraDataValue.asOutParam());
729 else
730 hrc = pMachine->GetExtraData(Bstr(strKey).raw(), bstrExtraDataValue.asOutParam());
731 if (FAILED(hrc))
732 LogRel(("Warning: Cannot get extra data key %s, hrc = %Rhrc\n", strKey.c_str(), hrc));
733
734 if (fFirst)
735 {
736 fFirst = false;
737 LogRel(("Extradata overrides:\n"));
738 }
739 LogRel((" %s=\"%ls\"%s\n", strKey.c_str(), bstrExtraDataValue.raw(), i2 < cGlobalValues ? " (global)" : ""));
740
741 /*
742 * The key will be in the format "Node1/Node2/Value" or simply "Value".
743 * Split the two and get the node, delete the value and create the node
744 * if necessary.
745 */
746 PCFGMNODE pNode;
747 const char *pszCFGMValueName = strrchr(pszExtraDataKey, '/');
748 if (pszCFGMValueName)
749 {
750 /* terminate the node and advance to the value (Utf8Str might not
751 offically like this but wtf) */
752 *(char *)pszCFGMValueName = '\0';
753 ++pszCFGMValueName;
754
755 /* does the node already exist? */
756 pNode = mpVMM->pfnCFGMR3GetChild(pRoot, pszExtraDataKey);
757 if (pNode)
758 mpVMM->pfnCFGMR3RemoveValue(pNode, pszCFGMValueName);
759 else
760 {
761 /* create the node */
762 vrc = mpVMM->pfnCFGMR3InsertNode(pRoot, pszExtraDataKey, &pNode);
763 if (RT_FAILURE(vrc))
764 {
765 AssertLogRelMsgRC(vrc, ("failed to insert node '%s'\n", pszExtraDataKey));
766 continue;
767 }
768 Assert(pNode);
769 }
770 }
771 else
772 {
773 /* root value (no node path). */
774 pNode = pRoot;
775 pszCFGMValueName = pszExtraDataKey;
776 pszExtraDataKey--;
777 mpVMM->pfnCFGMR3RemoveValue(pNode, pszCFGMValueName);
778 }
779
780 /*
781 * Now let's have a look at the value.
782 * Empty strings means that we should remove the value, which we've
783 * already done above.
784 */
785 Utf8Str strCFGMValueUtf8(bstrExtraDataValue);
786 if (strCFGMValueUtf8.isNotEmpty())
787 {
788 uint64_t u64Value;
789
790 /* check for type prefix first. */
791 if (!strncmp(strCFGMValueUtf8.c_str(), RT_STR_TUPLE("string:")))
792 vrc = mpVMM->pfnCFGMR3InsertString(pNode, pszCFGMValueName, strCFGMValueUtf8.c_str() + sizeof("string:") - 1);
793 else if (!strncmp(strCFGMValueUtf8.c_str(), RT_STR_TUPLE("integer:")))
794 {
795 vrc = RTStrToUInt64Full(strCFGMValueUtf8.c_str() + sizeof("integer:") - 1, 0, &u64Value);
796 if (RT_SUCCESS(vrc))
797 vrc = mpVMM->pfnCFGMR3InsertInteger(pNode, pszCFGMValueName, u64Value);
798 }
799 else if (!strncmp(strCFGMValueUtf8.c_str(), RT_STR_TUPLE("bytes:")))
800 {
801 char const *pszBase64 = strCFGMValueUtf8.c_str() + sizeof("bytes:") - 1;
802 ssize_t cbValue = RTBase64DecodedSize(pszBase64, NULL);
803 if (cbValue > 0)
804 {
805 void *pvBytes = RTMemTmpAlloc(cbValue);
806 if (pvBytes)
807 {
808 vrc = RTBase64Decode(pszBase64, pvBytes, cbValue, NULL, NULL);
809 if (RT_SUCCESS(vrc))
810 vrc = mpVMM->pfnCFGMR3InsertBytes(pNode, pszCFGMValueName, pvBytes, cbValue);
811 RTMemTmpFree(pvBytes);
812 }
813 else
814 vrc = VERR_NO_TMP_MEMORY;
815 }
816 else if (cbValue == 0)
817 vrc = mpVMM->pfnCFGMR3InsertBytes(pNode, pszCFGMValueName, NULL, 0);
818 else
819 vrc = VERR_INVALID_BASE64_ENCODING;
820 }
821 /* auto detect type. */
822 else if (RT_SUCCESS(RTStrToUInt64Full(strCFGMValueUtf8.c_str(), 0, &u64Value)))
823 vrc = mpVMM->pfnCFGMR3InsertInteger(pNode, pszCFGMValueName, u64Value);
824 else
825 vrc = mpVMM->pfnCFGMR3InsertString(pNode, pszCFGMValueName, strCFGMValueUtf8.c_str());
826 AssertLogRelMsgRCBreak(vrc, ("failed to insert CFGM value '%s' to key '%s'\n",
827 strCFGMValueUtf8.c_str(), pszExtraDataKey));
828 }
829 }
830 }
831 catch (ConfigError &x)
832 {
833 // InsertConfig threw something:
834 return x.m_vrc;
835 }
836 return vrc;
837}
838
839/**
840 * Dumps the API settings tweaks as specified by VBoxInternal2/XXX extra data
841 * values.
842 *
843 * @returns VBox status code.
844 * @param pVirtualBox Pointer to the IVirtualBox interface.
845 * @param pMachine Pointer to the IMachine interface.
846 */
847/* static */
848int Console::i_configDumpAPISettingsTweaks(IVirtualBox *pVirtualBox, IMachine *pMachine)
849{
850 {
851 SafeArray<BSTR> aGlobalExtraDataKeys;
852 HRESULT hrc = pVirtualBox->GetExtraDataKeys(ComSafeArrayAsOutParam(aGlobalExtraDataKeys));
853 AssertMsg(SUCCEEDED(hrc), ("VirtualBox::GetExtraDataKeys failed with %Rhrc\n", hrc));
854 bool hasKey = false;
855 for (size_t i = 0; i < aGlobalExtraDataKeys.size(); i++)
856 {
857 Utf8Str strKey(aGlobalExtraDataKeys[i]);
858 if (!strKey.startsWith("VBoxInternal2/"))
859 continue;
860
861 Bstr bstrValue;
862 hrc = pVirtualBox->GetExtraData(Bstr(strKey).raw(),
863 bstrValue.asOutParam());
864 if (FAILED(hrc))
865 continue;
866 if (!hasKey)
867 LogRel(("Global extradata API settings:\n"));
868 LogRel((" %s=\"%ls\"\n", strKey.c_str(), bstrValue.raw()));
869 hasKey = true;
870 }
871 }
872
873 {
874 SafeArray<BSTR> aMachineExtraDataKeys;
875 HRESULT hrc = pMachine->GetExtraDataKeys(ComSafeArrayAsOutParam(aMachineExtraDataKeys));
876 AssertMsg(SUCCEEDED(hrc), ("Machine::GetExtraDataKeys failed with %Rhrc\n", hrc));
877 bool hasKey = false;
878 for (size_t i = 0; i < aMachineExtraDataKeys.size(); i++)
879 {
880 Utf8Str strKey(aMachineExtraDataKeys[i]);
881 if (!strKey.startsWith("VBoxInternal2/"))
882 continue;
883
884 Bstr bstrValue;
885 hrc = pMachine->GetExtraData(Bstr(strKey).raw(),
886 bstrValue.asOutParam());
887 if (FAILED(hrc))
888 continue;
889 if (!hasKey)
890 LogRel(("Per-VM extradata API settings:\n"));
891 LogRel((" %s=\"%ls\"\n", strKey.c_str(), bstrValue.raw()));
892 hasKey = true;
893 }
894 }
895
896 return VINF_SUCCESS;
897}
898
899
900/**
901 * Ellipsis to va_list wrapper for calling setVMRuntimeErrorCallback.
902 */
903void Console::i_atVMRuntimeErrorCallbackF(uint32_t fFlags, const char *pszErrorId, const char *pszFormat, ...)
904{
905 va_list va;
906 va_start(va, pszFormat);
907 i_atVMRuntimeErrorCallback(NULL, this, fFlags, pszErrorId, pszFormat, va);
908 va_end(va);
909}
910
911/* XXX introduce RT format specifier */
912static uint64_t formatDiskSize(uint64_t u64Size, const char **pszUnit)
913{
914 if (u64Size > INT64_C(5000)*_1G)
915 {
916 *pszUnit = "TB";
917 return u64Size / _1T;
918 }
919 else if (u64Size > INT64_C(5000)*_1M)
920 {
921 *pszUnit = "GB";
922 return u64Size / _1G;
923 }
924 else
925 {
926 *pszUnit = "MB";
927 return u64Size / _1M;
928 }
929}
930
931/**
932 * Checks the location of the given medium for known bugs affecting the usage
933 * of the host I/O cache setting.
934 *
935 * @returns VBox status code.
936 * @param pMedium The medium to check.
937 * @param pfUseHostIOCache Where to store the suggested host I/O cache setting.
938 */
939int Console::i_checkMediumLocation(IMedium *pMedium, bool *pfUseHostIOCache)
940{
941#define H() AssertLogRelMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_MAIN_CONFIG_CONSTRUCTOR_COM_ERROR)
942 /*
943 * Some sanity checks.
944 */
945 RT_NOREF(pfUseHostIOCache);
946 ComPtr<IMediumFormat> pMediumFormat;
947 HRESULT hrc = pMedium->COMGETTER(MediumFormat)(pMediumFormat.asOutParam()); H();
948 ULONG uCaps = 0;
949 com::SafeArray <MediumFormatCapabilities_T> mediumFormatCap;
950 hrc = pMediumFormat->COMGETTER(Capabilities)(ComSafeArrayAsOutParam(mediumFormatCap)); H();
951
952 for (ULONG j = 0; j < mediumFormatCap.size(); j++)
953 uCaps |= mediumFormatCap[j];
954
955 if (uCaps & MediumFormatCapabilities_File)
956 {
957 Bstr bstrFile;
958 hrc = pMedium->COMGETTER(Location)(bstrFile.asOutParam()); H();
959 Utf8Str const strFile(bstrFile);
960
961 Bstr bstrSnap;
962 ComPtr<IMachine> pMachine = i_machine();
963 hrc = pMachine->COMGETTER(SnapshotFolder)(bstrSnap.asOutParam()); H();
964 Utf8Str const strSnap(bstrSnap);
965
966 RTFSTYPE enmFsTypeFile = RTFSTYPE_UNKNOWN;
967 int vrc2 = RTFsQueryType(strFile.c_str(), &enmFsTypeFile);
968 AssertMsgRCReturn(vrc2, ("Querying the file type of '%s' failed!\n", strFile.c_str()), vrc2);
969
970 /* Any VM which hasn't created a snapshot or saved the current state of the VM
971 * won't have a Snapshot folder yet so no need to log anything about the file system
972 * type of the non-existent directory in such cases. */
973 RTFSTYPE enmFsTypeSnap = RTFSTYPE_UNKNOWN;
974 vrc2 = RTFsQueryType(strSnap.c_str(), &enmFsTypeSnap);
975 if (RT_SUCCESS(vrc2) && !mfSnapshotFolderDiskTypeShown)
976 {
977 LogRel(("File system of '%s' (snapshots) is %s\n", strSnap.c_str(), RTFsTypeName(enmFsTypeSnap)));
978 mfSnapshotFolderDiskTypeShown = true;
979 }
980 LogRel(("File system of '%s' is %s\n", strFile.c_str(), RTFsTypeName(enmFsTypeFile)));
981 LONG64 i64Size;
982 hrc = pMedium->COMGETTER(LogicalSize)(&i64Size); H();
983#ifdef RT_OS_WINDOWS
984 if ( enmFsTypeFile == RTFSTYPE_FAT
985 && i64Size >= _4G)
986 {
987 const char *pszUnit;
988 uint64_t u64Print = formatDiskSize((uint64_t)i64Size, &pszUnit);
989 i_atVMRuntimeErrorCallbackF(0, "FatPartitionDetected",
990 N_("The medium '%s' has a logical size of %RU64%s "
991 "but the file system the medium is located on seems "
992 "to be FAT(32) which cannot handle files bigger than 4GB.\n"
993 "We strongly recommend to put all your virtual disk images and "
994 "the snapshot folder onto an NTFS partition"),
995 strFile.c_str(), u64Print, pszUnit);
996 }
997#else /* !RT_OS_WINDOWS */
998 if ( enmFsTypeFile == RTFSTYPE_FAT
999 || enmFsTypeFile == RTFSTYPE_EXT
1000 || enmFsTypeFile == RTFSTYPE_EXT2
1001 || enmFsTypeFile == RTFSTYPE_EXT3
1002 || enmFsTypeFile == RTFSTYPE_EXT4)
1003 {
1004 RTFILE file;
1005 int vrc = RTFileOpen(&file, strFile.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
1006 if (RT_SUCCESS(vrc))
1007 {
1008 RTFOFF maxSize;
1009 /* Careful: This function will work only on selected local file systems! */
1010 vrc = RTFileQueryMaxSizeEx(file, &maxSize);
1011 RTFileClose(file);
1012 if ( RT_SUCCESS(vrc)
1013 && maxSize > 0
1014 && i64Size > (LONG64)maxSize)
1015 {
1016 const char *pszUnitSiz;
1017 const char *pszUnitMax;
1018 uint64_t u64PrintSiz = formatDiskSize((LONG64)i64Size, &pszUnitSiz);
1019 uint64_t u64PrintMax = formatDiskSize(maxSize, &pszUnitMax);
1020 i_atVMRuntimeErrorCallbackF(0, "FatPartitionDetected", /* <= not exact but ... */
1021 N_("The medium '%s' has a logical size of %RU64%s "
1022 "but the file system the medium is located on can "
1023 "only handle files up to %RU64%s in theory.\n"
1024 "We strongly recommend to put all your virtual disk "
1025 "images and the snapshot folder onto a proper "
1026 "file system (e.g. ext3) with a sufficient size"),
1027 strFile.c_str(), u64PrintSiz, pszUnitSiz, u64PrintMax, pszUnitMax);
1028 }
1029 }
1030 }
1031#endif /* !RT_OS_WINDOWS */
1032
1033 /*
1034 * Snapshot folder:
1035 * Here we test only for a FAT partition as we had to create a dummy file otherwise
1036 */
1037 if ( enmFsTypeSnap == RTFSTYPE_FAT
1038 && i64Size >= _4G
1039 && !mfSnapshotFolderSizeWarningShown)
1040 {
1041 const char *pszUnit;
1042 uint64_t u64Print = formatDiskSize(i64Size, &pszUnit);
1043 i_atVMRuntimeErrorCallbackF(0, "FatPartitionDetected",
1044#ifdef RT_OS_WINDOWS
1045 N_("The snapshot folder of this VM '%s' seems to be located on "
1046 "a FAT(32) file system. The logical size of the medium '%s' "
1047 "(%RU64%s) is bigger than the maximum file size this file "
1048 "system can handle (4GB).\n"
1049 "We strongly recommend to put all your virtual disk images and "
1050 "the snapshot folder onto an NTFS partition"),
1051#else
1052 N_("The snapshot folder of this VM '%s' seems to be located on "
1053 "a FAT(32) file system. The logical size of the medium '%s' "
1054 "(%RU64%s) is bigger than the maximum file size this file "
1055 "system can handle (4GB).\n"
1056 "We strongly recommend to put all your virtual disk images and "
1057 "the snapshot folder onto a proper file system (e.g. ext3)"),
1058#endif
1059 strSnap.c_str(), strFile.c_str(), u64Print, pszUnit);
1060 /* Show this particular warning only once */
1061 mfSnapshotFolderSizeWarningShown = true;
1062 }
1063
1064#ifdef RT_OS_LINUX
1065 /*
1066 * Ext4 bug: Check if the host I/O cache is disabled and the disk image is located
1067 * on an ext4 partition.
1068 * This bug apparently applies to the XFS file system as well.
1069 * Linux 2.6.36 is known to be fixed (tested with 2.6.36-rc4).
1070 */
1071
1072 char szOsRelease[128];
1073 int vrc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szOsRelease, sizeof(szOsRelease));
1074 bool fKernelHasODirectBug = RT_FAILURE(vrc)
1075 || (RTStrVersionCompare(szOsRelease, "2.6.36-rc4") < 0);
1076
1077 if ( (uCaps & MediumFormatCapabilities_Asynchronous)
1078 && !*pfUseHostIOCache
1079 && fKernelHasODirectBug)
1080 {
1081 if ( enmFsTypeFile == RTFSTYPE_EXT4
1082 || enmFsTypeFile == RTFSTYPE_XFS)
1083 {
1084 i_atVMRuntimeErrorCallbackF(0, "Ext4PartitionDetected",
1085 N_("The host I/O cache for at least one controller is disabled "
1086 "and the medium '%s' for this VM "
1087 "is located on an %s partition. There is a known Linux "
1088 "kernel bug which can lead to the corruption of the virtual "
1089 "disk image under these conditions.\n"
1090 "Either enable the host I/O cache permanently in the VM "
1091 "settings or put the disk image and the snapshot folder "
1092 "onto a different file system.\n"
1093 "The host I/O cache will now be enabled for this medium"),
1094 strFile.c_str(), enmFsTypeFile == RTFSTYPE_EXT4 ? "ext4" : "xfs");
1095 *pfUseHostIOCache = true;
1096 }
1097 else if ( ( enmFsTypeSnap == RTFSTYPE_EXT4
1098 || enmFsTypeSnap == RTFSTYPE_XFS)
1099 && !mfSnapshotFolderExt4WarningShown)
1100 {
1101 i_atVMRuntimeErrorCallbackF(0, "Ext4PartitionDetected",
1102 N_("The host I/O cache for at least one controller is disabled "
1103 "and the snapshot folder for this VM "
1104 "is located on an %s partition. There is a known Linux "
1105 "kernel bug which can lead to the corruption of the virtual "
1106 "disk image under these conditions.\n"
1107 "Either enable the host I/O cache permanently in the VM "
1108 "settings or put the disk image and the snapshot folder "
1109 "onto a different file system.\n"
1110 "The host I/O cache will now be enabled for this medium"),
1111 enmFsTypeSnap == RTFSTYPE_EXT4 ? "ext4" : "xfs");
1112 *pfUseHostIOCache = true;
1113 mfSnapshotFolderExt4WarningShown = true;
1114 }
1115 }
1116
1117 /*
1118 * 2.6.18 bug: Check if the host I/O cache is disabled and the host is running
1119 * Linux 2.6.18. See @bugref{8690}. Apparently the same problem as
1120 * documented in https://lkml.org/lkml/2007/2/1/14. We saw such
1121 * kernel oopses on Linux 2.6.18-416.el5. We don't know when this
1122 * was fixed but we _know_ that 2.6.18 EL5 kernels are affected.
1123 */
1124 bool fKernelAsyncUnreliable = RT_FAILURE(vrc)
1125 || (RTStrVersionCompare(szOsRelease, "2.6.19") < 0);
1126 if ( (uCaps & MediumFormatCapabilities_Asynchronous)
1127 && !*pfUseHostIOCache
1128 && fKernelAsyncUnreliable)
1129 {
1130 i_atVMRuntimeErrorCallbackF(0, "Linux2618TooOld",
1131 N_("The host I/O cache for at least one controller is disabled. "
1132 "There is a known Linux kernel bug which can lead to kernel "
1133 "oopses under heavy load. To our knowledge this bug affects "
1134 "all 2.6.18 kernels.\n"
1135 "Either enable the host I/O cache permanently in the VM "
1136 "settings or switch to a newer host kernel.\n"
1137 "The host I/O cache will now be enabled for this medium"));
1138 *pfUseHostIOCache = true;
1139 }
1140#endif
1141 }
1142#undef H
1143
1144 return VINF_SUCCESS;
1145}
1146
1147/**
1148 * Unmounts the specified medium from the specified device.
1149 *
1150 * @returns VBox status code.
1151 * @param pUVM The usermode VM handle.
1152 * @param pVMM The VMM vtable.
1153 * @param enmBus The storage bus.
1154 * @param enmDevType The device type.
1155 * @param pcszDevice The device emulation.
1156 * @param uInstance Instance of the device.
1157 * @param uLUN The LUN on the device.
1158 * @param fForceUnmount Whether to force unmounting.
1159 */
1160int Console::i_unmountMediumFromGuest(PUVM pUVM, PCVMMR3VTABLE pVMM, StorageBus_T enmBus, DeviceType_T enmDevType,
1161 const char *pcszDevice, unsigned uInstance, unsigned uLUN,
1162 bool fForceUnmount) RT_NOEXCEPT
1163{
1164 /* Unmount existing media only for floppy and DVD drives. */
1165 int vrc = VINF_SUCCESS;
1166 PPDMIBASE pBase;
1167 if (enmBus == StorageBus_USB)
1168 vrc = pVMM->pfnPDMR3UsbQueryDriverOnLun(pUVM, pcszDevice, uInstance, uLUN, "SCSI", &pBase);
1169 else if ( (enmBus == StorageBus_SAS || enmBus == StorageBus_SCSI || enmBus == StorageBus_VirtioSCSI)
1170 || (enmBus == StorageBus_SATA && enmDevType == DeviceType_DVD))
1171 vrc = pVMM->pfnPDMR3QueryDriverOnLun(pUVM, pcszDevice, uInstance, uLUN, "SCSI", &pBase);
1172 else /* IDE or Floppy */
1173 vrc = pVMM->pfnPDMR3QueryLun(pUVM, pcszDevice, uInstance, uLUN, &pBase);
1174
1175 if (RT_FAILURE(vrc))
1176 {
1177 if (vrc == VERR_PDM_LUN_NOT_FOUND || vrc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
1178 vrc = VINF_SUCCESS;
1179 AssertRC(vrc);
1180 }
1181 else
1182 {
1183 PPDMIMOUNT pIMount = PDMIBASE_QUERY_INTERFACE(pBase, PDMIMOUNT);
1184 AssertReturn(pIMount, VERR_INVALID_POINTER);
1185
1186 /* Unmount the media (but do not eject the medium!) */
1187 vrc = pIMount->pfnUnmount(pIMount, fForceUnmount, false /*=fEject*/);
1188 if (vrc == VERR_PDM_MEDIA_NOT_MOUNTED)
1189 vrc = VINF_SUCCESS;
1190 /* for example if the medium is locked */
1191 else if (RT_FAILURE(vrc))
1192 return vrc;
1193 }
1194
1195 return vrc;
1196}
1197
1198/**
1199 * Removes the currently attached medium driver form the specified device
1200 * taking care of the controlelr specific configs wrt. to the attached driver chain.
1201 *
1202 * @returns VBox status code.
1203 * @param pCtlInst The controler instance node in the CFGM tree.
1204 * @param pcszDevice The device name.
1205 * @param uInstance The device instance.
1206 * @param uLUN The device LUN.
1207 * @param enmBus The storage bus.
1208 * @param fAttachDetach Flag whether this is a change while the VM is running
1209 * @param fHotplug Flag whether the guest should be notified about the device change.
1210 * @param fForceUnmount Flag whether to force unmounting the medium even if it is locked.
1211 * @param pUVM The usermode VM handle.
1212 * @param pVMM The VMM vtable.
1213 * @param enmDevType The device type.
1214 * @param ppLunL0 Where to store the node to attach the new config to on success.
1215 */
1216int Console::i_removeMediumDriverFromVm(PCFGMNODE pCtlInst,
1217 const char *pcszDevice,
1218 unsigned uInstance,
1219 unsigned uLUN,
1220 StorageBus_T enmBus,
1221 bool fAttachDetach,
1222 bool fHotplug,
1223 bool fForceUnmount,
1224 PUVM pUVM,
1225 PCVMMR3VTABLE pVMM,
1226 DeviceType_T enmDevType,
1227 PCFGMNODE *ppLunL0)
1228{
1229 int vrc = VINF_SUCCESS;
1230 bool fAddLun = false;
1231
1232 /* First check if the LUN already exists. */
1233 PCFGMNODE pLunL0 = pVMM->pfnCFGMR3GetChildF(pCtlInst, "LUN#%u", uLUN);
1234 AssertReturn(!RT_VALID_PTR(pLunL0) || fAttachDetach, VERR_INTERNAL_ERROR);
1235
1236 if (pLunL0)
1237 {
1238 /*
1239 * Unmount the currently mounted medium if we don't just hot remove the
1240 * complete device (SATA) and it supports unmounting (DVD).
1241 */
1242 if ( (enmDevType != DeviceType_HardDisk)
1243 && !fHotplug)
1244 {
1245 vrc = i_unmountMediumFromGuest(pUVM, pVMM, enmBus, enmDevType, pcszDevice, uInstance, uLUN, fForceUnmount);
1246 if (RT_FAILURE(vrc))
1247 return vrc;
1248 }
1249
1250 /*
1251 * Don't detach the SCSI driver when unmounting the current medium
1252 * (we are not ripping out the device but only eject the medium).
1253 */
1254 char *pszDriverDetach = NULL;
1255 if ( !fHotplug
1256 && ( (enmBus == StorageBus_SATA && enmDevType == DeviceType_DVD)
1257 || enmBus == StorageBus_SAS
1258 || enmBus == StorageBus_SCSI
1259 || enmBus == StorageBus_VirtioSCSI
1260 || enmBus == StorageBus_USB))
1261 {
1262 /* Get the current attached driver we have to detach. */
1263 PCFGMNODE pDrvLun = pVMM->pfnCFGMR3GetChildF(pCtlInst, "LUN#%u/AttachedDriver/", uLUN);
1264 if (pDrvLun)
1265 {
1266 char szDriver[128];
1267 RT_ZERO(szDriver);
1268 vrc = pVMM->pfnCFGMR3QueryString(pDrvLun, "Driver", &szDriver[0], sizeof(szDriver));
1269 if (RT_SUCCESS(vrc))
1270 pszDriverDetach = RTStrDup(&szDriver[0]);
1271
1272 pLunL0 = pDrvLun;
1273 }
1274 }
1275
1276 if (enmBus == StorageBus_USB)
1277 vrc = pVMM->pfnPDMR3UsbDriverDetach(pUVM, pcszDevice, uInstance, uLUN, pszDriverDetach,
1278 0 /* iOccurence */, fHotplug ? 0 : PDM_TACH_FLAGS_NOT_HOT_PLUG);
1279 else
1280 vrc = pVMM->pfnPDMR3DriverDetach(pUVM, pcszDevice, uInstance, uLUN, pszDriverDetach,
1281 0 /* iOccurence */, fHotplug ? 0 : PDM_TACH_FLAGS_NOT_HOT_PLUG);
1282
1283 if (pszDriverDetach)
1284 {
1285 RTStrFree(pszDriverDetach);
1286 /* Remove the complete node and create new for the new config. */
1287 pVMM->pfnCFGMR3RemoveNode(pLunL0);
1288 pLunL0 = pVMM->pfnCFGMR3GetChildF(pCtlInst, "LUN#%u", uLUN);
1289 if (pLunL0)
1290 {
1291 try
1292 {
1293 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
1294 }
1295 catch (ConfigError &x)
1296 {
1297 // InsertConfig threw something:
1298 return x.m_vrc;
1299 }
1300 }
1301 }
1302 if (vrc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
1303 vrc = VINF_SUCCESS;
1304 AssertRCReturn(vrc, vrc);
1305
1306 /*
1307 * Don't remove the LUN except for IDE/floppy/NVMe (which connects directly to the medium driver
1308 * even for DVD devices) or if there is a hotplug event which rips out the complete device.
1309 */
1310 if ( fHotplug
1311 || enmBus == StorageBus_IDE
1312 || enmBus == StorageBus_Floppy
1313 || enmBus == StorageBus_PCIe
1314 || (enmBus == StorageBus_SATA && enmDevType != DeviceType_DVD))
1315 {
1316 fAddLun = true;
1317 pVMM->pfnCFGMR3RemoveNode(pLunL0);
1318 }
1319 }
1320 else
1321 fAddLun = true;
1322
1323 try
1324 {
1325 if (fAddLun)
1326 InsertConfigNodeF(pCtlInst, &pLunL0, "LUN#%u", uLUN);
1327 }
1328 catch (ConfigError &x)
1329 {
1330 // InsertConfig threw something:
1331 return x.m_vrc;
1332 }
1333
1334 if (ppLunL0)
1335 *ppLunL0 = pLunL0;
1336
1337 return vrc;
1338}
1339
1340int Console::i_configMediumAttachment(const char *pcszDevice,
1341 unsigned uInstance,
1342 StorageBus_T enmBus,
1343 bool fUseHostIOCache,
1344 bool fBuiltinIOCache,
1345 bool fInsertDiskIntegrityDrv,
1346 bool fSetupMerge,
1347 unsigned uMergeSource,
1348 unsigned uMergeTarget,
1349 IMediumAttachment *pMediumAtt,
1350 MachineState_T aMachineState,
1351 HRESULT *phrc,
1352 bool fAttachDetach,
1353 bool fForceUnmount,
1354 bool fHotplug,
1355 PUVM pUVM,
1356 PCVMMR3VTABLE pVMM,
1357 DeviceType_T *paLedDevType,
1358 PCFGMNODE *ppLunL0)
1359{
1360 // InsertConfig* throws
1361 try
1362 {
1363 int vrc = VINF_SUCCESS;
1364 HRESULT hrc;
1365 Bstr bstr;
1366 PCFGMNODE pCtlInst = NULL;
1367
1368// #define RC_CHECK() AssertMsgReturn(RT_SUCCESS(vrc), ("vrc=%Rrc\n", vrc), vrc)
1369#define H() AssertLogRelMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_MAIN_CONFIG_CONSTRUCTOR_COM_ERROR)
1370
1371 LONG lDev;
1372 hrc = pMediumAtt->COMGETTER(Device)(&lDev); H();
1373 LONG lPort;
1374 hrc = pMediumAtt->COMGETTER(Port)(&lPort); H();
1375 DeviceType_T enmType;
1376 hrc = pMediumAtt->COMGETTER(Type)(&enmType); H();
1377 BOOL fNonRotational;
1378 hrc = pMediumAtt->COMGETTER(NonRotational)(&fNonRotational); H();
1379 BOOL fDiscard;
1380 hrc = pMediumAtt->COMGETTER(Discard)(&fDiscard); H();
1381
1382 if (enmType == DeviceType_DVD)
1383 fInsertDiskIntegrityDrv = false;
1384
1385 unsigned uLUN;
1386 PCFGMNODE pLunL0 = NULL;
1387 hrc = Console::i_storageBusPortDeviceToLun(enmBus, lPort, lDev, uLUN); H();
1388
1389 /* Determine the base path for the device instance. */
1390 if (enmBus != StorageBus_USB)
1391 pCtlInst = pVMM->pfnCFGMR3GetChildF(pVMM->pfnCFGMR3GetRootU(pUVM), "Devices/%s/%u/", pcszDevice, uInstance);
1392 else
1393 {
1394 /* If we hotplug a USB device create a new CFGM tree. */
1395 if (!fHotplug)
1396 pCtlInst = pVMM->pfnCFGMR3GetChildF(pVMM->pfnCFGMR3GetRootU(pUVM), "USB/%s/", pcszDevice);
1397 else
1398 pCtlInst = pVMM->pfnCFGMR3CreateTree(pUVM); /** @todo r=bird: Leaked in error paths! */
1399 }
1400 AssertReturn(pCtlInst, VERR_INTERNAL_ERROR);
1401
1402 if (enmBus == StorageBus_USB)
1403 {
1404 PCFGMNODE pCfg = NULL;
1405
1406 /* Create correct instance. */
1407 if (!fHotplug)
1408 {
1409 if (!fAttachDetach)
1410 InsertConfigNodeF(pCtlInst, &pCtlInst, "%d", lPort);
1411 else
1412 pCtlInst = pVMM->pfnCFGMR3GetChildF(pCtlInst, "%d/", lPort);
1413 }
1414
1415 if (!fAttachDetach)
1416 InsertConfigNode(pCtlInst, "Config", &pCfg);
1417
1418 uInstance = lPort; /* Overwrite uInstance with the correct one. */
1419
1420 /** @todo No LED after hotplugging. */
1421 if (!fHotplug && !fAttachDetach)
1422 {
1423 USBStorageDevice UsbMsd;
1424 UsbMsd.iPort = uInstance;
1425 vrc = RTUuidCreate(&UsbMsd.mUuid);
1426 AssertRCReturn(vrc, vrc);
1427
1428 InsertConfigStringF(pCtlInst, "UUID", "%RTuuid", &UsbMsd.mUuid);
1429
1430 mUSBStorageDevices.push_back(UsbMsd);
1431
1432 /** @todo This LED set is not freed if the device is unplugged. We could
1433 * keep the LED set index in the UsbMsd structure and clean it up in
1434 * i_detachStorageDevice. */
1435 /* Attach the status driver */
1436 i_attachStatusDriver(pCtlInst, RT_BIT_32(DeviceType_HardDisk),
1437 8, &paLedDevType, &mapMediumAttachments, pcszDevice, 0);
1438 }
1439 }
1440
1441 vrc = i_removeMediumDriverFromVm(pCtlInst, pcszDevice, uInstance, uLUN, enmBus, fAttachDetach,
1442 fHotplug, fForceUnmount, pUVM, pVMM, enmType, &pLunL0);
1443 if (RT_FAILURE(vrc))
1444 return vrc;
1445 if (ppLunL0)
1446 *ppLunL0 = pLunL0;
1447
1448 Utf8StrFmt devicePath("%s/%u/LUN#%u", pcszDevice, uInstance, uLUN);
1449 mapMediumAttachments[devicePath] = pMediumAtt;
1450
1451 ComPtr<IMedium> ptrMedium;
1452 hrc = pMediumAtt->COMGETTER(Medium)(ptrMedium.asOutParam()); H();
1453
1454 /*
1455 * 1. Only check this for hard disk images.
1456 * 2. Only check during VM creation and not later, especially not during
1457 * taking an online snapshot!
1458 */
1459 if ( enmType == DeviceType_HardDisk
1460 && ( aMachineState == MachineState_Starting
1461 || aMachineState == MachineState_Restoring))
1462 {
1463 vrc = i_checkMediumLocation(ptrMedium, &fUseHostIOCache);
1464 if (RT_FAILURE(vrc))
1465 return vrc;
1466 }
1467
1468 BOOL fPassthrough = FALSE;
1469 if (ptrMedium.isNotNull())
1470 {
1471 BOOL fHostDrive;
1472 hrc = ptrMedium->COMGETTER(HostDrive)(&fHostDrive); H();
1473 if ( ( enmType == DeviceType_DVD
1474 || enmType == DeviceType_Floppy)
1475 && !fHostDrive)
1476 {
1477 /*
1478 * Informative logging.
1479 */
1480 Bstr bstrFile;
1481 hrc = ptrMedium->COMGETTER(Location)(bstrFile.asOutParam()); H();
1482 Utf8Str strFile(bstrFile);
1483 RTFSTYPE enmFsTypeFile = RTFSTYPE_UNKNOWN;
1484 (void)RTFsQueryType(strFile.c_str(), &enmFsTypeFile);
1485 LogRel(("File system of '%s' (%s) is %s\n",
1486 strFile.c_str(), enmType == DeviceType_DVD ? "DVD" : "Floppy", RTFsTypeName(enmFsTypeFile)));
1487 }
1488
1489 if (fHostDrive)
1490 {
1491 hrc = pMediumAtt->COMGETTER(Passthrough)(&fPassthrough); H();
1492 }
1493 }
1494
1495 ComObjPtr<IBandwidthGroup> pBwGroup;
1496 Bstr bstrBwGroup;
1497 hrc = pMediumAtt->COMGETTER(BandwidthGroup)(pBwGroup.asOutParam()); H();
1498
1499 if (!pBwGroup.isNull())
1500 {
1501 hrc = pBwGroup->COMGETTER(Name)(bstrBwGroup.asOutParam()); H();
1502 }
1503
1504 /*
1505 * Insert the SCSI driver for hotplug events on the SCSI/USB based storage controllers
1506 * or for SATA if the new device is a CD/DVD drive.
1507 */
1508 if ( (fHotplug || !fAttachDetach)
1509 && ( enmBus == StorageBus_SCSI
1510 || enmBus == StorageBus_SAS
1511 || enmBus == StorageBus_USB
1512 || enmBus == StorageBus_VirtioSCSI
1513 || (enmBus == StorageBus_SATA && enmType == DeviceType_DVD && !fPassthrough)))
1514 {
1515 InsertConfigString(pLunL0, "Driver", "SCSI");
1516 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
1517 }
1518
1519 vrc = i_configMedium(pLunL0,
1520 !!fPassthrough,
1521 enmType,
1522 fUseHostIOCache,
1523 fBuiltinIOCache,
1524 fInsertDiskIntegrityDrv,
1525 fSetupMerge,
1526 uMergeSource,
1527 uMergeTarget,
1528 bstrBwGroup.isEmpty() ? NULL : Utf8Str(bstrBwGroup).c_str(),
1529 !!fDiscard,
1530 !!fNonRotational,
1531 ptrMedium,
1532 aMachineState,
1533 phrc);
1534 if (RT_FAILURE(vrc))
1535 return vrc;
1536
1537 if (fAttachDetach)
1538 {
1539 /* Attach the new driver. */
1540 if (enmBus == StorageBus_USB)
1541 {
1542 if (fHotplug)
1543 {
1544 USBStorageDevice UsbMsd;
1545 RTUuidCreate(&UsbMsd.mUuid);
1546 UsbMsd.iPort = uInstance;
1547 vrc = pVMM->pfnPDMR3UsbCreateEmulatedDevice(pUVM, pcszDevice, pCtlInst, &UsbMsd.mUuid, NULL);
1548 if (RT_SUCCESS(vrc))
1549 mUSBStorageDevices.push_back(UsbMsd);
1550 }
1551 else
1552 vrc = pVMM->pfnPDMR3UsbDriverAttach(pUVM, pcszDevice, uInstance, uLUN,
1553 fHotplug ? 0 : PDM_TACH_FLAGS_NOT_HOT_PLUG, NULL /*ppBase*/);
1554 }
1555 else if ( !fHotplug
1556 && ( (enmBus == StorageBus_SAS || enmBus == StorageBus_SCSI || enmBus == StorageBus_VirtioSCSI)
1557 || (enmBus == StorageBus_SATA && enmType == DeviceType_DVD)))
1558 vrc = pVMM->pfnPDMR3DriverAttach(pUVM, pcszDevice, uInstance, uLUN,
1559 fHotplug ? 0 : PDM_TACH_FLAGS_NOT_HOT_PLUG, NULL /*ppBase*/);
1560 else
1561 vrc = pVMM->pfnPDMR3DeviceAttach(pUVM, pcszDevice, uInstance, uLUN,
1562 fHotplug ? 0 : PDM_TACH_FLAGS_NOT_HOT_PLUG, NULL /*ppBase*/);
1563 AssertRCReturn(vrc, vrc);
1564
1565 /*
1566 * Make the secret key helper interface known to the VD driver if it is attached,
1567 * so we can get notified about missing keys.
1568 */
1569 PPDMIBASE pIBase = NULL;
1570 vrc = pVMM->pfnPDMR3QueryDriverOnLun(pUVM, pcszDevice, uInstance, uLUN, "VD", &pIBase);
1571 if (RT_SUCCESS(vrc) && pIBase)
1572 {
1573 PPDMIMEDIA pIMedium = (PPDMIMEDIA)pIBase->pfnQueryInterface(pIBase, PDMIMEDIA_IID);
1574 if (pIMedium)
1575 {
1576 vrc = pIMedium->pfnSetSecKeyIf(pIMedium, mpIfSecKey, mpIfSecKeyHlp);
1577 Assert(RT_SUCCESS(vrc) || vrc == VERR_NOT_SUPPORTED);
1578 }
1579 }
1580
1581 /* There is no need to handle removable medium mounting, as we
1582 * unconditionally replace everthing including the block driver level.
1583 * This means the new medium will be picked up automatically. */
1584 }
1585
1586 if (paLedDevType)
1587 i_setLedType(&paLedDevType[uLUN], enmType);
1588
1589 /* Dump the changed LUN if possible, dump the complete device otherwise */
1590 if ( aMachineState != MachineState_Starting
1591 && aMachineState != MachineState_Restoring)
1592 pVMM->pfnCFGMR3Dump(pLunL0 ? pLunL0 : pCtlInst);
1593 }
1594 catch (ConfigError &x)
1595 {
1596 // InsertConfig threw something:
1597 return x.m_vrc;
1598 }
1599
1600#undef H
1601
1602 return VINF_SUCCESS;
1603}
1604
1605int Console::i_configMedium(PCFGMNODE pLunL0,
1606 bool fPassthrough,
1607 DeviceType_T enmType,
1608 bool fUseHostIOCache,
1609 bool fBuiltinIOCache,
1610 bool fInsertDiskIntegrityDrv,
1611 bool fSetupMerge,
1612 unsigned uMergeSource,
1613 unsigned uMergeTarget,
1614 const char *pcszBwGroup,
1615 bool fDiscard,
1616 bool fNonRotational,
1617 ComPtr<IMedium> ptrMedium,
1618 MachineState_T aMachineState,
1619 HRESULT *phrc)
1620{
1621 // InsertConfig* throws
1622 try
1623 {
1624 HRESULT hrc;
1625 Bstr bstr;
1626 PCFGMNODE pCfg = NULL;
1627
1628#define H() \
1629 AssertMsgReturnStmt(SUCCEEDED(hrc), ("hrc=%Rhrc\n", hrc), if (phrc) *phrc = hrc, Global::vboxStatusCodeFromCOM(hrc))
1630
1631
1632 BOOL fHostDrive = FALSE;
1633 MediumType_T mediumType = MediumType_Normal;
1634 if (ptrMedium.isNotNull())
1635 {
1636 hrc = ptrMedium->COMGETTER(HostDrive)(&fHostDrive); H();
1637 hrc = ptrMedium->COMGETTER(Type)(&mediumType); H();
1638 }
1639
1640 if (fHostDrive)
1641 {
1642 Assert(ptrMedium.isNotNull());
1643 if (enmType == DeviceType_DVD)
1644 {
1645 InsertConfigString(pLunL0, "Driver", "HostDVD");
1646 InsertConfigNode(pLunL0, "Config", &pCfg);
1647
1648 hrc = ptrMedium->COMGETTER(Location)(bstr.asOutParam()); H();
1649 InsertConfigString(pCfg, "Path", bstr);
1650
1651 InsertConfigInteger(pCfg, "Passthrough", fPassthrough);
1652 }
1653 else if (enmType == DeviceType_Floppy)
1654 {
1655 InsertConfigString(pLunL0, "Driver", "HostFloppy");
1656 InsertConfigNode(pLunL0, "Config", &pCfg);
1657
1658 hrc = ptrMedium->COMGETTER(Location)(bstr.asOutParam()); H();
1659 InsertConfigString(pCfg, "Path", bstr);
1660 }
1661 }
1662 else
1663 {
1664 if (fInsertDiskIntegrityDrv)
1665 {
1666 /*
1667 * The actual configuration is done through CFGM extra data
1668 * for each inserted driver separately.
1669 */
1670 InsertConfigString(pLunL0, "Driver", "DiskIntegrity");
1671 InsertConfigNode(pLunL0, "Config", &pCfg);
1672 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
1673 }
1674
1675 InsertConfigString(pLunL0, "Driver", "VD");
1676 InsertConfigNode(pLunL0, "Config", &pCfg);
1677 switch (enmType)
1678 {
1679 case DeviceType_DVD:
1680 InsertConfigString(pCfg, "Type", "DVD");
1681 InsertConfigInteger(pCfg, "Mountable", 1);
1682 break;
1683 case DeviceType_Floppy:
1684 InsertConfigString(pCfg, "Type", "Floppy 1.44");
1685 InsertConfigInteger(pCfg, "Mountable", 1);
1686 break;
1687 case DeviceType_HardDisk:
1688 default:
1689 InsertConfigString(pCfg, "Type", "HardDisk");
1690 InsertConfigInteger(pCfg, "Mountable", 0);
1691 }
1692
1693 if ( ptrMedium.isNotNull()
1694 && ( enmType == DeviceType_DVD
1695 || enmType == DeviceType_Floppy)
1696 )
1697 {
1698 // if this medium represents an ISO image and this image is inaccessible,
1699 // the ignore it instead of causing a failure; this can happen when we
1700 // restore a VM state and the ISO has disappeared, e.g. because the Guest
1701 // Additions were mounted and the user upgraded VirtualBox. Previously
1702 // we failed on startup, but that's not good because the only way out then
1703 // would be to discard the VM state...
1704 MediumState_T mediumState;
1705 hrc = ptrMedium->RefreshState(&mediumState); H();
1706 if (mediumState == MediumState_Inaccessible)
1707 {
1708 Bstr loc;
1709 hrc = ptrMedium->COMGETTER(Location)(loc.asOutParam()); H();
1710 i_atVMRuntimeErrorCallbackF(0, "DvdOrFloppyImageInaccessible",
1711 N_("The image file '%ls' is inaccessible and is being ignored. "
1712 "Please select a different image file for the virtual %s drive."),
1713 loc.raw(),
1714 enmType == DeviceType_DVD ? "DVD" : "floppy");
1715 ptrMedium.setNull();
1716 }
1717 }
1718
1719 if (ptrMedium.isNotNull())
1720 {
1721 /* Start with length of parent chain, as the list is reversed */
1722 unsigned uImage = 0;
1723 ComPtr<IMedium> ptrTmp = ptrMedium;
1724 while (ptrTmp.isNotNull())
1725 {
1726 uImage++;
1727 ComPtr<IMedium> ptrParent;
1728 hrc = ptrTmp->COMGETTER(Parent)(ptrParent.asOutParam()); H();
1729 ptrTmp = ptrParent;
1730 }
1731 /* Index of last image */
1732 uImage--;
1733
1734# ifdef VBOX_WITH_EXTPACK
1735 if (mptrExtPackManager->i_isExtPackUsable(ORACLE_PUEL_EXTPACK_NAME))
1736 {
1737 /* Configure loading the VDPlugin. */
1738 static const char s_szVDPlugin[] = "VDPluginCrypt";
1739 PCFGMNODE pCfgPlugins = NULL;
1740 PCFGMNODE pCfgPlugin = NULL;
1741 Utf8Str strPlugin;
1742 hrc = mptrExtPackManager->i_getLibraryPathForExtPack(s_szVDPlugin, ORACLE_PUEL_EXTPACK_NAME, &strPlugin);
1743 // Don't fail, this is optional!
1744 if (SUCCEEDED(hrc))
1745 {
1746 InsertConfigNode(pCfg, "Plugins", &pCfgPlugins);
1747 InsertConfigNode(pCfgPlugins, s_szVDPlugin, &pCfgPlugin);
1748 InsertConfigString(pCfgPlugin, "Path", strPlugin);
1749 }
1750 }
1751# endif
1752
1753 hrc = ptrMedium->COMGETTER(Location)(bstr.asOutParam()); H();
1754 InsertConfigString(pCfg, "Path", bstr);
1755
1756 hrc = ptrMedium->COMGETTER(Format)(bstr.asOutParam()); H();
1757 InsertConfigString(pCfg, "Format", bstr);
1758
1759 if (mediumType == MediumType_Readonly)
1760 InsertConfigInteger(pCfg, "ReadOnly", 1);
1761 else if (enmType == DeviceType_Floppy)
1762 InsertConfigInteger(pCfg, "MaybeReadOnly", 1);
1763
1764 /* Start without exclusive write access to the images. */
1765 /** @todo Live Migration: I don't quite like this, we risk screwing up when
1766 * we're resuming the VM if some 3rd dude have any of the VDIs open
1767 * with write sharing denied. However, if the two VMs are sharing a
1768 * image it really is necessary....
1769 *
1770 * So, on the "lock-media" command, the target teleporter should also
1771 * make DrvVD undo TempReadOnly. It gets interesting if we fail after
1772 * that. Grumble. */
1773 if ( enmType == DeviceType_HardDisk
1774 && aMachineState == MachineState_TeleportingIn)
1775 InsertConfigInteger(pCfg, "TempReadOnly", 1);
1776
1777 /* Flag for opening the medium for sharing between VMs. This
1778 * is done at the moment only for the first (and only) medium
1779 * in the chain, as shared media can have no diffs. */
1780 if (mediumType == MediumType_Shareable)
1781 InsertConfigInteger(pCfg, "Shareable", 1);
1782
1783 if (!fUseHostIOCache)
1784 {
1785 InsertConfigInteger(pCfg, "UseNewIo", 1);
1786 /*
1787 * Activate the builtin I/O cache for harddisks only.
1788 * It caches writes only which doesn't make sense for DVD drives
1789 * and just increases the overhead.
1790 */
1791 if ( fBuiltinIOCache
1792 && (enmType == DeviceType_HardDisk))
1793 InsertConfigInteger(pCfg, "BlockCache", 1);
1794 }
1795
1796 if (fSetupMerge)
1797 {
1798 InsertConfigInteger(pCfg, "SetupMerge", 1);
1799 if (uImage == uMergeSource)
1800 InsertConfigInteger(pCfg, "MergeSource", 1);
1801 else if (uImage == uMergeTarget)
1802 InsertConfigInteger(pCfg, "MergeTarget", 1);
1803 }
1804
1805 if (pcszBwGroup)
1806 InsertConfigString(pCfg, "BwGroup", pcszBwGroup);
1807
1808 if (fDiscard)
1809 InsertConfigInteger(pCfg, "Discard", 1);
1810
1811 if (fNonRotational)
1812 InsertConfigInteger(pCfg, "NonRotationalMedium", 1);
1813
1814 /* Pass all custom parameters. */
1815 bool fHostIP = true;
1816 bool fEncrypted = false;
1817 hrc = i_configMediumProperties(pCfg, ptrMedium, &fHostIP, &fEncrypted); H();
1818
1819 /* Create an inverted list of parents. */
1820 uImage--;
1821 ComPtr<IMedium> ptrParentMedium = ptrMedium;
1822 for (PCFGMNODE pParent = pCfg;; uImage--)
1823 {
1824 ComPtr<IMedium> ptrCurMedium;
1825 hrc = ptrParentMedium->COMGETTER(Parent)(ptrCurMedium.asOutParam()); H();
1826 if (ptrCurMedium.isNull())
1827 break;
1828
1829 PCFGMNODE pCur;
1830 InsertConfigNode(pParent, "Parent", &pCur);
1831 hrc = ptrCurMedium->COMGETTER(Location)(bstr.asOutParam()); H();
1832 InsertConfigString(pCur, "Path", bstr);
1833
1834 hrc = ptrCurMedium->COMGETTER(Format)(bstr.asOutParam()); H();
1835 InsertConfigString(pCur, "Format", bstr);
1836
1837 if (fSetupMerge)
1838 {
1839 if (uImage == uMergeSource)
1840 InsertConfigInteger(pCur, "MergeSource", 1);
1841 else if (uImage == uMergeTarget)
1842 InsertConfigInteger(pCur, "MergeTarget", 1);
1843 }
1844
1845 /* Configure medium properties. */
1846 hrc = i_configMediumProperties(pCur, ptrCurMedium, &fHostIP, &fEncrypted); H();
1847
1848 /* next */
1849 pParent = pCur;
1850 ptrParentMedium = ptrCurMedium;
1851 }
1852
1853 /* Custom code: put marker to not use host IP stack to driver
1854 * configuration node. Simplifies life of DrvVD a bit. */
1855 if (!fHostIP)
1856 InsertConfigInteger(pCfg, "HostIPStack", 0);
1857
1858 if (fEncrypted)
1859 m_cDisksEncrypted++;
1860 }
1861 else
1862 {
1863 /* Set empty drive flag for DVD or floppy without media. */
1864 if ( enmType == DeviceType_DVD
1865 || enmType == DeviceType_Floppy)
1866 InsertConfigInteger(pCfg, "EmptyDrive", 1);
1867 }
1868 }
1869#undef H
1870 }
1871 catch (ConfigError &x)
1872 {
1873 // InsertConfig threw something:
1874 return x.m_vrc;
1875 }
1876
1877 return VINF_SUCCESS;
1878}
1879
1880/**
1881 * Adds the medium properties to the CFGM tree.
1882 *
1883 * @returns VBox status code.
1884 * @param pCur The current CFGM node.
1885 * @param pMedium The medium object to configure.
1886 * @param pfHostIP Where to return the value of the \"HostIPStack\" property if found.
1887 * @param pfEncrypted Where to return whether the medium is encrypted.
1888 */
1889int Console::i_configMediumProperties(PCFGMNODE pCur, IMedium *pMedium, bool *pfHostIP, bool *pfEncrypted)
1890{
1891 /* Pass all custom parameters. */
1892 SafeArray<BSTR> aNames;
1893 SafeArray<BSTR> aValues;
1894 HRESULT hrc = pMedium->GetProperties(NULL, ComSafeArrayAsOutParam(aNames), ComSafeArrayAsOutParam(aValues));
1895 if ( SUCCEEDED(hrc)
1896 && aNames.size() != 0)
1897 {
1898 PCFGMNODE pVDC;
1899 InsertConfigNode(pCur, "VDConfig", &pVDC);
1900 for (size_t ii = 0; ii < aNames.size(); ++ii)
1901 {
1902 if (aValues[ii] && *aValues[ii])
1903 {
1904 Utf8Str const strName = aNames[ii];
1905 Utf8Str const strValue = aValues[ii];
1906 size_t offSlash = strName.find("/", 0);
1907 if ( offSlash != strName.npos
1908 && !strName.startsWith("Special/"))
1909 {
1910 com::Utf8Str strFilter;
1911 hrc = strFilter.assignEx(strName, 0, offSlash);
1912 if (FAILED(hrc))
1913 break;
1914
1915 com::Utf8Str strKey;
1916 hrc = strKey.assignEx(strName, offSlash + 1, strName.length() - offSlash - 1); /* Skip slash */
1917 if (FAILED(hrc))
1918 break;
1919
1920 PCFGMNODE pCfgFilterConfig = mpVMM->pfnCFGMR3GetChild(pVDC, strFilter.c_str());
1921 if (!pCfgFilterConfig)
1922 InsertConfigNode(pVDC, strFilter.c_str(), &pCfgFilterConfig);
1923
1924 InsertConfigString(pCfgFilterConfig, strKey.c_str(), strValue);
1925 }
1926 else
1927 {
1928 InsertConfigString(pVDC, strName.c_str(), strValue);
1929 if ( strName.compare("HostIPStack") == 0
1930 && strValue.compare("0") == 0)
1931 *pfHostIP = false;
1932 }
1933
1934 if ( strName.compare("CRYPT/KeyId") == 0
1935 && pfEncrypted)
1936 *pfEncrypted = true;
1937 }
1938 }
1939 }
1940
1941 return hrc;
1942}
1943
1944
1945/**
1946 * Configure proxy parameters the Network configuration tree.
1947 *
1948 * Parameters may differ depending on the IP address being accessed.
1949 *
1950 * @returns VBox status code.
1951 *
1952 * @param virtualBox The VirtualBox object.
1953 * @param pCfg Configuration node for the driver.
1954 * @param pcszPrefix The prefix for CFGM parameters: "Primary" or "Secondary".
1955 * @param strIpAddr The public IP address to be accessed via a proxy.
1956 *
1957 * @thread EMT
1958 */
1959int Console::i_configProxy(ComPtr<IVirtualBox> virtualBox, PCFGMNODE pCfg, const char *pcszPrefix, const com::Utf8Str &strIpAddr)
1960{
1961/** @todo r=bird: This code doesn't handle cleanup correctly and may leak
1962 * when hitting errors or throwing exceptions (bad_alloc). */
1963 RTHTTPPROXYINFO ProxyInfo;
1964 ComPtr<ISystemProperties> systemProperties;
1965 ProxyMode_T enmProxyMode;
1966 HRESULT hrc = virtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam());
1967 if (FAILED(hrc))
1968 {
1969 LogRel(("CLOUD-NET: Failed to obtain system properties. hrc=%x\n", hrc));
1970 return false;
1971 }
1972 hrc = systemProperties->COMGETTER(ProxyMode)(&enmProxyMode);
1973 if (FAILED(hrc))
1974 {
1975 LogRel(("CLOUD-NET: Failed to obtain default machine folder. hrc=%x\n", hrc));
1976 return VERR_INTERNAL_ERROR;
1977 }
1978
1979 RTHTTP hHttp;
1980 int vrc = RTHttpCreate(&hHttp);
1981 if (RT_FAILURE(vrc))
1982 {
1983 LogRel(("CLOUD-NET: Failed to create HTTP context (vrc=%Rrc)\n", vrc));
1984 return vrc;
1985 }
1986
1987 char *pszProxyType = NULL;
1988
1989 if (enmProxyMode == ProxyMode_Manual)
1990 {
1991 /*
1992 * Unfortunately we cannot simply call RTHttpSetProxyByUrl because it never
1993 * exposes proxy settings. Calling RTHttpQueryProxyInfoForUrl afterward
1994 * won't help either as it uses system-wide proxy settings instead of
1995 * parameters we would have set with RTHttpSetProxyByUrl. Hence we parse
1996 * proxy URL ourselves here.
1997 */
1998 Bstr proxyUrl;
1999 hrc = systemProperties->COMGETTER(ProxyURL)(proxyUrl.asOutParam());
2000 if (FAILED(hrc))
2001 {
2002 LogRel(("CLOUD-NET: Failed to obtain proxy URL. hrc=%x\n", hrc));
2003 return false;
2004 }
2005 Utf8Str strProxyUrl = proxyUrl;
2006 if (!strProxyUrl.contains("://"))
2007 strProxyUrl = "http://" + strProxyUrl;
2008 const char *pcszProxyUrl = strProxyUrl.c_str();
2009 RTURIPARSED Parsed;
2010 vrc = RTUriParse(pcszProxyUrl, &Parsed);
2011 if (RT_FAILURE(vrc))
2012 {
2013 LogRel(("CLOUD-NET: Failed to parse proxy URL: %ls (vrc=%Rrc)\n", proxyUrl.raw(), vrc));
2014 return false;
2015 }
2016
2017 pszProxyType = RTUriParsedScheme(pcszProxyUrl, &Parsed);
2018 if (!pszProxyType)
2019 {
2020 LogRel(("CLOUD-NET: Failed to get proxy scheme from proxy URL: %s\n", pcszProxyUrl));
2021 return false;
2022 }
2023 RTStrToUpper(pszProxyType);
2024
2025 ProxyInfo.pszProxyHost = RTUriParsedAuthorityHost(pcszProxyUrl, &Parsed);
2026 if (!ProxyInfo.pszProxyHost)
2027 {
2028 LogRel(("CLOUD-NET: Failed to get proxy host name from proxy URL: %s\n", pcszProxyUrl));
2029 return false;
2030 }
2031 ProxyInfo.uProxyPort = RTUriParsedAuthorityPort(pcszProxyUrl, &Parsed);
2032 if (ProxyInfo.uProxyPort == UINT32_MAX)
2033 {
2034 LogRel(("CLOUD-NET: Failed to get proxy port from proxy URL: %s\n", pcszProxyUrl));
2035 return false;
2036 }
2037 ProxyInfo.pszProxyUsername = RTUriParsedAuthorityUsername(pcszProxyUrl, &Parsed);
2038 ProxyInfo.pszProxyPassword = RTUriParsedAuthorityPassword(pcszProxyUrl, &Parsed);
2039 }
2040 else if (enmProxyMode == ProxyMode_System)
2041 {
2042 vrc = RTHttpUseSystemProxySettings(hHttp);
2043 if (RT_FAILURE(vrc))
2044 {
2045 LogRel(("%s: RTHttpUseSystemProxySettings() failed: %Rrc", __FUNCTION__, vrc));
2046 RTHttpDestroy(hHttp);
2047 return vrc;
2048 }
2049 vrc = RTHttpQueryProxyInfoForUrl(hHttp, ("http://" + strIpAddr).c_str(), &ProxyInfo);
2050 RTHttpDestroy(hHttp);
2051 if (RT_FAILURE(vrc))
2052 {
2053 LogRel(("CLOUD-NET: Failed to get proxy for %s (vrc=%Rrc)\n", strIpAddr.c_str(), vrc));
2054 return vrc;
2055 }
2056
2057 switch (ProxyInfo.enmProxyType)
2058 {
2059 case RTHTTPPROXYTYPE_NOPROXY:
2060 /* Nothing to do */
2061 return VINF_SUCCESS;
2062 case RTHTTPPROXYTYPE_HTTP:
2063 pszProxyType = RTStrDup("HTTP");
2064 break;
2065 case RTHTTPPROXYTYPE_HTTPS:
2066 case RTHTTPPROXYTYPE_SOCKS4:
2067 case RTHTTPPROXYTYPE_SOCKS5:
2068 /* break; -- Fall through until support is implemented */
2069 case RTHTTPPROXYTYPE_UNKNOWN:
2070 case RTHTTPPROXYTYPE_INVALID:
2071 case RTHTTPPROXYTYPE_END:
2072 case RTHTTPPROXYTYPE_32BIT_HACK:
2073 LogRel(("CLOUD-NET: Unsupported proxy type %u\n", ProxyInfo.enmProxyType));
2074 RTHttpFreeProxyInfo(&ProxyInfo);
2075 return VERR_INVALID_PARAMETER;
2076 }
2077 }
2078 else
2079 {
2080 Assert(enmProxyMode == ProxyMode_NoProxy);
2081 return VINF_SUCCESS;
2082 }
2083
2084 /* Resolve proxy host name to IP address if necessary */
2085 RTNETADDR addr;
2086 RTSocketParseInetAddress(ProxyInfo.pszProxyHost, ProxyInfo.uProxyPort, &addr);
2087 if (addr.enmType != RTNETADDRTYPE_IPV4)
2088 {
2089 LogRel(("CLOUD-NET: Unsupported address type %u\n", addr.enmType));
2090 RTHttpFreeProxyInfo(&ProxyInfo);
2091 return VERR_INVALID_PARAMETER;
2092 }
2093
2094 InsertConfigString( pCfg, Utf8StrFmt("%sProxyType", pcszPrefix).c_str(), pszProxyType);
2095 InsertConfigInteger( pCfg, Utf8StrFmt("%sProxyPort", pcszPrefix).c_str(), ProxyInfo.uProxyPort);
2096 if (ProxyInfo.pszProxyHost)
2097 InsertConfigStringF( pCfg, Utf8StrFmt("%sProxyHost", pcszPrefix).c_str(), "%RTnaipv4", addr.uAddr.IPv4);
2098 if (ProxyInfo.pszProxyUsername)
2099 InsertConfigString( pCfg, Utf8StrFmt("%sProxyUser", pcszPrefix).c_str(), ProxyInfo.pszProxyUsername);
2100 if (ProxyInfo.pszProxyPassword)
2101 InsertConfigPassword(pCfg, Utf8StrFmt("%sProxyPassword", pcszPrefix).c_str(), ProxyInfo.pszProxyPassword);
2102
2103 RTHttpFreeProxyInfo(&ProxyInfo);
2104 RTStrFree(pszProxyType);
2105 return vrc;
2106}
2107
2108
2109/**
2110 * Construct the Network configuration tree
2111 *
2112 * @returns VBox status code.
2113 *
2114 * @param pszDevice The PDM device name.
2115 * @param uInstance The PDM device instance.
2116 * @param uLun The PDM LUN number of the drive.
2117 * @param aNetworkAdapter The network adapter whose attachment needs to be changed
2118 * @param pCfg Configuration node for the device
2119 * @param pLunL0 To store the pointer to the LUN#0.
2120 * @param pInst The instance CFGM node
2121 * @param fAttachDetach To determine if the network attachment should
2122 * be attached/detached after/before
2123 * configuration.
2124 * @param fIgnoreConnectFailure
2125 * True if connection failures should be ignored
2126 * (makes only sense for bridged/host-only networks).
2127 * @param pUVM The usermode VM handle.
2128 * @param pVMM The VMM vtable.
2129 *
2130 * @note Locks this object for writing.
2131 * @thread EMT
2132 */
2133int Console::i_configNetwork(const char *pszDevice,
2134 unsigned uInstance,
2135 unsigned uLun,
2136 INetworkAdapter *aNetworkAdapter,
2137 PCFGMNODE pCfg,
2138 PCFGMNODE pLunL0,
2139 PCFGMNODE pInst,
2140 bool fAttachDetach,
2141 bool fIgnoreConnectFailure,
2142 PUVM pUVM,
2143 PCVMMR3VTABLE pVMM)
2144{
2145 RT_NOREF(fIgnoreConnectFailure);
2146 AutoCaller autoCaller(this);
2147 AssertComRCReturn(autoCaller.hrc(), VERR_ACCESS_DENIED);
2148
2149 // InsertConfig* throws
2150 try
2151 {
2152 int vrc = VINF_SUCCESS;
2153 HRESULT hrc;
2154 Bstr bstr;
2155
2156#ifdef VBOX_WITH_CLOUD_NET
2157 /* We'll need device's pCfg for cloud attachments */
2158 PCFGMNODE pDevCfg = pCfg;
2159#endif /* VBOX_WITH_CLOUD_NET */
2160
2161#define H() AssertLogRelMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_MAIN_CONFIG_CONSTRUCTOR_COM_ERROR)
2162
2163 /*
2164 * Locking the object before doing VMR3* calls is quite safe here, since
2165 * we're on EMT. Write lock is necessary because we indirectly modify the
2166 * meAttachmentType member.
2167 */
2168 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2169
2170 ComPtr<IMachine> pMachine = i_machine();
2171
2172 ComPtr<IVirtualBox> virtualBox;
2173 hrc = pMachine->COMGETTER(Parent)(virtualBox.asOutParam()); H();
2174
2175 ComPtr<IHost> host;
2176 hrc = virtualBox->COMGETTER(Host)(host.asOutParam()); H();
2177
2178 BOOL fSniffer;
2179 hrc = aNetworkAdapter->COMGETTER(TraceEnabled)(&fSniffer); H();
2180
2181 NetworkAdapterPromiscModePolicy_T enmPromiscModePolicy;
2182 hrc = aNetworkAdapter->COMGETTER(PromiscModePolicy)(&enmPromiscModePolicy); H();
2183 const char *pszPromiscuousGuestPolicy;
2184 switch (enmPromiscModePolicy)
2185 {
2186 case NetworkAdapterPromiscModePolicy_Deny: pszPromiscuousGuestPolicy = "deny"; break;
2187 case NetworkAdapterPromiscModePolicy_AllowNetwork: pszPromiscuousGuestPolicy = "allow-network"; break;
2188 case NetworkAdapterPromiscModePolicy_AllowAll: pszPromiscuousGuestPolicy = "allow-all"; break;
2189 default: AssertFailedReturn(VERR_INTERNAL_ERROR_4);
2190 }
2191
2192 if (fAttachDetach)
2193 {
2194 vrc = pVMM->pfnPDMR3DeviceDetach(pUVM, pszDevice, uInstance, uLun, 0 /*fFlags*/);
2195 if (vrc == VINF_PDM_NO_DRIVER_ATTACHED_TO_LUN)
2196 vrc = VINF_SUCCESS;
2197 AssertLogRelRCReturn(vrc, vrc);
2198
2199 /* Nuke anything which might have been left behind. */
2200 pVMM->pfnCFGMR3RemoveNode(pVMM->pfnCFGMR3GetChildF(pInst, "LUN#%u", uLun));
2201 }
2202
2203 Bstr networkName, trunkName, trunkType;
2204 NetworkAttachmentType_T eAttachmentType;
2205 hrc = aNetworkAdapter->COMGETTER(AttachmentType)(&eAttachmentType); H();
2206
2207#ifdef VBOX_WITH_NETSHAPER
2208 ComObjPtr<IBandwidthGroup> pBwGroup;
2209 Bstr bstrBwGroup;
2210 hrc = aNetworkAdapter->COMGETTER(BandwidthGroup)(pBwGroup.asOutParam()); H();
2211
2212 if (!pBwGroup.isNull())
2213 {
2214 hrc = pBwGroup->COMGETTER(Name)(bstrBwGroup.asOutParam()); H();
2215 }
2216#endif /* VBOX_WITH_NETSHAPER */
2217
2218 AssertMsg(uLun == 0, ("Network attachments with LUN > 0 are not supported yet\n"));
2219 InsertConfigNodeF(pInst, &pLunL0, "LUN#%u", uLun);
2220
2221 /*
2222 * Do not insert neither a shaper nor a sniffer if we are not attached to anything.
2223 * This way we can easily detect if we are attached to anything at the device level.
2224 */
2225#ifdef VBOX_WITH_NETSHAPER
2226 if (bstrBwGroup.isNotEmpty() && eAttachmentType != NetworkAttachmentType_Null)
2227 {
2228 InsertConfigString(pLunL0, "Driver", "NetShaper");
2229 InsertConfigNode(pLunL0, "Config", &pCfg);
2230 InsertConfigString(pCfg, "BwGroup", bstrBwGroup);
2231 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
2232 }
2233#endif /* VBOX_WITH_NETSHAPER */
2234
2235 if (fSniffer && eAttachmentType != NetworkAttachmentType_Null)
2236 {
2237 InsertConfigString(pLunL0, "Driver", "NetSniffer");
2238 InsertConfigNode(pLunL0, "Config", &pCfg);
2239 hrc = aNetworkAdapter->COMGETTER(TraceFile)(bstr.asOutParam()); H();
2240 if (!bstr.isEmpty()) /* check convention for indicating default file. */
2241 InsertConfigString(pCfg, "File", bstr);
2242 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
2243 }
2244
2245 switch (eAttachmentType)
2246 {
2247 case NetworkAttachmentType_Null:
2248 break;
2249
2250 case NetworkAttachmentType_NAT:
2251 {
2252 ComPtr<INATEngine> natEngine;
2253 hrc = aNetworkAdapter->COMGETTER(NATEngine)(natEngine.asOutParam()); H();
2254 InsertConfigString(pLunL0, "Driver", "NAT");
2255 InsertConfigNode(pLunL0, "Config", &pCfg);
2256
2257 /* Configure TFTP prefix and boot filename. */
2258 hrc = virtualBox->COMGETTER(HomeFolder)(bstr.asOutParam()); H();
2259 if (!bstr.isEmpty())
2260 InsertConfigStringF(pCfg, "TFTPPrefix", "%ls%c%s", bstr.raw(), RTPATH_DELIMITER, "TFTP");
2261 hrc = pMachine->COMGETTER(Name)(bstr.asOutParam()); H();
2262 InsertConfigStringF(pCfg, "BootFile", "%ls.pxe", bstr.raw());
2263
2264 hrc = natEngine->COMGETTER(Network)(bstr.asOutParam()); H();
2265 if (!bstr.isEmpty())
2266 InsertConfigString(pCfg, "Network", bstr);
2267 else
2268 {
2269 ULONG uSlot;
2270 hrc = aNetworkAdapter->COMGETTER(Slot)(&uSlot); H();
2271 InsertConfigStringF(pCfg, "Network", "10.0.%d.0/24", uSlot+2);
2272 }
2273 hrc = natEngine->COMGETTER(HostIP)(bstr.asOutParam()); H();
2274 if (!bstr.isEmpty())
2275 InsertConfigString(pCfg, "BindIP", bstr);
2276 ULONG mtu = 0;
2277 ULONG sockSnd = 0;
2278 ULONG sockRcv = 0;
2279 ULONG tcpSnd = 0;
2280 ULONG tcpRcv = 0;
2281 hrc = natEngine->GetNetworkSettings(&mtu, &sockSnd, &sockRcv, &tcpSnd, &tcpRcv); H();
2282 if (mtu)
2283 InsertConfigInteger(pCfg, "SlirpMTU", mtu);
2284 if (sockRcv)
2285 InsertConfigInteger(pCfg, "SockRcv", sockRcv);
2286 if (sockSnd)
2287 InsertConfigInteger(pCfg, "SockSnd", sockSnd);
2288 if (tcpRcv)
2289 InsertConfigInteger(pCfg, "TcpRcv", tcpRcv);
2290 if (tcpSnd)
2291 InsertConfigInteger(pCfg, "TcpSnd", tcpSnd);
2292 hrc = natEngine->COMGETTER(TFTPPrefix)(bstr.asOutParam()); H();
2293 if (!bstr.isEmpty())
2294 {
2295 RemoveConfigValue(pCfg, "TFTPPrefix");
2296 InsertConfigString(pCfg, "TFTPPrefix", bstr);
2297 }
2298 hrc = natEngine->COMGETTER(TFTPBootFile)(bstr.asOutParam()); H();
2299 if (!bstr.isEmpty())
2300 {
2301 RemoveConfigValue(pCfg, "BootFile");
2302 InsertConfigString(pCfg, "BootFile", bstr);
2303 }
2304 hrc = natEngine->COMGETTER(TFTPNextServer)(bstr.asOutParam()); H();
2305 if (!bstr.isEmpty())
2306 InsertConfigString(pCfg, "NextServer", bstr);
2307 BOOL fDNSFlag;
2308 hrc = natEngine->COMGETTER(DNSPassDomain)(&fDNSFlag); H();
2309 InsertConfigInteger(pCfg, "PassDomain", fDNSFlag);
2310 hrc = natEngine->COMGETTER(DNSProxy)(&fDNSFlag); H();
2311 InsertConfigInteger(pCfg, "DNSProxy", fDNSFlag);
2312 hrc = natEngine->COMGETTER(DNSUseHostResolver)(&fDNSFlag); H();
2313 InsertConfigInteger(pCfg, "UseHostResolver", fDNSFlag);
2314
2315 ULONG aliasMode;
2316 hrc = natEngine->COMGETTER(AliasMode)(&aliasMode); H();
2317 InsertConfigInteger(pCfg, "AliasMode", aliasMode);
2318
2319 BOOL fLocalhostReachable;
2320 hrc = natEngine->COMGETTER(LocalhostReachable)(&fLocalhostReachable); H();
2321 InsertConfigInteger(pCfg, "LocalhostReachable", fLocalhostReachable);
2322
2323 /* port-forwarding */
2324 SafeArray<BSTR> pfs;
2325 hrc = natEngine->COMGETTER(Redirects)(ComSafeArrayAsOutParam(pfs)); H();
2326
2327 PCFGMNODE pPFTree = NULL;
2328 if (pfs.size() > 0)
2329 InsertConfigNode(pCfg, "PortForwarding", &pPFTree);
2330
2331 for (unsigned int i = 0; i < pfs.size(); ++i)
2332 {
2333 PCFGMNODE pPF = NULL; /* /Devices/Dev/.../Config/PortForwarding/$n/ */
2334
2335 uint16_t port = 0;
2336 Utf8Str utf = pfs[i];
2337 Utf8Str strName;
2338 Utf8Str strProto;
2339 Utf8Str strHostPort;
2340 Utf8Str strHostIP;
2341 Utf8Str strGuestPort;
2342 Utf8Str strGuestIP;
2343 size_t pos, ppos;
2344 pos = ppos = 0;
2345#define ITERATE_TO_NEXT_TERM(res, str, pos, ppos) \
2346 { \
2347 pos = str.find(",", ppos); \
2348 if (pos == Utf8Str::npos) \
2349 { \
2350 Log(( #res " extracting from %s is failed\n", str.c_str())); \
2351 continue; \
2352 } \
2353 res = str.substr(ppos, pos - ppos); \
2354 Log2((#res " %s pos:%d, ppos:%d\n", res.c_str(), pos, ppos)); \
2355 ppos = pos + 1; \
2356 } /* no do { ... } while because of 'continue' */
2357 ITERATE_TO_NEXT_TERM(strName, utf, pos, ppos);
2358 ITERATE_TO_NEXT_TERM(strProto, utf, pos, ppos);
2359 ITERATE_TO_NEXT_TERM(strHostIP, utf, pos, ppos);
2360 ITERATE_TO_NEXT_TERM(strHostPort, utf, pos, ppos);
2361 ITERATE_TO_NEXT_TERM(strGuestIP, utf, pos, ppos);
2362 strGuestPort = utf.substr(ppos, utf.length() - ppos);
2363#undef ITERATE_TO_NEXT_TERM
2364
2365 uint32_t proto = strProto.toUInt32();
2366 bool fValid = true;
2367 switch (proto)
2368 {
2369 case NATProtocol_UDP:
2370 strProto = "UDP";
2371 break;
2372 case NATProtocol_TCP:
2373 strProto = "TCP";
2374 break;
2375 default:
2376 fValid = false;
2377 }
2378 /* continue with next rule if no valid proto was passed */
2379 if (!fValid)
2380 continue;
2381
2382 InsertConfigNodeF(pPFTree, &pPF, "%u", i);
2383
2384 if (!strName.isEmpty())
2385 InsertConfigString(pPF, "Name", strName);
2386
2387 InsertConfigString(pPF, "Protocol", strProto);
2388
2389 if (!strHostIP.isEmpty())
2390 InsertConfigString(pPF, "BindIP", strHostIP);
2391
2392 if (!strGuestIP.isEmpty())
2393 InsertConfigString(pPF, "GuestIP", strGuestIP);
2394
2395 port = RTStrToUInt16(strHostPort.c_str());
2396 if (port)
2397 InsertConfigInteger(pPF, "HostPort", port);
2398
2399 port = RTStrToUInt16(strGuestPort.c_str());
2400 if (port)
2401 InsertConfigInteger(pPF, "GuestPort", port);
2402 }
2403 break;
2404 }
2405
2406 case NetworkAttachmentType_Bridged:
2407 {
2408#if (defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)) && !defined(VBOX_WITH_NETFLT)
2409 hrc = i_attachToTapInterface(aNetworkAdapter);
2410 if (FAILED(hrc))
2411 {
2412 switch (hrc)
2413 {
2414 case E_ACCESSDENIED:
2415 return pVMM->pfnVMR3SetError(pUVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
2416 "Failed to open '/dev/net/tun' for read/write access. Please check the "
2417 "permissions of that node. Either run 'chmod 0666 /dev/net/tun' or "
2418 "change the group of that node and make yourself a member of that group. "
2419 "Make sure that these changes are permanent, especially if you are "
2420 "using udev"));
2421 default:
2422 AssertMsgFailed(("Could not attach to host interface! Bad!\n"));
2423 return pVMM->pfnVMR3SetError(pUVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS,
2424 N_("Failed to initialize Host Interface Networking"));
2425 }
2426 }
2427
2428 Assert((intptr_t)maTapFD[uInstance] >= 0);
2429 if ((intptr_t)maTapFD[uInstance] >= 0)
2430 {
2431 InsertConfigString(pLunL0, "Driver", "HostInterface");
2432 InsertConfigNode(pLunL0, "Config", &pCfg);
2433 InsertConfigInteger(pCfg, "FileHandle", (intptr_t)maTapFD[uInstance]);
2434 }
2435
2436#elif defined(VBOX_WITH_NETFLT)
2437 /*
2438 * This is the new VBoxNetFlt+IntNet stuff.
2439 */
2440 Bstr BridgedIfName;
2441 hrc = aNetworkAdapter->COMGETTER(BridgedInterface)(BridgedIfName.asOutParam());
2442 if (FAILED(hrc))
2443 {
2444 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(BridgedInterface) failed, hrc (0x%x)\n", hrc));
2445 H();
2446 }
2447
2448 Utf8Str BridgedIfNameUtf8(BridgedIfName);
2449 const char *pszBridgedIfName = BridgedIfNameUtf8.c_str();
2450
2451 ComPtr<IHostNetworkInterface> hostInterface;
2452 hrc = host->FindHostNetworkInterfaceByName(BridgedIfName.raw(),
2453 hostInterface.asOutParam());
2454 if (!SUCCEEDED(hrc))
2455 {
2456 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: FindByName failed, hrc=%Rhrc (0x%x)\n", hrc, hrc));
2457 return pVMM->pfnVMR3SetError(pUVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
2458 N_("Nonexistent host networking interface, name '%ls'"),
2459 BridgedIfName.raw());
2460 }
2461
2462# if defined(RT_OS_DARWIN)
2463 /* The name is in the format 'ifX: long name', chop it off at the colon. */
2464 char szTrunk[INTNET_MAX_TRUNK_NAME];
2465 RTStrCopy(szTrunk, sizeof(szTrunk), pszBridgedIfName);
2466 char *pszColon = (char *)memchr(szTrunk, ':', sizeof(szTrunk));
2467// Quick fix for @bugref{5633}
2468// if (!pszColon)
2469// {
2470// /*
2471// * Dynamic changing of attachment causes an attempt to configure
2472// * network with invalid host adapter (as it is must be changed before
2473// * the attachment), calling Detach here will cause a deadlock.
2474// * See @bugref{4750}.
2475// * hrc = aNetworkAdapter->Detach(); H();
2476// */
2477// return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
2478// N_("Malformed host interface networking name '%ls'"),
2479// BridgedIfName.raw());
2480// }
2481 if (pszColon)
2482 *pszColon = '\0';
2483 const char *pszTrunk = szTrunk;
2484
2485# elif defined(RT_OS_SOLARIS)
2486 /* The name is in the format 'ifX[:1] - long name, chop it off at space. */
2487 char szTrunk[256];
2488 strlcpy(szTrunk, pszBridgedIfName, sizeof(szTrunk));
2489 char *pszSpace = (char *)memchr(szTrunk, ' ', sizeof(szTrunk));
2490
2491 /*
2492 * Currently don't bother about malformed names here for the sake of people using
2493 * VBoxManage and setting only the NIC name from there. If there is a space we
2494 * chop it off and proceed, otherwise just use whatever we've got.
2495 */
2496 if (pszSpace)
2497 *pszSpace = '\0';
2498
2499 /* Chop it off at the colon (zone naming eg: e1000g:1 we need only the e1000g) */
2500 char *pszColon = (char *)memchr(szTrunk, ':', sizeof(szTrunk));
2501 if (pszColon)
2502 *pszColon = '\0';
2503
2504 const char *pszTrunk = szTrunk;
2505
2506# elif defined(RT_OS_WINDOWS)
2507 HostNetworkInterfaceType_T eIfType;
2508 hrc = hostInterface->COMGETTER(InterfaceType)(&eIfType);
2509 if (FAILED(hrc))
2510 {
2511 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(InterfaceType) failed, hrc (0x%x)\n", hrc));
2512 H();
2513 }
2514
2515 if (eIfType != HostNetworkInterfaceType_Bridged)
2516 return pVMM->pfnVMR3SetError(pUVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
2517 N_("Interface ('%ls') is not a Bridged Adapter interface"),
2518 BridgedIfName.raw());
2519
2520 hrc = hostInterface->COMGETTER(Id)(bstr.asOutParam());
2521 if (FAILED(hrc))
2522 {
2523 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(Id) failed, hrc (0x%x)\n", hrc));
2524 H();
2525 }
2526 Guid hostIFGuid(bstr);
2527
2528 INetCfg *pNc;
2529 ComPtr<INetCfgComponent> pAdaptorComponent;
2530 LPWSTR pszApp;
2531
2532 hrc = VBoxNetCfgWinQueryINetCfg(&pNc, FALSE, L"VirtualBox", 10, &pszApp);
2533 Assert(hrc == S_OK);
2534 if (hrc != S_OK)
2535 {
2536 LogRel(("NetworkAttachmentType_Bridged: Failed to get NetCfg, hrc=%Rhrc (0x%x)\n", hrc, hrc));
2537 H();
2538 }
2539
2540 /* get the adapter's INetCfgComponent*/
2541 hrc = VBoxNetCfgWinGetComponentByGuid(pNc, &GUID_DEVCLASS_NET, (GUID*)hostIFGuid.raw(),
2542 pAdaptorComponent.asOutParam());
2543 if (hrc != S_OK)
2544 {
2545 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
2546 LogRel(("NetworkAttachmentType_Bridged: VBoxNetCfgWinGetComponentByGuid failed, hrc (0x%x)\n", hrc));
2547 H();
2548 }
2549# define VBOX_WIN_BINDNAME_PREFIX "\\DEVICE\\"
2550 char szTrunkName[INTNET_MAX_TRUNK_NAME];
2551 char *pszTrunkName = szTrunkName;
2552 wchar_t * pswzBindName;
2553 hrc = pAdaptorComponent->GetBindName(&pswzBindName);
2554 Assert(hrc == S_OK);
2555 if (hrc == S_OK)
2556 {
2557 int cwBindName = (int)wcslen(pswzBindName) + 1;
2558 int cbFullBindNamePrefix = sizeof(VBOX_WIN_BINDNAME_PREFIX);
2559 if (sizeof(szTrunkName) > cbFullBindNamePrefix + cwBindName)
2560 {
2561 strcpy(szTrunkName, VBOX_WIN_BINDNAME_PREFIX);
2562 pszTrunkName += cbFullBindNamePrefix-1;
2563 if (!WideCharToMultiByte(CP_ACP, 0, pswzBindName, cwBindName, pszTrunkName,
2564 sizeof(szTrunkName) - cbFullBindNamePrefix + 1, NULL, NULL))
2565 {
2566 DWORD err = GetLastError();
2567 hrc = HRESULT_FROM_WIN32(err);
2568 AssertMsgFailed(("hrc=%Rhrc %#x\n", hrc, hrc));
2569 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: WideCharToMultiByte failed, hr=%Rhrc (0x%x) err=%u\n",
2570 hrc, hrc, err));
2571 }
2572 }
2573 else
2574 {
2575 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: insufficient szTrunkName buffer space\n"));
2576 /** @todo set appropriate error code */
2577 hrc = E_FAIL;
2578 }
2579
2580 if (hrc != S_OK)
2581 {
2582 AssertFailed();
2583 CoTaskMemFree(pswzBindName);
2584 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
2585 H();
2586 }
2587
2588 /* we're not freeing the bind name since we'll use it later for detecting wireless*/
2589 }
2590 else
2591 {
2592 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
2593 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: VBoxNetCfgWinGetComponentByGuid failed, hrc (0x%x)",
2594 hrc));
2595 H();
2596 }
2597
2598 const char *pszTrunk = szTrunkName;
2599 /* we're not releasing the INetCfg stuff here since we use it later to figure out whether it is wireless */
2600
2601# elif defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)
2602# if defined(RT_OS_FREEBSD)
2603 /*
2604 * If we bridge to a tap interface open it the `old' direct way.
2605 * This works and performs better than bridging a physical
2606 * interface via the current FreeBSD vboxnetflt implementation.
2607 */
2608 if (!strncmp(pszBridgedIfName, RT_STR_TUPLE("tap"))) {
2609 hrc = i_attachToTapInterface(aNetworkAdapter);
2610 if (FAILED(hrc))
2611 {
2612 switch (hrc)
2613 {
2614 case E_ACCESSDENIED:
2615 return pVMM->pfnVMR3SetError(pUVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
2616 "Failed to open '/dev/%s' for read/write access. Please check the "
2617 "permissions of that node, and that the net.link.tap.user_open "
2618 "sysctl is set. Either run 'chmod 0666 /dev/%s' or change the "
2619 "group of that node to vboxusers and make yourself a member of "
2620 "that group. Make sure that these changes are permanent."),
2621 pszBridgedIfName, pszBridgedIfName);
2622 default:
2623 AssertMsgFailed(("Could not attach to tap interface! Bad!\n"));
2624 return pVMM->pfnVMR3SetError(pUVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS,
2625 N_("Failed to initialize Host Interface Networking"));
2626 }
2627 }
2628
2629 Assert((intptr_t)maTapFD[uInstance] >= 0);
2630 if ((intptr_t)maTapFD[uInstance] >= 0)
2631 {
2632 InsertConfigString(pLunL0, "Driver", "HostInterface");
2633 InsertConfigNode(pLunL0, "Config", &pCfg);
2634 InsertConfigInteger(pCfg, "FileHandle", (intptr_t)maTapFD[uInstance]);
2635 }
2636 break;
2637 }
2638# endif
2639 /** @todo Check for malformed names. */
2640 const char *pszTrunk = pszBridgedIfName;
2641
2642 /* Issue a warning if the interface is down */
2643 {
2644 int iSock = socket(AF_INET, SOCK_DGRAM, 0);
2645 if (iSock >= 0)
2646 {
2647 struct ifreq Req;
2648 RT_ZERO(Req);
2649 RTStrCopy(Req.ifr_name, sizeof(Req.ifr_name), pszBridgedIfName);
2650 if (ioctl(iSock, SIOCGIFFLAGS, &Req) >= 0)
2651 if ((Req.ifr_flags & IFF_UP) == 0)
2652 i_atVMRuntimeErrorCallbackF(0, "BridgedInterfaceDown",
2653 N_("Bridged interface %s is down. Guest will not be able to use this interface"),
2654 pszBridgedIfName);
2655
2656 close(iSock);
2657 }
2658 }
2659
2660# else
2661# error "PORTME (VBOX_WITH_NETFLT)"
2662# endif
2663
2664# if defined(RT_OS_DARWIN) && defined(VBOX_WITH_VMNET)
2665 InsertConfigString(pLunL0, "Driver", "VMNet");
2666 InsertConfigNode(pLunL0, "Config", &pCfg);
2667 InsertConfigString(pCfg, "Trunk", pszTrunk);
2668 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetFlt);
2669# else
2670 InsertConfigString(pLunL0, "Driver", "IntNet");
2671 InsertConfigNode(pLunL0, "Config", &pCfg);
2672 InsertConfigString(pCfg, "Trunk", pszTrunk);
2673 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetFlt);
2674 InsertConfigInteger(pCfg, "IgnoreConnectFailure", (uint64_t)fIgnoreConnectFailure);
2675 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
2676 char szNetwork[INTNET_MAX_NETWORK_NAME];
2677
2678# if defined(RT_OS_SOLARIS) || defined(RT_OS_DARWIN)
2679 /*
2680 * 'pszTrunk' contains just the interface name required in ring-0, while 'pszBridgedIfName' contains
2681 * interface name + optional description. We must not pass any description to the VM as it can differ
2682 * for the same interface name, eg: "nge0 - ethernet" (GUI) vs "nge0" (VBoxManage).
2683 */
2684 RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszTrunk);
2685# else
2686 RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszBridgedIfName);
2687# endif
2688 InsertConfigString(pCfg, "Network", szNetwork);
2689 networkName = Bstr(szNetwork);
2690 trunkName = Bstr(pszTrunk);
2691 trunkType = Bstr(TRUNKTYPE_NETFLT);
2692
2693 BOOL fSharedMacOnWire = false;
2694 hrc = hostInterface->COMGETTER(Wireless)(&fSharedMacOnWire);
2695 if (FAILED(hrc))
2696 {
2697 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(Wireless) failed, hrc (0x%x)\n", hrc));
2698 H();
2699 }
2700 else if (fSharedMacOnWire)
2701 {
2702 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
2703 Log(("Set SharedMacOnWire\n"));
2704 }
2705
2706# if defined(RT_OS_SOLARIS)
2707# if 0 /* bird: this is a bit questionable and might cause more trouble than its worth. */
2708 /* Zone access restriction, don't allow snooping the global zone. */
2709 zoneid_t ZoneId = getzoneid();
2710 if (ZoneId != GLOBAL_ZONEID)
2711 {
2712 InsertConfigInteger(pCfg, "IgnoreAllPromisc", true);
2713 }
2714# endif
2715# endif
2716# endif
2717
2718#elif defined(RT_OS_WINDOWS) /* not defined NetFlt */
2719 /* NOTHING TO DO HERE */
2720#elif defined(RT_OS_LINUX)
2721/// @todo aleksey: is there anything to be done here?
2722#elif defined(RT_OS_FREEBSD)
2723/** @todo FreeBSD: Check out this later (HIF networking). */
2724#else
2725# error "Port me"
2726#endif
2727 break;
2728 }
2729
2730 case NetworkAttachmentType_Internal:
2731 {
2732 hrc = aNetworkAdapter->COMGETTER(InternalNetwork)(bstr.asOutParam()); H();
2733 if (!bstr.isEmpty())
2734 {
2735 InsertConfigString(pLunL0, "Driver", "IntNet");
2736 InsertConfigNode(pLunL0, "Config", &pCfg);
2737 InsertConfigString(pCfg, "Network", bstr);
2738 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_WhateverNone);
2739 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
2740 networkName = bstr;
2741 trunkType = Bstr(TRUNKTYPE_WHATEVER);
2742 }
2743 break;
2744 }
2745
2746 case NetworkAttachmentType_HostOnly:
2747 {
2748 InsertConfigString(pLunL0, "Driver", "IntNet");
2749 InsertConfigNode(pLunL0, "Config", &pCfg);
2750
2751 Bstr HostOnlyName;
2752 hrc = aNetworkAdapter->COMGETTER(HostOnlyInterface)(HostOnlyName.asOutParam());
2753 if (FAILED(hrc))
2754 {
2755 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(HostOnlyInterface) failed, hrc (0x%x)\n", hrc));
2756 H();
2757 }
2758
2759 Utf8Str HostOnlyNameUtf8(HostOnlyName);
2760 const char *pszHostOnlyName = HostOnlyNameUtf8.c_str();
2761#ifdef VBOX_WITH_VMNET
2762 /* Check if the matching host-only network has already been created. */
2763 Bstr bstrLowerIP, bstrUpperIP, bstrNetworkMask;
2764 BstrFmt bstrNetworkName("Legacy %s Network", pszHostOnlyName);
2765 ComPtr<IHostOnlyNetwork> hostOnlyNetwork;
2766 hrc = virtualBox->FindHostOnlyNetworkByName(bstrNetworkName.raw(), hostOnlyNetwork.asOutParam());
2767 if (FAILED(hrc))
2768 {
2769 /*
2770 * With VMNET there is no VBoxNetAdp to create vboxnetX adapters,
2771 * which means that the Host object won't be able to re-create
2772 * them from extra data. Go through existing DHCP/adapter config
2773 * to derive the parameters for the new network.
2774 */
2775 BstrFmt bstrOldNetworkName("HostInterfaceNetworking-%s", pszHostOnlyName);
2776 ComPtr<IDHCPServer> dhcpServer;
2777 hrc = virtualBox->FindDHCPServerByNetworkName(bstrOldNetworkName.raw(),
2778 dhcpServer.asOutParam());
2779 if (SUCCEEDED(hrc))
2780 {
2781 /* There is a DHCP server available for this network. */
2782 hrc = dhcpServer->COMGETTER(LowerIP)(bstrLowerIP.asOutParam());
2783 if (FAILED(hrc))
2784 {
2785 LogRel(("Console::i_configNetwork: COMGETTER(LowerIP) failed, hrc (%Rhrc)\n", hrc));
2786 H();
2787 }
2788 hrc = dhcpServer->COMGETTER(UpperIP)(bstrUpperIP.asOutParam());
2789 if (FAILED(hrc))
2790 {
2791 LogRel(("Console::i_configNetwork: COMGETTER(UpperIP) failed, hrc (%Rhrc)\n", hrc));
2792 H();
2793 }
2794 hrc = dhcpServer->COMGETTER(NetworkMask)(bstrNetworkMask.asOutParam());
2795 if (FAILED(hrc))
2796 {
2797 LogRel(("Console::i_configNetwork: COMGETTER(NetworkMask) failed, hrc (%Rhrc)\n", hrc));
2798 H();
2799 }
2800 }
2801 else
2802 {
2803 /* No DHCP server for this hostonly interface, let's look at extra data */
2804 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPAddress",
2805 pszHostOnlyName).raw(),
2806 bstrLowerIP.asOutParam());
2807 if (SUCCEEDED(hrc) && !bstrLowerIP.isEmpty())
2808 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPNetMask",
2809 pszHostOnlyName).raw(),
2810 bstrNetworkMask.asOutParam());
2811
2812 }
2813 RTNETADDRIPV4 ipAddr, ipMask;
2814 vrc = bstrLowerIP.isEmpty() ? VERR_MISSING : RTNetStrToIPv4Addr(Utf8Str(bstrLowerIP).c_str(), &ipAddr);
2815 if (RT_FAILURE(vrc))
2816 {
2817 /* We failed to locate any valid config of this vboxnetX interface, assume defaults. */
2818 LogRel(("NetworkAttachmentType_HostOnly: Invalid or missing lower IP '%ls', using '%ls' instead.\n",
2819 bstrLowerIP.raw(), getDefaultIPv4Address(Bstr(pszHostOnlyName)).raw()));
2820 bstrLowerIP = getDefaultIPv4Address(Bstr(pszHostOnlyName));
2821 bstrNetworkMask.setNull();
2822 bstrUpperIP.setNull();
2823 vrc = RTNetStrToIPv4Addr(Utf8Str(bstrLowerIP).c_str(), &ipAddr);
2824 AssertLogRelMsgReturn(RT_SUCCESS(vrc), ("RTNetStrToIPv4Addr(%ls) failed, vrc=%Rrc\n", bstrLowerIP.raw(), vrc),
2825 VERR_MAIN_CONFIG_CONSTRUCTOR_COM_ERROR);
2826 }
2827 vrc = bstrNetworkMask.isEmpty() ? VERR_MISSING : RTNetStrToIPv4Addr(Utf8Str(bstrNetworkMask).c_str(), &ipMask);
2828 if (RT_FAILURE(vrc))
2829 {
2830 LogRel(("NetworkAttachmentType_HostOnly: Invalid or missing network mask '%ls', using '%s' instead.\n",
2831 bstrNetworkMask.raw(), VBOXNET_IPV4MASK_DEFAULT));
2832 bstrNetworkMask = VBOXNET_IPV4MASK_DEFAULT;
2833 vrc = RTNetStrToIPv4Addr(Utf8Str(bstrNetworkMask).c_str(), &ipMask);
2834 AssertLogRelMsgReturn(RT_SUCCESS(vrc), ("RTNetStrToIPv4Addr(%ls) failed, vrc=%Rrc\n", bstrNetworkMask.raw(), vrc),
2835 VERR_MAIN_CONFIG_CONSTRUCTOR_COM_ERROR);
2836 }
2837 vrc = bstrUpperIP.isEmpty() ? VERR_MISSING : RTNetStrToIPv4Addr(Utf8Str(bstrUpperIP).c_str(), &ipAddr);
2838 if (RT_FAILURE(vrc))
2839 {
2840 ipAddr.au32[0] = RT_H2N_U32((RT_N2H_U32(ipAddr.au32[0]) | ~RT_N2H_U32(ipMask.au32[0])) - 1); /* Do we need to exlude the last IP? */
2841 LogRel(("NetworkAttachmentType_HostOnly: Invalid or missing upper IP '%ls', using '%RTnaipv4' instead.\n",
2842 bstrUpperIP.raw(), ipAddr));
2843 bstrUpperIP = BstrFmt("%RTnaipv4", ipAddr);
2844 }
2845
2846 /* All parameters are set, create the new network. */
2847 hrc = virtualBox->CreateHostOnlyNetwork(bstrNetworkName.raw(), hostOnlyNetwork.asOutParam());
2848 if (FAILED(hrc))
2849 {
2850 LogRel(("NetworkAttachmentType_HostOnly: failed to create host-only network, hrc (0x%x)\n", hrc));
2851 H();
2852 }
2853 hrc = hostOnlyNetwork->COMSETTER(NetworkMask)(bstrNetworkMask.raw());
2854 if (FAILED(hrc))
2855 {
2856 LogRel(("NetworkAttachmentType_HostOnly: COMSETTER(NetworkMask) failed, hrc (0x%x)\n", hrc));
2857 H();
2858 }
2859 hrc = hostOnlyNetwork->COMSETTER(LowerIP)(bstrLowerIP.raw());
2860 if (FAILED(hrc))
2861 {
2862 LogRel(("NetworkAttachmentType_HostOnly: COMSETTER(LowerIP) failed, hrc (0x%x)\n", hrc));
2863 H();
2864 }
2865 hrc = hostOnlyNetwork->COMSETTER(UpperIP)(bstrUpperIP.raw());
2866 if (FAILED(hrc))
2867 {
2868 LogRel(("NetworkAttachmentType_HostOnly: COMSETTER(UpperIP) failed, hrc (0x%x)\n", hrc));
2869 H();
2870 }
2871 LogRel(("Console: created host-only network '%ls' with mask '%ls' and range '%ls'-'%ls'\n",
2872 bstrNetworkName.raw(), bstrNetworkMask.raw(), bstrLowerIP.raw(), bstrUpperIP.raw()));
2873 }
2874 else
2875 {
2876 /* The matching host-only network already exists. Tell the user to switch to it. */
2877 hrc = hostOnlyNetwork->COMGETTER(NetworkMask)(bstrNetworkMask.asOutParam());
2878 if (FAILED(hrc))
2879 {
2880 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(NetworkMask) failed, hrc (0x%x)\n", hrc));
2881 H();
2882 }
2883 hrc = hostOnlyNetwork->COMGETTER(LowerIP)(bstrLowerIP.asOutParam());
2884 if (FAILED(hrc))
2885 {
2886 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(LowerIP) failed, hrc (0x%x)\n", hrc));
2887 H();
2888 }
2889 hrc = hostOnlyNetwork->COMGETTER(UpperIP)(bstrUpperIP.asOutParam());
2890 if (FAILED(hrc))
2891 {
2892 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(UpperIP) failed, hrc (0x%x)\n", hrc));
2893 H();
2894 }
2895 }
2896 return pVMM->pfnVMR3SetError(pUVM, VERR_NOT_FOUND, RT_SRC_POS,
2897 N_("Host-only adapters are no longer supported!\n"
2898 "For your convenience a host-only network named '%ls' has been "
2899 "created with network mask '%ls' and IP address range '%ls' - '%ls'.\n"
2900 "To fix this problem, switch to 'Host-only Network' "
2901 "attachment type in the VM settings.\n"),
2902 bstrNetworkName.raw(), bstrNetworkMask.raw(),
2903 bstrLowerIP.raw(), bstrUpperIP.raw());
2904#endif /* VBOX_WITH_VMNET */
2905 ComPtr<IHostNetworkInterface> hostInterface;
2906 hrc = host->FindHostNetworkInterfaceByName(HostOnlyName.raw(),
2907 hostInterface.asOutParam());
2908 if (!SUCCEEDED(hrc))
2909 {
2910 LogRel(("NetworkAttachmentType_HostOnly: FindByName failed, vrc=%Rrc\n", vrc));
2911 return pVMM->pfnVMR3SetError(pUVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
2912 N_("Nonexistent host networking interface, name '%ls'"), HostOnlyName.raw());
2913 }
2914
2915 char szNetwork[INTNET_MAX_NETWORK_NAME];
2916 RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszHostOnlyName);
2917
2918#if defined(RT_OS_WINDOWS)
2919# ifndef VBOX_WITH_NETFLT
2920 hrc = E_NOTIMPL;
2921 LogRel(("NetworkAttachmentType_HostOnly: Not Implemented\n"));
2922 H();
2923# else /* defined VBOX_WITH_NETFLT*/
2924 /** @todo r=bird: Put this in a function. */
2925
2926 HostNetworkInterfaceType_T eIfType;
2927 hrc = hostInterface->COMGETTER(InterfaceType)(&eIfType);
2928 if (FAILED(hrc))
2929 {
2930 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(InterfaceType) failed, hrc (0x%x)\n", hrc));
2931 H();
2932 }
2933
2934 if (eIfType != HostNetworkInterfaceType_HostOnly)
2935 return pVMM->pfnVMR3SetError(pUVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
2936 N_("Interface ('%ls') is not a Host-Only Adapter interface"),
2937 HostOnlyName.raw());
2938
2939 hrc = hostInterface->COMGETTER(Id)(bstr.asOutParam());
2940 if (FAILED(hrc))
2941 {
2942 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(Id) failed, hrc (0x%x)\n", hrc));
2943 H();
2944 }
2945 Guid hostIFGuid(bstr);
2946
2947 INetCfg *pNc;
2948 ComPtr<INetCfgComponent> pAdaptorComponent;
2949 LPWSTR pszApp;
2950 hrc = VBoxNetCfgWinQueryINetCfg(&pNc, FALSE, L"VirtualBox", 10, &pszApp);
2951 Assert(hrc == S_OK);
2952 if (hrc != S_OK)
2953 {
2954 LogRel(("NetworkAttachmentType_HostOnly: Failed to get NetCfg, hrc=%Rhrc (0x%x)\n", hrc, hrc));
2955 H();
2956 }
2957
2958 /* get the adapter's INetCfgComponent*/
2959 hrc = VBoxNetCfgWinGetComponentByGuid(pNc, &GUID_DEVCLASS_NET, (GUID*)hostIFGuid.raw(),
2960 pAdaptorComponent.asOutParam());
2961 if (hrc != S_OK)
2962 {
2963 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
2964 LogRel(("NetworkAttachmentType_HostOnly: VBoxNetCfgWinGetComponentByGuid failed, hrc=%Rhrc (0x%x)\n", hrc, hrc));
2965 H();
2966 }
2967# define VBOX_WIN_BINDNAME_PREFIX "\\DEVICE\\"
2968 char szTrunkName[INTNET_MAX_TRUNK_NAME];
2969 bool fNdis6 = false;
2970 wchar_t * pwszHelpText;
2971 hrc = pAdaptorComponent->GetHelpText(&pwszHelpText);
2972 Assert(hrc == S_OK);
2973 if (hrc == S_OK)
2974 {
2975 Log(("help-text=%ls\n", pwszHelpText));
2976 if (!wcscmp(pwszHelpText, L"VirtualBox NDIS 6.0 Miniport Driver"))
2977 fNdis6 = true;
2978 CoTaskMemFree(pwszHelpText);
2979 }
2980 if (fNdis6)
2981 {
2982 strncpy(szTrunkName, pszHostOnlyName, sizeof(szTrunkName) - 1);
2983 Log(("trunk=%s\n", szTrunkName));
2984 }
2985 else
2986 {
2987 char *pszTrunkName = szTrunkName;
2988 wchar_t * pswzBindName;
2989 hrc = pAdaptorComponent->GetBindName(&pswzBindName);
2990 Assert(hrc == S_OK);
2991 if (hrc == S_OK)
2992 {
2993 int cwBindName = (int)wcslen(pswzBindName) + 1;
2994 int cbFullBindNamePrefix = sizeof(VBOX_WIN_BINDNAME_PREFIX);
2995 if (sizeof(szTrunkName) > cbFullBindNamePrefix + cwBindName)
2996 {
2997 strcpy(szTrunkName, VBOX_WIN_BINDNAME_PREFIX);
2998 pszTrunkName += cbFullBindNamePrefix-1;
2999 if (!WideCharToMultiByte(CP_ACP, 0, pswzBindName, cwBindName, pszTrunkName,
3000 sizeof(szTrunkName) - cbFullBindNamePrefix + 1, NULL, NULL))
3001 {
3002 DWORD err = GetLastError();
3003 hrc = HRESULT_FROM_WIN32(err);
3004 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: WideCharToMultiByte failed, hr=%Rhrc (0x%x) err=%u\n",
3005 hrc, hrc, err));
3006 }
3007 }
3008 else
3009 {
3010 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: insufficient szTrunkName buffer space\n"));
3011 /** @todo set appropriate error code */
3012 hrc = E_FAIL;
3013 }
3014
3015 if (hrc != S_OK)
3016 {
3017 AssertFailed();
3018 CoTaskMemFree(pswzBindName);
3019 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
3020 H();
3021 }
3022 }
3023 else
3024 {
3025 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
3026 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: VBoxNetCfgWinGetComponentByGuid failed, hrc=%Rhrc (0x%x)\n",
3027 hrc, hrc));
3028 H();
3029 }
3030
3031
3032 CoTaskMemFree(pswzBindName);
3033 }
3034
3035 trunkType = TRUNKTYPE_NETADP;
3036 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetAdp);
3037
3038 pAdaptorComponent.setNull();
3039 /* release the pNc finally */
3040 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
3041
3042 const char *pszTrunk = szTrunkName;
3043
3044 InsertConfigString(pCfg, "Trunk", pszTrunk);
3045 InsertConfigString(pCfg, "Network", szNetwork);
3046 InsertConfigInteger(pCfg, "IgnoreConnectFailure", (uint64_t)fIgnoreConnectFailure); /** @todo why is this
3047 windows only?? */
3048 networkName = Bstr(szNetwork);
3049 trunkName = Bstr(pszTrunk);
3050# endif /* defined VBOX_WITH_NETFLT*/
3051#elif defined(RT_OS_DARWIN)
3052 InsertConfigString(pCfg, "Trunk", pszHostOnlyName);
3053 InsertConfigString(pCfg, "Network", szNetwork);
3054 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetAdp);
3055 networkName = Bstr(szNetwork);
3056 trunkName = Bstr(pszHostOnlyName);
3057 trunkType = TRUNKTYPE_NETADP;
3058#else
3059 InsertConfigString(pCfg, "Trunk", pszHostOnlyName);
3060 InsertConfigString(pCfg, "Network", szNetwork);
3061 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetFlt);
3062 networkName = Bstr(szNetwork);
3063 trunkName = Bstr(pszHostOnlyName);
3064 trunkType = TRUNKTYPE_NETFLT;
3065#endif
3066 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
3067
3068#if !defined(RT_OS_WINDOWS) && defined(VBOX_WITH_NETFLT)
3069
3070 Bstr tmpAddr, tmpMask;
3071
3072 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPAddress",
3073 pszHostOnlyName).raw(),
3074 tmpAddr.asOutParam());
3075 if (SUCCEEDED(hrc) && !tmpAddr.isEmpty())
3076 {
3077 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPNetMask",
3078 pszHostOnlyName).raw(),
3079 tmpMask.asOutParam());
3080 if (SUCCEEDED(hrc) && !tmpMask.isEmpty())
3081 hrc = hostInterface->EnableStaticIPConfig(tmpAddr.raw(),
3082 tmpMask.raw());
3083 else
3084 hrc = hostInterface->EnableStaticIPConfig(tmpAddr.raw(),
3085 Bstr(VBOXNET_IPV4MASK_DEFAULT).raw());
3086 }
3087 else
3088 {
3089 /* Grab the IP number from the 'vboxnetX' instance number (see netif.h) */
3090 hrc = hostInterface->EnableStaticIPConfig(getDefaultIPv4Address(Bstr(pszHostOnlyName)).raw(),
3091 Bstr(VBOXNET_IPV4MASK_DEFAULT).raw());
3092 }
3093
3094 ComAssertComRC(hrc); /** @todo r=bird: Why this isn't fatal? (H()) */
3095
3096 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPV6Address",
3097 pszHostOnlyName).raw(),
3098 tmpAddr.asOutParam());
3099 if (SUCCEEDED(hrc))
3100 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPV6NetMask", pszHostOnlyName).raw(),
3101 tmpMask.asOutParam());
3102 if (SUCCEEDED(hrc) && !tmpAddr.isEmpty() && !tmpMask.isEmpty())
3103 {
3104 hrc = hostInterface->EnableStaticIPConfigV6(tmpAddr.raw(),
3105 Utf8Str(tmpMask).toUInt32());
3106 ComAssertComRC(hrc); /** @todo r=bird: Why this isn't fatal? (H()) */
3107 }
3108#endif
3109 break;
3110 }
3111
3112 case NetworkAttachmentType_Generic:
3113 {
3114 hrc = aNetworkAdapter->COMGETTER(GenericDriver)(bstr.asOutParam()); H();
3115 SafeArray<BSTR> names;
3116 SafeArray<BSTR> values;
3117 hrc = aNetworkAdapter->GetProperties(Bstr().raw(),
3118 ComSafeArrayAsOutParam(names),
3119 ComSafeArrayAsOutParam(values)); H();
3120
3121 InsertConfigString(pLunL0, "Driver", bstr);
3122 InsertConfigNode(pLunL0, "Config", &pCfg);
3123 for (size_t ii = 0; ii < names.size(); ++ii)
3124 {
3125 if (values[ii] && *values[ii])
3126 {
3127 Utf8Str const strName(names[ii]);
3128 Utf8Str const strValue(values[ii]);
3129 InsertConfigString(pCfg, strName.c_str(), strValue);
3130 }
3131 }
3132 break;
3133 }
3134
3135 case NetworkAttachmentType_NATNetwork:
3136 {
3137 hrc = aNetworkAdapter->COMGETTER(NATNetwork)(bstr.asOutParam()); H();
3138 if (!bstr.isEmpty())
3139 {
3140 /** @todo add intnet prefix to separate namespaces, and add trunk if dealing with vboxnatX */
3141 InsertConfigString(pLunL0, "Driver", "IntNet");
3142 InsertConfigNode(pLunL0, "Config", &pCfg);
3143 InsertConfigString(pCfg, "Network", bstr);
3144 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_WhateverNone);
3145 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
3146 networkName = bstr;
3147 trunkType = Bstr(TRUNKTYPE_WHATEVER);
3148 }
3149 break;
3150 }
3151
3152#ifdef VBOX_WITH_CLOUD_NET
3153 case NetworkAttachmentType_Cloud:
3154 {
3155 static const char *s_pszCloudExtPackName = "Oracle VM VirtualBox Extension Pack";
3156 /*
3157 * Cloud network attachments do not work wihout installed extpack.
3158 * Without extpack support they won't work either.
3159 */
3160# ifdef VBOX_WITH_EXTPACK
3161 if (!mptrExtPackManager->i_isExtPackUsable(s_pszCloudExtPackName))
3162# endif
3163 {
3164 return pVMM->pfnVMR3SetError(pUVM, VERR_NOT_FOUND, RT_SRC_POS,
3165 N_("Implementation of the cloud network attachment not found!\n"
3166 "To fix this problem, either install the '%s' or switch to "
3167 "another network attachment type in the VM settings."),
3168 s_pszCloudExtPackName);
3169 }
3170
3171 ComPtr<ICloudNetwork> network;
3172 hrc = aNetworkAdapter->COMGETTER(CloudNetwork)(bstr.asOutParam()); H();
3173 hrc = pMachine->COMGETTER(Name)(mGateway.mTargetVM.asOutParam()); H();
3174 hrc = virtualBox->FindCloudNetworkByName(bstr.raw(), network.asOutParam()); H();
3175 hrc = generateKeys(mGateway);
3176 if (FAILED(hrc))
3177 {
3178 if (hrc == E_NOTIMPL)
3179 return pVMM->pfnVMR3SetError(pUVM, VERR_NOT_FOUND, RT_SRC_POS,
3180 N_("Failed to generate a key pair due to missing libssh\n"
3181 "To fix this problem, either build VirtualBox with libssh "
3182 "support or switch to another network attachment type in "
3183 "the VM settings."));
3184 return pVMM->pfnVMR3SetError(pUVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
3185 N_("Failed to generate a key pair due to libssh error!"));
3186 }
3187 hrc = startCloudGateway(virtualBox, network, mGateway);
3188 if (FAILED(hrc))
3189 {
3190 if (hrc == VBOX_E_OBJECT_NOT_FOUND)
3191 return pVMM->pfnVMR3SetError(pUVM, hrc, RT_SRC_POS,
3192 N_("Failed to start cloud gateway instance.\nCould not find suitable "
3193 "standard cloud images. Make sure you ran 'VBoxManage cloud network setup' "
3194 "with correct '--gateway-os-name' and '--gateway-os-version' parameters. "
3195 "Check VBoxSVC.log for actual values used to look up cloud images."));
3196 return pVMM->pfnVMR3SetError(pUVM, hrc, RT_SRC_POS,
3197 N_("Failed to start cloud gateway instance.\nMake sure you set up "
3198 "cloud networking properly with 'VBoxManage cloud network setup'. "
3199 "Check VBoxSVC.log for details."));
3200 }
3201 InsertConfigBytes(pDevCfg, "MAC", &mGateway.mCloudMacAddress, sizeof(mGateway.mCloudMacAddress));
3202 if (!bstr.isEmpty())
3203 {
3204 InsertConfigString(pLunL0, "Driver", "CloudTunnel");
3205 InsertConfigNode(pLunL0, "Config", &pCfg);
3206 InsertConfigPassword(pCfg, "SshKey", mGateway.mPrivateSshKey);
3207 InsertConfigString(pCfg, "PrimaryIP", mGateway.mCloudPublicIp);
3208 InsertConfigString(pCfg, "SecondaryIP", mGateway.mCloudSecondaryPublicIp);
3209 InsertConfigBytes(pCfg, "TargetMAC", &mGateway.mLocalMacAddress, sizeof(mGateway.mLocalMacAddress));
3210 hrc = i_configProxy(virtualBox, pCfg, "Primary", mGateway.mCloudPublicIp);
3211 if (FAILED(hrc))
3212 {
3213 return pVMM->pfnVMR3SetError(pUVM, hrc, RT_SRC_POS,
3214 N_("Failed to configure proxy for accessing cloud gateway instance via primary VNIC.\n"
3215 "Check VirtualBox.log for details."));
3216 }
3217 hrc = i_configProxy(virtualBox, pCfg, "Secondary", mGateway.mCloudSecondaryPublicIp);
3218 if (FAILED(hrc))
3219 {
3220 return pVMM->pfnVMR3SetError(pUVM, hrc, RT_SRC_POS,
3221 N_("Failed to configure proxy for accessing cloud gateway instance via secondary VNIC.\n"
3222 "Check VirtualBox.log for details."));
3223 }
3224 networkName = bstr;
3225 trunkType = Bstr(TRUNKTYPE_WHATEVER);
3226 }
3227 break;
3228 }
3229#endif /* VBOX_WITH_CLOUD_NET */
3230
3231#ifdef VBOX_WITH_VMNET
3232 case NetworkAttachmentType_HostOnlyNetwork:
3233 {
3234 Bstr bstrId, bstrNetMask, bstrLowerIP, bstrUpperIP;
3235 ComPtr<IHostOnlyNetwork> network;
3236 hrc = aNetworkAdapter->COMGETTER(HostOnlyNetwork)(bstr.asOutParam()); H();
3237 hrc = virtualBox->FindHostOnlyNetworkByName(bstr.raw(), network.asOutParam());
3238 if (FAILED(hrc))
3239 {
3240 LogRel(("NetworkAttachmentType_HostOnlyNetwork: FindByName failed, hrc (0x%x)\n", hrc));
3241 return pVMM->pfnVMR3SetError(pUVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
3242 N_("Nonexistent host-only network '%ls'"), bstr.raw());
3243 }
3244 hrc = network->COMGETTER(Id)(bstrId.asOutParam()); H();
3245 hrc = network->COMGETTER(NetworkMask)(bstrNetMask.asOutParam()); H();
3246 hrc = network->COMGETTER(LowerIP)(bstrLowerIP.asOutParam()); H();
3247 hrc = network->COMGETTER(UpperIP)(bstrUpperIP.asOutParam()); H();
3248 if (!bstr.isEmpty())
3249 {
3250 InsertConfigString(pLunL0, "Driver", "VMNet");
3251 InsertConfigNode(pLunL0, "Config", &pCfg);
3252 // InsertConfigString(pCfg, "Trunk", bstr);
3253 // InsertConfigStringF(pCfg, "Network", "HostOnlyNetworking-%ls", bstr.raw());
3254 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetAdp);
3255 InsertConfigString(pCfg, "Id", bstrId);
3256 InsertConfigString(pCfg, "NetworkMask", bstrNetMask);
3257 InsertConfigString(pCfg, "LowerIP", bstrLowerIP);
3258 InsertConfigString(pCfg, "UpperIP", bstrUpperIP);
3259 // InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
3260 networkName.setNull(); // We do not want DHCP server on our network!
3261 // trunkType = Bstr(TRUNKTYPE_WHATEVER);
3262 }
3263 break;
3264 }
3265#endif /* VBOX_WITH_VMNET */
3266
3267 default:
3268 AssertMsgFailed(("should not get here!\n"));
3269 break;
3270 }
3271
3272 /*
3273 * Attempt to attach the driver.
3274 */
3275 switch (eAttachmentType)
3276 {
3277 case NetworkAttachmentType_Null:
3278 break;
3279
3280 case NetworkAttachmentType_Bridged:
3281 case NetworkAttachmentType_Internal:
3282 case NetworkAttachmentType_HostOnly:
3283#ifdef VBOX_WITH_VMNET
3284 case NetworkAttachmentType_HostOnlyNetwork:
3285#endif /* VBOX_WITH_VMNET */
3286 case NetworkAttachmentType_NAT:
3287 case NetworkAttachmentType_Generic:
3288 case NetworkAttachmentType_NATNetwork:
3289#ifdef VBOX_WITH_CLOUD_NET
3290 case NetworkAttachmentType_Cloud:
3291#endif /* VBOX_WITH_CLOUD_NET */
3292 {
3293 if (SUCCEEDED(hrc) && RT_SUCCESS(vrc))
3294 {
3295 if (fAttachDetach)
3296 {
3297 vrc = pVMM->pfnPDMR3DriverAttach(mpUVM, pszDevice, uInstance, uLun, 0 /*fFlags*/, NULL /* ppBase */);
3298 //AssertRC(vrc);
3299 }
3300
3301 {
3302 /** @todo pritesh: get the dhcp server name from the
3303 * previous network configuration and then stop the server
3304 * else it may conflict with the dhcp server running with
3305 * the current attachment type
3306 */
3307 /* Stop the hostonly DHCP Server */
3308 }
3309
3310 /*
3311 * NAT networks start their DHCP server theirself, see NATNetwork::Start()
3312 */
3313 if ( !networkName.isEmpty()
3314 && eAttachmentType != NetworkAttachmentType_NATNetwork)
3315 {
3316 /*
3317 * Until we implement service reference counters DHCP Server will be stopped
3318 * by DHCPServerRunner destructor.
3319 */
3320 ComPtr<IDHCPServer> dhcpServer;
3321 hrc = virtualBox->FindDHCPServerByNetworkName(networkName.raw(), dhcpServer.asOutParam());
3322 if (SUCCEEDED(hrc))
3323 {
3324 /* there is a DHCP server available for this network */
3325 BOOL fEnabledDhcp;
3326 hrc = dhcpServer->COMGETTER(Enabled)(&fEnabledDhcp);
3327 if (FAILED(hrc))
3328 {
3329 LogRel(("DHCP svr: COMGETTER(Enabled) failed, hrc (%Rhrc)\n", hrc));
3330 H();
3331 }
3332
3333 if (fEnabledDhcp)
3334 hrc = dhcpServer->Start(trunkName.raw(), trunkType.raw());
3335 }
3336 else
3337 hrc = S_OK;
3338 }
3339 }
3340
3341 break;
3342 }
3343
3344 default:
3345 AssertMsgFailed(("should not get here!\n"));
3346 break;
3347 }
3348
3349 meAttachmentType[uInstance] = eAttachmentType;
3350 }
3351 catch (ConfigError &x)
3352 {
3353 // InsertConfig threw something:
3354 return x.m_vrc;
3355 }
3356
3357#undef H
3358
3359 return VINF_SUCCESS;
3360}
3361
3362
3363/**
3364 * Configures the serial port at the given CFGM node with the supplied parameters.
3365 *
3366 * @returns VBox status code.
3367 * @param pInst The instance CFGM node.
3368 * @param ePortMode The port mode to sue.
3369 * @param pszPath The serial port path.
3370 * @param fServer Flag whether the port should act as a server
3371 * for the pipe and TCP mode or connect as a client.
3372 */
3373int Console::i_configSerialPort(PCFGMNODE pInst, PortMode_T ePortMode, const char *pszPath, bool fServer)
3374{
3375 PCFGMNODE pLunL0 = NULL; /* /Devices/Dev/0/LUN#0/ */
3376 PCFGMNODE pLunL1 = NULL; /* /Devices/Dev/0/LUN#0/AttachedDriver/ */
3377 PCFGMNODE pLunL1Cfg = NULL; /* /Devices/Dev/0/LUN#0/AttachedDriver/Config */
3378
3379 try
3380 {
3381 InsertConfigNode(pInst, "LUN#0", &pLunL0);
3382 if (ePortMode == PortMode_HostPipe)
3383 {
3384 InsertConfigString(pLunL0, "Driver", "Char");
3385 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
3386 InsertConfigString(pLunL1, "Driver", "NamedPipe");
3387 InsertConfigNode(pLunL1, "Config", &pLunL1Cfg);
3388 InsertConfigString(pLunL1Cfg, "Location", pszPath);
3389 InsertConfigInteger(pLunL1Cfg, "IsServer", fServer);
3390 }
3391 else if (ePortMode == PortMode_HostDevice)
3392 {
3393 InsertConfigString(pLunL0, "Driver", "Host Serial");
3394 InsertConfigNode(pLunL0, "Config", &pLunL1);
3395 InsertConfigString(pLunL1, "DevicePath", pszPath);
3396 }
3397 else if (ePortMode == PortMode_TCP)
3398 {
3399 InsertConfigString(pLunL0, "Driver", "Char");
3400 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
3401 InsertConfigString(pLunL1, "Driver", "TCP");
3402 InsertConfigNode(pLunL1, "Config", &pLunL1Cfg);
3403 InsertConfigString(pLunL1Cfg, "Location", pszPath);
3404 InsertConfigInteger(pLunL1Cfg, "IsServer", fServer);
3405 }
3406 else if (ePortMode == PortMode_RawFile)
3407 {
3408 InsertConfigString(pLunL0, "Driver", "Char");
3409 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
3410 InsertConfigString(pLunL1, "Driver", "RawFile");
3411 InsertConfigNode(pLunL1, "Config", &pLunL1Cfg);
3412 InsertConfigString(pLunL1Cfg, "Location", pszPath);
3413 }
3414 }
3415 catch (ConfigError &x)
3416 {
3417 /* InsertConfig threw something */
3418 return x.m_vrc;
3419 }
3420
3421 return VINF_SUCCESS;
3422}
3423
3424
3425#define H() AssertLogRelMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_MAIN_CONFIG_CONSTRUCTOR_COM_ERROR)
3426#define VRC() AssertLogRelMsgReturn(RT_SUCCESS(vrc), ("vrc=%Rrc\n", vrc), vrc)
3427
3428int Console::i_configAudioCtrl(ComPtr<IVirtualBox> pVBox, ComPtr<IMachine> pMachine, BusAssignmentManager *pBusMgr, PCFGMNODE pDevices,
3429 bool fOsXGuest, bool *pfAudioEnabled)
3430{
3431 Utf8Str strTmp;
3432 PCFGMNODE pDev = NULL; /* /Devices/Dev/ */
3433 PCFGMNODE pInst = NULL; /* /Devices/Dev/0/ */
3434 PCFGMNODE pCfg = NULL; /* /Devices/Dev/.../Config/ */
3435 PCFGMNODE pLunL0 = NULL; /* /Devices/Dev/0/LUN#0/ */
3436
3437 /*
3438 * AC'97 ICH / SoundBlaster16 audio / Intel HD Audio.
3439 */
3440 ComPtr<IAudioSettings> audioSettings;
3441 HRESULT hrc = pMachine->COMGETTER(AudioSettings)(audioSettings.asOutParam()); H();
3442
3443 BOOL fAudioEnabled = FALSE;
3444 ComPtr<IAudioAdapter> audioAdapter;
3445 hrc = audioSettings->COMGETTER(Adapter)(audioAdapter.asOutParam()); H();
3446 if (audioAdapter)
3447 {
3448 hrc = audioAdapter->COMGETTER(Enabled)(&fAudioEnabled); H();
3449 }
3450
3451 if (fAudioEnabled)
3452 {
3453 *pfAudioEnabled = true;
3454
3455 AudioControllerType_T enmAudioController;
3456 hrc = audioAdapter->COMGETTER(AudioController)(&enmAudioController); H();
3457 AudioCodecType_T enmAudioCodec;
3458 hrc = audioAdapter->COMGETTER(AudioCodec)(&enmAudioCodec); H();
3459
3460 GetExtraDataBoth(pVBox, pMachine, "VBoxInternal2/Audio/Device/TimerHz", &strTmp);
3461 const uint64_t uTimerHz = strTmp.toUInt64();
3462
3463 GetExtraDataBoth(pVBox, pMachine, "VBoxInternal2/Audio/Device/BufSizeInMs", &strTmp);
3464 const uint64_t uBufSizeInMs = strTmp.toUInt64();
3465
3466 GetExtraDataBoth(pVBox, pMachine, "VBoxInternal2/Audio/Device/BufSizeOutMs", &strTmp);
3467 const uint64_t uBufSizeOutMs = strTmp.toUInt64();
3468
3469 GetExtraDataBoth(pVBox, pMachine, "VBoxInternal2/Audio/Debug/Enabled", &strTmp);
3470 const bool fDebugEnabled = strTmp.equalsIgnoreCase("true") || strTmp.equalsIgnoreCase("1");
3471
3472 GetExtraDataBoth(pVBox, pMachine, "VBoxInternal2/Audio/Debug/Level", &strTmp);
3473 const uint32_t uDebugLevel = strTmp.toUInt32();
3474
3475 Utf8Str strDebugPathOut;
3476 GetExtraDataBoth(pVBox, pMachine, "VBoxInternal2/Audio/Debug/PathOut", &strDebugPathOut);
3477
3478#ifdef VBOX_WITH_AUDIO_VALIDATIONKIT
3479 GetExtraDataBoth(pVBox, pMachine, "VBoxInternal2/Audio/VaKit/Enabled", &strTmp); /* Deprecated; do not use! */
3480 if (strTmp.isEmpty())
3481 GetExtraDataBoth(pVBox, pMachine, "VBoxInternal2/Audio/ValKit/Enabled", &strTmp);
3482 /* Whether the Validation Kit audio backend runs as the primary backend.
3483 * Can also be used with VBox release builds. */
3484 const bool fValKitEnabled = strTmp.equalsIgnoreCase("true") || strTmp.equalsIgnoreCase("1");
3485#endif
3486 /** @todo Implement an audio device class, similar to the audio backend class, to construct the common stuff
3487 * without duplicating (more) code. */
3488
3489 const char *pszAudioDevice;
3490 switch (enmAudioController)
3491 {
3492 case AudioControllerType_AC97:
3493 {
3494 /* ICH AC'97. */
3495 pszAudioDevice = "ichac97";
3496
3497 InsertConfigNode(pDevices, pszAudioDevice, &pDev);
3498 InsertConfigNode(pDev, "0", &pInst);
3499 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
3500 hrc = pBusMgr->assignPCIDevice(pszAudioDevice, pInst); H();
3501 InsertConfigNode(pInst, "Config", &pCfg);
3502 switch (enmAudioCodec)
3503 {
3504 case AudioCodecType_STAC9700:
3505 InsertConfigString(pCfg, "Codec", "STAC9700");
3506 break;
3507 case AudioCodecType_AD1980:
3508 InsertConfigString(pCfg, "Codec", "AD1980");
3509 break;
3510 default: AssertFailedBreak();
3511 }
3512 if (uTimerHz)
3513 InsertConfigInteger(pCfg, "TimerHz", uTimerHz);
3514 if (uBufSizeInMs)
3515 InsertConfigInteger(pCfg, "BufSizeInMs", uBufSizeInMs);
3516 if (uBufSizeOutMs)
3517 InsertConfigInteger(pCfg, "BufSizeOutMs", uBufSizeOutMs);
3518 InsertConfigInteger(pCfg, "DebugEnabled", fDebugEnabled);
3519 if (strDebugPathOut.isNotEmpty())
3520 InsertConfigString(pCfg, "DebugPathOut", strDebugPathOut);
3521 break;
3522 }
3523 case AudioControllerType_SB16:
3524 {
3525 /* Legacy SoundBlaster16. */
3526 pszAudioDevice = "sb16";
3527
3528 InsertConfigNode(pDevices, pszAudioDevice, &pDev);
3529 InsertConfigNode(pDev, "0", &pInst);
3530 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
3531 InsertConfigNode(pInst, "Config", &pCfg);
3532 InsertConfigInteger(pCfg, "IRQ", 5);
3533 InsertConfigInteger(pCfg, "DMA", 1);
3534 InsertConfigInteger(pCfg, "DMA16", 5);
3535 InsertConfigInteger(pCfg, "Port", 0x220);
3536 InsertConfigInteger(pCfg, "Version", 0x0405);
3537 if (uTimerHz)
3538 InsertConfigInteger(pCfg, "TimerHz", uTimerHz);
3539 InsertConfigInteger(pCfg, "DebugEnabled", fDebugEnabled);
3540 if (strDebugPathOut.isNotEmpty())
3541 InsertConfigString(pCfg, "DebugPathOut", strDebugPathOut);
3542 break;
3543 }
3544 case AudioControllerType_HDA:
3545 {
3546 /* Intel HD Audio. */
3547 pszAudioDevice = "hda";
3548
3549 InsertConfigNode(pDevices, pszAudioDevice, &pDev);
3550 InsertConfigNode(pDev, "0", &pInst);
3551 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
3552 hrc = pBusMgr->assignPCIDevice(pszAudioDevice, pInst); H();
3553 InsertConfigNode(pInst, "Config", &pCfg);
3554 if (uBufSizeInMs)
3555 InsertConfigInteger(pCfg, "BufSizeInMs", uBufSizeInMs);
3556 if (uBufSizeOutMs)
3557 InsertConfigInteger(pCfg, "BufSizeOutMs", uBufSizeOutMs);
3558 InsertConfigInteger(pCfg, "DebugEnabled", fDebugEnabled);
3559 if (strDebugPathOut.isNotEmpty())
3560 InsertConfigString(pCfg, "DebugPathOut", strDebugPathOut);
3561
3562 /* macOS guests uses a different HDA variant to make 10.14+ (or maybe 10.13?) recognize the device. */
3563 if (fOsXGuest)
3564 InsertConfigString(pCfg, "DeviceName", "Intel Sunrise Point");
3565 break;
3566 }
3567 default:
3568 pszAudioDevice = "oops";
3569 AssertFailedBreak();
3570 }
3571
3572 PCFGMNODE pCfgAudioAdapter = NULL;
3573 InsertConfigNode(pInst, "AudioConfig", &pCfgAudioAdapter);
3574 SafeArray<BSTR> audioProps;
3575 hrc = audioAdapter->COMGETTER(PropertiesList)(ComSafeArrayAsOutParam(audioProps)); H();
3576
3577 std::list<Utf8Str> audioPropertyNamesList;
3578 for (size_t i = 0; i < audioProps.size(); ++i)
3579 {
3580 Bstr bstrValue;
3581 audioPropertyNamesList.push_back(Utf8Str(audioProps[i]));
3582 hrc = audioAdapter->GetProperty(audioProps[i], bstrValue.asOutParam());
3583 Utf8Str strKey(audioProps[i]);
3584 InsertConfigString(pCfgAudioAdapter, strKey.c_str(), bstrValue);
3585 }
3586
3587 /*
3588 * The audio driver.
3589 */
3590 const char *pszAudioDriver = NULL;
3591#ifdef VBOX_WITH_AUDIO_VALIDATIONKIT
3592 if (fValKitEnabled)
3593 {
3594 pszAudioDriver = "ValidationKitAudio";
3595 LogRel(("Audio: ValidationKit driver active\n"));
3596 }
3597#endif
3598 /* If nothing else was selected before, ask the API. */
3599 if (pszAudioDriver == NULL)
3600 {
3601 AudioDriverType_T enmAudioDriver;
3602 hrc = audioAdapter->COMGETTER(AudioDriver)(&enmAudioDriver); H();
3603
3604 /* The "Default" audio driver needs special treatment, as we need to figure out which driver to use
3605 * by default on the current platform. */
3606 bool const fUseDefaultDrv = enmAudioDriver == AudioDriverType_Default;
3607
3608 AudioDriverType_T const enmDefaultAudioDriver = settings::MachineConfigFile::getHostDefaultAudioDriver();
3609
3610 if (fUseDefaultDrv)
3611 {
3612 enmAudioDriver = enmDefaultAudioDriver;
3613 if (enmAudioDriver == AudioDriverType_Null)
3614 LogRel(("Audio: Warning: No default driver detected for current platform -- defaulting to Null audio backend\n"));
3615 }
3616
3617 switch (enmAudioDriver)
3618 {
3619 case AudioDriverType_Default: /* Can't happen, but handle it anyway. */
3620 RT_FALL_THROUGH();
3621 case AudioDriverType_Null:
3622 pszAudioDriver = "NullAudio";
3623 break;
3624#ifdef RT_OS_WINDOWS
3625# ifdef VBOX_WITH_WINMM
3626 case AudioDriverType_WinMM:
3627# error "Port WinMM audio backend!" /** @todo Still needed? */
3628 break;
3629# endif
3630 case AudioDriverType_DirectSound:
3631 /* Use the Windows Audio Session (WAS) API rather than Direct Sound on Windows
3632 versions we've tested it on (currently W7+). Since Vista, Direct Sound has
3633 been emulated on top of WAS according to the docs, so better use WAS directly.
3634
3635 Set extradata value "VBoxInternal2/Audio/WindowsDrv" "dsound" to no use WasAPI.
3636
3637 Keep this hack for backwards compatibility (introduced < 7.0).
3638 */
3639 GetExtraDataBoth(pVBox, pMachine, "VBoxInternal2/Audio/WindowsDrv", &strTmp); H();
3640 if ( enmDefaultAudioDriver == AudioDriverType_WAS
3641 && ( strTmp.isEmpty()
3642 || strTmp.equalsIgnoreCase("was")
3643 || strTmp.equalsIgnoreCase("wasapi")) )
3644 {
3645 /* Nothing to do here, fall through to WAS driver. */
3646 }
3647 else
3648 {
3649 pszAudioDriver = "DSoundAudio";
3650 break;
3651 }
3652 RT_FALL_THROUGH();
3653 case AudioDriverType_WAS:
3654 if (enmDefaultAudioDriver == AudioDriverType_WAS) /* WAS supported? */
3655 pszAudioDriver = "HostAudioWas";
3656 else if (enmDefaultAudioDriver == AudioDriverType_DirectSound)
3657 {
3658 LogRel(("Audio: Warning: Windows Audio Session (WAS) not supported, defaulting to DirectSound backend\n"));
3659 pszAudioDriver = "DSoundAudio";
3660 }
3661 break;
3662#endif /* RT_OS_WINDOWS */
3663#ifdef RT_OS_SOLARIS
3664 case AudioDriverType_SolAudio:
3665 /* Should not happen, as the Solaris Audio backend is not around anymore.
3666 * Remove this sometime later. */
3667 LogRel(("Audio: Warning: Solaris Audio is deprecated, please switch to OSS!\n"));
3668 LogRel(("Audio: Automatically setting host audio backend to OSS\n"));
3669
3670 /* Manually set backend to OSS for now. */
3671 pszAudioDriver = "OSSAudio";
3672 break;
3673#endif
3674#ifdef VBOX_WITH_AUDIO_OSS
3675 case AudioDriverType_OSS:
3676 pszAudioDriver = "OSSAudio";
3677 break;
3678#endif
3679#ifdef VBOX_WITH_AUDIO_ALSA
3680 case AudioDriverType_ALSA:
3681 pszAudioDriver = "ALSAAudio";
3682 break;
3683#endif
3684#ifdef VBOX_WITH_AUDIO_PULSE
3685 case AudioDriverType_Pulse:
3686 pszAudioDriver = "PulseAudio";
3687 break;
3688#endif
3689#ifdef RT_OS_DARWIN
3690 case AudioDriverType_CoreAudio:
3691 pszAudioDriver = "CoreAudio";
3692 break;
3693#endif
3694 default:
3695 pszAudioDriver = "oops";
3696 AssertFailedBreak();
3697 }
3698
3699 if (fUseDefaultDrv)
3700 LogRel(("Audio: Detected default audio driver type is '%s'\n", pszAudioDriver));
3701 }
3702
3703 BOOL fAudioEnabledIn = FALSE;
3704 hrc = audioAdapter->COMGETTER(EnabledIn)(&fAudioEnabledIn); H();
3705 BOOL fAudioEnabledOut = FALSE;
3706 hrc = audioAdapter->COMGETTER(EnabledOut)(&fAudioEnabledOut); H();
3707
3708 unsigned idxAudioLun = 0;
3709
3710 InsertConfigNodeF(pInst, &pLunL0, "LUN#%u", idxAudioLun);
3711 i_configAudioDriver(pVBox, pMachine, pLunL0, pszAudioDriver, !!fAudioEnabledIn, !!fAudioEnabledOut);
3712 idxAudioLun++;
3713
3714#ifdef VBOX_WITH_AUDIO_VRDE
3715 /* Insert dummy audio driver to have the LUN configured. */
3716 InsertConfigNodeF(pInst, &pLunL0, "LUN#%u", idxAudioLun);
3717 InsertConfigString(pLunL0, "Driver", "AUDIO");
3718 {
3719 AudioDriverCfg DrvCfgVRDE(pszAudioDevice, 0 /* Instance */, idxAudioLun, "AudioVRDE",
3720 !!fAudioEnabledIn, !!fAudioEnabledOut);
3721 int vrc = mAudioVRDE->InitializeConfig(&DrvCfgVRDE);
3722 AssertRCStmt(vrc, throw ConfigError(__FUNCTION__, vrc, "mAudioVRDE->InitializeConfig failed"));
3723 }
3724 idxAudioLun++;
3725#endif
3726
3727#ifdef VBOX_WITH_AUDIO_RECORDING
3728 /* Insert dummy audio driver to have the LUN configured. */
3729 InsertConfigNodeF(pInst, &pLunL0, "LUN#%u", idxAudioLun);
3730 InsertConfigString(pLunL0, "Driver", "AUDIO");
3731 {
3732 AudioDriverCfg DrvCfgVideoRec(pszAudioDevice, 0 /* Instance */, idxAudioLun, "AudioVideoRec",
3733 false /*a_fEnabledIn*/, true /*a_fEnabledOut*/);
3734 int vrc = mRecording.mAudioRec->InitializeConfig(&DrvCfgVideoRec);
3735 AssertRCStmt(vrc, throw ConfigError(__FUNCTION__, vrc, "Recording.mAudioRec->InitializeConfig failed"));
3736 }
3737 idxAudioLun++;
3738#endif
3739
3740 if (fDebugEnabled)
3741 {
3742#ifdef VBOX_WITH_AUDIO_DEBUG
3743# ifdef VBOX_WITH_AUDIO_VALIDATIONKIT
3744 /*
3745 * When both, ValidationKit and Debug mode (for audio) are enabled,
3746 * skip configuring the Debug audio driver, as both modes can
3747 * mess with the audio data and would lead to side effects.
3748 *
3749 * The ValidationKit audio driver has precedence over the Debug audio driver.
3750 *
3751 * This also can (and will) be used in VBox release builds.
3752 */
3753 if (fValKitEnabled)
3754 {
3755 LogRel(("Audio: Warning: ValidationKit running and Debug mode enabled -- disabling Debug driver\n"));
3756 }
3757 else /* Debug mode active -- run both (nice for catching errors / doing development). */
3758 {
3759 /*
3760 * The ValidationKit backend.
3761 */
3762 InsertConfigNodeF(pInst, &pLunL0, "LUN#%u", idxAudioLun);
3763 i_configAudioDriver(pVBox, pMachine, pLunL0, "ValidationKitAudio",
3764 !!fAudioEnabledIn, !!fAudioEnabledOut);
3765 idxAudioLun++;
3766# endif /* VBOX_WITH_AUDIO_VALIDATIONKIT */
3767 /*
3768 * The Debug audio backend.
3769 */
3770 InsertConfigNodeF(pInst, &pLunL0, "LUN#%u", idxAudioLun);
3771 i_configAudioDriver(pVBox, pMachine, pLunL0, "DebugAudio",
3772 !!fAudioEnabledIn, !!fAudioEnabledOut);
3773 idxAudioLun++;
3774# ifdef VBOX_WITH_AUDIO_VALIDATIONKIT
3775 }
3776# endif /* VBOX_WITH_AUDIO_VALIDATIONKIT */
3777#endif /* VBOX_WITH_AUDIO_DEBUG */
3778
3779 /*
3780 * Tweak the logging groups.
3781 */
3782 Utf8Str strGroups("drv_audio.e.l.l2.l3.f"
3783 " audio_mixer.e.l.l2.l3.f"
3784 " dev_hda_codec.e.l.l2.l3.f"
3785 " dev_hda.e.l.l2.l3.f"
3786 " dev_ac97.e.l.l2.l3.f"
3787 " dev_sb16.e.l.l2.l3.f");
3788
3789 LogRel(("Audio: Debug level set to %RU32\n", uDebugLevel));
3790
3791 switch (uDebugLevel)
3792 {
3793 case 0:
3794 strGroups += " drv_host_audio.e.l.l2.l3.f";
3795 break;
3796 case 1:
3797 RT_FALL_THROUGH();
3798 case 2:
3799 RT_FALL_THROUGH();
3800 case 3:
3801 strGroups += " drv_host_audio.e.l.l2.l3.f+audio_test.e.l.l2.l3.f";
3802 break;
3803 case 4:
3804 RT_FALL_THROUGH();
3805 default:
3806 strGroups += " drv_host_audio.e.l.l2.l3.l4.f+audio_test.e.l.l2.l3.l4.f";
3807 break;
3808 }
3809
3810 int vrc = RTLogGroupSettings(RTLogRelGetDefaultInstance(), strGroups.c_str());
3811 if (RT_FAILURE(vrc))
3812 LogRel(("Audio: Setting debug logging failed, vrc=%Rrc\n", vrc));
3813 }
3814 }
3815
3816 return VINF_SUCCESS;
3817}
3818
3819#undef H
3820#undef VRC
3821
3822#ifndef VBOX_WITH_EFI_IN_DD2
3823DECLHIDDEN(int) findEfiRom(IVirtualBox* vbox, PlatformArchitecture_T aPlatformArchitecture, FirmwareType_T aFirmwareType, Utf8Str *pEfiRomFile)
3824{
3825 Bstr aFilePath, empty;
3826 BOOL fPresent = FALSE;
3827 HRESULT hrc = vbox->CheckFirmwarePresent(aPlatformArchitecture, aFirmwareType, empty.raw(),
3828 empty.asOutParam(), aFilePath.asOutParam(), &fPresent);
3829 AssertComRCReturn(hrc, Global::vboxStatusCodeFromCOM(hrc));
3830
3831 if (!fPresent)
3832 {
3833 LogRel(("Failed to find an EFI ROM file.\n"));
3834 return VERR_FILE_NOT_FOUND;
3835 }
3836
3837 *pEfiRomFile = Utf8Str(aFilePath);
3838
3839 return VINF_SUCCESS;
3840}
3841#endif
Note: See TracBrowser for help on using the repository browser.

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