VirtualBox

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

Last change on this file since 100842 was 99913, checked in by vboxsync, 19 months ago

Main/src-client/ConsoleImpl: Add some _very_ basic config code to run an ARMv8 based guest inside the main VirtualBox frontend, can be activated by a CFGM key, bugref:10384

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