VirtualBox

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

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

Main/ConsoleImpl: Split the VM config code into a common and architecture specific part in preparation for ARMv8, bugref:10384

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